content
stringlengths 5
1.05M
|
---|
#!/usr/bin/env python3
if __name__ == '__main__':
data = open('input').read().splitlines()
grid = []
for row in data:
newrow = []
for column in row:
newrow += [int(column)]
grid += [newrow]
low_points = []
for i,row in enumerate(grid):
for j,val in enumerate(row):
up, down, left, right = 10, 10, 10, 10
# up
if i > 0:
up = grid[i - 1][j]
# down
if i < len(grid) - 1:
down = grid[i + 1][j]
# left
if j > 0:
left = grid[i][j - 1]
# right
if j < len(grid[i]) - 1:
right = grid[i][j + 1]
if val < up and val < down and val < left and val < right:
low_points += [val]
print(sum([p + 1 for p in low_points]))
|
#!/usr/bin/env python3
import numpy as np
import os
import sys
from scipy.stats import norm
##SOME CONSTANTS##############################################
epsilon0 = 8.854187817e-12 #F/m
hbar = 6.582119514e-16 #eV s
hbar2 = 1.054571800e-34 #J s
mass = 9.10938356e-31 #kg
c = 299792458 #m/s
e = 1.60217662e-19 #C
kb = 8.6173303e-5 #eV/K
amu = 1.660539040e-27 #kg
pi = np.pi
###############################################################
##ERROR FUNCTION###############################################
def fatal_error(msg):
print(msg)
sys.exit()
###############################################################
##GETS FREQUENCIES AND REDUCED MASSES##########################
def pega_freq(freqlog):
F, M = [], []
with open(freqlog, 'r') as f:
for line in f:
if "Frequencies --" in line:
line = line.split()
for j in range(2,len(line)):
if float(line[j]) in F:
pass
F.append(float(line[j]))
elif "Red. masses --" in line:
line = line.split()
for j in range(3,len(line)):
M.append(float(line[j]))
elif 'Thermochemistry' in line:
break
#conversion in angular frequency
F = np.array(F)*(c*100*2*pi)
try:
f = F[0]
except:
fatal_error("No frequencies in the log file! Goodbye!")
#conversion from amu to kg
M = np.asarray(M)*amu
return F, M
###############################################################
##GETS ATOMS AND LAST GEOMETRY IN FILE#########################
def pega_geom(freqlog):
if ".log" in freqlog:
status = 0
busca = "orientation:"
n = -1
with open(freqlog, 'r') as f:
for line in f:
if busca in line and 'Dipole' not in line:
n = 0
G = np.zeros((1,3))
atomos = []
elif n >= 0 and n < 4:
n += 1
elif n >= 4 and "---------------------------------------------------------------------" not in line:
line = line.split()
NG = []
for j in range(3,len(line)):
NG.append(float(line[j]))
atomos.append(line[1])
G = np.vstack((G,NG))
n += 1
elif "---------------------------------------------------------------------" in line and n>1:
n = -1
else:
G = np.zeros((1,3))
atomos = []
with open(freqlog, 'r') as f:
for line in f:
line = line.split()
try:
vetor = np.array([float(line[1]),float(line[2]), float(line[3])])
atomos.append(line[0])
G = np.vstack((G,vetor))
except:
pass
try:
G = G[1:,:]
except:
fatal_error("No geometry in the log file! Goodbye!")
return G, atomos
###############################################################
##SAVES OPT GEOMETRY###########################################
def salva_geom(G,atomos):
atomos = np.array([atomos]).astype(float)
atomos = atomos.T
G = np.hstack((atomos,G))
np.savetxt('opt_geom.lx', G, delimiter='\t', fmt=['%1.1u','%+1.5f','%+1.5f','%+1.5f'])
print("The optimized geometry that is used is saved in the opt_geom.lx file!")
###############################################################
##GETS NORMAL COORDINATES IN HIGH PRECISION####################
def pega_modosHP(G, freqlog):
F, M = pega_freq(freqlog)
n = -1
num_atom = np.shape(G)[0]
NC = np.zeros((3*num_atom,1))
with open(freqlog, 'r') as f:
for line in f:
if n == 0:
line = line.split()[3:]
C = np.asarray([float(i) for i in line])
n += 1
elif n < 0 or n > 3*num_atom:
if "Coord Atom Element:" in line:
n = 0
elif n > 0 and n < 3*num_atom:
line = line.split()[3:]
line = np.asarray([float(i) for i in line])
C = np.vstack((C,line))
n += 1
elif n == 3*num_atom:
NC = np.hstack((NC,C))
n += 1
NC = NC[:,1:]
MM = np.zeros((1,len(F)))
M = np.expand_dims(M,axis=0)
for _ in range(0,3*num_atom):
MM = np.vstack((MM,M))
M = MM[1:,:]
return NC
###############################################################
##GETS NORMAL COORDINATES IN REGULAR PRECISION#################
def pega_modosLP(G,freqlog):
F, M = pega_freq(freqlog)
C = []
n = -1
num_atom = np.shape(G)[0]
with open(freqlog, 'r') as f:
for line in f:
if n < 0 or n >= num_atom:
if "Atom AN X Y Z" in line:
n = 0
else:
pass
elif n >= 0 and n < num_atom:
line = line.split()
for j in range(2,len(line)):
C.append(float(line[j]))
n += 1
num_modos = len(F)
l = 0
p = 0
NNC = np.zeros((num_atom,1))
while l < num_modos:
NC = np.zeros((1,3))
k =0
while k < num_atom:
B = np.asarray(C[3*(l+3*k)+p:3*(l+3*k)+3+p])
NC = np.vstack((NC,B))
k += 1
NNC = np.hstack((NNC,NC[1:,:]))
l += 1
if l%3 == 0 and l != 0:
p = p + (num_atom-1)*9
NNC = NNC[:,1:] #matriz com as coordenadas normais de cada modo
D = np.zeros((3*num_atom,1))
for i in range(0,len(F)):
normal = NNC[:,3*i:3*i+3].flatten()
normal = np.expand_dims(normal,axis=1)
D = np.hstack((D,normal))
D = D[:,1:]
MM = np.zeros((1,len(F)))
M = np.expand_dims(M,axis=0)
for i in range(0,3*num_atom):
MM = np.vstack((MM,M))
M = MM[1:,:]
return D
###############################################################
##DETECTS WHETHER HIGH PRECISION IS USED#######################
def pega_modos(G,freqlog):
x = 'LP'
with open(freqlog, 'r') as f:
for line in f:
if "Coord Atom Element:" in line:
x = 'HP'
break
if x == 'LP':
return pega_modosLP(G,freqlog)
else:
return pega_modosHP(G,freqlog)
###############################################################
##WRITES ATOMS AND XYZ COORDS TO FILE##########################
def write_input(atomos,G,header,bottom,file):
with open(file, 'w') as f:
f.write(header)
for i in range(0,len(atomos)):
texto = "{:2s} {:.14f} {:.14f} {:.14f}\n".format(atomos[i],G[i,0],G[i,1],G[i,2])
f.write(texto)
f.write("\n"+bottom+'\n')
###############################################################
##DISPLACE GEOMETRY IN DIRECTIONS WITH IMAGINARY FREQ##########
def shake(freqlog, T, header):
F, _ = pega_freq(freqlog)
G, atomos = pega_geom(freqlog)
NNC = pega_modos(G,freqlog)
num_atom = np.shape(G)[0]
A1 = np.zeros((3*num_atom,1))
A2 = np.zeros((3*num_atom,1))
F = F[F < 0]
if len(F) == 0:
fatal_error("No imaginary frquencies in the log file. Goodbye!")
F = -1*F
for i in range(len(F)):
q = [-1*T,T]
A1 += q[0]*(np.expand_dims(NNC[:,i],axis=1))
A2 += q[1]*(np.expand_dims(NNC[:,i],axis=1))
A1 = np.reshape(A1,(num_atom,3))
A2 = np.reshape(A2,(num_atom,3))
Gfinal = A1 + G
Gfinal2 = A2 + G
write_input(atomos,Gfinal,header,'','distort_{}_.com'.format(T))
write_input(atomos,Gfinal2,header,'','distort_{}_.com'.format(-T))
print("Geometries are saved on files ditort_{}_.com and distort_{}_.com!".format(T,-T))
###############################################################
##CHECKS FOR EXISTING GEOMETRIES###############################
def start_counter():
files = [file for file in os.listdir('Geometries') if ".com" in file and "Geometr" in file]
return len(files)
###############################################################
##SAMPLES GEOMETRIES###########################################
def sample_geom(freqlog, num_geoms, T, header, bottom):
F, M = pega_freq(freqlog)
if F[0] < 0:
fatal_error("Imaginary frequency! Goodbye!")
try:
os.mkdir('Geometries')
except:
pass
counter = start_counter()
G, atomos = pega_geom(freqlog)
salva_geom(G,atomos)
NNC = pega_modos(G,freqlog)
num_atom = np.shape(G)[0]
print("\nGenerating geometries...\n")
with open('Magnitudes_{:.0f}K_.lx'.format(T), 'a') as file:
for n in range(1,num_geoms+1):
A = np.zeros((3*num_atom,1))
numbers = []
for i in range(0,len(F)):
scale = np.sqrt(hbar2/(2*M[i]*F[i]*np.tanh(hbar*F[i]/(2*kb*T))))
normal = norm(scale=scale,loc=0)
#Displacements in Å
q = normal.rvs()*1e10
numbers.append(q)
A += q*(np.expand_dims(NNC[:,i],axis=1))
numbers = np.round(np.array(numbers)[np.newaxis,:],4)
np.savetxt(file, numbers, delimiter='\t', fmt='%s')
A = np.reshape(A,(num_atom,3))
Gfinal = A + G
write_input(atomos,Gfinal,header.replace("UUUUU",str(n)),bottom.replace("UUUUU",str(n)),"Geometries/Geometry-"+str(n+counter)+"-.com")
progress = 100*n/num_geoms
text = "{:2.1f}%".format(progress)
print(' ', text, "of the geometries done.",end="\r", flush=True)
print("\n\nDone! Ready to run.")
###############################################################
##COLLECTS RESULTS##############################################
def gather_data(opc, tipo):
files = [file for file in os.listdir('Geometries') if ".log" in file and "Geometr" in file ]
files = sorted(files, key=lambda file: float(file.split("-")[1]))
with open("Samples.lx", 'w') as f:
for file in files:
num = file.split("-")[1]
broadening = opc
numeros, energies, fs, scfs = [], [], [], []
corrected, total_corrected = -1, -1
with open('Geometries/'+file, 'r') as g:
for line in g:
if "Excited State" in line:
line = line.split()
numeros.append(line[2])
energies.append(line[4])
fs.append(line[8][2:])
elif "Corrected transition energy" in line:
line = line.split()
corrected = line[4]
elif "Total energy after correction" in line:
line = line.split()
total_corrected = 27.2114*float(line[5])
elif "SCF Done:" in line:
line = line.split()
scfs.append(27.2114*float(line[4]))
if len(numeros) > 0:
f.write("Geometry "+num+": Vertical transition (eV) Oscillator strength Broadening Factor (eV) \n")
if corrected != -1 and tipo == 'abs': #abspcm
f.write("Excited State {}\t{}\t{}\t{}\n".format(numeros[0],corrected, fs[0], broadening))
elif corrected != -1 and tipo == 'emi': #emipcm
energy = total_corrected - scfs[-1]
f.write("Excited State {}\t{:.3f}\t{}\t{}\n".format(numeros[0],energy,fs[0],broadening))
elif corrected == -1 and tipo == 'emi':
f.write("Excited State {}\t{}\t{}\t{}\n".format(numeros[0],energies[0],fs[0],broadening))
else:
for i in range(len(energies)):
f.write("Excited State {}\t{}\t{}\t{}\n".format(numeros[i],energies[i],fs[i],broadening))
f.write("\n")
###############################################################
##NORMALIZED GAUSSIAN##########################################
def gauss(x,v,s):
y = (1/(np.sqrt(2*np.pi)*s))*np.exp(-0.5*((x-v)/s)**2)
return y
###############################################################
##COMPUTES AVG TRANSITION DIPOLE MOMENT########################
def calc_tdm(O,V):
#Energy terms converted to J
term = e*(hbar2**2)/V
dipoles = np.sqrt(3*term*O/(2*mass))
#Conversion in au
dipoles *= 1.179474389E29
return np.mean(dipoles)
###############################################################
##PREVENTS OVERWRITING#########################################
def naming(arquivo):
new_arquivo = arquivo
if arquivo in os.listdir('.'):
duplo = True
vers = 2
while duplo:
new_arquivo = str(vers)+arquivo
if new_arquivo in os.listdir('.'):
vers += 1
else:
duplo = False
return new_arquivo
###############################################################
##COMPUTES SPECTRA#############################################
def spectra(tipo, num_ex, nr):
if tipo == "abs":
constante = (np.pi*(e**2)*hbar)/(2*nr*mass*c*epsilon0)*10**(20)
elif tipo == 'emi':
constante = ((nr**2)*(e**2)/(2*np.pi*hbar*mass*(c**3)*epsilon0))
V, O, S = [], [], []
N = 0
with open("Samples.lx", 'r') as f:
for line in f:
if "Geometry" in line:
N += 1
elif "Excited State" in line and int(line.split()[2][:-1]) in num_ex:
line = line.split()
V.append(float(line[3]))
O.append(float(line[4]))
S.append(float(line[5]))
coms = start_counter()
if len(V) == 0 or len(O) == 0:
fatal_error("You need to run steps 1 and 2 first! Goodbye!")
elif len(V) != coms*max(num_ex):
print("Number of log files is less than the number of inputs. Something is not right! Computing the spectrum anyway...")
V = np.array(V)
O = np.array(O)
S = np.array(S)
if tipo == 'abs':
espectro = (constante*O)
else:
espectro = (constante*(V**2)*O)
tdm = calc_tdm(O,V)
x = np.linspace(min(V)-3*max(S), max(V)+ 3*max(S), 200)
y = np.zeros((1,len(x)))
if tipo == 'abs':
arquivo = 'cross_section.lx'
primeira = "{:8s} {:8s} {:8s}\n".format("#Energy(ev)", "cross_section(A^2)", "error")
else:
arquivo = 'differential_rate.lx'
primeira = "{:4s} {:4s} {:4s} TDM={:.3f} au\n".format("#Energy(ev)", "diff_rate", "error",tdm)
arquivo = naming(arquivo)
for i in range(0,len(espectro)):
contribution = espectro[i]*gauss(x,V[i],S[i])
y = np.vstack((y,contribution[np.newaxis,:]))
y = y[1:,:]
mean_y = np.sum(y,axis=0)/N
#Error estimate
sigma = np.sqrt(np.sum((y-mean_y)**2,axis=0)/(N*(N-1)))
if tipo == 'emi':
#Emission rate calculations
from lx.ld import calc_lifetime
mean_lifetime, error_lifetime = calc_lifetime(x, mean_y,sigma)
segunda = '# Fluorescence Lifetime: {:5.2e} +/- {:5.2e} s^-1\n'.format(mean_lifetime,error_lifetime)
else:
segunda = ''
print(N, "geometries considered.")
with open(arquivo, 'w') as f:
f.write(primeira)
f.write(segunda)
for i in range(0,len(x)):
text = "{:.6f} {:.6e} {:.6e}\n".format(x[i],mean_y[i], sigma[i])
f.write(text)
print('Spectrum printed in the {} file'.format(arquivo))
###############################################################
##CHECKS THE FREQUENCY LOG'S LEVEL OF THEORY###################
def busca_input(freqlog):
base = 'lalala'
exc = ''
header = ''
nproc = '4'
mem = '1GB'
scrf = ''
with open(freqlog, 'r') as f:
search = False
for line in f:
if '%nproc' in line:
line = line.split('=')
nproc = line[-1].replace('\n','')
elif '%mem' in line:
line = line.split('=')
mem = line[-1].replace('\n','')
elif "#" in line and not search and header == '':
search = True
header += line.lstrip().replace('\n','')
elif search and '----------' not in line:
header += line.lstrip().replace('\n','')
elif search and '----------' in line:
search = False
break
if 'TDA' in header.upper():
exc = 'tda'
spec = 'EMISPCT'
elif 'TD' in header.upper():
exc = 'td'
spec = 'EMISPCT'
else:
spec = 'ABSSPCT'
if 'SCRF' in header.upper():
new = header.split()
for elem in new:
if 'SCRF' in elem:
scrf = elem
break
header = header.split()
base = ''
for elem in header:
if "/" in elem and 'IOP' not in elem.upper():
base += elem.replace('#','')
elif 'IOP' in elem.upper() and ('108' in elem or '107' in elem):
base += ' '+elem
return base, exc, nproc, mem, scrf, spec
###############################################################
##CHECKS PROGRESS##############################################
def andamento():
coms = [file for file in os.listdir("Geometries") if 'Geometr' in file and '.com' in file]
logs = [file for file in os.listdir("Geometries") if 'Geometr' in file and '.log' in file]
factor = 1
try:
with open('Geometries/'+coms[0], 'r') as f:
for line in f:
if 'Link1' in line:
factor = 2
count = 0
for file in logs:
with open('Geometries/'+file, 'r') as f:
for line in f:
if "Normal termination" in line:
count += 1
print("\n\nThere are", int(count/factor), "completed calculations out of", len(coms), "inputs")
print("It is", np.round(100*count/(factor*len(coms)),1), "% done.")
except:
print('No files found! Check the folder!')
###############################################################
##FETCHES FILES###############################################
def fetch_file(frase,ends):
files = []
for file in [i for i in os.listdir('.')]:
for end in ends:
if end in file:
files.append(file)
if len(files) == 0:
fatal_error("No {} file found. Goodbye!".format(frase))
freqlog = 'nada0022'
for file in files:
print("\n"+file)
resp = input('Is this the {} file? y ou n?\n'.format(frase))
if resp.lower() == 'y':
freqlog = file
break
if freqlog == 'nada0022':
fatal_error("No {} file found. Goodbye!".format(frase))
return freqlog
###############################################################
##RUNS TASK MANAGER############################################
def batch():
script = fetch_file('batch script?',['.sh'])
limite = input("Maximum number of jobs to be submitted simultaneously?\n")
try:
limite = float(limite)
except:
fatal_error("It must be an integer. Goodbye!")
import subprocess
folder = os.path.dirname(os.path.realpath(__file__))
with open('limit.lx','w') as f:
f.write(str(limite))
subprocess.Popen(['nohup', 'python3', folder+'/batch_lx.py', script, '&'])
###############################################################
##RUNS W TUNING################################################
def omega_tuning():
geomlog = fetch_file('input or log',['.com','.log'])
base, _, nproc, mem, _, _ = busca_input(geomlog)
if 'IOP' in base.upper() and ('108' in base or '107' in base):
base2 = base.split()
for elem in base2:
if '/' in elem:
base = elem
break
omega1 = '0.1'
passo = '0.025'
relax = 'y'
print('This is the configuration taken from the file:\n')
print('Functional/basis: {}'.format(base))
print('%nproc='+nproc)
print('%mem='+mem)
print('Initial Omega: {} bohr^-1'.format(omega1))
print('Step: {} bohr^-1'.format(passo))
print('Optimize at each step: yes')
change = input('Are you satisfied with these parameters? y or n?\n')
if change == 'n':
base = default(base,"Functional/basis is {}. If ok, Enter. Otherwise, type functional/basis.\n".format(base))
nproc = default(nproc,'nproc={}. If ok, Enter. Otherwise, type it.\n'.format(nproc))
mem = default(mem,"mem={}. If ok, Enter. Otherwise, type it.\n".format(mem))
omega1 = default(omega1,"Initial omega is {} bohr^-1. If ok, Enter. Otherwise, type it.\n".format(omega1))
passo = default(passo,"Initial step is {} bohr^-1. If ok, Enter. Otherwise, type it.\n".format(passo))
relax = default(relax,"Optimize at each step: yes. If ok, Enter. Otherwise, type n\n")
script = fetch_file('batch script',['.sh'])
import subprocess
folder = os.path.dirname(os.path.realpath(__file__))
with open('limit.lx','w') as f:
f.write('Running')
subprocess.Popen(['nohup', 'python3', folder+'/leow.py', geomlog, base, nproc, mem, omega1, passo, relax, script, '&'])
###############################################################
##FINDS SUITABLE VALUE FOR STD#################################
def detect_sigma():
try:
files = [i for i in os.listdir('.') if 'Magnitudes' in i and '.lx' in i]
file = files[0]
temp = float(file.split('_')[1].strip('K'))
sigma = np.round(kb*temp,3)
except:
sigma = 0.000
return sigma
###############################################################
##CHECKS SPECTRUM TYPE#########################################
def get_spec():
coms = [file for file in os.listdir("Geometries") if 'Geometr' in file and '.com' in file]
with open('Geometries/'+coms[0],'r') as f:
for line in f:
if 'ABSSPCT' in line:
tipo = 'absorption'
break
elif 'EMISPCT' in line:
tipo = 'emission'
break
return tipo
###############################################################
##FETCHES REFRACTIVE INDEX#####################################
def get_nr():
buscar = False
coms = [file for file in os.listdir("Geometries") if 'Geometr' in file and '.com' in file]
with open('Geometries/'+coms[0],'r') as f:
for line in f:
if 'SCRF' in line.upper():
buscar = True
break
if buscar:
logs = [file for file in os.listdir("Geometries") if 'Geometr' in file and '.log' in file]
for log in logs:
with open('Geometries/'+log,'r') as f:
for line in f:
if 'Solvent' in line and 'Eps' in line:
line = line.split()
nr = np.sqrt(float(line[6]))
return nr
else:
return 1
###############################################################
##FETCHES CHARGE AND MULTIPLICITY##############################
def get_cm(freqlog):
with open(freqlog,'r') as f:
for line in f:
if 'Charge' in line and 'Multiplicity' in line:
line = line.split()
charge = line[2]
mult = line[5]
break
return charge+' '+mult
###############################################################
##QUERY FUNCTION###############################################
def default(a,frase):
b = input(frase)
if b == '':
return a
else:
return b
###############################################################
##SETS DIELECTRIC CONSTANTS####################################
def set_eps(scrf):
if 'READ' in scrf.upper():
eps1 = input("Type the static dielectric constant.\n")
eps2 = input("Type the dynamic dielectric constant (n^2).\n")
try:
float(eps1)
float(eps2)
except:
fatal_error("The constants must be numbers. Goodbye!")
epss = "Eps="+eps1+"\nEpsInf="+eps2+"\n\n"
else:
epss = '\n'
return epss
###############################################################
##STOP SUBMISSION OF JOBS######################################
def abort_batch():
choice = input('Are you sure you want to prevent new jobs from being submitted? y or n?\n')
if choice == 'y':
try:
os.remove('limit.lx')
print('Done!')
except:
print('Could not find the files. Maybe you are in the wrong folder.')
else:
print('OK, nevermind')
###############################################################
##DELETES CHK FILES############################################
def delchk(input,term):
num = input.split('-')[1]
if term == 1:
a = ''
elif term == 2:
a = '2'
try:
os.remove('step{}_{}.chk'.format(a,num))
except:
pass
###############################################################
##CHECKS WHETHER JOBS ARE DONE#################################
def watcher(files,counter):
rodando = files.copy()
done = []
exit = False
for input in rodando:
term = 0
try:
with open(input[:-3]+'log', 'r') as f:
for line in f:
if 'Normal termination' in line:
term += 1
if counter == 2:
delchk(input,term)
elif 'Error termination' in line:
print('The following job returned an error: {}'.format(input))
print('Please check the file for any syntax errors. Aborting the execution.')
exit = True
if term == counter:
done.append(input)
except:
pass
if exit:
sys.exit()
for elem in done:
del rodando[rodando.index(elem)]
return rodando
###############################################################
##GETS SPECTRA#################################################
def search_spectra():
Abs, Emi = 'None', 'None'
candidates = [i for i in os.listdir('.') if '.lx' in i]
for candidate in candidates:
with open(candidate, 'r') as f:
for line in f:
if 'cross_section' in line:
Abs = candidate
elif 'diff_rate' in line:
Emi = candidate
break
return Abs, Emi
###############################################################
##RUNS EXCITON ANALYSIS########################################
def ld():
Abs, Emi = search_spectra()
print('Absorption file: {}'.format(Abs))
print('Emission file: {}'.format(Emi))
check = input('Are these correct? y or n?\n')
if check == 'n':
Abs = input('Type name of the absorption spectrum file\n')
Emi = input('Type name of the emission spectrum file\n')
kappa = input('Orientation Factor (k^2):\n')
rmin = input("Average intermolecular distance in Å:\n")
Phi = input("Fluorescence quantum yield (from 0 to 1):\n")
try:
rmin = float(rmin)
kappa = np.sqrt(float(kappa))
Phi = float(Phi)
except:
fatal_error('These features must be numbers. Goodbye!')
if Phi > 1 or Phi < 0:
fatal_error('Quantum yield must be between 0 and 1. Goodbye!')
correct = input('Include correction for short distances? y or n?\n')
if correct == 'y':
alpha = 1.15*0.53
print('Employing correction!')
else:
alpha = 0
print('Not employing correction!')
print('Computing...')
from lx.ld import run_ld
try:
run_ld(Abs, Emi, alpha, rmin, kappa, Phi)
print('Results can be found in the ld.lx file')
except:
print('Something went wrong. Check if the name of the files are correct.')
############################################################### |
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.clock import Clock
from kivy.animation import Animation
from kivy.properties import ListProperty
from kivy.core.window import Window
from random import random,randrange
from kivy.graphics import Color, Rectangle
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from functools import partial
from kivy.graphics.instructions import InstructionGroup
from kivy.core.image import Image
from kivy.uix.spinner import Spinner, SpinnerOption
import time
class Mywidget(Widget):
SnakeX=[300,280,260,240]
SnakeY=[300,300,300,300]
direction=[0,20]
snake = InstructionGroup()
food = InstructionGroup()
foodx=randrange(0,200,20)
foody=randrange(100,300,20)
score = 0
count = 1
speed = 1
def __init__(self,**kwargs):
super(Mywidget,self).__init__(**kwargs)
self.canvas.clear()
Clock.schedule_once(self.get_speed)
def get_speed(self,args):
Clock.unschedule(self.draw_snake)
Clock.schedule_interval(self.draw_snake,1./(len(self.SnakeX)+self.speed))
def play_again(self,args):
#print 'play'
self.canvas.clear()
self.SnakeX=[300,280,260,240]
self.SnakeY=[300,300,300,300]
self.direction=[0,20]
self.snake = InstructionGroup()
self.food = InstructionGroup()
self.foodx=randrange(0,300,20)
self.foody=randrange(100,300,20)
self.count=1
self.score=0
self.getscore()
def on_touch_down(self, touch):
if self.isdead()==False:
if self.direction[0]==0:
if self.SnakeX[0]-touch.x>0:
self.direction=[-20,0]
else:
self.direction=[20,0]
else:
if self.SnakeY[0]-touch.y>0:
self.direction=[0,-20]
else:
self.direction=[0,20]
def changelevel(self,instance,value):
if value == 'level':
return
instance.text = value
if value=='easy':
self.speed = 10
self.get_speed(self)
elif value=='normal':
self.speed = 50
self.get_speed(self)
else:
self.speed=100
self.get_speed(self)
def draw_snake(self,args):
if (self.SnakeX[0]+self.direction[0]==self.SnakeX[1] and self.SnakeY[0]+self.direction[1]==self.SnakeY[1]):
self.direction *= -1
if self.isdead()==False:
self.snakefunc(self)
self.canvas.remove(self.snake)
self.snake = InstructionGroup()
for i in range(len(self.SnakeX)):
self.snake.add(Color(1, 0, 0, 1))
self.snake.add(Rectangle(pos=(self.SnakeX[i],self.SnakeY[i]), size=(20, 20)))
self.draw_food()
self.canvas.add(self.snake)
else:
self.gameover()
def draw_food(self):
self.canvas.remove(self.food)
self.food = InstructionGroup()
self.food.add(Color(0, 1, 0, 1))
self.food.add(Rectangle(pos=(self.foodx,self.foody), size=(20, 20)))
self.canvas.add(self.food)
def random_food(self):
self.foodx=randrange(0,self.width,20)
self.foody=randrange(100,self.height,20)
for i in range(0,len(self.SnakeX)-1):
if self.foodx==self.SnakeX[i] and self.foody==self.SnakeY[i]:
self.random_food()
def snakefunc(self,args):
new_X=self.SnakeX[0]+self.direction[0]
new_Y=self.SnakeY[0]+self.direction[1]
self.SnakeX.insert(0,new_X)
self.SnakeY.insert(0,new_Y)
if self.iseated()==True:
self.random_food()
self.get_speed(self)
else:
del self.SnakeX[-1]
del self.SnakeY[-1]
def iseated(self):
if self.foodx==self.SnakeX[0] and self.foody==self.SnakeY[0]:
self.score+=10
#print self.score
self.getscore()
return True
def isdead(self):
if self.SnakeX[0]< 0 or self.SnakeX[0]> Window.width or self.SnakeY[0]<self.y or self.SnakeY[0]> Window.height:
return True
for i in range(1,len(self.SnakeX)-1):
if self.SnakeX[i] ==self.SnakeX[0] and self.SnakeY[i]==self.SnakeY[0]:
return True
return False
def gameover(self):
self.canvas.clear()
with self.canvas:
Rectangle(source='gameover.png',color=(1,0,0,1), pos=self.pos, size=self.size)
def getscore(self):
self.label.text='score '+str(self.score)
class SnakeApp(App):
def build(self):
wid = Mywidget()
btn=Button(text='restart',on_press=partial(wid.play_again))
speedlevel = Spinner(
text='level',
values=('easy', 'normal', 'hard'))
speedlevel.bind(text=wid.changelevel)
layout = BoxLayout(size_hint=(1, None), height=100)
label=Label(text='score 0')
wid.label=label
layout.add_widget(label)
layout.add_widget(speedlevel)
layout.add_widget(btn)
root = BoxLayout(orientation='vertical')
root.add_widget(wid)
root.add_widget(layout)
return root
if __name__=='__main__':
SnakeApp().run()
|
import os
os.environ["OMP_NUM_THREADS"]= '1'
os.environ["OMP_THREAD_LIMIT"] = '1'
os.environ["MKL_NUM_THREADS"] = '1'
os.environ["NUMEXPR_NUM_THREADS"] = '1'
os.environ["OMP_NUM_THREADS"] = '1'
os.environ["PAPERLESS_AVX2_AVAILABLE"]="false"
os.environ["OCR_THREADS"] = '1'
import poppler
import pytesseract
from pdf2image import convert_from_bytes
from fastapi import APIRouter, File
import sqlalchemy
from dotenv import load_dotenv, find_dotenv
from sqlalchemy import create_engine
from app.BIA_Scraper import BIACase
import requests
import pandas as pd
import numpy as np
from PIL import Image
router = APIRouter()
load_dotenv(find_dotenv())
database_url = os.getenv('DATABASE_URL')
engine = sqlalchemy.create_engine(database_url)
@router.post('/insert')
async def create_upload_file(file: bytes = File(...)):
'''
This function inserts a PDF and the OCR converted text into a database
'''
text = []
### Converts the bytes object recieved from fastapi
pages = convert_from_bytes(file,200,fmt='png',thread_count=2)
### Uses pytesseract to convert each page of pdf to txt
text.append(pytesseract.image_to_string(pages))
### Joins the list to an output string
string_to_return = " ".join(text)
return {'Text': string_to_return}
@router.post('/get_fields')
async def create_upload_file_get_fields(file: bytes = File(...)):
text = []
### Converts the bytes object recieved from fastapi
pages = convert_from_bytes(file,200,fmt='png',thread_count=2)
### Uses pytesseract to convert each page of pdf to txt
for item in pages:
text.append(pytesseract.image_to_string(item))
### Joins the list to an output string
string = " ".join(text)
### Using the BIACase Class to populate fields
case = BIACase(string)
### Json object / dictionary to be returned
case_data = {}
### Case ID (dummy data)
case_data['case_id'] = 'test'
### Initial or appelate (dummy data)
case_data['initial_or_appellate'] = 'test'
### Case origin
case_data['case_origin'] = 'test'
### Application field
app = case.get_application()
app = [ap for ap, b in app.items() if b]
case_data['application_type'] = '; '.join(app) if app else None
### Date field
case_data['hearing_date'] = case.get_date()
### Country of origin
case_data['nation_of_origin'] = case.get_country_of_origin()
### Getting Panel members
panel = case.get_panel()
case_data['judge'] = '; '.join(panel) if panel else None
### Getting case outcome
case_data['case_outcome'] = case.get_outcome()
### Getting protected grounds
pgs = case.get_protected_grounds()
case_data['protected_ground'] = '; '.join(pgs) if pgs else None
### Getting the violence type on the asylum seeker
based_violence = case.get_based_violence()
violence = '; '.join([k for k, v in based_violence.items() if v]) \
if based_violence \
else None
### Getting keywords
keywords = '; '.join(['; '.join(v) for v in based_violence.values()]) \
if based_violence \
else None
case_data['type_of_violence_experienced'] = violence
case_data['keywords'] = keywords
### Getting references / sex of applicant
references = [
'Matter of AB, 27 I&N Dec. 316 (A.G. 2018)'
if case.references_AB27_216() else None,
'Matter of L-E-A-, 27 I&N Dec. 581 (A.G. 2019)'
if case.references_LEA27_581() else None
]
case_data['references'] = '; '.join([r for r in references if r])
case_data['applicant_sex'] = case.get_seeker_sex()
## Getting applicant's indigenous status
indigenous_status = case.get_applicant_indigenous_status()
case_data['applicant_indigenous_group'] = indigenous_status
## Getting applicant's native language
applicant_lang = case.get_applicant_language()
case_data['applicant_language'] = applicant_lang
### Getting ability to access interpreter
access_to_interpreter = case.get_applicant_access_interpeter()
case_data['applicant_access_to_interpreter'] = access_to_interpreter
### Getting applicant's credibility status
determined_applicant_credibility = case.get_applicant_determined_credibility()
case_data['applicant_perceived_credibility'] = determined_applicant_credibility
## Getting whether the case argued against the one-year guideline
case_data['case_filed_within_one_year'] = f'{case.check_for_one_year}'
return case_data
|
import redis
from random import choice
from Proxypool.proxypool.error import PoolEmptyError
MAX_SCORE = 100
MIN_SCORE = 0
INITIAL_SCORE = 10
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
REDIS_PASSWORD = None
REDIS_KEY = 'proxies'
class RedisClient(object):
def __init__(self, host=REDIS_HOST, port=REDIS_PORT, password=REDIS_PASSWORD):
"""
初始化
:param host:redis地址
:param port: redis端口
:param password: redis密码
"""
self.db = redis.StrictRedis(host=host, port=port, password=password, decode_responses=True)
def add(self, proxy, score=INITIAL_SCORE):
"""
添加代理
:param proxy:代理
:param score: 分数
:return: 添加结果
"""
if not self.db.zscore(REDIS_KEY, proxy):
return self.db.zadd((REDIS_KEY, score, proxy))
def random(self):
"""
随机获取有效代理 尝试获取分数最高代理 然后尝试排名获取 否则异常
:return: 随即接过
"""
result = self.db.zrangebyscore(REDIS_KEY, MAX_SCORE, MAX_SCORE)
if len(result):
return choice(result)
else:
result = self.db.zrevrange(REDIS_KEY, 0, 100)
if len(result):
return choice(result)
else:
raise PoolEmptyError
def decrease(self, proxy):
"""
代理失效 扣1分 分数低于0 移除代理
:param proxy: 代理链接
:return: 修改后代理分数
"""
scroe = self.db.zscore(REDIS_KEY, proxy)
if scroe and scroe > MIN_SCORE:
print("代理", proxy, '当前分数', scroe, '减一')
return self.db.zincrby(REDIS_KEY, proxy)
else:
print("代理", proxy, '当前分数', scroe, '移除')
return self.db.zrem(REDIS_KEY, proxy)
def exist(self, proxy):
"""
判断代理是否存在
:param proxy:代理
:return:是否存在
"""
return not self.db.zscore(REDIS_KEY, proxy) == None
def max(self, proxy):
"""
将代理设置为最高分
:param proxy: 代理
:return: 设置结束
"""
print("代理", proxy, '可用,设置为', MAX_SCORE, '移除')
return self.db.zadd(REDIS_KEY, MAX_SCORE, proxy)
def count(self):
"""
计算代理数量
:return: 代理数量
"""
return self.db.zcard(REDIS_KEY)
def all(self):
"""
获取全部代理
:return: 全部代理列表
"""
return self.db.zrangebyscore(REDIS_KEY, MIN_SCORE, MAX_SCORE)
def batch(self, start, stop):
"""
批量获取
:param start: 开始索引
:param stop: 结束索引
:return: 代理列表
"""
return self.db.zrevrange(REDIS_KEY, start, stop - 1)
if __name__ == '__main__':
conn = RedisClient()
result = conn.batch(680, 688)
print(result)
|
import numpy as np
from divide import Predicate
from node import Node
class DecisionTree:
def build(self, X, y):
self.root = self.build_subtree(X, y)
return self
def build_subtree(self, X, y):
predicate = DecisionTree.get_best_predicate(X, y)
if predicate:
X1, y1, X2, y2 = predicate.divide(X, y)
true_branch = self.build_subtree(X1, y1)
false_branch = self.build_subtree(X2, y2)
return Node(column=predicate.column, value=predicate.value,
true_branch=true_branch, false_branch=false_branch)
else:
unique_y = np.unique(y, return_counts=True)
return unique_y[np.argmax(unique_y[1])][0]
def get_best_predicate(X, y):
best_predicate = None
best_gain = 0.0
column_count = len(X[0])
for column in range(0, column_count):
column_values = np.unique(X[:, column])
for value in column_values:
predicate = Predicate(column, value)
gain = predicate.information_gain(X, y)
if gain > best_gain:
best_predicate = predicate
best_gain = gain
return best_predicate
def predict(self, x):
return self.classify_subtree(x, self.root)
def classify_subtree(self, x, sub_tree):
if not isinstance(sub_tree, Node):
return sub_tree
else:
v = x[sub_tree.column]
if isinstance(v, int) or isinstance(v, float):
if v >= sub_tree.value:
branch = sub_tree.true_branch
else:
branch = sub_tree.false_branch
else:
if v == sub_tree.value:
branch = sub_tree.true_branch
else:
branch = sub_tree.false_branch
return self.classify_subtree(x, branch)
def __repr__(self):
return f'Decision Tree: \n{self.root};\n' |
##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. law. Dissemination
# to non-U.S. persons whether in the United States or abroad requires
# an export license or other authorization.
#
# Contractor Name: Raytheon Company
# Contractor Address: 6825 Pine Street, Suite 340
# Mail Stop B8
# Omaha, NE 68106
# 402.291.0100
#
# See the AWIPS II Master Rights File ("Master Rights File.pdf") for
# further licensing information.
##
from __future__ import print_function
import sys, os, pwd, string, getopt, logging
import numpy
from dynamicserialize.dstypes.com.raytheon.uf.common.auth.resp import SuccessfulExecution
from dynamicserialize.dstypes.com.raytheon.uf.common.dataplugin.gfe.request import GetSingletonDbIdsRequest
from dynamicserialize.dstypes.com.raytheon.uf.common.dataplugin.gfe.request import GetSiteTimeZoneInfoRequest
from dynamicserialize.dstypes.com.raytheon.uf.common.dataplugin.gfe.request import GridLocRequest
from dynamicserialize.dstypes.com.raytheon.uf.common.localization import LocalizationContext
from dynamicserialize.dstypes.com.raytheon.uf.common.localization import LocalizationLevel
from dynamicserialize.dstypes.com.raytheon.uf.common.localization import LocalizationType
from dynamicserialize.dstypes.com.raytheon.uf.common.localization.msgs import DeleteUtilityCommand
from dynamicserialize.dstypes.com.raytheon.uf.common.localization.msgs import ListUtilityCommand
from dynamicserialize.dstypes.com.raytheon.uf.common.localization.msgs import UtilityRequestMessage
from dynamicserialize.dstypes.com.raytheon.uf.common.localization.msgs import PrivilegedUtilityRequestMessage
from dynamicserialize.dstypes.com.raytheon.uf.common.localization.stream import LocalizationStreamGetRequest
from dynamicserialize.dstypes.com.raytheon.uf.common.localization.stream import LocalizationStreamPutRequest
from dynamicserialize.dstypes.com.raytheon.uf.common.message import WsId
from dynamicserialize.dstypes.com.raytheon.uf.common.site.requests import GetActiveSitesRequest
from awips import ThriftClient
#
# The ifpServerText program. Stores, deletes, gets, and inventories text.
#
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# 12/17/10 dgilling Initial Creation.
# 11/17/15 #5129 dgilling Support changes to GetSiteTimeZoneInfoRequest.
# 07/17/17 #6285 randerso Change to use new Roles/Permissions framework.
# 02/19/18 #6602 dgilling Update for new text utility
# location.
#
#
class textInventoryRecord:
def __init__(self, fileName, path="", localCtx=None, protected=False):
self.fileName = fileName
self.path = path
if localCtx is None:
self.localCtx = LocalizationContext()
self.localCtx.setLocalizationType("UNKNOWN")
self.localCtx.setLocalizationLevel("UNKNOWN")
else:
self.localCtx = localCtx
self.protected = protected
def __str__(self):
return str(self.localCtx) + self.path + "/" + self.fileName
## Logging methods ##
logger = None
def __initLogger():
global logger
logger = logging.getLogger("ifpServerText")
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# Uncomment line below to enable debug-level logging
# ch.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s: %(message)s", "%H:%M:%S")
ch.setFormatter(formatter)
logger.addHandler(ch)
class ifpServerText:
BUFFER_SIZE = 512 * 1024
EXTENSION_DICT = {"Config": ".py",
"EditArea": ".xml",
"EditAreaGroup": ".txt",
"SampleSet": ".xml",
"ColorTable": ".cmap",
"WeatherElementGroup": ".xml",
"SelectTR": ".SELECTTR",
"Tool": ".py",
"Procedure": ".py",
"TextProduct": ".py",
"TextUtility": ".py",
"Utility": ".py",
"Combinations": ".py",
"ISCUtility": ".py"
}
LOCALIZATION_DICT = {"Config": ("CAVE_STATIC", "gfe/userPython/gfeConfig"),
"EditArea": ("COMMON_STATIC", "gfe/editAreas"),
"EditAreaGroup": ("COMMON_STATIC", "gfe/editAreaGroups"),
"SampleSet": ("COMMON_STATIC", "gfe/sampleSets"),
"ColorTable": ("COMMON_STATIC", "colormaps/GFE"),
"WeatherElementGroup": ("CAVE_STATIC", "gfe/weGroups"),
"SelectTR": ("COMMON_STATIC", "gfe/text/selecttr"),
"Tool": ("CAVE_STATIC", "gfe/userPython/smartTools"),
"Procedure": ("CAVE_STATIC", "gfe/userPython/procedures"),
"TextProduct": ("CAVE_STATIC", "gfe/userPython/textProducts"),
"TextUtility": ("CAVE_STATIC", "gfe/userPython/textUtilities"),
"Utility": ("CAVE_STATIC", "gfe/userPython/utilities"),
"Combinations": ("CAVE_STATIC", "gfe/combinations"),
"ISCUtility": ("COMMON_STATIC", "isc/utilities")
}
def __init__(self):
self.__host = None
self.__port = None
self.__siteID = None
self.__user = None
self.__mode = None
self.__name = None
self.__filename = None
self.__classType = None
self.__textCategory = None
self.__metaInfo = None
self.__osUser = pwd.getpwuid(os.getuid()).pw_name
self.__cmdLine()
self.__thrift = ThriftClient.ThriftClient(self.__host, self.__port, "/services")
# build inventory:
if self.__textCategory is not None:
self.__db = self.__buildInventory()
def process(self):
# meta information
if self.__metaInfo is not None:
self.__metaInformation()
# edit area
elif self.__classType == "EditArea":
if self.__mode == "SAVE":
self.__saveEA()
elif self.__mode == "DELETE":
self.__deleteEA()
elif self.__mode == "GET":
self.__getEA()
elif self.__mode == "INVENTORY":
self.__inventoryEA()
# edit area group
elif self.__classType == "EditAreaGroup":
if self.__mode == "SAVE":
self.__saveEAGroup()
elif self.__mode == "DELETE":
self.__deleteEAGroup()
elif self.__mode == "GET":
self.__getEAGroup()
elif self.__mode == "INVENTORY":
self.__inventoryEAGroup()
# sample set
elif self.__classType == "SampleSet":
if self.__mode == "SAVE":
self.__saveSamples()
elif self.__mode == "DELETE":
self.__deleteSamples()
elif self.__mode == "GET":
self.__getSamples()
elif self.__mode == "INVENTORY":
self.__inventorySamples()
# color table
elif self.__classType == "ColorTable":
if self.__mode == "SAVE":
self.__saveCT()
elif self.__mode == "DELETE":
self.__deleteCT()
elif self.__mode == "GET":
self.__getCT()
elif self.__mode == "INVENTORY":
self.__inventoryCT()
# text stuff
elif self.__textCategory is not None:
if self.__mode == "SAVE":
self.__saveText()
elif self.__mode == "DELETE":
self.__deleteText()
elif self.__mode == "GET":
self.__getText()
elif self.__mode == "INVENTORY":
self.__inventoryText()
#error
else:
raise Exception, "Unknown class type " + self.__classType
def __cmdLine(self):
optlist, oargs = getopt.getopt(sys.argv[1:], "h:p:o:u:sn:f:c:digm:")
for opt in optlist:
if opt[0] == '-h':
self.__host = opt[1]
elif opt[0] == '-p':
self.__port = int(opt[1])
elif opt[0] == '-o':
self.__siteID = opt[1]
elif opt[0] == '-u':
self.__user = opt[1]
elif opt[0] == '-n':
self.__name = opt[1]
elif opt[0] == '-f':
self.__filename = opt[1]
elif opt[0] == '-m':
self.__metaInfo = opt[1]
elif opt[0] == '-c':
if self.__classType is not None:
self.__usage()
raise SyntaxWarning, "Too many -c switches specified"
options = ["Tool", "Procedure", "Utility", "TextUtility",
"TextProduct", "Config", "EditArea", "SelectTR",
"EditAreaGroup", "SampleSet", "WeatherElementGroup",
"ColorTable", "Combinations", "SmartTool", "ISCUtility"]
if opt[1] not in options:
self.__usage()
s = "Error: Illegal class specified " + opt[1]
raise SyntaxWarning, s
self.__classType = opt[1]
if self.__classType == "SmartTool":
self.__classType = "Tool" #maintain backwards compatible
dic = {"Config": "GFECONFIG", "EditArea": "EditAreas",
"EditAreaGroup": "EditAreaGroup", "SampleSet": "SampleSets",
"ColorTable": "ColorTable",
"WeatherElementGroup": "BUNDLE",
"SelectTR": "SELECTTR", "Tool": "Tool",
"Procedure": "Procedure", "TextProduct": "TextProduct",
"TextUtility": "TextUtility", "Utility": "Utility",
"Combinations": "COMBINATIONS", "ISCUtility": "ISCUtility"}
self.__textCategory = dic[self.__classType]
elif opt[0] == '-s':
if self.__mode is not None:
self.__usage()
raise SyntaxWarning, "Error: More than one mode specified"
self.__mode = 'SAVE'
elif opt[0] == '-d':
if self.__mode is not None:
self.__usage()
raise SyntaxWarning, "Error: More than one mode specified"
self.__mode = 'DELETE'
elif opt[0] == '-g':
if self.__mode is not None:
self.__usage()
raise SyntaxWarning, "Error: More than one mode specified"
self.__mode = 'GET'
elif opt[0] == '-i':
if self.__mode is not None:
self.__usage()
raise SyntaxWarning, "Error: More than one mode specified"
self.__mode = 'INVENTORY'
# sanity checks, make sure all required switches are specified
if self.__user is None:
self.__user = self.__osUser
if self.__host is None or self.__port is None:
self.__usage()
raise SyntaxWarning, "Error: Missing host or port"
if self.__siteID is None and self.__metaInfo not in ['sitetimezone', 'site']:
self.__usage()
raise SyntaxWarning, "Error: Missing siteID information"
if self.__mode is None and self.__metaInfo is None:
self.__usage()
raise SyntaxWarning, \
"Error: Missing Mode -m, -s, -d, -i, or -n switch"
if self.__mode == "INVENTORY" and self.__classType is None:
self.__usage()
raise SyntaxWarning, \
"Error: INVENTORY mode requires -c switch"
if self.__mode == "SAVE" and \
(self.__name is None or self.__filename is None or \
self.__classType is None):
self.__usage()
raise SyntaxWarning, \
"Error: SAVE mode requires -n, -f, and -c switches"
if self.__mode == "DELETE" and \
self.__user not in [self.__osUser, "SITE"]:
self.__usage()
raise SyntaxWarning, \
"Error: DELETE mode can only be performed on SITE or " + self.__osUser + " owned files"
if self.__mode == "SAVE" and \
self.__user not in [self.__osUser, "SITE"]:
self.__usage()
raise SyntaxWarning, \
"Error: SAVE mode can only be performed on SITE or " + self.__osUser + " owned files"
if self.__mode == "DELETE" and (self.__name is None or \
self.__classType is None):
self.__usage()
raise SyntaxWarning, \
"Error: DELETE mode requires -n and -c switches"
if self.__mode == "GET" and (self.__name is None or \
self.__classType is None):
self.__usage()
raise SyntaxWarning, \
"Error: GET mode requires -n and -c switches"
if self.__metaInfo is not None:
valid = ["site", "singleton", "sitetimezone", "domain"]
if self.__metaInfo not in valid:
self.__usage()
raise SyntaxWarning, "Error: unknown -m keyword found"
elif self.__mode is not None:
self.__usage()
raise SyntaxWarning, \
"Error: -m with -s, -d, -i, -n switches not compatible with each other"
def __usage(self):
print("""
Usage: ifpServerText -h hostname -p rpcPortNumber -o siteID [-u user]
[-s -n name -f filename -c class]
[-d -n name [-c class]]
[-i [-c class]]
[-g [-f filename] -n [-c class]]
[-m infoType [-f filename]]
-h host where the ifpServer is running
-p rpc port number for the ifpServer.
-o siteid to retrieve information for.
-u userid, defaults to login user
-s SAVEMODE
-n name to store text under
-f filename of source
-c class, one of
EditAreaGroup, EditArea, WeatherElementGroup, ColorTable
SelectTR, SampleSet, Tool, Procedure, Utility,
TextUtility, TextProduct, Config, Combinations
-d DELETEMODE
-n name to delete from ifpServer
-c class, one of
EditAreaGroup, EditArea, WeatherElementGroup, ColorTable
SelectTR, SampleSet, Tool, Procedure, Utility,
TextUtility, TextProduct, Config, Combinations
-i INVENTORYMODE
-c class, one of
EditAreaGroup, EditArea, WeatherElementGroup, ColorTable
SelectTR, SampleSet, Tool, Procedure, Utility,
TextUtility, TextProduct, Config, Combinations
-g GETMODE
-n name to get from ifpServer
-f filename to store under, or if not specified stdout
-c class, one of
EditAreaGroup, EditArea, WeatherElementGroup, ColorTable
SelectTR, SampleSet, Tool, Procedure, Utility,
TextUtility, TextProduct, Config, Combinations
-m infoType
Depending upon infoType, simply returns the requested information.
infoType can be: site (for a list of site identifiers in use),
sitetimezone (for a list of time zones in use),
singleton (for a list of single databases in use)
domain (for the database grid location, domain)
-f filename to store under, or if not specified stdout
""")
def __buildInventory(self):
invTuple = self.LOCALIZATION_DICT[self.__classType]
localLevels = ["BASE", "CONFIGURED", "SITE", "USER"]
if self.__user == "SITE":
localLevels = localLevels[:-1]
if self.__user == "CONFIGURED":
localLevels = localLevels[:-2]
elif self.__user == "BASE":
localLevels = localLevels[0]
req = UtilityRequestMessage()
cmds = []
for level in localLevels:
cmd = ListUtilityCommand()
cmd.setSubDirectory(invTuple[1])
cmd.setRecursive(False)
cmd.setFilesOnly(True)
cmd.setLocalizedSite(self.__siteID)
ctx = LocalizationContext()
ll = LocalizationLevel(level)
locType = LocalizationType(invTuple[0])
ctx.setLocalizationType(locType)
ctx.setLocalizationLevel(ll)
if level in ["CONFIGURED", "SITE"]:
ctx.setContextName(self.__siteID)
elif (level == "USER"):
ctx.setContextName(self.__user)
cmd.setContext(ctx)
cmds.append(cmd)
req.setCommands(cmds)
try:
serverResponse = self.__thrift.sendRequest(req)
except Exception, e:
raise RuntimeError, "Could not retrieve product inventory: " + str(e)
inventory = {}
for response in serverResponse.getResponses():
for entry in response.getEntries():
filename = os.path.split(entry.getFileName())[1]
shortName = os.path.splitext(filename)[0]
record = textInventoryRecord(filename, response.getPathName(), entry.getContext(), entry.getProtectedFile())
inventory[shortName] = record
return inventory
def __saveText(self):
#Saves a text file
# read the file from disk
f = open(self.__filename, 'r')
txt = f.read()
f.close()
# verify the class based on the contents of the file
if self.__classType == "Tool":
self.__verifyClass(txt, "class Tool")
elif self.__classType == "Procedure":
self.__verifyClass(txt, "class Procedure")
elif self.__classType == "TextProduct":
self.__verifyClass(txt, "class TextProduct")
# Store the main file
# need to convert python bytearray type (which is just a list of ints)
# to numpy.int8 type to ensure this data is serialized as bytes
fileBytes = numpy.asarray(bytearray(txt, 'utf8'), dtype=numpy.int8)
totalSize = len(fileBytes)
request = LocalizationStreamPutRequest()
request.setOffset(0)
localizationInfo = self.LOCALIZATION_DICT[self.__classType]
if self.__user != "SITE":
levelName = "USER"
else:
levelName = self.__user
ctx = LocalizationContext()
ll = LocalizationLevel(levelName)
locType = LocalizationType(localizationInfo[0])
ctx.setLocalizationType(locType)
ctx.setLocalizationLevel(ll)
if self.__user != "SITE":
ctx.setContextName(self.__user)
else:
ctx.setContextName(self.__siteID)
request.setContext(ctx)
request.setMyContextName(ctx.getContextName())
request.setFileName(localizationInfo[1] + "/" + self.__name + self.EXTENSION_DICT[self.__classType])
totalSent = 0
finished = False
while (not finished):
request.setOffset(totalSent)
sendBuffer = fileBytes[:self.BUFFER_SIZE]
fileBytes = fileBytes[self.BUFFER_SIZE:]
totalSent += len(sendBuffer)
request.setBytes(sendBuffer)
request.setEnd(totalSent == totalSize)
finished = request.getEnd()
try:
serverResponse = self.__thrift.sendRequest(request)
if not isinstance(serverResponse, SuccessfulExecution):
message = ""
if hasattr(serverResponse, "getMessage"):
message = serverResponse.getMessage()
raise RuntimeError(message)
serverResponse = serverResponse.getResponse()
except Exception, e:
raise RuntimeError("Could not send file to localization server: " + str(e))
logger.info("Saved file " + self.__filename + " under " + self.__name)
def __deleteText(self):
#Deletes a text file
keys = self.__db.keys()
if self.__name not in keys:
s = "DELETE failed since " + self.__name + " not in inventory"
raise KeyError, s
record = self.__db[self.__name]
if self.__user != "SITE" and str(record.localCtx.getLocalizationLevel()) != "USER":
raise RuntimeError, "User can only delete user-level files."
if self.__user == "SITE" and str(record.localCtx.getLocalizationLevel()) != "SITE":
raise RuntimeError, "SITE can only delete site-level files."
req = PrivilegedUtilityRequestMessage()
cmds = []
cmd = DeleteUtilityCommand()
cmd.setContext(record.localCtx)
cmd.setFilename(record.path + "/" + record.fileName)
cmd.setMyContextName(record.localCtx.getContextName())
cmds.append(cmd)
# make sure to delete the .pyo and .pyc files as well
if os.path.splitext(record.fileName)[1] == ".py":
for ext in ["c", "o"]:
cmd = DeleteUtilityCommand()
cmd.setContext(record.localCtx)
cmd.setFilename(record.path + "/" + record.fileName + ext)
cmd.setMyContextName(record.localCtx.getContextName())
cmds.append(cmd)
req.setCommands(cmds)
try:
serverResponse = self.__thrift.sendRequest(req)
if not isinstance(serverResponse, SuccessfulExecution):
message = ""
if hasattr(serverResponse, "getMessage"):
message = serverResponse.getMessage()
raise RuntimeError(message)
serverResponse = serverResponse.getResponse()
except Exception, e:
raise RuntimeError("Could not delete file from localization server: " + str(e))
logger.info("Deleted " + self.__name)
def __getText(self):
#Gets the text file
keys = self.__db.keys()
if self.__name not in keys:
s = "GET failed since " + self.__name + " not in inventory"
raise KeyError, s
invRecord = self.__db[self.__name]
request = LocalizationStreamGetRequest()
request.setOffset(0)
request.setNumBytes(self.BUFFER_SIZE)
request.setContext(invRecord.localCtx)
request.setMyContextName(invRecord.localCtx.getContextName())
request.setFileName(invRecord.path + "/" + invRecord.fileName)
finished = False
txt = ""
while (not finished):
try:
serverResponse = self.__thrift.sendRequest(request)
if not isinstance(serverResponse, SuccessfulExecution):
message = ""
if hasattr(serverResponse, "getMessage"):
message = serverResponse.getMessage()
raise RuntimeError(message)
serverResponse = serverResponse.getResponse()
except Exception, e:
raise RuntimeError("Could not retrieve file from localization server: " + str(e))
# serverResponse will be returned as a LocalizationStreamPutRequest
# object. we'll use its methods to read back the serialized file
# data.
# bytes get returned to us as an numpy.ndarray
fileBytes = serverResponse.getBytes()
txt += fileBytes.tostring()
request.setOffset(request.getOffset() + len(fileBytes))
finished = serverResponse.getEnd()
if self.__filename is None:
print(txt)
else:
f = open(self.__filename, 'w', 0644)
f.write(txt)
f.close()
logger.info("Got " + self.__name + " --- written to " + self.__filename)
def __inventoryText(self):
#Returns the inventory
keys = self.__db.keys()
print("%-40s" % "Name", "%-15s" % "Access", "Protect")
print("%-40s" % "----", "%-15s" % "------", "-------")
keys.sort()
for k in keys:
a = self.__db[k]
if a.protected == True:
pro = 'Read-Only'
else:
pro = 'Read-Write'
print("%-40s" % k, "%-15s" % a.localCtx.getLocalizationLevel(), pro)
def __verifyClass(self, txt, searchString):
lines = string.split(txt, '\n')
for line in lines:
index = string.find(line, searchString)
if index != -1:
return 1
s = "Input file is not written in class format or contains improper type"
raise Exception(s)
def __saveSamples(self):
#Saves a sample set format: #points, lon/lat, lon/lat, .....
self.__saveText()
def __deleteSamples(self):
#Deletes a sample set
self.__deleteText()
def __getSamples(self):
#Gets a sample set
self.__getText()
def __inventorySamples(self):
#Returns the inventory for sample sets
self.__inventoryText()
def __saveCT(self):
#Saves a color table format: #points, rgb, rgb, rgb, rgb
self.__saveText()
def __deleteCT(self):
#Deletes a color table
self.__deleteText()
def __getCT(self):
#Gets a color table
self.__getText()
def __inventoryCT(self):
#Returns the inventory for color tables
self.__inventoryText()
def __saveEA(self):
#Saves an edit area
self.__saveText()
def __deleteEA(self):
#Deletes a text file
self.__deleteText()
def __getEA(self):
#Gets the edit area
self.__getText()
def __inventoryEA(self):
#Returns the inventory for edit areas
self.__inventoryText()
def __saveEAGroup(self):
#Saves a text file
self.__saveText()
def __deleteEAGroup(self):
#Deletes an edit area group
self.__deleteText()
def __getEAGroup(self):
#Gets the text file, decodes it
self.__getText()
def __inventoryEAGroup(self):
#Returns the inventory
self.__inventoryText()
def __metaInformation(self):
# gets the meta information
txt = ""
wsId = WsId(progName="ifpServerText")
if self.__metaInfo == "sitetimezone":
request = GetActiveSitesRequest()
try:
serverResponse = self.__thrift.sendRequest(request)
except Exception, e:
raise RuntimeError, "Could not retrieve meta information: " + str(e)
siteIds = serverResponse
request = GetSiteTimeZoneInfoRequest()
request.setWorkstationID(wsId)
request.setSiteID("")
request.setRequestedSiteIDs(siteIds)
try:
serverResponse = self.__thrift.sendRequest(request)
except Exception, e:
raise RuntimeError, "Could not retrieve meta information: " + str(e)
if (serverResponse.isOkay()):
tzInfo = serverResponse.getPayload()
for k in tzInfo.keys():
txt = txt + k + ' ' + tzInfo[k] + "\n"
else:
raise Exception, serverResponse.message()
elif self.__metaInfo == "site":
request = GetActiveSitesRequest()
try:
serverResponse = self.__thrift.sendRequest(request)
except Exception, e:
raise RuntimeError, "Could not retrieve meta information: " + str(e)
for site in serverResponse:
txt = txt + site + "\n"
elif self.__metaInfo == "singleton":
request = GetSingletonDbIdsRequest()
request.setWorkstationID(wsId)
request.setSiteID(self.__siteID)
try:
serverResponse = self.__thrift.sendRequest(request)
except Exception, e:
raise RuntimeError, "Could not retrieve meta information: " + str(e)
if (serverResponse.isOkay()):
singletons = serverResponse.getPayload()
for s in singletons:
txt = txt + str(s) + "\n"
else:
raise Exception, serverResponse.message()
elif self.__metaInfo == "domain":
request = GridLocRequest()
request.setWorkstationID(wsId)
request.setSiteID(self.__siteID)
try:
serverResponse = self.__thrift.sendRequest(request)
except Exception, e:
raise RuntimeError, "Could not retrieve meta information: " + str(e)
if (serverResponse.isOkay()):
domain = serverResponse.getPayload()
proj = domain.getProjection()
txt = "ProjectionID: " + proj.getProjectionID() + "\n"
txt = txt + "Grid Size: " + repr((domain.getNx(), domain.getNy())) + "\n"
txt = txt + "Grid Domain: " + repr((domain.getOrigin(), domain.getExtent())) + "\n"
keys = proj.keys()
for k in keys:
txt = txt + k + ': ' + str(getattr(proj, k)) + "\n"
else:
raise Exception, serverResponse.message()
if self.__filename is None:
print(txt)
else:
f = open(self.__filename, 'w', 0644)
f.write(txt)
f.close()
logger.info("Got MetaInfo " + self.__metaInfo + " --- written to " + self.__filename)
def main():
__initLogger()
logger.info("ifpServerText Starting")
try:
obj = ifpServerText()
obj.process()
except Exception, e:
logger.exception("Error encountered running ifpServerText:")
sys.exit(1)
logger.info("ifpServerText Finished")
sys.exit(0)
if __name__ == "__main__":
main()
|
from flask_sqlalchemy import SQLAlchemy
class Repository:
def __init__(self):
pass
db = SQLAlchemy
|
class SarsaAgent(acme.Actor):
def __init__(self,
environment_spec: specs.EnvironmentSpec,
epsilon: float,
step_size: float = 0.1
):
# Get number of states and actions from the environment spec.
self._num_states = environment_spec.observations.num_values
self._num_actions = environment_spec.actions.num_values
# Create the table of Q-values, all initialized at zero.
self._q = np.zeros((self._num_states, self._num_actions))
# Store algorithm hyper-parameters.
self._step_size = step_size
self._epsilon = epsilon
# Containers you may find useful.
self._state = None
self._action = None
self._next_state = None
@property
def q_values(self):
return self._q
def select_action(self, observation):
return epsilon_greedy(self._q[observation], self._epsilon)
def observe_first(self, timestep):
# Set current state.
self._state = timestep.observation
def observe(self, action, next_timestep):
# Unpacking the timestep to lighten notation.
s = self._state
a = action
r = next_timestep.reward
g = next_timestep.discount
next_s = next_timestep.observation
# Compute the action that would be taken from the next state.
next_a = self.select_action(next_s)
# Compute the on-policy Q-value update.
self._action = a
self._next_state = next_s
# TODO complete the line below to compute the temporal difference error
self._td_error = r + g * self._q[next_s, next_a] - self._q[s, a]
def update(self):
# Optional unpacking to lighten notation.
s = self._state
a = self._action
# Update the Q-value table value at (s, a).
# TODO: Update the Q-value table value at (s, a).
self._q[s, a] += self._step_size * self._td_error
# Update the current state.
self._state = self._next_state |
from typing import Tuple
from ..gameModel import GameModel
def putChess(cls: GameModel, pos: Tuple[int]):
"""
make in-place operation for both boards
and switch player.
Used in playing and test (pretend user and computer)
"""
cls.last_pos = pos
r, c = pos
cls.board_for_calc[r][c] = cls.point_map[cls.is_user_turn]
cls.board[r][c] = cls.chess_map[cls.is_user_turn]
cls.is_user_turn = not cls.is_user_turn
return |
#coding:utf-8
import os
import shutil
import tempfile
import unittest2 as unittest
import time
from replmon import Replmon
class StatusFileTestCase(unittest.TestCase):
def setUp(self):
self.test_dir = tempfile.mkdtemp()
self.status_file = os.path.join(self.test_dir, "replmon.status")
self.mon = Replmon({})
self.mon.status_file = self.status_file
def tearDown(self):
shutil.rmtree(self.test_dir)
def assertFileExists(self, path):
try:
open(path)
except IOError:
self.fail("File does not exist: {0}".format(path))
def test_create_status_file(self):
self.mon.touch_status_file()
self.assertFileExists(self.status_file)
def test_touch_status_file(self):
atime = mtime = 1
open(self.status_file, "w")
os.utime(self.status_file, (atime, mtime))
self.mon.touch_status_file()
stat = os.stat(self.status_file)
self.assertNotEqual(atime, stat.st_atime)
self.assertNotEqual(mtime, stat.st_mtime)
self.assertAlmostEqual(time.time(), stat.st_atime, delta=2)
self.assertAlmostEqual(time.time(), stat.st_mtime, delta=2)
|
# This class parses a gtfs text file
class Reader:
def __init__(self, file):
self.fields = []
self.fp = open(file, "r")
self.fields.extend(self.fp.readline().rstrip().split(","))
def get_line(self):
data = {}
line = self.fp.readline().rstrip().split(",")
for el, field in zip (line, self.fields):
data[field] = el
if len(data) == 1:
return None
else:
return data
def end(self):
self.fp.close() |
from Classes.Logic.LogicCommandManager import LogicCommandManager
from Classes.Messaging import Messaging
from Classes.Packets.PiranhaMessage import PiranhaMessage
class EndClientTurnMessage(PiranhaMessage):
def __init__(self, messageData):
super().__init__(messageData)
self.messageVersion = 0
def encode(self, fields):
pass
def decode(self):
fields = {}
self.readBoolean()
fields["Tick"] = self.readVInt()
fields["Checksum"] = self.readVInt()
fields["CommandsCount"] = self.readVInt()
super().decode(fields)
fields["Commands"] = []
for i in range(fields["CommandsCount"]):
fields["Commands"].append({"ID": self.readVInt()})
if LogicCommandManager.commandExist(fields["Commands"][i]["ID"]):
command = LogicCommandManager.createCommand(fields["Commands"][i]["ID"])
print("Command", LogicCommandManager.getCommandsName(fields["Commands"][i]["ID"]))
if command is not None:
fields["Commands"][i]["Fields"] = command.decode(self)
fields["Commands"][i]["Instance"] = command
return fields
def execute(message, calling_instance, fields):
fields["Socket"] = calling_instance.client
for command in fields["Commands"]:
if "Instance" not in command.keys():
return
if hasattr(command["Instance"], 'execute'):
command["Instance"].execute(calling_instance, command["Fields"])
def getMessageType(self):
return 14102
def getMessageVersion(self):
return self.messageVersion |
from setuptools import setup
with open("requirements.txt") as f:
requirements = f.read().splitlines()
setup(
name="reagan",
version="2.3.0",
description="Package for streamlining credentials, connections, and data flow",
url="https://github.com/schustda/reagan",
author="Douglas Schuster",
author_email="[email protected]",
packages=["reagan"],
zip_safe=False,
install_requires=requirements,
)
|
from urlparse import urlparse
import logging
import requests
logger = logging.getLogger('solr_detective.app')
class BaseDao(object):
def __init__(self):
pass
class HttpBaseDao(BaseDao):
PROXIES = None
def parse_url_data(self, url):
result = urlparse(url)
return {
'error_url': url,
'error_host': result.netloc,
'error_url_path': result.path,
'error_url_query_string': result.query
}
def get_data(self, url, **kwargs):
try:
if self.PROXIES:
return requests.get(url, proxies=self.PROXIES, **kwargs)
else:
return requests.get(url, **kwargs)
except requests.exceptions.ConnectTimeout as e:
logger.error('HttpBaseDao Connection timeout',
extra=self.parse_url_data(url))
except requests.exceptions.ReadTimeout as e:
logger.error('HttpBaseDao Read timeout',
extra=self.parse_url_data(url))
except requests.exceptions.ConnectionError as e:
logger.error('HttpBaseDao Connection error',
extra=self.parse_url_data(url))
def post_data(self, url, **kwargs):
try:
if self.PROXIES:
return requests.post(url, proxies=self.PROXIES, **kwargs)
else:
return requests.post(url, **kwargs)
except requests.exceptions.ConnectTimeout as e:
logger.error('HttpBaseDao Connection timeout',
extra=self.parse_url_data(url))
except requests.exceptions.ReadTimeout as e:
logger.error('HttpBaseDao Read timeout',
extra=self.parse_url_data(url))
except requests.exceptions.ConnectionError as e:
logger.error('HttpBaseDao Connection error',
extra=self.parse_url_data(url))
|
from django.db import models
from django.db.models.deletion import CASCADE
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
class BaseMeaning(models.Model):
global_id = models.CharField(max_length=50)
part_of_speech = models.CharField(max_length=50)
text = models.CharField(max_length=400)
def __str__(self) -> str:
return self.global_id
class Word(models.Model):
basemeaning = models.ForeignKey(BaseMeaning, on_delete=models.CASCADE)
word = models.CharField(max_length=50)
labels = models.CharField(max_length=100)
def __str__(self) -> str:
return self.word |
from .. import paths
MODELS_PATH = paths.ROOT_PATH.joinpath('models')
def imagenet():
path = MODELS_PATH.joinpath('nin_imagenet')
return path
def regnet_tf():
path = MODELS_PATH.joinpath('regnet-tf')
return path
def multimodal():
path = MODELS_PATH.joinpath('multimodal')
return path
|
"""PgQ ticker.
It will also launch maintenance job.
"""
import sys, os, time, threading
import skytools
from maint import MaintenanceJob
__all__ = ['SmallTicker']
class SmallTicker(skytools.DBScript):
"""Ticker that periodically calls pgq.ticker()."""
tick_count = 0
maint_thread = None
def __init__(self, args):
skytools.DBScript.__init__(self, 'pgqadm', args)
self.ticker_log_time = 0
self.ticker_log_delay = 5*60
def reload(self):
skytools.DBScript.reload(self)
self.ticker_log_delay = self.cf.getfloat("ticker_log_delay", 5*60)
def startup(self):
if self.maint_thread:
return
# launch maint thread
self.maint_thread = MaintenanceJob(self, [self.cf.filename])
t = threading.Thread(name = 'maint_thread',
target = self.maint_thread.run)
t.setDaemon(1)
t.start()
def work(self):
db = self.get_database("db", autocommit = 1)
cx = db.cursor()
# run ticker
cx.execute("select pgq.ticker()")
self.tick_count += cx.fetchone()[0]
cur_time = time.time()
if cur_time > self.ticker_log_time + self.ticker_log_delay:
self.ticker_log_time = cur_time
self.stat_increase('ticks', self.tick_count)
self.tick_count = 0
|
__author__ = 'feurerm'
import copy
import unittest
import numpy as np
import sklearn.datasets
import sklearn.metrics
from autosklearn.pipeline.components.data_preprocessing.balancing.balancing \
import Balancing
from autosklearn.pipeline.classification import SimpleClassificationPipeline
from autosklearn.pipeline.components.classification.adaboost import AdaboostClassifier
from autosklearn.pipeline.components.classification.decision_tree import DecisionTree
from autosklearn.pipeline.components.classification.extra_trees import ExtraTreesClassifier
from autosklearn.pipeline.components.classification.gradient_boosting import GradientBoostingClassifier
from autosklearn.pipeline.components.classification.random_forest import RandomForest
from autosklearn.pipeline.components.classification.liblinear_svc import LibLinear_SVC
from autosklearn.pipeline.components.classification.libsvm_svc import LibSVM_SVC
from autosklearn.pipeline.components.classification.sgd import SGD
from autosklearn.pipeline.components.feature_preprocessing\
.extra_trees_preproc_for_classification import ExtraTreesPreprocessorClassification
from autosklearn.pipeline.components.feature_preprocessing.liblinear_svc_preprocessor import LibLinear_Preprocessor
class BalancingComponentTest(unittest.TestCase):
def test_balancing_get_weights_treed_single_label(self):
Y = np.array([0] * 80 + [1] * 20)
balancing = Balancing(strategy='weighting')
init_params, fit_params = balancing.get_weights(
Y, 'adaboost', None, None, None)
self.assertTrue(np.allclose(fit_params['classifier:sample_weight'],
np.array([0.4] * 80 + [1.6] * 20)))
#init_params, fit_params = balancing.get_weights(
# Y, None, 'extra_trees_preproc_for_classification', None, None)
#self.assertTrue(np.allclose(fit_params['preprocessor:sample_weight'],
# np.array([0.4] * 80 + [1.6] * 20)))
def test_balancing_get_weights_treed_multilabel(self):
Y = np.array([[0, 0, 0]] * 100 + [[1, 0, 0]] * 100 + [[0, 1, 0]] * 100 +
[[1, 1, 0]] * 100 + [[0, 0, 1]] * 100 + [[1, 0, 1]] * 10)
balancing = Balancing(strategy='weighting')
init_params, fit_params = balancing.get_weights(
Y, 'adaboost', None, None, None)
self.assertTrue(np.allclose(fit_params['classifier:sample_weight'],
np.array([0.4] * 500 + [4.0] * 10)))
#init_params, fit_params = balancing.get_weights(
# Y, None, 'extra_trees_preproc_for_classification', None, None)
#self.assertTrue(np.allclose(fit_params['preprocessor:sample_weight'],
# np.array([0.4] * 500 + [4.0] * 10)))
def test_balancing_get_weights_svm_sgd(self):
Y = np.array([0] * 80 + [1] * 20)
balancing = Balancing(strategy='weighting')
init_params, fit_params = balancing.get_weights(
Y, 'libsvm_svc', None, None, None)
self.assertEqual(("classifier:class_weight", "auto"),
list(init_params.items())[0])
init_params, fit_params = balancing.get_weights(
Y, None, 'liblinear_svc_preprocessor', None, None)
self.assertEqual(("preprocessor:class_weight", "auto"),
list(init_params.items())[0])
def test_weighting_effect(self):
data = sklearn.datasets.make_classification(
n_samples=200, n_features=10, n_redundant=2, n_informative=2,
n_repeated=2, n_clusters_per_class=2, weights=[0.8, 0.2],
random_state=1)
for name, clf, acc_no_weighting, acc_weighting in \
[('adaboost', AdaboostClassifier, 0.810, 0.735),
('decision_tree', DecisionTree, 0.780, 0.643),
('extra_trees', ExtraTreesClassifier, 0.75, 0.800),
('gradient_boosting', GradientBoostingClassifier,
0.789, 0.762),
('random_forest', RandomForest, 0.75, 0.821),
('libsvm_svc', LibSVM_SVC, 0.769, 0.706),
('liblinear_svc', LibLinear_SVC, 0.762, 0.72),
('sgd', SGD, 0.739, 0.735)
]:
for strategy, acc in [('none', acc_no_weighting),
('weighting', acc_weighting)]:
# Fit
data_ = copy.copy(data)
X_train = data_[0][:100]
Y_train = data_[1][:100]
X_test = data_[0][100:]
Y_test = data_[1][100:]
include = {'classifier': [name],
'preprocessor': ['no_preprocessing']}
classifier = SimpleClassificationPipeline(
random_state=1, include=include)
cs = classifier.get_hyperparameter_search_space()
default = cs.get_default_configuration()
default._values['balancing:strategy'] = strategy
classifier = SimpleClassificationPipeline(
default, random_state=1, include=include)
predictor = classifier.fit(X_train, Y_train)
predictions = predictor.predict(X_test)
self.assertAlmostEqual(acc,
sklearn.metrics.f1_score(predictions, Y_test),
places=3)
# pre_transform and fit_estimator
data_ = copy.copy(data)
X_train = data_[0][:100]
Y_train = data_[1][:100]
X_test = data_[0][100:]
Y_test = data_[1][100:]
classifier = SimpleClassificationPipeline(
default, random_state=1, include=include)
classifier.set_hyperparameters(configuration=default)
Xt, fit_params = classifier.pre_transform(X_train, Y_train)
classifier.fit_estimator(Xt, Y_train, **fit_params)
predictions = classifier.predict(X_test)
self.assertAlmostEqual(acc,
sklearn.metrics.f1_score(
predictions, Y_test),
places=3)
for name, pre, acc_no_weighting, acc_weighting in \
[('extra_trees_preproc_for_classification',
ExtraTreesPreprocessorClassification, 0.625, 0.634),
('liblinear_svc_preprocessor', LibLinear_Preprocessor,
0.75, 0.706)]:
for strategy, acc in [('none', acc_no_weighting),
('weighting', acc_weighting)]:
data_ = copy.copy(data)
X_train = data_[0][:100]
Y_train = data_[1][:100]
X_test = data_[0][100:]
Y_test = data_[1][100:]
include = {'classifier': ['sgd'], 'preprocessor': [name]}
classifier = SimpleClassificationPipeline(
random_state=1, include=include)
cs = classifier.get_hyperparameter_search_space()
default = cs.get_default_configuration()
default._values['balancing:strategy'] = strategy
classifier.set_hyperparameters(default)
predictor = classifier.fit(X_train, Y_train)
predictions = predictor.predict(X_test)
self.assertAlmostEqual(acc,
sklearn.metrics.f1_score(
predictions, Y_test),
places=3)
# pre_transform and fit_estimator
data_ = copy.copy(data)
X_train = data_[0][:100]
Y_train = data_[1][:100]
X_test = data_[0][100:]
Y_test = data_[1][100:]
default._values['balancing:strategy'] = strategy
classifier = SimpleClassificationPipeline(
default, random_state=1, include=include)
Xt, fit_params = classifier.pre_transform(X_train, Y_train)
classifier.fit_estimator(Xt, Y_train, **fit_params)
predictions = classifier.predict(X_test)
self.assertAlmostEqual(acc,
sklearn.metrics.f1_score(
predictions, Y_test),
places=3)
|
import time
from kivy.animation import Animation
from kivy.lang.builder import Builder
from kivy.properties import BooleanProperty, NumericProperty, StringProperty
Builder.load_string(
"""
<AKAnimationBehaviorBase>:
canvas.before:
PushMatrix
Rotate:
angle: root._angle
origin: self.center
canvas.after:
PopMatrix
"""
)
class AKAnimationBehaviorBase:
duartion = NumericProperty(0.5)
transition = StringProperty("out_cubic")
animation_disabled = BooleanProperty(False)
_angle = NumericProperty()
_first_text = True
def _start_animate(self):
if self.animation_disabled:
return
if self._angle <= 180:
_angle = 360
else:
_angle = 0
if not self._first_text:
anim = Animation(
_angle=_angle, duration=self.duartion, t=self.transition
)
anim.start(self)
self._first_text = False
class AKAnimationTextBehavior(AKAnimationBehaviorBase):
def on_text(self, *args):
self._start_animate()
class AKAnimationIconBehavior(AKAnimationBehaviorBase):
def on_icon(self, *args):
self._start_animate()
|
from ariadne import MutationType
from .users import resolve_login, get_user, modify_user
from .guilds import get_guild, modify_guild
mutation = MutationType()
mutation.set_field("login", resolve_login)
mutation.set_field("user", get_user)
mutation.set_field("get_guild", get_guild)
mutation.set_field("modify_guild", modify_guild)
mutation.set_field("modify_user", modify_user)
|
# Copyright 2021 Waseda Geophysics Laboratory
#
# 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.
from setuptools import setup, find_packages
setup(
name = 'emulatte',
version = '0.1.0',
description = 'A Primitive Tools for Electromagnetic Explorations',
long_description = 'README',
author = 'Takumi Ueda',
author_email = '[email protected]',
url = 'https://github.com/WasedaGeophysics/emulatte.git',
license = license("Apache2.0"),
packages = find_packages(exclude=('docs', 'tests', 'tutorials')),
install_requires = open('requirements.txt').read().splitlines(),
) |
# Generated by Django 3.1.14 on 2021-12-17 07:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('log', '0008_workouttype_user'),
]
operations = [
migrations.AlterField(
model_name='workouttype',
name='icon',
field=models.ImageField(default='icons/star.png', upload_to='icons/'),
),
]
|
# -*- coding:utf-8 -*-
import json
import sys
from atp.utils.remoteBridge import RemoteBridge
from atp.api.comm_log import logger
class Encryption(RemoteBridge):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def map_to_sign(self, params):
if isinstance(params, str):
params_dict = eval(params)
else:
params_dict = params
body = {
"map_info": params_dict,
}
response = self.remote_http_post(self.map_to_sign_url, body)
r_dict = json.loads(response)
return r_dict
def map_to_sign_common(self, params, key='122111111'):
# params_dict = eval(params)
if isinstance(params, str):
params_dict = eval(params)
else:
params_dict = params
body = {
"secrectKey": key,
"map_info": params_dict,
}
response = self.remote_http_post(self.map_to_sign_common_url, body)
return response
def map_to_sign_new(self, params):
# params_dict = eval(params)
body = {
"map_info": params,
}
response = self.remote_http_post(self.map_to_sign_url, body)
r_dict = json.loads(response)
return r_dict
def map_to_sign_sdk(self, params, key="111+W111MBs="):
if isinstance(params, str):
params_dict = eval(params)
else:
params_dict = params
body = {
"secrectKey": key,
"map_info": params_dict,
}
response = self.remote_http_post(self.map_to_sign_sdk_url, body)
r_dict = json.loads(response)
return r_dict
def map_to_sign_capital_hub(self, params):
if isinstance(params, str):
params_dict = eval(params)
else:
params_dict = params
body = {
"map_info": params_dict,
}
response = self.remote_http_post(self.map_to_sign_capital_hub_url, body)
r_dict = json.loads(response)
return r_dict
def encrypt_public_key(self, plainText, publicKeyText):
body = {
"publicKey": publicKeyText,
"plainText": plainText,
}
response = self.remote_http_post(self.encrypt_public_key_url, body)
r_dict = json.loads(response)
try:
content = r_dict["content"]
except KeyError:
raise KeyError("调用{func_name}方法后, 解析返回内容失败, 缺少content".format(func_name=sys._getframe().f_code.co_name))
return content
def encrypt_public_key_df(self, plainText, publicKeyText):
body = {
"publicKey": publicKeyText,
"plainText": plainText,
}
response = self.remote_http_post(self.encrypt_public_key_url_df, body)
r_dict = json.loads(response)
try:
content = r_dict["content"]
except KeyError:
raise KeyError("调用{func_name}方法后, 解析返回内容失败, 缺少content".format(func_name=sys._getframe().f_code.co_name))
return content
def encryptByPublicKey(self, content, keyPair):
body = {
"publicKey": keyPair,
"plainText": content,
}
response = self.remote_http_post(self.encrypt_public_key_url, body)
r_dict = json.loads(response)
try:
content = r_dict["content"]
except KeyError:
raise KeyError("调用{func_name}方法后, 解析返回内容失败, 缺少content".format(func_name=sys._getframe().f_code.co_name))
return content
def aes(self, jsKey, text):
body = {
"publicKey": jsKey,
"plainText": text,
}
response = self.remote_http_post(self.aes_url, body)
r_dict = json.loads(response)
try:
content = r_dict["content"]
except KeyError:
raise KeyError("调用{func_name}方法后, 解析返回内容失败, 缺少content".format(func_name=sys._getframe().f_code.co_name))
return content
def encrypt(self, params_source, key="lV9pp312312312jYHkg=="):
body = {
"publicKey": key,
"plainText": params_source,
}
response = self.remote_http_post(self.encrypt_url, body)
r_dict = json.loads(response)
try:
content = r_dict["content"]
except KeyError:
raise KeyError("调用{func_name}方法后, 解析返回内容失败, 缺少content".format(func_name=sys._getframe().f_code.co_name))
return content
def decript(self, Key, cipherText, ec=None):
if ec:
body = {
"cipherText": cipherText,
"password": Key,
"ec": int(ec),
}
else:
body = {
"cipherText": cipherText,
"password": Key,
}
response = self.remote_http_post(self.decrypt_url, body)
return response
if __name__ == '__main__':
'''
test cases
'''
e = Encryption()
result = e.map_to_sign_common(json.dumps({
"content": "13213",
"timestamp": "1465802761723",
"contact": "13585662222"
}))
print(result)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import gensim
import itertools
import os
import shutil
import sys
import yaml
from dnnwsd.pipeline import supervised
def run_pipeline(corpus_dir, results_dir, experiments, configuration):
pipeline = supervised.SupervisedPipeline(
corpus_dir, results_dir, experiments,
corpus_directory_iterator=configuration['corpus']['iterator'],
iterations=configuration['pipeline']['iterations']
)
pipeline.run()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Main script to run experiments")
parser.add_argument("config_file", help="YAML Configuration File")
args = parser.parse_args()
with open(args.config_file, 'r') as f:
config = yaml.load(f.read())
results_directory = os.path.join(config['results']['directory'])
if os.path.isdir(results_directory):
overwrite = raw_input("Want to overwrite results? (Y/n)").strip().lower()
overwrite = "y" if overwrite == "" else overwrite
if overwrite.startswith("y"):
shutil.rmtree(results_directory)
else:
sys.exit(1)
os.makedirs(results_directory)
shutil.copy2(args.config_file, results_directory)
corpus_directory = config['corpus']['directory']
iterations = config['pipeline']['iterations']
print >> sys.stderr, "Loading word2vec model"
word2vec_model = gensim.models.Word2Vec.load_word2vec_format(
config['pipeline']['word2vec_model_path'], binary=True
)
experiment_set = []
for processor, model in itertools.product(config['pipeline']['processors'], config['pipeline']['models']):
model = model.copy() # To modify it without touching the original
pkey = processor
pparam = {'window_size': config['pipeline']['processors_defaults']['window_size']}
if pkey in {'bow', 'bopos', 'pos'}:
pparam['vocabulary_filter'] = config['pipeline']['processors_defaults']['vocabulary_filter']
if pkey in {'bopos', 'pos'}:
pparam['pos_filter'] = config['pipeline']['processors_defaults']['pos_filter']
if pkey in {'wordvec', 'wordvecpos'}:
pparam['word2vec_model'] = word2vec_model
mkey = model.pop('type')
mparam = model
mparam.update(config['pipeline']['models_defaults'].get(mkey, {}))
experiment_set.append((pkey, pparam, mkey, mparam))
run_pipeline(corpus_directory, results_directory, experiment_set, config)
print >> sys.stderr, "Finished all experiments"
|
import pathlib
import ssl
import os
import datetime
import json
import pywhatkit
import sys
import time
import urllib.request
import twilio
print("Check completed, All required modules are found - you can run : cowin_crawler_wraper.ksh | Windows users : A "
"direct run of cowin_slot_search.py <path> should be done ! Please refer Git readme")
print("Please note - Log will be captured in : ~/log_dump/cowin folder - script creates this path id required ! For "
"Windows Users : Script rel;ys on the passed path by user ! Please refer Git readme ")
print(
'Please verify if Drive path specified in config file is correct and sync is enabled for you to check heartbeats ! '
'path should have traiing folder slash - / for mac and unix ; // for windows Please note windows users shold give '
'path with //')
print("Refer readme.md") |
# Use setuptools if we can
try:
from setuptools.core import setup
except ImportError:
from distutils.core import setup
PACKAGE = 'django_ballads'
VERSION = '0.3'
setup(
name=PACKAGE, version=VERSION,
description="Django library for coordinating multi-system transactions (eg database, filesystem, remote API calls).",
packages=[
'django_ballads',
],
license='MIT',
author='James Aylett',
author_email='[email protected]',
install_requires=[
'Django~=1.8.0',
],
url = 'https://github.com/jaylett/django-ballads',
classifiers = [
'Intended Audience :: Developers',
'Framework :: Django',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
)
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 21 11:23:22 2020
@author: Admin
"""
import IPython
import matplotlib.pyplot as plt
import numpy as np
import soundfile as sf
from tqdm import tqdm
import pathlib
import os
from wpe import wpe
from wpe import get_power
from utils import stft, istft, get_stft_center_frequencies
project_root = pathlib.Path(os.path.abspath(
os.path.join(os.path.dirname(__file__), os.pardir)
))
#Audio Data
real_name='reverb_Nguyen_Doan_Toan _PCT'
file_type='.wav'
file_name=real_name + file_type
signal_list,sampling_rate = sf.read(str(project_root / 'my_data' / '0.1 - 0.7'/ 'reverb_data'/ file_name))
#Parameters
stft_options = dict(size=512, shift=128)
#Setup
channels = 1
delay = 3
iterations = 5
taps = 10
alpha=0.9999
y = np.stack(signal_list, axis=0)
y = np.reshape(y,(1,y.shape[0]))
IPython.display.Audio(y[0], rate=sampling_rate)
Y = stft(y, **stft_options).transpose(2, 0, 1)
Z = wpe(
Y,
taps=taps,
delay=delay,
iterations=iterations,
statistics_mode='full'
).transpose(1, 2, 0)
z = istft(Z, size=stft_options['size'], shift=stft_options['shift'])
IPython.display.Audio(z[0], rate=sampling_rate)
print("Finish dereverberation")
#Power spectrum
# plt.figure(1)
# fig, [ax1, ax2] = plt.subplots(1, 2, figsize=(20, 10))
# im1 = ax1.imshow(20 * np.log10(np.abs(Y[ :, 0, 200:400])), origin='lower')
# ax1.set_xlabel('frames')
# _ = ax1.set_title('reverberated')
# im2 = ax2.imshow(20 * np.log10(np.abs(Z[0, 200:400, :])).T, origin='lower', vmin=-120, vmax=0)
# ax2.set_xlabel('frames')
# _ = ax2.set_title('dereverberated')
# cb = fig.colorbar(im2)
#save the dereverbration sound file
z_save=np.reshape(z,(z.shape[1],))
outputname=real_name + '_offline_fix'+file_type
sf.write(str(project_root / 'output' / outputname), z_save, sampling_rate)
#plot signal
plt.figure(2)
axs1 = plt.subplot(211)
plt.plot(y[0,:])
plt.subplot(212, sharex=axs1, sharey=axs1)
plt.plot(z[0,:])
plt.show()
print(y[0,:].shape)
print(z[0,:].shape) |
# BlueGraph: unifying Python framework for graph analytics and co-occurrence analysis.
# Copyright 2020-2021 Blue Brain Project / EPFL
# 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.
from abc import (ABC, abstractmethod)
from bluegraph.exceptions import BlueGraphException, BlueGraphWarning
class MetricProcessor(ABC):
"""Abstract class for processing various graph metrics."""
@classmethod
def from_graph_object(cls, graph_object):
"""Instantiate a MetricProcessor directly from a Graph object."""
processor = cls()
processor.graph = graph_object
return processor
@staticmethod
@abstractmethod
def _generate_graph(pgframe):
"""Generate the appropiate graph representation from a PGFrame."""
pass
@abstractmethod
def degree_centrality(self, weight=None, write=False):
"""Compute (weighted) degree centrality."""
pass
@abstractmethod
def pagerank_centrality(self, weight=None, write=False):
"""Compute (weighted) PageRank centrality."""
pass
@abstractmethod
def betweenness_centrality(self, distance=None, write=False):
"""Compute (weighted) betweenness centrality."""
pass
@abstractmethod
def closeness_centrality(self, distance, write=False):
"""Compute (weighted) closeness centrality."""
pass
@abstractmethod
def get_pgframe(self):
"""Get a new pgframe object from the wrapped graph object."""
pass
@abstractmethod
def density(self):
pass
def compute_all_node_metrics(self,
degree_weights=None,
pagerank_weights=None,
betweenness_weights=None,
closeness_weights=None):
if degree_weights is None:
degree_weights = []
if pagerank_weights is None:
pagerank_weights = []
if betweenness_weights is None:
betweenness_weights = []
if closeness_weights is None:
closeness_weights = []
results = {
"degree": {},
"pagerank": {},
"betweenness": {},
"closeness": {}
}
for weight in degree_weights:
results["degree"][weight] = self.degree_centrality(weight)
for weight in pagerank_weights:
results["pagerank"][weight] = self.pagerank_centrality(weight)
for weight in betweenness_weights:
results["betweenness"][weight] = self.betweenness_centrality(
weight)
for weight in closeness_weights:
results["closeness"][weight] = self.closeness_centrality(
weight)
return results
class MetricProcessingException(BlueGraphException):
pass
class MetricProcessingWarning(BlueGraphWarning):
pass
|
import sys
import random
from itertools import product
import pygame
from pygame.sprite import Sprite, Group
GRID_SIZE = 30
WIN_WIDTH = 1020
WIN_HEIGHT = 620
BG = 0, 0, 0
class Walls():
"""Class to manage the walls."""
def __init__(self, screen):
"""Initialise the game walls"""
self.screen = screen
self.rect = pygame.Rect(0, 0, 2+GRID_SIZE*20, 2+GRID_SIZE*20)
self.rect.left = 9
self.rect.top = 9
self.color = 0, 255, 0
def draw_walls(self):
"""Draw walls to screen."""
pygame.draw.rect(self.screen, self.color, self.rect, 1)
class Segment(Sprite):
"""Class to manage each segment of the snake."""
def __init__(self, screen, x, y):
super().__init__()
self.screen = screen
self.rect = pygame.Rect(0, 0, 20, 20)
self.x = x
self.y = y
self.xdir = 0
self.ydir = 0
self.color = 0, 255, 0
self.rect.left = 10 + self.x * 20
self.rect.top = 10 + self.y * 20
def update(self):
"""Set the segment's coordinates and move them to position."""
self.x = self.x + self.xdir
self.y = self.y + self.ydir
self.rect.left = 10 + self.x * 20
self.rect.top = 10 + self.y * 20
def draw_segment(self):
"""Draw the segment to the screen."""
pygame.draw.rect(self.screen, self.color, self.rect)
class Snake():
"""Class to manage the snake."""
def __init__(self, screen, x, y, length=3):
self.screen = screen
self.xdir = 1
self.ydir = 0
self.body = []
for i in range(length):
self.body.append(Segment(self.screen, x-i, y))
self.head = self.body[0]
self.tail = Group(self.body[1:])
self.score = 0
def __iter__(self):
for segment in self.body:
yield segment
def __len__(self):
return len(self.body)
def update(self):
"""Enumerate backwards through segments.
Set position of each segment from tail to head.
Then update each segment.
"""
for i, segment in enumerate(self.body[::-1], 1):
pos = len(self) - i
if pos == 0:
segment.xdir = self.xdir
segment.ydir = self.ydir
else:
segment.x = self.body[pos-1].x
segment.y = self.body[pos-1].y
segment.update()
def move(self, dir):
if dir == 'left' and not self.xdir:
self.xdir = -1
self.ydir = 0
if dir == 'right' and not self.xdir:
self.xdir = 1
self.ydir = 0
if dir == 'up' and not self.ydir:
self.xdir = 0
self.ydir = -1
if dir == 'down' and not self.ydir:
self.xdir = 0
self.ydir = 1
def grow(self):
new = Segment(self.screen, self.body[-1].x, self.body[-1].y)
self.body.append(new)
self.tail.add(new)
self.score += 1
def draw_snake(self):
"""Draw segments of the snake."""
for segment in self:
segment.draw_segment()
class Food(Sprite):
def __init__(self, screen, x, y):
super().__init__()
self.screen = screen
self.x = x
self.y = y
self.color = 255, 0, 0
self.rect = pygame.Rect(0, 0, 20, 20)
self.rect.left = 10 + self.x * 20
self.rect.top = 10 + self.y * 20
def draw_food(self):
pygame.draw.rect(self.screen, self.color, self.rect)
def check_events(screen, snake, game_active):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snake.move('left')
if event.key == pygame.K_RIGHT:
snake.move('right')
if event.key == pygame.K_UP:
snake.move('up')
if event.key == pygame.K_DOWN:
snake.move('down')
def update_screen(screen, snake, foods, walls):
screen.fill(BG)
for food in foods:
food.draw_food()
walls.draw_walls()
snake.draw_snake()
pygame.display.update()
def check_food_eaten(snake, foods):
"""Check snake-food collisions"""
eaten = pygame.sprite.spritecollide(snake.head, foods, True)
if eaten:
snake.grow()
def spawn_food(screen, snake, foods, coords):
"""Spawn food in an empty location if no food exists"""
if not len(foods):
snake_pos = set((segment.x, segment.y) for segment in snake)
food_locs = list(coords - snake_pos)
x, y = random.choice(food_locs)
foods.add(Food(screen, x, y))
def main():
screen = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
pygame.display.set_caption('Snake')
clock = pygame.time.Clock()
coords = set(product(range(30), repeat=2))
walls = Walls(screen)
snake = Snake(screen, 14, 14)
foods = Group()
game_active = True
while True:
clock.tick(10)
check_events(screen, snake, game_active)
if game_active:
snake.update()
check_food_eaten(snake, foods)
spawn_food(screen, snake, foods, coords)
# Check tail collisions
hit_tail = pygame.sprite.spritecollide(snake.head, snake.tail, False)
if hit_tail:
game_active = False
# Check snake is inside field
in_area = walls.rect.contains(snake.head.rect)
if not in_area:
game_active = False
update_screen(screen, snake, foods, walls)
if __name__ == '__main__':
main() |
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.ensemble import RandomForestClassifier
from sklearn.calibration import CalibratedClassifierCV
from sklearn.metrics import log_loss
np.random.seed(0)
# Generate data
X, y = make_blobs(n_samples=1000, n_features=2, random_state=42,
cluster_std=5.0)
X_train, y_train = X[:600], y[:600]
X_valid, y_valid = X[600:800], y[600:800]
X_train_valid, y_train_valid = X[:800], y[:800]
X_test, y_test = X[800:], y[800:]
# Train uncalibrated random forest classifier on whole train and validation
# data and evaluate on test data
clf = RandomForestClassifier(n_estimators=25)
clf.fit(X_train_valid, y_train_valid)
clf_probs = clf.predict_proba(X_test)
score = log_loss(y_test, clf_probs)
clf = RandomForestClassifier(n_estimators=25)
clf.fit(X_train, y_train)
clf_probs = clf.predict_proba(X_test)
sig_clf = CalibratedClassifierCV(clf, method="sigmoid", cv="prefit")
sig_clf.fit(X_valid, y_valid)
sig_clf_probs = sig_clf.predict_proba(X_test)
sig_score = log_loss(y_test, sig_clf_probs) |
# Copyright 2018 Alexandru Catrina
#
# 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.
from __future__ import print_function
from buildok.util.log import Log
class UnicodeIcon(object):
VALID = u"\033[92m\u2713\033[0m"
INVALID = u"\033[91m\u237B\033[0m"
def crash(message):
"""Crash application with message.
Raises:
SystemExit.
"""
return Log.fatal("Unexpected crash! %s" % message)
def scan_statements(statement):
"""Scans all statements.
Returns:
dict: Dictionary of all statements with a counter.
"""
lines = {}
if statement is None:
return lines
for action in statement.get_actions():
for line in action.parse_statements():
if lines.get(line) is None:
lines.update({line: 0})
lines[line] += 1
return lines
def self_analyze(lines=None, statement=None):
"""Self analyze for errors.
Returns:
bool: True if all statements are ok, otherwise False.
"""
if lines is None:
lines = scan_statements(statement)
return all([v == 1 for v in lines.itervalues()])
def fmt(fmt, txt):
"""Text formatter helper.
"""
return fmt % txt
def analyze(statement, length=80):
"""Analyze all statements and print visual results.
Returns:
bool: True if all statements are ok, otherwise False.
"""
lines = scan_statements(statement)
results = self_analyze(lines)
Log.debug("Listing all statements...")
for action in statement.get_actions():
try:
text = action.parse_description()
except Exception:
text = "no description"
delimiter = "-" * (length-4)
c_txt = u"\033[96m %-{}s \033[0m".format(length-6)
r_txt = u"\033[91m %-{}s \033[0m".format(length-6)
g_txt = u"\033[92m %-{}s \033[0m".format(length-6)
print(u"\033[90m|---|%-{}s|\033[0m".format(length-4) % delimiter)
print(u"\033[90m| |\033[0m" + fmt(c_txt, text) + "\033[90m|\033[0m")
print(u"\033[90m|---|%-{}s|\033[0m".format(length-4) % delimiter)
for line in action.parse_statements():
if lines[line] > 1:
status = UnicodeIcon.INVALID
line_text = fmt(r_txt, line.strip())
else:
status = UnicodeIcon.VALID
line_text = fmt(g_txt, line.strip())
print_line = u"\033[90m|\033[0m " + status + u" \033[90m|\033[0m"
print_line += line_text + u"\033[90m|\033[0m"
print(print_line)
print(u"\033[90m|---|%-{}s|\033[0m".format(length-4) % delimiter)
if not results:
Log.error("Duplicated statements found!")
for line, times in lines.iteritems():
if times > 1:
err = (times, line.strip())
Log.error(" - line duplicated %d times: %s" % err)
Log.error("Please correct these problems before running again.")
else:
Log.debug("Everything looks OK!")
return results
|
# -*- coding: utf-8 -*-
"""Python 2/3 compatibility wrappers.
This module contains imports and functions that help mask Python 2/3
compatibility issues.
"""
import tempfile
# UserDict
try:
# pylint: disable-next=unused-import
from collections import UserDict
except ImportError:
from UserDict import UserDict # noqa: F401
# StringIO
try:
# pylint: disable-next=unused-import
from io import StringIO
except ImportError:
from StringIO import StringIO # noqa: F401
# This reproduces the py27 signature for this function, so we'll ignore the
# shadowed built-in in this case.
def TemporaryFile(mode='w+b', encoding=None, suffix='', prefix='tmp',
dir=None): # pylint: disable=redefined-builtin
"""
Provide py2/3 compatability for TemporaryFile.
Redefining TemporaryFile from py27 because it doesn't support the
`encoding` parameter.
"""
try:
return tempfile.TemporaryFile(
mode=mode, encoding=encoding, suffix=suffix, prefix=prefix,
dir=dir)
except TypeError:
return tempfile.TemporaryFile(
mode=mode, suffix=suffix, prefix=prefix, dir=dir)
|
"""
BIBLIOTECA DO BOT IMPERATOR!
lista de todos os comandos:
"""
import os
from random import shuffle, choice
# Lista de interação:
# Lista de comprimentos do usuario/ Bot
user_comp = ["Ola", "ola", "Oi", "oi", "Hey"]
bot_res = ["Olá, como vai? ", "Oi, Tudo bem? ", "Tudo bem? "]
# Resposta do usuario e pergunta;
user_per = ["Estou otimo e voce?", "Estou bem e voce?", "Sim e voce?"]
bot_est = [
"Sou uma maquina, não sinto dor e nem emoção",
"Não fui programado para sentir emoções"]
# Estado do usuario e resposta do Bot;
user_est = ["Bem", "Estou bem", "Estou otimo"]
bot_repp = ["Isso e ótimo!", "Que bom!", "Perfeito!"]
# Interação;
inte = ["O que voce pode fazer?"]
botinte = ["No momento posso jogar Jokempô..."]
# Função dedicada a interação do bot com o usuário;
def interacao(entrada):
if entrada in user_comp:
return bot_res.pop() #Resposta do bot
elif entrada in user_per:
return bot_est.pop() #Estado do bot
elif entrada in user_est:
return bot_repp.pop() #Resposta do bot
elif entrada in inte:
return botinte
elif entrada == "Bye":
return exit()
# Jogo de pedra, papel e tesoura usando a função Choice() da
# biblioteca Random()
elif entrada == "jokenpo":
jogadas = ["pedra", "papel", "tesoura"]
jogar = input("Faca sua jogada: ")
return choice(jogadas)
# Função de ações do bot;
def usuario(entrada): # A função recebe a entrada do user e processa;
# Função 'start' inicia o nosso Bot;
if entrada == "start":
mensagem = "Bot startado"
# Retorna a mensagem ao usuário;
return mensagem
elif entrada == "criador":
# Criador do Bot;
criador = "\033[1;31mCriador: UserDevz\033[0m"
return criador
elif entrada == "github":
# GitHub do Bot;
github = "github do bot: \033[1;31mhttps://github.com/UserDevz/imperator-bot\033[0m"
return github
elif entrada == "bye":
# Fecha o Bot;
print("God Bye")
return exit()
elif entrada == "ajuda":
# Lista todas os comandos do bot;
ajuda = [
"start - Inicia o bot",
"criador - Criador do bot",
"github - Github do bot",
"bye - Encerra o bot",
"interacao - Ativa o modo interacao do bot",
"search - Realiza uma pesquisa no google"
]
return ajuda
# Chamada para o modo Interação do Bot;
elif entrada == "interacao":
print("!Modo interacao ativado!")
interacao()
# Pesquisa no google;
elif entrada == "search":
from googlesearch import search
query = input("Palavra chave-> ")
result = list(
search(
query,
lang='pt-br',
num_results=1
)
)
return result
elif entrada == "imperator":
os.system("figlet ImperatorBot|lolcat")
print("""
\033[1;31mChatBot Imperator\033[0m
\033[1;31mCriador: \033[1;36mMaykonDev/UserDevz/Maykon~KKK\033[0m
\033[1;31mVersão: 1.0\033[0m
""")
return exit()
|
""" Python script to train HRNet + shiftNet for multi frame super resolution (MFSR) """
import json
import os
import datetime
import numpy as np
from sklearn.model_selection import train_test_split
from tqdm import tqdm
import torch
import torch.optim as optim
import argparse
from torch import nn
from torch.utils.data import DataLoader
from torch.optim import lr_scheduler
from DeepNetworks.HRNet import HRNet
from DeepNetworks.ShiftNet import ShiftNet
from DataLoader import ImagesetDataset
from Evaluator import shift_cPSNR
from utils import getImageSetDirectories, readBaselineCPSNR, collateFunction
from tensorboardX import SummaryWriter
def register_batch(shiftNet, lrs, reference):
"""
Registers images against references.
Args:
shiftNet: torch.model
lrs: tensor (batch size, views, W, H), images to shift
reference: tensor (batch size, W, H), reference images to shift
Returns:
thetas: tensor (batch size, views, 2)
"""
n_views = lrs.size(1)
thetas = []
for i in range(n_views):
theta = shiftNet(torch.cat([reference, lrs[:, i : i + 1]], 1))
thetas.append(theta)
thetas = torch.stack(thetas, 1)
return thetas
def apply_shifts(shiftNet, images, thetas, device):
"""
Applies sub-pixel translations to images with Lanczos interpolation.
Args:
shiftNet: torch.model
images: tensor (batch size, views, W, H), images to shift
thetas: tensor (batch size, views, 2), translation params
Returns:
new_images: tensor (batch size, views, W, H), warped images
"""
batch_size, n_views, height, width = images.shape
images = images.view(-1, 1, height, width)
thetas = thetas.view(-1, 2)
new_images = shiftNet.transform(thetas, images, device=device)
return new_images.view(-1, n_views, images.size(2), images.size(3))
def get_loss(srs, hrs, hr_maps, metric='cMSE'):
"""
Computes ESA loss for each instance in a batch.
Args:
srs: tensor (B, W, H), super resolved images
hrs: tensor (B, W, H), high-res images
hr_maps: tensor (B, W, H), high-res status maps
Returns:
loss: tensor (B), metric for each super resolved image.
"""
# ESA Loss: https://kelvins.esa.int/proba-v-super-resolution/scoring/
criterion = nn.MSELoss(reduction='none')
if metric == 'masked_MSE':
loss = criterion(hr_maps * srs, hr_maps * hrs)
return torch.mean(loss, dim=(1, 2))
nclear = torch.sum(hr_maps, dim=(1, 2)) # Number of clear pixels in target image
bright = torch.sum(hr_maps * (hrs - srs), dim=(1, 2)).clone().detach() / nclear # Correct for brightness
loss = torch.sum(hr_maps * criterion(srs + bright.view(-1, 1, 1), hrs), dim=(1, 2)) / nclear # cMSE(A,B) for each point
if metric == 'cMSE':
return loss
return -10 * torch.log10(loss) # cPSNR
def get_crop_mask(patch_size, crop_size):
"""
Computes a mask to crop borders.
Args:
patch_size: int, size of patches
crop_size: int, size to crop (border)
Returns:
torch_mask: tensor (1, 1, 3*patch_size, 3*patch_size), mask
"""
mask = np.ones((1, 1, 3 * patch_size, 3 * patch_size)) # crop_mask for loss (B, C, W, H)
mask[0, 0, :crop_size, :] = 0
mask[0, 0, -crop_size:, :] = 0
mask[0, 0, :, :crop_size] = 0
mask[0, 0, :, -crop_size:] = 0
torch_mask = torch.from_numpy(mask).type(torch.FloatTensor)
return torch_mask
def trainAndGetBestModel(fusion_model, regis_model, optimizer, dataloaders, baseline_cpsnrs, config):
"""
Trains HRNet and ShiftNet for Multi-Frame Super Resolution (MFSR), and saves best model.
Args:
fusion_model: torch.model, HRNet
regis_model: torch.model, ShiftNet
optimizer: torch.optim, optimizer to minimize loss
dataloaders: dict, wraps train and validation dataloaders
baseline_cpsnrs: dict, ESA baseline scores
config: dict, configuration file
"""
np.random.seed(123) # seed all RNGs for reproducibility
torch.manual_seed(123)
num_epochs = config["training"]["num_epochs"]
batch_size = config["training"]["batch_size"]
n_views = config["training"]["n_views"]
min_L = config["training"]["min_L"] # minimum number of views
beta = config["training"]["beta"]
subfolder_pattern = 'batch_{}_views_{}_min_{}_beta_{}_time_{}'.format(
batch_size, n_views, min_L, beta, f"{datetime.datetime.now():%Y-%m-%d-%H-%M-%S-%f}")
checkpoint_dir_run = os.path.join(config["paths"]["checkpoint_dir"], subfolder_pattern)
os.makedirs(checkpoint_dir_run, exist_ok=True)
tb_logging_dir = config['paths']['tb_log_file_dir']
logging_dir = os.path.join(tb_logging_dir, subfolder_pattern)
os.makedirs(logging_dir, exist_ok=True)
writer = SummaryWriter(logging_dir)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
best_score = 100
P = config["training"]["patch_size"]
offset = (3 * config["training"]["patch_size"] - 128) // 2
C = config["training"]["crop"]
torch_mask = get_crop_mask(patch_size=P, crop_size=C)
torch_mask = torch_mask.to(device) # crop borders (loss)
fusion_model.to(device)
regis_model.to(device)
scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=config['training']['lr_decay'],
verbose=True, patience=config['training']['lr_step'])
for epoch in tqdm(range(1, num_epochs + 1)):
# Train
fusion_model.train()
regis_model.train()
train_loss = 0.0 # monitor train loss
# Iterate over data.
for lrs, alphas, hrs, hr_maps, names in tqdm(dataloaders['train']):
optimizer.zero_grad() # zero the parameter gradients
lrs = lrs.float().to(device)
alphas = alphas.float().to(device)
hr_maps = hr_maps.float().to(device)
hrs = hrs.float().to(device)
# torch.autograd.set_detect_anomaly(mode=True)
srs = fusion_model(lrs, alphas) # fuse multi frames (B, 1, 3*W, 3*H)
# Register batch wrt HR
shifts = register_batch(regis_model,
srs[:, :, offset:(offset + 128), offset:(offset + 128)],
reference=hrs[:, offset:(offset + 128), offset:(offset + 128)].view(-1, 1, 128, 128))
srs_shifted = apply_shifts(regis_model, srs, shifts, device)[:, 0]
# Training loss
cropped_mask = torch_mask[0] * hr_maps # Compute current mask (Batch size, W, H)
# srs_shifted = torch.clamp(srs_shifted, min=0.0, max=1.0) # correct over/under-shoots
loss = -get_loss(srs_shifted, hrs, cropped_mask, metric='cPSNR')
loss = torch.mean(loss)
loss += config["training"]["lambda"] * torch.mean(shifts)**2
# Backprop
loss.backward()
optimizer.step()
epoch_loss = loss.detach().cpu().numpy() * len(hrs) / len(dataloaders['train'].dataset)
train_loss += epoch_loss
# Eval
fusion_model.eval()
val_score = 0.0 # monitor val score
for lrs, alphas, hrs, hr_maps, names in dataloaders['val']:
lrs = lrs.float().to(device)
alphas = alphas.float().to(device)
hrs = hrs.numpy()
hr_maps = hr_maps.numpy()
srs = fusion_model(lrs, alphas)[:, 0] # fuse multi frames (B, 1, 3*W, 3*H)
# compute ESA score
srs = srs.detach().cpu().numpy()
for i in range(srs.shape[0]): # batch size
if baseline_cpsnrs is None:
val_score -= shift_cPSNR(np.clip(srs[i], 0, 1), hrs[i], hr_maps[i])
else:
ESA = baseline_cpsnrs[names[i]]
val_score += ESA / shift_cPSNR(np.clip(srs[i], 0, 1), hrs[i], hr_maps[i])
val_score /= len(dataloaders['val'].dataset)
if best_score > val_score:
torch.save(fusion_model.state_dict(),
os.path.join(checkpoint_dir_run, 'HRNet.pth'))
torch.save(regis_model.state_dict(),
os.path.join(checkpoint_dir_run, 'ShiftNet.pth'))
best_score = val_score
writer.add_image('SR Image', (srs[0] - np.min(srs[0])) / np.max(srs[0]), epoch, dataformats='HW')
error_map = hrs[0] - srs[0]
writer.add_image('Error Map', error_map, epoch, dataformats='HW')
writer.add_scalar("train/loss", train_loss, epoch)
writer.add_scalar("train/val_loss", val_score, epoch)
scheduler.step(val_score)
writer.close()
def main(config):
"""
Given a configuration, trains HRNet and ShiftNet for Multi-Frame Super Resolution (MFSR), and saves best model.
Args:
config: dict, configuration file
"""
# Reproducibility options
np.random.seed(0) # RNG seeds
torch.manual_seed(0)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
# Initialize the network based on the network configuration
fusion_model = HRNet(config["network"])
regis_model = ShiftNet()
optimizer = optim.Adam(list(fusion_model.parameters()) + list(regis_model.parameters()), lr=config["training"]["lr"]) # optim
# ESA dataset
data_directory = config["paths"]["prefix"]
baseline_cpsnrs = None
if os.path.exists(os.path.join(data_directory, "norm.csv")):
baseline_cpsnrs = readBaselineCPSNR(os.path.join(data_directory, "norm.csv"))
train_set_directories = getImageSetDirectories(os.path.join(data_directory, "train"))
val_proportion = config['training']['val_proportion']
train_list, val_list = train_test_split(train_set_directories,
test_size=val_proportion,
random_state=1, shuffle=True)
# Dataloaders
batch_size = config["training"]["batch_size"]
n_workers = config["training"]["n_workers"]
n_views = config["training"]["n_views"]
min_L = config["training"]["min_L"] # minimum number of views
beta = config["training"]["beta"]
train_dataset = ImagesetDataset(imset_dir=train_list, config=config["training"],
top_k=n_views, beta=beta)
train_dataloader = DataLoader(train_dataset, batch_size=batch_size,
shuffle=True, num_workers=n_workers,
collate_fn=collateFunction(min_L=min_L),
pin_memory=True)
config["training"]["create_patches"] = False
val_dataset = ImagesetDataset(imset_dir=val_list, config=config["training"],
top_k=n_views, beta=beta)
val_dataloader = DataLoader(val_dataset, batch_size=1,
shuffle=False, num_workers=n_workers,
collate_fn=collateFunction(min_L=min_L),
pin_memory=True)
dataloaders = {'train': train_dataloader, 'val': val_dataloader}
# Train model
torch.cuda.empty_cache()
trainAndGetBestModel(fusion_model, regis_model, optimizer, dataloaders, baseline_cpsnrs, config)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--config", help="path of the config file", default='config/config.json')
args = parser.parse_args()
assert os.path.isfile(args.config)
with open(args.config, "r") as read_file:
config = json.load(read_file)
main(config)
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2014 Intel Corporation, 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.
from django import shortcuts
from django.views.decorators import vary
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.template.loader import get_template
from django.template import Context
from django.conf import settings
import horizon
from openstack_auth.views import login
from vsm_dashboard import api
def get_user_home(user):
#if user.is_superuser:
# return horizon.get_dashboard('admin').get_absolute_url()
return horizon.get_dashboard('vsm').get_absolute_url()
def license_gate(request):
_template = get_template('license.html')
context = Context()
html = _template.render(context=context)
return HttpResponse(html)
def license_accept(request):
api.vsm.license_create(request)
api.vsm.license_update(request, True)
#Redirect to cluster create page if user accept license.
#TODO(fengqian): When trun to cluster create page,
#All other functions should be unavaliable.
return shortcuts.redirect('/dashboard/vsm/clustermgmt')
def license_cancel(request):
return HttpResponseRedirect(settings.LOGOUT_URL)
@vary.vary_on_cookie
def splash(request):
if request.user.is_authenticated():
#license_status = api.vsm.license_get(request)[1]
#if license_status is None or\
# license_status.get('license_accept', False) == False:
# return license_gate(request)
#else:
return shortcuts.redirect(get_user_home(request.user))
form = login(request)
request.session.clear()
request.session.set_test_cookie()
return shortcuts.render(request, 'splash.html', {'form': form})
|
import collections
import unittest
from typing import List
import utils
from tree import TreeNode
# O(n) time. O(number of groups) space. Hash table.
class Solution:
def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
group_size_to_people = collections.defaultdict(list)
for person, group_size in enumerate(groupSizes):
group_size_to_people[group_size].append(person)
return [people[i:i + group_size] for group_size, people in
group_size_to_people.items() for i in range(0, len(people), group_size)]
class Test(unittest.TestCase):
def test(self):
cases = utils.load_test_json(__file__).test_cases
for case in cases:
args = str(case.args)
expected = [tuple(sorted(tuple(sorted(group)) for group in possible_solution))
for possible_solution in case.expected]
actual = Solution().groupThePeople(**case.args.__dict__)
actual = tuple(sorted(tuple(sorted(group)) for group in actual))
self.assertIn(actual, expected, msg=args)
if __name__ == '__main__':
unittest.main()
|
import pymunk
from enum import Enum
class Game:
types = {"player": 1, "zombie": 2}
MAX_VELOCITY = 100
ACCELERATION = 1
INTERNAL_TICK_TIME = 0.01
EXTERNAL_TICK_TIME = 0.01
MAX_TICKS = 60
def __init__(self, max_players = 8, min_players = 4, width = 1300.0, height = 700.0):
self.starting_positions = [(100, 300), (50, 450), (600, 600), (1000, 500),
(1200, 50), (500, 200), (700, 100), (100, 300),
(500, 500), (100, 100)]
self.max_players = max_players
self.min_players = min_players
self.players = dict()
self.width = width
self.height = height
self.space = pymunk.Space()
self.add_static_scenery()
self.zombie_collision_handler = self.space.add_collision_handler(Game.types["player"], Game.types["zombie"])
self.started = False
self.ended = False
self.winner = None
self.space.damping = 0.3
self.god = None
self.time_left = Game.MAX_TICKS
self.effects = set()
self.player_count = 0
def turn_zombie(arbiter, space, data):
if self.god is not None and GodAction.IMMUNE in self.god.current_actions:
return True
player = self.players[arbiter.shapes[0].id]
player.shape.collision_type = Game.types["zombie"]
ended = True
for player in self.players.values():
if player.shape.collision_type == Game.types["player"]:
ended = False
self.ended = ended
if ended:
self.winner = Game.types["zombie"]
return True
self.zombie_collision_handler.begin = turn_zombie
self.space.damping = 0.1
def add_player(self, id):
if self.player_count == 0:
self.players[id] = Player(id, self.space, self.starting_positions.pop(), self, isZombie=True)
elif self.player_count == 1 and self.god is None:
self.add_god(id)
else:
self.players[id] = Player(id, self.space, self.starting_positions.pop(), self)
self.player_count += 1
def add_god(self, id):
self.god = God(id)
def add_static_scenery(self):
static_body = self.space.static_body
static_lines = [pymunk.Segment(static_body, (0,0),
(self.width, 0), 0.0),
pymunk.Segment(static_body, (self.width, 0),
(self.width, self.height), 0.0),
pymunk.Segment(static_body, (self.width, self.height),
(0, self.height), 0.0),
pymunk.Segment(static_body, (0, self.height),
(0, 0), 0.0)]
for line in static_lines:
line.elasticity = 0.95
line.friction = 0.9
self.space.add(static_lines)
def input(self, id, key, action):
if action == "pressed":
self.players[id].current_accel_dirs.add(key[0])
else:
self.players[id].current_accel_dirs.remove(key[0])
def god_input(self, id, code):
if self.god is not None and id == self.god.id:
if code in self.god.possible_actions:
self.god.current_actions[code] = self.god.possible_actions[code]
self.god.cooldown_actions[code] = self.god.possible_actions[code]
del self.god.possible_actions[code]
def cure_player(self):
zombie_count = 0
zombie_obj = None
for obj in self.players.values():
if obj.shape.collision_type == Game.types["zombie"]:
print(obj.id)
zombie_count += 1
zombie_obj = obj
if zombie_count > 1:
zombie_obj.shape.collision_type = Game.types["player"]
else:
self.god.possible_actions[GodAction.CURE] = self.god.cooldown_actions[GodAction.CURE]
del self.god.cooldown_actions[GodAction.CURE]
# [playerId:{position:point, velocity:point, isZombie:bool}]
def tick(self):
self.space.step(Game.INTERNAL_TICK_TIME)
if self.god is not None and GodAction.CURE in self.god.current_actions:
self.cure_player()
self.time_left -= Game.INTERNAL_TICK_TIME
if self.god is not None:
self.god.tick()
if self.time_left <= 0:
self.ended = True
self.winner = Game.types["player"]
data = dict()
for player in self.players.items():
data[player[0]] = dict()
data[player[0]]["position"] = dict()
data[player[0]]["position"]["x"] = player[1].body.position[0]
data[player[0]]["position"]["y"] = player[1].body.position[1]
self.space.reindex_shapes_for_body(player[1].body)
data[player[0]]["isZombie"] = player[1].shape.collision_type == Game.types["zombie"]
if self.god is not None:
data["god_spells"] = {"possible": list(self.god.possible_actions.keys()),
"cooldown": {x.id : x.cooldown for x in self.god.cooldown_actions.values()}
}
return data, self.ended, self.winner
def start(self):
self.started = True
return {"width": self.width, "height": self.height}
class Player:
RADIUS = 60.0
def __init__(self, id, space, pos, game, isZombie=False):
self.id = id
self.body = pymunk.Body(1)
self.space = space
self.body.position = pos
self.shape = pymunk.Circle(self.body, Player.RADIUS)
self.shape.density = 3
self.space.add(self.body, self.shape)
self.shape.collision_type = Game.types["player"]
if isZombie:
self.shape.collision_type = Game.types["zombie"]
else:
self.shape.collision_type = Game.types["player"]
self.current_accel_dirs = set()
self.shape.id = id
self.game = game
def velocity_cb(body, gravity, damping, dt):
velocity_vector = [body.velocity[0], body.velocity[1]]
accel_modifier = 1
max_vel_mod = 1
if self.shape.collision_type == Game.types["zombie"] and \
self.game.god is not None and GodAction.FREEZE in self.game.god.current_actions:
body.velocity = [0, 0]
if self.shape.collision_type == Game.types["player"] and \
self.game.god is not None and \
GodAction.SPEED_UP in self.game.god.current_actions:
accel_modifier = 1.5
max_vel_mod = 2
if body.velocity[0] < Game.MAX_VELOCITY * max_vel_mod and "r" in self.current_accel_dirs:
velocity_vector[0] = min(Game.MAX_VELOCITY * max_vel_mod, body.velocity[0] + Game.ACCELERATION * accel_modifier )
if body.velocity[0] > -Game.MAX_VELOCITY * max_vel_mod and "l" in self.current_accel_dirs:
velocity_vector[0] = max(-Game.MAX_VELOCITY * max_vel_mod, body.velocity[0]-Game.ACCELERATION * accel_modifier)
if body.velocity[1] < Game.MAX_VELOCITY * max_vel_mod and "d" in self.current_accel_dirs:
velocity_vector[1] = min(Game.MAX_VELOCITY * max_vel_mod, body.velocity[1]+Game.ACCELERATION * accel_modifier)
if body.velocity[1] > -Game.MAX_VELOCITY * max_vel_mod and "u" in self.current_accel_dirs:
velocity_vector[1] = max(-Game.MAX_VELOCITY * max_vel_mod, body.velocity[1]-Game.ACCELERATION * accel_modifier)
body.velocity = velocity_vector
self.body.velocity_func = velocity_cb
class God:
def __init__(self, id):
self.id = id
self.current_actions = dict()
self.possible_actions = {GodAction.FREEZE: GodAction(GodAction.FREEZE, 3, 40),
GodAction.SPEED_UP: GodAction(GodAction.SPEED_UP, 2, 10),
GodAction.IMMUNE: GodAction(GodAction.IMMUNE, 2, 20)}
self.cooldown_actions = {GodAction.CURE: GodAction(GodAction.CURE, 0, 40)}
def tick(self):
to_splice = set()
for (act, obj) in self.cooldown_actions.items():
obj.cooldown -= Game.INTERNAL_TICK_TIME
if obj.cooldown <= 0:
to_splice.add(act)
self.possible_actions[act] = obj
obj.cooldown = obj.full_cooldown
for i in to_splice:
self.cooldown_actions.pop(i)
to_splice = set()
for (act, obj) in self.current_actions.items():
obj.duration -= Game.INTERNAL_TICK_TIME
if obj.duration <= 0:
to_splice.add(act)
self.cooldown_actions[act] = obj
obj.duration = obj.full_duration
for i in to_splice:
self.current_actions.pop(i)
class GodAction:
FREEZE = 1
SPEED_UP = 2
IMMUNE = 3
CURE = 4
def __init__(self, id, duration, cooldown):
self.id = id
self.full_duration = duration
self.full_cooldown = cooldown
self.duration = duration
self.cooldown = cooldown
|
import os
import h5py
import numpy as np
from conans import ConanFile, tools
from conan.tools.cmake import CMake, CMakeToolchain, CMakeDeps
from pathlib import Path
class Hdf5TestConan(ConanFile):
name = "Hdf5PackageTest"
settings = "os", "compiler", "build_type", "arch"
generators = "CMakeDeps"
requires = "hdf5/1.10.8"
exports = "CMakeLists.txt", "hdf5example.cpp"
def generate(self):
print("Generating toolchain")
tc = CMakeToolchain(self)
# Use the HDF5 cmake package in the share directory
tc.variables["CMAKE_PREFIX_PATH"] = Path(
self.deps_cpp_info["hdf5"].rootpath, 'share'
).as_posix()
tc.generate()
deps = CMakeDeps(self)
deps.generate()
def build(self):
cmake = CMake(self)
cmake.configure()
cmake.build()
def test(self):
if not tools.cross_building(self.settings):
# Create a test hdf5 file to test containing
# two datasets caled "dataset" and "query"
with h5py.File("dataset.hdf5", "w") as f:
np_d = np.random.randint(0, 128, size=(9000, 128), dtype=np.uint8)
np_d = np_d.astype(np.float64)
np_q = np.random.randint(0, 128, size=(1000, 128), dtype=np.uint8)
np_q = np_q.astype(np.float64)
f.create_dataset("test_dataset1", data=np_d)
f.create_dataset("test_dataset2", data=np_q)
print("Running hdf5 example...")
if self.settings.os == "Windows":
self.run(str(Path(Path.cwd(), "Release", "hdf5example.exe")) + " dataset.hdf5 test_dataset1" )
else:
self.run(str(Path(Path.cwd(), "hdf5example")) + " dataset.hdf5 test_dataset1" )
|
from gym.envs.registration import register
name = 'gym_flp'
register(id='qap-v0',
entry_point='gym_flp.envs:qapEnv')
register(id='fbs-v0', entry_point='gym_flp.envs:fbsEnv')
register(id='ofp-v0', entry_point='gym_flp.envs:ofpEnv')
register(id='sts-v0', entry_point='gym_flp.envs:stsEnv')
|
import pytchat,discord,asyncio,csv,os
from modules import settings
from logging import basicConfig, getLogger
from pytchat import LiveChatAsync
from os.path import join, dirname
basicConfig(level=settings.LOG_LEVEL)
LOG = getLogger(__name__)
bot = discord.Client(intents=discord.Intents.default())
async def main():
livechat = LiveChatAsync(settings.VIDEO_ID, callback = func)
while livechat.is_alive():
await asyncio.sleep(1)
#other background operation.
# If you want to check the reason for the termination,
# you can use `raise_for_status()` function.
try:
livechat.raise_for_status()
except pytchat.ChatDataFinished:
print("Chat data finished.")
except Exception as e:
print(type(e), str(e))
#callback function is automatically called periodically.
async def func(chatdata):
for c in chatdata.items:
youtube_chat_text = f"`{c.datetime}` -> [{c.author.name}] {c.message}"
LOG.info(youtube_chat_text)
await chatdata.tick_async()
if len(bot.guilds) == 1:
guild = bot.guilds[0] # BOTに紐づくギルドが1つのみという前提でギルドを取得
else:
LOG.error(f'BOTに紐づくギルドは1件である必要があります。お手数ですが登録/削除をお願いします。あなたのBOTに紐づくギルドの数:{bot.guilds}')
LOG.info('処理を終了します。')
return
if settings.DISCORD_CHANNEL_ID:
channel = guild.get_channel(settings.DISCORD_CHANNEL_ID)
await channel.send(youtube_chat_text)
if settings.CSV_OUTPUT_FLAG:
FILE_PATH = join(dirname(__file__), 'modules' + os.sep + 'files' + os.sep + 'csv' + os.sep + settings.VIDEO_ID + '.csv')
with open(FILE_PATH, 'a') as f:
writer = csv.writer(f)
writer.writerow([c.datetime, c.type, c.id, c.message, c.elapsedTime, c.amountString, c.currency, c.amountValue, c.author.name])
@bot.event
async def on_ready():
LOG.info('bot ready.')
await main()
if __name__=='__main__':
try:
bot.run(settings.DISCORD_TOKEN)
except asyncio.exceptions.CancelledError:
pass
|
# CC0 - free software.
# To the extent possible under law, all copyright and related or neighboring
# rights to this work are waived.
'''
2D, 3D and 4D point classes with various basic operators and operations
defined. Operators accept not only Point objects but any list-like object with
values.
>>> p1 = Point2d(x=4, y=1)
>>> p1.x
4
>>> p2 = Point2d(6, -5)
>>> p1 + p2
Point2d(10, -4)
>>> p2 * (2, 0.3)
Point2d(12, -1.5)
>>> p1.distance(p2)
6.324555320336759
`Swizzles`_ can be used to create arbitrary permutations:
>>> p3 = Point3d(1, 4, -3)
>>> p4 = Point4d(7, -9, 8, 7.4)
>>> p3.zy, p4.wzxy, p4.wwyy, p2.yy
(Point2d(-3, 4), Point4d(7.4, 8, 7, -9), Point4d(7.4, 7.4, -9, -9), Point2d(-5, -5))
Calculate the euclidean distance:
>>> p3.veclen()
5.0990195135927845
Various access methods are available:
>>> p3.y
4
>>> p3[1]
4
>>> p3['y']
4
>>> print(*p3)
1 4 -3
>>> 'z' in p3
True
>>> sum(p3)
2
>>> p3 > 0
(True, True, False)
>>> any(p3 <= 0)
True
Very basic color support is also included:
>>> rgb = ColorRgb(255, 10, 100)
>>> rgb.g
10
>>> rgb.gbr
ColorRgb(10, 100, 255)
Allowed colors values are either positive integers or floats between 0 and 1 (inclusive).
>>> invalid_float = ColorRgb(2.3, 0, 0)
Traceback (most recent call last):
...
ValueError: color value outside range (0, 1): 2.3
>>> invalid_neg = ColorRgb(-200, 0, 0)
Traceback (most recent call last):
...
ValueError: color value cannot be negative: -200
.. _Swizzles:
https://en.wikipedia.org/wiki/Swizzling_(computer_graphics)
'''
import math
import itertools
from copy import deepcopy
class BasePoint:
components = []
coercion = None
def __init__(self, *args, **kwargs):
args = list(args)
for c in self.components:
if type(self).coercion is not None:
setattr(self, c, type(self).coercion(kwargs[c] if c in kwargs else (args.pop(0) if len(args) > 0 else 0)))
else:
setattr(self, c, kwargs[c] if c in kwargs else (args.pop(0) if len(args) > 0 else 0))
# indexed access
def __getitem__(self, index):
if index in range(len(self.components)):
return getattr(self, self.components[index])
elif index in self.components:
return getattr(self, index)
else: raise IndexError('Point index out of range')
# arithmetic operators
def __add__(self, other):
try: return type(self)(*[getattr(self, self.components[i]) + other[i] for i in range(len(other))])
except TypeError: return type(self)(*[getattr(self, c) + other for c in self.components])
def __sub__(self, other):
try: return type(self)(*[getattr(self, self.components[i]) - other[i] for i in range(len(other))])
except TypeError: return type(self)(*[getattr(self, c) - other for c in self.components])
def __mul__(self, other):
try: return type(self)(*[getattr(self, self.components[i]) * other[i] for i in range(len(other))])
except TypeError: return type(self)(*[getattr(self, c) * other for c in self.components])
def __truediv__(self, other):
try: return type(self)(*[getattr(self, self.components[i]) / other[i] for i in range(len(other))])
except TypeError: return type(self)(*[getattr(self, c) / other for c in self.components])
def __floordiv__(self, other):
try: return type(self)(*[getattr(self, self.components[i]) // other[i] for i in range(len(other))])
except TypeError: return type(self)(*[getattr(self, c) // other for c in self.components])
def __mod__(self, other):
try: return type(self)(*[getattr(self, self.components[i]) % other[i] for i in range(len(other))])
except TypeError: return type(self)(*[getattr(self, c) % other for c in self.components])
def __neg__(self): return type(self)(*[-(getattr(self, c)) for c in self.components])
def __pos__(self): return self
# numerical properties
def __abs__(self): return type(self)(*[abs(getattr(self, c)) for c in self.components])
def __round__(self): return type(self)(*[round(getattr(self, c)) for c in self.components])
def __int__(self): return type(self)(*[int(getattr(self, c)) for c in self.components])
def __float__(self): return type(self)(*[float(getattr(self, c)) for c in self.components])
# comparisons
def __gt__(self, other):
try: return tuple(getattr(self, self.components[i]) > other[i] for i in range(len(other)))
except TypeError: return tuple(getattr(self, c) > other for c in self.components)
def __lt__(self, other):
try: return tuple(getattr(self, self.components[i]) < other[i] for i in range(len(other)))
except TypeError: return tuple(getattr(self, c) < other for c in self.components)
def __ge__(self, other):
try: return tuple(getattr(self, self.components[i]) >= other[i] for i in range(len(other)))
except TypeError: return tuple(getattr(self, c) >= other for c in self.components)
def __le__(self, other):
try: return tuple(getattr(self, self.components[i]) <= other[i] for i in range(len(other)))
except TypeError: return tuple(getattr(self, c) <= other for c in self.components)
def __eq__(self, other):
try: return tuple(getattr(self, self.components[i]) == other[i] for i in range(len(other)))
except TypeError: return tuple(getattr(self, c) == other for c in self.components)
# container properties
def __len__(self): return len(self.components)
def __contains__(self, component): return component in self.components
def __iter__(self):
for c in self.components:
yield getattr(self, c)
# object properties
def __deepcopy__(self, memo): return type(self)(*[getattr(self, c) for c in self.components])
def __str__(self): return '(' + ', '.join([str(getattr(self, c)) for c in self.components]) + ')'
def __repr__(self):
return type(self).__name__ + '(' + ', '.join([
str(getattr(self, c)) for c in self.components
# '{}={}'.format(c, getattr(self, c)) for c in self.components
]) + ')'
# actual methods
def distance(self, other):
'''Calculate the euclidean distance from another point.'''
return math.sqrt(sum([(other[i] - getattr(self, c))**2 for i, c in enumerate(self.components)]))
def veclen(self):
'''Calculate the euclidean distance from the origin.'''
return self.distance(type(self)())
@classmethod
def _make_swizzles(cls, partial_classes=[]):
'''Dynamically generate swizzles: xy, yx, xyz, yxz, xzy, and
so forth by creating class properties. '''
swizzle_classes = partial_classes + [cls]
perm_len_offset = max(0, len(cls.components) - len(partial_classes))
for i, swizzle_class in enumerate(swizzle_classes):
for c_order in itertools.product(cls.components, repeat=perm_len_offset + i):
setattr(cls, ''.join(c_order), property(cls._make_swizzle(swizzle_classes[i], c_order)))
@classmethod
def _make_swizzle(cls, return_class, components):
'''Swizzle factory. Needed because of python's late binding.'''
def swizzle(self):
return return_class(*[self[c] for c in deepcopy(components)])
return swizzle
### Numeric Points
def _number(value):
'''
Coerce components to a number, if possible. Does what :py:meth:`int` does
if it's an integer, otherwise, does what :py:meth:`float` does.
'''
f = float(value)
if f % 1.0 == 0:
return int(f)
else:
return f
class BaseNumericPoint(BasePoint):
coercion = _number
class Point2d(BaseNumericPoint):
'''A point in two dimensions.'''
components = ['x', 'y']
Point2d._make_swizzles()
class Point3d(BaseNumericPoint):
'''A point in three dimensions.'''
components = ['x', 'y', 'z']
Point3d._make_swizzles([Point2d])
class Point4d(BaseNumericPoint):
'''A point in four dimensions. The fourth dimension is `w`.'''
components = ['x', 'y', 'z', 'w']
# At this point one _make_swizzles()-line creates 300 properties (or 336
# without inheritance from Point3d)
Point4d._make_swizzles([Point2d, Point3d])
class Point2dTex(BaseNumericPoint):
'''Two-dimensional texture coordinates in `u` and `v`. '''
components = ['u', 'v']
Point2dTex._make_swizzles()
### Colors
def _color(value):
'''
Coerce components to a color value. Either a positive integer, or a float
between 0.0 and 1.0.
'''
f = float(value)
if f % 1.0 == 0:
if f >= 0:
return int(f)
else:
raise ValueError('color value cannot be negative: {}'.format(value))
elif 0 <= f <= 1:
return f
else:
raise ValueError('color value outside range (0, 1): {}'.format(value))
class BaseColor(BasePoint):
coercion = _color
class ColorRgb(BaseColor):
'''A color with `r`, `g` and `b` channels.'''
components = ['r', 'g', 'b']
ColorRgb._make_swizzles()
class ColorHsv(BaseColor):
'''A color in HSV space.'''
components = ['h', 's', 'v']
class ColorHsl(BaseColor):
'''A color in HSL space.'''
components = ['h', 's', 'l']
@property
def hls(self): return ColorHls(self.h, self.l, self.s)
class ColorHls(BaseColor):
'''A color in HLS space with luminance and saturation exchanged.'''
components = ['h', 'l', 's']
@property
def hsl(self): return ColorHsl(self.h, self.s, self.l)
|
# Generated by Django 3.1.7 on 2021-03-20 07:18
import ckeditor_uploader.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('stories', '0003_auto_20210319_1019'),
]
operations = [
migrations.AlterField(
model_name='story',
name='description',
field=ckeditor_uploader.fields.RichTextUploadingField(verbose_name='Mezmun'),
),
]
|
def sortByHeight(a):
heights = []
tree_trakcer_index = set()
for number in range(0, len(a)):
if a[number] == -1:
tree_trakcer_index.add(number)
else:
heights.append(a[number])
final = []
heights.sort()
for num in range(0, len(a)):
if num in tree_trakcer_index:
final.append(-1)
else:
final.append(heights.pop(0))
return final
def reverseInParentheses(inputString):
final_string = []
hash_table = {}
index = 0
depth = 0
max_depth = 0
while index < len(inputString):
if inputString[index] == "(" or inputString[index] == ")":
if inputString[index] == "(":
depth += 1
if depth > max_depth:
max_depth = depth
if depth in hash_table:
hash_table[depth].append(index)
else:
hash_table[depth] = []
hash_table[depth].append(index)
if inputString[index] == ")":
depth -= 1
index += 1
print(hash_table)
while max_depth != 0:
while len(hash_table[max_depth]) > 0:
index2 = int(hash_table[max_depth].pop())
index1 = int(hash_table[max_depth].pop())
str = inputString[index1: index2]
reverse_str = ''.join(reversed(str))
reverse_pointer = 0
inputString = inputString[:index1] + reverse_str + inputString[index2:]
reverse_pointer += 1
max_depth -= 1
inputString = inputString.replace('(', '')
inputString = inputString.replace(')', '')
print(inputString)
return inputString
def alternatingSums(a):
team1 = 0
team2 = 0
for num in range(0, len(a)):
if num == 0 or num%2 == 0:
team1 = team1 + a[num]
elif num%2 == 1:
team2 = team2 + a[num]
return[team1, team2]
def addBorder(picture):
length = len(picture[0])
frame = "*" * length
picture.insert(0, frame)
picture.append(frame)
framed_picture =[]
for line in picture:
add_frame = "*"+line+"*"
framed_picture.append(add_frame)
return framed_picture
def areSimilar(a, b):
similar = True
list1 = []
list2 = []
for num in range(0, len(a)):
if a[num] != b[num]:
list1.append(a[num])
list2.append(b[num])
if len(list1) > 2:
similar = False
break
list1.sort()
list2.sort()
if list1 != list2:
similar = False
return similar
def arrayChange(inputArray):
count = 0
for num in range(1, len(inputArray)):
if inputArray[num-1] >= inputArray[num]:
old_num = inputArray[num]
inputArray[num] = inputArray[num-1] + 1
difference = inputArray[num] - old_num
count = count + difference
return count
def palindromeRearranging(inputString):
hash_table = {}
for letter in inputString:
if letter in hash_table:
hash_table[letter] += 1
else:
hash_table[letter] = 1
exemption = 0
can_rearrange = True
for value in hash_table.values():
if value == 1 or value%2 == 1:
exemption += 1
if exemption > 1:
can_rearrange = False
break
return can_rearrange
def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight):
equallyStrong = False
you = []
freind = []
if yourLeft > yourRight:
you.append(yourLeft)
you.append(yourRight)
else:
you.append(yourRight)
you.append(yourLeft)
if friendsLeft > friendsRight:
freind.append(friendsLeft)
freind.append(friendsRight)
else:
freind.append(friendsRight)
freind.append(friendsLeft)
if you[0] == freind[0] and you[1] == freind[1]:
equallyStrong = True
return equallyStrong
def arrayMaximalAdjacentDifference(inputArray):
max_distance = 0
for num in range(0, len(inputArray)-1):
difference = abs(inputArray[num] - inputArray[num+1])
if difference > max_distance:
max_distance = difference
return max_distance
import re
def isIPv4Address(inputString):
letter = re.search("[a-zA-Z]", inputString)
special = re.search("[+]", inputString)
if letter != None or special != None:
print(letter)
print(special)
print("fail1")
return False
count = 0
for char in inputString:
if char == ".":
count += 1
if count != 3:
return False
IParray = inputString.replace(".", " ")
IParray = IParray.split()
if len(IParray) != 4:
print("fail2")
return False
print(IParray)
for num in IParray:
if str(int(num)) != num or int(num) > 255:
print("fail3")
return False
return True
def avoidObstacles(inputArray):
inputArray.sort()
arraySet = set(inputArray)
longest_jump = 1
while longest_jump in arraySet:
longest_jump += 1
jump_point = longest_jump
changed = False
additional = 0
while jump_point < inputArray[-1]:
jump_point = jump_point + longest_jump
while jump_point in arraySet:
changed = True
additional += 1
jump_point += 1
if changed == True:
longest_jump = longest_jump + additional
additional = 0
while longest_jump in arraySet:
longest_jump += 1
jump_point = longest_jump
changed = False
return longest_jump
def boxBlur(image):
def getSum(row, column):
surroundings = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 0], [0, 1], [1, -1], [1, 0], [1, 1]]
total = 0
for coordinate in surroundings:
total = total + image[row + coordinate[0]][column + coordinate[1]]
total = total/9
return math.floor(total)
blurredImage = []
index = -1
for row in range(1, len(image)-1):
blurredImage.append([])
index += 1
for column in range(1, len(image[row])-1):
value = getSum(row, column)
blurredImage[index].append(value)
return blurredImage
def minesweeper(matrix):
def getSum(row, column):
surroundings = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]
total = 0
for coordinate in surroundings:
if 0 <= row + coordinate[0] < len(matrix) and 0 <= column + coordinate[1] < len(matrix[row]):
if matrix[row + coordinate[0]][column + coordinate[1]] == True:
total+=1
return total
mineMatrix = []
index = -1
for row in range(0, len(matrix)):
mineMatrix.append([])
index += 1
for column in range(0, len(matrix[row])):
value = getSum(row, column)
mineMatrix[index].append(value)
return mineMatrix
def arrayReplace(inputArray, elemToReplace, substitutionElem):
for index in range(0, len(inputArray)):
if inputArray[index] == elemToReplace:
inputArray[index] = substitutionElem
return inputArray
def evenDigitsOnly(n):
even = True
strN = str(n)
for digit in strN:
if int(digit)%2 == 1:
even = False
break
return even
import re
def variableName(name):
startsWith = re.search("^[a-zA-Z]", name)
if startsWith == None:
startsWith = re.search("_", name)
if startsWith == None:
return False
for char in name:
match = re.search("[a-zA-Z]", char)
if match == None:
match = re.search("_", char)
if match == None:
match = re.search("[0-9]", char)
if match == None:
return False
return True
def alphabeticShift(inputString):
alphabet_hash = {}
alphabet_string_keys = string.ascii_lowercase
alphabet_string_values = alphabet_string_keys + 'a'
for index in range(0, 26):
alphabet_hash[alphabet_string_keys[index]] = alphabet_string_values[index + 1]
inputList = list(inputString)
for index in range(0, len(inputList)):
if inputList[index] in alphabet_hash:
inputList[index] = alphabet_hash[inputList[index]]
outputString = "".join(inputList)
return outputString
def chessBoardCellColor(cell1, cell2):
color1 = ''
color2 = ''
alphabet_hash = {
"A":1,
"B":2,
"C":3,
"D":4,
"E":5,
"F":6,
"G":7,
"H":8
}
coord1 = alphabet_hash[cell1[0]]
coord2 = alphabet_hash[cell2[0]]
if int(cell1[1])%2 == 0:
if int(coord1)%2 == 0:
color1 = "Black"
else:
color1 = "White"
else:
if int(coord1)%2 != 0:
color1 = "Black"
else:
color1 = "White"
if int(cell2[1])%2 == 0:
if int(coord2)%2 == 0:
color2 = "Black"
else:
color2 = "White"
else:
if int(coord2)%2 != 0:
color2 = "Black"
else:
color2 = "White"
if color1 == color2:
return True
else:
return False
def circleOfNumbers(n, firstNumber):
halfway = n/2
number = firstNumber+ halfway
if number < n:
return number
else:
number = number - n
return number
def depositProfit(deposit, rate, threshold):
difference = threshold - deposit
amount = deposit
rate = rate/100
interest = 1 + rate
periods = 0
while amount < threshold:
amount = amount * interest
periods += 1
return periods
def absoluteValuesSumMinimization(a):
lowest_value = 0
value = 0
for num1 in range(0, len(a)):
total = 0
for num2 in range(0, len(a)):
difference = abs(a[num1] - a[num2])
total = total + difference
if num2 == len(a)-1:
if num1 == 0:
lowest_value = total
value = a[num1]
if total < lowest_value:
lowest_value = total
value = a[num1]
if total == lowest_value and a[num1] < value:
value = a[num1]
return value
def extractEachKth(inputArray, k):
popList = []
popNum = k
while popNum <= len(inputArray):
popList.append(popNum)
popNum += k
popList.reverse()
for num in popList:
inputArray.pop(num-1)
return inputArray
import re
def firstDigit(inputString):
for char in inputString:
x = re.search("[0-9]", char)
if x:
return char
def differentSymbolsNaive(s):
letterSet = set()
for letter in s:
letterSet.add(letter)
return len(letterSet)
def arrayMaxConsecutiveSum(inputArray, k):
end = 0
indexSum = 0
start = 0
for index in range(0, k):
indexSum = indexSum + inputArray[index]
end += 1
largestNum = indexSum
while end < len(inputArray):
indexSum = indexSum + inputArray[end]
indexSum = indexSum - inputArray[start]
if indexSum > largestNum:
largestNum = indexSum
end += 1
start += 1
return largestNum
def growingPlant(upSpeed, downSpeed, desiredHeight):
if upSpeed > desiredHeight:
return 1
growthAmount = desiredHeight - upSpeed
dailyGrowth = upSpeed - downSpeed
days = math.ceil(growthAmount/dailyGrowth) + 1
return days
def knapsackLight(value1, weight1, value2, weight2, maxW):
total = weight1 + weight2
if total <= maxW:
return value1 + value2
if value1 > value2 and weight1 <= maxW:
return value1
if weight2 <= maxW:
return value2
if weight1 <= maxW:
return value1
return 0
def longestDigitsPrefix(inputString):
string = ""
for char in inputString:
try:
num = int(char)
except ValueError:
return string
string = string + char
return string
def stringsRearrangement(inputArray):
hash_table = {}
for index1 in range(0, len(inputArray)):
hash_table[inputArray[index1]] = []
for index2 in range(0, len(inputArray)):
differ = 0
for index3 in range(0, len(inputArray[index1])):
if index1 != index2:
if inputArray[index1][index3] != inputArray[index2][index3]:
differ += 1
if index3 == len(inputArray[index1])-1 and differ == 1:
hash_table[inputArray[index1]].append(inputArray[index2])
# print(hash_table)
for key, value in hash_table.items():
if len(value) == 0:
return False
letterSet = {inputArray[0]}
stack = [inputArray[0]]
while len(stack) > 0:
if stack[0] in hash_table:
for value in hash_table[stack[0]]:
letterSet.add(value)
stack.append(value)
hash_table.pop(stack[0])
stack.pop(0)
print(letterSet)
if len(letterSet) == len(inputArray):
return True
return False
def digitDegree(n):
count = 0
num = n
while len(str(num)) != 1:
total = 0
for num in str(num):
total = total + int(num)
num = total
count += 1
return count
def stringsRearrangement(inputArray):
hash_table = {}
for index1 in range(0, len(inputArray)):
hash_table[inputArray[index1]] = []
for index2 in range(0, len(inputArray)):
differ = 0
for index3 in range(0, len(inputArray[index1])):
if index1 != index2:
if inputArray[index1][index3] != inputArray[index2][index3]:
differ += 1
if index3 == len(inputArray[index1])-1 and differ == 1:
hash_table[inputArray[index1]].append(inputArray[index2])
for key, value in hash_table.items():
if len(value) == 0:
return False
letterSet = {inputArray[0]}
stack = [inputArray[0]]
while len(stack) > 0:
if stack[0] in hash_table:
for value in hash_table[stack[0]]:
letterSet.add(value)
stack.append(value)
hash_table.pop(stack[0])
stack.pop(0)
if len(letterSet) == len(inputArray):
return True
return False
import itertools
def stringsRearrangement(inputArray):
permutations_object = itertools.permutations(inputArray)
permutations_list = list(permutations_object)
iteration = 0
while iteration < len(permutations_list):
oneLetterChange = 0
for word in range(0, len(permutations_list[iteration])-1):
difference = 0
for letter in range(0, len(permutations_list[iteration][word])):
if permutations_list[iteration][word][letter] != permutations_list[iteration][word+1][letter]:
difference += 1
if difference == 1:
oneLetterChange += 1
else:
iteration += 1
break
if oneLetterChange == len(inputArray)-1:
return True
return False
def bishopAndPawn(bishop, pawn):
if bishop[0] == pawn[0] or bishop[1] == pawn[1]:
return False
directions = []
hash_table = {
"a": 0,
"b": 1,
"c": 2,
"d": 3,
"e": 4,
"f": 5,
"g": 6,
"h": 7
}
movement = ["a", "b", "c", "d", "e", "f", "g", "h"]
if bishop[0] > pawn[0]:
directions.append(-1)
else:
directions.append(1)
if int(bishop[1]) > int(pawn[1]):
directions.append(-1)
else:
directions.append(1)
while 0 < int(bishop[1]) <= 8:
print(bishop)
index = hash_table[bishop[0]] + directions[0]
bishop = movement[index] + bishop[1]
bishop = bishop[0] + str(int(bishop[1]) + directions[1])
if bishop == pawn:
return True
if bishop[0] == "a" or bishop[0] == "h":
return False
return False
def isBeautifulString(inputString):
sorted_characters = sorted(inputString)
sortedString = "". join(sorted_characters)
hash_table = {}
lastLetter = sortedString[-1]
alphabet = string.ascii_lowercase
letterList = []
for letter in alphabet:
if letter != lastLetter:
letterList.append(letter)
else:
letterList.append(letter)
break
for letter in sortedString:
if letter in hash_table:
hash_table[letter] += 1
else:
hash_table[letter] = 1
for index in range(0, len(letterList)-1):
print(letterList[index])
if letterList[index] not in hash_table:
return False
if letterList[index + 1] in hash_table:
if hash_table[letterList[index]] < hash_table[letterList[index+1]]:
return False
return True
def findEmailDomain(address):
addressList = address.split("@")
return addressList[-1]
def electionsWinners(votes, k):
current_winner = 0
tie = False
for vote in votes:
if vote == current_winner:
tie = True
if vote > current_winner:
current_winner = vote
tie = False
if k == 0:
print(tie)
if tie == False:
return 1
if tie == True:
return 0
potential_winners = 0
for vote in votes:
if vote+k > current_winner:
potential_winners += 1
return potential_winners
def buildPalindrome(st):
index = math.floor(len(st)/2)
pointer1 = index-1
pointer2 = index+1
while 0 <= pointer1 and pointer2 < len(st)-1:
if st[pointer1] == st[pointer2]:
pointer1 -= 1
pointer2 += 1
else:
index += 1
pointer1 = index-1
pointer2 = index+1
if index == len(st)-2 and st[pointer1] != st[pointer2]:
if st[index] != st[pointer2]:
pointer1 = index
elif st[pointer1] == st[pointer2]:
pointer1 -= 1
while pointer1 >= 0:
first_half = st[0: int(math.floor(len(st)/2))]
second_half = st[int(math.ceil(len(st)/2)): len(st)]
reverse = second_half[::-1]
if first_half == reverse:
return st
st = st + st[pointer1]
pointer1 -= 1
return st
import re
def isMAC48Address(inputString):
inputList = inputString.split("-")
if len(inputList) != 6:
return False
for group in inputList:
if len(group) != 2:
return False
for char in group:
if re.search("[0-9]|[A-F]", char) == None:
return False
return True
import re
def isDigit(symbol):
if re.search("[0-9]", symbol) == None:
return False
return True
def lineEncoding(s):
coded = ""
currentChar = s[0]
count = 0
for index in range(0, len(s)):
if s[index] == currentChar:
count += 1
else:
if count > 1:
coded = coded + str(count) + currentChar
else:
coded = coded + currentChar
currentChar = s[index]
count = 1
if index == len(s)-1:
if count > 1:
coded = coded + str(count) + currentChar
else:
coded = coded + currentChar
return coded
def deleteDigit(n):
numStr = str(n)
highestNum = 0
for index in range(0, len(numStr)):
replace = int(numStr.replace(numStr[index], '', 1))
if replace > highestNum:
highestNum = replace
return highestNum
import re
def longestWord(text):
textList = re.split(' |, |_|-|!|\[|\]', text)
longestWord = ""
for word in textList:
onlyLetters = re.findall("[a-z]|[A-Z]", word)
newWord = ""
for letter in onlyLetters:
newWord = newWord + letter
if len(newWord) > len(longestWord):
longestWord = newWord
return longestWord
def validTime(time):
time = time.split(":")
if 0 <= int(time[0]) <= 23 and 0 <= int(time[1]) <= 59:
return True
else:
return False
def sumUpNumbers(inputString):
previousInt = False
numberStr = ""
for char in inputString:
is_int = True
try:
int_char = int(char)
except:
is_int = False
if is_int == True:
numberStr = numberStr + char
previousInt = True
if is_int == False and previousInt == True:
numberStr = numberStr + " "
previousInt = False
numberList = numberStr.split()
total = 0
for number in numberList:
total = total + int(number)
return total
def differentSquares(matrix):
hashTable = {}
coordinates = [[-1, -1], [-1, 0], [0, -1], [0, 0]]
unique = 0
for column in range(1, len(matrix)):
for row in range(1, len(matrix[column])):
fourByFour = ""
for coordinate in coordinates:
number = matrix[column + coordinate[0]][row + coordinate[1]]
fourByFour = fourByFour + str(number)
if fourByFour not in hashTable:
hashTable[fourByFour] = fourByFour
unique += 1
return(unique)
def digitsProduct(product):
if product == 0:
return 10
if product < 10:
return product
prime = 2
remainder = product
hash_table = {}
index = 0
keys = []
while prime <= remainder:
if remainder % prime == 0:
if prime in hash_table:
hash_table[prime] += 1
else:
hash_table[prime] = 1
keys.append(prime)
remainder = remainder/prime
else:
prime += 1
index += 1
if product in hash_table:
return -1
for key in keys:
if key > 9:
return -1
if 2 in hash_table and hash_table[2] >= 3:
eights = math.floor(hash_table[2]/3)
hash_table[2] -= eights * 3
hash_table[8] = eights
keys.append(8)
if hash_table[2] == 0:
hash_table.pop(2, None)
keys.remove(2)
if 3 in hash_table and hash_table[3] >= 2:
nines = math.floor(hash_table[3]/2)
hash_table[3] -= nines * 2
hash_table[9] = nines
keys.append(9)
if hash_table[3] == 0:
hash_table.pop(3, None)
keys.remove(3)
if 2 in hash_table and 3 in hash_table:
hash_table[6] = 1
keys.append(6)
hash_table.pop(3, None)
keys.remove(3)
hash_table[2] -= 1
if hash_table[2] == 0:
hash_table.pop(2, None)
keys.remove(2)
if 2 in hash_table and hash_table[2] == 2:
hash_table[4] = 1
keys.append(4)
hash_table.pop(2, None)
keys.remove(2)
keys.sort()
number = ""
for key in keys:
values = str(key) * hash_table[key]
number = number + values
return int(number)
def fileNaming(names):
hashTable ={}
for index in range(0, len(names)):
original_name = names[index]
if original_name in hashTable:
newName = original_name + "(" + str(hashTable[original_name]) + ")"
while newName in hashTable:
hashTable[original_name] += 1
newName = original_name + "(" + str(hashTable[original_name]) + ")"
hashTable[original_name] += 1
hashTable[newName] = 1
names[index] = newName
else:
hashTable[original_name] = 1
return names
def messageFromBinaryCode(code):
decrypted = ""
start = 0
end = 8
while end <= len(code):
bit = chr(int(code[start: end], base=2))
decrypted = decrypted + bit
start += 8
end += 8
return decrypted
def spiralNumbers(n):
matrix = [ [ 0 for i in range(n) ] for j in range(n) ]
number = 1
limit = n*n
row = 0
column = -1
while number <= limit:
while column < n-1:
column += 1
if matrix[row][column] == 0:
matrix[row][column] = number
number += 1
else:
column -= 1
break
while row < n-1:
row += 1
if matrix[row][column] == 0:
matrix[row][column] = number
number += 1
else:
row -= 1
break
while column >= 0:
column -= 1
if matrix[row][column] == 0:
matrix[row][column] = number
number += 1
else:
column += 1
break
while row >= 0:
row -= 1
if matrix[row][column] == 0:
matrix[row][column] = number
number += 1
else:
row += 1
break
return matrix
def sudoku(grid):
hashTable = {
"rows": [],
"columns": {},
"square1": [],
"square2": [],
"square3": []
}
def check(arr):
sorted_arr = sorted(arr)
one_to_nine = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for index in range(0, len(one_to_nine)):
if one_to_nine[index] != sorted_arr[index]:
return False
return True
for row in range(0, len(grid)):
hashTable["rows"] = []
if row == 3 or row == 6:
if check(hashTable["square1"]) == False:
return False
if check(hashTable["square2"]) == False:
return False
if check(hashTable["square3"]) == False:
return False
hashTable["square1"] = []
hashTable["square2"] = []
hashTable["square3"] = []
for column in range(0, len(grid[row])):
hashTable["rows"].append(grid[row][column])
if column in hashTable["columns"]:
hashTable["columns"][column].append(grid[row][column])
else:
hashTable["columns"][column] = [grid[row][column]]
if 0 <= column <= 2:
hashTable["square1"].append(grid[row][column])
if 2 < column <= 5:
hashTable["square2"].append(grid[row][column])
if 5 < column <= 8:
hashTable["square3"].append(grid[row][column])
if check(hashTable["rows"]) == False:
return False
if check(hashTable["square1"]) == False:
return False
if check(hashTable["square2"]) == False:
return False
if check(hashTable["square3"]) == False:
return False
for value in hashTable["columns"].values():
if check(value) == False:
return False
return True
def newRoadSystem(roadRegister):
hashTable = {}
for inGoing in range(0, len(roadRegister)):
for outGoing in range(0, len(roadRegister[inGoing])):
if roadRegister[inGoing][outGoing] == True:
if inGoing in hashTable:
hashTable[inGoing][0].append(outGoing)
else:
hashTable[inGoing] = [[outGoing], []]
if outGoing in hashTable:
hashTable[outGoing][1].append(inGoing)
else:
hashTable[outGoing] = [[], [inGoing]]
for value in hashTable.values():
if len(value[0]) != len(value[1]):
return False
return True
def largestNumber(n):
num = ["9"]*n
num = int("".join(num))
return num
def roadsBuilding(cities, roads):
hashTable = {}
key = 0
while key < cities-1:
hashTable[key] = []
connection = key+1
while connection < cities:
hashTable[key].append([key, connection])
connection += 1
key += 1
for road in roads:
if road[0] > road[1]:
smallestValue = 1
largestValue = 0
else:
smallestValue = 0
largestValue = 1
hashTable[road[smallestValue]].remove([road[smallestValue], road[largestValue]])
roadsToBuild = []
for value in hashTable.values():
if len(value) > 0:
for connection in value:
roadsToBuild.append(connection)
return roadsToBuild
def efficientRoadNetwork(n, roads):
if n == 1:
return True
hashTable = {}
for road in roads:
if road[0] not in hashTable:
hashTable[road[0]] = []
if road[1] not in hashTable:
hashTable[road[1]] = []
hashTable[road[0]].append(road[1])
hashTable[road[1]].append(road[0])
city = 0
while city < n:
if city not in hashTable:
return False
visited = set(hashTable[city])
for destination in hashTable[city]:
visited.update(hashTable[destination])
if len(visited) < n:
return False
city += 1
return True
import copy
def financialCrisis(roadRegister):
removeCity = 0
removedRegister = []
while removeCity < len(roadRegister):
registerCopy = copy.deepcopy(roadRegister)
registerCopy.pop(removeCity)
for rowIndex in range(0, len(registerCopy)):
registerCopy[rowIndex].pop(removeCity)
removedRegister.append(registerCopy)
removeCity += 1
return removedRegister
def namingRoads(roads):
hashTable = {}
for road in roads:
if road[0] not in hashTable:
hashTable[road[0]] = []
if road[1] not in hashTable:
hashTable[road[1]] = []
hashTable[road[0]].append(road[2])
hashTable[road[1]].append(road[2])
for value in hashTable.values():
sortedValues = sorted(value)
for integer in range(0, len(sortedValues)-1):
if sortedValues[integer] + 1 == sortedValues[integer + 1]:
return False
return True
def greatRenaming(roadRegister):
firstCity = roadRegister.pop()
roadRegister.insert(0, firstCity)
for city in roadRegister:
shift = city.pop()
city.insert(0, shift)
return roadRegister
def phoneCall(min1, min2_10, min11, s):
mins = 0
if s >= min1:
s = s-min1
mins = 1
else:
return 0
if s >= min2_10:
numMins = math.floor(s/min2_10)
if numMins >= 9:
s = s - 9*min2_10
mins = 10
else:
mins = mins + numMins
return mins
else:
return mins
if s >= min11:
numMins = math.floor(s/min11)
return mins + numMins
else:
return mins
def mergingCities(roadRegister):
hashTable = {}
connected = []
for city in range(len(roadRegister)):
hashTable[city] = []
for road in range(len(roadRegister[city])):
if roadRegister[city][road] == True:
hashTable[city].append(road)
if road == 0 or road%2 == 0:
if road in hashTable and city in hashTable[road] and city-1 == road:
connected.append(road)
connected.append(city)
length = int(len(roadRegister) - len(connected)/2)
while len(connected) > 0:
hashTable[connected[0]] = list(set(hashTable[connected[0]] + hashTable[connected[1]]))
hashTable[connected[0]].remove(connected[0])
hashTable[connected[0]].remove(connected[1])
for pair in hashTable.items():
for index in range(len(pair[1])):
if hashTable[pair[0]][index] > connected[0]:
hashTable[pair[0]][index] -= 1
if pair[0] > connected[1]:
hashTable[pair[0]-1] = hashTable[pair[0]]
for index in range(len(connected)):
connected[index] = connected[index] - 1
hashTable.pop(pair[0])
connected.pop(0)
connected.pop(0)
newRegister = []
for index in range(length):
cities = [False]*length
newRegister.append(cities)
for key in range(length):
for value in hashTable[key]:
newRegister[key][value] = True
return newRegister
def isButterfly(adj):
hashTable = {}
for rowIndex in range(len(adj)):
hashTable[rowIndex] = []
for colIndex in range(len(adj[rowIndex])):
if adj[rowIndex][colIndex] == True:
hashTable[rowIndex].append(colIndex)
not2 = []
for key in hashTable.keys():
if len(hashTable[key]) != 2:
not2.append(key)
if len(not2) != 1:
return False
centerpoint = not2[0]
if len(hashTable[centerpoint]) != 4:
return False
for key in hashTable.keys():
if int(key) in hashTable[key]:
return False
if key != centerpoint:
if int(centerpoint) not in hashTable[key]:
return False
for value in hashTable[key]:
if int(key) not in hashTable[value]:
return False
return True
def countStars(adj):
hashTable = {}
centerpoints = []
keys = []
for rowIndex in range(len(adj)):
hashTable[rowIndex] = []
keys.append(rowIndex)
for columnIndex in range(len(adj[rowIndex])):
if adj[rowIndex][columnIndex] == True:
hashTable[rowIndex].append(columnIndex)
if len(hashTable[rowIndex]) > 1:
centerpoints.append(rowIndex)
if rowIndex in keys:
keys.remove(rowIndex)
keys = list(set(keys))
centerpoints = set(centerpoints)
shapes = 0
isShape = False
if len(centerpoints) > 0:
for centerpoint in centerpoints:
if isShape == True:
shapes += 1
isShape = True
for point in hashTable[centerpoint]:
if point in keys:
keys.remove(point)
if len(hashTable[point]) != 1 or hashTable[point][0] != centerpoint:
isShape = False
if isShape == True:
shapes += 1
visited = []
if len(keys) > 0:
for key in keys:
if key not in visited and len(hashTable[key]) > 0:
value = hashTable[key][0]
if len(hashTable[value]) > 0 and hashTable[value][0] == key and key != value:
visited.append(value)
shapes += 1
return shapes
def knapsackLight(value1, weight1, value2, weight2, maxW):
if weight1 + weight2 <= maxW:
return value1 + value2
if value1 > value2:
greaterValue = value1
greaterValueWeight = weight1
lesserValue = value2
lesserValueWeight = weight2
elif value2 > value1:
greaterValue = value2
greaterValueWeight = weight2
lesserValue = value1
lesserValueWeight = weight1
else:
if weight1 or weight2 <= maxW:
return value1
else:
return 0
if greaterValueWeight <= maxW:
return greaterValue
if lesserValueWeight <= maxW:
return lesserValue
return 0
def isInfiniteProcess(a, b):
while b >= a:
if a == b:
return False
a = a + 1
b = b - 1
return True
def isWheel(adj):
hashTable = {}
centerpoint = []
for rowIndex in range(len(adj)):
hashTable[rowIndex] = []
for columnIndex in range(len(adj[rowIndex])):
if adj[rowIndex][columnIndex] == True:
hashTable[rowIndex].append(columnIndex)
if len(hashTable[rowIndex]) == len(adj)-1:
centerpoint.append(rowIndex)
if len(centerpoint) == 4 and len(centerpoint) == len(adj):
return True
if len(centerpoint) != 1:
return False
centerpoint = centerpoint[0]
centerList = hashTable[centerpoint]
if centerpoint in centerList or len(centerList) != len(adj)-1:
return False
if centerpoint == 0:
point = 1
else:
point = 0
visited = []
previouspoint = ""
while point not in visited:
if centerpoint not in hashTable[point] or len(hashTable[point]) != 3:
return False
listCopy = hashTable[point].copy()
listCopy.remove(centerpoint)
if previouspoint != "":
listCopy.remove(previouspoint)
previouspoint = point
visited.append(point)
point = listCopy[0]
if len(visited) != len(adj)-1:
return False
return True
def tennisSet(score1, score2):
if score1 > 7 or score2 > 7:
return False
if score1 < 6 and score2 < 6:
return False
if score1 == 6 and score2 < 5:
return True
if score2 == 6 and score1 < 5:
return True
if score1 == 7 and 4 < score2 < 7:
return True
if score2 == 7 and 4 < score1 < 7:
return True
return False
def arrayPacking(a):
a.reverse()
bins = ""
for num in a:
number = str(bin(num).replace("0b",""))
if len(number) < 8:
numZeros = 8 - len(number)
zeros = "0"*numZeros
number = zeros + number
bins = bins + number
return int(bins, 2)
def rangeBitCount(a, b):
count = 0
num = a
while num <= b:
count += len(str(bin(num).replace("0b","").replace("0", "")))
num += 1
return count
def mirrorBits(a):
return int(str(bin(a).replace("0b",""))[::-1], 2)
def secondRightmostZeroBit(n):
return 2**(str(bin(n).replace("0b", "")[::-1].replace("0", "", 1)).find("0") + 1)
def swapAdjacentBits(n):
return swap(n)
def swap(n):
binary = str(bin(n).replace("0b", ""))
if len(binary)%2 != 0:
binary = "0" + binary
count = 0
while count <= len(binary)-1:
binary = ''.join((binary[:count], binary[count+1], binary[count], binary[count+2:]))
count += 2
return int(binary, 2)
def differentRightmostBit(n, m):
return 2 ** len(bin(n^m)) if bin(n^m).replace("0b", "")[::-1].find("1") == -1 else 2 ** bin(n^m).replace("0b", "")[::-1].find("1")
def equalPairOfBits(n, m):
return 2 ** len(bin(n^m).replace("0b", "")) if bin(n^m).replace("0b", "")[::-1].find("0") == -1 else 2 ** bin(n^m).replace("0b", "")[::-1].find("0")
def leastFactorial(n):
k = 1
m = 1
while k < n:
m += 1
k = k*m
return k
def countSumOfTwoRepresentations2(n, l, r):
A = l
B = n-l
count = 0
if A + B == n and l <= A <= B <= r:
while l <= A <= B <= r:
count += 1
A += 1
B -= 1
return count
B = r
A = n-r
if A + B == n and l <= A <= B <= r:
while l <= A <= B <= r:
count += 1
A += 1
B -= 1
return count
return count
def magicalWell(a, b, n):
total = 0
while n > 0:
total = a*b + total
a += 1
b += 1
n -= 1
return total
def lineUp(commands):
directions = [0, 0]
same = 0
for command in commands:
if command == "L":
directions[0] += 1
directions[1] -= 1
if command == "R":
directions[0] -= 1
directions[1] += 1
if command == "A":
directions[0] += 2
directions[1] -= 2
if directions[0] == -1:
directions[0] = 3
if directions[1] == -1:
directions[1] = 3
if directions[0] == -2:
directions[0] = 2
if directions[1] == -2:
directions[1] = 2
if directions[0] > 3:
directions[0] = directions[0]%4
if directions[1] > 3:
directions[1] = directions[1]%4
if directions[0] == directions[1]:
same += 1
return same
def increaseNumberRoundness(n):
string = str(n)[::-1]
index = 0
while string[index] == "0" and index < len(string):
string = string.replace('0','',1)
roundness = string.find("0")
if roundness == -1:
return False
return True
def rounders(n):
numList = [int(x) for x in str(n)[::-1]]
newNum = ''
for num in range(len(numList)-1):
if numList[num] >= 5:
numList[num+1]+=1
zeros = len(numList)-1
newNum = str(numList[-1]) + "0"*zeros
return int(newNum)
def candles(candlesNumber, makeNew):
num = candlesNumber
leftOvers = candlesNumber
while leftOvers >= makeNew:
candles = math.floor(leftOvers/makeNew)
remainder = leftOvers - candles*makeNew
num = num + candles
leftOvers = candles + remainder
return num
def countBlackCells(n, m):
intersection = 0
black_cells = 0
row = 1
while row <= n:
next_intersection = (m/n) * row
amount = math.ceil(next_intersection) - math.floor(intersection)
if row != n and next_intersection == math.floor(next_intersection):
black_cells+=2
black_cells = black_cells + amount
intersection = next_intersection
row += 1
return black_cells
def removeArrayPart(inputArray, l, r):
return inputArray[0:l] + inputArray[r+1:len(inputArray)]
def isSmooth(arr):
length = len(arr)
if length%2 != 0:
middle = arr[math.floor(length/2)]
else:
length = length/2
middle = arr[math.ceil(length)] + arr[math.floor(length-1)]
if arr[0] == arr[-1] == middle:
return True
else:
return False
def replaceMiddle(arr):
if len(arr)%2 == 0:
middle = math.floor(len(arr)/2)
arr[middle] = arr[middle] + arr[middle-1]
del arr[middle-1]
return arr
def makeArrayConsecutive2(statues):
statues.sort()
missing = 0
for index in range(len(statues)-1):
between = statues[index+1] - statues[index] - 1
missing += between
return missing
def isSumOfConsecutive2(n):
divisor = 2
ways = 1
while divisor <= n:
count = 0
while n%divisor == 0:
n = n/divisor
count+=1
if count > 0 and divisor%2 != 0:
ways = ways*(1+count)
divisor+=1
return ways-1
def squareDigitsSequence(a0):
occored = set()
num = a0
count = 1
while num not in occored:
occored.add(num)
count+=1
stringNum = str(num)
num = 0
for integer in stringNum:
num = num + int(integer)**2
return count
def pagesNumberingWithInk(current, numberOfDigits):
total = current-1
remainder = numberOfDigits
digitsPerInt = len(str(total))
roundUp = int("1" + digitsPerInt * "0") - 1
amountToGo = roundUp-total
rounding = 0
while remainder-amountToGo*digitsPerInt >= 0:
rounding = 1
total = roundUp
digitsPerInt = len(str(total))
remainder -= amountToGo * digitsPerInt
roundUp = roundUp*10 + 9
amountToGo = roundUp - total
total+=math.floor(remainder/(digitsPerInt + rounding))
return total
def weakNumbers(n):
if n <= 4:
return [0, n]
factorization = []
hashTable = {}
keys=[2]
answer = [0, 0]
for number in range(4, n+1):
copy=number
divisor = 2
while copy!=1:
count = 0
while copy%divisor == 0:
copy=copy/divisor
count+=1
if count > 0:
factorization.append(count)
divisor+=1
total=1
for power in factorization:
total*=(1+power)
if total > 2:
if total not in hashTable:
hashTable[total] = 0
keys.append(total)
hashTable[total]+=1
weakness = 0
index = -1
while keys[index] > total:
weakness+=hashTable[keys[index]]
index-=1
if weakness > answer[0]:
answer[0] = weakness
answer[1] = 1
elif weakness == answer[0]:
answer[1]+=1
factorization = []
return answer
def properNounCorrection(noun):
noun = noun[0].upper() + noun[1:].lower()
return noun
def isTandemRepeat(inputString):
concat = inputString[:int(len(inputString)/2)]
if concat + concat == inputString:
return True
return False
def isCaseInsensitivePalindrome(inputString):
inputString = inputString.lower()
half = math.floor(len(inputString)/2)
if len(inputString)%2 == 0:
if inputString[:half] == inputString[half:len(inputString)][::-1]:
return True
else:
return False
print(inputString[:half], inputString[half+1:len(inputString)][::-1])
if inputString[:half] == inputString[half+1:len(inputString)][::-1]:
return True
return False
def stringsConstruction(a, b):
hashTable = {}
for letter in a:
if letter not in hashTable:
hashTable[letter] = [0, 0]
hashTable[letter][0]+=1
for element in b:
if element in hashTable:
hashTable[element][1]+=1
minNum = math.floor(hashTable[a[0]][1]/hashTable[a[0]][0])
for values in hashTable.values():
if values[1]/values[0] < minNum:
minNum = math.floor(values[1]/values[0])
return minNum
def isSubstitutionCipher(string1, string2):
hashtable = {}
value = 0
code1 = ''
for letter in string1:
if letter not in hashtable:
hashtable[letter] = value
value += 1
code1+=str(hashtable[letter])
hashtable = {}
value = 0
code2 = ''
for letter in string2:
if letter not in hashtable:
hashtable[letter] = value
value += 1
code2+=str(hashtable[letter])
if code1 == code2:
return True
return False
def createAnagram(s, t):
for letter in s:
found = t.find(letter)
if found != -1:
t = t[0 : found : ] + t[found + 1 : :]
return len(t)
# This funciton works if the shape of the letters must match the shape of the number
def constructSquare(s):
hashTable = {}
largestPossible = math.floor(math.sqrt(int("9"*len(s))))
largestPossibleSquare=str(largestPossible**2)
counter = 0
while len(largestPossibleSquare) == len(s) and counter < len(s):
for index in range(len(s)):
if s[index] not in hashTable:
hashTable[s[index]] = largestPossibleSquare[index]
if hashTable[s[index]] != largestPossibleSquare[index]:
largestPossible-=1
largestPossibleSquare=str(largestPossible**2)
hashTable = {}
counter = 0
break
else:
counter+=1
if len(largestPossibleSquare) < len(s):
return -1
return int(largestPossibleSquare)
# This works if you can re-arrange the letter values
def constructSquare(s):
hashTable = {}
largestPossible = math.floor(math.sqrt(int("9"*len(s))))
largestPossibleSquare=str(largestPossible**2)
codeSet = set()
sequence1 = []
sequence2 = []
for letter in s:
if letter not in codeSet:
codeSet.add(letter)
sequence1.append(s.count(letter))
sequence1.sort()
largestPossible+=1
while sequence1 != sequence2:
codeSet = set()
sequence2 = []
largestPossible-=1
largestPossibleSquare=str(largestPossible**2)
if len(s) != len(largestPossibleSquare):
return -1
for integer in largestPossibleSquare:
if integer not in codeSet:
codeSet.add(integer)
sequence2.append(largestPossibleSquare.count(integer))
sequence2.sort()
return int(largestPossibleSquare)
def numbersGrouping(a):
total = set()
for num in a:
addition = math.ceil(num/(10000))
total.add(addition)
return len(total)+len(a)
def mostFrequentDigitSum(n):
hashTable = {}
number = 0
occorance = 0
while n > 0:
summation = 0
strN = str(n)
for value in strN:
summation+=int(value)
if summation not in hashTable:
hashTable[summation] = 0
hashTable[summation] += 1
if hashTable[summation] == occorance and summation > number:
number = summation
if hashTable[summation] > occorance:
number = summation
occorance = hashTable[summation]
n = n-int(summation)
return number
def numberOfClans(divisors, k):
clans = set()
for integer in range(1, k+1):
clanNum = ''
for divisor in divisors:
if integer%divisor == 0:
clanNum+=str(divisor)
clans.add(clanNum)
return len(clans)
def differentSquares(matrix):
squares = set()
coordinates = [[0,0], [0, +1], [+1, 0], [+1, +1]]
for rowIndex in range(len(matrix)-1):
for value in range(len(matrix[rowIndex])-1):
possibleSquare = ''
for coordinate in coordinates:
possibleSquare+=str(matrix[rowIndex+coordinate[0]][value+coordinate[1]])
squares.add(possibleSquare)
return len(squares)
def houseOfCats(legs):
combinations = []
people = 0
if legs == 0:
return [0]
if legs%4 == 0:
combinations.append(people)
while legs > 4:
people+=1
legs-=2
if legs%4 == 0:
combinations.append(people)
if legs == 4:
people+=2
combinations.append(people)
return combinations
people+=1
combinations.append(people)
return combinations
def alphabetSubsequence(s):
hashTable = {}
index = 0
alphabet_string = string.ascii_lowercase
for letter in alphabet_string:
hashTable[letter] = index
index+=1
for elem_index in range(len(s)-1):
if hashTable[s[elem_index]] >= hashTable[s[elem_index+1]]:
return False
return True
def addBorder(picture):
picture.insert(0, "*"*len(picture[0]))
picture.append("*"*len(picture[0]))
for index in range(len(picture)):
picture[index] = "*"+picture[index]+"*"
return picture
def timedReading(maxLength, text):
alphabet_string = string.ascii_uppercase + string.ascii_lowercase
alphabet_set = set(alphabet_string)
word_count = 0
letter_count = 0
for letter in text:
if letter == " ":
if letter_count <= maxLength:
word_count+=1
letter_count = 0
elif letter in alphabet_set:
letter_count+=1
if 0 < letter_count <= maxLength:
word_count+=1
return word_count
def areSimilar(a, b):
list1 = []
list2 = []
for index in range(len(a)):
if a[index] != b[index]:
list1.append(a[index])
list2.append(b[index])
if len(list1) > 2:
return False
list1.sort()
list2.sort()
if list1 == list2:
return True
return False
def higherVersion(ver1, ver2):
arr1 = []
arr2 = []
number = ""
for element in ver1:
if element == ".":
arr1.append(number)
number = ""
else:
number += element
arr1.append(number)
number = ""
for element in ver2:
if element == ".":
arr2.append(number)
number = ""
else:
number += element
arr2.append(number)
difference = len(arr1) - len(arr2)
if difference > 0:
arr2 = arr2 + [0] * difference
if difference < 0:
arr1 = arr1 + [0] * abs(difference)
print(arr1, arr2)
for index in range(len(arr1)):
num1 = int(arr1[index])
num2 = int(arr2[index])
if num1 > num2:
return True
if num2 > num1:
return False
return False
def pairOfShoes(shoes):
hashTable = {}
unpaired = 0
for shoe in shoes:
if shoe[0] == 0:
key = "1" + str(shoe[1])
else:
key = "0" + str(shoe[1])
if key in hashTable and hashTable[key] >= 1:
hashTable[key] -= 1
unpaired -= 1
# print(unpaired)
# print("1", hashTable)
else:
if shoe[0] == 0:
key = "0" + str(shoe[1])
else:
key = "1" + str(shoe[1])
if key not in hashTable:
hashTable[key] = 0
hashTable[key] += 1
# print("2", hashTable)
unpaired += 1
# print(unpaired)
if unpaired > 0:
return False
return True
def combs(comb1, comb2):
setComb = set()
listComb = []
for index in range(len(comb1)):
if comb1[index] == "*":
setComb.add(index)
for index in range(len(comb2)):
if comb2[index] == "*":
listComb.append(index)
if len(comb1) > len(comb2):
length = len(comb1)
else:
length = len(comb2)
longest = len(comb1)+len(comb2)
shift = 0
tooth = 0
while tooth < len(comb2)-1:
for tooth in listComb:
if (tooth+shift) in setComb:
shift+=1
break
if len(comb1) > len(comb2)+shift:
return len(comb1)
return len(comb2)+shift
def findEmailDomain(address):
return address[address.rfind("@")+1:len(address)]
def htmlEndTagByStartTag(startTag):
return "</"+startTag[1:startTag.find(" ")]+">"
def stringsCrossover(inputArray, result):
total = 0
for string1 in range(len(inputArray)):
for string2 in range(string1+1, len(inputArray)):
match = 0
for index in range(len(result)):
if result[index] != inputArray[string1][index] and result[index] != inputArray[string2][index]:
match = 0
break
else:
match+=1
if match == len(result):
total+=1
return total
def cipher26(message):
cypher = {}
alphabet = string.ascii_lowercase
for index in range(len(alphabet)):
cypher[alphabet[index]] = index
cypher[str(index)] = alphabet[index]
decoded = message[0]
lastValue = cypher[message[0]]
for index in range(1, len(message)):
currentValue = cypher[message[index]]
if currentValue < lastValue:
currentValue+=26
nextValue = currentValue - lastValue
decoded+=cypher[str(nextValue)]
lastValue = currentValue%26
return decoded
def extractMatrixColumn(matrix, column):
columnList = []
for row in matrix:
columnList.append(row[column])
return columnList
def areIsomorphic(array1, array2):
if len(array1) != len(array2):
return False
for index in range(len(array1)):
if len(array1[index]) != len(array2[index]):
return False
return True
def reverseOnDiagonals(matrix):
start = 0
end = len(matrix)-1
while start < len(matrix)/2:
matrix[start][start], matrix[end][end] = matrix[end][end], matrix[start][start]
matrix[start][end], matrix[end][start] = matrix[end][start], matrix[start][end]
start+=1
end-=1
return matrix
def swapDiagonals(matrix):
start = 0
end = -1
for row in matrix:
row[start], row[end] = row[end], row[start]
start+=1
end-=1
return matrix
def crossingSum(matrix, a, b):
total = 0
for element in matrix[a]:
total+=element
for row in range(len(matrix)):
total+=matrix[row][b]
total-=(matrix[a][b])
return total
def drawRectangle(canvas, rectangle):
side = ["*"] + ["-"]*(rectangle[2] - rectangle[0]-1) + ["*"]
canvas[rectangle[1]] = canvas[rectangle[1]][0:rectangle[0]] + side + canvas[rectangle[1]][rectangle[2]+1:len(canvas[rectangle[1]])]
canvas[rectangle[3]] = canvas[rectangle[3]][0:rectangle[0]] + side + canvas[rectangle[3]][rectangle[2]+1:len(canvas[rectangle[3]])]
for row in range(rectangle[1]+1, rectangle[3]):
canvas[row][rectangle[0]], canvas[row][rectangle[2]] = "|", "|"
return canvas
def volleyballPositions(formation, k):
k=k%6
if k==0:
return formation
positionsList = [[0, 1], [1, 2], [3, 2], [2, 1], [3, 0], [1, 0]]
playerList = []
for position in positionsList:
playerList.append(formation[position[0]][position[1]])
playerList = playerList[k: len(playerList)] + playerList[0: k]
for index in range(len(playerList)):
formation[positionsList[index][0]][positionsList[index][1]] = playerList[index]
return formation
def sudoku(grid):
squareCheck = [set(), set(), set()]
columnCheck = []
for row in range(len(grid)):
columnCheck.append(set())
for row in range(len(grid)):
rowSet = set(grid[row])
if len(rowSet) != 9:
return(False)
if row > 0 and row%3 == 0:
for square in squareCheck:
if len(square) != 9:
return False
squareCheck = [set(), set(), set()]
for column in range(len(grid[row])):
number = grid[row][column]
if column < 3:
squareCheck[0].add(number)
if 2 < column < 6:
squareCheck[1].add(number)
if column > 5:
squareCheck[2].add(number)
columnCheck[column].add(number)
rowCheck = set()
for square in squareCheck:
if len(square) != 9:
return False
for column in columnCheck:
if len(column) != 9:
return False
return True
def minesweeper(matrix):
checks = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]
newMatrix = []
for row in matrix:
newMatrix.append([0]*len(matrix[0]))
for rowIndex in range(len(matrix)):
for columnIndex in range(len(matrix[rowIndex])):
if matrix[rowIndex][columnIndex] == True:
for check in checks:
if 0<=rowIndex+check[0]<len(matrix) and 0<=columnIndex+check[1]<len(matrix[rowIndex]):
newMatrix[rowIndex+check[0]][columnIndex+check[1]]+=1
return newMatrix
def boxBlur(image):
coordinates = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 0], [0, 1], [1, -1], [1, 0], [1, 1]]
blurImage=[]
values=[]
for rowIndex in range(1, len(image)-1):
row = []
for columnIndex in range(1, len(image[rowIndex])-1):
total=0
for coordinate in coordinates:
total+=image[rowIndex+coordinate[0]][columnIndex+coordinate[1]]
values.append(image[rowIndex+coordinate[0]][columnIndex+coordinate[1]])
print(total/9)
total=math.floor(total/9)
row.append(total)
blurImage.append(row)
return blurImage
def shuffledArray(shuffled):
total = 0
shuffled.sort()
for number in shuffled:
total+=number
for index in range(len(shuffled)):
if total-shuffled[index] == shuffled[index]:
return shuffled[0:index] + shuffled[index+1:len(shuffled)]
def sortByHeight(a):
indexMap = []
order = []
for index in range(len(a)):
element = a[index]
if element != -1:
indexMap.append(index)
order.append(element)
order.sort()
for index in range(len(order)):
a[indexMap[index]] = order[index]
return a
def sortByLength(inputArray):
hashTable = {}
lengths = []
outputArray = []
for string in inputArray:
length = len(string)
if length not in hashTable:
hashTable[length] = []
lengths.append(length)
hashTable[length].append(string)
lengths.sort()
for key in lengths:
outputArray += hashTable[key]
return outputArray
def maximumSum(a, q):
mentions = [0]*len(a)
total = 0
for pair in q:
for number in range(pair[0], pair[1]+1):
mentions[number] += 1
mentions.sort()
a.sort()
mentions.reverse()
a.reverse()
index = 0
while index < len(mentions) and mentions[index] > 0:
total+=(a[index]*mentions[index])
index += 1
return total
def rowsRearranging(matrix):
if len(matrix) == 1:
return True
hashTable = {}
keys = []
for rowIndex in range(len(matrix)):
key = matrix[rowIndex][0]
if key in hashTable:
return False
hashTable[key] = matrix[rowIndex]
keys.append(key)
keys.sort()
for column in range(1, len(matrix[0])):
lastNum = hashTable[keys[0]][column]
for keyIndex in range(1, len(keys)):
nextNum = hashTable[keys[keyIndex]][column]
if lastNum >= nextNum:
return False
lastNum = nextNum
return True
def digitDifferenceSort(a):
hashTable = {}
keys = []
array = []
for number in a:
stringNum = str(number)
if len(stringNum) == 1:
if 0 not in hashTable:
hashTable[0] = []
keys.append(0)
hashTable[0] = [number] + hashTable[0]
else:
largest = int(stringNum[0])
smallest = int(stringNum[0])
for element in stringNum:
intNum = int(element)
if intNum > largest:
largest = intNum
if intNum < smallest:
smallest = intNum
difference = largest-smallest
if difference not in hashTable:
hashTable[difference] = []
keys.append(difference)
hashTable[difference] = [number] + hashTable[difference]
keys.sort()
for key in keys:
array = array + hashTable[key]
return array
def uniqueDigitProducts(a):
aSet = set()
for number in a:
stringNum = str(number)
if len(stringNum) == 1:
aSet.add(number)
else:
total = 1
for digit in stringNum:
total*=int(digit)
aSet.add(total)
return len(aSet)
def bishopAndPawn(bishop, pawn):
alphabet = {
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6,
"g": 7,
"h": 8
}
if abs(int(pawn[1]) - int(bishop[1])) == abs(alphabet[pawn[0]] - alphabet[bishop[0]]):
return True
return False
def chessKnightMoves(cell):
moveCount = 0
dictionary = {
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6,
"g": 7,
"h": 8
}
moves = [[-2, 1], [-1, 2], [1, 2], [2, 1], [2, -1], [1, -2], [-1, -2], [-2, -1]]
horizontal = dictionary[cell[0]]
vertical = int(cell[1])
for move in moves:
if 0 < horizontal + move[0] < 9 and 0 < vertical + move[1] < 9:
moveCount+=1
return moveCount
alphabet = {
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6,
"g": 7,
"h": 8,
1: "a",
2: "b",
3: "c",
4: "d",
5: "e",
6: "f",
7: "g",
8: "h"
}
def bishopDiagonal(bishop1, bishop2):
bishop1Dict = {
"horizontal": alphabet[bishop1[0]],
"vertical": int(bishop1[1]),
"horMove": 0,
"vertMove": 0
}
bishop2Dict = {
"horizontal": alphabet[bishop2[0]],
"vertical": int(bishop2[1]),
"horMove": 0,
"vertMove": 0
}
if abs(bishop1Dict["horizontal"] - bishop2Dict["horizontal"]) != abs(bishop1Dict["vertical"] - bishop2Dict["vertical"]):
return(chessOrder([bishop1, bishop2]))
operations = [["horizontal", "horMove"], ["vertical", "vertMove"]]
for operation in operations:
if bishop1Dict[operation[0]] < bishop2Dict[operation[0]]:
bishop1Dict[operation[1]] = bishop1Dict[operation[0]]*-1+1
bishop2Dict[operation[1]] = 8-bishop2Dict[operation[0]]
else:
bishop2Dict[operation[1]] = bishop2Dict[operation[0]]*-1+1
bishop1Dict[operation[1]] = 8-bishop1Dict[operation[0]]
bishops = [bishop1Dict, bishop2Dict]
for bishop in bishops:
if abs(bishop["horMove"]) <= abs(bishop["vertMove"]):
edgeCase = 1
if abs(bishop["vertMove"]) != bishop["vertMove"]:
edgeCase = -1
bishop["horizontal"]+=bishop["horMove"]
bishop["vertical"]+=abs(bishop["horMove"])*edgeCase
else:
edgeCase = 1
if abs(bishop["horMove"]) != bishop["horMove"]:
edgeCase = -1
bishop["horizontal"]+=abs(bishop["vertMove"])*edgeCase
bishop["vertical"]+=bishop["vertMove"]
bishops = [(alphabet[bishop1Dict["horizontal"]])+str(bishop1Dict["vertical"]), (alphabet[bishop2Dict["horizontal"]])+str(bishop2Dict["vertical"])]
return chessOrder(bishops)
def chessOrder(bishops):
if alphabet[bishops[0][0]] > alphabet[bishops[1][0]]:
bishops[0], bishops[1] = bishops[1], bishops[0]
return bishops
def threeSplit(a):
ways = 0
pointer1 = 0
peice1 = [a[0]]
total1 = a[0]
# container for possible cuts
# stable = []
while len(peice1) < len(a)-1:
total2 = 0
for index in range(len(peice1), len(a)-1):
total2+=a[index]
if total1 == total2:
# peice2 = a[len(peice1): index+1]
total3 = 0
peice3 = a[index+1: len(a)]
for number in peice3:
total3 += number
if total1 == total2 == total3:
# can be used to capture possible cuts
# stable.append([[peice1], [peice2], [peice3]])
ways+=1
pointer1+=1
peice1 = a[0: pointer1+1]
total1+=a[pointer1]
return ways
def threeSplitAlt(a):
total = 0
for number in a:
total+=number
ways = 0
pointer1 = 0
total1 = a[pointer1]
total2 = a[1]
total3 = total-total1-total2
while pointer1 < len(a)-2:
if total1 == total2 == total3:
ways+=1
pointer2 = pointer1+2
while pointer2 < len(a)-1:
total2 += a[pointer2]
total3 -= a[pointer2]
if total1 == total2 == total3:
ways+=1
pointer2+=1
total1+=a[pointer1-1]
total2=a[pointer1]
total3 = total-total1-total2
pointer1+=1
return ways
def threeSplitFaster(a):
total = 0
zeros = 0
for number in a:
if number == 0:
zeros+=1
else:
total+=number
if zeros == len(a):
return zeros+1
ways = 0
pointer1 = 0
total1 = a[pointer1]
secondaryWays = 0
while pointer1 < len(a)-2:
if (total-total1)/2 == total1:
pointer2 = pointer1+1
total2=a[pointer2]
if total1 == total2:
ways+=1
pointer2+=1
secondaryWays=0
while pointer2 < len(a)-1:
total2 += a[pointer2]
if total1 == total2:
ways+=1
secondaryWays+=1
pointer2+=1
pointer1+=1
while a[pointer1] == 0:
ways+=secondaryWays
pointer1+=1
total1+=a[pointer1]
else:
pointer1+=1
total1+=a[pointer1]
return ways
def polygonPerimeter(matrix):
parameter=0
rowAbove=set()
for row in range(len(matrix)):
leftCell=False
for column in range(len(matrix[row])):
cell = matrix[row][column]
if cell == True:
parameter+=4
if leftCell == True:
parameter-=2
if column in rowAbove:
parameter-=2
rowAbove.add(column)
leftCell = True
else:
if column in rowAbove:
rowAbove.remove(column)
leftCell = False
return parameter
def gravitation(rows):
columns = {}
smallestColumns = []
smallest = len(rows)
for rowIndex in range(len(rows)):
for columnIndex in range(len(rows[rowIndex])):
if rows[rowIndex][columnIndex] == ".":
if columnIndex in columns:
columns[columnIndex]+=1
else:
if columnIndex not in columns:
columns[columnIndex] = 0
if rowIndex == len(rows)-1:
if columnIndex not in columns:
columns[columnIndex] = 0
value = columns[columnIndex]
if value < smallest:
smallest = value
smallestColumns = [columnIndex]
elif value == smallest:
smallestColumns.append(columnIndex)
return smallestColumns
alphabetString = string.ascii_lowercase
alphabetDict = {}
value = 0
for letter in alphabetString:
alphabetDict[letter] = value
value+=1
def alphanumericLess(s1, s2):
pointer1 = 0
pointer2 = 0
zeros = ""
while pointer1 < len(s1):
if pointer2 >= len(s2):
return False
char1 = s1[pointer1]
char2 = s2[pointer2]
if char1 in alphabetDict:
if char2 not in alphabetDict or alphabetDict[char2] < alphabetDict[char1]:
return False
pointer1+=1
pointer2+=1
else:
if s2[pointer2] in alphabetDict:
return True
else:
array = findNumber(s1, pointer1)
pointer1 = array[0]
number1 = array[1]
s1LeadingZeros = array[2]
array = findNumber(s2, pointer2)
pointer2 = array[0]
if number1 > array[1]:
return False
if zeros == "" and s1LeadingZeros != array[2] and number1 == array[1]:
if s1LeadingZeros > array[2]:
zeros = "s1"
else:
zeros = "s2"
if s1[-1] == s2[-1]:
if zeros == "s1":
return True
return False
return True
def findNumber(s, pointer):
leadingZeros = 0
if s[pointer] == "0":
while s[pointer] == "0" and pointer<len(s)-1 and s[pointer] not in alphabetDict:
leadingZeros+=1
pointer+=1
number = "0"
while pointer<len(s) and s[pointer] not in alphabetDict:
number+=s[pointer]
pointer+=1
return([pointer, int(number), leadingZeros])
def videoPart(part, total):
totalSec = (int(total[0:2])*3600) + (int(total[3:5])*60) + int(total[6:8])
partSec = (int(part[0:2])*3600) + (int(part[3:5])*60) + int(part[6:8])
if totalSec == partSec:
return(1, 1)
return reduce(totalSec, partSec)
def reduce(total, part):
p1 = total
p2 = part
while True:
p1-=p2
if p1 == p2:
break
if p2 > p1:
p1, p2 = p2, p1
return(part/p1, total/p1)
def dayOfWeek(birthdayDate):
days = 0
day = int(birthdayDate[3:5])
year = int(birthdayDate[6:10])
startYear = int(birthdayDate[6:10])
if year%4 == 0 and int(birthdayDate[0:2]) < 3 and year%100 != 0:
if day < 29:
days+=366
year+=1
elif day == 29:
days+=1461
year+=4
return(leapDay(days, year)-startYear)
else:
days+=365
year+=1
return(nonLeapDay(days, year)-startYear)
def nonLeapDay(d, y):
while d%7 != 0:
if y%4 == 0 and y%100 != 0:
d+=366
else:
d+=365
y+=1
return(y)
def leapDay(d, y):
while d%7 != 0:
d+=1461
y+=4
if y%100 == 0:
d+=1460
y+=4
leapDay(d, y)
return(y) |
import boto3
import json
import os
import subprocess
import sys
import tempfile
FUNCTION_NAME = os.environ['FUNCTION_NAME']
ssm_client = boto3.client('ssm')
def get_ssm_param_name(key_group):
return '/{}/{}'.format(FUNCTION_NAME, key_group)
def install_paramiko(python_dir):
cmd = [
'pip', 'install',
'--no-cache-dir',
'--target', python_dir,
'paramiko==2.4.1',
]
subprocess.run(cmd, check=True)
def read_keys(key_group):
param_name = get_ssm_param_name(key_group)
try:
response = ssm_client.get_parameter(
Name=param_name,
WithDecryption=True,
)
except ssm_client.exceptions.ParameterNotFound:
return None
else:
return json.loads(response['Parameter']['Value'])
def write_keys(key_group, keys):
param_name = get_ssm_param_name(key_group)
ssm_client.put_parameter(
Name=param_name,
Description='Managed by terraform-aws-ssh-keys',
Value=json.dumps(keys),
Type='SecureString',
Overwrite=False,
)
def lambda_handler(event, context):
key_group = event['group']
keys = read_keys(key_group)
if not keys:
keys = {}
with tempfile.TemporaryDirectory() as temp_dir:
# Install and import Paramiko.
cmd = [
'pip', 'install',
'--no-cache-dir',
'--target', temp_dir,
'paramiko==2.4.1',
]
subprocess.run(cmd, check=True)
sys.path.insert(0, temp_dir)
import paramiko
# Generate key pairs for multiple algorithms.
algorithms = {
'ecdsa': lambda: paramiko.ECDSAKey.generate(),
'rsa': lambda: paramiko.RSAKey.generate(bits=2048),
}
for algorithm, generate_private_key in sorted(algorithms.items()):
keys[algorithm] = {}
# Generate a private key.
private_key_path = os.path.join(temp_dir, algorithm)
private_key = generate_private_key()
private_key.write_private_key_file(private_key_path, password=None)
with open(private_key_path) as open_file:
keys[algorithm]['private'] = open_file.read()
# Generate a public key.
public_key = private_key.from_private_key_file(private_key_path, password=None)
keys[algorithm]['public'] = '{} {}'.format(
public_key.get_name(),
public_key.get_base64(),
)
write_keys(key_group, keys)
return keys
|
from target.telegram import Telegram
|
'''
9-16. Text Processing. You are tired of seeing lines on your e-mail wrap because people type
lines that are too long for your mail reader application. Create a program to scan a
text file for all lines longer than 80 characters. For each of the offending lines, find the
closest word before 80 characters and break the line there, inserting the remaining
text to the next line (and pushing the previous next line down one). When you are
done, there should be no lines longer than 80 characters.
'''
import sys
import os.path
def find_last_word_pos(text, start=None):
if start is None:
start = len(text)-1
has_nonspace = False
i = start
while i > 0:
if text[i].isspace():
if has_nonspace:
break
else:
has_nonspace = True
i -= 1
return i
def split_long_lines(input_seq, max_line_len=80):
lines = []
for index, line in enumerate(input_seq):
if len(line) > max_line_len:
last_word_pos = find_last_word_pos(line)
while last_word_pos > 0 and last_word_pos > max_line_len:
last_word_pos = find_last_word_pos(line, last_word_pos)
if last_word_pos > 0:
lines.append(line[:last_word_pos-1]+'\n')
lines.append(line[last_word_pos:])
else:
lines.append(line)
else:
lines.append(line)
return lines
def main():
if len(sys.argv) != 2:
raise Exception('1 argument with file name expected')
file_name = sys.argv[1]
with open(file_name, 'r') as input_file:
lines = split_long_lines(input_file)
file_name_base, ext = os.path.splitext(file_name)
res_file_name = file_name_base + '-split' + ext
with open(res_file_name, 'w') as output_file:
output_file.writelines(lines)
if __name__ == '__main__':
main() |
from abc import ABC, abstractmethod
class BrokerProvider(ABC):
@abstractmethod
def declare_queues(self, channel_names):
pass
@abstractmethod
def disconnect(self):
pass
@abstractmethod
def get_next_message(self, queue_name, max_retry=5):
pass
@abstractmethod
def send_message(self, message, topic, routing_key=None):
pass
|
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import Dict, List # noqa: F401
from congress_api import util
from congress_api.models.base_model_ import Model
from congress_api.models.bill_text_content import BillTextContent # noqa: E501
class BillTextResponse(Model):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
Do not edit the class manually.
"""
def __init__(
self,
legislation_id=None,
legislation_version_id=None,
content=None,
legislation_version=None,
): # noqa: E501
"""BillTextResponse - a model defined in OpenAPI
:param legislation_id: The legislation_id of this BillTextResponse. # noqa: E501
:type legislation_id: int
:param legislation_version_id: The legislation_version_id of this BillTextResponse. # noqa: E501
:type legislation_version_id: int
:param content: The content of this BillTextResponse. # noqa: E501
:type content: List[BillTextContent]
:param legislation_version: The legislation_version of this BillTextResponse. # noqa: E501
:type legislation_version: str
"""
self.openapi_types = {
"legislation_id": int,
"legislation_version_id": int,
"content": List[BillTextContent],
"legislation_version": str,
}
self.attribute_map = {
"legislation_id": "legislation_id",
"legislation_version_id": "legislation_version_id",
"content": "content",
"legislation_version": "legislation_version",
}
self._legislation_id = legislation_id
self._legislation_version_id = legislation_version_id
self._content = content
self._legislation_version = legislation_version
@classmethod
def from_dict(cls, dikt) -> "BillTextResponse":
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The BillTextResponse of this BillTextResponse. # noqa: E501
:rtype: BillTextResponse
"""
return util.deserialize_model(dikt, cls)
@property
def legislation_id(self):
"""Gets the legislation_id of this BillTextResponse.
:return: The legislation_id of this BillTextResponse.
:rtype: int
"""
return self._legislation_id
@legislation_id.setter
def legislation_id(self, legislation_id):
"""Sets the legislation_id of this BillTextResponse.
:param legislation_id: The legislation_id of this BillTextResponse.
:type legislation_id: int
"""
self._legislation_id = legislation_id
@property
def legislation_version_id(self):
"""Gets the legislation_version_id of this BillTextResponse.
:return: The legislation_version_id of this BillTextResponse.
:rtype: int
"""
return self._legislation_version_id
@legislation_version_id.setter
def legislation_version_id(self, legislation_version_id):
"""Sets the legislation_version_id of this BillTextResponse.
:param legislation_version_id: The legislation_version_id of this BillTextResponse.
:type legislation_version_id: int
"""
self._legislation_version_id = legislation_version_id
@property
def content(self):
"""Gets the content of this BillTextResponse.
:return: The content of this BillTextResponse.
:rtype: List[BillTextContent]
"""
return self._content
@content.setter
def content(self, content):
"""Sets the content of this BillTextResponse.
:param content: The content of this BillTextResponse.
:type content: List[BillTextContent]
"""
self._content = content
@property
def legislation_version(self):
"""Gets the legislation_version of this BillTextResponse.
:return: The legislation_version of this BillTextResponse.
:rtype: str
"""
return self._legislation_version
@legislation_version.setter
def legislation_version(self, legislation_version):
"""Sets the legislation_version of this BillTextResponse.
:param legislation_version: The legislation_version of this BillTextResponse.
:type legislation_version: str
"""
self._legislation_version = legislation_version
|
# coding=utf-8
# Copyright 2022 The Pix2Seq Authors.
#
# 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.
# ==============================================================================
"""Common / shared settings among multiple configs."""
import ml_collections
def D(**kwargs):
return ml_collections.ConfigDict(initial_dictionary=kwargs)
architecture_config_map = {
'vit-b': D(
resnet_variant='c1',
num_encoder_layers=12,
dim_att=768,
dim_mlp=3072,
num_heads=12,
num_decoder_layers=6,
dim_att_dec=512,
dim_mlp_dec=2048,
num_heads_dec=16,
),
'vit-l': D(
resnet_variant='c1',
num_encoder_layers=24,
dim_att=1024,
dim_mlp=4096,
num_heads=16,
num_decoder_layers=8,
dim_att_dec=512,
dim_mlp_dec=2048,
num_heads_dec=16,
),
'resnet': D(
resnet_variant='standard',
resnet_depth=50,
resnet_sk_ratio=0.,
resnet_width_multiplier=1,
num_encoder_layers=6,
dim_att=256,
dim_mlp=1024,
num_heads=8,
num_decoder_layers=6,
dim_att_dec=256,
dim_mlp_dec=1024,
num_heads_dec=8,
),
'resnet-c': D(
resnet_variant='c4',
resnet_depth=50,
resnet_sk_ratio=0.,
resnet_width_multiplier=1,
num_encoder_layers=12,
dim_att=512,
dim_mlp=2048,
num_heads=16,
num_decoder_layers=8,
dim_att_dec=512,
dim_mlp_dec=2048,
num_heads_dec=16,
),
}
|
from discord.ext import commands
from discord import Member, Embed, Colour
from discord.utils import find
from typing import Optional
from difflib import get_close_matches
class Immagini(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print("Immagini caricate!")
@commands.command(name="avatar", aliases=['profilepic', 'pp'], help="Mostra l'immagine di profilo di un utente")
async def avatar(self, ctx, user : Optional[Member], username : Optional[str]):
if user is None:
if username == None or username == "":
user = ctx.author
else:
members = ctx.guild.members
usernames = [member.name for member in members] + [member.nick for member in members if member.nick is not None]
username = next(iter(get_close_matches(next(iter(get_close_matches(username.lower(), [username.lower() for username in usernames], 1, 0.3)), None), usernames, 1, 0.3)), None)
if username is None:
return await ctx.send(":warning: Unable to find that user.", reference=ctx.message, mention_author=False)
else:
user = find(lambda member: member.name == username or member.nick == username, members)
colors = {'online':Colour(0x43B582), 'idle':Colour(0xFAA81A), 'dnd':Colour(0xF04747), 'offline':Colour(0x747F8D)}
embed = Embed(colour=colors.get(user.raw_status))
embed.set_author(name=user.name+'#'+user.discriminator, url="https://discord.com/users/"+str(user.id), icon_url="https://cdn.discordapp.com"+user.avatar_url._url)
embed.set_image(url="https://cdn.discordapp.com"+user.avatar_url._url)
await ctx.send(embed=embed, reference=ctx.message, mention_author=False)
def setup(bot):
bot.add_cog(Immagini(bot)) |
import argparse
import re
class ParseError(Exception):
pass
def parse_register(rs):
if rs[0] != 'r':
raise ParseError(f'{rs} is not Register')
register_num = int(rs[1:])
if register_num < 0 or 32 <= register_num:
raise ParseError(f'{rs} needs to be more than 0 and less than 32')
return format(register_num, '05b')
def parse_immediate(num, length):
num = int(num)
if num < 0:
b = format(num, f'b')[1:]
return '1'*(length-len(b)) + b
return format(num, f'0{length}b')
ALU_REG = '0110011'
ALU_IMM = '0010011'
BRANCH = '1100011'
LOAD = '0000011'
STORE = '0100011'
JAL = '1101111'
JALR = '1100111'
def assemble(op, args):
if op == 'ADD':
return '0000000' + parse_register(args[1]) + parse_register(args[0]) + '000' + parse_register(args[2]) + ALU_REG
if op == 'SUB':
return '0100000' + parse_register(args[1]) + parse_register(args[0]) + '000' + parse_register(args[2]) + ALU_REG
if op == 'SLL':
return '0000000' + parse_register(args[1]) + parse_register(args[0]) + '001' + parse_register(args[2]) + ALU_REG
if op == 'SLT':
return '0000000' + parse_register(args[1]) + parse_register(args[0]) + '010' + parse_register(args[2]) + ALU_REG
if op == 'SLTU':
return '0000000' + parse_register(args[1]) + parse_register(args[0]) + '011' + parse_register(args[2]) + ALU_REG
if op == 'XOR':
return '0000000' + parse_register(args[1]) + parse_register(args[0]) + '100' + parse_register(args[2]) + ALU_REG
if op == 'SRL':
return '0000000' + parse_register(args[1]) + parse_register(args[0]) + '101' + parse_register(args[2]) + ALU_REG
if op == 'SRA':
return '0100000' + parse_register(args[1]) + parse_register(args[0]) + '101' + parse_register(args[2]) + ALU_REG
if op == 'OR':
return '0000000' + parse_register(args[1]) + parse_register(args[0]) + '110' + parse_register(args[2]) + ALU_REG
if op == 'AND':
return '0000000' + parse_register(args[1]) + parse_register(args[0]) + '111' + parse_register(args[2]) + ALU_REG
if op == 'ADDI':
return parse_immediate(args[1], 12) + parse_register(args[0]) + '000' + parse_register(args[2]) + ALU_IMM
if op == 'SLLI':
return '0000000' + parse_immediate(args[1], 5) + parse_register(args[0]) + '001' + parse_register(args[2]) + ALU_IMM
if op == 'SLTI':
return parse_immediate(args[1], 12) + parse_register(args[0]) + '010' + parse_register(args[2]) + ALU_IMM
if op == 'SLTIU':
return parse_immediate(args[1], 12) + parse_register(args[0]) + '011' + parse_register(args[2]) + ALU_IMM
if op == 'XORI':
return parse_immediate(args[1], 12) + parse_register(args[0]) + '100' + parse_register(args[2]) + ALU_IMM
if op == 'SRLI':
return '0000000' + parse_immediate(args[1], 5) + parse_register(args[0]) + '101' + parse_register(args[2]) + ALU_IMM
if op == 'SRAI':
return '0100000' + parse_immediate(args[1], 5) + parse_register(args[0]) + '101' + parse_register(args[2]) + ALU_IMM
if op == 'ORI':
return parse_immediate(args[1], 12) + parse_register(args[0]) + '110' + parse_register(args[2]) + ALU_IMM
if op == 'ANDI':
return parse_immediate(args[1], 12) + parse_register(args[0]) + '111' + parse_register(args[2]) + ALU_IMM
if op == 'BEQ':
immediate = parse_immediate(args[2], 13)
return immediate[0] + immediate[2:8] + parse_register(args[1]) + parse_register(args[0]) + '000' + immediate[8:12] + immediate[1] + BRANCH
if op == 'BNE':
immediate = parse_immediate(args[2], 13)
return immediate[0] + immediate[2:8] + parse_register(args[1]) + parse_register(args[0]) + '001' + immediate[8:12] + immediate[1] + BRANCH
if op == 'BLT':
immediate = parse_immediate(args[2], 13)
return immediate[0] + immediate[2:8] + parse_register(args[1]) + parse_register(args[0]) + '100' + immediate[8:12] + immediate[1] + BRANCH
if op == 'BGE':
immediate = parse_immediate(args[2], 13)
return immediate[0] + immediate[2:8] + parse_register(args[1]) + parse_register(args[0]) + '101' + immediate[8:12] + immediate[1] + BRANCH
if op == 'BLTU':
immediate = parse_immediate(args[2], 13)
return immediate[0] + immediate[2:8] + parse_register(args[1]) + parse_register(args[0]) + '110' + immediate[8:12] + immediate[1] + BRANCH
if op == 'BGEU':
immediate = parse_immediate(args[2], 13)
return immediate[0] + immediate[2:8] + parse_register(args[1]) + parse_register(args[0]) + '111' + immediate[8:12] + immediate[1] + BRANCH
if op == 'JAL':
immediate = parse_immediate(args[1], 21)
return immediate[0] + immediate[10:20] + immediate[9] + immediate[1:9] + parse_register(args[0]) + JAL
if op == 'JALR':
return parse_immediate(args[2], 12) + parse_register(args[1]) + '000' + parse_register(args[0]) + JALR
if op == 'LUI':
return parse_immediate(args[1], 20) + parse_register(args[0]) + '0110111'
if op == 'LW':
return parse_immediate(args[1], 12) + parse_register(args[0]) + '010' + parse_register(args[2]) + LOAD
if op == 'SW':
immediate = parse_immediate(args[2], 12)
return immediate[:7] + parse_register(args[0]) + parse_register(args[1]) + '010' + immediate[7:] + STORE
if op == 'IMM':
num = int(args[1])
is_minus = (num < 0)
upper_num = num & 0xfffff000
lower_num = num & 0x00000fff
if is_minus:
lower_num *= -1
ADDI = assemble('ADDI', [args[0], str(lower_num), args[0]])
if ADDI[0] == '1':
upper_num ^= 0xfffff000
shifted_upper_num = upper_num >> 12
LUI = assemble('LUI', [args[0], str(shifted_upper_num)])
return LUI + '\n' + ADDI
def main(file_name):
with open(file_name, 'r') as f:
lines = f.readlines()
for line in lines:
line = re.sub('\s+', ' ', line.strip()) # 前後の空白と途中の空白を1つにする
line = re.sub('//.*$', '', line) # コメントを削除
if not line:
continue
splitted_line = line.split()
op, *args = splitted_line
# print(op, args)
bin_code = assemble(op, args)
print(bin_code)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('file', help='assembler file')
args = parser.parse_args()
main(args.file)
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.formula.api as smf
import seaborn as sns
def get_quick_sample(num_samples):
df = pd.DataFrame(columns=["Y", "D", "X"])
for i in range(num_samples):
x = np.random.normal()
d = (x + np.random.normal()) > 0
y = d + x + np.random.normal()
df.loc[i] = [y, d, x]
df = df.astype({"D": int})
return df
def plot_freedman_exercise(df):
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.hist(df["F-statistic"])
ax1.set_title("Prob(F-statistic)")
ax2.hist(df["Regressors"])
ax2.set_title("Number of regressors")
def run_freedman_exercise():
columns = ["Y"]
for i in range(50):
columns.append("X{:}".format(i))
df = pd.DataFrame(np.random.normal(size=(100, 51)), columns=columns)
formula = "Y ~ " + " + ".join(columns[1:]) + "- 1"
rslt = smf.ols(formula=formula, data=df).fit()
final_covariates = list()
for label in rslt.params.keys():
if rslt.pvalues[label] > 0.25:
continue
final_covariates.append(label)
formula = "Y ~ " + " + ".join(final_covariates)
rslt = smf.ols(formula=formula, data=df).fit()
return rslt
def get_correlation(x, y, df):
stat = df[x].corr(df[y])
if pd.isnull(stat):
return 0.0
else:
return stat
def get_sample_bias_illustration(sample, num_agents=1000):
columns = ["Y", "D", "Y_1", "Y_0", "V_1", "V_0", "C"]
df = pd.DataFrame(columns=columns, dtype=np.float)
for i in range(num_agents):
group = np.random.choice(range(2))
if sample == 0:
if group == 0:
attr_ = 20, 10, 0, 5, 20, 1, 0
elif group == 1:
attr_ = 20, 0, 0, -5, 0, 0, -5
else:
raise NotImplementedError
elif sample == 1:
if group == 0:
attr_ = 20, 10, 2.5, 0, 20, 1, 2.5
elif group == 1:
attr_ = 15, 10, -2.5, 0, 10, 0, 0
else:
raise NotImplementedError
elif sample == 2:
if group == 0:
attr_ = 25, 5, 5, -2.5, 25, 1, 5
elif group == 1:
attr_ = 15, 10, -5, 2.5, 10, 0, 2.5
else:
raise NotImplementedError
y_1, y_0, v_1, v_0, y, d, c = attr_
df.loc[i] = [y, d, y_1, y_0, v_1, v_0, c]
# We set all but the treatment dummy to float values.
df = df.astype(np.float)
df = df.astype({"D": np.int})
return df
def get_sample_regression_adjustment(sample, num_agents=1000, seed=123):
"""There exist six different groups in the population with equal shares"""
np.random.seed(seed)
columns = ["Y", "D", "X", "Y_1", "Y_0", "V_1", "V_0"]
df = pd.DataFrame(columns=columns)
for i in range(num_agents):
group = np.random.choice(range(6))
if sample == 0:
# This is a direct copy from the top panel in Table 6.4
if group in [0, 1]:
attr_ = (
20,
10,
2.5,
2.5,
20,
1,
1,
)
elif group == 2:
attr_ = 15, 5, -2.5, -2.5, 15, 1, 0
elif group == 3:
attr_ = 20, 10, 2.5, 2.5, 10, 0, 1
elif group == 4:
attr_ = 15, 5, -2.5, -2.5, 5, 0, 0
elif group == 5:
attr_ = 15, 5, -2.5, -2.5, 5, 0, 0
else:
raise NotImplementedError
elif sample == 1:
if group in [0, 1]:
attr_ = 20, 10, 2.83, 2.5, 20, 1, 1
elif group == 2:
attr_ = 15, 5, -2.17, -2.5, 15, 1, 0
elif group == 3:
attr_ = 18, 10, 0.83, 2.5, 10, 0, 1
elif group == 4:
attr_ = 15, 5, -2.17, -2.5, 5, 0, 0
elif group == 5:
attr_ = 15, 5, -2.17, -2.5, 5, 0, 0
else:
raise NotImplementedError
y_1, y_0, v_1, v_0, y, d, x = attr_
df.loc[i] = [y, d, x, y_1, y_0, v_1, v_0]
df = df.astype({"D": np.int})
return df
def get_sample_demonstration_1(num_agents):
data = np.tile(np.nan, (num_agents, 5))
for i in range(num_agents):
u = np.random.uniform()
if 0.00 <= u < 0.36:
s, d = 1, 0
elif 0.36 <= u < 0.48:
s, d = 2, 0
elif 0.48 <= u < 0.60:
s, d = 3, 0
elif 0.60 <= u < 0.68:
s, d = 1, 1
elif 0.68 <= u < 0.80:
s, d = 2, 1
else:
s, d = 3, 1
# get potential outcomes
def get_potential_outcomes(s):
if s == 1:
y_1, y_0 = 4, 2
elif s == 2:
y_1, y_0 = 8, 6
elif s == 3:
y_1, y_0 = 14, 10
else:
raise AssertionError
# We want some randomness
y_1 += np.random.normal()
y_0 += np.random.normal()
return y_1, y_0
y_1, y_0 = get_potential_outcomes(s)
y = d * y_1 + (1 - d) * y_0
data[i, :] = y, d, s, y_1, y_0
df = pd.DataFrame(data, columns=["Y", "D", "S", "Y_1", "Y_0"])
df = df.astype({"D": np.int, "S": np.int})
return df
def plot_conditional_expectation_demonstration_1(df):
fig, ax = plt.subplots(1, 1)
rslt = df[df["D"] == 1].groupby("S")["Y"].mean().to_dict()
x, y = rslt.keys(), rslt.values()
ax.plot(list(x), list(y), label="Treated")
rslt = df[df["D"] == 0].groupby("S")["Y"].mean().to_dict()
x, y = rslt.keys(), rslt.values()
ax.plot(list(x), list(y), label="Control")
# We study the treatment effect heterogeneity.
plt.plot((1, 1), (2, 4), "k-")
ax.text(0.95, 6, r"$\Delta Y_{S = 1}$", fontsize=15)
plt.plot((2, 2), (6, 8), "k-")
ax.text(1.95, 10, r"$\Delta Y_{S = 2}$", fontsize=15)
plt.plot((3, 3), (10, 14), "k-")
ax.text(2.95, 15, r"$\Delta Y_{S = 3}$", fontsize=15)
ax.set_title("Conditional Expectations")
ax.set_xticks([1, 2, 3])
ax.set_ylim([0, 16])
ax.legend()
def get_predictions_demonstration_1(df):
df_extend = df.join(pd.get_dummies(df["S"], prefix="S"))
df_extend["predict_1"] = (
smf.ols(formula="Y ~ D + S", data=df_extend).fit().predict()
)
df_extend["predict_2"] = (
smf.ols(formula="Y ~ D + S_2 + S_3", data=df_extend).fit().predict()
)
df_extend["predict_3"] = (
smf.ols(formula="Y ~ D + S_2 + S_3 + S_2 * D + S_3 * D", data=df_extend)
.fit()
.predict()
)
rslt = dict()
rslt["observed"] = dict()
rslt["predict_1"] = dict()
rslt["predict_2"] = dict()
rslt["predict_3"] = dict()
for key_, d in [("treated", 1), ("control", 0)]:
df_subset = df_extend[df_extend["D"] == d]
# observed outcomes
rslt["observed"][key_] = df_subset.groupby(["S"])["Y"].mean().to_dict()
# predicted, model 1
rslt["predict_1"][key_] = df_subset.groupby(["S"])["predict_1"].mean().to_dict()
rslt["predict_2"][key_] = df_subset.groupby(["S"])["predict_2"].mean().to_dict()
rslt["predict_3"][key_] = df_subset.groupby(["S"])["predict_3"].mean().to_dict()
return rslt
def plot_predictions_demonstration_1(df):
rslt = get_predictions_demonstration_1(df)
y = np.array([1, 2, 3])
fig, (ax1, ax2) = plt.subplots(1, 2)
for label, ax in [("treated", ax1), ("control", ax2)]:
ax.bar(y - 0.3, rslt["observed"][label].values(), width=0.2, label="actual")
ax.bar(y - 0.1, rslt["predict_1"][label].values(), width=0.2, label="first")
ax.bar(y + 0.1, rslt["predict_2"][label].values(), width=0.2, label="second")
ax.bar(y + 0.3, rslt["predict_3"][label].values(), width=0.2, label="third")
ax.set_title(label.title())
ax.set_ylim([0, 22])
ax.legend()
def plot_anscombe_dataset():
df = sns.load_dataset("anscombe")
sns.lmplot(
x="x",
y="y",
col="dataset",
hue="dataset",
data=df,
col_wrap=2,
ci=None,
palette="muted",
height=4,
scatter_kws={"s": 50, "alpha": 1},
)
def get_anscombe_datasets():
df = sns.load_dataset("anscombe")
# This is an exmple of a list comprehension
rslt = list()
for numeral in ["I", "II", "III", "IV"]:
rslt.append(df[df["dataset"] == numeral])
return rslt
|
from typing import TYPE_CHECKING
from ..validation import Validator
if TYPE_CHECKING:
from ..validation import RuleEnclosure, MessageBag
class ValidatesRequest:
"""Request mixin to add inputs validation to requests."""
def validate(self, *rules: "str|dict|RuleEnclosure") -> "MessageBag":
"""Validate request inputs against the given rules."""
validator = Validator()
return validator.validate(self.all(), *rules)
|
s = pd.Series(
data=np.random.randn(100),
index=pd.date_range('2000-01-01', freq='D', periods=100))
result = {
'2000-02-29': s['2000-02-29'],
'first': s[0],
'last': s[-1],
'middle': s[s.size // 2],
}
|
#!/usr/bin/env python
#
# Test cases for tournament.py
from tournament_extra import *
import os
def clearScreen():
os.system('cls' if os.name == 'nt' else 'clear')
def testDeleteTournaments():
deleteMatches()
print "1. Tournaments can be deleted."
def testDeleteMatches():
deleteMatches()
print "2. Matches can be deleted."
def testDeletePlayers():
deletePlayers()
print "3. Players can be deleted."
def testCountTournaments():
deleteTournaments()
c = countTournaments()
if c == '0':
raise TypeError(
"countTournaments() should return numeric zero, not string '0'.")
if c != 0:
raise ValueError("After deleting, countTournaments should return zero.")
print "4. After deleting, countTournaments() returns zero."
def testCountMatches():
deleteMatches()
c = countMatches(1)
if c == '0':
raise TypeError(
"countMatches() should return numeric zero, not string '0'.")
if c != 0:
raise ValueError("After deleting, countMatches should return zero.")
print "5. After deleting, countMatches() returns zero."
def testCountPlayers():
deletePlayers()
c = countPlayers(0)
if c == '0':
raise TypeError(
"countPlayers() should return numeric zero, not string '0'.")
if c != 0:
raise ValueError("After deleting, countPlayers should return zero.")
print "6. After deleting, countPlayers() returns zero."
def testRegisterTournament():
registerTournament("Tennis")
c = countTournaments()
if c != 1:
raise ValueError(
"After one tournament is registered, countTournaments() should be 1.")
print "7. After registering a tournament, countTournaments() returns 1."
def testRegisterPlayer():
registerPlayer("Player", "One", "[email protected]")
c = countPlayers(0)
if c != 1:
raise ValueError(
"After one player registers, countPlayers() should be 1.")
print "8. After registering a player, countPlayers() returns 1."
def testRegisterPlayerToTournament():
registerPlayerToTournament(1, 1)
c = countPlayers(1)
if c != 1:
raise ValueError(
"After one player registers to tournament 1, countPlayers(1) should be 1.")
print "9. After registering a player to tournament 1, countPlayers(1) returns 1."
def testRegisterCountDelete():
deleteTournaments()
deleteMatches()
deletePlayers()
registerPlayer("Player1", "One", "[email protected]")
registerPlayer("Player2", "Two", "[email protected]")
registerPlayer("Player3", "Three", "[email protected]")
registerPlayer("Player4", "Four", "[email protected]")
c = countPlayers(0)
if c != 4:
raise ValueError(
"After registering four players, countPlayers should be 4.")
deletePlayers()
c = countPlayers(0)
if c != 0:
raise ValueError("After deleting, countPlayers should return zero.")
print "10. Players can be registered and deleted."
def testStandingsBeforeMatches():
deleteTournaments()
deleteMatches()
deletePlayers()
registerPlayer("Player1", "One", "[email protected]")
registerPlayer("Player2", "Two", "[email protected]")
registerTournament("Tennis")
registerPlayerToTournament(1, 1)
registerPlayerToTournament(2, 1)
standings = playerStandings(1)
if len(standings) < 2:
raise ValueError("Players should appear in playerStandings even before "
"they have played any matches.")
elif len(standings) > 2:
raise ValueError("Only registered players should appear in standings.")
if len(standings[0]) != 4:
raise ValueError("Each playerStandings row should have four columns.")
[(id1, name1, wins1, matches1), (id2, name2, wins2, matches2)] = standings
if matches1 != 0 or matches2 != 0 or wins1 != 0 or wins2 != 0:
raise ValueError(
"Newly registered players should have no matches or wins.")
if set([name1, name2]) != set(["Player1", "Player2"]):
raise ValueError("Registered players' names should appear in standings, "
"even if they have no matches played.")
print "11. Newly registered players appear in the standings with no matches."
registerTournament("Tennis - Double")
registerPlayer("Player3", "Three", "[email protected]")
registerPlayer("Player4", "Four", "[email protected]")
registerPlayerToTournament(1, 2)
registerPlayerToTournament(2, 2)
registerPlayerToTournament(3, 2)
registerPlayerToTournament(4, 2)
standings = playerStandings(2)
if len(standings) < 4:
raise ValueError("Players should appear in playerStandings even before "
"they have played any matches.")
elif len(standings) > 4:
raise ValueError("Only registered players should appear in standings.")
if len(standings[0]) != 4:
raise ValueError("Each playerStandings row should have four columns.")
[(id1, name1, wins1, matches1), (id2, name2, wins2, matches2), (id3, name3, wins3, matches3),
(id4, name4, wins4, matches4)] = standings
if matches1 != 0 or matches2 != 0 or wins1 != 0 or wins2 != 0 or matches3 != 0 or matches4 != 0 or wins3 != 0 or wins4 != 0:
raise ValueError(
"Newly registered players should have no matches or wins.")
if set([name1, name2, name3, name4]) != set(["Player1", "Player2", "Player3", "Player4"]):
raise ValueError("Registered players' names should appear in standings, "
"even if they have no matches played.")
print "11. Newly registered players appear in the standings with no matches."
def testReportMatches():
deleteTournaments()
deleteMatches()
deletePlayers()
registerPlayer("Player1", "One", "[email protected]")
registerPlayer("Player2", "Two", "[email protected]")
registerPlayer("Player3", "Three", "[email protected]")
registerPlayer("Player4", "Four", "[email protected]")
registerTournament("Tennis")
registerPlayerToTournament(1, 1)
registerPlayerToTournament(2, 1)
registerPlayerToTournament(3, 1)
registerPlayerToTournament(4, 1)
standings = playerStandings(1)
[id1, id2, id3, id4] = [row[0] for row in standings]
reportMatch(1, id1, id2)
reportMatch(1, id3, id4)
if reportMatch(1, id4, 200) != "ERROR: player/s not registered in tournament":
raise ValueError("It is possible to register a match for a player not registered in the specified tournament.")
if reportMatch(1, 1, 2) != "ERROR: You tried to register a rematch":
raise ValueError("It is possible to play a rematch.")
if reportMatch(1, 2, 1) != "ERROR: You tried to register a rematch":
raise ValueError("It is possible to play a rematch.")
if reportMatch(1, 1, 1) != "ERROR: Rematch":
raise ValueError("It is possible to have a match with the same player both winning and losing.")
standings = playerStandings(1)
for (id_player, name, wins, matches) in standings:
if matches != 1:
raise ValueError("Each player should have one match recorded.")
if id_player in (id2, id4) and wins != 1:
raise ValueError("Each match winner should have one win recorded.")
elif id_player in (id1, id3) and wins != 0:
raise ValueError("Each match loser should have zero wins recorded.")
print "12. Match can be registered correctly. After a match, players have updated standings."
def testPairings():
deleteTournaments()
deleteMatches()
deletePlayers()
registerPlayer("Player1", "One", "[email protected]")
registerPlayer("Player2", "Two", "[email protected]")
registerPlayer("Player3", "Three", "[email protected]")
registerPlayer("Player4", "Four", "[email protected]")
registerTournament("Tennis - Double")
registerPlayerToTournament(1, 1)
registerPlayerToTournament(2, 1)
registerPlayerToTournament(3, 1)
registerPlayerToTournament(4, 1)
standings = playerStandings(1)
[id1, id2, id3, id4] = [row[0] for row in standings]
reportMatch(1, id1, id2)
reportMatch(1, id3, id4)
pairings = swissPairings(1)
if len(pairings) != 2:
raise ValueError(
"For four players, swissPairings should return two pairs.")
[(pid1, pname1, pid2, pname2), (pid3, pname3, pid4, pname4)] = pairings
correct_pairs = set([frozenset([id1, id3]), frozenset([id2, id4])])
actual_pairs = set([frozenset([pid1, pid2]), frozenset([pid3, pid4])])
if correct_pairs != actual_pairs:
raise ValueError(
"After one match, players with one win should be paired.")
print "13. After one match, players with one win are paired."
def myTest():
deleteTournaments()
deleteMatches()
deletePlayers()
registerTournament("Hide and seek")
registerTournament("Wrestling")
registerPlayer("Player1", "One", "[email protected]")
registerPlayer("Player2", "Two", "[email protected]")
registerPlayer("Player3", "Three", "[email protected]")
registerPlayer("Player4", "Four", "[email protected]")
registerPlayer("Player5", "Five", "[email protected]")
registerPlayer("Player6", "Six", "[email protected]")
registerPlayerToTournament(1, 1)
registerPlayerToTournament(2, 1)
registerPlayerToTournament(3, 1)
registerPlayerToTournament(4, 1)
registerPlayerToTournament(5, 1)
registerPlayerToTournament(6, 1)
registerPlayerToTournament(5, 2)
registerPlayerToTournament(6, 2)
reportMatch(1, 1, 2)
standings = playerStandings(1)
if __name__ == '__main__':
clearScreen()
testDeleteTournaments()
testDeleteMatches()
testDeletePlayers()
testCountTournaments()
testCountMatches()
testCountPlayers()
testRegisterTournament()
testRegisterPlayer()
testRegisterPlayerToTournament()
testRegisterCountDelete()
testStandingsBeforeMatches()
testReportMatches()
testPairings()
myTest()
print "\nHooray! All tests pass!\n"
|
import warnings
import os
import unittest
from test import test_support
# The warnings module isn't easily tested, because it relies on module
# globals to store configuration information. setUp() and tearDown()
# preserve the current settings to avoid bashing them while running tests.
# To capture the warning messages, a replacement for showwarning() is
# used to save warning information in a global variable.
class WarningMessage:
"Holds results of latest showwarning() call"
pass
def showwarning(message, category, filename, lineno, file=None):
msg.message = str(message)
msg.category = category.__name__
msg.filename = os.path.basename(filename)
msg.lineno = lineno
class TestModule(unittest.TestCase):
def setUp(self):
global msg
msg = WarningMessage()
self._filters = warnings.filters[:]
self._showwarning = warnings.showwarning
warnings.showwarning = showwarning
self.ignored = [w[2].__name__ for w in self._filters
if w[0]=='ignore' and w[1] is None and w[3] is None]
def tearDown(self):
warnings.filters = self._filters[:]
warnings.showwarning = self._showwarning
def test_warn_default_category(self):
for i in range(4):
text = 'multi %d' %i # Different text on each call
warnings.warn(text)
self.assertEqual(msg.message, text)
self.assertEqual(msg.category, 'UserWarning')
def test_warn_specific_category(self):
text = 'None'
for category in [DeprecationWarning, FutureWarning,
PendingDeprecationWarning, RuntimeWarning,
SyntaxWarning, UserWarning, Warning]:
if category.__name__ in self.ignored:
text = 'filtered out' + category.__name__
warnings.warn(text, category)
self.assertNotEqual(msg.message, text)
else:
text = 'unfiltered %s' % category.__name__
warnings.warn(text, category)
self.assertEqual(msg.message, text)
self.assertEqual(msg.category, category.__name__)
def test_filtering(self):
warnings.filterwarnings("error", "", Warning, "", 0)
self.assertRaises(UserWarning, warnings.warn, 'convert to error')
warnings.resetwarnings()
text = 'handle normally'
warnings.warn(text)
self.assertEqual(msg.message, text)
self.assertEqual(msg.category, 'UserWarning')
warnings.filterwarnings("ignore", "", Warning, "", 0)
text = 'filtered out'
warnings.warn(text)
self.assertNotEqual(msg.message, text)
warnings.resetwarnings()
warnings.filterwarnings("error", "hex*", Warning, "", 0)
self.assertRaises(UserWarning, warnings.warn, 'hex/oct')
text = 'nonmatching text'
warnings.warn(text)
self.assertEqual(msg.message, text)
self.assertEqual(msg.category, 'UserWarning')
def test_options(self):
# Uses the private _setoption() function to test the parsing
# of command-line warning arguments
self.assertRaises(warnings._OptionError,
warnings._setoption, '1:2:3:4:5:6')
self.assertRaises(warnings._OptionError,
warnings._setoption, 'bogus::Warning')
self.assertRaises(warnings._OptionError,
warnings._setoption, 'ignore:2::4:-5')
warnings._setoption('error::Warning::0')
self.assertRaises(UserWarning, warnings.warn, 'convert to error')
def test_main(verbose=None):
# Obscure hack so that this test passes after reloads or repeated calls
# to test_main (regrtest -R).
if '__warningregistry__' in globals():
del globals()['__warningregistry__']
test_support.run_unittest(TestModule)
if __name__ == "__main__":
test_main(verbose=True)
|
# -*- coding: utf-8 -*-
import pytest
from processing import *
class GildedRose(object):
def __init__(self, items):
self.items = items
def update_quality(self):
for item in self.items:
update_item(item)
def update_item(item):
process_standard(item)
if itemIsConjuredCheck(item):
item.quality = process_conjured(item)
if itemIsBackstagePassCheck(item):
item.quality = process_backstagepasses(item)
if itemIsBrieCheck(item):
item.quality = process_brie(item)
if itemNotSulfurasCheck(item):
item.sell_in = decreaseSellIn(item)
class Item:
def __init__(self, name, sell_in, quality):
self.name = name
self.sell_in = sell_in
self.quality = quality
def __repr__(self):
return "%s, %s, %s" % (self.name, self.sell_in, self.quality)
|
from django import forms
from base_app.models import Referral
from auth_app.models import BusinessOwner, Contest
from django.core.validators import RegexValidator
from django.forms import ValidationError
from tempus_dominus.widgets import DateTimePicker
class BusinessRegistrationForm(forms.ModelForm):
class Meta:
model = Referral
fields = ("refer_name", "phone_number")
def __init__(self, *args, **kwargs):
super(BusinessRegistrationForm, self).__init__(*args, **kwargs)
self.fields["refer_name"].label = ""
self.fields[
"refer_name"
].help_text = "<small>Enter the name of the Referral</small>"
self.fields["refer_name"].widget.attrs = {
"class": "form-control",
"placeholder": "Your name...",
}
self.fields["phone_number"].label = ""
self.fields[
"phone_number"
].help_text = "<small>Enter your WhatsApp Number...</small>"
self.fields["phone_number"].widget.attrs = {
"class": "form-control",
"placeholder": "Your Whatsapp No...",
}
class ReferralRegistration(forms.ModelForm):
class Meta:
model = Referral
fields = ("refer_name", "phone_number")
def __init__(self, *args, **kwargs):
super(ReferralRegistration, self).__init__(*args, **kwargs)
self.fields["refer_name"].label = ""
self.fields["refer_name"].widget.attrs = {
"class": "form-control",
"placeholder": "Your name...",
}
self.fields["phone_number"].label = ""
self.fields["phone_number"].widget.attrs = {
"class": "form-control",
"placeholder": "Your Whatsapp No...",
}
#
def clean_phone_number(self):
phone_number = self.cleaned_data["phone_number"]
print(phone_number)
return phone_number
class NewContestForm(forms.ModelForm):
starting_date = forms.DateTimeField(
input_formats=["%Y-%m-%d %H:%M:%S"],
widget=DateTimePicker(
attrs={
"append": "fa fa-calendar",
"icon_toggle": True,
},
),
)
ending_date = forms.DateTimeField(
input_formats=["%Y-%m-%d %H:%M:%S"],
widget=DateTimePicker(
attrs={
"append": "fa fa-calendar",
"icon_toggle": True,
},
),
)
class Meta:
model = Contest
fields = ("cash_price", "starting_date", "ending_date")
def __init__(self, *args, **kwargs):
# self.request = kwargs.pop('request', None)
super(NewContestForm, self).__init__(*args, **kwargs)
# self.fields["username"] = forms.CharField(label='Phone Number', max_length=100)
self.fields["cash_price"].widget.attrs[
"placeholder"
] = "The total worth of the Cash/Product."
self.fields["cash_price"].widget.attrs["class"] = "form-control"
self.fields["starting_date"].widget.attrs["class"] = "form-control"
# self.fields[
# "starting_date"
# ].help_text = "Select starting date & time for your contest"
self.fields["ending_date"].widget.attrs["class"] = "form-control"
# self.fields[
# "ending_date"
# ].help_text = "Select ending date & time for your contest"
def clean_cash_price(self):
cash_price = self.cleaned_data["cash_price"]
print("Cash :", cash_price)
if len(str(cash_price)) < 6:
return cash_price
else:
raise ValidationError(
"Ensure that there are no more than 5 digits in total."
)
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
try:
from .error_details_py3 import ErrorDetails
from .error_response_py3 import ErrorResponse, ErrorResponseException
from .operation_display_properties_py3 import OperationDisplayProperties
from .operation_py3 import Operation
from .check_name_availability_result_py3 import CheckNameAvailabilityResult
from .tenant_backfill_status_result_py3 import TenantBackfillStatusResult
from .management_group_info_py3 import ManagementGroupInfo
from .parent_group_info_py3 import ParentGroupInfo
from .management_group_details_py3 import ManagementGroupDetails
from .management_group_child_info_py3 import ManagementGroupChildInfo
from .management_group_py3 import ManagementGroup
from .operation_results_py3 import OperationResults
from .entity_parent_group_info_py3 import EntityParentGroupInfo
from .entity_info_py3 import EntityInfo
from .entity_hierarchy_item_py3 import EntityHierarchyItem
from .patch_management_group_request_py3 import PatchManagementGroupRequest
from .create_parent_group_info_py3 import CreateParentGroupInfo
from .create_management_group_details_py3 import CreateManagementGroupDetails
from .create_management_group_child_info_py3 import CreateManagementGroupChildInfo
from .create_management_group_request_py3 import CreateManagementGroupRequest
from .check_name_availability_request_py3 import CheckNameAvailabilityRequest
except (SyntaxError, ImportError):
from .error_details import ErrorDetails
from .error_response import ErrorResponse, ErrorResponseException
from .operation_display_properties import OperationDisplayProperties
from .operation import Operation
from .check_name_availability_result import CheckNameAvailabilityResult
from .tenant_backfill_status_result import TenantBackfillStatusResult
from .management_group_info import ManagementGroupInfo
from .parent_group_info import ParentGroupInfo
from .management_group_details import ManagementGroupDetails
from .management_group_child_info import ManagementGroupChildInfo
from .management_group import ManagementGroup
from .operation_results import OperationResults
from .entity_parent_group_info import EntityParentGroupInfo
from .entity_info import EntityInfo
from .entity_hierarchy_item import EntityHierarchyItem
from .patch_management_group_request import PatchManagementGroupRequest
from .create_parent_group_info import CreateParentGroupInfo
from .create_management_group_details import CreateManagementGroupDetails
from .create_management_group_child_info import CreateManagementGroupChildInfo
from .create_management_group_request import CreateManagementGroupRequest
from .check_name_availability_request import CheckNameAvailabilityRequest
from .management_group_info_paged import ManagementGroupInfoPaged
from .operation_paged import OperationPaged
from .entity_info_paged import EntityInfoPaged
from .management_groups_api_enums import (
Reason,
Status,
Type,
)
__all__ = [
'ErrorDetails',
'ErrorResponse', 'ErrorResponseException',
'OperationDisplayProperties',
'Operation',
'CheckNameAvailabilityResult',
'TenantBackfillStatusResult',
'ManagementGroupInfo',
'ParentGroupInfo',
'ManagementGroupDetails',
'ManagementGroupChildInfo',
'ManagementGroup',
'OperationResults',
'EntityParentGroupInfo',
'EntityInfo',
'EntityHierarchyItem',
'PatchManagementGroupRequest',
'CreateParentGroupInfo',
'CreateManagementGroupDetails',
'CreateManagementGroupChildInfo',
'CreateManagementGroupRequest',
'CheckNameAvailabilityRequest',
'ManagementGroupInfoPaged',
'OperationPaged',
'EntityInfoPaged',
'Reason',
'Status',
'Type',
]
|
from .node_encoder import *
from .edge_encoder import *
from .graph_encoder import * |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def get_reverse_complement(s):
complements = {
'A': 'T',
'T': 'A',
'C': 'G',
'G': 'C'
}
result = ''.join(reversed([complements[x] for x in s]))
return result
if __name__ == "__main__":
import unittest
class ReverseComplementsTestCase(unittest.TestCase):
def test_empty_string(self):
s = ''
model = ''
self.assertEqual(get_reverse_complement(s), model)
def test_one_symbol(self):
s = 'A'
model = 'T'
self.assertEqual(get_reverse_complement(s), model)
def test_all_nucleotides(self):
s = 'GTCA'
model = 'TGAC'
self.assertEqual(get_reverse_complement(s), model)
unittest.main()
|
"""Unit test package for player_tech_assignment."""
|
# coding: utf-8
from enum import Enum
from datetime import datetime
from six import string_types, iteritems
from bitmovin_api_sdk.common.poscheck import poscheck_model
from bitmovin_api_sdk.models.bitmovin_response import BitmovinResponse
import pprint
import six
class PlayerLicense(BitmovinResponse):
@poscheck_model
def __init__(self,
id_=None,
name=None,
created_at=None,
license_key=None,
impressions=None,
max_impressions=None,
third_party_licensing_enabled=None,
domains=None,
analytics_key=None):
# type: (string_types, string_types, datetime, string_types, int, int, bool, list[Domain], string_types) -> None
super(PlayerLicense, self).__init__(id_=id_)
self._name = None
self._created_at = None
self._license_key = None
self._impressions = None
self._max_impressions = None
self._third_party_licensing_enabled = None
self._domains = list()
self._analytics_key = None
self.discriminator = None
if name is not None:
self.name = name
if created_at is not None:
self.created_at = created_at
if license_key is not None:
self.license_key = license_key
if impressions is not None:
self.impressions = impressions
if max_impressions is not None:
self.max_impressions = max_impressions
if third_party_licensing_enabled is not None:
self.third_party_licensing_enabled = third_party_licensing_enabled
if domains is not None:
self.domains = domains
if analytics_key is not None:
self.analytics_key = analytics_key
@property
def openapi_types(self):
types = {}
if hasattr(super(PlayerLicense, self), 'openapi_types'):
types = getattr(super(PlayerLicense, self), 'openapi_types')
types.update({
'name': 'string_types',
'created_at': 'datetime',
'license_key': 'string_types',
'impressions': 'int',
'max_impressions': 'int',
'third_party_licensing_enabled': 'bool',
'domains': 'list[Domain]',
'analytics_key': 'string_types'
})
return types
@property
def attribute_map(self):
attributes = {}
if hasattr(super(PlayerLicense, self), 'attribute_map'):
attributes = getattr(super(PlayerLicense, self), 'attribute_map')
attributes.update({
'name': 'name',
'created_at': 'createdAt',
'license_key': 'licenseKey',
'impressions': 'impressions',
'max_impressions': 'maxImpressions',
'third_party_licensing_enabled': 'thirdPartyLicensingEnabled',
'domains': 'domains',
'analytics_key': 'analyticsKey'
})
return attributes
@property
def name(self):
# type: () -> string_types
"""Gets the name of this PlayerLicense.
Name of the resource (required)
:return: The name of this PlayerLicense.
:rtype: string_types
"""
return self._name
@name.setter
def name(self, name):
# type: (string_types) -> None
"""Sets the name of this PlayerLicense.
Name of the resource (required)
:param name: The name of this PlayerLicense.
:type: string_types
"""
if name is not None:
if not isinstance(name, string_types):
raise TypeError("Invalid type for `name`, type has to be `string_types`")
self._name = name
@property
def created_at(self):
# type: () -> datetime
"""Gets the created_at of this PlayerLicense.
Creation timestamp, returned as UTC expressed in ISO 8601 format: YYYY-MM-DDThh:mm:ssZ (required)
:return: The created_at of this PlayerLicense.
:rtype: datetime
"""
return self._created_at
@created_at.setter
def created_at(self, created_at):
# type: (datetime) -> None
"""Sets the created_at of this PlayerLicense.
Creation timestamp, returned as UTC expressed in ISO 8601 format: YYYY-MM-DDThh:mm:ssZ (required)
:param created_at: The created_at of this PlayerLicense.
:type: datetime
"""
if created_at is not None:
if not isinstance(created_at, datetime):
raise TypeError("Invalid type for `created_at`, type has to be `datetime`")
self._created_at = created_at
@property
def license_key(self):
# type: () -> string_types
"""Gets the license_key of this PlayerLicense.
License Key (required)
:return: The license_key of this PlayerLicense.
:rtype: string_types
"""
return self._license_key
@license_key.setter
def license_key(self, license_key):
# type: (string_types) -> None
"""Sets the license_key of this PlayerLicense.
License Key (required)
:param license_key: The license_key of this PlayerLicense.
:type: string_types
"""
if license_key is not None:
if not isinstance(license_key, string_types):
raise TypeError("Invalid type for `license_key`, type has to be `string_types`")
self._license_key = license_key
@property
def impressions(self):
# type: () -> int
"""Gets the impressions of this PlayerLicense.
Number of impressions recorded (required)
:return: The impressions of this PlayerLicense.
:rtype: int
"""
return self._impressions
@impressions.setter
def impressions(self, impressions):
# type: (int) -> None
"""Sets the impressions of this PlayerLicense.
Number of impressions recorded (required)
:param impressions: The impressions of this PlayerLicense.
:type: int
"""
if impressions is not None:
if not isinstance(impressions, int):
raise TypeError("Invalid type for `impressions`, type has to be `int`")
self._impressions = impressions
@property
def max_impressions(self):
# type: () -> int
"""Gets the max_impressions of this PlayerLicense.
Maximum number of impressions (required)
:return: The max_impressions of this PlayerLicense.
:rtype: int
"""
return self._max_impressions
@max_impressions.setter
def max_impressions(self, max_impressions):
# type: (int) -> None
"""Sets the max_impressions of this PlayerLicense.
Maximum number of impressions (required)
:param max_impressions: The max_impressions of this PlayerLicense.
:type: int
"""
if max_impressions is not None:
if not isinstance(max_impressions, int):
raise TypeError("Invalid type for `max_impressions`, type has to be `int`")
self._max_impressions = max_impressions
@property
def third_party_licensing_enabled(self):
# type: () -> bool
"""Gets the third_party_licensing_enabled of this PlayerLicense.
Flag if third party licensing is enabled (required)
:return: The third_party_licensing_enabled of this PlayerLicense.
:rtype: bool
"""
return self._third_party_licensing_enabled
@third_party_licensing_enabled.setter
def third_party_licensing_enabled(self, third_party_licensing_enabled):
# type: (bool) -> None
"""Sets the third_party_licensing_enabled of this PlayerLicense.
Flag if third party licensing is enabled (required)
:param third_party_licensing_enabled: The third_party_licensing_enabled of this PlayerLicense.
:type: bool
"""
if third_party_licensing_enabled is not None:
if not isinstance(third_party_licensing_enabled, bool):
raise TypeError("Invalid type for `third_party_licensing_enabled`, type has to be `bool`")
self._third_party_licensing_enabled = third_party_licensing_enabled
@property
def domains(self):
# type: () -> list[Domain]
"""Gets the domains of this PlayerLicense.
Whitelisted domains (required)
:return: The domains of this PlayerLicense.
:rtype: list[Domain]
"""
return self._domains
@domains.setter
def domains(self, domains):
# type: (list) -> None
"""Sets the domains of this PlayerLicense.
Whitelisted domains (required)
:param domains: The domains of this PlayerLicense.
:type: list[Domain]
"""
if domains is not None:
if not isinstance(domains, list):
raise TypeError("Invalid type for `domains`, type has to be `list[Domain]`")
self._domains = domains
@property
def analytics_key(self):
# type: () -> string_types
"""Gets the analytics_key of this PlayerLicense.
Analytics License Key
:return: The analytics_key of this PlayerLicense.
:rtype: string_types
"""
return self._analytics_key
@analytics_key.setter
def analytics_key(self, analytics_key):
# type: (string_types) -> None
"""Sets the analytics_key of this PlayerLicense.
Analytics License Key
:param analytics_key: The analytics_key of this PlayerLicense.
:type: string_types
"""
if analytics_key is not None:
if not isinstance(analytics_key, string_types):
raise TypeError("Invalid type for `analytics_key`, type has to be `string_types`")
self._analytics_key = analytics_key
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
if hasattr(super(PlayerLicense, self), "to_dict"):
result = super(PlayerLicense, self).to_dict()
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if value is None:
continue
if isinstance(value, list):
if len(value) == 0:
continue
result[self.attribute_map.get(attr)] = [y.value if isinstance(y, Enum) else y for y in [x.to_dict() if hasattr(x, "to_dict") else x for x in value]]
elif hasattr(value, "to_dict"):
result[self.attribute_map.get(attr)] = value.to_dict()
elif isinstance(value, Enum):
result[self.attribute_map.get(attr)] = value.value
elif isinstance(value, dict):
result[self.attribute_map.get(attr)] = {k: (v.to_dict() if hasattr(v, "to_dict") else v) for (k, v) in value.items()}
else:
result[self.attribute_map.get(attr)] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, PlayerLicense):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
import datetime
import tzlocal
import pytz
import json
import zlib
class TimezoneAwarenessException(Exception):
pass
class ScalingException(Exception):
pass
MINUTES_IN_A_DAY = 1440
MINUTES_IN_A_WEEK = 7 * MINUTES_IN_A_DAY
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
class WeeklyCalendar(object):
def __init__(self, resolution_in_minutes=60, timezone=None, tz_aware=False, bitmap_as_hex=None):
assert MINUTES_IN_A_DAY % resolution_in_minutes == 0
self.tz_aware = tz_aware
if bitmap_as_hex is None:
self.bitmap = [1 for i in xrange(MINUTES_IN_A_WEEK / resolution_in_minutes)]
else:
self.bitmap = map(int, list('{0:b}'.format(int(bitmap_as_hex, 16))))
self.resolution_in_minutes = resolution_in_minutes
if timezone is None:
self._tzinfo = tzlocal.get_localzone()
else:
self._tzinfo = pytz.timezone(timezone)
@property
def tzinfo(self):
if self.tz_aware:
return self._tzinfo
@property
def bitmap_as_hex(self):
return str(hex(int(''.join(map(str, self.bitmap)), 2)))[:-1]
def __eq__(self, other):
return self.dumps() == other.dumps()
def __add__(self, other):
if self.resolution_in_minutes <= other.resolution_in_minutes:
assert other.resolution_in_minutes % self.resolution_in_minutes == 0
assert other.tzinfo == self.tzinfo
scaled_other = other.copy(self.resolution_in_minutes)
bitmap_as_hex = str(hex(int(self.bitmap_as_hex, 16) & int(scaled_other.bitmap_as_hex, 16)))[:-1]
tw = WeeklyCalendar(
resolution_in_minutes=scaled_other.resolution_in_minutes,
timezone=self._tzinfo.zone,
tz_aware=self.tz_aware,
bitmap_as_hex=bitmap_as_hex)
return tw
else:
return other.__add__(self)
def __mul__(self, other):
if self.resolution_in_minutes <= other.resolution_in_minutes:
assert other.resolution_in_minutes % self.resolution_in_minutes == 0
assert other.tzinfo == self.tzinfo
scaled_other = other.copy(self.resolution_in_minutes)
bitmap_as_hex = str(hex(int(self.bitmap_as_hex, 16) | int(scaled_other.bitmap_as_hex, 16)))[:-1]
tw = WeeklyCalendar(
resolution_in_minutes=scaled_other.resolution_in_minutes,
timezone=self._tzinfo.zone,
tz_aware=self.tz_aware,
bitmap_as_hex=bitmap_as_hex)
return tw
else:
return other.__mul__(self)
def copy(self, resolution_in_minutes=None, lossy=False):
if resolution_in_minutes is None:
resolution_in_minutes = self.resolution_in_minutes
assert MINUTES_IN_A_DAY % resolution_in_minutes == 0
if resolution_in_minutes < self.resolution_in_minutes:
assert self.resolution_in_minutes % resolution_in_minutes == 0
change_factor = self.resolution_in_minutes / resolution_in_minutes
bitmap = []
for bit in self.bitmap:
bitmap.extend([bit] * change_factor)
elif resolution_in_minutes > self.resolution_in_minutes:
assert resolution_in_minutes % self.resolution_in_minutes == 0
change_factor = resolution_in_minutes / self.resolution_in_minutes
bitmap = []
for chunk in chunks(self.bitmap, change_factor):
if lossy:
bit = any(chunk)
else:
bit = all(chunk)
if not bit:
if not any(chunk):
bit = False
else:
raise ScalingException('Cannot garantee lossless resoltion change')
bitmap.append(int(bit))
else:
bitmap = self.bitmap
t = WeeklyCalendar(
resolution_in_minutes=resolution_in_minutes,
timezone=self._tzinfo.zone,
tz_aware=self.tz_aware)
t.bitmap = bitmap
return t
def dumps(self):
json_str = json.dumps({
'resolution_in_minutes': self.resolution_in_minutes,
'bitmap_as_hex': self.bitmap_as_hex,
'timezone': self._tzinfo.zone,
'tz_aware': self.tz_aware
})
return zlib.compress(json_str)
@classmethod
def loads(cls, str_repr):
params = json.loads(zlib.decompress(str_repr))
return cls(**params)
def is_idle(self, t):
i = self._get_index_from_datetime(t)
return not self._is_busy(i)
def is_busy(self, t):
i = self._get_index_from_datetime(t)
return self._is_busy(i)
def get_busy_intervals(self, start_time, end_time):
return self._get_time_intervals(start_time, end_time, busy=True)
def get_idle_intervals(self, start_time, end_time):
return self._get_time_intervals(start_time, end_time, busy=False)
def get_closest_busy(self, t):
return self._get_closest(t, busy=True)
def get_closest_idle(self, t):
return self._get_closest(t, busy=False)
def _get_closest(self, t, busy=False):
start_index = self._get_index_from_datetime(t)
for i in range(start_index, start_index + len(self.bitmap)):
if self._is_busy(i) == busy:
return max(t, self._get_datetime_from_index(t, i))
def add_busy_interval(self, start_time, end_time, on_conflict='merge'):
# TODO: make sure the date interval is 1 week maximum
assert on_conflict in ['merge', 'fail']
start_index, end_index = self._index_interval_from_datetime(start_time, end_time)
if on_conflict == 'fail':
# check if its possible
if any(self._is_busy(i) for i in range(start_index, end_index)):
return False
for i in range(start_index, end_index):
if not self._is_busy(i):
self._set(i)
return True
def del_busy_interval(self, start_time, end_time):
start_index, end_index = self._index_interval_from_datetime(start_time, end_time)
for i in range(start_index, end_index + 1):
if self._is_busy(i):
self._unset(i)
return True
def get_time_interval(self, t):
i = self._get_index_from_datetime(t)
return (self._get_datetime_from_index(t, i), self._get_datetime_from_index(t, i + 1))
def _is_busy(self, i):
return self.bitmap[i % len(self.bitmap)] == 0
def _set(self, i):
self.bitmap[i % len(self.bitmap)] = 0
def _unset(self, i):
self.bitmap[i % len(self.bitmap)] = 1
def _index_interval_from_datetime(self, start_time, end_time):
assert end_time > start_time
start_time = self._parse_datetime(start_time)
end_time = self._parse_datetime(end_time)
week_difference = end_time.isocalendar()[1] - start_time.isocalendar()[1]
start_index = self._get_index_from_datetime(start_time)
end_index = self._get_index_from_datetime(end_time) + len(self.bitmap) * week_difference
return (start_index, end_index)
def _get_time_intervals(self, start_time, end_time, busy=True):
start_time = self._parse_datetime(start_time)
end_time = self._parse_datetime(end_time)
start_index, end_index = self._index_interval_from_datetime(start_time, end_time)
intervals = []
current_interval_start_index = None
for i in range(start_index, end_index):
if self._is_busy(i) == busy:
if current_interval_start_index is None:
current_interval_start_index = i
else:
if current_interval_start_index is not None:
interval = [int(current_interval_start_index), i - 1]
intervals.append(interval)
current_interval_start_index = None
if current_interval_start_index is not None:
index = end_index
if busy:
index += 1
interval = [current_interval_start_index, index]
intervals.append(interval)
ref = start_time
time_intervals = []
for interval in intervals:
# busy case
_start_index = interval[0]
_end_index = interval[1] + 1
interval_start_time = self._get_datetime_from_index(ref, _start_index)
interval_end_time = self._get_datetime_from_index(ref, _end_index)
ref = interval_end_time
time_intervals.append([max(start_time, interval_start_time), min(interval_end_time, end_time)])
return time_intervals
def _get_index_from_datetime(self, t):
t = self._parse_datetime(t)
midnight = datetime.datetime(year=t.year, month=t.month, day=t.day, tzinfo=self.tzinfo)
minutes = (t - midnight).seconds / (60 * self.resolution_in_minutes)
index = t.weekday() * (MINUTES_IN_A_DAY / self.resolution_in_minutes) + minutes
return index % len(self.bitmap)
def _get_datetime_from_index(self, t, i):
t = self._parse_datetime(t)
dt = datetime.datetime(year=t.year, month=t.month, day=t.day)
dt -= datetime.timedelta(days=t.weekday())
dt += datetime.timedelta(minutes=i * self.resolution_in_minutes)
return dt.replace(tzinfo=self.tzinfo)
def _parse_datetime(self, t):
# TODO: make a consistent choice to deal with time-ware datetime objects
if t.tzinfo is not None:
if not self.tz_aware:
raise TimezoneAwarenessException('Only datetimes without timezone are allowed')
t = t.astimezone(self.tzinfo).replace(tzinfo=self.tzinfo)
else:
# raise warning that your timestamp is considered local
t = t.replace(tzinfo=self.tzinfo)
return t
|
from __future__ import absolute_import, division, print_function
from iotbx.cns.crystal_symmetry_utils import crystal_symmetry_as_sg_uc
from cctbx.array_family import flex
from six.moves import range
from six.moves import zip
def crystal_symmetry_as_cns_comments(crystal_symmetry, out):
if ( crystal_symmetry.unit_cell() is not None
or crystal_symmetry.space_group_info() is not None):
print("{ %s }" % crystal_symmetry_as_sg_uc(
crystal_symmetry=crystal_symmetry), file=out)
def export_as_cns_hkl(self,
file_object,
file_name,
info,
array_names,
r_free_flags):
out = file_object
if (file_name): print("{ file:", file_name, "}", file=out)
if (self.info() is not None):
print("{", self.info(), "}", file=out)
crystal_symmetry_as_cns_comments(crystal_symmetry=self, out=out)
for line in info: print("{", line, "}", file=out)
print("NREFlections=%d" % self.indices().size(), file=out)
if (self.anomalous_flag()):
print("ANOMalous=TRUE", file=out)
else:
print("ANOMalous=FALSe", file=out)
if (self.sigmas() is not None):
if (array_names is None): array_names = ["FOBS", "SIGMA"]
else: assert len(array_names) == 2
assert isinstance(self.data(), flex.double)
assert isinstance(self.sigmas(), flex.double)
if (self.is_xray_intensity_array()):
f_obs = self.f_sq_as_f()
else:
f_obs = self
nf, ns = array_names
print("DECLare NAME=%s DOMAin=RECIprocal TYPE=REAL END" % nf, file=out)
print("DECLare NAME=%s DOMAin=RECIprocal TYPE=REAL END" % ns, file=out)
if (r_free_flags is None):
for h,f,s in zip(f_obs.indices(),f_obs.data(),f_obs.sigmas()):
print("INDEx %d %d %d" % h, "%s= %.6g %s= %.6g" % (nf,f,ns,s), file=out)
else:
assert r_free_flags.indices().all_eq(f_obs.indices())
print("DECLare NAME=TEST DOMAin=RECIprocal TYPE=INTE END", file=out)
for h,f,s,t in zip(f_obs.indices(),f_obs.data(),f_obs.sigmas(),
r_free_flags.data()):
print("INDEx %d %d %d" % h, "%s= %.6g %s= %.6g" % (nf,f,ns,s),\
"TEST= %d" % int(t), file=out)
elif (self.is_complex_array()):
if (array_names is None): array_names = ["F"]
else: assert len(array_names) == 1
assert r_free_flags is None
n = array_names[0]
print("DECLare NAME=%s DOMAin=RECIprocal TYPE=COMPLEX END" % n, file=out)
for h,a,p in zip(self.indices(),
flex.abs(self.data()),
flex.arg(self.data(), True)):
print("INDEx %d %d %d" % h, "%s= %.6g %.6g" % (n,a,p), file=out)
elif (self.is_hendrickson_lattman_array()):
if (array_names is None): array_names = ["PA", "PB", "PC", "PD"]
else: assert len(array_names) == 4
assert r_free_flags is None
for i in range(4):
print("DECLare NAME=%s DOMAin=RECIprocal TYPE=REAL END" %(
array_names[i]), file=out)
print("GROUp TYPE=HL", file=out)
for i in range(4):
print(" OBJEct=%s" %(array_names[i]), file=out)
print("END", file=out)
for h,hl in zip(self.indices(), self.data()):
print("INDEx %d %d %d" % h, end=' ', file=out)
print("%s= %.6g" % (array_names[0], hl[0]), end=' ', file=out)
print("%s= %.6g" % (array_names[1], hl[1]), end=' ', file=out)
print("%s= %.6g" % (array_names[2], hl[2]), end=' ', file=out)
print("%s= %.6g" % (array_names[3], hl[3]), file=out)
else:
if (array_names is None): array_names = ["DATA"]
else: assert len(array_names) == 1
assert r_free_flags is None
if (isinstance(self.data(), flex.double)):
print("DECLare NAME=%s DOMAin=RECIprocal TYPE=REAL END" % array_names[0], file=out)
fmt = "%.6g"
elif ( isinstance(self.data(), flex.int)
or isinstance(self.data(), flex.bool)):
print("DECLare NAME=%s DOMAin=RECIprocal TYPE=INTEger END" % array_names[0], file=out)
fmt = "%d"
else:
raise RuntimeError("Cannot write array type %s to CNS reflection file" % type(self.data()))
fmt = array_names[0] + "= " + fmt
for h,d in zip(self.indices(),self.data()):
print("INDEx %d %d %d" % h, fmt % d, file=out)
|
import sys
from sklearn.svm import LinearSVC
from sklearn.linear_model import LogisticRegression
from sklearn.feature_selection import SelectFromModel
from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier
import matplotlib.pyplot as plot
from sklearn.svm import SVC
from sklearn.model_selection import StratifiedKFold
from sklearn.feature_selection import RFECV
from sklearn.datasets import make_classification
from nalaf.learning.lib.sklsvm import SklSVM
from nalaf.structures.data import Dataset
from loctext.learning.train import read_corpus
from loctext.util import PRO_ID, LOC_ID, ORG_ID, REL_PRO_LOC_ID, repo_path
from loctext.learning.annotators import LocTextDXModelRelationExtractor
from util import *
from loctext.util import *
from sklearn.model_selection import cross_val_score
import time
from sklearn.pipeline import Pipeline
from sklearn.decomposition import PCA, TruncatedSVD
from sklearn.linear_model import RandomizedLogisticRegression
sentence_distance = int(sys.argv[1])
predict_entities = sys.argv[2]
print(sentence_distance, predict_entities)
# ----------------------------------------------------------------------------------------------------
annotator, X, y, groups = get_model_and_data(sentence_distance, predict_entities)
# X = X.toarray()
print("SVC after preprocessing, #features: {} && max value: {}".format(X.shape[1], max(sklearn.utils.sparsefuncs.min_max_axis(X, axis=0)[1])))
print("Shape X, before: ", X.shape)
feature_selections = [
# ("LinearSVC_C=4.0", SelectFromModel(LinearSVC(C=4.0, penalty="l1", dual=False, random_state=2727, tol=1e-5))),
("LinearSVC_C=2.0", SelectFromModel(LinearSVC(C=2.0, penalty="l1", dual=False, random_state=2727, tol=1e-5))),
("LinearSVC_C=1.0", SelectFromModel(LinearSVC(C=1.0, penalty="l1", dual=False, random_state=2727, tol=1e-5))),
# ("LinearSVC_C=0.5", SelectFromModel(LinearSVC(C=0.5, penalty="l1", dual=False, random_state=2727, tol=1e-5))),
# ("LinearSVC_C=0.25", SelectFromModel(LinearSVC(C=0.25, penalty="l1", dual=False, random_state=2727, tol=1e-5))),
# ("RandomizedLogisticRegression_C=1", SelectFromModel(RandomizedLogisticRegression(C=1))),
# ("RandomizedLogisticRegression_C=0.5", SelectFromModel(RandomizedLogisticRegression(C=0.5))),
# ("PCA_2", PCA(2)),
# ("PCA_10", PCA(2)),
# ("PCA_100", PCA(2)),
# ("PCA_400", PCA(2)),
#
# ("TruncatedSVD_2", TruncatedSVD(2)),
# ("TruncatedSVD_10", TruncatedSVD(2)),
# ("TruncatedSVD_100", TruncatedSVD(2)),
# ("TruncatedSVD_400", TruncatedSVD(2)),
# ("LogisticRegression", SelectFromModel(LogisticRegression(penalty="l1"))),
# ("RandomForestClassifier_20", SelectFromModel(RandomForestClassifier(n_estimators=20, max_depth=3))),
# ("RandomForestClassifier_100", SelectFromModel(RandomForestClassifier(n_estimators=100, max_depth=None))),
]
estimators = [
("SVC_linear", SVC(kernel='linear')),
# ("LinearSVC", LinearSVC(penalty='l1', dual=False)),
# ("SVC_rbf", SVC(kernel='rbf')),
# ("RandomForestClassifier_20", RandomForestClassifier(n_estimators=20, max_depth=3)),
# ("RandomForestClassifier_100", RandomForestClassifier(n_estimators=100, max_depth=5)),
]
for fsel_name, feature_selection in feature_selections:
X_new = feature_selection.fit_transform(X, y)
print()
print()
print()
print(fsel_name, " --- ", X_new.shape)
print()
selected_feature_keys = feature_selection.get_support(indices=True)
fsel_names, _ = print_selected_features(
selected_feature_keys,
annotator.pipeline.feature_set,
file_prefix=("_".join([str(sentence_distance), str(predict_entities), fsel_name]))
)
print(fsel_names)
print()
for est_name, estimator in estimators:
cv_scores = cross_val_score(
estimator,
X_new,
y,
scoring="f1",
cv=my_cv_generator(groups, len(y)),
verbose=True,
n_jobs=-1
)
print()
print(cv_scores.mean(), estimator)
|
'''
`Op` `Archive` `Ls`
`col2str` `fastlog`
>>> Op.enc(
x:all,
indent=_Default,
ensure_ascii=False,
sort_keys=False,
)->bytes
>>> Op.w(
x:all,
pth:str,
indent:Union=_Default,
ensure_ascii=False,
sort_keys=False,
save_old=False,
)->None
>>> Op.dec(
x:bytes,
t=bytes,
indent='\\n',
ensure_ascii=False,
)->all
>>> Op.r(
pth:str,
t=bytes,
indent='\\n',
ensure_ascii=False,
default=_Default,
w=True,
)->all
>>> Op.denc(
x:all,
pth:str,
xisnew=False,
indent='\n',
ensure_ascii=False,
w=True,
)->all
>>> Op.a(
x:all,
pth:str,
xisnew=True,
indent=_Default,
ensure_ascii=False,
sort_keys=False,
save_old=False,
)->None
>>> Archive(base=10,le=3,lstr='.',rstr='.archive',table:str)
>>> Ls(pth='./')
>>> col2str(col='default')->str
>>> fastlog(name='Log',level='warn',out='debug.log',err:str)->logger
'''
from userelaina._op import Op
from userelaina._archive import Archive
from userelaina._ls import exts,col2str,Ls
from userelaina._log import fastlog
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import itertools
import logging
import os
import util
import tempfile
MODULE_NAME = __name__
MODULE_DESCRIPTION = '''Run analysis of code built with a command like:
gradle [options] [task]
Analysis examples:
infer -- gradle build
infer -- ./gradlew build'''
LANG = ['java']
def gen_instance(*args):
return GradleCapture(*args)
# This creates an empty argparser for the module, which provides only
# description/usage information and no arguments.
create_argparser = util.base_argparser(MODULE_DESCRIPTION, MODULE_NAME)
def extract_filepath(parts):
size = len(parts)
pos = size - 1
while pos >= 0:
path = ' '.join(itertools.islice(parts, pos, None))
if os.path.isfile(path):
return parts[:pos], path
pos -= 1
return parts, None
def pop(the_list):
if len(the_list) > 0:
return the_list.pop()
return None
def extract_argfiles_from_rev(javac_arguments):
"""Extract class names and @argfiles from the reversed list."""
# Reverse the list, so it's in a natural order now
javac_arguments = list(reversed(javac_arguments))
java_opts = []
saved = []
java_arg = pop(javac_arguments)
while java_arg is not None:
if java_arg.startswith('@'):
# Probably got an @argfile
path = ' '.join([java_arg[1:]] + saved)
if os.path.isfile(path):
java_opts.insert(0, '@' + path)
saved = []
else:
# @ at the middle of the path
saved.insert(0, java_arg)
else:
# Either a class name or a part of the @argfile path
saved.insert(0, java_arg)
java_arg = pop(javac_arguments)
# Only class names left
java_opts[0:0] = saved
return java_opts
# Please run the doctests using:
# $ python -m doctest -v gradle.py
def extract_all(javac_arguments):
"""Extract Java filenames and Javac options from the Javac arguments.
>>> os.path.isfile = lambda s: s[1:].startswith('path/to/')
>>> extract_all([])
{'files': [], 'opts': []}
>>> extract_all(['-opt1', 'optval1', '/path/to/1.java'])
{'files': ['/path/to/1.java'], 'opts': ['-opt1', 'optval1']}
>>> extract_all(['-opt1', 'optval1', '/path/to/a', 'b/1.java'])
{'files': ['/path/to/a b/1.java'], 'opts': ['-opt1', 'optval1']}
>>> extract_all(['-opt1', 'opt', 'val1', '/path/to/1.java'])
{'files': ['/path/to/1.java'], 'opts': ['-opt1', 'opt val1']}
>>> extract_all(['-opt1', '/path/to/a', 'b/c', 'd/1.java', '-opt2'])
{'files': ['/path/to/a b/c d/1.java'], 'opts': ['-opt1', '-opt2']}
>>> extract_all(['-opt1', 'optval1', '-path/to/1.java'])
{'files': ['-path/to/1.java'], 'opts': ['-opt1', 'optval1']}
>>> extract_all(['-opt1', 'optval1', '/path/to/', '-1.java'])
{'files': ['/path/to/ -1.java'], 'opts': ['-opt1', 'optval1']}
>>> extract_all(['undef1', 'undef2'])
{'files': [], 'opts': ['undef1', 'undef2']}
>>> extract_all(['-o', '/path/to/1.java', 'cls.class', '@/path/to/1'])
{'files': ['/path/to/1.java'], 'opts': ['-o', 'cls.class', '@/path/to/1']}
>>> extract_all(['-opt1', 'optval1', '/path/to/1.java', 'cls.class'])
{'files': ['/path/to/1.java'], 'opts': ['-opt1', 'optval1', 'cls.class']}
>>> extract_all(['cls.class', '@/path/to/a', 'b.txt'])
{'files': [], 'opts': ['cls.class', '@/path/to/a b.txt']}
>>> extract_all(['cls.class', '@/path/to/a', '@b.txt'])
{'files': [], 'opts': ['cls.class', '@/path/to/a @b.txt']}
>>> v = extract_all(['-opt1', 'optval1'] * 1000 + ['/path/to/1.java'])
>>> len(v['opts'])
2000
"""
java_files = []
java_opts = []
# Reversed Javac options parameters
rev_opt_params = []
java_arg = pop(javac_arguments)
while java_arg is not None:
if java_arg.endswith('.java'):
# Probably got a file
remainder, path = extract_filepath(javac_arguments + [java_arg])
if path is not None:
java_files.append(path)
javac_arguments = remainder
# The file name can't be in the middle of the option
java_opts.extend(extract_argfiles_from_rev(rev_opt_params))
rev_opt_params = []
else:
# A use-case here: *.java dir as an option parameter
rev_opt_params.append(java_arg)
elif java_arg.startswith('-'):
# Got a Javac option
option = [java_arg]
if len(rev_opt_params) > 0:
option.append(' '.join(reversed(rev_opt_params)))
rev_opt_params = []
java_opts[0:0] = option
else:
# Got Javac option parameter
rev_opt_params.append(java_arg)
java_arg = pop(javac_arguments)
# We may have class names and @argfiles besides java files and options
java_opts.extend(extract_argfiles_from_rev(rev_opt_params))
return {'files': java_files, 'opts': java_opts}
def normalize(path):
from inferlib import utils
# From Javac docs: If a filename contains embedded spaces,
# put the whole filename in double quotes
quoted_path = path
if ' ' in path:
quoted_path = '"' + path + '"'
return utils.encode(quoted_path)
class GradleCapture:
def __init__(self, args, cmd):
from inferlib import config, utils
self.args = args
# TODO: make the extraction of targets smarter
self.build_cmd = [cmd[0], '--debug'] + cmd[1:]
# That contains javac version as well
version_str = util.run_cmd_ignore_fail([cmd[0], '--version'])
path = os.path.join(self.args.infer_out,
config.JAVAC_FILELISTS_FILENAME)
if not os.path.exists(path):
os.mkdir(path)
logging.info('Running with:\n' + utils.decode(version_str))
def get_infer_commands(self, verbose_output):
from inferlib import config, jwlib
argument_start_pattern = ' Compiler arguments: '
calls = []
seen_build_cmds = set([])
for line in verbose_output.split('\n'):
if argument_start_pattern in line:
content = line.partition(argument_start_pattern)[2].strip()
# if we're building both the debug and release configuration
# and the build commands are identical up to "release/debug",
# only do capture for one set of commands
build_agnostic_cmd = content.replace('release', 'debug')
if build_agnostic_cmd in seen_build_cmds:
continue
seen_build_cmds.add(build_agnostic_cmd)
arguments = content.split(' ')
# Note: do *not* try to filter out empty strings from the arguments (as was done
# here previously)! It will make compilation commands like
# `javac -classpath '' -Xmaxerrs 1000` fail with "Unrecognized option 1000"
extracted = extract_all(arguments)
java_files = extracted['files']
java_args = extracted['opts']
with tempfile.NamedTemporaryFile(
mode='w',
suffix='.txt',
prefix='gradle_',
dir=os.path.join(self.args.infer_out,
config.JAVAC_FILELISTS_FILENAME),
delete=False) as sources:
sources.write('\n'.join(map(normalize, java_files)))
sources.flush()
java_args.append('@' + sources.name)
capture = jwlib.create_infer_command(java_args)
calls.append(capture)
return calls
def capture(self):
print('Running and capturing gradle compilation...')
(build_code, (verbose_out, _)) = util.get_build_output(self.build_cmd)
cmds = self.get_infer_commands(verbose_out)
capture_code = util.run_compilation_commands(cmds)
if build_code != os.EX_OK:
return build_code
return capture_code
|
import os
import sys
from string import Template
import flickrapi
import yaml
import micawber
import urllib2
import socket
providers = micawber.bootstrap_basic()
api = yaml.load(open('api.yaml'))
flickr = flickrapi.FlickrAPI(api['key'], api['secret'])
(token, frob) = flickr.get_token_part_one(perms='write')
if not token:
raw_input("Press ENTER after you authorize this program")
flickr.get_token_part_two((token, frob))
def load_template(tpl):
tpl_file = open(tpl)
return Template(tpl_file.read())
def safe_list_get (l, idx, default):
try:
return l[idx]
except IndexError:
return default
def gallery():
set_list = flickr.photosets_getList()
set_thumbnails = '<ul class="thumbnails">'
for i, item in enumerate(set_list[0]):
set_title = item[0].text
prev_set = safe_list_get(set_list[0], (i-1), None)
if prev_set is not None:
prev_set_title = prev_set[0].text
else:
prev_set_title = None
next_set = safe_list_get(set_list[0], (i+1), None)
if next_set is not None:
next_set_title = next_set[0].text
else:
next_set_title = None
set_dir = "".join(x for x in set_title.replace(' ', '_') if x.isalnum() or x == '_').lower()
if prev_set_title is not None:
prev_set_dir = "".join(x for x in prev_set_title.replace(' ', '_') if x.isalnum() or x == '_').lower()
else:
prev_set_dir = None
if next_set_title is not None:
next_set_dir = "".join(x for x in next_set_title.replace(' ', '_') if x.isalnum() or x == '_').lower()
else:
next_set_dir = None
if not os.path.exists(os.path.join('sights', set_dir)):
os.mkdir(os.path.join('sights', set_dir))
this_set = flickr.walk_set(item.attrib['id'])
#print item.attrib['id']
thumbnails = list()
set_index_tpl = load_template('templates/sights/thumbnail_index.tpl')
set_index = open('sights/index.html', 'w')
set_thumbnail = '<li class="span12"><a href="/sights/%s/index.html">%s</a></li>' % (set_dir, set_title.title())
set_thumbnails += set_thumbnail
set_thumbnails += '</ul>'
set_index_str = set_index_tpl.substitute({'title': 'Sights', 'thumbnail_str': set_thumbnails, 'pager': ''})
set_index.writelines(set_index_str)
set_index.close()
for photo in this_set:
photo_id = photo.get('id')
try:
resp = flickr.photos_getInfo(photo_id=photo_id)
photo_url = resp[0].getchildren()[-1][0].text
except (IndexError, urllib2.URLError) as e:
print e
continue
print photo_id, photo_url, set_title
try:
flickr_thumbnail = micawber.extract('http://www.flickr.com/photos/davidwatson/%s/sizes/q/' %(photo_id), providers)[1]['http://www.flickr.com/photos/davidwatson/%s/sizes/q/' %(photo_id)]['thumbnail_url']
photo_page = micawber.extract('http://www.flickr.com/photos/davidwatson/%s/in/photostream/' % (photo_id), providers)[0][0]
photo_url = micawber.extract('http://www.flickr.com/photos/davidwatson/%s/in/photostream/' % (photo_id), providers)[1]['http://www.flickr.com/photos/davidwatson/%s/in/photostream/' % (photo_id)]['url']
except (socket.timeout, KeyError) as e:
print e
continue
page_img = '<a href="%s" class="thumbnail"><img src="%s"></a>' % (photo_page, photo_url)
thumbnail = '<a href="/sights/%s/%s.html" class="thumbnail"><img src="%s"></a>' % (set_dir, photo_id, flickr_thumbnail)
page_template = load_template('templates/sights/thumbnail_index.tpl')
page_thumbnail = '<ul class="thumbnails"><li class="span12">%s</li></ul>' % (page_img)
page_str = page_template.substitute({'title': set_title.title(), 'thumbnail_str': page_thumbnail, 'pager': ''})
page = open('sights/%s/%s.html' % (set_dir, photo_id), 'w')
page.writelines(page_str)
thumbnails.append(thumbnail)
thumbnail_template = load_template('templates/sights/thumbnail_index.tpl')
thumbnail_index = open('sights/%s/index.html' % (set_dir), 'w')
thumbnail_str = ('<ul class="thumbnails">')
for thumbnail in thumbnails:
thumbnail_str += '<li class="span1">'
thumbnail_str += thumbnail
thumbnail_str += '</li>'
thumbnail_str += '</ul>'
if prev_set_dir is not None:
previous = "/sights/%s/index.html" % (prev_set_dir)
else:
previous = "#"
if next_set_dir is not None:
next = "/sights/%s/index.html" % (next_set_dir)
else:
next = "#"
pager = '<ul class="pager"><li><a href="%s">Previous</a></li><li><a href="%s">Next</a></li></ul>' % (previous, next)
thumbnail_ul = thumbnail_template.substitute({'title': set_title.title(), 'thumbnail_str': thumbnail_str, 'pager': pager})
thumbnail_index.writelines(thumbnail_ul)
thumbnail_index.close()
def main():
path = "posts"
jts = load_template('templates/journal/index.tpl')
pts = load_template('templates/journal/post.tpl')
rts = load_template('templates/journal/row.tpl')
jhf = open('journal/index.html', 'w')
rows = str()
for (path, dirs, files) in os.walk(path):
for i, f in enumerate(files):
pf = open(os.path.join(path, f))
row = {'id': i,
'filename': f,
'date': pf.readline(),
'title': pf.readline(),
'content': pf.read()}
rows += rts.substitute(**row)
phf = open(os.path.join('journal', row['filename']), 'w')
post = pts.substitute(**row)
phf.writelines(post)
jrnl_html = jts.substitute(rows=rows)
jhf.writelines(jrnl_html)
if __name__ == '__main__':
gallery()
#main()
|
"""
Copyright 2019 Goldman Sachs.
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.
"""
import datetime as dt
import logging
from time import sleep
from typing import List, Union, Dict
import pandas as pd
from gs_quant.api.gs.portfolios import GsPortfolioApi
from gs_quant.api.gs.reports import GsReportApi
from gs_quant.api.gs.assets import GsAssetApi
from gs_quant.entities.entitlements import Entitlements
from gs_quant.entities.entity import PositionedEntity, EntityType
from gs_quant.errors import MqError
from gs_quant.errors import MqValueError
from gs_quant.markets.report import PerformanceReport
from gs_quant.markets.report import ReportJobFuture
from gs_quant.markets.portfolio_manager_utils import build_macro_portfolio_exposure_df
from gs_quant.models.risk_model import MacroRiskModel, ReturnFormat
from gs_quant.target.common import Currency
from gs_quant.target.portfolios import RiskAumSource
from gs_quant.target.risk_models import RiskModelDataAssetsRequest as DataAssetsRequest, \
RiskModelUniverseIdentifierRequest as UniverseIdentifierRequest
_logger = logging.getLogger(__name__)
class CustomAUMDataPoint:
"""
Custom AUM Data Point represents a portfolio's AUM value for a specific date
"""
def __init__(self,
date: dt.date,
aum: float):
self.__date = date
self.__aum = aum
@property
def date(self) -> dt.date:
return self.__date
@date.setter
def date(self, value: dt.date):
self.__date = value
@property
def aum(self) -> float:
return self.__aum
@aum.setter
def aum(self, value: float):
self.__aum = value
class PortfolioManager(PositionedEntity):
"""
Portfolio Manager is used to manage Marquee portfolios (setting entitlements, running and retrieving reports, etc)
"""
def __init__(self,
portfolio_id: str):
"""
Initialize a Portfolio Manager
:param portfolio_id: Portfolio ID
"""
self.__portfolio_id = portfolio_id
PositionedEntity.__init__(self, portfolio_id, EntityType.PORTFOLIO)
@property
def portfolio_id(self) -> str:
return self.__portfolio_id
@portfolio_id.setter
def portfolio_id(self, value: str):
self.__portfolio_id = value
def get_performance_report(self) -> PerformanceReport:
reports = GsReportApi.get_reports(limit=100,
position_source_type='Portfolio',
position_source_id=self.id,
report_type='Portfolio Performance Analytics')
if len(reports) == 0:
raise MqError('This portfolio has no performance report.')
return PerformanceReport.from_target(reports[0])
def schedule_reports(self,
start_date: dt.date = None,
end_date: dt.date = None,
backcast: bool = False):
GsPortfolioApi.schedule_reports(self.__portfolio_id, start_date, end_date, backcast=backcast)
def run_reports(self,
start_date: dt.date = None,
end_date: dt.date = None,
backcast: bool = False,
is_async: bool = True) -> List[Union[pd.DataFrame, ReportJobFuture]]:
"""
Run all reports associated with a portfolio
:param start_date: start date of report job
:param end_date: end date of report job
:param backcast: true if reports should be backcasted; defaults to false
:param is_async: true if reports should run asynchronously; defaults to true
:return: if is_async is true, returns a list of ReportJobFuture objects; if is_async is false, returns a list
of dataframe objects containing report results for all portfolio results
"""
self.schedule_reports(start_date, end_date, backcast)
reports = self.get_reports()
report_futures = [report.get_most_recent_job() for report in reports]
if is_async:
return report_futures
counter = 100
while counter > 0:
is_done = [future.done() for future in report_futures]
if False not in is_done:
return [job_future.result() for job_future in report_futures]
sleep(6)
raise MqValueError(f'Your reports for Portfolio {self.__portfolio_id} are taking longer than expected '
f'to finish. Please contact the Marquee Analytics team at '
f'[email protected]')
def set_entitlements(self,
entitlements: Entitlements):
"""
Set the entitlements of a portfolio
:param entitlements: Entitlements object
"""
entitlements_as_target = entitlements.to_target()
portfolio_as_target = GsPortfolioApi.get_portfolio(self.__portfolio_id)
portfolio_as_target.entitlements = entitlements_as_target
GsPortfolioApi.update_portfolio(portfolio_as_target)
def get_schedule_dates(self,
backcast: bool = False) -> List[dt.date]:
"""
Get recommended start and end dates for a portfolio report scheduling job
:param backcast: true if reports should be backcasted
:return: a list of two dates, the first is the suggested start date and the second is the suggested end date
"""
return GsPortfolioApi.get_schedule_dates(self.id, backcast)
def get_aum_source(self) -> RiskAumSource:
"""
Get portfolio AUM Source
:return: AUM Source
"""
portfolio = GsPortfolioApi.get_portfolio(self.portfolio_id)
return portfolio.aum_source if portfolio.aum_source is not None else RiskAumSource.Long
def set_aum_source(self,
aum_source: RiskAumSource):
"""
Set portfolio AUM Source
:param aum_source: aum source for portfolio
:return:
"""
portfolio = GsPortfolioApi.get_portfolio(self.portfolio_id)
portfolio.aum_source = aum_source
GsPortfolioApi.update_portfolio(portfolio)
def get_custom_aum(self,
start_date: dt.date = None,
end_date: dt.date = None) -> List[CustomAUMDataPoint]:
"""
Get AUM data for portfolio
:param start_date: start date
:param end_date: end date
:return: list of AUM data between the specified range
"""
aum_data = GsPortfolioApi.get_custom_aum(self.portfolio_id, start_date, end_date)
return [CustomAUMDataPoint(date=dt.datetime.strptime(data['date'], '%Y-%m-%d'),
aum=data['aum']) for data in aum_data]
def get_aum(self, start_date: dt.date, end_date: dt.date):
"""
Get AUM data for portfolio
:param start_date: start date
:param end_date: end date
:return: dictionary of dates with corresponding AUM values
"""
aum_source = self.get_aum_source()
if aum_source == RiskAumSource.Custom_AUM:
aum = self.get_custom_aum(start_date=start_date, end_date=end_date)
return {aum_point.date.strftime('%Y-%m-%d'): aum_point.aum for aum_point in aum}
if aum_source == RiskAumSource.Long:
aum = self.get_performance_report().get_long_exposure(start_date=start_date, end_date=end_date)
return {row['date']: row['longExposure'] for index, row in aum.iterrows()}
if aum_source == RiskAumSource.Short:
aum = self.get_performance_report().get_short_exposure(start_date=start_date, end_date=end_date)
return {row['date']: row['shortExposure'] for index, row in aum.iterrows()}
if aum_source == RiskAumSource.Gross:
aum = self.get_performance_report().get_gross_exposure(start_date=start_date, end_date=end_date)
return {row['date']: row['grossExposure'] for index, row in aum.iterrows()}
if aum_source == RiskAumSource.Net:
aum = self.get_performance_report().get_net_exposure(start_date=start_date, end_date=end_date)
return {row['date']: row['netExposure'] for index, row in aum.iterrows()}
def upload_custom_aum(self,
aum_data: List[CustomAUMDataPoint],
clear_existing_data: bool = None):
"""
Add AUM data for portfolio
:param aum_data: list of AUM data to upload
:param clear_existing_data: delete all previously uploaded AUM data for the portfolio
(defaults to false)
:return:
"""
formatted_aum_data = [{'date': data.date.strftime('%Y-%m-%d'), 'aum': data.aum} for data in aum_data]
GsPortfolioApi.upload_custom_aum(self.portfolio_id, formatted_aum_data, clear_existing_data)
def get_pnl_contribution(self,
start_date: dt.date = None,
end_date: dt.date = None,
currency: Currency = None) -> pd.DataFrame:
"""
Get PnL Contribution of your portfolio broken down by constituents
:param start_date: optional start date
:param end_date: optional end date
:param currency: optional currency; defaults to your portfolio's currency
:return: a Pandas DataFrame of results
"""
return pd.DataFrame(GsPortfolioApi.get_attribution(self.portfolio_id, start_date, end_date, currency))
def get_macro_exposure_table(self,
macro_risk_model: MacroRiskModel,
date: dt.date,
factors: List[str] = [],
factors_by_name: bool = True,
group_by_factor_category: bool = False,
return_format: ReturnFormat = ReturnFormat.DATA_FRAME) -> Union[Dict, pd.DataFrame]:
"""
Get portfolio and asset exposure to macro factors
:param macro_risk_model: the macro risk model
:param date: date for which to get exposure
:param factors: macro factors to get portfolio and asset exposure for.
If empty, return exposure for all factors in the macro risk model
:param factors_by_name: whether to identify factors by their name or identifier
:param group_by_factor_category: whether to return results with factors grouped within their respective
categories.
:param return_format: whether to return a dict or a pandas dataframe
:return: a Pandas Dataframe or a Dict of portfolio exposure to macro factors
"""
performance_report = self.get_performance_report()
constituents_df = performance_report.get_portfolio_constituents(fields=['netExposure'],
start_date=date,
end_date=date)
if constituents_df.empty:
raise MqValueError(f"Macro Exposure can't be calculated as the portfolio constituents could not be found on"
f" the requested date {date}. Make sure the portfolio performance report is up-to-date.")
constituents_df = constituents_df.dropna()
constituents_df = constituents_df.loc[:, ["assetId", "netExposure"]]
constituents_df = constituents_df.set_index("assetId")
constituents_df.index.name = "Asset Identifier"
assets_data = GsAssetApi.get_many_assets_data_scroll(fields=['name', 'gsid', 'id'],
as_of=dt.datetime(date.year, date.month, date.day),
limit=1000,
id=constituents_df.index.tolist())
df_assets_data = pd.DataFrame.from_records(assets_data).set_index("id"). \
fillna(value={"name": "Name not available"})
df_assets_data.index.name = "Asset Identifier"
# Merge the constituents dataframe and asset data dataframe to get gsid, name, notional
constituents_and_notional_df = df_assets_data.merge(constituents_df, on='Asset Identifier')
constituents_and_notional_df = constituents_and_notional_df.reset_index(drop=True).set_index("gsid")
universe = constituents_and_notional_df.index.dropna().tolist()
constituents_and_notional_df.index.name = 'Asset Identifier'
constituents_and_notional_df = constituents_and_notional_df.sort_index()
# Query universe sensitivity
universe_sensitivities_df = macro_risk_model.get_universe_sensitivity(start_date=date,
end_date=date,
assets=DataAssetsRequest(
UniverseIdentifierRequest.gsid,
universe))
if universe_sensitivities_df.empty:
print(f"None of the assets in the portfolio are exposed to the macro factors in model "
f"{macro_risk_model.id} ")
return pd.DataFrame()
universe_sensitivities_df = universe_sensitivities_df.reset_index(level=1, drop=True)
universe_sensitivities_df.index.name = 'Asset Identifier'
universe_sensitivities_df = universe_sensitivities_df.sort_index()
factors_in_model = macro_risk_model.get_many_factors()
if factors:
factor_dict = {f.id: f.name for f in factors_in_model if f.name in factors} \
if factors_by_name else {f.id: f.name for f in factors_in_model if f.id in factors}
wrong_factors = list(set(factors) - set(factor_dict.values())) if factors_by_name else \
list(set(factors) - set(factor_dict.keys()))
if wrong_factors:
identifier = "name" if factors_by_name else "identifier"
print(f"The following factors with {identifier}(s) {', '.join(wrong_factors)} could not be found")
else:
factor_dict = {f.id: f.name for f in factors_in_model}
factor_category_dict = {}
if group_by_factor_category:
factor_category_dict = {f.name: f.category for f in factors_in_model} if factors_by_name else \
{f.id: f.category for f in factors_in_model}
exposure_df = build_macro_portfolio_exposure_df(
constituents_and_notional_df, universe_sensitivities_df, factor_dict, factor_category_dict, factors_by_name)
if return_format == ReturnFormat.JSON:
return exposure_df.to_dict()
return exposure_df
|
#!/usr/bin/env python
# coding: utf-8
import json
import torch
from torch.utils.data import Dataset
from random import choice
class GeometryDataset(Dataset):
"""Geometry dataset."""
def __init__(self, split, diagram_logic_file, text_logic_file, seq_file, tokenizer):
self.tokenizer = tokenizer
self.split = split
assert self.split in ['train', 'val']
if self.split == 'train':
self.pid_lst = range(0, 2101)
elif self.split == 'val':
self.pid_lst = range(2101, 2401)
with open(diagram_logic_file) as f:
diagram_logic_forms = json.load(f)
with open(text_logic_file) as f:
text_logic_forms = json.load(f)
self.combined_logic_forms = {}
for pid in self.pid_lst:
self.combined_logic_forms[pid] = diagram_logic_forms[str(pid)]['diagram_logic_forms'] + \
text_logic_forms[str(pid)]['text_logic_forms']
with open(seq_file) as f:
self.sequence = json.load(f)
self.keys = sorted([int(i) for i in list(self.sequence.keys())])
print(len(self.keys))
print(max(self.keys))
self.valid_lst = [pid for pid in self.pid_lst if pid in self.keys ]
self.data = { i: self.combined_logic_forms[i] for i in self.pid_lst if i in self.keys }
self.sequences = { i: self.sequence[str(i)] for i in self.pid_lst if i in self.keys }
def __len__(self):
return len(self.valid_lst)
def __getitem__(self, idx):
# print(idx)
pid = self.valid_lst[idx]
## input logic form sequence
input = str(self.combined_logic_forms[pid])
tokenized_inp = self.tokenizer.encode(input)
if len(tokenized_inp) > 500:
tokenized_inp = tokenized_inp[:500]
torch.LongTensor(tokenized_inp)
## target theorem sequence
targets = self.sequences[pid]['seqs']
# target = choice(targets) # random choice one sequence
target = targets[0] # min length
tokenized_tar = self.tokenizer.encode(str(target))
# print(tokenized_inp, tokenized_tar)
return tokenized_inp, tokenized_tar
|
"""
.. _extract_edges_example:
Extract Edges
~~~~~~~~~~~~~
Extract edges from a surface.
"""
# sphinx_gallery_thumbnail_number = 2
import pyvista as pv
from pyvista import examples
###############################################################################
# From vtk documentation, the edges of a mesh are one of the following:
#
# 1. boundary (used by one polygon) or a line cell
# 2. non-manifold (used by three or more polygons)
# 3. feature edges (edges used by two triangles and whose dihedral angle > feature_angle)
# 4. manifold edges (edges used by exactly two polygons).
#
# The :func:`extract_feature_edges() <pyvista.PolyDataFilters.extract_feature_edges>`
# filter will extract those edges given a feature angle and return a dataset
# with lines that represent the edges of the original mesh.
#
# To demonstrate, we will first extract the edges around a sample CAD model:
# Download the example CAD model and extract all feature edges above 45 degrees
mesh = examples.download_cad_model()
edges = mesh.extract_feature_edges(45)
# Render the edge lines on top of the original mesh. Zoom in to provide a better figure.
p = pv.Plotter()
p.add_mesh(mesh, color=True)
p.add_mesh(edges, color="red", line_width=5)
p.camera.zoom(1.5)
p.show()
###############################################################################
# We can do this analysis for any :class:`pyvista.PolyData` object. Let's try
# the cow mesh example:
mesh = examples.download_cow()
edges = mesh.extract_feature_edges(20)
p = pv.Plotter()
p.add_mesh(mesh, color=True)
p.add_mesh(edges, color="red", line_width=5)
p.camera_position = [(9.5, 3.0, 5.5), (2.5, 1, 0), (0, 1, 0)]
p.show()
###############################################################################
# We can leverage the :any:`pyvista.PolyData.n_open_edges` property and
# :func:`pyvista.PolyDataFilters.extract_feature_edges` filter to count and extract the
# open edges on a :class:`pyvista.PolyData` mesh.
# Download a sample surface mesh with visible open edges
mesh = examples.download_bunny()
mesh
###############################################################################
# We can get a count of the open edges with:
mesh.n_open_edges
###############################################################################
# And we can extract those edges with the ``boundary_edges`` option of
# :func:`pyvista.PolyDataFilters.extract_feature_edges`:
edges = mesh.extract_feature_edges(boundary_edges=True, feature_edges=False, manifold_edges=False)
p = pv.Plotter()
p.add_mesh(mesh, color=True)
p.add_mesh(edges, color="red", line_width=5)
p.camera_position = [(-0.2, -0.13, 0.12), (-0.015, 0.10, -0.0), (0.28, 0.26, 0.9)]
p.show()
|
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt;
train_X = np.linspace(-1, 1, 100);
train_Y = 2 * train_X + np.random.randn(*train_X.shape) * 0.3
plt.plot(train_X, train_Y, 'ro', label='Original data')
plt.legend()
plt.show()
X = tf.placeholder("float")
Y = tf.placeholder("float")
W = tf.Variable(tf.random_normal([1]), name='weight')
b = tf.Variable(tf.zeros([1]), name='bias')
z = tf.multiply(X, W) + b
cost = tf.reduce_mean(tf.square(Y - z))
learning_rate = 0.01
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
init = tf.global_variables_initializer()
training_epochs = 20
display_step = 2
with tf.Session() as sess:
sess.run(init)
plotdata={"batchsize":[],"loss":[]}
for epoch in range(training_epochs):
for (x, y) in zip(train_X, train_Y):
sess.run(optimizer, feed_dict={X:x, Y:y})
if epoch % display_step == 0:
loss = sess.run(cost, feed_dict={X:train_X, Y:train_Y})
print ("Epoch:", epoch+1, "cost=", loss, "W=", sess.run(W), "b=", sess.run(b))
if not (loss == 'NA'):
plotdata['batchsize'].append(epoch)
plotdata['loss'].append(loss)
print ("Finished!")
print ("cost=", sess.run(cost, feed_dict={X:train_X, Y:train_Y}),
"W=", sess.run(W), "b=", sess.run(b))
|
import abc
class DataCollector(object, metaclass=abc.ABCMeta):
def end_epoch(self, epoch):
pass
def get_diagnostics(self):
return {}
def get_snapshot(self):
return {}
@abc.abstractmethod
def get_epoch_paths(self):
pass
class PathCollector(DataCollector, metaclass=abc.ABCMeta):
@abc.abstractmethod
def collect_new_paths(
self,
max_path_length,
num_steps,
discard_incomplete_paths,
):
pass
class StepCollector(DataCollector, metaclass=abc.ABCMeta):
@abc.abstractmethod
def collect_new_steps(
self,
max_path_length,
num_steps,
discard_incomplete_paths,
):
pass
|
'''
Created on Sep 20, 2013
@author: nshearer
'''
from datetime import datetime
from ConsoleSimpleQuestion import ConsoleSimpleQuestion
from ConsoleSimpleQuestion import UserAnswerValidationError
class ConsoleDateQuestion(ConsoleSimpleQuestion):
def __init__(self, question):
super(ConsoleDateQuestion, self).__init__(question)
def present_question(self, format_help=None):
fmt_help = datetime.now().strftime(self.question.date_format)
super(ConsoleDateQuestion, self).present_question(format_help=fmt_help)
def encode_answer_to_native(self, user_answer):
'''Get value as a datetime'''
if user_answer is None or len(user_answer) == 0:
return None
try:
return datetime.strptime(user_answer.strip(),
self.question.date_format)
except ValueError:
msg = "Does not match format: %s" % (self.question.date_format)
raise UserAnswerValidationError(msg)
def decode_answer_to_text(self, answer):
'''Given a previous or default answer, convert it to a text value'''
if answer is None or len(str(answer).strip()) == 0:
return None
return answer.strftime(self.question.date_format) |
#!/usr/bin/env python
import sys
import numpy
import math
from Bio.PDB import *
from Bio import pairwise2
# Allowed nucleotides in a loop
NUCLEOTIDE = set([ 'DA', 'DC', 'DG', 'DT', 'DI' ])
def nucleotide_translate(name):
# Subtitute 8-bromoguanosines for normal DG (see 2E4I)
if name == 'BGM':
return 'DG'
# Modified DG compound (see 2M53)
if name == 'LCG':
return 'DG'
return name
def resi_name(resi):
''' Get residue nucleotide name. '''
return nucleotide_translate(resi.get_resname().strip(' ')).strip('D')
def point_rmsd(a, b):
''' Calculate RMSD between two points. '''
sub = a - b
sub = (sub[0], sub[1], sub[2]) # Python3 compatibility
return numpy.sqrt(numpy.dot(sub, sub))
def tetragon_cog(atoms):
''' Calculate center of gravity for given tetragon.
@note This only works for non self-intersecting tetragons. '''
vectors = [atom.get_vector() for atom in atoms]
cog1 = (vectors[0] + vectors[3]) / 2.0
cog2 = (vectors[1] + vectors[2]) / 2.0
return (cog1 + cog2) / 2.0
def analyze_planarity(tetrads):
''' Analyze tetrads planarity. An ideal tetrad consists of an outer and
inner tetragon. Outer tetragon is formed by N9 atoms where the DG
connects to the backbone and the inner angle is formed by O6 atoms
which are formed around the metal ion in the center.
Planarity is represented by a standard deviation between the
centers of gravity of the outer and inner tetragon. '''
deviation = []
for tetrad in tetrads:
outer_cog = tetragon_cog([resi['N9'] for resi in tetrad])
inner_cog = tetragon_cog([resi['O6'] for resi in tetrad])
# @TODO maximum deviaton is probably the best, but need to verify later
dist = point_rmsd(outer_cog, inner_cog)
deviation.append(dist)
return deviation
def analyze_twist(tetrads):
''' Analyze C1' twist angle. '''
twist_angles = []
visited = []
for tetrad in tetrads:
# Select first N guanines' C1' atoms
level1 = [resi['C1\''].get_vector() for resi in tetrad]
level2 = [None, None, None, None]
# Find closest tetrad, this is hard to guess as the C1' distance is fairly varied
# mean value is around 4-6A, too low produces false negative and too high hopscotchs
# a level
min_rmsd = 7.0 # Max 7A
closest = None
visited.append((tetrad, tetrad))
for adjacent in tetrads:
# Omit visisted pairs
if ((tetrad, adjacent) in visited) or ((adjacent, tetrad) in visited):
continue
# Find closest C1' complete mapping
adjacent_level = [None, None, None, None]
adjacent_rmsd = []
for i in range(0, len(level1)):
local_rmsd = 7.0 # Max 7A
for resi in adjacent:
# Ignore already mapped atoms
if resi in adjacent_level:
continue
paired = resi['C1\''].get_vector()
rmsd = point_rmsd(level1[i], paired)
if rmsd < local_rmsd:
local_rmsd = rmsd
adjacent_level[i] = paired
# Identify incomplete mapping
if adjacent_level[i] is None:
# print('pair for',i,'at',local_rmsd)
# print('incomplete mapping of',tetrads.index(adjacent),tetrads.index(tetrad))
break
adjacent_rmsd.append(local_rmsd)
# Pair closest, completely mapped tetrads
if len(adjacent_rmsd) != len(level1):
continue
# We are guaranteed that it does not exceed local RMSD constraint, try to minimize mean value now
adjacent_rmsd_mean = numpy.mean(adjacent_rmsd)
if adjacent_rmsd_mean < min_rmsd:
min_rmsd = adjacent_rmsd_mean
closest = adjacent
level2 = adjacent_level
# Orphan tetrad or an outlier
if closest is None:
continue
# Mark closest tetrad pair as visited
visited.append((tetrad, closest))
# Calculate dihedral twist angle
# Since we don't know which level is higher or lower, absolute value of
# the angle has to stay within the <0, 60>deg
twist = 0.0
for side in [(0,1), (1,2), (2,3), (3,0)]:
(a, b) = side
pair_twist = abs(calc_dihedral(level1[a], level1[b], level2[b], level2[a]))
twist += abs(pair_twist)
twist /= 4.0
twist_angles.append(twist)
# Return mean twist angle
return twist_angles
def closest_guanine(target, guanines, paired_from = 'N7', paired_to = 'N2', rmsd_min = 5.0, same_level = False):
''' Find closest guanine to target form the list. Attempts to find a shortest RMSD between two
connected atoms. H21/N7 is closer, but not always present in the structure, so N2/N7 is selected. '''
adjacent = None
# No remaining guanines
if len(guanines) == 0:
return None
# Find minimal N7 - H21/N2 identifying adjacent DG
for resi in guanines:
# Ignore guanine residues without N7 - H21/N2 bonds
if paired_to not in resi:
continue
rmsd = target[paired_from] - resi[paired_to]
rmsd_o6 = 0.0
# Same level guanines have the close inner O6-N1 core
if same_level:
rmsd_o6 = target['O6'] - resi['N1']
# @todo We shouldn't pair to the closest DG which isn't connected to the GQ core
# @note Disabled by default, as some GQs have really twisted tetrads (f.e. 1OZ8)
if rmsd < rmsd_min and rmsd_o6 < rmsd_min:
rmsd_min = rmsd
adjacent = resi
return adjacent
def sort_tetrads(tetrads):
''' We don't know how the tetrads stack yet, but we know the first tetrad is eith top or bottom.
With that we find the next closest tetrad and align it so the first DG in the tetrad is the next
one attached to the same P backbone. '''
unsorted = tetrads[1:]
stack = [tetrads[0]]
while len(unsorted) > 0:
# Align to first element of the last sorted level
lead = stack[-1][0]
guanines = reduce(lambda t1, t2: t1 + t2, unsorted)
closest = closest_guanine(lead, guanines, "C1'", "C1'", rmsd_min = 15.0, same_level = False)
# Identify originating level and align
for tetrad in unsorted:
if closest in tetrad:
offset = tetrad.index(closest)
# Rotate tetrad so the closest DG is first
unsorted.remove(tetrad)
stack.append(tetrad[offset:] + tetrad[:offset])
break
# Odd, couldn't find a closest guanine pair
if closest is None:
# This can happen for disconnected GQ levels like in 3CDM
# @todo We can't solve two interconnected GQs here, return the partial result
break
return stack
def group_tetrads(guanines):
''' Identify guanine tetrads by N7-H21/N2 shortest RMSD distances. '''
tetrads = []
visited = set([])
while len(guanines) != 0:
tetrad = [guanines.pop(0)]
if tetrad[0] in visited:
break
while len(tetrad) != 4:
adjacent = closest_guanine(tetrad[-1], guanines)
# No N2 in range, discard incomplete tetrad
if adjacent is None:
break
# Append adjacent DG to tetrad list
tetrad.append(adjacent)
guanines.remove(adjacent)
# Check if tetrad forms a closed loop
pin = closest_guanine(tetrad[-1], tetrad[0:3] + guanines)
# Form complete interconnected tetrad
if len(tetrad) == 4 and pin == tetrad[0]:
tetrads.append(tetrad)
else:
# Reinsert other guanines before visited guanines
split = len(guanines) - len(visited)
for resi in tetrad[1:]:
guanines.insert(split, resi)
# Mark guanine as visited and append, so we know
# when to stop trying to match them
guanines.append(tetrad[0])
visited.add(tetrad[0])
# Not enough tetrads identified
if len(tetrads) < 2:
return tetrads
# Sort tetrads into adjacent floors
return sort_tetrads(tetrads)
def tetrad_pos(target, tetrads):
''' Identify DG molecule position in tetrad stack. '''
for i in range(0, len(tetrads)):
for k in range(0, len(tetrads[i])):
if tetrads[i][k] is target:
return (i, k)
return None
def loop_type(entry, closure, tetrads):
''' Analyze loop type. '''
entry_pos = tetrad_pos(entry, tetrads)
closure_pos = tetrad_pos(closure, tetrads)
level_dist = abs(entry_pos[0] - closure_pos[0])
strand_dist = abs(entry_pos[1] - closure_pos[1])
# Loop connects G on the same level.
if level_dist == 0:
# Loop connects edge-wise to the neighbouring strand
if strand_dist % 2 == 1:
return 'L'
else:
# Diagonal loop
return 'D'
else:
# Propeller-type loop
# @todo Identify diagonal/edge-wise ?
return 'P'
# Unidentified loop type
return 'X'
def analyze_loops(tetrads, strands):
''' Analyze backbone direction. '''
core = reduce(lambda t1, t2: t1 + t2, tetrads)
loop_list = []
topology = []
# Strands are symmetric for dimolecular GQs
for strand in [strands[0]]:
loop = []
loop_entry = None
for resi in strand:
if loop_entry is not None:
# Find loop closure
if resi in core:
topology.append(loop_type(loop_entry, resi, tetrads))
loop_list.append(''.join([resi_name(r) for r in loop]))
loop_entry = None
loop = [resi]
# # Final loop
# if len(loop_list) == 3:
# break
else:
loop.append(resi)
else:
# If next residue is not part of the DG core, start loop with the last
# identified core DG on the strand
if resi not in core:
# Cutoff leading nucleotides
if len(loop) == 0:
continue
loop_entry = loop[-1]
# @todo Nucleotide-less loop in advanced structures
# We could detect it by comparing the direction of previous step with current that could hint
# strand reversal.
loop.append(resi)
# No closed loop (therefore not connected)
if len(topology) == 0:
loop_list = [''.join([resi_name(r) for r in loop])]
topology = 'O'
return (''.join(topology), '|'.join(loop_list))
def analyze(model, output = None):
''' Assemble guanine tetrads and analyze properties. '''
guanines = []
strands = []
chain_count = 0
for chain in model:
strand = []
chain_dg = []
for residue in chain:
residue_name = nucleotide_translate(residue.get_resname().strip())
# Allow Inosine to substitute for Guanine,
if residue_name == 'DG' or residue_name == 'DI':
chain_dg.append(residue)
# Build input sequence chain
if residue_name.startswith('D'):
# Filter out only nucleotide chains
if residue_name in NUCLEOTIDE:
strand.append(residue)
# Ignore chains without DG
if len(chain_dg) > 0:
chain_count += 1
guanines += chain_dg
strands.append(strand)
# Must have at least 8 guanines to form a tetrad
if len(guanines) < 8:
sys.stderr.write(' [!!] less than 8 DGs found, ignoring\n')
return None
# Group tetrads from guanine list
print(' * scanning model %s, %d DGs' % (model.__repr__(), len(guanines)))
tetrads = group_tetrads(guanines)
print(' - assembly: %d tetrads' % len(tetrads))
if len(tetrads) < 2:
sys.stderr.write(' [!!] at least 2 tetrads are required\n')
return None
planarity = analyze_planarity(tetrads)
planarity_mean = numpy.mean(planarity)
planarity_std = numpy.std(planarity)
print(' - mean planarity: %.02f A, stddev %.02f A' % (planarity_mean, planarity_std))
twist_angles = analyze_twist(tetrads)
if len(twist_angles) == 0:
sys.stderr.write(' [!!] can\'t calculate twist angles\n')
return None
twist = numpy.mean(twist_angles)
twist_dev = numpy.std(twist_angles)
print(' - twist angle: %.02f rad (%.02f deg), stddev %.02f rad' % (twist, math.degrees(twist), twist_dev))
# Calculate consensus loop
consensus = ''.join([resi_name(resi) for resi in strands[0]])
print(' - chains: %d, consensus: %s' % (chain_count, consensus))
(topology, loops) = analyze_loops(tetrads, strands)
print(' - topology: %s, fragments: %s' % (topology, loops))
return [planarity_mean, planarity_std, math.degrees(twist), math.degrees(twist_dev), chain_count, topology, loops]
|
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
def main():
#print("誕生日のパラドックスの検証")
#print("文字列変換時に制度が失われるのでパーセント表示は厳密な値ではない")
x = []
y = []
a = _factorial(365)
for i in range(365):
j = i + 1
x.append(j)
b = 365 ** j
c = _factorial(365 - j)
d = 1.0 - a / (b * c)
#print(str(j) + "人の時に一人も誕生日が被らない確率: "+str(d * 100)+"%")
y.append(d * 100)
plt.plot(x, y)
plt.title('Birthday Paradox')
plt.xlabel('Number of people')
plt.ylabel('Probability of a pair')
plt.show()
def factorial(x):
for i in range(x.size):
x[i] = _factorial(x[i])
return x
def _factorial(x):
if x == 1:
return 1
elif x != 1 and x >= 1:
return x * _factorial(x - 1)
else:
return 1
if __name__ == '__main__':
main() |
class Solution(object):
def lengthOfLongestSubstringTwoDistinct(self, s):
"""
:type s: str
:rtype: int
"""
start=end=0
cnt=[0]*128
count=res=0
while end<len(s):
if cnt[ord(s[end])]==0:
count+=1
cnt[ord(s[end])]+=1
end+=1
while count>2:
if cnt[ord(s[start])]==1:
count-=1
cnt[ord(s[start])]-=1
start+=1
res=max(res,end-start)
return res |
#Problem Link: https://www.hackerrank.com/challenges/defaultdict-tutorial/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import defaultdict
n,m = map(int,raw_input().split())
A = defaultdict(list)
index =1
for i in range(n):
word = raw_input()
A[word].append(index)
index+=1
B = list()
for i in range(m):
word = raw_input()
B.append(word)
for x in B:
if(len(A[x])!=0):
for i in range(len(A[x])):
print A[x][i],
else:
print '-1',
print
|
# coding: utf-8
""" Convert metadata into the new format """
from io import open
from click import echo, style
from tmt.utils import ConvertError, StructuredFieldError
import fmf.utils
import tmt.utils
import pprint
import yaml
import re
import os
log = fmf.utils.Logging('tmt').logger
# Import nitrate conditionally (reading from nitrate can be skipped)
try:
from nitrate import TestCase
except ImportError:
TestCase = None
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# YAML
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Special hack to store multiline text with the '|' style
# See https://stackoverflow.com/questions/45004464/
# Python 2 version
try:
yaml.SafeDumper.orig_represent_unicode = yaml.SafeDumper.represent_unicode
def repr_unicode(dumper, data):
if '\n' in data:
return dumper.represent_scalar(
u'tag:yaml.org,2002:str', data, style='|')
return dumper.orig_represent_unicode(data)
yaml.add_representer(unicode, repr_unicode, Dumper=yaml.SafeDumper)
# Python 3 version
except AttributeError:
yaml.SafeDumper.orig_represent_str = yaml.SafeDumper.represent_str
def repr_str(dumper, data):
if '\n' in data:
return dumper.represent_scalar(
u'tag:yaml.org,2002:str', data, style='|')
return dumper.orig_represent_str(data)
yaml.add_representer(str, repr_str, Dumper=yaml.SafeDumper)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Convert
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def read(path, makefile, nitrate, purpose):
""" Read old metadata from various sources """
echo(style("Checking the '{0}' directory.".format(path), fg='red'))
data = dict()
# Makefile (extract summary, component and duration)
if makefile:
echo(style('Makefile ', fg='blue'), nl=False)
makefile_path = os.path.join(path, 'Makefile')
try:
with open(makefile_path, encoding='utf-8') as makefile:
content = makefile.read()
except IOError:
raise ConvertError("Unable to open '{0}'.".format(makefile_path))
echo("found in '{0}'.".format(makefile_path))
# Test
test = re.search('export TEST=(.*)\n', content).group(1)
echo(style('test: ', fg='green') + test)
# Summary
data['summary'] = re.search(
r'echo "Description:\s*(.*)"', content).group(1)
echo(style('description: ', fg='green') + data['summary'])
# Component
data['component'] = re.search(
r'echo "RunFor:\s*(.*)"', content).group(1)
echo(style('component: ', fg='green') + data['component'])
# Duration
data['duration'] = re.search(
r'echo "TestTime:\s*(.*)"', content).group(1)
echo(style('duration: ', fg='green') + data['duration'])
# Purpose (extract everything after the header as a description)
if purpose:
echo(style('Purpose ', fg='blue'), nl=False)
purpose_path = os.path.join(path, 'PURPOSE')
try:
with open(purpose_path, encoding='utf-8') as purpose:
content = purpose.read()
except IOError:
raise ConvertError("Unable to open '{0}'.".format(purpose_path))
echo("found in '{0}'.".format(purpose_path))
for header in ['PURPOSE', 'Description', 'Author']:
content = re.sub('^{0}.*\n'.format(header), '', content)
data['description'] = content.lstrip('\n')
echo(style('description:', fg='green'))
echo(data['description'].rstrip('\n'))
# Nitrate (extract contact, environment and relevancy)
if nitrate:
echo(style('Nitrate ', fg='blue'), nl=False)
if test is None:
raise ConvertError('No test name detected for nitrate search')
if TestCase is None:
raise ConvertError('Need nitrate module to import metadata')
testcases = list(TestCase.search(script=test))
if not testcases:
raise ConvertError("No testcase found for '{0}'.".format(test))
elif len(testcases) > 1:
log.warn("Multiple test cases found for '{0}', using {1}".format(
test, testcases[0].identifier))
testcase = testcases[0]
echo("test case found '{0}'.".format(testcase.identifier))
# Contact
if testcase.tester:
data['contact'] = '{} <{}>'.format(
testcase.tester.name, testcase.tester.email)
echo(style('contact: ', fg='green') + data['contact'])
# Environment
if testcase.arguments:
data['environment'] = tmt.utils.variables_to_dictionary(
testcase.arguments)
echo(style('environment:', fg='green'))
echo(pprint.pformat(data['environment']))
# Relevancy
field = tmt.utils.StructuredField(testcase.notes)
data['relevancy'] = field.get('relevancy')
echo(style('relevancy:', fg='green'))
echo(data['relevancy'].rstrip('\n'))
log.debug('Gathered metadata:\n' + pprint.pformat(data))
return data
def write(path, data):
""" Write gathered metadata in the fmf format """
# Make sure there is a metadata tree initialized
try:
tree = fmf.Tree(path)
except fmf.utils.RootError:
raise ConvertError("Initialize metadata tree using 'fmf init'.")
# Store all metadata into a new main.fmf file
fmf_path = os.path.join(path, 'main.fmf')
try:
with open(fmf_path, 'w', encoding='utf-8') as fmf_file:
yaml.safe_dump(
data, fmf_file,
encoding='utf-8', allow_unicode=True,
indent=4, default_flow_style=False)
except IOError:
raise ConvertError("Unable to write '{0}'".format(fmf_path))
echo(style(
"Metadata successfully stored into '{0}'.".format(fmf_path), fg='red'))
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from copyandpay.models import Transaction
import responses, json
from .datas import SUCCESS_PAYMENT, RECURRING_SUCCESS
from .utils import create_scheduled_payment
from ..models import ScheduledPayment
DATA = '''{"id": "8acda4a65dc5f75f015e0b0d35d3758c", "registrationId": "8acda4a25dc5f763015e0b0d34f4142a", "paymentType": "DB", "paymentBrand": "VISA", "amount": "200.00", "currency": "ZAR", "descriptor": "0847.3136.9170 AG01 Nedbank App", "merchantTransactionId": "None/1/30e317e8-a045-43c4-8893-37a73eed404d", "recurringType": "INITIAL", "result": {"code": "000.000.000", "description": "Transaction succeeded"}, "resultDetails": {"ExtendedDescription": "Approved", "ConnectorTxID2": "{CDAD95B8-F93A-4339-B5D5-797C840B5A5F}", "AcquirerResponse": "0", "ConnectorTxID1": "{D943BEFE-7B04-4B65-A476-E1E8408C0F31}", "clearingInstituteName": "NEDBANK"}, "card": {"bin": "479012", "binCountry": "ZA", "last4Digits": "1118", "holder": "R de Beer", "expiryMonth": "01", "expiryYear": "2018"}, "customer": {"givenName": "Taryn", "companyName": "Bananas and Burpees", "mobile": "+27765684520", "email": "[email protected]", "ip": "196.210.62.4"}, "customParameters": {"CTPE_DESCRIPTOR_TEMPLATE": ""}, "cart": {"items": [{"merchantItemId": "1", "name": "AppointmentGuru subscription (discounted)", "quantity": "1", "price": "200", "originalPrice": "200"}]}, "buildNumber": "6b1a3415e53ece34d6bb3f0421c774d82620c4ab@2017-08-10 11:34:40 +0000", "timestamp": "2017-08-22 17:46:10+0000", "ndc": "4F7AA9626EC1F26B5A777C22EF9CCEF5.prod01-vm-tx05"}'''
# class TransactionTestCase(TestCase):
# def setUp(self):
# transaction = Transaction()
# transaction.registration_id = '123'
# transaction.data = DATA
# self.transaction = transaction
class RecurringScheduledPaymentSuccessTestCase(TestCase):
@responses.activate
def setUp(self):
reg_id = '1234'
responses.add(
responses.POST,
'https://test.oppwa.com/v1/registrations/{}/payments'.format(reg_id),
body=json.dumps(RECURRING_SUCCESS)
)
responses.add(
responses.POST,
'https://communicationguru.appointmentguru.co/communications/'
)
responses.add(
responses.POST,
'https://slack.com/api/chat.postMessage',
body=json.dumps({}),
status=201,
content_type='application/json'
)
self.scheduled_payment = create_scheduled_payment(
card_registration_id=reg_id,
run_on_creation=True,
is_recurring=True)
self.reg_id = reg_id
def test_it_hits_peach(self):
'''This is verified in setup'''
pass
def test_it_creates_a_new_recurring_payment(self):
new_scheduled_payment = ScheduledPayment.objects.last()
assert new_scheduled_payment.id != self.scheduled_payment.id,\
'New and old scheduled payment have the same id (no new shceduled payment was created! new:{} | old: {}'.format(new_scheduled_payment.id, self.scheduled_payment.id)
def test_it_sets_status_to_new_for_new_scheduled_payment(self):
new_scheduled_payment = ScheduledPayment.objects.last()
assert new_scheduled_payment.status == 'new',\
'Status should be new. Got: {}'.format(new_scheduled_payment.status)
def test_it_sets_run_on_creation_false_for_new_scheduled_payment(self):
new_scheduled_payment = ScheduledPayment.objects.last()
assert new_scheduled_payment.run_on_creation == False,\
'Status should be False. Got: {}'.format(new_scheduled_payment.run_on_creation)
def test_it_sets_card_on_new_scheduled_payment(self):
new_scheduled_payment = ScheduledPayment.objects.last()
assert new_scheduled_payment.card.id == self.scheduled_payment.card.id
def test_it_sets_product_on_new_scheduled_payment(self):
new_scheduled_payment = ScheduledPayment.objects.last()
assert new_scheduled_payment.product.id == self.scheduled_payment.product.id
def test_it_sets_customer_on_new_scheduled_payment(self):
new_scheduled_payment = ScheduledPayment.objects.last()
assert new_scheduled_payment.customer.id == self.scheduled_payment.customer.id
def test_it_creates_a_transaction(self):
assert Transaction.objects.count() == 1
def test_it_sets_transaction_customer(self):
t = Transaction.objects.first()
assert t.customer.id == self.scheduled_payment.customer.id
def test_it_sets_transaction_card(self):
t = Transaction.objects.first()
assert t.card.id == self.scheduled_payment.card.id
def test_it_sends_receipt(self):
'''Verified in setup'''
pass
def test_it_posts_to_slack(self):
'''Verified in setup'''
pass |
import numpy as np
from pflacs import Premise, Calc
def rectangle_area(w, b=None):
"""Calculate the area of a rectange with side lengths «w» and «b».
https://en.wikipedia.org/wiki/Rectangle
"""
if b is None:
b = w
return w * b
def box_volume(h, w=None, b=None, base_area=None):
"""Calculate the volume of a box (rectangular cuboid) with
side lengths «h», «w» and «b».
https://en.wikipedia.org/wiki/Cuboid
"""
if base_area:
return h * base_area
if b is None:
b = h
if w is None:
w = h
base_area = rectangle_area(w, b)
return h * base_area
def box_surface_area(h=None, w=None, b=None, area_hw=None,
area_wb=None, area_bh=None):
"""Calculate the surface area of a box (rectangular cuboid) with
side lengths «h», «w» and «b».
https://en.wikipedia.org/wiki/Cuboid
https://mathworld.wolfram.com/Cube.html
https://mathworld.wolfram.com/Cuboid.html
"""
# if [h, w, b].count(None) == 2:
# if h is not None: w = b = h
# if w is not None: h = b = w
# if b is not None: h = w = b
# elif h:
# if b is None:
# b = h
# if w is None:
# w = h
# if [area_hw, area_wb, area_bh].count(None) == 1:
# if area_hw is None: w = b = h
if h and w is None and b is None:
w = b = h
area_hw = area_wb = area_bh = rectangle_area(h,w)
else:
if area_hw is None:
area_hw = rectangle_area(h,w)
if area_wb is None:
area_wb = rectangle_area(w,b)
if area_bh is None:
area_bh = rectangle_area(b,h)
area = 2.0*(area_hw + area_wb + area_bh)
return area
basecase = Premise("Study base-case",
parameters={
"w": 4,
"b": 5,
"h": 3.5,
} )
basecase.plugin_func(rectangle_area)
basecase.plugin_func(box_volume)
print(f"Base-case rectange area = {basecase.rectangle_area()}")
print(f"Base-case cube volume = {basecase.box_volume()}")
parastudy = Premise("Parameter study", parent=basecase,
parameters={
"w": np.array([1.0, 1.35, 2.0, 4.5]),
"b": np.linspace(2.2, 5.5, 4),
"h": 10.0,
} )
rect = Calc("Study rectangle area", parent=parastudy,
funcname="rectangle_area" )
Calc("Study cube volume", parent=rect, funcname="box_volume" )
rect()
rect.df
box = rect.get_child_by_name("Study cube volume")
box()
box.df
|
from asyncio.events import AbstractEventLoop
from typing import List, Union
from .base import BaseResource
__all__ = [
'RBEResource',
]
class RBEInstrument(object):
__slots__ = [
'_id',
'_display_name',
'_data',
]
def __init__(self, data: dict) -> None:
self._id = data.get("id")
self._display_name = data.get("displayName")
self._data = data
@property
def id(self) -> int:
return self._id
@property
def display_name(self) -> str:
return self._display_name
@property
def to_dict(self) -> dict:
return self._data
@classmethod
def from_dict(cls, data: dict) -> "RBEInstrument":
return cls(data)
class RBELinkedEvent(object):
__slots__ = [
'_activity_id',
'_data',
]
def __init__(self, data: dict) -> None:
self._activity_id = data.get("activityID")
self._data = data
@property
def activity_id(self) -> str:
return self._activity_id
@property
def id(self) -> str:
return self.activity_id
@property
def to_dict(self) -> dict:
return self._data
@classmethod
def from_dict(cls, data: dict) -> "RBELinkedEvent":
return cls(data)
class RBEResource(BaseResource):
__slots__ = [
'_id',
'_event_time',
'_link',
'_data',
]
_cache = {}
def __init__(self, data: dict,
loop: AbstractEventLoop = None) -> None:
super(RBEResource, self).__init__(data, loop=loop)
self._id = data.get("rbeID")
self._event_time = data.get("eventTime")
self._link = data.get("link")
self._data = data
@property
def id(self) -> str:
return self._id
@property
def rbeID(self) -> str:
return self.id
@property
def event_time(self) -> str: # TODO: Implement datetime.datetime
return self._event_time
def _process_instruments(self) -> Union[List[RBEInstrument], RBEInstrument, None]:
if not (instrs := self._data.get("instruments")):
return None
elif len(instrs) != 1:
return [RBEInstrument(data) for data in instrs]
else:
return RBEInstrument(instrs[0])
@property
def instruments(self) -> Union[List[RBEInstrument], RBEInstrument, None]:
if (instr := f"{self}instr") not in self._cache:
self._cache[instr] = self._process_instruments()
return self._cache[instr]
def _process_linked_events(self) -> Union[List[RBELinkedEvent], RBELinkedEvent, None]:
if not (le := self._data.get("linkedEvents")):
return None
elif len(le) != 1:
return [RBELinkedEvent(data) for data in le]
else:
return RBELinkedEvent(le[0])
@property
def linked_events(self) -> Union[List[RBELinkedEvent], RBELinkedEvent, None]:
if (le := f"{self}le") not in self._cache:
self._cache[le] = self._process_linked_events()
return self._cache[le]
@property
def link(self) -> str:
return self._link
@property
def to_dict(self) -> dict:
return self._data
@classmethod
def from_dict(cls, data: dict,
loop: AbstractEventLoop = None) -> "RBEResource":
return cls(data, loop=loop)
|
import csv
from pathlib import Path
from win32com.client import Dispatch
from .images import Images
from ..config import get_analyze
from ..constants import msoOrientationHorizontal
from ..utils import (layouts, layout_to_dict, pt_to_px, is_text, is_image, is_title, check_collision_between_shapes,
get_shape_dimensions, get_shape_crop_values, get_download_path, dict_to_string)
Application = Dispatch("PowerPoint.Application")
config = get_analyze()
class Analyze:
def __init__(self, presentation_path):
super().__init__()
self._Images = Images(presentation_path)
self._Presentation = Application.Presentations.Open(presentation_path, WithWindow=False)
def which_layout(self):
for layout in layouts:
layout_positions = layout_to_dict(
pt_to_px(self._Presentation.PageSetup.SlideWidth),
pt_to_px(self._Presentation.PageSetup.SlideHeight),
layout
)
elements, collision = set(), set()
for Slide in self._Presentation.Slides:
if Slide.SlideIndex == 2 or Slide.SlideIndex == 3:
for Shape in Slide.Shapes:
elements.add(Shape.Name)
layout_position = layout_positions[Slide.SlideIndex]
shape_dims = get_shape_dimensions(Shape)
cur_layout_position = []
if is_title(Shape) or is_text(Shape):
cur_layout_position = layout_position["title"] + layout_position["text"]
elif is_image(Shape):
cur_layout_position = layout_position["images"]
for pos in cur_layout_position:
if check_collision_between_shapes(shape_dims, pos):
collision.add(Shape.Name)
if len(elements) == len(collision):
return layout
return False
def __analyze_count_of_slides(self):
if self._Presentation.Slides.Count == int(config['slides']):
return True
return False
def __analyze_slides_aspect_ratio(self):
PageSetup = self._Presentation.PageSetup
aspect_ratio = config['aspect_ratio'].split('/')
if (PageSetup.SlideWidth / PageSetup.SlideHeight) / (int(aspect_ratio[0]) / int(aspect_ratio[1])):
return True
return False
def __analyze_typefaces(self):
typefaces = set()
for Slide in self._Presentation.Slides:
for Shape in Slide.Shapes:
if is_text(Shape):
typefaces.add(Shape.TextFrame.TextRange.Font.Name)
if len(typefaces) == 1:
return True
else:
tmp_typefaces = set()
for typeface in list(typefaces):
tmp_typefaces.add(typeface.split()[0])
if len(tmp_typefaces) == 1:
return True
return False
def __collisions_between_slide_elements(self, slide):
overlaps = set()
shapes_1, shapes_2 = ([Shape for Shape in self._Presentation.Slides(slide).Shapes],
[Shape for Shape in self._Presentation.Slides(slide).Shapes])
for k in range(len(shapes_1) - 1):
for j in range(1, len(shapes_2)):
dims_1, dims_2 = get_shape_dimensions(shapes_1[k]), get_shape_dimensions(shapes_2[j])
if shapes_1[k].Name != shapes_2[j].Name:
collision = check_collision_between_shapes(dims_1, dims_2)
overlaps.add(collision)
if len(overlaps) == 1:
return True
return False
def __analyze_slide_text_image_blocks(self, slide):
text, images, title, subtitle = 0, 0, False, False
for Shape in self._Presentation.Slides(slide).Shapes:
if is_title(Shape):
if slide == 1:
if not title and not subtitle:
title = True
elif title and not subtitle:
subtitle = True
else:
if not title:
title = True
elif is_text(Shape):
text += 1
elif is_image(Shape):
images += 1
a_text, a_images, a_title, a_subtitle = False, False, False, False
if slide == 1:
if text == int(config[f'text_blocks_{slide}']) and not title and not subtitle:
a_text, a_title, a_subtitle = True, True, True
elif text == int(config[f'text_blocks_{slide}']) - 1 and title and not subtitle:
a_text, a_title, a_subtitle = True, True, False
elif text == int(config[f'text_blocks_{slide}']) - 2 and title and subtitle:
a_text, a_title, a_subtitle = True, True, True
if images == int(config[f'images_{slide}']):
a_images = True
return a_text, a_images, a_title, a_subtitle
else:
if text == int(config[f'text_blocks_{slide}']) and not title:
a_text, a_title = True, True
elif text == int(config[f'text_blocks_{slide}']) - 1 and title:
a_text = True
elif text == int(config[f'text_blocks_{slide}']) - 1 and not title:
a_text = True
if images == int(config[f'images_{slide}']):
a_images = True
return a_text, a_images, a_title, a_subtitle
def __analyze_slide_font_sizes(self, slide):
font_sizes, correct_counter = [], 0
for Shape in self._Presentation.Slides(slide).Shapes:
if is_text(Shape):
font_sizes.append(Shape.TextFrame.TextRange.Font.Size)
required_font_sizes = config[f'font_sizes_{slide}'].split(",")
for f in range(len(required_font_sizes)):
required_font_sizes[f] = float(required_font_sizes[f])
if len(required_font_sizes) == len(font_sizes) == int(config[f'text_blocks_{slide}']):
if required_font_sizes == font_sizes:
return True
elif len(required_font_sizes) - 1 == len(font_sizes) == int(config[f'text_blocks_{slide}']) - 1:
required_font_sizes.pop(0)
if required_font_sizes == font_sizes:
return True
return False
def presentation(self):
analyze = {}
layout = self.which_layout()
analyze[0] = self.__analyze_count_of_slides()
analyze[1] = self.__analyze_slides_aspect_ratio()
analyze[2] = self._Presentation.PageSetup.SlideOrientation == msoOrientationHorizontal
analyze[3] = self.__analyze_typefaces()
analyze[4] = self._Images.compare()
analyze[5], analyze[6] = True if layout else False, layout if layout else None
analyze[13] = self._Images.distorted_images()
return analyze
def slide_1(self):
analyze = {}
text, images, title, subtitle = self.__analyze_slide_text_image_blocks(1)
analyze[7], analyze[8] = title, subtitle
analyze[9] = self.__collisions_between_slide_elements(1)
analyze[10] = self.__analyze_slide_font_sizes(1)
return analyze
def slide_2(self):
analyze = {}
text, images, title, subtitle = self.__analyze_slide_text_image_blocks(2)
analyze[7] = title
analyze[9] = self.__collisions_between_slide_elements(2)
analyze[10] = self.__analyze_slide_font_sizes(2)
analyze[11], analyze[12] = text, images
return analyze
def slide_3(self):
analyze = {}
text, images, title, subtitle = self.__analyze_slide_text_image_blocks(3)
analyze[7] = title
analyze[9] = self.__collisions_between_slide_elements(3)
analyze[10] = self.__analyze_slide_font_sizes(3)
analyze[11], analyze[12] = text, images
return analyze
@staticmethod
def __translate(analyze, grade):
presentation_analyze = {
"Соотношение сторон 16:9": "Выполнено" if analyze[1] else "Не выполнено",
"Горизонтальная ориентация": "Выполнено" if analyze[2] else "Не выполнено"
}
structure_analyze = {
"Три слайда в презентации": "Выполнено" if analyze[0] else "Не выполнено",
"Соответствует макету": "Выполнено" if analyze[5] else "Не выполнено",
"Заголовки на слайдах": "Выполнено" if analyze[7] else "Не выполнено",
"Подзаголовок на первом слайде": "Выполнено" if analyze[8] else "Не выполнено",
"Элементы не перекрывают друг друга": "Выполнено" if analyze[9] else "Не выполнено",
"Текстовые блоки на 2, 3 слайде": "Выполнено" if analyze[11] else "Не выполнено",
"Картинки на 2, 3 слайде": "Выполнено" if analyze[12] else "Не выполнено"
}
fonts_analyze = {
"Единый тип шрифта": "Выполнено" if analyze[3] else "Не выполнено",
"Размер шрифта": "Выполнено" if analyze[10] else "Не выполнено"
}
images_analyze = {
"Оригинальные картинки": "Выполнено" if analyze[4] else "Не выполнено",
"Картинки не искажены": "Выполнено" if not analyze[13] else "Не выполнено"
}
return presentation_analyze, structure_analyze, fonts_analyze, images_analyze, analyze[6], grade
def __summary(self):
"""
0 - does prs have 3 slides
1 - right aspect ratio of presentation
2 - horizontal orientation
3 - right typefaces
4 - original photos
5 - contatins layout
6 - which layout
7 - title
8 - subtitle
9 - overlaps
10 - font sizes
11 - text blocks
12 - image blocks
13 - distorted images
Presentation:
1, 2
Structure:
0, 5, 7, 8, 9, 11, 12
Fonts:
3, 10
Images:
4 13
"""
# 16 HOURS HERE
presentation_info, first_slide, second_slide = (self.presentation(),
self.slide_1(),
self.slide_2())
if self._Presentation.Slides.Count >= 3:
third_slide = self.slide_3()
data = {**presentation_info, **first_slide, **second_slide, **third_slide}
err_structure = [data[k] for k in data if k in [0, 5, 7, 8, 9, 11, 12]].count(False)
err_fonts = [data[k] for k in data if k in [3, 10]].count(False)
err_images = [data[k] for k in data if k in [4, 13]].count(False)
# compute grade
r_grade = 0
# check if we can give grade 2 (max)
if all(value for value in data.values()):
r_grade = 2
return self.__translate(data, r_grade)
# or if we can give 1
if err_structure == 1 and not err_fonts and not err_images:
r_grade = 1
elif not err_structure and err_fonts == 1 and not err_images:
r_grade = 1
elif not err_structure and not err_fonts and err_images == 1:
r_grade = 1
return self.__translate(data, r_grade)
elif self._Presentation.Slides.Count == 2:
data = {**presentation_info, **first_slide, **second_slide}
err_structure = [data[k] for k in data if k in [0, 5, 7, 8, 9, 11, 12]].count(False)
err_fonts = [data[k] for k in data if k in [3, 10]].count(False)
err_images = [data[k] for k in data if k in [4, 13]].count(False)
# compute grade
r_grade = 0
if err_structure == 1 and not err_fonts and not err_images:
r_grade = 1
return self.__translate(data, r_grade)
def get(self, typeof="analyze"):
if typeof == "analyze":
return self.__summary()
elif typeof == "thumb":
return self._Images.get("thumb")
elif typeof == "slides":
return self._Presentation.Slides.Count
def __del__(self):
Application.Quit()
def __exit__(self):
Application.Quit()
@property
def warnings(self):
warnings = {0: [], 1: [], 2: [], 3: []}
shape_animations, slide_1_text_blocks = 0, 0
for Slide in self._Presentation.Slides:
# count slide animations or entry effects
if Slide.TimeLine.MainSequence.Count >= 1:
shape_animations += Slide.TimeLine.MainSequence.Count
if Slide.SlideShowTransition.EntryEffect:
warnings[0].append(f"Анимация перехода на слайде {Slide.SlideIndex}.")
for Shape in Slide.Shapes:
crop = get_shape_crop_values(Shape)
if crop:
crop_warning = (f'Объект {Shape.Name}, {Shape.Id} обрезан {crop["left"]}:{crop["right"]}:'
f':{crop["top"]}:{crop["bottom"]}')
if Slide.SlideIndex == 1:
if is_image(Shape):
warnings[1].append(f"Изображение {Shape.Name} с ID {Shape.Id}")
elif is_text(Shape) is True:
slide_1_text_blocks += 1
elif is_text(Shape) is None:
warnings[1].append(f"Пустой текстовый блок {Shape.Name}, {Shape.Id}")
elif not is_text(Shape):
warnings[1].append(f"Неизвестный объект {Shape.Name}, {Shape.Id}")
if slide_1_text_blocks > 2:
warnings[1].append(f"Больше двух текстовых элементов на слайде.")
elif Slide.SlideIndex == 2:
if is_text(Shape) is None:
warnings[2].append(f"Пустой текстовый блок {Shape.Name}, {Shape.Id}")
elif not is_text(Shape) and not is_image(Shape):
warnings[2].append(f"Неизвестный объект {Shape.Name}, {Shape.Id}")
if crop:
warnings[2].append(crop_warning)
elif Slide.SlideIndex == 3:
if is_text(Shape) is None:
warnings[3].append(f"Пустой текстовый блок {Shape.Name}, {Shape.Id}")
elif not is_text(Shape) and not is_image(Shape):
warnings[3].append(f"Неизвестный объект {Shape.Name} с ID {Shape.Id}")
if crop:
warnings[3].append(crop_warning)
if shape_animations:
warnings[0].append(f"Анимации в объектах: {shape_animations}.")
return warnings
def export_csv(self):
warnings = self.warnings
presentation, structure, fonts, images, layout, grade = self.get()
warn_0, warn_1, warn_2, warn_3 = warnings[0], warnings[1], warnings[2], warnings[3]
path = Path.joinpath(Path(get_download_path()), self._Presentation.Name + ".csv")
fieldnames = ['Презентация', 'Структура', 'Шрифты', 'Картинки', 'Предупреждения', 'Слайд 1', 'Слайд 2',
'Слайд 3']
with open(path, "w", newline='', encoding="windows-1251") as fCsv:
writer = csv.writer(fCsv, delimiter=',')
writer.writerow(fieldnames)
writer.writerow([
dict_to_string(presentation),
dict_to_string(structure),
dict_to_string(fonts),
dict_to_string(images),
'\n'.join(warn_0),
'\n'.join(warn_1),
'\n'.join(warn_2),
'\n'.join(warn_3),
])
return path
|
from rest_framework import serializers
from news.models import News
class NewsSerializer(serializers.ModelSerializer):
class Meta:
model = News
fields = ['id', 'title', 'context']
|
n=int(input("Enter a no:"))
a=0
b=1
print(a)
sum=a+b
print(sum)
for i in range(n):
c=a+b
a=b
b=c
print(c)
|
# flake8: noqa: F401
from .copy_file import copy_file
from .git_version import git_version
from .local import local
from .remote import remote
from .sync import sync
|
# License: BSD 3-Clause
from collections import OrderedDict
import copy
import unittest
from distutils.version import LooseVersion
import sklearn
from sklearn import ensemble
import pandas as pd
import openml
from openml.testing import TestBase
import openml.extensions.sklearn
class TestFlowFunctions(TestBase):
_multiprocess_can_split_ = True
def setUp(self):
super(TestFlowFunctions, self).setUp()
def tearDown(self):
super(TestFlowFunctions, self).tearDown()
def _check_flow(self, flow):
self.assertEqual(type(flow), dict)
self.assertEqual(len(flow), 6)
self.assertIsInstance(flow["id"], int)
self.assertIsInstance(flow["name"], str)
self.assertIsInstance(flow["full_name"], str)
self.assertIsInstance(flow["version"], str)
# There are some runs on openml.org that can have an empty external version
ext_version_str_or_none = (
isinstance(flow["external_version"], str) or flow["external_version"] is None
)
self.assertTrue(ext_version_str_or_none)
def test_list_flows(self):
openml.config.server = self.production_server
# We can only perform a smoke test here because we test on dynamic
# data from the internet...
flows = openml.flows.list_flows()
# 3000 as the number of flows on openml.org
self.assertGreaterEqual(len(flows), 1500)
for fid in flows:
self._check_flow(flows[fid])
def test_list_flows_output_format(self):
openml.config.server = self.production_server
# We can only perform a smoke test here because we test on dynamic
# data from the internet...
flows = openml.flows.list_flows(output_format="dataframe")
self.assertIsInstance(flows, pd.DataFrame)
self.assertGreaterEqual(len(flows), 1500)
def test_list_flows_empty(self):
openml.config.server = self.production_server
flows = openml.flows.list_flows(tag="NoOneEverUsesThisTag123")
if len(flows) > 0:
raise ValueError("UnitTest Outdated, got somehow results (please adapt)")
self.assertIsInstance(flows, dict)
def test_list_flows_by_tag(self):
openml.config.server = self.production_server
flows = openml.flows.list_flows(tag="weka")
self.assertGreaterEqual(len(flows), 5)
for did in flows:
self._check_flow(flows[did])
def test_list_flows_paginate(self):
openml.config.server = self.production_server
size = 10
maximum = 100
for i in range(0, maximum, size):
flows = openml.flows.list_flows(offset=i, size=size)
self.assertGreaterEqual(size, len(flows))
for did in flows:
self._check_flow(flows[did])
def test_are_flows_equal(self):
flow = openml.flows.OpenMLFlow(
name="Test",
description="Test flow",
model=None,
components=OrderedDict(),
parameters=OrderedDict(),
parameters_meta_info=OrderedDict(),
external_version="1",
tags=["abc", "def"],
language="English",
dependencies="abc",
class_name="Test",
custom_name="Test",
)
# Test most important values that can be set by a user
openml.flows.functions.assert_flows_equal(flow, flow)
for attribute, new_value in [
("name", "Tes"),
("external_version", "2"),
("language", "english"),
("dependencies", "ab"),
("class_name", "Tes"),
("custom_name", "Tes"),
]:
new_flow = copy.deepcopy(flow)
setattr(new_flow, attribute, new_value)
self.assertNotEqual(
getattr(flow, attribute), getattr(new_flow, attribute),
)
self.assertRaises(
ValueError, openml.flows.functions.assert_flows_equal, flow, new_flow,
)
# Test that the API ignores several keys when comparing flows
openml.flows.functions.assert_flows_equal(flow, flow)
for attribute, new_value in [
("flow_id", 1),
("uploader", 1),
("version", 1),
("upload_date", "18.12.1988"),
("binary_url", "openml.org"),
("binary_format", "gzip"),
("binary_md5", "12345"),
("model", []),
("tags", ["abc", "de"]),
]:
new_flow = copy.deepcopy(flow)
setattr(new_flow, attribute, new_value)
self.assertNotEqual(
getattr(flow, attribute), getattr(new_flow, attribute),
)
openml.flows.functions.assert_flows_equal(flow, new_flow)
# Now test for parameters
flow.parameters["abc"] = 1.0
flow.parameters["def"] = 2.0
openml.flows.functions.assert_flows_equal(flow, flow)
new_flow = copy.deepcopy(flow)
new_flow.parameters["abc"] = 3.0
self.assertRaises(ValueError, openml.flows.functions.assert_flows_equal, flow, new_flow)
# Now test for components (subflows)
parent_flow = copy.deepcopy(flow)
subflow = copy.deepcopy(flow)
parent_flow.components["subflow"] = subflow
openml.flows.functions.assert_flows_equal(parent_flow, parent_flow)
self.assertRaises(
ValueError, openml.flows.functions.assert_flows_equal, parent_flow, subflow
)
new_flow = copy.deepcopy(parent_flow)
new_flow.components["subflow"].name = "Subflow name"
self.assertRaises(
ValueError, openml.flows.functions.assert_flows_equal, parent_flow, new_flow
)
def test_are_flows_equal_ignore_parameter_values(self):
paramaters = OrderedDict((("a", 5), ("b", 6)))
parameters_meta_info = OrderedDict((("a", None), ("b", None)))
flow = openml.flows.OpenMLFlow(
name="Test",
description="Test flow",
model=None,
components=OrderedDict(),
parameters=paramaters,
parameters_meta_info=parameters_meta_info,
external_version="1",
tags=["abc", "def"],
language="English",
dependencies="abc",
class_name="Test",
custom_name="Test",
)
openml.flows.functions.assert_flows_equal(flow, flow)
openml.flows.functions.assert_flows_equal(flow, flow, ignore_parameter_values=True)
new_flow = copy.deepcopy(flow)
new_flow.parameters["a"] = 7
self.assertRaisesRegex(
ValueError,
r"values for attribute 'parameters' differ: "
r"'OrderedDict\(\[\('a', 5\), \('b', 6\)\]\)'\nvs\n"
r"'OrderedDict\(\[\('a', 7\), \('b', 6\)\]\)'",
openml.flows.functions.assert_flows_equal,
flow,
new_flow,
)
openml.flows.functions.assert_flows_equal(flow, new_flow, ignore_parameter_values=True)
del new_flow.parameters["a"]
self.assertRaisesRegex(
ValueError,
r"values for attribute 'parameters' differ: "
r"'OrderedDict\(\[\('a', 5\), \('b', 6\)\]\)'\nvs\n"
r"'OrderedDict\(\[\('b', 6\)\]\)'",
openml.flows.functions.assert_flows_equal,
flow,
new_flow,
)
self.assertRaisesRegex(
ValueError,
r"Flow Test: parameter set of flow differs from the parameters "
r"stored on the server.",
openml.flows.functions.assert_flows_equal,
flow,
new_flow,
ignore_parameter_values=True,
)
def test_are_flows_equal_ignore_if_older(self):
paramaters = OrderedDict((("a", 5), ("b", 6)))
parameters_meta_info = OrderedDict((("a", None), ("b", None)))
flow_upload_date = "2017-01-31T12-01-01"
assert_flows_equal = openml.flows.functions.assert_flows_equal
flow = openml.flows.OpenMLFlow(
name="Test",
description="Test flow",
model=None,
components=OrderedDict(),
parameters=paramaters,
parameters_meta_info=parameters_meta_info,
external_version="1",
tags=["abc", "def"],
language="English",
dependencies="abc",
class_name="Test",
custom_name="Test",
upload_date=flow_upload_date,
)
assert_flows_equal(flow, flow, ignore_parameter_values_on_older_children=flow_upload_date)
assert_flows_equal(flow, flow, ignore_parameter_values_on_older_children=None)
new_flow = copy.deepcopy(flow)
new_flow.parameters["a"] = 7
self.assertRaises(
ValueError,
assert_flows_equal,
flow,
new_flow,
ignore_parameter_values_on_older_children=flow_upload_date,
)
self.assertRaises(
ValueError,
assert_flows_equal,
flow,
new_flow,
ignore_parameter_values_on_older_children=None,
)
new_flow.upload_date = "2016-01-31T12-01-01"
self.assertRaises(
ValueError,
assert_flows_equal,
flow,
new_flow,
ignore_parameter_values_on_older_children=flow_upload_date,
)
assert_flows_equal(flow, flow, ignore_parameter_values_on_older_children=None)
@unittest.skipIf(
LooseVersion(sklearn.__version__) < "0.20",
reason="OrdinalEncoder introduced in 0.20. "
"No known models with list of lists parameters in older versions.",
)
def test_sklearn_to_flow_list_of_lists(self):
from sklearn.preprocessing import OrdinalEncoder
ordinal_encoder = OrdinalEncoder(categories=[[0, 1], [0, 1]])
extension = openml.extensions.sklearn.SklearnExtension()
# Test serialization works
flow = extension.model_to_flow(ordinal_encoder)
# Test flow is accepted by server
self._add_sentinel_to_flow_name(flow)
flow.publish()
TestBase._mark_entity_for_removal("flow", (flow.flow_id, flow.name))
TestBase.logger.info("collected from {}: {}".format(__file__.split("/")[-1], flow.flow_id))
# Test deserialization works
server_flow = openml.flows.get_flow(flow.flow_id, reinstantiate=True)
self.assertEqual(server_flow.parameters["categories"], "[[0, 1], [0, 1]]")
self.assertEqual(server_flow.model.categories, flow.model.categories)
def test_get_flow1(self):
# Regression test for issue #305
# Basically, this checks that a flow without an external version can be loaded
openml.config.server = self.production_server
flow = openml.flows.get_flow(1)
self.assertIsNone(flow.external_version)
def test_get_flow_reinstantiate_model(self):
model = ensemble.RandomForestClassifier(n_estimators=33)
extension = openml.extensions.get_extension_by_model(model)
flow = extension.model_to_flow(model)
flow.publish(raise_error_if_exists=False)
TestBase._mark_entity_for_removal("flow", (flow.flow_id, flow.name))
TestBase.logger.info("collected from {}: {}".format(__file__.split("/")[-1], flow.flow_id))
downloaded_flow = openml.flows.get_flow(flow.flow_id, reinstantiate=True)
self.assertIsInstance(downloaded_flow.model, sklearn.ensemble.RandomForestClassifier)
def test_get_flow_reinstantiate_model_no_extension(self):
# Flow 10 is a WEKA flow
self.assertRaisesRegex(
RuntimeError,
"No extension could be found for flow 10: weka.SMO",
openml.flows.get_flow,
flow_id=10,
reinstantiate=True,
)
@unittest.skipIf(
LooseVersion(sklearn.__version__) == "0.19.1", reason="Target flow is from sklearn 0.19.1"
)
def test_get_flow_reinstantiate_model_wrong_version(self):
# Note that CI does not test against 0.19.1.
openml.config.server = self.production_server
_, sklearn_major, _ = LooseVersion(sklearn.__version__).version[:3]
flow = 8175
expected = "Trying to deserialize a model with dependency" " sklearn==0.19.1 not satisfied."
self.assertRaisesRegex(
ValueError, expected, openml.flows.get_flow, flow_id=flow, reinstantiate=True
)
if LooseVersion(sklearn.__version__) > "0.19.1":
# 0.18 actually can't deserialize this because of incompatibility
flow = openml.flows.get_flow(flow_id=flow, reinstantiate=True, strict_version=False)
# ensure that a new flow was created
assert flow.flow_id is None
assert "0.19.1" not in flow.dependencies
def test_get_flow_id(self):
clf = sklearn.tree.DecisionTreeClassifier()
flow = openml.extensions.get_extension_by_model(clf).model_to_flow(clf).publish()
self.assertEqual(openml.flows.get_flow_id(model=clf, exact_version=True), flow.flow_id)
flow_ids = openml.flows.get_flow_id(model=clf, exact_version=False)
self.assertIn(flow.flow_id, flow_ids)
self.assertGreater(len(flow_ids), 2)
# Check that the output of get_flow_id is identical if only the name is given, no matter
# whether exact_version is set to True or False.
flow_ids_exact_version_True = openml.flows.get_flow_id(name=flow.name, exact_version=True)
flow_ids_exact_version_False = openml.flows.get_flow_id(
name=flow.name, exact_version=False,
)
self.assertEqual(flow_ids_exact_version_True, flow_ids_exact_version_False)
self.assertIn(flow.flow_id, flow_ids_exact_version_True)
self.assertGreater(len(flow_ids_exact_version_True), 2)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 13 13:44:12 2019
@author: avelinojaver
"""
from .unet_base import UNetBase, ConvBlock, UpSimple, init_weights
import torch
import math
import collections
from torch import nn
from torchvision.models._utils import IntermediateLayerGetter
from torchvision.models import resnet
from torchvision.ops.misc import FrozenBatchNorm2d
#dummy variable used for compatibility with the unetbase
NF = collections.namedtuple('NF', 'n_filters')
class FrozenBatchNorm2dv2(FrozenBatchNorm2d):
def __init__(self, *args, **argkws):
super().__init__( *args, **argkws)
#the batchnorm in resnext is missing a variable in the presaved values, but the pytorch does not have it FrozenBatchNorm2d
#so I am adding it
self.register_buffer('num_batches_tracked', torch.tensor(0, dtype=torch.long))
class UnetResnet(UNetBase):
def __init__(self,
n_inputs,
n_outputs,
backbone_name = 'resnet34',
batchnorm = False,
init_type = 'xavier',
pad_mode = 'constant',
return_feat_maps = False,
is_imagenet_normalized = True,
load_pretrained = True
):
self.n_inputs = n_inputs
self.n_outputs = n_outputs
self.is_imagenet_normalized = is_imagenet_normalized
self.image_mean = [0.485, 0.456, 0.406]
self.image_std = [0.229, 0.224, 0.225]
if n_inputs != 3:
self.image_mean = sum(self.image_mean)/3
self.image_std = sum(self.image_std)/3
if backbone_name == 'resnet34' or backbone_name == 'resnet18':
nf_initial = 512
output_block_size = 64
else:
nf_initial = 2048
output_block_size = 256
## REAL DOWNSTREAM
return_layers = {'layer1':1, 'layer2':2, 'layer3':3, 'layer4':4}
#UPSTREAM
nf = nf_initial
up_blocks = []
for ii in range(len(return_layers) - 1):
nf_next = int(math.ceil(nf/2))
filters = [nf + nf_next] + [nf_next]*2
nf = nf_next
#scale_factor = 4 if ii == (len(return_layers) - 1) else 2
_up = UpSimple(filters, batchnorm = batchnorm, scale_factor = 2)
up_blocks.append(_up)
#OUTPUT
output_block = nn.Sequential(
nn.Upsample(scale_factor = 4, mode = 'bilinear', align_corners = False),
ConvBlock(output_block_size, 64, kernel_size = 3, batchnorm = batchnorm),
ConvBlock(64, 64, kernel_size = 3, batchnorm = batchnorm),
)
super().__init__([],
[],
up_blocks,
output_block,
return_feat_maps = return_feat_maps
)
## initial
self.adaptor = nn.Sequential(
ConvBlock(n_inputs, 64, kernel_size = 7, batchnorm = batchnorm),
ConvBlock(64, 3, kernel_size = 3, batchnorm = batchnorm)
)
#dummy variable used for compatibility with the UNetBase
self.down_blocks = [NF([ nf_initial // (2**ii)]) for ii in range(len(return_layers))][::-1]
self.n_levels = len(self.down_blocks)
#real downstream
norm_layer = FrozenBatchNorm2dv2 if 'resnext' in backbone_name else FrozenBatchNorm2d
backbone = resnet.__dict__[backbone_name](pretrained = load_pretrained, norm_layer = norm_layer)
self.backbone = IntermediateLayerGetter(backbone, return_layers)
for name, parameter in backbone.named_parameters():
if 'layer2' not in name and 'layer3' not in name and 'layer4' not in name:
parameter.requires_grad_(False)
self.loc_head = nn.Conv2d(64, n_outputs, kernel_size = 3, padding = 1)
self.n_inputs = n_inputs
self.n_outputs = n_outputs
#initialize model
if init_type is not None:
for part in [self.adaptor, self.up_blocks, self.output_block, self.loc_head]:
for m in part.modules():
init_weights(m, init_type = init_type)
def normalize(self, image):
#taken from https://github.com/pytorch/vision/blob/master/torchvision/models/detection/transform.py
if self.n_inputs == 3:
dtype, device = image.dtype, image.device
mean = torch.as_tensor(self.image_mean, dtype=dtype, device=device)
std = torch.as_tensor(self.image_std, dtype=dtype, device=device)
return (image - mean[:, None, None]) / std[:, None, None]
else:
return (image - self.image_mean) / self.image_std
def _unet(self, x_input):
if self.is_imagenet_normalized:
x_input = self.normalize(x_input)
x = self.adaptor(x_input)
resnet_feats = self.backbone(x)
x_downs = [x for x in resnet_feats.values()]
x_downs = x_downs[::-1]
x, x_downs = x_downs[0], x_downs[1:]
feats = [x]
for x_down, up in zip(x_downs, self.up_blocks):
x = up(x, x_down)
feats.append(x)
x = self.output_block(x)
feats.append(x)
xout = self.loc_head(x)
return xout, feats
if __name__ == '__main__':
X = torch.rand((1, 1, 100, 100))
#feats = backbone(X)
model = UnetResnet(1, 1, return_feat_maps = True, backbone_name = 'resnext101_32x8d')
xout, feats = model(X)
assert xout.shape[2:] == X.shape[2:]
loss = ((xout - X)**2).mean()
loss.backward()
|
import disnake as discord
from disnake.ext import commands
from api.check import utils, block
from api.server import base, main
import sqlite3
connection = sqlite3.connect('data/db/main/Database.db')
cursor = connection.cursor()
class Dropdown(discord.ui.Select):
def __init__(self, guild):
self.guild = guild
options = [
discord.SelectOption(label=f"📰 {main.get_lang(guild, 'HELP_INFO')}", value="11"),
discord.SelectOption(label=f"👦 {main.get_lang(guild, 'HELP_RP')}", value="22"),
discord.SelectOption(label=f"😹 {main.get_lang(guild, 'HELP_FUN')}", value="33"),
discord.SelectOption(label=f"🖼️ {main.get_lang(guild, 'HELP_IMAGE')}", value="44"),
discord.SelectOption(label=f"🔔 {main.get_lang(guild, 'HELP_OTHER')}", value="55"),
discord.SelectOption(label=f"⚙️ {main.get_lang(guild, 'HELP_CONFIG')}", value="66"),
discord.SelectOption(label=f"⛏️ {main.get_lang(guild, 'HELP_MODER')}", value="77"),
discord.SelectOption(label=f"💰 {main.get_lang(guild, 'HELP_ECONOMY')}", value="88")
]
super().__init__(
placeholder=f"{main.get_lang(guild, 'HELP_NEED')}",
min_values=1,
max_values=1,
options=options,
)
class DropdownView(discord.ui.View):
def __init__(self, guild):
super().__init__()
self.add_item(Dropdown(guild))
connection = sqlite3.connect('data/db/main/Database.db')
cursor = connection.cursor()
class Help(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(aliases=['помощь', 'хелп', 'helpy', 'help-me', 'bot-help', '/хелп', '/бот-хелп', '/help'])
@block.block()
async def help(self, ctx):
emb = discord.Embed(title = main.get_lang(ctx.guild, "HELP_TITLE"), description = main.get_lang(ctx.guild, "HELP_DESC").format(ctx.prefix), color = 0xFFA500)
view=DropdownView(ctx.guild)
await ctx.send(embed=emb, view=view)
@commands.Cog.listener()
async def on_dropdown(self, inter:discord.MessageInteraction):
color = 0xff4444
prefix = cursor.execute("SELECT prefix FROM guilds WHERE guild = {}".format(inter.guild.id)).fetchone()[0]
embed = discord.Embed(title = main.get_lang(inter.guild, "HELP_INFO"), description = main.get_lang(inter.guild, "HELP_CATEGORY_INFO").format(prefix), color = 0xFFA500)
embed1 = discord.Embed(title = main.get_lang(inter.guild, "HELP_RP"), description = main.get_lang(inter.guild, "HELP_CATEGORY_RP").format(prefix), color = 0xFFA500)
embed2 = discord.Embed(title = main.get_lang(inter.guild, "HELP_FUN"), description = main.get_lang(inter.guild, "HELP_CATEGORY_FUN").format(prefix), color = 0xFFA500)
embed3 = discord.Embed(title = main.get_lang(inter.guild, "HELP_IMAGE"), description = main.get_lang(inter.guild, "HELP_CATEGORY_IMAGE").format(prefix), color = 0xFFA500)
embed4 = discord.Embed(title = main.get_lang(inter.guild, "HELP_OTHER"), description = main.get_lang(inter.guild, "HELP_CATEGORY_OTHER").format(prefix), color = 0xFFA500)
embed5 = discord.Embed(title = main.get_lang(inter.guild, "HELP_CONFIG"), description = main.get_lang(inter.guild, "HELP_CATEGORY_CONFIG").format(prefix), color = 0xFFA500)
embed6 = discord.Embed(title = main.get_lang(inter.guild, "HELP_ECONOMY"), description = main.get_lang(inter.guild, "HELP_CATEGORY_ECONOMY").format(prefix), color = 0xFFA500)
embed7 = discord.Embed(title = main.get_lang(inter.guild, "HELP_MODER"), description = main.get_lang(inter.guild, "HELP_CATEGORY_MODER").format(prefix), color = 0xFFA500)
if inter.values[0] == '11':
await inter.send(embed=embed, ephemeral=True)
if inter.values[0] == '22':
await inter.send(embed=embed1, ephemeral=True)
if inter.values[0] == '33':
await inter.send(embed=embed2, ephemeral=True)
if inter.values[0] == '44':
await inter.send(embed=embed3, ephemeral=True)
if inter.values[0] == '55':
await inter.send(embed=embed4, ephemeral=True)
if inter.values[0] == '66':
await inter.send(embed=embed5, ephemeral=True)
if inter.values[0] == '77':
await inter.send(embed=embed7, ephemeral=True)
if inter.values[0] == '88':
await inter.send(embed=embed6, ephemeral=True)
def setup(client):
client.add_cog(Help(client)) |
# -*- coding: utf-8; -*-
from __future__ import print_function
from __future__ import absolute_import
import os
import re
import sys
import copy
import argparse
import subprocess
from getpass import getpass
from functools import partial
import lxml.etree
import ruamel.yaml as yaml
from jenkins import Jenkins, JenkinsError
from requests.exceptions import RequestException, HTTPError
from . import __version__
from . import utils, job
#-----------------------------------------------------------------------------
# Compatibility imports.
try:
from itertools import ifilterfalse as filterfalse
except ImportError:
from itertools import filterfalse
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
try:
input = raw_input
except NameError:
pass
#-----------------------------------------------------------------------------
usage = '''\
Usage: %s [options] <config.yaml>
General Options:
-n, --dry-run simulate execution
-v, --version show version and exit
-d, --debug debug config inheritance
-t, --debug-http debug http requests
Repository Options:
-r, --repo-url <arg> repository url
-y, --scm-user <arg> scm username (use '-' to read from stdin)
-o, --scm-pass <arg> scm password (use '-' to read from stdin)
Jenkins Options:
-j, --jenkins-url <arg> jenkins server url
-u, --jenkins-user <arg> jenkins username (use '-' to read from stdin)
-p, --jenkins-pass <arg> jenkins password (use '-' to read from stdin)
--no-verify-ssl do not verify jenkins server certificate
--cert-bundle <path> path to CA bundle file or directory
--client-cert <path> path to SSL client certificate
A client certificate can be specified as a single file, containing the
private key and certificate) or as 'path/to/client.cert:path/to/client.key'.\
''' % os.path.basename(sys.argv[0])
#-----------------------------------------------------------------------------
# The *global* connection to jenkins - assigned in main().
jenkins = None
def parseopts(args):
parser = argparse.ArgumentParser()
opt = parser.add_argument
opt('-n', '--dry-run', action='store_true')
opt('-v', '--version', action='version', version='%(prog) version ' + __version__)
opt('-d', '--debug', action='store_true')
opt('-t', '--debug-http', action='store_true')
opt('--no-verify-ssl', action='store_false', dest='verify_ssl')
opt('--cert-bundle')
opt('--client-cert')
opt('-r', '--repo-url')
opt('-y', '--scm-user', type=utils.PromptArgtype(input, 'SCM User: '))
opt('-o', '--scm-pass', type=utils.PromptArgtype(getpass, 'SCM Password: '))
opt('-j', '--jenkins-url')
opt('-u', '--jenkins-user', type=utils.PromptArgtype(input, 'Jenkins User: '))
opt('-p', '--jenkins-pass', type=utils.PromptArgtype(getpass, 'Jenkins Password: '))
opt('yamlconfig', metavar='config.yaml', type=argparse.FileType('r'), nargs="?")
return parser.parse_args(args)
def main(argv, create_job, list_branches, config=None):
'''
:param argv: command-line arguments to parse (defaults to sys.argv[1:])
:param create_job: scm specific function that configures and creates jobs
:param list_branches: scm specific function that lists all branches/refs
:param getoptfmt: getopt short and long options
:param config: a config dictionary to use instead of parsing the
configuration from yaml (useful for testing)
'''
if '-h' in argv or '--help' in argv:
print(usage)
sys.exit(0)
opts = parseopts(argv)
if not opts.yamlconfig and not config:
print(usage, file=sys.stderr)
print('error: config file not specified', file=sys.stderr)
sys.exit(2)
# Load config, set default values and compile regexes.
if not config:
print('loading config from "%s"' % os.path.abspath(opts.yamlconfig.name))
config = yaml.load(opts.yamlconfig)
config = c = get_default_config(config, opts)
if config['debughttp']:
enable_http_logging()
# Connect to jenkins.
try:
global jenkins
verify = c['cert-bundle'] if c['cert-bundle'] else c['verify-ssl']
jenkins = main.jenkins = Jenkins(c['jenkins'], c['username'], c['password'],
verify=verify, cert=c['client-cert'])
except (RequestException, JenkinsError) as e:
print(e)
sys.exit(1)
#-------------------------------------------------------------------------
# Get all the template names that the config references.
templates = set(i['template'] for i in c['refs'].values())
# Check if all referenced template jobs exist on the server.
missing = list(filterfalse(jenkins.job_exists, templates))
if missing:
missing.insert(0, '\nconfig references non-existent template jobs:')
print('\n - '.join(missing))
sys.exit(1)
# Convert them to etree objects of the templates' config xmls.
templates = dict((i, get_job_etree(i)) for i in templates)
#-------------------------------------------------------------------------
# Check if all referenced views exist.
view_names = set(view for i in c['refs'].values() for view in i['view'])
missing = list(filterfalse(jenkins.view_exists, view_names))
if missing:
missing.insert(0, '\nconfig references non-existent views:')
print('\n - '.join(missing))
sys.exit(1)
#-------------------------------------------------------------------------
# List all git refs, svn branches etc (implemented by child classes).
try:
branches = list(list_branches(config))
except subprocess.CalledProcessError as e:
print('! cannot list branches')
print('! command %s failed' % ' '.join(e.cmd))
exit(1)
# See if any of the branches are ignored.
ignored, branches = get_ignored(branches, c['ignore'])
if ignored:
msg = ['\nexplicitly ignored:'] + ignored
print('\n - '.join(msg))
# Get branch config for each branch.
configs = map(partial(resolveconfig, config), branches)
configs = zip(branches, configs)
configs = filter(lambda x: bool(x[1]), configs)
# The names of all successfully created or updated jobs.
job_names = {}
for branch, branch_config in configs:
tmpl = templates[branch_config['template']]
job_name = create_job(branch, tmpl, config, branch_config)
job_names[job_name] = branch_config
# Add newly create jobs to views, if any.
views = branch_config['view']
for view_name in views:
view = jenkins.view(view_name)
if job_name in view:
print('. job already in view: %s' % view_name)
else:
if not config['dryrun']:
jenkins.view_add_job(view_name, job_name)
print('. job added to view: %s' % view_name)
if config['cleanup']:
job_names[config['template']] = {}
cleanup(config, job_names, jenkins)
#-----------------------------------------------------------------------------
def cleanup(config, created_job_names, jenkins, verbose=True):
print('\ncleaning up old jobs:')
filter_function = partial(
filter_jobs,
by_views=config['cleanup-filters']['views'],
by_name_regex=config['cleanup-filters']['jobs']
)
removed_jobs = []
managed_jobs = get_managed_jobs(created_job_names, jenkins, filter_function)
for job, job_config in managed_jobs:
# If cleanup is a tag name, only cleanup builds with that tag.
if isinstance(config['cleanup'], str):
clean_tags = get_autojobs_tags(job_config, config['tag-method'])
if not config['cleanup'] in clean_tags:
if config['debug']:
print('. skipping %s' % job.name)
continue
removed_jobs.append(job)
if not config['dryrun']:
job_removed = safe_job_delete(job)
else:
job_removed = True
if job_removed:
print(' - %s' % job.name)
else:
print(' ! permission denied for %s' % job.name)
if not removed_jobs:
print('. nothing to do')
def get_autojobs_tags(job_config, method):
xml = lxml.etree.fromstring(job_config.encode('utf8'))
if method == 'element':
tags = xml.xpath('createdByJenkinsAutojobs/tag/text()')
elif method == 'description':
_, description = job.Job.find_description_el(xml)
description = description[0].text if description else ''
tags = re.findall(r'\n\(jenkins-autojobs-tag: (.*)\)', description)
tags = tags[0].split() if tags else []
return tags
def filter_jobs(jenkins, by_views=(), by_name_regex=()):
'''Select only jobs that belong to a given view or the names of which match a regex.'''
jobs = set()
if not by_views and not by_name_regex:
return jenkins.jobs
# Select jobs in the by_views list.
for view_name in by_views:
view_jobs = jenkins.view_jobs(view_name)
jobs.update(view_jobs) # set.update() is a union operation.
# Select jobs names that match the by_name_regex list.
for job in jenkins.jobs:
if utils.anymatch(by_name_regex, job.name):
jobs.add(job)
return jobs
def get_managed_jobs(created_job_names, jenkins, filter_function=None, safe_codes=(403,)):
'''
Returns jobs which were created by jenkins-autojobs. This is determined by
looking for a special string or element in the job's config.xml.
'''
tag_el = '</createdByJenkinsAutojobs>'
tag_desc = '(created by jenkins-autojobs)'
if callable(filter_function):
jobs = filter_function(jenkins)
else:
jobs = jenkins.jobs
for job in jobs:
if job.name in created_job_names:
continue
try:
job_config = job.config
if (tag_desc in job_config) or (tag_el in job_config):
yield job, job_config
except HTTPError as error:
if error.response.status_code not in safe_codes:
raise
def safe_job_delete(job, safe_codes=(403,)):
try:
job.delete()
return True
except HTTPError as error:
if error.response.status_code not in safe_codes:
raise
return False
#-----------------------------------------------------------------------------
def get_default_config(config, opts):
'''Set default config values and compile regexes.'''
c, o = copy.deepcopy(config), opts
# Default global settings (not inheritable).
c['dryrun'] = False
c['debug'] = config.get('debug', False)
c['debughttp'] = config.get('debughttp', False)
c['cleanup'] = config.get('cleanup', False)
c['username'] = config.get('username', None)
c['password'] = config.get('password', None)
c['scm-username'] = config.get('scm-username', None)
c['scm-password'] = config.get('scm-password', None)
c['verify-ssl'] = config.get('verify-ssl', True)
c['cert-bundle'] = config.get('cert-bundle', None)
c['client-cert'] = config.get('client-cert', None)
c['tag-method'] = config.get('tag-method', 'description')
c['cleanup-filters'] = config.get('cleanup-filters', {})
# Default settings for each git ref/branch config.
c['defaults'] = {
'namesep': c.get('namesep', '-'),
'namefmt': c.get('namefmt', '{shortref}'),
'overwrite': c.get('overwrite', True),
'enable': c.get('enable', 'sticky'),
'substitute': c.get('substitute', {}),
'template': c.get('template'),
'sanitize': c.get('sanitize', {'@!?#&|\^_$%*': '_'}),
'tag': c.get('tag', []),
'view': c.get('view', []),
'build-on-create': c.get('build-on-create', False)
}
# Default cleanup filters.
c['cleanup-filters']['views'] = c['cleanup-filters'].get('views', [])
c['cleanup-filters']['jobs'] = c['cleanup-filters'].get('jobs', [])
# Make sure some options are always lists.
c['defaults']['view'] = utils.pluralize(c['defaults']['view'])
# Options that can be overwritten from the command-line.
if o.repo_url: c['repo'] = opts.repo_url
if o.jenkins_url: c['jenkins'] = opts.jenkins_url
if o.dry_run: c['dryrun'] = True
if o.debug: c['debug'] = True
if o.debug_http: c['debughttp'] = True
if o.cert_bundle: c['cert-bundle'] = opts.cert_bundle
if o.client_cert: c['client-cert'] = opts.client_cert
if not o.verify_ssl: c['verify-ssl'] = opts.verify_ssl
# Jenkins authentication options.
if o.jenkins_user: c['username'] = o.jenkins_user
if o.jenkins_pass: c['password'] = o.jenkins_pass
# SCM authentication options.
if o.scm_user: c['scm-username'] = o.scm_user
if o.scm_pass: c['scm-password'] = o.scm_pass
# Compile ignore regexes.
c.setdefault('ignore', {})
c['ignore'] = [re.compile(i) for i in c['ignore']]
# Compile cleanup-filters job name regexes.
c['cleanup-filters']['jobs'] = [re.compile(i) for i in c['cleanup-filters']['jobs']]
# The 'All' view doesn't have an API endpoint (i.e. no /view/All/api).
# Since all jobs are added to it by default, we can ignore all other views.
if 'All' in c['cleanup-filters']['views']:
c['cleanup-filters']['views'] = []
if 'refs' not in c:
c['refs'] = ['.*']
if c['client-cert'] and ':' in c['client-cert']:
c['client-cert'] = tuple(c['client-cert'].split(':', 1))
# Get the effective (accounting for inheritance) config for all refs.
cfg = get_effective_branch_config(c['refs'], c['defaults'])
c['refs'] = cfg
return c
#-----------------------------------------------------------------------------
def get_effective_branch_config(branches, defaults):
'''Compile ref/branch regexes and map to their configuration with
inheritance factored in (think maven help:effective-pom).'''
ec = OrderedDict()
assert isinstance(branches, (list, tuple))
for entry in branches:
if isinstance(entry, dict):
key, overrides = list(entry.items())[0]
config = defaults.copy()
config.update(overrides)
ec[re.compile(key)] = config
else:
ec[re.compile(entry)] = defaults
# The 'All' view doesn't have an API endpoint (i.e. no /view/All/api).
# Since all jobs are added to it by default, it is safe to ignore it.
for config in ec.values():
if 'All' in config['view']:
config['view'].remove('All')
return ec
def get_ignored(branches, regexes):
'''Get refs, excluding ignored.'''
isignored = partial(utils.anymatch, regexes)
ignored, branches = utils.filtersplit(isignored, branches)
return ignored, branches
def resolveconfig(effective_config, branch):
'''Resolve a ref to its effective config.'''
for regex, config in effective_config['refs'].items():
if regex.match(branch):
config['re'] = regex
return config.copy()
def get_job_etree(job):
res = jenkins.job(job).config
res = lxml.etree.fromstring(res.encode('utf8'))
return res
def debug_refconfig(ref_config):
print('. config:')
for k, v in ref_config.items():
if k == 're':
print(' . %s: %s' % (k, v.pattern))
continue
if v:
print(' . %s: %s' % (k, v))
def enable_http_logging():
import logging
try:
from http.client import HTTPConnection
except ImportError:
from httplib import HTTPConnection
HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger('requests.packages.urllib3')
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
|
def steal(all_loots, comm):
count = int(comm[1])
items_to_steal = all_loots[-count:None]
print(", ".join(items_to_steal))
del all_loots[-count:None]
return all_loots
def drop(all_loots, comm):
index = int(comm[1])
if 0 <= index < len(all_loots):
all_loots.append(all_loots.pop(index))
return all_loots
def loot(all_loost,comm):
loot_items = comm[1:]
for current_loot in loot_items:
if current_loot not in all_loost:
all_loost.insert(0, current_loot)
return all_loost
chest = input().split("|")
command = input()
while command != "Yohoho!":
command = command.split(" ")
to_do = command[0]
if to_do == "Loot":
chest = loot(chest, command)
elif to_do == "Drop":
chest = drop(chest, command)
elif to_do == "Steal":
chest = steal(chest, command)
command = input()
if not chest:
print("Failed treasure hunt.")
else:
sum_all_treasures = sum([len(i) for i in chest])
average_treasure_gain = sum_all_treasures / len(chest)
print(f"Average treasure gain: {average_treasure_gain:.2f} pirate credits.")
|
import numpy as np
class Householder:
"""
Classe que representa o algoritmo utilizado para fazer transformações de Householder
para reduzir uma matriz simétrica a uma tridiagonal simetrica semelhante.
Args:
A (numpy.ndarray): Array n por n que representa a matriz completa a ser reduzida.
print_steps (bool, optional): Indica se deve ou não imprimir os passos intermediários. Padrão é False.
Attributes:
n (int): Variável que indica a dimensão da matriz do sistema.
k (int): Guarda o número da iteração atual do algorítmo.
print_steps (bool): Indica se deve imprimir informações de cada iteração na tela.
A (numpy.ndarray): Guarda o valor atual da matriz A.
Ht (numpy.ndarray): Guarda o valor atual da matriz H transposta.
"""
def __init__(self, A, print_steps=False):
assert A.shape[0] == A.shape[1]
self.n = A.shape[0]
self.k = 0
self.print_steps = print_steps
self.A = np.ndarray(A.shape, dtype=float)
self.Ht = np.identity(self.n, dtype=float)
np.copyto(self.A, A)
def _get_alfa_beta(self):
"""
Retorna a diagonal pricipal e subdiagonal da matriz tridiagonalizada pelo algoritmo.
Returns:
dict: Dicionário com dois elementos, um numpy.ndarray representando a diagonal principal
cuja chave é "alfa", e um representando as subdiagonais, com chave "beta".
"""
alfa = np.ndarray(self.n, dtype=float)
beta = np.ndarray(self.n-1, dtype=float)
for i in range(self.n-1):
alfa[i] = self.A[i][i]
beta[i] = self.A[i+1][i]
alfa[self.n-1] = self.A[self.n-1][self.n-1]
result = {
'alfa' : alfa,
'beta' : beta,
}
return result
def _iterate_once(self):
"""
Método que representa uma iteração de transformações de Householder para uma matriz simétrica.
"""
if self.print_steps:
print(f'Iteração {self.k+1}:')
# Calcula o valor do wk da iteracao atual
ak_ = self.A[self.k+1 :, [self.k]]
wk_ = np.copy(ak_)
wk_[0] += np.sign(ak_[0]) * np.linalg.norm(ak_)
if self.print_steps:
print(f'w{self.k+1}_:\n{wk_}')
# Multiplica a matriz H_wk a esquerda de A
for i in range(self.k, self.n):
ai_ = self.A[self.k+1 :, [i]]
self.A[self.k+1 :, [i]] = ai_ - 2 * np.dot(ai_.T, wk_) / np.dot(wk_.T, wk_) * wk_
if self.print_steps:
print(f'H_w{self.k+1} A:\n{self.A}')
# Multiplica a matriz H_wk a direita de A
for i in range(self.k+1, self.n):
bi_ = self.A[[i], self.k+1 :]
self.A[[i], self.k+1 :] = bi_ - 2 * np.dot(bi_, wk_) / np.dot(wk_.T, wk_) * wk_.T
if self.print_steps:
print(f'H_w{self.k+1} A H_w{self.k+1}:\n{self.A}')
# Multiplica a matriz H_wk a direita de Ht
for i in range(0, self.n):
bi_ = self.Ht[[i], self.k+1 :]
self.Ht[[i], self.k+1 :] = bi_ - 2 * np.dot(bi_, wk_) / np.dot(wk_.T, wk_) * wk_.T
if self.print_steps:
print(f'Ht H_w{self.k+1}:\n{self.Ht}\n')
self.k += 1
def iterate(self):
"""
Método que executa as transformações de Householder para a matriz fornecida no construtor.
Returns:
dict: Dicionário contendo a matriz tridiagonal e a matriz tranposta de H, para serem
utilizados pelo método QR.
"""
for m in range(self.n-2):
self._iterate_once()
result = {}
result['T'] = self._get_alfa_beta()
result['Ht'] = self.Ht
return result
if __name__ == '__main__':
print('Esse arquivo contem apenas o algoritmo Householder, mas não os testes.')
print('Para rodar os testes corretamente, por favor consulte o LEIAME.txt')
|
# Generated by Django 2.2.13 on 2020-12-14 08:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0105_auto_20201211_0758'),
]
operations = [
migrations.AddField(
model_name='country',
name='disputed',
field=models.BooleanField(default=False, help_text='Is this country disputed?'),
),
migrations.AddField(
model_name='country',
name='sovereign_state',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='api.Country', verbose_name='Country ID of the Sovereign State'),
),
]
|
# -*- coding: utf-8 -*-
from .processor import NormProcessor, SeqProcessor
from .dataset import NormDataset, SeqDataset
from .tool import split_dataset |
# coding: utf8
from marshmallow import (Schema, fields)
class CreateSuscriberSchema(Schema):
email = fields.String()
new_email = fields.String()
user_id = fields.String()
time_zone = fields.String()
lifetime_value = fields.Integer()
ip_address = fields.String()
custom_fields = fields.Dict()
tags = fields.List(fields.String())
remove_tags = fields.List(fields.String())
prospect = fields.Boolean()
base_lead_score = fields.Integer()
eu_consent = fields.String()
eu_consent_message = fields.String()
|
# -*- coding: utf-8 -*-
"""
functions for upgrading to the database version 2.
Created on Wed Dec 23 21:33:03 2020
@author: Alon Diament, Tuller Lab
"""
import json
import os
import pickle
import sqlite3
import paraschut as psu
def run(db_path=psu.QFile):
with connect(db_path, exists_OK=False) as conn:
psu.init_db(conn)
populate_db(db_path)
def connect(QFile, exists_OK=True, **kwargs):
db_file = '.'.join(QFile.split('.')[:-1] + ['db'])
psu.QFile = db_file
if os.path.isfile(db_file) and not exists_OK:
raise Exception(f'database "{db_file}" already exist')
return sqlite3.connect(db_file, **kwargs)
def populate_db(QFile=psu.QFile):
""" add all currently queued jobs to new DB. """
conn = connect(QFile, exists_OK=True)
Q = get_queue(QFile='.'.join(QFile.split('.')[:-1] + ['pkl']))
for batch_id, batch in Q.items():
for job in batch:
upgrade_job(job)
metadata = psu.pack_job(job)
conn.execute("""INSERT INTO job(JobIndex, BatchID, state,
priority, metadata, md5)
VALUES (?,?,?,?,?,?)""",
[job['JobIndex'], batch_id, job['state'],
job['priority'], metadata, job['md5']])
conn.execute("""INSERT INTO batch
VALUES (?,?,?)""",
[batch_id, '/'.join(batch[0]['name']),
batch[0]['batch_type']])
conn.commit()
conn.close()
# test new DB
reconstructed_Q = psu.get_sql_queue()
assert all([json.dumps(reconstructed_Q[b], default=set_default) ==
json.dumps(Q[b], default=set_default)
for b in Q])
def upgrade_job(JobInfo):
if 'status' in JobInfo:
JobInfo['state'] = JobInfo['status']
del JobInfo['status']
if 'PBS_ID' in JobInfo:
JobInfo['ClusterID'] = JobInfo['PBS_ID']
del JobInfo['PBS_ID']
if 'data_type' in JobInfo:
JobInfo['batch_type'] = JobInfo['data_type']
if 'organism' in JobInfo:
JobInfo['name'] = [JobInfo['organism']] + JobInfo['name']
def get_queue(QFile):
""" legacy get_queue for databse version 1. """
# reads from global job queue file
Q = pickle.load(open(QFile, 'rb'))
for BatchID in sorted(list(Q)):
processed = []
for p, pfile in enumerate(Q[BatchID]):
try:
pinfo = pickle.load(open(pfile, 'rb'))
except Exception as err:
print(f'pickle error: {err}')
continue
pinfo = rename_key(pinfo, 'JobID', 'BatchID')
pinfo = rename_key(pinfo, 'JobPart', 'JobIndex')
Q[BatchID][p] = pinfo # replace `pfile` with data
processed.append(p)
Q[BatchID] = [Q[BatchID][p] for p in processed]
if len(Q[BatchID]) == 0:
del Q[BatchID]
continue
return Q
def rename_key(d, old_key, new_key):
return {new_key if k == old_key else k:v for k,v in d.items()}
def set_default(obj):
if isinstance(obj, set):
return list(obj)
raise TypeError
|
# -*- coding: utf-8 -*-
import unittest
import sys
sys.path.append(u'../ftplugin')
import vim
from orgmode._vim import ORGMODE
from orgmode.py3compat.encode_compatibility import *
counter = 0
class EditStructureTestCase(unittest.TestCase):
def setUp(self):
global counter
counter += 1
vim.CMDHISTORY = []
vim.CMDRESULTS = {}
vim.EVALHISTORY = []
vim.EVALRESULTS = {
# no org_todo_keywords for b
u_encode(u'exists("b:org_todo_keywords")'): u_encode('0'),
# global values for org_todo_keywords
u_encode(u'exists("g:org_todo_keywords")'): u_encode('1'),
u_encode(u'g:org_todo_keywords'): [u_encode(u'TODO'), u_encode(u'|'), u_encode(u'DONE')],
u_encode(u'exists("g:org_improve_split_heading")'): u_encode(u'0'),
u_encode(u'exists("b:org_improve_split_heading")'): u_encode(u'0'),
u_encode(u'exists("g:org_debug")'): u_encode(u'0'),
u_encode(u'exists("b:org_debug")'): u_encode(u'0'),
u_encode(u'exists("*repeat#set()")'): u_encode(u'0'),
u_encode(u'b:changedtick'): u_encode(u'%d' % counter),
u_encode(u'&ts'): u_encode(u'8'),
u_encode(u'exists("g:org_tag_column")'): u_encode(u'0'),
u_encode(u'exists("b:org_tag_column")'): u_encode(u'0'),
u_encode(u"v:count"): u_encode(u'0'),
# jump to insert mode after adding heading/checkbox
u_encode(u'exists("g:org_prefer_insert_mode")'): u_encode(u'0'),
u_encode(u'exists("b:org_prefer_insert_mode")'): u_encode(u'0')}
if not u'EditStructure' in ORGMODE.plugins:
ORGMODE.register_plugin(u'EditStructure')
self.editstructure = ORGMODE.plugins[u'EditStructure']
vim.current.buffer[:] = [ u_encode(i) for i in u"""
* Überschrift 1
Text 1
Bla bla
** Überschrift 1.1
Text 2
Bla Bla bla
** Überschrift 1.2
Text 3
**** Überschrift 1.2.1.falsch
Bla Bla bla bla
*** Überschrift 1.2.1
* Überschrift 2
* Überschrift 3
asdf sdf
""".split(u'\n')]
def test_new_heading_below_normal_behavior(self):
vim.current.window.cursor = (1, 0)
self.assertNotEqual(self.editstructure.new_heading(below=True), None)
self.assertEqual(vim.current.buffer[0], u_encode(u'* '))
self.assertEqual(vim.current.buffer[1], u_encode(u'* Überschrift 1'))
def test_new_heading_above_normal_behavior(self):
vim.current.window.cursor = (1, 1)
self.assertNotEqual(self.editstructure.new_heading(below=False), None)
self.assertEqual(vim.current.buffer[0], u_encode(u'* '))
self.assertEqual(vim.current.buffer[1], u_encode(u'* Überschrift 1'))
def test_new_heading_below(self):
vim.current.window.cursor = (2, 0)
vim.current.buffer[5] = u_encode(u'** Überschrift 1.1 :Tag:')
self.assertNotEqual(self.editstructure.new_heading(below=True, insert_mode=False), None)
self.assertEqual(vim.CMDHISTORY[-1], u_encode(u'exe "normal 6gg"|startinsert!'))
self.assertEqual(vim.current.buffer[4], u_encode(u'Bla bla'))
self.assertEqual(vim.current.buffer[5], u_encode(u'* '))
self.assertEqual(vim.current.buffer[6], u_encode(u'** Überschrift 1.1 :Tag:'))
self.assertEqual(vim.current.buffer[10], u_encode(u'** Überschrift 1.2'))
self.assertEqual(vim.current.buffer[13], u_encode(u'**** Überschrift 1.2.1.falsch'))
self.assertEqual(vim.current.buffer[16], u_encode(u'*** Überschrift 1.2.1'))
self.assertEqual(vim.current.buffer[17], u_encode(u'* Überschrift 2'))
def test_new_heading_below_insert_mode(self):
vim.current.window.cursor = (2, 1)
self.assertNotEqual(self.editstructure.new_heading(below=True, insert_mode=True), None)
self.assertEqual(vim.CMDHISTORY[-1], u_encode(u'exe "normal 3gg"|startinsert!'))
self.assertEqual(vim.current.buffer[2], u_encode(u'* Überschrift 1'))
self.assertEqual(vim.current.buffer[5], u_encode(u'Bla bla'))
self.assertEqual(vim.current.buffer[6], u_encode(u'** Überschrift 1.1'))
self.assertEqual(vim.current.buffer[10], u_encode(u'** Überschrift 1.2'))
self.assertEqual(vim.current.buffer[13], u_encode(u'**** Überschrift 1.2.1.falsch'))
self.assertEqual(vim.current.buffer[16], u_encode(u'*** Überschrift 1.2.1'))
self.assertEqual(vim.current.buffer[17], u_encode(u'* Überschrift 2'))
def test_new_heading_below_split_text_at_the_end(self):
vim.current.buffer[1] = u_encode(u'* Überschriftx1')
vim.current.window.cursor = (2, 14)
self.assertNotEqual(self.editstructure.new_heading(below=True, insert_mode=True), None)
self.assertEqual(vim.CMDHISTORY[-1], u_encode(u'exe "normal 3gg"|startinsert!'))
self.assertEqual(vim.current.buffer[2], u_encode(u'* '))
self.assertEqual(vim.current.buffer[5], u_encode(u'Bla bla'))
self.assertEqual(vim.current.buffer[6], u_encode(u'** Überschrift 1.1'))
self.assertEqual(vim.current.buffer[10], u_encode(u'** Überschrift 1.2'))
self.assertEqual(vim.current.buffer[13], u_encode(u'**** Überschrift 1.2.1.falsch'))
self.assertEqual(vim.current.buffer[16], u_encode(u'*** Überschrift 1.2.1'))
self.assertEqual(vim.current.buffer[17], u_encode(u'* Überschrift 2'))
def test_new_heading_below_split_text_at_the_end_insert_parts(self):
vim.current.window.cursor = (2, 14)
self.assertNotEqual(self.editstructure.new_heading(below=True, insert_mode=True), None)
self.assertEqual(vim.CMDHISTORY[-1], u_encode(u'exe "normal 3gg"|startinsert!'))
self.assertEqual(vim.current.buffer[2], u_encode(u'* 1'))
self.assertEqual(vim.current.buffer[5], u_encode(u'Bla bla'))
self.assertEqual(vim.current.buffer[6], u_encode(u'** Überschrift 1.1'))
self.assertEqual(vim.current.buffer[10], u_encode(u'** Überschrift 1.2'))
self.assertEqual(vim.current.buffer[13], u_encode(u'**** Überschrift 1.2.1.falsch'))
self.assertEqual(vim.current.buffer[16], u_encode(u'*** Überschrift 1.2.1'))
self.assertEqual(vim.current.buffer[17], u_encode(u'* Überschrift 2'))
def test_new_heading_below_in_the_middle(self):
vim.current.window.cursor = (10, 0)
self.assertNotEqual(self.editstructure.new_heading(below=True, insert_mode=True), None)
self.assertEqual(vim.CMDHISTORY[-1], u_encode(u'exe "normal 13gg"|startinsert!'))
self.assertEqual(vim.current.buffer[11], u_encode(u''))
self.assertEqual(vim.current.buffer[12], u_encode(u'** '))
self.assertEqual(vim.current.buffer[13], u_encode(u'**** Überschrift 1.2.1.falsch'))
def test_new_heading_below_in_the_middle2(self):
vim.current.window.cursor = (13, 0)
self.assertNotEqual(self.editstructure.new_heading(below=True, insert_mode=True), None)
self.assertEqual(vim.CMDHISTORY[-1], u_encode(u'exe "normal 16gg"|startinsert!'))
self.assertEqual(vim.current.buffer[14], u_encode(u'Bla Bla bla bla'))
self.assertEqual(vim.current.buffer[15], u_encode(u'**** '))
self.assertEqual(vim.current.buffer[16], u_encode(u'*** Überschrift 1.2.1'))
def test_new_heading_below_in_the_middle3(self):
vim.current.window.cursor = (16, 0)
self.assertNotEqual(self.editstructure.new_heading(below=True, insert_mode=True), None)
self.assertEqual(vim.CMDHISTORY[-1], u_encode(u'exe "normal 17gg"|startinsert!'))
self.assertEqual(vim.current.buffer[15], u_encode(u'*** Überschrift 1.2.1'))
self.assertEqual(vim.current.buffer[16], u_encode(u'*** '))
self.assertEqual(vim.current.buffer[17], u_encode(u'* Überschrift 2'))
def test_new_heading_below_at_the_end(self):
vim.current.window.cursor = (18, 0)
self.assertNotEqual(self.editstructure.new_heading(below=True, insert_mode=True), None)
self.assertEqual(vim.CMDHISTORY[-1], u_encode(u'exe "normal 21gg"|startinsert!'))
self.assertEqual(vim.current.buffer[19], u_encode(u''))
self.assertEqual(vim.current.buffer[20], u_encode(u'* '))
self.assertEqual(len(vim.current.buffer), 21)
def test_new_heading_above(self):
vim.current.window.cursor = (2, 0)
self.assertNotEqual(self.editstructure.new_heading(below=False, insert_mode=True), None)
self.assertEqual(vim.CMDHISTORY[-1], u_encode(u'exe "normal 2gg"|startinsert!'))
self.assertEqual(vim.current.buffer[0], u_encode(u''))
self.assertEqual(vim.current.buffer[1], u_encode(u'* '))
self.assertEqual(vim.current.buffer[2], u_encode(u'* Überschrift 1'))
def test_new_heading_above_in_the_middle(self):
vim.current.window.cursor = (10, 0)
self.assertNotEqual(self.editstructure.new_heading(below=False, insert_mode=True), None)
self.assertEqual(vim.CMDHISTORY[-1], u_encode(u'exe "normal 10gg"|startinsert!'))
self.assertEqual(vim.current.buffer[8], u_encode(u'Bla Bla bla'))
self.assertEqual(vim.current.buffer[9], u_encode(u'** '))
self.assertEqual(vim.current.buffer[10], u_encode(u'** Überschrift 1.2'))
def test_new_heading_above_in_the_middle2(self):
vim.current.window.cursor = (13, 0)
self.assertNotEqual(self.editstructure.new_heading(below=False, insert_mode=True), None)
self.assertEqual(vim.CMDHISTORY[-1], u_encode(u'exe "normal 13gg"|startinsert!'))
self.assertEqual(vim.current.buffer[11], u_encode(u''))
self.assertEqual(vim.current.buffer[12], u_encode(u'**** '))
self.assertEqual(vim.current.buffer[13], u_encode(u'**** Überschrift 1.2.1.falsch'))
def test_new_heading_above_in_the_middle3(self):
vim.current.window.cursor = (16, 0)
self.assertNotEqual(self.editstructure.new_heading(below=False, insert_mode=True), None)
self.assertEqual(vim.CMDHISTORY[-1], u_encode(u'exe "normal 16gg"|startinsert!'))
self.assertEqual(vim.current.buffer[14], u_encode(u'Bla Bla bla bla'))
self.assertEqual(vim.current.buffer[15], u_encode(u'*** '))
self.assertEqual(vim.current.buffer[16], u_encode(u'*** Überschrift 1.2.1'))
def test_new_heading_above_at_the_end(self):
vim.current.window.cursor = (18, 0)
self.assertNotEqual(self.editstructure.new_heading(below=False, insert_mode=True), None)
self.assertEqual(vim.CMDHISTORY[-1], u_encode(u'exe "normal 18gg"|startinsert!'))
self.assertEqual(vim.current.buffer[16], u_encode(u'* Überschrift 2'))
self.assertEqual(vim.current.buffer[17], u_encode(u'* '))
self.assertEqual(vim.current.buffer[18], u_encode(u'* Überschrift 3'))
def test_new_heading_below_split_heading_title(self):
vim.current.buffer[:] = [ u_encode(i) for i in u"""
* Überschrift 1 :Tag:
Text 1
Bla bla
** Überschrift 1.1
Text 2
Bla Bla bla
** Überschrift 1.2
Text 3
**** Überschrift 1.2.1.falsch
Bla Bla bla bla
*** Überschrift 1.2.1
* Überschrift 2
* Überschrift 3
asdf sdf
""".split(u'\n')]
vim.current.window.cursor = (2, 6)
self.assertNotEqual(self.editstructure.new_heading(insert_mode=True), None)
self.assertEqual(vim.current.buffer[0], u_encode(u''))
self.assertEqual(vim.current.buffer[1], u_encode(u'* Über :Tag:'))
self.assertEqual(vim.current.buffer[2], u_encode(u'* schrift 1'))
self.assertEqual(vim.current.buffer[3], u_encode(u'Text 1'))
def test_new_heading_below_split_heading_title_with_todo(self):
vim.current.buffer[:] = [ u_encode(i) for i in u"""
* TODO Überschrift 1 :Tag:
Text 1
Bla bla
** Überschrift 1.1
Text 2
Bla Bla bla
** Überschrift 1.2
Text 3
**** Überschrift 1.2.1.falsch
Bla Bla bla bla
*** Überschrift 1.2.1
* Überschrift 2
* Überschrift 3
asdf sdf
""".split(u'\n')]
vim.current.window.cursor = (2, 5)
self.assertNotEqual(self.editstructure.new_heading(insert_mode=True), None)
self.assertEqual(vim.current.buffer[0], u_encode(u''))
self.assertEqual(vim.current.buffer[1], u_encode(u'* TODO :Tag:'))
self.assertEqual(vim.current.buffer[2], u_encode(u'* Überschrift 1'))
self.assertEqual(vim.current.buffer[3], u_encode(u'Text 1'))
def test_demote_heading(self):
vim.current.window.cursor = (13, 0)
self.assertNotEqual(self.editstructure.demote_heading(), None)
self.assertEqual(vim.current.buffer[10], u_encode(u'Text 3'))
self.assertEqual(vim.current.buffer[11], u_encode(u''))
self.assertEqual(vim.current.buffer[12], u_encode(u'***** Überschrift 1.2.1.falsch'))
self.assertEqual(vim.current.buffer[13], u_encode(u''))
# actually the indentation comes through vim, just the heading is updated
self.assertEqual(vim.current.buffer[14], u_encode(u'Bla Bla bla bla'))
self.assertEqual(vim.current.buffer[15], u_encode(u'*** Überschrift 1.2.1'))
self.assertEqual(vim.current.window.cursor, (13, 1))
def test_demote_newly_created_level_one_heading(self):
vim.current.window.cursor = (2, 0)
self.assertNotEqual(self.editstructure.new_heading(below=True), None)
self.assertEqual(vim.current.buffer[1], u_encode(u'* Überschrift 1'))
self.assertEqual(vim.current.buffer[5], u_encode(u'* '))
self.assertEqual(vim.current.buffer[6], u_encode(u'** Überschrift 1.1'))
self.assertEqual(vim.current.buffer[10], u_encode(u'** Überschrift 1.2'))
self.assertEqual(vim.current.buffer[13], u_encode(u'**** Überschrift 1.2.1.falsch'))
self.assertEqual(vim.current.buffer[16], u_encode(u'*** Überschrift 1.2.1'))
self.assertEqual(vim.current.buffer[17], u_encode(u'* Überschrift 2'))
vim.current.window.cursor = (6, 2)
self.assertNotEqual(self.editstructure.demote_heading(), None)
self.assertEqual(vim.current.buffer[5], u_encode(u'** '))
self.assertEqual(vim.current.buffer[6], u_encode(u'*** Überschrift 1.1'))
self.assertEqual(vim.current.buffer[10], u_encode(u'*** Überschrift 1.2'))
self.assertEqual(vim.current.buffer[13], u_encode(u'***** Überschrift 1.2.1.falsch'))
self.assertEqual(vim.current.buffer[16], u_encode(u'**** Überschrift 1.2.1'))
self.assertEqual(vim.current.buffer[17], u_encode(u'* Überschrift 2'))
def test_demote_newly_created_level_two_heading(self):
vim.current.window.cursor = (10, 0)
self.assertNotEqual(self.editstructure.new_heading(below=True), None)
self.assertEqual(vim.current.buffer[1], u_encode(u'* Überschrift 1'))
self.assertEqual(vim.current.buffer[5], u_encode(u'** Überschrift 1.1'))
self.assertEqual(vim.current.buffer[9], u_encode(u'** Überschrift 1.2'))
self.assertEqual(vim.current.buffer[12], u_encode(u'** '))
self.assertEqual(vim.current.buffer[13], u_encode(u'**** Überschrift 1.2.1.falsch'))
self.assertEqual(vim.current.buffer[16], u_encode(u'*** Überschrift 1.2.1'))
self.assertEqual(vim.current.buffer[17], u_encode(u'* Überschrift 2'))
vim.current.window.cursor = (13, 3)
self.assertNotEqual(self.editstructure.demote_heading(including_children=False, on_heading=True), None)
self.assertEqual(vim.CMDHISTORY[-1], u_encode(u'exe "normal 13gg"|startinsert!'))
self.assertEqual(vim.current.buffer[1], u_encode(u'* Überschrift 1'))
self.assertEqual(vim.current.buffer[5], u_encode(u'** Überschrift 1.1'))
self.assertEqual(vim.current.buffer[9], u_encode(u'** Überschrift 1.2'))
self.assertEqual(vim.current.buffer[12], u_encode(u'*** '))
self.assertEqual(vim.current.buffer[13], u_encode(u'**** Überschrift 1.2.1.falsch'))
self.assertEqual(vim.current.buffer[16], u_encode(u'*** Überschrift 1.2.1'))
self.assertEqual(vim.current.buffer[17], u_encode(u'* Überschrift 2'))
def test_demote_last_heading(self):
vim.current.buffer[:] = [ u_encode(i) for i in u"""
* Überschrift 2
* Überschrift 3""".split('\n')]
vim.current.window.cursor = (3, 0)
h = ORGMODE.get_document().current_heading()
self.assertNotEqual(self.editstructure.demote_heading(), None)
self.assertEqual(h.end, 2)
self.assertFalse(vim.CMDHISTORY)
self.assertEqual(vim.current.buffer[2], u_encode(u'** Überschrift 3'))
self.assertEqual(vim.current.window.cursor, (3, 1))
def test_promote_heading(self):
vim.current.window.cursor = (13, 0)
self.assertNotEqual(self.editstructure.promote_heading(), None)
self.assertEqual(vim.current.buffer[10], u_encode(u'Text 3'))
self.assertEqual(vim.current.buffer[11], u_encode(u''))
self.assertEqual(vim.current.buffer[12], u_encode(u'*** Überschrift 1.2.1.falsch'))
self.assertEqual(vim.current.buffer[13], u_encode(u''))
# actually the indentation comes through vim, just the heading is updated
self.assertEqual(vim.current.buffer[14], u_encode(u'Bla Bla bla bla'))
self.assertEqual(vim.current.buffer[15], u_encode(u'*** Überschrift 1.2.1'))
self.assertEqual(vim.current.window.cursor, (13, -1))
def test_promote_level_one_heading(self):
vim.current.window.cursor = (2, 0)
self.assertEqual(self.editstructure.promote_heading(), None)
self.assertEqual(len(vim.CMDHISTORY), 0)
self.assertEqual(vim.current.buffer[1], u_encode(u'* Überschrift 1'))
self.assertEqual(vim.current.window.cursor, (2, 0))
def test_demote_parent_heading(self):
vim.current.window.cursor = (2, 0)
self.assertNotEqual(self.editstructure.demote_heading(), None)
self.assertEqual(vim.current.buffer[1], u_encode(u'** Überschrift 1'))
self.assertEqual(vim.current.buffer[5], u_encode(u'*** Überschrift 1.1'))
self.assertEqual(vim.current.buffer[9], u_encode(u'*** Überschrift 1.2'))
self.assertEqual(vim.current.buffer[12], u_encode(u'***** Überschrift 1.2.1.falsch'))
self.assertEqual(vim.current.buffer[15], u_encode(u'**** Überschrift 1.2.1'))
self.assertEqual(vim.current.buffer[16], u_encode(u'* Überschrift 2'))
self.assertEqual(vim.current.window.cursor, (2, 1))
def test_promote_parent_heading(self):
vim.current.window.cursor = (10, 0)
self.assertNotEqual(self.editstructure.promote_heading(), None)
self.assertEqual(vim.CMDHISTORY[-1], u_encode(u'normal 10ggV16gg='))
self.assertEqual(vim.current.buffer[5], u_encode(u'** Überschrift 1.1'))
self.assertEqual(vim.current.buffer[9], u_encode(u'* Überschrift 1.2'))
self.assertEqual(vim.current.buffer[12], u_encode(u'*** Überschrift 1.2.1.falsch'))
self.assertEqual(vim.current.buffer[15], u_encode(u'** Überschrift 1.2.1'))
self.assertEqual(vim.current.buffer[16], u_encode(u'* Überschrift 2'))
self.assertEqual(vim.current.window.cursor, (10, -1))
# run tests with count
def test_demote_parent_heading_count(self):
vim.current.window.cursor = (2, 0)
vim.EVALRESULTS[u"v:count"] = u_encode(u'3')
self.assertNotEqual(self.editstructure.demote_heading(), None)
self.assertEqual(vim.current.buffer[1], u_encode(u'**** Überschrift 1'))
self.assertEqual(vim.current.buffer[5], u_encode(u'***** Überschrift 1.1'))
self.assertEqual(vim.current.buffer[9], u_encode(u'***** Überschrift 1.2'))
self.assertEqual(vim.current.buffer[12], u_encode(u'******* Überschrift 1.2.1.falsch'))
self.assertEqual(vim.current.buffer[15], u_encode(u'****** Überschrift 1.2.1'))
self.assertEqual(vim.current.buffer[16], u_encode(u'* Überschrift 2'))
self.assertEqual(vim.current.buffer[16], u_encode(u'* Überschrift 2'))
self.assertEqual(vim.current.window.cursor, (2, 3))
def test_promote_parent_heading(self):
vim.current.window.cursor = (13, 0)
vim.EVALRESULTS[u"v:count"] = u_encode(u'3')
self.assertNotEqual(self.editstructure.promote_heading(), None)
self.assertEqual(vim.current.buffer[5], u_encode(u'** Überschrift 1.1'))
self.assertEqual(vim.current.buffer[9], u_encode(u'** Überschrift 1.2'))
self.assertEqual(vim.current.buffer[12], u_encode(u'* Überschrift 1.2.1.falsch'))
self.assertEqual(vim.current.buffer[15], u_encode(u'** Überschrift 1.2.1'))
self.assertEqual(vim.current.buffer[16], u_encode(u'* Überschrift 2'))
self.assertEqual(vim.current.window.cursor, (13, -3))
def suite():
return unittest.TestLoader().loadTestsFromTestCase(EditStructureTestCase)
|
#!/usr/bin/env python
from tabulate import tabulate
from sul.remote_integrity.models import Server, Checksum, Event
class Inspector:
def __init__(self, args):
self.args = args
def run(self):
if self.args.list == "servers":
return self._list_servers()
if self.args.list == "checksums":
return self._list_checksums()
if self.args.list == "events":
return self._list_events()
def _list_servers(self):
data = Server.query().all()
print(tabulate([d.values() for d in data], Server.keys(), "grid"))
def _list_checksums(self):
data = Checksum.query().all()
print(tabulate([d.values() for d in data], Checksum.keys(), "grid"))
def _list_events(self):
data = Event.query().all()
print(tabulate([d.values() for d in data], Event.keys(), "grid"))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.