blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 616 | content_id stringlengths 40 40 | detected_licenses listlengths 0 69 | license_type stringclasses 2
values | repo_name stringlengths 5 118 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 63 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 2.91k 686M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 220
values | src_encoding stringclasses 30
values | language stringclasses 1
value | is_vendor bool 2
classes | is_generated bool 2
classes | length_bytes int64 2 10.3M | extension stringclasses 257
values | content stringlengths 2 10.3M | authors listlengths 1 1 | author_id stringlengths 0 212 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0f1f7254fd96bb713e5593186bd1750f7efe4b14 | a35ec35378575cba8effee630e8ce6afcf599e6a | /undertalealpacapy.py | e684f1aa179cd025106e809ef9d0839e57e447b5 | [] | no_license | AlpacaPlayz/codecraftlab-python | 382881402e0b64d18728ec83d5c50de48da885b7 | a9f96bdb174951c0e9cf95ad38c5ea99dc58bc37 | refs/heads/master | 2020-04-10T22:45:05.456915 | 2017-03-01T22:55:23 | 2017-03-01T22:55:23 | 68,246,527 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,330 | py | import pygame
import random
from pygame.locals import *
class Player(pygame.sprite.Sprite):
## def __init__(self):
## super(Player, self).__init__()
## self.surf = pygame.Surface((75, 75))
## self.surf.fill((255, 255, 255))
## self.rect = self.surf.get_rect()
def __init__(self):
super(Player, self).__init__()
self.image = pygame.image.load('SOULL.jpg').convert()
self.image.set_colorkey((255, 255, 255), RLEACCEL)
self.rect = self.image.get_rect()
self.rect.top = 400 # y
self.rect.left = 350 # x
def update(self, pressed_keys):
if pressed_keys[K_UP]:
self.rect.move_ip(0, -1)
if pressed_keys[K_DOWN]:
self.rect.move_ip(0, 1)
if pressed_keys[K_LEFT]:
self.rect.move_ip(-1, 0)
if pressed_keys[K_RIGHT]:
self.rect.move_ip(1, 0)
if self.rect.left < 0:
self.rect.left = 0
if self.rect.top < 0:
self.rect.top = 0
if self.rect.right > 800:
self.rect.right = 800
if self.rect.bottom > 600:
self.rect.bottom = 600
class Opponent(pygame.sprite.Sprite):
def __init__(self):
super(Opponent, self).__init__()
self.image = pygame.image.load('FIRE.jpg').convert()
self.image.set_colorkey((255, 255, 255), RLEACCEL)
self.rect = self.image.get_rect(
center=(random.randint(300, 500), random.randint(300, 301))
)
self.speed = random.randint(1,1)
def update(self):
self.rect.move_ip(0, self.speed)
if self.rect.bottom > 600:
self.rect.bottom = 600
#initialize pygame
pygame.init()
#create screen
screen = pygame.display.set_mode((800, 600))
player = Player()
opponent = Opponent()
background = pygame.Surface(screen.get_size())
background.fill((0,0,0))
players = pygame.sprite.Group()
opponents = pygame.sprite.Group()
all_sprites = pygame.sprite.Group()
all_sprites.add(player)
ADDOPPONENT = pygame.USEREVENT + 1
pygame.time.set_timer(ADDOPPONENT, 400)
#create main loop
running = True
while running:
for event in pygame.event.get():
if event.type == KEYDOWN:
#and if that key happens to be the escape key
if event.key == K_ESCAPE:
running = False
elif event.type == QUIT:
running = False
elif(event.type == ADDOPPONENT):
new_opponent = Opponent()
opponents.add(new_opponent)
all_sprites.add(new_opponent)
screen.blit(background, (0,0))
pressed_keys = pygame.key.get_pressed()
player.update(pressed_keys)
opponents.update()
for entity in all_sprites:
screen.blit(entity.image, entity.rect)
pygame.display.flip()
if pygame.sprite.spritecollideany(player, opponents):
player.kill()
#end pygame
pygame.quit()
| [
"noreply@github.com"
] | AlpacaPlayz.noreply@github.com |
eb7ea1fa5ef9b6d3b9b41c49fb051d256edeeb0e | 41fd80f9ccc72a17c2db16b7019312a87d3181e8 | /zhang_local/pdep/network3396_1.py | cf88478cfa806d77eb44abbf591e5dc37db88509 | [] | no_license | aberdeendinius/n-heptane | 1510e6704d87283043357aec36317fdb4a2a0c34 | 1806622607f74495477ef3fd772908d94cff04d9 | refs/heads/master | 2020-05-26T02:06:49.084015 | 2019-07-01T15:12:44 | 2019-07-01T15:12:44 | 188,069,618 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 117,871 | py | species(
label = '[CH2]C=COC([CH2])[O](6739)',
structure = SMILES('[CH2]C=COC([CH2])[O]'),
E0 = (167.03,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,1380,1390,370,380,2900,435,2995,3025,975,1000,1300,1375,400,500,1630,1680,345.431,345.433,345.461,345.467],'cm^-1')),
HinderedRotor(inertia=(0.00141228,'amu*angstrom^2'), symmetry=1, barrier=(0.119627,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.293775,'amu*angstrom^2'), symmetry=1, barrier=(24.8776,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.293655,'amu*angstrom^2'), symmetry=1, barrier=(24.8775,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.293655,'amu*angstrom^2'), symmetry=1, barrier=(24.8768,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 4,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.387926,0.0686611,-5.02055e-05,8.33984e-09,3.6305e-12,20228.6,28.3893], Tmin=(100,'K'), Tmax=(1000.22,'K')), NASAPolynomial(coeffs=[18.6967,0.0174656,-6.4574e-06,1.19483e-09,-8.59121e-14,15464.4,-65.4513], Tmin=(1000.22,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(167.03,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(315.95,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + radical(CCOJ) + radical(CJCO) + radical(Allyl_P)"""),
)
species(
label = 'C=C[O](594)',
structure = SMILES('C=C[O]'),
E0 = (-25.1807,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2950,3100,1380,975,1025,1650,3010,987.5,1337.5,450,1655,180],'cm^-1')),
],
spinMultiplicity = 2,
opticalIsomers = 1,
molecularWeight = (43.0446,'amu'),
collisionModel = TransportData(shapeIndex=2, epsilon=(3625.12,'J/mol'), sigma=(3.97,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=2.0, comment="""GRI-Mech"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[3.34719,0.00128739,5.39982e-05,-7.84138e-08,3.24083e-11,-2992.85,8.97297], Tmin=(100,'K'), Tmax=(914.213,'K')), NASAPolynomial(coeffs=[11.726,-0.0014735,2.90737e-06,-5.96989e-10,3.70275e-14,-5941.49,-38.4465], Tmin=(914.213,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-25.1807,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(133.032,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-(Cds-Cd)H) + group(Cds-CdsOsH) + group(Cds-CdsHH) + radical(C=COJ)"""),
)
species(
label = 'C=CC=O(5269)',
structure = SMILES('C=CC=O'),
E0 = (-81.3387,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2782.5,750,1395,475,1775,1000,3010,987.5,1337.5,450,1655,2950,3100,1380,975,1025,1650],'cm^-1')),
HinderedRotor(inertia=(0.873408,'amu*angstrom^2'), symmetry=1, barrier=(20.0814,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (56.0633,'amu'),
collisionModel = TransportData(shapeIndex=2, epsilon=(3136.31,'J/mol'), sigma=(5.14154,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0, comment="""Epsilon & sigma estimated with Tc=489.88 K, Pc=52.36 bar (from Joback method)"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.9738,0.0193269,-1.02836e-06,-7.40922e-09,2.6466e-12,-9743.32,12.1361], Tmin=(100,'K'), Tmax=(1315.19,'K')), NASAPolynomial(coeffs=[7.40832,0.0154746,-7.62321e-06,1.50372e-09,-1.06406e-13,-11743,-13.6408], Tmin=(1315.19,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-81.3387,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(178.761,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cd-Cd(CO)H) + group(Cds-O2d(Cds-Cds)H) + group(Cds-CdsHH)"""),
)
species(
label = '[CH2][CH]C1OC([CH2])O1(14763)',
structure = SMILES('[CH2][CH]C1OC([CH2])O1'),
E0 = (267.885,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.33428,0.0452373,2.3349e-06,-3.41814e-08,1.53732e-11,32326.8,28.8875], Tmin=(100,'K'), Tmax=(1036.19,'K')), NASAPolynomial(coeffs=[14.7399,0.0236938,-1.02052e-05,2.01969e-09,-1.48637e-13,27927,-44.0881], Tmin=(1036.19,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(267.885,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(320.107,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(O2s-CsCs) + group(Cs-CsCsHH) + group(Cs-CsOsOsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-CsHHH) + ring(Cyclobutane) + radical(RCCJ) + radical(CCJCO) + radical(CJCO)"""),
)
species(
label = '[CH2][CH]C1CC([O])O1(14764)',
structure = SMILES('[CH2][CH]C1CC([O])O1'),
E0 = (274.1,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.80415,0.0398087,6.90936e-06,-3.65842e-08,1.76597e-11,33053.5,27.1087], Tmin=(100,'K'), Tmax=(911.702,'K')), NASAPolynomial(coeffs=[9.85898,0.0267524,-8.27181e-06,1.32544e-09,-8.69102e-14,30658.7,-16.0855], Tmin=(911.702,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(274.1,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(324.264,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(O2s-CsH) + group(Cs-CsCsOsH) + group(Cs-CsCsHH) + group(Cs-CsCsHH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + ring(Oxetane) + radical(CCJCO) + radical(CCOJ) + radical(RCCJ)"""),
)
species(
label = 'H(8)',
structure = SMILES('[H]'),
E0 = (211.805,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (1.00794,'amu'),
collisionModel = TransportData(shapeIndex=0, epsilon=(1205.6,'J/mol'), sigma=(2.05,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0.0, comment="""GRI-Mech"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.5,9.24385e-15,-1.3678e-17,6.66185e-21,-1.00107e-24,25474.2,-0.444973], Tmin=(100,'K'), Tmax=(3459.6,'K')), NASAPolynomial(coeffs=[2.5,9.20456e-12,-3.58608e-15,6.15199e-19,-3.92042e-23,25474.2,-0.444973], Tmin=(3459.6,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(211.805,'kJ/mol'), Cp0=(20.7862,'J/(mol*K)'), CpInf=(20.7862,'J/(mol*K)'), label="""H""", comment="""Thermo library: primaryThermoLibrary"""),
)
species(
label = '[CH2]C(=O)O[CH]C=C(12761)',
structure = SMILES('[CH2]C(=O)O[CH]C=C'),
E0 = (-31.4003,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3000,3100,440,815,1455,1000,3025,407.5,1350,352.5,3010,987.5,1337.5,450,1655,2950,3100,1380,975,1025,1650,200,800,933.333,1066.67,1200,1333.33,1466.67,1600],'cm^-1')),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (98.0999,'amu'),
collisionModel = TransportData(shapeIndex=2, epsilon=(3501.16,'J/mol'), sigma=(5.80453,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0, comment="""Epsilon & sigma estimated with Tc=546.87 K, Pc=40.62 bar (from Joback method)"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.92643,0.045461,-2.48199e-05,6.03209e-09,-5.67048e-13,-3702.22,26.6594], Tmin=(100,'K'), Tmax=(2430.73,'K')), NASAPolynomial(coeffs=[18.7682,0.0177467,-7.71766e-06,1.34157e-09,-8.46359e-14,-11889.9,-69.5513], Tmin=(2430.73,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-31.4003,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(291.007,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-O2d)) + group(Cs-(Cds-Cds)OsHH) + group(Cs-(Cds-O2d)HHH) + group(Cds-CdsCsH) + group(Cds-OdCsOs) + group(Cds-CdsHH) + radical(CJCO) + radical(C=CCJ(O)C)"""),
)
species(
label = '[CH2]C([O])OC=C=C(14765)',
structure = SMILES('[CH2]C([O])OC=C=C'),
E0 = (192.135,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2950,3100,1380,975,1025,1650,540,610,2055,3010,987.5,1337.5,450,1655,1380,1390,370,380,2900,435,3000,3100,440,815,1455,1000,256.466,256.585,256.602,256.733],'cm^-1')),
HinderedRotor(inertia=(0.471919,'amu*angstrom^2'), symmetry=1, barrier=(22.0371,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.471661,'amu*angstrom^2'), symmetry=1, barrier=(22.0362,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.471818,'amu*angstrom^2'), symmetry=1, barrier=(22.0366,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (98.0999,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.290657,0.0723323,-7.27596e-05,3.59159e-08,-6.87423e-12,23249.9,27.5162], Tmin=(100,'K'), Tmax=(1282.97,'K')), NASAPolynomial(coeffs=[18.733,0.0148328,-5.53274e-06,9.82586e-10,-6.70505e-14,18517.7,-66.0526], Tmin=(1282.97,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(192.135,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(295.164,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cds-CdsOsH) + group(Cds-CdsHH) + group(Cdd-CdsCds) + radical(CCOJ) + radical(CJCO)"""),
)
species(
label = 'CH2(T)(28)',
structure = SMILES('[CH2]'),
E0 = (381.37,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1066.91,2790.99,3622.37],'cm^-1')),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (14.0266,'amu'),
collisionModel = TransportData(shapeIndex=2, epsilon=(1197.29,'J/mol'), sigma=(3.8,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0.0, comment="""GRI-Mech"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[4.01192,-0.000154979,3.26298e-06,-2.40422e-09,5.69497e-13,45867.7,0.5332], Tmin=(100,'K'), Tmax=(1104.58,'K')), NASAPolynomial(coeffs=[3.14983,0.00296674,-9.76056e-07,1.54115e-10,-9.50338e-15,46058.1,4.77808], Tmin=(1104.58,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(381.37,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(58.2013,'J/(mol*K)'), label="""CH2(T)""", comment="""Thermo library: primaryThermoLibrary"""),
)
species(
label = 'C=C[CH]OC=O(6118)',
structure = SMILES('C=C[CH]OC=O'),
E0 = (-187.12,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3025,407.5,1350,352.5,2782.5,750,1395,475,1775,1000,3010,987.5,1337.5,450,1655,2950,3100,1380,975,1025,1650,510.201,511.893,512],'cm^-1')),
HinderedRotor(inertia=(0.000649394,'amu*angstrom^2'), symmetry=1, barrier=(0.119627,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.000644744,'amu*angstrom^2'), symmetry=1, barrier=(0.119627,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.273992,'amu*angstrom^2'), symmetry=1, barrier=(50.5657,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 2,
opticalIsomers = 1,
molecularWeight = (85.0813,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.41277,0.0299172,-1.27966e-06,-1.11624e-08,3.99297e-12,-22444.3,21.2798], Tmin=(100,'K'), Tmax=(1287.52,'K')), NASAPolynomial(coeffs=[7.96996,0.025828,-1.18657e-05,2.267e-09,-1.57909e-13,-24967.3,-11.1758], Tmin=(1287.52,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-187.12,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(245.277,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-O2d)) + group(Cs-(Cds-Cds)OsHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + group(Cds-OdOsH) + radical(C=CCJ(O)C)"""),
)
species(
label = 'O(T)(63)',
structure = SMILES('[O]'),
E0 = (243.034,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (15.9994,'amu'),
collisionModel = TransportData(shapeIndex=0, epsilon=(665.16,'J/mol'), sigma=(2.75,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0.0, comment="""GRI-Mech"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.5,9.24385e-15,-1.3678e-17,6.66185e-21,-1.00107e-24,29230.2,4.09104], Tmin=(100,'K'), Tmax=(3459.6,'K')), NASAPolynomial(coeffs=[2.5,9.20456e-12,-3.58608e-15,6.15199e-19,-3.92042e-23,29230.2,4.09104], Tmin=(3459.6,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(243.034,'kJ/mol'), Cp0=(20.7862,'J/(mol*K)'), CpInf=(20.7862,'J/(mol*K)'), label="""O(T)""", comment="""Thermo library: primaryThermoLibrary"""),
)
species(
label = 'C=C[CH]OC=C(6503)',
structure = SMILES('C=C[CH]OC=C'),
E0 = (34.9912,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3025,407.5,1350,352.5,2995,3025,975,1000,1300,1375,400,500,1630,1680,2950,3000,3050,3100,1330,1430,900,1050,1000,1050,1600,1700,370.801,371.2,371.495,371.793],'cm^-1')),
HinderedRotor(inertia=(0.268082,'amu*angstrom^2'), symmetry=1, barrier=(26.1652,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.267439,'amu*angstrom^2'), symmetry=1, barrier=(26.1658,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.268082,'amu*angstrom^2'), symmetry=1, barrier=(26.1667,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 2,
opticalIsomers = 1,
molecularWeight = (83.1085,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.43522,0.0419787,9.71864e-06,-4.81203e-08,2.2894e-11,4313.9,21.927], Tmin=(100,'K'), Tmax=(956.054,'K')), NASAPolynomial(coeffs=[16.1489,0.0158741,-4.95219e-06,8.99655e-10,-6.74629e-14,-119.9,-56.871], Tmin=(956.054,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(34.9912,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(295.164,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(Cs-(Cds-Cds)OsHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + group(Cds-CdsHH) + group(Cds-CdsHH) + radical(C=CCJ(O)C)"""),
)
species(
label = '[CH2]C=C[O](5266)',
structure = SMILES('[CH2]C=C[O]'),
E0 = (90.2929,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2995,3025,975,1000,1300,1375,400,500,1630,1680,3000,3100,440,815,1455,1000,180],'cm^-1')),
HinderedRotor(inertia=(1.57685,'amu*angstrom^2'), symmetry=1, barrier=(36.2549,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (56.0633,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.69019,0.0144913,4.15491e-05,-7.27602e-08,3.14101e-11,10920.2,13.4175], Tmin=(100,'K'), Tmax=(922.751,'K')), NASAPolynomial(coeffs=[14.044,0.00224417,1.35973e-06,-3.04875e-10,1.62832e-14,7250.86,-48.974], Tmin=(922.751,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(90.2929,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(178.761,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-(Cds-Cd)H) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + radical(Allyl_P) + radical(C=COJ)"""),
)
species(
label = '[CH2]C=CO[C]([CH2])O(13880)',
structure = SMILES('[CH2]C=CO[C]([CH2])O'),
E0 = (146.571,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,360,370,350,3615,1277.5,1000,2995,3025,975,1000,1300,1375,400,500,1630,1680,200,800,1600],'cm^-1')),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 4,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.122663,0.0714593,-4.61269e-05,-7.08398e-09,1.22239e-11,17780.7,29.861], Tmin=(100,'K'), Tmax=(940.853,'K')), NASAPolynomial(coeffs=[22.7691,0.00944933,-1.90215e-06,2.94372e-10,-2.38937e-14,12002.5,-86.0753], Tmin=(940.853,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(146.571,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(311.793,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + radical(Allyl_P) + radical(Cs_P) + radical(CJCO)"""),
)
species(
label = '[CH2][CH][CH]OC(C)=O(13711)',
structure = SMILES('[CH2][CH][CH]OC(C)=O'),
E0 = (111.808,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2800,2850,1350,1500,750,1050,1375,1000,3000,3100,440,815,1455,1000,3000,3050,390,425,1340,1360,335,370,200,800,933.333,1066.67,1200,1333.33,1466.67,1600],'cm^-1')),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 4,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.21494,0.0581538,-4.43402e-05,1.7401e-08,-2.80505e-12,13550,30.5294], Tmin=(100,'K'), Tmax=(1437.1,'K')), NASAPolynomial(coeffs=[12.5612,0.0265727,-1.13767e-05,2.10931e-09,-1.44872e-13,10288.8,-28.3243], Tmin=(1437.1,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(111.808,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(311.793,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-O2d)) + group(Cs-CsCsHH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-(Cds-O2d)HHH) + group(Cds-OdCsOs) + radical(CCsJOC(O)) + radical(RCCJ) + radical(CCJCO)"""),
)
species(
label = '[CH2]C([O])OC=[C]C(14766)',
structure = SMILES('[CH2]C([O])OC=[C]C'),
E0 = (253.372,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.572198,0.0731758,-7.44235e-05,3.89679e-08,-8.13909e-12,30599,27.9229], Tmin=(100,'K'), Tmax=(1157.98,'K')), NASAPolynomial(coeffs=[14.9725,0.0234336,-9.99037e-06,1.87333e-09,-1.30736e-13,27263.9,-43.6629], Tmin=(1157.98,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(253.372,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(315.95,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + radical(CCOJ) + radical(Cds_S) + radical(CJCO)"""),
)
species(
label = '[CH2]C([O])O[C]=CC(14767)',
structure = SMILES('[CH2]C([O])O[C]=CC'),
E0 = (255.275,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.00905,0.0679662,-6.78973e-05,3.68765e-08,-8.27517e-12,30808.4,29.016], Tmin=(100,'K'), Tmax=(1059.77,'K')), NASAPolynomial(coeffs=[11.2191,0.0294291,-1.33517e-05,2.56353e-09,-1.80707e-13,28644.3,-20.8344], Tmin=(1059.77,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(255.275,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(315.95,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + radical(CJCO) + radical(C=CJO) + radical(CCOJ)"""),
)
species(
label = '[CH2]C=[C]OC([CH2])O(13882)',
structure = SMILES('[CH2]C=[C]OC([CH2])O'),
E0 = (181.069,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,1685,370,3010,987.5,1337.5,450,1655,3615,1277.5,1000,1380,1390,370,380,2900,435,200,800,1600],'cm^-1')),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 4,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.268225,0.0728027,-6.36654e-05,2.0856e-08,-1.42733e-13,21920.2,31.0859], Tmin=(100,'K'), Tmax=(983.917,'K')), NASAPolynomial(coeffs=[19.0185,0.0155601,-5.34007e-06,9.46972e-10,-6.67773e-14,17311.5,-63.7391], Tmin=(983.917,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(181.069,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(311.793,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + radical(C=CJO) + radical(CJCO) + radical(Allyl_P)"""),
)
species(
label = '[CH2]C=[C]OC(C)[O](13713)',
structure = SMILES('[CH2]C=[C]OC(C)[O]'),
E0 = (195.185,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3000,3100,440,815,1455,1000,2750,2800,2850,1350,1500,750,1050,1375,1000,1380,1390,370,380,2900,435,1685,370,3010,987.5,1337.5,450,1655,335.667,335.669,335.67,335.676],'cm^-1')),
HinderedRotor(inertia=(0.00149611,'amu*angstrom^2'), symmetry=1, barrier=(0.119627,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.00149611,'amu*angstrom^2'), symmetry=1, barrier=(0.119627,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.312455,'amu*angstrom^2'), symmetry=1, barrier=(24.9826,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.312455,'amu*angstrom^2'), symmetry=1, barrier=(24.9826,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 4,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.795547,0.0646031,-5.46214e-05,2.35074e-08,-4.06167e-12,23595.5,29.4259], Tmin=(100,'K'), Tmax=(1378.52,'K')), NASAPolynomial(coeffs=[15.0184,0.0233326,-9.71351e-06,1.78924e-09,-1.22956e-13,19674.2,-43.7569], Tmin=(1378.52,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(195.185,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(315.95,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + radical(CCOJ) + radical(C=CJO) + radical(Allyl_P)"""),
)
species(
label = '[CH2][C]=COC([CH2])O(13881)',
structure = SMILES('[CH2][C]=COC([CH2])O'),
E0 = (179.166,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,1685,370,3010,987.5,1337.5,450,1655,3615,1277.5,1000,1380,1390,370,380,2900,435,200,800,1600],'cm^-1')),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 4,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.616201,0.0830424,-8.67012e-05,4.29567e-08,-7.98602e-12,21730.7,31.6161], Tmin=(100,'K'), Tmax=(1478.21,'K')), NASAPolynomial(coeffs=[23.5091,0.00829358,-1.24465e-06,8.38728e-11,-2.5273e-15,15632.5,-90.7051], Tmin=(1478.21,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(179.166,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(311.793,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + radical(Cds_S) + radical(CJCO) + radical(Allyl_P)"""),
)
species(
label = '[CH2][C]=COC(C)[O](13712)',
structure = SMILES('[CH2][C]=COC(C)[O]'),
E0 = (193.283,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3000,3100,440,815,1455,1000,2750,2800,2850,1350,1500,750,1050,1375,1000,1380,1390,370,380,2900,435,1685,370,3010,987.5,1337.5,450,1655,421.589,421.607,421.608,421.638],'cm^-1')),
HinderedRotor(inertia=(0.134851,'amu*angstrom^2'), symmetry=1, barrier=(17.0113,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.134875,'amu*angstrom^2'), symmetry=1, barrier=(17.0114,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.134863,'amu*angstrom^2'), symmetry=1, barrier=(17.0111,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.948558,'amu*angstrom^2'), symmetry=1, barrier=(119.627,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 4,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.467111,0.0685096,-5.65876e-05,1.9878e-08,-1.63265e-12,23381.6,27.947], Tmin=(100,'K'), Tmax=(1072.15,'K')), NASAPolynomial(coeffs=[17.1054,0.0200675,-7.88678e-06,1.45493e-09,-1.02104e-13,19030.3,-57.1363], Tmin=(1072.15,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(193.283,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(315.95,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + radical(CCOJ) + radical(Cds_S) + radical(Allyl_P)"""),
)
species(
label = '[CH2]C(=O)O[CH][CH]C(2373)',
structure = SMILES('[CH2]C(=O)O[CH][CH]C'),
E0 = (118.151,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2800,2850,1350,1500,750,1050,1375,1000,3000,3100,440,815,1455,1000,3000,3050,390,425,1340,1360,335,370,200,800,933.333,1066.67,1200,1333.33,1466.67,1600],'cm^-1')),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 4,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.05771,0.0622505,-5.25325e-05,2.31575e-08,-4.17591e-12,14318.1,29.9403], Tmin=(100,'K'), Tmax=(1305.63,'K')), NASAPolynomial(coeffs=[12.7673,0.0263763,-1.13177e-05,2.1128e-09,-1.46306e-13,11260.4,-29.6745], Tmin=(1305.63,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(118.151,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(311.793,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-O2d)) + group(Cs-CsCsHH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-(Cds-O2d)HHH) + group(Cds-OdCsOs) + radical(CJCO) + radical(CCJCO) + radical(CCsJOC(O))"""),
)
species(
label = '[CH2][CH][O](719)',
structure = SMILES('[CH2][CH][O]'),
E0 = (361.021,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3025,407.5,1350,352.5,3000,3100,440,815,1455,1000,1878.99],'cm^-1')),
HinderedRotor(inertia=(0.232981,'amu*angstrom^2'), symmetry=1, barrier=(5.35669,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 4,
opticalIsomers = 1,
molecularWeight = (43.0446,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[3.03639,0.0272039,-5.17476e-05,5.40082e-08,-2.05139e-11,43449.8,12.3205], Tmin=(100,'K'), Tmax=(879.689,'K')), NASAPolynomial(coeffs=[2.12305,0.0164211,-7.89343e-06,1.47303e-09,-9.88046e-14,44188.4,19.8945], Tmin=(879.689,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(361.021,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(128.874,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + radical(CCsJOH) + radical(CJCO) + radical(CCOJ)"""),
)
species(
label = '[CH2]C([O])[O](696)',
structure = SMILES('[CH2]C([O])[O]'),
E0 = (206.197,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1380,1390,370,380,2900,435,3000,3100,440,815,1455,1000,1958.04,1961.92],'cm^-1')),
HinderedRotor(inertia=(0.117955,'amu*angstrom^2'), symmetry=1, barrier=(2.71202,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 4,
opticalIsomers = 1,
molecularWeight = (59.044,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.98521,0.0307914,-6.07535e-05,7.05352e-08,-2.93746e-11,24828.1,16.2791], Tmin=(100,'K'), Tmax=(843.556,'K')), NASAPolynomial(coeffs=[-0.613396,0.0260677,-1.36113e-05,2.66003e-09,-1.84546e-13,26210.4,37.6228], Tmin=(843.556,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(206.197,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(153.818,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + radical(CJCO) + radical(CCOJ) + radical(CCOJ)"""),
)
species(
label = '[CH]C=C(8168)',
structure = SMILES('[CH]C=C'),
E0 = (376.808,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2950,3100,1380,975,1025,1650,3010,987.5,1337.5,450,1655,192.655,193.544,193.915],'cm^-1')),
HinderedRotor(inertia=(1.88068,'amu*angstrom^2'), symmetry=1, barrier=(50.3487,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (40.0639,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[3.32096,0.00806329,3.46645e-05,-4.52343e-08,1.64854e-11,45350.1,10.7121], Tmin=(100,'K'), Tmax=(975.253,'K')), NASAPolynomial(coeffs=[5.21066,0.0176207,-6.65616e-06,1.20944e-09,-8.49962e-14,44158.4,-2.57721], Tmin=(975.253,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(376.808,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(153.818,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(AllylJ2_triplet)"""),
)
species(
label = '[CH2][CH][CH]OC([CH2])=O(6733)',
structure = SMILES('[CH2][CH][CH]OC([CH2])=O'),
E0 = (323.397,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3000,3050,390,425,1340,1360,335,370,3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,200,800,933.333,1066.67,1200,1333.33,1466.67,1600],'cm^-1')),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 5,
opticalIsomers = 1,
molecularWeight = (98.0999,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.21376,0.0615629,-5.79898e-05,2.90132e-08,-5.95561e-12,38995.8,31.8624], Tmin=(100,'K'), Tmax=(1155.91,'K')), NASAPolynomial(coeffs=[11.5721,0.0257181,-1.14747e-05,2.18576e-09,-1.53391e-13,36601.1,-19.6115], Tmin=(1155.91,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(323.397,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(286.849,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-O2d)) + group(Cs-CsCsHH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-(Cds-O2d)HHH) + group(Cds-OdCsOs) + radical(CJCO) + radical(CCJCO) + radical(CCsJOC(O)) + radical(RCCJ)"""),
)
species(
label = '[CH2][C]=COC([CH2])[O](14446)',
structure = SMILES('[CH2][C]=COC([CH2])[O]'),
E0 = (404.872,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1685,370,3010,987.5,1337.5,450,1655,1380,1390,370,380,2900,435,3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,361.684,361.685,361.685,361.686],'cm^-1')),
HinderedRotor(inertia=(0.00128862,'amu*angstrom^2'), symmetry=1, barrier=(0.119627,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.257862,'amu*angstrom^2'), symmetry=1, barrier=(23.9367,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.257852,'amu*angstrom^2'), symmetry=1, barrier=(23.9366,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.257853,'amu*angstrom^2'), symmetry=1, barrier=(23.9367,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 5,
opticalIsomers = 1,
molecularWeight = (98.0999,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.312231,0.0737246,-7.63938e-05,3.90439e-08,-7.75853e-12,48833.8,29.1369], Tmin=(100,'K'), Tmax=(1234.55,'K')), NASAPolynomial(coeffs=[18.1576,0.0159045,-6.14082e-06,1.10646e-09,-7.60284e-14,44427.7,-60.7165], Tmin=(1234.55,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(404.872,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(291.007,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + radical(Allyl_P) + radical(CCOJ) + radical(CJCO) + radical(Cds_S)"""),
)
species(
label = '[CH2]C=[C]OC([CH2])[O](14444)',
structure = SMILES('[CH2]C=[C]OC([CH2])[O]'),
E0 = (406.774,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1685,370,3010,987.5,1337.5,450,1655,1380,1390,370,380,2900,435,3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,275.914,955.375,958.201,962.459],'cm^-1')),
HinderedRotor(inertia=(0.108252,'amu*angstrom^2'), symmetry=1, barrier=(5.67964,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.417623,'amu*angstrom^2'), symmetry=1, barrier=(19.0051,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.529444,'amu*angstrom^2'), symmetry=1, barrier=(25.7345,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.416024,'amu*angstrom^2'), symmetry=1, barrier=(19.0025,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 5,
opticalIsomers = 1,
molecularWeight = (98.0999,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.815125,0.0678236,-6.78165e-05,3.47292e-08,-7.10159e-12,49040.2,29.9867], Tmin=(100,'K'), Tmax=(1180.27,'K')), NASAPolynomial(coeffs=[14.3518,0.0219467,-9.51138e-06,1.79576e-09,-1.25732e-13,45844.8,-37.5637], Tmin=(1180.27,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(406.774,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(291.007,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + radical(Allyl_P) + radical(CCOJ) + radical(C=CJO) + radical(CJCO)"""),
)
species(
label = '[CH2]C([O])OC1[CH]C1(12058)',
structure = SMILES('[CH2]C([O])OC1[CH]C1'),
E0 = (289.766,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2883.33,3016.67,3150,900,966.667,1033.33,1100,1380,1390,370,380,2900,435,3000,3100,440,815,1455,1000,300,800,800,800,800,800,800,1600,1600,1600,1600,1600,1600],'cm^-1')),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 4,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.15566,0.0541371,-3.31902e-05,7.5488e-09,-2.53015e-15,34960.1,29.814], Tmin=(100,'K'), Tmax=(1272.35,'K')), NASAPolynomial(coeffs=[13.6507,0.0249566,-1.06971e-05,2.00275e-09,-1.3879e-13,30962.8,-36.6901], Tmin=(1272.35,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(289.766,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(320.107,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(O2s-CsH) + group(Cs-CsCsOsH) + group(Cs-CsCsHH) + group(Cs-CsCsHH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + ring(Cyclopropane) + radical(CJCO) + radical(CCJCO) + radical(CCOJ)"""),
)
species(
label = '[CH2]C1[CH]OC([CH2])O1(14679)',
structure = SMILES('[CH2]C1[CH]OC([CH2])O1'),
E0 = (194.31,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.640573,0.0799435,-9.49296e-05,5.39865e-08,-1.0948e-11,23556.4,26.2961], Tmin=(100,'K'), Tmax=(1504.04,'K')), NASAPolynomial(coeffs=[18.2218,0.00467628,5.17077e-06,-1.47995e-09,1.16105e-13,20721.7,-62.9639], Tmin=(1504.04,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(194.31,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(324.264,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(O2s-CsCs) + group(Cs-CsCsOsH) + group(Cs-CsOsOsH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + ring(1,3-Dioxolane) + radical(CCsJOCs) + radical(CJCO) + radical(CJC(C)OC)"""),
)
species(
label = '[CH2]C1[CH]OC([O])C1(14768)',
structure = SMILES('[CH2]C1[CH]OC([O])C1'),
E0 = (179.629,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.72997,0.0398491,1.5466e-05,-5.40631e-08,2.70102e-11,21695.7,22.1897], Tmin=(100,'K'), Tmax=(866.457,'K')), NASAPolynomial(coeffs=[11.9439,0.0220722,-4.61331e-06,5.14547e-10,-2.6949e-14,18823.1,-31.9854], Tmin=(866.457,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(179.629,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(328.422,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(O2s-CsH) + group(Cs-CsCsCsH) + group(Cs-CsCsHH) + group(Cs-CsOsOsH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + ring(Tetrahydrofuran) + radical(CCOJ) + radical(Isobutyl) + radical(CCsJOCs)"""),
)
species(
label = 'C=C[CH]OC(=C)O(13875)',
structure = SMILES('C=C[CH]OC(=C)O'),
E0 = (-122.146,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3025,407.5,1350,352.5,2950,3000,3050,3100,1330,1430,900,1050,1000,1050,1600,1700,3010,987.5,1337.5,450,1655,3615,1277.5,1000,350,440,435,1725,267.891,267.892,267.896,267.899],'cm^-1')),
HinderedRotor(inertia=(0.00234882,'amu*angstrom^2'), symmetry=1, barrier=(0.119627,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.475001,'amu*angstrom^2'), symmetry=1, barrier=(24.1908,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.475002,'amu*angstrom^2'), symmetry=1, barrier=(24.1907,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.475025,'amu*angstrom^2'), symmetry=1, barrier=(24.1907,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 2,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.486889,0.0683947,-5.60492e-05,1.75959e-08,-1.71501e-13,-14556.4,25.1179], Tmin=(100,'K'), Tmax=(1012.33,'K')), NASAPolynomial(coeffs=[17.1856,0.0188209,-6.90594e-06,1.24305e-09,-8.69112e-14,-18778.1,-59.8009], Tmin=(1012.33,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-122.146,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(315.95,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-(Cds-Cd)H) + group(Cs-(Cds-Cds)OsHH) + group(Cds-CdsCsH) + group(Cds-CdsCsCs) + group(Cds-CdsHH) + group(Cds-CdsHH) + radical(C=CCJ(O)C)"""),
)
species(
label = 'C=C[CH]OC(C)=O(12663)',
structure = SMILES('C=C[CH]OC(C)=O'),
E0 = (-242.989,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2800,2850,1350,1500,750,1050,1375,1000,2950,3100,1380,975,1025,1650,3010,987.5,1337.5,450,1655,3025,407.5,1350,352.5,200,800,933.333,1066.67,1200,1333.33,1466.67,1600],'cm^-1')),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 2,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.83242,0.0429711,-1.36453e-05,-3.11715e-09,1.76562e-12,-29143.1,25.6846], Tmin=(100,'K'), Tmax=(1451.82,'K')), NASAPolynomial(coeffs=[10.3014,0.0314055,-1.38542e-05,2.56181e-09,-1.73661e-13,-32842.4,-22.6021], Tmin=(1451.82,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-242.989,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(315.95,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-O2d)) + group(Cs-(Cds-Cds)OsHH) + group(Cs-(Cds-O2d)HHH) + group(Cds-CdsCsH) + group(Cds-OdCsOs) + group(Cds-CdsHH) + radical(C=CCJ(O)C)"""),
)
species(
label = '[CH2]C(=O)OC=CC(14769)',
structure = SMILES('[CH2]C(=O)OC=CC'),
E0 = (-174.505,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.654622,0.0639404,-5.28859e-05,2.2034e-08,-3.64334e-12,-20859.7,26.5912], Tmin=(100,'K'), Tmax=(1452.89,'K')), NASAPolynomial(coeffs=[16.4635,0.0204154,-7.94858e-06,1.41387e-09,-9.51311e-14,-25453.3,-55.5828], Tmin=(1452.89,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-174.505,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(315.95,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-(Cds-O2d)(Cds-Cd)) + group(Cs-(Cds-Cds)HHH) + group(Cs-(Cds-O2d)HHH) + group(Cds-CdsCsH) + group(Cds-OdCsOs) + group(Cds-CdsOsH) + radical(CJCO)"""),
)
species(
label = '[CH2]C(O)OC=C=C(13876)',
structure = SMILES('[CH2]C(O)OC=C=C'),
E0 = (-33.5702,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3615,1277.5,1000,540,610,2055,2950,3100,1380,975,1025,1650,3000,3100,440,815,1455,1000,3010,987.5,1337.5,450,1655,1380,1390,370,380,2900,435,180,180,180],'cm^-1')),
HinderedRotor(inertia=(0.92561,'amu*angstrom^2'), symmetry=1, barrier=(21.2816,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.925306,'amu*angstrom^2'), symmetry=1, barrier=(21.2746,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.925681,'amu*angstrom^2'), symmetry=1, barrier=(21.2832,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.925806,'amu*angstrom^2'), symmetry=1, barrier=(21.2861,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 2,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.659109,0.0818627,-8.36622e-05,4.04401e-08,-7.3093e-12,-3852.17,30.0751], Tmin=(100,'K'), Tmax=(1538.27,'K')), NASAPolynomial(coeffs=[23.613,0.00791995,-1.00102e-06,4.00513e-11,1.63196e-16,-10038.5,-93.3129], Tmin=(1538.27,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-33.5702,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(315.95,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cds-CdsOsH) + group(Cds-CdsHH) + group(Cdd-CdsCds) + radical(CJCO)"""),
)
species(
label = 'C=C=COC(C)[O](13704)',
structure = SMILES('C=C=COC(C)[O]'),
E0 = (-19.4542,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2800,2850,1350,1500,750,1050,1375,1000,2950,3100,1380,975,1025,1650,1380,1390,370,380,2900,435,540,610,2055,3010,987.5,1337.5,450,1655,198.791,201.392,201.532,203.532],'cm^-1')),
HinderedRotor(inertia=(0.767291,'amu*angstrom^2'), symmetry=1, barrier=(21.3284,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.726889,'amu*angstrom^2'), symmetry=1, barrier=(21.3142,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.746902,'amu*angstrom^2'), symmetry=1, barrier=(21.3235,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 2,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.56137,0.0658027,-4.86037e-05,1.14738e-08,1.34223e-12,-2207.48,25.9075], Tmin=(100,'K'), Tmax=(1042.71,'K')), NASAPolynomial(coeffs=[17.037,0.02004,-7.86037e-06,1.46496e-09,-1.04017e-13,-6591.42,-58.813], Tmin=(1042.71,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-19.4542,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(320.107,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cds-CdsOsH) + group(Cds-CdsHH) + group(Cdd-CdsCds) + radical(CCOJ)"""),
)
species(
label = '[CH2][CH]CO[C]([CH2])[O](2383)',
structure = SMILES('[CH2][CH]CO[C]([CH2])[O]'),
E0 = (550.305,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2850,1437.5,1250,1305,750,350,360,370,350,3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,3025,407.5,1350,352.5,211.509,829.515,1178.27,1554.05,1957.14],'cm^-1')),
HinderedRotor(inertia=(0.113644,'amu*angstrom^2'), symmetry=1, barrier=(3.18827,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.113644,'amu*angstrom^2'), symmetry=1, barrier=(3.18827,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.113644,'amu*angstrom^2'), symmetry=1, barrier=(3.18827,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.113644,'amu*angstrom^2'), symmetry=1, barrier=(3.18827,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.113644,'amu*angstrom^2'), symmetry=1, barrier=(3.18827,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 6,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
collisionModel = TransportData(shapeIndex=2, epsilon=(3800.62,'J/mol'), sigma=(6.68442,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0, comment="""Epsilon & sigma estimated with Tc=593.65 K, Pc=28.87 bar (from Joback method)"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.879862,0.076051,-0.000110871,9.89353e-08,-3.59728e-11,66291.6,34.0529], Tmin=(100,'K'), Tmax=(793.721,'K')), NASAPolynomial(coeffs=[5.97549,0.0389327,-1.91066e-05,3.7034e-09,-2.58547e-13,65843,12.9164], Tmin=(793.721,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(550.305,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(311.793,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(O2s-CsH) + group(Cs-CsCsHH) + group(Cs-CsOsOsH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + radical(CCJCO) + radical(CCOJ) + radical(RCCJ) + radical(CJCO) + radical(Cs_P)"""),
)
species(
label = '[CH2]C[CH]O[C]([CH2])[O](6734)',
structure = SMILES('[CH2]C[CH]O[C]([CH2])[O]'),
E0 = (530.859,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2850,1437.5,1250,1305,750,350,360,370,350,3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,3025,407.5,1350,352.5,200,800,1066.67,1333.33,1600],'cm^-1')),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 6,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.360017,0.0885477,-0.000139438,1.22732e-07,-4.26708e-11,63970.5,32.8686], Tmin=(100,'K'), Tmax=(826.94,'K')), NASAPolynomial(coeffs=[8.34678,0.0355725,-1.733e-05,3.31612e-09,-2.28548e-13,63139.9,-1.18025], Tmin=(826.94,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(530.859,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(311.793,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(O2s-CsH) + group(Cs-CsCsHH) + group(Cs-CsOsOsH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + radical(RCCJ) + radical(CCOJ) + radical(Cs_P) + radical(CJCO) + radical(CCsJOCs)"""),
)
species(
label = '[CH2]C=COC1CO1(6594)',
structure = SMILES('[CH2]C=COC1CO1'),
E0 = (-80.7007,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.816098,0.049352,2.61097e-05,-9.12505e-08,4.63827e-11,-9571.77,22.4043], Tmin=(100,'K'), Tmax=(884.124,'K')), NASAPolynomial(coeffs=[23.419,0.00465321,4.28543e-06,-1.15428e-09,8.37417e-14,-15818.3,-96.5807], Tmin=(884.124,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-80.7007,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(320.107,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(O2s-Cs(Cds-Cd)) + group(Cs-CsOsOsH) + group(Cs-CsOsHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + ring(Ethylene_oxide) + radical(Allyl_P)"""),
)
species(
label = '[CH2]C1OC=CCO1(14722)',
structure = SMILES('[CH2]C1OC=CCO1'),
E0 = (-110.249,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.40996,0.0307789,7.35608e-05,-1.35027e-07,5.96454e-11,-13142.2,19.0172], Tmin=(100,'K'), Tmax=(910.323,'K')), NASAPolynomial(coeffs=[22.9455,0.00476339,3.37117e-06,-8.28296e-10,5.24612e-14,-19906,-98.4706], Tmin=(910.323,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-110.249,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(328.422,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(O2s-Cs(Cds-Cd)) + group(Cs-CsOsOsH) + group(Cs-(Cds-Cds)OsHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + ring(24dihydro13dioxin) + radical(CJCO)"""),
)
species(
label = '[O]C1CCC=CO1(14770)',
structure = SMILES('[O]C1CCC=CO1'),
E0 = (-128.912,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.97555,0.0255627,6.22009e-05,-1.01353e-07,4.15606e-11,-15414.3,18.7861], Tmin=(100,'K'), Tmax=(940.553,'K')), NASAPolynomial(coeffs=[14.6001,0.019935,-5.47364e-06,9.44085e-10,-7.09505e-14,-19915,-52.6474], Tmin=(940.553,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-128.912,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(332.579,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-CsH) + group(Cs-CsCsHH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsOsOsH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + ring(3,4-Dihydro-2H-pyran) + radical(CCOJ)"""),
)
species(
label = '[CH2]C([O])C([CH2])C=O(12644)',
structure = SMILES('[CH2]C([O])C([CH2])C=O'),
E0 = (223.346,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2782.5,750,1395,475,1775,1000,1380,1383.33,1386.67,1390,370,373.333,376.667,380,2800,3000,430,440,3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,237.377,2887.88],'cm^-1')),
HinderedRotor(inertia=(0.31931,'amu*angstrom^2'), symmetry=1, barrier=(12.7646,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.00299155,'amu*angstrom^2'), symmetry=1, barrier=(0.119627,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.319235,'amu*angstrom^2'), symmetry=1, barrier=(12.7648,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.788709,'amu*angstrom^2'), symmetry=1, barrier=(31.5423,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 4,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
collisionModel = TransportData(shapeIndex=2, epsilon=(4030.69,'J/mol'), sigma=(6.74566,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0, comment="""Epsilon & sigma estimated with Tc=629.58 K, Pc=29.8 bar (from Joback method)"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.624896,0.0788821,-0.000101868,7.41622e-08,-2.20348e-11,26979.6,29.0184], Tmin=(100,'K'), Tmax=(817.816,'K')), NASAPolynomial(coeffs=[10.399,0.0310773,-1.41882e-05,2.68947e-09,-1.86674e-13,25380.9,-16.1705], Tmin=(817.816,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(223.346,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(315.95,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(Cs-(Cds-O2d)CsCsH) + group(Cs-CsCsOsH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cds-OdCsH) + radical(CJCO) + radical(CC(C)OJ) + radical(CJC(C)C=O)"""),
)
species(
label = '[CH2][CH]OC=C[CH2](6363)',
structure = SMILES('[CH2][CH]OC=C[CH2]'),
E0 = (335.483,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3025,407.5,1350,352.5,2995,3025,975,1000,1300,1375,400,500,1630,1680,3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,180,180,180],'cm^-1')),
HinderedRotor(inertia=(0.981069,'amu*angstrom^2'), symmetry=1, barrier=(22.5567,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.981067,'amu*angstrom^2'), symmetry=1, barrier=(22.5567,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.981059,'amu*angstrom^2'), symmetry=1, barrier=(22.5565,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.981065,'amu*angstrom^2'), symmetry=1, barrier=(22.5566,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 4,
opticalIsomers = 1,
molecularWeight = (83.1085,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.374208,0.0653949,-3.60498e-05,-1.81815e-08,1.69684e-11,40493.2,24.5856], Tmin=(100,'K'), Tmax=(920.64,'K')), NASAPolynomial(coeffs=[22.8909,0.00525337,5.31957e-07,-2.04763e-10,1.18042e-14,34750,-90.8571], Tmin=(920.64,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(335.483,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(291.007,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + radical(CCsJOC(O)) + radical(Allyl_P) + radical(CJCO)"""),
)
species(
label = '[CH2][CH][CH]OC=O(6547)',
structure = SMILES('[CH2][CH][CH]OC=O'),
E0 = (168.429,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3000,3050,390,425,1340,1360,335,370,3000,3100,440,815,1455,1000,2782.5,750,1395,475,1775,1000,250.409,1067.4,1067.5],'cm^-1')),
HinderedRotor(inertia=(0.00524154,'amu*angstrom^2'), symmetry=1, barrier=(4.23753,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.0052383,'amu*angstrom^2'), symmetry=1, barrier=(4.23745,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.590347,'amu*angstrom^2'), symmetry=1, barrier=(26.263,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.590471,'amu*angstrom^2'), symmetry=1, barrier=(26.2629,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 4,
opticalIsomers = 1,
molecularWeight = (85.0813,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.5531,0.04703,-3.6011e-05,1.22399e-08,-1.21273e-12,20351.1,27.0842], Tmin=(100,'K'), Tmax=(1165.4,'K')), NASAPolynomial(coeffs=[12.7055,0.0165408,-6.79333e-06,1.26092e-09,-8.78008e-14,17222.7,-30.6957], Tmin=(1165.4,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(168.429,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(241.12,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-O2d)) + group(Cs-CsCsHH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cds-OdOsH) + radical(CCsJOC(O)H) + radical(CCJCO) + radical(RCCJ)"""),
)
species(
label = '[CH]=COC([CH2])[O](4648)',
structure = SMILES('[CH]=COC([CH2])[O]'),
E0 = (298.652,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3120,650,792.5,1650,3010,987.5,1337.5,450,1655,1380,1390,370,380,2900,435,3000,3100,440,815,1455,1000,373.66,375.843,376.452],'cm^-1')),
HinderedRotor(inertia=(0.193374,'amu*angstrom^2'), symmetry=1, barrier=(19.3668,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.194489,'amu*angstrom^2'), symmetry=1, barrier=(19.3527,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.196222,'amu*angstrom^2'), symmetry=1, barrier=(19.3407,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 4,
opticalIsomers = 1,
molecularWeight = (85.0813,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.979736,0.0588882,-5.41492e-05,1.9832e-08,-1.24517e-12,36035,24.5814], Tmin=(100,'K'), Tmax=(1000.58,'K')), NASAPolynomial(coeffs=[16.534,0.0110573,-3.95674e-06,7.22918e-10,-5.18627e-14,32204,-54.0573], Tmin=(1000.58,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(298.652,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(245.277,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cds-CdsOsH) + group(Cds-CdsHH) + radical(CJCO) + radical(CCOJ) + radical(Cds_P)"""),
)
species(
label = '[CH]C([O])OC=C[CH2](14771)',
structure = SMILES('[CH]C([O])OC=C[CH2]'),
E0 = (403.656,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3000,3100,440,815,1455,1000,1380,1390,370,380,2900,435,2995,3025,975,1000,1300,1375,400,500,1630,1680,200,800,960,1120,1280,1440,1600],'cm^-1')),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 5,
opticalIsomers = 1,
molecularWeight = (98.0999,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.496166,0.0664275,-4.96174e-05,8.39362e-09,3.6094e-12,48684.2,28.3712], Tmin=(100,'K'), Tmax=(997.504,'K')), NASAPolynomial(coeffs=[18.7271,0.0152563,-5.65372e-06,1.05631e-09,-7.67575e-14,43955.8,-65.0073], Tmin=(997.504,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(403.656,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(291.007,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + radical(CCJ2_triplet) + radical(CCOJ) + radical(Allyl_P)"""),
)
species(
label = '[CH]C=COC([CH2])[O](14772)',
structure = SMILES('[CH]C=COC([CH2])[O]'),
E0 = (386.215,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3000,3100,440,815,1455,1000,1380,1390,370,380,2900,435,2995,3025,975,1000,1300,1375,400,500,1630,1680,200,800,960,1120,1280,1440,1600],'cm^-1')),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 5,
opticalIsomers = 1,
molecularWeight = (98.0999,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.175571,0.0734367,-6.58772e-05,2.97381e-08,-5.29333e-12,46597.6,29.9889], Tmin=(100,'K'), Tmax=(1363.15,'K')), NASAPolynomial(coeffs=[18.1352,0.0207364,-7.886e-06,1.37676e-09,-9.18771e-14,41701.3,-62.2196], Tmin=(1363.15,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(386.215,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(291.007,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + radical(CJCO) + radical(CCOJ) + radical(AllylJ2_triplet)"""),
)
species(
label = '[CH2]C([O])OC[C]=C(14773)',
structure = SMILES('[CH2]C([O])OC[C]=C'),
E0 = (311.091,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1685,370,2750,2850,1437.5,1250,1305,750,350,2950,3100,1380,975,1025,1650,1380,1390,370,380,2900,435,3000,3100,440,815,1455,1000,200,800,1066.67,1333.33,1600],'cm^-1')),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 4,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.978458,0.0753823,-0.000114422,1.07287e-07,-4.02056e-11,37515.7,30.058], Tmin=(100,'K'), Tmax=(811.442,'K')), NASAPolynomial(coeffs=[4.22253,0.0420569,-2.07759e-05,4.0235e-09,-2.8009e-13,37559.9,18.6014], Tmin=(811.442,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(311.091,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(315.95,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-(Cds-Cds)OsHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(CJCO) + radical(CCOJ) + radical(Cds_S)"""),
)
species(
label = '[CH2][C]([O])OCC=C(2374)',
structure = SMILES('[CH2][C]([O])OCC=C'),
E0 = (278.496,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3000,3100,440,815,1455,1000,2750,2850,1437.5,1250,1305,750,350,2950,3100,1380,975,1025,1650,3010,987.5,1337.5,450,1655,360,370,350,200,800,1066.67,1333.33,1600],'cm^-1')),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 4,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.08282,0.0710946,-9.85501e-05,8.82697e-08,-3.28719e-11,33593.6,29.8991], Tmin=(100,'K'), Tmax=(776.972,'K')), NASAPolynomial(coeffs=[5.02484,0.0405831,-1.99202e-05,3.87783e-09,-2.72026e-13,33289.5,13.8606], Tmin=(776.972,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(278.496,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(315.95,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-(Cds-Cds)OsHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(CJCO) + radical(Cs_P) + radical(CCOJ)"""),
)
species(
label = '[CH]=CCOC([CH2])[O](14774)',
structure = SMILES('[CH]=CCOC([CH2])[O]'),
E0 = (320.345,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3000,3100,440,815,1455,1000,2750,2850,1437.5,1250,1305,750,350,1380,1390,370,380,2900,435,3120,650,792.5,1650,3010,987.5,1337.5,450,1655,304.7,307.307,307.351,314.699],'cm^-1')),
HinderedRotor(inertia=(0.00294434,'amu*angstrom^2'), symmetry=1, barrier=(6.90859,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.106754,'amu*angstrom^2'), symmetry=1, barrier=(6.89096,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.00290334,'amu*angstrom^2'), symmetry=1, barrier=(6.86965,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.425213,'amu*angstrom^2'), symmetry=1, barrier=(28.6042,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 4,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.961142,0.0740055,-0.000105143,9.37954e-08,-3.4444e-11,38631.1,30.0512], Tmin=(100,'K'), Tmax=(784.791,'K')), NASAPolynomial(coeffs=[5.56673,0.0398799,-1.95585e-05,3.7988e-09,-2.65859e-13,38236.3,11.0378], Tmin=(784.791,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(320.345,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(315.95,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-(Cds-Cds)OsHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(CCOJ) + radical(Cds_P) + radical(CJCO)"""),
)
species(
label = '[CH]C=COC([CH2])O(13888)',
structure = SMILES('[CH]C=COC([CH2])O'),
E0 = (160.51,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3000,3100,440,815,1455,1000,2995,3025,975,1000,1300,1375,400,500,1630,1680,3615,1277.5,1000,1380,1390,370,380,2900,435,200,800,1000,1200,1400,1600],'cm^-1')),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 4,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.0800845,0.0732131,-4.4098e-05,-6.1937e-09,1.07408e-11,19457.8,29.4608], Tmin=(100,'K'), Tmax=(953.249,'K')), NASAPolynomial(coeffs=[20.6461,0.017853,-5.66945e-06,9.78589e-10,-6.96117e-14,14131.2,-76.1469], Tmin=(953.249,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(160.51,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(311.793,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + radical(CJCO) + radical(AllylJ2_triplet)"""),
)
species(
label = '[CH]C=COC(C)[O](13718)',
structure = SMILES('[CH]C=COC(C)[O]'),
E0 = (174.626,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2800,2850,1350,1500,750,1050,1375,1000,1380,1390,370,380,2900,435,2995,3025,975,1000,1300,1375,400,500,1630,1680,200,800,960,1120,1280,1440,1600],'cm^-1')),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 4,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.51617,0.0661435,-3.93276e-05,2.57275e-09,3.92875e-12,21137.1,28.1253], Tmin=(100,'K'), Tmax=(1046.47,'K')), NASAPolynomial(coeffs=[15.8307,0.0269007,-1.07349e-05,1.97711e-09,-1.38314e-13,16875.4,-51.5018], Tmin=(1046.47,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(174.626,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(315.95,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + radical(CCOJ) + radical(AllylJ2_triplet)"""),
)
species(
label = '[CH2]C1O[CH][CH]CO1(14726)',
structure = SMILES('[CH2]C1O[CH][CH]CO1'),
E0 = (183.754,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.52756,0.0371434,4.44963e-05,-1.01943e-07,4.9584e-11,22206.2,21.3823], Tmin=(100,'K'), Tmax=(855.761,'K')), NASAPolynomial(coeffs=[17.9576,0.0105652,3.05821e-06,-1.08665e-09,8.68723e-14,17555.4,-66.0676], Tmin=(855.761,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(183.754,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(328.422,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(O2s-CsCs) + group(Cs-CsCsHH) + group(Cs-CsOsOsH) + group(Cs-CsOsHH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + ring(1,3-Dioxane) + radical(CCsJOCs) + radical(CJCO) + radical(CCJCO)"""),
)
species(
label = '[O]C1CC[CH][CH]O1(14775)',
structure = SMILES('[O]C1CC[CH][CH]O1'),
E0 = (161.67,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.8747,0.0340844,3.22358e-05,-6.78274e-08,3.0024e-11,19532.7,22.4052], Tmin=(100,'K'), Tmax=(907.223,'K')), NASAPolynomial(coeffs=[11.6615,0.0241867,-6.37946e-06,9.50597e-10,-6.2256e-14,16388.5,-31.3994], Tmin=(907.223,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(161.67,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(332.579,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(O2s-CsH) + group(Cs-CsCsHH) + group(Cs-CsCsHH) + group(Cs-CsCsHH) + group(Cs-CsOsOsH) + group(Cs-CsOsHH) + ring(Oxane) + radical(CCJCO) + radical(CCsJOCs) + radical(CCOJ)"""),
)
species(
label = '[CH2]C(=O)OCC=C(6109)',
structure = SMILES('[CH2]C(=O)OCC=C'),
E0 = (-142.339,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.43117,0.0510405,-3.06177e-05,8.76767e-09,-1.00368e-12,-17022.6,27.5112], Tmin=(100,'K'), Tmax=(1980.67,'K')), NASAPolynomial(coeffs=[15.1892,0.0232561,-9.57623e-06,1.68545e-09,-1.09769e-13,-22472.6,-48.2662], Tmin=(1980.67,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-142.339,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(315.95,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-O2d)) + group(Cs-(Cds-Cds)OsHH) + group(Cs-(Cds-O2d)HHH) + group(Cds-CdsCsH) + group(Cds-OdCsOs) + group(Cds-CdsHH) + radical(CJCO)"""),
)
species(
label = '[CH2]C1OC(C=C)O1(12658)',
structure = SMILES('[CH2]C1OC(C=C)O1'),
E0 = (-10.6155,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.35377,0.0455231,9.02785e-09,-2.99542e-08,1.33839e-11,-1170.6,24.3426], Tmin=(100,'K'), Tmax=(1057.31,'K')), NASAPolynomial(coeffs=[14.1266,0.0252917,-1.11403e-05,2.20318e-09,-1.61046e-13,-5441.7,-45.4158], Tmin=(1057.31,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-10.6155,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(324.264,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(O2s-CsCs) + group(Cs-CsOsOsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + ring(Cyclobutane) + radical(CJCO)"""),
)
species(
label = 'C=CC1CC([O])O1(12647)',
structure = SMILES('C=CC1CC([O])O1'),
E0 = (-3.60279,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (99.1079,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.91685,0.0334418,3.01206e-05,-6.31108e-08,2.7444e-11,-346.892,23.8039], Tmin=(100,'K'), Tmax=(922.717,'K')), NASAPolynomial(coeffs=[11.2837,0.0246091,-7.17158e-06,1.15092e-09,-7.7891e-14,-3428.06,-27.9616], Tmin=(922.717,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-3.60279,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(328.422,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(O2s-CsH) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-CsCsHH) + group(Cs-CsOsOsH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + ring(Oxetane) + radical(CCOJ)"""),
)
species(
label = '[CH]OC([CH2])[O](1022)',
structure = SMILES('[CH]OC([CH2])[O]'),
E0 = (462.226,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1380,1390,370,380,2900,435,3000,3100,440,815,1455,1000,180,180,1120.97,1123.08,1124.4,3203.45],'cm^-1')),
HinderedRotor(inertia=(0.140235,'amu*angstrom^2'), symmetry=1, barrier=(3.22428,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.140732,'amu*angstrom^2'), symmetry=1, barrier=(3.23572,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.141736,'amu*angstrom^2'), symmetry=1, barrier=(3.25879,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 5,
opticalIsomers = 1,
molecularWeight = (72.0627,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.89406,0.0535552,-9.25983e-05,8.89474e-08,-3.30686e-11,55661.8,21.1964], Tmin=(100,'K'), Tmax=(822.987,'K')), NASAPolynomial(coeffs=[4.79137,0.0246598,-1.29331e-05,2.5429e-09,-1.77544e-13,55686.6,10.8309], Tmin=(822.987,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(462.226,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(195.39,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-OsHHH) + radical(CCOJ) + radical(CH2_triplet) + radical(CJCO)"""),
)
species(
label = '[CH]=C(64)',
structure = SMILES('[CH]=C'),
E0 = (289.245,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2950,3100,1380,975,1025,1650,826.012,826.012,3240.27],'cm^-1')),
],
spinMultiplicity = 2,
opticalIsomers = 1,
molecularWeight = (27.0452,'amu'),
collisionModel = TransportData(shapeIndex=2, epsilon=(1737.73,'J/mol'), sigma=(4.1,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=1.0, comment="""GRI-Mech"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[3.90671,-0.00406241,3.8678e-05,-4.62976e-08,1.729e-11,34797.2,6.09789], Tmin=(100,'K'), Tmax=(931.962,'K')), NASAPolynomial(coeffs=[5.44797,0.00498356,-1.08821e-06,1.79837e-10,-1.45096e-14,33829.8,-4.87808], Tmin=(931.962,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(289.245,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(108.088,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cds-CdsHH) + group(Cds-CdsHH) + radical(Cds_P)"""),
)
species(
label = 'N2',
structure = SMILES('N#N'),
E0 = (-8.64289,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (28.0135,'amu'),
collisionModel = TransportData(shapeIndex=1, epsilon=(810.913,'J/mol'), sigma=(3.621,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(1.76,'angstroms^3'), rotrelaxcollnum=4.0, comment="""GRI-Mech"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[3.53101,-0.000123661,-5.02999e-07,2.43531e-09,-1.40881e-12,-1046.98,2.96747], Tmin=(200,'K'), Tmax=(1000,'K')), NASAPolynomial(coeffs=[2.95258,0.0013969,-4.92632e-07,7.8601e-11,-4.60755e-15,-923.949,5.87189], Tmin=(1000,'K'), Tmax=(6000,'K'))], Tmin=(200,'K'), Tmax=(6000,'K'), E0=(-8.64289,'kJ/mol'), Cp0=(29.1007,'J/(mol*K)'), CpInf=(37.4151,'J/(mol*K)'), label="""N2""", comment="""Thermo library: primaryThermoLibrary"""),
)
species(
label = 'Ne',
structure = SMILES('[Ne]'),
E0 = (-6.19738,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (20.1797,'amu'),
collisionModel = TransportData(shapeIndex=0, epsilon=(1235.53,'J/mol'), sigma=(3.758e-10,'m'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0, comment="""Epsilon & sigma estimated with fixed Lennard Jones Parameters. This is the fallback method! Try improving transport databases!"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.5,0,0,0,0,-745.375,3.35532], Tmin=(200,'K'), Tmax=(1000,'K')), NASAPolynomial(coeffs=[2.5,0,0,0,0,-745.375,3.35532], Tmin=(1000,'K'), Tmax=(6000,'K'))], Tmin=(200,'K'), Tmax=(6000,'K'), E0=(-6.19738,'kJ/mol'), Cp0=(20.7862,'J/(mol*K)'), CpInf=(20.7862,'J/(mol*K)'), label="""Ne""", comment="""Thermo library: primaryThermoLibrary"""),
)
species(
label = 'He',
structure = SMILES('[He]'),
E0 = (-6.19738,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (4.0026,'amu'),
collisionModel = TransportData(shapeIndex=0, epsilon=(84.8076,'J/mol'), sigma=(2.576,'angstroms'), dipoleMoment=(0,'De'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0.0, comment="""NOx2018"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.5,0,0,0,0,-745.375,0.928724], Tmin=(200,'K'), Tmax=(1000,'K')), NASAPolynomial(coeffs=[2.5,0,0,0,0,-745.375,0.928724], Tmin=(1000,'K'), Tmax=(6000,'K'))], Tmin=(200,'K'), Tmax=(6000,'K'), E0=(-6.19738,'kJ/mol'), Cp0=(20.7862,'J/(mol*K)'), CpInf=(20.7862,'J/(mol*K)'), label="""He""", comment="""Thermo library: primaryThermoLibrary"""),
)
species(
label = 'Ar',
structure = SMILES('[Ar]'),
E0 = (-6.19738,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (39.348,'amu'),
collisionModel = TransportData(shapeIndex=0, epsilon=(1134.93,'J/mol'), sigma=(3.33,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0.0, comment="""GRI-Mech"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.5,0,0,0,0,-745.375,4.37967], Tmin=(200,'K'), Tmax=(1000,'K')), NASAPolynomial(coeffs=[2.5,0,0,0,0,-745.375,4.37967], Tmin=(1000,'K'), Tmax=(6000,'K'))], Tmin=(200,'K'), Tmax=(6000,'K'), E0=(-6.19738,'kJ/mol'), Cp0=(20.7862,'J/(mol*K)'), CpInf=(20.7862,'J/(mol*K)'), label="""Ar""", comment="""Thermo library: primaryThermoLibrary"""),
)
transitionState(
label = 'TS1',
E0 = (167.03,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS2',
E0 = (289.073,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS3',
E0 = (274.1,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS4',
E0 = (201.973,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS5',
E0 = (415.739,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS6',
E0 = (250.337,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS7',
E0 = (278.025,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS8',
E0 = (167.03,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS9',
E0 = (281.002,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS10',
E0 = (308.518,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS11',
E0 = (374.761,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS12',
E0 = (422.254,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS13',
E0 = (225.377,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS14',
E0 = (288.185,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS15',
E0 = (223.464,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS16',
E0 = (233.182,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS17',
E0 = (255.312,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS18',
E0 = (451.314,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS19',
E0 = (598.425,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS20',
E0 = (535.202,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS21',
E0 = (616.676,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS22',
E0 = (619.037,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS23',
E0 = (392.966,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS24',
E0 = (224.382,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS25',
E0 = (241.313,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS26',
E0 = (189.891,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS27',
E0 = (189.891,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS28',
E0 = (192.003,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS29',
E0 = (192.003,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS30',
E0 = (192.003,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS31',
E0 = (613.705,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS32',
E0 = (555.832,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS33',
E0 = (172.424,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS34',
E0 = (174.561,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS35',
E0 = (175.23,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS36',
E0 = (480.83,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS37',
E0 = (742.364,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS38',
E0 = (584.114,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS39',
E0 = (714.338,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS40',
E0 = (615.461,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS41',
E0 = (598.02,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS42',
E0 = (300.602,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS43',
E0 = (450.446,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS44',
E0 = (437.906,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS45',
E0 = (465.53,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS46',
E0 = (295.751,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS47',
E0 = (306.903,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS48',
E0 = (227.916,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS49',
E0 = (254.507,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS50',
E0 = (255.998,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS51',
E0 = (174.938,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS52',
E0 = (174.938,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS53',
E0 = (785.788,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
reaction(
label = 'reaction1',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['C=C[O](594)', 'C=CC=O(5269)'],
transitionState = 'TS1',
kinetics = Arrhenius(A=(5e+12,'s^-1'), n=0, Ea=(0,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1500,'K'), comment="""Exact match found for rate rule [RJJ]
Euclidian distance = 0
family: 1,4_Linear_birad_scission"""),
)
reaction(
label = 'reaction2',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[CH2][CH]C1OC([CH2])O1(14763)'],
transitionState = 'TS2',
kinetics = Arrhenius(A=(2.724e+10,'s^-1','*|/',3), n=0.478, Ea=(122.043,'kJ/mol'), T0=(1,'K'), Tmin=(600,'K'), Tmax=(2000,'K'), comment="""Estimated using an average for rate rule [R5_SS_D;doublebond_intra;radadd_intra_O]
Euclidian distance = 0
family: Intra_R_Add_Exocyclic"""),
)
reaction(
label = 'reaction3',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[CH2][CH]C1CC([O])O1(14764)'],
transitionState = 'TS3',
kinetics = Arrhenius(A=(177207,'s^-1'), n=1.88643, Ea=(107.07,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R5_SS;multiplebond_intra;radadd_intra_cs2H] for rate rule [R5_SS_D;doublebond_intra;radadd_intra_cs2H]
Euclidian distance = 1.41421356237
family: Intra_R_Add_Exocyclic
Ea raised from 103.0 to 107.1 kJ/mol to match endothermicity of reaction."""),
)
reaction(
label = 'reaction4',
reactants = ['H(8)', '[CH2]C(=O)O[CH]C=C(12761)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS4',
kinetics = Arrhenius(A=(92.1383,'m^3/(mol*s)'), n=1.68375, Ea=(21.5685,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [CO_O;HJ]
Euclidian distance = 0
family: R_Addition_MultipleBond"""),
)
reaction(
label = 'reaction5',
reactants = ['H(8)', '[CH2]C([O])OC=C=C(14765)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS5',
kinetics = Arrhenius(A=(4.42e+08,'cm^3/(mol*s)'), n=1.64, Ea=(11.7989,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1500,'K'), comment="""From training reaction 2713 used for Ca_Cds-HH;HJ
Exact match found for rate rule [Ca_Cds-HH;HJ]
Euclidian distance = 0
family: R_Addition_MultipleBond"""),
)
reaction(
label = 'reaction6',
reactants = ['CH2(T)(28)', 'C=C[CH]OC=O(6118)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS6',
kinetics = Arrhenius(A=(0.0201871,'m^3/(mol*s)'), n=2.2105, Ea=(56.0866,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [CO-NdH_O;YJ] for rate rule [CO-NdH_O;CH2_triplet]
Euclidian distance = 2.0
family: R_Addition_MultipleBond"""),
)
reaction(
label = 'reaction7',
reactants = ['O(T)(63)', 'C=C[CH]OC=C(6503)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS7',
kinetics = Arrhenius(A=(53.4257,'m^3/(mol*s)'), n=1.6025, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [Cds_Cds;O_atom_triplet] for rate rule [Cds-OsH_Cds;O_atom_triplet]
Euclidian distance = 1.0
family: R_Addition_MultipleBond
Ea raised from -5.8 to 0 kJ/mol."""),
)
reaction(
label = 'reaction8',
reactants = ['C=C[O](594)', '[CH2]C=C[O](5266)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS8',
kinetics = Arrhenius(A=(1.3e+11,'cm^3/(mol*s)'), n=0, Ea=(101.918,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1500,'K'), comment="""Estimated using an average for rate rule [CO_O;O_rad/OneDe]
Euclidian distance = 0
family: R_Addition_MultipleBond
Ea raised from 99.5 to 101.9 kJ/mol to match endothermicity of reaction."""),
)
reaction(
label = 'reaction9',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[CH2]C=CO[C]([CH2])O(13880)'],
transitionState = 'TS9',
kinetics = Arrhenius(A=(2.15e+14,'s^-1','+|-',2), n=-0.27, Ea=(113.972,'kJ/mol'), T0=(1,'K'), Tmin=(700,'K'), Tmax=(1800,'K'), comment="""Estimated using an average for rate rule [R2H_S;O_rad_out;XH_out]
Euclidian distance = 0
family: intra_H_migration"""),
)
reaction(
label = 'reaction10',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[CH2][CH][CH]OC(C)=O(13711)'],
transitionState = 'TS10',
kinetics = Arrhenius(A=(17481.2,'s^-1'), n=2.56136, Ea=(141.488,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [R2H_S;C_rad_out_2H;XH_out]
Euclidian distance = 0
family: intra_H_migration"""),
)
reaction(
label = 'reaction11',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[CH2]C([O])OC=[C]C(14766)'],
transitionState = 'TS11',
kinetics = Arrhenius(A=(1.63e+08,'s^-1'), n=1.73, Ea=(207.731,'kJ/mol'), T0=(1,'K'), comment="""From training reaction 123 used for R2H_S;C_rad_out_2H;Cd_H_out_doubleC
Exact match found for rate rule [R2H_S;C_rad_out_2H;Cd_H_out_doubleC]
Euclidian distance = 0
family: intra_H_migration"""),
)
reaction(
label = 'reaction12',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[CH2]C([O])O[C]=CC(14767)'],
transitionState = 'TS12',
kinetics = Arrhenius(A=(1.91e+11,'s^-1'), n=0.63, Ea=(255.224,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1500,'K'), comment="""From training reaction 199 used for R3H_SD;C_rad_out_2H;Cd_H_out_singleNd
Exact match found for rate rule [R3H_SD;C_rad_out_2H;Cd_H_out_singleNd]
Euclidian distance = 0
family: intra_H_migration"""),
)
reaction(
label = 'reaction13',
reactants = ['[CH2]C=[C]OC([CH2])O(13882)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS13',
kinetics = Arrhenius(A=(37100,'s^-1'), n=2.23, Ea=(44.3086,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R4H_RSS;Cd_rad_out;XH_out] for rate rule [R4H_SSS_OCs;Cd_rad_out_Cd;O_H_out]
Euclidian distance = 3.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction14',
reactants = ['[CH2]C=[C]OC(C)[O](13713)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS14',
kinetics = Arrhenius(A=(2.74832e+07,'s^-1'), n=1.435, Ea=(93,'kJ/mol'), T0=(1,'K'), comment="""Estimated using average of templates [R4H_SSS_OCs;Y_rad_out;Cs_H_out_2H] + [R4H_RSS;Cd_rad_out;Cs_H_out] for rate rule [R4H_SSS_OCs;Cd_rad_out_Cd;Cs_H_out_2H]
Euclidian distance = 3.0
Multiplied by reaction path degeneracy 3.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction15',
reactants = ['[CH2][C]=COC([CH2])O(13881)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS15',
kinetics = Arrhenius(A=(380071,'s^-1'), n=1.62386, Ea=(44.2978,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R5H_RSSR;Y_rad_out;XH_out] for rate rule [R5H_DSSS;Cd_rad_out;O_H_out]
Euclidian distance = 2.44948974278
family: intra_H_migration"""),
)
reaction(
label = 'reaction16',
reactants = ['[CH2][C]=COC(C)[O](13712)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS16',
kinetics = Arrhenius(A=(263079,'s^-1'), n=1.73643, Ea=(39.8993,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R5H_RSSR;Y_rad_out;Cs_H_out_2H] for rate rule [R5H_DSSS;Cd_rad_out;Cs_H_out_2H]
Euclidian distance = 2.2360679775
Multiplied by reaction path degeneracy 3.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction17',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[CH2]C(=O)O[CH][CH]C(2373)'],
transitionState = 'TS17',
kinetics = Arrhenius(A=(126000,'s^-1'), n=1.85, Ea=(88.2824,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [R5H_SMSS;C_rad_out_2H;XH_out]
Euclidian distance = 0
family: intra_H_migration"""),
)
reaction(
label = 'reaction18',
reactants = ['[CH2][CH][O](719)', '[CH2]C=C[O](5266)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS18',
kinetics = Arrhenius(A=(1.63841e+06,'m^3/(mol*s)'), n=0.151, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [O_rad/OneDe;Y_rad]
Euclidian distance = 0
family: R_Recombination
Ea raised from -0.7 to 0 kJ/mol."""),
)
reaction(
label = 'reaction19',
reactants = ['[CH2]C([O])[O](696)', '[CH]C=C(8168)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS19',
kinetics = Arrhenius(A=(7.15767e+07,'m^3/(mol*s)'), n=0.0716491, Ea=(15.4197,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [Y_rad;O_rad/NonDe] for rate rule [Cd_rad;O_rad/NonDe]
Euclidian distance = 1.0
Multiplied by reaction path degeneracy 2.0
family: R_Recombination"""),
)
reaction(
label = 'reaction20',
reactants = ['H(8)', '[CH2][CH][CH]OC([CH2])=O(6733)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS20',
kinetics = Arrhenius(A=(4.34078e+06,'m^3/(mol*s)'), n=0.278577, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [Y_rad;H_rad]
Euclidian distance = 0
family: R_Recombination
Ea raised from -1.4 to 0 kJ/mol."""),
)
reaction(
label = 'reaction21',
reactants = ['H(8)', '[CH2][C]=COC([CH2])[O](14446)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS21',
kinetics = Arrhenius(A=(4.34078e+06,'m^3/(mol*s)'), n=0.278577, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [Y_rad;H_rad]
Euclidian distance = 0
family: R_Recombination
Ea raised from -1.4 to 0 kJ/mol."""),
)
reaction(
label = 'reaction22',
reactants = ['H(8)', '[CH2]C=[C]OC([CH2])[O](14444)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS22',
kinetics = Arrhenius(A=(5.78711e+07,'m^3/(mol*s)'), n=0.0433333, Ea=(0.458029,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [Cd_rad;H_rad]
Euclidian distance = 0
family: R_Recombination"""),
)
reaction(
label = 'reaction23',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[CH2]C([O])OC1[CH]C1(12058)'],
transitionState = 'TS23',
kinetics = Arrhenius(A=(1.05e+08,'s^-1'), n=1.192, Ea=(225.936,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1600,'K'), comment="""Estimated using template [R3_D;doublebond_intra_pri;radadd_intra_cs2H] for rate rule [R3_D;doublebond_intra_pri_HNd_O;radadd_intra_cs2H]
Euclidian distance = 2.0
family: Intra_R_Add_Endocyclic"""),
)
reaction(
label = 'reaction24',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[CH2]C1[CH]OC([CH2])O1(14679)'],
transitionState = 'TS24',
kinetics = Arrhenius(A=(1.66591e+07,'s^-1'), n=1.01661, Ea=(57.3526,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R5_SS_D;doublebond_intra_pri;radadd_intra] for rate rule [R5_SS_D;doublebond_intra_pri;radadd_intra_O]
Euclidian distance = 1.0
family: Intra_R_Add_Endocyclic"""),
)
reaction(
label = 'reaction25',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[CH2]C1[CH]OC([O])C1(14768)'],
transitionState = 'TS25',
kinetics = Arrhenius(A=(4.47079e+07,'s^-1'), n=0.909323, Ea=(74.2834,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [R5_SS_D;doublebond_intra_pri;radadd_intra_cs2H]
Euclidian distance = 0
family: Intra_R_Add_Endocyclic"""),
)
reaction(
label = 'reaction26',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['C=C[CH]OC(=C)O(13875)'],
transitionState = 'TS26',
kinetics = Arrhenius(A=(1.949e+11,'s^-1'), n=0.486, Ea=(22.8614,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [R2radExo;Y_rad;XH_Rrad]
Euclidian distance = 0
family: Intra_Disproportionation"""),
)
reaction(
label = 'reaction27',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['C=C[CH]OC(C)=O(12663)'],
transitionState = 'TS27',
kinetics = Arrhenius(A=(1.949e+11,'s^-1'), n=0.486, Ea=(22.8614,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [R2radExo;Y_rad;XH_Rrad]
Euclidian distance = 0
family: Intra_Disproportionation"""),
)
reaction(
label = 'reaction28',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[CH2]C(=O)OC=CC(14769)'],
transitionState = 'TS28',
kinetics = Arrhenius(A=(2.1261e+09,'s^-1'), n=0.137, Ea=(24.9733,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R5;Y_rad;XH_Rrad] for rate rule [R5radExo;Y_rad;XH_Rrad]
Euclidian distance = 1.0
family: Intra_Disproportionation"""),
)
reaction(
label = 'reaction29',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[CH2]C(O)OC=C=C(13876)'],
transitionState = 'TS29',
kinetics = Arrhenius(A=(2.1261e+09,'s^-1'), n=0.137, Ea=(24.9733,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R5;Y_rad;XH_Rrad] for rate rule [R5radExo;Y_rad;XH_Rrad]
Euclidian distance = 1.0
family: Intra_Disproportionation"""),
)
reaction(
label = 'reaction30',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['C=C=COC(C)[O](13704)'],
transitionState = 'TS30',
kinetics = Arrhenius(A=(2.1261e+09,'s^-1'), n=0.137, Ea=(24.9733,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R5;Y_rad;XH_Rrad] for rate rule [R5radExo;Y_rad;XH_Rrad]
Euclidian distance = 1.0
family: Intra_Disproportionation"""),
)
reaction(
label = 'reaction11',
reactants = ['[CH2][CH]CO[C]([CH2])[O](2383)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS31',
kinetics = Arrhenius(A=(1.4874e+09,'s^-1'), n=1.045, Ea=(63.4002,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [R3radExo;Y_rad;XH_Rrad]
Euclidian distance = 0
Multiplied by reaction path degeneracy 2.0
family: Intra_Disproportionation"""),
)
reaction(
label = 'reaction32',
reactants = ['[CH2]C[CH]O[C]([CH2])[O](6734)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS32',
kinetics = Arrhenius(A=(1.02844e+09,'s^-1'), n=0.311, Ea=(24.9733,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R4;Y_rad;XH_Rrad] for rate rule [R4radEndo;Y_rad;XH_Rrad]
Euclidian distance = 1.0
Multiplied by reaction path degeneracy 2.0
family: Intra_Disproportionation"""),
)
reaction(
label = 'reaction33',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[CH2]C=COC1CO1(6594)'],
transitionState = 'TS33',
kinetics = Arrhenius(A=(5.94212e+13,'s^-1'), n=0.0123667, Ea=(5.39457,'kJ/mol'), T0=(1,'K'), comment="""Estimated using average of templates [Rn;Y_rad_out;Cpri_rad_out_2H] + [R3_SS;Y_rad_out;Ypri_rad_out] for rate rule [R3_SS;O_rad;Cpri_rad_out_2H]
Euclidian distance = 2.2360679775
family: Birad_recombination"""),
)
reaction(
label = 'reaction34',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[CH2]C1OC=CCO1(14722)'],
transitionState = 'TS34',
kinetics = Arrhenius(A=(2e+12,'s^-1'), n=0, Ea=(7.5312,'kJ/mol'), T0=(1,'K'), Tmin=(550,'K'), Tmax=(650,'K'), comment="""Estimated using template [R6_SSSDS;Y_rad_out;Cpri_rad_out_2H] for rate rule [R6_SSSDS;O_rad;Cpri_rad_out_2H]
Euclidian distance = 1.0
family: Birad_recombination"""),
)
reaction(
label = 'reaction35',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[O]C1CCC=CO1(14770)'],
transitionState = 'TS35',
kinetics = Arrhenius(A=(2.53377e+11,'s^-1'), n=0.0685, Ea=(8.20064,'kJ/mol'), T0=(1,'K'), comment="""Estimated using average of templates [R6;C_rad_out_2H;Cpri_rad_out_2H] + [R6_SSSDS;C_rad_out_single;Cpri_rad_out_2H] for rate rule [R6_SSSDS;C_rad_out_2H;Cpri_rad_out_2H]
Euclidian distance = 1.0
family: Birad_recombination"""),
)
reaction(
label = 'reaction44',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[CH2]C([O])C([CH2])C=O(12644)'],
transitionState = 'TS36',
kinetics = Arrhenius(A=(7040,'s^-1'), n=2.66, Ea=(313.8,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1500,'K'), comment="""Estimated using an average for rate rule [R_ROR;R1_doublebond;R2_doublebond_H;R_O_C]
Euclidian distance = 0
family: ketoenol"""),
)
reaction(
label = 'reaction37',
reactants = ['O(T)(63)', '[CH2][CH]OC=C[CH2](6363)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS37',
kinetics = Arrhenius(A=(93609.6,'m^3/(mol*s)'), n=1.13083, Ea=(163.847,'kJ/mol'), T0=(1,'K'), Tmin=(303.03,'K'), Tmax=(2000,'K'), comment="""From training reaction 2 used for Y_rad;O_birad
Exact match found for rate rule [Y_rad;O_birad]
Euclidian distance = 0
family: Birad_R_Recombination"""),
)
reaction(
label = 'reaction38',
reactants = ['CH2(T)(28)', '[CH2][CH][CH]OC=O(6547)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS38',
kinetics = Arrhenius(A=(1.14854e+06,'m^3/(mol*s)'), n=0.575199, Ea=(34.3157,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [Y_rad;Birad]
Euclidian distance = 0
family: Birad_R_Recombination"""),
)
reaction(
label = 'reaction39',
reactants = ['CH2(T)(28)', '[CH]=COC([CH2])[O](4648)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS39',
kinetics = Arrhenius(A=(1.14854e+06,'m^3/(mol*s)'), n=0.575199, Ea=(34.3157,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [Y_rad;Birad] for rate rule [Cd_pri_rad;Birad]
Euclidian distance = 2.0
family: Birad_R_Recombination"""),
)
reaction(
label = 'reaction40',
reactants = ['H(8)', '[CH]C([O])OC=C[CH2](14771)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS40',
kinetics = Arrhenius(A=(1e+07,'m^3/(mol*s)'), n=0, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [H_rad;Birad]
Euclidian distance = 0
family: Birad_R_Recombination"""),
)
reaction(
label = 'reaction41',
reactants = ['H(8)', '[CH]C=COC([CH2])[O](14772)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS41',
kinetics = Arrhenius(A=(1e+07,'m^3/(mol*s)'), n=0, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [H_rad;Birad]
Euclidian distance = 0
family: Birad_R_Recombination"""),
)
reaction(
label = 'reaction42',
reactants = ['[CH2][CH][O](719)', 'C=CC=O(5269)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS42',
kinetics = Arrhenius(A=(373000,'cm^3/(mol*s)'), n=2.53, Ea=(20.92,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1500,'K'), comment="""Estimated using template [Od_CO-CdH;YJ] for rate rule [Od_CO-CdH;CJ]
Euclidian distance = 1.0
family: R_Addition_MultipleBond"""),
)
reaction(
label = 'reaction43',
reactants = ['[CH2]C([O])OC[C]=C(14773)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS43',
kinetics = Arrhenius(A=(1.89098e+10,'s^-1'), n=0.9884, Ea=(139.355,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R2H_S;Cd_rad_out_Cd;Cs_H_out_1H] for rate rule [R2H_S;Cd_rad_out_Cd;Cs_H_out_H/NonDeO]
Euclidian distance = 1.0
Multiplied by reaction path degeneracy 2.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction44',
reactants = ['[CH2][C]([O])OCC=C(2374)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS44',
kinetics = Arrhenius(A=(3.32e+07,'s^-1'), n=1.69, Ea=(159.41,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1500,'K'), comment="""Estimated using an average for rate rule [R3H_SS_O;Y_rad_out;Cs_H_out_H/Cd]
Euclidian distance = 0
Multiplied by reaction path degeneracy 2.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction45',
reactants = ['[CH]=CCOC([CH2])[O](14774)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS45',
kinetics = Arrhenius(A=(1.846e+10,'s^-1'), n=0.74, Ea=(145.185,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1500,'K'), comment="""Estimated using template [R3H_DS;Cd_rad_out_singleH;Cs_H_out_1H] for rate rule [R3H_DS;Cd_rad_out_singleH;Cs_H_out_H/NonDeO]
Euclidian distance = 1.0
Multiplied by reaction path degeneracy 2.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction46',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[CH]C=COC([CH2])O(13888)'],
transitionState = 'TS46',
kinetics = Arrhenius(A=(3.427,'s^-1'), n=3.311, Ea=(128.721,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [RnH;O_rad_out;Cd_H_out_singleH] for rate rule [R6HJ_3;O_rad_out;Cd_H_out_singleH]
Euclidian distance = 2.0
Multiplied by reaction path degeneracy 2.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction47',
reactants = ['[CH]C=COC(C)[O](13718)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS47',
kinetics = Arrhenius(A=(22.7193,'s^-1'), n=3.21897, Ea=(132.277,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [RnH;Cd_rad_out_singleH;Cs_H_out_2H] for rate rule [R6HJ_2;Cd_rad_out_singleH;Cs_H_out_2H]
Euclidian distance = 2.0
Multiplied by reaction path degeneracy 3.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction48',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[CH2]C1O[CH][CH]CO1(14726)'],
transitionState = 'TS48',
kinetics = Arrhenius(A=(9.91671e+09,'s^-1'), n=0.30082, Ea=(60.8864,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R6_linear;doublebond_intra_pri_2H;radadd_intra] for rate rule [R6_linear;doublebond_intra_pri_2H;radadd_intra_O]
Euclidian distance = 1.0
family: Intra_R_Add_Endocyclic"""),
)
reaction(
label = 'reaction49',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[O]C1CC[CH][CH]O1(14775)'],
transitionState = 'TS49',
kinetics = Arrhenius(A=(9.63396e+08,'s^-1'), n=0.483333, Ea=(87.4777,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [R6_linear;doublebond_intra_pri_2H;radadd_intra_cs2H]
Euclidian distance = 0
family: Intra_R_Add_Endocyclic"""),
)
reaction(
label = 'reaction50',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[CH2]C(=O)OCC=C(6109)'],
transitionState = 'TS50',
kinetics = Arrhenius(A=(2.6374e+09,'s^-1'), n=0.37, Ea=(88.9686,'kJ/mol'), T0=(1,'K'), comment="""Estimated using average of templates [R3;Y_rad_De;XH_Rrad] + [R3radExo;Y_rad;XH_Rrad] for rate rule [R3radExo;Y_rad_De;XH_Rrad]
Euclidian distance = 1.0
family: Intra_Disproportionation"""),
)
reaction(
label = 'reaction51',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['[CH2]C1OC(C=C)O1(12658)'],
transitionState = 'TS51',
kinetics = Arrhenius(A=(1.8e+12,'s^-1'), n=-0.1525, Ea=(7.90776,'kJ/mol'), T0=(1,'K'), comment="""Estimated using average of templates [Rn;C_rad_out_H/OneDe;Ypri_rad_out] + [R4_SSS;C_rad_out_single;Ypri_rad_out] for rate rule [R4_SSS;C_rad_out_H/OneDe;Opri_rad]
Euclidian distance = 2.2360679775
family: Birad_recombination"""),
)
reaction(
label = 'reaction52',
reactants = ['[CH2]C=COC([CH2])[O](6739)'],
products = ['C=CC1CC([O])O1(12647)'],
transitionState = 'TS52',
kinetics = Arrhenius(A=(1.8e+12,'s^-1'), n=-0.1525, Ea=(7.90776,'kJ/mol'), T0=(1,'K'), comment="""Estimated using average of templates [Rn;C_rad_out_H/OneDe;Cpri_rad_out_2H] + [R4_SSS;C_rad_out_single;Cpri_rad_out_2H] for rate rule [R4_SSS;C_rad_out_H/OneDe;Cpri_rad_out_2H]
Euclidian distance = 2.0
family: Birad_recombination"""),
)
reaction(
label = 'reaction53',
reactants = ['[CH]OC([CH2])[O](1022)', '[CH]=C(64)'],
products = ['[CH2]C=COC([CH2])[O](6739)'],
transitionState = 'TS53',
kinetics = Arrhenius(A=(1.14854e+06,'m^3/(mol*s)'), n=0.575199, Ea=(34.3157,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [Y_rad;Birad] for rate rule [Cd_pri_rad;Birad]
Euclidian distance = 2.0
family: Birad_R_Recombination"""),
)
network(
label = '3396',
isomers = [
'[CH2]C=COC([CH2])[O](6739)',
],
reactants = [
('C=C[O](594)', 'C=CC=O(5269)'),
],
bathGas = {
'N2': 0.25,
'Ne': 0.25,
'He': 0.25,
'Ar': 0.25,
},
)
pressureDependence(
label = '3396',
Tmin = (1200,'K'),
Tmax = (1500,'K'),
Tcount = 10,
Tlist = ([1201.48,1213.22,1236.21,1269.31,1310.55,1356.92,1404.16,1447.02,1479.84,1497.7],'K'),
Pmin = (1,'atm'),
Pmax = (10,'atm'),
Pcount = 10,
Plist = ([1.02771,1.14872,1.41959,1.89986,2.67608,3.83649,5.40396,7.23219,8.93758,9.98989],'bar'),
maximumGrainSize = (0.5,'kcal/mol'),
minimumGrainCount = 250,
method = 'modified strong collision',
interpolationModel = ('Chebyshev', 6, 4),
activeKRotor = True,
activeJRotor = True,
rmgmode = True,
)
| [
"dinius.ab@husky.neu.edu"
] | dinius.ab@husky.neu.edu |
a607cfd0c82f0951367c489f47dad4d25eb49d58 | 00829e1ff78f73dab073a201d68139960c1d1922 | /tools/toolset/tool/rigging/pipline_tool/ui/his/ui_create_character.py | 42c99cc1874dedb0e213f77abca01d3414e1a31e | [] | no_license | liangyongg/Beam_Tools | a021ceb4187107508536c46726da5b9629ffd1cf | 21b5d06e660f058434e589ae4f672f96296b7540 | refs/heads/master | 2018-11-04T04:43:02.523654 | 2018-08-26T12:33:09 | 2018-08-26T12:33:09 | 115,005,481 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,908 | py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_create_character.ui'
#
# Created: Thu Apr 26 11:29:46 2018
# by: pyside-uic 0.2.15 running on PySide 1.2.4
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(430, 262)
self.verticalLayout = QtGui.QVBoxLayout(Form)
self.verticalLayout.setObjectName("verticalLayout")
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setContentsMargins(-1, -1, 50, -1)
self.horizontalLayout.setObjectName("horizontalLayout")
self.label = QtGui.QLabel(Form)
self.label.setObjectName("label")
self.horizontalLayout.addWidget(self.label)
self.lineEdit = QtGui.QLineEdit(Form)
self.lineEdit.setObjectName("lineEdit")
self.horizontalLayout.addWidget(self.lineEdit)
self.verticalLayout.addLayout(self.horizontalLayout)
self.verticalLayout_2 = QtGui.QVBoxLayout()
self.verticalLayout_2.setContentsMargins(50, -1, 50, -1)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.pushButton = QtGui.QPushButton(Form)
self.pushButton.setObjectName("pushButton")
self.verticalLayout_2.addWidget(self.pushButton)
self.verticalLayout.addLayout(self.verticalLayout_2)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("Form", "name:", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton.setText(QtGui.QApplication.translate("Form", "create", None, QtGui.QApplication.UnicodeUTF8))
| [
"hhhh"
] | hhhh |
26167a55797b51de9a737b401be65741bbeeaf68 | 56c60735c500e69ee546de493c8f42a7752624a7 | /botDS.py | 93588109d4c2744ff28b8dc73b9126b75b382e61 | [] | no_license | bialx/bot | 4e703fb22152a86a22751187d48f8985c84d26c6 | f2783ba17f07cb0a746f4e690c58e04b2649002b | refs/heads/master | 2020-03-23T02:27:58.818158 | 2018-07-14T20:16:45 | 2018-07-14T20:16:45 | 140,975,237 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,063 | py |
# id : https://discordapp.com/oauth2/authorize?client_id=465241470182621214&scope=bot&permissions=0
import discord
from discord.ext import commands
import os
import pickle
import random
import aiohttp
from aiohttp import web
import asyncio
TOKEN = 'NDY1MjQxNDcwMTgyNjIxMjE0.DiKpcw.U2WHrB_RYEFKc4X0FSxKDWniDOo'
grid = ['-']*9
listeplayer = []
liste_classe = [
'eca',
'eni',
'iop',
'cra',
'feca',
'sacri',
'sadi',
'osa',
'enu',
'sram',
'xel',
'panda',
'roub',
'zobal',
'elio',
'steam',
'ougi',
'hupper',
]
listeA = []
listeB = []
listeBan = []
def rules():
print ("Bienvenue dans ce jeu de morpion")
print ("Pour jouer un coup donner la case a jouer ! (0 en haut a gauche, 2 en haut a droite, 8 en bas a droite)")
def morpion():
rules()
return 0
def classement(l, personne):
n = 0
for i in range(0, len(l)):
e = l[i]
joueur = e[0]
score = e[1]
if joueur == personne:
score = score + 1
e[1] = score
n = 1
break
if n == 0:
l.append([personne, 1])
classer = sorted(l, key=lambda v: v[1], reverse=True)
return classer
def display(grid):
for i in range(0,3):
print(" "+str(grid[3*i]) + "|" + str(grid[3*i+1]) + "|" + str(grid[3*i+2]))
return
def gagne(grid,player):
for i in range(0,3):
if (grid[3*i] == grid[3*i+1] == grid[3*i+2] == player):
return 1
for i in range(0,3):
if (grid[i] == grid[i+3] == grid[i+6]== player):
return 1
if (grid[2] == grid[4] == grid[6]== player):
return 1
if (grid[0] == grid[4] == grid[8]== player):
return 1
else:
return 0
def play(player, i, grid):
if (grid[i] != "-"):
print("case invalide veuillez rejouer")
else:
grid[i] = player
if gagne(grid,player) == 1:
print ("Le joueur %s a gagne ! felicitation", player)
display(grid)
return grid
def clean(grid):
for i in range(0,9):
grid[i] = '-'
return 0
description = '''Bot Python'''
bot = commands.Bot(command_prefix='!', description='on code pas un bot de merde nouuuuus')
bot.remove_command('help')
@bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
@bot.command()
async def bibi():
embed = discord.Embed(title="Botons en touche", description="Listes des commandes:", color=0xeee657)
embed.add_field(name="!mp 'P' I", value="Permet de jouer à un jeu de morpion. Le joueur courant 'X' ou '0' doit passer dans l'argument **P** et la case sur laquelle jouer est **I**.\nLes cases vont de 1 à 9, à lire de gauche à droite et de haut en bas", inline=False)
embed.add_field(name="!NTM", value = "permet d\'insulter un membre aléatoire du discord et de le mentionner directement, parfait pour vous calmer apres un petit koli vs 3piliers espagnol JAJAJAJA", inline=False)
await bot.say(embed=embed)
@bot.command()
async def cleanmp():
clean(grid)
await bot.say("Le jeu de morpion a été réinitialisé vous pouvez jouer !")
@bot.command(pass_context = True)
async def mp(context, player: str , pos):
auth = str(context.message.author).split('#')[0]
try:
pos = int(pos)
except:
await bot.say("Tu te prends pour qui la ? de 1 à 9 les cases, on dirait kyky ca sait pas compter.....")
return 0
c = 0
pos2 = pos - 1
if player != 'X' and player != 'O':
await bot.say("T'es con comme sledax toi croix ou round rien d'autre fdp :fencer:")
return 0
if pos2 < 0 or pos2 > 9 or grid[pos2] != '-' :
await bot.say("Mauvaise case espèce de débile")
else:
play(player, pos2, grid)
for i in range(0,9):
if grid[i] != '-':
c += 1
for i in range(0,3):
await bot.say(str(grid[3*i]) + " | " + str(grid[3*i+1]) + " | " + str(grid[3*i+2]))
if c == 9 and gagne(grid,player) == 0:
await bot.say("Match nul wola NUL NUL NUL")
clean(grid)
if gagne(grid,player) == 1:
await bot.say("Le joueur {} a gagné, mes félicitations {} !".format(player,auth))
fd = open("classement.txt", "w")
l = classement(listeplayer, auth)
# with open('classement.txt', 'wb') as fichier:
# mon_pickler = pickle.Pickler(fichier)
# mon_pickler.dump(l)
await bot.say(" :dab: :dab: :dab: :dab: ")
clean(grid)
fd.close()
@bot.command()
async def rankingmp():
fd = open("classement.txt", "w")
if len(listeplayer) == 0:
await bot.say("Aucun joueur n'est actuellement classé")
for i in range(0, len(listeplayer)):
p = listeplayer[i]
await bot.say("{}. {} -> {} points\n".format(i+1, p[0],p[1]))
fd.write("{}. {} -> {} points\n".format(i+1, p[0],p[1]))
fd.close()
#Insulte aléatoire un membre du discord
@bot.command(pass_context = True)
async def swear(context):
mem = 0 #nombre de membre dans le serveur du bot
nb = 0 #nombre de ligne du fichier d'insulte
c = 0 #compteur pour le fichier insulte
d = 0 #compteur pour prendre un membre random
if context.message.author == "Sledax#8137" or context.message.author== "ulkile#9617":
await bot.say("Ptdrrr " + context.message.author.mention + " tu te prends pour qui à vouloir insulter des gens ? t'es la pute de tout le monde")
#On compte le nombre de ligne dans le fichier pour choisir une ligne aléatoire
fich = open("insulte.txt")
for line in fich:
nb += 1
n = random.randint(1,nb+1)
fich.close()
#On compte le nombre de membres dans le serveur puis on en prend un au hasard
for server in bot.servers:
members = server.members
for m in members:
mem += 1
n2 = random.randint(1,mem+1)
print(n2)
for m in members:
d += 1
if d == n2:
target = m
print (target)
fich = open("insulte.txt")
for line in fich:
c += 1
if c == n:
line2 = line.split("• ")[1]
line3 = line2.split("\n")[0]
line4 = list(line3)
print(line4)
print(line4[len(line4)-1 ])
if line4[len(line4)-1 ] == 'e':
await bot.say(target.mention + " tu es une " + line2.lower())
else:
await bot.say(target.mention + " tu es un " + line2.lower())
fich.close()
@bot.command()
async def clearD():
liste_classe = [
'eca',
'eni',
'iop',
'cra',
'feca',
'sacri',
'sadi',
'osa',
'enu',
'sram',
'xel',
'panda',
'roub',
'zobal',
'elio',
'steam',
'ougi',
'hupper',
]
listeA = []
listeB = []
listeBan = []
@bot.command(pass_context = True)
async def draft(contexte, side, choix, classe):
if choix == 'p' and side == 'A':
listeA.append(classe)
if choix == 'p' and side == 'B':
listeB.append(classe)
elif choix == 'b':
listeBan.append(classe)
liste_classe.remove(classe)
msgPick = "-".join(listeA) + " vs " + "-".join(listeB) + "\n"
msgBan = "-".join(listeBan) + "\n"
msgRest = " ".join(liste_classe)
# await bot.say(msg)
embed = discord.Embed(title="DRAFT", color=0xeee657)
embed.add_field(name="Pick", value = msgPick, inline=False)
embed.add_field(name="Ban", value = msgBan ,inline=False)
embed.add_field(name="Classes restantes : ", value = msgRest ,inline=False)
await bot.say(embed=embed)
# @bot.event
# async def on_message(message):
# if message.content.startswith('t\'es con ?'):
# await bot.send_message(message.channel, 't\'es con ?')
# msg = await bot.wait_for_message(content='t\'es con ?')
# await bot.send_message(message.channel, 't\'es con ?')
bot.run(TOKEN)
| [
"noreply@github.com"
] | bialx.noreply@github.com |
0b2b5899160b350128d8d74c3257841738ba6249 | 5bcc9e2f3394152a01c4fe803ec5bd0f9a4dd678 | /client/ultrasonic.py | f52be5bfb8d33586dee05445388a2ce81cad7777 | [] | no_license | TXZhe/Magic_Mirror | 74cb3414dde73703f9d2855e8c3bad3b15856676 | 3b7b1d9a09535c2b9aef459fdb7ec38e02f8010b | refs/heads/master | 2020-03-18T16:22:04.675059 | 2018-07-16T14:29:52 | 2018-07-16T14:29:52 | 134,961,885 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 843 | py | import RPi.GPIO as GPIO
import time
TRIG = 23
ECHO = 24
class UltraSonic:
def __init__(self):
GPIO.setmode(GPIO.BCM)
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
GPIO.output(TRIG, False)
'''
def __del__(self):
GPIO.cleanup()
'''
def distance(self):
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
while GPIO.input(ECHO)==0:
pulse_start = time.time()
while GPIO.input(ECHO)==1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration*17150
distance = round(distance, 2)
print distance
return distance
if __name__ == '__main__':
test = UltraSonic()
for i in range(5):
print test.distance()
time.sleep(1)
GPIO.cleanup()
| [
"450111801@qq.com"
] | 450111801@qq.com |
ce74a238c917af6de5cfc93964163002750f06d8 | 59de7788673ade984b9c9fbc33664a7cbdba67d3 | /res/scripts/client_common/shared_utils/__init__.py | 9b417b171ce7cf3e50a53c5b6006973b705af2f6 | [] | no_license | webiumsk/WOT-0.9.15-CT | 3fa24ab37a6c91b7073034afb2f355efa5b7fe36 | fbd194fbaa6bdece51c7a68fc35bbb5257948341 | refs/heads/master | 2020-12-24T21:27:23.175774 | 2016-05-01T13:47:44 | 2016-05-01T13:47:44 | 57,600,180 | 0 | 0 | null | null | null | null | WINDOWS-1250 | Python | false | false | 4,366 | py | # 2016.05.01 15:25:53 Střední Evropa (letní čas)
# Embedded file name: scripts/client_common/shared_utils/__init__.py
import weakref
import itertools
import types
import BigWorld
from debug_utils import LOG_ERROR, LOG_WARNING
ScalarTypes = (types.IntType,
types.LongType,
types.FloatType,
types.BooleanType) + types.StringTypes
IntegralTypes = (types.IntType, types.LongType)
def makeTupleByDict(ntClass, data):
unsupportedFields = set(data) - set(ntClass._fields)
supported = {}
for k, v in data.iteritems():
if k not in unsupportedFields:
supported[k] = v
return ntClass(**supported)
class BoundMethodWeakref(object):
def __init__(self, func):
self.methodName = func.__name__
raise not self.methodName.startswith('__') or AssertionError('BoundMethodWeakref: private methods are not supported')
self.wrefCls = weakref.ref(func.__self__)
def __call__(self, *args, **kwargs):
return getattr(self.wrefCls(), self.methodName)(*args, **kwargs)
def forEach(function, sequence):
for e in sequence:
function(e)
def isEmpty(sequence):
try:
next(sequence)
except StopIteration:
return True
return False
def safeCancelCallback(callbackID):
try:
BigWorld.cancelCallback(callbackID)
except ValueError:
LOG_ERROR('Cannot cancel BigWorld callback: incorrect callback ID.')
def prettyPrint(dict, sort_keys = True, indent = 4):
import json
return json.dumps(dict, sort_keys=sort_keys, indent=indent)
def findFirst(function_or_None, sequence, default = None):
try:
return next(itertools.ifilter(function_or_None, sequence))
except StopIteration:
return default
def first(sequence, default = None):
return findFirst(None, sequence, default)
class CONST_CONTAINER(object):
__keyByValue = None
@classmethod
def getIterator(cls):
for k, v in cls.__dict__.iteritems():
if not k.startswith('_') and type(v) in ScalarTypes:
yield (k, v)
@classmethod
def getKeyByValue(cls, value):
cls.__doInit()
return cls.__keyByValue.get(value)
@classmethod
def hasKey(cls, key):
return key in cls.__dict__
@classmethod
def hasValue(cls, value):
cls.__doInit()
return value in cls.__keyByValue
@classmethod
def ALL(cls):
return tuple([ v for k, v in cls.getIterator() ])
@classmethod
def __doInit(cls):
if cls.__keyByValue is None:
cls.__keyByValue = dict(((v, k) for k, v in cls.getIterator()))
return
class BitmaskHelper(object):
@classmethod
def add(cls, mask, flag):
if not mask & flag:
mask |= flag
return mask
return -1
@classmethod
def addIfNot(cls, mask, flag):
if not mask & flag:
mask |= flag
return mask
@classmethod
def remove(cls, mask, flag):
if mask & flag > 0:
mask ^= flag
return mask
return -1
@classmethod
def removeIfHas(cls, mask, flag):
if mask & flag > 0:
mask ^= flag
return mask
class AlwaysValidObject(object):
def __init__(self, name = ''):
self.__name = name
def __getattr__(self, item):
if item in self.__dict__:
return self.__dict__[item]
return AlwaysValidObject(self._makeName(self.__name, item))
def __call__(self, *args, **kwargs):
return AlwaysValidObject()
def getName(self):
return self.__name
@classmethod
def _makeName(cls, parentName, nodeName):
return '%s/%s' % (parentName, nodeName)
def isDefaultDict(sourceDict, defaultDict):
for k, v in defaultDict.iteritems():
if k not in sourceDict:
return False
if sourceDict[k] != v:
return False
return True
def nextTick(func):
"""
Moves function calling to the next frame
"""
def wrapper(*args, **kwargs):
BigWorld.callback(0.01, lambda : func(*args, **kwargs))
return wrapper
# okay decompyling c:\Users\PC\wotsources\files\originals\res\scripts\client_common\shared_utils\__init__.pyc
# decompiled 1 files: 1 okay, 0 failed, 0 verify failed
# 2016.05.01 15:25:53 Střední Evropa (letní čas)
| [
"info@webium.sk"
] | info@webium.sk |
4cec80ef5706409c00bd637115c1cd8fac68858c | aab3df1e96ef417a6f85837eca1d640b787e1276 | /sklearn_porter/estimator/classifier/KNeighborsClassifier/__init__.py | 401a6844995e4c7e01075a246cbf79d7bff3a43d | [
"MIT"
] | permissive | apasanen/sklearn-porter | 88634b6f4985e1cd1ee09869495a8a3a3f6c1134 | 43a403c45c7538876df5dbe3c2f79e4aca965d47 | refs/heads/master | 2020-04-10T21:28:19.501112 | 2018-12-11T08:39:40 | 2018-12-11T09:21:05 | 161,297,343 | 0 | 0 | MIT | 2018-12-11T07:52:21 | 2018-12-11T07:52:21 | null | UTF-8 | Python | false | false | 8,456 | py | # -*- coding: utf-8 -*-
import os
import json
from json import encoder
from sklearn_porter.estimator.classifier.Classifier import Classifier
class KNeighborsClassifier(Classifier):
"""
See also
--------
sklearn.neighbors.KNeighborsClassifier
http://scikit-learn.org/stable/modules/generated/
sklearn.neighbors.KNeighborsClassifier.html
"""
SUPPORTED_METHODS = ['predict']
# @formatter:off
TEMPLATES = {
'java': {
'type': '{0}',
'arr': '{{{0}}}',
'arr[]': '{type}[] {name} = {{{values}}};',
'arr[][]': '{type}[][] {name} = {{{values}}};',
'indent': ' ',
},
'js': {
'type': '{0}',
'arr': '[{0}]',
'arr[]': 'var {name} = [{values}];',
'arr[][]': 'var {name} = [{values}];',
'indent': ' ',
},
}
# @formatter:on
def __init__(self, estimator, target_language='java',
target_method='predict', **kwargs):
"""
Port a trained estimator to the syntax of a chosen programming
language.
Parameters
----------
:param estimator : KNeighborsClassifier
An instance of a trained KNeighborsClassifier estimator.
:param target_language : string, default: 'java'
The target programming language.
:param target_method : string, default: 'predict'
The target method of the estimator.
"""
super(KNeighborsClassifier, self).__init__(
estimator, target_language=target_language,
target_method=target_method, **kwargs)
if estimator.weights != 'uniform':
msg = "Only 'uniform' weights are supported for this classifier."
raise NotImplementedError(msg)
self.estimator = estimator
def export(self, class_name, method_name, export_data=False,
export_dir='.', export_filename='data.json',
export_append_checksum=False, **kwargs):
"""
Port a trained estimator to the syntax of a chosen programming language.
Parameters
----------
:param class_name : string
The name of the class in the returned result.
:param method_name : string
The name of the method in the returned result.
:param export_data : bool, default: False
Whether the model data should be saved or not.
:param export_dir : string, default: '.' (current directory)
The directory where the model data should be saved.
:param export_filename : string, default: 'data.json'
The filename of the exported model data.
:param export_append_checksum : bool, default: False
Whether to append the checksum to the filename or not.
Returns
-------
:return : string
The transpiled algorithm with the defined placeholders.
"""
# Arguments:
self.class_name = class_name
self.method_name = method_name
# Estimator:
est = self.estimator
# Basic parameters:
self.metric = est.metric
self.n_classes = len(est.classes_)
self.n_templates = len(est._fit_X) # pylint: disable=W0212
self.n_features = len(est._fit_X[0]) # pylint: disable=W0212
self.n_neighbors = est.n_neighbors
self.algorithm = est.algorithm
self.power_param = est.p
if self.algorithm != 'brute':
from sklearn.neighbors.kd_tree import KDTree # pylint: disable-msg=E0611
from sklearn.neighbors.ball_tree import BallTree # pylint: disable-msg=E0611
tree = est._tree # pylint: disable=W0212
if isinstance(tree, (KDTree, BallTree)):
self.tree = tree
if self.target_method == 'predict':
# Exported:
if export_data and os.path.isdir(export_dir):
self.export_data(export_dir, export_filename,
export_append_checksum)
return self.predict('exported')
# Separated:
return self.predict('separated')
def export_data(self, directory, filename, with_md5_hash=False):
"""
Save model data in a JSON file.
Parameters
----------
:param directory : string
The directory.
:param filename : string
The filename.
:param with_md5_hash : bool, default: False
Whether to append the checksum to the filename or not.
"""
model_data = {
'X': self.estimator._fit_X.tolist(), # pylint: disable=W0212
'y': self.estimator._y.tolist(), # pylint: disable=W0212
'kNeighbors': self.n_neighbors,
'nClasses': self.n_classes,
'power': self.power_param
}
encoder.FLOAT_REPR = lambda o: self.repr(o)
json_data = json.dumps(model_data, sort_keys=True)
if with_md5_hash:
import hashlib
json_hash = hashlib.md5(json_data).hexdigest()
filename = filename.split('.json')[0] + '_' + json_hash + '.json'
path = os.path.join(directory, filename)
with open(path, 'w') as fp:
fp.write(json_data)
def predict(self, temp_type):
"""
Transpile the predict method.
Parameters
----------
:param temp_type : string
The kind of export type (embedded, separated, exported).
Returns
-------
:return : string
The transpiled predict method as string.
"""
# Exported:
if temp_type == 'exported':
temp = self.temp('exported.class')
return temp.format(class_name=self.class_name,
method_name=self.method_name,
n_features=self.n_features)
# Separated:
if temp_type == 'separated':
meth = self.create_method()
return self.create_class(meth)
def create_method(self):
"""
Build the estimator method or function.
Returns
-------
:return : string
The built method as string.
"""
# Distance computation
metric_name = '.'.join(['separated', 'metric', self.metric])
distance_comp = self.temp(metric_name, n_indents=1, skipping=True)
temp_method = self.temp('separated.method.predict', n_indents=1,
skipping=True)
return temp_method.format(class_name=self.class_name,
method_name=self.method_name,
distance_computation=distance_comp)
def create_class(self, method):
"""
Build the estimator class.
Returns
-------
:return : string
The built class as string.
"""
temp_type = self.temp('type')
temp_arr = self.temp('arr')
temp_arr_ = self.temp('arr[]')
temp_arr__ = self.temp('arr[][]')
# Samples:
temps = []
for atts in enumerate(self.estimator._fit_X): # pylint: disable=W0212
tmp = [temp_type.format(self.repr(a)) for a in atts[1]]
tmp = temp_arr.format(', '.join(tmp))
temps.append(tmp)
temps = ', '.join(temps)
temps = temp_arr__.format(type='double', name='X', values=temps,
n=self.n_templates, m=self.n_features)
# Classes:
classes = self.estimator._y # pylint: disable=W0212
classes = [temp_type.format(int(c)) for c in classes]
classes = ', '.join(classes)
classes = temp_arr_.format(type='int', name='y', values=classes,
n=self.n_templates)
temp_class = self.temp('separated.class')
return temp_class.format(class_name=self.class_name,
method_name=self.method_name, method=method,
n_features=self.n_features, X=temps, y=classes,
n_neighbors=self.n_neighbors,
n_templates=self.n_templates,
n_classes=self.n_classes,
power=self.power_param)
| [
"darius.morawiec@nok.onl"
] | darius.morawiec@nok.onl |
52790bf2abe2bc685b4f7e3d84b7a57846ce14d8 | ca9b9ece987e948b4373654bda555cd89330dd2e | /venv/bin/django-admin | cfcb2c10e2c507a5d9dee79a25fb4f836df6b3ec | [] | no_license | Tamim101/portfolio | 2795ecb1aeb504010603d41c9199cc8dbd8a6eb3 | 60cc69bae3557d816b35c7685bf5ff03b6f6e29c | refs/heads/master | 2023-03-17T19:07:05.112382 | 2021-03-13T13:22:22 | 2021-03-13T13:22:22 | 344,207,829 | 0 | 0 | null | 2021-03-13T13:22:23 | 2021-03-03T17:27:33 | Python | UTF-8 | Python | false | false | 305 | #!/home/tamim/PycharmProjects/portfolio_pink/venv/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from django.core.management import execute_from_command_line
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(execute_from_command_line())
| [
"tamimkhan7133@gmail.com"
] | tamimkhan7133@gmail.com | |
d60e67e7956b681d4e6625da2a48b77f247e407e | 2f0efc8c179ba33c56e66e5421a65dfa6631fae7 | /learnpythoncode/leapyear.py | 45dbc77f426ca2018464ff579eb3263d1f051b20 | [] | no_license | testgurus/python | f0f8f00062be248dfcc7729ccb542fbf1f83f03a | 212f346244a9efba2bd7951c46c1dbe1f7277532 | refs/heads/master | 2021-01-21T10:51:58.598197 | 2017-09-16T21:03:41 | 2017-09-16T21:03:41 | 101,991,751 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 209 | py | year = input("Enter year: ")
if year.isalpha():
print("Enter only number")
year = input("Enter year: ")
y = int(year)
if(y % 4) == 0:
print("{0} is a leap year")
else:
print("{0} is not a leap year") | [
"ravi.mca.chauhan@gmail.com"
] | ravi.mca.chauhan@gmail.com |
908f096cd27da560b36d3a1fce83253f7716a801 | 893a3dda2e5f8aac4b6c07ae3404074f1dd1465c | /chap2/video_writer.py | 2c33b8b2a9884570e5d78404681f28a71a04d893 | [] | no_license | chenjingfan14/ee674Flight_Dynamics-master | 98053c649e128b96d1057e5c2f67c67aacfb2484 | 2480f2b4c9a5b55c7e7a46d69b39134a18752b5e | refs/heads/master | 2022-04-14T12:46:49.276826 | 2020-04-04T06:39:14 | 2020-04-04T06:39:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,320 | py | """
mavsimPy: video making function
- Beard & McLain, PUP, 2012
- Update history:
1/10/2019 - RWB
"""
import numpy as np
import cv2
#from PIL import ImageGrab
class video_writer():
def __init__(self, video_name="video.avi", bounding_box=(0, 0, 1000, 1000), output_rate = 0.1):
# bbox specifies specific region (bbox= top_left_x, top_left_y, width, height)
# set up video writer by grabbing first image and initializing
img = ImageGrab.grab(bbox=bounding_box)
img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
height, width, channels = img.shape
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
self.video = cv2.VideoWriter(video_name, fourcc, 20.0, (width, height))
self.bounding_box = bounding_box
self.output_rate = output_rate
self.time_of_last_frame = 0
###################################
# public functions
def update(self, time):
if (time-self.time_of_last_frame) >= self.output_rate:
img = ImageGrab.grab(bbox=self.bounding_box)
img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
self.video.write(img)
self.time_of_last_frame = time
def close(self):
self.video.release()
| [
"noreply@github.com"
] | chenjingfan14.noreply@github.com |
abcdca2d558b3f49a0a8e90bd7073824ebc3b77a | 12663ec882f7f7c2c9e9dd3095e1ba4be6c580e0 | /mysiteS19/myapp/models.py | 1b36222411863b0eb602d9b7cd95c4fbfe26a2f1 | [] | no_license | khyati2304/Life-Sport-Store | 3a4787487c0d1e0c864632e58206a76f8ba5f0ef | fe57c6fd7572dc70e57e970b528c4043f9ed564e | refs/heads/master | 2020-06-12T14:50:39.992581 | 2019-06-28T21:11:08 | 2019-06-28T21:11:08 | 194,334,548 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,626 | py | from django.db import models
import datetime
from django.contrib.auth.models import User
from django.utils import timezone
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=200)
warehouse = models.CharField(max_length=100, default="Windsor")
class Meta:
ordering = ['id']
def __str__(self):
return self.name
class Product(models.Model):
category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE)
name = models.CharField(max_length=200)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField(default=100)
available = models.BooleanField(default=True)
description = models.TextField(max_length=500, blank=True, default='')
class Meta:
ordering = ['id']
def __str__(self):
return '{}{}{}{}{}{}'.format(self.name, self.category.name, self.price, self.stock, self.available,
self.description)
class Client(User):
PROVINCE_CHOICES = [('AB', 'Alberta'), ('MB', 'Manitoba'), ('ON', 'Ontario'), ('QC', 'Quebec'), ]
company = models.CharField(max_length=50, blank=True, default='')
shipping_address = models.CharField(max_length=300, null=True, blank=True)
city = models.CharField(max_length=20, default="Windsor")
province = models.CharField(max_length=2, choices=PROVINCE_CHOICES, default='ON')
interested_in = models.ManyToManyField(Category)
class Meta:
ordering = ['id']
def __str__(self):
return '{}{}{}{}{}{}{}'.format(self.first_name, self.last_name, self.company, self.shipping_address, self.city,
self.province, self.interested_in)
class Order(models.Model):
product = models.ForeignKey(Product, related_name="product", on_delete=models.CASCADE)
client = models.ForeignKey(Client, related_name="clients", on_delete=models.CASCADE)
num_units = models.PositiveIntegerField(default=100)
status_choices = [(0, 'Order Cancelled'), (1, 'Order Placed'), (2, 'Order Shipped'), (3, 'Order Delivered')]
order_status = models.IntegerField(choices=status_choices, default=1)
status_date = models.DateField("Date", default=datetime.date.today)
class Meta:
ordering = ['id']
def total_cost(self):
return self.num_units * self.product.price
def __str__(self):
return '{}{}{}{}{}'.format(self.product.name, self.client.first_name, self.client.last_name, self.num_units,
self.order_status, self.status_date)
| [
"patel1so@uwindsor.ca"
] | patel1so@uwindsor.ca |
fde158d70c7cb58f45944cee248462fd1bc999ca | d17055e15f88fae2597115ff98ce8006ceda1d51 | /pooltable_manager.py | 58934a5665320d11556109eb269703bf8bfe5e72 | [] | no_license | welchsoft/pool_table_project | 3ba7946520b5b8274a11451d9f5f19e80414f5dc | 010d53df7c97d5af7d72a9483428f755f8f9692c | refs/heads/master | 2020-03-16T17:14:03.880580 | 2018-07-15T22:55:59 | 2018-07-15T22:55:59 | 132,822,925 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,245 | py | #import datetime
from datetime import datetime
import time
from pooltable import Pooltable
import json
import os
import smtplib
from email.message import EmailMessage
class Manager:
def __init__(self):
self.table_count = 12
self.hourly_rate = 30.0
self.table_array = []
self.dict_array = []
self.report_array = []
self.config = {}
self.flag = True
self.total_sales = 0
#checks to make sure pool tables are cashed out before allowing a re-initialization of pool tables
# figure out on the fly pool table count changes and hourly rate changes
def table_reset_permissions(self):
self.flag = True
for table in self.table_array:
if table.status == "occupied":
print(f"Table[{table.table_number}] is occupied cash out first!")
self.flag = False
if self.flag == False:
print("Error you must cash out before proceeding")
input()
else:
return True
#changes the table count, checks permission first, saves to config then re-initialized tables
def change_table_count(self,new_table_count):
if self.table_reset_permissions():
self.table_count = new_table_count
self.dump_config()
self.set_up_tables()
input(f"Table count is now: {self.table_count}")
#changes the hourly rate, checks permission first, saves to config then re-initialized tables
def change_hourly_rate(self,new_hourly_rate):
if self.table_reset_permissions():
self.hourly_rate = new_hourly_rate
self.dump_config()
self.set_up_tables()
input(f"Hourly Rate is now: ${self.hourly_rate}")
#used for reinitalization of tables, checks permission first
def set_up_tables(self):
if self.table_reset_permissions():
self.table_array = []
for index in range(1,self.table_count+1):
self.table_array.append(Pooltable(index,"open",self.hourly_rate))
print("I AM THE TABLE!")
self.big_dump()
#forced re-initialize tables, NO PERMISSIONS CHECK!
def force_set_up_tables(self):
self.table_array = []
for index in range(1,self.table_count+1):
self.table_array.append(Pooltable(index,"open",self.hourly_rate))
print("I AM THE TABLE!")
self.big_dump()
#reads in table state from .json file, if nothing there it calls set up tables instead
def load_table_state(self):
os.system("touch pooltable_save_state.json")
with open('pooltable_save_state.json') as file:
file.seek(0)
first_char = file.read(1)
if not first_char:
self.set_up_tables()
return
else:
with open('pooltable_save_state.json') as load_table:
self.dict_array = json.load(load_table)
#dumps the array and loads in the .json record, stay sour python pickle users!
self.table_array = []
for dict in self.dict_array:
pooltable = Pooltable(dict["table_number"],dict["status"],dict["rate"])
pooltable.rebuild(dict["start_stamp"],dict["start_time"],dict["end_stamp"],dict["end_time"],dict["total_stamp"],dict["total_time"],dict["sales"])
self.table_array.append(pooltable)
#displays the tables and their state, shouldnt this be in the main menu???
def display_tables(self):
for table in self.table_array:
if table.status == "occupied":
print(f"TABLE[{table.table_number}]\t[\33[94m{table.status.upper()}\33[0m]\t[Start: {table.start_stamp}: Play Time: {round((time.time() - table.start_time)/60,2)} minutes]")
elif table.status == "closed":
print(f"TABLE[{table.table_number}]\t[\33[91m{table.status.upper()}\33[0m]\t[Down Since: {table.start_stamp}]")
else:
print(f"TABLE[{table.table_number}]\t[\33[92m{table.status.upper()}\33[0m]")
#Tried to make 2 columns, didnt work out maybe some day!
#if len(self.table_array)%2 == 0:
# split_index = int(len(self.table_array)/2)
#else:
# split_index = int((len(self.table_array)+1)/2)
#for index in range(split_index):
# print(f"Table[{self.table_array[index].table_number}]: {self.table_array[index].status}:",end= '\t')
#for index in range(split_index,len(self.table_array)):
# print(f"Table[{self.table_array[index].table_number}]: {self.table_array[index].status}:")
#consider moving to views also show time stamps in menu
#set table to occupied
def rent_out_table(self,table_select):
if table_select not in range(len(self.table_array)):
print("incorrect table number try again")
else:
self.table_array[table_select].occupy_table()
self.big_dump()
#cash out occupied table
def cash_out(self,table_select):
if table_select not in range(len(self.table_array)):
print("incorrect table number try again")
else:
self.table_array[table_select].cash_table()
self.append_report(table_select)
self.big_dump()
self.total_sales_lookup()
#revive table that is in maintenance
def open_up_table(self,table_select):
if table_select not in range(len(self.table_array)):
print("incorrect table number try again")
else:
self.table_array[table_select].open_table()
self.big_dump()
#put a table out of its misery
def close_table(self,table_select):
if table_select not in range(len(self.table_array)):
print("incorrect table number try again")
else:
self.table_array[table_select].close_table()
self.append_report(table_select)
self.big_dump()
#constructs array of dictionaries that are table objects cast to __dict__
def table_to_dict(self):
self.dict_array = []
for index in range(len(self.table_array)):
self.dict_array.append(self.table_array[index].__dict__)
#contrcuts the save state file, this keeps the state of tables between sessions
def big_dump(self):
self.table_to_dict()
with open('pooltable_save_state.json','w') as file:
file.write(json.dumps(self.dict_array,indent=2))
#makes Reports directory and generates files to it for each unique day of operation
def generate_report(self):
os.system("mkdir Reports")
self.report_date = time.strftime("%m-%d-%Y")
os.system("touch Reports/"+self.report_date+".json")
#Appends the report of the day any time it is called with new info
def append_report(self,table_select):
self.generate_report()
with open("Reports/"+self.report_date+".json",'r+') as file:
file.seek(0)
first_char = file.read(1)
if not first_char:
file.write("[]")
else:
with open("Reports/"+self.report_date+".json") as load_report:
self.report_array = json.load(load_report)
self.report_array.append(self.table_array[table_select].__dict__)
with open("Reports/"+self.report_date+".json",'w') as report_json:
report_json.write(json.dumps(self.report_array,indent=2))
def total_sales_lookup(self):
self.generate_report()
with open("Reports/"+self.report_date+".json",'r+') as file:
file.seek(0)
first_char = file.read(1)
if not first_char:
file.write("[]")
else:
with open("Reports/"+self.report_date+".json") as load_report:
self.report_array = json.load(load_report)
self.total_sales = 0
for report in self.report_array:
self.total_sales += report["sales"]
#allows the Manager to update its data from a config file
def update_from_config(self):
os.system("touch config.json")
with open('config.json') as config:
self.config = json.load(config)
self.table_count = self.config["table_count"]
self.hourly_rate = self.config["hourly_rate"]
#updates the config content
def dump_config(self):
self.config.update({"table_count":self.table_count, "hourly_rate":self.hourly_rate})
with open('config.json','w') as config:
config.write(json.dumps(self.config))
#send email of report for extreme hard mode
#error 61 apparently im being denied by either my ISP or by my email service
#probably for security or anti spam reasons
def send_email(self):
with open("Reports/"+self.report_date+".json") as fp:
msg = EmailMessage()
msg.set_content(fp.read())
msg['Subject'] = 'The contents of %s' % self.report_date+".json"
#be sure not to share personal email on github
msg['From'] = 'make up an email'
msg['To'] = 'make up an email'
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
#most of the code assumes table_count will not change after set-up has already been called
| [
"wade.c.welch@gmail.com"
] | wade.c.welch@gmail.com |
80e2f8af7ea59d0050205501609dac9eb0bc03e9 | e17ba18f57f14ab315789be2b6ac4f6bd6b01f65 | /blog/migrations/0004_auto_20171014_1452.py | ba847c3423b5bc59bae19f68586768c433a4a445 | [] | no_license | fangweiren/Django | 766715681b384f63ffb8d8cf4083cbad5db48a04 | afe42009596d5b77cc25a2c11057540859831eb2 | refs/heads/master | 2023-04-04T09:58:56.751711 | 2017-11-19T13:51:48 | 2017-11-19T13:51:48 | 105,427,129 | 0 | 0 | null | 2021-03-31T18:34:33 | 2017-10-01T07:49:59 | Python | UTF-8 | Python | false | false | 448 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0003_auto_20171014_1431'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='user_avatar',
field=models.ImageField(blank=True, upload_to='avatar', default='images/01.jpg'),
),
]
| [
"513069595@qq.com"
] | 513069595@qq.com |
65cf6179e020f271bc3a57d6184f464c168ce98e | c1150e6977b060ae60a7354813691cb937165b74 | /merge_txt.py | 9beaa7411da753d330f45a0eeb88fc54c3276441 | [] | no_license | loomis3632/extract | 4d6ecdf95fa0fa6ea7b60b37cb7615aa42544f9a | 4980f5ade1d2f4eed8edc781796035d532e5dca3 | refs/heads/master | 2021-05-18T06:59:29.132758 | 2020-04-24T07:57:19 | 2020-04-24T07:57:19 | 251,169,764 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,781 | py | # encoding: utf-8
"""
@author: baimianhuluwa
@time: 2020/4/22 15:11
@file: merge_txt.py
@desc:
"""
import os
import chardet
def get_all_path(open_file_path):
"""
获取当前目录以及子目录下所有的.txt文件,
:param open_file_path:
:return:
"""
rootdir = open_file_path
path_list = []
list = os.listdir(rootdir) # 列出文件夹下所有的目录与文件
for i in range(0, len(list)):
com_path = os.path.join(rootdir, list[i])
if os.path.isfile(com_path) and com_path.endswith(".txt"):
path_list.append(com_path)
if os.path.isdir(com_path):
path_list.extend(get_all_path(com_path))
return path_list
def get_encoding(file):
"""
# 获取文件编码类型
:param file: 文件路径
:return: 编码
"""
# 二进制方式读取,获取字节数据,不必全部read,检测编码类型
with open(file, 'rb') as f:
data = f.read(1024)
return chardet.detect(data)['encoding']
def merge_txt():
res_txt = r'E:\dataset\基金代码_pro\merge1.txt'
# rootdir = r'E:\dataset\test' # 待处理的数据文件夹
rootdir = r'E:\dataset\基金代码' # 待处理的数据文件夹
path_lists = get_all_path(rootdir)
print(path_lists)
count = 0
for path in path_lists:
count += 1
print(count)
coding = get_encoding(path)
with open(path, 'r', encoding=coding, errors='ignore') as rf, open(res_txt, 'a', encoding='utf-8',
errors='ignore') as wf:
for line in rf:
count += 1
print(count)
wf.write(line)
if __name__ == '__main__':
merge_txt()
| [
"“614798797@qq.comgit config --global user.name “loomis3632"
] | “614798797@qq.comgit config --global user.name “loomis3632 |
01bc8dd81cafcbbf52dd9b8525c0fd40f828b6f4 | 274521d5ccfbaebb97cdfbfa340d951eee7c9efa | /Python/PythonProgrammingLanguage/Encapsulation/encap_env/bin/jsonschema | 116515a0218c94456db568d63ab738fffe5c5f5e | [
"MIT"
] | permissive | nitin-cherian/LifeLongLearning | ef8e1ed61e4bf8b6ae4a0ae642c559ab47be84b4 | 84084792058358365162c645742c70064a2d5fd6 | refs/heads/master | 2021-01-21T10:38:41.797326 | 2018-08-23T01:28:10 | 2018-08-23T01:28:10 | 91,701,351 | 6 | 0 | null | null | null | null | UTF-8 | Python | false | false | 323 | #!/home/nitin/Learn/Repositories/Github/LifeLongLearning/Python/PythonProgrammingLanguage/Encapsulation/encap_env/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from jsonschema.cli import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"nitin.cherian@gmail.com"
] | nitin.cherian@gmail.com | |
76ba202c34534ea332d0d9c2b7c22175514cb943 | bf331831c2c532d76b91c11127cc4c76cf9f0031 | /166/D/ans_errorneous.py | eac398768204dd7b212a8fb9e6f37ee62331d50c | [] | no_license | mugenen/Codeforces-Solution | 519899d658a52dc87bfdba81110e9851ccf3b6de | f69874ad46acc511f4485dc29249f7010f562ea9 | refs/heads/master | 2021-01-22T04:49:48.986989 | 2013-02-25T12:36:10 | 2013-02-25T12:36:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,288 | py | import sys
import collections
import bisect
import math
class Trie:
class Node:
def __init__(self, x, bros = None, child = None):
self.data = x
self.bros = bros
self.child = child
def get_child(self, x):
child = self.child
while child:
if child.data == x: break
child = child.bros
return child
def set_child(self, x):
child = Trie.Node(x, self.child)
self.child = child
return child
def traverse(self, leaf, filter, count, k):
# print self.data
if self.data == '$':
yield []
else:
child = self.child
while child:
temp = count
if self.data in filter:
temp += 1
if temp > k:
child = child.bros
continue
for x in child.traverse(leaf, filter, temp, k):
yield [self.data] + x
child = child.bros
def __init__(self, x = None):
self.root = Trie.Node(None)
self.leaf = x
def insert(self, seq):
node = self.root
for x in seq:
child = node.get_child(x)
if not child:
child = node.set_child(x)
node = child
if not node.get_child(self.leaf):
node.set_child(self.leaf)
def traverse(self, filter, k):
node = self.root.child
while node:
for x in node.traverse(self.leaf, filter, 0, k):
yield x
node = node.bros
string = raw_input()
filter_txt = raw_input()
k = int(raw_input())
filter = set()
A = ord('a')
for i in xrange(len(filter_txt)):
if filter_txt[i] == '0':
filter.add(chr(A + i))
trie = Trie()
for i in xrange(len(string)):
for j in xrange(i + 1, len(string) + 1):
trie.insert(string[i:j] + '$')
# print string[i:j] + '$', i, j
result = 0
check = set()
for s in trie.traverse(filter, k):
if s != []:
# print s
check.add(''.join(s))
# result += 1
#print result
print len(check)
| [
"8monkey.theorem@gmail.com"
] | 8monkey.theorem@gmail.com |
9f6c1e251a682544de076c221d0328be196756ff | a8f1573dab2a4f74331fda435b5e9d4d12db3ff7 | /predict.py | 306983b2cf1a546058468bbd89dc6ef7fc15310a | [] | no_license | Jexulie/CNN-Text | 29df8ba944d18bf738264c727e5e14c929527a5e | a68c3bdfbef3222f4445c07cf4d656909994fb28 | refs/heads/master | 2020-06-20T16:35:21.240771 | 2019-07-16T11:20:00 | 2019-07-16T11:20:00 | 197,179,814 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 814 | py | import numpy as np
from keras.models import load_model
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
class Predict:
def __init__(self, modelPath, maxlen):
self._model = load_model(modelPath)
self._maxLen = maxlen
def __tokenizeX(self, X):
tokenizer = Tokenizer(num_words=5000)
tokenizer.fit_on_texts(X)
tokens = tokenizer.texts_to_sequences(X)
tokens = pad_sequences(tokens, padding='post', maxlen=self._maxLen)
return tokens
def predict(self, sentence):
X = self.__tokenizeX(sentence)
pred = self._model.predict(X)
for _, p in enumerate(pred):
if p[0] > 0:
print('Spam ', p)
else:
print('Ham ', p)
| [
"fejitj3n@yahoo.com"
] | fejitj3n@yahoo.com |
627649476ff37a030466b373ef750b7e153b0eb0 | 498fcf34fa4482be5c9fefc488666e60edcf46c7 | /supervised_learning/0x01-classification/17-deep_neural_network.py~ | 90473c634dabec13840cc70707d19fee907312fb | [] | no_license | MansourKef/holbertonschool-machine_learning | 7dbc465def04c311c1afb0e8b8903cbe34c72ad3 | 19f78fc09f0ebeb9f27f3f76b98e7a0e9212fd22 | refs/heads/main | 2023-03-12T16:18:08.919099 | 2021-03-05T09:42:09 | 2021-03-05T09:42:09 | 317,303,125 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,201 | #!/usr/bin/env python3
"""module"""
import numpy as np
class DeepNeuralNetwork:
"""Deep Neural Network"""
def __init__(self, nx, layers):
"""Constructor"""
if not type(nx) is int:
raise TypeError("nx must be an integer")
if nx < 1:
raise ValueError("nx must be a positive integer")
if not type(layers) is list or len(layers) == 0:
raise TypeError("layers must be a list of positive integers")
self.L = len(layers)
self.cache = {}
self.weights = {}
for i in range(len(layers)):
if layers[i] <= 0 or not type(layers[i]) is int:
raise TypeError("layers must be a list of positive integers")
if i == 0:
self.weights['W{}'.format(i+1)] = \
np.random.randn(layers[i], nx) * np.sqrt(2/(nx))
self.weights['b{}'.format(i+1)] = np.zeros([layers[i], 1])
else:
self.weights['W{}'.format(i+1)] = \
np.random.randn(layers[i], layers[i-1]) * \
np.sqrt(2/(layers[i-1]))
self.weights['b{}'.format(i+1)] = np.zeros([layers[i], 1])
| [
"2798@holbertonschool.com"
] | 2798@holbertonschool.com | |
d3ac15d1a1b310e9fa40c1f85843907c80188625 | 4f21bcbb86bd2f5d45deda8b348b48516759403b | /src/mask_generator.py | 96267b0965facf2bbda560a7641dc11e531cac1f | [] | no_license | pettod/prostate-cancer-grade-assessment | 34b56a9eefeb3e251a83c2e747ceef806d346bb3 | 1aa546a00767b18ef816e5c7fe1c03f90694e8d3 | refs/heads/master | 2022-10-10T22:06:02.581687 | 2020-06-08T15:08:10 | 2020-06-08T15:08:10 | 260,496,042 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,406 | py | import numpy as np
import math
import random
import pandas as pd
import os
import glob
import cv2
from skimage.io import MultiImage
from openslide import OpenSlide
from PIL import Image
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
class MaskGenerator(Dataset):
def __init__(
self, mask_directory, image_directory, train_csv_path,
patch_size, normalize=False):
self.__image_directory = image_directory
self.__mask_directory = mask_directory
self.__mask_names = []
self.__normalize = normalize
self.__patch_size = patch_size
self.__train_csv_path = train_csv_path
self.__readDatasetFileNames()
def __cropPatchesFromImageAndMask(
self, image_name, mask_name, downsample_level=None):
patch_shape = (self.__patch_size, self.__patch_size)
# downsample_level: 0, 1, 2, None (random)
# Use only 2 or None (MultiImage is used for low resolution image,
# OpenSlide for high resolution image (to save memory and faster
# process, Openslide did not work for low resolution image))
# Resolution downsample levels: 1, 4, 16
multi_image = MultiImage(image_name)
multi_mask = MultiImage(mask_name)
image_slide = OpenSlide(image_name)
mask_slide = OpenSlide(mask_name)
if downsample_level is None:
downsample_level = 2
image_to_crop = multi_image[-1]
mask_to_crop = multi_mask[-1]
else:
image_to_crop = multi_image[downsample_level]
mask_to_crop = multi_mask[downsample_level]
image_shape = tuple(image_to_crop.shape[::-1][1:])
resolution_relation = 4 ** (2 - downsample_level)
# Find coordinates from where to select patch
cell_coordinates = self.__getCellCoordinatesFromImage(multi_image)
# Iterate good patch
for j in range(5):
random_index = random.randint(0, cell_coordinates.shape[1] - 1)
# Scale coordinates by the number of resolution relation
# between low-resolution image and high/mid-resolution.
# Take center of the cell coordinate by subtracting
# 0.5*patch_size.
start_y, start_x = (
cell_coordinates[:, random_index] * resolution_relation -
int(0.5 * self.__patch_size))
start_x = max(0, min(
start_x, image_shape[0] - self.__patch_size))
start_y = max(0, min(
start_y, image_shape[1] - self.__patch_size))
end_x, end_y = np.array(
[start_x, start_y]) + self.__patch_size
# Crop from mid/high resolution image
if downsample_level == 0:
image_patch = np.array(image_slide.read_region((
start_x, start_y), 0, patch_shape))[..., :3]
mask_patch = np.array(mask_slide.read_region((
start_x, start_y), 0, patch_shape))[..., :3]
else:
image_patch = image_to_crop[start_y:end_y, start_x:end_x]
mask_patch = mask_to_crop[start_y:end_y, start_x:end_x]
# Resize if original image size was smaller than image_patch_size
if image_patch.shape[:2] != patch_shape:
padding = np.subtract(patch_shape, image_patch.shape[:2])
padding = ([0, padding[0]], [0, padding[1]], [0, 0])
image_patch = np.pad(image_patch, padding, constant_values=255)
mask_patch = np.pad(mask_patch, padding, constant_values=0)
# Patch has enough colored areas (not pure white)
# Otherwise iterate again
if np.mean(image_patch) < 230:
break
return image_patch, mask_patch
def __getCellCoordinatesFromImage(self, multi_image):
# Threshold of color value to define cell (0 to 255)
detection_threshold = 200
# Read low resolution image (3 images resolutions)
low_resolution_image = multi_image[-1]
image_shape = low_resolution_image.shape
# Find pixels which have cell / exclude white pixels
cell_coordinates = np.array(np.where(np.mean(
low_resolution_image, axis=-1) < detection_threshold))
# If image includes only white areas or very white, generate random
# coordinates
if cell_coordinates.shape[1] == 0:
random_coordinates = []
for i in range(100):
random_x = random.randint(
0, image_shape[0] - self.__patch_size)
random_y = random.randint(
0, image_shape[1] - self.__patch_size)
random_coordinates.append([random_y, random_x])
cell_coordinates = np.transpose(np.array(random_coordinates))
return cell_coordinates
def __readDatasetFileNames(self):
train_csv = pd.read_csv(self.__train_csv_path)
radboud_image_names = train_csv[
train_csv["data_provider"] == "radboud"][
"image_id"].values.tolist()
radboud_image_names = [
os.path.join(self.__mask_directory, i + "_mask.tiff") for i in
radboud_image_names]
existing_mask_names = list(filter(
lambda x: os.path.exists(x), radboud_image_names))
self.__mask_names = np.array(existing_mask_names)
def normalizeArray(self, data_array, max_value=255):
return ((data_array / max_value - 0.5) * 2).astype(np.float32)
def unnormalizeArray(self, data_array, max_value=255):
data_array = (data_array / 2 + 0.5) * max_value
data_array[data_array < 0.0] = 0.0
data_array[data_array > max_value] = max_value
return data_array.astype(np.uint8)
def __len__(self):
return len(self.__mask_names)
def __getitem__(self, idx):
mask_name = str(self.__mask_names[idx])
image_name = os.path.join(
self.__image_directory,
mask_name.split('/')[-1].replace("_mask", ""))
return self.__cropPatchesFromImageAndMask(image_name, mask_name)
if __name__ == "__main__":
from matplotlib import colors
# Data paths
ROOT = os.path.realpath("../input/prostate-cancer-grade-assessment")
TRAIN_X_DIR = os.path.join(ROOT, "train_images")
TRAIN_Y_DIR = os.path.join(ROOT, "train_label_masks")
TRAIN_CSV_PATH = os.path.join(ROOT, "train.csv")
# Create Pytorch generator
dataset = MaskGenerator(
TRAIN_Y_DIR, TRAIN_X_DIR, TRAIN_CSV_PATH, patch_size=256)
dataloader = DataLoader(
dataset, batch_size=1, shuffle=False, num_workers=1)
# Radboud clinic colors
RADBOUD_COLOR_CODES = {
"0": np.array(["0 Background", np.array([ 0, 0, 0])]),
"1": np.array(["1 Stroma", np.array([153, 221, 255])]),
"2": np.array(["2 Healthy", np.array([ 0, 153, 51])]),
"3": np.array(["3 Gleason 3", np.array([255, 209, 26])]),
"4": np.array(["4 Gleason 4", np.array([255, 102, 0])]),
"5": np.array(["5 Gleason 5", np.array([255, 0, 0])]),
}
# Color bar details
cmap = colors.ListedColormap(
list(np.array(list(RADBOUD_COLOR_CODES.values()))[:, 1] / 255))
grades = list(np.arange(0, 13))
grades_descriptions = [""] * 13
grades_descriptions[1::2] = list(np.array(list(
RADBOUD_COLOR_CODES.values()))[:, 0])
norm = colors.BoundaryNorm(grades, cmap.N+1)
# Load batch
for image_batch, mask_batch in dataloader:
image = image_batch.numpy()[0]
mask = mask_batch.numpy()[0, ..., 0]
# Colorize mask
r = np.copy(mask)
g = np.copy(mask)
b = np.copy(mask)
for i in range(len(RADBOUD_COLOR_CODES)):
r[r == i] = RADBOUD_COLOR_CODES[str(i)][1][0]
g[g == i] = RADBOUD_COLOR_CODES[str(i)][1][1]
b[b == i] = RADBOUD_COLOR_CODES[str(i)][1][2]
mask = cv2.merge((r, g, b))
# Plot mask and image
plotted_cell_mask = plt.imshow(
cv2.hconcat([image, mask]), cmap=cmap, norm=norm)
colorbar = plt.colorbar(plotted_cell_mask, cmap=cmap, ticks=grades)
colorbar.ax.set_yticklabels(grades_descriptions)
plt.draw()
plt.pause(2)
plt.clf()
| [
"peter.todorov@live.com"
] | peter.todorov@live.com |
0c98c3fa06970c85f3b2a81e02355551274fcf41 | 5b22437902bffa0f62b375d56bfb2b4485ef43f0 | /src/video_inpainting/padded_masked_video_tar_dataset.py | 93491de023c768894243ad89932a5aa1d0875600 | [
"MIT",
"CC-BY-SA-3.0",
"CC-BY-SA-4.0"
] | permissive | JohnsonzxChang/devil | eafa09f5258b4f33eda9564077814c6e63473a0f | 296115cd5f4952c7dc65bbcaaf2d1d5c55ef5d35 | refs/heads/public | 2023-07-03T12:07:58.917440 | 2021-08-10T00:06:38 | 2021-08-10T00:06:38 | 555,846,483 | 1 | 0 | MIT | 2022-10-22T13:22:43 | 2022-10-22T13:22:42 | null | UTF-8 | Python | false | false | 1,437 | py | import tarfile
from itertools import cycle
from .padded_masked_video_dataset import PaddedMaskedVideoDataset
class PaddedMaskedVideoTarDataset(PaddedMaskedVideoDataset):
def __init__(self, frames_dataset_path, masks_dataset_path):
self._frames_dataset_tar = tarfile.open(frames_dataset_path, 'r')
self._masks_dataset_tar = tarfile.open(masks_dataset_path, 'r')
frame_video_names = sorted([info.name for info in self._frames_dataset_tar.getmembers() if info.isdir()])
mask_video_names = sorted([info.name for info in self._masks_dataset_tar.getmembers() if info.isdir()])
super().__init__(frame_video_names, mask_video_names)
def video_frame_files_iter(self, frame_video_name):
frame_paths = sorted([info.name for info in self._frames_dataset_tar.getmembers()
if info.name.startswith(frame_video_name) and info.isfile()])
for frame_path in frame_paths:
yield self._frames_dataset_tar.extractfile(frame_path)
def video_mask_files_iter(self, mask_video_name):
mask_paths = sorted([info.name for info in self._masks_dataset_tar.getmembers()
if info.name.startswith(mask_video_name) and info.isfile()])
mask_paths_c = cycle(mask_paths + mask_paths[len(mask_paths)-2:0:-1])
for mask_path in mask_paths_c:
yield self._masks_dataset_tar.extractfile(mask_path)
| [
"szetor@umich.edu"
] | szetor@umich.edu |
b70adaf17f7be82b2a5dda0a1c4117fbb56e8e65 | 7bbcdace3b10190cf72941ccb821459313915d4f | /test1.py | 19a01573b9f129a381d5ba50d3dee0fcb2757ffa | [] | no_license | jasongti/visualization | 75c3b4b7a6d4bcaa727a3f4cfa419b99c5cb2111 | 575b46a39a5d32853f0b33f0777867e5035d23a3 | refs/heads/master | 2022-04-16T17:21:49.206789 | 2020-04-15T10:15:02 | 2020-04-15T10:15:02 | 250,243,955 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 545 | py | import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 2 * np.pi, 0.02)
y = np.sin(x)
y1 = np.sin(2 * x)
y2 = np.sin(3 * x)
ym1 = np.ma.masked_where(y1 > 0.5, y1)
ym2 = np.ma.masked_where(y2 < -0.5, y2)
lines = plt.plot(x, y, x, ym1, x, ym2, 'o')
# 设置线的属性
plt.setp(lines[0], linewidth=1)
plt.setp(lines[1], linewidth=2)
plt.setp(lines[2], linestyle='-', marker='^', markersize=4)
# 线的标签
plt.legend(('No mask', 'Masked if > 0.5', 'Masked if < -0.5'), loc='upper right')
plt.title('Masked line demo')
plt.show()
| [
"rhythmlee@gmail.com"
] | rhythmlee@gmail.com |
6c6ac0405307578b110806b41808b8fc2e69e5d9 | 4b500447a3b94cff810e61858a1f2cae43b0fb29 | /ex1.py | 6986c764118fecf8a7e3b2e064b5a22ae41da756 | [] | no_license | knowone/OS2PythonWorkEx1 | e8dcf42e07919130a6155ac6877b92a1cc0bf35c | e14776176b2d760881d3f21d7c8c5b8d6b2c9225 | refs/heads/master | 2021-01-18T23:17:33.227262 | 2017-04-25T09:24:58 | 2017-04-25T09:24:58 | 87,103,831 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,809 | py | # ------------------------------------------------------------------------------
def quest1():
"""
Question 1: prints all numbers that their sum of digits cubed are equal to
themselves.
"""
for i in range(100, 500):
j = i
s = 0
while j > 0:
s += (j % 10) ** 3
j //= 10
if s == i:
print(i)
# ------------------------------------------------------------------------------
def quest2():
"""
Question 2: Solves the question - if you buy 100 tickets for 400$, when each
ticket costs either 3$,10$ or 15$
How many tickets of each type did you buy?
"""
def find(tickets, budget):
"""Finds, for a given tickets amount and budget how many tickets of each
type you bought"""
for x in range(tickets):
for y in range(tickets):
for z in range(tickets):
if ((3*x) + (10*y) + (15*z) == budget) & \
((x + y + z) == tickets):
return[str(x) + " tickets for 3$", str(y) +
" tickets for 10$", str(z) + " tickets for 15$"]
print("To purchase 100 tickets with 400$ you need:")
for found in find(100, 400):
print(found)
# ------------------------------------------------------------------------------
def quest3():
"""
Question 3: Plays with user 7 boom! where starting player is selected
randomly for extra fun.
Each player types the next number, but if the number is a multiple of 7
or has 7 in it then player must type
"Boom" instead of the number. Also correct order of numbers must be
kept.
Player is winner if was able to get to 30.
"""
from random import randint
turn = randint(1, 2)
print("7 Boom!")
if turn == 1:
print("you start:")
else:
print("I start:")
for x in range(1, 31):
if turn == 2:
if ((x % 7) == 0) | ((x % 10) == 7):
print("Computer: Boom!")
else:
print("Computer: " + str(x))
turn -= 1
elif turn == 1:
user = input("You: ")
if ((x % 7) == 0) | ((x % 10) == 7):
if (user != "Boom") & (user != "boom") & (user != "Boom!") & \
(user != "boom!"):
print("You loose!")
break
else:
usr_int = getint(user)
if usr_int == "invalid":
print("You loose!")
break
elif usr_int != x:
print("You loose!")
break
turn += 1
if x == 30:
print("You Win!")
# ------------------------------------------------------------------------------
def quest4():
"""
Question 4: Implement a stack using list with operations:
i - insert (push) to stack
e - eject(pop) from stack
p - print the stack
When stack is empty, print will print "Empty"
If stack is empty and e (pop) is called, the function will exit.
"""
def insert(obj, stack: list):
"""Using list, appends to the end of the list.
obj can be anything. Must be a printable object"""
stack.append(obj)
def eject(stack: list):
"""using list, pop the end of the list from the list.
returns the ejected object"""
if not stack: # not stack will return true if list is [] (empty)
return "Empty"
else:
obj = stack.pop()
return obj
def prt_stack(stack: list):
"""Print the list in 2 columns starting from 0 index.
Prints the list backwards to simulate stack order (FIFO)
Prints "Empty" if list is empty"""
if not stack:
print("Empty")
else:
for index, obj in enumerate(stack[::-1]):
print(index, obj)
my_stack = []
user_choice = input("Enter a command (i to insert, "
"e to pop or p to print):\n")
while 1:
if user_choice == 'i':
obj_str = input("Enter string to insert to stack:\n")
insert(obj_str, my_stack)
elif user_choice == 'e':
status = eject(my_stack)
if status == "Empty":
break # stop only if stack is already empty
elif user_choice == 'p':
prt_stack(my_stack)
else:
print("Invalid choice. Try again..")
user_choice = input("Enter a command (i, e, p):\n")
# ------------------------------------------------------------------------------
def getint(z):
"""
Error preventing convert-to-int function.
Catches ValueError exceptions if int() is being called with a string
type argument.
"""
try:
return int(z)
except ValueError:
return "invalid"
# ------------------------------------------------------------------------------
def main():
"""
Prompts a selection for user to choose between the 4 assignments.
1,2,3,4 corresponds to the question numbers.
0 will exit the program.
For all other inputs, the program will display a retry message.
"""
quest = [quest1, quest2, quest3, quest4]
menu = getint(input("Question number? (0 to quit)\n"))
while menu != 0:
if 0 < menu <= 4:
quest[menu-1]()
else:
print("Invalid choice. Try again..\n")
menu = getint(input("Question number? (0 to quit)\n"))
# --------------------------- Run The Program ----------------------------------
main()
# ------------------------------------------------------------------------------
| [
"knowone.omer@gmail.com"
] | knowone.omer@gmail.com |
494f9412713ce88fb3b852646746e54ca1e236e5 | 67956b30144a965e4333c32a7a1978fdd524847b | /preprocessing tweet hashtags using dictionaries.py | 6b445d1debed44dc63d423004a4c8e4f8c2874d7 | [] | no_license | priyank9320/twitter-sub-event-detection-and-sentiment-analysis-using-graph-theory | 99b2cd89ffceecae5069c6e2646817086f8950ef | ac600768e629cb76b6b3ffd0d5b4be1ef10e9565 | refs/heads/master | 2023-02-05T10:57:52.567136 | 2020-12-26T09:21:33 | 2020-12-26T09:21:33 | 263,738,410 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,921 | py | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
import mysql.connector ## database connection
import pandas as pd ## for pandas dataframe
from nltk.tokenize import RegexpTokenizer ## tokenizer
# In[ ]:
##### DATABASE CONNECTION
db_connection = mysql.connector.connect(host='localhost', database='tweet_data', user='root', password='password')
# In[ ]:
## import raw reduced adjacency list (SOURCE)
raw_reduc_adj = pd.read_sql('SELECT Source as raw_source from reduced_ex_adjacency', con=db_connection)
# In[ ]:
raw_reduc_adj.head(50)
# In[ ]:
## import prcocessed reduced adjacency list (non finlasied data) (SOURCE)
proc_reduc_adj = pd.read_sql('SELECT Source as proc_source from proc_ex_adjacency', con=db_connection)
# In[ ]:
proc_reduc_adj.head(50)
# In[ ]:
## import reduced MAIN DATA
reduc_full = pd.read_sql('SELECT * from reduced_ex_full', con=db_connection)
# In[ ]:
reduc_full.head(50)
# In[ ]:
## join the data proc and raw adjacency into one , for easy comparision
joined_proc_raw_adj = pd.concat([raw_reduc_adj, proc_reduc_adj], axis=1)
joined_proc_raw_adj.shape
# In[ ]:
joined_proc_raw_adj.head(50)
# In[ ]:
###### tokenize the MAIN DATA (this we are doing to convert the text into a list of words)
## tokenizer is converting into a list and stores it back in the hashtags column
tokenizer = RegexpTokenizer(r'\w+')
reduc_full['hashtags']=reduc_full['hashtags'].apply(lambda x: tokenizer.tokenize(x))
# In[ ]:
## create a dictionary from SOURCE columns
joined_dict1 = joined_proc_raw_adj.set_index('raw_source').T.to_dict('record')[0]
# In[ ]:
joined_dict1
# In[ ]:
#joined_dict1['Gold']
# In[ ]:
## create dictionary from TARGET columns
## import raw reduced adjacency list
raw_reduc_adj2 = pd.read_sql('SELECT Target as raw_target from reduced_ex_adjacency', con=db_connection)
## import prcocessed reduced adjacency list (non finlasied data)
proc_reduc_adj2 = pd.read_sql('SELECT Target as proc_target from proc_ex_adjacency', con=db_connection)
## join them
joined_proc_raw_adj2 = pd.concat([raw_reduc_adj2, proc_reduc_adj2], axis=1)
## create dictionary
joined_dict2 = joined_proc_raw_adj2.set_index('raw_target').T.to_dict('record')[0]
# In[ ]:
joined_dict2
# In[ ]:
len(joined_dict1)
# In[ ]:
len(joined_dict2)
# In[ ]:
joined_dict1.update(joined_dict2)
len(joined_dict1)
# In[ ]:
reduc_full #before
# In[ ]:
#replace the values in MAIN DATA using DICTIONARIES
for x in range(reduc_full.shape[0]):
for y in range(len(reduc_full['hashtags'][x])):
if reduc_full['hashtags'][x][y] in joined_dict1:
reduc_full['hashtags'][x][y] = joined_dict1[reduc_full['hashtags'][x][y]]
# In[ ]:
reduc_full #after
# In[ ]:
#Joining the lists back to get a final string of processed hashtags
reduc_full['hashtags']=reduc_full['hashtags'].apply(lambda x: ' '.join(x))
# In[ ]:
reduc_full # final
# In[ ]:
#just converting everything to lower once
reduc_full["hashtags"] = reduc_full["hashtags"].str.lower()
# In[ ]:
reduc_full
# In[ ]:
##### FINAL STEP : storing the data back into mysql database
## inserting pandas data frame back to the mysql
from sqlalchemy import create_engine
import pymysql
connection = pymysql.connect(host='localhost',
user='root',
password='password',
db='tweet_data')
cursor=connection.cursor()
engine = create_engine("mysql+pymysql://{user}:{pw}@localhost/{db}"
.format(user = "root",
pw="password",
db="tweet_data"))
#insert the entire dataframe into mysql
# df is the name of our data frame
reduc_full.to_sql('proc_reduced_ex_full',con=engine,if_exists='append',chunksize=1000)
print("Success !! preprocessing is completed for the full data set ")
# In[ ]:
# In[ ]:
| [
"priyank.m9320@gmail.com"
] | priyank.m9320@gmail.com |
92e1f674207fd73f5bacb5a9b1bcf5a56f7419b3 | 3e902a191bc66be2f80f31eda220e55920863e55 | /loop/__init__.py | d0f7541e0eca3b9cdc059062368d73a043767220 | [] | no_license | Knight-Ops/xtensa-dis | 2871775598959f65e3322fb7478ae79553c93e75 | 50ff9879fd1c4d0a1e15a187beb16d367e3ed658 | refs/heads/master | 2022-06-26T16:43:08.565351 | 2020-05-09T01:06:29 | 2020-05-09T01:06:29 | 260,047,011 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 32 | py | from .loop_instructions import * | [
"carl@basilisklabs.com"
] | carl@basilisklabs.com |
6579e872948f51bf21e7c2ea85957dcf238da3da | 1b862f34c125ce200244dd79e4fda4b5b605ce2e | /.history/ML_T2_Validation_20210612133304.py | f4916063cc50283bddabf46d8c1a1f2ed57ad41b | [] | no_license | edwino26/CoreImages | 26085a49cf1cb79442ae563a88354b2fdceace87 | 6bf6e68cac8ab36c87b1e6ea702bfe6882b0f40e | refs/heads/master | 2023-06-22T12:53:37.344895 | 2021-07-21T04:31:44 | 2021-07-21T04:31:44 | 309,553,247 | 0 | 4 | null | 2021-04-29T23:23:15 | 2020-11-03T02:45:07 | Lasso | UTF-8 | Python | false | false | 9,517 | py | #T2 TEST DATA
# %%
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pickle
from scipy import interpolate
from scipy.integrate import simps
from numpy import trapz
from sklearn.metrics import mean_squared_error
# %%
#Load Stack
UVStack = pd.read_excel('./ML_Results/T2_test/ImgStack.xls')
ImgStackk = UVStack.copy().to_numpy()
# %%
def integrate(y_vals, h):
i = 1
total = y_vals[0] + y_vals[-1]
for y in y_vals[1:-1]:
if i % 2 == 0:
total += 2 * y
else:
total += 4 * y
i += 1
return total * (h / 3.0)
# %% Load and resample "results" (res) file
sub = pd.read_excel('./ML_Results/T2_test/sub.xls')
res = pd.read_excel('./ML_Results/T2_test/Results.xls')
res = res[res.Well == 'T2']
res.sort_values(by=['DEPT'])
res.drop(['Unnamed: 0', 'Set'], axis=1, inplace=True)
res.reset_index(inplace=True, drop=True)
dep = np.arange(min(res.DEPT), max(res.DEPT),0.5) #res is not at 0.5 thanks to balancing
res_rs = pd.DataFrame(columns=[res.columns])
res_rs.DEPT = dep
for i in range(len(res.columns)):
if i != 8:
f = interpolate.interp1d(res.DEPT, res.iloc[:,i])
res_rs.iloc[:,i] =f(dep)
else:
res_rs.iloc[:,i] = res.Well[0]
#T2_rs.dropna(inplace=True)
res = res_rs.copy()
difference = res.DEPT.diff()
difference.describe()
# %%
TT = pd.read_excel('./ML_Results/Train_Test_Results.xls')
istr = 0
iend = 42344
dplot_o = 3671
dplot_n = 3750
shading = 'bone'
# %% Load Log Calculations
T2_x = pd.read_excel('./Excel_Files/T2.xls',sheet_name='T2_data')
T2_x = T2_x[['DEPTH','GR_EDTC','RHOZ','AT90','NPHI','Vsh','Vclay','grain_density','porosity',
'RW2','Sw_a','Sw_a1','Sw_p','Sw_p1','SwWS','Swsim','Swsim1','PAY_archie',
'PAY_poupon','PAY_waxman','PAY_simandoux']]
# %%
T2_rs = pd.DataFrame(columns=[T2_x.columns])
T2_rs.iloc[:,0] = dep
for i in range(len(T2_x.columns)):
f = interpolate.interp1d(T2_x.DEPTH, T2_x.iloc[:,i])
T2_rs.iloc[:,i] =f(dep)
#T2_rs.dropna(inplace=True)
T2_x = T2_rs.copy()
difference_T2 = T2_x.DEPTH.diff()
difference.describe()
# %%
plt.figure()
plt.subplot2grid((1, 10), (0, 0), colspan=3)
plt.plot(sub['GRAY'], sub['DEPTH'], 'mediumseagreen', linewidth=0.5);
plt.axis([50, 250, dplot_o, dplot_n]);
plt.gca().invert_yaxis();
plt.fill_between(sub['GRAY'], 0, sub['DEPTH'], facecolor='green', alpha=0.5)
plt.xlabel('Gray Scale RGB')
plt.subplot2grid((1, 10), (0, 3), colspan=7)
plt.imshow(ImgStackk[istr:iend,80:120], aspect='auto', origin='upper', extent=[0,1,dplot_n,dplot_o], cmap=shading);
plt.axis([0, 1, dplot_o, dplot_n]);
plt.gca().invert_yaxis()
plt.xlabel('Processed Image')
plt.colorbar()
p_50 = np.percentile(sub['DEPTH'], 50)
plt.yticks([]); plt.xticks([])
plt.subplots_adjust(wspace = 20, left = 0.1, right = 0.9, bottom = 0.1, top = 0.9)
plt.show()
# %%
CORE =pd.read_excel('./CORE/CORE.xlsx',sheet_name='XRD')
mask = CORE.Well.isin(['T2'])
T2_Core = CORE[mask]
prof=T2_Core['Depth']
clays=T2_Core['Clays']
xls1 = pd.read_excel ('./CORE/CORE.xlsx', sheet_name='Saturation')
mask = xls1.Well.isin(['T2'])
T2_sat = xls1[mask]
long=T2_sat ['Depth']
poro=T2_sat ['PHIT']
grain=T2_sat ['RHOG']
sw_core=T2_sat ['Sw']
klinkenberg = T2_sat ['K']
minimo=grain.min()
maximo=grain.max()
c=2.65
d=2.75
norm=(((grain-minimo)*(d-c)/(maximo-minimo))+c)
xls2 = pd.read_excel ('./CORE/CORE.xlsx', sheet_name='Gamma')
mask = xls2.Well.isin(['T2'])
T2_GR = xls2[mask]
h=T2_GR['Depth']
cg1=T2_GR['GR_Scaled']
# %%
# ~~~~~~~~~~~~~~~~~~ Plot Results ~~~~~~~~~~~~~~~~~~~~~~
ct = 0
top= dplot_o
bottom= dplot_n
no_plots = 9
ct+=1
plt.figure(figsize=(13,9))
plt.subplot(1,no_plots,ct)
plt.plot (T2_x.GR_EDTC,T2_x.DEPTH,'g', lw=3)
#plt.fill_between(T2_x.GR_EDTC.values.reshape(-1), T2_x.DEPTH.values.reshape(-1), y2=0,color='g', alpha=0.8)
plt.title('$Gamma Ray$',fontsize=8)
plt.axis([40,130,top,bottom])
plt.xticks(fontsize=8)
plt.yticks(fontsize=8)
plt.xlabel('Gamma Ray ',fontsize=6)
plt.gca().invert_yaxis()
plt.grid(True)
plt.hlines(y=3665.65, xmin=0, xmax=130)
plt.hlines(y=3889.5, xmin=0, xmax=130)
ct+=1
plt.subplot(1,no_plots,ct)
plt.plot (T2_x.PAY_poupon,T2_x.DEPTH,'r',lw=0.5)
h_P = integrate(T2_x.PAY_poupon.values, 0.5)
plt.title('$PAY Poupon$',fontsize=8)
plt.fill_between(T2_x.PAY_poupon.values.reshape(-1),T2_x.DEPTH.values.reshape(-1), color='r', alpha=0.8)
plt.axis([0.01,0.0101,top,bottom])
plt.xticks(fontsize=8)
plt.gca().invert_yaxis()
plt.gca().xaxis.set_visible(False)
plt.gca().yaxis.set_visible(False)
plt.grid(True)
plt.hlines(y=3665.65, xmin=0, xmax=130)
plt.hlines(y=3889.5, xmin=0, xmax=130)
#Waxman-Smits
ct+=1
plt.subplot(1,no_plots,ct)
plt.plot (T2_x.PAY_waxman,T2_x.DEPTH,'g',lw=0.5)
h_WS = integrate(T2_x.PAY_waxman.values, 0.5)
plt.title('$PAY Waxman$',fontsize=8)
plt.fill_between(T2_x.PAY_waxman.values.reshape(-1),T2_x.DEPTH.values.reshape(-1), color='g', alpha=0.8)
plt.axis([0.01,0.0101,top,bottom])
plt.xticks(fontsize=8)
plt.gca().invert_yaxis()
plt.gca().xaxis.set_visible(False)
plt.gca().yaxis.set_visible(False)
plt.grid(True)
plt.hlines(y=3665.65, xmin=0, xmax=130)
plt.hlines(y=3889.5, xmin=0, xmax=130)
#Simandoux
ct+=1
plt.subplot(1,no_plots,ct)
plt.plot (T2_x.PAY_simandoux,T2_x.DEPTH,'y',lw=0.5)
h_S = integrate(T2_x.PAY_simandoux.values, 0.5)
plt.title('$PAY Simandoux$',fontsize=8)
plt.fill_between(T2_x.PAY_simandoux.values.reshape(-1),T2_x.DEPTH.values.reshape(-1), color='y', alpha=0.8)
plt.axis([0.01,0.0101,top,bottom])
plt.xticks(fontsize=8)
plt.gca().invert_yaxis()
plt.gca().xaxis.set_visible(False)
plt.gca().yaxis.set_visible(False)
plt.grid(True)
plt.hlines(y=3665.65, xmin=0, xmax=130)
plt.hlines(y=3889.5, xmin=0, xmax=130)
ct+=1 #RGB Gray from Image
plt.subplot(1,no_plots,ct)
plt.plot(sub['GRAY'], sub['DEPTH'], 'mediumseagreen', linewidth=0.5);
plt.axis([50, 250, dplot_o, dplot_n]);
plt.xticks(fontsize=8)
#plt.title('$Core Img$',fontsize=8)
plt.gca().invert_yaxis();
plt.gca().yaxis.set_visible(False)
plt.fill_between(sub['GRAY'], 0, sub['DEPTH'], facecolor='green', alpha=0.5)
plt.xlabel('Gray Scale RGB', fontsize=7)
ct+=1 # True UV from Image
plt.subplot(1,no_plots,ct, facecolor='#302f43')
corte= 170
PAY_Gray_scale = res['GRAY'].copy()
PAY_Gray_scale.GRAY[PAY_Gray_scale.GRAY<corte] = 0
PAY_Gray_scale.GRAY[PAY_Gray_scale.GRAY>=corte] = 1
h_TRUE_UV = integrate(PAY_Gray_scale.values, 0.5)
plt.plot (PAY_Gray_scale,res.DEPT,'#7d8d9c',lw=0.5)
plt.title('$OBJETIVO (suavizado-a-2.5ft)$',fontsize=10)
plt.fill_between(PAY_Gray_scale.values.reshape(-1),res.DEPT.values.reshape(-1), color='#7d8d9c', alpha=0.8)
plt.axis([0.01,0.0101,top,bottom])
plt.xticks(fontsize=8)
plt.gca().invert_yaxis()
plt.gca().xaxis.set_visible(False)
plt.gca().yaxis.set_visible(False)
plt.grid(True)
ct+=1
plt.subplot(1,no_plots,ct)
plt.imshow(ImgStackk[istr:iend,80:120], aspect='auto', origin='upper', extent=[0,1,dplot_n,dplot_o], cmap=shading);
plt.axis([0, 1, dplot_o, dplot_n]);
plt.xticks(fontsize=8)
plt.gca().invert_yaxis()
plt.xlabel('Stacked UV Photos', fontsize=7)
plt.colorbar()
p_50 = np.percentile(sub['DEPTH'], 50)
plt.yticks([]); plt.xticks([])
ct+=1
plt.subplot(1,no_plots,ct)
plt.plot (res['RandomForest'],res.DEPT,'r',lw=1)
plt.plot (res.GRAY,res.DEPT,'k',lw=0.5)
plt.title('ML: GRIS',fontsize=12)
plt.axis([0,2,top,bottom])
plt.xticks(fontsize=8)
plt.xlabel('RandomForest',fontsize=7)
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
plt.gca().yaxis.set_visible(False)
plt.grid(True)
plt.xlim(0, 255)
plt.hlines(y=3665.65, xmin=0, xmax=130)
plt.hlines(y=3889.5, xmin=0, xmax=130)
ct+=1
plt.subplot(1,no_plots,ct, facecolor='#302f43')
PAY_Gray_scale2 = res['RandomForest'].copy().rename(columns={'RandomForest':'GRAY'})
PAY_Gray_scale2.GRAY[PAY_Gray_scale2.GRAY<corte] = 0
PAY_Gray_scale2.GRAY[PAY_Gray_scale2.GRAY>=corte] = 1
h_ML = integrate(PAY_Gray_scale2.values, 0.5)
plt.plot (PAY_Gray_scale2, res.DEPT,'#7d8d9c',lw=0.5)
plt.title('$RESULTADO$',fontsize=8)
plt.fill_between(PAY_Gray_scale2.values.reshape(-1),res.DEPT.values.reshape(-1), color='#7d8d9c', alpha=0.8)
plt.axis([0.01,0.0101,top,bottom])
plt.xticks(fontsize=8)
plt.gca().invert_yaxis()
plt.gca().xaxis.set_visible(False)
plt.gca().yaxis.set_visible(False)
plt.grid(True)
plt.suptitle('Pozo T2: Comparación Final')
plt.show()
# %%
plt.figure(figsize=(10,9))
plt.subplot(1,1,1)
plt.plot(res.GRAY, res['RandomForest'], 'ko')
plt.plot(res.GRAY, res.GRAY, 'r')
plt.xlim(0, 255)
plt.ylim(0, 255)
plt.xlabel('Valor en Escala de Gris Suavizado a res. de Registros',fontsize=17)
plt.ylabel('Predicción de Escala de Gris usando Random Forest',fontsize=17)
plt.show()
# %% Erro Calculation
# T2_x.PAY_poupon,T2_x.DEPTH
# T2_x.PAY_waxman
# T2_x.PAY_simandoux
# %%
pay = pd.DataFrame(columns=['Poupon', 'Waxman_Smits', 'Simandoux', 'Machine_L', 'True_UV'], index=['ft','RMSE'])
pay.loc['ft', 'Poupon'] = h_P.round(2)
pay.loc['ft', 'Waxman_Smits'] = h_WS.round(2)
pay.loc['ft', 'Simandoux'] = h_S.round(2)
pay.loc['ft', 'Machine_L'] = h_ML.round(2)
pay.loc['ft', 'True_UV'] = h_TRUE_UV.round(2)
pay.loc['RMSE', 'Poupon'] = pay.iloc[0,0] - pay.iloc[0,4]
pay.loc['RMSE', 'Waxman_Smits'] = pay.iloc[0,1] - pay.iloc[0,4]
pay.loc['RMSE', 'Simandoux'] = (pay.iloc[0,2] - pay.iloc[0,4]).round(2)
pay.loc['RMSE', 'Machine_L'] = pay.iloc[0,3] - pay.iloc[0,4]
pay.loc['RMSE', 'True_UV'] = pay.iloc[0,4] - pay.iloc[0,4]
pay.head()
# %%
payN = pay.T.copy()
payN.reset_index(inplace=True)
plt.figure()
ax = payN.plot.bar(x='index', y='RMSE', rot=0)
# %%
| [
"ortega.edwin.y@gmail.com"
] | ortega.edwin.y@gmail.com |
c4c42784587d12889c3cdc885e8f437879a6747a | 3cb2cc1f4eeb746a2b3318381cd39489f7c80544 | /n prime number using while loop.py | de7162858e3d25f927e9ac3257da67916452d4aa | [] | no_license | mrkhan10/python_letsupgrade-DAY-3 | 1c59d95721783fe3279660204434c114c565acc7 | 75478318203c8259f5bdeec08a6a32fd6024bb94 | refs/heads/main | 2023-01-24T16:15:09.234435 | 2020-12-12T16:25:19 | 2020-12-12T16:25:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 460 | py | #program to print X prime numbers from 0 using while loop
x = int(input(" Please Enter Any Number: "))
Number = 1
print("Prime numbers between", 1, "and",x, "are:")
while(Number <= x):
count = 0
i = 2
while(i <= Number//2):
if(Number % i == 0):
count = count + 1
break
i = i + 1
if (count == 0 and Number != 1):
print(" %d" %Number, end = ' ')
Number = Number + 1 | [
"noreply@github.com"
] | mrkhan10.noreply@github.com |
c5b9d6862e88d4985aca4aef466341647504da89 | 61b044c885c5b0e8fd392304855c3a9d417da466 | /functions/randmcmc/L+C_mcmc_rand_sig_tau_3.py | 400646b4f2a12722170161c70bfb415e0971a992 | [] | no_license | noahkrever/pg1302 | 8e74efbed16ad63daeecd50f94c0c3a268723a65 | c800f9ac491180013466b8e08ed300fdc94df700 | refs/heads/master | 2022-12-09T12:04:01.915425 | 2020-08-27T21:14:02 | 2020-08-27T21:14:02 | 285,685,079 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 309 | py |
import time
import calculateL
start = time.time()
calculateL.drw_MCMC(r"/rigel/astro/users/ndk2115/pg1302/data/L+C_mcmc_rand_sig_tau_3.h5",r"/rigel/astro/users/ndk2115/pg1302/outputs/L+C_mcmc_rand_sig_tau_info_3.h5")
end = time.time()
print("The run took " + str(end - start) + " seconds.")
| [
"ndk2115@columbia.edu"
] | ndk2115@columbia.edu |
5ca2ca31d57e7c843a5e90303dd041003f64e812 | 4458f2e9f694e7f864a7587f8840d8e132031554 | /learning_templates/basic_app/urls.py | 2c9bcbb7cfcb9009b2a8576aaf3804c5c0f92a93 | [] | no_license | iApolloBear/DjangoLevel4 | aa424c6b619d590665ea55dd785b9f68a1177159 | 549d2224a6a708ae8f861553a5e6539d08d8be97 | refs/heads/master | 2021-05-25T20:43:23.166670 | 2020-04-07T22:34:31 | 2020-04-07T22:34:31 | 253,911,451 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 222 | py | from django.urls import path
from . import views
# Template Tagging
app_name = 'basic_app'
urlpatterns = [
path('relative/', views.relative, name='relative'),
path('other/', views.other, name='other'),
]
| [
"aldoespinosaperez1@gmail.com"
] | aldoespinosaperez1@gmail.com |
c51a1e996599f1ff816105ef3e9c1f1172432007 | 9b1b41932330192d01ecfe6a873131e4b0611423 | /accounts/migrations/0003_profile.py | 476832c44d1902e9536b6c4b2e3b12b1da415929 | [] | no_license | someOne404/FinanceApp | c22c376eeb159ce6f60eb7be0e1b17f4b2c2791c | 2e0401d680fdd2009fc2ed03ea3fd44121c77874 | refs/heads/master | 2020-04-26T10:24:12.271187 | 2019-03-03T14:41:26 | 2019-03-03T14:41:26 | 173,485,013 | 0 | 0 | null | 2019-03-03T14:41:27 | 2019-03-02T18:37:30 | Python | UTF-8 | Python | false | false | 950 | py | # Generated by Django 2.1.7 on 2019-03-03 01:44
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('accounts', '0002_auto_20190302_2004'),
]
operations = [
migrations.CreateModel(
name='Profile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('bio', models.TextField(blank=True, max_length=500)),
('location', models.CharField(blank=True, max_length=30)),
('birth_date', models.DateField(blank=True, null=True)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"jiayilu96@gmail.com"
] | jiayilu96@gmail.com |
a3392be60bc656170a178d7024e13bbff66399ff | f8543f8292b42a7e8670b3ae6d80ee2eeecfb777 | /analytic/analytic.py | 28a4a71fb6593c726eb740e96dd851dbc9af74da | [] | no_license | alexandercorvinus/monthly-commitment-management | 6b64a62de7ac15336eb1dbf84cf2459abbc9e0e0 | 186875bb23ae8dad2b66ff0ce4878c6dfdd364a6 | refs/heads/master | 2021-01-10T14:27:23.000202 | 2016-04-08T14:12:45 | 2016-04-08T14:12:45 | 55,698,106 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 19,345 | py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import time
from datetime import datetime
from openerp.osv import fields, osv
from openerp import tools
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
class account_analytic_account(osv.osv):
_name = 'account.analytic.account'
_inherit = ['mail.thread']
_description = 'Analytic Account'
_track = {
'state': {
'analytic.mt_account_pending': lambda self, cr, uid, obj, ctx=None: obj.state == 'pending',
'analytic.mt_account_closed': lambda self, cr, uid, obj, ctx=None: obj.state == 'close',
'analytic.mt_account_opened': lambda self, cr, uid, obj, ctx=None: obj.state == 'open',
},
}
def _compute_level_tree(self, cr, uid, ids, child_ids, res, field_names, context=None):
currency_obj = self.pool.get('res.currency')
recres = {}
def recursive_computation(account):
result2 = res[account.id].copy()
for son in account.child_ids:
result = recursive_computation(son)
for field in field_names:
if (account.currency_id.id != son.currency_id.id) and (field!='quantity'):
result[field] = currency_obj.compute(cr, uid, son.currency_id.id, account.currency_id.id, result[field], context=context)
result2[field] += result[field]
return result2
for account in self.browse(cr, uid, ids, context=context):
if account.id not in child_ids:
continue
recres[account.id] = recursive_computation(account)
return recres
def _debit_credit_bal_qtty(self, cr, uid, ids, fields, arg, context=None):
res = {}
if context is None:
context = {}
child_ids = tuple(self.search(cr, uid, [('parent_id', 'child_of', ids)]))
for i in child_ids:
res[i] = {}
for n in fields:
res[i][n] = 0.0
if not child_ids:
return res
where_date = ''
where_clause_args = [tuple(child_ids)]
if context.get('from_date', False):
where_date += " AND l.date >= %s"
where_clause_args += [context['from_date']]
if context.get('to_date', False):
where_date += " AND l.date <= %s"
where_clause_args += [context['to_date']]
cr.execute("""
SELECT a.id,
sum(
CASE WHEN l.amount > 0
THEN l.amount
ELSE 0.0
END
) as debit,
sum(
CASE WHEN l.amount < 0
THEN -l.amount
ELSE 0.0
END
) as credit,
COALESCE(SUM(l.amount),0) AS balance,
COALESCE(SUM(l.unit_amount),0) AS quantity
FROM account_analytic_account a
LEFT JOIN account_analytic_line l ON (a.id = l.account_id)
WHERE a.id IN %s
""" + where_date + """
GROUP BY a.id""", where_clause_args)
for row in cr.dictfetchall():
res[row['id']] = {}
for field in fields:
res[row['id']][field] = row[field]
return self._compute_level_tree(cr, uid, ids, child_ids, res, fields, context)
def name_get(self, cr, uid, ids, context=None):
res = []
if not ids:
return res
if isinstance(ids, (int, long)):
ids = [ids]
for id in ids:
elmt = self.browse(cr, uid, id, context=context)
res.append((id, self._get_one_full_name(elmt)))
return res
def _get_full_name(self, cr, uid, ids, name=None, args=None, context=None):
if context == None:
context = {}
res = {}
for elmt in self.browse(cr, uid, ids, context=context):
res[elmt.id] = self._get_one_full_name(elmt)
return res
def _get_one_full_name(self, elmt, level=6):
if level<=0:
return '...'
if elmt.parent_id and not elmt.type == 'template':
parent_path = self._get_one_full_name(elmt.parent_id, level-1) + " / "
else:
parent_path = ''
return parent_path + elmt.name
def _child_compute(self, cr, uid, ids, name, arg, context=None):
result = {}
if context is None:
context = {}
for account in self.browse(cr, uid, ids, context=context):
result[account.id] = map(lambda x: x.id, [child for child in account.child_ids if child.state != 'template'])
return result
def _get_analytic_account(self, cr, uid, ids, context=None):
company_obj = self.pool.get('res.company')
analytic_obj = self.pool.get('account.analytic.account')
accounts = []
for company in company_obj.browse(cr, uid, ids, context=context):
accounts += analytic_obj.search(cr, uid, [('company_id', '=', company.id)])
return accounts
def _set_company_currency(self, cr, uid, ids, name, value, arg, context=None):
if isinstance(ids, (int, long)):
ids=[ids]
for account in self.browse(cr, uid, ids, context=context):
if account.company_id:
if account.company_id.currency_id.id != value:
raise osv.except_osv(_('Error!'), _("If you set a company, the currency selected has to be the same as it's currency. \nYou can remove the company belonging, and thus change the currency, only on analytic account of type 'view'. This can be really useful for consolidation purposes of several companies charts with different currencies, for example."))
if value:
cr.execute("""update account_analytic_account set currency_id=%s where id=%s""", (value, account.id))
self.invalidate_cache(cr, uid, ['currency_id'], [account.id], context=context)
def _currency(self, cr, uid, ids, field_name, arg, context=None):
result = {}
for rec in self.browse(cr, uid, ids, context=context):
if rec.company_id:
result[rec.id] = rec.company_id.currency_id.id
else:
result[rec.id] = rec.currency_id.id
return result
_columns = {
'contract_name': fields.char('Account/Contract Name'),
'complete_name': fields.function(_get_full_name, type='char', string='Full Name'),
'code': fields.char('Reference', select=True, track_visibility='onchange', copy=False),
'type': fields.selection([('view','Analytic View'), ('normal','Analytic Account'),('contract','Contract or Project'),('template','Template of Contract')], 'Type of Account', required=True,
help="If you select the View Type, it means you won\'t allow to create journal entries using that account.\n"\
"The type 'Analytic account' stands for usual accounts that you only want to use in accounting.\n"\
"If you select Contract or Project, it offers you the possibility to manage the validity and the invoicing options for this account.\n"\
"The special type 'Template of Contract' allows you to define a template with default data that you can reuse easily."),
'template_id': fields.many2one('account.analytic.account', 'Template of Contract'),
'description': fields.text('Description'),
'parent_id': fields.many2one('account.analytic.account', 'Parent Analytic Account', select=2),
'child_ids': fields.one2many('account.analytic.account', 'parent_id', 'Child Accounts', copy=True),
'child_complete_ids': fields.function(_child_compute, relation='account.analytic.account', string="Account Hierarchy", type='many2many'),
'line_ids': fields.one2many('account.analytic.line', 'account_id', 'Analytic Entries', copy=False),
'balance': fields.function(_debit_credit_bal_qtty, type='float', string='Balance', multi='debit_credit_bal_qtty', digits_compute=dp.get_precision('Account')),
'debit': fields.function(_debit_credit_bal_qtty, type='float', string='Debit', multi='debit_credit_bal_qtty', digits_compute=dp.get_precision('Account')),
'credit': fields.function(_debit_credit_bal_qtty, type='float', string='Credit', multi='debit_credit_bal_qtty', digits_compute=dp.get_precision('Account')),
'quantity': fields.function(_debit_credit_bal_qtty, type='float', string='Quantity', multi='debit_credit_bal_qtty'),
'quantity_max': fields.float('Prepaid Service Units', help='Sets the higher limit of time to work on the contract, based on the timesheet. (for instance, number of hours in a limited support contract.)'),
'partner_id': fields.many2one('res.partner', 'Customer'),
'user_id': fields.many2one('res.users', 'Project Manager', track_visibility='onchange'),
'manager_id': fields.many2one('res.users', 'Account Manager', track_visibility='onchange'),
'date_start': fields.date('Start Date'),
'date': fields.date('Expiration Date', select=True, track_visibility='onchange'),
'company_id': fields.many2one('res.company', 'Company', required=False), #not required because we want to allow different companies to use the same chart of account, except for leaf accounts.
'state': fields.selection([('template', 'Template'),
('draft','New'),
('open','Open'),
('pending','To Renew'),
('close','Closed'),
('cancelled', 'Cancelled')],
'Status', required=True,
track_visibility='onchange', copy=False),
'currency_id': fields.function(_currency, fnct_inv=_set_company_currency, #the currency_id field is readonly except if it's a view account and if there is no company
store = {
'res.company': (_get_analytic_account, ['currency_id'], 10),
}, string='Currency', type='many2one', relation='res.currency'),
'name': fields.char('Reference', select=True, track_visibility='onchange', copy=False),
'service_type': fields.selection([
('loan','Loan'),
('utility','Utility'),
('cc','Credit Card')], string="Service Type"),
}
def create(self, cr, uid, vals, context=None):
print 'add create function'
if vals.get('name','') == '':
vals['name'] = self.pool.get('ir.sequence').get(cr, uid, 'account.analytic.account') or ''
ctx = dict(context or {}, mail_create_nolog=True)
res = super(account_analytic_account, self).create(cr, uid, vals, context=ctx)
return res
def on_change_template(self, cr, uid, ids, template_id, date_start=False, context=None):
if not template_id:
return {}
res = {'value':{}}
template = self.browse(cr, uid, template_id, context=context)
if template.date_start and template.date:
from_dt = datetime.strptime(template.date_start, tools.DEFAULT_SERVER_DATE_FORMAT)
to_dt = datetime.strptime(template.date, tools.DEFAULT_SERVER_DATE_FORMAT)
timedelta = to_dt - from_dt
res['value']['date'] = datetime.strftime(datetime.now() + timedelta, tools.DEFAULT_SERVER_DATE_FORMAT)
if not date_start:
res['value']['date_start'] = fields.date.today()
res['value']['quantity_max'] = template.quantity_max
res['value']['parent_id'] = template.parent_id and template.parent_id.id or False
res['value']['description'] = template.description
return res
def on_change_partner_id(self, cr, uid, ids,partner_id, name, context=None):
res={}
if partner_id:
partner = self.pool.get('res.partner').browse(cr, uid, partner_id, context=context)
if partner.user_id:
res['manager_id'] = partner.user_id.id
if not name:
res['contract_name'] = _('Agreement: ') + partner.name
return {'value': res}
def _default_company(self, cr, uid, context=None):
user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
if user.company_id:
return user.company_id.id
return self.pool.get('res.company').search(cr, uid, [('parent_id', '=', False)])[0]
def _get_default_currency(self, cr, uid, context=None):
user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
return user.company_id.currency_id.id
_defaults = {
'type': 'contract',
'company_id': _default_company,
# 'number' : lambda obj, cr, uid, context: '/',
'state': 'open',
'user_id': lambda self, cr, uid, ctx: uid,
'partner_id': lambda self, cr, uid, ctx: ctx.get('partner_id', False),
'manager_id': lambda self, cr, uid, ctx: ctx.get('manager_id', False),
'date_start': lambda *a: time.strftime('%Y-%m-%d'),
'currency_id': _get_default_currency,
}
def check_recursion(self, cr, uid, ids, context=None, parent=None):
return super(account_analytic_account, self)._check_recursion(cr, uid, ids, context=context, parent=parent)
_order = 'code, name asc'
_constraints = [
(check_recursion, 'Error! You cannot create recursive analytic accounts.', ['parent_id']),
]
def name_create(self, cr, uid, name, context=None):
raise osv.except_osv(_('Warning'), _("Quick account creation disallowed."))
def copy(self, cr, uid, id, default=None, context=None):
""" executed only on the toplevel copied object of the hierarchy.
Subobject are actually copied with copy_data"""
if not default:
default = {}
analytic = self.browse(cr, uid, id, context=context)
default['name'] = _("%s (copy)") % analytic['name']
return super(account_analytic_account, self).copy(cr, uid, id, default, context=context)
def on_change_company(self, cr, uid, id, company_id):
if not company_id:
return {}
currency = self.pool.get('res.company').read(cr, uid, [company_id], ['currency_id'])[0]['currency_id']
return {'value': {'currency_id': currency}}
def on_change_parent(self, cr, uid, id, parent_id):
if not parent_id:
return {}
parent = self.read(cr, uid, [parent_id], ['partner_id','code'])[0]
if parent['partner_id']:
partner = parent['partner_id'][0]
else:
partner = False
res = {'value': {}}
if partner:
res['value']['partner_id'] = partner
return res
def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
if not args:
args=[]
if context is None:
context={}
account_ids = []
if name:
account_ids = self.search(cr, uid, [('code', '=', name)] + args, limit=limit, context=context)
if not account_ids:
dom = []
if '/' in name:
for name2 in name.split('/'):
# intermediate search without limit and args - could be expensive for large tables if `name` is not selective
account_ids = self.search(cr, uid, dom + [('name', operator, name2.strip())], limit=None, context=context)
if not account_ids: break
dom = [('parent_id','in',account_ids)]
if account_ids and args:
# final filtering according to domain (args)4
account_ids = self.search(cr, uid, [('id', 'in', account_ids)] + args, limit=limit, context=context)
if not account_ids:
return super(account_analytic_account, self).name_search(cr, uid, name, args, operator=operator, context=context, limit=limit)
return self.name_get(cr, uid, account_ids, context=context)
class account_analytic_line(osv.osv):
_name = 'account.analytic.line'
_description = 'Analytic Line'
_columns = {
'name': fields.char('Description', required=True),
'date': fields.date('Date', required=True, select=True),
'amount': fields.float('Amount', required=True, help='Calculated by multiplying the quantity and the price given in the Product\'s cost price. Always expressed in the company main currency.', digits_compute=dp.get_precision('Account')),
'unit_amount': fields.float('Quantity', help='Specifies the amount of quantity to count.'),
'account_id': fields.many2one('account.analytic.account', 'Analytic Account', required=True, ondelete='restrict', select=True, domain=[('type','<>','view')]),
'user_id': fields.many2one('res.users', 'User'),
'company_id': fields.related('account_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
}
def _get_default_date(self, cr, uid, context=None):
return fields.date.context_today(self, cr, uid, context=context)
def __get_default_date(self, cr, uid, context=None):
return self._get_default_date(cr, uid, context=context)
_defaults = {
'date': __get_default_date,
'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.analytic.line', context=c),
'amount': 0.00
}
_order = 'date desc'
def _check_no_view(self, cr, uid, ids, context=None):
analytic_lines = self.browse(cr, uid, ids, context=context)
for line in analytic_lines:
if line.account_id.type == 'view':
return False
return True
_constraints = [
(_check_no_view, 'You cannot create analytic line on view account.', ['account_id']),
]
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| [
"alexandercorvinus221@gmail.com"
] | alexandercorvinus221@gmail.com |
d6e9d373af82d2a2ecb6d81b58bba30f87d34c24 | 55978323c87857a5ae10bc45632c2db9bcaf482d | /Face_and_Eye_Detection.py | 7e00ab77f0b2c465cecef9d5c86d111fb9488bd3 | [] | no_license | Hi-Uday/Real-time-Face-and-Eyes-detection | f80d26908f570b346de63853321a6eb6f8ecc004 | 4947f49fc7275cb74c24055081c6110f660f9998 | refs/heads/master | 2022-07-22T05:58:25.020474 | 2020-05-14T03:48:44 | 2020-05-14T03:48:44 | 263,807,435 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,176 | py | import cv2
faceCascade = cv2.CascadeClassifier("Temp/haarcascade_fromtalface_default.xml")
L_eyeCascade=cv2.CascadeClassifier("Temp/LeftEye.xml")
R_eyeCascade=cv2.CascadeClassifier("Temp/RightEye.xml")
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
)
LEye = L_eyeCascade.detectMultiScale(gray, 1.1, 4)
REye = R_eyeCascade.detectMultiScale(gray, 1.1, 4)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
for (x, y, w, h) in LEye:
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
for (x, y, w, h) in REye:
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
| [
"noreply@github.com"
] | Hi-Uday.noreply@github.com |
7a7e96ffb61726de2d180025d83908a58c2436e9 | 99b4956b0026c1c4cb023424342fc75f523aa4fa | /04.adventure/22.rangement/sprite.py | ce61013bdaa892c349ce6963e7e4749ba8b9451b | [
"MIT"
] | permissive | Gaetz/python-training | 37c234128d834ee29e0e625f265cf0b68158c228 | 542f658883c66aaa932fb9e385225cfd573bb6de | refs/heads/master | 2021-05-09T03:44:22.990658 | 2020-10-02T18:29:50 | 2020-10-02T18:29:50 | 119,250,880 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,028 | py | import pygame
class Sprite(object):
path = 'D:\\Code\\ArtFx\\Python\\python-training\\01.adventure\\22.rangement\\images\\'
def __init__(self, x, y, filename, centered):
self.x = x
self.y = y
self.surface = pygame.image.load(Sprite.path + filename).convert_alpha()
self.ox = 0
self.oy = 0
if(centered):
self.ox = -self.surface.get_width() / 2
self.oy = -self.surface.get_height()
def set_position(self, position):
self.x = position[0]
self.y = position[1]
def intersects(self, sprite):
x1, y1, w1, h1 = self.x + self.ox, self.y + self.oy, self.surface.get_width(), self.surface.get_height()
x2, y2, w2, h2 = sprite.x + sprite.ox, sprite.y + sprite.oy, sprite.surface.get_width(), sprite.surface.get_height()
return not(x1 + w1 < x2 or x2 + w2 < x1 or y1 + h1 < y2 or y2 + h2 < y1)
def draw(self, screen):
screen.blit(self.surface, (self.x + self.ox, self.y + self.oy))
| [
"gaetan.blaisecazalet@gmail.com"
] | gaetan.blaisecazalet@gmail.com |
c2284bb43fb4e394112d42285ea0651e895b3bad | ed1e306db93ccbb599c37013190bf624dad6b1cd | /1149(두 수 중 큰 수 출력).py | bf9c340dd8168d808bb467d91390ac52b3b4a74c | [] | no_license | subinYoun/CodeUp-1101-1161- | 8965de4f655f30f154729eae54a909bba24749de | 1a58cece10215effd93f6d2fce6b5b9cbbb0d65b | refs/heads/master | 2023-02-23T17:17:20.485922 | 2021-01-29T15:06:43 | 2021-01-29T15:06:43 | 334,177,845 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 83 | py | #두 수 중 큰 수 출력
a, b=map(int, input().split())
print("%d" %(max(a, b))) | [
"younsue0825@naver.com"
] | younsue0825@naver.com |
6abfcba35e49972578fffffe12179486b1abcd5f | 670e2cda023384ff2c6902e22db698abedd86a92 | /babynames/solution/babynames.py | 48dd52dbd2f5d68586d5cd8d00b3ff1672b7fda4 | [] | no_license | MichaelDeutschCoding/Python_Baby_Projects | e204b99734606daea7008e7d1e29deffc20bf8c8 | 49186be14dcc8cd0135aa6ba8c4dcd7d1ccd8dd1 | refs/heads/master | 2020-09-12T10:16:46.700884 | 2019-11-26T18:25:32 | 2019-11-26T18:25:32 | 222,391,782 | 0 | 0 | null | 2019-11-26T18:25:33 | 2019-11-18T07:50:28 | HTML | UTF-8 | Python | false | false | 3,867 | py | #!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
"""Baby Names exercise
Define the extract_names() function below and change main()
to call it.
For writing regex, it's nice to include a copy of the target
text for inspiration.
Here's what the html looks like in the baby.html files:
...
<h3 align="center">Popularity in 1990</h3>
....
<tr align="right"><td>1</td><td>Michael</td><td>Jessica</td>
<tr align="right"><td>2</td><td>Christopher</td><td>Ashley</td>
<tr align="right"><td>3</td><td>Matthew</td><td>Brittany</td>
...
Suggested milestones for incremental development:
-Extract the year and print it
-Extract the names and rank numbers and just print them
-Get the names data into a dict and print it
-Build the [year, 'name rank', ... ] list and print it
-Fix main() to use the extract_names list
"""
def extract_names(filename):
"""
Given a file name for baby.html, returns a list starting with the year string
followed by the name-rank strings in alphabetical order.
['2006', 'Aaliyah 91', Aaron 57', 'Abagail 895', ' ...]
"""
# +++your code here+++
# LAB(begin solution)
# The list [year, name_and_rank, name_and_rank, ...] we'll eventually return.
names = []
# Open and read the file.
f = open(filename, 'r')
text = f.read()
f.close()
# Could process the file line-by-line, but regex on the whole text
# at once is even easier.
# Get the year.
year_match = re.search(r'Popularity\sin\s(\d\d\d\d)', text)
if not year_match:
# We didn't find a year, so we'll exit with an error message.
sys.stderr.write('Couldn\'t find the year!\n')
sys.exit(1)
year = year_match.group(1)
names.append(year)
# Extract all the data tuples with a findall()
# each tuple is: (rank, boy-name, girl-name)
tuples = re.findall(r'<td>(\d+)</td><td>(\w+)</td>\<td>(\w+)</td>', text)
#print tuples
# Store data into a dict using each name as a key and that
# name's rank number as the value.
# (if the name is already in there, don't add it, since
# this new rank will be bigger than the previous rank).
names_to_rank = {}
for rank_tuple in tuples:
(rank, boyname, girlname) = rank_tuple # unpack the tuple into 3 vars
if boyname not in names_to_rank:
names_to_rank[boyname] = rank
if girlname not in names_to_rank:
names_to_rank[girlname] = rank
# You can also write:
# for rank, boyname, girlname in tuples:
# ...
# To unpack the tuples inside a for-loop.
# Get the names, sorted in the right order
sorted_names = sorted(names_to_rank.keys())
# Build up result list, one element per line
for name in sorted_names:
names.append(name + " " + names_to_rank[name])
return names
# LAB(replace solution)
# return
# LAB(end solution)
def main():
# This command-line parsing code is provided.
# Make a list of command line arguments, omitting the [0] element
# which is the script itself.
args = sys.argv[1:]
if not args:
print ('usage: [--summaryfile] file [file ...]')
sys.exit(1)
# Notice the summary flag and remove it from args if it is present.
summary = False
if args[0] == '--summaryfile':
summary = True
del args[0]
# +++your code here+++
# For each filename, get the names, then either print the text output
# or write it to a summary file
# LAB(begin solution)
for filename in args:
names = extract_names(filename)
# Make text out of the whole list
text = '\n'.join(names)
if summary:
outf = open(filename + '.summary', 'w')
outf.write(text + '\n')
outf.close()
else:
print (text)
# LAB(end solution)
if __name__ == '__main__':
main()
| [
"noreply@github.com"
] | MichaelDeutschCoding.noreply@github.com |
67e264c9876bb2fce3543c2d00cd2b862a584618 | 0d5b83606fa6d3fabc09bffd4b17522aea598229 | /vgg19.py | 4c2232b066214964869459bb7c244b99a474e456 | [] | no_license | nihaotiancai/style_transform | cf6eeaed5fffee63c9aad1a0b897c6ab406d3f93 | 23af9ac958f8233eba6a4e11268c6141ec46a8db | refs/heads/master | 2020-04-23T13:09:35.855207 | 2019-02-18T02:00:35 | 2019-02-18T02:00:35 | 171,194,086 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,868 | py | #coding:utf-8
import os
import tensorflow as tf
import numpy as np
import inspect
VGG_MEAN = [103.939, 116.779, 123.68]
# 封装Vgg19模型及操作
class Vgg19:
# 初始化 加载预训练模型 vgg19.npy
def __init__(self, vgg19_npy_path=None):
if vgg19_npy_path is None:
path = inspect.getfile(Vgg19)
path = os.path.abspath(os.path.join(path, os.pardir))
path = os.path.join(path, "vgg19.npy")
vgg19_npy_path = path
print(vgg19_npy_path)
self.data_dict = np.load(vgg19_npy_path, encoding='latin1').item()
print("npy file loaded")
# 编码器(特征提取)
def encoder(self, inputs, target_layer):
# 构建指定层与数字的对应关系
layer_num =dict(zip(['relu1', 'relu2', 'relu3', 'relu4', 'relu5'],range(1, 6)))[target_layer]
encode = inputs
# 定义 编码器参数表
encoder_arg={
'1': [('conv1_1', 64),
('conv1_2', 64),
('pool1', 64)],
'2': [('conv2_1', 128),
('conv2_2', 128),
('pool2', 128)],
'3': [('conv3_1', 256),
('conv3_2', 256),
('conv3_3', ),
('conv3_4', 256),
('pool3', 256)],
'4': [('conv4_1', 512),
('conv4_2', 512),
('conv4_3', 512),
('conv4_4', 512),
('pool4', 512)],
'5': [('conv5_1', 512),
('conv5_2', 512),
('conv5_3', 512),
('conv5_4', 512)]}
# 根据需要提取的指定层特征,将输入 依次进行 该层之前的所有变换,获得该层特征
for d in range(1, layer_num+1):
for layer in encoder_arg[str(d)]:
# 如果是卷积层,进行卷积操作
if 'conv' in layer[0] :
encode =self.conv_layer(encode, layer[0])
# 如果是池化层,进行池化操作
if 'pool' in layer[0] and d < layer_num:
encode = self.max_pool(encode, layer[0])
return encode
# 对输入进行池化操作
def max_pool(self, bottom, name):
# 对输入进行池化操作,尺寸为2 步长为 2 全0填充
return tf.nn.max_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name)
# 对输入进行卷积操作
def conv_layer(self, bottom, name):
with tf.variable_scope(name):
# 从模型中取卷积核参数
filt = self.get_conv_filter(name)
# 定义卷积核尺寸
filt_size = 3
# 对输入图片进行边缘填充,消除边界效应
bottom = tf.pad(bottom,[[0,0],[int(filt_size/2),int(filt_size/2)],[int(filt_size/2),int(filt_size/2)],[0,0]],mode= 'REFLECT')
# 对bottom 以 filt为卷积核进行卷积
conv = tf.nn.conv2d(bottom, filt, [1, 1, 1, 1], padding='VALID')
# 预训练模型中读取偏置项参数
conv_biases = self.get_bias(name)
# 引入偏置
bias = tf.nn.bias_add(conv, conv_biases)
# 进行 relu 非线性变换
relu = tf.nn.relu(bias)
return relu
# 从模型中获取 卷积核的值
def get_conv_filter(self, name):
return tf.constant(self.data_dict[name][0], name="filter")
# 从模型中获取 偏置项的值
def get_bias(self, name):
return tf.constant(self.data_dict[name][1], name="biases")
# 从模型中获取 权重的值
def get_fc_weight(self, name):
return tf.constant(self.data_dict[name][0], name="weights")
| [
"824938649@qq.com"
] | 824938649@qq.com |
918c5792164f2295977dfd0a68a09cf4c43c4379 | 41bc3f4c8cf5e723f6764a878e36838762bf6b9e | /libs/image_helper.py | 1c5caeb957be0964614eb01889f58dc861ca9757 | [] | no_license | WilsonPhooYK/udemy-advanced-restapi-flask-python | 109f5b92db34ce49affdea060ff1800cde9686a5 | d06b28a9c7a898abf2d126e4a47a0f4fcab7489c | refs/heads/main | 2023-05-06T22:50:03.838524 | 2021-06-01T08:58:09 | 2021-06-01T08:58:09 | 370,373,721 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,200 | py | import os
import re
from typing import Optional, Union
from werkzeug.datastructures import FileStorage
from flask_uploads import UploadSet, IMAGES
# "images" must be same as the center of UPLOADED_IMAGES_DEST in config
IMAGE_SET = UploadSet("images", IMAGES) # set name and allowed extensions
def save_image(image: FileStorage, folder: Optional[str] = None, name: Optional[str] = None) -> str:
"""Takes FileStorage and saves it to a folder
"""
return IMAGE_SET.save(image, folder, name)
def get_path(filename: str, folder: str) -> str:
"""Take image name and folder and return full path
"""
return IMAGE_SET.path(filename, folder)
def find_image_any_format(filename: str, folder: str) -> Union[str, None]:
"""Takes a filename and returns an iamge on any of the accepted formats.
"""
for _format in IMAGES:
image = f"{filename}.{_format}"
image_path = IMAGE_SET.path(filename=image, folder=folder)
if os.path.isfile(image_path):
return image_path
def _retrieve_filename(file: Union[str, FileStorage]) -> Union[str, None]:
"""Take FileStorage and return the file name
Allows our function to call with both file names and FileStorages and always get back a file name.
"""
if isinstance(file, FileStorage):
return file.filename
return file
def is_filename_safe(file: Union[str, FileStorage]) -> bool:
"""Check our regex and return whether the string matches or not
"""
filename = _retrieve_filename(file)
if not filename:
return False
allowed_format = "|".join(IMAGES) # png|svg|jpg
regex = f"^[a-zA-Z0-9][a-zA-Z0-9_()-\\.]*\\.({allowed_format})$"
return re.match(regex, filename) is not None
def get_basename(file: Union[str, FileStorage]) -> str:
"""Return full name of image in the path
get basename('some/folder/image.jpg') returns 'image.jpg'
"""
filename = _retrieve_filename(file)
return os.path.split(filename)[1] # type: ignore
def get_extension(file: Union[str, FileStorage]) -> str:
"""Return file extension
"""
filename = _retrieve_filename(file)
return os.path.splitext(filename)[1] # type: ignore
| [
"wilson@policypal.com"
] | wilson@policypal.com |
351429a0b415e319d26caf353060320b8d7c63bb | bf41ebd8931c92cfb82bd0934a82d94eacd72c95 | /2second.py | ac23a3c11a0d8ac29e7c9744e938d228d30fb9a2 | [] | no_license | DjPetuhe/euler-project | 8ce990fc078710e988966e5262aa9a1e6ca7e267 | 0365d6b0f5b424063317838c318fa0062080fadf | refs/heads/master | 2022-12-31T11:48:48.100041 | 2020-10-24T18:10:45 | 2020-10-24T18:10:45 | 302,047,440 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 157 | py | i = 0
x = 1
y = 1
Result = 0
while (i <= 4000000):
i = x + y
if (i % 2 == 0 and i <= 4000000):
Result += i
x = y
y = i
print(Result)
| [
"validhernufKPI@gmail.com"
] | validhernufKPI@gmail.com |
dbe01cfd78374273c1c4be47f16e8c86a9962fcb | 13d222bc3332378d433835914da26ed16b583c8b | /src/pemjh/challenge52/main.py | b1407abc5c0d32694b4aaf0241a641dcaad75fcd | [] | no_license | mattjhussey/pemjh | c27a09bab09cd2ade31dc23fffac07374bea9366 | 2ebb0a525d2d1c0ee28e83fdc2638c2bec97ac99 | refs/heads/master | 2023-04-16T03:08:59.390698 | 2023-04-08T10:54:00 | 2023-04-08T10:54:00 | 204,912,926 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 681 | py | """ Challenge052 """
def get_sorted_string(unsorted):
"""
>>> get_sorted_string(54326)
'23456'
>>> get_sorted_string("aBayU")
'BUaay'
"""
return "".join(sorted(str(unsorted)))
def main():
""" challenge052 """
root = 0
found = False
while not found:
root += 1
root_sorted = get_sorted_string(root)
found = True
for i in range(2, 7):
# Try i * root
multiple = root * i
multiple_sorted = get_sorted_string(multiple)
if root_sorted != multiple_sorted:
found = False
break
return root
| [
"matthew.hussey@googlemail.com"
] | matthew.hussey@googlemail.com |
93387f1dc695c60c5047d6ab3abd0328d63afe8d | 848bb1e6266c0d7ab52a19a65a052f9635a9f1e5 | /sss.py | 669b9e42decd5da475ffabc3e9170cc11f67e9bf | [] | no_license | giuseppegargiulo/GargiuloPy | 58e8e680e2a196fb47d29d2f87181b9f32d899e8 | e8a1dee0341cd8688aaf42af5479e42ef467d04f | refs/heads/master | 2023-02-26T01:13:12.234315 | 2021-01-24T20:52:14 | 2021-01-24T20:52:14 | 318,179,905 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 252 | py | def max_frequency(x):
for i in x:
n=0
for j in x:
if i == j :
n += 1
print("la lettera",i,"é ripetuta", n, "volte nella parola")
x= input("inserisci una parola:")
print(max_frequency(x))
| [
"giuseppe.gargiulo.s4@liceoviconapoli.it"
] | giuseppe.gargiulo.s4@liceoviconapoli.it |
fcf6d5b203f22c6e42690390171431383fde3627 | 9b328903c7ce1ddfc957c6db4a5fef265bce1dad | /preprocess.py | 2d04c659dfe88bfdce2082cc1a99285c36834611 | [] | no_license | matatabinoneko/viral_tweet_generation | 4a610b0327d7ce0e8e2b94eec0f82aa9f1c35ca1 | 1e26de293420dbed6f50f161b3210c9d14e3b2d4 | refs/heads/main | 2023-03-12T16:11:14.187622 | 2021-03-02T00:11:47 | 2021-03-02T00:11:47 | 330,305,509 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,466 | py | '''
ツイートの前処理を行う
'''
import argparse
import logzero
from logzero import logger
import logging
from os import path
from typing import List
from filtering_type import EmoticonFilter
import json
import MeCab
from collections import defaultdict
import re
logger.setLevel(logging.INFO)
mecabTagger = MeCab.Tagger("-Ochasen")
hiragana = re.compile('[ぁ-ゟ]+')
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'-i', '--input', type=path.abspath, help='input file path')
parser.add_argument(
'-o', '--output', type=path.abspath, help='output file path')
parser.add_argument(
"--tokenizer", type=str, default="char", help="tokenizer. Select mecab if you want to use mecab"
)
args = parser.parse_args()
return args
def full_width2half_width(text: str) -> str:
'''
全角文字を半角文字に変換
'''
# 変換
text = text.translate(str.maketrans(
{chr(0xFF01 + i): chr(0x21 + i) for i in range(94)}))
return text
def test_full_width2half_width():
text = "!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`>?@abcdefghijklmnopqrstuvwxyz{|}~"
trans_text = full_width2half_width(text)
answer = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`>?@abcdefghijklmnopqrstuvwxyz{|}~'
assert trans_text == answer, f"{trans_text}\n{answer}"
def is_char_length(text: str, max_length=140) -> bool:
'''
max_length以上のツイートの場合はFalseを返す
'''
return len(text) <= 140
def test_is_char_length():
text_list = ["", ''.join(['a' for _ in range(139)]), ''.join(
['a' for _ in range(140)]), ''.join(['a' for _ in range(141)])]
answer_list = [True, True, True, False]
for text, answer in zip(text_list, answer_list):
assert is_char_length(text) == answer
def get_keywords(text: str) -> List[str]:
"""
ツイートからキーワードを抽出
Parameters
----------
text : str
ツイート
Returns
-------
keywords : List[str]
キーワードのリスト
"""
keywords = []
node = mecabTagger.parseToNode(text)
while node:
word = node.surface
hinshi = node.feature.split(",")
if hinshi[0] == "名詞" and hinshi[1] != "代名詞" and not hiragana.fullmatch(word):
keywords.append(word)
node = node.next
keywords = list(set(keywords))
return keywords
def test_get_keywords():
queries = ["私のご飯", 'あれとこれ', 'ももとすもも']
answers = [["ご飯"], [], []]
for q, a in zip(queries, answers):
q = get_keywords(q)
assert set(q) == set(a), f"{q},{a}"
def main():
args = parse_args()
logger.info(args)
def tokenizer(text): return self.mecab.parse(text).split(
) if args.tokenizer == 'mecab' else ' '.join(list(text))
filter = EmoticonFilter()
cnt_dic = defaultdict(int)
with open(args.input, 'r') as fin, open(args.output, 'w') as fout:
for line in fin:
try:
line = json.loads(line)
text = line["text"]
# 顔文字を含むツイートは除外
if filter._has_emoticon(text):
cnt_dic['emoji'] += 1
continue
if not is_char_length(text):
logger.debug(f"this tweet is exceed 140 chars. \n{text}")
cnt_dic["more_than_140"] += 1
continue
# user nameを削除
text = filter._username_filter(text)
# スペースなどを置換
text = filter._normalization(text)
keywords = list(map(tokenizer, get_keywords(text)))
text = tokenizer(text)
print(json.dumps(
{"keywords": keywords, "tweet": text}, ensure_ascii=False), file=fout)
except:
cnt_dic['error'] += 1
logger.error(f"this data is skipped {line}")
logger.info(
f"emoji tweet: {cnt_dic['emoji']}\nmore than 140 tweet:{cnt_dic['more_than_140']}\nerror:{cnt_dic['error']}")
if __name__ == '__main__':
main()
| [
"matatabinoneko0721@gmail.com"
] | matatabinoneko0721@gmail.com |
f9eee3d75da6c00be6f06d18eadf0dc2d8d29d0e | c47e4d8ae6673b5a84d1cd0377e1de0667fd1716 | /Tranlator_sysargv.py | 60e29e32063a374bb79106af543b4af50ac27ded | [] | no_license | Group1SohrabiMirdamadi/Session1819 | a071c17dd1f07653efef5f072efbd1d5805c62d5 | 949301cb24e95b5459866cf31c228814866c0928 | refs/heads/main | 2023-04-12T08:14:16.402148 | 2021-05-07T18:03:03 | 2021-05-07T18:03:03 | 364,950,988 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 442 | py | import translators as ts
import sys
import argparse
if __name__ == '__main__':
first_file, second_file, from_language, to_language, provider = sys.argv[1:]
with open(first_file, 'r') as file:
text = file.read()
with open(second_file, 'w') as file2:
result = str(getattr(ts, provider)(text, from_language=from_language, to_language=to_language))
print(result)
file2.write(result)
| [
"noreply@github.com"
] | Group1SohrabiMirdamadi.noreply@github.com |
45b646902cf554c6366326fa77166b47d450b073 | 4bb4cdc2d69e1214edbc98a46a9ac6127bf13361 | /app/models.py | 01d87a8227b201de78f8ff7bc8b27589e3fa8820 | [] | no_license | KirillSefirov/microblog | 2413b75f1cf8c84b6b057dc9af64b3f3f9491681 | 0917b2d3d07f674d6601d638d55827ffa5767fae | refs/heads/main | 2023-01-19T19:40:55.663780 | 2020-11-30T15:14:04 | 2020-11-30T15:14:04 | 317,256,363 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 758 | py | from app import db
from datetime import datetime
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
posts = db.relationship('Post', backref='author', lazy='dynamic')
def __repr__(self):
return '<User {}>'.format(self.username)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String(140))
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
def __repr__(self):
return '<Post {}>'.format(self.body)
| [
"kirill.sefirov@gmail.com"
] | kirill.sefirov@gmail.com |
5d13fd9be23e0669146b534fc415bc453768ddae | 4510e511cd166791ce027cd099c865da090c0095 | /technology/languages/serverSide/python/webFrameworks/socket/udpClientDemo.py | a068290c9b076e5c8906a30cafece4a471817dbc | [] | no_license | Alex-wfh/Learn | 504d5fd32290835e6894092f10989072da20ee61 | 7138d4308227be934dff8ce7f8419ecca0ca0b5d | refs/heads/master | 2021-06-01T10:54:13.704152 | 2021-04-02T10:16:05 | 2021-04-02T10:16:05 | 109,950,435 | 1 | 2 | null | null | null | null | UTF-8 | Python | false | false | 213 | py | import socket
HOST = '127.0.0.1'
PORT = 9527
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
data = 'Hello UDP!'
s.sendto(data.encode('utf8'), (HOST, PORT))
print(f'Send: {data} to {HOST}:{PORT}')
s.close() | [
"837473220@qq.com"
] | 837473220@qq.com |
d2073b44941a8b10b0f318e261b778ebfa05acb5 | ac437ec9da993386ef0348cc176f4519274aadf0 | /schemas/product/productSubTypeSchema.py | 651efc87dc23dac4ca9e0418ba7ec7697ef5d4a3 | [] | no_license | Syed-Bakhtiyar/SalesManCompleteApp | d853e459e79ddf023249ab20bc6205813d7913ec | 8c956e5c8e109a2c186af7a4e7ea9c48d34e0ba7 | refs/heads/master | 2021-05-11T15:41:56.555234 | 2019-01-20T13:24:49 | 2019-01-20T13:24:49 | 117,736,146 | 0 | 0 | null | 2018-10-20T09:16:17 | 2018-01-16T20:13:25 | Python | UTF-8 | Python | false | false | 566 | py | sqlCreateProductSubTypeTable = "CREATE TABLE IF NOT EXISTS product_sub_type_table(ID INT NOT NULL AUTO_INCREMENT, " \
"PRODUCT_TYPE_ID INT NOT NULL, " \
"TITLE VARCHAR(40) NOT NULL DEFAULT ''," \
"UNIQUE (PRODUCT_TYPE_ID, TITLE)," \
"PRIMARY KEY (ID)," \
"FOREIGN KEY (PRODUCT_TYPE_ID) REFERENCES product_type_table(ID)"\
")"
| [
"syedbakhtiyar120@gmail.com"
] | syedbakhtiyar120@gmail.com |
caa4886993b2a6034b738129474f78353d70e2af | c427d9142df033af2b509412153dae35706ede61 | /recognition/pytorch_crnn/models/layers.py | fbaa09d9385382391ff58e1b8a380ebc4e74d249 | [] | no_license | brahimbellahcen/ocr_toolkit | 0b68776fe20b05f48807f856fffac752e3e08e66 | b4516d4193132eb48f821926dd6ef5d368f53899 | refs/heads/master | 2022-11-13T10:21:14.083497 | 2020-06-26T15:31:38 | 2020-06-26T15:31:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,032 | py | import torch
import torch.nn as nn
import torch.nn.functional as F
class blockCNN(nn.Module):
def __init__(self, in_nc, out_nc, kernel_size, padding, stride=1):
super(blockCNN, self).__init__()
self.in_nc = in_nc
self.out_nc = out_nc
self.kernel_size = kernel_size
self.padding = padding
# layers
self.conv = nn.Conv2d(in_nc, out_nc,
kernel_size=kernel_size,
stride=stride,
padding=padding)
self.bn = nn.BatchNorm2d(out_nc)
def forward(self, batch, use_bn=False, use_relu=False,
use_maxpool=False, maxpool_kernelsize=None):
"""
in:
batch - [batch_size, in_nc, H, W]
out:
batch - [batch_size, out_nc, H', W']
"""
batch = self.conv(batch)
if use_bn:
batch = self.bn(batch)
if use_relu:
batch = F.relu(batch)
if use_maxpool:
assert maxpool_kernelsize is not None
batch = F.max_pool2d(batch, kernel_size=maxpool_kernelsize, stride=2)
return batch
class blockRNN(nn.Module):
def __init__(self, in_size, hidden_size, out_size, bidirectional, dropout=0):
super(blockRNN, self).__init__()
self.in_size = in_size
self.hidden_size = hidden_size
self.out_size = out_size
self.bidirectional = bidirectional
# layers
self.gru = nn.GRU(in_size, hidden_size, bidirectional=bidirectional)
def forward(self, batch, add_output=False):
"""
in array:
batch - [seq_len , batch_size, in_size]
out array:
out - [seq_len , batch_size, out_size]
"""
# batch_size = batch.size(1)
outputs, hidden = self.gru(batch)
out_size = int(outputs.size(2) / 2)
if add_output:
outputs = outputs[:, :, :out_size] + outputs[:, :, out_size:]
return outputs
| [
"selcukcaglar08@gmail.com"
] | selcukcaglar08@gmail.com |
5047da393e9ac594565718071d047097aaa75afb | c4dd0e3177abcbf0e2043d99bbec953278f38fe3 | /JD/jdIndex/views.py | 1c207e26de8ea3a025782ded248ca0d831042ad9 | [] | no_license | hehaowen/djangotest | 37fba79bcb3c4be2d354f57724a07714e69974ad | f87f919a70a0d87bbf027f9c3ed96805c73ce739 | refs/heads/master | 2020-03-08T07:41:59.440604 | 2018-04-04T10:12:07 | 2018-04-04T10:12:07 | 128,000,970 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 131 | py | from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'jdIndex/index.html') | [
"944818557@qq.com"
] | 944818557@qq.com |
b67789d4edbbbe1481c6e7f78a355e9e062e37aa | 27dc1dbb14a74caed22c4d242d70aa8a39c7a891 | /tcpClient.py | c79dbede494c5221ca23929839a79d8caac0b974 | [] | no_license | AglaianWoman/blackhatPython | 8debf9d6abe029ed386211decf56aff783c1a6ad | 648e6bb0aad6cd403175576165de7d28d9f24268 | refs/heads/master | 2021-05-06T20:58:28.438969 | 2017-11-03T13:29:08 | 2017-11-03T13:29:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 336 | py | #!/usr/bin/env python2
import socket;
target_host = "127.0.0.1";
target_port = 9999;
# AF_INET = IPv4
# SOCK_STREAM = TCP client
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
client.connect((target_host, target_port));
client.send("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n");
answer = client.recv(4096);
print answer; | [
"Jeppesen@tutanota.com"
] | Jeppesen@tutanota.com |
3e4af5c3428191b0f79157993cb4dc07ac9263b8 | bb983b38f9be7b6fd4ab1a651484db37c1aeff39 | /1122/my_library.py | 4e67830a25ee13ef2bb56196db5322f8047d4396 | [] | no_license | nakanishi-akitaka/python2018_backup | c214df78372cca993d69f8001010ec2f6dcaf1be | 45766d3c3777de2a91b3e2cf50c6bfedca8627da | refs/heads/master | 2023-02-18T08:04:28.625532 | 2022-06-07T01:02:53 | 2022-06-07T01:02:53 | 201,399,236 | 5 | 30 | null | 2023-02-10T21:06:51 | 2019-08-09T05:48:22 | Jupyter Notebook | UTF-8 | Python | false | false | 20,812 | py | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 8 10:29:27 2018
@author: Akitaka
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
from sklearn.model_selection import KFold
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import cross_val_predict
from sklearn.metrics import confusion_matrix, accuracy_score
from sklearn.neighbors import NearestNeighbors
from sklearn.svm import OneClassSVM
from scipy.spatial.distance import cdist
def print_gscv_score(gscv):
"""
print score of results of GridSearchCV
Parameters
----------
gscv :
GridSearchCV (scikit-learn)
Returns
-------
None
"""
print("Best parameters set found on development set:")
print()
print(gscv.best_params_)
print()
print("Grid scores on development set:")
print()
# means = gscv.cv_results_['mean_test_score']
# stds = gscv.cv_results_['std_test_score']
# for mean, std, params in zip(means, stds, gscv.cv_results_['params']):
# print("{:.3f} (+/-{:.03f}) for {:}".format(mean, std * 2, params))
def print_gscv_score_rgr(gscv, X_train, X_test, y_train, y_test, cv):
"""
print score of results of GridSearchCV (regression)
Parameters
----------
gscv :
GridSearchCV (scikit-learn)
X_train : array-like, shape = [n_samples, n_features]
X training data
y_train : array-like, shape = [n_samples]
y training data
X_test : array-like, sparse matrix, shape = [n_samples, n_features]
X test data
y_test : array-like, shape = [n_samples]
y test data
cv : int, cross-validation generator or an iterable
ex: 3, 5, KFold(n_splits=5, shuffle=True)
Returns
-------
None
"""
lgraph = False
print()
print("Best parameters set found on development set:")
print(gscv.best_params_)
y_calc = gscv.predict(X_train)
rmse = np.sqrt(mean_squared_error (y_train, y_calc))
mae = mean_absolute_error(y_train, y_calc)
r2 = r2_score (y_train, y_calc)
print('C: RMSE, MAE, R^2 = {:6.3f}, {:6.3f}, {:6.3f}'\
.format(rmse, mae, r2))
if(lgraph):
yyplot(y_train, y_calc)
y_incv = cross_val_predict(gscv, X_train, y_train, cv=cv)
rmse = np.sqrt(mean_squared_error (y_train, y_incv))
mae = mean_absolute_error(y_train, y_incv)
r2 = r2_score (y_train, y_incv)
print('CV: RMSE, MAE, R^2 = {:6.3f}, {:6.3f}, {:6.3f}'\
.format(rmse, mae, r2))
if(lgraph):
yyplot(y_train, y_incv)
y_pred = gscv.predict(X_test)
rmse = np.sqrt(mean_squared_error (y_test, y_pred))
mae = mean_absolute_error(y_test, y_pred)
r2 = r2_score (y_test, y_pred)
print('TST:RMSE, MAE, R^2 = {:6.3f}, {:6.3f}, {:6.3f}'\
.format(rmse, mae, r2))
if(lgraph):
yyplot(y_test, y_pred)
# y_calc = gscv.predict(X_train)
# gscv.fit(X_train, y_train, cv=3)
# -> split X_train, y_train & optimize hyper parameters
# -> finally, learn with all X_train, y_train
# C: RMSE, MAE, R^2 = score for training data
# CV: RMSE, MAE, R^2 = score for validation data
# Validation data is not used, but CV is used.
# TST:RMSE, MAE, R^2 = score for test data
# In dcv_rgr,
# DCV:RMSE, MAE, R^2 = average and standard deviation of score for test data
print()
def print_gscv_score_clf(gscv, X_train, X_test, y_train, y_test, cv):
"""
print score of results of GridSearchCV (classification)
Parameters
----------
gscv :
GridSearchCV (scikit-learn)
X_train : array-like, shape = [n_samples, n_features]
X training data
y_train : array-like, shape = [n_samples]
y training data
X_test : array-like, sparse matrix, shape = [n_samples, n_features]
X test data
y_test : array-like, shape = [n_samples]
y test data
cv : int, cross-validation generator or an iterable
ex: 3, 5, KFold(n_splits=5, shuffle=True)
Returns
-------
None
"""
print()
print("Best parameters set found on development set:")
print(gscv.best_params_)
y_calc = gscv.predict(X_train)
tn, fp, fn, tp = confusion_matrix(y_train, y_calc).ravel()
print('C: TP, FP, FN, TN, Acc. = {0}, {1}, {2}, {3}, {4:.3f}'.\
format(tp, fp, fn, tn, accuracy_score(y_train, y_calc)))
y_incv = cross_val_predict(gscv, X_train, y_train, cv=cv)
tn, fp, fn, tp = confusion_matrix(y_train, y_incv).ravel()
print('CV: TP, FP, FN, TN, Acc. = {0}, {1}, {2}, {3}, {4:.3f}'.\
format(tp, fp, fn, tn, accuracy_score(y_train, y_incv)))
y_pred = gscv.predict(X_test)
tn, fp, fn, tp = confusion_matrix(y_test, y_pred).ravel()
print('TST:TP, FP, FN, TN, Acc. = {0}, {1}, {2}, {3}, {4:.3f}'.\
format(tp, fp, fn, tn, accuracy_score(y_test, y_pred)))
print()
def print_score_rgr(y_test,y_pred):
"""
print score of results of regression
Parameters
----------
y_test : array-like, shape = [n_samples]
y test data
y_pred : array-like, shape = [n_samples]
y predicted data
Returns
-------
None
"""
rmse = np.sqrt(mean_squared_error (y_test,y_pred))
mae = mean_absolute_error(y_test,y_pred)
if(mae > 0):
rmae = np.sqrt(mean_squared_error (y_test,y_pred))/mae
else:
rmae = 0.0
r2 = r2_score (y_test,y_pred)
print('RMSE, MAE, RMSE/MAE, R^2 = {:.3f}, {:.3f}, {:.3f}, {:.3f}'\
.format(rmse, mae, rmae, r2))
if(rmae > np.sqrt(np.pi/2.0)):
print("RMSE/MAE = {:.3f} > sqrt(pi/2), some sample have large error?"\
.format(rmae))
elif(rmae < np.sqrt(np.pi/2.0)):
print("RMSE/MAE = {:.3f} < sqrt(pi/2), each sample have same error?"\
.format(rmae))
elif(rmae == np.sqrt(np.pi/2.0)):
print("RMSE/MAE = {:.3f} = sqrt(pi/2), normal distribution error?"\
.format(rmae))
def yyplot(y_obs, y_pred):
"""
print yy-plot
Parameters
----------
y_obs : array-like, shape = [n_samples]
y observed data
y_pred : array-like, shape = [n_samples]
y predicted data
Returns
-------
Figure object
"""
fig = plt.figure(figsize=(9,4))
plt.subplot(1,2,1)
plt.title("yy-plot")
plt.scatter(y_obs, y_pred)
y_all = np.concatenate([y_obs, y_pred])
ylowlim = np.amin(y_all) - 0.05 * np.ptp(y_all)
yupplim = np.amax(y_all) + 0.05 * np.ptp(y_all)
plt.plot([ylowlim, yupplim],
[ylowlim, yupplim],'k-')
plt.ylim( ylowlim, yupplim)
plt.xlim( ylowlim, yupplim)
plt.xlabel("y_observed")
plt.ylabel("y_predicted")
plt.subplot(1,2,2)
error = np.array(y_pred-y_obs)
plt.hist(error)
plt.title("Error histogram")
plt.xlabel('prediction error')
plt.ylabel('Frequency')
plt.tight_layout()
plt.show()
return fig
def dcv(X,y,mod,param_grid):
"""
Double cross validation
Parameters
----------
X : array-like, shape = [n_samples, n_features]
X training+test data
y : array-like, shape = [n_samples]
y training+test data
mod :
machine learning model (scikit-learn)
param_grid : dict or list of dictionaries
Dictionary with parameters names (string) as keys and lists of
parameter settings to try as values, or a list of such dictionaries,
in which case the grids spanned by each dictionary in the list are
explored.
Returns
-------
None
"""
# parameters
ns_in = 3 # n_splits for inner loop
ns_ou = 3 # n_splits for outer loop
i = 1 # index of loop
scores = np.array([]) # list of test scores in outer loop
kf_ou = KFold(n_splits=ns_ou, shuffle=True)
# [start] outer loop for test of the generalization error
for train_index, test_index in kf_ou.split(X):
X_train, X_test = X[train_index], X[test_index] # inner loop CV
y_train, y_test = y[train_index], y[test_index] # outer loop
# [start] inner loop CV for hyper parameter optimization
kf_in = KFold(n_splits=ns_in, shuffle=True)
gscv = GridSearchCV(mod, param_grid, cv=kf_in)
gscv.fit(X_train, y_train)
# [end] inner loop CV for hyper parameter optimization
# test of the generalization error
score = gscv.score(X_test, y_test)
scores = np.append(scores, score)
# print('dataset: {}/{} accuracy of inner CV: {:.3f} time: {:.3f} s'.\
# format(i,ns_ou,score,(time() - start)))
i+=1
# [end] outer loop for test of the generalization error
print(' ave, std of accuracy of inner CV: {:.3f} (+/-{:.3f})'\
.format(scores.mean(), scores.std()*2 ))
def dcv_rgr(X, y, model, param_grid, niter):
"""
Double cross validation (regression)
Parameters
----------
X : array-like, shape = [n_samples, n_features]
X training+test data
y : array-like, shape = [n_samples]
y training+test data
model:
machine learning model (scikit-learn)
param_grid : dict or list of dictionaries
Dictionary with parameters names (string) as keys and lists of
parameter settings to try as values, or a list of such dictionaries,
in which case the grids spanned by each dictionary in the list are
explored.
niter : int
number of DCV iteration
Returns
-------
None
"""
# parameters
ns_in = 3 # n_splits for inner loop
ns_ou = 3 # n_splits for outer loop
scores = np.zeros((niter,3))
for iiter in range(niter):
ypreds = np.array([]) # list of predicted y in outer loop
ytests = np.array([]) # list of y_test in outer loop
kf_ou = KFold(n_splits=ns_ou, shuffle=True)
# [start] outer loop for test of the generalization error
for train_index, test_index in kf_ou.split(X):
X_train, X_test = X[train_index], X[test_index] # inner loop CV
y_train, y_test = y[train_index], y[test_index] # outer loop
# [start] inner loop CV for hyper parameter optimization
kf_in = KFold(n_splits=ns_in, shuffle=True)
gscv = GridSearchCV(model, param_grid, cv=kf_in)
gscv.fit(X_train, y_train)
# [end] inner loop CV for hyper parameter optimization
# test of the generalization error
ypred = gscv.predict(X_test)
ypreds = np.append(ypreds, ypred)
ytests = np.append(ytests, y_test)
# [end] outer loop for test of the generalization error
rmse = np.sqrt(mean_squared_error (ytests, ypreds))
mae = mean_absolute_error(ytests, ypreds)
r2 = r2_score (ytests, ypreds)
# print('DCV:RMSE, MAE, R^2 = {:.3f}, {:.3f}, {:.3f}'\
# .format(rmse, mae, r2))
scores[iiter,:] = np.array([rmse,mae,r2])
means, stds = np.mean(scores, axis=0),np.std(scores, axis=0)
print()
print('Double Cross Validation')
print('In {:} iterations, average +/- standard deviation'.format(niter))
# print('RMSE: {:6.3f} (+/-{:6.3f})'.format(means[0], stds[0]))
# print('MAE : {:6.3f} (+/-{:6.3f})'.format(means[1], stds[1]))
# print('R^2 : {:6.3f} (+/-{:6.3f})'.format(means[2], stds[2]))
print('DCV:RMSE, MAE, R^2 = {:6.3f}, {:6.3f}, {:6.3f} (ave)'\
.format(means[0], means[1], means[2]))
print('DCV:RMSE, MAE, R^2 = {:6.3f}, {:6.3f}, {:6.3f} (std)'\
.format(stds[0], stds[1], stds[2]))
def dcv_clf(X, y, model, param_grid, niter):
"""
Double cross validation (classification)
Parameters
----------
X : array-like, shape = [n_samples, n_features]
X training+test data
y : array-like, shape = [n_samples]
y training+test data
model: estimator object.
This is assumed to implement the scikit-learn estimator interface.
param_grid : dict or list of dictionaries
Dictionary with parameters names (string) as keys and lists of
parameter settings to try as values, or a list of such dictionaries,
in which case the grids spanned by each dictionary in the list are
explored.
niter : int
number of DCV iteration
Returns
-------
None
"""
# parameters
ns_in = 3 # n_splits for inner loop
ns_ou = 3 # n_splits for outer loop
scores = np.zeros((niter,5))
for iiter in range(niter):
ypreds = np.array([]) # list of predicted y in outer loop
ytests = np.array([]) # list of y_test in outer loop
kf_ou = KFold(n_splits=ns_ou, shuffle=True)
# [start] outer loop for test of the generalization error
for train_index, test_index in kf_ou.split(X):
X_train, X_test = X[train_index], X[test_index] # inner loop CV
y_train, y_test = y[train_index], y[test_index] # outer loop
# [start] inner loop CV for hyper parameter optimization
kf_in = KFold(n_splits=ns_in, shuffle=True)
gscv = GridSearchCV(model, param_grid, cv=kf_in)
gscv.fit(X_train, y_train)
# [end] inner loop CV for hyper parameter optimization
# test of the generalization error
ypred = gscv.predict(X_test)
ypreds = np.append(ypreds, ypred)
ytests = np.append(ytests, y_test)
# [end] outer loop for test of the generalization error
tn, fp, fn, tp = confusion_matrix(ytests, ypreds).ravel()
acc = accuracy_score(ytests, ypreds)
scores[iiter,:] = np.array([tp,fp,fn,tn,acc])
means, stds = np.mean(scores, axis=0),np.std(scores, axis=0)
print()
print('Double Cross Validation')
print('In {:} iterations, average +/- standard deviation'.format(niter))
print('TP DCV: {:.3f} (+/-{:.3f})'.format(means[0], stds[0]))
print('FP DCV: {:.3f} (+/-{:.3f})'.format(means[1], stds[1]))
print('FN DCV: {:.3f} (+/-{:.3f})'.format(means[2], stds[2]))
print('TN DCV: {:.3f} (+/-{:.3f})'.format(means[3], stds[3]))
print('Acc. DCV: {:.3f} (+/-{:.3f})'.format(means[4], stds[4]))
def optimize_gamma(X, gammas):
"""
Optimize gamma by maximizing variance in Gram matrix
Parameters
----------
X : array-like, shape = [n_samples, n_features]
X training+test data
gammas : list
list of gammas
Returns
-------
real
optimized gamma
"""
var_matrix = list()
for gamma in gammas:
gram_matrix = np.exp(-gamma*((X[:, np.newaxis] - X)**2).sum(axis=2))
var_matrix.append(gram_matrix.var(ddof=1))
return gammas[ np.where( var_matrix == np.max(var_matrix) )[0][0] ]
def ad_knn(X_train, X_test):
"""
Determination of Applicability Domain (k-Nearest Neighbor)
Parameters
----------
X_train : array-like, shape = [n_samples, n_features]
X training data
X_test : array-like, shape = [n_samples, n_features]
X test data
Returns
-------
array-like, shape = [n_samples]
-1 (outer of AD) or 1 (inner of AD)
"""
n_neighbors = 5 # number of neighbors
r_ad = 0.9 # ratio of X_train inside AD / all X_train
# ver.1
neigh = NearestNeighbors(n_neighbors=n_neighbors+1)
neigh.fit(X_train)
dist_list = np.mean(neigh.kneighbors(X_train)[0][:,1:], axis=1)
dist_list.sort()
ad_thr = dist_list[round(X_train.shape[0] * r_ad) - 1]
neigh = NearestNeighbors(n_neighbors=n_neighbors)
neigh.fit(X_train)
dist = np.mean(neigh.kneighbors(X_test)[0], axis=1)
y_appd = 2 * (dist < ad_thr) -1
# ver.2
if(False):
# ref
# https://datachemeng.com/wp-content/uploads/assignment15.py
dist_matrix = cdist(X_train, X_train)
dist_matrix.sort()
dist_list = np.mean(dist_matrix[:, 1:n_neighbors+1], axis=1)
dist_list.sort()
ad_thr = dist_list[round(X_train.shape[0] * r_ad) - 1]
dist_matrix = cdist(X_test, X_train)
dist_matrix.sort()
dist = np.mean(dist_matrix[:, 0:n_neighbors], axis=1)
y_appd2 = 2 * (dist < ad_thr) -1
print(np.allclose(y_appd,y_appd2))
return y_appd
def ad_knn_list(X_train, X_test, max_neighbors):
"""
Determination of Applicability Domain (k-Nearest Neighbor)
Parameters
----------
X_train : array-like, shape = [n_samples, n_features]
X training data
X_test : array-like, shape = [n_samples, n_features]
X test data
max_neighbors : maximum of neighbors
Returns
-------
array-like, shape = [n_samples, max_neighbors]
-1 (outer of AD) or 1 (inner of AD) for k=1, ..., max_neighbors
"""
# ref
# https://datachemeng.com/wp-content/uploads/assignment15.py
r_ad = 0.997 # ratio of X_train inside AD / all X_train
y_appd = np.zeros((X_test.shape[0], max_neighbors))
for i in range(max_neighbors):
n_neighbors = i + 1 # number of neighbors
# ver.1
neigh = NearestNeighbors(n_neighbors=n_neighbors+1)
neigh.fit(X_train)
dist_list = np.mean(neigh.kneighbors(X_train)[0][:,1:], axis=1)
# neigh.kneighbors[0] = distances [nsample, n_neighbors]
# neigh.kneighbors[1] = indices [nsample, n_neighbors]
# http://gratk.hatenablog.jp/entry/2017/12/10/205033
dist_list.sort()
ad_thr = dist_list[round(X_train.shape[0] * r_ad) - 1]
neigh = NearestNeighbors(n_neighbors=n_neighbors)
neigh.fit(X_train)
dist = np.mean(neigh.kneighbors(X_test)[0], axis=1)
y_appd_test1 = 2 * (dist < ad_thr) -1
if(False):
# ver.2
# ref
# https://datachemeng.com/wp-content/uploads/assignment15.py
dist_matrix_train = cdist(X_train, X_train)
dist_matrix_train.sort()
dist_list = np.mean(dist_matrix_train[:, 1:n_neighbors+1], axis=1)
# skip [:,0] = 0.0 = distance from self.
dist_list.sort()
ad_thr = dist_list[round(X_train.shape[0] * r_ad) - 1]
dist_matrix_test = cdist(X_test, X_train)
dist_matrix_test.sort()
dist = np.mean(dist_matrix_test[:, 0:n_neighbors], axis=1)
y_appd_test2 = 2 * (dist < ad_thr) -1
print(np.allclose(y_appd_test1,y_appd_test2))
y_appd[:,i] = 2 * (dist < ad_thr) -1
return y_appd
def ad_ocsvm(X_train, X_test):
"""
Determination of Applicability Domains (One-Class Support Vector Machine)
Parameters
----------
X_train : array-like, shape = [n_samples, n_features]
X training data
X_test : array-like, shape = [n_samples, n_features]
X test data
Returns
-------
array-like, shape = [n_samples]
-1 (outer of AD) or 1 (inner of AD)
"""
range_g = 2**np.arange( -20, 11, dtype=float)
optgamma = optimize_gamma(X_train, range_g)
clf = OneClassSVM(nu=0.003, gamma=optgamma)
clf.fit(X_train)
y_appd = clf.predict(X_test) # outliers = -1
return y_appd
def y_randamization_rgr(X,y,model,param_grid,niter):
# parameters
scores = np.zeros((niter,3))
for iiter in range(niter):
y_rand = np.random.permutation(y)
gscv = GridSearchCV(model, param_grid, cv=KFold(n_splits=3, shuffle=True))
gscv.fit(X, y_rand)
y_pred = gscv.predict(X)
rmse = np.sqrt(mean_squared_error (y_rand, y_pred))
mae = mean_absolute_error(y_rand, y_pred)
r2 = r2_score (y_rand, y_pred)
scores[iiter,:] = np.array([rmse,mae,r2])
means, stds = np.mean(scores, axis=0),np.std(scores, axis=0)
print()
print("y-randomization")
print('In {:} iterations, average +/- standard deviation'.format(niter))
# print('RMSE: {:6.3f} (+/-{:.3f})'.format(means[0], stds[0]))
# print('MAE : {:6.3f} (+/-{:.3f})'.format(means[1], stds[1]))
# print('R^2 : {:6.3f} (+/-{:.3f})'.format(means[2], stds[2]))
print('rnd:RMSE, MAE, R^2 = {:6.3f}, {:6.3f}, {:6.3f} (ave)'\
.format(means[0], means[1], means[2]))
print('rnd:RMSE, MAE, R^2 = {:6.3f}, {:6.3f}, {:6.3f} (std)'\
.format(stds[0], stds[1], stds[2]))
return
if __name__ == '__main__':
print('Hello world')
| [
"noreply@github.com"
] | nakanishi-akitaka.noreply@github.com |
333356308bf67247ffab922853f0ef721496998e | a216f8ed103affb7bb2cb9ab3b0e2f1d9e3e2d49 | /get_started/dictionary/problem34.py | e17290c33c3fead0ad7664bbae2161c3cc520a91 | [] | no_license | rwaidaAlmehanni/python_course | c2fe0c0448891c2c9a11434a09aa4074775a24f0 | 903e6d5a77b6ece5e36daf0e2c369a4a4e9715d9 | refs/heads/master | 2020-12-25T18:33:21.403084 | 2017-06-17T10:47:51 | 2017-06-17T10:47:51 | 93,965,508 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 332 | py | #Improve the above program to print the words in the descending order of the number of occurrences.
import sys
def test(words): # return factorial
x=[]
f={}
for w in words:
f[w] = f.get(w, 0) + 1
for word, count in f.items():
x.append((word,count))
x.sort()
print x[::-1]
test(open(sys.argv[1]).read().split()) | [
"rwaidaAlmehanni"
] | rwaidaAlmehanni |
39aeb6e973594342d29c7e0c62856e9bdb055bea | e5ee4f343d9523129298e1cd989b52a142028cfe | /samples/contrib/azure-samples/databricks-pipelines/databricks_cluster_pipeline.py | 4cbd45e50b4cab9d62b7e153d21fb6660ecc37ea | [
"Apache-2.0"
] | permissive | joaoalvarenga/pipelines | 67c5b2c906134be8d4814a0851e4b60dfa4adf44 | 493c3d4e980b94a963a257247c6eb2d970b3dafa | refs/heads/master | 2020-12-08T18:22:52.433779 | 2020-01-10T05:00:34 | 2020-01-10T05:00:34 | 233,059,234 | 1 | 0 | Apache-2.0 | 2020-01-10T14:03:36 | 2020-01-10T14:03:35 | null | UTF-8 | Python | false | false | 1,780 | py | """Create a cluster in Databricks. Then submit a one-time Run to that cluster."""
import kfp.dsl as dsl
import kfp.compiler as compiler
import databricks
def create_cluster(cluster_name):
return databricks.CreateClusterOp(
name="createcluster",
cluster_name=cluster_name,
spark_version="5.3.x-scala2.11",
node_type_id="Standard_D3_v2",
spark_conf={
"spark.speculation": "true"
},
num_workers=2
)
def submit_run(run_name, cluster_id, parameter):
return databricks.SubmitRunOp(
name="submitrun",
run_name=run_name,
existing_cluster_id=cluster_id,
libraries=[{"jar": "dbfs:/docs/sparkpi.jar"}],
spark_jar_task={
"main_class_name": "org.apache.spark.examples.SparkPi",
"parameters": [parameter]
}
)
def delete_run(run_name):
return databricks.DeleteRunOp(
name="deleterun",
run_name=run_name
)
def delete_cluster(cluster_name):
return databricks.DeleteClusterOp(
name="deletecluster",
cluster_name=cluster_name
)
@dsl.pipeline(
name="DatabricksCluster",
description="A toy pipeline that computes an approximation to pi with Azure Databricks."
)
def calc_pipeline(cluster_name="test-cluster", run_name="test-run", parameter="10"):
create_cluster_task = create_cluster(cluster_name)
submit_run_task = submit_run(run_name, create_cluster_task.outputs["cluster_id"], parameter)
delete_run_task = delete_run(run_name)
delete_run_task.after(submit_run_task)
delete_cluster_task = delete_cluster(cluster_name)
delete_cluster_task.after(delete_run_task)
if __name__ == "__main__":
compiler.Compiler().compile(calc_pipeline, __file__ + ".tar.gz")
| [
"k8s-ci-robot@users.noreply.github.com"
] | k8s-ci-robot@users.noreply.github.com |
74cb61526fe2c6c0696942829281e1a903153a9b | 3740d53844d7c3178789590a16f479778f72155e | /wordcount/settings.py | b98de4a963c7fae4ffbfe5c6adf7fcccbceea7f3 | [] | no_license | pike-taken/wordcount---project1 | d1b0bb64d4632a70cd21d1d9d76a829ef7de4785 | 0fd7730e0cfad5cf87264da00378cc4b1f2bbc04 | refs/heads/master | 2020-12-10T05:09:08.364864 | 2020-01-13T04:27:58 | 2020-01-13T04:27:58 | 233,509,847 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,108 | py | """
Django settings for wordcount project.
Generated by 'django-admin startproject' using Django 2.2.8.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '+o&q^ax-tl)k+fz2+q#@6wg%64bro*w)m%)_kf3*#nmpo+ry94'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'wordcount.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'wordcount.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
| [
"piketaken00@gmail.com"
] | piketaken00@gmail.com |
dd9c4e13f64a8ad0f0ec0fe2b2c7035fab754415 | 903f479b8186020f0630c07c504b64ff50ee7b3b | /Task_0_4.py | ef4cacdd067c4d2a49c4489923ae69c60130b7ca | [] | no_license | Mpho-L/Level-0-Coding-Challenges | c85704c7ee2e92a205d3832024fe9ef5dae8ab00 | 7b673d50178b6032cf5844c2afb57ef7270f41e8 | refs/heads/main | 2023-08-28T04:54:23.115260 | 2021-09-28T06:46:29 | 2021-09-28T06:46:29 | 407,781,099 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 99 | py | def even_or_odd(x):
if x % 2 == 0:
print('even')
else:
print('odd')
even_or_odd(6) | [
"mpholeqoalane@gmail.com"
] | mpholeqoalane@gmail.com |
eda475b4a0ab689cf97894c2af87c4b6bbcf78d3 | 428ea81730a7102cb3ede62d16d16ed79cab7905 | /Mundo_2/desafio054.py | 28f219ecdc7bf86cf9834c23759b0280864158ff | [] | no_license | reinaldoboas/Curso_em_Video_Python | 290f5387bd70caf74c06b33cdb34d9b2809088c3 | 7c36b84df957721ff20019eb90fdabdd49acaa94 | refs/heads/master | 2020-11-27T06:59:24.683947 | 2020-06-10T13:49:09 | 2020-06-10T13:49:09 | 229,346,624 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 626 | py | ### Curso em Vídeo - Exercicio: desafio054.py
### Link: https://www.youtube.com/watch?v=IL5iBWoKRIs
### Crie um programa que leia o ano de nascimento de sete pessoas.
### No final, mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores.
from datetime import date
ano_atual = date.today().year
maiores = 0
menores = 0
for c in range(0, 7):
ano_nasc=int(input("Digite o ano de nascimento da pessoa:"))
idade = ano_atual - ano_nasc
if idade < 18:
menores += 1
else:
maiores += 1
print(f"No final das contas temos {menores} menores de 18 anos e {maiores} maiores.")
| [
"noreply@github.com"
] | reinaldoboas.noreply@github.com |
5b46996c84345b6406c48c03241e97ddfdbd1ac8 | d066f7fe739fb78f74ec2de8ccbfefdd4270f60f | /appimagebuilder/__init__.py | 5b4148a08e2776e617d6700c316eba5fc4629b93 | [
"MIT"
] | permissive | AppImageCrafters/appimage-builder | 666e75363a74f615cdb3673b3ca9d51a6d292a49 | f38699ef3644fa5409a5a262b7b6d99d6fb85db9 | refs/heads/main | 2023-08-17T06:34:54.029664 | 2023-06-03T17:51:04 | 2023-06-03T17:51:04 | 218,847,680 | 270 | 54 | MIT | 2023-09-06T17:04:18 | 2019-10-31T19:44:17 | Python | UTF-8 | Python | false | false | 651 | py | #!/usr/bin/env python3
# Copyright 2020 Alexis Lopez Zubieta
#
# 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.
| [
"contact@azubieta.net"
] | contact@azubieta.net |
18456f70a13ab649bec041f59c07887ad6b793d1 | 7f188822de3ea6fabb0e13786524c9e470a7888b | /Parte2/Semana3/Ex1_Triangulos_Retangulos.py | 15383dbd0ad0d8b326ce56fde65572f8b71614e9 | [] | no_license | mayaragualberto/Introducao-CC-com-Python | e8ecfa7d580b6f5be15c4ed2cf06147ab990f4ce | 8b26247e49e2735e2353f0b6b33bc062faa7ad8a | refs/heads/master | 2023-03-17T14:33:06.408639 | 2021-03-11T01:29:51 | 2021-03-11T01:29:51 | 267,616,690 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 628 | py | class Triangulo:
def __init__(self,a,b,c):
self.a =a
self.b =b
self.c =c
def retangulo(self):
retangulo = False
if self.a**2==self.b**2+self.c**2:
retangulo=True
return retangulo
if self.b**2==self.c**2+self.a**2:
retangulo=True
return retangulo
if self.c**2==self.a**2+self.b**2:
retangulo=True
return retangulo
if (self.a == self.b == self.c):
retangulo=False
return retangulo
else:
retangulo=False
return retangulo
| [
"noreply@github.com"
] | mayaragualberto.noreply@github.com |
a44dddd493284c3d87790f159fd35a7df45feb5a | 147bc95b8b8a36014ec001bb1f79100095fa90a4 | /day05/字典实现通讯录功能.py | 118765e0740f80e3d6060493272d6942d3ffdf3d | [] | no_license | zhangwei725/PythonBase | fd20293b7f7ebee9f11a5df8f4761cad7f1ff4c7 | 6c9165caed48418eb55cf7622359105c9124e580 | refs/heads/master | 2020-04-30T00:32:40.360722 | 2019-04-03T01:41:51 | 2019-04-03T01:41:51 | 176,505,618 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,100 | py | # 1、实现通讯录功能(字典的方式)
# 1. 查询联系人
# 2. 添加联系人
# 3. 更新联系人
# 4. 删除联系人
# 5. 退出程序
# 用来存储联系人的通信相关的信息
contacts = {'宝宝': 110}
while True:
print('=======简易通讯录======')
print('1. 查询联系人')
print('2. 添加联系人')
print('3. 更新联系人')
print('4. 删除联系人')
print('5. 退出程序')
print('=======================')
num = input('请选择相关的操作!!!')
if num == '1':
# 查询的操作
name = input('请输入联系人姓名:\n')
if name:
# 查询 get() 字典[key] for循环
#
# 如果in跟字典配合使用 判断键是否存在
if name in contacts:
print('{} : {}'.format(name, contacts.get(name)))
else:
print("输入的用户名不能为空!!!")
elif num == '2':
# 添加操作
name = input('请输入联系人姓名:\n')
if name in contacts:
print('联系人已存在!!!! 请重新选择!!!')
else:
phone = input('请输入电话号码!!!')
# 字典[key] = 值 update(k=v) setdefault(k,v)
contacts[name] = phone
elif num == '3':
# 更新操作
# update() 字典[key] = 值
name = input('请输入联系人姓名:\n')
if name in contacts:
phone = input('请输入电话号码!!!')
contacts[name] = phone
else:
print('联系人不存在')
elif num == '4':
# pop
name = input('请输入要删除的联系人的姓名:\n')
if name in contacts:
contacts.pop(name)
print('删除成功!!!')
else:
print('联系人不存在!!!')
elif num == '5':
print('系统安全退出ing')
break
else:
print('输入有误请重新输入')
print('本次循环结束,继续下一次循环')
# 字符串的常用操作
# 推导
# 集合 去重
| [
"36558563@qq.com"
] | 36558563@qq.com |
01d0dda66acc0233bb2265310298798754cc5d7e | 589c2e7e0a5559d6a8dd618c3181b28df9a9bdde | /connector/MyIO.py | 77f1e7ae12f1b1c56f3f43b2e9d1cdc8412e2be0 | [] | no_license | athenasaurav/rasa_connector | 4a276a8db658e057ff593da013fb91e84a952168 | 35c7286aad273db26998f8f2f084fff2b930fca5 | refs/heads/main | 2023-04-01T17:31:13.981836 | 2021-04-19T11:10:57 | 2021-04-19T11:10:57 | 351,421,438 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,624 | py | import asyncio
import inspect
from sanic import Sanic, Blueprint, response
from sanic.request import Request
from sanic.response import HTTPResponse
from typing import Text, Dict, Any, Optional, Callable, Awaitable, NoReturn
from asyncio import Queue, CancelledError
import rasa.utils.endpoints
from rasa.core.channels.channel import (
InputChannel,
CollectingOutputChannel,
UserMessage,
)
class MyioInput(InputChannel):
@classmethod
def name(cls) -> Text:
return "myio"
@staticmethod
async def on_message_wrapper(
on_new_message: Callable[[UserMessage], Awaitable[Any]],
text: Text,
queue: Queue,
sender_id: Text,
input_channel: Text,
metadata: Optional[Dict[Text, Any]],
) -> None:
collector = QueueOutputChannel(queue)
message = UserMessage(
text, collector, sender_id, input_channel=input_channel, metadata=metadata
)
await on_new_message(message)
await queue.put("DONE")
async def _extract_sender(self, req: Request) -> Optional[Text]:
return req.json.get("sender", None)
# noinspection PyMethodMayBeStatic
def _extract_message(self, req: Request) -> Optional[Text]:
return req.json.get("message", None)
def _extract_input_channel(self, req: Request) -> Text:
return req.json.get("input_channel") or self.name()
def stream_response(
self,
on_new_message: Callable[[UserMessage], Awaitable[None]],
text: Text,
sender_id: Text,
input_channel: Text,
metadata: Optional[Dict[Text, Any]],
) -> Callable[[Any], Awaitable[None]]:
async def stream(resp: Any) -> None:
q = Queue()
task = asyncio.ensure_future(
self.on_message_wrapper(
on_new_message, text, q, sender_id, input_channel, metadata
)
)
while True:
result = await q.get()
if result == "DONE":
break
else:
await resp.write(json.dumps(result) + "\n")
await task
return stream
def blueprint(
self, on_new_message: Callable[[UserMessage], Awaitable[None]]
) -> Blueprint:
custom_webhook = Blueprint(
"custom_webhook_{}".format(type(self).__name__),
inspect.getmodule(self).__name__,
)
# noinspection PyUnusedLocal
@custom_webhook.route("/", methods=["GET"])
async def health(request: Request) -> HTTPResponse:
return response.json({"status": "ok"})
@custom_webhook.route("/webhook", methods=["POST"])
async def receive(request: Request) -> HTTPResponse:
sender_id = await self._extract_sender(request)
text = self._extract_message(request)
should_use_stream = rasa.utils.endpoints.bool_arg(
request, "stream", default=False
)
input_channel = self._extract_input_channel(request)
metadata = self.get_metadata(request)
if should_use_stream:
return response.stream(
self.stream_response(
on_new_message, text, sender_id, input_channel, metadata
),
content_type="text/event-stream",
)
else:
collector = MyioOutput()
# noinspection PyBroadException
try:
await on_new_message(
UserMessage(
text,
collector,
sender_id,
input_channel=input_channel,
metadata=metadata,
)
)
except CancelledError:
logger.error(
f"Message handling timed out for " f"user message '{text}'."
)
except Exception:
logger.exception(
f"An exception occured while handling "
f"user message '{text}'."
)
return response.json(collector.messages)
return custom_webhook
class MyioOutput(CollectingOutputChannel):
@classmethod
def name(cls) -> Text:
return "myio"
| [
"noreply@github.com"
] | athenasaurav.noreply@github.com |
ef1e94a8445224c7eee92e7c9481beaba7653abf | 8c33821ff99e2a08853c6c8ecc31d8c33c13fa3d | /users.py | 7db4c70aef46f6a7dfda04ed8945cc6e8d025818 | [] | no_license | turtlekingster/lunchTable | 5bd49c8393e31b3a222b6ec5e682ca9ea1035d9f | 7732b034987492464e98e69a0d65424da4ff3885 | refs/heads/master | 2020-03-16T19:23:21.078920 | 2018-05-23T14:59:58 | 2018-05-23T14:59:58 | 132,913,667 | 0 | 0 | null | 2018-05-17T14:44:25 | 2018-05-10T14:42:00 | HTML | UTF-8 | Python | false | false | 5,227 | py | #!/usr/bin/python
from dbhelper import dbhelper
import bcrypt
class User():
def __init__(self, _id=-1, name="", description="", _hash="", email="", atLunch = False, group = -1):
self._id = _id
self.name = name
self.desc = description
self._hash = _hash
self.email = email
self.atLunch = atLunch
self.group = group
def hashpw(self):
self._hash = bcrypt.hashpw(self._hash.encode('utf8'), bcrypt.gensalt())
def auth(self, password):
htemp = bcrypt.hashpw(password.encode('utf8'), self._hash)
print htemp + "\n" + self._hash + "\n"
return bcrypt.checkpw(password.encode('utf8'), self._hash)
def editDescription(self, description):
self.description = description
def checkOut(self):
self.atLunch = True;
def checkIn(self):
self.atLunch = False;
class Group():
def __init__(self, _id=-1, name="", priv=9):
self._id = _id
self.name = name
self.priv = priv
class groupHelper(dbhelper):
def __init__(self):
self.tableName = "usergroups"
self.dbName = "lunch"
dbhelper.__init__(self,"localhost", self.dbName, "justin", "0828")
self.lastID = 0
self.getGroups()
def getGroups(self):
entries = dbhelper.getTableContents(self, self.tableName, "*")
self.groups = []
for entry in entries:
self.groups.append(Group(entry[0], entry[1], entry[2]))
self.lastID = self.groups[len(self.groups) - 1]._id
return self.groups
def addGroup(self, name="", priv=9):
self.lastID = self.lastID + 1
group = Group(self.lastID, name, priv)
valueNames = ["id","name","priv"]
values = ["'" + group._id + "'", "'" + group.name + "'", "'" + group.priv + "'"]
dbhelper.insertIntoTable(self, self.tableNames, valueNames, values)
self.getGroups(self)
def getGroup(self, _id = -1, name = ""):
if type(_id) is not int:
raise TypeError('_id must be an int, _id is a ' + str(type(_id)))
if type(name) is not str:
raise TypeError('name must be a str, name is a ' + str(type(name)))
if(_id != -1):
if _id > len(self.groups) or _id < -1:
raise ValueError("_id is out range with a value of:" + str(_id) + " range is 0 to " + str(len(self.groups)))
return self.groups[_id - 1]
elif(name != ""):
for group in self.groups:
if group.name == name:
return group
return 0
def __del__(self):
dbhelper.__del__(self)
class userHelper(dbhelper):
def __init__(self):
self.tableName = "users"
self.dbName = "lunch"
dbhelper.__init__(self,"localhost", self.dbName, "justin", "0828")
self.groups = groupHelper()
def getAllUsers(self):
return dbhelper.getTableContents(self, self.tableName, "*")
def getUser(self, name="", email="", _id=-1):
entry = []
if(name != ""):
entry = dbhelper.getByValue(self, self.tableName, "name", str(name))
elif(email != ""):
entry = dbhelper.getByValue(self, self.tableName, "email", str(email))
elif(_id > 0):
user_id = str(_id)
entry = dbhelper.getByValue(self, self.tableName, "id", str(user_id))
else:
raise ValueError('No UserName, Email, or ID Specified')
if entry:
_id = entry[0][0]
name = entry[0][1]
description = entry[0][2]
_hash = entry[0][3]
email = entry[0][4]
atLunch = entry[0][5]
group_id= entry[0][6]
return User(_id, name, description, _hash, email, atLunch, group_id)
return 0
def addUser(self, user):
if not isinstance(user, User):
raise TypeError('Need user type')
elif user.name == "":
raise ValueError('Blank Username')
valueNames = ["name", "description", "password", "email", "atLunch", "usergroup"]
values = ["'" + user.name + "'","'" + user.desc + "'","'" + user._hash + "'",
"'" + user.email + "'","'" + str(int(user.atLunch)) +"'", "'" + str(user.group) + "'"]
dbhelper.insertIntoTable(self, self.tableName, valueNames, values)
def updateUser(self, user):
if not isinstance(user, User):
raise TypeError('Need user type')
elif user.name == "":
raise ValueError('Blank Username')
try:
valueNames = ["id", "name", "description", "password", "email", "atLunch", "usergroup"]
values = ["'" + str(user._id) + "'", "'" + user.name + "'","'" + user.desc + "'",
"'" + user._hash + "'","'" + user.email + "'","'" + str(int(user.atLunch)) +"'", "'" + str(user.group) + "'"]
dbhelper.updateEntry(self, self.tableName, valueNames, values)
except Exception, e:
print "-------In updateUser:"
print e
def getColumnNames(self):
return dbhelper.getColumnNames(self, self.tableName)
def __del__(self):
dbhelper.__del__(self)
| [
"turtlekingster@gmail.com"
] | turtlekingster@gmail.com |
c1502bcef9902a24cdc78287de541c30638a0269 | ded1639953820eaee25dd3cfee87cff5a9cd9a86 | /mim_turniej/urls.py | 6fd275e74dcc225f5d8c3fbf5d9db559ce7b77f4 | [] | no_license | Arthan/cardmaker | 77e98faa26406c3b816107428b47a8aa5ac3bb73 | ce7e5358da59fb6de768d69d9aed3fbc5bceb079 | refs/heads/master | 2021-01-19T19:45:39.304115 | 2017-09-05T20:57:07 | 2017-09-05T20:57:07 | 101,207,940 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 817 | py | """mim_turniej URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('turniej.urls')),
]
| [
"krzysztof.lemka@gmail.com"
] | krzysztof.lemka@gmail.com |
15d2b575651bdea86b38c0e958fcaf83eaae4442 | 760fbf0e4675212a89dbba28ef771bf7ff7a0d91 | /Leetcode2019/145. 二叉树的后序遍历.py | 06d8fc7c4c1096758d26866d0f867745ac54876d | [] | no_license | chixujohnny/Leetcode | 1a420e318005140a2be036ab7c3fcd054b4ae011 | 3faa41556f13f45a08b49d4dcd371ed590f9cb14 | refs/heads/master | 2021-06-19T14:44:28.464335 | 2021-01-11T08:16:26 | 2021-01-11T08:16:26 | 155,142,704 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 563 | py | # coding: utf-8
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
def helper(root):
if root == None:
return
helper(root.left)
helper(root.right)
res.append(root.val)
helper(root)
return res | [
"1390463349@qq.com"
] | 1390463349@qq.com |
fc6df4e04a1928392e332ee17c6b97ae8b2b54f4 | a7f46698931a4951ed160909601cd9a5506035de | /todolist_project/settings.py | edb7b77262de1e81bb0be6cd698a7618752de046 | [] | no_license | ahsherlock/todolist | b60ca9f5cdf5b0f3bc91fcf8a256ae6ead3b70ee | 128cfe56901f5be22de5533185350e14d344a6c2 | refs/heads/master | 2022-11-06T10:45:03.329388 | 2020-06-28T03:38:42 | 2020-06-28T03:38:42 | 273,394,143 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,218 | py | """
Django settings for todolist_project project.
Generated by 'django-admin startproject' using Django 3.0.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '79b(86+zkgj7baos+(&5mn9q+q0tci531_-)m549#_m+@bo68+'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'todolist.apps.TodolistConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'todolist_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'todolist_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
LOGIN_URL= '/login' | [
"ahsherlock0@gmail.com"
] | ahsherlock0@gmail.com |
bc4632fd8d972b9b3f2f1687f5d267bfb1774c23 | 7bda8b0104016db8f98357301a85b19b1998d470 | /Jesus/infoLines/infoLines/middlewares.py | f15ed8f7f85b3046f2a7797e8644e810ad569da9 | [] | no_license | AnaFernandezCruz/ObtencionDatos | a733a40dc71b6d7ddc3fbd1411a37a46e4382603 | c9f7977e1eddee513204145123106a5182cf3665 | refs/heads/master | 2020-12-02T04:58:05.741141 | 2020-01-15T20:57:30 | 2020-01-15T20:57:30 | 230,896,102 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 3,603 | py | # -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
class InfolinesSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the spider middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_spider_input(self, response, spider):
# Called for each response that goes through the spider
# middleware and into the spider.
# Should return None or raise an exception.
return None
def process_spider_output(self, response, result, spider):
# Called with the results returned from the Spider, after
# it has processed the response.
# Must return an iterable of Request, dict or Item objects.
for i in result:
yield i
def process_spider_exception(self, response, exception, spider):
# Called when a spider or process_spider_input() method
# (from other spider middleware) raises an exception.
# Should return either None or an iterable of Response, dict
# or Item objects.
pass
def process_start_requests(self, start_requests, spider):
# Called with the start requests of the spider, and works
# similarly to the process_spider_output() method, except
# that it doesn’t have a response associated.
# Must return only requests (not items).
for r in start_requests:
yield r
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
class InfolinesDownloaderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# scrapy acts as if the downloader middleware does not modify the
# passed objects.
@classmethod
def from_crawler(cls, crawler):
# This method is used by Scrapy to create your spiders.
s = cls()
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
return s
def process_request(self, request, spider):
# Called for each request that goes through the downloader
# middleware.
# Must either:
# - return None: continue processing this request
# - or return a Response object
# - or return a Request object
# - or raise IgnoreRequest: process_exception() methods of
# installed downloader middleware will be called
return None
def process_response(self, request, response, spider):
# Called with the response returned from the downloader.
# Must either;
# - return a Response object
# - return a Request object
# - or raise IgnoreRequest
return response
def process_exception(self, request, exception, spider):
# Called when a download handler or a process_request()
# (from other downloader middleware) raises an exception.
# Must either:
# - return None: continue processing this exception
# - return a Response object: stops process_exception() chain
# - return a Request object: stops process_exception() chain
pass
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
| [
"jesus.gallego.olivas@gmail.com"
] | jesus.gallego.olivas@gmail.com |
e63bf6f36802dff4766a8c5ef5a8ee83e795d812 | 7da3346fa0e6a8627c5c678589129df192b0bfa8 | /7/7-2.py | cf899f247073094966e13cf484c9e9dac2e1289e | [] | no_license | gunbux/aoc-2020 | 2768169bbb1b332231e9be97ab911d090d5f0ff8 | 756ce22d18316d645c7b6c5df3db3d97eccd9c12 | refs/heads/main | 2023-02-07T18:04:18.629666 | 2020-12-22T03:16:40 | 2020-12-22T03:16:40 | 318,797,404 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,535 | py | #!python
with open('7.txt') as input:
hasGold = []
noGold = []
bbl = {}
c = {}
def containsGold(bag):
##print(f'checking {bag} for gold')
if bbl[bag] == None or bag == None:
noGold.append(bag)
return False
else:
if bag in hasGold:
return True
elif bag in noGold:
return False
elif bag == 'shiny gold':
return True
for i in bbl[bag]:
if containsGold(i):
##print('gold found')
# if i not in hasGold and i != 'shiny gold':
# hasGold.append(i)
hasGold.append(bag)
return True
else:
noGold.append(i)
def countbags(bag):
bc = 0
l = bbl[bag]
##print(f'counting bags: {bag}')
##print(f'dp list is {c}')
if l == None:
if bag not in c:
c[bag] = 0
return 0
if bag in c:
return c[bag]
else:
for i in l:
##print(f'i is {i} and l is {l}')
bc += l[i]
y = l[i]
bc += y*countbags(i)
if bag not in c:
c[bag] = bc
return bc
for g in input:
h = g.rstrip()[:-1].split(' contain ')
a = h[0].replace(' bags','')
b = h[1].split(', ')
o = {}
for n in b:
if n == 'no other bags':
o = None
continue
n = n.replace(' bags','')
n = n.replace(' bag','')
o[n[2:]] = int(n[0])
bbl[a] = o
for v in bbl:
##print(f'searching for bag {v}')
containsGold(v)
print(countbags('shiny gold'))
# Potato Code
# class bag(object):
# def __init__(self,name,baglist):
# self.baglist = baglist
# self.name = name
#
# def getBaglist(self):
# return self.baglist
#
# def getName(self):
# return self.name
#
# def __str__(self):
# return f'{self.name} bag contains {str(self.baglist)}'
#
# def containsGold(bag):
# if bag in hasGold:
# return True
# else:
# if bag == None:
# return False
# for i in bag.getBaglist():
# if containsGold(i):
# hasGold.append(i)
# return True
| [
"lamchunyu00@gmail.com"
] | lamchunyu00@gmail.com |
7dcbcaa847c475cb4d1f139f4cd8eb41abab09cb | 2f989d067213e7a1e19904d482a8f9c15590804c | /lib/python3.4/site-packages/django/contrib/contenttypes/apps.py | e5708adc99840e3b4a4bc3212d26d134a8462203 | [
"MIT"
] | permissive | levabd/smart4-portal | beb1cf8847134fdf169ab01c38eed7e874c66473 | 2c18ba593ce7e9a1e17c3559e6343a14a13ab88c | refs/heads/master | 2023-02-18T05:49:40.612697 | 2022-08-02T09:35:34 | 2022-08-02T09:35:34 | 116,001,098 | 0 | 1 | MIT | 2023-02-15T21:34:01 | 2018-01-02T10:00:07 | Roff | UTF-8 | Python | false | false | 693 | py | from django.apps import AppConfig
from django.contrib.contenttypes.checks import check_generic_foreign_keys
from django.core import checks
from django.db.models.signals import post_migrate, pre_migrate
from django.utils.translation import ugettext_lazy as _
from .management import (
inject_rename_contenttypes_operations, update_contenttypes,
)
class ContentTypesConfig(AppConfig):
name = 'django.contrib.contenttypes'
verbose_name = _("Content Types")
def ready(self):
pre_migrate.connect(inject_rename_contenttypes_operations, sender=self)
post_migrate.connect(update_contenttypes)
checks.register(check_generic_foreign_keys, checks.Tags.models)
| [
"levabd@gmail.com"
] | levabd@gmail.com |
59e22f98d350ea5b45fcfb9fc47ea110043bdec0 | 9556f7e1d81a305d71a66b9768eba199e396d733 | /Thread/venv/bin/pip | 698fcef12df25482e9901a7aecb433703142f6b8 | [] | no_license | gitgaoqian/Python | 301a2823b50ec754a2c1a3f47c39ae8b0b8e6890 | 164f5271044b235d256a9bbe0a34caacf1e81fc8 | refs/heads/master | 2023-01-08T21:23:59.640828 | 2020-11-01T13:06:21 | 2020-11-01T13:06:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 394 | #!/home/ros/pycharm/MyFiles/thread/venv/bin/python
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==9.0.1','console_scripts','pip'
__requires__ = 'pip==9.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==9.0.1', 'console_scripts', 'pip')()
)
| [
"734756851@qq.com"
] | 734756851@qq.com | |
ec2a4cada39a330c68d47fc77a5d2628793ec118 | fee83f11fd343d0443f3316d7a26f68f5129df05 | /grouper/fe/handlers/permissions_grant_tag.py | dc10d9a9434fb1284d1c99ebaa0092e3d98c68dd | [
"Apache-2.0"
] | permissive | lfaraone/grouper | c797b7d4e52eef198e895450e3a69f5c34a22251 | 7df5eda8003a0b4a9ba7f0dcb044ae1e4710b171 | refs/heads/master | 2021-01-17T01:14:18.469581 | 2017-04-14T18:57:16 | 2017-04-14T19:02:30 | 29,040,748 | 0 | 0 | NOASSERTION | 2018-12-14T00:41:20 | 2015-01-09T23:52:33 | Python | UTF-8 | Python | false | false | 2,726 | py | from grouper.constants import TAG_EDIT
from grouper.fe.forms import PermissionGrantTagForm
from grouper.fe.util import GrouperHandler
from grouper.models.audit_log import AuditLog
from grouper.models.permission import Permission
from grouper.models.public_key_tag import PublicKeyTag
from grouper.permissions import grant_permission_to_tag
from grouper.user_permissions import user_has_permission
class PermissionsGrantTag(GrouperHandler):
def get(self, name=None):
tag = PublicKeyTag.get(self.session, None, name)
if not tag:
return self.notfound()
if not user_has_permission(self.session, self.current_user, TAG_EDIT, tag.name):
return self.forbidden()
form = PermissionGrantTagForm()
form.permission.choices = [["", "(select one)"]]
for perm in self.session.query(Permission).all():
form.permission.choices.append([perm.name, "{} (*)".format(perm.name)])
return self.render(
"permission-grant-tag.html", form=form, tag=tag,
)
def post(self, name=None):
tag = PublicKeyTag.get(self.session, None, name)
if not tag:
return self.notfound()
if not user_has_permission(self.session, self.current_user, TAG_EDIT, tag.name):
return self.forbidden()
form = PermissionGrantTagForm(self.request.arguments)
form.permission.choices = [["", "(select one)"]]
for perm in self.session.query(Permission).all():
form.permission.choices.append([perm.name, "{} (*)".format(perm.name)])
if not form.validate():
return self.render(
"permission-grant-tag.html", form=form, tag=tag,
alerts=self.get_form_alerts(form.errors)
)
permission = Permission.get(self.session, form.data["permission"])
if not permission:
return self.notfound() # Shouldn't happen.
success = grant_permission_to_tag(self.session, tag.id, permission.id,
argument=form.data["argument"])
if not success:
form.argument.errors.append(
"Permission and Argument already mapped to this tag."
)
return self.render(
"permission-grant-tag.html", form=form, tag=tag,
alerts=self.get_form_alerts(form.errors),
)
AuditLog.log(self.session, self.current_user.id, 'grant_permission_tag',
'Granted permission with argument: {}'.format(form.data["argument"]),
on_permission_id=permission.id, on_tag_id=tag.id)
return self.redirect("/tags/{}?refresh=yes".format(tag.name))
| [
"tyleromeara@dropbox.com"
] | tyleromeara@dropbox.com |
513d3e5a271b23319d3bd3cf6215c2b9cfa2b2cd | 1fe44c9f227707b6cabac7e63c7bc4fd1d4b543c | /beamdesign/codecheck/codecheck.py | abb846294b324005b538402bc74d9ae59ab8dda5 | [] | no_license | skane88/BeamDesign | ff8477c768d2639c9dc81b0c199b92c96989a4f5 | 23bdc61ead945c763286255175afcfa7c6a30273 | refs/heads/master | 2021-10-28T18:06:13.965253 | 2019-04-24T10:40:16 | 2019-04-24T10:40:16 | 77,765,089 | 2 | 2 | null | 2019-02-12T22:53:07 | 2017-01-01T03:54:46 | Python | UTF-8 | Python | false | false | 12,252 | py | """
This will contain an Abstract Base Class that all codecheck classes should inherit from.
"""
from abc import ABC, abstractmethod
from typing import List, Union, Tuple
import numpy as np
from beamdesign.beam import Beam
from beamdesign.sections.section import Section
from beamdesign.utility.exceptions import CodeCheckError, SectionOnlyError
from beamdesign.const import LoadComponents
DEFAULT_ASSESSMENT_POINTS = 20
class CodeCheck(ABC):
"""
This is an abstract base class for carrying out code checks of Beam objects.
The intent is to require only a minimal set of methods that are common across all
likely design checks.
For descriptions of methods that need to be implemented refer to method
documentation below.
"""
def __init__(
self, *, beam: Beam = None, section=None, assessment_points: int = None
):
"""
Constructor for a ``CodeCheck`` object.
:param beam: A beam object to be checked. Can be ``None`` if a section is
provided instead.
:param section: A section object to be checked. Can be ``None`` if a beam is
provided instead.
:param assessment_points: The minimum number of points to be checked when
determining utilisations etc. Note that more points may actually be checked
due to load and element discontinuities etc.
"""
if beam is None and section is None:
raise CodeCheckError(
f"Expected either a beam or a section, both were None."
+ f" Cannot create a {self.__class__.__name__} instance"
)
self._beam = beam
self._section = section
if assessment_points is None:
self._assessment_points = DEFAULT_ASSESSMENT_POINTS
else:
self._assessment_points = assessment_points
@property
def beam(self) -> Beam:
"""
The ``Beam`` object that the ``CodeCheck`` object is checking.
:return: The ``Beam`` object that the ``CodeCheck`` object is checking. May be
``None`` if the ``CodeCheck`` object is based on a ``Section``.
"""
return self._beam
@property
def section(self):
"""
:return: The ``Section`` object that the ``CodeCheck`` object contains. May be
``None`` if the ``CodeCheck`` object is based on a ``Beam``.
"""
return self._section
@property
@abstractmethod
def sections(self) -> List[Section]:
"""
Returns all the sections from the elements that make up the ``codecheck``
object.
:return: A list of all the sections. If there is no beam (and only a section) a
list is still returned for consistency.
"""
if self.beam is None:
return [self.section]
return self.beam.sections
@property
def assessment_points(self) -> int:
"""
The minimum number of points at which utilisation etc. will be assessed.
The actual no. of points may vary as the ``CodeCheck`` obects are expected to
be able to handle discontinuities at loads and starts / ends of elements etc.
"""
return self._assessment_points
@assessment_points.setter
def assessment_points(self, assessment_points: int):
"""
The minimum number of points at which utilisation etc. will be assessed.
The actual no. of points may vary as the ``CodeCheck`` obects are expected to
be able to handle discontinuities at loads and starts / ends of elements etc.
:param assessment_points: The minimum number of assessment points.
"""
self._assessment_points = assessment_points
@abstractmethod
def tension_capacity(self, *, position: Union[List[float], float] = None):
"""
Get the limiting tension capacity of the member being checked.
:param position: The position to calculate the capacity at. Can be a float, can
be a list of floats or can be None.
Note that if None is provided, a single tension capacity is returned which
is the minimum tension capacity of the entire object.
:return: the limiting tension capacity of the member being checked. If the code
includes capacity reduction factors these will be included.
"""
raise NotImplementedError()
@abstractmethod
def tension_utilisation(
self, *, load_case: int = None, position: Union[List[float], float] = None
) -> float:
"""
Get the utilisation ratio of the section in tension.
The utilisation ratio is a % value indicating that the load is x% of the load
that will cause load to match capacity.
NOTE: This should NOT be a simple division equation of load / capacity. Whilst
true when capacity is independent of loads, many code capacity equations depend
on the applied load.
:param position: The position to calculate the utilisation at. Can be a float,
can be a list of floats or can be None.
Note that if None is provided, a single tension utilisation is returned
which is the highest tension utilisation of the entire object.
:param load_case: The load case to get the utilisation ratio in - if ``None``,
return the highest utilisation ratio of any load case.
:return: The utilisation of the section in tension.
"""
raise NotImplementedError()
@abstractmethod
def get_section(
self,
*,
position: Union[List[float], float] = None,
min_positions: int = None,
load_case: int = None,
) -> Tuple[List[float], List[Section]]:
"""
Gets the section properties at a given position or list of positions.
The positions can either be requested directly, or as a minimum number of
positions along the beam. If specified as minimum positions, a load case can be
specified as well (to include load discontinuities etc.
If the ``CodeCheck`` object is a section based object, it will raise a
SectionOnlyError.
:param min_positions: The minimum no. of positions to return.
:param position: The position to return the section from. If the ``codecheck``
object has only a section property (and not a ``Beam`` property) it returns
``self.section``. If ``None`` it returns all sections. If a position is
given it returns the sections at the given positions.
:param load_case: he load case to consider if using min_positions. Can be
``None``, in which case only the start & ends of elements are returned.
:return: Returns a tuple of positions and sections:
(
[pos_1, ..., pos_n]
[section_1, ..., section_n]
)
"""
if self.beam is None:
raise SectionOnlyError(
f"get_section does not apply to Section based CodeCheck objects."
)
return self.beam.get_section(
position=position, min_positions=min_positions, load_case=load_case
)
@abstractmethod
def get_loads(
self,
*,
load_case: int,
position: Union[List[float], float] = None,
min_positions: int = None,
component: Union[int, str, LoadComponents] = None,
) -> np.ndarray:
"""
Gets the load on a ``CodeCheck`` object in a given load case and at a given
position.
If there are multiple loads at a position it returns all of them. Returns in the
form of a numpy array of the format:
[[pos, load_1]
[pos, load_2]
...
[pos, load_n]
]
If ``component`` is not provided, then an array of all loads at the given
position is returned:
[[pos, vx_1, vy_1, N_1, mx_1, my_1, T_1]
[pos, vx_2, vy_2, N_2, mx_2, my_2, T_2]
...
[pos, vx_n, vy_n, N_n, mx_n, my_n, T_n]
]
The values of position are 'real' positions along the underlying beam.
:param load_case: The load case to get the loads in.
:param position: The position at which to return the load. Position values
should be entered as floats between 0.0 and ``Beam.length``
Positions can be a single position or a list of positions. If a list is
provided, any duplicate values will be ignored, and the order will be
ignored - return values will be at positions sorted ascending from 0.0 to
``Beam.length``. If the specified position is at an element or load
discontinuity multiple values may be returned.
If ``position`` is provided, ``min_positions`` must be ``None`` to
avoid ambiguity.
:param min_positions: The minimum number of positions to return. Positions will
be returned such that loads are returned at equally spaced positions between
0.0 and ``Beam.length`` (inclusive). All stored load positions and element
start / end positions will also be included to ensure that discontinuities
are included.
If ``min_positions`` is provided,
``position`` must be ``None`` to avoid ambiguity.
:param component: The component of load to return.
:return: A numpy array containing the loads at the specified position.
"""
if self.beam is None:
raise SectionOnlyError(
"The CodeCheck object is a section only object and has no stored loads."
)
return self.beam.get_loads(
load_case=load_case,
position=position,
min_positions=min_positions,
component=component,
)
@abstractmethod
def get_tension(
self, *, load_case, position=None, min_positions=None
) -> np.ndarray:
"""
Gets the tension load on a ``CodeCheck`` object in a given load case and at a
given position.
If there are multiple loads at a position it returns all of them. Returns in the
form of a numpy array of the format:
[[pos, tension_1]
[pos, tension_2]
...
[pos, tension_n]
]
The values of position are 'real' positions along the underlying beam.
Always returns positive values or 0.0. If the axial load at a given position is
-ve (i.e. in compression) it returns 0.0.
:param load_case: The load case to get the loads in.
:param position: The position at which to return the load. Position values
should be entered as floats between 0.0 and ``Beam.length``
Positions can be a single position or a list of positions. If a list is
provided, any duplicate values will be ignored, and the order will be
ignored - return values will be at positions sorted ascending from 0.0 to
``Beam.length``. If the specified position is at an element or load
discontinuity multiple values may be returned.
If ``position`` is provided, ``min_positions`` must be ``None`` to
avoid ambiguity.
:param min_positions: The minimum number of positions to return. Positions will
be returned such that loads are returned at equally spaced positions between
0.0 and ``Beam.length`` (inclusive). All stored load positions and element
start / end positions will also be included to ensure that discontinuities
are included.
If ``min_positions`` is provided,
``position`` must be ``None`` to avoid ambiguity.
:return: A numpy array containing the loads at the specified position.
"""
tension = self.beam.get_loads(
load_case=load_case,
position=position,
min_positions=min_positions,
component="N",
)
# replace all the tension elements that are in compression with 0.
tension[:, 1][tension[:, 1] < 0] = 0
return tension
| [
"sean.kane@outlook.com.au"
] | sean.kane@outlook.com.au |
61d841a540a06f74ec8d73ed015cc090e6283cd5 | 55c250525bd7198ac905b1f2f86d16a44f73e03a | /Python/Apps/Riddle Game App/temp.py | f841eb3bfa477531b1280da74ffd298624106bfc | [] | no_license | NateWeiler/Resources | 213d18ba86f7cc9d845741b8571b9e2c2c6be916 | bd4a8a82a3e83a381c97d19e5df42cbababfc66c | refs/heads/master | 2023-09-03T17:50:31.937137 | 2023-08-28T23:50:57 | 2023-08-28T23:50:57 | 267,368,545 | 2 | 1 | null | 2022-09-08T15:20:18 | 2020-05-27T16:18:17 | null | UTF-8 | Python | false | false | 127 | py | version https://git-lfs.github.com/spec/v1
oid sha256:dfddd312c5f04ffd65ec672ab6d6d80e68a8e6e69b98e472123679a87dc1e254
size 52
| [
"nateweiler84@gmail.com"
] | nateweiler84@gmail.com |
0ca61efac890a3e5b9ec88603400a76a2101c4fa | ee9ee98e1320e2836651896ac9e2fb87deaa15f4 | /GameOfPython/GameOfPython/GameOfPython.py | ca709f26763ccc771e64986c54638a2aad2bd633 | [] | no_license | GusatfGL/titration-computational | 7b42d740917af2ea97cdc898a18da2e430c2411b | 6cb49dbc15e8c6cd46257a553e24b2b678214d83 | refs/heads/master | 2023-03-25T21:11:44.480359 | 2021-03-12T13:55:25 | 2021-03-12T13:55:25 | 346,800,580 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 552 | py |
#Variables needed
width = 10
height = 10
data = [[int for i in range(width)] for j in range(10)]
# Functions needed
def PrintBoard():
for y in range(height):
for x in range(width):
if data[x][y] ==1:
print("1", end='')
if data[x][y] == 0:
print("0", end='')
print("")
def InitBoard():
for y in range(height):
for x in range(width):
data[x][y] = 0;
def GetNeighbours(x, y):
for i in range(1, 4):
# Main
InitBoard()
PrintBoard()
| [
"gustaf.linder@hotmail.com"
] | gustaf.linder@hotmail.com |
6219761f970e8e5092dc5685a25e4b03b1003c2c | 65cd7291b8a16ebbfb38c507cf9d420487a85907 | /3.py | ecbab9ec428592b8cb2f30091ee9c02e2c831aaa | [] | no_license | darthkenobi5319/Python-Lab-5 | d9050797e702ca0fd5a955c4098285b02c71c5e4 | 03d7ac51e7ca0b5df13c7ee50c1eda9f1bb36308 | refs/heads/master | 2020-03-28T12:26:53.059303 | 2018-09-11T10:17:08 | 2018-09-11T10:17:08 | 148,299,237 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 516 | py | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 19 10:41:31 2017
@author: ZHENGHAN ZHANG
"""
#define the list and numerators
x = [[1, 2], [3], [4, 5, 6, 7], [8, 9]]
m=0
n=0
#Count the number of even values in the list
for i in range(len(x)):
for j in range(len(x[i])):
m+=int(x[i][j]%2==0)
print(m)
#Count the number of odd values contained in sublists with more than two elements
for i in range(len(x)):
for j in range(len(x[i])):
if len(x[i])>2:
n+=int(x[i][j]%2!=0)
print(n) | [
"43033983+darthkenobi5319@users.noreply.github.com"
] | 43033983+darthkenobi5319@users.noreply.github.com |
cb753f23834a547fa79fbba2497dd33fcae8b5ef | 4d6c7854661a73e1a0225bfb15bcfd4361dc7bd8 | /momlink/demography.py | 4f5588827b3a1e2482a7a9fc60153b0eb091b24f | [] | no_license | cspencer3/two_locus_selection_moments | 22eaac16427e40773a0ff842291cfb63633d2439 | f90ef651628be8c14665660af3e71b3823b0ccb6 | refs/heads/main | 2023-03-24T06:29:01.392104 | 2021-03-24T19:42:14 | 2021-03-24T19:42:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,526 | py | import numpy as np
import csv
class Demography(object):
def __init__(self, fn=None, popsize=None):
if fn is None and popsize is None:
raise InvalidDemography('Please specify demography file or fixed population size.')
elif popsize is not None and fn is not None:
raise InvalidDemography('Please specify either a demography file or a fixed population size but not both.')
elif popsize is None:
self.interval_type = []
self.event_times = []
self.init_pop_sizes = []
self.exp_rate = []
self.parse_dem(fn)
self.n0 = self.init_pop_sizes[0]
self.last_time = self.event_times[-1]
self.seg_num = len(self.interval_type)
elif fn is None:
self.interval_type = ['setSize']
self.event_times = [0]
self.init_pop_sizes = [popsize]
self.n0 = self.init_pop_sizes[0]
self.last_time = self.event_times[-1]
self.seg_num = len(self.interval_type)
def parse_dem(self, fn):
# Input order: interval type, start time, popsize/scale/rate
with open(fn) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for i, line in enumerate(csv_reader):
# Set interval type
self.interval_type.append(line[0].strip())
time = float(line[1].strip())
# Make sure initial interval specifies the initial population with a 'setSize' statment
if i == 0 and self.interval_type[0] != 'setSize':
raise IndentationError('First line of demography must specify the initial population size using a "setSize" epoch type.')
elif i > 1 and time < self.event_times[-1]:
raise InvalidDemography('Event times must be in increasing order.')
# Set event time
try:
self.event_times.append(time)
except ValueError:
raise InvalidDemography('Event times must be numeric.')
# Set population size
if self.interval_type[-1] == 'setSize':
try:
self.init_pop_sizes.append(int(line[2].strip()))
prev_size = self.init_pop_sizes[-1]
self.exp_rate.append(0.)
except ValueError:
raise InvalidDemography('Population sizes must be specified in integers.')
elif self.interval_type[-1] == 'reSize':
try:
frac = float(line[2].strip())
self.exp_rate.append(0.)
except ValueError:
raise InvalidDemography('reSize parameters must be numeric.')
if frac > 1 or frac < 0:
raise InvalidDemography('reSize parameters must be between 0.0 and 1.0.')
prev_size = prev_size * frac
self.init_pop_sizes.append(prev_size)
elif self.interval_type[-1] == 'expGrow':
try:
frac = float(line[2].strip())
self.init_pop_sizes.append(prev_size)
self.exp_rate.append(frac)
except ValueError:
raise InvalidDemography('Growth rate must be numeric.')
int_len = self.event_times[-1] - self.event_times[-2]
prev_size = prev_size * np.exp(frac * int_len)
else:
raise InvalidDemography('Must specify "setSize", "reSize", or "expGrow" for interval type.')
def initialize(self):
self.time = 0
self.current_seg = self.interval_type[0]
self.current_seg_num = 0
self.current_pop_size = self.init_pop_sizes[0]
def get_popsize_at(self, gen):
epoch = np.searchsorted(self.event_times, gen, side='right')-1
current_seg = self.interval_type[epoch]
if current_seg in ['setSize', 'reSize']:
out = self.init_pop_sizes[epoch]
elif current_seg == 'expGrow':
out = self.init_pop_sizes[epoch]*np.exp(self.exp_rate[epoch]*(gen - self.event_times[epoch]))
return out
class InvalidDemography(Exception):
"""Raised when invalid demography is given."""
pass | [
"EricF2218@gmail.com"
] | EricF2218@gmail.com |
4423ec6bb8916668ed1224532d6f59eb0264210b | 65625235b667159ee0c8664e1a3e202ed271ea99 | /python/MyScripts/tk_message.py | 12019f3f079e6387c04529afba73b6af19673fb6 | [] | no_license | mustafashakeel/learning | 76c210d523568ffe88943d1268eedbdc91edcc4a | 6c9df524cdc43cc5e3228bff7186145007827ae7 | refs/heads/master | 2020-09-21T23:16:02.911191 | 2018-07-02T05:45:22 | 2018-07-02T05:45:22 | 67,166,087 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 407 | py | from tkinter import *
import tkinter.messagebox as box
window = Tk()
window.title( 'Message Box Example' )
def dialog() :
var = box.askyesno( 'Message Box' , 'Proceed?' )
if var == 1 :
box.showinfo( 'Yes Box', 'Proceeding...' )
else :
box.showwarning( 'No Box', 'Cancelling...' )
btn = Button( window , text = 'Click' , command=dialog )
btn.pack( padx = 120 , pady = 50 )
window.mainloop() | [
"mustafa queshi"
] | mustafa queshi |
01b2be76c7a39b05d6db36b19dba8018456848d3 | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_125/ch22_2020_03_02_20_28_19_768242.py | 6c3da9295a0c587ec5b4d1b65f83ce4882ba77e4 | [] | no_license | gabriellaec/desoft-analise-exercicios | b77c6999424c5ce7e44086a12589a0ad43d6adca | 01940ab0897aa6005764fc220b900e4d6161d36b | refs/heads/main | 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 143 | py | dias = int(input('quantos cigarros voce fuma por dia ? '))
anos = int(input('há quantos anos voce fuma?' ))
print ((anos*365*24*60)*dias*144) | [
"you@example.com"
] | you@example.com |
eb68245bf2ea825502d241e93d47540d2b749b3f | 0160f6cdfc7fcbf4da893d44f256bac59fdcbe35 | /src/FullyConnectedModel.py | 004f9376b4571ec8f9757d67c318c4770d07c4b4 | [] | no_license | ruinanwang/cub-classification | 0bcfe6cf7775975cf02aac1d057c0e8266549aaa | f43ed2af45499ab23da64070955dcf4b4977b57a | refs/heads/master | 2023-06-02T03:51:15.656157 | 2021-06-25T21:43:45 | 2021-06-25T21:43:45 | 365,622,882 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,000 | py | import torch
import torch.nn as nn
class FullyConnectedModel(nn.Module):
def __init__(self, input_size, hidden_size, num_classes, num_layers=2):
super(FullyConnectedModel, self).__init__()
if num_layers == 1:
self.model = nn.Linear(input_size, num_classes)
elif num_layers == 2:
self.model = nn.Sequential(
nn.Linear(input_size, hidden_size),
nn.ReLU(),
nn.Linear(hidden_size, num_classes)
)
elif num_layers == 3:
if type(hidden_size) == int:
hidden_size = [hidden_size, hidden_size]
self.model = nn.Sequential(
nn.Linear(input_size, hidden_size[0]),
nn.ReLU(),
nn.Linear(hidden_size[0], hidden_size[1]),
nn.ReLU(),
nn.Linear(hidden_size[1], num_classes)
)
def forward(self, x):
out = self.model(x)
return out | [
"nancywng@sina.com"
] | nancywng@sina.com |
dba2f8e1a2489ee8595497efbce2fbe54822fbb2 | c8a04384030c3af88a8e16de4cedc4ef8aebfae5 | /stubs/pandas/tests/indexes/test_setops.pyi | 3493fb22582660788efeadee60d6a7bc60cb4307 | [
"MIT"
] | permissive | Accern/accern-xyme | f61fce4b426262b4f67c722e563bb4297cfc4235 | 6ed6c52671d02745efabe7e6b8bdf0ad21f8762c | refs/heads/master | 2023-08-17T04:29:00.904122 | 2023-05-23T09:18:09 | 2023-05-23T09:18:09 | 226,960,272 | 3 | 2 | MIT | 2023-07-19T02:13:18 | 2019-12-09T20:21:59 | Python | UTF-8 | Python | false | false | 660 | pyi | # Stubs for pandas.tests.indexes.test_setops (Python 3)
#
# NOTE: This dynamically typed stub was automatically generated by stubgen.
# pylint: disable=unused-argument,redefined-outer-name,no-self-use,invalid-name
# pylint: disable=relative-beyond-top-level
from typing import Any
COMPATIBLE_INCONSISTENT_PAIRS: Any
def index_pair(request: Any) -> Any:
...
def test_union_same_types(indices: Any) -> None:
...
def test_union_different_types(index_pair: Any) -> None:
...
def test_compatible_inconsistent_pairs(idx_fact1: Any, idx_fact2: Any) -> None:
...
def test_union_dtypes(left: Any, right: Any, expected: Any) -> None:
...
| [
"josua.krause@gmail.com"
] | josua.krause@gmail.com |
2a6d9451bfd61d97820d126c06640ac4cec21490 | ddbba4be8dc2ac8875becbbd951e8a2d2cf8a6e4 | /InceptionV4.py | 50105438dbc092065290559f87c4da376a037094 | [
"MIT"
] | permissive | YKSIAT/InceptionV4 | 4bcef13953175cff8a3e1289f0b937e0e9e59822 | 95559af854c63b673e8fc21b679eae9765b33411 | refs/heads/master | 2020-04-05T20:34:19.385722 | 2018-11-12T09:44:30 | 2018-11-12T09:44:30 | 157,186,481 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 17,208 | py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Contains the definition of the Inception V4 architecture.
As described in http://arxiv.org/abs/1602.07261.
Inception-v4, Inception-ResNet and the Impact of Residual Connections
on Learning
Christian Szegedy, Sergey Ioffe, Vincent Vanhoucke, Alex Alemi
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import inception_utils
slim = tf.contrib.slim
"""Builds Inception-A block for Inception v4 network."""
# By default use stride=1 and SAME padding
def block_inception_a(inputs, scope=None, reuse=None):
with slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d], stride=1, padding='SAME'):
with tf.variable_scope(scope, 'BlockInceptionA', [inputs], reuse=reuse):
with tf.variable_scope('Branch_0'):
branch_0 = slim.conv2d(inputs, 96, [1, 1], scope='Conv2d_0a_1x1')
with tf.variable_scope('Branch_1'):
branch_1 = slim.conv2d(inputs, 64, [1, 1], scope='Conv2d_0a_1x1')
branch_1 = slim.conv2d(branch_1, 96, [3, 3], scope='Conv2d_0b_3x3')
with tf.variable_scope('Branch_2'):
branch_2 = slim.conv2d(inputs, 64, [1, 1], scope='Conv2d_0a_1x1')
branch_2 = slim.conv2d(branch_2, 96, [3, 3], scope='Conv2d_0b_3x3')
branch_2 = slim.conv2d(branch_2, 96, [3, 3], scope='Conv2d_0c_3x3')
with tf.variable_scope('Branch_3'):
branch_3 = slim.avg_pool2d(inputs, [3, 3], scope='AvgPool_0a_3x3')
branch_3 = slim.conv2d(branch_3, 96, [1, 1], scope='Conv2d_0b_1x1')
return tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3])
def block_reduction_a(inputs, scope=None, reuse=None):
"""Builds Reduction-A block for Inception v4 network."""
# By default use stride=1 and SAME padding
with slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d], stride=1, padding='SAME'):
with tf.variable_scope(scope, 'BlockReductionA', [inputs], reuse=reuse):
with tf.variable_scope('Branch_0'):
branch_0 = slim.conv2d(inputs, 384, [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3')
with tf.variable_scope('Branch_1'):
branch_1 = slim.conv2d(inputs, 192, [1, 1], scope='Conv2d_0a_1x1')
branch_1 = slim.conv2d(branch_1, 224, [3, 3], scope='Conv2d_0b_3x3')
branch_1 = slim.conv2d(branch_1, 256, [3, 3], stride=2,
padding='VALID', scope='Conv2d_1a_3x3')
with tf.variable_scope('Branch_2'):
branch_2 = slim.max_pool2d(inputs, [3, 3], stride=2, padding='VALID',
scope='MaxPool_1a_3x3')
return tf.concat(axis=3, values=[branch_0, branch_1, branch_2])
"""Builds Inception-B block for Inception v4 network."""
# By default use stride=1 and SAME padding
def block_inception_b(inputs, scope=None, reuse=None):
with slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d], stride=1, padding='SAME'):
with tf.variable_scope(scope, 'BlockInceptionB', [inputs], reuse=reuse):
with tf.variable_scope('Branch_0'):
branch_0 = slim.conv2d(inputs, 384, [1, 1], scope='Conv2d_0a_1x1')
with tf.variable_scope('Branch_1'):
branch_1 = slim.conv2d(inputs, 192, [1, 1], scope='Conv2d_0a_1x1')
branch_1 = slim.conv2d(branch_1, 224, [1, 7], scope='Conv2d_0b_1x7')
branch_1 = slim.conv2d(branch_1, 256, [7, 1], scope='Conv2d_0c_7x1')
with tf.variable_scope('Branch_2'):
branch_2 = slim.conv2d(inputs, 192, [1, 1], scope='Conv2d_0a_1x1')
branch_2 = slim.conv2d(branch_2, 192, [7, 1], scope='Conv2d_0b_7x1')
branch_2 = slim.conv2d(branch_2, 224, [1, 7], scope='Conv2d_0c_1x7')
branch_2 = slim.conv2d(branch_2, 224, [7, 1], scope='Conv2d_0d_7x1')
branch_2 = slim.conv2d(branch_2, 256, [1, 7], scope='Conv2d_0e_1x7')
with tf.variable_scope('Branch_3'):
branch_3 = slim.avg_pool2d(inputs, [3, 3], scope='AvgPool_0a_3x3')
branch_3 = slim.conv2d(branch_3, 128, [1, 1], scope='Conv2d_0b_1x1')
return tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3])
"""Builds Reduction-B block for Inception v4 network."""
# By default use stride=1 and SAME padding
def block_reduction_b(inputs, scope=None, reuse=None):
with slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d], stride=1, padding='SAME'):
with tf.variable_scope(scope, 'BlockReductionB', [inputs], reuse=reuse):
with tf.variable_scope('Branch_0'):
branch_0 = slim.conv2d(inputs, 192, [1, 1], scope='Conv2d_0a_1x1')
branch_0 = slim.conv2d(branch_0, 192, [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3')
with tf.variable_scope('Branch_1'):
branch_1 = slim.conv2d(inputs, 256, [1, 1], scope='Conv2d_0a_1x1')
branch_1 = slim.conv2d(branch_1, 256, [1, 7], scope='Conv2d_0b_1x7')
branch_1 = slim.conv2d(branch_1, 320, [7, 1], scope='Conv2d_0c_7x1')
branch_1 = slim.conv2d(branch_1, 320, [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3')
with tf.variable_scope('Branch_2'):
branch_2 = slim.max_pool2d(inputs, [3, 3], stride=2, padding='VALID', scope='MaxPool_1a_3x3')
return tf.concat(axis=3, values=[branch_0, branch_1, branch_2])
def block_inception_c(inputs, scope=None, reuse=None):
"""Builds Inception-C block for Inception v4 network."""
# By default use stride=1 and SAME padding
with slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d], stride=1, padding='SAME'):
with tf.variable_scope(scope, 'BlockInceptionC', [inputs], reuse=reuse):
with tf.variable_scope('Branch_0'):
branch_0 = slim.conv2d(inputs, 256, [1, 1], scope='Conv2d_0a_1x1')
with tf.variable_scope('Branch_1'):
branch_1 = slim.conv2d(inputs, 384, [1, 1], scope='Conv2d_0a_1x1')
branch_1 = tf.concat(axis=3, values=[
slim.conv2d(branch_1, 256, [1, 3], scope='Conv2d_0b_1x3'),
slim.conv2d(branch_1, 256, [3, 1], scope='Conv2d_0c_3x1')])
with tf.variable_scope('Branch_2'):
branch_2 = slim.conv2d(inputs, 384, [1, 1], scope='Conv2d_0a_1x1')
branch_2 = slim.conv2d(branch_2, 448, [3, 1], scope='Conv2d_0b_3x1')
branch_2 = slim.conv2d(branch_2, 512, [1, 3], scope='Conv2d_0c_1x3')
branch_2 = tf.concat(axis=3, values=[
slim.conv2d(branch_2, 256, [1, 3], scope='Conv2d_0d_1x3'),
slim.conv2d(branch_2, 256, [3, 1], scope='Conv2d_0e_3x1')])
with tf.variable_scope('Branch_3'):
branch_3 = slim.avg_pool2d(inputs, [3, 3], scope='AvgPool_0a_3x3')
branch_3 = slim.conv2d(branch_3, 256, [1, 1], scope='Conv2d_0b_1x1')
return tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3])
def inception_v4_base(inputs, final_endpoint='Mixed_7d', scope=None):
"""Creates the Inception V4 network up to the given final endpoint.
Args:
inputs: a 4-D tensor of size [batch_size, height, width, 3].
final_endpoint: specifies the endpoint to construct the network up to.
It can be one of [ 'Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3',
'Mixed_3a', 'Mixed_4a', 'Mixed_5a', 'Mixed_5b', 'Mixed_5c', 'Mixed_5d',
'Mixed_5e', 'Mixed_6a', 'Mixed_6b', 'Mixed_6c', 'Mixed_6d', 'Mixed_6e',
'Mixed_6f', 'Mixed_6g', 'Mixed_6h', 'Mixed_7a', 'Mixed_7b', 'Mixed_7c',
'Mixed_7d']
scope: Optional variable_scope.
Returns:
logits: the logits outputs of the model.
end_points: the set of end_points from the inception model.
Raises:
ValueError: if final_endpoint is not set to one of the predefined values,
"""
end_points = {}
def add_and_check_final(name, net):
end_points[name] = net
return name == final_endpoint
with tf.variable_scope(scope, 'InceptionV4', [inputs]):
with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d],
stride=1, padding='SAME'):
# 299 x 299 x 3
net = slim.conv2d(inputs, 32, [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3')
if add_and_check_final('Conv2d_1a_3x3', net): return net, end_points
# 149 x 149 x 32
net = slim.conv2d(net, 32, [3, 3], padding='VALID', scope='Conv2d_2a_3x3')
if add_and_check_final('Conv2d_2a_3x3', net): return net, end_points
# 147 x 147 x 32
net = slim.conv2d(net, 64, [3, 3], scope='Conv2d_2b_3x3')
if add_and_check_final('Conv2d_2b_3x3', net): return net, end_points
# 147 x 147 x 64
with tf.variable_scope('Mixed_3a'):
with tf.variable_scope('Branch_0'):
branch_0 = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID',
scope='MaxPool_0a_3x3')
with tf.variable_scope('Branch_1'):
branch_1 = slim.conv2d(net, 96, [3, 3], stride=2, padding='VALID', scope='Conv2d_0a_3x3')
net = tf.concat(axis=3, values=[branch_0, branch_1])
if add_and_check_final('Mixed_3a', net): return net, end_points
# 73 x 73 x 160
with tf.variable_scope('Mixed_4a'):
with tf.variable_scope('Branch_0'):
branch_0 = slim.conv2d(net, 64, [1, 1], scope='Conv2d_0a_1x1')
branch_0 = slim.conv2d(branch_0, 96, [3, 3], padding='VALID', scope='Conv2d_1a_3x3')
with tf.variable_scope('Branch_1'):
branch_1 = slim.conv2d(net, 64, [1, 1], scope='Conv2d_0a_1x1')
branch_1 = slim.conv2d(branch_1, 64, [1, 7], scope='Conv2d_0b_1x7')
branch_1 = slim.conv2d(branch_1, 64, [7, 1], scope='Conv2d_0c_7x1')
branch_1 = slim.conv2d(branch_1, 96, [3, 3], padding='VALID', scope='Conv2d_1a_3x3')
net = tf.concat(axis=3, values=[branch_0, branch_1])
if add_and_check_final('Mixed_4a', net): return net, end_points
# 71 x 71 x 192
with tf.variable_scope('Mixed_5a'):
with tf.variable_scope('Branch_0'):
branch_0 = slim.conv2d(net, 192, [3, 3], stride=2, padding='VALID', scope='Conv2d_1a_3x3')
with tf.variable_scope('Branch_1'):
branch_1 = slim.max_pool2d(net, [3, 3], stride=2, padding='VALID', scope='MaxPool_1a_3x3')
net = tf.concat(axis=3, values=[branch_0, branch_1])
if add_and_check_final('Mixed_5a', net): return net, end_points
# 35 x 35 x 384
# 4 x Inception-A blocks
for idx in range(4):
block_scope = 'Mixed_5' + chr(ord('b') + idx)
net = block_inception_a(net, block_scope)
if add_and_check_final(block_scope, net): return net, end_points
# 35 x 35 x 384
# Reduction-A block
net = block_reduction_a(net, 'Mixed_6a')
if add_and_check_final('Mixed_6a', net): return net, end_points
# 17 x 17 x 1024
# 7 x Inception-B blocks
for idx in range(7):
block_scope = 'Mixed_6' + chr(ord('b') + idx)
net = block_inception_b(net, block_scope)
if add_and_check_final(block_scope, net): return net, end_points
# 17 x 17 x 1024
# Reduction-B block
net = block_reduction_b(net, 'Mixed_7a')
if add_and_check_final('Mixed_7a', net): return net, end_points
# 8 x 8 x 1536
# 3 x Inception-C blocks
for idx in range(3):
block_scope = 'Mixed_7' + chr(ord('b') + idx)
net = block_inception_c(net, block_scope)
if add_and_check_final(block_scope, net): return net, end_points
raise ValueError('Unknown final endpoint %s' % final_endpoint)
def inception_v4(inputs, num_classes=2, is_training=True,
dropout_keep_prob=0.8,
reuse=None,
scope='InceptionV4',
create_aux_logits=True):
"""Creates the Inception V4 model.
Args:
inputs: a 4-D tensor of size [batch_size, height, width, 3].
num_classes: number of predicted classes. If 0 or None, the logits layer
is omitted and the input features to the logits layer (before dropout)
are returned instead.
is_training: whether is training or not.
dropout_keep_prob: float, the fraction to keep before final layer.
reuse: whether or not the network and its variables should be reused. To be
able to reuse 'scope' must be given.
scope: Optional variable_scope.
create_aux_logits: Whether to include the auxiliary logits.
Returns:
net: a Tensor with the logits (pre-softmax activations) if num_classes
is a non-zero integer, or the non-dropped input to the logits layer
if num_classes is 0 or None.
end_points: the set of end_points from the inception model.
"""
end_points = {}
with tf.variable_scope(scope, 'InceptionV4', [inputs], reuse=reuse) as scope:
with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_training):
net, end_points = inception_v4_base(inputs, scope=scope)
with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d], stride=1, padding='SAME'):
# Auxiliary Head logits
if create_aux_logits and num_classes:
with tf.variable_scope('AuxLogits'):
# 17 x 17 x 1024
aux_logits = end_points['Mixed_6h']
aux_logits = slim.avg_pool2d(aux_logits, [5, 5], stride=3, padding='VALID', scope='AvgPool_1a_5x5')
aux_logits = slim.conv2d(aux_logits, 128, [1, 1], scope='Conv2d_1b_1x1')
aux_logits = slim.conv2d(aux_logits, 768, aux_logits.get_shape()[1:3], padding='VALID', scope='Conv2d_2a')
aux_logits = slim.flatten(aux_logits)
aux_logits = slim.fully_connected(aux_logits, num_classes, activation_fn=None, scope='Aux_logits')
end_points['AuxLogits'] = aux_logits
# Final pooling and prediction
# TODO(sguada,arnoegw): Consider adding a parameter global_pool which
# can be set to False to disable pooling here (as in resnet_*()).
with tf.variable_scope('Logits'):
# 8 x 8 x 1536
kernel_size = net.get_shape()[1:3]
if kernel_size.is_fully_defined():
net = slim.avg_pool2d(net, kernel_size, padding='VALID', scope='AvgPool_1a')
else:
net = tf.reduce_mean(net, [1, 2], keep_dims=True, name='global_pool')
end_points['global_pool'] = net
if not num_classes:
return net, end_points
# 1 x 1 x 1536
net = slim.dropout(net, dropout_keep_prob, scope='Dropout_1b')
net = slim.flatten(net, scope='PreLogitsFlatten')
end_points['PreLogitsFlatten'] = net
# 1536
logits = slim.fully_connected(net, num_classes, activation_fn=None, scope='Logits')
end_points['Logits'] = logits
end_points['Predictions'] = tf.nn.softmax(logits, name='Predictions')
return logits, end_points
inception_v4.default_image_size = 299
inception_v4_arg_scope = inception_utils.inception_arg_scope
| [
"noreply@github.com"
] | YKSIAT.noreply@github.com |
b33e87bfce2e4f32599652342ed6bd5e1b196570 | 6b3830e43ddd95ca0e946a0f4c459a57b87d144e | /tests/app/main/test_asset_fingerprinter.py | c2cbc5df707394fa429d4ca5eb2e31487d90d70f | [
"MIT"
] | permissive | pyexcel/notifications-admin | 043a2157fb77a9adb57b569a1aa68a54f0fcbd50 | 886fb2bb3cfc598ac45b2528228afb298e0e715a | refs/heads/master | 2023-06-12T00:07:40.887509 | 2017-08-17T22:52:34 | 2017-08-17T22:52:34 | 100,309,827 | 0 | 0 | null | 2017-08-14T21:10:43 | 2017-08-14T21:10:43 | null | UTF-8 | Python | false | false | 3,582 | py | # coding=utf-8
import os
from unittest import mock
from app.asset_fingerprinter import AssetFingerprinter
class TestAssetFingerprint(object):
def test_url_format(self, mocker):
get_file_content_mock = mocker.patch.object(AssetFingerprinter, 'get_asset_file_contents')
get_file_content_mock.return_value = """
body {
font-family: nta;
}
"""
asset_fingerprinter = AssetFingerprinter(
asset_root='/suppliers/static/'
)
assert (
asset_fingerprinter.get_url('application.css') ==
'/suppliers/static/application.css?418e6f4a6cdf1142e45c072ed3e1c90a' # noqa
)
assert (
asset_fingerprinter.get_url('application-ie6.css') ==
'/suppliers/static/application-ie6.css?418e6f4a6cdf1142e45c072ed3e1c90a' # noqa
)
def test_building_file_path(self, mocker):
get_file_content_mock = mocker.patch.object(AssetFingerprinter, 'get_asset_file_contents')
get_file_content_mock.return_value = """
document.write('Hello world!');
"""
fingerprinter = AssetFingerprinter()
fingerprinter.get_url('javascripts/application.js')
fingerprinter.get_asset_file_contents.assert_called_with(
'app/static/javascripts/application.js'
)
def test_hashes_are_consistent(self, mocker):
get_file_content_mock = mocker.patch.object(AssetFingerprinter, 'get_asset_file_contents')
get_file_content_mock.return_value = """
body {
font-family: nta;
}
"""
asset_fingerprinter = AssetFingerprinter()
assert (
asset_fingerprinter.get_asset_fingerprint('application.css') ==
asset_fingerprinter.get_asset_fingerprint('same_contents.css')
)
def test_hashes_are_different_for_different_files(
self, mocker
):
get_file_content_mock = mocker.patch.object(AssetFingerprinter, 'get_asset_file_contents')
asset_fingerprinter = AssetFingerprinter()
get_file_content_mock.return_value = """
body {
font-family: nta;
}
"""
css_hash = asset_fingerprinter.get_asset_fingerprint('application.css')
get_file_content_mock.return_value = """
document.write('Hello world!');
"""
js_hash = asset_fingerprinter.get_asset_fingerprint('application.js')
assert (
js_hash != css_hash
)
def test_hash_gets_cached(self, mocker):
get_file_content_mock = mocker.patch.object(AssetFingerprinter, 'get_asset_file_contents')
get_file_content_mock.return_value = """
body {
font-family: nta;
}
"""
fingerprinter = AssetFingerprinter()
assert (
fingerprinter.get_url('application.css') ==
'/static/application.css?418e6f4a6cdf1142e45c072ed3e1c90a'
)
fingerprinter._cache[
'application.css'
] = 'a1a1a1'
assert (
fingerprinter.get_url('application.css') ==
'a1a1a1'
)
fingerprinter.get_asset_file_contents.assert_called_once_with(
'app/static/application.css'
)
class TestAssetFingerprintWithUnicode(object):
def test_can_read_self(self):
string_with_unicode_character = 'Ralph’s apostrophe'
AssetFingerprinter(filesystem_path='tests/app/main/').get_url('test_asset_fingerprinter.py')
| [
"me@quis.cc"
] | me@quis.cc |
a6e6adc0bdda7113806c00b2529a06b8744a1706 | 9b130727b93d1ef7247ff378ef4af4c324a13f10 | /pw-python-03/exercicio_2/main.py | f85ea7c400eddc744ccb4de30b3ef9d959fda814 | [] | no_license | Joao-21903149/pw-python-ex | a05eab583155c09c70c626fb05e0217da0086689 | b72509b29b2a0a18d1adcf62b0f24d469aa9c523 | refs/heads/main | 2023-04-26T08:45:43.156523 | 2021-05-21T21:19:53 | 2021-05-21T21:19:53 | 365,194,663 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 331 | py | import analise_pasta as al
def main():
foldername = al.pede_pasta()
informacao = al.faz_calculos(foldername)
print(informacao)
al.guarda_resultados(foldername)
al.faz_grafico_queijos("Queijo", foldername)
al.faz_grafico_barras("Barra", foldername)
if __name__ == "__main__":
main()
| [
"noreply@github.com"
] | Joao-21903149.noreply@github.com |
5724b790dcd125fd9a138ef2f96230faa1dabcb5 | 6c31c2b4e5508ff72ef380ffb1ee6f568b8c197a | /sporco/linalg.py | 3e92cd9ce7b975bccdc4216b7ebde46d8712e0e8 | [
"BSD-3-Clause"
] | permissive | runngezhang/sporco | a5c07c6bf58e8b6d236460fc4b419d5b1bb55a84 | 60fed3558ea6ad503f4c7b4cd19094cd50c44ab9 | refs/heads/master | 2021-01-11T12:20:17.885451 | 2016-11-28T02:18:29 | 2016-11-28T02:18:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 32,565 | py | #-*- coding: utf-8 -*-
# Copyright (C) 2015-2016 by Brendt Wohlberg <brendt@ieee.org>
# All rights reserved. BSD 3-clause License.
# This file is part of the SPORCO package. Details of the copyright
# and user license can be found in the 'LICENSE.txt' file distributed
# with the package.
"""Linear algebra functions"""
from __future__ import division
from builtins import range
import numpy as np
from scipy import linalg
from scipy import fftpack
from scipy.sparse.linalg import LinearOperator
from scipy.sparse.linalg import cg
import multiprocessing
import pyfftw
try:
import numexpr as ne
except ImportError:
have_numexpr = False
else:
have_numexpr = True
__author__ = """Brendt Wohlberg <brendt@ieee.org>"""
pyfftw.interfaces.cache.enable()
pyfftw.interfaces.cache.set_keepalive_time(300)
pyfftw_threads = multiprocessing.cpu_count()
"""Global variable setting the number of threads used in :mod:`pyfftw`
computations"""
def complex_dtype(dtype):
"""
Construct the corresponding complex dtype for a given real dtype,
e.g. the complex dtype corresponding to np.float32 is np.complex64.
Parameters
----------
dtype : dtype
A real dtype, e.g. np.float32, np.float64
Returns
-------
cdtype : dtype
The complex dtype corresponding to the input dtype
"""
return (np.zeros(1, dtype)+1j).dtype
def pyfftw_empty_aligned(shape, dtype, order='C', n=None):
"""
Construct an empty byte-aligned array for efficient use by :mod:`pyfftw`.
This function is a wrapper for :func:`pyfftw.empty_aligned`
Parameters
----------
shape : sequence of ints
Output array shape
dtype : dtype
Output array dtype
n : int, optional (default None)
Output array should be aligned to n-byte boundary
Returns
-------
a : ndarray
Empty array with required byte-alignment
"""
return pyfftw.empty_aligned(shape, dtype, order, n)
def fftn(a, s=None, axes=None):
"""
Compute the multi-dimensional discrete Fourier transform. This function
is a wrapper for :func:`pyfftw.interfaces.numpy_fft.fftn`,
with an interface similar to that of :func:`numpy.fft.fftn`.
Parameters
----------
a : array_like
Input array (can be complex)
s : sequence of ints, optional (default None)
Shape of the output along each axis (input is cropped or zero-padded
to match).
axes : sequence of ints, optional (default None)
Axes over which to compute the DFT.
Returns
-------
af : complex ndarray
DFT of input array
"""
return pyfftw.interfaces.numpy_fft.fftn(a, s=s, axes=axes,
overwrite_input=False, planner_effort='FFTW_MEASURE',
threads=pyfftw_threads)
def ifftn(a, s=None, axes=None):
"""
Compute the multi-dimensional inverse discrete Fourier transform.
This function is a wrapper for :func:`pyfftw.interfaces.numpy_fft.ifftn`,
with an interface similar to that of :func:`numpy.fft.ifftn`.
Parameters
----------
a : array_like
Input array (can be complex)
s : sequence of ints, optional (default None)
Shape of the output along each axis (input is cropped or zero-padded
to match).
axes : sequence of ints, optional (default None)
Axes over which to compute the inverse DFT.
Returns
-------
af : complex ndarray
Inverse DFT of input array
"""
return pyfftw.interfaces.numpy_fft.ifftn(a, s=s, axes=axes,
overwrite_input=False, planner_effort='FFTW_MEASURE',
threads=pyfftw_threads)
def rfftn(a, s=None, axes=None):
"""
Compute the multi-dimensional discrete Fourier transform for real input.
This function is a wrapper for :func:`pyfftw.interfaces.numpy_fft.rfftn`,
with an interface similar to that of :func:`numpy.fft.rfftn`.
Parameters
----------
a : array_like
Input array (taken to be real)
s : sequence of ints, optional (default None)
Shape of the output along each axis (input is cropped or zero-padded
to match).
axes : sequence of ints, optional (default None)
Axes over which to compute the DFT.
Returns
-------
af : complex ndarray
DFT of input array
"""
return pyfftw.interfaces.numpy_fft.rfftn(a, s=s, axes=axes,
overwrite_input=False, planner_effort='FFTW_MEASURE',
threads=pyfftw_threads)
def irfftn(a, s=None, axes=None):
"""
Compute the inverse of the multi-dimensional discrete Fourier transform
for real input. This function is a wrapper for
:func:`pyfftw.interfaces.numpy_fft.irfftn`, with an interface similar to
that of :func:`numpy.fft.irfftn`.
Parameters
----------
a : array_like
Input array
s : sequence of ints, optional (default None)
Shape of the output along each axis (input is cropped or zero-padded
to match).
axes : sequence of ints, optional (default None)
Axes over which to compute the inverse DFT.
Returns
-------
af : ndarray
Inverse DFT of input array
"""
return pyfftw.interfaces.numpy_fft.irfftn(a, s=s, axes=axes,
overwrite_input=False, planner_effort='FFTW_MEASURE',
threads=pyfftw_threads)
def dctii(x, axes=None):
"""
Compute a multi-dimensional DCT-II over specified array axes. This
function is implemented by calling the one-dimensional DCT-II
:func:`scipy.fftpack.dct` with normalization mode 'ortho' for each
of the specified axes.
Parameters
----------
a : array_like
Input array
axes : sequence of ints, optional (default None)
Axes over which to compute the DCT-II.
Returns
-------
y : ndarray
DCT-II of input array
"""
if axes is None:
axes = list(range(x.ndim))
for ax in axes:
x = fftpack.dct(x, type=2, axis=ax, norm='ortho')
return x
def idctii(x, axes=None):
"""
Compute a multi-dimensional inverse DCT-II over specified array axes.
This function is implemented by calling the one-dimensional inverse
DCT-II :func:`scipy.fftpack.idct` with normalization mode 'ortho'
for each of the specified axes.
Parameters
----------
a : array_like
Input array
axes : sequence of ints, optional (default None)
Axes over which to compute the inverse DCT-II.
Returns
-------
y : ndarray
Inverse DCT-II of input array
"""
if axes is None:
axes = list(range(x.ndim))
for ax in axes[::-1]:
x = fftpack.idct(x, type=2, axis=ax, norm='ortho')
return x
def solvedbi_sm(ah, rho, b, c=None, axis=4):
"""
Solve a diagonal block linear system with a scaled identity term
using the Sherman-Morrison equation.
The solution is obtained by independently solving a set of linear
systems of the form (see :cite:`wohlberg-2016-efficient`)
.. math::
(\\rho I + \mathbf{a} \mathbf{a}^H ) \; \mathbf{x} = \mathbf{b} \;\;.
In this equation inner products and matrix products are taken along
the specified axis of the corresponding multi-dimensional arrays; the
solutions are independent over the other axes.
Parameters
----------
ah : array_like
Linear system component :math:`\mathbf{a}^H`
rho : float
Linear system parameter :math:`\\rho`
b : array_like
Linear system component :math:`\mathbf{b}`
c : array_like, optional (default None)
Solution component :math:`\mathbf{c}` that may be pre-computed using
:func:`solvedbi_sm_c` and cached for re-use.
axis : int, optional (default 4)
Axis along which to solve the linear system
Returns
-------
x : ndarray
Linear system solution :math:`\mathbf{x}`
"""
a = np.conj(ah)
if c is None:
c = solvedbi_sm_c(ah, a, rho, axis)
if have_numexpr:
cb = np.sum(c * b, axis=axis, keepdims=True)
return ne.evaluate('(b - (a * cb)) / rho')
else:
return (b - (a * np.sum(c * b, axis=axis, keepdims=True))) / rho
def solvedbi_sm_c(ah, a, rho, axis=4):
"""
Compute cached component used by :func:`solvedbi_sm`.
Parameters
----------
ah : array_like
Linear system component :math:`\mathbf{a}^H`
a : array_like
Linear system component :math:`\mathbf{a}`
rho : float
Linear system parameter :math:`\\rho`
axis : int, optional (default 4)
Axis along which to solve the linear system
Returns
-------
c : ndarray
Argument :math:`\mathbf{c}` used by :func:`solvedbi_sm`
"""
return ah / (np.sum(ah * a, axis=axis, keepdims=True) + rho)
def solvemdbi_ism(ah, rho, b, axisM, axisK):
"""
Solve a multiple diagonal block linear system with a scaled
identity term by iterated application of the Sherman-Morrison
equation. The computation is performed in a way that avoids
explictly constructing the inverse operator, leading to an
:math:`O(K^2)` time cost.
The solution is obtained by independently solving a set of linear
systems of the form (see :cite:`wohlberg-2016-efficient`)
.. math::
(\\rho I + \mathbf{a}_0 \mathbf{a}_0^H + \mathbf{a}_1 \mathbf{a}_1^H +
\; \ldots \; + \mathbf{a}_{K-1} \mathbf{a}_{K-1}^H) \; \mathbf{x} =
\mathbf{b}
where each :math:`\mathbf{a}_k` is an :math:`M`-vector.
The sums, inner products, and matrix products in this equation are taken
along the M and K axes of the corresponding multi-dimensional arrays;
the solutions are independent over the other axes.
Parameters
----------
ah : array_like
Linear system component :math:`\mathbf{a}^H`
rho : float
Linear system parameter :math:`\\rho`
b : array_like
Linear system component :math:`\mathbf{b}`
axisM : int
Axis in input corresponding to index m in linear system
axisK : int
Axis in input corresponding to index k in linear system
Returns
-------
x : ndarray
Linear system solution :math:`\mathbf{x}`
"""
K = ah.shape[axisK]
a = np.conj(ah)
gamma = np.zeros(a.shape, a.dtype)
delta = np.zeros(a.shape[0:axisM] + (1,), a.dtype)
slcnc = (slice(None),)*axisK
alpha = a[slcnc + (slice(0, 1),)] / rho
beta = b / rho
del b
for k in range(0, K):
slck = slcnc + (slice(k, k+1),)
gamma[slck] = alpha
delta[slck] = 1.0 + np.sum(ah[slck] * gamma[slck], axisM, keepdims=True)
c = np.sum(ah[slck] * beta, axisM, keepdims=True)
d = c * gamma[slck]
beta = beta - (d / delta[slck])
if k < K-1:
alpha = a[slcnc + (slice(k+1, k+2),)] / rho
for l in range(0, k+1):
slcl = slcnc + (slice(l, l+1),)
c = np.sum(ah[slcl] * alpha, axisM, keepdims=True)
d = c * gamma[slcl]
alpha = alpha - (d / delta[slcl])
return beta
def solvemdbi_rsm(ah, rho, b, axisK, dimN=2):
"""
Solve a multiple diagonal block linear system with a scaled
identity term by repeated application of the Sherman-Morrison
equation. The computation is performed by explictly constructing
the inverse operator, leading to an :math:`O(K)` time cost and
:math:`O(M^2)` memory cost, where :math:`M` is the dimension of
the axis over which inner products are taken.
The solution is obtained by independently solving a set of linear
systems of the form (see :cite:`wohlberg-2016-efficient`)
.. math::
(\\rho I + \mathbf{a}_0 \mathbf{a}_0^H + \mathbf{a}_1 \mathbf{a}_1^H +
\; \ldots \; + \mathbf{a}_{K-1} \mathbf{a}_{K-1}^H) \; \mathbf{x} =
\mathbf{b}
where each :math:`\mathbf{a}_k` is an :math:`M`-vector.
The sums, inner products, and matrix products in this equation are taken
along the M and K axes of the corresponding multi-dimensional arrays;
the solutions are independent over the other axes.
Parameters
----------
ah : array_like
Linear system component :math:`\mathbf{a}^H`
rho : float
Linear system parameter :math:`\\rho`
b : array_like
Linear system component :math:`\mathbf{b}`
axisK : int
Axis in input corresponding to index k in linear system
dimN : int, optional (default 2)
Number of spatial dimensions arranged as leading axes in input array.
Axis M is taken to be at dimN+2.
Returns
-------
x : ndarray
Linear system solution :math:`\mathbf{x}`
"""
axisM = dimN + 2
slcnc = (slice(None),)*axisK
M = ah.shape[axisM]
K = ah.shape[axisK]
a = np.conj(ah)
Ainv = np.ones(ah.shape[0:dimN] + (1,)*4) * \
np.reshape(np.eye(M,M) / rho, (1,)*(dimN+2) + (M, M))
for k in range(0, K):
slck = slcnc + (slice(k, k+1),) + (slice(None), np.newaxis,)
Aia = np.sum(Ainv * np.swapaxes(a[slck], dimN+2, dimN+3),
dimN+3, keepdims=True)
ahAia = 1.0 + np.sum(ah[slck] * Aia, dimN+2, keepdims=True)
ahAi = np.sum(ah[slck] * Ainv, dimN+2, keepdims=True)
AiaahAi = Aia * ahAi
Ainv = Ainv - AiaahAi / ahAia
return np.sum(Ainv * np.swapaxes(b[(slice(None),)*b.ndim + (np.newaxis,)],
dimN+2, dimN+3), dimN+3)
def solvemdbi_cg(ah, rho, b, axisM, axisK, tol=1e-5, mit=1000, isn=None):
"""
Solve a multiple diagonal block linear system with a scaled
identity term using Conjugate Gradient (CG) via
:func:`scipy.sparse.linalg.cg`.
The solution is obtained by independently solving a set of linear
systems of the form (see :cite:`wohlberg-2016-efficient`)
.. math::
(\\rho I + \mathbf{a}_0 \mathbf{a}_0^H + \mathbf{a}_1 \mathbf{a}_1^H +
\; \ldots \; + \mathbf{a}_{K-1} \mathbf{a}_{K-1}^H) \; \mathbf{x} =
\mathbf{b}
where each :math:`\mathbf{a}_k` is an :math:`M`-vector.
The inner products and matrix products in this equation are taken
along the M and K axes of the corresponding multi-dimensional arrays;
the solutions are independent over the other axes.
Parameters
----------
ah : array_like
Linear system component :math:`\mathbf{a}^H`
rho : float
Parameter rho
b : array_like
Linear system component :math:`\mathbf{b}`
axisM : int
Axis in input corresponding to index m in linear system
axisK : int
Axis in input corresponding to index k in linear system
tol : float
CG tolerance
mit : int
CG maximum iterations
isn : array_like
CG initial solution
Returns
-------
x : ndarray
Linear system solution :math:`\mathbf{x}`
cgit : int
Number of CG iterations
"""
a = np.conj(ah)
if isn is not None:
isn = isn.ravel()
Aop = lambda x: np.sum(ah * x, axis=axisM, keepdims=True)
AHop = lambda x: np.sum(a * x, axis=axisK, keepdims=True)
AHAop = lambda x: AHop(Aop(x))
vAHAoprI = lambda x: AHAop(x.reshape(b.shape)).ravel() + rho*x.ravel()
lop = LinearOperator((b.size, b.size), matvec=vAHAoprI, dtype=b.dtype)
vx, cgit = cg(lop, b.ravel(), isn, tol, mit)
return vx.reshape(b.shape), cgit
def lu_factor(A, rho):
"""
Compute LU factorisation of either :math:`A^T A + \\rho I` or
:math:`A A^T + \\rho I`, depending on which matrix is smaller.
Parameters
----------
A : array_like
Array :math:`A`
rho : float
Scalar :math:`\\rho`
Returns
-------
lu : ndarray
Matrix containing U in its upper triangle, and L in its lower triangle,
as returned by :func:`scipy.linalg.lu_factor`
piv : ndarray
Pivot indices representing the permutation matrix P, as returned by
:func:`scipy.linalg.lu_factor`
"""
N, M = A.shape
# If N < M it is cheaper to factorise A*A^T + rho*I and then use the
# matrix inversion lemma to compute the inverse of A^T*A + rho*I
if N >= M:
lu, piv = linalg.lu_factor(A.T.dot(A) + rho*np.identity(M,
dtype=A.dtype))
else:
lu, piv = linalg.lu_factor(A.dot(A.T) + rho*np.identity(N,
dtype=A.dtype))
return lu, piv
def lu_solve_ATAI(A, rho, b, lu, piv):
"""
Solve the linear system :math:`(A^T A + \\rho I)\\mathbf{x} = \\mathbf{b}`
or :math:`(A^T A + \\rho I)X = B` using :func:`scipy.linalg.lu_solve`.
Parameters
----------
A : array_like
Matrix :math:`A`
rho : float
Scalar :math:`\\rho`
b : array_like
Vector :math:`\\mathbf{b}` or matrix :math:`B`
lu : array_like
Matrix containing U in its upper triangle, and L in its lower triangle,
as returned by :func:`scipy.linalg.lu_factor`
piv : array_like
Pivot indices representing the permutation matrix P, as returned by
:func:`scipy.linalg.lu_factor`
Returns
-------
x : ndarray
Solution to the linear system.
"""
N, M = A.shape
if N >= M:
x = linalg.lu_solve((lu, piv), b)
else:
x = (b - A.T.dot(linalg.lu_solve((lu, piv), A.dot(b), 1))) / rho
return x
def lu_solve_AATI(A, rho, b, lu, piv):
"""
Solve the linear system :math:`(A A^T + \\rho I)\\mathbf{x} = \\mathbf{b}`
or :math:`(A A^T + \\rho I)X = B` using :func:`scipy.linalg.lu_solve`.
Parameters
----------
A : array_like
Matrix :math:`A`
rho : float
Scalar :math:`\\rho`
b : array_like
Vector :math:`\\mathbf{b}` or matrix :math:`B`
lu : array_like
Matrix containing U in its upper triangle, and L in its lower triangle,
as returned by :func:`scipy.linalg.lu_factor`
piv : array_like
Pivot indices representing the permutation matrix P, as returned by
:func:`scipy.linalg.lu_factor`
Returns
-------
x : ndarray
Solution to the linear system.
"""
N, M = A.shape
if N >= M:
x = (b - linalg.lu_solve((lu, piv), b.dot(A).T).T.dot(A.T)) / rho
else:
x = linalg.lu_solve((lu, piv), b.T).T
return x
def zpad(x, pd, ax):
"""
Zero-pad array x with pd=(leading,trailing) zeros on axis ax.
Parameters
----------
x : array_like
Array to be padded
pd : tuple
Sequence of two ints (leading,trailing) specifying number of zeros
for padding
ax : int
Axis to be padded
Returns
-------
xp : array_like
Padded array
"""
xpd = ((0,0),)*ax + (pd,) + ((0,0),)*(x.ndim-ax-1)
return np.pad(x, xpd, 'constant')
def Gax(x, ax):
"""
Compute gradient of `x` along axis `ax`.
Parameters
----------
x : array_like
Input array
ax : int
Axis on which gradient is to be computed
Returns
-------
xg : ndarray
Output array
"""
slc0 = (slice(None),)*ax
return zpad(x[slc0 + (slice(1,None),)] - x[slc0 + (slice(-1),)], (0,1), ax)
def GTax(x, ax):
"""
Compute transpose of gradient of `x` along axis `ax`.
Parameters
----------
x : array_like
Input array
ax : int
Axis on which gradient transpose is to be computed
Returns
-------
xg : ndarray
Output array
"""
slc0 = (slice(None),)*ax
return zpad(x[slc0 + (slice(-1),)], (1,0), ax) - \
zpad(x[slc0 + (slice(-1),)], (0,1), ax)
def GradientFilters(ndim, axes, axshp, dtype=None):
"""
Construct a set of filters for computing gradients in the frequency
domain.
Parameters
----------
ndim : integer
Total number of dimensions in array in which gradients are to be
computed
axes : tuple of integers
Axes on which gradients are to be computed
axshp : tuple of integers
Shape of axes on which gradients are to be computed
dtype : dtype
Data type of output arrays
Returns
-------
Gf : ndarray
Frequency domain gradient operators :math:`\hat{G}_i`
GHGf : ndarray
Sum of products :math:`\sum_i \hat{G}_i^H \hat{G}_i`
"""
if dtype is None:
dtype = np.float32
g = np.zeros([2 if k in axes else 1 for k in range(ndim)] +
[len(axes),], dtype)
for k in axes:
g[(0,)*k +(slice(None),)+(0,)*(g.ndim-2-k)+(k,)] = [1,-1]
Gf = rfftn(g, axshp, axes=axes)
GHGf = np.sum(np.conj(Gf)*Gf, axis=-1)
return Gf, GHGf
def shrink1(x, alpha):
"""
Scalar shrinkage/soft thresholding function
.. math::
\mathcal{S}_{1,\\alpha}(\mathbf{x}) = \mathrm{sign}(\mathbf{x}) \odot
\max(0, |\mathbf{x}| - \\alpha) = \mathrm{prox}_f(\mathbf{x}) \;\;
\\text{where} \;\; f(\mathbf{u}) = \\alpha \|\mathbf{u}\|_1 \;\;.
Parameters
----------
x : array_like
Input array :math:`\mathbf{x}`
alpha : float or array_like
Shrinkage parameter :math:`\\alpha`
Returns
-------
x : ndarray
Output array
"""
if have_numexpr:
return ne.evaluate(
'where(abs(x)-alpha > 0, where(x >= 0, 1, -1) * (abs(x)-alpha), 0)'
)
else:
return np.sign(x) * (np.clip(np.abs(x) - alpha, 0, float('Inf')))
def zdivide(x, y):
"""
Return x/y, with 0 instead of NaN where y is 0.
Parameters
----------
x : array_like
Numerator
y : array_like
Denominator
Returns
-------
z : ndarray
Quotient `x`/`y`
"""
with np.errstate(divide='ignore', invalid='ignore'):
div = x / y
div[np.logical_or(np.isnan(div), np.isinf(div))] = 0
return div
def shrink2(x, alpha, axis=-1):
"""
Vector shrinkage/soft thresholding function
.. math::
\mathcal{S}_{2,\\alpha}(\mathbf{x}) =
\\frac{\mathbf{x}}{\|\mathbf{x}\|_2} \max(0, \|\mathbf{x}\|_2 - \\alpha)
= \mathrm{prox}_f(\mathbf{x}) \;\;
\\text{where} \;\; f(\mathbf{u}) = \\alpha \|\mathbf{u}\|_2 \;\;.
The :math:`\ell_2` norm is applied over the specified axis of a
multi-dimensional input (the last axis by default).
Parameters
----------
x : array_like
Input array :math:`\mathbf{x}`
alpha : float or array_like
Shrinkage parameter :math:`\\alpha`
axis : int, optional (default -1)
Axis of x over which the :math:`\ell_2` norm
Returns
-------
x : ndarray
Output array
"""
a = np.sqrt(np.sum(x**2, axis=axis, keepdims=True))
b = np.maximum(0, a - alpha)
b = zdivide(b, a)
return b*x
def shrink12(x, alpha, beta, axis=-1):
"""
Compound shrinkage/soft thresholding function
:cite:`wohlberg-2012-local` :cite:`chartrand-2013-nonconvex`
.. math::
\mathcal{S}_{1,2,\\alpha,\\beta}(\mathbf{x}) =
\mathcal{S}_{2,\\beta}(\mathcal{S}_{1,\\alpha}(\mathbf{x}))
= \mathrm{prox}_f(\mathbf{x}) \;\;
\\text{where} \;\; f(\mathbf{u}) = \\alpha \|\mathbf{u}\|_1 +
\\beta \|\mathbf{u}\|_2 \;\;.
The :math:`\ell_2` norm is applied over the specified axis of a
multi-dimensional input (the last axis by default).
Parameters
----------
x : array_like
Input array :math:`\mathbf{x}`
alpha : float or array_like
Shrinkage parameter :math:`\\alpha`
beta : float or array_like
Shrinkage parameter :math:`\\beta`
axis : int, optional (default -1)
Axis of x over which the :math:`\ell_2` norm
Returns
-------
x : ndarray
Output array
"""
return shrink2(shrink1(x, alpha), beta, axis)
def proj_l2ball(b, s, r, axes=None):
"""
Project :math:`\mathbf{b}` into the :math:`\ell_2` ball of radius
:math:`r` about :math:`\mathbf{s}`, i.e.
:math:`\{ \mathbf{x} : \|\mathbf{x} - \mathbf{s} \|_2 \leq r \}`.
Parameters
----------
b : array_like
Vector :math:`\mathbf{b}` to be projected
s : array_like
Centre of :math:`\ell_2` ball :math:`\mathbf{s}`
r : float
Radius of ball
axes : sequence of ints, optional (default all axes)
Axes over which to compute :math:`\ell_2` norms
Returns
-------
x : ndarray
Projection of :math:`\mathbf{b}` into ball
"""
d = np.sqrt(np.sum((b - s)**2, axis=axes, keepdims=True))
p = zdivide(b - s, d)
return np.asarray((d <= r) * b + (d > r) * (s + r*p), b.dtype)
def promote16(u, fn=None, *args, **kwargs):
"""
Utility function for use with functions that do not support arrays
of dtype np.float16. This function has two distinct modes of
operation. If called with only the `u` parameter specified, the
returned value is either `u` itself if u is not of dtype
np.float16, or `u` promoted to np.float32 dtype if it is. If the
function parameter `fn` is specified then `u` is conditionally
promoted as described above, passed as the first argument to
function `fn`, and the returned values are converted back to dtype
np.float16 if u is of that dtype.
Parameters
----------
u : array_like
Array to be promoted to np.float32 if it is of dtype np.float16
fn : function or None, optional (default None)
Function to be called with promoted `u` as first parameter and
\*args and \*\*kwargs as additional parameters
*args
Variable length list of arguments for function `fn`
**kwargs
Keyword arguments for function `fn`
Returns
-------
up : ndarray
Conditionally dtype-promoted version of `u` if `fn` is None,
or value(s) returned by `fn`, converted to the same dtype as `u`,
if `fn` is a function
"""
dtype = np.float32 if u.dtype == np.float16 else u.dtype
up = np.asarray(u, dtype=dtype)
if fn is None:
return up
else:
v = fn(up, *args, **kwargs)
if isinstance(v, tuple):
vp = tuple([np.asarray(vk, dtype=u.dtype) for vk in v])
else:
vp = np.asarray(v, dtype=u.dtype)
return vp
def atleast_nd(n, u):
"""
If the input array has fewer than n dimensions, append singleton
dimensions so that it is n dimensional. Note that the interface
differs substantially from that of :func:`numpy.atleast_3d` etc.
Parameters
----------
n : int
Minimum number of required dimensions
u : array_like
Input array
Returns
-------
v : ndarray
Output array with at least n dimensions
"""
if u.ndim >= n:
return u
else:
return u.reshape(u.shape + (1,)*(n-u.ndim))
def roll(u, shift):
"""
Apply :func:`numpy.roll` to multiple array axes.
Parameters
----------
u : array_like
Input array
shift : array_like of int
Shifts to apply to axes of input `u`
Returns
-------
v : ndarray
Output array
"""
v = u.copy()
for k in range(len(shift)):
v = np.roll(v, shift[k], axis=k)
return v
def blockcirculant(A):
"""
Construct a block circulant matrix from a tuple of arrays. This is a
block-matrix variant of :func:`scipy.linalg.circulant`.
Parameters
----------
A : tuple of array_like
Tuple of arrays corresponding to the first block column of the output
block matrix
Returns
-------
B : ndarray
Output array
"""
r,c = A[0].shape
B = np.zeros((len(A)*r, len(A)*c), dtype=A[0].dtype)
for k in range(len(A)):
for l in range(len(A)):
kl = np.mod(k + l, len(A))
B[r*kl:r*(kl+1), c*k:c*(k+1)] = A[l]
return B
def fl2norm2(xf, axis=(0,1)):
"""
Compute the squared :math:`\ell_2` norm in the DFT domain, taking
into account the unnormalised DFT scaling, i.e. given the DFT of a
multi-dimensional array computed via :func:`fftn`, return the
squared :math:`\ell_2` norm of the original array.
Parameters
----------
xf : array_like
Input array
axis : sequence of ints, optional (default (0,1))
Axes on which the input is in the frequency domain
Returns
-------
x : float
:math:`\|\mathbf{x}\|_2^2` where the input array is the result of
applying :func:`fftn` to the specified axes of multi-dimensional
array :math:`\mathbf{x}`
"""
xfs = xf.shape
return 0.5*(linalg.norm(xf)**2)/np.prod(np.array([xfs[k] for k in axis]))
def rfl2norm2(xf, xs, axis=(0,1)):
"""
Compute the squared :math:`\ell_2` norm in the DFT domain, taking
into account the unnormalised DFT scaling, i.e. given the DFT of a
multi-dimensional array computed via :func:`rfftn`, return the
squared :math:`\ell_2` norm of the original array.
Parameters
----------
xf : array_like
Input array
xs : sequence of ints
Shape of original array to which :func:`rfftn` was applied to
obtain the input array
axis : sequence of ints, optional (default (0,1))
Axes on which the input is in the frequency domain
Returns
-------
x : float
:math:`\|\mathbf{x}\|_2^2` where the input array is the result of
applying :func:`rfftn` to the specified axes of multi-dimensional
array :math:`\mathbf{x}`
"""
scl = 1.0 / np.prod(np.array([xs[k] for k in axis]))
slc0 = (slice(None),)*axis[-1]
nrm0 = linalg.norm(xf[slc0 + (0,)])
idx1 = (xs[axis[-1]]+1)//2
nrm1 = linalg.norm(xf[slc0 + (slice(1,idx1),)])
if xs[axis[-1]]%2 == 0:
nrm2 = linalg.norm(xf[slc0 + (slice(-1,None),)])
else:
nrm2 = 0.0
return scl*(nrm0**2 + 2.0*nrm1**2 + nrm2**2)
def rrs(ax, b):
"""
Compute relative residual :math:`\|\mathbf{b} - A \mathbf{x}\|_2 /
\|\mathbf{b}\|_2` of the solution to a linear equation :math:`A \mathbf{x}
= \mathbf{b}`. Returns 1.0 if :math:`\mathbf{b} = 0`.
Parameters
----------
ax : array_like
Linear component :math:`A \mathbf{x}` of equation
b : array_like
Constant component :math:`\mathbf{b}` of equation
Returns
-------
x : float
Relative residual
"""
nrm = linalg.norm(b.ravel())
if nrm == 0.0:
return 1.0
else:
return linalg.norm((ax - b).ravel()) / nrm
def mae(vref, vcmp):
"""
Compute Mean Absolute Error (MAE) between two images.
Parameters
----------
vref : array_like
Reference image
vcmp : array_like
Comparison image
Returns
-------
x : float
MAE between `vref` and `vcmp`
"""
r = np.asarray(vref, dtype=np.float64).ravel()
c = np.asarray(vcmp, dtype=np.float64).ravel()
return np.mean(np.fabs(r - c))
def mse(vref, vcmp):
"""
Compute Mean Squared Error (MSE) between two images.
Parameters
----------
vref : array_like
Reference image
vcmp : array_like
Comparison image
Returns
-------
x : float
MSE between `vref` and `vcmp`
"""
r = np.asarray(vref, dtype=np.float64).ravel()
c = np.asarray(vcmp, dtype=np.float64).ravel()
return np.mean(np.fabs(r - c)**2)
def snr(vref, vcmp):
"""
Compute Signal to Noise Ratio (SNR) of two images.
Parameters
----------
vref : array_like
Reference image
vcmp : array_like
Comparison image
Returns
-------
x : float
SNR of `vcmp` with respect to `vref`
"""
dv = np.var(vref)
with np.errstate(divide='ignore'):
rt = dv/mse(vref, vcmp)
return 10.0*np.log10(rt)
def psnr(vref, vcmp, rng=None):
"""
Compute Peak Signal to Noise Ratio (PSNR) of two images. The PSNR
calculation defaults to using the less common definition in terms
of the actual range (i.e. max minus min) of the reference signal
instead of the maximum possible range for the data type
(i.e. :math:`2^b-1` for a :math:`b` bit representation).
Parameters
----------
vref : array_like
Reference image
vcmp : array_like
Comparison image
rng : None or int, optional (default None)
Signal range, either the value to use (e.g. 255 for 8 bit samples) or
None, in which case the actual range of the reference signal is used
Returns
-------
x : float
PSNR of `vcmp` with respect to `vref`
"""
if rng is None:
rng = vref.max() - vref.min()
dv = (rng + 0.0)**2
with np.errstate(divide='ignore'):
rt = dv/mse(vref, vcmp)
return 10.0*np.log10(rt)
| [
"brendt.wohlberg@gmail.com"
] | brendt.wohlberg@gmail.com |
fbb307fb4bf6fec98b548793718ceabbf19429a6 | 320475ba2ca520f982cf776705b73c00a9c35ca9 | /include/subdags/training_subdag.py | ca8f5a73978afb89fac2fdcaf512bc48baace6a8 | [] | no_license | spudnik99/airflow_cicd | eae7f7b765e7b4821b8c1dc4d9cdf9f53588f267 | b17fef576a2c7664e6f72dd91c45710e9a7b9820 | refs/heads/master | 2023-03-11T05:24:17.014175 | 2021-03-01T16:27:28 | 2021-03-01T16:27:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,117 | py | from airflow import DAG
from airflow.providers.papermill.operators.papermill import PapermillOperator
def subdag_factory(parent_dag_id, child_dag_id, default_args):
with DAG(dag_id=f"{parent_dag_id}.{child_dag_id}", default_args=default_args) as dag:
n_estimators = [100, 150]
max_features = ['auto','sqrt']
training_model_tasks = []
for feature in max_features:
for estimator in n_estimators:
ml_id = f"{feature}_{estimator}"
training_model_tasks.append(PapermillOperator(
task_id=f'training_model_{ml_id}',
input_nb='/usr/local/airflow/include/notebooks/avocado_prediction.ipynb',
output_nb=f'/tmp/out-model-avocado-prediction-{ml_id}.ipynb',
pool='training_pool',
parameters={
'filepath': '/tmp/avocado.csv',
'n_estimators': estimator,
'max_features': feature,
'ml_id': ml_id
}
))
return dag | [
"marclamberti@Marcs-MacBook-Pro.local"
] | marclamberti@Marcs-MacBook-Pro.local |
08433cd3b827cf6eb7b778bdd0d1964b74989bac | 41c2d7ddc60d60ccbf08b317bf886e04c2dd6392 | /extract_binary.py | 1b72ab5a88bf4498dc4f4c8c035da236990d3262 | [] | no_license | joshwatson/microcorruption | c137402d0f46f5cbf2e437bd559d90a34f16dd19 | 554d8e76453d371975115d7ac3f70d807bc548db | refs/heads/master | 2020-05-20T12:34:43.573877 | 2014-01-18T22:25:35 | 2014-01-18T22:25:35 | 16,034,865 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 249 | py | import sys
def main():
input_file = sys.argv[1]
output_file = sys.argv[2]
with open(output_file, 'wb') as outF:
with open(input_file, 'r') as inF:
for line in inF:
outF.write(line[11:31])
if __name__ == "__main__":
main() | [
"josh@joshwatson.com"
] | josh@joshwatson.com |
1dea180a74d2d0bf7d2e180071b9519d5bff6151 | fc8f3638a1e9e80b386a14aa211d0ac55cb75215 | /python/examples/5_Wavedash/agent.py | cd1240b1ae43bf7035d2ff06b2d1f3ae8127703f | [
"MIT"
] | permissive | azeemba/RLUtilities | 750c88785e0ba8f7a3fa900b56f0bada7f35475b | eb887b312e33136b27a64516179ea812c366c2fa | refs/heads/master | 2023-02-21T16:45:55.240270 | 2020-02-23T18:50:35 | 2020-02-23T18:50:35 | 279,155,362 | 0 | 0 | null | 2020-07-12T22:02:12 | 2020-07-12T22:02:12 | null | UTF-8 | Python | false | false | 2,824 | py | from math import sin, cos
import random
from rlbot.agents.base_agent import BaseAgent, SimpleControllerState
from rlbot.utils.structures.game_data_struct import GameTickPacket
from rlbot.utils.game_state_util import GameState, BallState, CarState, Physics, Vector3, Rotator
from rlutilities.linear_algebra import *
from rlutilities.mechanics import Wavedash
from rlutilities.simulation import Game, Ball, Car
class State:
RESET = 0
WAIT = 1
INITIALIZE = 2
RUNNING = 3
class Agent(BaseAgent):
def __init__(self, name, team, index):
self.game = Game(index, team)
self.controls = SimpleControllerState()
self.timer = 0.0
self.timeout = 3.0
self.action = None
self.state = State.RESET
def get_output(self, packet: GameTickPacket) -> SimpleControllerState:
self.game.read_game_information(packet,
self.get_rigid_body_tick(),
self.get_field_info())
self.controls = SimpleControllerState()
next_state = self.state
if self.state == State.RESET:
self.timer = 0.0
# put the car in the middle of the field
car_state = CarState(physics=Physics(
location=Vector3(0, 0, 18),
velocity=Vector3(0, 0, 0),
rotation=Rotator(0, 0, 0),
angular_velocity=Vector3(0, 0, 0)
), jumped=False, double_jumped=False)
theta = random.uniform(0, 6.28)
pos = Vector3(sin(theta) * 1000.0, cos(theta) * 1000.0, 100.0)
# put the ball somewhere out of the way
ball_state = BallState(physics=Physics(
location=pos,
velocity=Vector3(0, 0, 0),
rotation=Rotator(0, 0, 0),
angular_velocity=Vector3(0, 0, 0)
))
self.set_game_state(GameState(
ball=ball_state,
cars={self.game.id: car_state})
)
next_state = State.WAIT
if self.state == State.WAIT:
if self.timer > 0.2:
next_state = State.INITIALIZE
if self.state == State.INITIALIZE:
self.action = Wavedash(self.game.my_car)
self.action.direction = vec2(self.game.ball.location)
next_state = State.RUNNING
if self.state == State.RUNNING:
self.action.step(self.game.time_delta)
self.controls = self.action.controls
if self.timer > self.timeout:
next_state = State.RESET
self.timer += self.game.time_delta
self.state = next_state
return self.controls
| [
"samuelpmish@users.noreply.github.com"
] | samuelpmish@users.noreply.github.com |
f5f1da26faa4e650ada80ce5c30d5f930a184396 | 0631e8234c7abeaa2e613107d2719e8254ccae43 | /djclass/products/migrations/0002_product_featured.py | 296ff441bb06be61645f2fa1630edb21cd540ffc | [] | no_license | raj356/django_files | 5e8d348c68c387e26ca8a3e99c8b66d46aa8a975 | 5767b59b2f3b703c41c1096e38601dc462bf0755 | refs/heads/master | 2023-02-03T22:14:01.225837 | 2020-12-20T15:19:12 | 2020-12-20T15:19:12 | 323,099,333 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 415 | py | # Generated by Django 3.1.4 on 2020-12-15 15:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='product',
name='featured',
field=models.BooleanField(default=True),
preserve_default=False,
),
]
| [
"rajarshi356@gmail.com"
] | rajarshi356@gmail.com |
cc6016e65e7b3e125b87d996e95b98ff5f2a1e52 | c17ca7a7824056f7ad58d0f71abc25670b20c1fc | /spirit/urls/admin/__init__.py | 1bc65e9f0daf9e9e944ad49a9811b0f1d6942c43 | [
"Apache-2.0"
] | permissive | Si-elegans/Web-based_GUI_Tools | cd35b72e80aa400105593c5c819355437e204a81 | 58a9b7a76bc46467554192a38ff5329a94e2b627 | refs/heads/master | 2023-01-11T09:11:21.896172 | 2017-07-18T11:10:31 | 2017-07-18T11:10:31 | 97,445,306 | 3 | 1 | Apache-2.0 | 2022-12-26T20:14:59 | 2017-07-17T07:03:13 | JavaScript | UTF-8 | Python | false | false | 536 | py | #-*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^$', 'spirit.views.admin.index.dashboard', name='admin'),
url(r'^index/', include('spirit.urls.admin.index')),
url(r'^category/', include('spirit.urls.admin.category')),
url(r'^comment/flag/', include('spirit.urls.admin.comment_flag')),
url(r'^config/', include('spirit.urls.admin.config')),
url(r'^topic/', include('spirit.urls.admin.topic')),
url(r'^user/', include('spirit.urls.admin.user')),
) | [
"gepelde@vicomtech.org"
] | gepelde@vicomtech.org |
cdb24bf3e5c486628f5ca536771e2238b5d47169 | 5c8b736497fda2ca0d476e298ea3b1adeb079712 | /venv/Scripts/pip3-script.py | 3702aebd4d3ad0afa26d86768f92ca15ed7f7c7e | [] | no_license | PrinceSnow/Comment-analysis | 7ba59193bfe94e49a9bbf55e36c6e20f2865a341 | 099536ff84c30a29c290aeb44409397f360ee40a | refs/heads/master | 2022-11-22T20:55:39.712265 | 2020-07-16T06:05:52 | 2020-07-16T06:05:52 | 279,182,674 | 0 | 0 | null | 2020-07-16T06:05:54 | 2020-07-13T01:46:00 | null | UTF-8 | Python | false | false | 405 | py | #!D:\PythonProj\Comment_analysis\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip3'
__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')()
)
| [
"50870271+EvanHung0957@users.noreply.github.com"
] | 50870271+EvanHung0957@users.noreply.github.com |
ce83f6f21d196ee7f74d5c34853bb6f269f035e1 | 11fa5d961dde172a402078cfdf7c2955baa4d818 | /app/resolvers/SpecialShiftResolver.py | bae1e0875046218b5d1448f30ae7e4a8e235ba48 | [] | no_license | Perciva/AM-BackEnd | 3763c062fa536d06d3b6700837301797f22bab68 | a3f7df98627ba5883a59fe94ca2e40765c38516f | refs/heads/master | 2023-05-10T21:26:56.883631 | 2021-01-22T09:56:34 | 2021-01-22T09:56:34 | 296,833,937 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 917 | py | from flask_jwt_extended import jwt_required
from app.model import special_shift
from app.database import query, mutation
@mutation.field("InsertSpecialShift")
@jwt_required
def insertSpecialShift(_, info, period_id, description, assistant_ids, date, _in, _out):
res = special_shift.insert(period_id, description, assistant_ids, date, _in, _out)
return res
@mutation.field("UpdateSpecialShift")
@jwt_required
def updateSpecialShift(_, info, id, period_id, description, assistant_ids, date, _in, _out):
res = special_shift.update(id,period_id, description, assistant_ids, date, _in, _out)
return res
@mutation.field("DeleteSpecialShift")
@jwt_required
def deleteSpecialShift(_, info, id):
return special_shift.delete(id)
@query.field("GetSpecialShiftByPeriodId")
@jwt_required
def getSpecialShiftByPeriodId(_, info, period_id):
return special_shift.getAllSpecialShiftByPeriodId(period_id)
| [
"stromchild@gmail.com"
] | stromchild@gmail.com |
1d8542da9fe05431ce0785b0c97e19b60e7aec39 | e15ec378360536d5215bf0f0a8fa9ab8a41ff6cc | /ch06/p6-3-1.py | 344f657d4d90d4170ca1d407f4091c37e6166324 | [] | no_license | michlin0825/book-mP21926 | 2ece5685ded2c913f51c830fd6f3280b8394646f | 5c4ebd828e593efd5fc7ba40bbcf606babd52640 | refs/heads/main | 2023-01-02T05:48:49.832014 | 2020-10-12T02:22:21 | 2020-10-12T02:22:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 433 | py | from selenium import webdriver
from bs4 import BeautifulSoup
import time
url = 'https://www.cwb.gov.tw/V8/C/W/OBS_County.html?ID=menu'
web = webdriver.Chrome('chromedriver.exe')
web.implicitly_wait(60)
web.get(url)
html = web.page_source
web.quit()
soup = BeautifulSoup(html, 'html.parser')
target = soup.select('#County option')
counties = list()
for item in target:
counties.append((item.text,item['value']))
print(counties)
| [
"skynet.tw@gmail.com"
] | skynet.tw@gmail.com |
a034cf0fc8738440a76859b08612f7ffa557a93f | 8a3970cec4bb399d7d0e152ac231b2e96d92b3c8 | /gustavo_saibro_fullstack/gustavo_saibro_fullstack/wsgi.py | 6dd29b9ea6b88f4bf2645eb787ef50b25746cd02 | [] | no_license | GustavoSaibro/gustavo_saibro_fullstack | 3b4ddef0945321c60ffb9270a03994b6623a96f0 | 65303619a8a63b2e5b6dd9091f9e3c5ef632dd96 | refs/heads/master | 2023-03-15T19:00:57.685874 | 2022-05-28T21:42:12 | 2022-05-28T21:42:12 | 248,352,323 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 425 | py | """
WSGI config for gustavo_saibro_fullstack project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gustavo_saibro_fullstack.settings')
application = get_wsgi_application()
| [
"gustavosaibro@gmail.com"
] | gustavosaibro@gmail.com |
fccbacc18d223c61e0780580353eff33ebd3f0ba | e34c465d880cd034084f4fa0eab0f0e3f387f181 | /blockcerts/issuer/tests/test_no_fs.py | 8d06e1204975c60c0a0ff84871c77a6ae0a80b1e | [
"MIT"
] | permissive | docknetwork/verifiable-claims-engine | f70ad3f45642b881b8e71dc09f1ca2cbd91c2759 | 1aab94510f421ce131642b64aefcd9a21c888f23 | refs/heads/master | 2023-05-14T13:48:01.713818 | 2020-04-30T17:01:55 | 2020-04-30T17:01:55 | 212,443,879 | 6 | 2 | MIT | 2023-05-01T20:18:59 | 2019-10-02T21:22:41 | Python | UTF-8 | Python | false | false | 1,487 | py | from cert_issuer.simple import SimplifiedCertificateBatchIssuer
def test_simplfied_issuing_process(config, unsigned_certs, write_private_key_file):
"""Please note this test actually anchors to Ropsten so you need internet access and funds in the given account."""
simple_certificate_batch_issuer = SimplifiedCertificateBatchIssuer(config, unsigned_certs)
tx_id, signed_certs = simple_certificate_batch_issuer.issue()
one_cert_id = list(signed_certs.keys())[0]
merkle_root = signed_certs[one_cert_id]['signature']['merkleRoot']
print(f'Check https://ropsten.etherscan.io/tx/{tx_id} to confirm it contains the merkle root "{merkle_root}"')
assert tx_id
assert merkle_root == 'cffe57bac8b8f47df9f5bb89e88dda893774b45b77d6600d5f1836d309505b61'
def test_simplfied_issuing_process_with_private_key(config_priv, unsigned_certs):
"""Please note this test actually anchors to Ropsten so you need internet access and funds in the given account."""
simple_certificate_batch_issuer = SimplifiedCertificateBatchIssuer(config_priv, unsigned_certs)
tx_id, signed_certs = simple_certificate_batch_issuer.issue()
one_cert_id = list(signed_certs.keys())[0]
merkle_root = signed_certs[one_cert_id]['signature']['merkleRoot']
print(f'Check https://ropsten.etherscan.io/tx/{tx_id} to confirm it contains the merkle root "{merkle_root}"')
assert tx_id
assert merkle_root == 'cffe57bac8b8f47df9f5bb89e88dda893774b45b77d6600d5f1836d309505b61'
| [
"faustow@gmail.com"
] | faustow@gmail.com |
f4c696c10ebd246b29c37bd67aaea8363dd48954 | 8da0e308d81aac676a81135c689f0236f0272b03 | /product/migrations/0015_auto_20190819_1900.py | 230ea454881aa1cbb9ac747ed211a47345f96a29 | [] | no_license | antodasns/Billingsoftware | 7b7b3e20ce0e1aabf3e7ff403200621dc764fe51 | 0c3679dd04995a40cc69c7d1ce9dd0211af72bf1 | refs/heads/master | 2023-06-26T21:07:19.043851 | 2021-07-24T08:54:39 | 2021-07-24T08:54:39 | 275,405,911 | 3 | 2 | null | null | null | null | UTF-8 | Python | false | false | 671 | py | # Generated by Django 2.2.3 on 2019-08-19 13:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0014_auto_20190817_1803'),
]
operations = [
migrations.AddField(
model_name='products',
name='wholesale_taxable_price',
field=models.CharField(default=1, max_length=50),
preserve_default=False,
),
migrations.AddField(
model_name='sub_products',
name='wholesale_taxable_price',
field=models.CharField(default=1, max_length=50),
preserve_default=False,
),
]
| [
"antodasanto@gmail.com"
] | antodasanto@gmail.com |
bdee7a9b276dbab681b2b2f56a3625e1ec9ed2e6 | 97a6e0f135a664bb5b346d15aa1be4ca67427c28 | /conftest.py | 833acc6fd43dd04ac4142a2ffabc07630cc928d1 | [] | no_license | TerekhovaIS/-FinalProject | f0fbe46acbe1999ff41fdb1f7554dc192a504b86 | 424e116086a4eb1b877b4eb7ac1b3c5d8d557ee5 | refs/heads/main | 2023-02-03T05:09:44.831436 | 2020-12-11T07:37:54 | 2020-12-11T07:37:54 | 319,936,770 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,239 | py | import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def pytest_addoption(parser):
parser.addoption('--browser_name', action='store', default="chrome", \
help="Choose browser: chrome or firefox")
parser.addoption('--language', action='store', default="ru", \
help="Choose language: ru or es")
@pytest.fixture(scope="function")
def browser(request):
browser_name = request.config.getoption("browser_name")
user_language = request.config.getoption("language")
if browser_name == "chrome":
options = Options()
options.add_experimental_option('prefs', \
{'intl.accept_languages': user_language})
print("\nstart chrome browser for test..")
browser = webdriver.Chrome(options=options)
elif browser_name == "firefox":
fp = webdriver.FirefoxProfile()
fp.set_preference("intl.accept_languages", user_language)
print("\nstart firefox browser for test..")
browser = webdriver.Firefox(firefox_profile=fp)
else:
raise pytest.UsageError("--browser_name should be chrome or firefox")
yield browser
print("\nquit browser..")
browser.quit()
| [
"noreply@github.com"
] | TerekhovaIS.noreply@github.com |
723292723f887ac195ee2242bc1ad6e79d39864f | 22eb1412d09e5f042d854db0ef40c643fad114f1 | /module_1/1_6_3.py | a6d3b7f1bc024a08f4463cf568654e5437f46516 | [] | no_license | semennikova09/Stepik_Autotest | 4038799aec3e9a1508999c04692cfe163487ce18 | ffbbbd29260a29fb654c9206161ae0635ab80b0d | refs/heads/master | 2022-12-20T23:15:08.654810 | 2020-10-01T08:32:29 | 2020-10-01T08:32:29 | 297,413,360 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 413 | py | from selenium import webdriver
import time
try:
browser = webdriver.Chrome()
browser.get("http://suninjuly.github.io/huge_form.html")
elements = browser.find_elements_by_css_selector("input")
for element in elements:
element.send_keys("Мой ответ")
button = browser.find_element_by_css_selector("button.btn")
button.click()
finally:
time.sleep(30)
browser.quit()
| [
"semennikova09@gmail.com"
] | semennikova09@gmail.com |
2641b7996ae263eba11eb3e44f40fb1baa200106 | e72014a1dc8efc6d63c97480eee82e5cbd083c05 | /maps/samples/soundsamples.py | c8c6def48c5b03e58b554e1bcc5ea3e1fa14c29d | [] | no_license | bastibe/Dissertation-Website | 0cc1cc3dfed61d7681ad928d841c04e10432d2f8 | f415735005d8f079b06d461d5f32904f600613f1 | refs/heads/master | 2023-07-09T20:54:27.922234 | 2021-02-14T09:19:20 | 2021-02-14T09:23:29 | 274,396,364 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,428 | py | import json
import numpy
import soundfile
from tqdm import tqdm
from evaluation import db, create_test_signal, get_true_base_frequency, pesto_experiment
samplerate = 48000
noise = {'cafeteria': 'CAFE-CAFE-1.au',
'traffic': 'STREET-CITY-1.au',
'car': 'CAR-WINDOWNB-1.au'}
speech = {'male1': 'mic_M01_si629.au',
'male2': 'mic_M02_sx77.au',
'female1': 'mic_F01_si499.au',
'female2': 'mic_F02_si671.au'}
for k, v in list(noise.items()):
noise[k] = db.find({'filename': v})[0]['_id']
for k, v in list(speech.items()):
speech[k] = db.find({'filename': v})[0]['_id']
noise['white'] = 'white noise'
tracks = {}
for snr in tqdm([40, 35, 30, 25, 20, 15, 10, 5, 0, -5, -10, -15, -20]):
for noisename, noiseid in noise.items():
for speechname, speechid in speech.items():
signal = create_test_signal(speechid, noiseid, 10*60, snr, samplerate)
filename = speechname + noisename + str(snr) + '.wav'
soundfile.write(filename, signal, samplerate)
true_f, true_t = get_true_base_frequency(speechid)
est_t, est_f, est_p = pesto_experiment(signal, samplerate)
est_f[est_p < 0.5] = 0
tracks[filename] = {'true_t': list(true_t), 'true_f': list(true_f),
'est_t': list(est_t), 'est_f': list(est_f)}
with open('tracks.json', 'w') as f:
json.dump(tracks, f)
| [
"basti@bastibe.de"
] | basti@bastibe.de |
8892c52bc5ad86a71bf3b85f12c69434c17512b6 | 2aa4c5fc960c5c05b6ef9891fd7ae85e5e38ac57 | /municipal_finance/models/municipal_staff_contacts.py | 9ffc675ea0fca3dd670d33414ba09cbbb1793568 | [
"MIT"
] | permissive | OpenUpSA/municipal-data | 4a4e8239f41bc179705f8858c82f15246160ba90 | 21ee3a4cf3614ac1fe32ff730843a238f39e1f40 | refs/heads/master | 2023-08-30T23:52:45.924118 | 2023-08-23T13:33:55 | 2023-08-23T13:33:55 | 55,236,579 | 24 | 15 | MIT | 2023-09-14T14:12:18 | 2016-04-01T14:01:37 | JavaScript | UTF-8 | Python | false | false | 533 | py |
from django.db import models
class MunicipalStaffContacts(models.Model):
id = models.AutoField(primary_key=True)
demarcation_code = models.TextField()
role = models.TextField()
title = models.TextField(null=True)
name = models.TextField(null=True)
office_number = models.TextField(null=True)
fax_number = models.TextField(null=True)
email_address = models.TextField(null=True)
class Meta:
db_table = "municipal_staff_contacts"
unique_together = (("demarcation_code", "role"),)
| [
"juriejanbotha@gmail.com"
] | juriejanbotha@gmail.com |
d0ce9c03d795884a1f9214122612ef6f4cfeb11f | 127c47e0b57a9a56adf666b8c8578110292f608a | /pyvista/core/pyvista_ndarray.py | 22613d469deabd87a889028062d9ef0583e9f267 | [
"MIT"
] | permissive | condoratberlin/pyvista | b6a1358971ff39b42e5bae40e02d54f2b4e7ee5c | c102f1a0f1e3aa9177b100659c41e48efff03a02 | refs/heads/main | 2023-08-22T12:19:46.436003 | 2021-10-26T12:53:01 | 2021-10-26T12:53:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,739 | py | """Contains pyvista_ndarray a numpy ndarray type used in pyvista."""
from collections.abc import Iterable
from typing import Union
import numpy as np
from pyvista import _vtk
from pyvista.utilities.helpers import FieldAssociation, convert_array
class pyvista_ndarray(np.ndarray):
"""An ndarray which references the owning dataset and the underlying vtkArray."""
def __new__(cls, array: Union[Iterable, _vtk.vtkAbstractArray], dataset=None,
association=FieldAssociation.NONE):
"""Allocate the array."""
if isinstance(array, Iterable):
obj = np.asarray(array).view(cls)
elif isinstance(array, _vtk.vtkAbstractArray):
obj = convert_array(array).view(cls)
obj.VTKObject = array
else:
raise TypeError(f'pyvista_ndarray got an invalid type {type(array)}. '
'Expected an Iterable or vtk.vtkAbstractArray')
obj.association = association
obj.dataset = _vtk.vtkWeakReference()
if isinstance(dataset, _vtk.VTKObjectWrapper):
obj.dataset.Set(dataset.VTKObject)
else:
obj.dataset.Set(dataset)
return obj
def __array_finalize__(self, obj):
"""Finalize array (associate with parent metadata)."""
# this is necessary to ensure that views/slices of pyvista_ndarray
# objects stay associated with those of their parents.
#
# the VTKArray class uses attributes called `DataSet` and `Assocation`
# to hold this data. I don't know why this class doesn't use the same
# convention, but here we just map those over to the appropriate
# attributes of this class
_vtk.VTKArray.__array_finalize__(self, obj)
if np.shares_memory(self, obj):
self.dataset = getattr(obj, 'dataset', None)
self.association = getattr(obj, 'association', FieldAssociation.NONE)
self.VTKObject = getattr(obj, 'VTKObject', None)
else:
self.dataset = None
self.association = FieldAssociation.NONE
self.VTKObject = None
def __setitem__(self, key: int, value):
"""Implement [] set operator.
When the array is changed it triggers "Modified()" which updates
all upstream objects, including any render windows holding the
object.
"""
super().__setitem__(key, value)
if self.VTKObject is not None:
self.VTKObject.Modified()
# the associated dataset should also be marked as modified
dataset = self.dataset
if dataset is not None and dataset.Get():
dataset.Get().Modified()
__getattr__ = _vtk.VTKArray.__getattr__
| [
"noreply@github.com"
] | condoratberlin.noreply@github.com |
f6178d7d92c115ee3e13dce1dde047e198787a78 | adc733a6f58bdea5c891653c154231d587c81a18 | /test_cifar10.py | 643c8099447d25d4be59e5fc208e9bbc7869ad6c | [] | no_license | hj-hejie/hj-speech-commands | a586a91ad091bbe339a41979e76027b30228de28 | 96b5be0dabdc974f8233cbed2c8e955a48bf2a10 | refs/heads/master | 2020-03-24T20:42:29.949370 | 2019-06-24T02:16:06 | 2019-06-24T02:16:06 | 142,992,821 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,880 | py | #!/usr/bin/env python
"""Test a pretrained CNN for CIFAR10."""
__author__ = 'Yuan Xu, Erdene-Ochir Tuguldur'
import argparse
import time
from tqdm import *
import torch
from torch.autograd import Variable
from torch.utils.data import DataLoader
import torchvision
from torchvision.transforms import *
import torchnet
import models
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--dataset-root", type=str, default='./datasets', help='path of train dataset')
parser.add_argument("--test-batch-size", type=int, default=100, help='test batch size')
parser.add_argument("--dataload-workers-nums", type=int, default=2, help='number of workers for dataloader')
parser.add_argument("model", help='a pretrained neural network model')
args = parser.parse_args()
print("loading model...")
model = torch.load(args.model)
model.float()
use_gpu = torch.cuda.is_available()
print('use_gpu', use_gpu)
if use_gpu:
torch.backends.cudnn.benchmark = True
model.cuda()
to_tensor_and_normalize = Compose([
ToTensor(),
Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
test_dataset = torchvision.datasets.CIFAR10(root=args.dataset_root, train=False, download=True, transform=to_tensor_and_normalize)
test_dataloader = DataLoader(test_dataset, batch_size=args.test_batch_size, shuffle=False, num_workers=args.dataload_workers_nums)
CLASSES = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
criterion = torch.nn.CrossEntropyLoss()
def test():
model.eval() # Set model to evaluate mode
running_loss = 0.0
it = 0
correct = 0
total = 0
confusion_matrix = torchnet.meter.ConfusionMeter(len(CLASSES))
pbar = tqdm(test_dataloader, unit="images", unit_scale=test_dataloader.batch_size)
for batch in pbar:
inputs, targets = batch
inputs = Variable(inputs, volatile = True)
targets = Variable(targets, requires_grad=False)
if use_gpu:
inputs = inputs.cuda()
targets = targets.cuda(async=True)
# forward
outputs = model(inputs)
loss = criterion(outputs, targets)
# statistics
running_loss += loss.data[0]
it += 1
pred = outputs.data.max(1, keepdim=True)[1]
correct += pred.eq(targets.data.view_as(pred)).sum()
total += targets.size(0)
confusion_matrix.add(pred, targets.data)
# update the progress bar
pbar.set_postfix({
'loss': "%.05f" % (running_loss / it),
'acc': "%.02f%%" % (100*correct/total)
})
accuracy = correct/total
epoch_loss = running_loss / it
print("accuracy: %f%%, loss: %f" % (100*accuracy, epoch_loss))
print("confusion matrix:")
print(confusion_matrix.value())
print("testing...")
test()
| [
"tugstugi@gmail.com"
] | tugstugi@gmail.com |
0c826b71c27b17e526b9807cbca19ce674539404 | b57d337ddbe946c113b2228a0c167db787fd69a1 | /scr/py00468notices.py | c8f23c8ddfd5182e7ed018cb580fa0c212a0c0c1 | [] | no_license | aademchenko/ToEE | ebf6432a75538ae95803b61c6624e65b5cdc53a1 | dcfd5d2de48b9d9031021d9e04819b309d71c59e | refs/heads/master | 2020-04-06T13:56:27.443772 | 2018-11-14T09:35:57 | 2018-11-14T09:35:57 | 157,520,715 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,612 | py | from toee import *
from utilities import *
import _include
from co8Util.TimedEvent import *
from combat_standard_routines import *
from py00439script_daemon import get_f, set_f, get_v, set_v, tpsts, record_time_stamp
def san_use( attachee, triggerer ):
if (attachee.name == 11063):
game.quests[110].state = qs_mentioned
game.new_sid = 0
elif (attachee.name == 11064):
game.quests[90].state = qs_mentioned
game.new_sid = 0
elif (attachee.name == 11065):
game.quests[111].state = qs_mentioned
game.new_sid = 0
elif (attachee.name == 11066):
game.quests[112].state = qs_mentioned
game.new_sid = 0
elif (attachee.name == 11067):
game.quests[108].state = qs_mentioned
game.global_vars[939] = 1
game.new_sid = 0
elif (attachee.name == 11068):
if (game.quests[97].state != qs_botched):
game.quests[97].state = qs_botched
if (game.party[0].reputation_has(53) == 0):
game.party[0].reputation_add( 53 )
game.global_vars[510] = 2
game.global_flags[504] = 1
game.new_sid = 0
elif (attachee.name == 11069):
triggerer.money_adj(-10000)
attachee.destroy()
elif (attachee.name == 11070):
game.quests[106].state = qs_mentioned
game.new_sid = 0
elif (attachee.name == 11071):
game.quests[95].state = qs_completed
game.new_sid = 0
elif (attachee.name == 11072):
game.quests[105].state = qs_mentioned
set_bethany()
game.new_sid = 0
elif (attachee.name == 11073):
game.quests[105].state = qs_mentioned
set_bethany()
game.new_sid = 0
return RUN_DEFAULT
def set_bethany():
game.encounter_queue.append(3447)
set_f('s_bethany_scheduled')
return RUN_DEFAULT | [
"demchenko.recruitment@gmail.com"
] | demchenko.recruitment@gmail.com |
4981a7e806be3173914d83131e900e93b70cefac | c89f5856fe74cff49a9d96dde9ed0117109e3845 | /A-bit-of-py/exceptions_raise.py | 18c685701366068a4acd2f51c1194d541cbb8930 | [] | no_license | sinoclover/python | b2b3f435d15840ec16a34c62d50308bdfb9d6c3e | 02f5347bc8219f1df52486077adf0017fe6d5211 | refs/heads/master | 2020-08-27T22:14:20.672846 | 2019-12-01T13:27:42 | 2019-12-01T13:27:42 | 158,791,898 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 647 | py | # encoding=UTF-8
class ShortInputException(Exception):
'''一个由用户定义的异常类'''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
text = input('Enter something --> ')
if len(text) < 3:
raise ShortInputException(len(text), 3)
# 其他工作能在此处继续正常运行
except EOFError:
print('Why did you do an EOF on me?')
except ShortInputException as ex:
print(('ShortInputException: The input was {0} long, expected at least {1}').format(ex.length, ex.atleast))
else:
print('No exception was raised') | [
"zzxy123007@163.com"
] | zzxy123007@163.com |
4fc31a6ff5a7263512d12b5b20ad20f35c45dff3 | 2c510687bdc03fbb8383130e68cc796bfef1088c | /3_basic_ds/exercises.py | 328dff7335a429dab792cb7b5a6f8adc62aeda37 | [] | no_license | jimjshields/pswads | 59758a0972fe71ca6f77305ff8ab86673d9b5d46 | 9568622805e24416f4a227cbecc1ef4927fa7ba3 | refs/heads/master | 2016-09-06T12:37:53.254464 | 2015-02-17T02:13:00 | 2015-02-17T02:13:00 | 30,149,564 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,772 | py | # Chapter 3 Programming Exercises
# Skip all pre-/post-/infix questions; not worth the time.
# Also skip any 'experiment' questions. Maybe come back to them.
# 5. Implement the Queue ADT, using a list such that the rear of the queue is at the end of the list.
class Queue(object):
"""Represents a queue ADT. The rear of the queue is the end of the list used.
Necessary methods: enqueue, dequeue, size, is_empty."""
def __init__(self):
"""Initializes an empty queue using a list."""
self.items = []
def enqueue(self, item):
"""Adds an item to the rear of the queue."""
self.items.append(item)
def dequeue(self):
"""Removes and returns an item from the front of the queue."""
return self.items.pop(0)
def size(self):
"""Returns the number of items in the queue."""
return len(self.items)
def is_empty(self):
"""Checks whether the queue has no items."""
return self.items == []
# q = Queue()
# q.enqueue(1)
# q.enqueue(2)
# q.enqueue(3)
# q.enqueue(4)
# q.enqueue(5)
# print q.items
# print q.dequeue()
# print q.dequeue()
# print q.dequeue()
# print q.dequeue()
# print q.dequeue()
# print q.is_empty()
# 7. It is possible to implement a queue such that both enqueue and dequeue have O(1) performance on average. In this case it means that most of the time enqueue and dequeue will be O(1) except in one particular circumstance where dequeue will be O(n).
class Queue_2(object):
"""Represents a queue ADT with O(1) enqueue and dequeue time on average."""
def __init__(self):
"""Initializes an empty queue with a list.
Also initializes the dequeue variable for O(1) access time."""
self.items = []
self.to_be_dequeued = ''
def enqueue(self, item):
self.items.append(item)
self.to_be_dequeued = self.items[0]
| [
"jim.j.shields@gmail.com"
] | jim.j.shields@gmail.com |
e103e52c8d1db2ceda089eb62bb3d134391fee80 | 102a33464fd3a16ceedd134e9c64fea554ca5273 | /apps/config/models.py | 39260020ed66b83fc8e77d4bf08ecae9ee053a6b | [] | no_license | pythonguru101/django-ecommerce | b688bbe2b1a53c906aa80f86f764cf9787e6c2fe | f94de9c21223716db5ffcb86ba87219da88d2ff4 | refs/heads/master | 2020-07-24T14:57:02.047702 | 2020-06-10T06:06:23 | 2020-06-10T06:06:23 | 207,961,132 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,658 | py | # encoding: utf-8
from django.db import models
from django.utils.translation import ugettext as _
class ConfigAbstractManager(models.Manager):
def get_config(self):
try:
return self.get(pk=1)
except self.model.DoesNotExist:
return {}
class ConfigAbstract(models.Model):
text_main_bot = models.TextField(_(u'текст на главной внизу'), blank=True)
phone = models.CharField(_(u'номер телефона'), max_length=32, blank=True)
email = models.EmailField(_(u'email'), blank=True)
title_page = models.CharField(_(u'заголовок страницы'), max_length=140,
blank=True)
meta_keywords = models.CharField(_(u'meta keywords'), max_length=200,
blank=True)
meta_description = models.TextField(_(u'meta description'), blank=True)
yandex_verification = models.CharField(_(u'Yandex Verification'),
max_length=100, blank=True)
yml_name = models.CharField(_(u'YML: name'), max_length=250)
yml_email = models.EmailField(_(u'YML: email'))
yml_company = models.CharField(_(u'YML: company'), max_length=250)
objects = ConfigAbstractManager()
class Meta:
abstract = True
verbose_name = _(u'настройки')
verbose_name_plural = _(u'настройки')
def __unicode__(self):
return u'настройки'
def save(self, *args, **kwargs):
self.pk = 1
return super(ConfigAbstract, self).save(*args, **kwargs)
class ConfigManagerManager(models.Manager):
def get_emails(self):
return [m['email'] for m in self.values('email')]
class Config(ConfigAbstract):
title_blog = models.CharField(_(u'заголовок блога'), max_length=140,
blank=True)
facebook_app_id = models.CharField(_(u'FaceBook App ID'), max_length=100,
blank=True)
afrek_id = models.CharField(_(u'Партнёрка afrek.ru'), max_length=100,
blank=True)
class ConfigManager(models.Model):
config = models.ForeignKey(Config,
verbose_name=_(u'менеджер'), on_delete=models.CASCADE)
name = models.CharField(_(u'имя'), max_length=100)
email = models.EmailField(_(u'email'))
objects = ConfigManagerManager()
class Meta:
verbose_name = _(u'менеджер')
verbose_name_plural = _(u'менеджеры')
def __unicode__(self):
return "%s <%s>" % (self.name, self.email)
| [
"pythonguru101@gmail.com"
] | pythonguru101@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.