blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
281
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 6
116
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 313
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 18.2k
668M
⌀ | star_events_count
int64 0
102k
| fork_events_count
int64 0
38.2k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 107
values | src_encoding
stringclasses 20
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 4
6.02M
| extension
stringclasses 78
values | content
stringlengths 2
6.02M
| authors
listlengths 1
1
| author
stringlengths 0
175
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a3dbfd07afbe0391b734bd981eafc9d8ac28b53b | 64fe4fcaeb71b5e4d448abed92e03bebd838b1a2 | /Models/Form_Factors.py | b5559332237915e69187a8b4ae18f8282d5fa4c1 | []
| no_license | Caster89/Scattering_Analysis | ea2ddbd9311f0beebae6f083a37d843f44d3d00b | 2bd14efb2d1bb6c1af5173a8ed98b668dbfc4673 | refs/heads/master | 2021-01-19T16:04:41.322316 | 2017-12-17T16:22:46 | 2017-12-17T16:22:46 | 88,247,591 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 10,797 | py | from config import _AvlbUnits, _UnitsSymbols,_UnitsConv, _AvlbSASFit, _AvlbSASFitDic, _AvlbSASFitDicInv, _lmfitModels, _lmfitModelFunctions, _lmfitDistFunctions
import numpy as np
import scipy as sp
from scipy import signal
from scipy import interpolate
from scipy.integrate import dblquad, tplquad
import logging
import lmfit
from Distributions import *
from lmfit import minimize, Parameter, report_fit
try:
import gmpy2
from gmpy2 import mpz,mpq,mpfr,mpc
except:
gmpy2 = None
from decimal import Decimal
print 'The Schultz fitting function is optimized by using the GMPY2 module to\
deal with the large numbers required. The module was not found, so Decimal will\
be used instead, but the calculations will be slower.'
"""
The distriutions presented here can be found in Polydispersity analysis of scattering
data from self-assembled systems. Phy. Rev. A,45, 2428-2438.
DOI: 10.1103/PhysRevA.45.2428
"""
def single_gauss_spheres(q,R_av = 1,sigma = 1,I0 = 1,bckg=0):
"""sing_gauss_spheres: calculates the scattering pattern of an assembly of
spheres which have a Gaussian number density size distribution.
Args
q (numpy.array): the array containg the list of q-values for which to
calculate the scattering
R_av (int): the mean of the size distribution. Defaults to 1
sigma (int): the dispersion of the distribution. Defaults to 1
I0 (int): the prefactor which includes information on the scattering
length density (SLD) and the concentration of particles. Defaults
to 1
bckg (int): the background value to use in case the background is
not perfectly subtracted. Defaults to 0.
Returns
the scattering curve which has the same size as q
"""
P_q=(4.*np.pi/q**3.)**2.*((1.+q**2.*(R_av**2.+sigma**2.))/2.+\
(((-1.+q**2*R_av**2)/2.-3./2.*q**2.*sigma**2.-2.*q**4.*sigma**4.)*\
np.cos(2.*q*R_av)-q*R_av*(1.+2.*q**2.*sigma**2.)*\
np.sin(2.*q*R_av))*np.exp(-2.*q**2.*sigma**2))
return np.array(10**(I0)*P_q+bckg)
def double_gauss_spheres(q,R1_av = 1,sigma1 = 1, R2_av = 1, sigma2 = 1, I0 = 1,ratio=0.5, bckg = 0):
"""double_gauss_spheres: calculates the scattering pattern of an assembly of
spheres which have a bimodal Gaussian size distribution.
Args
q (numpy.array): the array containg the list of q-values for which to
calculate the scattering
R_av1 (int): the mean of the size distribution of the first
peak. Defaults to 1
sigma1 (int): the dispersion of the first peak. Defaults to 1
R_av2 (int): the mean of the size distribution of the second
peak. Defaults to 1
sigma2 (int): the dispersion of the second peak. Defaults to 1
I0 (int): the prefactor which includes information on the scattering
length density (SLD) and the concentration of particles. Defaults
to 1
ratio (int): the ratio between the first and the second peak. Defaults
to 0.5
bckg (int): the background value to use in case the background is
not perfectly subtracted. Defaults to 0.
Returns
the scattering curve which has the same size as q
"""
return np.array(ratio*single_gauss_spheres(q,R1_av, sigma1,I0,0)+(1-ratio)*single_gauss_spheres(q,R2_av, sigma2,I0,0)+bckg)
def single_schultz_spheres(q, R_av = 1, Z = 50, I0 = 1, bckg = 0 ):
"""sing_schultz_spheres: calculates the scattering pattern of an assembly of
spheres which have a Schultz-Zimm size distribution. Devimal is used to
ensure that the for vey monodisperse distributions (Z>171) the values are not
rounded off to inf. The integrated function is taken from 'Analysis of small
angle neutron scattering spectra from pplydisperse interacting colloids',
DOI: 10.1063/1.446055
sigma = R_av/(Z+1)^0.5
?The Z parameter is defined as z = 1 / sigma^2.?
The definition was taken from:
ttp://sasfit.ingobressler.net/manual/Schultz-Zimm
"""
if gmpy2 is None:
aD = np.array([Decimal((Z+1.)/(qq*R_av)) for qq in q])
"""
numpy trigonometric functions do not support Decimal, therefore the
numpy array is created on the spot using float numbers and transforming
them to Decimal after the calculation
"""
a = (Z+1.)/(q*R_av)
p1 = Decimal(8. * np.pi**2 * R_av**6 * (Z+1)**(-6)) * aD**Decimal(Z+7.)
G11 = aD**Decimal(-(Z+1.)) - (Decimal(4.)+aD**2)**(Decimal(-(Z+1.)/2.)) *\
np.array([Decimal(np.cos((Z+1) * np.arctan(2./aa))) for aa in a])
G12 = Decimal((Z+2.)*(Z+1.)) * (aD**Decimal(-(Z+3.)) + (Decimal(4.) + aD**Decimal(2.))**Decimal(-(Z+3.)/2.) *\
np.array([Decimal(np.cos((Z+3)*np.arctan(2./aa))) for aa in a]))
G13 = Decimal(2.*(Z+1.)) * (Decimal(4.) + aD**2.)**Decimal(-(Z+2.)/2) *\
np.array([Decimal(np.sin((Z+2.)*np.arctan(2./aa))) for aa in a])
G1 = G11+G12-G13
returnVal = Decimal(10**I0)*p1*G1+Decimal(bckg)
else:
a = np.array([mpfr((Z+1.)/(qq*R_av)) for qq in q])
a2 = a**2
a2_1 = (mpfr(4.)+a2)
R_av = mpfr(R_av)
Z = mpfr(Z)
I0 = mpfr(I0)
bckg = mpfr(bckg)
"""
numpy trigonometric functions do not support Decimal, therefore the
numpy array is created on the spot using float numbers and transforming
them to Decimal after the calculation
"""
p1 = 8. * np.pi**2 * R_av**6 * (Z+1)**(-6) * a**(Z+7.)
#G11 = a**-(Z+1.) - (4.+a**2)**(-(Z+1.)/2.) *\
#np.array([gmpy2.cos((Z+1) * gmpy2.atan(2./aa)) for aa in a])
G11 = a**-(Z+1.) - a2_1**(-(Z+1.)/2.) *\
np.array([gmpy2.cos((Z+1) * gmpy2.atan(2./aa)) for aa in a])
G12 = (Z+2.)*(Z+1.) * (a**-(Z+3.) + a2_1**(-(Z+3.)/2.) *\
np.array([gmpy2.cos((Z+3)*gmpy2.atan(2./aa)) for aa in a]))
G13 = 2.*(Z+1.) * a2_1**(-(Z+2.)/2) *\
np.array([gmpy2.sin((Z+2.)*gmpy2.atan(2./aa)) for aa in a])
G1 = G11+G12-G13
returnVal = 10**I0*p1*G1+bckg
returnVal = np.array(returnVal.astype(np.float64))
#print 'Single_schultz calculated with:\nR_av:{} Z:{} I0:{}'.format(R_av, Z, I0)
#print 'length is:{}, of which nan: {}'.format(len(returnVal), np.sum(np.isnan(returnVal)))
return returnVal
def single_schultz_spheres_old(q,R_av = 1,Z = 1, I0 = 1, bckg = 0):
"""sing_schultz_spheres: calculates the scattering pattern of an assembly of
spheres which have a Flory schultz size distribution. the Z parameter is
defined as z = 1 / sigma^2. THe definistion was taken forom:
ttp://sasfit.ingobressler.net/manual/Schultz-Zimm
Args
q (numpy.array): the array containg the list of q-values for which to
calculate the scattering
R_av (int): the mean of the size distribution. Defaults to 1
Z (int): the dispersion of the distribution. For a Flory-Schultz
distribution the Z parameter is defined as Z = 1/sigma^2.
Defaults to 1
I0 (int): the prefactor which includes information on the scattering
length density (SLD) and the concentration of particles. Defaults
to 1
bckg (int): the background value to use in case the background is
not perfectly subtracted. Defaults to 0.
Returns
the scattering curve which has the same size as q
"""
a = (Z+1.)/(q*R_av)
P_q = 8.*np.pi**2*R_av**6*(Z-1.)**(-6.)*a**(Z+7.)*(a**(-(Z+1.))- \
(4.+a**2)**(-(Z+1.)/2)*np.cos((Z+1.)*np.arctan(2/a)) + \
(Z+2.)*(Z+1.)*(a**(-Z-3.)+(4+a**2)**((-Z-3.)/2.)*np.cos((Z+3.)*np.arctan(2./a))) - \
2.*(Z+1.)*(4.+a**2.)**(-(Z+2.)/2.)*np.sin((Z+2.)*np.arctan(2./a)))
return np.nan_to_num(10**I0*P_q+bckg)
def double_schultz_spheres(q, R1_av = 1, Z1 = 1, R2_av = 1,Z2 = 1, I0 = 1, ratio = 0.5, bckg = 0):
"""double_schultz_spheres: calculates the scattering pattern of an assembly of
spheres which have a bimodal Flory Schultz distribution.
Args
q (numpy.array): the array containg the list of q-values for which to
calculate the scattering
R_av1 (int): the mean of the size distribution of the first
peak. Defaults to 1
Z1 (int): the dispersion of the first distribution. For a Flory-Schultz
distribution the Z parameter is defined as Z = 1/sigma^2.
Defaults to 1
R_av2 (int): the mean of the size distribution of the second
peak. Defaults to 1
Z2 (int): the dispersion of the second distribution. For a Flory-Schultz
distribution the Z parameter is defined as Z = 1/sigma^2.
Defaults to 1
I0 (int): the pre-factor which includes information on the scattering
length density (SLD) and the concentration of particles. Defaults
to 1
ratio (int): the ratio between the first and the second peak. Defaults
to 0.5
bckg (int): the background value to use in case the background is
not perfectly subtracted. Defaults to 0.
Returns
the scattering curve which has the same size as q
"""
return np.nan_to_num(ratio*single_schultz_spheres(q,R1_av,Z1,I0,0)+(1-ratio)*single_schultz_spheres(q,R2_av,Z2,I0,0)+bckg)
def monodisperse_cube(q, L=1, I0=1, bckg = 0):
"""
http://www.sasview.org/sasview/user/models/model_functions.html#rectangularprismmodel
:param q: the wavevector, vna be aither a number of a numpy array
:param L: The side of the cube
:param I0: The prefactor in front of the form factor
:param bckg: The constant background to sum
:return: The complete, integrated form factor for a cube
"""
def FF(theta, phi):
A = q*L/2.*np.cos(theta)
B = q*L/2.*np.sin(theta)*np.sin(phi)
C = q*L/2.*np.sin(theta)*np.cos(phi)
return np.sinc(A)*np.sinc(B)+np.sinc(C)
return 10**I0*dblquad(FF, 0, np.pi/2., lambda x: 0, lambda x: np.pi/2.0)[0]+bckg
def single_gaussian_cube(q, L_av=1, sigma=1, I0=1, bckg = 0):
def FF(theta,phi,L):
A = q*L/2.*np.cos(theta)
B = q*L/2.*np.sin(theta)*np.sin(phi)
C = q*L/2.*np.sin(theta)*np.cos(phi)
return single_gauss_distribution(L,L_av,sigma,1)*np.sinc(A)*np.sinc(B)+np.sinc(C)
l_min = max(0,L_av-4*(L_av*sigma))
l_max = L_av+4*(L_av*sigma)
return 10**I0*tplquad(FF, 0, np.pi/2., lambda x: 0, lambda x: np.pi/2.0,)[0]+bckg
| [
"="
]
| = |
8817c6128119450c0fb5105ac6f32c7a7f78a753 | c57ce2b6aab3350dedf10942f893b86951076fbc | /link/mongo/__init__.py | 092c06d8331b86e49a60f2566d0767944c5d7e11 | []
| no_license | linkdd/link.mongo | b1c5e66b0519aecdb9d5832d1f74ea1f4e7e8bd4 | 3cd9d264a4e0e44726767385add871c67af2928c | refs/heads/master | 2020-04-10T20:34:23.847508 | 2016-09-02T21:48:22 | 2016-09-02T21:48:22 | 60,538,453 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 77 | py | # -*- coding: utf-8 -*-
__version__ = '0.10'
CONF_BASE_PATH = 'link/mongo'
| [
"[email protected]"
]
| |
91b336f5e46675f4257c72221a97a55902640453 | d9d87bc977bd930a7ab52cb8e4ccabc16b778380 | /phenom/utils/QNMdata/__init__.py | 82a6b87906d667dc1aee526928224b75dfdbb075 | [
"MIT"
]
| permissive | LBJ-Wade/phenom_gw_waveform | 077844a9a3db0241395cc49e846671d33dd62ef6 | 2c705e6ba85510c573d23dca8be4456665d29edf | refs/heads/master | 2023-08-11T17:19:12.814330 | 2020-05-29T08:22:29 | 2020-05-29T08:22:29 | 412,703,992 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 48 | py | # from phenom.utils.QNMdata.QNMphenomd import *
| [
"[email protected]"
]
| |
d2095f9693d06f64b5b692ae4ac6a001a0efe756 | 7ccce5e822fe204308ba25275cd94dc2232b9041 | /osha/process.py | 899ae2b1c34b13fb0254ac1cd6652431e7980a4a | []
| no_license | ecgonzalez/rp_test_develop | a84f94e9ceef5e48dfd6280301b78f748f0bf90f | 84fce90bd695fbff2651f598af9f0454b2f9707d | refs/heads/master | 2020-04-24T01:09:57.945291 | 2019-02-20T03:38:54 | 2019-02-20T03:38:54 | 171,589,287 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,001 | py | #https://www.osha.gov/pls/imis/establishment.html
import requests
from bs4 import BeautifulSoup
import os
import psycopg2
import time
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from time import sleep
import re
import hashlib
import threading
import json
class inicio():
def extractextra(self,itemll):
with open('activities.json', 'r') as filer:
objextra = json.load(filer)
valit = str(objextra['name'])
linkitemm = objextra['activities']
if str(valit) == str(itemll):
print("runing process console intern")
for ittt in linkitemm:
print("ARRAY ___________________________________________________________"+str(ittt))
def extract(self,item, nnum,obj,doc,itobj):
browser = webdriver.Chrome()
gralcount = 0
objetlistint = 0
browser.get('https://www.osha.gov/pls/imis/establishment.html')
esta1 = browser.find_element_by_xpath('//*[@id="estab_search"]/div[3]/div/select')
esta = Select(browser.find_element_by_xpath('//*[@id="estab_search"]/div[3]/div/select'))
esta.select_by_value(item)
browser.implicitly_wait(15)
nameesta = esta1.get_attribute('value')
print("????????????????????????"+str(nameesta))
if nnum == 1:
self.fin1 = False
if nnum == 2:
self.fin2 = False
if nnum == 3:
self.fin3 = False
if nnum == 4:
self.fin4 = False
select2 = browser.find_element_by_xpath('//*[@id="estab_search"]/div[6]/div/label[2]/input')
select2.click()
submit = browser.find_element_by_xpath('//*[@id="estab_search"]/div[10]/div/button[1]')
submit.click()
browser.implicitly_wait(15)
dataint = {}
valres = True
try:
#aa = browser.find_element_by_xpath('//*[@id="maincontain"]/div/div[4]/table/tbody/tr[1]/td[3]/a')
#alink = aa.get_attribute('href')
#print("LINK"+str(alink))
spags = browser.find_element_by_xpath('//*[@id="maincontain"]/div/div[2]/div[2]/div')
tspags = spags.text
tspagss = str(tspags).replace("Results 1 - 20 of","")
tspagss = str(tspagss).strip()
itspags = 0
itspags = int(tspagss)/20
litspags = str(itspags).split(".")
lenlistpags = int(len(litspags))
if lenlistpags != 0:
itspags = int(litspags[0])
else:
itspags = int(itspags)
iitspags = 0
iitspags = int(tspagss)%20
if iitspags == 0:
itspags -= 1
listalinks = []
print("pags "+str(tspagss))
print("pags mod "+str(iitspags))
print("pags dov "+str(itspags))
try:
obj['results_int'] = str(tspagss)
obj['name']= str(item)
obj['verresult']= True
obj['activities'] = []
obj['results_insert'] = ""
print(str(obj))
obj1 = {}
valinobj1 = ""
with open(doc, 'r') as filerin1:
obj1 = json.load(filerin1)
with open(doc, 'w') as filewin1:
obj1['offices'].append(obj)
json.dump(obj1, filewin1,indent=5)
except Exception as errins:
print("Error json :")
try:
for itera in range(1,int(itspags)):
print("_____________________________________________________PAGS")
print("Iterando pag: "+str(itera))
ac = browser.find_element_by_xpath('//*[@id="maincontain"]/div/div[2]/div[3]')
acc = ac.find_elements_by_tag_name('a')
objetlistint = int(int(item)-2)
acarray = []
for itarray1 in acc:
acarray.append(itarray1)
objurllist = acarray[-1]
ulrefpags = acarray[-1].get_attribute('href')
print("LINK: "+str(ulrefpags)+str(acarray[-1].text))
print("LLLLL"+str(acarray))
ab = browser.find_element_by_xpath('//*[@id="maincontain"]/div/div[4]/table/tbody')
aslink = ab.find_elements_by_tag_name('tr')
conitins = 0
for itaslink in aslink:
itlink = itaslink.find_elements_by_tag_name('td')
tdlinkit = itlink[2]
aitlink = tdlinkit.find_element_by_tag_name('a')
rlinks = aitlink.get_attribute('href')
print(rlinks)
listalinks.append(str(rlinks))
conitins += 1
itobj += 1
gralcount += 1
objfin = {}
objfin1 = {
"offices":[
]
}
valinobj = ""
#obj['activities'].append(str(rlinks))
with open(doc, 'r') as filerin:
objfin = json.load(filerin)
for iteobjin in objfin['offices']:
valinobj = iteobjin['name']
if str(valinobj) == str(item):
iteobjin['activities'] = listalinks
iteobjin['results_insert'] = str(itobj)
with open(doc, 'w') as filewin:
objfin1['offices'].append(iteobjin)
json.dump(objfin1, filewin,indent=5)
objurllist.click()
print("Siguiente pag....."+str(itera)+" | HILO | "+str(nnum)+"| OBJETO |"+str(item))
browser.quit()
if nnum == 1:
self.fin1 = True
if nnum == 2:
self.fin2 = True
if nnum == 3:
self.fin3 = True
if nnum == 4:
self.fin4 = True
print("______________________________________________")
print("Fin Hilo "+str(nnum)+" |Objeto: "+str(item))
except Exception as ecxint:
print("Error interno Funcion Extract :"+str(ecxint))
#res = requests.get(str(alink))
#bsobjeto = BeautifulSoup(res.text, 'html.parser')
#objins = bsobjeto.find('div',{'id':'maincontain'})
#div1 =objins.find_all('div')
#divu = div1[0]
#div2 =divu.find_all('div')
#divd = div1[1]
#tablef = divu.find_all('table')
#trs = tablef[2].find_all('tr')
#print(str(trs))
except Exception as excext:
#print("No hay resultados"+str(excext))
print("Fin Hilo "+str(nnum)+" |Objeto: "+str(item)+" | Sin Resultados")
obj2 = {}
obj2['results_int'] = str("0")
obj2['name']= str(item)
obj2['verresult']= False
obj2['activities'] = []
obj2['results_insert'] = "0"
print(str(obj2))
with open(doc, 'r') as filero:
objfie = json.load(filero)
with open(doc, 'w') as filewio:
objfie['offices'].append(obj2)
json.dump(objfie, filewio,indent=5)
def __init__(self):
self.hilo1val = False
self.hilo2val = False
self.hilo3val = False
self.hilo4val = False
listate = ["1050210","213100","625100","317900","950615","1032100","521100","950411","950412","418100","418200","111100","521400","625400","213400","950647","316100","112900",
"625700","215600","1032300","830100","418300","830300","1032500","111500","213600","950600","316400","524200","521700","950654","522000","522300","418500","522500","111700",
"150900","626000","950681","626300","830500","728100","316120","523900","627500","627410","830600","336000","524530","636900","950613","419000","950612","950625","418800",
"934000","934010","316700","112000","214500","951510","950661","950662","936300","626600","626700","551702","551701","551800","523100","751910","419400","419700","728500",
"452110","950667","950665","522900","936500","627100","950635","214700","950641","627400","627510","523300","152300","215000","213900","352400","352460","352450","352440",
"352430","352420","352410","552600","552651","552652","570100","523400","523700","552700","729710","418600","950624","950644","453730","453710","453720","253400","253410",
"253420","953220","953210","253600","253620","253690","253680","253670","253660","253650","253610","253630","253640","420100","953200","653510","316300","134000","453700",
"1054195","1054115","1054194","1054119","1054114","1054196","1054116","1054112","1054191","1054192","1054111","1054190","1054118","1054199","1054100","1054113","1054193",
"936100","950614","570110","627700","728900","257210","257220","257230","257200","257240","257250","257260","214200","524500","317000","936400","317500","1032700","950673",
"950671","950674","950672","112300","215300","420300","950623","100000","1000000","200000","300000","400000","500000","600000","700000","800000","900000","950621","950651",
"830700","625500","625410","950633","950653","936200","950632","935000","950611","950631","418400","830400","111400","454510","454520","112600","729300","215800","454723",
"454733","454713","454726","454716","454725","454735","454715","454736","454724","454734","454714","454721","454731","454711","454722","454732","454712","420600","216000",
"454700","524700","854910","355110","355117","355125","355114","355124","355112","355121","355111","355123","355118","355122","355116","355115","257800","257810","257820",
"950643","950652","155010","355100","355126","1055310","1055320","1055360","1055330","1055340","1055370","1055380","1055350","1055300","729700","317700","317300","570120","855610"]
self.userdbr = os.environ['USERRISKD']
self.hostdbr = os.environ['HOSTRISKD']
self.portbdr = os.environ['PORTRISKD']
self.passdbr = os.environ['PSERISKD']
self.baser = os.environ['BDRISKD']
self.userdbl = os.environ['LOCALU']
self.hostdbl = os.environ['LOCALH']
self.portbdl = os.environ['LOCALP']
self.passdbl = os.environ['LOCALC']
self.basel = os.environ['LOCALD']
self.fin1 = False
self.fin2 = False
self.fin3 = False
self.fin4 = False
self.ccone = "RISK"
print("2222")
if self.ccone == "RISK":
try:
self.con = psycopg2.connect("dbname="+self.baser+" user="+self.userdbr+" host="+self.hostdbr+" password="+self.passdbr+"")
print("DB Amazon Risk Connection")
except:
#print("Conexion:"+str(con))
print("Unable to connect to the Amazon database")
quit()
else:
if self.ccone == "LOCAL":
try:
self.con = psycopg2.connect("dbname="+self.basel+" user="+self.userdbl+" host="+self.hostdbl+" password="+self.passdbl+"")
print("DB LocalHost Connection")
except:
#print("Conexion:"+str(con))
print("Unable to connect to LocalHost database")
quit()
else:
print("No se configuro conexion")
contadortt = 0
for iteml in listate:
contadortt += 1
if contadortt <= 4:
print(str(iteml))
if contadortt ==1:
obj1 = {
'results_int': "",
'name': "",
'verresult': True,
'activities': [],
'results_insert' : ""}
itobj1 = 0
hilo1 = threading.Thread(target=self.extract,args=(iteml,contadortt,obj1,'activitiesthread1.json',itobj1,))
print("Arrancando Hilo 1")
obj11 = str(iteml)
if contadortt ==2:
obj2 = {
'results_int': "",
'name': "",
'verresult': True,
'activities': [],
'results_insert' : ""}
itobj2 = 0
hilo2 = threading.Thread(target=self.extract, args=(iteml,contadortt,obj2,'activitiesthread2.json',itobj2,))
print("Arrancando Hilo 2")
obj21 = str(iteml)
if contadortt ==3:
obj3 = {
'results_int': "",
'name': "",
'verresult': True,
'activities': [],
'results_insert' : ""}
itobj3 = 0
hilo3 = threading.Thread(target=self.extract, args=(iteml,contadortt,obj3,'activitiesthread3.json',itobj3,))
print("Arrancando Hilo 3")
obj31 = str(iteml)
if contadortt ==4:
obj4 = {
'results_int': "",
'name': "",
'verresult': True,
'activities': [],
'results_insert' : ""}
itobj4 = 0
hilo4 = threading.Thread(target=self.extract, args=(iteml,contadortt,obj4,'activitiesthread4.json',itobj4,))
print("Arrancando Hilo 4")
obj41 = str(iteml)
hilo1.start()
hilo2.start()
hilo3.start()
hilo4.start()
hilo1.join()
hilo1in = threading.Thread(target=self.extractextra, args=(obj11,))
hilo2.join()
hilo2in = threading.Thread(target=self.extractextra, args=(obj21,))
hilo3.join()
hilo3in = threading.Thread(target=self.extractextra, args=(obj31,))
hilo4.join()
hilo4in = threading.Thread(target=self.extractextra, args=(obj41,))
contadortt = 0
#valialive = hilo1.is_alive()
#if valialive == True:
# hilo1.join()
#valialive2 = hilo2.is_alive()
#if valialive2 == True:
# hilo2.join()
#valialive3 = hilo3.is_alive()
#if valialive3 == True:
# hilo3.join()
#valialive4 = hilo4.is_alive()
#if valialive4 == True:
# hilo4.join()
#contadortt = 0
#print("Next"+str(pagnext))
if __name__ == '__main__':
inicio()
| [
"[email protected]"
]
| |
2c813b8ed7eea428debed8bc6625f01ed1762759 | 0c5925a28299ca2149f4ca7c09cc666da947db04 | /prometheus/tornadoWS/ws_client.py | 95e4f9bc54e4d0d4340870194cf1c29b714a14ef | [
"Apache-2.0"
]
| permissive | sonata-nfv/son-monitor | cdc006908429edf790e3f5ea3236c7e39752f49f | a48a15d0190f20913cf313ca28e3daabb3753285 | refs/heads/master | 2023-01-12T16:28:06.992353 | 2020-01-09T13:56:37 | 2020-01-09T13:56:37 | 53,059,670 | 5 | 9 | Apache-2.0 | 2022-12-27T14:57:57 | 2016-03-03T15:07:03 | Python | UTF-8 | Python | false | false | 846 | py | #!/usr/bin/python
## sudo pip install websocket-client
import websocket
import urllib2, json
import thread
import time
def on_message(ws, message):
print message
def on_error(ws, error):
print str(error)
def on_close(ws):
print "### closed ###"
def on_open(ws):
pass
if __name__ == "__main__":
msg = urllib2.urlopen("http://localhost:8888/new/?metric=vm_mem_perc¶ms=['lakis','pakis']").read()
ws_id = json.loads(msg)
print(msg)
time.sleep(1)
websocket.enableTrace(True)
url = "ws://localhost:8888/ws/"+ws_id['name_space']
print url
ws = websocket.WebSocketApp(url,
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()
| [
"[email protected]"
]
| |
5a36613e9b97b721caae632c80b847e119156d04 | f5c44c434585fef2118b072379e9cc3edb2b694e | /webcam_utils.py | 1127d87f51aaa128f6e1a8e62ff07827f1bf01f6 | []
| no_license | TeraMind244/SmartParkingDeepLearning | 993b2bf0bbda8c23a6784aea4c246d6861a9bab8 | 5b3640e0a63472565f961c7b597374d34a5aeb2e | refs/heads/master | 2020-04-29T12:16:12.758966 | 2020-01-22T06:03:56 | 2020-01-22T06:03:56 | 176,112,208 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,272 | py | #import numpy as np
import cv2
import image_utils as iu
import sys
import read_data as rd
#import opencv_identifier as opencv
# %%
data = rd.get_data()
# %%
def capture_video(source):
cap = cv2.VideoCapture(source)
# Check if camera opened successfully
if (cap.isOpened() == False):
print("Unable to read camera feed")
# Default resolutions of the frame are obtained.The default resolutions are system dependent.
# We convert the resolutions from float to integer.
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
# Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file.
out = None
capturing = False
while(True):
ret, frame = cap.read()
if ret == True:
# Write the frame into the file 'output.avi'
if capturing:
out.write(frame)
cv2.putText(frame, 'CAPTURING', (30, 35),
cv2.FONT_HERSHEY_SIMPLEX,
0.7, (255, 255, 255), 2)
# Display the resulting frame
cv2.imshow('frame', frame)
# Press Q on keyboard to stop recording
keypress = cv2.waitKey(1) & 0xFF
if keypress == ord('q'):
break
if keypress == ord('c'):
if out == None:
out = cv2.VideoWriter('outpy.avi', cv2.VideoWriter_fourcc(
'M', 'J', 'P', 'G'), 10, (frame_width, frame_height))
if capturing:
capturing = False
else:
capturing = True
# Break the loop
else:
break
# When everything done, release the video capture and video write objectsqq
if out != None:
out.release()
cap.release()
# Closes all the frames
cv2.destroyAllWindows()
# %%
def show_video():
cap = cv2.VideoCapture('outpy.avi')
import time
while(cap.isOpened()):
ret, frame = cap.read()
if ret == True:
# Display the resulting frame
cv2.imshow('frame', frame)
time.sleep(0.1)
# Press Q on keyboard to stop recording
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Break the loop
else:
break
# When everything done, release the video capture and video write objectsqq
cap.release()
# Closes all the frames
cv2.destroyAllWindows()
# %%
def write_a_random_frame():
cap = cv2.VideoCapture('outpy.avi')
count = 0
while(cap.isOpened()):
ret, frame = cap.read()
if ret == True:
count += 1
if count == 20:
filename = "webcam_test/test_frame.jpg"
cv2.imwrite(filename, frame)
# Break the loop
else:
break
# When everything done, release the video capture and video write objectsqq
cap.release()
# Closes all the frames
cv2.destroyAllWindows()
# %%
def write_random_frames():
cap = cv2.VideoCapture('outpy.avi')
# import time
count = 0
while(cap.isOpened()):
ret, frame = cap.read()
if ret == True:
if count % 10 == 0:
filename = "webcam_test/test_frame_%d.jpg" %count
# print(filename)
cv2.imwrite(filename, frame)
count += 1
# Break the loop
else:
break
# When everything done, release the video capture and video write objectsqq
cap.release()
# %%
def save_images_for_cnn(camId):
images = iu.get_all_image('webcam_test/*.jpg')
img_count = 0
for image in images:
test_image = image
cam_data = next(filter(lambda cam: cam['cam_id'] == camId, data['cam_list']))
roi_array = cam_data['roi_array']
pt_array = cam_data['pt_array']
kernel_size = cam_data['kernel_size']
gap = cam_data['gap']
lane_list = cam_data['lane_list']
roi_image = iu.select_region(test_image, roi_array)
rotated_image, transform_matrix = iu.four_point_transform(roi_image, pt_array)
resized_image, scale = iu.resize(rotated_image, 360)
blurred_image = iu.blur(resized_image, kernel_size=kernel_size)
edge_image = iu.detect_edges(blurred_image)
lines = iu.hough_lines(edge_image)
line_image, cleaned = iu.draw_lines(resized_image, lines)
blocked_image, rects = iu.identify_blocks(resized_image, cleaned)
parking_slot_image, spot_dict = iu.draw_parking(resized_image, rects, gap=gap, lane_list=lane_list)
iu.save_images_for_cnn(resized_image, spot_dict, folder_name='for_cnn/', img_count=img_count)
img_count += 1
# %%
def main():
# print command line arguments
mode = sys.argv[1]
if mode == "capture":
capture_video()
return
if mode == "show-video":
show_video()
return
if mode == "save-a-frame":
write_a_random_frame()
return
if mode == "save-frames":
write_random_frames()
return
if mode == "get-training-data":
save_images_for_cnn()
return
print("You provided wrong input! Please try again!")
source = sys.argv[1]
capture_video(int(source))
write_a_random_frame()
if __name__ == "__main__":
main()
# %%%
#cap1 = cv2.VideoCapture(1)
#cap2 = cv2.VideoCapture(2)
#
#while(True):
# ret, frame1 = cap1.read()
# ret, frame2 = cap2.read()
#
# if ret == True:
#
# # Display the resulting frame
# cv2.imshow('frame1', frame1)
# cv2.imshow('frame2', frame2)
#
# # Press Q on keyboard to stop recording
# keypress = cv2.waitKey(1) & 0xFF
# if keypress == ord('q'):
# break
#
# # Break the loop
# else:
# break
#
#cap1.release()
#cap2.release()
#
## Closes all the frames
#cv2.destroyAllWindows()
# %%
#capture_video(2)
#show_video()
#write_a_random_frame()
#write_random_frames()
#save_images_for_cnn(2)
| [
"[email protected]"
]
| |
013ad4f8eb3ba02e9770aed25cb228d75475289b | 6f05f7d5a67b6bb87956a22b988067ec772ba966 | /data/test/python/030d0c5ebc377ba768e6bdbbc82d64a6cfcbb7d4__main__.py | 030d0c5ebc377ba768e6bdbbc82d64a6cfcbb7d4 | [
"MIT"
]
| permissive | harshp8l/deep-learning-lang-detection | 93b6d24a38081597c610ecf9b1f3b92c7d669be5 | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | refs/heads/master | 2020-04-07T18:07:00.697994 | 2018-11-29T23:21:23 | 2018-11-29T23:21:23 | 158,597,498 | 0 | 0 | MIT | 2018-11-21T19:36:42 | 2018-11-21T19:36:41 | null | UTF-8 | Python | false | false | 580 | py | import gi
from ghue.controller import Controller
from ghue.device.hue import HueDeviceManager
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib
import phue
from .application import GHueApplication
if __name__ == '__main__':
GLib.set_application_name("Philips Hue")
controller = Controller()
hue_device_manager = HueDeviceManager(bridge=phue.Bridge('philips-hue.local'),
controller=controller)
controller.add_device_manager(hue_device_manager)
app = GHueApplication(controller)
app.run(None)
| [
"[email protected]"
]
| |
7dbd29bffaf83e67b074c5c83a4b80d149c08915 | b5d6219ac738ed05485439540f38d63d21694c51 | /DAT/ED6_DT01/T0401.帕赛尔农场.py | a052afc836ef6b9539bb500251eaf69edad7b457 | []
| no_license | otoboku/ED6-FC-Steam-CN | f87ffb2ff19f9272b986fa32a91bec360c21dffa | c40d9bc5aaea9446dda27e7b94470d91cb5558c5 | refs/heads/master | 2021-01-21T02:37:30.443986 | 2015-11-27T07:41:41 | 2015-11-27T07:41:41 | 46,975,651 | 1 | 0 | null | 2015-11-27T10:58:43 | 2015-11-27T10:58:42 | null | UTF-8 | Python | false | false | 55,311 | py | from ED6ScenarioHelper import *
def main():
# 帕赛尔农场
CreateScenaFile(
FileName = 'T0401 ._SN',
MapName = 'Rolent',
Location = 'T0401.x',
MapIndex = 13,
MapDefaultBGM = "ed60084",
Flags = 0,
EntryFunctionIndex = 0xFFFF,
Reserved = 0,
IncludedScenario = [
'',
'',
'',
'',
'',
'',
'',
''
],
)
BuildStringList(
'@FileName', # 8
'魔兽', # 9
'魔兽', # 10
'魔兽', # 11
'魔兽', # 12
'魔兽', # 13
'魔兽', # 14
'魔兽', # 15
'缇欧', # 16
'维鲁', # 17
'查儿', # 18
'弗兰兹', # 19
'汉娜', # 20
'艾丝蒂尔', # 21
'牛', # 22
'牛', # 23
'目标用摄像机', # 24
'米尔西街道方向', # 25
)
DeclEntryPoint(
Unknown_00 = 21000,
Unknown_04 = 0,
Unknown_08 = 24000,
Unknown_0C = 4,
Unknown_0E = 0,
Unknown_10 = 0,
Unknown_14 = 8000,
Unknown_18 = -10000,
Unknown_1C = 0,
Unknown_20 = 0,
Unknown_24 = 0,
Unknown_28 = 3000,
Unknown_2C = 262,
Unknown_30 = 45,
Unknown_32 = 0,
Unknown_34 = 360,
Unknown_36 = 0,
Unknown_38 = 0,
Unknown_3A = 13,
InitScenaIndex = 0,
InitFunctionIndex = 0,
EntryScenaIndex = 0,
EntryFunctionIndex = 1,
)
DeclEntryPoint(
Unknown_00 = 21000,
Unknown_04 = 0,
Unknown_08 = 24000,
Unknown_0C = 4,
Unknown_0E = 0,
Unknown_10 = 0,
Unknown_14 = 8000,
Unknown_18 = -10000,
Unknown_1C = 0,
Unknown_20 = 0,
Unknown_24 = 0,
Unknown_28 = 3000,
Unknown_2C = 262,
Unknown_30 = 45,
Unknown_32 = 0,
Unknown_34 = 360,
Unknown_36 = 0,
Unknown_38 = 0,
Unknown_3A = 13,
InitScenaIndex = 0,
InitFunctionIndex = 0,
EntryScenaIndex = 0,
EntryFunctionIndex = 1,
)
AddCharChip(
'ED6_DT09/CH10100 ._CH', # 00
'ED6_DT09/CH10101 ._CH', # 01
'ED6_DT07/CH02480 ._CH', # 02
'ED6_DT07/CH01060 ._CH', # 03
'ED6_DT07/CH01070 ._CH', # 04
'ED6_DT07/CH01020 ._CH', # 05
'ED6_DT07/CH01030 ._CH', # 06
'ED6_DT07/CH00100 ._CH', # 07
'ED6_DT07/CH01710 ._CH', # 08
'ED6_DT07/CH00107 ._CH', # 09
'ED6_DT07/CH00102 ._CH', # 0A
)
AddCharChipPat(
'ED6_DT09/CH10100P._CP', # 00
'ED6_DT09/CH10101P._CP', # 01
'ED6_DT07/CH02480P._CP', # 02
'ED6_DT07/CH01060P._CP', # 03
'ED6_DT07/CH01070P._CP', # 04
'ED6_DT07/CH01020P._CP', # 05
'ED6_DT07/CH01030P._CP', # 06
'ED6_DT07/CH00100P._CP', # 07
'ED6_DT07/CH01710P._CP', # 08
'ED6_DT07/CH00107P._CP', # 09
'ED6_DT07/CH00102P._CP', # 0A
)
DeclNpc(
X = 0,
Z = 0,
Y = 0,
Direction = 0,
Unknown2 = 0,
Unknown3 = 0,
ChipIndex = 0x0,
NpcIndex = 0x181,
InitFunctionIndex = -1,
InitScenaIndex = -1,
TalkFunctionIndex = -1,
TalkScenaIndex = -1,
)
DeclNpc(
X = 0,
Z = 0,
Y = 0,
Direction = 0,
Unknown2 = 0,
Unknown3 = 2,
ChipIndex = 0x1,
NpcIndex = 0x181,
InitFunctionIndex = -1,
InitScenaIndex = -1,
TalkFunctionIndex = -1,
TalkScenaIndex = -1,
)
DeclNpc(
X = 0,
Z = 0,
Y = 0,
Direction = 0,
Unknown2 = 0,
Unknown3 = 2,
ChipIndex = 0x1,
NpcIndex = 0x181,
InitFunctionIndex = -1,
InitScenaIndex = -1,
TalkFunctionIndex = -1,
TalkScenaIndex = -1,
)
DeclNpc(
X = 0,
Z = 0,
Y = 0,
Direction = 0,
Unknown2 = 0,
Unknown3 = 2,
ChipIndex = 0x1,
NpcIndex = 0x181,
InitFunctionIndex = -1,
InitScenaIndex = -1,
TalkFunctionIndex = -1,
TalkScenaIndex = -1,
)
DeclNpc(
X = 0,
Z = 0,
Y = 0,
Direction = 0,
Unknown2 = 0,
Unknown3 = 2,
ChipIndex = 0x0,
NpcIndex = 0x181,
InitFunctionIndex = -1,
InitScenaIndex = -1,
TalkFunctionIndex = -1,
TalkScenaIndex = -1,
)
DeclNpc(
X = 0,
Z = 0,
Y = 0,
Direction = 0,
Unknown2 = 0,
Unknown3 = 2,
ChipIndex = 0x0,
NpcIndex = 0x181,
InitFunctionIndex = -1,
InitScenaIndex = -1,
TalkFunctionIndex = -1,
TalkScenaIndex = -1,
)
DeclNpc(
X = 0,
Z = 0,
Y = 0,
Direction = 0,
Unknown2 = 0,
Unknown3 = 2,
ChipIndex = 0x0,
NpcIndex = 0x181,
InitFunctionIndex = -1,
InitScenaIndex = -1,
TalkFunctionIndex = -1,
TalkScenaIndex = -1,
)
DeclNpc(
X = -75800,
Z = 0,
Y = 2400,
Direction = 0,
Unknown2 = 0,
Unknown3 = 0,
ChipIndex = 0x2,
NpcIndex = 0x101,
InitFunctionIndex = 0,
InitScenaIndex = 2,
TalkFunctionIndex = -1,
TalkScenaIndex = -1,
)
DeclNpc(
X = 1730,
Z = 0,
Y = 24300,
Direction = 0,
Unknown2 = 0,
Unknown3 = 0,
ChipIndex = 0x3,
NpcIndex = 0x101,
InitFunctionIndex = 0,
InitScenaIndex = 2,
TalkFunctionIndex = -1,
TalkScenaIndex = -1,
)
DeclNpc(
X = 1730,
Z = 0,
Y = 23000,
Direction = 0,
Unknown2 = 0,
Unknown3 = 0,
ChipIndex = 0x4,
NpcIndex = 0x101,
InitFunctionIndex = 0,
InitScenaIndex = 2,
TalkFunctionIndex = -1,
TalkScenaIndex = -1,
)
DeclNpc(
X = -75800,
Z = 0,
Y = 2400,
Direction = 0,
Unknown2 = 0,
Unknown3 = 0,
ChipIndex = 0x5,
NpcIndex = 0x101,
InitFunctionIndex = 0,
InitScenaIndex = 2,
TalkFunctionIndex = -1,
TalkScenaIndex = -1,
)
DeclNpc(
X = -75800,
Z = 0,
Y = 2400,
Direction = 0,
Unknown2 = 0,
Unknown3 = 0,
ChipIndex = 0x6,
NpcIndex = 0x101,
InitFunctionIndex = 0,
InitScenaIndex = 2,
TalkFunctionIndex = -1,
TalkScenaIndex = -1,
)
DeclNpc(
X = 0,
Z = 0,
Y = 0,
Direction = 0,
Unknown2 = 0,
Unknown3 = 0,
ChipIndex = 0x7,
NpcIndex = 0x101,
InitFunctionIndex = -1,
InitScenaIndex = -1,
TalkFunctionIndex = -1,
TalkScenaIndex = -1,
)
DeclNpc(
X = 39010,
Z = 600,
Y = 23300,
Direction = 180,
Unknown2 = 0,
Unknown3 = 8,
ChipIndex = 0x8,
NpcIndex = 0x105,
InitFunctionIndex = 0,
InitScenaIndex = 2,
TalkFunctionIndex = 0,
TalkScenaIndex = 4,
)
DeclNpc(
X = 40980,
Z = 600,
Y = 23300,
Direction = 180,
Unknown2 = 0,
Unknown3 = 8,
ChipIndex = 0x8,
NpcIndex = 0x105,
InitFunctionIndex = 0,
InitScenaIndex = 2,
TalkFunctionIndex = 0,
TalkScenaIndex = 4,
)
DeclNpc(
X = 0,
Z = 0,
Y = 0,
Direction = 0,
Unknown2 = 0,
Unknown3 = 0,
ChipIndex = 0x0,
NpcIndex = 0x80,
InitFunctionIndex = -1,
InitScenaIndex = -1,
TalkFunctionIndex = -1,
TalkScenaIndex = -1,
)
DeclNpc(
X = 23910,
Z = 30,
Y = 66820,
Direction = 0,
Unknown2 = 0,
Unknown3 = 0,
ChipIndex = 0x0,
NpcIndex = 0xFF,
InitFunctionIndex = -1,
InitScenaIndex = -1,
TalkFunctionIndex = -1,
TalkScenaIndex = -1,
)
DeclEvent(
X = 41200,
Y = -500,
Z = 21800,
Range = 48300,
Unknown_10 = 0x3E8,
Unknown_14 = 0x4FB0,
Unknown_18 = 0x0,
Unknown_1C = 11,
)
DeclEvent(
X = 34900,
Y = -1000,
Z = 33900,
Range = 43000,
Unknown_10 = 0x3E8,
Unknown_14 = 0xAD70,
Unknown_18 = 0x0,
Unknown_1C = 12,
)
DeclEvent(
X = 38700,
Y = -500,
Z = 37000,
Range = 35200,
Unknown_10 = 0x3E8,
Unknown_14 = 0xB4DC,
Unknown_18 = 0x0,
Unknown_1C = 29,
)
DeclEvent(
X = 26000,
Y = -500,
Z = 26000,
Range = 19000,
Unknown_10 = 0x3E8,
Unknown_14 = 0x7148,
Unknown_18 = 0x0,
Unknown_1C = 30,
)
DeclEvent(
X = 42360,
Y = -500,
Z = 15300,
Range = 50900,
Unknown_10 = 0x3E8,
Unknown_14 = 0x490C,
Unknown_18 = 0x0,
Unknown_1C = 31,
)
DeclEvent(
X = 35830,
Y = -1000,
Z = 26140,
Range = 34270,
Unknown_10 = 0x3E8,
Unknown_14 = 0x5D2A,
Unknown_18 = 0x0,
Unknown_1C = 13,
)
DeclEvent(
X = 39000,
Y = -500,
Z = 42000,
Range = 1000,
Unknown_10 = 0x3E8,
Unknown_14 = 0x0,
Unknown_18 = 0x40,
Unknown_1C = 18,
)
DeclEvent(
X = 22700,
Y = -500,
Z = 25300,
Range = 1000,
Unknown_10 = 0x3E8,
Unknown_14 = 0x0,
Unknown_18 = 0x40,
Unknown_1C = 19,
)
DeclEvent(
X = 46100,
Y = -500,
Z = 15200,
Range = 1000,
Unknown_10 = 0x3E8,
Unknown_14 = 0x0,
Unknown_18 = 0x40,
Unknown_1C = 20,
)
ScpFunction(
"Function_0_486", # 00, 0
"Function_1_552", # 01, 1
"Function_2_58D", # 02, 2
"Function_3_5A3", # 03, 3
"Function_4_5DE", # 04, 4
"Function_5_5E4", # 05, 5
"Function_6_5EA", # 06, 6
"Function_7_61D", # 07, 7
"Function_8_62C", # 08, 8
"Function_9_643", # 09, 9
"Function_10_857", # 0A, 10
"Function_11_861", # 0B, 11
"Function_12_92E", # 0C, 12
"Function_13_C37", # 0D, 13
"Function_14_F16", # 0E, 14
"Function_15_1178", # 0F, 15
"Function_16_119B", # 10, 16
"Function_17_11A3", # 11, 17
"Function_18_11B8", # 12, 18
"Function_19_11CC", # 13, 19
"Function_20_11E0", # 14, 20
"Function_21_11F4", # 15, 21
"Function_22_225A", # 16, 22
"Function_23_229E", # 17, 23
"Function_24_230E", # 18, 24
"Function_25_2323", # 19, 25
"Function_26_2338", # 1A, 26
"Function_27_234D", # 1B, 27
"Function_28_238A", # 1C, 28
"Function_29_2392", # 1D, 29
"Function_30_2424", # 1E, 30
"Function_31_24A2", # 1F, 31
"Function_32_2534", # 20, 32
"Function_33_2A62", # 21, 33
"Function_34_2A6A", # 22, 34
)
def Function_0_486(): pass
label("Function_0_486")
SetChrFlags(0x9, 0x40)
SetChrFlags(0xA, 0x40)
SetChrFlags(0xB, 0x40)
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 4)), scpexpr(EXPR_END)), "loc_4C7")
OP_A2(0x0)
OP_A3(0x1)
OP_A3(0x2)
ClearChrFlags(0x9, 0x8)
ClearChrFlags(0x9, 0x80)
SetChrPos(0x9, 39000, 0, 42000, 270)
OP_43(0x9, 0x3, 0x0, 0x2)
label("loc_4C7")
Switch(
(scpexpr(EXPR_PUSH_VALUE_INDEX, 0x0), scpexpr(EXPR_END)),
(1, "loc_4DB"),
(102, "loc_53A"),
(103, "loc_53A"),
(SWITCH_DEFAULT, "loc_551"),
)
label("loc_4DB")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 0)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_52A")
SetMapFlags(0x400000)
ClearMapFlags(0x1)
OP_6D(28000, 0, 41000, 0)
OP_6C(200000, 0)
OP_6B(5000, 0)
SetChrFlags(0x101, 0x80)
SetChrFlags(0x102, 0x80)
FadeToBright(3000, 0)
Event(0, 6)
Jump("loc_537")
label("loc_52A")
FadeToBright(3000, 0)
Event(0, 9)
label("loc_537")
Jump("loc_551")
label("loc_53A")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 1)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 2)), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 4)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_54E")
Event(0, 14)
label("loc_54E")
Jump("loc_551")
label("loc_551")
Return()
# Function_0_486 end
def Function_1_552(): pass
label("Function_1_552")
Jc((scpexpr(EXPR_PUSH_VALUE_INDEX, 0x29), scpexpr(EXPR_PUSH_LONG, 0x393), scpexpr(EXPR_EQU), scpexpr(EXPR_PUSH_VALUE_INDEX, 0x3), scpexpr(EXPR_PUSH_LONG, 0x0), scpexpr(EXPR_EQU), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_570")
OP_4F(0x1, (scpexpr(EXPR_PUSH_LONG, 0xF), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
label("loc_570")
OP_16(0x2, 0xFA0, 0xFFFE8518, 0xFFFE8900, 0x30004)
OP_1B(0x4, 0x0, 0x22)
OP_22(0x1CF, 0x0, 0x64)
Return()
# Function_1_552 end
def Function_2_58D(): pass
label("Function_2_58D")
Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_5A2")
OP_99(0xFE, 0x0, 0x7, 0x5DC)
Jump("Function_2_58D")
label("loc_5A2")
Return()
# Function_2_58D end
def Function_3_5A3(): pass
label("Function_3_5A3")
Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_5DD")
OP_95(0xFE, 0xFFFFFC18, 0x0, 0x0, 0x258, 0x640)
OP_95(0xFE, 0x3E8, 0x0, 0x0, 0x258, 0x640)
Jump("Function_3_5A3")
label("loc_5DD")
Return()
# Function_3_5A3 end
def Function_4_5DE(): pass
label("Function_4_5DE")
OP_22(0x190, 0x0, 0x64)
Return()
# Function_4_5DE end
def Function_5_5E4(): pass
label("Function_5_5E4")
OP_22(0x191, 0x0, 0x64)
Return()
# Function_5_5E4 end
def Function_6_5EA(): pass
label("Function_6_5EA")
EventBegin(0x0)
Sleep(500)
OP_43(0x0, 0x2, 0x0, 0x8)
OP_43(0x0, 0x1, 0x0, 0x7)
OP_6C(225000, 9000)
FadeToDark(1000, 0, -1)
OP_0D()
NewScene("ED6_DT01/T0411 ._SN", 1, 0, 0)
IdleLoop()
Return()
# Function_6_5EA end
def Function_7_61D(): pass
label("Function_7_61D")
Sleep(2000)
OP_6B(3000, 9000)
Return()
# Function_7_61D end
def Function_8_62C(): pass
label("Function_8_62C")
Sleep(2000)
OP_6D(16700, 0, 18800, 9000)
Return()
# Function_8_62C end
def Function_9_643(): pass
label("Function_9_643")
SetMapFlags(0x400000)
ClearMapFlags(0x1)
OP_6D(26700, 0, 14500, 0)
OP_6C(225000, 0)
OP_6B(3500, 0)
SetChrPos(0x101, 28000, 0, 14200, 90)
SetChrPos(0x102, 25350, 570, 15020, 90)
EventBegin(0x0)
OP_43(0x0, 0x1, 0x0, 0xA)
OP_8E(0x102, 0x6E28, 0x0, 0x3C28, 0x5DC, 0x0)
Sleep(1000)
ChrTalk(
0x101,
"#004F哇~天色已经这么暗了。\x02",
)
CloseMessageWindow()
TurnDirection(0x0, 0x1, 400)
ChrTalk(
0x101,
(
"#000F喂,约修亚。\x01",
"该怎么巡逻比较好呢?\x02",
)
)
CloseMessageWindow()
TurnDirection(0x1, 0x0, 400)
ChrTalk(
0x102,
(
"#010F是呀……\x02\x03",
"#010F屋子周围、田地里、牲口棚\x01",
"和温室都要巡视一遍吧。\x02\x03",
"#010F这样整个农场都能照顾到了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#006F嗯,知道了。\x02\x03",
"#001F好的~我们出发吧!\x02",
)
)
CloseMessageWindow()
OP_44(0x101, 0xFF)
OP_44(0x102, 0xFF)
EventEnd(0x0)
ClearMapFlags(0x400000)
Return()
# Function_9_643 end
def Function_10_857(): pass
label("Function_10_857")
OP_6B(3000, 4500)
Return()
# Function_10_857 end
def Function_11_861(): pass
label("Function_11_861")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 1)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_92D")
OP_A2(0x231)
OP_28(0x2, 0x1, 0x10)
EventBegin(0x0)
OP_6D(48090, 480, 19550, 3000)
Fade(1000)
SetChrPos(0x101, 43760, 280, 21120, 135)
SetChrPos(0x102, 42420, 370, 21480, 135)
OP_6D(43760, 280, 21120, 0)
OP_6C(315000, 0)
Sleep(1000)
OP_62(0x101, 0x0, 2000, 0x18, 0x1B, 0xFA, 0x0)
Sleep(2000)
OP_63(0x101)
ChrTalk(
0x101,
"#000F……魔兽好像也不在这里。\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
"#010F是啊,到别的地方看看吧。\x02",
)
CloseMessageWindow()
EventEnd(0x0)
label("loc_92D")
Return()
# Function_11_861 end
def Function_12_92E(): pass
label("Function_12_92E")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 3)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_C36")
OP_A2(0x233)
OP_28(0x2, 0x1, 0x40)
EventBegin(0x0)
OP_6D(39020, -300, 38660, 2000)
Fade(1000)
SetChrPos(0x101, 42390, -40, 37580, 270)
SetChrPos(0x102, 42500, 30, 38900, 270)
OP_6D(40310, -300, 38250, 0)
OP_6C(135000, 0)
Sleep(1000)
ChrTalk(
0x101,
(
"#000F#4P真安静啊~……\x01",
"只能听到虫子的声音。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#010F#4P看样子那些魔兽\x01",
"还没有进入菜园里面。\x02\x03",
"#010F是因为我们在巡逻吗?\x02",
)
)
CloseMessageWindow()
TurnDirection(0x101, 0x102, 400)
ChrTalk(
0x101,
(
"#501F#4P对了,约修亚。\x01",
"你小时候有没有听过这种说法?\x02\x03",
"#501F就是说,\x01",
"婴儿是从白菜地里长出来的。\x02",
)
)
CloseMessageWindow()
TurnDirection(0x102, 0x101, 400)
ChrTalk(
0x102,
(
"#017F#4P又突然说这些了……\x02\x03",
"#010F我倒是听说过\x01",
"是长着银色翅膀的天使送过来的……\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#501F#4P嗯……不同的地方说法也不同啊。\x02\x03",
"#501F…………………………\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#010F#4P…………………………\x02\x03",
"#010F我们继续巡逻吧?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
"#000F#4P嗯。\x02",
)
CloseMessageWindow()
EventEnd(0x0)
label("loc_C36")
Return()
# Function_12_92E end
def Function_13_C37(): pass
label("Function_13_C37")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 1)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 2)), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 4)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_F15")
OP_A2(0x233)
OP_A2(0x234)
OP_28(0x2, 0x1, 0x80)
EventBegin(0x0)
SetMapFlags(0x400000)
ClearMapFlags(0x1)
SetChrPos(0x9, 24900, 50, 30180, 86)
ClearChrFlags(0x9, 0x8)
ClearChrFlags(0x9, 0x80)
OP_43(0x9, 0x3, 0x0, 0x2)
ChrTalk(
0x101,
"#004F啊……\x02",
)
CloseMessageWindow()
Sleep(100)
Fade(1000)
SetChrPos(0x101, 35400, 350, 25540, 267)
SetChrPos(0x102, 35360, 340, 24500, 261)
def lambda_CCC():
label("loc_CCC")
TurnDirection(0xFE, 0x9, 0)
OP_48()
Jump("loc_CCC")
QueueWorkItem2(0x101, 1, lambda_CCC)
def lambda_CDD():
label("loc_CDD")
TurnDirection(0xFE, 0x9, 0)
OP_48()
Jump("loc_CDD")
QueueWorkItem2(0x102, 1, lambda_CDD)
OP_0D()
def lambda_CEF():
OP_6D(34540, 80, 30070, 3000)
ExitThread()
QueueWorkItem(0x101, 2, lambda_CEF)
def lambda_D07():
OP_6C(45000, 4000)
ExitThread()
QueueWorkItem(0x101, 3, lambda_D07)
def lambda_D17():
OP_8E(0x9, 0x8656, 0x46, 0x758A, 0xBB8, 0x0)
ExitThread()
QueueWorkItem(0x9, 1, lambda_D17)
WaitChrThread(0x9, 0x1)
OP_62(0x9, 0x0, 2000, 0x2, 0x7, 0x50, 0x1)
OP_22(0x27, 0x0, 0x64)
TurnDirection(0x9, 0x101, 200)
Sleep(1000)
OP_95(0x9, 0x0, 0x0, 0x0, 0x320, 0x2EE0)
OP_22(0x194, 0x0, 0x64)
ChrTalk(
0x9,
"咪呜!\x02",
)
CloseMessageWindow()
OP_62(0x9, 0x0, 2000, 0x28, 0x2B, 0x64, 0x3)
OP_22(0x81, 0x0, 0x64)
OP_8E(0x9, 0xAF64, 0x118, 0x9042, 0x2EE0, 0x0)
SetChrPos(0x9, 39000, 0, 42000, 270)
ChrTalk(
0x101,
"#004F啊,逃跑了!\x02",
)
CloseMessageWindow()
OP_44(0x101, 0xFF)
OP_44(0x102, 0xFF)
OP_8E(0x101, 0x89C6, 0x140, 0x6EAA, 0x1388, 0x0)
OP_8C(0x101, 45, 400)
OP_44(0x101, 0xFF)
ChrTalk(
0x101,
"#005F喂!给我等一下!\x02",
)
CloseMessageWindow()
OP_8E(0x102, 0x8994, 0x136, 0x68CE, 0x7D0, 0x0)
TurnDirection(0x102, 0x101, 400)
ChrTalk(
0x102,
(
"#012F气息还没有消失……\x02\x03",
"#012F那只魔兽应该还在菜园里面。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#009F哼哼,正合我意……\x02\x03",
"#005F绝对要抓住它!\x02",
)
)
CloseMessageWindow()
OP_44(0x101, 0xFF)
OP_44(0x102, 0xFF)
OP_44(0x9, 0xFF)
OP_A2(0x0)
OP_A3(0x1)
OP_A3(0x2)
Sleep(50)
EventEnd(0x4)
ClearMapFlags(0x400000)
OP_43(0x9, 0x3, 0x0, 0x2)
label("loc_F15")
Return()
# Function_13_C37 end
def Function_14_F16(): pass
label("Function_14_F16")
OP_A2(0x233)
OP_A2(0x234)
OP_28(0x2, 0x1, 0x80)
EventBegin(0x0)
SetMapFlags(0x400000)
ClearMapFlags(0x1)
SetChrPos(0x9, 24100, 0, 54800, 0)
ClearChrFlags(0x9, 0x8)
ClearChrFlags(0x9, 0x80)
OP_43(0x9, 0x3, 0x0, 0x2)
OP_90(0x101, 0x3E8, 0x0, 0x0, 0x7D0, 0x0)
TurnDirection(0x101, 0x9, 400)
ChrTalk(
0x101,
"#004F啊……\x02",
)
CloseMessageWindow()
OP_43(0x101, 0x1, 0x0, 0x11)
OP_43(0x102, 0x1, 0x0, 0x11)
OP_43(0x9, 0x1, 0x0, 0xF)
OP_8E(0x9, 0x5BCC, 0x0, 0x9C40, 0xBB8, 0x0)
OP_62(0x9, 0x0, 2000, 0x2, 0x7, 0x50, 0x1)
OP_22(0x27, 0x0, 0x64)
TurnDirection(0x9, 0x101, 200)
Sleep(1000)
OP_95(0x9, 0x0, 0x0, 0x0, 0x320, 0x2EE0)
OP_22(0x194, 0x0, 0x64)
ChrTalk(
0x9,
"咪呜!\x02",
)
CloseMessageWindow()
OP_43(0x101, 0x1, 0x0, 0x10)
OP_62(0x9, 0x0, 2000, 0x28, 0x2B, 0x64, 0x3)
OP_22(0x81, 0x0, 0x64)
OP_8E(0x9, 0x7148, 0x0, 0x7148, 0x2EE0, 0x0)
SetChrPos(0x9, 39000, 0, 42000, 270)
ChrTalk(
0x101,
"#004F啊,逃跑了!\x02",
)
CloseMessageWindow()
OP_8E(0x101, 0x55BE, 0x0, 0x98F8, 0x1388, 0x0)
OP_8C(0x101, 135, 400)
ChrTalk(
0x101,
"#005F喂!给我等一下!\x02",
)
CloseMessageWindow()
OP_44(0x102, 0xFF)
TurnDirection(0x102, 0x101, 400)
ChrTalk(
0x102,
(
"#012F气息还没有消失……\x02\x03",
"#012F那只魔兽应该还在菜园里面。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#009F哼哼,正合我意……\x02\x03",
"#005F绝对要抓住它!\x02",
)
)
CloseMessageWindow()
OP_44(0x101, 0xFF)
OP_44(0x102, 0xFF)
OP_44(0x9, 0xFF)
OP_A2(0x0)
OP_A3(0x1)
OP_A3(0x2)
EventEnd(0x0)
ClearMapFlags(0x400000)
OP_43(0x9, 0x3, 0x0, 0x2)
Return()
# Function_14_F16 end
def Function_15_1178(): pass
label("Function_15_1178")
OP_6D(24100, 0, 47800, 1000)
OP_6D(23500, 0, 40000, 4000)
Return()
# Function_15_1178 end
def Function_16_119B(): pass
label("Function_16_119B")
OP_69(0x101, 0x3E8)
Return()
# Function_16_119B end
def Function_17_11A3(): pass
label("Function_17_11A3")
Jc((scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_END)), "loc_11B7")
TurnDirection(0xFE, 0x9, 0)
OP_48()
Jump("Function_17_11A3")
label("loc_11B7")
Return()
# Function_17_11A3 end
def Function_18_11B8(): pass
label("Function_18_11B8")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 4)), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_11CB")
Call(0, 21)
Call(0, 29)
label("loc_11CB")
Return()
# Function_18_11B8 end
def Function_19_11CC(): pass
label("Function_19_11CC")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 4)), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_11DF")
Call(0, 21)
Call(0, 30)
label("loc_11DF")
Return()
# Function_19_11CC end
def Function_20_11E0(): pass
label("Function_20_11E0")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 2)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 4)), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_11F3")
Call(0, 21)
Call(0, 31)
label("loc_11F3")
Return()
# Function_20_11E0 end
def Function_21_11F4(): pass
label("Function_21_11F4")
EventBegin(0x0)
ClearMapFlags(0x1)
TurnDirection(0x0, 0x9, 0)
TurnDirection(0x1, 0x9, 0)
OP_62(0x9, 0x0, 2000, 0x2, 0x7, 0x50, 0x1)
OP_22(0x27, 0x0, 0x64)
OP_22(0x194, 0x0, 0x64)
OP_44(0x9, 0xFF)
OP_95(0x9, 0x0, 0x0, 0x0, 0x320, 0x2EE0)
TurnDirection(0x9, 0x0, 400)
ChrTalk(
0x101,
(
"#006F太好了,终于抓住了!\x02\x03",
"#006F这次一定要给你们点颜色看看!\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#012F接下来才是动真格的。\x01",
"切记不可疏忽大意啊!\x02",
)
)
CloseMessageWindow()
Battle(0x393, 0x0, 0x0, 0x2, 0xFF)
Switch(
(scpexpr(EXPR_PUSH_VALUE_INDEX, 0x3), scpexpr(EXPR_END)),
(1, "loc_1310"),
(3, "loc_1315"),
(0, "loc_1316"),
(SWITCH_DEFAULT, "loc_2259"),
)
label("loc_1310")
OP_B4(0x0)
Jump("loc_2259")
label("loc_1315")
Return()
label("loc_1316")
EventBegin(0x0)
FadeToBright(2000, 0)
ClearChrFlags(0xA, 0x8)
ClearChrFlags(0xA, 0x80)
OP_43(0xA, 0x3, 0x0, 0x2)
ClearChrFlags(0xB, 0x8)
ClearChrFlags(0xB, 0x80)
OP_43(0xB, 0x3, 0x0, 0x2)
ClearChrFlags(0xC, 0x8)
ClearChrFlags(0xC, 0x80)
OP_43(0xC, 0x3, 0x0, 0x2)
ClearChrFlags(0xD, 0x8)
ClearChrFlags(0xD, 0x80)
OP_43(0xD, 0x3, 0x0, 0x2)
ClearChrFlags(0xE, 0x8)
ClearChrFlags(0xE, 0x80)
OP_43(0xE, 0x3, 0x0, 0x2)
SetChrPos(0xC, 33150, 0, 16129, 225)
SetChrPos(0xD, 33390, 0, 15210, 270)
SetChrPos(0xE, 32990, 0, 14530, 315)
SetChrPos(0x12, 29700, 0, 16600, 0)
SetChrPos(0xF, 29000, 0, 14200, 0)
SetChrPos(0x10, 28100, 0, 15300, 0)
SetChrPos(0x13, 28300, 0, 16400, 0)
SetChrPos(0x11, 29300, 0, 17100, 0)
SetChrPos(0x101, 30920, 0, 15780, 270)
SetChrPos(0x102, 30630, 0, 14650, 315)
TurnDirection(0xF, 0xE, 0)
TurnDirection(0x10, 0xD, 0)
TurnDirection(0x11, 0xE, 0)
TurnDirection(0x12, 0x101, 0)
TurnDirection(0x13, 0x102, 0)
OP_44(0x12, 0xFF)
OP_44(0xF, 0xFF)
OP_44(0x10, 0xFF)
OP_44(0x13, 0xFF)
OP_44(0x11, 0xFF)
OP_44(0xC, 0xFF)
OP_44(0xD, 0xFF)
OP_44(0xE, 0xFF)
OP_43(0x11, 0x3, 0x0, 0x17)
OP_6D(30470, 0, 16280, 0)
OP_6C(315000, 0)
OP_6B(3000, 0)
OP_6B(2800, 3000)
OP_22(0x194, 0x0, 0x64)
ChrTalk(
0xC,
"咪呜~~……\x02",
)
CloseMessageWindow()
OP_43(0x10, 0x3, 0x0, 0x16)
OP_22(0x194, 0x0, 0x64)
ChrTalk(
0xE,
"咪~~……\x02",
)
CloseMessageWindow()
ChrTalk(
0x12,
"哎呀,真不愧是游击士啊。\x02",
)
CloseMessageWindow()
ChrTalk(
0x12,
(
"这么轻松就把\x01",
"这群敏捷的家伙抓住了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#000F#4P嘿嘿,过奖了。\x02\x03",
"#000F话说回来,该怎么处理它们呢?\x02",
)
)
CloseMessageWindow()
FadeToDark(300, 0, 100)
RunExpression(0x0, (scpexpr(EXPR_PUSH_LONG, 0x0), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
OP_4F(0x28, (scpexpr(EXPR_PUSH_LONG, 0x18), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
Menu(
0,
10,
10,
0,
(
"『应该不会再做坏事了吧……』\x01", # 0
"『……非要把它们杀掉不可吗?』\x01", # 1
)
)
MenuEnd(0x0)
OP_4F(0x28, (scpexpr(EXPR_PUSH_LONG, 0xFFFF), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
OP_5F(0x0)
OP_56(0x0)
FadeToBright(300, 0)
Switch(
(scpexpr(EXPR_GET_RESULT, 0x0), scpexpr(EXPR_END)),
(0, "loc_1688"),
(1, "loc_188C"),
(SWITCH_DEFAULT, "loc_1A26"),
)
label("loc_1688")
ChrTalk(
0x101,
(
"#000F#4P已经教训过它们了,\x01",
"应该不会再做坏事了吧……\x02",
)
)
CloseMessageWindow()
TurnDirection(0x102, 0x101, 400)
ChrTalk(
0x102,
(
"#012F#3P艾丝蒂尔……\x01",
"你怎么能感情用事呢?\x02\x03",
"#012F我们不是为了打倒魔兽而来的吗?\x02",
)
)
CloseMessageWindow()
TurnDirection(0x101, 0x102, 400)
ChrTalk(
0x101,
"#003F#4P可、可是……\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#015F#3P而且,我们这次是\x01",
"代替父亲来执行任务的……\x02\x03",
"#015F如果下次再出现同类的事件,\x01",
"你打算怎么向协会交代?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#007F#4P唔唔……\x01",
"说的也是……\x02",
)
)
CloseMessageWindow()
Jump("loc_1A26")
label("loc_188C")
ChrTalk(
0x101,
"#003F#4P……非要把它们杀掉不可吗?\x02",
)
CloseMessageWindow()
TurnDirection(0x102, 0x101, 400)
ChrTalk(
0x102,
(
"#012F#3P这当然无庸置疑了,艾丝蒂尔。\x01",
"我们是为了打倒魔兽而来的。\x02",
)
)
CloseMessageWindow()
TurnDirection(0x101, 0x102, 400)
ChrTalk(
0x101,
"#003F#4P可、可是……\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#015F#3P游击士的使命\x01",
"是保卫百姓、维护正义……\x02\x03",
"#015F绝对不能存有同情魔兽的心态。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#007F#4P唔唔……\x01",
"说的也是……\x02",
)
)
CloseMessageWindow()
Jump("loc_1A26")
label("loc_1A26")
ChrTalk(
0xF,
"……………………\x02",
)
CloseMessageWindow()
ChrTalk(
0xF,
(
"算了算了,\x01",
"反正受害的只有我们家种的菜而已……\x02",
)
)
CloseMessageWindow()
ChrTalk(
0xF,
"就放了它们吧?\x02",
)
CloseMessageWindow()
ChrTalk(
0x13,
"是啊。\x02",
)
CloseMessageWindow()
ChrTalk(
0x13,
(
"反正它们已经得到应有的教训,\x01",
"这件事就算了吧。\x02",
)
)
CloseMessageWindow()
TurnDirection(0x101, 0x10, 400)
ChrTalk(
0x101,
"#501F#4P缇欧,阿姨……\x02",
)
CloseMessageWindow()
TurnDirection(0x102, 0x13, 400)
ChrTalk(
0x102,
"#012F#3P但是……\x02",
)
CloseMessageWindow()
ChrTalk(
0x12,
"……我也反对杀掉它们。\x02",
)
CloseMessageWindow()
ChrTalk(
0x12,
(
"它们虽然是魔兽,\x01",
"却也和我们生活在同一片土地上啊。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x12,
(
"有时候还是要互相忍让的,\x01",
"大家和睦相处不是很好吗。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x12,
(
"约修亚……\x01",
"这次就放了它们吧?\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#015F#3P……………………\x02\x03",
"#010F……我明白了。\x02\x03",
"#010F既然受害者都同意放过它们,\x01",
"那我也没有反对的理由。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x12,
(
"真是抱歉,\x01",
"还让你们特地来这里。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x12,
(
"我们以后也要加固栅栏,\x01",
"想办法避免再遇到这样的事情。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
"#001F#4P那就这样决定了。\x02",
)
CloseMessageWindow()
TurnDirection(0x101, 0xD, 400)
TurnDirection(0x102, 0xD, 400)
ChrTalk(
0x101,
(
"#006F就是这么回事,\x01",
"你们还不感谢大家?\x02",
)
)
CloseMessageWindow()
OP_8E(0x101, 0x7AD0, 0x0, 0x3DA4, 0x7D0, 0x0)
Sleep(100)
SetChrFlags(0x101, 0x800)
SetChrChipByIndex(0x101, 10)
OP_22(0x1F4, 0x0, 0x64)
OP_99(0x101, 0x0, 0xC, 0x7D0)
OP_44(0x11, 0xFF)
OP_44(0x10, 0xFF)
ChrTalk(
0x101,
"#005F再有下次的话就送你们下地狱!\x02",
)
CloseMessageWindow()
OP_62(0xC, 0x0, 2000, 0x28, 0x2B, 0x64, 0x3)
OP_95(0xC, 0x0, 0x0, 0x0, 0x320, 0x2EE0)
TurnDirection(0xC, 0x101, 0)
OP_62(0xD, 0x0, 2000, 0x28, 0x2B, 0x64, 0x3)
OP_95(0xD, 0x0, 0x0, 0x0, 0x320, 0x2EE0)
TurnDirection(0xD, 0x101, 0)
OP_62(0xE, 0x0, 2000, 0x28, 0x2B, 0x64, 0x3)
OP_95(0xE, 0x0, 0x0, 0x0, 0x320, 0x2EE0)
TurnDirection(0xE, 0x101, 0)
OP_22(0x194, 0x0, 0x64)
ChrTalk(
0xC,
"咪嘎~~!!\x02",
)
CloseMessageWindow()
Sleep(100)
OP_A2(0x3)
SetChrPos(0xC, 0, 0, 0, 0)
SetChrPos(0x9, 33150, 0, 16129, 0)
OP_22(0x81, 0x0, 0x64)
OP_43(0x9, 0x1, 0x0, 0x18)
Sleep(200)
OP_43(0xB, 0x2, 0x0, 0x1B)
SetChrPos(0xD, 0, 0, 0, 0)
SetChrPos(0xA, 33390, 0, 15210, 0)
OP_22(0x81, 0x0, 0x64)
OP_43(0xA, 0x1, 0x0, 0x19)
Sleep(200)
SetChrPos(0xE, 0, 0, 0, 0)
SetChrPos(0xB, 32990, 0, 14530, 0)
OP_22(0x81, 0x0, 0x64)
OP_43(0xB, 0x1, 0x0, 0x1A)
Sleep(1000)
OP_A3(0x3)
OP_44(0x9, 0xFF)
OP_44(0xA, 0xFF)
OP_44(0xB, 0xFF)
OP_44(0xC, 0xFF)
OP_44(0xD, 0xFF)
OP_44(0xE, 0xFF)
TurnDirection(0x101, 0xB, 0)
Sleep(2000)
TurnDirection(0x12, 0x101, 400)
ChrTalk(
0x12,
(
"好了,终于解决了。\x01",
"已经这么晚了,都该睡了。\x02",
)
)
CloseMessageWindow()
OP_43(0xF, 0x1, 0x0, 0x1C)
OP_43(0x10, 0x1, 0x0, 0x1C)
OP_43(0x11, 0x1, 0x0, 0x1C)
OP_43(0x13, 0x1, 0x0, 0x1C)
OP_44(0x101, 0xFF)
OP_51(0x101, 0x8, (scpexpr(EXPR_PUSH_LONG, 0x0), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
ClearChrFlags(0x101, 0x800)
SetChrChipByIndex(0x101, 65535)
TurnDirection(0x101, 0x10, 400)
TurnDirection(0x102, 0x12, 400)
ChrTalk(
0x12,
"你们也留下好好休息吧。\x02",
)
CloseMessageWindow()
ChrTalk(
0x101,
"#001F#4P好~\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
"#010F#3P又给你们添麻烦了。\x02",
)
CloseMessageWindow()
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 5)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_221E")
OP_2B(0x2, 0x2)
Jump("loc_222B")
label("loc_221E")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 6)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_222B")
OP_2B(0x2, 0x1)
label("loc_222B")
OP_A2(0x239)
OP_28(0x2, 0x1, 0x800)
OP_28(0x2, 0x1, 0x1000)
OP_28(0x2, 0x4, 0x10)
OP_20(0x5DC)
FadeToDark(1000, 0, -1)
OP_0D()
OP_21()
NewScene("ED6_DT01/T0411 ._SN", 1, 0, 0)
IdleLoop()
label("loc_2259")
Return()
# Function_21_11F4 end
def Function_22_225A(): pass
label("Function_22_225A")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 3)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_229D")
OP_95(0xFE, 0x0, 0x0, 0x0, 0x190, 0xBB8)
Sleep(300)
OP_95(0xFE, 0x0, 0x0, 0x0, 0x190, 0xBB8)
Sleep(2500)
Jump("Function_22_225A")
label("loc_229D")
Return()
# Function_22_225A end
def Function_23_229E(): pass
label("Function_23_229E")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 3)), scpexpr(EXPR_EQUZ), scpexpr(EXPR_END)), "loc_230D")
Sleep(3000)
OP_8F(0xFE, 0x733C, 0x0, 0x4394, 0x12C, 0x0)
Sleep(2000)
OP_8F(0xFE, 0x7274, 0x0, 0x42CC, 0x5DC, 0x0)
Sleep(3000)
OP_8F(0xFE, 0x72D8, 0x0, 0x4330, 0x12C, 0x0)
Sleep(500)
OP_8F(0xFE, 0x7274, 0x0, 0x42CC, 0x2BC, 0x0)
Jump("Function_23_229E")
label("loc_230D")
Return()
# Function_23_229E end
def Function_24_230E(): pass
label("Function_24_230E")
OP_8E(0x9, 0x85AC, 0x32, 0x740E, 0x2EE0, 0x0)
Return()
# Function_24_230E end
def Function_25_2323(): pass
label("Function_25_2323")
OP_8E(0xA, 0x85AC, 0x32, 0x740E, 0x2EE0, 0x0)
Return()
# Function_25_2323 end
def Function_26_2338(): pass
label("Function_26_2338")
OP_8E(0xB, 0x85AC, 0x32, 0x740E, 0x2EE0, 0x0)
Return()
# Function_26_2338 end
def Function_27_234D(): pass
label("Function_27_234D")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 3)), scpexpr(EXPR_END)), "loc_2389")
TurnDirection(0xF, 0xA, 0)
TurnDirection(0x10, 0xA, 0)
TurnDirection(0x11, 0xA, 0)
TurnDirection(0x12, 0xA, 0)
TurnDirection(0x13, 0xA, 0)
TurnDirection(0x101, 0xA, 0)
TurnDirection(0x102, 0xA, 0)
OP_48()
Jump("Function_27_234D")
label("loc_2389")
Return()
# Function_27_234D end
def Function_28_238A(): pass
label("Function_28_238A")
TurnDirection(0xFE, 0x101, 400)
Return()
# Function_28_238A end
def Function_29_2392(): pass
label("Function_29_2392")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 0)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 4)), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_2423")
EventBegin(0x0)
ClearMapFlags(0x1)
OP_A3(0x0)
OP_A2(0x1)
OP_A3(0x2)
OP_62(0x9, 0x0, 2000, 0x2, 0x7, 0x50, 0x1)
OP_22(0x27, 0x0, 0x64)
OP_69(0x9, 0x1F4)
OP_43(0x101, 0x1, 0x0, 0x11)
OP_43(0x102, 0x1, 0x0, 0x11)
OP_22(0x81, 0x0, 0x64)
OP_8E(0x9, 0xB1BC, 0x0, 0xB220, 0x2EE0, 0x0)
OP_8E(0x9, 0xBB80, 0x0, 0xC738, 0x2EE0, 0x0)
SetChrPos(0x9, 22700, 0, 25300, 0)
OP_44(0x101, 0xFF)
OP_44(0x102, 0xFF)
Call(0, 32)
label("loc_2423")
Return()
# Function_29_2392 end
def Function_30_2424(): pass
label("Function_30_2424")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 1)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 4)), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_24A1")
EventBegin(0x0)
ClearMapFlags(0x1)
OP_A3(0x0)
OP_A3(0x1)
OP_A2(0x2)
OP_62(0x9, 0x0, 2000, 0x2, 0x7, 0x50, 0x1)
OP_22(0x27, 0x0, 0x64)
OP_69(0x9, 0x1F4)
OP_43(0x101, 0x1, 0x0, 0x11)
OP_43(0x102, 0x1, 0x0, 0x11)
OP_22(0x81, 0x0, 0x64)
OP_8E(0x9, 0x846C, 0x0, 0x3A98, 0x2EE0, 0x0)
SetChrPos(0x9, 46100, 0, 15200, 0)
OP_44(0x101, 0xFF)
OP_44(0x102, 0xFF)
Call(0, 32)
label("loc_24A1")
Return()
# Function_30_2424 end
def Function_31_24A2(): pass
label("Function_31_24A2")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x0, 2)), scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 4)), scpexpr(EXPR_NEQUZ_I64), scpexpr(EXPR_END)), "loc_2533")
EventBegin(0x0)
ClearMapFlags(0x1)
OP_A2(0x0)
OP_A3(0x1)
OP_A3(0x2)
OP_62(0x9, 0x0, 2000, 0x2, 0x7, 0x50, 0x1)
OP_22(0x27, 0x0, 0x64)
OP_69(0x9, 0x1F4)
OP_43(0x101, 0x1, 0x0, 0x11)
OP_43(0x102, 0x1, 0x0, 0x11)
OP_22(0x81, 0x0, 0x64)
OP_8E(0x9, 0xA4D8, 0x0, 0x2A94, 0x2EE0, 0x0)
OP_8E(0x9, 0x927C, 0x0, 0x27D8, 0x2EE0, 0x0)
OP_44(0x101, 0xFF)
OP_44(0x102, 0xFF)
SetChrPos(0x9, 39000, 0, 42000, 270)
Call(0, 32)
label("loc_2533")
Return()
# Function_31_24A2 end
def Function_32_2534(): pass
label("Function_32_2534")
Jc((scpexpr(EXPR_PUSH_VALUE_INDEX, 0x3), scpexpr(EXPR_PUSH_LONG, 0x3), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_25E0")
ChrTalk(
0x101,
"#000F啊啊。又逃走了~\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#010F这么小的家伙,\x01",
"逃跑起来动作也特别的灵活。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x102,
"#010F好好想一下战斗的方法哦,艾丝蒂尔。(※仮)\x02",
)
CloseMessageWindow()
Jump("loc_2A4C")
label("loc_25E0")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 6)), scpexpr(EXPR_END)), "loc_26AC")
OP_A2(0x237)
OP_28(0x2, 0x1, 0x400)
ChrTalk(
0x101,
"#007F啊啊……\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#012F真可惜啊。\x02\x03",
"#012F总之当它跳得起劲的时候\x01",
"从背后靠近它,然后再去抓它。\x02",
)
)
CloseMessageWindow()
Jump("loc_2A4C")
label("loc_26AC")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 5)), scpexpr(EXPR_END)), "loc_2991")
OP_A2(0x236)
OP_28(0x2, 0x1, 0x200)
ChrTalk(
0x101,
(
"#009F又、又逃走了!?\x02\x03",
"#009F这家伙身子圆圆胖胖的,\x01",
"怎么动作还这么灵活啊?\x02",
)
)
CloseMessageWindow()
TurnDirection(0x1, 0x0, 0)
ChrTalk(
0x102,
(
"#012F动作的确是很灵活,\x01",
"而且反应也相当灵敏。\x02\x03",
"#012F不过,掌握好时机就没问题了。\x02",
)
)
CloseMessageWindow()
TurnDirection(0x0, 0x1, 500)
ClearMapFlags(0x1)
OP_51(0x17, 0x1, (scpexpr(EXPR_GET_CHR_WORK, 0x101, 0x1), scpexpr(EXPR_GET_CHR_WORK, 0x102, 0x1), scpexpr(EXPR_GET_CHR_WORK, 0x101, 0x1), scpexpr(EXPR_SUB), scpexpr(EXPR_PUSH_LONG, 0x2), scpexpr(EXPR_IDIV), scpexpr(EXPR_ADD), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
OP_51(0x17, 0x2, (scpexpr(EXPR_GET_CHR_WORK, 0x101, 0x2), scpexpr(EXPR_GET_CHR_WORK, 0x102, 0x2), scpexpr(EXPR_GET_CHR_WORK, 0x101, 0x2), scpexpr(EXPR_SUB), scpexpr(EXPR_PUSH_LONG, 0x2), scpexpr(EXPR_IDIV), scpexpr(EXPR_ADD), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
OP_51(0x17, 0x3, (scpexpr(EXPR_GET_CHR_WORK, 0x101, 0x3), scpexpr(EXPR_GET_CHR_WORK, 0x102, 0x3), scpexpr(EXPR_GET_CHR_WORK, 0x101, 0x3), scpexpr(EXPR_SUB), scpexpr(EXPR_PUSH_LONG, 0x2), scpexpr(EXPR_IDIV), scpexpr(EXPR_ADD), scpexpr(EXPR_STUB), scpexpr(EXPR_END)))
OP_69(0x17, 0x320)
ChrTalk(
0x101,
"#004F掌握时机?\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
(
"#012F看得出这种魔兽跳起来的时候\x01",
"警戒性会相对减弱。\x02\x03",
"#012F瞄准这个空档,然后从背后靠近它,\x01",
"这样就应该可以抓住它了。\x02",
)
)
CloseMessageWindow()
ChrTalk(
0x101,
(
"#006F原来是这样啊……\x01",
"当它跳得起劲的时候从背后靠近它对吧。\x02\x03",
"#006F嗯,一定要试试看才行!\x02",
)
)
CloseMessageWindow()
Jump("loc_2A4C")
label("loc_2991")
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 4)), scpexpr(EXPR_END)), "loc_2A4C")
OP_A2(0x235)
OP_28(0x2, 0x1, 0x100)
ChrTalk(
0x101,
"#004F啊啊!\x02",
)
CloseMessageWindow()
ChrTalk(
0x102,
"#012F真可惜,被它发现了。\x02",
)
CloseMessageWindow()
ChrTalk(
0x101,
"#009F唔~下次一定抓到你!\x02",
)
CloseMessageWindow()
label("loc_2A4C")
OP_44(0x0, 0xFF)
OP_44(0x1, 0xFF)
OP_44(0x9, 0xFF)
EventEnd(0x1)
OP_43(0x9, 0x3, 0x0, 0x2)
Return()
# Function_32_2534 end
def Function_33_2A62(): pass
label("Function_33_2A62")
OP_69(0x101, 0x3E8)
Return()
# Function_33_2A62 end
def Function_34_2A6A(): pass
label("Function_34_2A6A")
EventBegin(0x1)
Jc((scpexpr(EXPR_TEST_SCENA_FLAGS, MakeScenarioFlags(0x46, 4)), scpexpr(EXPR_END)), "loc_2B58")
Jc((scpexpr(EXPR_PUSH_VALUE_INDEX, 0xA), scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_2AE9")
ChrTalk(
0x102,
(
"#012F魔兽一定还在农场里面。\x01",
" \x02\x03",
"我们还是不要去别的地方吧。\x02",
)
)
CloseMessageWindow()
Jump("loc_2B55")
label("loc_2AE9")
TurnDirection(0x102, 0x101, 400)
ChrTalk(
0x102,
(
"#012F魔兽一定还在农场里面某个地方。\x01",
" \x02\x03",
"我们还是回去巡逻吧。\x02",
)
)
CloseMessageWindow()
label("loc_2B55")
Jump("loc_2C08")
label("loc_2B58")
Jc((scpexpr(EXPR_PUSH_VALUE_INDEX, 0xA), scpexpr(EXPR_PUSH_LONG, 0x1), scpexpr(EXPR_EQU), scpexpr(EXPR_END)), "loc_2BB6")
ChrTalk(
0x102,
(
"#012F这里是农场的出口……\x01",
"我们要在农场里面巡逻才行。\x02",
)
)
CloseMessageWindow()
Jump("loc_2C08")
label("loc_2BB6")
TurnDirection(0x102, 0x101, 400)
ChrTalk(
0x102,
(
"#012F那里是农场的出口呢。\x01",
"我们要在农场里面巡逻才行。\x02",
)
)
CloseMessageWindow()
label("loc_2C08")
OP_8E(0x0, 0x5E24, 0x14, 0xD1C4, 0xBB8, 0x0)
Sleep(50)
EventEnd(0x4)
Return()
# Function_34_2A6A end
SaveToFile()
Try(main)
| [
"[email protected]"
]
| |
0dac5829221d058f43409e95e5d6afb11cbbcefd | 2e2c9cf0bf1f6218f82e7ecddbec17da49756114 | /day14ddt_opnpyxl/day14_封装Hand_excel/demo5列表推导式.py | 450b10ac6ae56ab647b20b0e36b9b6e0c8cf6283 | []
| no_license | guoyunfei0603/py31 | c3cc946cd9efddb58dad0b51b72402a77e9d7592 | 734a049ecd84bfddc607ef852366eb5b7d16c6cb | refs/heads/master | 2023-03-02T20:50:02.052878 | 2021-02-05T06:17:24 | 2021-02-05T06:17:24 | 279,454,793 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 513 | py | """
============================
Author:小白31
Time:2020/8/2 22:03
E-mail:[email protected]
============================
"""
# 生成1-100到列表
# li = []
# for i in range(1,101):
# li.append(i)
#
# print(li)
#
# print(list(range(1,101)))
# 生成 ["学号101","学号102","学号103"..."学号150"]
li = []
for i in range(101,151):
li.append("学号{}".format(i))
print(li)
print("-----------------列表推导式------------------")
li2 = ["学号{}".format(i) for i in range(101,151)]
print(li2) | [
"[email protected]"
]
| |
44550763f641d321195402710e48112bca809066 | fbcd5c97110077f67d4a7320a1cbdd1d7e2c1ab4 | /set_transformer.py | 94b6b4c26d566a7b65ff534d96cc4a5ebfe73d07 | []
| no_license | davzha/recurrently_predicting_hypergraphs | b3cd924bb50801717b2b45d204f7cfddd8051423 | c2b9a4959a1b9e3bac05ad3e5264029ccad2447d | refs/heads/master | 2023-07-30T10:04:48.500489 | 2021-09-21T09:02:52 | 2021-09-21T09:02:52 | 380,384,180 | 7 | 1 | null | null | null | null | UTF-8 | Python | false | false | 4,451 | py | """Set transformer code adapted from https://github.com/juho-lee/set_transformer (MIT License)
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class MAB(nn.Module):
def __init__(self, dim_Q, dim_K, dim_V, num_heads, ln=False):
super(MAB, self).__init__()
self.dim_V = dim_V
self.num_heads = num_heads
self.fc_q = nn.Linear(dim_Q, dim_V)
self.fc_k = nn.Linear(dim_K, dim_V)
self.fc_v = nn.Linear(dim_K, dim_V)
if ln:
self.ln0 = nn.LayerNorm(dim_V)
self.ln1 = nn.LayerNorm(dim_V)
self.fc_o = nn.Linear(dim_V, dim_V)
def forward(self, Q, K):
Q = self.fc_q(Q)
K, V = self.fc_k(K), self.fc_v(K)
dim_split = self.dim_V // self.num_heads
Q_ = torch.cat(Q.split(dim_split, 2), 0)
K_ = torch.cat(K.split(dim_split, 2), 0)
V_ = torch.cat(V.split(dim_split, 2), 0)
A = torch.softmax(Q_.bmm(K_.transpose(1,2))/math.sqrt(self.dim_V), 2)
O = torch.cat((Q_ + A.bmm(V_)).split(Q.size(0), 0), 2)
O = O if getattr(self, 'ln0', None) is None else self.ln0(O)
O = O + F.relu(self.fc_o(O))
O = O if getattr(self, 'ln1', None) is None else self.ln1(O)
return O
class SAB(nn.Module):
def __init__(self, dim_in, dim_out, num_heads, ln=False):
super(SAB, self).__init__()
self.mab = MAB(dim_in, dim_in, dim_out, num_heads, ln=ln)
def forward(self, X):
return self.mab(X, X)
class ISAB(nn.Module):
def __init__(self, dim_in, dim_out, num_heads, num_inds, ln=False):
super(ISAB, self).__init__()
self.I = nn.Parameter(torch.Tensor(1, num_inds, dim_out))
nn.init.xavier_uniform_(self.I)
self.mab0 = MAB(dim_out, dim_in, dim_out, num_heads, ln=ln)
self.mab1 = MAB(dim_in, dim_out, dim_out, num_heads, ln=ln)
def forward(self, X):
H = self.mab0(self.I.repeat(X.size(0), 1, 1), X)
return self.mab1(X, H)
class PMA(nn.Module):
def __init__(self, dim, num_heads, num_seeds, ln=False):
super(PMA, self).__init__()
self.num_seeds = num_seeds
self.edges_mu = nn.Parameter(torch.randn(1, 1, dim))
self.edges_logsigma = nn.Parameter(torch.zeros(1, 1, dim))
nn.init.xavier_uniform_(self.edges_logsigma)
self.mab = MAB(dim, dim, dim, num_heads, ln=ln)
def forward(self, X):
b, _, _, device = *X.shape, X.device
mu = self.edges_mu.expand(b, self.num_seeds, -1)
sigma = self.edges_logsigma.exp().expand(b, self.num_seeds, -1)
edges = mu + sigma * torch.randn(mu.shape, device = device)
return self.mab(edges, X)
class SetTransformer(nn.Module):
def __init__(self, dim_input, num_outputs, dim_output,
dim_hidden=128, num_heads=4, ln=False):
super(SetTransformer, self).__init__()
self.enc = nn.Sequential(
SAB(dim_input, dim_hidden, num_heads, ln=ln),
SAB(dim_hidden, dim_hidden, num_heads, ln=ln),
SAB(dim_hidden, dim_hidden, num_heads, ln=ln),
SAB(dim_hidden, dim_hidden, num_heads, ln=ln))
self.dec = nn.Sequential(
PMA(dim_hidden, num_heads, num_outputs, ln=ln),
SAB(dim_hidden, dim_hidden, num_heads, ln=ln),
SAB(dim_hidden, dim_hidden, num_heads, ln=ln),
nn.Linear(dim_hidden, dim_output))
def forward(self, X):
return self.dec(self.enc(X))
class STSet2Hypergraph(nn.Module):
def __init__(self, max_k, d_in, d_hid):
super().__init__()
self.proj_in = nn.Linear(d_in, d_hid)
self.set2set = SetTransformer(d_hid, max_k, d_hid, ln=True)
self.mlp_out = nn.Sequential(
nn.Linear(2 * d_hid, d_hid),
nn.ReLU(inplace=True),
nn.Linear(d_hid, 1),
nn.Sigmoid()
)
self.edge_ind = nn.Sequential(
nn.Linear(d_hid, 1),
nn.Sigmoid()
)
def forward(self, x):
x = self.proj_in(x)
e = self.set2set(x)
n_nodes = x.size(1)
n_edges = e.size(1)
outer = torch.cat([
x.unsqueeze(1).expand(-1, n_edges, -1, -1),
e.unsqueeze(2).expand(-1, -1, n_nodes, -1)], dim=3)
incidence = self.mlp_out(outer).squeeze(3)
ind = self.edge_ind(e)
return torch.cat([incidence, ind], dim=-1) | [
"[email protected]"
]
| |
a59ca1f99c5f53cd1737d4fcb2670dc70f7ec927 | ca22c441ec0eabf61b3b415fc9be8453855481cf | /rapid/__init__.py | b47d1e365bbc7cdc678e8f7640ddc873208950a7 | [
"MIT"
]
| permissive | linhao1998/rapid | cc1d45a119a4c7c3c384ad708c3220226c5c7edd | 1611e47fffac0f61e6c07ad5388eb2368a426f06 | refs/heads/main | 2023-06-16T16:24:57.498657 | 2021-07-08T14:48:47 | 2021-07-08T14:48:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 979 | py | from gym.envs.registration import register
register(
id='EpisodeInvertedPendulum-v2',
entry_point='rapid.mujoco_envs:EpisodeInvertedPendulumEnv',
max_episode_steps=1000,
reward_threshold=950.0,
)
register(
id='EpisodeSwimmer-v2',
entry_point='rapid.mujoco_envs:EpisodeSwimmerEnv',
max_episode_steps=1000,
reward_threshold=360.0,
)
register(
id='DensityEpisodeSwimmer-v2',
entry_point='rapid.mujoco_envs:DensityEpisodeSwimmerEnv',
max_episode_steps=1000,
reward_threshold=360.0,
)
register(
id='ViscosityEpisodeSwimmer-v2',
entry_point='rapid.mujoco_envs:ViscosityEpisodeSwimmerEnv',
max_episode_steps=1000,
reward_threshold=360.0,
)
register(
id='EpisodeWalker2d-v2',
max_episode_steps=1000,
entry_point='rapid.mujoco_envs:EpisodeWalker2dEnv',
)
register(
id='EpisodeHopper-v2',
entry_point='rapid.mujoco_envs:EpisodeHopperEnv',
max_episode_steps=1000,
reward_threshold=3800.0,
)
| [
"[email protected]"
]
| |
01c569faba32bfac184adca54ccdb6d7303cb050 | 6b1cf01918ae2f3ad120b09f21ccde842ed2c5ba | /util/send_mail.py | 93ea52e70e5579fb237728d74c84e83cccbf39e3 | []
| no_license | exiaohao/mini_monitor | e7c10a16f6bac0f9066f7fb499a09b0d10feeba4 | c6ad0f9dac5f4de86d88ca906a7e576b56686194 | refs/heads/master | 2021-01-09T20:53:24.424991 | 2016-07-22T06:07:48 | 2016-07-22T06:07:48 | 58,460,884 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 915 | py | from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from email.header import Header
from config import App
import urllib.parse
def send_mail_util(recvs, subject, msg):
s = SMTP_SSL('smtp.exmail.qq.com', 465)
s.login(App.send_mail_sender, App.send_mail_sender_passwd)
message = MIMEText(msg, 'plain', 'utf-8')
for recv in recvs.split(','):
# send_msg = "From: {}\r\nTo: {}\r\nSubject: {}\r\n{}".format(App.send_mail_sender, recv, subject, msg)
message['From'] = Header(App.send_mail_sender, 'utf-8')
message['To'] = Header(recv, 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
try:
print(message.as_string())
s.sendmail(from_addr=App.send_mail_sender, to_addrs=recv, msg=message.as_string())
except Exception as ex:
# print('Error occured @ {}'.format(str(ex)))
pass
s.quit()
| [
"[email protected]"
]
| |
3e1c6cb80595d1550b9a27b99ab2478eb35a4eee | 673d37daf3ad3915b74491da55fd46f37f401eaf | /firefly/server/admin.py | 0d2d980a8bb63df9ea49c20c089e2d0ad7f0683b | []
| no_license | ruaruagerry/mahjong_firefly | 3f0d06e72061b52d153d075d1919655253c48de2 | 8f8c2f3a9b474d43ab15fb333d16028fd853f7d3 | refs/heads/master | 2022-07-15T17:09:32.941087 | 2020-05-11T15:25:05 | 2020-05-11T15:25:05 | 263,080,891 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 842 | py | #coding:utf8
'''
Created on 2013-8-12
@author: lan (www.9miao.com)
'''
from globalobject import GlobalObject,masterserviceHandle
from twisted.internet import reactor
from twisted.python import log
from common.log import logger
reactor = reactor
@masterserviceHandle
def serverStop():
"""
停止服务
:return:
"""
reactor.callLater(0.5, reactor.stop)
return True
@masterserviceHandle
def sreload():
"""
重载模块
:return:
"""
log.msg('reload')
if GlobalObject().reloadmodule:
reload(GlobalObject().reloadmodule)
return True
@masterserviceHandle
def remote_connect(rname, rhost):
"""
连接远程节点
:param rname:
:param rhost:
:return:
"""
# logger.debug("rname:%s, rhost:%s", rname, rhost)
GlobalObject().remote_connect(rname, rhost)
| [
"gerry"
]
| gerry |
d2755b5837aed68c45d5c4b4707b5df295306987 | 5575c1e2596f546f4277fe79ba5155aa2db9f074 | /ecommerce/shipping.py | 0d4848aca5274e49f253e177653548f23affa074 | []
| no_license | plankan39/pythontest | 521a99eeb9417ba96dba132d154f5fde5d1a0228 | 6bad96807ed1b0cd3164f1612e67300869728972 | refs/heads/master | 2023-02-26T05:43:40.885698 | 2021-01-25T12:05:30 | 2021-01-25T12:05:30 | 317,344,085 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 74 | py | def calc_shipping(parameter_list):
"""
docstring
"""
pass
| [
"[email protected]"
]
| |
92bda0387d9d98eb70e6077ff9a9ac8da8450137 | dd65e3cbfa3fb5ef378e83f810d67822db396269 | /oracle_mon/views.py | 6abc95f240b3de063267206dfd9120e30846c67d | []
| no_license | ampere1984/dbmon | a385ffa43377df9a203cee443c648f846782f035 | 60a39bb311008e33e08c9df7547be6142bbef6b0 | refs/heads/master | 2020-04-22T02:45:08.430898 | 2019-01-29T09:45:37 | 2019-01-29T09:45:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 24,217 | py | #! /usr/bin/python
# encoding:utf-8
from django.shortcuts import render
from django.shortcuts import render,render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# Create your views here.
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
import datetime
from frame import tools
# 配置文件
import ConfigParser
import base64
import frame.models as models_frame
import oracle_mon.models as models_oracle
import frame.oracle_do as ora_do
# Create your views here.
@login_required(login_url='/login')
def oracle_monitor(request):
messageinfo_list = models_frame.TabAlarmInfo.objects.all()
tagsinfo = models_oracle.TabOracleServers.objects.all().order_by('tags')
tagsdefault = request.GET.get('tagsdefault')
if not tagsdefault:
tagsdefault = models_oracle.TabOracleServers.objects.order_by('tags')[0].tags
conn_range_default = request.GET.get('conn_range_default')
if not conn_range_default:
conn_range_default = '1小时'.decode("utf-8")
undo_range_default = request.GET.get('undo_range_default')
if not undo_range_default:
undo_range_default = '1小时'.decode("utf-8")
tmp_range_default = request.GET.get('tmp_range_default')
if not tmp_range_default:
tmp_range_default = '1小时'.decode("utf-8")
ps_range_default = request.GET.get('ps_range_default')
if not ps_range_default:
ps_range_default = '1小时'.decode("utf-8")
conn_begin_time = tools.range(conn_range_default)
undo_begin_time = tools.range(undo_range_default)
tmp_begin_time = tools.range(tmp_range_default)
ps_begin_time = tools.range(ps_range_default)
end_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# 取当前数据库状态
try:
oracle_curr = models_oracle.OracleDb.objects.filter(tags=tagsdefault).get(
tags=tagsdefault, )
except models_oracle.OracleDb.DoesNotExist:
oracle_curr = \
models_oracle.OracleDbHis.objects.filter(tags=tagsdefault).order_by(
'-chk_time')[0]
# 取上一次有效采集的数据
try:
try:
oracleinfo = models_oracle.OracleDb.objects.filter(tags=tagsdefault, percent_process__isnull=False).get(tags=tagsdefault,)
except models_oracle.OracleDb.DoesNotExist:
oracleinfo = \
models_oracle.OracleDbHis.objects.filter(tags=tagsdefault, percent_process__isnull=False).order_by(
'-chk_time')[0]
except Exception, e:
oracleinfo = \
models_oracle.OracleDbHis.objects.filter(tags=tagsdefault).order_by(
'-chk_time')[0]
if oracle_curr.mon_status == 'connected':
check_status = 'success'
oracle_status = '在线'
else:
check_status = 'danger'
oracle_status = '离线'
eventinfo = models_oracle.OracleDbEvent.objects.filter(tags=tagsdefault)
lockinfo = models_oracle.OracleLock.objects.filter(tags=tagsdefault)
conngrow = models_oracle.OracleDbHis.objects.filter(tags=tagsdefault, percent_process__isnull=False).filter(
chk_time__gt=conn_begin_time, chk_time__lt=end_time).order_by('-chk_time')
conngrow_list = list(conngrow)
conngrow_list.reverse()
try:
undoinfo = models_oracle.OracleUndoTbs.objects.get(tags=tagsdefault)
except models_oracle.OracleUndoTbs.DoesNotExist:
undoinfo = models_oracle.OracleUndoTbsHis.objects.filter(tags=tagsdefault, pct_used__isnull=False).order_by('-chk_time')
if not undoinfo:
models_oracle.OracleUndoTbsHis.objects.create(tags=tagsdefault,undo_tbs_name='UNDOTBS1', total_mb=0, used_mb=0,
pct_used=0,rate_level='green')
undoinfo = models_oracle.OracleUndoTbsHis.objects.filter(tags=tagsdefault, pct_used__isnull=False).order_by('-chk_time')[0]
undogrow = models_oracle.OracleUndoTbsHis.objects.filter(tags=tagsdefault, pct_used__isnull=False).filter(
chk_time__gt=undo_begin_time, chk_time__lt=end_time).order_by('-chk_time')
undogrow_list = list(undogrow)
undogrow_list.reverse()
try:
tmpinfo = models_oracle.OracleTmpTbs.objects.get(tags=tagsdefault,tmp_tbs_name='TEMP')
except models_oracle.OracleTmpTbs.DoesNotExist:
tmpinfo = models_oracle.OracleTmpTbsHis.objects.filter(tags=tagsdefault, pct_used__isnull=False).order_by('-chk_time')
if not tmpinfo:
models_oracle.OracleTmpTbsHis.objects.create(tags=tagsdefault, tmp_tbs_name='UNDOTBS1', total_mb=0,
used_mb=0,
pct_used=0, rate_level='green')
tmpinfo = models_oracle.OracleTmpTbsHis.objects.filter(tags=tagsdefault, pct_used__isnull=False).order_by('-chk_time')[0]
tmpgrow = models_oracle.OracleTmpTbsHis.objects.filter(tags=tagsdefault, pct_used__isnull=False).filter(
chk_time__gt=tmp_begin_time, chk_time__lt=end_time).order_by('-chk_time')
tmpgrow_list = list(tmpgrow)
tmpgrow_list.reverse()
psgrow = models_oracle.OracleDbHis.objects.filter(tags=tagsdefault, qps__isnull=False).filter(
chk_time__gt=ps_begin_time, chk_time__lt=end_time).order_by('-chk_time')
psgrow_list = list(psgrow)
psgrow_list.reverse()
# 连接信息
sql = "select host,port,service_name,user,password,user_os,password_os from tab_oracle_servers where tags= '%s' " % tagsdefault
oracle = tools.mysql_query(sql)
host = oracle[0][0]
port = oracle[0][1]
service_name = oracle[0][2]
user = oracle[0][3]
password = oracle[0][4]
password = base64.decodestring(password)
url = host + ':' + port + '/' + service_name
if request.method == 'POST':
if request.POST.has_key('select_tags') or request.POST.has_key('select_conn') or request.POST.has_key('select_undo') or request.POST.has_key('select_tmp') or request.POST.has_key('select_ps'):
if request.POST.has_key('select_tags'):
tagsdefault = request.POST.get('select_tags', None).encode("utf-8")
elif request.POST.has_key('select_conn'):
conn_range_default = request.POST.get('select_conn',None)
elif request.POST.has_key('select_undo'):
undo_range_default = request.POST.get('select_undo', None)
elif request.POST.has_key('select_tmp'):
tmp_range_default = request.POST.get('select_tmp', None)
elif request.POST.has_key('select_ps'):
ps_range_default = request.POST.get('select_ps', None)
return HttpResponseRedirect('/oracle_monitor?tagsdefault=%s&conn_range_default=%s&undo_range_default=%s&tmp_range_default=%s&ps_range_default=%s' %(tagsdefault,conn_range_default,undo_range_default,tmp_range_default,ps_range_default))
else:
logout(request)
return HttpResponseRedirect('/login/')
if messageinfo_list:
msg_num = len(messageinfo_list)
msg_last = models_frame.TabAlarmInfo.objects.latest('id')
msg_last_content = msg_last.alarm_content
tim_last = (datetime.datetime.now() - msg_last.alarm_time).seconds / 60
else:
msg_num = 0
msg_last_content = ''
tim_last = ''
return render_to_response('oracle_monitor.html',
{'conngrow_list': conngrow_list, 'undogrow_list': undogrow_list, 'tmpinfo': tmpinfo,
'tmpgrow_list': tmpgrow_list,'psgrow_list': psgrow_list, 'tagsdefault': tagsdefault, 'tagsinfo': tagsinfo,
'oracleinfo': oracleinfo, 'undoinfo': undoinfo, 'eventinfo': eventinfo,
'lockinfo': lockinfo, 'messageinfo_list': messageinfo_list,
'msg_num': msg_num, 'conn_range_default': conn_range_default,
'undo_range_default': undo_range_default, 'tmp_range_default': tmp_range_default,'ps_range_default': ps_range_default,
'msg_last_content': msg_last_content, 'tim_last': tim_last,'check_status':check_status,'oracle_status':oracle_status})
@login_required(login_url='/login')
def show_oracle(request):
messageinfo_list = models_frame.TabAlarmInfo.objects.all()
dbinfo_list = models_oracle.OracleDb.objects.order_by("rate_level")
paginator = Paginator(dbinfo_list, 10)
page = request.GET.get('page')
try:
dbinfos = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
dbinfos = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
dbinfos = paginator.page(paginator.num_pages)
if request.method == 'POST':
logout(request)
return HttpResponseRedirect('/login/')
if messageinfo_list:
msg_num = len(messageinfo_list)
msg_last = models_frame.TabAlarmInfo.objects.latest('id')
msg_last_content = msg_last.alarm_content
tim_last = (datetime.datetime.now() - msg_last.alarm_time).seconds / 60
else:
msg_num = 0
msg_last_content = ''
tim_last = ''
return render_to_response('show_oracle.html',
{'dbinfos': dbinfos, 'messageinfo_list': messageinfo_list, 'msg_num': msg_num,
'msg_last_content': msg_last_content, 'tim_last': tim_last})
@login_required(login_url='/login')
def show_oracle_resource(request):
messageinfo_list = models_frame.TabAlarmInfo.objects.all()
tagsinfo = models_oracle.OracleDb.objects.filter(mon_status='connected')
tagsdefault = request.GET.get('tagsdefault')
if not tagsdefault:
tagsdefault = models_oracle.OracleDb.objects.filter(mon_status='connected').order_by('tags')[0].tags
typedefault = request.GET.get('typedefault')
redo_range_default = request.GET.get('redo_range_default')
if not redo_range_default:
redo_range_default = 7
tbsinfo_list = models_oracle.OracleTbs.objects.filter(tags=tagsdefault).order_by('-pct_used')
# 分页
paginator_tbs = Paginator(tbsinfo_list, 5)
undotbsinfo_list = models_oracle.OracleUndoTbs.objects.filter(tags=tagsdefault).order_by('-pct_used')
paginator_undo = Paginator(undotbsinfo_list, 5)
tmptbsinfo_list = models_oracle.OracleTmpTbs.objects.filter(tags=tagsdefault).order_by('-pct_used')
paginator_tmp = Paginator(tmptbsinfo_list, 5)
page_tbs = request.GET.get('page_tbs')
try:
tbsinfos = paginator_tbs.page(page_tbs)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
tbsinfos = paginator_tbs.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
tbsinfos = paginator_tbs.page(paginator_tbs.num_pages)
page_undo = request.GET.get('page_undo')
try:
undotbsinfos = paginator_undo.page(page_undo)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
undotbsinfos = paginator_undo.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
undotbsinfos = paginator_undo.page(paginator_undo.num_pages)
page_tmp = request.GET.get('page_tmp')
try:
tmptbsinfos = paginator_undo.page(page_tmp)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
tmptbsinfos = paginator_tmp.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
tmptbsinfos = paginator_tmp.page(paginator_tmp.num_pages)
# 获取控制文件信息
sql = "select host,port,service_name,user,password,user_os,password_os from tab_oracle_servers where tags= '%s' " % tagsdefault
oracle = tools.mysql_query(sql)
host = oracle[0][0]
port = oracle[0][1]
service_name = oracle[0][2]
user = oracle[0][3]
password = oracle[0][4]
password = base64.decodestring(password)
url = host + ':' + port + '/' + service_name
sql = """
select name,round(block_size*file_size_blks/1024/1024,2) size_M,'controlfile' tpye from v$controlfile
"""
oracle_controlfiles = tools.oracle_django_query(user, password, url, sql)
# 获取在线日志
sql = """
select a.GROUP# group_no,b.THREAD# thread_no,a.TYPE,b.SEQUENCE# sequence_no,b.BYTES/1024/1024 SIZE_M,b.ARCHIVED,b.STATUS,a.MEMBER from v$logfile a,v$log b where a.GROUP#=b.GROUP#(+)
"""
oracle_redo_files = tools.oracle_django_query(user, password, url, sql)
# 在线日志统计
if redo_range_default == '1':
sql = """
select 'hh'||to_char(first_time, 'hh24') stat_date,
count(1) log_count,
(select bytes / 1024 / 1024 sizem from v$log where rownum < 2) log_size
from v$log_history
where to_char(first_time, 'yyyymmdd') < to_char(sysdate, 'yyyymmdd')
and to_char(first_time, 'yyyymmdd') >=
to_char(sysdate - 1, 'yyyymmdd')
group by to_char(first_time, 'hh24'),to_char(first_time, 'dy')
order by to_char(first_time, 'hh24')
"""
oracle_redo_cnts = tools.oracle_django_query(user, password, url, sql)
else:
sql = """ select to_char(first_time, 'yyyy-mm-dd') stat_date,
count(1) log_count,
(select bytes / 1024 / 1024 sizem from v$log where rownum < 2) log_size
from v$log_history
where to_char(first_time, 'yyyymmdd') < to_char(sysdate, 'yyyymmdd')
and to_char(first_time, 'yyyymmdd') >= to_char(sysdate-%s, 'yyyymmdd')
group by to_char(first_time, 'yyyy-mm-dd'), to_char(first_time, 'dy') order by to_char(first_time, 'yyyy-mm-dd')""" % redo_range_default
oracle_redo_cnts = tools.oracle_django_query(user, password, url, sql)
# 表变化记录
sql = """
select table_owner,table_name,inss,upds,dels,
to_char(inss + upds + dels) dmls,to_char(sysdate , 'yyyy-mm-dd') get_date,truncated,num_rows,
to_char(last_analyzed ,'yyyy-mm-dd hh24:mi:ss') last_analyzed
from (select m.table_owner, m.table_name, inserts as inss, updates as upds, deletes as dels, truncated, t.num_rows,t.last_analyzed
from sys.dba_tab_modifications m, dba_tables t
where m.table_name = t.table_name
and t.owner not in ('SYS','SYSTEM','OUTLN','DIP','ORACLE_OCM','DBSNMP','APPQOSSYS','WMSYS','EXFSYS',
'CTXSYS','ANONYMOUS','XDB','XS$NULL','ORDDATA','SI_INFORMTN_SCHEMA','ORDPLUGINS','ORDSYS','MDSYS','OLAPSYS',
'MDDATA','SPATIAL_WFS_ADMIN_USR','SPATIAL_CSW_ADMIN_USR','SYSMAN','MGMT_VIEW','APEX_030200','FLOWS_FILES',
'APEX_PUBLIC_USER','OWBSYS','OWBSYS_AUDIT','SCOTT')
and m.table_owner = t.owner and m.partition_name is null)
"""
oracle_table_changes = tools.oracle_django_query(user, password, url, sql)
# 序列
sql = """
select sequence_owner,sequence_name,min_value,max_value,increment_by,cycle_flag,order_flag,
cache_size,last_number,
round((max_value - last_number) / (max_value - min_value), 2) * 100 pct_used,
(case when (round((max_value - last_number) / (max_value - min_value), 2) * 100) > 30
then 'green'
when (round((max_value - last_number) / (max_value - min_value), 2) * 100) <= 30 and (round((max_value - last_number) / (max_value - min_value), 2) * 100) > 10
then 'yellow'
when (round((max_value - last_number) / (max_value - min_value), 2) * 100) <= 10
then 'red'
else ''
end) seq_color,
to_char(sysdate, 'yyyy-mm-dd') last_analyzed
from dba_sequences s
where s.sequence_owner not in ('SYS','SYSTEM','OUTLN','DIP','ORACLE_OCM','DBSNMP','APPQOSSYS','WMSYS','EXFSYS',
'CTXSYS','ANONYMOUS','XDB','XS$NULL','ORDDATA','SI_INFORMTN_SCHEMA','ORDPLUGINS','ORDSYS','MDSYS','OLAPSYS',
'MDDATA','SPATIAL_WFS_ADMIN_USR','SPATIAL_CSW_ADMIN_USR','SYSMAN','MGMT_VIEW','APEX_030200','FLOWS_FILES',
'APEX_PUBLIC_USER','OWBSYS','OWBSYS_AUDIT','SCOTT')
"""
oracle_sequences = tools.oracle_django_query(user, password, url, sql)
# 账号
sql = """
select username,profile,to_char(created,'yyyy-mm-dd hh24:mi:ss') created,
account_status,
(case when account_status <> 'OPEN' then 'red' else 'green'end ) account_color,
to_char(lock_date,'yyyy-mm-dd hh24:mi:ss') lock_date,
to_char(expiry_date,'yyyy-mm-dd hh24:mi:ss') expiry_date,
(case when expiry_date - sysdate > 30
then 'green'
when expiry_date - sysdate <= 30 and expiry_date - sysdate > 7
then 'yellow'
when expiry_date - sysdate <= 7
then 'red'
else ''
end) expiry_color,default_tablespace,temporary_tablespace
from dba_users
"""
oracle_users = tools.oracle_django_query(user, password, url, sql)
# alert日志
oracle_alert_logs = models_oracle.AlertLog.objects.filter(server_type='Oracle',tags=tagsdefault).order_by('-log_time')
if request.method == 'POST':
if request.POST.has_key('select_tags') :
tagsdefault = request.POST.get('select_tags', None).encode("utf-8")
return HttpResponseRedirect('/show_oracle_resource?tagsdefault=%s&redo_range_default=%s' %(tagsdefault,redo_range_default))
else:
logout(request)
return HttpResponseRedirect('/login/')
if messageinfo_list:
msg_num = len(messageinfo_list)
msg_last = models_frame.TabAlarmInfo.objects.latest('id')
msg_last_content = msg_last.alarm_content
tim_last = (datetime.datetime.now() - msg_last.alarm_time).seconds / 60
else:
msg_num = 0
msg_last_content = ''
tim_last = ''
return render_to_response('show_oracle_res.html', {'tagsdefault': tagsdefault,'typedefault':typedefault,'tagsinfo': tagsinfo,'msg_num':msg_num,
'msg_last_content': msg_last_content, 'tim_last': tim_last,
'tbsinfos': tbsinfos, 'undotbsinfos': undotbsinfos,'tmptbsinfos': tmptbsinfos,'oracle_controlfiles':oracle_controlfiles,
'oracle_redo_files':oracle_redo_files,'oracle_redo_cnts':oracle_redo_cnts,'oracle_table_changes':oracle_table_changes,
'oracle_sequences':oracle_sequences,'oracle_users':oracle_users,'oracle_alert_logs':oracle_alert_logs})
@login_required(login_url='/login')
def oracle_profile(request):
messageinfo_list = models_frame.TabAlarmInfo.objects.all()
tags = request.GET.get('tags')
profile_name = request.GET.get('profile_name')
sql = "select host,port,service_name,user,password,user_os,password_os from tab_oracle_servers where tags= '%s' " %tags
oracle = tools.mysql_query(sql)
host = oracle[0][0]
port = oracle[0][1]
service_name = oracle[0][2]
user = oracle[0][3]
password = oracle[0][4]
password = base64.decodestring(password)
url = host + ':' + port + '/' + service_name
sql = """
select profile,resource_name,resource_type,limit,to_char(sysdate,'yyyy-mm-dd') get_date
from dba_profiles where profile = '%s'
""" %profile_name
oracle_profiles = tools.oracle_django_query(user,password,url,sql)
now = tools.now()
if request.method == 'POST':
logout(request)
return HttpResponseRedirect('/login/')
if messageinfo_list:
msg_num = len(messageinfo_list)
msg_last = models_frame.TabAlarmInfo.objects.latest('id')
msg_last_content = msg_last.alarm_content
tim_last = (datetime.datetime.now() - msg_last.alarm_time).seconds / 60
else:
msg_num = 0
msg_last_content = ''
tim_last = ''
return render_to_response('oracle_profile.html',
{'messageinfo_list': messageinfo_list,'msg_num':msg_num, 'oracle_profiles': oracle_profiles, 'profile_name':profile_name,'tags': tags,
'now': now,
'msg_last_content': msg_last_content, 'tim_last': tim_last})
@login_required(login_url='/login')
def oracle_grant(request):
messageinfo_list = models_frame.TabAlarmInfo.objects.all()
tags = request.GET.get('tags')
username = request.GET.get('username')
sql = "select host,port,service_name,user,password,user_os,password_os from tab_oracle_servers where tags= '%s' " %tags
oracle = tools.mysql_query(sql)
host = oracle[0][0]
port = oracle[0][1]
service_name = oracle[0][2]
user = oracle[0][3]
password = oracle[0][4]
password = base64.decodestring(password)
url = host + ':' + port + '/' + service_name
# 角色权限
sql = """
select grantee,
granted_role,
admin_option,
default_role,
to_char(sysdate, 'yyyy-mm-dd') get_date
from dba_role_privs where grantee = '%s'
""" %username
user_roles = tools.oracle_django_query(user,password,url,sql)
# 系统权限
sql = """
select grantee,privilege,admin_option,to_char(sysdate,'yyyy-mm-dd') get_date
from dba_sys_privs where grantee = '%s'
""" %username
sys_privs = tools.oracle_django_query(user,password,url,sql)
# 对象权限
sql = """
select owner,grantee,grantor,table_name,privilege
,grantable,hierarchy,to_char(sysdate,'yyyy-mm-dd') get_date
from dba_tab_privs
where grantee <> 'PUBLIC' and privilege <> 'EXECUTE' and grantee = '%s'
""" %username
tab_privs = tools.oracle_django_query(user,password,url,sql)
now = tools.now()
if request.method == 'POST':
logout(request)
return HttpResponseRedirect('/login/')
if messageinfo_list:
msg_num = len(messageinfo_list)
msg_last = models_frame.TabAlarmInfo.objects.latest('id')
msg_last_content = msg_last.alarm_content
tim_last = (datetime.datetime.now() - msg_last.alarm_time).seconds / 60
else:
msg_num = 0
msg_last_content = ''
tim_last = ''
return render_to_response('oracle_grant.html',
{'messageinfo_list': messageinfo_list, 'msg_num':msg_num,'user_roles': user_roles,'sys_privs':sys_privs,
'tab_privs':tab_privs,'username':username,'tags': tags,'now': now,
'msg_last_content': msg_last_content, 'tim_last': tim_last})
@login_required(login_url='/login')
def show_oracle_rate(request):
messageinfo_list = models_frame.TabAlarmInfo.objects.all()
oracle_rate_list = models_oracle.OracleDbRate.objects.order_by("db_rate")
if request.method == 'POST':
logout(request)
return HttpResponseRedirect('/login/')
if messageinfo_list:
msg_num = len(messageinfo_list)
msg_last = models_frame.TabAlarmInfo.objects.latest('id')
msg_last_content = msg_last.alarm_content
tim_last = (datetime.datetime.now() - msg_last.alarm_time).seconds / 60
else:
msg_num = 0
msg_last_content = ''
tim_last = ''
return render_to_response('show_oracle_rate.html',
{'oracle_rate_list': oracle_rate_list, 'messageinfo_list': messageinfo_list,
'msg_num': msg_num,
'msg_last_content': msg_last_content, 'tim_last': tim_last})
| [
"[email protected]"
]
| |
a6610f3481b08658f371b6904911bc55a74f4c12 | ff481a22256d045e28403f4ee65480dc3d6ce1d9 | /gerencia/views.py | 073e9d8eb381f5ced2498a8713c677de275c3ce7 | []
| no_license | redcliver/inomont | 83fa6501cbca74e79fc1a42509e5bb5c05eea2dd | 0b8d6511618b6509a5208c8a5d9f82903de8da87 | refs/heads/master | 2023-04-27T03:22:57.138482 | 2020-01-14T21:22:19 | 2020-01-14T21:22:19 | 221,098,331 | 1 | 0 | null | 2023-04-21T20:40:39 | 2019-11-12T00:51:22 | CSS | UTF-8 | Python | false | false | 65,237 | py | from django.shortcuts import render
from website.models import funcaoModel, cadastroSite, fornecedorModel, colaboradorModel, clienteModel, contaPagarModel, contaReceberModel
import datetime
from django.contrib.auth.models import User
from django.utils.crypto import get_random_string
# Create your views here.
def home(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
return render (request, 'gerencia/home.html', {'title':'Home',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
#Colaboradores
def colaboradores(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
return render (request, 'gerencia/colaboradores/home.html', {'title':'Home',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def colaboradoresNovo(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == "POST" and request.POST.get('nome') != None:
nome = request.POST.get('nome')
sobrenome = request.POST.get('sobrenome')
cpf = request.POST.get('cpf')
rg = request.POST.get('rg')
dataNasc = request.POST.get('dataNasc')
email = request.POST.get('email')
celular = request.POST.get('celular')
telefone = request.POST.get('telefone')
estadoCivil = request.POST.get('estadoCivil')
funcaoID = request.POST.get('funcaoID')
tempoExperiencia = request.POST.get('tempoExperiencia')
escolaridade = request.POST.get('escolaridade')
resideEmTresLagoas = request.POST.get('resideEmTresLagoas')
trabalhouInomont = request.POST.get('trabalhouInomont')
pqInomont = request.POST.get('pqInomont')
empresa1 = request.POST.get('empresa1')
funcao1 = request.POST.get('funcao1')
periodo1 = request.POST.get('periodo1')
empresa2 = request.POST.get('empresa2')
funcao2 = request.POST.get('funcao2')
periodo2 = request.POST.get('periodo2')
empresa3 = request.POST.get('empresa3')
funcao3 = request.POST.get('funcao3')
periodo3 = request.POST.get('periodo3')
funcaoObj = funcaoModel.objects.filter(id=funcaoID).get()
novoColaborador = cadastroSite(nome=nome,
sobrenome=sobrenome,
telefone=telefone,
celular=celular,
cpf=cpf,
rg=rg,
dataNasc=dataNasc,
email=email,
estadoCivil=estadoCivil,
escolaridade=escolaridade,
ehDeTresLagoas=resideEmTresLagoas,
trabalhouInomont=trabalhouInomont,
pqInomont=pqInomont,
experiencia=tempoExperiencia,
funcao=funcaoObj,
empresa1=empresa1,
funcao1=funcao1,
periodo1=periodo1,
empresa2=empresa2,
funcao2=funcao2,
periodo2=periodo2,
empresa3=empresa3,
funcao3=funcao1,
periodo3=periodo3)
novoColaborador.save()
msgConfirmacao = "Colaborador salvo com sucesso!"
return render (request, 'gerencia/colaboradores/colaboradorNovo.html', {'title':'Novo Colaborador',
'msgTelaInicial':msgTelaInicial,
'msgConfirmacao':msgConfirmacao})
if request.method == 'GET' and request.GET.get('colaboradorSiteID') != None:
colaboradorSiteID = request.GET.get('colaboradorSiteID')
colaboradorSiteObj = cadastroSite.objects.filter(id=colaboradorSiteID).get()
todasFuncoes = funcaoModel.objects.all().order_by('nome')
return render (request, 'gerencia/colaboradores/colaboradorNovo.html', {'title':'Novo Colaborador',
'msgTelaInicial':msgTelaInicial,
'colaboradorSiteObj':colaboradorSiteObj,
'todasFuncoes':todasFuncoes})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def colaboradoresVisualizar(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
colaboradoresCadastrados = colaboradorModel.objects.all().order_by('funcao')
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == "POST" and request.POST.get('colaboradorID') != None:
colaboradorID = request.POST.get('colaboradorID')
colaboradorObj = colaboradorModel.objects.filter(id=colaboradorID).get()
return render (request, 'gerencia/colaboradores/colaboradorVisualizar1.html', {'title':'Visualizar Colaborador',
'msgTelaInicial':msgTelaInicial,
'colaboradorObj':colaboradorObj})
return render (request, 'gerencia/colaboradores/colaboradorVisualizar.html', {'title':'Visualizar Colaborador',
'msgTelaInicial':msgTelaInicial,
'colaboradoresCadastrados':colaboradoresCadastrados})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def colaboradoresSite(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
colaboradoresSite = cadastroSite.objects.filter(estado=1).all().order_by('dataCadastro')
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
return render (request, 'gerencia/colaboradores/colaboradorSite.html', {'title':'Colaboradores Site',
'msgTelaInicial':msgTelaInicial,
'colaboradoresSite':colaboradoresSite})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def colaboradoresSiteVisualizar(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
colaboradoresSite = cadastroSite.objects.all().order_by('funcao')
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == "POST" and request.POST.get('colaboradorID') != None:
colaboradorID = request.POST.get('colaboradorID')
colaboradorObj = cadastroSite.objects.all().filter(id=colaboradorID).get()
return render (request, 'gerencia/colaboradores/colaboradorSiteVisualizar.html', {'title':'Visualizar Colaborador',
'msgTelaInicial':msgTelaInicial,
'colaboradorObj':colaboradorObj})
return render (request, 'gerencia/colaboradores/colaboradorSiteVisualizar.html', {'title':'Visualizar Colaborador',
'msgTelaInicial':msgTelaInicial,
'colaboradoresSite':colaboradoresSite,
'colaboradorObj':colaboradorObj})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
#Fornecedores
def fornecedores(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
return render (request, 'gerencia/fornecedores/home.html', {'title':'Home',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def fornecedoresNovo(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == "POST":
nome = request.POST.get('nome')
contatoPrincipal = request.POST.get('contatoPrincipal')
email = request.POST.get('email')
cnpj = request.POST.get('cnpj')
cep = request.POST.get('cep')
telefone = request.POST.get('telefone')
celular = request.POST.get('celular')
endereco = request.POST.get('endereco')
numero = request.POST.get('numero')
bairro = request.POST.get('bairro')
cidade = request.POST.get('cidade')
uf = request.POST.get('uf')
fornecedorObj = fornecedorModel(nome=nome, contatoPrincipal=contatoPrincipal, email=email, cnpj=cnpj, telefone=telefone, celular=celular, cep=cep, endereco=endereco, numero=numero, bairro=bairro, cidade=cidade, uf=uf)
fornecedorObj.save()
msgConfirmacao = "Fornecedor salvo com sucesso!"
return render (request, 'gerencia/fornecedores/fornecedorNovo.html', {'title':'Novo Fornecedor',
'msgTelaInicial':msgTelaInicial,
'msgConfirmacao':msgConfirmacao})
return render (request, 'gerencia/fornecedores/fornecedorNovo.html', {'title':'Novo Fornecedor',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def fornecedoresVisualizar(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
fornecedores = fornecedorModel.objects.all().order_by('nome')
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == "POST" and request.POST.get('fornecedorID') != None:
fornecedorID = request.POST.get('fornecedorID')
fornecedorObj = fornecedorModel.objects.filter(id=fornecedorID).get()
return render (request, 'gerencia/fornecedores/fornecedorVisualizar1.html', {'title':'Visualizar Fornecedor',
'msgTelaInicial':msgTelaInicial,
'fornecedorObj':fornecedorObj})
return render (request, 'gerencia/fornecedores/fornecedorVisualizar.html', {'title':'Visualizar Fornecedor',
'msgTelaInicial':msgTelaInicial,
'fornecedores':fornecedores})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def fornecedoresEditar(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
fornecedores = fornecedorModel.objects.all().order_by('nome')
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == "POST" and request.POST.get('fornecedorID') != None:
fornecedorID = request.POST.get('fornecedorID')
fornecedorObj = fornecedorModel.objects.filter(id=fornecedorID).get()
return render (request, 'gerencia/fornecedores/fornecedorEditar.html', {'title':'Editar Fornecedor',
'msgTelaInicial':msgTelaInicial,
'fornecedorObj':fornecedorObj})
return render (request, 'gerencia/fornecedores/fornecedorVisualizar.html', {'title':'Visualizar Fornecedor',
'msgTelaInicial':msgTelaInicial,
'fornecedores':fornecedores})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def fornecedoresSalvar(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == "POST":
fornecedorID = request.POST.get('fornecedorID')
fornecedorObj = fornecedorModel.objects.filter(id=fornecedorID).get()
nome = request.POST.get('nome')
contatoPrincipal = request.POST.get('contatoPrincipal')
email = request.POST.get('email')
cnpj = request.POST.get('cnpj')
cep = request.POST.get('cep')
telefone = request.POST.get('telefone')
celular = request.POST.get('celular')
endereco = request.POST.get('endereco')
numero = request.POST.get('numero')
bairro = request.POST.get('bairro')
cidade = request.POST.get('cidade')
uf = request.POST.get('uf')
fornecedorObj.nome = nome
fornecedorObj.contatoPrincipal = contatoPrincipal
fornecedorObj.email = email
fornecedorObj.cnpj = cnpj
fornecedorObj.cep = cep
fornecedorObj.telefone = telefone
fornecedorObj.celular = celular
fornecedorObj.endereco = endereco
fornecedorObj.numero = numero
fornecedorObj.bairro = bairro
fornecedorObj.cidade = cidade
fornecedorObj.uf = uf
fornecedorObj.save()
msgConfirmacao = "Fornecedor editado com sucesso!"
return render (request, 'gerencia/fornecedores/fornecedorEditar.html', {'title':'Editar Fornecedor',
'msgTelaInicial':msgTelaInicial,
'msgConfirmacao':msgConfirmacao,
'fornecedorObj':fornecedorObj})
return render (request, 'gerencia/fornecedores/fornecedorNovo.html', {'title':'Novo Fornecedor',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
#Funções
def funcaoHome(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
return render (request, 'gerencia/funcoes/home.html', {'title':'Funeções',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def funcaoNovo(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == 'POST' and request.POST.get('nome'):
nome = request.POST.get('nome')
observacao = request.POST.get('observacao')
novaFuncao = funcaoModel(nome=nome, observacao=observacao)
novaFuncao.save()
msgConfirmacao = "Nova função cadastrada com sucesso!"
return render (request, 'gerencia/funcoes/funcaoNovo.html', {'title':'Nova Função',
'msgTelaInicial':msgTelaInicial,
'msgConfirmacao':msgConfirmacao})
return render (request, 'gerencia/funcoes/funcaoNovo.html', {'title':'Nova Função',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def funcaoVisualizar(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
funcoes = funcaoModel.objects.all().order_by('id')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == 'POST' and request.POST.get('funcaoID'):
funcaoID = request.POST.get('funcaoID')
funcaoObj = funcaoModel.objects.filter(id=funcaoID).get()
return render (request, 'gerencia/funcoes/funcaoEditar.html', {'title':'Editar Função',
'msgTelaInicial':msgTelaInicial,
'funcaoObj':funcaoObj})
return render (request, 'gerencia/funcoes/funcaoVisualizar.html', {'title':'Visualizar Função',
'msgTelaInicial':msgTelaInicial,
'funcoes':funcoes})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def funcaoSalvar(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
funcoes = funcaoModel.objects.all().order_by('id')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == 'POST' and request.POST.get('funcaoID'):
funcaoID = request.POST.get('funcaoID')
funcaoObj = funcaoModel.objects.filter(id=funcaoID).get()
nome = request.POST.get('nome')
observacao = request.POST.get('observacao')
funcaoObj.nome = nome
funcaoObj.observacao = observacao
funcaoObj.save()
msgConfirmacao = "Função editada com sucesso!"
return render (request, 'gerencia/funcoes/funcaoVisualizar.html', {'title':'Visualizar Função',
'msgTelaInicial':msgTelaInicial,
'funcoes':funcoes,
'msgConfirmacao':msgConfirmacao})
return render (request, 'gerencia/funcoes/funcaoVisualizar.html', {'title':'Visualizar Função',
'msgTelaInicial':msgTelaInicial,
'funcoes':funcoes})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
#Clientes
def clientesHome(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
return render (request, 'gerencia/clientes/home.html', {'title':'Clientes',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def clientesNovo(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == 'POST' and request.POST.get('nome'):
nome = request.POST.get('nome')
contato = request.POST.get('contato')
cnpj = request.POST.get('cnpj')
email = request.POST.get('email')
telefone = request.POST.get('telefone')
cep = request.POST.get('cep')
endereco = request.POST.get('endereco')
numero = request.POST.get('numero')
bairro = request.POST.get('bairro')
cidade = request.POST.get('cidade')
uf = request.POST.get('uf')
novoCliente = clienteModel(nome=nome, contato=contato, cnpj=cnpj, email=email, telefone=telefone, cep=cep, endereco=endereco, numero=numero, bairro=bairro, cidade=cidade, uf=uf)
novoCliente.save()
msgConfirmacao = "Novo cliente cadastrado com sucesso!"
return render (request, 'gerencia/clientes/clienteNovo.html', {'title':'Novo Cliente',
'msgTelaInicial':msgTelaInicial,
'msgConfirmacao':msgConfirmacao})
return render (request, 'gerencia/clientes/clienteNovo.html', {'title':'Novo Cliente',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def clientesVisualizar(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
clientes = clienteModel.objects.all().order_by('id')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == 'POST' and request.POST.get('clienteID'):
clienteID = request.POST.get('clienteID')
clienteObj = clienteModel.objects.filter(id=clienteID).get()
return render (request, 'gerencia/clientes/clienteVisualizar1.html', {'title':'Visualizar Cliente',
'msgTelaInicial':msgTelaInicial,
'clienteObj':clienteObj})
return render (request, 'gerencia/clientes/clienteVisualizar.html', {'title':'Visualizar Cliente',
'msgTelaInicial':msgTelaInicial,
'clientes':clientes})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def clientesEditar(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == 'GET':
clienteID = request.GET.get('clienteID')
clienteObj = clienteModel.objects.filter(id=clienteID).get()
return render (request, 'gerencia/clientes/clienteEditar.html', {'title':'Editar Cliente',
'msgTelaInicial':msgTelaInicial,
'clienteObj':clienteObj})
if request.method == 'POST' and request.POST.get('clienteID'):
clienteID = request.POST.get('clienteID')
clienteObj = clienteModel.objects.filter(id=clienteID).get()
nome = request.POST.get('nome')
contato = request.POST.get('contato')
cnpj = request.POST.get('cnpj')
email = request.POST.get('email')
telefone = request.POST.get('telefone')
cep = request.POST.get('cep')
endereco = request.POST.get('endereco')
numero = request.POST.get('numero')
bairro = request.POST.get('bairro')
cidade = request.POST.get('cidade')
uf = request.POST.get('uf')
clienteObj.nome = nome
clienteObj.contato = contato
clienteObj.cnpj = cnpj
clienteObj.email = email
clienteObj.telefone = telefone
clienteObj.cep = cep
clienteObj.endereco = endereco
clienteObj.numero = numero
clienteObj.bairro = bairro
clienteObj.cidade = cidade
clienteObj.uf = uf
clienteObj.save()
msgConfirmacao = "Cliente editado com sucesso!"
return render (request, 'gerencia/clientes/clienteVisualizar1.html', {'title':'Visualizar Cliente',
'msgTelaInicial':msgTelaInicial,
'clienteObj':clienteObj,
'msgConfirmacao':msgConfirmacao})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
#Orçamentos
def orcamentosHome(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
return render (request, 'gerencia/orcamentos/home.html', {'title':'Orçamentos',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
#Estoque
def estoqueHome(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
return render (request, 'gerencia/estoque/home.html', {'title':'Estoque',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
#Equipamentos
def equipamentosHome(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
return render (request, 'gerencia/estoque/equipamentos/home.html', {'title':'Serviços',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def equipamentosNovo(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == 'POST' and request.POST.get('nome'):
nome = request.POST.get('nome')
observacao = request.POST.get('observacao')
novaFuncao = funcaoModel(nome=nome, observacao=observacao)
novaFuncao.save()
msgConfirmacao = "Novo serviço cadastrado com sucesso!"
return render (request, 'gerencia/estoque/equipamentos/equipamentoNovo.html', {'title':'Novo Serviços',
'msgTelaInicial':msgTelaInicial,
'msgConfirmacao':msgConfirmacao})
return render (request, 'gerencia/estoque/equipamentos/equipamentoNovo.html', {'title':'Novo Serviços',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def equipamentosVisualizar(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
funcoes = funcaoModel.objects.all().order_by('id')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == 'POST' and request.POST.get('funcaoID'):
funcaoID = request.POST.get('funcaoID')
funcaoObj = funcaoModel.objects.filter(id=funcaoID).get()
return render (request, 'gerencia/estoque/equipamentos/equipamentoEditar.html', {'title':'Editar Serviço',
'msgTelaInicial':msgTelaInicial,
'funcaoObj':funcaoObj})
return render (request, 'gerencia/estoque/equipamentos/equipamentoVisualizar.html', {'title':'Visualizar Serviço',
'msgTelaInicial':msgTelaInicial,
'funcoes':funcoes})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def equipamentosSalvar(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
funcoes = funcaoModel.objects.all().order_by('id')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == 'POST' and request.POST.get('funcaoID'):
funcaoID = request.POST.get('funcaoID')
funcaoObj = funcaoModel.objects.filter(id=funcaoID).get()
nome = request.POST.get('nome')
observacao = request.POST.get('observacao')
funcaoObj.nome = nome
funcaoObj.observacao = observacao
funcaoObj.save()
msgConfirmacao = "Função editada com sucesso!"
return render (request, 'gerencia/estoque/equipamentos/equipamentoVisualizar.html', {'title':'Visualizar Serviços',
'msgTelaInicial':msgTelaInicial,
'funcoes':funcoes,
'msgConfirmacao':msgConfirmacao})
return render (request, 'gerencia/estoque/equipamentos/equipamentoVisualizar.html', {'title':'Visualizar Serviços',
'msgTelaInicial':msgTelaInicial,
'funcoes':funcoes})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
#Contas
def contasHome(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
return render (request, 'gerencia/contas/home.html', {'title':'Contas',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def contasRelatorioHome(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
return render (request, 'gerencia/contas/relatorios.html', {'title':'Relatórios',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def contasPagarHome(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
return render (request, 'gerencia/contas/pagar/home.html', {'title':'Contas a pagar',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def contasReceberHome(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
return render (request, 'gerencia/contas/receber/home.html', {'title':'Contas a receber',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def contasPagarNovo(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == "POST" and request.POST.get('nome') != None:
nome = request.POST.get('nome')
dataVencimento = request.POST.get('dataVencimento')
if request.POST.get('fixa') != None:
fixa = "1"
else:
fixa = "2"
observacao = request.POST.get('observacao')
valor = request.POST.get('valor')
novaContaPagar = contaPagarModel(nome=nome, observacao=observacao, dataVencimento=dataVencimento, fixa=fixa, valor=valor)
novaContaPagar.save()
msgConfirmacao = "Conta registrada com sucesso!"
return render (request, 'gerencia/contas/pagar/pagarNovo.html', {'title':'Nova conta a pagar',
'msgTelaInicial':msgTelaInicial,
'msgConfirmacao':msgConfirmacao})
return render (request, 'gerencia/contas/pagar/pagarNovo.html', {'title':'Nova conta a pagar',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def contasPagarVisualizar(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
contas = contaPagarModel.objects.all()
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == "POST" and request.POST.get('contaID') != None:
contaID = request.POST.get('contaID')
contaObj = contaPagarModel.objects.filter(id=contaID).get()
return render (request, 'gerencia/contas/pagar/pagarVisualizar.html', {'title':'Visualizar conta a pagar',
'msgTelaInicial':msgTelaInicial,
'contaObj':contaObj})
return render (request, 'gerencia/contas/pagar/pagarBusca.html', {'title':'Visualizar conta a pagar',
'msgTelaInicial':msgTelaInicial,
'contas':contas})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def contasPagarEditar(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
try:
contaID = request.GET.get('contaID')
contaObj = contaPagarModel.objects.filter(id=contaID).get()
except:
print("Erro ao procurar com GET")
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == "POST" and request.POST.get('contaID') != None:
contaID = request.POST.get('contaID')
contaObj = contaPagarModel.objects.filter(id=contaID).get()
nome = request.POST.get('nome')
dataVencimento = request.POST.get('dataVencimento')
if request.POST.get('fixa') != None:
fixa = "1"
else:
fixa = "2"
observacao = request.POST.get('observacao')
valor = request.POST.get('valor')
contaObj.nome = nome
contaObj.dataVencimento = dataVencimento
contaObj.fixa = fixa
contaObj.observacao = observacao
contaObj.valor = valor
contaObj.save()
msgConfirmacao = "Conta alterada com sucesso!"
contas = contaPagarModel.objects.all()
return render (request, 'gerencia/contas/pagar/pagarBusca.html', {'title':'Editar conta a pagar',
'msgTelaInicial':msgTelaInicial,
'contaObj':contaObj,
'msgConfirmacao':msgConfirmacao,
'contas':contas})
return render (request, 'gerencia/contas/pagar/pagarEditar.html', {'title':'Editar conta a pagar',
'msgTelaInicial':msgTelaInicial,
'contaObj':contaObj})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def contasReceberNovo(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == "POST" and request.POST.get != None:
nome = request.POST.get('nome')
dataVencimento = request.POST.get('dataVencimento')
if request.POST.get('fixa') != None:
fixa = "1"
else:
fixa = "2"
observacao = request.POST.get('observacao')
valor = request.POST.get('valor')
novaContaReceber = contaReceberModel(nome=nome, observacao=observacao, dataVencimento=dataVencimento, fixa=fixa, valor=valor)
novaContaReceber.save()
msgConfirmacao = "Conta registrada com sucesso!"
return render (request, 'gerencia/contas/receber/receberNovo.html', {'title':'Nova conta a receber',
'msgTelaInicial':msgTelaInicial,
'msgConfirmacao':msgConfirmacao})
return render (request, 'gerencia/contas/receber/receberNovo.html', {'title':'Nova conta a receber',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def contasReceberVisualizar(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
contas = contaReceberModel.objects.all()
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == "POST" and request.POST.get('contaID') != None:
contaID = request.POST.get('contaID')
contaObj = contaReceberModel.objects.filter(id=contaID).get()
return render (request, 'gerencia/contas/receber/receberVisualizar.html', {'title':'Visualizar conta a receber',
'msgTelaInicial':msgTelaInicial,
'contaObj':contaObj})
return render (request, 'gerencia/contas/receber/receberBusca.html', {'title':'Visualizar conta a receber',
'msgTelaInicial':msgTelaInicial,
'contas':contas})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def contasReceberEditar(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
try:
contaID = request.GET.get('contaID')
contaObj = contaReceberModel.objects.filter(id=contaID).get()
except:
print("Erro ao procurar com GET")
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
if request.method == "POST" and request.POST.get('contaID') != None:
contaID = request.POST.get('contaID')
contaObj = contaReceberModel.objects.filter(id=contaID).get()
nome = request.POST.get('nome')
dataVencimento = request.POST.get('dataVencimento')
if request.POST.get('fixa') != None:
fixa = "1"
else:
fixa = "2"
observacao = request.POST.get('observacao')
valor = request.POST.get('valor')
contaObj.nome = nome
contaObj.dataVencimento = dataVencimento
contaObj.fixa = fixa
contaObj.observacao = observacao
contaObj.valor = valor
contaObj.save()
msgConfirmacao = "Conta alterada com sucesso!"
contas = contaPagarModel.objects.all()
return render (request, 'gerencia/contas/receber/receberBusca.html', {'title':'Editar conta a receber',
'msgTelaInicial':msgTelaInicial,
'contaObj':contaObj,
'msgConfirmacao':msgConfirmacao,
'contas':contas})
return render (request, 'gerencia/contas/receber/receberEditar.html', {'title':'Editar conta a receber',
'msgTelaInicial':msgTelaInicial,
'contaObj':contaObj})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
#Caixa
def caixaHome(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
return render (request, 'gerencia/caixa/home.html', {'title':'Caixa',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def caixaEntradaNovo(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
return render (request, 'gerencia/caixa/entradaNovo.html', {'title':'Nova entrada',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def caixaSaidaNovo(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
return render (request, 'gerencia/caixa/saidaNovo.html', {'title':'Nova saída',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'})
def balancoHome(request):
if request.user.is_authenticated:
if request.user.last_name == "GERENCIA":
now = datetime.datetime.now().strftime('%H')
now = int(now)
msgTelaInicial = "Olá, " + request.user.get_short_name()
if now >= 4 and now <= 11:
msgTelaInicial = "Bom dia, " + request.user.get_short_name()
elif now > 11 and now < 18:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
elif now >= 18 and now < 4:
msgTelaInicial = "Boa Tarde, " + request.user.get_short_name()
return render (request, 'gerencia/caixa/balanco.html', {'title':'Balanço',
'msgTelaInicial':msgTelaInicial})
return render (request, 'site/login.html', {'title':'Login'})
return render (request, 'site/login.html', {'title':'Login'}) | [
"[email protected]"
]
| |
2765c72d48178ec65db0c1e6936c7650767cba82 | d8a23825c56920d5125c5bc2ca89fecb7ac61c4a | /integral_vector_w.py | ba9c92cdf63bf8c1eed14fdc333187d90b61d701 | []
| no_license | eranbTAU/DronDetection_ML_ALGO | 45e8f24bcf3cdc531ddf273d52b4829ab4596f00 | 22e27cb92c4b8767bde144936e5d86fa6ba89ae3 | refs/heads/master | 2022-03-29T09:59:05.458262 | 2019-12-04T11:24:09 | 2019-12-04T11:24:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,604 | py | #ERAN BAMANI
#17.12.16
#integral_vector_w function
#===============================================
import numpy as np
import pandas as pd
import random
import cv2
import matplotlib.pyplot as plt
from GDecent import *
# --------------------------
def integralImage_sum(ii,x,y,new_width,new_length):
A = ii[x, y]
B = ii[x + new_width, y]
C = ii[x, y + new_length]
D = ii[x + new_width, y + new_length]
sum = D + A - B - C
return sum
def w_vector(x_train,x_test,y_train,y_test):
c_vec = 2**(np.linspace(-5,2,15))
EP = 5
err_vec = np.zeros((1, len(c_vec)))
n, m = np.size(x_train)
N, M = np.size(x_test)
train_norm = np.zeros((n, m))
test_norm = np.zeros((N, M))
max_train = np.zeros((1, m))
max_test = np.zeros((1, M))
min_train = np.zeros((1, m))
min_test = np.zeros((1, M))
for i in range(m):
max_train[i] = max(x_train[:, i])
min_train[i] = min(x_train[:, i])
train_norm[:, i] = (x_train[:, i] - min_train[i]) / (max_train[i] - min_train[i])
for j in range(M):
max_test[j] = max(x_test[:, j])
min_test[j] = min(x_test[:, j])
test_norm[:, j] = (x_test[:, j] - min_test[i])/(max_test[i] - min_test[i])
for q in range(len(c_vec)):
temp = c_vec[q]
err_avg = 0
for ii in range(EP):
w, b, e = SGD(train_norm, y_train, temp)
err_vec[q] = e / EP
min_c = c_vec(err_vec == min(err_vec))
w = SGD(x_train, y_train, min_c)
w = np.mean(w)
return w, min_c
| [
"[email protected]"
]
| |
0ed941616c8a5ccb0dddbae4449753711b1cdffa | 9b476bc2491c132006bbd04c74e95d1924065dbd | /Lab2codec_PRAC.py | ed539769aff4726f3f8341ceb4ed5c5171f9a6a2 | []
| no_license | eoinpayne/Python | 6b949e78f574645aa0b151eaa8abff1c8632d2ba | 5e7fa7d30da5ace3821af8d19f9885481008dfcf | refs/heads/master | 2021-01-10T12:38:19.958363 | 2016-02-12T18:38:42 | 2016-02-12T18:38:42 | 51,600,935 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 334 | py |
def check_word(word):
if len(word) <=1:
print ("Please type word")
else:
translation = ((word[1:]) + (word[0] + "ay"))
#translation = (word[1] + "ay")
return translation
def main():
word = str(input("Enter word: "))
translation = (check_word(word))
print (translation)
main()
| [
"[email protected]"
]
| |
2fdb7660c7e1846dad4006fc484535aefb0750e2 | f1233261dcbee20a3393e175f96e108138f1c6d1 | /instaclone/urls.py | 3fcbf096762f47e1e4c9c9462b91526695d6f197 | []
| no_license | GisangLee/instaClone | 23c0d19693b1383d3105299fc19c77093a5763db | b6ab95d9e89f979b82f53807b38fad9eb501d130 | refs/heads/master | 2022-11-06T16:55:36.195441 | 2020-06-17T02:07:54 | 2020-06-17T02:07:54 | 272,372,779 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,019 | py | from django.conf import settings
from django.contrib import admin
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.conf.urls.static import static
from django.urls import path, include
from django.views.generic import RedirectView
from django_pydenticon.views import image as pydenticon_image
@login_required
def root(request):
return render(request, 'root.html')
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('accounts.urls')),
path('identicon/image/<path:data>/',
pydenticon_image, name='pydenticon_image'),
path('instagram/', include('instagram.urls')),
path('', login_required(RedirectView.as_view(
pattern_name="instagram:index")), name="root"),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns += [
path("__debug__/", include(debug_toolbar.urls)),
]
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
| [
"[email protected]"
]
| |
049bc00faea5418346385574bc6c905ee3785011 | dddb781a8bd9d30e59201f8a96e06b22feb2c9eb | /python/hello_world.py | 6f6d5ea62bea9b2f7fd00bec481901dc6be37ff5 | []
| no_license | elewisQA/Example | 57c799d76e8143d4afa52fdab18ff824941e1578 | 9fa8edf9f3500bf7a109d9e4392267839914b940 | refs/heads/master | 2022-12-07T21:46:12.174865 | 2020-08-20T10:53:39 | 2020-08-20T10:53:39 | 288,949,036 | 0 | 0 | null | 2020-08-20T10:53:40 | 2020-08-20T08:24:45 | Python | UTF-8 | Python | false | false | 66 | py | # This is a sample python program
print("Hello!")
print("World!")
| [
"[email protected]"
]
| |
64ee18e6b33ccd293838fbfd6a3b6a9ce8560ff3 | 0c68477d24ebb4d16d04fdabdc59a5a587347374 | /Data-Science/statics-datas.py | 8fa3fdc07dbcbcd99569845012dd409635b3eda1 | []
| no_license | Sousa83/estudos-ia | 8f55a106d5a0b35d01bbf6778b11ad461bb704ff | a6fd364de7f8ac48b029da83bbb9817db12da5a3 | refs/heads/master | 2023-08-15T04:28:46.526824 | 2021-10-07T01:08:23 | 2021-10-07T01:08:23 | 364,556,746 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 550 | py | import pandas as pd
dic = {
'students': ['ricardo', 'aline', 'herran', 'patrick', 'grabiel'],
'age': [19, 17, 18, 18, 18],
'note': [8.9, 8.9, 7.9, 10.0, 9.99]
}
df = pd.DataFrame(dic, columns=['students', 'age', 'note'])
#Maior valor: em Strings são mostrados por ordem alfabetica
#As informações são sobre os dados sem relação alguma de registro
df.max()
df['age'].max()
#Menor valor
df.min()
#Média: String não é possível fazer médias
df.mean()
#Mediana
df.median()
#Soma: A soma, nas strings, é a concatenação
df.sum()
| [
"[email protected]"
]
| |
0d155686d2b7d638897fc2d02dc556dd3da8babb | ce76b3ef70b885d7c354b6ddb8447d111548e0f1 | /other_time/last_part_and_thing/problem_or_world.py | e42537b5fd907d85a61cab4911bd521a6bc81f4a | []
| no_license | JingkaiTang/github-play | 9bdca4115eee94a7b5e4ae9d3d6052514729ff21 | 51b550425a91a97480714fe9bc63cb5112f6f729 | refs/heads/master | 2021-01-20T20:18:21.249162 | 2016-08-19T07:20:12 | 2016-08-19T07:20:12 | 60,834,519 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 236 | py |
#! /usr/bin/env python
def feel_eye(str_arg):
early_life(str_arg)
print('find_next_part_about_small_person')
def early_life(str_arg):
print(str_arg)
if __name__ == '__main__':
feel_eye('take_company_at_little_case')
| [
"[email protected]"
]
| |
755035fe63a1cd62b201b7bbffcfb1d463736a5c | 1610fe2d9c5ee000942033bc7b76d98a9d7fe6b9 | /2.py | 7756e29e40b807921234eec079f28cb8a3d7fa14 | []
| no_license | bondlee/leetcode | 806cd94cf0307f8ec38aa769b1a9c2dded497b6a | 04919147dca5b4772e3414cc2e967033c229e8e5 | refs/heads/master | 2021-01-19T01:27:05.513852 | 2016-07-23T13:57:42 | 2016-07-23T13:57:42 | 61,933,312 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 89 | py | # coding: utf-8
# Created by bondlee on 2016/5/31
if __name__ == '__main__':
pass | [
"[email protected]"
]
| |
5e8e9e4cc04b87577c04e4b09ce745dd68a85d04 | 706fcc0630a2a1befa32e8d0e9e0a61978dcc947 | /config.py | 7fcc7def7a3c78d71daf7c805bc812e5aabcc542 | []
| no_license | paulgowdy/hal_split | a8f731a5a6e77f605d45de345d1c48bbc774738d | f618a6b1a132e192f4778c237a92c86f24540ca0 | refs/heads/master | 2022-11-17T00:51:37.343265 | 2020-07-07T22:25:49 | 2020-07-07T22:25:49 | 277,934,370 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 187 | py | BOARD_SIZE = 9
MAX_NB_SHIPS = 2
NB_SHIP_ACTIONS = 5
#TRAIN_EPISODES = 10
STEPS_PER_EP = 200
GAMMA = 0.99
PPO_BATCHES = 10000000
PPO_STEPS = 32
LOSS_CLIPPING = 0.2
ENTROPY_LOSS = 5e-2
| [
"[email protected]"
]
| |
d8523d8ab509471206516117cb9d5228bbe36542 | c45b49f5b32c0371042a625d0e2058a67e365aac | /midterm_exam/problem3.py | 050c9184f14b867654e7bd173d78734eac294389 | []
| no_license | mahendrark/Python-MOOC | 368deea274a0f2c3babd17462cee73444792165e | cd1397b5ee54ddfcbb4330b5b9ead809e6421a79 | refs/heads/master | 2021-01-06T09:52:42.861608 | 2020-02-23T20:45:38 | 2020-02-23T20:45:38 | 241,286,796 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,637 | py | # Write a Python function, twoQuadratics, that takes in two sets of coefficients
# and x-values and prints the sum of the results of evaluating two quadratic equations.
# It does not do anything else.
# That is, you should evaluate and print the result of the following equation:
# (a1∗(x1^2))+(b1∗x1)+c1+(a2∗(x2^2))+(b2∗x2)+c2
"""
You are given the following function, evalQuadratic
def evalQuadratic(a, b, c, x):
'''
a, b, c: numerical values for the coefficients of a quadratic equation
x: numerical value at which to evaluate the quadratic.
'''
return a*x*x + b*x + c
"""
"""
Use the given function (you don't need to redefine evalQuadratic in this box; when you call evalQuadratic, our definition will be used).
def twoQuadratics(a1, b1, c1, x1, a2, b2, c2, x2):
'''
a1, b1, c1: one set of coefficients of a quadratic equation
a2, b2, c2: another set of coefficients of a quadratic equation
x1, x2: values at which to evaluate the quadratics
'''
# Your code here
"""
# SOLUTION:
def evalQuadratic(a, b, c, x):
'''
a, b, c: numerical values for the coefficients of a quadratic equation
x: numerical value at which to evaluate the quadratic.
'''
return a*x*x + b*x + c
def twoQuadratics(a1, b1, c1, x1, a2, b2, c2, x2):
'''
a1, b1, c1: one set of coefficients of a quadratic equation
a2, b2, c2: another set of coefficients of a quadratic equation
x1, x2: values at which to evaluate the quadratics
'''
sumOfquads = evalQuadratic(a1, b1, c1, x1) + evalQuadratic(a2, b2, c2, x2)
print(sumOfquads)
twoQuadratics(1,2,3,4,5,6,7,8)
| [
"[email protected]"
]
| |
f27732e2f3b66542ab4ff218cce203fc42ec0538 | 1fca08dcb7f06eb9d7c52e6ec153fab7056f95a9 | /YoloTensorRTWrapper.py | eb750990554ba8450076f119c76d6b17b4c74298 | []
| no_license | ankhafizov/EvrazHackCV | c2c00806dd64a79b84a74614c716f7c1d73539b6 | 09f8c3ed8f7921f4bd51688b9b035119ca49aa30 | refs/heads/main | 2023-08-20T04:42:17.841644 | 2021-10-31T06:53:40 | 2021-10-31T06:53:40 | 422,587,500 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 15,114 | py | """
An example that uses TensorRT's Python api to make inferences.
"""
import ctypes
import os
import shutil
import random
import sys
import threading
import time
import cv2
import numpy as np
import pycuda.autoinit
import pycuda.driver as cuda
import tensorrt as trt
CONF_THRESH = 0.5
IOU_THRESHOLD = 0.4
def get_img_path_batches(batch_size, img_dir):
ret = []
batch = []
for root, dirs, files in os.walk(img_dir):
for name in files:
if len(batch) == batch_size:
ret.append(batch)
batch = []
batch.append(os.path.join(root, name))
if len(batch) > 0:
ret.append(batch)
return ret
def plot_one_box(x, img, color=None, label=None, line_thickness=None):
"""
description: Plots one bounding box on image img,
this function comes from YoLov5 project.
param:
x: a box likes [x1,y1,x2,y2]
img: a opencv image object
color: color to draw rectangle, such as (0,255,0)
label: str
line_thickness: int
return:
no return
"""
tl = (
line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1
) # line/font thickness
color = color or [random.randint(0, 255) for _ in range(3)]
c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
if label:
tf = max(tl - 1, 1) # font thickness
t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filled
cv2.putText(
img,
label,
(c1[0], c1[1] - 2),
0,
tl / 3,
[225, 255, 255],
thickness=tf,
lineType=cv2.LINE_AA,
)
class YoLov5TRT(object):
"""
description: A YOLOv5 class that warps TensorRT ops, preprocess and postprocess ops.
"""
def __init__(self, engine_file_path):
# Create a Context on this device,
self.ctx = cuda.Device(0).make_context()
stream = cuda.Stream()
TRT_LOGGER = trt.Logger(trt.Logger.INFO)
runtime = trt.Runtime(TRT_LOGGER)
# Deserialize the engine from file
with open(engine_file_path, "rb") as f:
engine = runtime.deserialize_cuda_engine(f.read())
context = engine.create_execution_context()
host_inputs = []
cuda_inputs = []
host_outputs = []
cuda_outputs = []
bindings = []
for binding in engine:
print('bingding:', binding, engine.get_binding_shape(binding))
size = trt.volume(engine.get_binding_shape(binding)) * engine.max_batch_size
dtype = trt.nptype(engine.get_binding_dtype(binding))
# Allocate host and device buffers
host_mem = cuda.pagelocked_empty(size, dtype)
cuda_mem = cuda.mem_alloc(host_mem.nbytes)
# Append the device buffer to device bindings.
bindings.append(int(cuda_mem))
# Append to the appropriate list.
if engine.binding_is_input(binding):
self.input_w = engine.get_binding_shape(binding)[-1]
self.input_h = engine.get_binding_shape(binding)[-2]
host_inputs.append(host_mem)
cuda_inputs.append(cuda_mem)
else:
host_outputs.append(host_mem)
cuda_outputs.append(cuda_mem)
# Store
self.stream = stream
self.context = context
self.engine = engine
self.host_inputs = host_inputs
self.cuda_inputs = cuda_inputs
self.host_outputs = host_outputs
self.cuda_outputs = cuda_outputs
self.bindings = bindings
self.batch_size = engine.max_batch_size
def infer(self, raw_image_generator):
threading.Thread.__init__(self)
# Make self the active context, pushing it on top of the context stack.
self.ctx.push()
# Restore
stream = self.stream
context = self.context
engine = self.engine
host_inputs = self.host_inputs
cuda_inputs = self.cuda_inputs
host_outputs = self.host_outputs
cuda_outputs = self.cuda_outputs
bindings = self.bindings
# Do image preprocess
batch_image_raw = []
batch_origin_h = []
batch_origin_w = []
batch_input_image = np.empty(shape=[self.batch_size, 3, self.input_h, self.input_w])
for i, image_raw in enumerate(raw_image_generator):
input_image, image_raw, origin_h, origin_w = self.preprocess_image(image_raw)
batch_image_raw.append(image_raw)
batch_origin_h.append(origin_h)
batch_origin_w.append(origin_w)
np.copyto(batch_input_image[i], input_image)
batch_input_image = np.ascontiguousarray(batch_input_image)
# Copy input image to host buffer
np.copyto(host_inputs[0], batch_input_image.ravel())
start = time.time()
# Transfer input data to the GPU.
cuda.memcpy_htod_async(cuda_inputs[0], host_inputs[0], stream)
# Run inference.
context.execute_async(batch_size=self.batch_size, bindings=bindings, stream_handle=stream.handle)
# Transfer predictions back from the GPU.
cuda.memcpy_dtoh_async(host_outputs[0], cuda_outputs[0], stream)
# Synchronize the stream
stream.synchronize()
end = time.time()
# Remove any context from the top of the context stack, deactivating it.
self.ctx.pop()
# Here we use the first row of output in that batch_size = 1
output = host_outputs[0]
# Do postprocess
bboxes = []
for i in range(self.batch_size):
result_boxes, result_scores, result_classid = self.post_process(
output[i * 6001: (i + 1) * 6001], batch_origin_h[i], batch_origin_w[i]
)
""" - - - - - - - - - - - - - - - """
# Return rectangles, scores and labels of the original image
for j in range(len(result_boxes)):
box = result_boxes[j]
bboxes.append({'cat': int(result_classid[j]),
'score': result_scores[j],
'xmin': box[0]/batch_origin_w[0],
'ymin': box[1]/batch_origin_h[0],
'xmax': box[2]/batch_origin_w[0],
'ymax': box[3]/batch_origin_h[0]})
return bboxes, end - start
def destroy(self):
# Remove any context from the top of the context stack, deactivating it.
self.ctx.pop()
def get_raw_image(self, image_path_batch):
"""
description: Read an image from image path
"""
for img_path in image_path_batch:
yield cv2.imread(img_path)
def get_raw_image_zeros(self, image_path_batch=None):
"""
description: Ready data for warmup
"""
for _ in range(self.batch_size):
yield np.zeros([self.input_h, self.input_w, 3], dtype=np.uint8)
def preprocess_image(self, raw_bgr_image):
"""
description: Convert BGR image to RGB,
resize and pad it to target size, normalize to [0,1],
transform to NCHW format.
param:
input_image_path: str, image path
return:
image: the processed image
image_raw: the original image
h: original height
w: original width
"""
image_raw = raw_bgr_image
h, w, c = image_raw.shape
image = cv2.cvtColor(image_raw, cv2.COLOR_BGR2RGB)
# Calculate widht and height and paddings
r_w = self.input_w / w
r_h = self.input_h / h
if r_h > r_w:
tw = self.input_w
th = int(r_w * h)
tx1 = tx2 = 0
ty1 = int((self.input_h - th) / 2)
ty2 = self.input_h - th - ty1
else:
tw = int(r_h * w)
th = self.input_h
tx1 = int((self.input_w - tw) / 2)
tx2 = self.input_w - tw - tx1
ty1 = ty2 = 0
# Resize the image with long side while maintaining ratio
image = cv2.resize(image, (tw, th))
# Pad the short side with (128,128,128)
image = cv2.copyMakeBorder(
image, ty1, ty2, tx1, tx2, cv2.BORDER_CONSTANT, (128, 128, 128)
)
image = image.astype(np.float32)
# Normalize to [0,1]
image /= 255.0
# HWC to CHW format:
image = np.transpose(image, [2, 0, 1])
# CHW to NCHW format
image = np.expand_dims(image, axis=0)
# Convert the image to row-major order, also known as "C order":
image = np.ascontiguousarray(image)
return image, image_raw, h, w
def xywh2xyxy(self, origin_h, origin_w, x):
"""
description: Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
param:
origin_h: height of original image
origin_w: width of original image
x: A boxes numpy, each row is a box [center_x, center_y, w, h]
return:
y: A boxes numpy, each row is a box [x1, y1, x2, y2]
"""
y = np.zeros_like(x)
r_w = self.input_w / origin_w
r_h = self.input_h / origin_h
if r_h > r_w:
y[:, 0] = x[:, 0] - x[:, 2] / 2
y[:, 2] = x[:, 0] + x[:, 2] / 2
y[:, 1] = x[:, 1] - x[:, 3] / 2 - (self.input_h - r_w * origin_h) / 2
y[:, 3] = x[:, 1] + x[:, 3] / 2 - (self.input_h - r_w * origin_h) / 2
y /= r_w
else:
y[:, 0] = x[:, 0] - x[:, 2] / 2 - (self.input_w - r_h * origin_w) / 2
y[:, 2] = x[:, 0] + x[:, 2] / 2 - (self.input_w - r_h * origin_w) / 2
y[:, 1] = x[:, 1] - x[:, 3] / 2
y[:, 3] = x[:, 1] + x[:, 3] / 2
y /= r_h
return y
def post_process(self, output, origin_h, origin_w):
"""
description: postprocess the prediction
param:
output: A numpy likes [num_boxes,cx,cy,w,h,conf,cls_id, cx,cy,w,h,conf,cls_id, ...]
origin_h: height of original image
origin_w: width of original image
return:
result_boxes: finally boxes, a boxes numpy, each row is a box [x1, y1, x2, y2]
result_scores: finally scores, a numpy, each element is the score correspoing to box
result_classid: finally classid, a numpy, each element is the classid correspoing to box
"""
# Get the num of boxes detected
num = int(output[0])
# Reshape to a two dimentional ndarray
pred = np.reshape(output[1:], (-1, 6))[:num, :]
# Do nms
boxes = self.non_max_suppression(pred, origin_h, origin_w, conf_thres=CONF_THRESH, nms_thres=IOU_THRESHOLD)
result_boxes = boxes[:, :4] if len(boxes) else np.array([])
result_scores = boxes[:, 4] if len(boxes) else np.array([])
result_classid = boxes[:, 5] if len(boxes) else np.array([])
return result_boxes, result_scores, result_classid
def bbox_iou(self, box1, box2, x1y1x2y2=True):
"""
description: compute the IoU of two bounding boxes
param:
box1: A box coordinate (can be (x1, y1, x2, y2) or (x, y, w, h))
box2: A box coordinate (can be (x1, y1, x2, y2) or (x, y, w, h))
x1y1x2y2: select the coordinate format
return:
iou: computed iou
"""
if not x1y1x2y2:
# Transform from center and width to exact coordinates
b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2
b1_y1, b1_y2 = box1[:, 1] - box1[:, 3] / 2, box1[:, 1] + box1[:, 3] / 2
b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, box2[:, 0] + box2[:, 2] / 2
b2_y1, b2_y2 = box2[:, 1] - box2[:, 3] / 2, box2[:, 1] + box2[:, 3] / 2
else:
# Get the coordinates of bounding boxes
b1_x1, b1_y1, b1_x2, b1_y2 = box1[:, 0], box1[:, 1], box1[:, 2], box1[:, 3]
b2_x1, b2_y1, b2_x2, b2_y2 = box2[:, 0], box2[:, 1], box2[:, 2], box2[:, 3]
# Get the coordinates of the intersection rectangle
inter_rect_x1 = np.maximum(b1_x1, b2_x1)
inter_rect_y1 = np.maximum(b1_y1, b2_y1)
inter_rect_x2 = np.minimum(b1_x2, b2_x2)
inter_rect_y2 = np.minimum(b1_y2, b2_y2)
# Intersection area
inter_area = np.clip(inter_rect_x2 - inter_rect_x1 + 1, 0, None) * \
np.clip(inter_rect_y2 - inter_rect_y1 + 1, 0, None)
# Union Area
b1_area = (b1_x2 - b1_x1 + 1) * (b1_y2 - b1_y1 + 1)
b2_area = (b2_x2 - b2_x1 + 1) * (b2_y2 - b2_y1 + 1)
iou = inter_area / (b1_area + b2_area - inter_area + 1e-16)
return iou
def non_max_suppression(self, prediction, origin_h, origin_w, conf_thres=0.5, nms_thres=0.4):
"""
description: Removes detections with lower object confidence score than 'conf_thres' and performs
Non-Maximum Suppression to further filter detections.
param:
prediction: detections, (x1, y1, x2, y2, conf, cls_id)
origin_h: original image height
origin_w: original image width
conf_thres: a confidence threshold to filter detections
nms_thres: a iou threshold to filter detections
return:
boxes: output after nms with the shape (x1, y1, x2, y2, conf, cls_id)
"""
# Get the boxes that score > CONF_THRESH
boxes = prediction[prediction[:, 4] >= conf_thres]
# Trandform bbox from [center_x, center_y, w, h] to [x1, y1, x2, y2]
boxes[:, :4] = self.xywh2xyxy(origin_h, origin_w, boxes[:, :4])
# clip the coordinates
boxes[:, 0] = np.clip(boxes[:, 0], 0, origin_w - 1)
boxes[:, 2] = np.clip(boxes[:, 2], 0, origin_w - 1)
boxes[:, 1] = np.clip(boxes[:, 1], 0, origin_h - 1)
boxes[:, 3] = np.clip(boxes[:, 3], 0, origin_h - 1)
# Object confidence
confs = boxes[:, 4]
# Sort by the confs
boxes = boxes[np.argsort(-confs)]
# Perform non-maximum suppression
keep_boxes = []
while boxes.shape[0]:
large_overlap = self.bbox_iou(np.expand_dims(boxes[0, :4], 0), boxes[:, :4]) > nms_thres
label_match = boxes[0, -1] == boxes[:, -1]
# Indices of boxes with lower confidence scores, large IOUs and matching labels
invalid = large_overlap & label_match
keep_boxes += [boxes[0]]
boxes = boxes[~invalid]
boxes = np.stack(keep_boxes, 0) if len(keep_boxes) else np.array([])
return boxes
| [
"[email protected]"
]
| |
997aedd9b1fbbc378290401f2c2b7c44582d73f1 | 2c003186be02c48093798047d9e439a87a9ead22 | /Day4_20210601/homework_tcj_20210601.py | 564b099ea101624a7cfa797bd958a21052cb7652 | []
| no_license | twcxjq/python_29 | 38a7774d8814273fbf70d8e822873ccdcc3f8ca6 | 398bbdefe2b82d24412d9bff70d605f3ca7ec37d | refs/heads/master | 2023-05-13T04:07:18.945088 | 2021-06-05T14:17:05 | 2021-06-05T14:17:05 | 371,929,079 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,346 | py | # -*- coding:utf8 -*- #
# -----------------------------------------------------------------------------------
# ProjectName: python_29
# FileName: homework_tcj_20210601
# Author: TianChangJun
# Datetime: 2021/6/1 12:50
# Description:
# -----------------------------------------------------------------------------------
import random
"""
猜字小游戏
总共5次机会,每猜错一次,机会减一,
当机会用完,提示是否继续!
如果继续就重新给5次机会,如果不继续就跳出程序
判断用户输入的是否为0-100的整数,如果不是则重新输入
"""
# number = random.randint(1, 100) #闭区间(左右都可以取到)
# choice_number = 5
#
# while True:
# if choice_number > 0:
# user_number = input("请输入一个1-100范围内的整数: ")
# user_number_int = int(user_number)
# if user_number.isdigit() and user_number_int >= 1 and user_number_int <= 100:
# if user_number_int == number:
# print("恭喜你,猜对了!!!")
# break
# elif user_number_int > number:
# if choice_number > 0:
# choice_number -= 1
# print("你猜的数字大了,请重新猜, " + "你还剩下{}次机会".format(choice_number))
# elif choice_number == 0:
# user_chice = input("五次机会以用完, 是否继续游戏, 如果继续请输入y,如果不继续请输入n: ")
# if user_chice == "y":
# choice_number = 5
# elif user_chice == "n":
# print("游戏结束, 欢迎下次来玩啊!!!")
# break
# else:
# if choice_number > 0:
# choice_number -= 1
# print("你猜的数字小了,请重新猜, " + "你还剩下{}次机会".format(choice_number))
# elif choice_number == 0:
# user_chice = input("五次机会以用完, 是否继续游戏, 如果继续请输入y,如果不继续请输入n: ")
# if user_chice == "y":
# choice_number = 5
# elif user_chice == "n":
# print("游戏结束, 欢迎下次来玩啊!!!")
# break
# else:
# print("输入数字有误!!!")
"""
2, 打印如下图形
"""
# total = 4
# for i in range(1, total + 1):
# if i == 2:
# print(" " * (total - i) + "*" + " " * (i * 2 - 3) + "*")
# elif i == 3:
# print(" " * (total - i) + "*" + " " * (i * 2 - 3) + "*")
# else:
# print(" " * (total - i) + "*" * (i * 2 - 1))
"""
3、dict1 = {"小花":18,"小兰":20,10:20},
判断dict1的是不是字典,如果是字典,把字典里的偶数进行相加,最后输出和
"""
# dict1 = {"小花":18,"小兰":20,10:20}
# if (isinstance(dict1, dict)):
# list_kv = []
# for k in dict1.keys():
# if type(k) == int and k % 2 == 0:
# list_kv.append(k)
# for v in dict1.values():
# if type(v).__name__ == "int" and v % 2 == 0:
# list_kv.append(v)
# print("字典里的偶数和为{}".format(sum(list_kv)))
# else:
# print("不是字典")
"""
4、使用while循环输出 1 2 3 4 5 6 8 9 10
"""
# item = 1
# while item <= 10:
# if item != 7:
# print(item)
# item += 1
"""
5、打印水仙花数
水仙花数是指一个 n 位数(n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身
例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。153 = 1**3+5**3+3**3
利用for循环输出1000以内的水仙花数
"""
# list_item_str = []
# num = 0
# for item in range(100, 1000):
# item_str = str(item)
# list_item_str.append(item_str)
# # print(list_item_str)
# # print(list_item_str[0][0])
# for list_vlaue in list_item_str:
# if int(list_vlaue[0]) ** 3 + int(list_vlaue[1]) ** 3 + int(list_vlaue[2]) ** 3 == int(list_vlaue):
# item_str = int(list_vlaue)
# print(item_str)
# num += 1
# print("1000以内的水仙花数共有{}个".format(num))
"""
6、打印九九乘法表(方法不限)
"""
for num1 in range(1, 10):
for num2 in range(1, num1 + 1):
print("{}X{}={}".format(num2, num1, num1 * num2), end="\t")
print()
| [
"[email protected]"
]
| |
df365e8db5a83aa23b10dbeeeeea6c4d09fd2a75 | be7c3f25ef4295ba006af14675d689e93f362ac7 | /algos/sorting/count_sort.py | b8d783f536eadab0357536540de2efd0cef73ff2 | []
| no_license | stayaKotov/sandbox | 4d85869515c9e6f04d6a110a69c039236c169a53 | 8dc753e488c8a59de22a68ac09e63ecc40b88a81 | refs/heads/master | 2023-06-03T22:27:10.724678 | 2021-06-19T20:29:42 | 2021-06-19T20:29:42 | 367,702,749 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 535 | py | import typing as t
class CountSort:
def __init__(self, elements: t.List):
self.elements = elements
def sort(self):
el_2_count = {}
result = []
for el in self.elements:
if el not in el_2_count.keys():
el_2_count[el] = 1
else:
el_2_count[el] += 1
tpl = [(k, v) for k, v in el_2_count.items()]
tpl = sorted(tpl, key=lambda x: x[0])
for k, v in tpl:
result += [k for _ in range(v)]
return result
| [
"[email protected]"
]
| |
258f9b5aa4529b7a18f4aa0b5e97a1adb004730d | c7300ea4853236d35eef0bab01b4b8770f286218 | /pub/iyu/neihanduanzi.py | a244a2388fafdc383c8f86b2fa483f4318a294de | []
| no_license | yuolvv/TestPython | b1cdf724add22b005bd1fb618722c6e9f558f275 | e0f05bb017c5d3e035f6e6f09b17c93db2e3a251 | refs/heads/master | 2021-01-20T13:39:00.147447 | 2017-05-31T14:06:09 | 2017-05-31T14:06:09 | 90,511,170 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,340 | py | #!/usr/bin/env python
# encoding: utf-8
"""
@version: 2016
@author: yuolvv
@license: Apache Licence
@file: neihanduanzi.py
@time: 2016/10/5 9:21
"""
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import pymysql.cursors
#请求URL并把结果用UTF-8编码
resp = urlopen("http://neihanshequ.com/").read().decode("utf-8")
#使用BeautifulSoup解析
soup = BeautifulSoup(resp,"html.parser")
#print(soup)
#print(soup.find_all("h1"))
#print(soup.find_all(attrs={"class": "title"}))
#print(soup.find_all(class_="title"))
duanzi = soup.find_all(class_="title")
count = 1
for dz in duanzi:
if dz.get_text().find("登录") == -1 & dz.get_text().find("举报") == -1 & dz.get_text().find("投稿") == -1:
print(str(count) + dz.get_text())
count = count+1
# 获取数据库链接
connection = pymysql.connect(host='localhost',user='root',password='123456',db='duanzi',charset='utf8mb4')
try:
# 获取会话指针
with connection.cursor() as cursor:
# 创建sql语句
sql = "insert into `duanzi`(`text`) VALUES(%s)"
# 执行sql语句
cursor.execute(sql, (dz.get_text()))
# 提交
connection.commit()
finally:
connection.close() | [
"[email protected]"
]
| |
96fa04e366583289c3563975997d9dfdfd0879b7 | 6f1dbf209cfa70a7f37de155cdc86a1687cb5734 | /venv/Scripts/easy_install-script.py | 7388155bd5ceaff8d42272cf69bd3b67b01358f3 | []
| no_license | super168168/StudentSignInSystem | 46fbb513cc32f51454ede38aad0154f8111ac3f9 | 6ddea705294d741df41ab6650f3943bbd771d78d | refs/heads/master | 2022-11-17T09:04:58.329726 | 2020-07-11T06:44:21 | 2020-07-11T06:44:21 | 278,804,467 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 436 | py | #!D:\machineview\StuSigSys\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==40.8.0','console_scripts','easy_install'
__requires__ = 'setuptools==40.8.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('setuptools==40.8.0', 'console_scripts', 'easy_install')()
)
| [
"[email protected]"
]
| |
27fb6b67d1b5509fe372290ee9b4ee5748234ce7 | bf4da9fc472d72aad42fb65a61d333fd5f23b0e0 | /accounts/admin.py | 98f03584fa5c0ec6d8daf3c5044cf8ad5f07f228 | []
| no_license | n0nama/storesb | 93726518834d2a1d3104584e5f7990d044b19462 | b550f63995bb2600339c92c4b5e22be488909e2d | refs/heads/master | 2020-05-16T03:09:00.550523 | 2019-04-22T08:29:41 | 2019-04-22T08:29:41 | 182,655,366 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,084 | py | from django.contrib import admin
from .models import UserProfile, ActivationProfile, UserComments, Subscribers, Reviews
from .models import CardData, SocialNetwork # , SocialAccount,
# Register your models here.
class SocialNetworkAdmin(admin.ModelAdmin):
list_display = ("title", "network_id","updated")
list_filter = ("created", "updated")
ordering = ["title", "created"]
# class SocialAccountsAdmin(admin.ModelAdmin):
# list_display = ("user", "social_network", "auto_post_updated")
# list_filter = ("social_network", "auto_post_updated", "updated", "created")
# search_fields = ('user',)
# ordering = ["updated"]
class UserProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'slug', 'org_form', 'created', 'updated')
list_filter = ('sex', 'city', 'country',)
search_fields = ('user__username', 'description', 'country', 'city', 'phone', 'skype')
date_hierarchy = 'updated'
ordering = ['updated', "user"]
readonly_fields = ('avatar_tag',)
class ActivationProfileAdmin(admin.ModelAdmin):
list_display = ('user', 'valid_through')
class UserCommentsAdmin(admin.ModelAdmin):
list_display = ('user', 'about_user', 'created')
list_filter = ('user', 'about_user')
search_fields = ('text',)
class SubscribersAdmin(admin.ModelAdmin):
list_display = ('owner', 'updated')
search_fields = ('owner__username',)
class ReviewsAdmin(admin.ModelAdmin):
list_display = ('author', 'about_user', 'mark', 'created')
list_filter = ('mark', 'created',)
search_fields = ('text', 'author__username')
class CardDataAdmin(admin.ModelAdmin):
list_display = ('user', 'number')
admin.site.register(SocialNetwork, SocialNetworkAdmin)
# admin.site.register(SocialAccount, SocialAccountsAdmin)
admin.site.register(UserProfile, UserProfileAdmin)
admin.site.register(ActivationProfile, ActivationProfileAdmin)
admin.site.register(UserComments, UserCommentsAdmin)
admin.site.register(Subscribers, SubscribersAdmin)
admin.site.register(Reviews, ReviewsAdmin)
admin.site.register(CardData, CardDataAdmin) | [
"[email protected]"
]
| |
36c8acfb797eb95d0cff11050a40dc75a0bd3fa0 | 8211c2cd810fe785333ace3f2823d92560c61be4 | /src/data_reader_onecommon.py | 0c9f0c8be023cd733d8c0bb89ca465509a1bf228 | []
| no_license | Alab-NII/lcfp | 4432cf51f824ad5926399e41ad2223cc0ddc3e8d | c0455805dc37dabd9f7c2a4b8cdd7e61f301e8b6 | refs/heads/master | 2022-04-13T19:12:51.668465 | 2020-04-11T15:23:14 | 2020-04-11T15:23:14 | 226,287,328 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,686 | py | # coding: utf-8
import json
import numpy as np
import os
try:
import data_reader_base
except ModuleNotFoundError as e:
import sys
sys.path += ['src']
from data_reader_base import DatasetReaderBase, VisualSelectionTaskInstance
class OneCommonDataReader(DatasetReaderBase):
task_name = 'onecommon.selection'
token_eos = '<eos>'
token_selection = '<selection>'
token_you = '<you>'
token_them = '<them>'
control_tokens = {
'main':[task_name, token_eos, token_selection, token_you, token_them],
'sub':[],
}
full_canvas_size = 224
min_size=0.025
max_size=0.05
min_col=0.2
max_col=0.8
min_pos = full_canvas_size*max_size*0.5
max_pos = full_canvas_size*(1 - max_size*0.5)
@classmethod
def instance_to_text(cls, inst):
"""Returns a space-splitted text given an instance."""
text = inst['dialogue']
text = text.replace('YOU:', cls.token_you)
text = text.replace('THEM:', cls.token_them)
text = text.lower()
return text
@classmethod
def count_tokens(cls, dataset_spec, textifier, n_tokens):
"""Return a dict whose key and value are token and its frequency."""
with open(dataset_spec['path'], 'r') as f:
dataset = json.load(f)
target_n_tokens = n_tokens['main']
for inst in dataset:
tokens = textifier(cls.task_name, inst, to_ids=False)
for token in tokens:
target_n_tokens[token] = target_n_tokens.get(token, 0) + 1
return n_tokens
@classmethod
def compile_dataset(cls, dataset_spec, textifier):
"""Returns a list of VisualSelectionTaskInstance."""
provide_image = dataset_spec.get('provide_image', True)
asarray = lambda x, t: np.asarray(x, dtype=t)
get_min_max = lambda obj: (obj['x_min'], obj['y_min'], obj['x_max'], obj['y_max'])
def get_attributes(obj):
x_center = 2*(0.5*(obj['x_min'] + obj['x_max']) - cls.min_pos)/(cls.max_pos - cls.min_pos) - 1
y_center = 2*(0.5*(obj['y_min'] + obj['y_max']) - cls.min_pos)/(cls.max_pos - cls.min_pos) - 1
size = 2*(obj['size'][0] / (cls.full_canvas_size*(1 - cls.max_size)) - cls.min_size)/(cls.max_size - cls.min_size) - 1
color = 2*(obj['color']/255 - cls.min_col) / (cls.max_col - cls.min_col) - 1
return [x_center, y_center, size, color]
with open(dataset_spec['path'], 'r') as f:
dataset = json.load(f)
instances = []
for inst in dataset:
_id = os.path.splitext(os.path.basename(inst['image_path']))[0]
tokens = asarray(textifier(cls.task_name, inst, to_ids=True), np.int)
object_bboxes = asarray([get_min_max(o) for o in inst['objects']], np.float32)
if provide_image:
object_optional_info = None
else:
object_optional_info = asarray([get_attributes(o) for o in inst['objects']], np.float32)
instances.append(VisualSelectionTaskInstance(
task_name=cls.task_name,
instance_id=_id,
image_path=inst['image_path'],
tokens=tokens,
n_tokens=asarray(tokens.shape[0], np.int),
object_bboxes=object_bboxes,
object_optional_info=object_optional_info,
n_objects=asarray(object_bboxes.shape[0], np.int),
ground_truth_id=asarray(inst['selected_id'], np.int),
))
return instances
| [
"[email protected]"
]
| |
4d5025e2c60823b309ab8b5dd652fb0b05866cc1 | d2d971ccd0dc52f2f3c448c0fb1110fd25ef09a0 | /models/multitarget/aggregation.py | a3ae91397e83b4e30368227ff5e1bbf7f90426bf | []
| no_license | stepanov2112/emergency_datahack_nss | 0400987fd3f23a57370ee7e5ebb6cfe962149081 | f91ce67a531e048d0268e7807a5bd22242d7ce59 | refs/heads/main | 2023-07-07T08:31:05.200479 | 2021-08-14T21:42:50 | 2021-08-14T21:42:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,939 | py | """НЕ ЗАБУДЬТЕ:
- отсортировать df по дате.
- перевести значения колонки в int or float.
"""
import numpy as np
import pandas as pd
from collections import Counter
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
pd.options.mode.chained_assignment = None
def occ(x: list):
c = Counter(x)
c = dict(sorted(c.items(), key=lambda item: item[1]))
res = list(c.keys())[-1]
return res
def days_agg(dataframe: pd.DataFrame, column_name: str, agg_func: str, days: int):
"""Агрегирует данные в выбранной колонке за заданное колчество дней. По сути юзер-френдли 'скользящее окно'.
params agg_func: модет принимать значение ['mean', 'std', 'sum', 'amplitude', 'occ'].
- amplitude: max(value) - min(value)
- occ: максимальное встречающееся значение
[2,3,4,2,2,2,3]: {2: 4, 3: 2, 4: 1} => вернет 2, максимально встречающееся значение
params days: ширина окна
params column_name: что агрегировать
params dataframe: dataframe
return: ...
"""
d = {
'mean': np.mean,
'sum': np.sum,
'std': np.std,
'amplitude': lambda x: np.max(x) - np.min(x),
'first_minus_last': lambda x: x[0] - x[-1],
'occ': occ
}
agg_f = d[agg_func]
values = np.array(dataframe[column_name])
result = []
for i in range(0, len(values)):
i_ = i - days
if i_ < 0:
i_ = 0
result.append(agg_f(values[i_:i + 1]))
return result
def ts_to_table(idx, time_series, window_size):
""" Method convert time series to lagged form.
:param idx: the indices of the time series to convert
:param time_series: source time series
:param window_size: size of sliding window, which defines lag
:return updated_idx: clipped indices of time series
:return features_columns: lagged time series feature table
"""
# Convert data to lagged form
lagged_dataframe = pd.DataFrame({'t_id': time_series})
vals = lagged_dataframe['t_id']
for i in range(1, window_size + 1):
frames = [lagged_dataframe, vals.shift(i)]
lagged_dataframe = pd.concat(frames, axis=1)
# Remove incomplete rows
lagged_dataframe.dropna(inplace=True)
transformed = np.array(lagged_dataframe)
# Generate dataset with features
features_columns = transformed[:, 1:]
features_columns = np.fliplr(features_columns)
return idx, features_columns
def convert_water_codes(value):
water_codes = pd.read_csv('../../data/meteo_data/ref_code_hazard.csv')
values = list(map(int, map(lambda x: x.strip(), value.split(','))))
res = 0
for val in values:
res += water_codes[water_codes['water_code'] == val].reset_index(drop=True).iloc[0][1]
return res
def feature_aggregation(dataframe: pd.DataFrame):
""" Функция агрегирует знаения по столбцам """
columns = dataframe.columns
columns_drop = []
if 'discharge' in columns:
# Расход - среднее за 7 суток
dataframe['discharge_mean'] = days_agg(dataframe, 'discharge', 'mean', 7)
columns_drop.append('discharge')
if 'stage_max' in columns:
# Целевая переменная - среднее и амплитуда за 7 и 3 суток
dataframe['stage_max_amplitude'] = days_agg(dataframe, 'stage_max', 'amplitude', 7)
dataframe['stage_max_mean'] = days_agg(dataframe, 'stage_max', 'mean', 4)
if 'snow_coverage_station' in columns:
# Доля снежного покрова - амплитуда за 30 суток
dataframe['snow_coverage_station_amplitude'] = days_agg(dataframe, 'snow_coverage_station', 'amplitude', 30)
columns_drop.append('snow_coverage_station')
if 'snow_height' in columns:
# Высота снежного покрова
dataframe['snow_height_mean'] = days_agg(dataframe, 'snow_height', 'mean', 15)
dataframe['snow_height_amplitude'] = days_agg(dataframe, 'snow_height', 'first_minus_last', 30)
columns_drop.append('snow_height')
if 'precipitation' in columns:
# Сумма осадков за 20 суток
dataframe['precipitation_sum'] = days_agg(dataframe, 'precipitation', 'sum', 20)
columns_drop.append('precipitation')
if 'water_hazard' in columns:
# Сумма кодов произошедших событий за 2 суток
dataframe['water_hazard_sum'] = days_agg(dataframe, 'water_hazard', 'sum', 2)
columns_drop.append('water_hazard')
dataframe.drop(columns_drop, axis=1, inplace=True)
return dataframe
| [
"[email protected]"
]
| |
21b9c07f5745ad1954c3ca3af77d74dac67620d0 | bfb113c3076f5b0570953583e7a2321c774d73ea | /venv/Scripts/easy_install-3.8-script.py | 88b18d55d3cfc7b1e4ca627aaafb9710ef93d7c3 | []
| no_license | gsudarshan1990/Training_Projects | 82c48d5492cb4be94db09ee5c66142c370794e1c | 2b7edfafc4e448bd558c034044570496ca68bf2d | refs/heads/master | 2022-12-10T15:56:17.535096 | 2020-09-04T06:02:31 | 2020-09-04T06:02:31 | 279,103,151 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 440 | py | #!E:\Training_Projects\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==40.8.0','console_scripts','easy_install-3.8'
__requires__ = 'setuptools==40.8.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('setuptools==40.8.0', 'console_scripts', 'easy_install-3.8')()
)
| [
"[email protected]"
]
| |
d19900843a543c71b3c6b42cd0625657db46def1 | 1714707d842bc3e465cf95449a3440a64b4ceb98 | /MSG-MIR/models/stn/local_stn.py | 67a5b2613d0d2b5a82692bc1e9094a5951cb609a | []
| no_license | BugIITheGreat/MSG-MIR | 178ff1b52ea86ebb978d4e222a0ee6d27089aea2 | c425d129ae8eb96cf81f5bd4473e72434461e613 | refs/heads/main | 2023-07-27T20:06:39.493150 | 2021-09-07T02:33:11 | 2021-09-07T02:33:11 | 403,804,562 | 3 | 1 | null | null | null | null | UTF-8 | Python | false | false | 18,011 | py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .layers import DownBlock, Conv, ResnetTransformer, get_activation, TransConv
from .stn_losses import smoothness_loss, deformation_equality_loss
sampling_align_corners = False
sampling_mode = 'bilinear'
# The number of filters in each block of the encoding part (down-sampling).
ndf = {'A': [32, 32, 64, 64, 128, 128, 256], }
# The number of filters in each block of the decoding part (up-sampling).
# If len(ndf[cfg]) > len(nuf[cfg]) - then the deformation field is up-sampled to match the input size.
nuf = {'A': [256, 128, 128, 64, 64, 32, 32], }
# Indicate if res-blocks are used in the down-sampling path.
use_down_resblocks = {'A': True, }
# indicate the number of res-blocks applied on the encoded features.
resnet_nblocks = {'A': 5, }
# indicate the time for output the intact affine parameters.
convs_for_intact = {'A': 7, }
# control the contribution of intact feature and local feature.
para_for_local = {'A': 0.9, }
# Indicate if the a final refinement layer is applied on the before deriving the deformation field
refine_output = {'A': True, }
# The activation used in the down-sampling path.
down_activation = {'A': 'leaky_relu', }
# The activation used in the up-sampling path.
up_activation = {'A': 'leaky_relu', }
affine_dimentions = {'A': 6, }
class LocalNet(nn.Module):
def __init__(self, nc_a, nc_b, cfg, height, width, init_func, init_to_identity):
super(LocalNet, self).__init__()
act = down_activation[cfg]
# ------------ Down-sampling path
self.ndown_blocks = len(ndf[cfg])
self.nup_blocks = len(nuf[cfg])
self.h, self.w = height, width
self.convs_for_intact = convs_for_intact[cfg]
assert self.ndown_blocks >= self.nup_blocks
in_nf = nc_a + nc_b
conv_num = 1
skip_nf = {}
for out_nf in ndf[cfg]:
setattr(self, 'down_{}'.format(conv_num),
DownBlock(in_nf, out_nf, 3, 1, 1, activation=act, init_func=init_func, bias=True,
use_resnet=use_down_resblocks[cfg], use_norm=True))
skip_nf['down_{}'.format(conv_num)] = out_nf
in_nf = out_nf
conv_num += 1
conv_num -= 1
actIntact = get_activation(activation='relu')
self.outputIntact = nn.Sequential(
nn.Linear(ndf[cfg][self.convs_for_intact - 1] *
(self.h // 2 ** (self.convs_for_intact - 1)) *
(self.w // 2 ** (self.convs_for_intact - 1)),
ndf[cfg][self.convs_for_intact - 1], bias=True),
actIntact,
nn.Linear(ndf[cfg][self.convs_for_intact - 1], affine_dimentions[cfg], bias=True))
self.outputIntact[-1].weight.data.normal_(mean=0.0, std=5e-4)
self.outputIntact[-1].bias.data.zero_()
if use_down_resblocks[cfg]:
self.c1 = Conv(in_nf, 2 * in_nf, 1, 1, 0, activation=act, init_func=init_func, bias=True,
use_resnet=False, use_norm=False)
self.t = ((lambda x: x) if resnet_nblocks[cfg] == 0
else ResnetTransformer(2 * in_nf, resnet_nblocks[cfg], init_func))
self.c2 = Conv(2 * in_nf, in_nf, 1, 1, 0, activation=act, init_func=init_func, bias=True,
use_resnet=False, use_norm=False)
# ------------- Up-sampling path
act = up_activation[cfg]
for out_nf in nuf[cfg]:
setattr(self, 'up_{}'.format(conv_num),
Conv(in_nf + skip_nf['down_{}'.format(conv_num)], out_nf, 3, 1, 1, bias=True, activation=act,
init_fun=init_func, use_norm=True, use_resnet=True))
setattr(self, 'output_{}'.format(conv_num),
Conv(out_nf, 2, 3, 1, 1, use_resnet=False, bias=True,
init_func=('zeros' if init_to_identity else init_func), activation=act,
use_norm=False)
)
# ------------- Deformation Field TransposeConv Block
setattr(self, 'field_transconv_{}'.format(conv_num),
TransConv(2, 2, 3, 2, 0, use_resnet=True, bias=True,
init_func=('zeros' if init_to_identity else init_func), activation=act,
use_norm=False)
)
if refine_output[cfg]:
setattr(self, 'refine_{}'.format(conv_num),
nn.Sequential(ResnetTransformer(out_nf, 1, init_func),
Conv(out_nf, out_nf, 1, 1, 0, use_resnet=False, init_func=init_func,
activation=act,
use_norm=False)
)
)
else:
setattr(self, 'refine_{}'.format(conv_num), lambda x: x)
in_nf = out_nf
conv_num -= 1
def forward(self, img_a, img_b):
use_transpose_conv_in_fields = False
para_for_multiscale = 0.9
x = torch.cat([img_a, img_b], 1)
skip_vals = {}
conv_num = 1
# Down
while conv_num <= self.ndown_blocks:
x, skip = getattr(self, 'down_{}'.format(conv_num))(x)
skip_vals['down_{}'.format(conv_num)] = skip
conv_num += 1
tus = skip_vals['down_{}'.format(self.convs_for_intact)]
# print(str(tus.shape) + "tus_shape")
intact_x = tus.view(tus.size(0), -1)
# print(str(intact_x.shape) + "intact_x_shape")
# print(self.outputIntact)
dtheta_for_intact = self.outputIntact(intact_x)
if hasattr(self, 't'):
x = self.c1(x)
x = self.t(x)
x = self.c2(x)
# Up
conv_num -= 1
deform_scale_output = {}
while conv_num > (self.ndown_blocks - self.nup_blocks):
s = skip_vals['down_{}'.format(conv_num)]
x = F.interpolate(x, (s.size(2), s.size(3)), mode='bilinear')
x = torch.cat([x, s], 1)
x = getattr(self, 'up_{}'.format(conv_num))(x)
x = getattr(self, 'refine_{}'.format(conv_num))(x)
deform_scale_output[conv_num] = getattr(self, 'output_{}'.format(conv_num))(x)
if use_transpose_conv_in_fields is False:
if conv_num is self.nup_blocks:
def_for_local = deform_scale_output[conv_num]
else:
def_for_local = para_for_multiscale * F.interpolate(def_for_local,
(deform_scale_output[conv_num].shape[2],
deform_scale_output[conv_num].shape[3]),
mode='bilinear') \
+ deform_scale_output[conv_num]
else:
if conv_num is self.nup_blocks:
def_for_local = deform_scale_output[conv_num]
else:
ppr = getattr(self, 'field_transconv_{}'.format(conv_num))(def_for_local)
ppr = F.interpolate(ppr,
(deform_scale_output[conv_num].shape[2],
deform_scale_output[conv_num].shape[3]),
mode='bilinear')
def_for_local = para_for_multiscale * ppr + deform_scale_output[conv_num]
conv_num -= 1
# x = self.outputLocal(x)
return dtheta_for_intact, def_for_local, deform_scale_output
class LocalSTN(nn.Module):
"""This class is generates and applies the deformable transformation on the input images."""
def __init__(self, in_channels_a, in_channels_b, height, width, cfg, init_func, stn_bilateral_alpha,
init_to_identity, multi_resolution_regularization):
super(LocalSTN, self).__init__()
self.oh, self.ow = height, width
self.in_channels_a = in_channels_a
self.in_channels_b = in_channels_b
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.all_offsets = LocalNet(self.in_channels_a, self.in_channels_b, cfg, height, width,
init_func, init_to_identity).to(self.device)
self.identity_grid = self.get_identity_grid()
self.identity_theta = torch.tensor([1, 0, 0, 0, 1, 0], dtype=torch.float).to(self.device)
if affine_dimentions[cfg] is 8:
self.identity_theta = torch.tensor([1, 0, 0, 0, 1, 0, 0, 0, 1], dtype=torch.float).to(self.device)
if affine_dimentions[cfg] is 6:
self.identity_theta = torch.tensor([1, 0, 0, 0, 1, 0], dtype=torch.float).to(self.device)
elif affine_dimentions[cfg] is 4:
self.justian_matrix = torch.tensor([1, 0, 1, 0, 1, 1], dtype=torch.float).unsqueeze(0)
# self.transfer_matrix = torch.tensor(self.justian_matrix, dtype=torch.float).to(self.device)
self.alpha = stn_bilateral_alpha
self.multi_resolution_regularization = multi_resolution_regularization
self.para_for_local = para_for_local[cfg]
def get_identity_grid(self):
"""Returns a sampling-grid that represents the identity transformation."""
x = torch.linspace(-1.0, 1.0, self.ow)
y = torch.linspace(-1.0, 1.0, self.oh)
xx, yy = torch.meshgrid([y, x])
xx = xx.unsqueeze(dim=0)
yy = yy.unsqueeze(dim=0)
identity = torch.cat((yy, xx), dim=0).unsqueeze(0)
return identity
def get_homography_grid(self, matrix):
# matrix = torch.cat((matrix, torch.ones([1, 1]).to(matrix.device)), dim=1)
matrix = matrix.view(3, 3)
identity_grid = self.get_identity_grid()
height = identity_grid.shape[2]
width = identity_grid.shape[3]
identity_grid = identity_grid.view(1, 2, -1).to(matrix.device)
com = torch.ones([1, 1, identity_grid.shape[-1]]).to(identity_grid.device)
identity_grid = torch.cat((identity_grid, com), dim=1).squeeze(0)
homo_grid = torch.matmul(matrix, identity_grid)
with torch.no_grad():
homo_grid[0, :] = torch.div(homo_grid[0, :], homo_grid[2, :])
homo_grid[1, :] = torch.div(homo_grid[1, :], homo_grid[2, :])
torch.set_grad_enabled(True)
return homo_grid[0:2, :].view(1, 2, height, width)
def get_affine_grid(self, matrix):
matrix = matrix.view(2, 3)
identity_grid = self.get_identity_grid()
height = identity_grid.shape[2]
width = identity_grid.shape[3]
identity_grid = identity_grid.view(1, 2, -1).to(matrix.device)
com = torch.ones([1, 1, identity_grid.shape[-1]]).to(identity_grid.device)
identity_grid = torch.cat((identity_grid, com), dim=1).squeeze(0)
aff_suf = torch.tensor([0, 0, 1], dtype=torch.float).unsqueeze(0).to(self.device)
matrix = torch.cat((matrix, aff_suf), dim=0)
affine_grid = torch.matmul(matrix, identity_grid)
return affine_grid[0:2, :].view(1, 2, height, width)
def get_grid(self, img_a, img_b, return_offsets_only=False):
"""Return the predicted sampling grid that aligns img_a with img_b."""
if img_a.is_cuda and not self.identity_grid.is_cuda:
self.identity_grid = self.identity_grid.to(img_a.device)
# Get Deformation Field
b_size = img_a.size(0)
all_offsets = self.all_offsets(img_a, img_b)
dtheta_for_intact = all_offsets[0]
theta_for_intact = dtheta_for_intact + self.identity_theta.unsqueeze(0).repeat(img_a.size(0), 1)
if dtheta_for_intact.shape[-1] == 6:
theta_for_intact = dtheta_for_intact + self.identity_theta.unsqueeze(0).repeat(img_a.size(0), 1)
trans_grid = self.get_affine_grid(theta_for_intact)
elif dtheta_for_intact.shape[-1] == 8:
dtheta_for_intact = torch.cat((dtheta_for_intact, torch.ones([1, 1]).to(img_a.device)), dim=1)
theta_for_intact = dtheta_for_intact + self.identity_theta.unsqueeze(0).repeat(img_a.size(0), 1)
trans_grid = self.get_homography_grid(theta_for_intact)
deformation = all_offsets[1]
deformation_upsampled = deformation
if deformation.size(2) != self.oh and deformation.size(3) != self.ow:
deformation_upsampled = F.interpolate(deformation, (self.oh, self.ow), mode=sampling_mode,
align_corners=sampling_align_corners)
if return_offsets_only:
resampling_grid = deformation_upsampled.permute([0, 2, 3, 1])
else:
resampling_grid = (self.identity_grid.repeat(b_size, 1, 1, 1) + deformation_upsampled).permute([0, 2, 3, 1])
if dtheta_for_intact.shape[-1] < 6:
resampling_grid_intact = F.affine_grid(theta_for_intact.view(-1, 2, 3), img_a.size())
else:
resampling_grid_intact = trans_grid.permute([0, 2, 3, 1])
kkp = resampling_grid
resampling_grid = resampling_grid_intact + self.para_for_local * resampling_grid
ksa = all_offsets[2]
return resampling_grid_intact
def forward(self, img_a, img_b, apply_on=None):
"""
Predicts the spatial alignment needed to align img_a with img_b. The spatial transformation will be applied
on the tensors passed by apply_on (if apply_on is None then the transformation will be applied on img_a).
:param img_a: the source image.
:param img_b: the target image.
:param apply_on: the geometric transformation can be applied on different tensors provided by this list.
If not set, then the transformation will be applied on img_a.
:return: a list of the warped images (matching the order they appeared in apply on), and the regularization term
calculated for the predicted transformation."""
if img_a.is_cuda and not self.identity_grid.is_cuda:
self.identity_grid = self.identity_grid.to(img_a.device)
# Get Deformation Field
b_size = img_a.size(0)
all_offsets = self.all_offsets(img_a, img_b)
dtheta_for_intact = all_offsets[0]
if dtheta_for_intact.shape[-1] < 6:
# dtheta_for_intact = dtheta_for_intact * self.transfer_matrix
theta_for_intact = dtheta_for_intact + self.identity_theta.unsqueeze(0).repeat(img_a.size(0), 1)
else:
if dtheta_for_intact.shape[-1] == 6:
theta_for_intact = dtheta_for_intact + self.identity_theta.unsqueeze(0).repeat(img_a.size(0), 1)
trans_grid = self.get_affine_grid(theta_for_intact)
elif dtheta_for_intact.shape[-1] == 8:
dtheta_for_intact = torch.cat((dtheta_for_intact, torch.ones([1, 1]).to(img_a.device)), dim=1)
theta_for_intact = dtheta_for_intact + self.identity_theta.unsqueeze(0).repeat(img_a.size(0), 1)
trans_grid = self.get_homography_grid(dtheta_for_intact)
deformation = all_offsets[1]
deformation_upsampled = deformation
if deformation.size(2) != self.oh and deformation.size(3) != self.ow:
deformation_upsampled = F.interpolate(deformation, (self.oh, self.ow), mode=sampling_mode)
resampling_grid = (self.identity_grid.repeat(b_size, 1, 1, 1) + deformation_upsampled).permute([0, 2, 3, 1])
# Wrap image wrt to the deformation field
if apply_on is None:
apply_on = [img_a]
warped_images = []
for img in apply_on:
if dtheta_for_intact.shape[-1] < 6:
resampling_grid_intact = F.affine_grid(theta_for_intact.view(-1, 2, 3), img_a.size())
else:
resampling_grid_intact = trans_grid.permute([0, 2, 3, 1])
resampling_grid = (1 - self.para_for_local) * resampling_grid_intact + self.para_for_local * resampling_grid
warped_images.append(F.grid_sample(img, resampling_grid, mode=sampling_mode, padding_mode='zeros',
align_corners=sampling_align_corners))
# Calculate STN regularization term
reg_term = self._calculate_regularization_term(deformation, warped_images[0])
# return warped_images, reg_term, resampling_grid
return warped_images, reg_term
def _calculate_regularization_term(self, deformation, img):
"""Calculate the regularization term of the predicted deformation.
The regularization may-be applied to different resolution for larger images."""
dh, dw = deformation.size(2), deformation.size(3)
img = None if img is None else img.detach()
reg = 0.0
factor = 1.0
for i in range(self.multi_resolution_regularization):
if i != 0:
deformation_resized = F.interpolate(deformation, (dh // (2 ** i), dw // (2 ** i)), mode=sampling_mode,
align_corners=sampling_align_corners)
img_resized = F.interpolate(img, (dh // (2 ** i), dw // (2 ** i)), mode=sampling_mode,
align_corners=sampling_align_corners)
elif deformation.size()[2::] != img.size()[2::]:
deformation_resized = deformation
img_resized = F.interpolate(img, deformation.size()[2::], mode=sampling_mode,
align_corners=sampling_align_corners)
else:
deformation_resized = deformation
img_resized = img
reg += factor * smoothness_loss(deformation_resized, img_resized, alpha=self.alpha)
factor /= 2.0
return reg
| [
"[email protected]"
]
| |
14a1346e9377eebc91bfe385c290409c7e2ee92d | 2f0cc6fb3fef1785fe056d4a82ed2610a401b63a | /tools/pylab/gfx/__init__.py | 72fd3d7cb7a73ea87ccac2c64120351c4a06dc5d | []
| no_license | tim-napoli/lab | 7a4d788b65603b2f1d9375c5cce38977b5265f3c | cbae4752fbacf18ec050805d7afc449bdf73d206 | refs/heads/master | 2021-01-12T15:07:02.325843 | 2017-10-03T18:48:49 | 2017-10-03T18:48:49 | 71,699,029 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 28 | py | from pylab.gfx import image
| [
"[email protected]"
]
| |
e2ad0ac71e50ae293c404f706bc0dd8350d8397d | 018281e13b8fbb34f0cfe035635c1196b6f861ca | /task 21_22_Anand-Python Practice Book/6. Functional Programming/7.py | cf5043b2b01abc618311c931593a7f288de7f329 | []
| no_license | JishnuSaseendran/Recursive_Lab | dcda1e1d092cced4829e86da65942e162e70e07c | e710c4adcc650f8eeb0508a06af323c46514f444 | refs/heads/master | 2020-05-29T08:46:44.052029 | 2016-10-22T01:03:47 | 2016-10-22T01:03:47 | 69,469,796 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 598 | py | '''
Problem 7: Implement a program dirtree.py that takes a directory as argument and prints all the files in that directory recursively as a tree.
'''
import os
import sys
a='| '
i=0
def dirtree(dir,i):
filenames=os.listdir(dir)
for filename in filenames:
if not os.path.isdir(os.path.abspath(dir+'/'+filename)):
if filename==filenames[-1]:
print a*i+'\--',filename
else:
print a*i+'|--',filename
else:
print a*i+'|--',filename
dir=dir+'/'+filename
dirtree(dir,i+1)
dir=sys.argv[1]
print dir
dirtree(dir,i)
| [
"[email protected]"
]
| |
26d8aaa4d2b005645c48370b880a005933c1fdc0 | 9129a791f45cd3b25d8a5da57ee6936bfe4e73a2 | /learn-django/jango/Scripts/pip3-script.py | d5c70d9b707ed3b9eea1c0bec34cc59c4c2ec8ba | []
| no_license | Sunsetjue/Django2.0 | 94be49ed9d65dab6398ab8f0ddd02bb1871afb6b | 102bf0f2bd2d309b76f3247e396b7e83c5f6c2f8 | refs/heads/master | 2020-04-22T03:25:24.014196 | 2019-02-15T16:18:23 | 2019-02-15T16:18:23 | 170,086,151 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 399 | py | #!C:\Users\l\learn-django\jango\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip3'
__requires__ = 'pip==10.0.1'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==10.0.1', 'console_scripts', 'pip3')()
)
| [
"10073631822qq.com"
]
| 10073631822qq.com |
543db5403219ea73e88c510b470c95cc4e6a7ff0 | 18c8a7cb838702cdf1c4d4e9f66b2cffd63130aa | /{{cookiecutter.project_slug}}/config/settings/test.py | 69b8d3be1f0ba85b3bda931e3cd01983f435d82f | [
"MIT"
]
| permissive | DiscordApps/launchr | c304008a0d05bdf2d3ed77ada365f80d861f307d | 61049879591ba851ce50d1651abc7193aae4aca0 | refs/heads/master | 2022-02-26T21:22:36.656108 | 2019-10-11T13:05:35 | 2019-10-11T13:05:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,695 | py | """
With these settings, tests run faster.
"""
from .base import * # noqa
from .base import env
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = env(
"DJANGO_SECRET_KEY",
default="!!!SET DJANGO_SECRET_KEY!!!",
)
# https://docs.djangoproject.com/en/dev/ref/settings/#test-runner
TEST_RUNNER = "django.test.runner.DiscoverRunner"
# CACHES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#caches
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": "",
}
}
# PASSWORDS
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers
PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]
# TEMPLATES
# ------------------------------------------------------------------------------
TEMPLATES[0]["OPTIONS"]["loaders"] = [ # noqa F405
(
"django.template.loaders.cached.Loader",
[
"django.template.loaders.filesystem.Loader",
"django.template.loaders.app_directories.Loader",
],
)
]
TEMPLATES[0]['OPTIONS']['debug'] = True # noqa F405
# EMAIL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"
# Your stuff...
# ------------------------------------------------------------------------------
| [
"[email protected]"
]
| |
7e5b96550afe812018fe239ac8ed2783e7cc8f84 | 04d6dbf3978c83e1c807bec4f3f06a40814752e3 | /获取ip代理.py | 479da46166ed3a82f768ebaa656d8b27a00522e8 | [
"MIT"
]
| permissive | Outman888/test | bccf34a789aca962fa3db7187e7fbc2d3cb78070 | af8a903ddde6cf8506effe72914bb6099d3009a9 | refs/heads/master | 2020-04-01T16:27:32.293906 | 2018-10-24T12:00:20 | 2018-10-24T12:00:20 | 153,382,318 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,429 | py | #作者:晴天
#链接:https://www.zhihu.com/question/47464143/answer/234430051
#来源:知乎
#著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
#-*- coding:utf-8 -*-
import urllib.request
import re
import requests
import pymysql
#抓取三个网页上比较新的免费代理ip和port到_crawl
def _gaoni():
urls=['http://www.ip3366.net/free/?stype=1&page=1',
'http://www.ip3366.net/free/?stype=1&page=2']
re_gaoni=re.compile(r'(\d{2,3}.\d{2,3}.\d{2,3}.\d{2,3})</td>\s*?\n\s*?<td>(\d{2,5})')
list_gaoni=[]
maxtrynum=10
for url in urls:
for tries in range(maxtrynum):
try:
response=urllib.request.Request(url)
page=urllib.request.urlopen(response)
except:
if tries < (maxtrynum-1):
continue
else:
print ('failed')
html=page.read().decode('utf-8',errors='ignore')#python3
list_gaoni=list_gaoni+re_gaoni.findall(html)
return list_gaoni
def _66ip():
urls=['http://www.66ip.cn/index.html',
'http://www.66ip.cn/2.html']
re_66ip=re.compile(r'(\d{2,3}.\d{2,3}.\d{2,3}.\d{2,3})</td><td>(\d{2,5})')
list_66ip=[]
maxtrynum=10
for url in urls:
for tries in range(maxtrynum):
try:
response=urllib.request.Request(url)
page=urllib.request.urlopen(response)
except:
if tries < (maxtrynum-1):
continue
else:
print ('failed')
html=page.read().decode('utf-8',errors='ignore')#python3
list_66ip=list_66ip+re_66ip.findall(html)
print(list_66ip)
return list_66ip
def _httpdaili():
re_httpdaili=re.compile(r'(\d{2,3}.\d{2,3}.\d{2,3}.\d{2,3})</td>\s*?\n\s*?<td>(\d{2,5})')
list_httpdaili=[]
maxtrynum=10
for tries in range(maxtrynum):
try:
response=urllib.request.Request('http://www.httpdaili.com/mfdl/')
page=urllib.request.urlopen(response)
except:
if tries < (maxtrynum-1):
continue
else:
print ('failed')
html=page.read().decode('utf-8',errors='ignore')#python3
list_httpdaili=list_httpdaili+re_httpdaili.findall(html)
return list_httpdaili
_crawl=_gaoni()+_66ip()+_httpdaili()
#抓取数据库中ip_agent表的数据到_MySQLdata,清空ip_agent
host='127.0.0.1'
dbName='hello'
user='root'
password='root'
db=pymysql.connect(host,user,password,dbName,charset='utf8')
cur=db.cursor()
try:
cur.execute("SELECT * FROM ip_agent")
_MySQLdata=cur.fetchall()
except:
print ("can't fetch MySQLdata")
db.commit()
try:
cur.execute("DELETE FROM ip_agent")
db.commit()
except:
db.rollback()
#整合去重
_all=[]
for m in _crawl:
if m not in _all:
_all.append(m)
for n in _MySQLdata:
if n not in _all:
_all.append(n)
#筛选出有效数据
_useful=[]
for i in _all:
proxies={"http":"http://"+i[0]+":"+i[1]}
url='http://www.baidu.com'
try:
requests.get(url,proxies)
except:
pass
else:
if i not in _useful:
_useful.append(i)
#存入数据库
for m in _useful:
param=(m[0],m[1])
sql="INSERT INTO ip_agent VALUES (%s,%s)"
cur.execute(sql,param)
cur.close()
db.commit()
db.close() | [
"[email protected]"
]
| |
82678ca0bbaa92ebe8ee87c145c0472f2d1a6f8c | 6985139dfc6b313d47d2a3e390aa97d5b95a9245 | /presensi/urls.py | 76004872647df3f9be84e279f522332dea4350eb | []
| no_license | rafiem/Attendance-Apps | 41294b19f27bf045fb7d5223acf7b54c53f2f2b8 | 449c61fd5be393513e2c58969c3f63f141ddd8fd | refs/heads/master | 2020-05-15T20:22:56.607294 | 2019-04-21T02:54:07 | 2019-04-21T02:54:07 | 182,473,037 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 814 | py | """ghidza URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('presensi.presensi_api.urls')),
]
| [
"[email protected]"
]
| |
2be3f71105891c23fcae4397b78ff9eeb9fd1e82 | f1d32956219c4d7f63f47031fbf8ae4b8bf15eef | /gcpbt.py | 687f5218dd6bff5de9d469bc3ddb4971bed11b19 | []
| no_license | VaishnaviPunagin/GraphColoring-ComparativeAnalysisOfAlgorithms | 9946756c8b2b9f3d27fb0b29d14b9df316afef7d | d769f37bde209d976139d0105c0ac219d98fbbce | refs/heads/master | 2022-11-06T10:07:25.951199 | 2020-06-28T18:43:53 | 2020-06-28T18:43:53 | 266,312,564 | 5 | 2 | null | null | null | null | UTF-8 | Python | false | false | 1,588 | py | import time
# starting time
start = time.time()
n=0
def is_safe(n, graph, colors, c):
# Iterate trough adjacent vertices
# and check if the vertex color is different from c
for i in range(n):
if graph[n][i] and c == colors[i]: return False
return True
# n = vertex nb
def graphColoringUtil(graph, color_nb, colors, n):
# Check if all vertices are assigned a color
if color_nb+1 == n :
return True
# Trying differents color for the vertex n
for c in range(1, color_nb+1):
# Check if assignment of color c to n is possible
if is_safe(n, graph, colors, c):
# Assign color c to n
colors[n] = c
# Recursively assign colors to the rest of the vertices
if graphColoringUtil(graph, color_nb, colors, n+1): return True
# If there is no solution, remove color (BACKTRACK)
colors[n] = 0
colors[n] = 0
#We test the algorithm for the following graph and test whether it is 3 colorable:
# (3)---(2)
# | / |
# | / |
# | / |
# (0)---(1)
vertex_nb = 5
# nb of colors
color_nb = 4
# Initiate vertex colors
colors = [0] * vertex_nb
graph = [
[0,0,1,1,0],
[0,0,0,1,1],
[1,0,0,0,1],
[1,1,0,0,0],
[0,1,1,0,0],
]
#beginning with vertex 0
if graphColoringUtil(graph, color_nb, colors, 0):
print()
else:
print ("No solutions")
#sleeping for 1 second to get 10 seconds runtime
time.sleep(1)
# program body ends
# end time
end = time.time()
tt=end-start
# total time taken
print("Backtracking Algorithm : %f" %tt)
print()
| [
"[email protected]"
]
| |
bc198b1bbdd90d4dee4ee10abd4ca15226d57dd9 | e03ae6c0a87187d1ad24a172d1d573c2efa43117 | /homework2-5.py | 262af9fc0d870bf2a604e00ff4047150257f4911 | []
| no_license | AlSavva/Python-basics-homework | 3dc4841974d0fc5d5b1ff9ac7a50934540ab9be1 | 1d21e365c4a4524eb62b0fa1f23da848f9b066d5 | refs/heads/master | 2023-08-01T13:54:17.487022 | 2020-09-30T21:58:30 | 2020-09-30T21:58:30 | 290,989,515 | 0 | 0 | null | 2020-09-30T21:58:31 | 2020-08-28T08:12:05 | Python | UTF-8 | Python | false | false | 2,425 | py | # Реализовать структуру «Рейтинг», представляющую собой не возрастающий набор
# натуральных чисел. У пользователя необходимо запрашивать новый элемент
# рейтинга. Если в рейтинге существуют элементы с одинаковыми значениями, то
# новый элемент с тем же значением должен разместиться после них.
# Подсказка. Например, набор натуральных чисел: 7, 5, 3, 3, 2.
# Пользователь ввел число 3. Результат: 7, 5, 3, 3, 3, 2.
# Пользователь ввел число 8. Результат: 8, 7, 5, 3, 3, 2.
# Пользователь ввел число 1. Результат: 7, 5, 3, 3, 2, 1.
# Набор натуральных чисел можно задать непосредственно в коде, например,
# my_list = [7, 5, 3, 3, 2].
rating_list = []
pre_rating_list = input('Для создания списка введите группу целых чисел,'
'разделённых пробелами: ').split()
for n in pre_rating_list: # поскольку нами не пройдена функция "map", делаем цикл для перевода строк в число
rating_list.append(int(n))
for num in range(1, len(rating_list)): #сортировка введенного списка методом вставки
i = num
while i > 0 and rating_list[i - 1] < rating_list[i]:
rating_list[i], rating_list[i - 1] = rating_list[i - 1], rating_list[i]
i -= 1
print(f'Введённый список отсортирован:\n{rating_list}')
new_num = input('Добавьте ещё одно целое число в список: ')
rating_list.append(int(new_num))
for ind in range(len(rating_list) - 1):#сортировка введенного списка методом выбора
for i in range(ind + 1, len(rating_list)):
if rating_list[i] > rating_list[ind]:
rating_list[i], rating_list[ind] = rating_list[ind], rating_list[i]
print(f'Новый элемент добавлен в соответствии с его рейтингом:\n{rating_list}')
| [
"[email protected]"
]
| |
914b43a3f40792a728183c80d318067f6bfb208e | 1278be8cb9f536b6a9c576440e2673279beded2e | /app.py | 0181a61877e31070b4ecafe09aea6524a06d4894 | []
| no_license | patrickhpatin/web-scraping-challenge | ba8dade253aa7b4d1aeec53d0ccdabc9e263bd35 | 5f591d642b5970e65494f624bbc98ac403e2edd9 | refs/heads/master | 2021-02-16T14:57:14.011696 | 2020-03-13T11:11:56 | 2020-03-13T11:11:56 | 245,018,298 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,440 | py | # Dependencies
import pandas as pd
import time as time
import numpy as np
import requests
from flask import Flask, render_template, redirect, jsonify
import flask
import scrape_mars
#################################################
# Flask Setup
#################################################
app = Flask(__name__)
#################################################
# Flask Routes
#################################################
# Display routes
@app.route('/routes')
def routes():
"""List of all available api routes."""
return (
f"Available Routes:<br>"
f"/routes<br>"
f"/scrape"
)
# end def routes()
@app.route("/scrape")
def scrape():
try:
if scrape_mars.populate_mars_db() == 200:
mars_data = scrape_mars.get_mars_data_from_db()
# Redirect to the home
return redirect("/", code=302)
else:
print("There was a problem scraping data from NASA. Please try again later.")
# end if
except Exception as e:
print(e)
# end def scrape()
@app.route('/')
def index():
try:
mars_data = scrape_mars.get_mars_data_from_db()
# Return the index.html with mars data populated
return render_template("index.html",
news_title=mars_data[0]["news_title"],
news_p=mars_data[0]["news_p"],
featured_image_url=mars_data[0]["featured_image_url"],
mars_weather=mars_data[0]["mars_weather"],
mars_table=mars_data[0]["mars_table"],
hem1_name=mars_data[0]["hemisphere_image_urls"][0]["title"],
hem1_image=mars_data[0]["hemisphere_image_urls"][0]["img_url"],
hem2_name=mars_data[0]["hemisphere_image_urls"][1]["title"],
hem2_image=mars_data[0]["hemisphere_image_urls"][1]["img_url"],
hem3_name=mars_data[0]["hemisphere_image_urls"][2]["title"],
hem3_image=mars_data[0]["hemisphere_image_urls"][2]["img_url"],
hem4_name=mars_data[0]["hemisphere_image_urls"][3]["title"],
hem4_image=mars_data[0]["hemisphere_image_urls"][3]["img_url"],
background="../Images/Mars.jpg")
except Exception as e:
print(e)
# end def index()
if __name__ == '__main__':
app.run(debug=False) | [
"[email protected]"
]
| |
b35d9f4b2981a58a702913613a20ccf0b2c12694 | 27617bdbbc666d3faccd12f1afe1fa40ea0a0c08 | /oeis.py | ff88e9c6652d0ab3caf192fec0b121e9b3507cf5 | []
| no_license | AndrewWalker/oeis | 1625cf1f0673c2ae0fa61e9e1a96d3f7cd675299 | ee128a71b7eaa52ef96364ab0997038e707913ce | refs/heads/master | 2020-04-30T11:45:38.137476 | 2013-02-14T09:17:30 | 2013-02-14T09:17:30 | 8,188,260 | 6 | 3 | null | null | null | null | UTF-8 | Python | false | false | 4,097 | py | """Access to the Online Encylopedia of Integer Sequences (OEIS)
The OEIS is accessible via a web interface at http://oeis.org/
This module uses requests to access the OEIS, and then parses a minimal
subset of the information contained there.
If you want to search for the 5 best matches for the sequence [1,2,3,4,5],
you could do something like:
>>> import oeis
>>> sequences = oeis.query([1, 2, 3, 4, 5], 5)
>>> for seq in sequences:
>>> print seq.id
>>> print seq.name
>>> print seq.formula
>>> print seq.sequence
>>> print seq.comments
This code is copyright 2013 Andrew Walker
See the end of the source file for the license of use.
"""
import requests
__version__ = '0.1'
__all__ = ['query']
class IntegerSequence(object):
"""Integer sequence API around the OEIS internal format
References
----------
[1] http://oeis.org/eishelp1.html
"""
def __init__(self, blk):
"""Parse the OEIS text data"""
self.id = None
self.name = None
self.formula = None
self.sequence = []
self.comments = ''
for line in blk:
# TODO - adopt a more robust approach to this split
data_type = line[1]
sequence_name = line[3:10]
data = line[10:].strip()
if data_type == 'I':
self.id = sequence_name
elif data_type == 'S':
if data[-1] == ',':
data = data[:-1]
self.sequence = [int(num) for num in data.split(',')]
elif data_type == 'N':
self.name = data
elif data_type == 'C':
self.comments += (data + '\n')
elif data_type == 'F':
self.formula = data
class OEISError(Exception):
def __init__(self, message):
Exception.__init__(self, message)
def raw_query(sequence, n=1):
"""Execute a raw query to the OEIS database
"""
payload = {}
payload['q'] = ','.join(str(s) for s in sequence)
payload['n'] = str(n)
payload['fmt'] = 'text'
response = requests.get('http://oeis.org/search', params=payload)
if response.status_code != 200:
raise OEISError('Invalid HTTP response from the OEIS')
return response.content
def split_blocks(content):
"""Split the response text into blocks related to each sequence
"""
blocks = content.split('\n\n')
return [block for block in blocks if _valid_block(block)]
def _valid_block(block):
"""Identify Valid blocks of sequence text
A valid block must be non-empty, and start with
an appropriate marker (%)
"""
return len(block) > 0 and block[0] == '%'
def query(sequence, n=1):
"""Search the OEIS for upto `n` of the best matches for a sequence
"""
content = raw_query(sequence, n)
blocks = split_blocks(content)
return [IntegerSequence(block.split('\n')) for block in blocks]
# Copyright (c) 2012 Andrew Walker <[email protected]>
#
# 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.
# vim: set filetype=python ts=4 sw=4 et si tw=75
| [
"[email protected]"
]
| |
d126e8fa49a599dc0ff3362ab3d9678917d6d3e1 | 32499375e19a40c33e4d7f4930bbe957f344b5fb | /regenerate-moderator-list.py | 90f87f3d66155e620c8981da80dc90c88756aa43 | []
| no_license | diazona/pingbot | 7e96c71f7cb0a2d80e00ba03dd23bc6fe21ded20 | c23ff32bfcd9041391da89fa5ffb78ebd3a653b1 | refs/heads/master | 2021-05-25T09:00:28.049885 | 2018-04-18T07:12:06 | 2018-04-18T07:12:06 | 55,352,168 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,507 | py | try:
import stackexchange
except ImportError:
print('This script requires Py-StackExchange')
raise
import io
import json
import shutil
# An incomplete mapping of site codes that might be used for pinging to their
# corresponding domain names
SITE_CODE_MAPPINGS = {
'so': 'stackoverflow.com',
'su': 'superuser.com',
'sf': 'serverfault.com',
'askubuntu': 'askubuntu.com'
}
def site_domain_from_key(key):
try:
return SITE_CODE_MAPPINGS[key]
except KeyError:
return '{}.stackexchange.com'.format(key)
def update_moderator_list(filename):
with io.open(filename, encoding='UTF-8') as f:
mod_info = json.load(f)
mod_info['moderators'] = {
site_key: [
{
'name': mod.display_name,
'id': mod.id
}
for mod in stackexchange.Site(
site_domain_from_key(site_key)
).moderators() # not moderators_elected(), because I want appointed mods too
if not mod.is_employee and mod.id > 0 # exclude Community
]
for site_key in mod_info['moderators']
}
shutil.copy2(filename, filename + '.backup')
with io.open(filename, mode='w', encoding='UTF-8') as f:
json.dump(mod_info, f, indent=4, sort_keys=True)
def main():
import sys
try:
filename = sys.argv[1]
except IndexError:
filename = 'moderators.json'
update_moderator_list(filename)
if __name__ == '__main__':
main()
| [
"[email protected]"
]
| |
1bec5a0aed0cd7b8937fbca5beced2494d070731 | e163c1e2d03d4a480bfdf323bda71ebec4f8cdbc | /API_Project/venv/Scripts/django-admin.py | 7dacfaec9b272c3ea19e9e6bf67fe45580ec4745 | []
| no_license | elenghazaryan/All-in-group-tasks | 0d09e835cc24d4c5e636d7ce61d5e786d820626c | 2e0d0c010f6e224875b36ae3c87fae1a71b3dfe8 | refs/heads/main | 2023-02-24T05:12:05.112523 | 2020-12-09T19:41:23 | 2020-12-09T19:41:23 | 334,922,488 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 706 | py | #!c:\users\user\desktop\allin_tasks\api_project\venv\scripts\python.exe
# When the django-admin.py deprecation ends, remove this script.
import warnings
from django.core import management
try:
from django.utils.deprecation import RemovedInDjango40Warning
except ImportError:
raise ImportError(
'django-admin.py was deprecated in Django 3.1 and removed in Django '
'4.0. Please manually remove this script from your virtual environment '
'and use django-admin instead.'
)
if __name__ == "__main__":
warnings.warn(
'django-admin.py is deprecated in favor of django-admin.',
RemovedInDjango40Warning,
)
management.execute_from_command_line()
| [
"[email protected]"
]
| |
826f0cd3c5eac6916f5ae7bebf7a5c54ce15cce7 | 3e550f7bd72fafbf09acf92371b93c6ea2b87146 | /testif.py | 614648e899e28b252fd578241bd7e1fdb02165cc | []
| no_license | falaqm/basicm | 0a6cd7260670742d0988c6c54bd138bb77267f7a | bb5d5d7bdeb1db14df52c80afd0aa06ec9fb4c35 | refs/heads/master | 2021-04-18T21:06:49.496637 | 2018-05-16T08:14:25 | 2018-05-16T08:14:25 | 126,450,335 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 419 | py | # usa=['atlanta','new york','chicago','baltimore']
# uk=['london','bristol','cambridge']
# india=['mumbai','delhi','bengaluru']
# city1=input("enter city: ")
# city2=input('enter city: ')
# if city1 in usa and city2 in usa:
# print('USA')
# elif city1 in uk and city2 in uk:
# print("uK")
# elif city1 in india and city2 in india:
# print("india")
# else:
# print('invalid')
x=input('enter the number')
| [
"[email protected]"
]
| |
e58c4031eae13c74ca563b3d4e9cc76ceb6b8101 | db6ecee15f9f8d38156b402a5aa019ccdecc76e1 | /train.py | 7c75b05bbc9a84379f9bbaa2579a05c4bce56be0 | [
"Apache-2.0"
]
| permissive | USTCPCS/End-to-End-Learning-for-Self-Driving-Cars | 275db7e4f940851eb338c465ea1ef636eede18bb | a8f24f10f70177e1c97659c2c4f91eee1bfeff22 | refs/heads/master | 2020-04-14T19:59:20.218401 | 2017-12-30T16:31:14 | 2017-12-30T16:31:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,107 | py | import argparse
import os
import tensorflow as tf
from model import Nivdia_Model
import reader
FLAGS = None
def batch_eval(target, data, x_image, y, keep_prob, batch_size, sess):
value = 0
batch_num = (data.num_expamles + batch_size - 1) // batch_size
for i in range(batch_num):
batch_x, batch_y = data.next_batch(batch_size, shuffle=False)
res = sess.run(
target, feed_dict={
x_image: batch_x,
y: batch_y,
keep_prob: 1.0
})
value += res * len(batch_x)
return value / data.num_expamles
def train():
x_image = tf.placeholder(tf.float32, [None, 66, 200, 3])
y = tf.placeholder(tf.float32, [None, 1])
keep_prob = tf.placeholder(tf.float32)
model = Nivdia_Model(x_image, y, keep_prob, FLAGS)
# dataset reader
dataset = reader.Reader(FLAGS.data_dir, FLAGS)
saver = tf.train.Saver()
with tf.Session() as sess:
merged = tf.summary.merge_all()
train_writer = tf.summary.FileWriter(FLAGS.log_dir + '/train',
sess.graph)
# initialize all varibales
sess.run(tf.global_variables_initializer())
min_validation_loss = float('Inf')
# restore model
if not FLAGS.disable_restore:
path = tf.train.latest_checkpoint(FLAGS.model_dir)
if not (path is None):
saver.restore(sess, path)
# validation
min_validation_loss = batch_eval(
model.loss, dataset.validation, x_image, y, keep_prob,
FLAGS.batch_size, sess)
print('Restore model from', path)
for i in range(FLAGS.max_steps):
batch_x, batch_y = dataset.train.next_batch(FLAGS.batch_size)
# train model
if i % 100 == 99: # Record execution stats
run_options = tf.RunOptions(
trace_level=tf.RunOptions.FULL_TRACE)
run_metadata = tf.RunMetadata()
summary, _ = sess.run(
[merged, model.optimization],
feed_dict={x_image: batch_x,
y: batch_y,
keep_prob: 0.8},
options=run_options,
run_metadata=run_metadata)
train_writer.add_run_metadata(run_metadata, 'step%03d' % i)
else:
summary, _ = sess.run(
[merged, model.optimization],
feed_dict={
x_image: batch_x,
y: batch_y,
keep_prob: 0.8
})
train_writer.add_summary(summary, i)
# validation
validation_loss = batch_eval(model.loss, dataset.validation,
x_image, y, keep_prob,
FLAGS.batch_size, sess)
if (validation_loss < min_validation_loss):
min_validation_loss = validation_loss
saver.save(sess, os.path.join(FLAGS.model_dir, "model.ckpt"))
if i % FLAGS.print_steps == 0:
loss = sess.run(
model.loss,
feed_dict={
x_image: batch_x,
y: batch_y,
keep_prob: 1.0
})
print("Step", i, "train_loss: ", loss, "validation_loss: ",
validation_loss)
train_writer.close()
def main():
if tf.gfile.Exists(FLAGS.log_dir):
tf.gfile.DeleteRecursively(FLAGS.log_dir)
tf.gfile.MakeDirs(FLAGS.log_dir)
if not tf.gfile.Exists(FLAGS.model_dir):
tf.gfile.MakeDirs(FLAGS.model_dir)
train()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--max_steps',
type=int,
default=20000,
help='Number of steps to run trainer')
parser.add_argument(
'--print_steps',
type=int,
default=100,
help='Number of steps to print training loss')
parser.add_argument(
'--learning_rate',
type=float,
default=1e-4,
help='Initial learning rate')
parser.add_argument(
'--batch_size', type=int, default=500, help='Train batch size')
parser.add_argument(
'--data_dir',
type=str,
default=os.path.join('.', 'driving_dataset'),
help='Directory of data')
parser.add_argument(
'--log_dir',
type=str,
default=os.path.join('.', 'logs'),
help='Directory of log')
parser.add_argument(
'--model_dir',
type=str,
default=os.path.join('.', 'saved_model'),
help='Directory of saved model')
parser.add_argument(
'--disable_restore',
type=int,
default=0,
help='Whether disable restore model from model directory')
FLAGS, unparsed = parser.parse_known_args()
main()
| [
"[email protected]"
]
| |
64592adb22e89fb479d53c7323860b590acec211 | d2d6e0a5eaf82f65da0505daa500aa7a589e637d | /rcsworld/rcs/network.py | 50d45dfd113e993ce840903b1664381a56be7227 | [
"MIT"
]
| permissive | Indeximal/RailControlSystemV3 | 74280c200efc303e9047dc3451968d262e277bd8 | 4be7a368660f0ddb0830a0cfeba555b0559274aa | refs/heads/main | 2023-08-08T01:21:44.725001 | 2021-09-12T08:36:54 | 2021-09-12T08:36:54 | 405,358,666 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,353 | py | from .point import DirectedPoint
from .block import RailBlock
def example_usage():
loop = (RailNetworkBuilder()
.start(0, -1)
.mark("start")
.track_to(1, 0)
.track_to(0, 1)
.track_to(-1, 0)
.connect_to("start")
.build())
network = (RailNetworkBuilder()
.start(-1, 1)
.mark("start")
.track_to(0, 0)
.split()
.track_to(2, 1)
.track_to(0, 3)
.mark("A")
.build_other()
.track_to(1, 1)
.merge_into("A") # the rail doesn't actually exist yet
.connect_to("start")
.build())
return network
class RailNetwork:
def __init__(self):
self.point_connections_right = dict()
self.point_connections_left = dict()
self.blocks = list()
def connect(self, point_a: DirectedPoint, point_b: DirectedPoint) -> RailBlock:
block = RailBlock(point_a, point_b)
# TODO: maybe implement this?
return block
class RailNetworkBuilder:
def __init__(self):
self.network: RailNetwork = RailNetwork()
self.prev_point = None
self.prev_track = None
self.marks = dict()
def start(self, x: float, y: float):
self.prev_point = DirectedPoint((x, y), (0.5, 0))
return self
def mark(self, mark_name: str):
self.marks[mark_name] = self.prev_point
return self
def track_to(self, x: float, y: float):
point = DirectedPoint((x, y), (0.5, 0))
track = RailBlock(self.prev_point.opposite(), point)
if self.prev_track:
self.prev_track.b_connections.append(track)
track.a_connections = [self.prev_track]
self.network.blocks.append(track)
self.prev_point = point
self.prev_track = track
return self
def connect_to(self, mark_name: str):
raise NotImplementedError("todo: fix the mark system, to be based on tracks not points")
point = self.marks[mark_name]
track = RailBlock(self.prev_point.opposite(), point)
if self.prev_track:
self.prev_track.b_connections.append(track)
track.a_connections = [self.prev_track]
next_track = None
for block in self.network.blocks:
if point == block.a_point:
next_track = block
break
if not next_track:
raise Exception("Coundn't find track to connect to")
track.b_connections = [next_track]
next_track.a_connections.append(track)
self.network.blocks.append(track)
self.prev_point = None
self.prev_track = None
return self
def build(self):
return self.network
| [
"[email protected]"
]
| |
6bd1b8075da7a6011954a7dd97c91bca1878a74c | 32a73d1c9359c8edb184a09ed602f218429458b5 | /tests/apps/bad_rollback_flow_drop_column_with_notnull_app/migrations/0001_initial.py | 6dc41e4f4ce11ff4ba761a96b62f6f7d8af7e39b | [
"MIT"
]
| permissive | tbicr/django-pg-zero-downtime-migrations | bf705cd4655efc3d698ffec859945e921671979f | a96fb4dea8361857ca24b05e84a9ab6f612a3bb6 | refs/heads/master | 2023-08-29T00:11:07.514299 | 2023-06-23T01:14:11 | 2023-06-24T23:31:35 | 137,562,760 | 468 | 25 | MIT | 2023-06-24T23:31:37 | 2018-06-16T07:36:35 | Python | UTF-8 | Python | false | false | 787 | py | # Generated by Django 3.1 on 2019-09-22 21:00
from django.db import migrations, models
def insert_objects(apps, schema_editor):
db_alias = schema_editor.connection.alias
TestTable = apps.get_model('bad_rollback_flow_drop_column_with_notnull_app', 'TestTable')
TestTable.objects.using(db_alias).create(field=1)
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='TestTable',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('field', models.IntegerField()),
],
),
migrations.RunPython(insert_objects, migrations.RunPython.noop),
]
| [
"[email protected]"
]
| |
f17ed08bf47fc77482e427e5e7c87e52a0ab5d46 | 756d50be34245115ad28e79f4dfceb5516d17225 | /relsearch.py | af268beec2663fa43b51c0f5de63ab395fea2d2b | []
| no_license | abyssonym/gg3 | f1ce189a2a70786da8b2ab78281b39615fc59af2 | 1e6adadc6765d339ebbd7ca650d9b435d56fb366 | refs/heads/master | 2021-01-18T13:51:25.702975 | 2017-11-16T22:26:30 | 2017-11-16T22:26:30 | 34,976,112 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,264 | py | from sys import argv
from string import ascii_lowercase
from shutil import copyfile
filename = argv[1]
outfile = "test.smc"
searchstr = argv[2].lower()
if '.' in searchstr:
searchstr = map(int, searchstr.split('.'))
else:
numdict = dict([(b, a) for (a, b) in enumerate(ascii_lowercase)])
searchstr = [numdict[c] if c in numdict else c for c in searchstr]
print searchstr
f = open(filename, 'r+b')
addr = 0
checkstr = None
while True:
f.seek(addr)
bytestr = f.read(len(searchstr))
if len(bytestr) != len(searchstr):
break
bytestr = map(ord, bytestr)
offset = bytestr[0] - searchstr[0]
newbytestr = [i - offset for i in bytestr]
if all([a == b for (a, b) in zip(newbytestr, searchstr)]):
print "%x" % addr
print bytestr
check = None
if not checkstr:
check = raw_input("> ")
if check and check.lower()[0] == 'y':
checkstr = bytestr
if checkstr and all([a == b for (a, b) in zip(checkstr, bytestr)]):
copyfile(filename, outfile)
f2 = open(outfile, 'r+b')
f2.seek(addr)
f2.write("".join([chr(bytestr[0]) for _ in bytestr]))
f2.close()
check = raw_input("> ")
addr += 1
| [
"none"
]
| none |
d2719e8aa61923b461559fd373afeb6183e795b1 | 421f860e10431ad15b0a368d337cf5cd974b3daa | /tests/test_corpora/standard-swe/convert.py | e575f1876574b060ab586d5c6a620d42b7c15f5b | [
"MIT"
]
| permissive | borsna/sparv-pipeline | 1eca7c1bce7b30d288b273df572c9a298e5c68ff | 0fe5f27d0d82548ecc6cb21a69289668aac54cf1 | refs/heads/master | 2023-02-22T04:44:33.722404 | 2020-12-07T16:45:04 | 2020-12-07T16:45:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 349 | py | """Example for a custom annotator."""
from sparv import Annotation, Output, annotator
@annotator("Convert every word to uppercase")
def uppercase(word: Annotation = Annotation("<token:word>"),
out: Output = Output("<token>:custom.convert.upper")):
"""Convert to uppercase."""
out.write([val.upper() for val in word.read()])
| [
"[email protected]"
]
| |
3563896c1af07e2461d9a34778a0132efd4ca7a9 | 81e72efa668ae404b6b9edd12c8f11c9f1e6319a | /Backend/app/quote_of/models.py | 521d0136fdc25fb390a5ce877d82bb15af54df0c | []
| no_license | khannatanmai/RottenTomatoes-webapp | 773e7111d939c895d88ede1f35edb962087630f4 | a0c3d58e81b5f9b15b7244242397e6b7fd9e854e | refs/heads/master | 2021-10-27T06:51:39.602911 | 2019-04-16T18:01:24 | 2019-04-16T18:01:24 | 104,780,666 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 748 | py | from flask_sqlalchemy import SQLAlchemy
from app import db
class Quote_Of(db.Model):
__tablename__ = 'quote_of'
quote_of_id = db.Column(db.Integer, primary_key = True, autoincrement = True)
quotes_id = db.Column(db.Integer, db.ForeignKey('quotes.quotes_id', ondelete='CASCADE'))
ent_id = db.Column(db.Integer, db.ForeignKey('ent.ent_id'))
def __init__(self, quotes_id, ent_id):
self.quotes_id = quotes_id
self.ent_id = ent_id
def to_dict(self):
return {
'quoute_of_id': self.quote_of_id,
'quotes_id': self.quotes_id,
'ent_id': self.ent_id
}
def __repr__(self):
return "Quote<%d> is of Entertainment<%d>" %(self.quotes_id, self.ent_id)
| [
"[email protected]"
]
| |
6ca3c25866e8bb939115c64e727679830d0397ed | 3514b1e55ba48b54a7834e2b834cccc8c1fed856 | /PAIS/blog/urls.py | b004ab83d1ed08ee46c2f30934558b7338d96326 | []
| no_license | clarenceehsu/blog_with_django | 540d4e57ca0367ad7494b992020847b28107adc1 | 7d13ca7057e1d2d278c2b88075fca0263e1a5e98 | refs/heads/master | 2020-06-27T21:27:16.847823 | 2019-10-07T15:12:01 | 2019-10-07T15:12:01 | 200,053,365 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 270 | py | from django.urls import path
from django.urls import re_path
from blog import views as blog_views
app_name = 'blog'
urlpatterns = [
# re_path(r'^post/(?P<pk>[0-9]+)/$', blog_views.render, name='render'),
path('<path:match>', blog_views.match, name='match'),
] | [
"[email protected]"
]
| |
e1bc080590be397ae15d86246e7de108caaf0d0f | 6fcfb638fa725b6d21083ec54e3609fc1b287d9e | /python/benanne_kaggle-ndsb/kaggle-ndsb-master/dihedral_ops.py | e5d8d87655fb7072e1ad79d489e425aaca16ac92 | []
| no_license | LiuFang816/SALSTM_py_data | 6db258e51858aeff14af38898fef715b46980ac1 | d494b3041069d377d6a7a9c296a14334f2fa5acc | refs/heads/master | 2022-12-25T06:39:52.222097 | 2019-12-12T08:49:07 | 2019-12-12T08:49:07 | 227,546,525 | 10 | 7 | null | 2022-12-19T02:53:01 | 2019-12-12T07:29:39 | Python | UTF-8 | Python | false | false | 12,079 | py | import numpy as np
import theano
import theano.sandbox.cuda as cuda
from pycuda.compiler import SourceModule
import theano.misc.pycuda_init
class PyCudaOp(cuda.GpuOp):
def __eq__(self, other):
return type(self) == type(other)
def __hash__(self):
return hash(type(self))
def __str__(self):
return self.__class__.__name__
def output_type(self, inp):
raise NotImplementedError
def make_node(self, inp):
inp = cuda.basic_ops.gpu_contiguous(
cuda.basic_ops.as_cuda_ndarray_variable(inp))
assert inp.dtype == "float32"
return theano.Apply(self, [inp], [self.output_type(inp)()])
class CyclicRollOp(PyCudaOp):
def output_type(self, inp):
return cuda.CudaNdarrayType(broadcastable=[False] * (inp.type.ndim))
def make_thunk(self, node, storage_map, _, _2):
inputs = [storage_map[v] for v in node.inputs]
outputs = [storage_map[v] for v in node.outputs]
mod = SourceModule("""
__global__ void cyclic_roll(float * input, float * output, int batch_size, int num_features) {
int x = blockIdx.x*blockDim.x + threadIdx.x; // feature dim, fastest varying index!
int y = blockIdx.y*blockDim.y + threadIdx.y; // batch dim
int height = 4 * batch_size;
int width = 4 * num_features;
if (x < num_features && y < height) {
for (int i = 0; i < 4; i++) {
int y_out = (y + batch_size * (4 - i)) % height;
int x_out = x + num_features * i;
output[y_out * width + x_out] = input[y * num_features + x];
}
}
}""")
kernel = mod.get_function("cyclic_roll")
def thunk():
in_shape = inputs[0][0].shape
rows, cols = in_shape
assert rows % 4 == 0
out_shape = (rows, 4 * cols)
batch_size = rows // 4
num_features = cols
out = outputs[0]
# only allocate if there is no previous allocation of the right size.
if out[0] is None or out[0].shape != out_shape:
out[0] = cuda.CudaNdarray.zeros(out_shape)
x_block = 16
y_block = 16
block = (x_block, y_block, 1)
x_grid = int(np.ceil(float(in_shape[1]) / x_block))
y_grid = int(np.ceil(float(in_shape[0]) / y_block))
grid = (x_grid, y_grid, 1)
kernel(inputs[0][0], out[0], np.intc(batch_size), np.intc(num_features), block=block, grid=grid)
thunk.inputs = inputs
thunk.outputs = outputs
thunk.lazy = False
return thunk
def grad(self, inp, grads):
top, = grads
top = cuda.basic_ops.gpu_contiguous(top)
return [CyclicRollGradOp()(top)]
cyclic_roll = CyclicRollOp()
class CyclicRollGradOp(PyCudaOp):
def output_type(self, inp):
return cuda.CudaNdarrayType(broadcastable=[False] * (inp.type.ndim))
def make_thunk(self, node, storage_map, _, _2):
inputs = [storage_map[v] for v in node.inputs]
outputs = [storage_map[v] for v in node.outputs]
mod = SourceModule("""
__global__ void cyclic_roll_grad(float * input, float * output, int batch_size, int num_features) {
int x = blockIdx.x*blockDim.x + threadIdx.x; // feature dim, fastest varying index!
int y = blockIdx.y*blockDim.y + threadIdx.y; // batch dim
int height = 4 * batch_size;
int width = 4 * num_features;
float val = 0;
if (x < num_features && y < height) {
for (int i = 0; i < 4; i++) {
int y_in = (y + batch_size * (4 - i)) % height;
int x_in = x + num_features * i;
val += input[y_in * width + x_in];
}
output[y * num_features + x] = val;
}
}""")
kernel = mod.get_function("cyclic_roll_grad")
def thunk():
in_shape = inputs[0][0].shape
rows, cols = in_shape
assert rows % 4 == 0
assert cols % 4 == 0
out_shape = (rows, cols // 4)
batch_size = rows // 4
num_features = cols // 4
out = outputs[0]
# only allocate if there is no previous allocation of the right size.
if out[0] is None or out[0].shape != out_shape:
out[0] = cuda.CudaNdarray.zeros(out_shape)
x_block = 16
y_block = 16
block = (x_block, y_block, 1)
x_grid = int(np.ceil(float(out_shape[1]) / x_block))
y_grid = int(np.ceil(float(out_shape[0]) / y_block))
grid = (x_grid, y_grid, 1)
kernel(inputs[0][0], out[0], np.intc(batch_size), np.intc(num_features), block=block, grid=grid)
thunk.inputs = inputs
thunk.outputs = outputs
thunk.lazy = False
return thunk
class CyclicConvRollOp(PyCudaOp):
def output_type(self, inp):
return cuda.CudaNdarrayType(broadcastable=[False] * (inp.type.ndim))
def make_thunk(self, node, storage_map, _, _2):
inputs = [storage_map[v] for v in node.inputs]
outputs = [storage_map[v] for v in node.outputs]
mod = SourceModule("""
__global__ void cyclic_convroll(float * input, float * output, int batch_size, int num_channels, int map_size) {
int x = blockIdx.x*blockDim.x + threadIdx.x; // feature dim, fastest varying index!
int y = blockIdx.y*blockDim.y + threadIdx.y; // batch dim
int map_size_sq = map_size * map_size;
int example_size = num_channels * map_size_sq;
int num_rows = 4 * batch_size; // number of rows in the input/output, seen as a 2D array
int num_cols = 4 * example_size; // number of columns in the output, seen as a 2D array
// feature indices (channels, height, width)
int x_channel = x / map_size_sq;
int x_f0 = (x % map_size_sq) / map_size;
int x_f1 = x % map_size;
int x_out_f0 = x_f0;
int x_out_f1 = x_f1;
int tmp;
if (x < example_size && y < num_rows) {
for (int i = 0; i < 4; i++) {
int y_out = (y + batch_size * (4 - i)) % num_rows;
int x_out = example_size * i + x_channel * map_size_sq + x_out_f0 * map_size + x_out_f1;
output[y_out * num_cols + x_out] = input[y * example_size + x];
// note that the writes to output go in reverse order for all the rotated feature maps.
// this may slow things down a little, perhaps there is room for further optimization.
// rotate
tmp = x_out_f0;
x_out_f0 = x_out_f1;
x_out_f1 = map_size - 1 - tmp;
}
}
}""")
kernel = mod.get_function("cyclic_convroll")
def thunk():
in_shape = inputs[0][0].shape
full_batch_size, num_channels, height, width = in_shape
assert height == width # else convroll doesn't make sense
assert full_batch_size % 4 == 0
out_shape = (full_batch_size, 4 * num_channels, height, width)
batch_size = full_batch_size // 4
example_size = num_channels * height * width
map_size = height
out = outputs[0]
# only allocate if there is no previous allocation of the right size.
if out[0] is None or out[0].shape != out_shape:
out[0] = cuda.CudaNdarray.zeros(out_shape)
x_block = 16
y_block = 16
block = (x_block, y_block, 1)
x_grid = int(np.ceil(float(example_size) / x_block))
y_grid = int(np.ceil(float(full_batch_size) / y_block))
grid = (x_grid, y_grid, 1)
kernel(inputs[0][0], out[0], np.intc(batch_size), np.intc(num_channels), np.intc(map_size), block=block, grid=grid)
thunk.inputs = inputs
thunk.outputs = outputs
thunk.lazy = False
return thunk
def grad(self, inp, grads):
top, = grads
top = cuda.basic_ops.gpu_contiguous(top)
return [CyclicConvRollGradOp()(top)]
cyclic_convroll = CyclicConvRollOp()
class CyclicConvRollGradOp(PyCudaOp):
def output_type(self, inp):
return cuda.CudaNdarrayType(broadcastable=[False] * (inp.type.ndim))
def make_thunk(self, node, storage_map, _, _2):
inputs = [storage_map[v] for v in node.inputs]
outputs = [storage_map[v] for v in node.outputs]
mod = SourceModule("""
__global__ void cyclic_convroll_grad(float * input, float * output, int batch_size, int num_channels, int map_size) {
int x = blockIdx.x*blockDim.x + threadIdx.x; // feature dim, fastest varying index!
int y = blockIdx.y*blockDim.y + threadIdx.y; // batch dim
int map_size_sq = map_size * map_size;
int example_size = num_channels * map_size_sq;
int num_rows = 4 * batch_size; // number of rows in the input/output, seen as a 2D array
int num_cols = 4 * example_size; // number of columns in the input, seen as a 2D array
// feature indices (channels, height, width)
int x_channel = x / map_size_sq;
int x_f0 = (x % map_size_sq) / map_size;
int x_f1 = x % map_size;
int x_in_f0 = x_f0;
int x_in_f1 = x_f1;
int tmp;
float val;
if (x < example_size && y < num_rows) {
for (int i = 0; i < 4; i++) {
int y_in = (y + batch_size * (4 - i)) % num_rows;
int x_in = example_size * i + x_channel * map_size_sq + x_in_f0 * map_size + x_in_f1;
val += input[y_in * num_cols + x_in];
// rotate
tmp = x_in_f0;
x_in_f0 = x_in_f1;
x_in_f1 = map_size - 1 - tmp;
}
output[y * example_size + x] = val;
}
}""")
kernel = mod.get_function("cyclic_convroll_grad")
def thunk():
in_shape = inputs[0][0].shape
full_batch_size, num_channels_rolled, height, width = in_shape
assert height == width # else convroll doesn't make sense
assert full_batch_size % 4 == 0
assert num_channels_rolled % 4 == 0
num_channels = num_channels_rolled // 4
batch_size = full_batch_size // 4
out_shape = (full_batch_size, num_channels, height, width)
example_size = num_channels * height * width
map_size = height
out = outputs[0]
# only allocate if there is no previous allocation of the right size.
if out[0] is None or out[0].shape != out_shape:
out[0] = cuda.CudaNdarray.zeros(out_shape)
x_block = 16
y_block = 16
block = (x_block, y_block, 1)
x_grid = int(np.ceil(float(example_size) / x_block))
y_grid = int(np.ceil(float(full_batch_size) / y_block))
grid = (x_grid, y_grid, 1)
kernel(inputs[0][0], out[0], np.intc(batch_size), np.intc(num_channels), np.intc(map_size), block=block, grid=grid)
thunk.inputs = inputs
thunk.outputs = outputs
thunk.lazy = False
return thunk
| [
"[email protected]"
]
| |
42de801c7fa9b1c00c589a99d087d02dec697b05 | 3cf9f3042a8797a6b819b67e76fe7b7b0bfe3cb8 | /SQLWITHPROFINS/deletestack.py | 807e48e3ec5f0064fac67e310195e5dd85ce1785 | []
| no_license | Melissaa12/Kindle-book-review---big-data- | 3b855ff8dfd89e816e0ee02efcc9d344928a53e1 | 14330d733c0967a0a48db801dc8f6838c17d77be | refs/heads/main | 2023-02-24T08:20:28.269120 | 2020-12-08T03:00:30 | 2020-12-08T03:00:30 | 333,365,172 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 658 | py | from re import template
import boto3, yaml, json
import sys
# file must in the same dir as script
import json
from time import sleep
#To Delete Stack
stack_name = 'DBPJT3'
cloud_formation_client = boto3.client('cloudformation',aws_access_key_id= sys.argv[1],aws_secret_access_key=sys.argv[2],aws_session_token=sys.argv[3],region_name=sys.argv[4])
response = cloud_formation_client.delete_stack(
StackName=stack_name,
)
#to delete the key pair
ec2 = boto3.client('ec2',region_name='us-east-1',aws_access_key_id=sys.argv[1],aws_secret_access_key=sys.argv[2],aws_session_token=sys.argv[3])
response = ec2.delete_key_pair(KeyName=sys.argv[5])
print(response) | [
"[email protected]"
]
| |
39ce366767eb979edd3220b8406fcd87ed5005d5 | 738150687713893325accbf6fe1326651c4172e5 | /archer/core/job.py | 228b4ec7201dc4ed8641a9e35616780df73d509c | []
| no_license | vnetserg/archer | ae5e74a741e573481633a1d6019e571d5817a03d | 8f74b84f667ca82c66ead6a3ce2bde9a5e61f62c | refs/heads/master | 2020-12-24T11:17:58.001980 | 2016-11-07T02:55:28 | 2016-11-07T02:55:28 | 73,037,961 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,977 | py |
class Job:
'''
Class that represents a subprocess job.
It implements the functionality of starting a job, reading it's
stdout, writing to it's stdin and sending signals to it.
Also this class loads job's manifest (description of what program
expects as input and what it provides as output) and based on it
does the parsing of stdout, generating events that are then
analyzed by LocalHost.
'''
# General case error
class Error(Exception): pass
# Exception for constructor if job manifest with given name is not found
class NameError(Error): pass
# Exception for constructor if given context is inappropriatet for job
class ContextError(Error): pass
# Exception for signal() if there is no signal with given name
class SignalError(Error): pass
def __init__(self, name, context={}):
'''
Initialize the instance by loading manifest file for a job
with given name and saving its context.
Raise self.NameError if manifest for a job with given name
is not found.
Raise self.ContextError if given context is inappropriate for
this job.
Context is a dictionary with the following keys:
interface - Interface object
host - Host object
port - Port object
When ommitted, context values are considered None.
'''
# Make None context values explicit
for key in ["interface", "host", "port"]:
if key not in context:
context[key] = None
self.name = name # job manifest name
self.context = context # job context
self.jid = None # job id, assigned by LocalHost before running
self.pid = None # os proccess id, assigned when run
self.state = "init" # job state
self.return_code = None # job return code
def run(self):
'''
Run the job by creating a subproccess and launching it.
'''
# ...
self.pid = 0 # assign id of created proccess
self.state = "running"
def update(self):
'''
Read subproccess stdout, save in internal buffer, parse it
and return list of events. If neccesary, update self.state
and self.return_code.
'''
def read(self):
'''
Read proccess stdout from Job's internal buffer.
Note: should be called only after update() because this method
does not actually communicate with subproccess.
'''
def write(self, data):
'''
Write to subproccess stdin.
'''
def signal(self, sig="term"):
'''
Send signal to subproccess.
Raise self.SignalError if signal name is invalid.
'''
def isRunning(self):
'''
Return True if job is running now.
'''
| [
"[email protected]"
]
| |
cedc86c60287d2aa953379b03f884778d3db8f98 | baf080cb2ff76697daade8ca105b71d786c00fde | /util/plot_cpu.py | e957232679533d7bbca0807ec4d3c622e18023c3 | []
| no_license | bentenballer/SimulatingNetworks | d7bbf272a62f0a50043fc3ddb104b1cccb927e8d | 32a6c5914d967dc45bd91ac7faa2f67dcdb22489 | refs/heads/main | 2023-08-17T14:37:29.611721 | 2021-10-10T06:41:17 | 2021-10-10T06:41:17 | 415,506,886 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,449 | py | '''
Plot CPU utilization of each virtual host.
'''
from helper import *
parser = argparse.ArgumentParser("Plot stacked bar chart of CPU usage")
parser.add_argument('--files', '-f',
help="File to read CPU usage from.",
required=True,
nargs="+",
dest="files")
parser.add_argument('--out', '-o',
help="Output png for plot",
default=None,
dest="out")
parser.add_argument('-s', '--summarise',
help="Summarise the time series plot (boxplot). First 10 and last 10 values are ignored.",
default=False,
dest="summarise",
action="store_true")
parser.add_argument('--labels', '-l',
help="Labels for x-axis if summarising; defaults to file names",
required=False,
default=None,
nargs="+",
dest="labels")
args = parser.parse_args()
if args.labels is None:
args.labels = args.files
def aggregate(data):
"""Aggregates to give a total cpu usage"""
data = list(map(list, data))
return list(map(sum, list(zip(*data))))
def plot_series():
data = parse_cpu_usage(args.files[0])
N = len(data)
data = transpose(data)
ind = list(range(N))
width=1
colours = ['y','g','r','b','purple','brown','cyan']
legend = "user,system,nice,iowait,hirq,sirq,steal".split(',')
nfields = 7
legend = legend[0:nfields]
p = [0]*nfields
bottom = [0]*N
plt.ylabel("CPU %")
plt.xlabel("Seconds")
for i in range(nfields):
p[i] = plt.bar(ind[0:N], data[i], width, bottom=bottom, color=colours[i])
for j in range(N):
bottom[j] += data[i][j]
plt.legend([e[0] for e in p], legend)
def plot_summary():
plt.ylabel("CPU %")
to_plot=[]
for f in args.files:
data = parse_cpu_usage(f)
N = len(data)
data = transpose(data)
ind = list(range(N))
data = aggregate(data)
to_plot.append(data[10:-10])
plots = plt.boxplot(to_plot)
plt.yticks(list(range(0,110,10)))
plt.title("CPU utilisation")
plt.grid()
plt.xticks(list(range(1, 1+len(args.files))), args.labels)
if args.summarise:
plot_summary()
else:
plot_series()
if args.out is None:
plt.show()
else:
plt.savefig(args.out)
| [
"[email protected]"
]
| |
63309f5b16e32ac3d1a5c83f1cabc9d2e02f0132 | d05a59feee839a4af352b7ed2fd6cf10a288a3cb | /xlsxwriter/test/workbook/test_write_workbook_view.py | 683d301b318446951f7cca09b7fc061d5ee04506 | [
"BSD-2-Clause-Views"
]
| permissive | elessarelfstone/XlsxWriter | 0d958afd593643f990373bd4d8a32bafc0966534 | bb7b7881c7a93c89d6eaac25f12dda08d58d3046 | refs/heads/master | 2020-09-24T06:17:20.840848 | 2019-11-24T23:43:01 | 2019-11-24T23:43:01 | 225,685,272 | 1 | 0 | NOASSERTION | 2019-12-03T18:09:06 | 2019-12-03T18:09:05 | null | UTF-8 | Python | false | false | 4,953 | py | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2019, John McNamara, [email protected]
#
import unittest
from ...compatibility import StringIO
from ...workbook import Workbook
class TestWriteWorkbookView(unittest.TestCase):
"""
Test the Workbook _write_workbook_view() method.
"""
def setUp(self):
self.fh = StringIO()
self.workbook = Workbook()
self.workbook._set_filehandle(self.fh)
def test_write_workbook_view1(self):
"""Test the _write_workbook_view() method"""
self.workbook._write_workbook_view()
exp = """<workbookView xWindow="240" yWindow="15" windowWidth="16095" windowHeight="9660"/>"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_workbook_view2(self):
"""Test the _write_workbook_view() method"""
self.workbook.worksheet_meta.activesheet = 1
self.workbook._write_workbook_view()
exp = """<workbookView xWindow="240" yWindow="15" windowWidth="16095" windowHeight="9660" activeTab="1"/>"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_workbook_view3(self):
"""Test the _write_workbook_view() method"""
self.workbook.worksheet_meta.firstsheet = 1
self.workbook.worksheet_meta.activesheet = 1
self.workbook._write_workbook_view()
exp = """<workbookView xWindow="240" yWindow="15" windowWidth="16095" windowHeight="9660" firstSheet="2" activeTab="1"/>"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_workbook_view4(self):
"""Test the _write_workbook_view() method"""
self.workbook.set_size(0, 0)
self.workbook._write_workbook_view()
exp = """<workbookView xWindow="240" yWindow="15" windowWidth="16095" windowHeight="9660"/>"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_workbook_view5(self):
"""Test the _write_workbook_view() method"""
self.workbook.set_size(None, None)
self.workbook._write_workbook_view()
exp = """<workbookView xWindow="240" yWindow="15" windowWidth="16095" windowHeight="9660"/>"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_workbook_view6(self):
"""Test the _write_workbook_view() method"""
self.workbook.set_size(1073, 644)
self.workbook._write_workbook_view()
exp = """<workbookView xWindow="240" yWindow="15" windowWidth="16095" windowHeight="9660"/>"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_workbook_view7(self):
"""Test the _write_workbook_view() method"""
self.workbook.set_size(123, 70)
self.workbook._write_workbook_view()
exp = """<workbookView xWindow="240" yWindow="15" windowWidth="1845" windowHeight="1050"/>"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_workbook_view8(self):
"""Test the _write_workbook_view() method"""
self.workbook.set_size(719, 490)
self.workbook._write_workbook_view()
exp = """<workbookView xWindow="240" yWindow="15" windowWidth="10785" windowHeight="7350"/>"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_workbook_view9(self):
"""Test the _write_workbook_view() method"""
self.workbook.set_tab_ratio()
self.workbook._write_workbook_view()
exp = """<workbookView xWindow="240" yWindow="15" windowWidth="16095" windowHeight="9660"/>"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_workbook_view10(self):
"""Test the _write_workbook_view() method"""
self.workbook.set_tab_ratio(34.6)
self.workbook._write_workbook_view()
exp = """<workbookView xWindow="240" yWindow="15" windowWidth="16095" windowHeight="9660" tabRatio="346"/>"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_workbook_view11(self):
"""Test the _write_workbook_view() method"""
self.workbook.set_tab_ratio(0)
self.workbook._write_workbook_view()
exp = """<workbookView xWindow="240" yWindow="15" windowWidth="16095" windowHeight="9660" tabRatio="0"/>"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
def test_write_workbook_view12(self):
"""Test the _write_workbook_view() method"""
self.workbook.set_tab_ratio(100)
self.workbook._write_workbook_view()
exp = """<workbookView xWindow="240" yWindow="15" windowWidth="16095" windowHeight="9660" tabRatio="1000"/>"""
got = self.fh.getvalue()
self.assertEqual(got, exp)
def tearDown(self):
self.workbook.fileclosed = 1
| [
"[email protected]"
]
| |
4041ef0ddfca556771d9ad29a6c5b1bb3bfff056 | b2cb3fba925ff4c74ec6f4e9e47f6d81cf8ab314 | /10809.py | 030b749129b66912b12ed78cae0b3ef73955c312 | []
| no_license | haka913/boj | 599c693ed6c2e06b30a68d7b7e53c5a04b09a67f | 1f634b6e6036b080a876656dbf36c2dbd4f6383e | refs/heads/master | 2022-12-24T06:53:31.621957 | 2020-10-04T15:34:43 | 2020-10-04T15:34:43 | 212,800,293 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 142 | py | s = input()
dic = [-1] * 26
for i in s:
if(dic[ord(i) - ord('a')] == -1):
dic[ord(i) - ord('a')] = s.index(i)
print(*dic)
| [
"[email protected]"
]
| |
5ddba1270c889ab28de1f6107a603b4c97f4d9f3 | 8b63d77758f20f688f40fce82c6210d22e104da7 | /Project challanges/PROTO/Assistant/Test/Audio bestand naar tekst/assistant.py | db8395ca024a5d3152c9212486ac55cfb012e4a0 | []
| no_license | rouwens/S2-Applicatie | effa50d959729a3ddd6259e71be2229f46dafe69 | d5a412b7019451a18f3074c18bd5a879271a5fb5 | refs/heads/main | 2023-05-05T15:56:09.200904 | 2021-05-24T14:22:21 | 2021-05-24T14:22:21 | 370,379,023 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 232 | py | import speech_recognition as sr
r = sr.Recognizer()
#r.recognize_google()
testaudio = sr.AudioFile('welcome.wav')
with testaudio as source:
audio = r.record(source)
type(audio)
output = r.recognize_google(audio)
print (output) | [
"[email protected]"
]
| |
6bf30575f24d2e0b2e63132edf72de8253947be6 | c0df30b792e665cafbfe620a9b12e3a3b1969b08 | /vector2.py | ea09060361b342d88cf9e91e62276b97af1d302f | []
| no_license | mffigueroa/BattleshipRL | 16f617638599781fe8f8ab54be252ac231eeaef3 | 1d5363b4f028ef3adcd02a2842b0554ddf9cf648 | refs/heads/master | 2020-05-02T18:51:48.845605 | 2019-03-28T02:24:40 | 2019-03-28T02:24:40 | 178,141,940 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 748 | py | from operator import itemgetter
class Vector2(tuple):
__slots__ = []
def __new__(cls, x, y):
return tuple.__new__(cls, (x, y))
x = property(itemgetter(0))
y = property(itemgetter(1))
def __add__(self, other):
return Vector2(self.x + other[0], self.y + other[1])
def __sub__(self, other):
return Vector2(self.x - other[0], self.y - other[1])
def __mul__(self, other):
return Vector2(self.x * other, self.y * other)
def __iadd__(self, other):
self.x += other[0]
self.y += other[1]
def __isub__(self, other):
self.x -= other[0]
self.y -= other[1]
def __imul__(self, other):
self.x *= other
self.y *= other
def __str__(self):
return '({}, {})'.format(self.x, self.y)
| [
"[email protected]"
]
| |
4e55a3b8932491e1702cac0fb0038ccbd6ba129d | 9e386edf894d2c79070603df95137b53e09fa63a | /packetToClick/initPacket.py | df7240fc0653b18488aeb90d932be0503a9b6d14 | []
| no_license | ecks/click2warp | d921829dba12957e6e89a4ab151a62582695a76b | 7f89842473e99890022151f6e68a0df2bc8b7344 | refs/heads/master | 2020-04-01T12:57:05.350987 | 2009-05-13T22:20:51 | 2009-05-13T22:20:51 | 33,202,759 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 929 | py | import asyncore
import socket, time
class PacketToClick(asyncore.dispatcher):
def __init__(self, host, port=7777):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((host, port))
self.buffer = "a1"
self.buffer = self.buffer.decode("hex")
def writable(self):
return (len(self.buffer) > 0)
def handle_write(self):
sent = self.send(self.buffer)
self.buffer = self.buffer[sent:]
if len(self.buffer) == 0:
self.buffer = raw_input("Type in your packet: ")
self.buffer = self.buffer.decode("hex")
print self.buffer
def handle_connect(self):
pass # connection succeeded
def handle_expt(self):
self.close() # connection failed, shutdown
def handle_read(self):
print self.recv(8192)
def handle_close(self):
self.close()
request = PacketToClick("localhost")
asyncore.loop()
| [
"hristo.s.asenov@8bd78f8e-2ba5-11de-9b0f-33ff132f608d"
]
| hristo.s.asenov@8bd78f8e-2ba5-11de-9b0f-33ff132f608d |
761cee9bc33bc3cdd7d2e32c4faecdbf2ed7481f | bab76d8cf312ee3eae66472b6abd119903e17e8e | /CountAndSay.py | 13420321dce191e20923da4c08ead73e60c68669 | []
| no_license | lixuanhong/LeetCode | 91131825d5eca144a46abe82a2ef04ea1f3ff025 | 48d436701840f8c162829cb101ecde444def2307 | refs/heads/master | 2020-04-05T02:54:52.473259 | 2018-11-07T05:31:30 | 2018-11-07T05:31:30 | 156,494,213 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,485 | py | """
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"
"""
#题目大意:
#n=1 返回1
#n=2由于n=1的结果为1,有1个1,所以返回11
#n=3由于n=2结果为11,有2个1,返回21
#n=4由于n=3结果为21,有1个2和1个1,所以返回1211
#给定n,以此类推
class Solution(object):
def countAndSay(self, n):
def count(s):
res = ""
count = 1
for idx, value in enumerate(s):
if idx < len(s) - 1 and s[idx] != s[idx+1]: #因为要从第一个元素开始,所以比较idx和idx+1;要判断idx < len(s) - 1
res += str(count) + value
count = 1
elif idx < len(s) - 1:
count += 1
res += str(count) + value #对最后一个元素操作
return res
s = "1"
for i in range(1, n):
s = count(s) #初始化s = "1", 所以循环n-1次就可以得到结果
return s
obj = Solution()
print(obj.countAndSay(6)) #312211
| [
"[email protected]"
]
| |
5dc88cb58f283310fa7eee6f9c3f583230e5d0c5 | 4554a28c6c9ef57ed3f75f36e47f211d1336266f | /engine/eventmanager/eventmanager.py | d8a97a101b02a71bbad93dbcab905d145432c5b0 | []
| no_license | jnethery/Platformer | 3a46955b5a63b4190e03c3bcb1eb1ffcadb706bb | 6d8ce9d1e07fcd7cceaa76c58679967214052f30 | refs/heads/master | 2020-06-01T04:36:17.738214 | 2014-06-22T02:05:38 | 2014-06-22T02:05:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 889 | py | __author__ = 'josiah'
import pygame
import keyboardmanager
from engine.editor import editor
def run_event_processes():
events = pygame.event.get()
keydown_events = []
for event in events:
if event.type is pygame.KEYDOWN:
keydown_events.append(event)
keyboardmanager.run_keyboard_processes(keydown_events)
def run_editor_event_processes():
events = pygame.event.get()
keydown_events = []
for event in events:
if event.type is pygame.KEYDOWN:
keydown_events.append(event)
keyboardmanager.run_editor_keyboard_processes(keydown_events)
# Mouse stuff
mouse_pos = pygame.mouse.get_pos()
mouse_pressed = pygame.mouse.get_pressed()
editor.show_editor_cursor(mouse_pos)
if mouse_pressed[0] == 1:
editor.add_object(mouse_pos)
if mouse_pressed[2] == 1:
editor.delete_object(mouse_pos)
| [
"[email protected]"
]
| |
68e328c9648ea200735877f178284df1e80ab990 | 1fb76677ceb77a0f6782d387e8057565f57a82cc | /colecoes-listas-vetores.py | cc7e1e31ec4e946ea634ceb30f329bc25155accc | []
| no_license | eduruiz333/python | 7c88d369eaf3ddb4d7802e67969bba0eda62f14e | 500efa1e4c9483ed1fe5ea568d3dee3abbcf61ee | refs/heads/master | 2020-02-29T14:40:17.043131 | 2017-08-28T12:29:04 | 2017-08-28T12:29:04 | 89,487,085 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 609 | py | """
lista_qualquer = ['Aqui é um texto, bla bla bla', 122, -58.0, 'E']
lista_qualquer[3] = 'X'
lista_qualquer.append('Mais um item inserido')
print(lista_qualquer[3])
print(len(lista_qualquer))
print(type(lista_qualquer[0]))
print(type(lista_qualquer[2]))
"""
def ordena_numeros():
lista = []
print('Digite números inteiros começando com 0 (ZERO), ex: 010, 0145, etc, e digite 0 para finalizar', end='\n\n')
entrada = int(input('Digite aqui: '))
while entrada != 0:
lista.append(entrada)
entrada = int(input('Digite aqui: '))
return print(lista)
ordena_numeros()
| [
"[email protected]"
]
| |
550f5009ce1e9ff9ab80bfc92868db0fb181ce46 | 0549b7bfba799c95dc9232c49569d690b2c3b536 | /src/user_info/consumables/enums.py | 1f8b6bb4da10e0c2d466498811a41009f4159541 | []
| no_license | ilof2/ELiquid | 4f74e37469366a772dfcc3dbabb77aac2b3782f8 | 675c278030c826c91bc258ef22b1fad971ec6595 | refs/heads/master | 2023-04-22T15:37:37.099888 | 2021-05-09T17:29:42 | 2021-05-09T17:29:42 | 362,571,045 | 1 | 0 | null | 2021-05-09T17:24:40 | 2021-04-28T18:34:42 | Python | UTF-8 | Python | false | false | 76 | py | from enum import Enum
class FlavorType(Enum):
VG = "VG"
PG = "PG"
| [
"[email protected]"
]
| |
da7735dd9f12766395639c3be0898efd1916fa6c | d1dabd032696e16c063812ffb5d28f0c29585faf | /venv/Scripts/pip3.8-script.py | 366e18d8a8118257c8c8ed61a7c61d5cd5a3bf5c | []
| no_license | sashamerchuk/algo_lab_2 | a7f9df88a518f3325f806352720ddc10d9c93093 | 9fb9af05872de6669ce2ebf51962be6db89c8e8a | refs/heads/master | 2020-08-23T11:26:59.710387 | 2019-10-21T21:56:12 | 2019-10-21T21:56:12 | 216,605,840 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 411 | py | #!C:\Users\User\Desktop\algo_lab_2\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip3.8'
__requires__ = 'pip==19.0.3'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==19.0.3', 'console_scripts', 'pip3.8')()
)
| [
"[email protected]"
]
| |
e5bbcfc9133153620d7c5230df6080405c903b22 | 9450abba5b19a2cadd4118b709cf11786f72623d | /largerhhdf5.py | 12eb634e4152163bcc5493b35425d60ea8bea269 | []
| no_license | Askjensen/keras-LSTM | f21b7a1e10d66e6dc732e78e2b0a9dbaf6d74879 | b8eeaf085dd752e8f48dbdb0d170cb32471d3fed | refs/heads/master | 2021-05-07T05:05:20.789557 | 2017-11-20T13:43:46 | 2017-11-20T13:43:46 | 111,415,247 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,942 | py | # Larger LSTM Network to Generate Text for Alice in Wonderland
import numpy
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint
from keras.utils import np_utils
# load ascii text and covert to lowercase
filename = "wonderland.txt"
raw_text = open(filename).read()
raw_text = raw_text.lower()
# create mapping of unique chars to integers, and a reverse mapping
chars = sorted(list(set(raw_text)))
char_to_int = dict((c, i) for i, c in enumerate(chars))
# summarize the loaded data
n_chars = len(raw_text)
n_vocab = len(chars)
print "Total Characters: ", n_chars
print "Total Vocab: ", n_vocab
# prepare the dataset of input to output pairs encoded as integers - ask changed this from 100
seq_length = 50
dataX = []
dataY = []
for i in range(0, n_chars - seq_length, 1):
seq_in = raw_text[i:i + seq_length]
seq_out = raw_text[i + seq_length]
dataX.append([char_to_int[char] for char in seq_in])
dataY.append(char_to_int[seq_out])
n_patterns = len(dataX)
print "Total Patterns: ", n_patterns
# reshape X to be [samples, time steps, features]
X = numpy.reshape(dataX, (n_patterns, seq_length, 1))
# normalize
X = X / float(n_vocab)
# one hot encode the output variable
y = np_utils.to_categorical(dataY)
# define the LSTM model
model = Sequential()
model.add(LSTM(256, input_shape=(X.shape[1], X.shape[2]), return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(256))
model.add(Dropout(0.2))
model.add(Dense(y.shape[1], activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam')
# define the checkpoint
filepath="weights-improvement-{epoch:02d}-{loss:.4f}-bigger.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')
callbacks_list = [checkpoint]
# fit the model
model.fit(X, y, nb_epoch=50, batch_size=64, callbacks=callbacks_list) | [
"[email protected]"
]
| |
b52e256f0a8a9c2d165f8a149cddf88616e8b42f | a4b9db38e6d9a6b18adda06c7dded17ae8a3386a | /Trie.py | 46c20e428351dcc20ee32a66d61a9c477f72f008 | []
| no_license | TeoWeber/trabalhoCPD | 4d2c0f62917c84ee7331bfa376f02a89ac6d541b | 9504d86e15f2753e330dde0202e615641445dff2 | refs/heads/master | 2020-04-09T01:42:02.424916 | 2018-12-03T02:50:30 | 2018-12-03T02:50:30 | 159,913,868 | 0 | 0 | null | 2018-12-01T05:54:54 | 2018-12-01T05:54:54 | null | UTF-8 | Python | false | false | 1,815 | py | import pickle
class Trie():
# Construtor
def __init__(self, char='RAIZ', value=-1, level=0):
self.id = id
self.char = char
self.value = value
self.children = {}
self.level = level
def __str__(self):
s = "_"*self.level + self.char + " >>> " + str(self.value)
for char in sorted(self.children):
s += "\n" + str(self.children[char])
return s
def insereTrie(raiz, pokemon, n_pok):
node = raiz
lastId = None
# Procura um pedaço ja existente
for id, char in enumerate(pokemon):
if char in node.children:
node = node.children[char]
else:
lastId = id
break
# Nao encontrou o nodo necessario, entao preenche o resto da palavra
if lastId != None:
for id, char in enumerate(pokemon[lastId:-1]):
node.children[char] = Trie(char, -1, lastId+id)
node = node.children[char]
node.children[pokemon[-1]] = Trie(pokemon[-1], n_pok, len(pokemon)-1)
else:
node.value = n_pok
def buscaTrie(raiz, pokemon):
node = raiz
achou = True
for id, char in enumerate(pokemon):
if char in node.children:
node = node.children[char]
else:
achou = False
break
if achou:
return node.value
else:
print("Elemento inexistente")
return -1
def runTrie(list_objs_pokemon):
try:
with open('trie.data', 'rb') as file:
raiz = pickle.load(file)
file.close()
except:
raiz = Trie()
for i in range(len(list_objs_pokemon)): # Cria uma Trie
insereTrie(raiz, list_objs_pokemon[i].name.strip(), list_objs_pokemon[i].id)
with open('trie.data', 'wb') as file:
pickle.dump(raiz, file)
file.close()
name = input("Informe um nome de pokemon: ")
id = buscaTrie(raiz, name.lower())
if id == -1:
print("Erro!")
else:
print(list_objs_pokemon[id - 1])
return raiz
| [
"[email protected]"
]
| |
e41f37fe6a45d787c1021cb5256d1689e960cb4c | 2b343d1bcad14a03bf45902881cc7a2490d4af0e | /src/load.py | a40d28e946abc0fbd5d5a37bab32db175173f7ae | []
| no_license | dslaw/fatal-accidents | 3f0e2f23e94bb7ac98fad964f3908c5fbf9ff26d | fd4047850faf58f42cb6f43bd44ee131aed3b9c2 | refs/heads/master | 2023-02-13T03:16:36.954254 | 2021-01-16T16:48:48 | 2021-01-16T16:51:33 | 273,564,419 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,524 | py | """Load to staging."""
from datetime import datetime, timezone
from io import StringIO
from pathlib import Path
from psycopg2 import sql
from typing import Dict, Iterable, List, NamedTuple, Tuple
from uuid import UUID
from zipfile import ZipFile
import csv
from src import data_mapping
from src.common import Connectable, connect
from src.fetch import make_zipfile
Record = Dict[str, str]
class Metadata(NamedTuple):
etl_run_id: UUID
etl_year: int
etl_loaded_at: datetime
@classmethod
def create(cls, run_id: UUID, year: int) -> "Metadata":
loaded_at = datetime.utcnow().astimezone(timezone.utc)
return cls(run_id, year, loaded_at)
STAGING_SCHEMA = "staging"
def read_data(table: str, year: int) -> str:
input_file = make_zipfile(year)
with ZipFile(input_file, "r") as zf:
# There's at least one file for one year that has the
# suffix lowercased, while others are uppercased, so
# we build a case-insensitive map to simplify.
names = {Path(name).stem.lower(): name for name in zf.namelist()}
filename = names[table.lower()]
data = zf.read(filename)
return data.decode()
def deserialize(data: str) -> Iterable[Record]:
with StringIO(data) as buffer:
reader = csv.DictReader(buffer)
for record in reader:
yield record
return
def make_row(record: Record, columns: List[str], metadata: Metadata) -> Tuple:
row = tuple(record.get(column) for column in columns)
return row + metadata
def delete_partition(conn: Connectable, dst_table: sql.Identifier, year: int) -> None:
stmt = sql.SQL("delete from {} where etl_year = %(year)s").format(dst_table)
with conn.cursor() as cursor:
cursor.execute(stmt, {"year": year})
return
def load_table_partition(conn: Connectable, table: str, year: int, run_id: UUID) -> None:
try:
dst_table = data_mapping.tables[table]
except KeyError:
raise ValueError(f"Unknown table: {table}")
qualified_table = sql.Identifier(STAGING_SCHEMA, dst_table)
metadata = Metadata.create(run_id, year)
try:
data = read_data(table, year)
except KeyError:
# Table is registered as known, but doesn't exist for
# this year.
return
# Prepare data for bulk load.
records = deserialize(data)
columns = data_mapping.table_columns[dst_table]
cased_columns = [column.upper() for column in columns]
rows = map(lambda record: make_row(record, cased_columns, metadata), records)
dst_columns = columns + list(metadata._fields)
delimiter = ","
buffer = StringIO()
writer = csv.writer(buffer, delimiter=delimiter)
writer.writerows(rows)
buffer.seek(0)
# Insert or replace partition.
with conn, conn.cursor() as cursor:
delete_partition(conn, qualified_table, year)
cursor.copy_from(
buffer,
qualified_table.as_string(conn),
sep=delimiter,
null="",
columns=dst_columns
)
return
def load_partition(year: int, run_id: UUID) -> None:
conn = connect()
# XXX: Not atomic - tables may have mixed failure/success.
for table in data_mapping.tables:
load_table_partition(conn, table, year, run_id)
# Ensure table statistics are updated, in case autovacuum doesn't run
# before the next read.
conn.autocommit = True
with conn.cursor() as cursor:
cursor.execute("vacuum analyze")
return
| [
"[email protected]"
]
| |
894f3558e7c71d3dddc26e67f412ce6089f639f2 | 4da640cbf45783282c3e382331013eecb5553492 | /lits.py | 3a4e748a40878bc3c7453b93d1b0ef73eec3fd0b | []
| no_license | kuzeydev/mbv-python-projects | 70f455c5e33e9bfa3feddbcffb2ee776fa477706 | a166f3f6f24c33da66f474c886fa7840ec4fdc97 | refs/heads/main | 2023-07-05T03:17:55.021821 | 2021-08-31T19:25:49 | 2021-08-31T19:25:49 | 401,819,818 | 0 | 0 | null | 2021-08-31T19:25:06 | 2021-08-31T19:25:05 | null | UTF-8 | Python | false | false | 132 | py | names = ['mbv' , 'kbv' , 'bob', 'rick']
print(names [1])
print(names[-1])
names[1] = 'bugra'
print(names)
print(names[0:3])
| [
"[email protected]"
]
| |
f36bac8cb3c65b13ba04323591cf99f819b50868 | 431c8beacf2b1a54982bf2d06b3dc5cebba87c69 | /buttontest.py | 1b228e5bfeb4437a78e6f55ab31ba9c5574807e5 | [
"MIT"
]
| permissive | watrt/micropython-tft-gui | 290c27ba810943033d26214b7f9ec38129fa774e | 1ae9eafccb7084093eb80354e9e30d1f02367221 | refs/heads/master | 2020-12-10T06:49:51.299653 | 2019-05-25T07:30:57 | 2019-05-25T07:30:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,508 | py | # buttontest.py Test/demo of pushbutton classes for Pybboard TFT GUI
# The MIT License (MIT)
#
# Copyright (c) 2016 Peter Hinch
#
# 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 constants import *
from ugui import Button, ButtonList, RadioButtons, Checkbox, Label, Screen
import font14
import font10
from tft_local import setup
class ButtonScreen(Screen):
def __init__(self):
super().__init__()
# These tables contain args that differ between members of a set of related buttons
table = [
{'fgcolor' : GREEN, 'text' : 'Yes', 'args' : ('Oui', 2), 'fontcolor' : (0, 0, 0)},
{'fgcolor' : RED, 'text' : 'No', 'args' : ('Non', 2)},
{'fgcolor' : BLUE, 'text' : '???', 'args' : ('Que?', 2), 'fill': False},
{'fgcolor' : GREY, 'text' : 'Rats', 'args' : ('Rats', 2), 'shape' : CLIPPED_RECT,},
]
# Highlight buttons: only tabulate data that varies
table_highlight = [
{'text' : 'P', 'args' : ('p', 2)},
{'text' : 'Q', 'args' : ('q', 2)},
{'text' : 'R', 'args' : ('r', 2)},
{'text' : 'S', 'args' : ('s', 2)},
]
# A Buttonset with two entries
table_buttonset = [
{'fgcolor' : GREEN, 'shape' : CLIPPED_RECT, 'text' : 'Start', 'args' : ('Live', 2)},
{'fgcolor' : RED, 'shape' : CLIPPED_RECT, 'text' : 'Stop', 'args' : ('Die', 2)},
]
table_radiobuttons = [
{'text' : '1', 'args' : ('1', 3)},
{'text' : '2', 'args' : ('2', 3)},
{'text' : '3', 'args' : ('3', 3)},
{'text' : '4', 'args' : ('4', 3)},
]
labels = { 'width' : 70,
'fontcolor' : WHITE,
'border' : 2,
'fgcolor' : RED,
'bgcolor' : (0, 40, 0),
'font' : font14,
}
# Uncomment this line to see 'skeleton' style greying-out:
# Screen.tft.grey_color()
# Labels
self.lstlbl = []
for n in range(5):
self.lstlbl.append(Label((390, 40 * n), **labels))
# Button assortment
x = 0
for t in table:
Button((x, 0), font = font14, callback = self.callback, **t)
x += 70
# Highlighting buttons
x = 0
for t in table_highlight:
Button((x, 60), fgcolor = GREY, fontcolor = BLACK, litcolor = WHITE,
font = font14, callback = self.callback, **t)
x += 70
# Start/Stop toggle
self.bs = ButtonList(self.callback)
self.bs0 = None
for t in table_buttonset: # Buttons overlay each other at same location
button = self.bs.add_button((0, 240), font = font14, fontcolor = BLACK, height = 30, **t)
if self.bs0 is None: # Save for reset button callback
self.bs0 = button
# Radio buttons
x = 0
self.rb = RadioButtons(BLUE, self.callback) # color of selected button
self.rb0 = None
for t in table_radiobuttons:
button = self.rb.add_button((x, 140), font = font14, fontcolor = WHITE,
fgcolor = (0, 0, 90), height = 40, width = 40, **t)
if self.rb0 is None: # Save for reset button callback
self.rb0 = button
x += 60
# Checkbox
self.cb1 = Checkbox((340, 0), callback = self.cbcb, args = (0,))
self.cb2 = Checkbox((340, 40), fillcolor = RED, callback = self.cbcb, args = (1,))
# Reset button
self.lbl_reset = Label((200, 220), font = font10, value = 'Reset also responds to long press')
self.btn_reset = Button((300, 240), font = font14, height = 30, width = 80,
fgcolor = BLUE, shape = RECTANGLE, text = 'Reset', fill = True,
callback = self.cbreset, args = (4,), onrelease = False,
lp_callback = self.callback, lp_args = ('long', 4))
# Quit
self.btn_quit = Button((390, 240), font = font14, height = 30, width = 80,
fgcolor = RED, shape = RECTANGLE, text = 'Quit',
callback = self.quit)
# Enable/Disable toggle
self.bs_en = ButtonList(self.cb_en_dis)
self.tup_en_dis = (self.cb1, self.cb2, self.rb, self.bs) # Items affected by enable/disable button
self.bs_en.add_button((200, 240), font = font14, fontcolor = BLACK, height = 30, width = 90,
fgcolor = GREEN, shape = RECTANGLE, text = 'Disable', args = (True,))
self.bs_en.add_button((200, 240), font = font14, fontcolor = BLACK, height = 30, width = 90,
fgcolor = RED, shape = RECTANGLE, text = 'Enable', args = (False,))
def callback(self, button, arg, idx_label):
self.lstlbl[idx_label].value(arg)
def quit(self, button):
Screen.shutdown()
def cbcb(self, checkbox, idx_label):
if checkbox.value():
self.lstlbl[idx_label].value('True')
else:
self.lstlbl[idx_label].value('False')
def cbreset(self, button, idx_label):
self.cb1.value(False)
self.cb2.value(False)
self.bs.value(self.bs0)
self.rb.value(self.rb0)
self.lstlbl[idx_label].value('Short')
def cb_en_dis(self, button, disable):
for item in self.tup_en_dis:
item.greyed_out(disable)
def test():
print('Testing TFT...')
setup()
Screen.change(ButtonScreen)
test()
| [
"[email protected]"
]
| |
386c4a0c4a4eb7b1ac27de8017edc894986c9e55 | 301027bc251f9b02e10f2edefe5df7a7945839d9 | /CeldasLibres/celdas_libres/parqueaderos/urls.py | 38f115b37aa12208635a7eaad75e7b9ba062186b | []
| no_license | juczapatama/CeldasLibres | c4fb7d5c6d50167dbfacf376e833836fd0052f8b | 4578db6e880cc42289d6793518b8ba065485a21e | refs/heads/master | 2020-06-14T23:43:20.533904 | 2019-07-04T02:32:56 | 2019-07-04T02:32:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 651 | py | from django.urls import path
from .views import CrearTarifa, VerTarifas, CrearEntradaVehiculo, VerIngresados, ModificarTarifa, EliminarTarifa
urlpatterns = [
path('crear_tarifa/', CrearTarifa.as_view(), name='crear_tarifa'),
path('tarifas/', VerTarifas.as_view(), name='tarifas'),
path('ingresar-vehiculo/', CrearEntradaVehiculo.as_view(), name='ingresar-vehiculo'),
path('vehiculos-ingresados/', VerIngresados.as_view(), name='vehiculos-ingresados'),
path('modificar-tarifa/<int:pk>', ModificarTarifa.as_view(), name='modificar-tarifa'),
path('eliminar-tarifa/<int:pk>', EliminarTarifa.as_view(), name='eliminar-tarifa'),
]
| [
"[email protected]"
]
| |
bc1348aa7e3c66f0d24bdec742c4d682ff052a4a | 6a9d9ed9ee3639e20f109957643666f87bfff9a7 | /drinkmaker/recepies/models.py | 22343fe3633abc482fd45b6512765581213c0d4b | []
| no_license | thegreatdrinkmaker/drinkmaker | da06a30b7eda548014003db510a3ef3744f3e6c0 | 8e3733b1e5322f399eab951f678e3286afb94833 | refs/heads/master | 2021-01-19T22:13:21.987444 | 2017-04-19T21:16:58 | 2017-04-19T21:16:58 | 88,769,354 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,003 | py | from django.db import models
from rawingredients.models import Ingredient
class MeasurementSize(models.Model):
name = models.CharField(max_length = 256, blank = False, null = False)
unit = models.CharField(max_length = 10, blank = True, null = True)
description = models.TextField(max_length = 500, default = "", blank = True, null = True)
def __str__(self):
if self.unit is None or self.unit is "":
return(self.name)
else:
return(self.unit)
# Create your models here.
class Recepie(models.Model):
name = models.CharField(max_length = 256, blank = False, null = False)
ingredients = models.ManyToManyField(Ingredient, through = "IngredientList", through_fields= ('recepie', 'ingredient'))
description = models.TextField(max_length = 500, default = "", blank = True, null = True)
post_drink_instruction = models.TextField(max_length = 500, blank = True, null = True) #save what to do after poring, drink, or what garnish to add, etc
#Ratings for this recepie
number_of_ratings_global = models.IntegerField(default = 0)
average_rating_global = models.IntegerField(default = 0) #this is the number of starts out of 10
number_of_ratings_local = models.IntegerField(default = 0)
average_rating_local = models.IntegerField(default = 0)
#number of times consumed
number_of_times_consumed_local = models.IntegerField(default = 0)
number_of_times_consumed_global = models.IntegerField(default = 0)
comments = models.CharField(max_length = 256, blank = True, null = True, default = "No Comments") #local comments for the user, this comment will be added to the server as a cumulative comment
class IngredientList(models.Model):
recepie = models.ForeignKey(Recepie, on_delete = models.CASCADE)
ingredient = models.ForeignKey(Ingredient, on_delete = models.CASCADE)
quantity = models.DecimalField(max_digits = 8, decimal_places=3)
quantity_size = models.ForeignKey(MeasurementSize)
| [
"[email protected]"
]
| |
9f22581ff365fe95c0f65d9ca24246c7fbe4324b | fa271dab310985513171512b01863a9722aea797 | /강의 자료/02-알고리즘/07~08-두 포인터/문제별 코드/2559-수열/solution.py | 9511d30e637710061424ea5a513b9fa7431277fb | [
"MIT"
]
| permissive | norimsu/FastCampus | f2ad944f0c9ba4ace0813d31dddc75a40e8f2d5f | f6173a997f71a0335756c4407baced1aca4bb316 | refs/heads/main | 2023-06-12T05:18:26.410875 | 2021-07-03T02:37:18 | 2021-07-03T02:37:18 | 382,628,475 | 1 | 0 | MIT | 2021-07-03T13:57:49 | 2021-07-03T13:57:48 | null | UTF-8 | Python | false | false | 327 | py | import sys
si = sys.stdin.readline
n, S = list(map(int, si().split()))
a = list(map(int, si().split()))
R, sum, ans = -1, 0, n + 1
for L in range(n):
while R + 1 < n and sum < S:
R += 1
sum += a[R]
if sum >= S:
ans = min(ans, R - L + 1)
sum -= a[L]
if ans == n + 1: ans = 0
print(ans) | [
"[email protected]"
]
| |
efe854c65e8348927573faaf27d384468a2f32dc | a90d490bf8a9df04334746acbafa5f8dad20c677 | /recipes/migrations/0009_auto_20160410_2021.py | 6dc28757abd45521c92ee402fe3f6ff6cb9d9162 | [
"MIT"
]
| permissive | vanatteveldt/luctor | 8e8ffc20c05cc20a241c677bbe5400a5d71f2882 | 9871fa7afa85f36353b3f4740f73ae3e36d68643 | refs/heads/master | 2023-03-15T20:05:29.220407 | 2023-03-08T22:06:53 | 2023-03-08T22:06:53 | 14,639,858 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,307 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-04-10 20:21
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('recipes', '0008_auto_20160405_0044'),
]
operations = [
migrations.CreateModel(
name='Recipe',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('ingredients', models.TextField()),
('instructions', models.TextField()),
],
),
migrations.AlterField(
model_name='lesson',
name='parsed',
field=models.TextField(help_text="Pas hier de opdeling van de kookles in recepten aan. De titel van elk recept wordt aangegeven met ## titel, en ingredienten met | ingredient |. Als je klaar bent klik dan op 'save and continue editing' en op 'view on site'", null=True),
),
migrations.AddField(
model_name='recipe',
name='lesson',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='recipes.Lesson'),
),
]
| [
"[email protected]"
]
| |
bd419d0a197a5e5a99a370e45cdb53a276ac5507 | e1a846a215ca119f47216d1d2121ac03fff4d493 | /All_Contents/Cluster_EM/kmeans.py | b43243eda18e51604eea12d394b5d992f7c4c586 | []
| no_license | wqainlpdl/ML_with_Python3 | f5af1437f62a7e853c23ac0f22da6c8b702f61a7 | 5e1987e36d6a58faf7b653e9aafa2ff2724b2580 | refs/heads/master | 2020-04-05T21:42:20.609733 | 2019-01-02T16:15:04 | 2019-01-02T16:15:04 | 157,230,062 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,649 | py | from sklearn import cluster
from sklearn.metrics import adjusted_rand_score
import matplotlib.pyplot as plt
def test_Kmeans(*data):
x,labels_true = data
clst = cluster.KMeans()
clst.fit(x)
predicted_labels = clst.predict(x)
print("ARI: %s" % adjusted_rand_score(labels_true, predicted_labels))
print("Sum center distance %s" % (clst.inertia_,))
def test_Kmeans_nclusters(*data):
"""
测试KMeans的聚类结果随参数n_clusters的参数的影响
在这里,主要分别研究ARI和所有样本距离各簇中心的距离值和随簇的个数
的变化情况
"""
x, labels_true = data
nums = range(1, 50)
ARIs = []
Distances = []
for num in nums:
clst = cluster.KMeans(n_clusters = num)
clst.fit(x)
predicted_labels = clst.predict(x)
ARIs.append(adjusted_rand_score(labels_true, predicted_labels))
Distances.append(clst.inertia_)
# 绘图
fig = plt.figure()
ax = fig.add_subplot(1, 2, 1)
ax.plot(nums, ARIs, marker = "+")
ax.set_xlabel("n_clusters")
ax.set_ylabel("ARI")
ax = fig.add_subplot(1, 2, 2)
ax.plot(nums, Distances, marker = "o")
ax.set_xlabel("n_cluster")
ax.set_ylabel("intertia_")
fig.suptitle("KMeans")
plt.show()
def test_KMeans_n_init(*data):
"""
该函数考察KMeans算法运行的次数和选择的初始中心向量策略的影响
"""
x, labels_true = data
nums = range(1, 50)
# 绘图
fig = plt.figure()
ARIs_k = []
Distances_k = []
ARIs_r = []
Distances_r = []
for num in nums:
clst = cluster.KMeans(n_init = num, init = "k-means++")
clst.fit(x)
predicted_labels = clst.predict(x)
ARIs_k.append(adjusted_rand_score(labels_true, predicted_labels))
Distances_k.append(clst.inertia_)
clst = cluster.KMeans(n_init = num, init = "random")
clst.fit(x)
predicted_labels = clst.predict(x)
ARIs_r.append(adjusted_rand_score(labels_true, predicted_labels))
Distances_r.append(clst.inertia_)
ax = fig.add_subplot(1, 2, 1)
ax.plot(nums, ARIs_k, marker = "+", label = "k-means++")
ax.plot(nums, ARIs_r, marker = "+", label = "random")
ax.set_xlabel("n_init")
ax.set_ylabel("ARI")
ax.set_ylim(0, 1)
ax.legend(loc = "best")
ax = fig.add_subplot(1, 2, 2)
ax.plot(nums, Distances_k, marker = "o", label = "k-means++")
ax.plot(nums, Distances_r, marker = "o", label = "random")
ax.set_xlabel("n_init")
ax.set_ylabel("inertia_")
ax.legend(loc = "best")
fig.suptitle("KMeans")
plt.show()
| [
"[email protected]"
]
| |
8cdb72d897874d4be0eec570f41c00bf4414a993 | 329a5845bda92818c9f54d6eec84b1c928ca0b7d | /restaurant/bestellung/migrations/0001_initial.py | 5c715fb27943d3f7d06562f969951a097bf7dd26 | []
| no_license | MohamdAbdelgayed/RestaurantProjekt-with-Django | 21bdd079431adcb51b1371d39ad6dc8721912404 | a59f6db80ba208088d9a8cdab56d6c1fe3cf45ab | refs/heads/main | 2023-07-13T05:06:18.235469 | 2021-09-05T21:41:05 | 2021-09-05T21:41:05 | 400,842,265 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 719 | py | # Generated by Django 3.2.6 on 2021-08-22 18:02
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Product',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('price', models.FloatField()),
('piece', models.IntegerField()),
('img_path', models.CharField(max_length=255)),
('description', models.CharField(max_length=400)),
],
),
]
| [
"[email protected]"
]
| |
c3ccf4e0c76e93b359190807ae0de1c11b195805 | 8dfda6368e8f566ac2b727980ad4278a43326e60 | /fc.py | ed4768fc7a6fe70bd3dd91084c5eee29d1abb4cd | []
| no_license | Stupidd-Pumpkin/Python-Projects | d5d10652034f02b41e8d7328310630adc55f81a7 | 0b88daed705504d455463690d209509ed8215b9c | refs/heads/main | 2023-03-26T10:45:03.655376 | 2021-03-27T07:13:09 | 2021-03-27T07:13:09 | 352,001,755 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,183 | py |
#file_name="dict.txt"
#file_list=[]
#fin = open(file_name)
#for eachline in fin:
# file_list.append(eachline.strip())
#
#print file_list
#file_set=set(file_list)
import string
#from difflib import *
f=open('dict.txt','r')
open('lists.txt','w').close()
q=open('lists.txt','a')
open('back.txt','w').close()
z=open('back.txt','a')
word_set = set(word.strip().upper() for word in f)
start_word="NOSE"
end_word="CHIN"
maxsize=10
length=len(start_word)
alphabet_list=list(string.ascii_uppercase)
'''
list1=[]
for i in range(0,4):
for a in alphabet_list:
temp=list(start_word)
temp[i]=a
st="".join(temp)
if(st in word_set):
if st != start_word:
list1.append(st)
print ( list1,'\n',file=q)
print ("\n")
list_set=set(list1)
'''
count=0
parentlist=[]
parentlist.append([start_word])
for i in range (1,maxsize):
parentlist.append([])
for st1 in parentlist[i-1]:
for a in alphabet_list:
for j in range(0,length):
temp=list(st1)
temp[j]=a
st="".join(temp)
if(st in word_set):
if(st not in parentlist[i]):
parentlist[i].append(st)
print (i,'\n\n\n\n',parentlist[i],'\n',file=q)
if(end_word in parentlist[i]) and (count ==0 ):
count=i
print (count)
count+=1
backtrack=[]
backtrack.append([end_word])
print ('\n',backtrack[0])
count+=1
for i in range (1,count):
backtrack.append([])
for st1 in backtrack[i-1]:
for a in alphabet_list:
for j in range(0,length):
temp=list(st1)
temp[j]=a
st="".join(temp)
if(st in parentlist[count-i-1]):
if(st not in backtrack[i]) and (st not in backtrack[i-1]):
backtrack[i].append(st)
print('\n',backtrack[i])
print (i,'\n\n\n\n',backtrack[i],'\n',file=z)
| [
"[email protected]"
]
| |
171f8ff483c3386ba48cab36f6dbfbfd0b5a1471 | 72ab330a358e3d85fb7d3ce29f9da3b9fb1aa6b8 | /quickbooks/objects/timeactivity.py | 459175558f4a1afa9c1e9e0294a3ead28c38c5c9 | [
"MIT"
]
| permissive | fuhrysteve/python-quickbooks | d21415c2eb0e758dece4dbdcd3890361781f9ca5 | c017355fa0e9db27001040bf45bc8c48bbd1de45 | refs/heads/master | 2021-01-21T16:04:24.393172 | 2016-01-03T17:50:50 | 2016-01-03T17:50:50 | 48,954,178 | 0 | 0 | null | 2016-01-03T17:18:51 | 2016-01-03T17:18:49 | null | UTF-8 | Python | false | false | 1,302 | py | from six import python_2_unicode_compatible
from .base import Ref, QuickbooksManagedObject, QuickbooksTransactionEntity, LinkedTxnMixin, AttachableRef
@python_2_unicode_compatible
class TimeActivity(QuickbooksManagedObject, QuickbooksTransactionEntity, LinkedTxnMixin):
"""
QBO definition: The TimeActivity entity represents a record of time worked by a vendor or employee.
"""
class_dict = {
"VendorRef": Ref,
"CustomerRef": Ref,
"DepartmentRef": Ref,
"EmployeeRef": Ref,
"ItemRef": Ref,
"ClassRef": Ref,
"AttachableRef": AttachableRef
}
qbo_object_name = "TimeActivity"
def __init__(self):
super(TimeActivity, self).__init__()
self.NameOf = ""
self.TimeZone = ""
self.TxnDate = ""
self.BillableStatus = ""
self.Taxable = False
self.HourlyRate = 0
self.Hours = 0
self.Minutes = 0
self.BreakHours = 0
self.BreakMinutes = 0
self.StartTime = ""
self.EndTime = ""
self.Description = ""
self.VendorRef = None
self.CustomerRef = None
self.DepartmentRef = None
self.EmployeeRef = None
self.ItemRef = None
self.ClassRef = None
self.AttachableRef = None | [
"[email protected]"
]
| |
82cbd2304696415df1c92ba0cedca7acc29983b8 | 98c6ea9c884152e8340605a706efefbea6170be5 | /examples/data/Assignment_6/mdlyud002/question2.py | ebdc1dede1c8a1ab523e6c9a607a685c9867f7a7 | []
| no_license | MrHamdulay/csc3-capstone | 479d659e1dcd28040e83ebd9e3374d0ccc0c6817 | 6f0fa0fa1555ceb1b0fb33f25e9694e68b6a53d2 | refs/heads/master | 2021-03-12T21:55:57.781339 | 2014-09-22T02:22:22 | 2014-09-22T02:22:22 | 22,372,174 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,270 | py | # Yudhi Moodley
# Assignment 6 - Vector Calculator
# 23/04/2014
import math
vectorA = []
vectorB = []
addition = []
dotProduct = []
normalization = []
def vector_calculator():
vector1 = input("Enter vector A:\n")
vectorA = vector1.split(' ') # splits the input
vector2 = input("Enter vector B:\n")
vectorB = vector2.split(' ') # splits the input
# addition funtion
for i in range (3):
addNum = eval(vectorA[i]) + eval(vectorB[i])
addition.append(addNum)
print("A+B = [" + str(addition[0]) + ", " + str(addition[1]) + ", " + str(addition[2]) + "]")
# calculates the funtion of the vector
for i in range (3):
multNum = eval(vectorA[i]) * eval(vectorB[i])
dotProduct.append(multNum)
product = 0
for i in range (3):
product += dotProduct[i]
print("A.B = " + str(product))
# normalizes the vector
aSum = eval(vectorA[0])**2 + eval(vectorA[1])**2 + eval(vectorA[2])**2
aRoot = ("{0:.2f}".format(math.sqrt(aSum)))
print("|A| =",aRoot)
bSum = eval(vectorB[0])**2 + eval(vectorB[1])**2 + eval(vectorB[2])**2
bRoot = ("{0:.2f}".format(math.sqrt(bSum)))
print("|B| =",bRoot)
vector_calculator() | [
"[email protected]"
]
| |
786f35f8876ad00ec0ef8dcc90fb1ffa18300fb8 | 2045faf65d972824d50fde231f5cd7ac855ca486 | /some_ideas/check_palindrome.py | aa46de6ccf904e79e3cb7dea4e1c180afb92cff5 | []
| no_license | varerysan/python_start_lessons | e87f1cbe01918a9dc91dc54fb25f7bb2ab50245b | 6a2aa3f0343017777ef30a117debf4160e8cf3a1 | refs/heads/master | 2020-04-02T15:40:10.725703 | 2019-11-17T04:01:53 | 2019-11-17T04:01:53 | 154,577,677 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 141 | py |
text = ['abc', 'aabaa', '245235', '123321']
t2 = text[::-1]
print("t2=", t2)
pal = [s for s in text if s == s[::-1] ]
print("pal=", pal) | [
"[email protected]"
]
| |
85375cf6494e037516705f9a0e24e817069008ef | 96b6fd3cc99e00b86ec3887e314f8d5fa73f3f2f | /decorator_pattern/decorator_example.py | bb9899faf48e6f0429133ca112a59cf5647621b8 | []
| no_license | tim-ts-chu/design-pattern | 296afbe4e2a9e86ef45539975c1972864d26b0f2 | d66cc836c8040fa1765c14ca3f648386049248ad | refs/heads/master | 2020-04-23T01:40:31.822933 | 2019-03-12T16:49:52 | 2019-03-12T16:49:52 | 170,820,108 | 9 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,902 | py | #!/usr/bin/python3
import decorator_module
class MochaHouseBlend(decorator_module.HouseBlend):
@decorator_module.Mocha('description')
def getDescription(self):
return super().getDescription()
@decorator_module.Mocha('cost')
def cost(self):
return super().cost()
class MilkEspresso(decorator_module.Espresso):
@decorator_module.Milk('description')
def getDescription(self):
return super().getDescription()
@decorator_module.Milk('cost')
def cost(self):
return super().cost()
class WhipSoyDecaf(decorator_module.Decaf):
@decorator_module.Whip('description')
@decorator_module.Soy('description')
def getDescription(self):
return super().getDescription()
@decorator_module.Whip('cost')
@decorator_module.Soy('cost')
def cost(self):
return super().cost()
class WhipSoyMochaDarkRoast(decorator_module.DarkRoast):
@decorator_module.Whip('description')
@decorator_module.Soy('description')
@decorator_module.Mocha('description')
def getDescription(self):
return super().getDescription()
@decorator_module.Whip('cost')
@decorator_module.Soy('cost')
@decorator_module.Mocha('cost')
def cost(self):
return super().cost()
def main():
print("Hello, decorator world!")
print("===============")
b = decorator_module.HouseBlend()
print(b.getDescription())
print(b.cost())
print("===============")
b = MochaHouseBlend()
print(b.getDescription())
print(b.cost())
print("===============")
b = MilkEspresso()
print(b.getDescription())
print(b.cost())
print("===============")
b = WhipSoyDecaf()
print(b.getDescription())
print(b.cost())
print("===============")
b = WhipSoyMochaDarkRoast()
print(b.getDescription())
print(b.cost())
if __name__ == "__main__":
main()
| [
"[email protected]"
]
| |
b212f30ce3a4c9af92e433cec3f79e72b4586b9f | c71a1053315e9277daf01f2b6d3b7b3f9cc77075 | /menu/urls.py | 7755a066a01883ca36d599c7d6927de8a072fdae | []
| no_license | ingafter60/dinner | f59bb42135d5dd8eb9a42bf665ea1dfc30e01937 | 08b4a33d899ffa45bb7f56b58cfef97703bd2083 | refs/heads/master | 2020-07-03T20:28:27.635316 | 2019-08-18T03:14:44 | 2019-08-18T03:14:44 | 202,040,200 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 207 | py | # menu urls.py
from django.urls import path
from menu import views
app_name = 'menu'
urlpatterns = [
path('', views.menuList, name='menuList'),
path('<slug:slug>', views.menuDetail, name='menuDetail'),
] | [
"[email protected]"
]
| |
ae3a3ffcb68e562877fe9d0be3b3cc68aac3c5be | f1be9bdd633f6d0f9e15d3acc8966eacc8d185dc | /3.py | 1ae242dde02875586e9bbff27a6cca8d9fb12293 | []
| no_license | soorajnair/pyt | aa89f6f9a0bffa7df41ef11c899e74d5118da07d | 82a79a351caeb68818879212b673b024726a9743 | refs/heads/master | 2021-05-02T06:37:41.729974 | 2018-07-03T15:35:07 | 2018-07-03T15:35:07 | 112,445,379 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 115 | py | #! /usr/bin/python
l=[1,1,2,3,5,8,13,21,34,55,89]
nl=[]
for i in l:
if i<5:
nl.append(i)
print nl
| [
"[email protected]"
]
| |
6f747b5fb9f472c6c4e89b6ca3610f1726436bee | a5fc521abe901fe9db46a605ec0ba71635bc308b | /managment/migrations/0001_initial.py | 059c4d114c5c4f2ebd8c9b576271218cb6f43401 | []
| no_license | revankarrajat/rms | 020b3736fb0855e547ffe7b3f91eae609cee80c7 | ed68bf427ab5612ae7f3a5308cd8075e19fc1daf | refs/heads/master | 2020-04-12T18:21:32.834786 | 2018-12-24T11:01:57 | 2018-12-24T11:01:57 | 162,676,399 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,218 | py | # Generated by Django 2.1.4 on 2018-12-14 06:29
from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0009_alter_user_last_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('is_owner', models.BooleanField(default=False)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
migrations.CreateModel(
name='owner',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('num_properties', models.IntegerField(default=0)),
('owner_name', models.CharField(max_length=30)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='property',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('description', models.TextField(default='')),
('price', models.IntegerField()),
('location', models.CharField(max_length=50)),
('num_views', models.IntegerField(default=0)),
('avg_rating', models.IntegerField(default=0)),
('owner', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='managment.owner')),
],
),
migrations.CreateModel(
name='review',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('rating', models.IntegerField(default=0)),
('comment', models.CharField(max_length=100)),
('prop_id', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='id+', to='managment.property')),
],
),
migrations.CreateModel(
name='visitor',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('profile', models.TextField()),
('pref_location', models.CharField(max_length=30)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='review',
name='visitor_id',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='id+', to='managment.visitor'),
),
]
| [
"[email protected]"
]
| |
20c349b51d5f811b2dcc8e70aab41bb19f60d17f | c515967aaeeaffc59b61a69adb300de579a0d0c1 | /main.py | e8fd20342932567d72209a85512850b036120a03 | []
| no_license | PedroCondeOfficial/Python-Piano | 4fc1fc90cf688862051327df7d841f8127b0762f | 6f03836853f97515210d9dbcba5cbdcc342fb333 | refs/heads/master | 2020-08-07T09:03:38.186750 | 2019-10-07T13:01:45 | 2019-10-07T13:01:45 | 213,383,387 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,138 | py | """
Made by Pedro E. Conde
v1.0.0
10/07/2019
"""
# Imports pygame and playsound libraries to set up window and playback functions
from playsound import playsound
import pygame, sys
import pygame.locals
# Creates class called Piano
class Piano():
# Initializing function to prepare program window
def __init__(self):
pygame.init()
bg = pygame.image.load('piano.jpg')
BLACK = (0,0,0)
HEIGHT = 167
WIDTH = 200
w = pygame.display.set_mode((WIDTH, HEIGHT), 0, 0)
pygame.mixer.init()
i = 0
while True:
w.blit(bg, (0, 0))
# Gets key press events and plays the appropriate key and displays a blip of the pressed key
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
pygame.mixer.music.load('C.wav')
pygame.mixer.music.play()
font = pygame.font.Font(None, 36)
text = font.render('C', 1, (255, 0, 0))
w.blit(text, (5, 145) )
elif event.key == pygame.K_w:
pygame.mixer.music.load('C#.wav')
pygame.mixer.music.play()
font = pygame.font.Font(None, 36)
text = font.render('C#', 1, (255, 0, 0))
w.blit(text, (10, 90))
elif event.key == pygame.K_s:
pygame.mixer.music.load('D.wav')
pygame.mixer.music.play()
font = pygame.font.Font(None, 36)
text = font.render('D', 1, (255, 0, 0))
w.blit(text, (30, 145))
elif event.key == pygame.K_e:
pygame.mixer.music.load('Eb.wav')
pygame.mixer.music.play()
font = pygame.font.Font(None, 36)
text = font.render('Eb', 1, (255, 0, 0))
w.blit(text, (50, 90))
elif event.key == pygame.K_d:
pygame.mixer.music.load('E.wav')
pygame.mixer.music.play()
font = pygame.font.Font(None, 36)
text = font.render('E', 1, (255, 0, 0))
w.blit(text, (60, 145))
elif event.key == pygame.K_f:
pygame.mixer.music.load('F.wav')
pygame.mixer.music.play()
font = pygame.font.Font(None, 36)
text = font.render('F', 1, (255, 0, 0))
w.blit(text, (95, 145))
elif event.key == pygame.K_t:
pygame.mixer.music.load('F#.wav')
pygame.mixer.music.play()
font = pygame.font.Font(None, 36)
text = font.render('F#', 1, (255, 0, 0))
w.blit(text, (100, 90))
elif event.key == pygame.K_g:
pygame.mixer.music.load('G.wav')
pygame.mixer.music.play()
font = pygame.font.Font(None, 36)
text = font.render('G', 1, (255, 0, 0))
w.blit(text, (120, 145))
elif event.key == pygame.K_y:
pygame.mixer.music.load('G#.wav')
pygame.mixer.music.play()
font = pygame.font.Font(None, 36)
text = font.render('G#', 1, (255, 0, 0))
w.blit(text, (135, 90))
elif event.key == pygame.K_h:
pygame.mixer.music.load('A.wav')
pygame.mixer.music.play()
font = pygame.font.Font(None, 36)
text = font.render('A', 1, (255, 0, 0))
w.blit(text, (145, 145))
elif event.key == pygame.K_u:
pygame.mixer.music.load('Bb.wav')
pygame.mixer.music.play()
font = pygame.font.Font(None, 36)
text = font.render('Bb', 1, (255, 0, 0))
w.blit(text, (160, 90))
elif event.key == pygame.K_j:
pygame.mixer.music.load('B.wav')
pygame.mixer.music.play()
font = pygame.font.Font(None, 36)
text = font.render('B', 1, (255, 0, 0))
w.blit(text, (180, 145))
# Creates quit function
elif event.key == pygame.K_ESCAPE:
self.i += 1
# Prevents other key events from triggering playback
else:
print("Not a valid key")
pygame.display.update()
# Calls the Piano class
piano = Piano()
| [
"[email protected]"
]
| |
c1aecb5f5ba8e76b8436c371feeb5d0732281585 | 2f7a05fe584a948d203f0236b6f139220865aabc | /plugins/extractit/icon_extractit/actions/mac_extractor/schema.py | f38e6445d4d28a79313deafb2f2c1e1d6495cd13 | [
"MIT"
]
| permissive | Kano69/insightconnect-plugins | 6671995e9c3127137f59939369ab79bdd152127d | 4dc54260470cd8a3d1cb31ae1c48ad3e8ec75194 | refs/heads/master | 2023-08-25T19:14:14.919805 | 2021-10-15T15:01:18 | 2021-10-15T15:01:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,304 | py | # GENERATED BY KOMAND SDK - DO NOT EDIT
import insightconnect_plugin_runtime
import json
class Component:
DESCRIPTION = "Extracts all MAC addresses from a string or file"
class Input:
FILE = "file"
STR = "str"
class Output:
MAC_ADDRS = "mac_addrs"
class MacExtractorInput(insightconnect_plugin_runtime.Input):
schema = json.loads("""
{
"type": "object",
"title": "Variables",
"properties": {
"file": {
"type": "string",
"title": "File",
"displayType": "bytes",
"description": "Input file as bytes",
"format": "bytes",
"order": 2
},
"str": {
"type": "string",
"title": "String",
"description": "Input string",
"order": 1
}
}
}
""")
def __init__(self):
super(self.__class__, self).__init__(self.schema)
class MacExtractorOutput(insightconnect_plugin_runtime.Output):
schema = json.loads("""
{
"type": "object",
"title": "Variables",
"properties": {
"mac_addrs": {
"type": "array",
"title": "MAC Addresses",
"description": "List of extracted MAC Addresses",
"items": {
"type": "string"
},
"order": 1
}
}
}
""")
def __init__(self):
super(self.__class__, self).__init__(self.schema)
| [
"[email protected]"
]
| |
152fe3ddd50b67a56fdbcc413e150071d290d729 | 36b1e387555398e942ccb7ed44b71ea2a036fee4 | /accounting.py | af315222d74f79dc1fd177042413722ffa956e5e | []
| no_license | RomanKhudobei/Accounting-Project | 8e99df581d3a75c182a330ad2913a8ec831c88b1 | 45a95e535578b0fa84fcb7f216c0b351886ba740 | refs/heads/master | 2021-07-18T19:01:54.389635 | 2017-10-26T21:04:27 | 2017-10-26T21:04:27 | 105,196,874 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 13,488 | py | import time
from pprint import pprint
DATABASE = {} # Data base to store accounting information
# account is special, if it doesn't have sub_account
SPECIAL_ACCOUNTS = ('01', '03', '05', '06', '08', '09', '22', '23', '24',
'25', '26', '27', '38', '39', '43', '46', '54', '55',
'69', '76', '79', '84', '85', '91', '92', '93', '98')
# valid accounts of accounting (3 digits)
# to avoid entering accounts like '999' or any mistakes in entering
# and it's a lot easier to validate account
VALID_ACCOUNTS = ('100', '101', '102', '103', '104', '105', '106', '107',
'108', '109', '111', '112', '113', '114', '115', '116',
'117', '121', '122', '123', '124', '125', '127', '131',
'132', '133', '134', '135', '141', '142', '143', '151',
'152', '153', '154', '155', '161', '162', '163', '164',
'165', '166', '181', '182', '183', '184', '191', '193',
'201', '202', '203', '204', '205', '206', '207', '208',
'209', '211', '212', '213', '281', '282', '283', '284',
'285', '286', '301', '302', '311', '312', '313', '314',
'315', '316', '331', '332', '333', '334', '335', '341',
'342', '351', '352', '361', '362', '363', '364', '371',
'372', '373', '374', '375', '376', '377', '378', '379',
'401', '402', '403', '404', '411', '412', '413', '414',
'421', '422', '423', '424', '425', '441', '442', '443',
'451', '452', '453', '471', '472', '473', '474', '475',
'476', '477', '478', '481', '482', '483', '484', '491',
'492', '493', '494', '495', '496', '501', '502', '503',
'504', '505', '506', '511', '512', '521', '522', '523',
'531', '532', '601', '602', '603', '604', '605', '606',
'611', '612', '621', '622', '631', '632', '633', '641',
'642', '643', '644', '651', '652', '654', '655', '661',
'662', '663', '671', '672', '680', '681', '682', '683',
'684', '685', '701', '702', '703', '704', '705', '710',
'711', '712', '713', '714', '715', '716', '717', '718',
'719', '721', '722', '723', '731', '732', '733', '740',
'741', '742', '744', '745', '746', '791', '792', '793',
'801', '802', '803', '804', '805', '806', '807', '808',
'809', '811', '812', '813', '814', '815', '816', '821',
'824', '831', '832', '833', '901', '902', '903', '904',
'940', '941', '942', '943', '944', '945', '946', '947',
'948', '949', '951', '952', '961', '962', '963', '970',
'971', '972', '974', '975', '976', '977', '021', '021',
'022', '023', '024', '025', '041', '042', '071', '072')
def check_valid_account(account):
'''Checks account. If it's not valid - throw according exception.'''
assert type(account) == str, 'Account has to be str type.'
assert account.isdigit() == True, 'Account has to be a number str type.'
assert account in SPECIAL_ACCOUNTS or account in VALID_ACCOUNTS, 'You entered invalid account.'
def check_in(database, account, start_remainder=0):
'''Check out if account already in database
and if it's not - creates data structure for it.
Returns:
number of account, sub_account (str type).
'''
check_valid_account(account)
if account in SPECIAL_ACCOUNTS:
if account not in database:
database[account] = {
'start_remainder': start_remainder,
'debit': {},
'credit': {}
}
return account, None
else:
# e.g. if given argument account is 301, than
# account = 30, sub_account = 301
sub_account, account = account, account[0:2]
if account not in database:
database[account] = {
sub_account: {
'start_remainder': start_remainder,
'debit': {},
'credit': {}
}
}
elif sub_account not in database[account]:
database[account].update({
sub_account: {
'start_remainder': start_remainder,
'debit': {},
'credit': {}
}
})
return account, sub_account
def set_start_remainder(database, account, start_remainder):
'''Rewrites start_remainder, even if it already exist.'''
account, sub_account = check_in(database, account)
if sub_account == None:
database[account]['start_remainder'] = start_remainder
else:
database[account][sub_account]['start_remainder'] = start_remainder
def add_debit_operation(database, number, debit, amount, description):
'''Adds operation to debit account. If it's already exist -
rewrites it.'''
account, sub_account = check_in(database, debit)
if sub_account == None:
database[account]['debit'].update({
number: {
'amount': amount,
'description': description
}
})
else:
database[account][sub_account]['debit'].update({
number: {
'amount': amount,
'description': description
}
})
def add_credit_operation(database, number, credit, amount, description):
'''Adds operation to credit account. If it's already exist -
rewrites it.'''
account, sub_account = check_in(database, credit)
if sub_account == None:
database[account]['credit'].update({
number: {
'amount': amount,
'description': description
}
})
else:
database[account][sub_account]['credit'].update({
number: {
'amount': amount,
'description': description
}
})
def add_operation(database, number, debit, credit, amount, description=None):
'''Adds operation to accounting database.'''
assert type(number) == str, 'Number of operation has to be a str type.'
assert type(description) == str or description == None, 'Description has to be a str type.'
assert type(amount) == int or type(amount) == float, 'Amount should be int or float type.'
assert amount >= 0, 'Amount has to be greater or equal to zero.'
assert debit.isdigit() == True, 'Number of account has to be number str type.'
assert credit.isdigit() == True, 'Number of account has to be number str type.'
add_debit_operation(database, number, debit, amount, description)
add_credit_operation(database, number, credit, amount, description)
def calculate_debit_turnover(database, account, sub_account=None):
'''The summ of all debit/credit operations is called turnover.
This function calculate debit turnover.'''
if account in database: # additional checking for case if function invoked alone
turnover = 0
if account in SPECIAL_ACCOUNTS:
operations = database[account]['debit']
for operation in operations:
turnover = turnover + operations[operation]['amount']
return turnover
else:
if sub_account in database[account]:
operations = database[account][sub_account]['debit']
for operation in operations:
turnover = turnover + operations[operation]['amount']
return turnover
def calculate_credit_turnover(database, account, sub_account=None):
'''The summ of all debit/credit operations is called turnover.
This function calculate credit turnover.'''
if account in database: # additional checking for case if function invoked alone
turnover = 0
if account in SPECIAL_ACCOUNTS:
operations = database[account]['credit']
for operation in operations:
turnover = turnover + operations[operation]['amount']
return turnover
else:
if sub_account in database[account]:
operations = database[account][sub_account]['credit']
for operation in operations:
turnover = turnover + operations[operation]['amount']
return turnover
def sumbit_turnover(database):
'''Caltulates and sets debit/credit turnover for each account.'''
for account in database:
if account in SPECIAL_ACCOUNTS:
database[account]['debit']['turnover'] = calculate_debit_turnover(database, account, None)
database[account]['credit']['turnover'] = calculate_credit_turnover(database, account, None)
else:
for sub_account in database[account]:
database[account][sub_account]['debit']['turnover'] = calculate_debit_turnover(database, account, sub_account)
database[account][sub_account]['credit']['turnover'] = calculate_credit_turnover(database, account, sub_account)
def sumbit_end_remainder(database):
'''Calculates and sets end remainder for each account.'''
for account in database:
if account in SPECIAL_ACCOUNTS:
assert 'turnover' in database[account]['debit'], 'You have to invoke sumbit_turnover at first.'
start_remainder = database[account]['start_remainder']
debit_turnover = database[account]['debit']['turnover']
credit_turnover = database[account]['credit']['turnover']
end_remainder = start_remainder + debit_turnover - credit_turnover
database[account]['end_remainder'] = end_remainder
else:
for sub_account in database[account]:
assert 'turnover' in database[account][sub_account]['debit'], 'You have to invoke sumbit_turnover at first.'
start_remainder = database[account][sub_account]['start_remainder']
debit_turnover = database[account][sub_account]['debit']['turnover']
credit_turnonver = database[account][sub_account]['credit']['turnover']
end_remainder = start_remainder + debit_turnover - credit_turnonver
database[account][sub_account]['end_remainder'] = end_remainder
""" If you want to look up how it works, you can use following code """
def test_check_in(database):
accounts = ['101', '131', '201', '207', '23', '26', '301', '311', '372', '377',
'39', '401', '441', '471', '601', '631', '641', '651', '661', '685']
start_remainders = [590000, 120000, 95000, 6000, 10000, 7000, 150, 10350, 500,
10000, 5000, 540000, 15000, 2000, 14000, 17000, 5000, 4000,
15000, 2000]
assert len(accounts) == len(start_remainders)
for index in range(0, len(accounts)):
check_in(database, accounts[index], start_remainders[index])
def test_add_operation(database):
operations = [str(x) for x in range(1, 50)]
deb_accounts = ['101', '92', '131', '972', '311', '79', '701', '79', '201', '201',
'201', '311', '23', '23', '23', '92', '23', '23', '92', '23',
'92', '471', '661', '92', '92', '92', '26', '361', '701', '311',
'311', '901', '701', '301', '661', '372', '98', '311', '641',
'631', '631', '651', '685', '601', '684', '79', '79', '79', '79']
cred_accounts = ['401','131','101','101','701','972','79','441','631','631',
'631','601','201','201','201','201','471','661','661','651',
'651','661','641','207','372','39','23','701','641','361',
'377','26','79','311','301','301','641','641','311','311',
'311','311','311','311','311','92','98','901','441']
amounts = [30000,6700,500,1000,2000,1000,2000,1000,82500,30000,7500,27000,
105000,35000,2000,15000,3000,30000,12000,11250,4500,2000,4500,
500,200,1200,177400,265213,34594,265213,3000,177400,230619,43000,
42000,200,10644,6800,4500,120000,12500,4000,1000,27000,2700,40100,
10644,177400,0]
assert len(operations) == len(deb_accounts) == len(cred_accounts) == len(amounts)
for index in range(0, len(operations)):
add_operation(database, operations[index], deb_accounts[index], cred_accounts[index], amounts[index])
def test_function(database): # compare summs of all deb and cred turnovers. Have to be the same.
deb_turnover = 0
cred_turnonver = 0
for account in database:
if account in SPECIAL_ACCOUNTS:
deb_turnover += database[account]['debit']['turnover']
cred_turnonver += database[account]['credit']['turnover']
else:
for sub_account in database[account]:
deb_turnover += database[account][sub_account]['debit']['turnover']
cred_turnonver += database[account][sub_account]['credit']['turnover']
print((deb_turnover, cred_turnonver))
t = time.time()
test_check_in(DATABASE)
test_add_operation(DATABASE)
sumbit_turnover(DATABASE)
sumbit_end_remainder(DATABASE)
test_function(DATABASE)
print(time.time() - t)
pprint(DATABASE)
| [
"[email protected]"
]
| |
dbc1c10415f60b72f07487f2f9e354e0d17427be | db94236acf2ec1150f768906dca872bc8109e424 | /.metadata/.plugins/org.eclipse.core.resources/.history/7b/20c08447c30b001713a6aee85c38bf9c | de40ebc1f38157a62b88184413ce4abf8ce65f5e | []
| no_license | ivanganchev93/TurtlebotProject2017 | 8188adf54afc2073b346ba4ec282e70172763fb6 | 84140ecdb04b3755cbe19c37fe52271f287680b8 | refs/heads/master | 2020-04-05T12:08:50.709200 | 2017-10-22T18:20:26 | 2017-10-22T18:20:26 | 95,221,352 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 11,262 | #!/usr/bin/env python
import roslib
import sys
import rospy
import binascii
import math
import numpy as np
import cv2
import io
import os
import warnings
from std_msgs.msg import String
from nav_msgs.msg import Odometry, OccupancyGrid
from geometry_msgs.msg import Point
from sensor_msgs.msg import LaserScan, Image, PointCloud2, PointField
import sensor_msgs.point_cloud2 as pc2
from google.cloud import vision
from google.cloud.vision.feature import Feature
from google.cloud.vision.feature import FeatureTypes
from cv_bridge import CvBridge, CvBridgeError
import Image as mig
# Google vision client to enable image recognition
client = vision.Client()
#list in which to store detected objects from world
objects_detected=[]
# class Item is the object detected in the world + its location
class Item:
def __init__(self):
self.description = None
self.x_location = None
self.y_location = None
# LabelDetector is the main class detecting objects in the world
class LabelDetector:
def __init__(self):
self.odometry = None
self.receivedNewOdometry = False
self.depthImage = None
self.receivedNewDepthImage = False
self.image = None
self.receivedNewImage = False
self.points = None
self.receivedNewPoints = False
#Callback function that processes the Image message.
def image_callback(self, image_msg):
bridge = CvBridge()
self.image = bridge.imgmsg_to_cv2(image_msg, "rgb8")
self.receivedNewImage = True
#Callback function that processes the Odometry message.
def odom_callback(self, odom_msg):
self.odometry = odom_msg
self.receivedNewOdometry = True
#Callback function that processes the Depth message.
#!! Currently not in use as new implementation found using PointCloud data
def depth_callback(self, depth_msg):
self.depthImage=depth_msg
self.receivedNewDepthImage = True
#Callback function that processes the PointCloud message.
def point_callback(self, point_msg):
self.points = point_msg
self.receivedNewPoints = True
#get single moment data to process and label objects
def get_moment_data(self):
if self.receivedNewImage:
rgb_image = self.image
else:
rospy.loginfo("RGB image not received")
if self.receivedNewDepthImage:
depth_image = self.depthImage
else:
rospy.loginfo("Depth image not received")
if self.receivedNewOdometry:
odometry_data = self.odometry
else:
rospy.loginfo("Odometry data not received")
if self.receivedNewPoints:
points = self.points
else:
rospy.loginfo("Odometry data not received")
return [rgb_image,depth_image,odometry_data, points]
#function to get distance measurements from depth image
def get_distance(self, depth_img):
bridge=CvBridge()
cv_depth_image = bridge.imgmsg_to_cv2(depth_img)
return cv_depth_image
#function to extract x,y,z points of objects
def get_point_data(self, points):
point_list = []
for p in pc2.read_points(points, field_names = ("x", "y", "z")):
point_list.append((p[0],p[1],p[2]))
point_array = np.array(point_list)
point_3d_array = np.reshape(point_array, (480,640,3))
return point_3d_array
#get the bounding box of an object, and its centre pixel, in an image in order to label it and find its position
def get_object_boundingbox(self, rgb_image):
imgray = cv2.cvtColor(rgb_image,cv2.COLOR_RGB2GRAY)
img_filt = cv2.medianBlur(imgray, 5)
img_th = cv2.adaptiveThreshold(img_filt,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,7,2)
contours, hierarchy = cv2.findContours(img_th, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
sortedContours = sorted(contours, key =cv2.contourArea, reverse = True)
largestContours = sortedContours[0:2]
contourCentres = {}
contourNumber = 1
img = rgb_image
for contour in largestContours:
x,y,w,h = cv2.boundingRect(contour)
contourCentres[contourNumber]=[(x+w)/2,(y+h)/2, w,h]
contourNumber+=1
#cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
return contourCentres
#get the object distances from the robot
def get_object_data(self, rgb_image, depth_image,points):
object_images=[]
object_distances=[]
object_point_distances=[]
depth_img = self.get_distance(depth_image)
points = self.get_point_data(points)
objects = self.get_object_boundingbox(rgb_image)
for object in objects:
object_image = rgb_image[objects[object][0]
-objects[object][2]/2:objects[object][0]
+objects[object][2]/2 , objects[object][1]
-objects[object][3]/2:objects[object][1]
+objects[object][3]/2, :]
point_distance = points[objects[object][0]-
10:objects[object][0]+10,objects[object][1]-10:objects[object][1]+10]
object_distance_im = depth_img[objects[object][0]-
10:objects[object][0]+10,objects[object][1]-10:objects[object][1]+10]
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
average_distance = np.nanmean(object_distance_im)/1000
point_distance_x = []
point_distance_y = []
point_distance_z = []
for i in range(point_distance.shape[0]):
for j in range(point_distance.shape[1]):
point_distance_x.append(point_distance[i][j][0])
point_distance_y.append(point_distance[i][j][1])
point_distance_z.append(point_distance[i][j][2])
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
point_average_x = np.nanmean(np.array(point_distance_x))
point_average_y = np.nanmean(np.array(point_distance_y))
point_average_z = np.nanmean(np.array(point_distance_z))
if math.isnan(point_average_x) or math.isnan(point_average_y) or math.isnan(point_average_z):
break
object_images.append(object_image)
object_distances.append(average_distance)
object_point_distances.append([point_average_x,point_average_y,point_average_z])
return object_images, object_distances,object_point_distances
#The function that uses the google api to recognise objects from images
def process_image(self,rgb_image):
object_description = []
bytes = rgb_image.tobytes()
im = mig.fromarray(rgb_image)
imgByteArr = io.BytesIO()
im.save(imgByteArr, format='PNG')
imgByteArr = imgByteArr.getvalue()
image = client.image(content = imgByteArr)
features =[Feature(FeatureTypes.LABEL_DETECTION, 1),
Feature(FeatureTypes.FACE_DETECTION,1)]
annotations = image.detect(features)
for annotation in annotations:
for label in annotation.labels:
object_description.append([label.description, label.score])
return object_description
#compute the object's location on the map + check if object is already on the map storage list
def detect_objects(self):
item = Item()
# gets the most current data from the robot topics (image,odometry,depth,pointcloud)
data = self.get_moment_data()
# the current position of the robot
x_position = self.odometry.pose.pose.position.x
y_position = self.odometry.pose.pose.position.y
z_position = self.odometry.pose.pose.position.z
#the processed data to get the objects
object_images, object_distances, object_point_distances = self.get_object_data(data[0],data[1],data[3])
for i in range (len(object_images)):
# get the object description from object_images and its location
print object_images[i].shape
item.description = self.process_image(object_images[i])[0][0]
item.x_location = x_position+object_point_distances[i][0]
item.y_location = y_position+object_point_distances[i][1]
#flag to check dupicate items based on their location
duplicate_found = False
radius = 0.3
for detected_item in objects_detected:
#if item.description == detected_item.description and \
#item.x_location >= detected_item.x_location-0.30 and item.x_location <= detected_item.x_location+0.30 and \
#item.y_location >= detected_item.y_location-0.30 and item.y_location <= detected_item.y_location+0.30:
# duplicate_found = True
# rospy.loginfo("found duplicate Item: " + item.description)
# break
if item.description == detected_item.description and \
(np.power(item.x_location-detected_item.x_location, 2) + np.power(item.y_location-detected_item.y_location,2))<=np.power(radius,2):
duplicate_found = True
rospy.loginfo("found duplicate Item: " + item.description)
break
if not duplicate_found:
objects_detected.append(item)
rospy.loginfo("found new Item: " + str(item.description) + " at " + str(item.x_location) + ", " + str(item.y_location) + " location")
return objects_detected
# store the labels and locations of the objects on the map in a file to be used by the navigation module
def store_image(self):
rospy.loginfo("Storing items to file")
item_file = open(os.path.dirname(__file__)+"/../../../maps/items_detected.txt","w")
for item in objects_detected:
item_file.write("%s, %f, %f\n" %(item.description, item.x_location, item.y_location))
# stop module
def shutdown(self):
rospy.loginfo("Quit program")
rospy.sleep()
if __name__== '__main__':
ld = LabelDetector()
rospy.init_node("turtlebot_vision")
image_sub = rospy.Subscriber("/camera/rgb/image_raw", Image , ld.image_callback)
odom_sub = rospy.Subscriber("/odom", Odometry, ld.odom_callback)
laser_sub = rospy.Subscriber("/camera/depth/image_raw", Image, ld.depth_callback)
point_sub = rospy.Subscriber("/camera/depth/points", PointCloud2, ld.point_callback)
rospy.sleep(1.0)
rospy.loginfo("Starting Object Detection.")
while not rospy.is_shutdown():
objects = ld.detect_objects()
ld.store_image()
rospy
rospy.spin() | [
"[email protected]"
]
| ||
91c49178d5dce7ea6fae1aa3f8561b745143e0c8 | d8ad69f58827b45cecc4b747d40474bacf3b70c6 | /dsc_connect_app/apps.py | 7595f6e5a13d83e23b9769aa77467663706c11b0 | []
| no_license | dsckiet/dsc-connect-backend | 8cd644e5991edf43c31735bb2abb62e895ce53ae | 584b42525497991e1aa4d9dae2670d607cf0f299 | refs/heads/master | 2020-12-23T18:15:16.570009 | 2020-04-25T12:21:21 | 2020-04-25T12:21:21 | 233,260,515 | 0 | 2 | null | 2020-01-24T13:57:32 | 2020-01-11T16:21:09 | Python | UTF-8 | Python | false | false | 187 | py | from django.apps import AppConfig
class DscConnectAppConfig(AppConfig):
name = 'dsc_connect_app'
#def ready(self):
# import dsc_connect_backend.apps.dsc_connect_app.signals | [
"[email protected]"
]
| |
4dfb6d16bcfe5cdc4bec9b9739e75f6880607027 | ac7abb68539f884b477c19c80d76ff1e1ef3b4cc | /Runner/Principal.py | 255a84bad72ee88bfec1f56abba2f023060cf01e | []
| no_license | Retravel/Retravel-Fin | 81f28791a926d4b6abba91711ef013c86be29aca | a58287708fb3e2032cda5e96094cb576c2fb761c | refs/heads/master | 2020-03-17T14:35:02.967645 | 2018-05-21T10:01:38 | 2018-05-21T10:01:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 16,277 | py | import pygame as pg
import random
from Runner.Options import *
from Runner.Classes import *
class Jeu :
def __init__(self) :
# initialisation de la fenêtre, etc
pg.init()
pg.mixer.init()
self.fenetre = pg.display.set_mode((LARGEUR,HAUTEUR))
pg.display.set_caption(TITRE)
self.clock = pg.time.Clock()
self.running = True
self.font_name = pg.font.match_font(FONT_NAME)
self.load_data()
def load_data(self):
# charger les différents sons du jeu
self.jump_son = pg.mixer.Sound('Runner/son/Jump15.wav')
self.boost_son = pg.mixer.Sound('Runner/son/Randomize87.wav')
self.hurt_son = pg.mixer.Sound('Runner/son/Hit_Hurt5.wav')
self.list_fond = []
# charger les différentes images de fond
for i in range (1, 6):
self.list_fond.append(pg.image.load('Runner/img/fond' + str(i) + '.png').convert())
self.list_fond2 = [self.list_fond[1], self.list_fond[2]]
self.list_fond3 = [self.list_fond[3], self.list_fond[4]]
self.fond = self.list_fond[0]
def new(self) :
# commencer une nouvelle partie
self.score = 0
self.gem_score = 0
self.mob_timer = 0
self.boss_timer = 0
self.portal_timer = 0
self.current_frame = 0
self.last_update = 0
self.spawned_portal = False
self.pass_portal = False
self.spawned_portal2 = False
self.pass_portal2 = False
self.spawn_sol = False
self.spawned_boss = False
self.combat = False
self.boss_died = False
self.all_sprites = pg.sprite.LayeredUpdates()
self.platforms = pg.sprite.Group()
self.objects = pg.sprite.Group()
self.mobs = pg.sprite.Group()
self.portals = pg.sprite.Group()
self.obstacles = pg.sprite.Group()
self.boss = pg.sprite.Group()
self.player = Player(self)
for plat in PLATFORM_LIST :
Platform(self, *plat)
pg.mixer.music.load('Runner/son/Chagrin.ogg')
self.run()
def run(self):
# boucle du jeu
pg.mixer.music.play(loops=-1)
self.playing = True
self.win = False
while self.playing == True :
self.clock.tick(FPS)
self.events()
self.update()
self.display()
if self.win :
self.victory_screen()
pg.mixer.music.fadeout(500)
def update(self):
# boucle du jeu mise à jour
self.all_sprites.update()
self.animation_fond()
# apparition ennemis
now = pg.time.get_ticks()
if now - self.mob_timer > MOQ_FREQ + random.choice([-1000, -500, 0, 500, 1000]) :
self.mob_timer = now
if self.score <= SCORE_LIMIT :
Mob_ship(self)
#collision ennemis - phase 1
mob_hits = pg.sprite.spritecollide(self.player, self.mobs, False, pg.sprite.collide_mask)
mob_died = False
for mob in self.mobs :
if not self.player.invincible :
if (mob.rect.left <= self.player.rect.centerx <= mob.rect.right and \
mob.rect.top-5 <= self.player.rect.bottom <= mob.rect.centery) and self.player.jumping :
mob_died = True
mob.kill()
if not self.spawned_portal :
self.score += 1
if mob_hits and not mob_died :
self.hurt_son.play()
self.player.vie -= 1
self.player.invincible = True
#collision obstacles - phase 2
obst_hits = pg.sprite.spritecollide(self.player, self.obstacles, False, pg.sprite.collide_mask)
if obst_hits :
if not self.player.invincible :
self.hurt_son.play()
self.player.vie -= 1
self.player.invincible = True
# on vérifie si le joueur touche une plateforme (uniquement en descendant)
if self.player.vit.y > 0 :
hits = pg.sprite.spritecollide(self.player, self.platforms, False)
if hits:
lowest = hits[0]
for hit in hits :
if hit.rect.bottom > lowest.rect.bottom :
lowest = hit
if lowest.rect.left-10 < self.player.pos.x < lowest.rect.right+10 :
if self.player.pos.y < lowest.rect.bottom+5 :
self.player.pos.y = lowest.rect.top+0.3
self.player.vit.y = 0
self.player.jumping = False
#si le joueur arrive au 2/3 de la largeur de l'écran
if self.player.rect.x >= LARGEUR/3:
if not self.pass_portal and not self.pass_portal2:
self.player.pos.x -= max(abs(self.player.vit.x), 2)
for mob in self.mobs :
mob.rect.x -= max(abs(self.player.vit.x),2)
for plat in self.platforms :
plat.rect.right -= max(abs(self.player.vit.x),2)
for portal in self.portals :
portal.rect.right -= max(abs(self.player.vit.x),2)
# collision entre un object collectable et le joueur
object_hits = pg.sprite.spritecollide(self.player, self.objects, True)
for object in object_hits :
if object.type == 'boost':
self.boost_son.play()
self.player.vit.x = SPEED_BOOST
self.player.vit.y = -JUMP_BOOST
self.player.walking = False
if object.type == 'gem':
self.gem_score += 1
#créer de nouvelles plateformes
if self.spawned_portal2 == False :
while len(self.platforms) < 8 :
if self.spawned_portal == False :
Platform(self, random.randrange(LARGEUR, LARGEUR+240),
random.randrange(150, HAUTEUR-20))
else :
Platform(self, random.randrange(LARGEUR, LARGEUR+240),
random.choice([150, 300, 450 ]))
else :
if not self.spawn_sol :
Platform(self, LARGEUR + 240, HAUTEUR-50)
self.spawn_sol = True
# déclenchement phase 2
if self.score > SCORE_LIMIT:
if now - self.portal_timer > 5000 and not self.spawned_portal and not self.spawned_portal2:
self.portal_timer = now
self.portal1 = Portal(self, 'portal1')
self.spawned_portal = True
# déclenchement phase 3
if self.gem_score > SCORE_LIMIT:
if now - self.portal_timer > 5000 and not self.spawned_portal2:
self.portal_timer = now
self.portal2 = Portal(self, 'portal2')
self.spawned_portal2 = True
for portal in self.portals :
# franchissement portails
if portal.type == 'portal1' :
if self.player.rect.right > portal.rect.centerx+10 :
self.pass_portal = True
else :
self.pass_portal = False
if portal.type == 'portal2' :
if self.player.rect.right > portal.rect.centerx+10 :
self.pass_portal2 = True
else :
self.pass_portal2 = False
if self.pass_portal and not self.pass_portal2 :
#la vitesse est réduite pour ne pas que le joueur aille trop vite par rapport au scrolling
self.player.vit.x *= 0.75
# scrolling indépendant du joueur pour la phase 2
if self.player.vit.x <= 0 :
self.player.pos.x -= VIT_SCROLLING
for plat in self.platforms :
if plat.rect.right <= 0 :
plat.kill()
else :
plat.rect.right -= VIT_SCROLLING
for portal in self.portals :
portal.rect.right -= VIT_SCROLLING
if self.pass_portal2 :
for plat in self.platforms :
if plat.num_image == 4 :
if plat.rect.right <= -240 :
plat.kill()
else :
plat.rect.right -= VIT_SCROLLING
if plat.num_image == 1 :
if plat.rect.right-20 > LARGEUR :
plat.rect.x -= VIT_SCROLLING
for portal in self.portals :
portal.rect.right -= VIT_SCROLLING
if portal.rect.left < 1 and not self.spawned_boss:
Boss(self, 700, HAUTEUR-48)
self.spawned_boss = True
if self.spawned_boss :
#démarrage combat avec le changement d'animation
if self.player.rect.x > LARGEUR*0.6 :
self.combat = True
if self.combat :
#combat de boss
for boss in self.boss :
if boss.rect.x < self.player.rect.x :
boss.vit.x = 2
if boss.rect.x > self.player.rect.x :
boss.vit.x = -2
if self.player.rect.x-1 <= boss.rect.x <= self.player.rect.x+1 :
boss.vit.x = 0
#collisions boss - phase 3
boss_hit = pg.sprite.spritecollide(self.player, self.boss, False, pg.sprite.collide_mask)
if not self.player.invincible and not boss.protection:
if (boss.rect.left+5 <= self.player.rect.centerx <= boss.rect.right-5 and \
boss.rect.top-5 <= self.player.rect.bottom <= boss.rect.centery) and self.player.jumping :
boss.vie -= 1
boss.protection = True
if boss_hit and not self.boss_died:
self.hurt_son.play()
self.player.vie -= 1
self.player.invincible = True
for boss in self.boss :
#si l'ennemi est à cours de vies
if boss.vie <= 0 :
self.boss_died = True
boss.image = boss.died_img
boss.vit.x = 0
if boss.rect.bottom < HAUTEUR -30 :
boss.vit.y = 1
if boss.rect.top > HAUTEUR :
self.win = True
# si le joueur tombe dans le vide
if self.player.rect.top > HAUTEUR :
self.playing = False
# si le joueur n'a plus de vies
if self.player.vie <= 0 :
self.playing = False
# phase 2 - si le joueur n'arrive plus à suivre
if self.player.rect.right < -5 :
self.playing = False
def animation_fond(self):
# changement du fond selon les phase
now = pg.time.get_ticks()
if not self.pass_portal and not self.pass_portal2 :
self.fond = self.list_fond[0]
else :
if self.pass_portal and not self.pass_portal2 :
if now - self.last_update > 2000 :
self.last_update = now
self.current_frame = (self.current_frame + 1) % len(self.list_fond2)
self.fond = self.list_fond2[self.current_frame]
if self.pass_portal2 :
if now - self.last_update > 2000 :
self.last_update = now
self.current_frame = (self.current_frame + 1) % len(self.list_fond3)
self.fond = self.list_fond3[self.current_frame]
def events(self) :
# actions / événements
for event in pg.event.get() :
if event.type == pg.QUIT :
if self.playing == True :
self.playing = False
self.running = False
if event.type == pg.KEYDOWN :
if event.key == pg.K_SPACE :
self.player.jump()
if event.type == pg.KEYUP :
if event.key == pg.K_SPACE :
self.player.jump_cut()
def display(self) :
# boucle d'affichage du jeu
self.fenetre.blit(self.fond, (0, 0))
self.all_sprites.draw(self.fenetre)
if self.player.invincible and self.player.vie > 0:
self.fenetre.blit(self.player.shield, (self.player.rect.x-10, self.player.rect.y-3))
for portal in self.portals :
if self.pass_portal == True :
self.fenetre.blit(portal.image, portal.rect)
if not self.pass_portal and not self.pass_portal2 :
self.affiche_text(str(self.score), 30, BLANC, LARGEUR-20, 20)
if self.pass_portal and not self.pass_portal2 :
self.affiche_text(str(self.gem_score), 30, VERT, LARGEUR-20, 20)
for i in range (self.player.vie):
self.fenetre.blit(self.player.coeur,(10+35*i, 10))
for boss in self.boss :
if self.combat :
if boss.vie >= 1 :
self.fenetre.blit(boss.head,(597, 10))
for i in range (boss.vie):
self.fenetre.blit(boss.coeur,(625+35*i, 10))
# après affichage de tous les éléments, on rafraîchit l'écran
pg.display.flip()
def affiche_text(self, text, size, color, x, y) :
#affiche le nombre d'ennemis tués lors de la phase 1
font = pg.font.Font(self.font_name, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
self.fenetre.blit(text_surface, text_rect)
def start_screen(self):
# écran d'accueil
pg.mixer.music.load('Runner/son/Son_start_screen.ogg')
pg.mixer.music.play(loops=-1)
self.fenetre.fill(COULEUR_FOND)
self.affiche_text('RUNNER', 48, JAUNE, LARGEUR/2, HAUTEUR/6 - 20)
self.affiche_text("FLECHES pour BOUGER, ESPACE pour SAUTER", 22 , JAUNE, LARGEUR/2, HAUTEUR*(2/6))
self.affiche_text("Phase 1 : tuer 5 ennemis", 22 , JAUNE, LARGEUR/2, HAUTEUR/2)
self.affiche_text("Phase 2 : ramasser 5 gemmes vertes", 22 , JAUNE, LARGEUR/2, HAUTEUR/2 + 25)
self.affiche_text("Phase 3 : affronter le boss", 22 , JAUNE, LARGEUR/2, HAUTEUR/2 + 50)
self.affiche_text("APPUYEZ sur ENTER pour JOUER", 22 , JAUNE, LARGEUR/2, HAUTEUR*3/4)
pg.display.flip()
self.wait_for_key()
pg.mixer.music.fadeout(500)
def game_over_screen(self):
# écran lorsque l'on perd
if self.running == False :
return
pg.mixer.music.load('Runner/son/Son_game_over.ogg')
pg.mixer.music.play(loops=-1)
self.fenetre.fill(COULEUR_FOND)
self.affiche_text('GAME OVER', 48, ROUGE, LARGEUR/2, HAUTEUR/4)
self.affiche_text("APPUYEZ sur ENTER pour REESAYER", 22 ,
ROUGE, LARGEUR/2, HAUTEUR/2)
pg.display.flip()
self.wait_for_key()
pg.mixer.music.fadeout(500)
def victory_screen(self):
# écran de fin - de victoire
self.fenetre.fill(COULEUR_FOND)
self.affiche_text('YOU WIN - FELICITATIONS', 48, ORANGE, LARGEUR/2, HAUTEUR/4)
self.affiche_text("APPUYEZ sur LA CROIX pour QUITTER le jeu", 22 , ORANGE, LARGEUR/2, HAUTEUR/2)
pg.display.flip()
self.wait_for_key()
if self.running == False :
pg.quit()
def wait_for_key(self):
waiting = True
while waiting :
self.clock.tick(FPS)
for event in pg.event.get() :
if event.type == pg.QUIT :
waiting = False
self.running = False
if event.type == pg.KEYUP :
if event.key == pg.K_RETURN :
waiting = False
| [
"[email protected]"
]
| |
92ab9664c246ea81f1d8201f3f2d42aa6404c8c4 | 666100eef842fde48b2d478193ab5604f620ed0c | /env/lib/python3.9/site-packages/bson/dbref.py | 3c9ae5f4c997b94f31b440aaaf0a3710650b3fe4 | []
| no_license | bhavyagoel/ServerStat | 342d5dc63909fe88fe4ce0fb270c5b595471c789 | 976d5596f07f3a833ba3448aad42fea42ae901cf | refs/heads/main | 2023-09-03T03:32:07.793752 | 2021-11-17T23:33:08 | 2021-11-17T23:33:08 | 429,194,079 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,806 | py | # Copyright 2009-2015 MongoDB, Inc.
#
# 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.
"""Tools for manipulating DBRefs (references to MongoDB documents)."""
from copy import deepcopy
from bson.py3compat import iteritems, string_type
from bson.son import SON
class DBRef(object):
"""A reference to a document stored in MongoDB.
"""
# DBRef isn't actually a BSON "type" so this number was arbitrarily chosen.
_type_marker = 100
def __init__(self, collection, id, database=None, _extra={}, **kwargs):
"""Initialize a new :class:`DBRef`.
Raises :class:`TypeError` if `collection` or `database` is not
an instance of :class:`basestring` (:class:`str` in python 3).
`database` is optional and allows references to documents to work
across databases. Any additional keyword arguments will create
additional fields in the resultant embedded document.
:Parameters:
- `collection`: name of the collection the document is stored in
- `id`: the value of the document's ``"_id"`` field
- `database` (optional): name of the database to reference
- `**kwargs` (optional): additional keyword arguments will
create additional, custom fields
.. seealso:: The MongoDB documentation on `dbrefs <https://dochub.mongodb.org/core/dbrefs>`_.
"""
if not isinstance(collection, string_type):
raise TypeError("collection must be an "
"instance of %s" % string_type.__name__)
if database is not None and not isinstance(database, string_type):
raise TypeError("database must be an "
"instance of %s" % string_type.__name__)
self.__collection = collection
self.__id = id
self.__database = database
kwargs.update(_extra)
self.__kwargs = kwargs
@property
def collection(self):
"""Get the name of this DBRef's collection as unicode.
"""
return self.__collection
@property
def id(self):
"""Get this DBRef's _id.
"""
return self.__id
@property
def database(self):
"""Get the name of this DBRef's database.
Returns None if this DBRef doesn't specify a database.
"""
return self.__database
def __getattr__(self, key):
try:
return self.__kwargs[key]
except KeyError:
raise AttributeError(key)
# Have to provide __setstate__ to avoid
# infinite recursion since we override
# __getattr__.
def __setstate__(self, state):
self.__dict__.update(state)
def as_doc(self):
"""Get the SON document representation of this DBRef.
Generally not needed by application developers
"""
doc = SON([("$ref", self.collection),
("$id", self.id)])
if self.database is not None:
doc["$db"] = self.database
doc.update(self.__kwargs)
return doc
def __repr__(self):
extra = "".join([", %s=%r" % (k, v)
for k, v in iteritems(self.__kwargs)])
if self.database is None:
return "DBRef(%r, %r%s)" % (self.collection, self.id, extra)
return "DBRef(%r, %r, %r%s)" % (self.collection, self.id,
self.database, extra)
def __eq__(self, other):
if isinstance(other, DBRef):
us = (self.__database, self.__collection,
self.__id, self.__kwargs)
them = (other.__database, other.__collection,
other.__id, other.__kwargs)
return us == them
return NotImplemented
def __ne__(self, other):
return not self == other
def __hash__(self):
"""Get a hash value for this :class:`DBRef`."""
return hash((self.__collection, self.__id, self.__database,
tuple(sorted(self.__kwargs.items()))))
def __deepcopy__(self, memo):
"""Support function for `copy.deepcopy()`."""
return DBRef(deepcopy(self.__collection, memo),
deepcopy(self.__id, memo),
deepcopy(self.__database, memo),
deepcopy(self.__kwargs, memo))
| [
"[email protected]"
]
| |
4b18bbafce196b41f74a02a0ded69010dc374a94 | 569db39ea53d67b695d5573e567e1b85cd83176f | /testcases/tutu/Android/AITest/__init__.py | 9596f08c4a577f19f599f5dd0c5ffe3af31631ff | []
| no_license | 1weifang/tutuandroidautotest | f38d9c86023e4d3857b04a8860f9d5ec810c485d | f3fb49eacee27682f478cb8b27a5e8f38d62e2b1 | refs/heads/master | 2022-11-15T04:48:25.333206 | 2020-07-14T03:38:16 | 2020-07-14T03:38:16 | 279,472,772 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 181 | py | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2019/11/19 9:54
# @Author : Durat
# @Email : [email protected]
# @File : __init__.py.py
# @Software: PyCharm | [
"1qaz!QAZ1"
]
| 1qaz!QAZ1 |
85570c14233ea78fc115c1b370a14dfd5d0785a1 | 63ccd06dc73ae23018138979d6631554c7160794 | /experiments/sl-fmri-expt/dec2018_fmri/visual/visual_fmri_run1.py | 0d21aa5421751a9e7d2d0b6e07be1587a050b0d4 | []
| no_license | zhenghanQ/qlab | d82b318a8c10d9a4d3ab144d029ed20ac83060c7 | aaf7dd591b77b9e611366f2bacefd2b613644c83 | refs/heads/master | 2021-06-01T17:38:51.634923 | 2021-03-23T01:15:44 | 2021-03-23T01:15:44 | 128,655,996 | 1 | 0 | null | 2018-04-08T15:37:37 | 2018-04-08T15:37:36 | null | UTF-8 | Python | false | false | 148,138 | py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy2 Experiment Builder (v1.83.04), Wed Apr 26 09:23:33 2017
If you publish work using this script please cite the relevant PsychoPy publications
Peirce, JW (2007) PsychoPy - Psychophysics software in Python. Journal of Neuroscience Methods, 162(1-2), 8-13.
Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy. Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""
from __future__ import division # so that 1/3=0.333 instead of 1/3=0
from psychopy import locale_setup, visual, core, data, event, logging, sound, gui
from psychopy.constants import * # things like STARTED, FINISHED
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import sin, cos, tan, log, log10, pi, average, sqrt, std, deg2rad, rad2deg, linspace, asarray
from numpy.random import random, randint, normal, shuffle
import os # handy system and path functions
import sys # to get file system encoding
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__)).decode(sys.getfilesystemencoding())
os.chdir(_thisDir)
# Store info about the experiment session
expName = 'visual' # from the Builder filename that created this script
expInfo = {u'ltarget': u'',u'vtarget': u'', u'PartID': u''} # block: R(andom) and S(equential); language: 1 or 2; target: if language 1, then bi, pu, du, da; if block 2, then ku, tu, pi, do.
dlg = gui.DlgFromDict(dictionary=expInfo, title=expName)
if dlg.OK == False: core.quit() # user pressed cancel
expInfo['date'] = data.getDateStr() # add a simple timestamp
expInfo['expName'] = expName
expInfo['Run'] = "1"
# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
filename = _thisDir + os.sep + u'data/%s_%s_%s' %(expInfo['PartID'], expName, expInfo['Run'])
# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath=None,
savePickle=True, saveWideText=True,
dataFileName=filename)
#save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file
endExpNow = False # flag for 'escape' or other condition => quit the exp
# Start Code - component code to be run before the window creation
# Setup the Window
win = visual.Window(size=(1366, 768), fullscr=True, screen=0, allowGUI=False, allowStencil=False,
monitor=u'testMonitor', color=u'white', colorSpace='rgb',
blendMode='avg', useFBO=True,
)
# store frame rate of monitor if we can measure it successfully
expInfo['frameRate']=win.getActualFrameRate()
if expInfo['frameRate']!=None:
frameDur = 1.0/round(expInfo['frameRate'])
else:
frameDur = 1.0/60.0 # couldn't get a reliable measure so guess
# Initialize components for Routine "instr2"
instr2Clock = core.Clock()
instr2_text = visual.TextStim(win=win, ori=0, name='instr2_text',
text=u"Hi there! We're going to see a parade today.", font=u'Arial',
pos=[0, 0], height=0.1, wrapWidth=None,
color=u'black', colorSpace='rgb', opacity=1,
depth=-1.0)
# Initialize components for Routine "instr3"
instr3Clock = core.Clock()
instr3_text = visual.TextStim(win=win, ori=0, name='instr3_text',
text=u'This is Klaptoo!', font=u'Arial',
pos=[0, -0.3], height=0.1, wrapWidth=None,
color=u'black', colorSpace='rgb', opacity=1,
depth=-1.0)
instr3_image = visual.ImageStim(win=win, name='instr3_image',
image=u'klaptoo.png', mask=None,
ori=0, pos=[0, 0.3], size=None,
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-2.0)
# Initialize components for Routine "instr4"
instr4Clock = core.Clock()
instr4_text = visual.TextStim(win=win, ori=0, name='instr4_text',
text=u"Klaptoo is going to hold up signs for the parade. We need you to help us keep track of his favorite sign. We'll show you Klaptoo's favorite sign now.", font=u'Arial',
pos=[0, -0.4], height=0.1, wrapWidth=None,
color=u'black', colorSpace='rgb', opacity=1,
depth=-1.0)
instr4_image = visual.ImageStim(win=win, name='instr4_image',
image=u'klaptoo.png', mask=None,
ori=0, pos=[0, 0.3], size=None,
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-2.0)
# Initialize components for Routine "target_letter"
target_letterClock = core.Clock()
target_letter_image = visual.ImageStim(win=win, name='target_letter_image',
image='%s.png' % str(expInfo['ltarget']), mask=None,
ori=0, pos=[0, 0], size=None,
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)
# Initialize components for Routine "instr5"
instr5Clock = core.Clock()
instr5_text = visual.TextStim(win=win, ori=0, name='instr5_text',
text=u"Klaptoo is going to show you many signs now. Remember, this is the special sign to keep track of. Klaptoo will show you one sign at a time on the screen. Press the button whenever you see it.", font=u'Arial',
pos=[-0.4, 0], height=0.1, wrapWidth=None,
color=u'black', colorSpace='rgb', opacity=1,
depth=-1.0)
instr5_image = visual.ImageStim(win=win, name='instr5_image',
image='%s.png' % str(expInfo['ltarget']), mask=None,
ori=0, pos=[0.5, 0], size=None,
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-2.0)
# Initialize components for Routine "explain_aliens_task"
explain_aliens_taskClock = core.Clock()
explain_aliens_task_text = visual.TextStim(win=win, ori=0, name='explain_aliens_task_text',
text=u"You will also see many of Klaptoo' friends in the parade. We need you to help us keep track of a very special alien. We will show you the alien now.", font=u'Arial',
pos=[0, 0], height=0.1, wrapWidth=None,
color=u'black', colorSpace='rgb', opacity=1,
depth=0.0)
explain_aliens_task_sound = sound.Sound(u'explain_aliens.wav', secs=-1)
explain_aliens_task_sound.setVolume(1)
# Initialize components for Routine "show_target_alien"
show_target_alienClock = core.Clock()
show_target_alien_image = visual.ImageStim(win=win, name='show_target_alien_image',
image=u'Alien%s.BMP' % str(expInfo['vtarget']), mask=None,
ori=0, pos=[0, 0], size=None,
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)
# Initialize components for Routine "target_alien_reminder"
target_alien_reminderClock = core.Clock()
target_alien_reminder_image = visual.ImageStim(win=win, name='target_alien_reminder_image',
image=u'Alien%s.BMP' % str(expInfo['vtarget']), mask=None,
ori=0, pos=[0, -0.3], size=None,
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)
target_alien_reminder_text = visual.TextStim(win=win, ori=0, name='target_alien_reminder_text',
text=u'Remember, this is the special alien to keep track of. The aliens will appear one at a time on the screen as they line up. To keep track of our special alien, press the button whenever you see it. ', font=u'Arial',
pos=[0, 0.5], height=0.1, wrapWidth=None,
color=u'black', colorSpace='rgb', opacity=1,
depth=-1.0)
# Initialize components for Routine "start"
startClock = core.Clock()
start_text = visual.TextStim(win=win, ori=0, name='start_text',
text=u"Are you ready? Let's get started!", font=u'Arial',
pos=[0, 0], height=0.1, wrapWidth=None,
color=u'black', colorSpace='rgb', opacity=1,
depth=-1.0)
# Initialize components for Routine "vreminder"
vreminderClock = core.Clock()
vreminder_image = visual.ImageStim(win=win, name='vreminder_image',
image=u'Alien%s.BMP' % str(expInfo['vtarget']), mask=None,
ori=0, pos=[0, -0.3], size=None,
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)
vreminder_text = visual.TextStim(win=win, ori=0, name='vreminder_text',
text='Press the button when you see this!', font='Arial',
pos=[0, 4], height=0.1, wrapWidth=None,
color='black', colorSpace='rgb', opacity=1,
depth=0.0)
vreminder_sound = sound.Sound(u'reminder.wav', secs=-1)
vreminder_sound.setVolume(1)
# Initialize components for Routine "lreminder"
lreminderClock = core.Clock()
lreminder_image = visual.ImageStim(win=win, name='lreminder_image',
image='%s.png' % str(expInfo['ltarget']), mask=None,
ori=0, pos=[0, -0.3], size=None,
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)
lreminder_text = visual.TextStim(win=win, ori=0, name='lreminder_text',
text='Press the button when you see this!', font='Arial',
pos=[-.0, .4], height=0.1, wrapWidth=None,
color='black', colorSpace='rgb', opacity=1,
depth=0.0)
lreminder_sound = sound.Sound(u'reminder.wav', secs=-1)
lreminder_sound.setVolume(1)
# Initialize components for Routine "l_block_trial"
l_block_trialClock = core.Clock()
l_block_trial_image = visual.ImageStim(win=win, name='l_block_trial_image',
image='sin', mask=None,
ori=0, pos=[0, 0], size=None,
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)
l_block_trial_blank = visual.ImageStim(win=win, name='l_block_trial_blank',
image=u'blanka.png', mask=None,
ori=0, pos=[0, 0], size=None,
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-1.0)
# Initialize components for Routine "v_block_trial"
v_block_trialClock = core.Clock()
v_block_trial_image = visual.ImageStim(win=win, name='v_block_trial_image',
image='sin', mask=None,
ori=0, pos=[0, 0], size=None,
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=0.0)
blank_image = visual.ImageStim(win=win, name='blank_image',
image=u'blank.PNG', mask=None,
ori=0, pos=[0, 0], size=None,
color=[1,1,1], colorSpace='rgb', opacity=1,
flipHoriz=False, flipVert=False,
texRes=128, interpolate=True, depth=-2.0)
# Create some handy timers
globalClock = core.Clock() # to track the time since experiment started
routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine
#------Prepare to start Routine "instr2"-------
t = 0
instr2Clock.reset() # clock
frameN = -1
# update component parameters for each repeat
instr2_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
instr2_key_resp.status = NOT_STARTED
# keep track of which components have finished
instr2Components = []
instr2Components.append(instr2_text)
instr2Components.append(instr2_key_resp)
for thisComponent in instr2Components:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "instr2"-------
continueRoutine = True
while continueRoutine:
# get current time
t = instr2Clock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *instr2_text* updates
if t >= 0.0 and instr2_text.status == NOT_STARTED:
# keep track of start time/frame for later
instr2_text.tStart = t # underestimates by a little under one frame
instr2_text.frameNStart = frameN # exact frame index
instr2_text.setAutoDraw(True)
# *instr2_key_resp* updates
if t >= 0.0 and instr2_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
instr2_key_resp.tStart = t # underestimates by a little under one frame
instr2_key_resp.frameNStart = frameN # exact frame index
instr2_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(instr2_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if instr2_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_1', '1','num_4','num_2','num_3','2','3','4'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
instr2_key_resp.keys = theseKeys[-1] # just the last key pressed
instr2_key_resp.rt = instr2_key_resp.clock.getTime()
# a response ends the routine
continueRoutine = False
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in instr2Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "instr2"-------
for thisComponent in instr2Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "instr2" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
#------Prepare to start Routine "instr3"-------
t = 0
instr3Clock.reset() # clock
frameN = -1
# update component parameters for each repeat
instr3_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
instr3_key_resp.status = NOT_STARTED
# keep track of which components have finished
instr3Components = []
instr3Components.append(instr3_text)
instr3Components.append(instr3_image)
instr3Components.append(instr3_key_resp)
for thisComponent in instr3Components:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "instr3"-------
continueRoutine = True
while continueRoutine:
# get current time
t = instr3Clock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *instr3_text* updates
if t >= 0.0 and instr3_text.status == NOT_STARTED:
# keep track of start time/frame for later
instr3_text.tStart = t # underestimates by a little under one frame
instr3_text.frameNStart = frameN # exact frame index
instr3_text.setAutoDraw(True)
# *instr3_image* updates
if t >= 0.0 and instr3_image.status == NOT_STARTED:
# keep track of start time/frame for later
instr3_image.tStart = t # underestimates by a little under one frame
instr3_image.frameNStart = frameN # exact frame index
instr3_image.setAutoDraw(True)
# *instr3_key_resp* updates
if t >= 0.0 and instr3_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
instr3_key_resp.tStart = t # underestimates by a little under one frame
instr3_key_resp.frameNStart = frameN # exact frame index
instr3_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(instr3_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if instr3_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_1', '1','num_4','num_2','num_3','2','3','4'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
instr3_key_resp.keys = theseKeys[-1] # just the last key pressed
instr3_key_resp.rt = instr3_key_resp.clock.getTime()
# a response ends the routine
continueRoutine = False
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in instr3Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "instr3"-------
for thisComponent in instr3Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "instr3" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
#------Prepare to start Routine "instr4"-------
t = 0
instr4Clock.reset() # clock
frameN = -1
# update component parameters for each repeat
instr4_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
instr4_key_resp.status = NOT_STARTED
# keep track of which components have finished
instr4Components = []
instr4Components.append(instr4_text)
instr4Components.append(instr4_image)
instr4Components.append(instr4_key_resp)
for thisComponent in instr4Components:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "instr4"-------
continueRoutine = True
while continueRoutine:
# get current time
t = instr4Clock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *instr4_text* updates
if t >= 0.0 and instr4_text.status == NOT_STARTED:
# keep track of start time/frame for later
instr4_text.tStart = t # underestimates by a little under one frame
instr4_text.frameNStart = frameN # exact frame index
instr4_text.setAutoDraw(True)
# *instr4_image* updates
if t >= 0.0 and instr4_image.status == NOT_STARTED:
# keep track of start time/frame for later
instr4_image.tStart = t # underestimates by a little under one frame
instr4_image.frameNStart = frameN # exact frame index
instr4_image.setAutoDraw(True)
# *instr4_key_resp* updates
if t >= 0.0 and instr4_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
instr4_key_resp.tStart = t # underestimates by a little under one frame
instr4_key_resp.frameNStart = frameN # exact frame index
instr4_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(instr4_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if instr4_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_1', '1','num_4','num_2','num_3','2','3','4'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
instr4_key_resp.keys = theseKeys[-1] # just the last key pressed
instr4_key_resp.rt = instr4_key_resp.clock.getTime()
# a response ends the routine
continueRoutine = False
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in instr4Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "instr4"-------
for thisComponent in instr4Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "instr4" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
#------Prepare to start Routine "target_letter"-------
t = 0
target_letterClock.reset() # clock
frameN = -1
# update component parameters for each repeat
target_letter_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
target_letter_key_resp.status = NOT_STARTED
# keep track of which components have finished
target_letterComponents = []
target_letterComponents.append(target_letter_image)
target_letterComponents.append(target_letter_key_resp)
for thisComponent in target_letterComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "target_letter"-------
continueRoutine = True
while continueRoutine:
# get current time
t = target_letterClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *target_letter_image* updates
if t >= 0.0 and target_letter_image.status == NOT_STARTED:
# keep track of start time/frame for later
target_letter_image.tStart = t # underestimates by a little under one frame
target_letter_image.frameNStart = frameN # exact frame index
target_letter_image.setAutoDraw(True)
# *target_letter_key_resp* updates
if t >= 0.0 and target_letter_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
target_letter_key_resp.tStart = t # underestimates by a little under one frame
target_letter_key_resp.frameNStart = frameN # exact frame index
target_letter_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(target_letter_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if target_letter_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_1', '1','num_4','num_2','num_3','2','3','4'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
target_letter_key_resp.keys = theseKeys[-1] # just the last key pressed
target_letter_key_resp.rt = target_letter_key_resp.clock.getTime()
# a response ends the routine
continueRoutine = False
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in target_letterComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "target_letter"-------
for thisComponent in target_letterComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "target_letter" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
#------Prepare to start Routine "instr5"-------
t = 0
instr5Clock.reset() # clock
frameN = -1
# update component parameters for each repeat
instr5_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
instr5_key_resp.status = NOT_STARTED
# keep track of which components have finished
instr5Components = []
instr5Components.append(instr5_text)
instr5Components.append(instr5_image)
instr5Components.append(instr5_key_resp)
for thisComponent in instr5Components:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "instr5"-------
continueRoutine = True
while continueRoutine:
# get current time
t = instr5Clock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *instr5_text* updates
if t >= 0.0 and instr5_text.status == NOT_STARTED:
# keep track of start time/frame for later
instr5_text.tStart = t # underestimates by a little under one frame
instr5_text.frameNStart = frameN # exact frame index
instr5_text.setAutoDraw(True)
# *instr5_image* updates
if t >= 0.0 and instr5_image.status == NOT_STARTED:
# keep track of start time/frame for later
instr5_image.tStart = t # underestimates by a little under one frame
instr5_image.frameNStart = frameN # exact frame index
instr5_image.setAutoDraw(True)
# *instr5_key_resp* updates
if t >= 0.0 and instr5_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
instr5_key_resp.tStart = t # underestimates by a little under one frame
instr5_key_resp.frameNStart = frameN # exact frame index
instr5_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(instr5_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if instr5_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_1', '1','num_4','num_2','num_3','2','3','4'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
instr5_key_resp.keys = theseKeys[-1] # just the last key pressed
instr5_key_resp.rt = instr5_key_resp.clock.getTime()
# a response ends the routine
continueRoutine = False
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in instr5Components:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "instr5"-------
for thisComponent in instr5Components:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "instr5" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
#------Prepare to start Routine "explain_aliens_task"-------
t = 0
explain_aliens_taskClock.reset() # clock
frameN = -1
# update component parameters for each repeat
explain_aliens_task_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
explain_aliens_task_key_resp.status = NOT_STARTED
# keep track of which components have finished
explain_aliens_taskComponents = []
explain_aliens_taskComponents.append(explain_aliens_task_text)
explain_aliens_taskComponents.append(explain_aliens_task_key_resp)
for thisComponent in explain_aliens_taskComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "explain_aliens_task"-------
continueRoutine = True
while continueRoutine:
# get current time
t = explain_aliens_taskClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *explain_aliens_task_text* updates
if t >= 0.0 and explain_aliens_task_text.status == NOT_STARTED:
# keep track of start time/frame for later
explain_aliens_task_text.tStart = t # underestimates by a little under one frame
explain_aliens_task_text.frameNStart = frameN # exact frame index
explain_aliens_task_text.setAutoDraw(True)
# *explain_aliens_task_key_resp* updates
if t >= 0.0 and explain_aliens_task_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
explain_aliens_task_key_resp.tStart = t # underestimates by a little under one frame
explain_aliens_task_key_resp.frameNStart = frameN # exact frame index
explain_aliens_task_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(explain_aliens_task_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if explain_aliens_task_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_1', '1','num_4','num_2','num_3','2','3','4'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
explain_aliens_task_key_resp.keys = theseKeys[-1] # just the last key pressed
explain_aliens_task_key_resp.rt = explain_aliens_task_key_resp.clock.getTime()
# a response ends the routine
continueRoutine = False
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in explain_aliens_taskComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "explain_aliens_task"-------
for thisComponent in explain_aliens_taskComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "explain_aliens_task" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
#------Prepare to start Routine "show_target_alien"-------
t = 0
show_target_alienClock.reset() # clock
frameN = -1
# update component parameters for each repeat
show_target_alien_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
show_target_alien_key_resp.status = NOT_STARTED
# keep track of which components have finished
show_target_alienComponents = []
show_target_alienComponents.append(show_target_alien_image)
show_target_alienComponents.append(show_target_alien_key_resp)
for thisComponent in show_target_alienComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "show_target_alien"-------
continueRoutine = True
while continueRoutine:
# get current time
t = show_target_alienClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *show_target_alien_image* updates
if t >= 0.0 and show_target_alien_image.status == NOT_STARTED:
# keep track of start time/frame for later
show_target_alien_image.tStart = t # underestimates by a little under one frame
show_target_alien_image.frameNStart = frameN # exact frame index
show_target_alien_image.setAutoDraw(True)
# *show_target_alien_key_resp* updates
if t >= 0.0 and show_target_alien_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
show_target_alien_key_resp.tStart = t # underestimates by a little under one frame
show_target_alien_key_resp.frameNStart = frameN # exact frame index
show_target_alien_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(show_target_alien_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if show_target_alien_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_1', '1','num_4','num_2','num_3','2','3','4'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
show_target_alien_key_resp.keys = theseKeys[-1] # just the last key pressed
show_target_alien_key_resp.rt = show_target_alien_key_resp.clock.getTime()
# a response ends the routine
continueRoutine = False
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in show_target_alienComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "show_target_alien"-------
for thisComponent in show_target_alienComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "show_target_alien" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
#------Prepare to start Routine "target_alien_reminder"-------
t = 0
target_alien_reminderClock.reset() # clock
frameN = -1
# update component parameters for each repeat
target_alien_reminder_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
target_alien_reminder_key_resp.status = NOT_STARTED
# keep track of which components have finished
target_alien_reminderComponents = []
target_alien_reminderComponents.append(target_alien_reminder_image)
target_alien_reminderComponents.append(target_alien_reminder_text)
target_alien_reminderComponents.append(target_alien_reminder_key_resp)
for thisComponent in target_alien_reminderComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "target_alien_reminder"-------
continueRoutine = True
while continueRoutine:
# get current time
t = target_alien_reminderClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *target_alien_reminder_image* updates
if t >= 0.0 and target_alien_reminder_image.status == NOT_STARTED:
# keep track of start time/frame for later
target_alien_reminder_image.tStart = t # underestimates by a little under one frame
target_alien_reminder_image.frameNStart = frameN # exact frame index
target_alien_reminder_image.setAutoDraw(True)
# *target_alien_reminder_text* updates
if t >= 0.0 and target_alien_reminder_text.status == NOT_STARTED:
# keep track of start time/frame for later
target_alien_reminder_text.tStart = t # underestimates by a little under one frame
target_alien_reminder_text.frameNStart = frameN # exact frame index
target_alien_reminder_text.setAutoDraw(True)
# *target_alien_reminder_key_resp* updates
if t >= 0.0 and target_alien_reminder_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
target_alien_reminder_key_resp.tStart = t # underestimates by a little under one frame
target_alien_reminder_key_resp.frameNStart = frameN # exact frame index
target_alien_reminder_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(target_alien_reminder_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if target_alien_reminder_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_1', '1','num_4','num_2','num_3','2','3','4'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
target_alien_reminder_key_resp.keys = theseKeys[-1] # just the last key pressed
target_alien_reminder_key_resp.rt = target_alien_reminder_key_resp.clock.getTime()
# a response ends the routine
continueRoutine = False
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in target_alien_reminderComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "target_alien_reminder"-------
for thisComponent in target_alien_reminderComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "target_alien_reminder" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
#------Prepare to start Routine "start"-------
t = 0
startClock.reset() # clock
frameN = -1
# update component parameters for each repeat
start_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
start_key_resp.status = NOT_STARTED
# keep track of which components have finished
startComponents = []
startComponents.append(start_text)
startComponents.append(start_key_resp)
for thisComponent in startComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "start"-------
continueRoutine = True
while continueRoutine:
# get current time
t = startClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *start_text* updates
if t >= 0.0 and start_text.status == NOT_STARTED:
# keep track of start time/frame for later
start_text.tStart = t # underestimates by a little under one frame
start_text.frameNStart = frameN # exact frame index
start_text.setAutoDraw(True)
# *start_key_resp* updates
if t >= 0.0 and start_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
start_key_resp.tStart = t # underestimates by a little under one frame
start_key_resp.frameNStart = frameN # exact frame index
start_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(start_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if start_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_5', '5'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
start_key_resp.keys = theseKeys[-1] # just the last key pressed
start_key_resp.rt = start_key_resp.clock.getTime()
# a response ends the routine
continueRoutine = False
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in startComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "start"-------
for thisComponent in startComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# the Routine "start" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
#------Prepare to start Routine "lreminder"-------
t = 0
lreminderClock.reset() # clock
frameN = -1
# update component parameters for each repeat
lreminder_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
lreminder_key_resp.status = NOT_STARTED
# keep track of which components have finished
lreminderComponents = []
lreminderComponents.append(lreminder_sound)
for thisComponent in lreminderComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "lreminder"-------
continueRoutine = True
while continueRoutine:
# get current time
t = lreminderClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *lreminder_image* updates
if t >= 0.0 and lreminder_image.status == NOT_STARTED:
# keep track of start time/frame for later
lreminder_image.tStart = t # underestimates by a little under one frame
lreminder_image.frameNStart = frameN # exact frame index
lreminder_image.draw()
# *lreminder_text* updates
if t >= 0.0 and lreminder_text.status == NOT_STARTED:
# keep track of start time/frame for later
lreminder_text.tStart = t # underestimates by a little under one frame
lreminder_text.frameNStart = frameN # exact frame index
lreminder_text.draw()
# start/stop lreminder_sound
if t >= 0.0 and lreminder_sound.status == NOT_STARTED:
# keep track of start time/frame for later
lreminder_sound.tStart = t # underestimates by a little under one frame
lreminder_sound.frameNStart = frameN # exact frame index
lreminder_sound.play() # start the sound (it finishes automatically)
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in lreminderComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "lreminder"-------
for thisComponent in lreminderComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
lreminder_sound.stop() #ensure sound has stopped at end of routine
# the Routine "lreminder" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
l_block_trial_loop = data.TrialHandler(nReps=1, method='sequential',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions(u'visual_run1_1.xlsx'),
seed=None, name='l_block_trial_loop')
thisExp.addLoop(l_block_trial_loop) # add the loop to the experiment
thisL_block_trial_loop = l_block_trial_loop.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisL_block_trial_loop.rgb)
if thisL_block_trial_loop != None:
for paramName in thisL_block_trial_loop.keys():
exec(paramName + '= thisL_block_trial_loop.' + paramName)
for thisL_block_trial_loop in l_block_trial_loop:
currentLoop = l_block_trial_loop
# abbreviate parameter names if possible (e.g. rgb = thisL_block_trial_loop.rgb)
if thisL_block_trial_loop != None:
for paramName in thisL_block_trial_loop.keys():
exec(paramName + '= thisL_block_trial_loop.' + paramName)
#------Prepare to start Routine "l_block_trial"-------
t = 0
l_block_trialClock.reset() # clock
frameN = -1
routineTimer.add(1.000000)
# update component parameters for each repeat
l_block_trial_image.setImage(image)
l_block_trial_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
l_block_trial_key_resp.status = NOT_STARTED
# keep track of which components have finished
l_block_trialComponents = []
l_block_trialComponents.append(l_block_trial_image)
l_block_trialComponents.append(l_block_trial_blank)
l_block_trialComponents.append(l_block_trial_key_resp)
for thisComponent in l_block_trialComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "l_block_trial"-------
continueRoutine = True
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = l_block_trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *l_block_trial_image* updates
if t >= 0.0 and l_block_trial_image.status == NOT_STARTED:
# keep track of start time/frame for later
l_block_trial_image.tStart = t # underestimates by a little under one frame
l_block_trial_image.frameNStart = frameN # exact frame index
l_block_trial_image.setAutoDraw(True)
if l_block_trial_image.status == STARTED and t >= (0.0 + (0.8-win.monitorFramePeriod*0.75)): #most of one frame period left
l_block_trial_image.setAutoDraw(False)
# *l_block_trial_blank* updates
if t >= 0.79 and l_block_trial_blank.status == NOT_STARTED:
# keep track of start time/frame for later
l_block_trial_blank.tStart = t # underestimates by a little under one frame
l_block_trial_blank.frameNStart = frameN # exact frame index
l_block_trial_blank.setAutoDraw(True)
if l_block_trial_blank.status == STARTED and t >= (0.79 + (0.21-win.monitorFramePeriod*0.75)): #most of one frame period left
l_block_trial_blank.setAutoDraw(False)
# *l_block_trial_key_resp* updates
if t >= 0.0 and l_block_trial_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
l_block_trial_key_resp.tStart = t # underestimates by a little under one frame
l_block_trial_key_resp.frameNStart = frameN # exact frame index
l_block_trial_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(l_block_trial_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if l_block_trial_key_resp.status == STARTED and t >= (0.0 + (1-win.monitorFramePeriod*0.75)): #most of one frame period left
l_block_trial_key_resp.status = STOPPED
if l_block_trial_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_1', '1','num_4','num_2','num_3','2','3','4'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
l_block_trial_key_resp.keys = theseKeys[-1] # just the last key pressed
l_block_trial_key_resp.rt = l_block_trial_key_resp.clock.getTime()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in l_block_trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "l_block_trial"-------
for thisComponent in l_block_trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if l_block_trial_key_resp.keys in ['', [], None]: # No response was made
l_block_trial_key_resp.keys=None
# store data for l_block_trial_loop (TrialHandler)
l_block_trial_loop.addData('l_block_trial_key_resp.keys',l_block_trial_key_resp.keys)
if l_block_trial_key_resp.keys != None: # we had a response
l_block_trial_loop.addData('l_block_trial_key_resp.rt', l_block_trial_key_resp.rt)
thisExp.nextEntry()
#------Prepare to start Routine "vreminder"-------
t = 0
vreminderClock.reset() # clock
frameN = -1
# update component parameters for each repeat
vreminder_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
vreminder_key_resp.status = NOT_STARTED
# keep track of which components have finished
vreminderComponents = []
vreminderComponents.append(vreminder_sound)
for thisComponent in vreminderComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "vreminder"-------
continueRoutine = True
while continueRoutine:
# get current time
t = vreminderClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *vreminder_image* updates
if t >= 0.0 and vreminder_image.status == NOT_STARTED:
# keep track of start time/frame for later
vreminder_image.tStart = t # underestimates by a little under one frame
vreminder_image.frameNStart = frameN # exact frame index
vreminder_image.draw()
# *vreminder_text* updates
if t >= 0.0 and vreminder_text.status == NOT_STARTED:
# keep track of start time/frame for later
vreminder_text.tStart = t # underestimates by a little under one frame
vreminder_text.frameNStart = frameN # exact frame index
vreminder_text.draw()
# start/stop vreminder_sound
if t >= 0.0 and vreminder_sound.status == NOT_STARTED:
# keep track of start time/frame for later
vreminder_sound.tStart = t # underestimates by a little under one frame
vreminder_sound.frameNStart = frameN # exact frame index
vreminder_sound.play() # start the sound (it finishes automatically)
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in vreminderComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "vreminder"-------
for thisComponent in vreminderComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
vreminder_sound.stop() #ensure sound has stopped at end of routine
# the Routine "vreminder" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
v_block_trials = data.TrialHandler(nReps=1, method='sequential',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions(u'visual_run1_2.xlsx'),
seed=None, name='v_block_trials')
thisExp.addLoop(v_block_trials) # add the loop to the experiment
thisV_block_trial = v_block_trials.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisV_block_trial.rgb)
if thisV_block_trial != None:
for paramName in thisV_block_trial.keys():
exec(paramName + '= thisV_block_trial.' + paramName)
for thisV_block_trial in v_block_trials:
currentLoop = v_block_trials
# abbreviate parameter names if possible (e.g. rgb = thisV_block_trial.rgb)
if thisV_block_trial != None:
for paramName in thisV_block_trial.keys():
exec(paramName + '= thisV_block_trial.' + paramName)
#------Prepare to start Routine "v_block_trial"-------
t = 0
v_block_trialClock.reset() # clock
frameN = -1
routineTimer.add(1.000000)
# update component parameters for each repeat
v_block_trial_image.setImage(image)
v_block_trial_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
v_block_trial_key_resp.status = NOT_STARTED
# keep track of which components have finished
v_block_trialComponents = []
v_block_trialComponents.append(v_block_trial_image)
v_block_trialComponents.append(v_block_trial_key_resp)
v_block_trialComponents.append(blank_image)
for thisComponent in v_block_trialComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "v_block_trial"-------
continueRoutine = True
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = v_block_trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *v_block_trial_image* updates
if t >= 0.0 and v_block_trial_image.status == NOT_STARTED:
# keep track of start time/frame for later
v_block_trial_image.tStart = t # underestimates by a little under one frame
v_block_trial_image.frameNStart = frameN # exact frame index
v_block_trial_image.setAutoDraw(True)
if v_block_trial_image.status == STARTED and t >= (0.0 + (0.8-win.monitorFramePeriod*0.75)): #most of one frame period left
v_block_trial_image.setAutoDraw(False)
# *v_block_trial_key_resp* updates
if t >= 0.0 and v_block_trial_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
v_block_trial_key_resp.tStart = t # underestimates by a little under one frame
v_block_trial_key_resp.frameNStart = frameN # exact frame index
v_block_trial_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(v_block_trial_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if v_block_trial_key_resp.status == STARTED and t >= (0.0 + (1.0-win.monitorFramePeriod*0.75)): #most of one frame period left
v_block_trial_key_resp.status = STOPPED
if v_block_trial_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_1', '1','num_4','num_2','num_3','2','3','4'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
v_block_trial_key_resp.keys = theseKeys[-1] # just the last key pressed
v_block_trial_key_resp.rt = v_block_trial_key_resp.clock.getTime()
# *blank_image* updates
if t >= 0.8 and blank_image.status == NOT_STARTED:
# keep track of start time/frame for later
blank_image.tStart = t # underestimates by a little under one frame
blank_image.frameNStart = frameN # exact frame index
blank_image.setAutoDraw(True)
if blank_image.status == STARTED and t >= (0.8 + (0.2-win.monitorFramePeriod*0.75)): #most of one frame period left
blank_image.setAutoDraw(False)
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in v_block_trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "v_block_trial"-------
for thisComponent in v_block_trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if v_block_trial_key_resp.keys in ['', [], None]: # No response was made
v_block_trial_key_resp.keys=None
# store data for v_block_trials (TrialHandler)
v_block_trials.addData('v_block_trial_key_resp.keys',v_block_trial_key_resp.keys)
if v_block_trial_key_resp.keys != None: # we had a response
v_block_trials.addData('v_block_trial_key_resp.rt', v_block_trial_key_resp.rt)
thisExp.nextEntry()
#------Prepare to start Routine "lreminder"-------
t = 0
lreminderClock.reset() # clock
frameN = -1
# update component parameters for each repeat
lreminder_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
lreminder_key_resp.status = NOT_STARTED
# keep track of which components have finished
lreminderComponents = []
lreminderComponents.append(lreminder_sound)
for thisComponent in lreminderComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "lreminder"-------
continueRoutine = True
while continueRoutine:
# get current time
t = lreminderClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *lreminder_image* updates
if t >= 0.0 and lreminder_image.status == NOT_STARTED:
# keep track of start time/frame for later
lreminder_image.tStart = t # underestimates by a little under one frame
lreminder_image.frameNStart = frameN # exact frame index
lreminder_image.draw()
# *lreminder_text* updates
if t >= 0.0 and lreminder_text.status == NOT_STARTED:
# keep track of start time/frame for later
lreminder_text.tStart = t # underestimates by a little under one frame
lreminder_text.frameNStart = frameN # exact frame index
lreminder_text.draw()
# start/stop lreminder_sound
if t >= 0.0 and lreminder_sound.status == NOT_STARTED:
# keep track of start time/frame for later
lreminder_sound.tStart = t # underestimates by a little under one frame
lreminder_sound.frameNStart = frameN # exact frame index
lreminder_sound.play() # start the sound (it finishes automatically)
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in lreminderComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "lreminder"-------
for thisComponent in lreminderComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
lreminder_sound.stop() #ensure sound has stopped at end of routine
# the Routine "lreminder" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
l_block_trial_loop = data.TrialHandler(nReps=1, method='sequential',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions(u'visual_run1_3.xlsx'),
seed=None, name='l_block_trial_loop')
thisExp.addLoop(l_block_trial_loop) # add the loop to the experiment
thisL_block_trial_loop = l_block_trial_loop.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisL_block_trial_loop.rgb)
if thisL_block_trial_loop != None:
for paramName in thisL_block_trial_loop.keys():
exec(paramName + '= thisL_block_trial_loop.' + paramName)
for thisL_block_trial_loop in l_block_trial_loop:
currentLoop = l_block_trial_loop
# abbreviate parameter names if possible (e.g. rgb = thisL_block_trial_loop.rgb)
if thisL_block_trial_loop != None:
for paramName in thisL_block_trial_loop.keys():
exec(paramName + '= thisL_block_trial_loop.' + paramName)
#------Prepare to start Routine "l_block_trial"-------
t = 0
l_block_trialClock.reset() # clock
frameN = -1
routineTimer.add(1.000000)
# update component parameters for each repeat
l_block_trial_image.setImage(image)
l_block_trial_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
l_block_trial_key_resp.status = NOT_STARTED
# keep track of which components have finished
l_block_trialComponents = []
l_block_trialComponents.append(l_block_trial_image)
l_block_trialComponents.append(l_block_trial_blank)
l_block_trialComponents.append(l_block_trial_key_resp)
for thisComponent in l_block_trialComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "l_block_trial"-------
continueRoutine = True
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = l_block_trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *l_block_trial_image* updates
if t >= 0.0 and l_block_trial_image.status == NOT_STARTED:
# keep track of start time/frame for later
l_block_trial_image.tStart = t # underestimates by a little under one frame
l_block_trial_image.frameNStart = frameN # exact frame index
l_block_trial_image.setAutoDraw(True)
if l_block_trial_image.status == STARTED and t >= (0.0 + (0.8-win.monitorFramePeriod*0.75)): #most of one frame period left
l_block_trial_image.setAutoDraw(False)
# *l_block_trial_blank* updates
if t >= 0.79 and l_block_trial_blank.status == NOT_STARTED:
# keep track of start time/frame for later
l_block_trial_blank.tStart = t # underestimates by a little under one frame
l_block_trial_blank.frameNStart = frameN # exact frame index
l_block_trial_blank.setAutoDraw(True)
if l_block_trial_blank.status == STARTED and t >= (0.79 + (0.21-win.monitorFramePeriod*0.75)): #most of one frame period left
l_block_trial_blank.setAutoDraw(False)
# *l_block_trial_key_resp* updates
if t >= 0.0 and l_block_trial_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
l_block_trial_key_resp.tStart = t # underestimates by a little under one frame
l_block_trial_key_resp.frameNStart = frameN # exact frame index
l_block_trial_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(l_block_trial_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if l_block_trial_key_resp.status == STARTED and t >= (0.0 + (1-win.monitorFramePeriod*0.75)): #most of one frame period left
l_block_trial_key_resp.status = STOPPED
if l_block_trial_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_1', '1','num_4','num_2','num_3','2','3','4'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
l_block_trial_key_resp.keys = theseKeys[-1] # just the last key pressed
l_block_trial_key_resp.rt = l_block_trial_key_resp.clock.getTime()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in l_block_trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "l_block_trial"-------
for thisComponent in l_block_trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if l_block_trial_key_resp.keys in ['', [], None]: # No response was made
l_block_trial_key_resp.keys=None
# store data for l_block_trial_loop (TrialHandler)
l_block_trial_loop.addData('l_block_trial_key_resp.keys',l_block_trial_key_resp.keys)
if l_block_trial_key_resp.keys != None: # we had a response
l_block_trial_loop.addData('l_block_trial_key_resp.rt', l_block_trial_key_resp.rt)
thisExp.nextEntry()
#------Prepare to start Routine "vreminder"-------
t = 0
vreminderClock.reset() # clock
frameN = -1
# update component parameters for each repeat
vreminder_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
vreminder_key_resp.status = NOT_STARTED
# keep track of which components have finished
vreminderComponents = []
vreminderComponents.append(vreminder_sound)
for thisComponent in vreminderComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "vreminder"-------
continueRoutine = True
while continueRoutine:
# get current time
t = vreminderClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *vreminder_image* updates
if t >= 0.0 and vreminder_image.status == NOT_STARTED:
# keep track of start time/frame for later
vreminder_image.tStart = t # underestimates by a little under one frame
vreminder_image.frameNStart = frameN # exact frame index
vreminder_image.draw()
# *vreminder_text* updates
if t >= 0.0 and vreminder_text.status == NOT_STARTED:
# keep track of start time/frame for later
vreminder_text.tStart = t # underestimates by a little under one frame
vreminder_text.frameNStart = frameN # exact frame index
vreminder_text.draw()
# start/stop vreminder_sound
if t >= 0.0 and vreminder_sound.status == NOT_STARTED:
# keep track of start time/frame for later
vreminder_sound.tStart = t # underestimates by a little under one frame
vreminder_sound.frameNStart = frameN # exact frame index
vreminder_sound.play() # start the sound (it finishes automatically)
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in vreminderComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "vreminder"-------
for thisComponent in vreminderComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
vreminder_sound.stop() #ensure sound has stopped at end of routine
# the Routine "vreminder" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
v_block_trials = data.TrialHandler(nReps=1, method='sequential',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions(u'visual_run1_4.xlsx'),
seed=None, name='v_block_trials')
thisExp.addLoop(v_block_trials) # add the loop to the experiment
thisV_block_trial = v_block_trials.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisV_block_trial.rgb)
if thisV_block_trial != None:
for paramName in thisV_block_trial.keys():
exec(paramName + '= thisV_block_trial.' + paramName)
for thisV_block_trial in v_block_trials:
currentLoop = v_block_trials
# abbreviate parameter names if possible (e.g. rgb = thisV_block_trial.rgb)
if thisV_block_trial != None:
for paramName in thisV_block_trial.keys():
exec(paramName + '= thisV_block_trial.' + paramName)
#------Prepare to start Routine "v_block_trial"-------
t = 0
v_block_trialClock.reset() # clock
frameN = -1
routineTimer.add(1.000000)
# update component parameters for each repeat
v_block_trial_image.setImage(image)
v_block_trial_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
v_block_trial_key_resp.status = NOT_STARTED
# keep track of which components have finished
v_block_trialComponents = []
v_block_trialComponents.append(v_block_trial_image)
v_block_trialComponents.append(v_block_trial_key_resp)
v_block_trialComponents.append(blank_image)
for thisComponent in v_block_trialComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "v_block_trial"-------
continueRoutine = True
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = v_block_trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *v_block_trial_image* updates
if t >= 0.0 and v_block_trial_image.status == NOT_STARTED:
# keep track of start time/frame for later
v_block_trial_image.tStart = t # underestimates by a little under one frame
v_block_trial_image.frameNStart = frameN # exact frame index
v_block_trial_image.setAutoDraw(True)
if v_block_trial_image.status == STARTED and t >= (0.0 + (0.8-win.monitorFramePeriod*0.75)): #most of one frame period left
v_block_trial_image.setAutoDraw(False)
# *v_block_trial_key_resp* updates
if t >= 0.0 and v_block_trial_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
v_block_trial_key_resp.tStart = t # underestimates by a little under one frame
v_block_trial_key_resp.frameNStart = frameN # exact frame index
v_block_trial_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(v_block_trial_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if v_block_trial_key_resp.status == STARTED and t >= (0.0 + (1.0-win.monitorFramePeriod*0.75)): #most of one frame period left
v_block_trial_key_resp.status = STOPPED
if v_block_trial_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_1', '1','num_4','num_2','num_3','2','3','4'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
v_block_trial_key_resp.keys = theseKeys[-1] # just the last key pressed
v_block_trial_key_resp.rt = v_block_trial_key_resp.clock.getTime()
# *blank_image* updates
if t >= 0.8 and blank_image.status == NOT_STARTED:
# keep track of start time/frame for later
blank_image.tStart = t # underestimates by a little under one frame
blank_image.frameNStart = frameN # exact frame index
blank_image.setAutoDraw(True)
if blank_image.status == STARTED and t >= (0.8 + (0.2-win.monitorFramePeriod*0.75)): #most of one frame period left
blank_image.setAutoDraw(False)
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in v_block_trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "v_block_trial"-------
for thisComponent in v_block_trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if v_block_trial_key_resp.keys in ['', [], None]: # No response was made
v_block_trial_key_resp.keys=None
# store data for v_block_trials (TrialHandler)
v_block_trials.addData('v_block_trial_key_resp.keys',v_block_trial_key_resp.keys)
if v_block_trial_key_resp.keys != None: # we had a response
v_block_trials.addData('v_block_trial_key_resp.rt', v_block_trial_key_resp.rt)
thisExp.nextEntry()
#------Prepare to start Routine "lreminder"-------
t = 0
lreminderClock.reset() # clock
frameN = -1
# update component parameters for each repeat
lreminder_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
lreminder_key_resp.status = NOT_STARTED
# keep track of which components have finished
lreminderComponents = []
lreminderComponents.append(lreminder_sound)
for thisComponent in lreminderComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "lreminder"-------
continueRoutine = True
while continueRoutine:
# get current time
t = lreminderClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *lreminder_image* updates
if t >= 0.0 and lreminder_image.status == NOT_STARTED:
# keep track of start time/frame for later
lreminder_image.tStart = t # underestimates by a little under one frame
lreminder_image.frameNStart = frameN # exact frame index
lreminder_image.draw()
# *lreminder_text* updates
if t >= 0.0 and lreminder_text.status == NOT_STARTED:
# keep track of start time/frame for later
lreminder_text.tStart = t # underestimates by a little under one frame
lreminder_text.frameNStart = frameN # exact frame index
lreminder_text.draw()
# start/stop lreminder_sound
if t >= 0.0 and lreminder_sound.status == NOT_STARTED:
# keep track of start time/frame for later
lreminder_sound.tStart = t # underestimates by a little under one frame
lreminder_sound.frameNStart = frameN # exact frame index
lreminder_sound.play() # start the sound (it finishes automatically)
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in lreminderComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "lreminder"-------
for thisComponent in lreminderComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
lreminder_sound.stop() #ensure sound has stopped at end of routine
# the Routine "lreminder" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
l_block_trial_loop = data.TrialHandler(nReps=1, method='sequential',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions(u'visual_run1_5.xlsx'),
seed=None, name='l_block_trial_loop')
thisExp.addLoop(l_block_trial_loop) # add the loop to the experiment
thisL_block_trial_loop = l_block_trial_loop.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisL_block_trial_loop.rgb)
if thisL_block_trial_loop != None:
for paramName in thisL_block_trial_loop.keys():
exec(paramName + '= thisL_block_trial_loop.' + paramName)
for thisL_block_trial_loop in l_block_trial_loop:
currentLoop = l_block_trial_loop
# abbreviate parameter names if possible (e.g. rgb = thisL_block_trial_loop.rgb)
if thisL_block_trial_loop != None:
for paramName in thisL_block_trial_loop.keys():
exec(paramName + '= thisL_block_trial_loop.' + paramName)
#------Prepare to start Routine "l_block_trial"-------
t = 0
l_block_trialClock.reset() # clock
frameN = -1
routineTimer.add(1.000000)
# update component parameters for each repeat
l_block_trial_image.setImage(image)
l_block_trial_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
l_block_trial_key_resp.status = NOT_STARTED
# keep track of which components have finished
l_block_trialComponents = []
l_block_trialComponents.append(l_block_trial_image)
l_block_trialComponents.append(l_block_trial_blank)
l_block_trialComponents.append(l_block_trial_key_resp)
for thisComponent in l_block_trialComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "l_block_trial"-------
continueRoutine = True
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = l_block_trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *l_block_trial_image* updates
if t >= 0.0 and l_block_trial_image.status == NOT_STARTED:
# keep track of start time/frame for later
l_block_trial_image.tStart = t # underestimates by a little under one frame
l_block_trial_image.frameNStart = frameN # exact frame index
l_block_trial_image.setAutoDraw(True)
if l_block_trial_image.status == STARTED and t >= (0.0 + (0.8-win.monitorFramePeriod*0.75)): #most of one frame period left
l_block_trial_image.setAutoDraw(False)
# *l_block_trial_blank* updates
if t >= 0.79 and l_block_trial_blank.status == NOT_STARTED:
# keep track of start time/frame for later
l_block_trial_blank.tStart = t # underestimates by a little under one frame
l_block_trial_blank.frameNStart = frameN # exact frame index
l_block_trial_blank.setAutoDraw(True)
if l_block_trial_blank.status == STARTED and t >= (0.79 + (0.21-win.monitorFramePeriod*0.75)): #most of one frame period left
l_block_trial_blank.setAutoDraw(False)
# *l_block_trial_key_resp* updates
if t >= 0.0 and l_block_trial_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
l_block_trial_key_resp.tStart = t # underestimates by a little under one frame
l_block_trial_key_resp.frameNStart = frameN # exact frame index
l_block_trial_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(l_block_trial_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if l_block_trial_key_resp.status == STARTED and t >= (0.0 + (1-win.monitorFramePeriod*0.75)): #most of one frame period left
l_block_trial_key_resp.status = STOPPED
if l_block_trial_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_1', '1','num_4','num_2','num_3','2','3','4'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
l_block_trial_key_resp.keys = theseKeys[-1] # just the last key pressed
l_block_trial_key_resp.rt = l_block_trial_key_resp.clock.getTime()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in l_block_trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "l_block_trial"-------
for thisComponent in l_block_trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if l_block_trial_key_resp.keys in ['', [], None]: # No response was made
l_block_trial_key_resp.keys=None
# store data for l_block_trial_loop (TrialHandler)
l_block_trial_loop.addData('l_block_trial_key_resp.keys',l_block_trial_key_resp.keys)
if l_block_trial_key_resp.keys != None: # we had a response
l_block_trial_loop.addData('l_block_trial_key_resp.rt', l_block_trial_key_resp.rt)
thisExp.nextEntry()
#------Prepare to start Routine "vreminder"-------
t = 0
vreminderClock.reset() # clock
frameN = -1
# update component parameters for each repeat
vreminder_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
vreminder_key_resp.status = NOT_STARTED
# keep track of which components have finished
vreminderComponents = []
vreminderComponents.append(vreminder_sound)
for thisComponent in vreminderComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "vreminder"-------
continueRoutine = True
while continueRoutine:
# get current time
t = vreminderClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *vreminder_image* updates
if t >= 0.0 and vreminder_image.status == NOT_STARTED:
# keep track of start time/frame for later
vreminder_image.tStart = t # underestimates by a little under one frame
vreminder_image.frameNStart = frameN # exact frame index
vreminder_image.draw()
# *vreminder_text* updates
if t >= 0.0 and vreminder_text.status == NOT_STARTED:
# keep track of start time/frame for later
vreminder_text.tStart = t # underestimates by a little under one frame
vreminder_text.frameNStart = frameN # exact frame index
vreminder_text.draw()
# start/stop vreminder_sound
if t >= 0.0 and vreminder_sound.status == NOT_STARTED:
# keep track of start time/frame for later
vreminder_sound.tStart = t # underestimates by a little under one frame
vreminder_sound.frameNStart = frameN # exact frame index
vreminder_sound.play() # start the sound (it finishes automatically)
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in vreminderComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "vreminder"-------
for thisComponent in vreminderComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
vreminder_sound.stop() #ensure sound has stopped at end of routine
# the Routine "vreminder" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
v_block_trials = data.TrialHandler(nReps=1, method='sequential',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions(u'visual_run1_6.xlsx'),
seed=None, name='v_block_trials')
thisExp.addLoop(v_block_trials) # add the loop to the experiment
thisV_block_trial = v_block_trials.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisV_block_trial.rgb)
if thisV_block_trial != None:
for paramName in thisV_block_trial.keys():
exec(paramName + '= thisV_block_trial.' + paramName)
for thisV_block_trial in v_block_trials:
currentLoop = v_block_trials
# abbreviate parameter names if possible (e.g. rgb = thisV_block_trial.rgb)
if thisV_block_trial != None:
for paramName in thisV_block_trial.keys():
exec(paramName + '= thisV_block_trial.' + paramName)
#------Prepare to start Routine "v_block_trial"-------
t = 0
v_block_trialClock.reset() # clock
frameN = -1
routineTimer.add(1.000000)
# update component parameters for each repeat
v_block_trial_image.setImage(image)
v_block_trial_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
v_block_trial_key_resp.status = NOT_STARTED
# keep track of which components have finished
v_block_trialComponents = []
v_block_trialComponents.append(v_block_trial_image)
v_block_trialComponents.append(v_block_trial_key_resp)
v_block_trialComponents.append(blank_image)
for thisComponent in v_block_trialComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "v_block_trial"-------
continueRoutine = True
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = v_block_trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *v_block_trial_image* updates
if t >= 0.0 and v_block_trial_image.status == NOT_STARTED:
# keep track of start time/frame for later
v_block_trial_image.tStart = t # underestimates by a little under one frame
v_block_trial_image.frameNStart = frameN # exact frame index
v_block_trial_image.setAutoDraw(True)
if v_block_trial_image.status == STARTED and t >= (0.0 + (0.8-win.monitorFramePeriod*0.75)): #most of one frame period left
v_block_trial_image.setAutoDraw(False)
# *v_block_trial_key_resp* updates
if t >= 0.0 and v_block_trial_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
v_block_trial_key_resp.tStart = t # underestimates by a little under one frame
v_block_trial_key_resp.frameNStart = frameN # exact frame index
v_block_trial_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(v_block_trial_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if v_block_trial_key_resp.status == STARTED and t >= (0.0 + (1.0-win.monitorFramePeriod*0.75)): #most of one frame period left
v_block_trial_key_resp.status = STOPPED
if v_block_trial_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_1', '1','num_4','num_2','num_3','2','3','4'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
v_block_trial_key_resp.keys = theseKeys[-1] # just the last key pressed
v_block_trial_key_resp.rt = v_block_trial_key_resp.clock.getTime()
# *blank_image* updates
if t >= 0.8 and blank_image.status == NOT_STARTED:
# keep track of start time/frame for later
blank_image.tStart = t # underestimates by a little under one frame
blank_image.frameNStart = frameN # exact frame index
blank_image.setAutoDraw(True)
if blank_image.status == STARTED and t >= (0.8 + (0.2-win.monitorFramePeriod*0.75)): #most of one frame period left
blank_image.setAutoDraw(False)
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in v_block_trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "v_block_trial"-------
for thisComponent in v_block_trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if v_block_trial_key_resp.keys in ['', [], None]: # No response was made
v_block_trial_key_resp.keys=None
# store data for v_block_trials (TrialHandler)
v_block_trials.addData('v_block_trial_key_resp.keys',v_block_trial_key_resp.keys)
if v_block_trial_key_resp.keys != None: # we had a response
v_block_trials.addData('v_block_trial_key_resp.rt', v_block_trial_key_resp.rt)
thisExp.nextEntry()
#------Prepare to start Routine "lreminder"-------
t = 0
lreminderClock.reset() # clock
frameN = -1
# update component parameters for each repeat
lreminder_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
lreminder_key_resp.status = NOT_STARTED
# keep track of which components have finished
lreminderComponents = []
lreminderComponents.append(lreminder_sound)
for thisComponent in lreminderComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "lreminder"-------
continueRoutine = True
while continueRoutine:
# get current time
t = lreminderClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *lreminder_image* updates
if t >= 0.0 and lreminder_image.status == NOT_STARTED:
# keep track of start time/frame for later
lreminder_image.tStart = t # underestimates by a little under one frame
lreminder_image.frameNStart = frameN # exact frame index
lreminder_image.draw()
# *lreminder_text* updates
if t >= 0.0 and lreminder_text.status == NOT_STARTED:
# keep track of start time/frame for later
lreminder_text.tStart = t # underestimates by a little under one frame
lreminder_text.frameNStart = frameN # exact frame index
lreminder_text.draw()
# start/stop lreminder_sound
if t >= 0.0 and lreminder_sound.status == NOT_STARTED:
# keep track of start time/frame for later
lreminder_sound.tStart = t # underestimates by a little under one frame
lreminder_sound.frameNStart = frameN # exact frame index
lreminder_sound.play() # start the sound (it finishes automatically)
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in lreminderComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "lreminder"-------
for thisComponent in lreminderComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
lreminder_sound.stop() #ensure sound has stopped at end of routine
# the Routine "lreminder" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
l_block_trial_loop = data.TrialHandler(nReps=1, method='sequential',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions(u'visual_run1_7.xlsx'),
seed=None, name='l_block_trial_loop')
thisExp.addLoop(l_block_trial_loop) # add the loop to the experiment
thisL_block_trial_loop = l_block_trial_loop.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisL_block_trial_loop.rgb)
if thisL_block_trial_loop != None:
for paramName in thisL_block_trial_loop.keys():
exec(paramName + '= thisL_block_trial_loop.' + paramName)
for thisL_block_trial_loop in l_block_trial_loop:
currentLoop = l_block_trial_loop
# abbreviate parameter names if possible (e.g. rgb = thisL_block_trial_loop.rgb)
if thisL_block_trial_loop != None:
for paramName in thisL_block_trial_loop.keys():
exec(paramName + '= thisL_block_trial_loop.' + paramName)
#------Prepare to start Routine "l_block_trial"-------
t = 0
l_block_trialClock.reset() # clock
frameN = -1
routineTimer.add(1.000000)
# update component parameters for each repeat
l_block_trial_image.setImage(image)
l_block_trial_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
l_block_trial_key_resp.status = NOT_STARTED
# keep track of which components have finished
l_block_trialComponents = []
l_block_trialComponents.append(l_block_trial_image)
l_block_trialComponents.append(l_block_trial_blank)
l_block_trialComponents.append(l_block_trial_key_resp)
for thisComponent in l_block_trialComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "l_block_trial"-------
continueRoutine = True
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = l_block_trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *l_block_trial_image* updates
if t >= 0.0 and l_block_trial_image.status == NOT_STARTED:
# keep track of start time/frame for later
l_block_trial_image.tStart = t # underestimates by a little under one frame
l_block_trial_image.frameNStart = frameN # exact frame index
l_block_trial_image.setAutoDraw(True)
if l_block_trial_image.status == STARTED and t >= (0.0 + (0.8-win.monitorFramePeriod*0.75)): #most of one frame period left
l_block_trial_image.setAutoDraw(False)
# *l_block_trial_blank* updates
if t >= 0.79 and l_block_trial_blank.status == NOT_STARTED:
# keep track of start time/frame for later
l_block_trial_blank.tStart = t # underestimates by a little under one frame
l_block_trial_blank.frameNStart = frameN # exact frame index
l_block_trial_blank.setAutoDraw(True)
if l_block_trial_blank.status == STARTED and t >= (0.79 + (0.21-win.monitorFramePeriod*0.75)): #most of one frame period left
l_block_trial_blank.setAutoDraw(False)
# *l_block_trial_key_resp* updates
if t >= 0.0 and l_block_trial_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
l_block_trial_key_resp.tStart = t # underestimates by a little under one frame
l_block_trial_key_resp.frameNStart = frameN # exact frame index
l_block_trial_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(l_block_trial_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if l_block_trial_key_resp.status == STARTED and t >= (0.0 + (1-win.monitorFramePeriod*0.75)): #most of one frame period left
l_block_trial_key_resp.status = STOPPED
if l_block_trial_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_1', '1','num_4','num_2','num_3','2','3','4'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
l_block_trial_key_resp.keys = theseKeys[-1] # just the last key pressed
l_block_trial_key_resp.rt = l_block_trial_key_resp.clock.getTime()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in l_block_trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "l_block_trial"-------
for thisComponent in l_block_trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if l_block_trial_key_resp.keys in ['', [], None]: # No response was made
l_block_trial_key_resp.keys=None
# store data for l_block_trial_loop (TrialHandler)
l_block_trial_loop.addData('l_block_trial_key_resp.keys',l_block_trial_key_resp.keys)
if l_block_trial_key_resp.keys != None: # we had a response
l_block_trial_loop.addData('l_block_trial_key_resp.rt', l_block_trial_key_resp.rt)
thisExp.nextEntry()
#------Prepare to start Routine "vreminder"-------
t = 0
vreminderClock.reset() # clock
frameN = -1
# update component parameters for each repeat
vreminder_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
vreminder_key_resp.status = NOT_STARTED
# keep track of which components have finished
vreminderComponents = []
vreminderComponents.append(vreminder_sound)
for thisComponent in vreminderComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "vreminder"-------
continueRoutine = True
while continueRoutine:
# get current time
t = vreminderClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *vreminder_image* updates
if t >= 0.0 and vreminder_image.status == NOT_STARTED:
# keep track of start time/frame for later
vreminder_image.tStart = t # underestimates by a little under one frame
vreminder_image.frameNStart = frameN # exact frame index
vreminder_image.draw()
# *vreminder_text* updates
if t >= 0.0 and vreminder_text.status == NOT_STARTED:
# keep track of start time/frame for later
vreminder_text.tStart = t # underestimates by a little under one frame
vreminder_text.frameNStart = frameN # exact frame index
vreminder_text.draw()
# start/stop vreminder_sound
if t >= 0.0 and vreminder_sound.status == NOT_STARTED:
# keep track of start time/frame for later
vreminder_sound.tStart = t # underestimates by a little under one frame
vreminder_sound.frameNStart = frameN # exact frame index
vreminder_sound.play() # start the sound (it finishes automatically)
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in vreminderComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "vreminder"-------
for thisComponent in vreminderComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
vreminder_sound.stop() #ensure sound has stopped at end of routine
# the Routine "vreminder" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
v_block_trials = data.TrialHandler(nReps=1, method='sequential',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions(u'visual_run1_8.xlsx'),
seed=None, name='v_block_trials')
thisExp.addLoop(v_block_trials) # add the loop to the experiment
thisV_block_trial = v_block_trials.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisV_block_trial.rgb)
if thisV_block_trial != None:
for paramName in thisV_block_trial.keys():
exec(paramName + '= thisV_block_trial.' + paramName)
for thisV_block_trial in v_block_trials:
currentLoop = v_block_trials
# abbreviate parameter names if possible (e.g. rgb = thisV_block_trial.rgb)
if thisV_block_trial != None:
for paramName in thisV_block_trial.keys():
exec(paramName + '= thisV_block_trial.' + paramName)
#------Prepare to start Routine "v_block_trial"-------
t = 0
v_block_trialClock.reset() # clock
frameN = -1
routineTimer.add(1.000000)
# update component parameters for each repeat
v_block_trial_image.setImage(image)
v_block_trial_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
v_block_trial_key_resp.status = NOT_STARTED
# keep track of which components have finished
v_block_trialComponents = []
v_block_trialComponents.append(v_block_trial_image)
v_block_trialComponents.append(v_block_trial_key_resp)
v_block_trialComponents.append(blank_image)
for thisComponent in v_block_trialComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "v_block_trial"-------
continueRoutine = True
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = v_block_trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *v_block_trial_image* updates
if t >= 0.0 and v_block_trial_image.status == NOT_STARTED:
# keep track of start time/frame for later
v_block_trial_image.tStart = t # underestimates by a little under one frame
v_block_trial_image.frameNStart = frameN # exact frame index
v_block_trial_image.setAutoDraw(True)
if v_block_trial_image.status == STARTED and t >= (0.0 + (0.8-win.monitorFramePeriod*0.75)): #most of one frame period left
v_block_trial_image.setAutoDraw(False)
# *v_block_trial_key_resp* updates
if t >= 0.0 and v_block_trial_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
v_block_trial_key_resp.tStart = t # underestimates by a little under one frame
v_block_trial_key_resp.frameNStart = frameN # exact frame index
v_block_trial_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(v_block_trial_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if v_block_trial_key_resp.status == STARTED and t >= (0.0 + (1.0-win.monitorFramePeriod*0.75)): #most of one frame period left
v_block_trial_key_resp.status = STOPPED
if v_block_trial_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_1', '1','num_4','num_2','num_3','2','3','4'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
v_block_trial_key_resp.keys = theseKeys[-1] # just the last key pressed
v_block_trial_key_resp.rt = v_block_trial_key_resp.clock.getTime()
# *blank_image* updates
if t >= 0.8 and blank_image.status == NOT_STARTED:
# keep track of start time/frame for later
blank_image.tStart = t # underestimates by a little under one frame
blank_image.frameNStart = frameN # exact frame index
blank_image.setAutoDraw(True)
if blank_image.status == STARTED and t >= (0.8 + (0.2-win.monitorFramePeriod*0.75)): #most of one frame period left
blank_image.setAutoDraw(False)
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in v_block_trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "v_block_trial"-------
for thisComponent in v_block_trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if v_block_trial_key_resp.keys in ['', [], None]: # No response was made
v_block_trial_key_resp.keys=None
# store data for v_block_trials (TrialHandler)
v_block_trials.addData('v_block_trial_key_resp.keys',v_block_trial_key_resp.keys)
if v_block_trial_key_resp.keys != None: # we had a response
v_block_trials.addData('v_block_trial_key_resp.rt', v_block_trial_key_resp.rt)
thisExp.nextEntry()
#------Prepare to start Routine "lreminder"-------
t = 0
lreminderClock.reset() # clock
frameN = -1
# update component parameters for each repeat
lreminder_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
lreminder_key_resp.status = NOT_STARTED
# keep track of which components have finished
lreminderComponents = []
lreminderComponents.append(lreminder_sound)
for thisComponent in lreminderComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "lreminder"-------
continueRoutine = True
while continueRoutine:
# get current time
t = lreminderClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *lreminder_image* updates
if t >= 0.0 and lreminder_image.status == NOT_STARTED:
# keep track of start time/frame for later
lreminder_image.tStart = t # underestimates by a little under one frame
lreminder_image.frameNStart = frameN # exact frame index
lreminder_image.draw()
# *lreminder_text* updates
if t >= 0.0 and lreminder_text.status == NOT_STARTED:
# keep track of start time/frame for later
lreminder_text.tStart = t # underestimates by a little under one frame
lreminder_text.frameNStart = frameN # exact frame index
lreminder_text.draw()
# start/stop lreminder_sound
if t >= 0.0 and lreminder_sound.status == NOT_STARTED:
# keep track of start time/frame for later
lreminder_sound.tStart = t # underestimates by a little under one frame
lreminder_sound.frameNStart = frameN # exact frame index
lreminder_sound.play() # start the sound (it finishes automatically)
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in lreminderComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "lreminder"-------
for thisComponent in lreminderComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
lreminder_sound.stop() #ensure sound has stopped at end of routine
# the Routine "lreminder" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
l_block_trial_loop = data.TrialHandler(nReps=1, method='sequential',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions(u'visual_run1_9.xlsx'),
seed=None, name='l_block_trial_loop')
thisExp.addLoop(l_block_trial_loop) # add the loop to the experiment
thisL_block_trial_loop = l_block_trial_loop.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisL_block_trial_loop.rgb)
if thisL_block_trial_loop != None:
for paramName in thisL_block_trial_loop.keys():
exec(paramName + '= thisL_block_trial_loop.' + paramName)
for thisL_block_trial_loop in l_block_trial_loop:
currentLoop = l_block_trial_loop
# abbreviate parameter names if possible (e.g. rgb = thisL_block_trial_loop.rgb)
if thisL_block_trial_loop != None:
for paramName in thisL_block_trial_loop.keys():
exec(paramName + '= thisL_block_trial_loop.' + paramName)
#------Prepare to start Routine "l_block_trial"-------
t = 0
l_block_trialClock.reset() # clock
frameN = -1
routineTimer.add(1.000000)
# update component parameters for each repeat
l_block_trial_image.setImage(image)
l_block_trial_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
l_block_trial_key_resp.status = NOT_STARTED
# keep track of which components have finished
l_block_trialComponents = []
l_block_trialComponents.append(l_block_trial_image)
l_block_trialComponents.append(l_block_trial_blank)
l_block_trialComponents.append(l_block_trial_key_resp)
for thisComponent in l_block_trialComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "l_block_trial"-------
continueRoutine = True
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = l_block_trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *l_block_trial_image* updates
if t >= 0.0 and l_block_trial_image.status == NOT_STARTED:
# keep track of start time/frame for later
l_block_trial_image.tStart = t # underestimates by a little under one frame
l_block_trial_image.frameNStart = frameN # exact frame index
l_block_trial_image.setAutoDraw(True)
if l_block_trial_image.status == STARTED and t >= (0.0 + (0.8-win.monitorFramePeriod*0.75)): #most of one frame period left
l_block_trial_image.setAutoDraw(False)
# *l_block_trial_blank* updates
if t >= 0.79 and l_block_trial_blank.status == NOT_STARTED:
# keep track of start time/frame for later
l_block_trial_blank.tStart = t # underestimates by a little under one frame
l_block_trial_blank.frameNStart = frameN # exact frame index
l_block_trial_blank.setAutoDraw(True)
if l_block_trial_blank.status == STARTED and t >= (0.79 + (0.21-win.monitorFramePeriod*0.75)): #most of one frame period left
l_block_trial_blank.setAutoDraw(False)
# *l_block_trial_key_resp* updates
if t >= 0.0 and l_block_trial_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
l_block_trial_key_resp.tStart = t # underestimates by a little under one frame
l_block_trial_key_resp.frameNStart = frameN # exact frame index
l_block_trial_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(l_block_trial_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if l_block_trial_key_resp.status == STARTED and t >= (0.0 + (1-win.monitorFramePeriod*0.75)): #most of one frame period left
l_block_trial_key_resp.status = STOPPED
if l_block_trial_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_1', '1','num_4','num_2','num_3','2','3','4'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
l_block_trial_key_resp.keys = theseKeys[-1] # just the last key pressed
l_block_trial_key_resp.rt = l_block_trial_key_resp.clock.getTime()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in l_block_trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "l_block_trial"-------
for thisComponent in l_block_trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if l_block_trial_key_resp.keys in ['', [], None]: # No response was made
l_block_trial_key_resp.keys=None
# store data for l_block_trial_loop (TrialHandler)
l_block_trial_loop.addData('l_block_trial_key_resp.keys',l_block_trial_key_resp.keys)
if l_block_trial_key_resp.keys != None: # we had a response
l_block_trial_loop.addData('l_block_trial_key_resp.rt', l_block_trial_key_resp.rt)
thisExp.nextEntry()
#------Prepare to start Routine "vreminder"-------
t = 0
vreminderClock.reset() # clock
frameN = -1
# update component parameters for each repeat
vreminder_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
vreminder_key_resp.status = NOT_STARTED
# keep track of which components have finished
vreminderComponents = []
vreminderComponents.append(vreminder_sound)
for thisComponent in vreminderComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "vreminder"-------
continueRoutine = True
while continueRoutine:
# get current time
t = vreminderClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *vreminder_image* updates
if t >= 0.0 and vreminder_image.status == NOT_STARTED:
# keep track of start time/frame for later
vreminder_image.tStart = t # underestimates by a little under one frame
vreminder_image.frameNStart = frameN # exact frame index
vreminder_image.draw()
# *vreminder_text* updates
if t >= 0.0 and vreminder_text.status == NOT_STARTED:
# keep track of start time/frame for later
vreminder_text.tStart = t # underestimates by a little under one frame
vreminder_text.frameNStart = frameN # exact frame index
vreminder_text.draw()
# start/stop vreminder_sound
if t >= 0.0 and vreminder_sound.status == NOT_STARTED:
# keep track of start time/frame for later
vreminder_sound.tStart = t # underestimates by a little under one frame
vreminder_sound.frameNStart = frameN # exact frame index
vreminder_sound.play() # start the sound (it finishes automatically)
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in vreminderComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "vreminder"-------
for thisComponent in vreminderComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
vreminder_sound.stop() #ensure sound has stopped at end of routine
# the Routine "vreminder" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
v_block_trials = data.TrialHandler(nReps=1, method='sequential',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions(u'visual_run1_10.xlsx'),
seed=None, name='v_block_trials')
thisExp.addLoop(v_block_trials) # add the loop to the experiment
thisV_block_trial = v_block_trials.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisV_block_trial.rgb)
if thisV_block_trial != None:
for paramName in thisV_block_trial.keys():
exec(paramName + '= thisV_block_trial.' + paramName)
for thisV_block_trial in v_block_trials:
currentLoop = v_block_trials
# abbreviate parameter names if possible (e.g. rgb = thisV_block_trial.rgb)
if thisV_block_trial != None:
for paramName in thisV_block_trial.keys():
exec(paramName + '= thisV_block_trial.' + paramName)
#------Prepare to start Routine "v_block_trial"-------
t = 0
v_block_trialClock.reset() # clock
frameN = -1
routineTimer.add(1.000000)
# update component parameters for each repeat
v_block_trial_image.setImage(image)
v_block_trial_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
v_block_trial_key_resp.status = NOT_STARTED
# keep track of which components have finished
v_block_trialComponents = []
v_block_trialComponents.append(v_block_trial_image)
v_block_trialComponents.append(v_block_trial_key_resp)
v_block_trialComponents.append(blank_image)
for thisComponent in v_block_trialComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "v_block_trial"-------
continueRoutine = True
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = v_block_trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *v_block_trial_image* updates
if t >= 0.0 and v_block_trial_image.status == NOT_STARTED:
# keep track of start time/frame for later
v_block_trial_image.tStart = t # underestimates by a little under one frame
v_block_trial_image.frameNStart = frameN # exact frame index
v_block_trial_image.setAutoDraw(True)
if v_block_trial_image.status == STARTED and t >= (0.0 + (0.8-win.monitorFramePeriod*0.75)): #most of one frame period left
v_block_trial_image.setAutoDraw(False)
# *v_block_trial_key_resp* updates
if t >= 0.0 and v_block_trial_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
v_block_trial_key_resp.tStart = t # underestimates by a little under one frame
v_block_trial_key_resp.frameNStart = frameN # exact frame index
v_block_trial_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(v_block_trial_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if v_block_trial_key_resp.status == STARTED and t >= (0.0 + (1.0-win.monitorFramePeriod*0.75)): #most of one frame period left
v_block_trial_key_resp.status = STOPPED
if v_block_trial_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_1', '1','num_4','num_2','num_3','2','3','4'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
v_block_trial_key_resp.keys = theseKeys[-1] # just the last key pressed
v_block_trial_key_resp.rt = v_block_trial_key_resp.clock.getTime()
# *blank_image* updates
if t >= 0.8 and blank_image.status == NOT_STARTED:
# keep track of start time/frame for later
blank_image.tStart = t # underestimates by a little under one frame
blank_image.frameNStart = frameN # exact frame index
blank_image.setAutoDraw(True)
if blank_image.status == STARTED and t >= (0.8 + (0.2-win.monitorFramePeriod*0.75)): #most of one frame period left
blank_image.setAutoDraw(False)
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in v_block_trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "v_block_trial"-------
for thisComponent in v_block_trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if v_block_trial_key_resp.keys in ['', [], None]: # No response was made
v_block_trial_key_resp.keys=None
# store data for v_block_trials (TrialHandler)
v_block_trials.addData('v_block_trial_key_resp.keys',v_block_trial_key_resp.keys)
if v_block_trial_key_resp.keys != None: # we had a response
v_block_trials.addData('v_block_trial_key_resp.rt', v_block_trial_key_resp.rt)
thisExp.nextEntry()
#------Prepare to start Routine "lreminder"-------
t = 0
lreminderClock.reset() # clock
frameN = -1
# update component parameters for each repeat
lreminder_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
lreminder_key_resp.status = NOT_STARTED
# keep track of which components have finished
lreminderComponents = []
lreminderComponents.append(lreminder_sound)
for thisComponent in lreminderComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "lreminder"-------
continueRoutine = True
while continueRoutine:
# get current time
t = lreminderClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *lreminder_image* updates
if t >= 0.0 and lreminder_image.status == NOT_STARTED:
# keep track of start time/frame for later
lreminder_image.tStart = t # underestimates by a little under one frame
lreminder_image.frameNStart = frameN # exact frame index
lreminder_image.draw()
# *lreminder_text* updates
if t >= 0.0 and lreminder_text.status == NOT_STARTED:
# keep track of start time/frame for later
lreminder_text.tStart = t # underestimates by a little under one frame
lreminder_text.frameNStart = frameN # exact frame index
lreminder_text.draw()
# start/stop lreminder_sound
if t >= 0.0 and lreminder_sound.status == NOT_STARTED:
# keep track of start time/frame for later
lreminder_sound.tStart = t # underestimates by a little under one frame
lreminder_sound.frameNStart = frameN # exact frame index
lreminder_sound.play() # start the sound (it finishes automatically)
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in lreminderComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "lreminder"-------
for thisComponent in lreminderComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
lreminder_sound.stop() #ensure sound has stopped at end of routine
# the Routine "lreminder" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
l_block_trial_loop = data.TrialHandler(nReps=1, method='sequential',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions(u'visual_run1_11.xlsx'),
seed=None, name='l_block_trial_loop')
thisExp.addLoop(l_block_trial_loop) # add the loop to the experiment
thisL_block_trial_loop = l_block_trial_loop.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisL_block_trial_loop.rgb)
if thisL_block_trial_loop != None:
for paramName in thisL_block_trial_loop.keys():
exec(paramName + '= thisL_block_trial_loop.' + paramName)
for thisL_block_trial_loop in l_block_trial_loop:
currentLoop = l_block_trial_loop
# abbreviate parameter names if possible (e.g. rgb = thisL_block_trial_loop.rgb)
if thisL_block_trial_loop != None:
for paramName in thisL_block_trial_loop.keys():
exec(paramName + '= thisL_block_trial_loop.' + paramName)
#------Prepare to start Routine "l_block_trial"-------
t = 0
l_block_trialClock.reset() # clock
frameN = -1
routineTimer.add(1.000000)
# update component parameters for each repeat
l_block_trial_image.setImage(image)
l_block_trial_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
l_block_trial_key_resp.status = NOT_STARTED
# keep track of which components have finished
l_block_trialComponents = []
l_block_trialComponents.append(l_block_trial_image)
l_block_trialComponents.append(l_block_trial_blank)
l_block_trialComponents.append(l_block_trial_key_resp)
for thisComponent in l_block_trialComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "l_block_trial"-------
continueRoutine = True
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = l_block_trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *l_block_trial_image* updates
if t >= 0.0 and l_block_trial_image.status == NOT_STARTED:
# keep track of start time/frame for later
l_block_trial_image.tStart = t # underestimates by a little under one frame
l_block_trial_image.frameNStart = frameN # exact frame index
l_block_trial_image.setAutoDraw(True)
if l_block_trial_image.status == STARTED and t >= (0.0 + (0.8-win.monitorFramePeriod*0.75)): #most of one frame period left
l_block_trial_image.setAutoDraw(False)
# *l_block_trial_blank* updates
if t >= 0.79 and l_block_trial_blank.status == NOT_STARTED:
# keep track of start time/frame for later
l_block_trial_blank.tStart = t # underestimates by a little under one frame
l_block_trial_blank.frameNStart = frameN # exact frame index
l_block_trial_blank.setAutoDraw(True)
if l_block_trial_blank.status == STARTED and t >= (0.79 + (0.21-win.monitorFramePeriod*0.75)): #most of one frame period left
l_block_trial_blank.setAutoDraw(False)
# *l_block_trial_key_resp* updates
if t >= 0.0 and l_block_trial_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
l_block_trial_key_resp.tStart = t # underestimates by a little under one frame
l_block_trial_key_resp.frameNStart = frameN # exact frame index
l_block_trial_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(l_block_trial_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if l_block_trial_key_resp.status == STARTED and t >= (0.0 + (1-win.monitorFramePeriod*0.75)): #most of one frame period left
l_block_trial_key_resp.status = STOPPED
if l_block_trial_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_1', '1','num_4','num_2','num_3','2','3','4'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
l_block_trial_key_resp.keys = theseKeys[-1] # just the last key pressed
l_block_trial_key_resp.rt = l_block_trial_key_resp.clock.getTime()
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in l_block_trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "l_block_trial"-------
for thisComponent in l_block_trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if l_block_trial_key_resp.keys in ['', [], None]: # No response was made
l_block_trial_key_resp.keys=None
# store data for l_block_trial_loop (TrialHandler)
l_block_trial_loop.addData('l_block_trial_key_resp.keys',l_block_trial_key_resp.keys)
if l_block_trial_key_resp.keys != None: # we had a response
l_block_trial_loop.addData('l_block_trial_key_resp.rt', l_block_trial_key_resp.rt)
thisExp.nextEntry()
#------Prepare to start Routine "vreminder"-------
t = 0
vreminderClock.reset() # clock
frameN = -1
# update component parameters for each repeat
vreminder_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
vreminder_key_resp.status = NOT_STARTED
# keep track of which components have finished
vreminderComponents = []
vreminderComponents.append(vreminder_sound)
for thisComponent in vreminderComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "vreminder"-------
continueRoutine = True
while continueRoutine:
# get current time
t = vreminderClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *vreminder_image* updates
if t >= 0.0 and vreminder_image.status == NOT_STARTED:
# keep track of start time/frame for later
vreminder_image.tStart = t # underestimates by a little under one frame
vreminder_image.frameNStart = frameN # exact frame index
vreminder_image.draw()
# *vreminder_text* updates
if t >= 0.0 and vreminder_text.status == NOT_STARTED:
# keep track of start time/frame for later
vreminder_text.tStart = t # underestimates by a little under one frame
vreminder_text.frameNStart = frameN # exact frame index
vreminder_text.draw()
# start/stop vreminder_sound
if t >= 0.0 and vreminder_sound.status == NOT_STARTED:
# keep track of start time/frame for later
vreminder_sound.tStart = t # underestimates by a little under one frame
vreminder_sound.frameNStart = frameN # exact frame index
vreminder_sound.play() # start the sound (it finishes automatically)
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in vreminderComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "vreminder"-------
for thisComponent in vreminderComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
vreminder_sound.stop() #ensure sound has stopped at end of routine
# the Routine "vreminder" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
v_block_trials = data.TrialHandler(nReps=1, method='sequential',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions(u'visual_run1_12.xlsx'),
seed=None, name='v_block_trials')
thisExp.addLoop(v_block_trials) # add the loop to the experiment
thisV_block_trial = v_block_trials.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisV_block_trial.rgb)
if thisV_block_trial != None:
for paramName in thisV_block_trial.keys():
exec(paramName + '= thisV_block_trial.' + paramName)
for thisV_block_trial in v_block_trials:
currentLoop = v_block_trials
# abbreviate parameter names if possible (e.g. rgb = thisV_block_trial.rgb)
if thisV_block_trial != None:
for paramName in thisV_block_trial.keys():
exec(paramName + '= thisV_block_trial.' + paramName)
#------Prepare to start Routine "v_block_trial"-------
t = 0
v_block_trialClock.reset() # clock
frameN = -1
routineTimer.add(1.000000)
# update component parameters for each repeat
v_block_trial_image.setImage(image)
v_block_trial_key_resp = event.BuilderKeyResponse() # create an object of type KeyResponse
v_block_trial_key_resp.status = NOT_STARTED
# keep track of which components have finished
v_block_trialComponents = []
v_block_trialComponents.append(v_block_trial_image)
v_block_trialComponents.append(v_block_trial_key_resp)
v_block_trialComponents.append(blank_image)
for thisComponent in v_block_trialComponents:
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
#-------Start Routine "v_block_trial"-------
continueRoutine = True
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = v_block_trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *v_block_trial_image* updates
if t >= 0.0 and v_block_trial_image.status == NOT_STARTED:
# keep track of start time/frame for later
v_block_trial_image.tStart = t # underestimates by a little under one frame
v_block_trial_image.frameNStart = frameN # exact frame index
v_block_trial_image.setAutoDraw(True)
if v_block_trial_image.status == STARTED and t >= (0.0 + (0.8-win.monitorFramePeriod*0.75)): #most of one frame period left
v_block_trial_image.setAutoDraw(False)
# *v_block_trial_key_resp* updates
if t >= 0.0 and v_block_trial_key_resp.status == NOT_STARTED:
# keep track of start time/frame for later
v_block_trial_key_resp.tStart = t # underestimates by a little under one frame
v_block_trial_key_resp.frameNStart = frameN # exact frame index
v_block_trial_key_resp.status = STARTED
# keyboard checking is just starting
win.callOnFlip(v_block_trial_key_resp.clock.reset) # t=0 on next screen flip
event.clearEvents(eventType='keyboard')
if v_block_trial_key_resp.status == STARTED and t >= (0.0 + (1.0-win.monitorFramePeriod*0.75)): #most of one frame period left
v_block_trial_key_resp.status = STOPPED
if v_block_trial_key_resp.status == STARTED:
theseKeys = event.getKeys(keyList=['num_add', '+', 'num_1', '1','num_4','num_2','num_3','2','3','4'])
# check for quit:
if "escape" in theseKeys:
endExpNow = True
if len(theseKeys) > 0: # at least one key was pressed
v_block_trial_key_resp.keys = theseKeys[-1] # just the last key pressed
v_block_trial_key_resp.rt = v_block_trial_key_resp.clock.getTime()
# *blank_image* updates
if t >= 0.8 and blank_image.status == NOT_STARTED:
# keep track of start time/frame for later
blank_image.tStart = t # underestimates by a little under one frame
blank_image.frameNStart = frameN # exact frame index
blank_image.setAutoDraw(True)
if blank_image.status == STARTED and t >= (0.8 + (0.2-win.monitorFramePeriod*0.75)): #most of one frame period left
blank_image.setAutoDraw(False)
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in v_block_trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
#-------Ending Routine "v_block_trial"-------
for thisComponent in v_block_trialComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
# check responses
if v_block_trial_key_resp.keys in ['', [], None]: # No response was made
v_block_trial_key_resp.keys=None
# store data for v_block_trials (TrialHandler)
v_block_trials.addData('v_block_trial_key_resp.keys',v_block_trial_key_resp.keys)
if v_block_trial_key_resp.keys != None: # we had a response
v_block_trials.addData('v_block_trial_key_resp.rt', v_block_trial_key_resp.rt)
thisExp.nextEntry()
# these shouldn't be strictly necessary (should auto-save)
thisExp.saveAsWideText(filename+'.csv')
thisExp.saveAsPickle(filename)
logging.flush()
# make sure everything is closed down
thisExp.abort() # or data files will save again on exit
win.close()
core.quit()
| [
"[email protected]"
]
| |
5b9b16d3f350192012b8a8d223b402d78902b5c8 | fbbe424559f64e9a94116a07eaaa555a01b0a7bb | /Spacy/source2.7/spacy/lang/id/tokenizer_exceptions.py | 3bba57e4cbd39db28e872da9aa8cb1051962e24a | [
"MIT"
]
| permissive | ryfeus/lambda-packs | 6544adb4dec19b8e71d75c24d8ed789b785b0369 | cabf6e4f1970dc14302f87414f170de19944bac2 | refs/heads/master | 2022-12-07T16:18:52.475504 | 2022-11-29T13:35:35 | 2022-11-29T13:35:35 | 71,386,735 | 1,283 | 263 | MIT | 2022-11-26T05:02:14 | 2016-10-19T18:22:39 | Python | UTF-8 | Python | false | false | 1,722 | py | # coding: utf8
from __future__ import unicode_literals
import regex as re
from ._tokenizer_exceptions_list import ID_BASE_EXCEPTIONS
from ..tokenizer_exceptions import URL_PATTERN
from ...symbols import ORTH
_exc = {}
for orth in ID_BASE_EXCEPTIONS:
_exc[orth] = [{ORTH: orth}]
orth_title = orth.title()
_exc[orth_title] = [{ORTH: orth_title}]
orth_caps = orth.upper()
_exc[orth_caps] = [{ORTH: orth_caps}]
orth_lower = orth.lower()
_exc[orth_lower] = [{ORTH: orth_lower}]
if '-' in orth:
orth_title = '-'.join([part.title() for part in orth.split('-')])
_exc[orth_title] = [{ORTH: orth_title}]
orth_caps = '-'.join([part.upper() for part in orth.split('-')])
_exc[orth_caps] = [{ORTH: orth_caps}]
for orth in [
"'d", "a.m.", "Adm.", "Bros.", "co.", "Co.", "Corp.", "D.C.", "Dr.", "e.g.",
"E.g.", "E.G.", "Gen.", "Gov.", "i.e.", "I.e.", "I.E.", "Inc.", "Jr.",
"Ltd.", "Md.", "Messrs.", "Mo.", "Mont.", "Mr.", "Mrs.", "Ms.", "p.m.",
"Ph.D.", "Rep.", "Rev.", "Sen.", "St.", "vs.",
"B.A.", "B.Ch.E.", "B.Sc.", "Dr.", "Dra.", "Drs.", "Hj.", "Ka.", "Kp.",
"M.Ag.", "M.Hum.", "M.Kes,", "M.Kom.", "M.M.", "M.P.", "M.Pd.", "M.Sc.",
"M.Si.", "M.Sn.", "M.T.", "M.Th.", "No.", "Pjs.", "Plt.", "R.A.", "S.Ag.",
"S.E.", "S.H.", "S.Hut.", "S.K.M.", "S.Kedg.", "S.Kedh.", "S.Kom.",
"S.Pd.", "S.Pol.", "S.Psi.", "S.S.", "S.Sos.", "S.T.", "S.Tekp.", "S.Th.",
"a.l.", "a.n.", "a.s.", "b.d.", "d.a.", "d.l.", "d/h", "dkk.", "dll.",
"dr.", "drh.", "ds.", "dsb.", "dst.", "faks.", "fax.", "hlm.", "i/o",
"n.b.", "p.p." "pjs.", "s.d.", "tel.", "u.p.",
]:
_exc[orth] = [{ORTH: orth}]
TOKENIZER_EXCEPTIONS = _exc
| [
"[email protected]"
]
| |
5506648e5839441f8042bcb8beadaa3a9c211d93 | ef0220b65d3ac860d33d77b6a8eef74d2df3b81b | /mod10/flask/venv/bin/wheel-3.8 | e1b86e3bb58c1e5edfcfb27af7a4be942b7afe75 | []
| no_license | safwanvk/py | b9922df211fe7f4356be3221c639cdd6d3dcf2d8 | 52482a90fb39f15846987607f1988c50f07e758b | refs/heads/master | 2022-12-12T12:21:51.335733 | 2020-09-07T08:21:49 | 2020-09-07T08:21:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 241 | 8 | #!/home/safwan/xanthron/mod10/flask/venv/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from wheel.cli import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"[email protected]"
]
| |
d4a8da26e252085f122e551fb397f2999bd76eec | 17c9bdd9f740f5549c2ae95c22d0f42907af6bf4 | /beautiful.py | 74906ad989a3ec033998b8f2093f95878b9d36ae | []
| no_license | vim-scripts/beautiful-pastebin | e8a2510aaeff1d782f7fd7552c5475edc1f9a380 | 854f3373b0b8e52a697e9856486906311efd138c | refs/heads/master | 2021-01-13T02:14:33.027077 | 2011-06-08T00:00:00 | 2011-06-23T22:51:24 | 1,865,838 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 646 | py | #File: beautiful.py
#Author : Aman Agarwal <[email protected]>
#License : MIT
#version 1.0
#Dependencies : BeautifulSoup <http://www.crummy.com/software/BeautifulSoup/>
#
import urllib2
from BeautifulSoup import BeautifulSoup
import sys
data=urllib2.urlopen(sys.argv[1]).read();
soup = BeautifulSoup(''.join(data))
code=soup('div', {'id' : 'code_frame'})
soup = BeautifulSoup(''.join(str(code[0]).strip()))
code_text = soup.div.div
text=''.join(BeautifulSoup(str(code_text).strip()).findAll(text=True))
code_for_vim = BeautifulSoup(str(text).strip(), convertEntities=BeautifulSoup.HTML_ENTITIES)
print code_for_vim
#print sys.argv[1]
| [
"[email protected]"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.