blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 281 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2
values | repo_name stringlengths 6 116 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 313
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 18.2k 668M ⌀ | star_events_count int64 0 102k | fork_events_count int64 0 38.2k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 107
values | src_encoding stringclasses 20
values | language stringclasses 1
value | is_vendor bool 2
classes | is_generated bool 2
classes | length_bytes int64 4 6.02M | extension stringclasses 78
values | content stringlengths 2 6.02M | authors listlengths 1 1 | author stringlengths 0 175 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7a9a4729ecfc4018368aacf4a7eb92916cf59270 | 2d83e3a54242e4683f469dd2f6f691f2eea41ff7 | /sc2/play_collect_and_destroy.py | 437805a9276c1e010b555041b090c230e8e4a5f3 | [] | no_license | JIElite/pysc2-A3C | 0d0ae13b64b32b1ef0c53d720ec4c8fb89bb7697 | eb3d629ce3b175d5eb328e8a4f43e39b190fb579 | refs/heads/master | 2023-07-02T06:09:40.725595 | 2021-08-05T18:03:46 | 2021-08-05T18:03:46 | 124,791,245 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,995 | py | from itertools import count
import time
import sys
import os
os.environ['OMP_NUM_THREADS']='1' #???
from absl import app, flags
from pysc2.env import sc2_env
from pysc2.lib import actions, features
from envs import create_pysc2_env, GameInterfaceHandler
import numpy as np
import torch
from torch.autograd import Variable
from model2 import (
CollectAndDestroyGraftingNet,
CollectAndDestroyGraftingDropoutNet,
CollectAndDestroyGraftingDropoutNetConv4,
CollectAndDestroyGraftingDropoutNetConv6,
CollectAndDestroyBaseline,
CollectAndDestroyGraftingDropoutNetBN
)
FLAGS = flags.FLAGS
# Game related settings
flags.DEFINE_string("map", "CollectAndDestroyAirSCV", "Name of a map to use.")
flags.DEFINE_integer("screen_resolution", 48, "Resolution for screen feature layers.")
flags.DEFINE_integer("minimap_resolution", 48, "Resolution for minimap feature layers.")
flags.DEFINE_bool("visualize", False, "Whether to render with pygame.")
flags.DEFINE_integer("step_mul", 8, "Game steps per agent step.")
flags.DEFINE_enum("agent_race", None, sc2_env.races.keys(), "Agent's race.")
flags.DEFINE_enum("bot_race", None, sc2_env.races.keys(), "Bot's race.")
flags.DEFINE_integer('max_eps_length', 5000, "max length run for each episode")
# Learning related settings
flags.DEFINE_float("gamma", 0.99, "Discount rate for future rewards.")
flags.DEFINE_integer("n_steps", 8, "How many steps do we compute the Return (TD)")
flags.DEFINE_integer("num_episodes", 100, "# of episode for agent to play with environment")
flags.DEFINE_integer("seed", 5, "torch random seed")
flags.DEFINE_integer("gpu", 0, "gpu device")
flags.DEFINE_integer("version", 0, "version of network")
flags.DEFINE_integer('transfer', 0, 'transfer module type')
FLAGS(sys.argv)
# PySC2 actions
_NO_OP = actions.FUNCTIONS.no_op.id
_MOVE_SCREEN = actions.FUNCTIONS.Move_screen.id
_SELECT_POINT = actions.FUNCTIONS.select_point.id
_RIGHT_CLICK = actions.FUNCTIONS.Smart_screen.id
# PySC2 features
_SCREEN_PLAYER_RELATIVE = features.SCREEN_FEATURES.player_relative.index
# torch.cuda.set_device(FLAGS.gpu)
torch.cuda.set_device(0)
print("CUDA device:", torch.cuda.current_device())
def main(argv):
torch.manual_seed(FLAGS.seed)
# build environment
env_args = {
'map_name': FLAGS.map,
'agent_race': FLAGS.agent_race,
'bot_race': FLAGS.bot_race,
'step_mul': FLAGS.step_mul,
'screen_size_px': [FLAGS.screen_resolution] * 2,
'minimap_size_px': [FLAGS.minimap_resolution] * 2,
'visualize': FLAGS.visualize,
}
env = create_pysc2_env(env_args)
game_inferface = GameInterfaceHandler(screen_resolution=FLAGS.screen_resolution,
minimap_resolution=FLAGS.minimap_resolution)
# model
if FLAGS.version == 0:
model = CollectAndDestroyGraftingNet
elif FLAGS.version == 1:
model = CollectAndDestroyGraftingDropoutNet
elif FLAGS.version == 2:
model = CollectAndDestroyGraftingDropoutNetBN
elif FLAGS.version == 3:
model = CollectAndDestroyBaseline
elif FLAGS.version == 4:
model = CollectAndDestroyGraftingDropoutNetConv6
print("model type:", model)
agent = model(screen_channels=8, screen_resolution=(FLAGS.screen_resolution, FLAGS.screen_resolution)).cuda()
# agent.load_state_dict(torch.load('./models/model_latest_test'))
agent.load_state_dict(torch.load('./models/model_latest_collect_and_destroy_air_scv_conv6_bn_wo_annealing_7'))
agent.train()
agent.dropout_rate = 0.95
# agent.eval()
print('---- load model successfully. ----')
total_eps_reward = 0
with env:
for i_episode in range(FLAGS.num_episodes):
env.reset()
state = env.step([actions.FunctionCall(_NO_OP, [])])[0]
episodic_reward = 0
for step in count(start=1):
screen_observation = Variable(torch.from_numpy(game_inferface.get_screen_obs(
timesteps=state,
indexes=[4, 5, 6, 7, 8, 9, 14, 15],
))).cuda()
select_unit_action_prob, value, selected_task = agent(screen_observation,
Variable(torch.zeros(1, 1, 48, 48).cuda()),
0)
# select unit
selection_mask = torch.from_numpy(
(state.observation['screen'][_SCREEN_PLAYER_RELATIVE] == 1).astype('float32'))
selection_mask = Variable(selection_mask.view(1, -1), requires_grad=False).cuda()
masked_select_unit_action_prob = select_unit_action_prob * selection_mask
if float(masked_select_unit_action_prob.sum().cpu().data.numpy()) < 1e-12:
masked_select_unit_action_prob += 1.0 * selection_mask
masked_select_unit_action_prob /= masked_select_unit_action_prob.sum()
else:
masked_select_unit_action_prob = masked_select_unit_action_prob / masked_select_unit_action_prob.sum()
try:
select_action = masked_select_unit_action_prob.multinomial()
except:
print("Error detect!")
print(masked_select_unit_action_prob)
# select task type
task = selected_task.multinomial()
action = game_inferface.build_action(_SELECT_POINT, select_action[0].cpu())
state = env.step([action])[0]
time.sleep(0.5)
if state.reward > 1:
reward = np.asscalar(np.array([10]))
else:
reward = np.asscalar(np.array([-0.2]))
episodic_reward += reward
episode_done = (step >= FLAGS.max_eps_length) or state.last()
if episode_done:
env.reset()
state = env.step([actions.FunctionCall(_NO_OP, [])])[0]
break
task = int(task.cpu().data.numpy())
if task == 0 and _MOVE_SCREEN in state.observation['available_actions']:
# collection mineral shards
screen_observation = Variable(torch.from_numpy(game_inferface.get_screen_obs(
timesteps=state,
indexes=[4, 5, 6, 7, 8, 9, 14, 15],
))).cuda()
spatial_action_prob, value, _ = agent(screen_observation,
Variable(torch.ones(1, 1, 48, 48)).cuda(), 1)
spatial_action = spatial_action_prob.multinomial()
action = game_inferface.build_action(_MOVE_SCREEN, spatial_action[0].cpu())
state = env.step([action])[0]
if state.reward > 1:
reward = np.asscalar(np.array([10]))
else:
reward = np.asscalar(np.array([-0.2]))
elif task == 1 and _RIGHT_CLICK in state.observation['available_actions']:
# destroy enemy's buildings
screen_observation = Variable(torch.from_numpy(game_inferface.get_screen_obs(
timesteps=state,
indexes=[4, 5, 6, 7, 8, 9, 14, 15],
))).cuda()
destroy_action_prob, value, _ = agent(screen_observation,
Variable(torch.ones(1, 1, 48, 48) * 2).cuda(), 2)
destroy_position = destroy_action_prob.multinomial()
action = game_inferface.build_action(_RIGHT_CLICK, destroy_position[0].cpu())
state = env.step([action])[0]
if state.reward > 1:
reward = np.asscalar(np.array([10]))
else:
reward = np.asscalar(np.array([-0.2]))
else:
action = actions.FunctionCall(_NO_OP, [])
state = env.step([action])[0]
if state.reward > 1:
reward = np.asscalar(np.array([10]))
else:
reward = np.asscalar(np.array([-0.2]))
time.sleep(0.5)
episodic_reward += reward
episode_done = (step >= FLAGS.max_eps_length) or state.last()
if episode_done:
env.reset()
state = env.step([actions.FunctionCall(_NO_OP, [])])[0]
break
print('eps reward:', episodic_reward)
total_eps_reward += episodic_reward
mean_performance = total_eps_reward / FLAGS.num_episodes
print("Mean performance:", mean_performance)
if __name__ == '__main__':
app.run(main)
| [
"ita3051@gmail.com"
] | ita3051@gmail.com |
d5193135b93cf859ce3b44e6c891377ec69c0b92 | 03dc4baef99521e6d4ed2ebc9473f0f7a69a2be9 | /tests/conftest.py | 6308f003359ab39927218feecd8666caa5fb35e2 | [
"MIT"
] | permissive | gregnwosu/test-dags-for-k8-airflow | a52dde84fff5fff8bc52622b9862d85cc0a6885b | 1be4920d10c059a0bd44e7ea0edf371f29833f7c | refs/heads/master | 2020-05-07T14:03:56.377271 | 2019-04-18T01:52:58 | 2019-04-18T01:52:58 | 180,576,092 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 267 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Dummy conftest.py for test_dags_for_k8_airflow.
If you don't know what this is for, just leave it empty.
Read more about conftest.py under:
https://pytest.org/latest/plugins.html
"""
# import pytest
| [
"greg.nwosu@gmail.com"
] | greg.nwosu@gmail.com |
4904b07f8f0ec2792882ee0298f1595dce8b5300 | e6db25851518940a4cc6d76bcfd8271d031111e5 | /app/__init__.py | ec69a65b46e0ea864156a794cb36d064d7060c2d | [] | no_license | Thovarantony/info3180-project-one | c85240e5f220a636ef4a2c3d6f34117cec84507c | 02d4da8f5717c3a1ce28afb0bd8d786af19f1806 | refs/heads/master | 2020-05-22T07:44:50.411875 | 2017-03-12T07:10:14 | 2017-03-12T07:10:14 | 84,681,552 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 132 | py | # coding=utf-8;
from flask import Flask
app = Flask(__name__)
app.config.from_pyfile('app.cfg', silent=True)
from app import views | [
"thovargreen@gmail.com"
] | thovargreen@gmail.com |
cbfd72141df5c97ba512dcef1a3443c614784429 | 67a65d28662aef0627628fd083e5049074c200c8 | /object oriented programming/Cash register2.py | b9e6a3f0094648e1ffae216428e5f9ac1e374101 | [] | no_license | techadddict/Python-programmingRG | 036e8e5b56e21006a2bca2a5bc7951768a0eba82 | dc9c561a655bde232b68de5fb8bfd82230ed49ee | refs/heads/master | 2021-01-23T22:30:50.231232 | 2018-04-20T21:39:21 | 2018-04-20T21:39:21 | 102,937,901 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,148 | py | ##Re-implement the CashRegister class so that it keeps track of each added item in the list.
##Remove the _itemCount and _totalPrice instance variables. Re-implement the clear,
##addItem, getTotal and getCount methods. Add a method displayAll that displays the
##prices of all items in the current sale
class CashREgister:
def __init__(self):
self.itemList=[]
def addItem(self,item):
self.itemList.append(item)
def getCount(self):
count= len(self.itemList)
return count
def getTotal(self):
sumList= sum(self.itemList)
return sumList
def displayAll(self):
for i in self.itemList:
print(i)
def clearList(self):
self.itemList=[]
myCashREgister=CashREgister()
myCashREgister.addItem(5.78)
myCashREgister.addItem(3.00)
myCashREgister.addItem(1.20)
myCashREgister.addItem(2.20)
myCashREgister.addItem(0.99)
print(myCashREgister.getCount())
print(myCashREgister.getTotal())
myCashREgister.displayAll()
myCashREgister.clearList()
print(myCashREgister.getCount())
print(myCashREgister.getTotal())
| [
"noreply@github.com"
] | noreply@github.com |
64ec3bc87b011adb9b0fbd4ed1e3dd342e321d5d | 1c4328ff0b9098051c3a2f67ef8fcd7baf95c7d4 | /gestionBD/admin.py | c5733c61dd17ad86cce09a8d0935679fe1263670 | [] | no_license | juanrjc97/ProyectoDistribuidos | 550d1a8be42b25ded73c21ff4dbd03e7bae0fa3e | cd128fdfa2a1c847b89bb7ebad8af4b2fef761c4 | refs/heads/master | 2022-12-05T02:12:46.027345 | 2020-08-24T17:05:26 | 2020-08-24T17:05:26 | 287,396,008 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 309 | py | from django.contrib import admin
from .models import usuario, sector, noticiaTip, puntoRecoleccion, horarioRecoleccion
# Register your models here.
myModels = [usuario, sector, noticiaTip, puntoRecoleccion, horarioRecoleccion] # iterable list
admin.site.register(myModels)
# admin.site.register(Usuarios)
| [
"juanj121297@gmail.com"
] | juanj121297@gmail.com |
ab39f51aadebf09c7fb9657f2cf2f829677b028c | 6821584af1068861f00732743574465519aa21a2 | /2017/10/python/soln.py | f85e9f9e5f290fbd1eb68989f0009ea559e9f7bf | [] | no_license | srfraser/adventofcode | d2c4c0dfede02c4762d0c9c74d11052aa3cd2512 | 6ef270fb5c9820dfe9055b3a2e9f0f5b581c9102 | refs/heads/master | 2023-02-04T21:28:03.226075 | 2020-12-19T17:58:44 | 2020-12-19T17:58:44 | 112,802,053 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,450 | py | import sys
import pytest
from operator import xor
from functools import reduce
@pytest.mark.parametrize('circle,position,length,expected', (
([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 0, 2, [1, 0, 2, 3, 4, 5, 6, 7, 8, 9]),
([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 5, 2, [0, 1, 2, 3, 4, 6, 5, 7, 8, 9]),
([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 5, 6, [5, 1, 2, 3, 4, 0, 9, 8, 7, 6]),
([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 5, 10, [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]),
))
def test_reverse(circle, position, length, expected):
assert reverse(circle, position, length) == expected
def reverse(circle, position, length):
rotate(circle, -position)
circle[0:length] = circle[0:length][::-1]
rotate(circle, position)
return circle
def rotate(lst, x):
lst[:] = lst[-x:] + lst[:-x]
def part1(data):
current_position = 0
skip_size = 0
circle = list(range(256))
for length in data:
circle = reverse(circle, current_position, length)
current_position = (current_position + length + skip_size) % len(circle)
skip_size += 1
print("circle[0] * circle[1] = {} * {} = {}".format(circle[0],
circle[1], circle[0] * circle[1]))
@pytest.mark.parametrize("data,expected", (
("", 'a2582a3a0e66e6e86e3812dcb672a272'),
("AoC 2017", "33efeb34ea91902bb2f59c9920caa6cd"),
("1,2,3", "3efbe78a8d82f29979031a4aa0b16a9d"),
("1,2,4", "63960835bcdc130f0b66d7ff4f6a5a8e")
))
def test_part2(data, expected):
assert part2(data) == expected
def part2(raw_data):
data = [ord(c) for c in raw_data]
# Arbitrary question data
data.extend([17, 31, 73, 47, 23])
current_position = 0
skip_size = 0
circle = list(range(256))
for _ in range(64):
for length in data:
circle = reverse(circle, current_position, length)
current_position = (current_position + length + skip_size) % len(circle)
skip_size += 1
# Create dense hash
dhash = list()
for chunk in range(0, 255, 16):
dhash.append(reduce(xor, circle[chunk:chunk + 16]))
return "".join(["{0:0{1}x}".format(d, 2) for d in dhash])
def main():
with open(sys.argv[1], 'r') as f:
raw_data = f.readline()
part1_data = [int(i) for i in raw_data.split(',')]
part1(part1_data)
result = part2(raw_data.strip())
print("Knot hash: {}".format(result))
if __name__ == '__main__':
main()
| [
"sfraser@mozilla.com"
] | sfraser@mozilla.com |
8f0e61f7f72d8acc85691fe034dcad892cd17838 | f1bf5b94f2c3108b022251f8043c9f252771c9fa | /yolov3/test.py | bcbbbf29a27c5dd114825e3bd4140dfcd5afb07f | [] | no_license | Luchixiang/dip_final | b942e2934e13a423dea76d0d8d246c48fccb4901 | 308f3af9c569fe08ae283735b8731bbbe4326fdc | refs/heads/master | 2020-12-02T05:11:39.665257 | 2019-12-30T11:03:59 | 2019-12-30T11:03:59 | 230,900,071 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,022 | py | from __future__ import division
from models import *
from utils.utils import *
from utils.datasets import *
from utils.parse_config import *
import os
import sys
import time
import datetime
import argparse
import tqdm
import torch
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision import transforms
from torch.autograd import Variable
import torch.optim as optim
def evaluate(model, path, iou_thres, conf_thres, nms_thres, img_size, batch_size):
model.eval()
# Get dataloader
dataset = ListDataset(path, img_size=img_size, augment=False, multiscale=False)
dataloader = torch.utils.data.DataLoader(
dataset, batch_size=batch_size, shuffle=False, num_workers=1, collate_fn=dataset.collate_fn
)
Tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor
labels = []
sample_metrics = [] # List of tuples (TP, confs, pred)
for batch_i, (_, imgs, targets) in enumerate(tqdm.tqdm(dataloader, desc="Detecting objects")):
# Extract labels
labels += targets[:, 1].tolist()
# Rescale target
targets[:, 2:] = xywh2xyxy(targets[:, 2:])
targets[:, 2:] *= img_size
imgs = Variable(imgs.type(Tensor), requires_grad=False)
with torch.no_grad():
outputs = model(imgs)
outputs = non_max_suppression(outputs, conf_thres=conf_thres, nms_thres=nms_thres)
sample_metrics += get_batch_statistics(outputs, targets, iou_threshold=iou_thres)
# Concatenate sample statistics
true_positives, pred_scores, pred_labels = [np.concatenate(x, 0) for x in list(zip(*sample_metrics))]
precision, recall, AP, f1, ap_class = ap_per_class(true_positives, pred_scores, pred_labels, labels)
return precision, recall, AP, f1, ap_class
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--batch_size", type=int, default=8, help="size of each image batch")
parser.add_argument("--model_def", type=str, default="config/yolov3.cfg", help="path to model definition file")
parser.add_argument("--data_config", type=str, default="config/coco.data", help="path to data config file")
parser.add_argument("--weights_path", type=str, default="weights/yolov3.weights", help="path to weights file")
parser.add_argument("--class_path", type=str, default="data/coco.names", help="path to class label file")
parser.add_argument("--iou_thres", type=float, default=0.5, help="iou threshold required to qualify as detected")
parser.add_argument("--conf_thres", type=float, default=0.001, help="object confidence threshold")
parser.add_argument("--nms_thres", type=float, default=0.5, help="iou thresshold for non-maximum suppression")
parser.add_argument("--n_cpu", type=int, default=8, help="number of cpu threads to use during batch generation")
parser.add_argument("--img_size", type=int, default=416, help="size of each image dimension")
opt = parser.parse_args()
print(opt)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
data_config = parse_data_config(opt.data_config)
valid_path = data_config["valid"]
class_names = load_classes(data_config["names"])
# Initiate model
model = Darknet(opt.model_def).to(device)
if opt.weights_path.endswith(".weights"):
# Load darknet weights
model.load_darknet_weights(opt.weights_path)
else:
# Load checkpoint weights
model.load_state_dict(torch.load(opt.weights_path))
print("Compute mAP...")
precision, recall, AP, f1, ap_class = evaluate(
model,
path=valid_path,
iou_thres=opt.iou_thres,
conf_thres=opt.conf_thres,
nms_thres=opt.nms_thres,
img_size=opt.img_size,
batch_size=8,
)
print("Average Precisions:")
for i, c in enumerate(ap_class):
print("+ Class '{}' ({}) - AP: {}".format(c,class_names[c],AP[i]))
print("mAP: {}".format(AP.mean()))
| [
"984335792@qq.com"
] | 984335792@qq.com |
e3e9ebff801a044b0319f8a61bbd6e8638abcdf5 | 921c6ff6f7f31e0349314bc40426fff12107a705 | /GeneralPython/DefDict.py | 6985b1ba9939e02bd1f4932358dbdac3512fb79c | [
"BSD-2-Clause"
] | permissive | prashantas/MyDataScience | 0828d5e443de9633fe1199ef4d13a7699b2ebffa | 8db4f288b30840161c6422bde7c7a7770f85c09d | refs/heads/master | 2021-06-02T12:06:45.609262 | 2019-04-25T03:03:25 | 2019-04-25T03:03:25 | 96,012,955 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,818 | py | ## https://www.accelebrate.com/blog/using-defaultdict-python/
'''
class collections.defaultdict([default_factory[, ...]])
Returns a new dictionary-like object. defaultdict is a subclass of the built-in dict class.
It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the dict class and is not documented here.
The first argument provides the initial value for the default_factory attribute; it defaults to None.
All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.
'''
from collections import defaultdict
def fun1():
ice_cream = defaultdict(lambda : "vanilla")
ice_cream['Sarah'] = 'Chunkey'
ice_cream['Abdul']= 'Butter'
print(ice_cream['Sarah'])
print("###############")
for name, flavour in ice_cream.items():
print("Name:{} :: Flavour:{}".format(name,flavour))
print(ice_cream['prashanta'])
'''When called fun1(), the output is ::
Chunkey
###############
Name:Sarah :: Flavour:Chunkey
Name:Abdul :: Flavour:Butter
vanilla
'''
def fun2():
food_list = 'spam spam spam egg rice egg spam'.split()
food_count = defaultdict(int) # default value of int is zero ## Note: “lambda: 0″ would also work in this situation
for food in food_list:
food_count[food] +=1
print(food_count)
for k,v in food_count.items():
print(k,v)
'''when calles fun2(), the output is :
defaultdict(<class 'int'>, {'spam': 4, 'egg': 2, 'rice': 1})
spam 4
egg 2
rice 1
'''
def fun3():
city_list = [('TX', 'Austin'), ('TX', 'Houston'), ('NY', 'Albany'), ('NY', 'Syracuse'), ('NY', 'Buffalo'),
('NY', 'Rochester'), ('TX', 'Dallas'), ('CA', 'Sacramento'), ('CA', 'Palo Alto'), ('GA', 'Atlanta')]
cities_by_state = defaultdict(list)
for state, city in city_list:
cities_by_state[state].append(city)
print(cities_by_state)
print("###############")
for state, cities in cities_by_state.items():
print(state,":",",".join(cities))
'''when called fun3(), the output is ::
defaultdict(<class 'list'>, {'TX': ['Austin', 'Houston', 'Dallas'], 'NY': ['Albany', 'Syracuse', 'Buffalo', 'Rochester'], 'CA': ['Sacramento', 'Palo Alto'],
'GA': ['Atlanta']})
###############
TX : Austin,Houston,Dallas
NY : Albany,Syracuse,Buffalo,Rochester
CA : Sacramento,Palo Alto
GA : Atlanta
'''
if __name__ == '__main__':
fun3()
'''
Setting the default_factory to int makes the defaultdict useful for counting (like a bag or multiset in other languages):
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
... d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
'''
| [
"noreply@github.com"
] | noreply@github.com |
34ed20b435629b542eb0e524e0f9cc8ef963cd73 | ac25612c927d8e279071933f7c92f6359da525df | /faceDetector.py | f90337157ad791343cd5f7718d033f84276c0826 | [] | no_license | CodingMirec/FaceDetector | 2b20c37e17f7a7ad9b53861b94a28a5c3f156b13 | 26376e4105351f848dc042d6ba8ba9b19049cdeb | refs/heads/master | 2023-02-10T12:59:20.980475 | 2021-01-04T22:58:43 | 2021-01-04T22:58:43 | 326,828,595 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 42 | py | print("Hi World, let's do some AI stuff")
| [
"m.sykora01@gmail.com"
] | m.sykora01@gmail.com |
854b12f30c05681e1d3cd700beb44eaf0ced4d70 | 0196d924a6c3c20e665a4e1cdcf036dc57eb421c | /test4.py | 15d2c2bc69d89b4f4a82098343facbbd94373a96 | [] | no_license | cordx56/graduation-research-implementation | cfd6bfa3d997cdc588d333496f87cb269dcaaff1 | d8c6b5d4c2dbb9a69856ab89820359e3c94f66a4 | refs/heads/master | 2023-03-18T16:41:58.877851 | 2021-03-12T20:01:26 | 2021-03-12T20:01:26 | 317,415,721 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 72 | py | from typing import List
def test() -> List[float]:
return [1, 2.3]
| [
"cordx56@cordx.net"
] | cordx56@cordx.net |
64f3f19c9acc0c5120f14e43ea424666c7f627c9 | 0ceb424bd27a9a6d919ca165c470ced69bd9fad2 | /web/app/main/views.py | efec4a89902e7c93a287c8ffdc64e56813faf917 | [] | no_license | qq850482461/python3 | 92d667c642ff7b02792092f20e481323bceb7c70 | 1a9d5898a7286cf305df301f3fc81d8d35585d69 | refs/heads/master | 2021-01-11T19:57:55.092410 | 2017-11-07T03:03:33 | 2017-11-07T03:03:33 | 79,432,999 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,899 | py | from os import path, pardir
from flask import render_template, request, redirect, url_for, flash, session, abort, jsonify, send_from_directory
from werkzeug.utils import secure_filename # 上传文件
from flask_login import login_required, current_user # 登录模块
from . import main # 导入蓝图
from .forms import CommentForm, PostForm # 表单
from .. import db # 引用orm
from ..models import Post, Comment, Tag # 表单
from datetime import datetime
import os
nowtime = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 当前时间
basepath = path.abspath(path.join(path.dirname(__file__), pardir, pardir, 'upload')) # 路径
# 全局模板变量,上下文处理器
@main.app_context_processor
def tag_list():
tags = Tag.query.all()
# 过滤没有关联的tag
rm_repeat = []
for i in tags:
if i.posts:
rm_repeat.append(i)
return dict(tag_list=rm_repeat)
@main.route('/') # 装饰起用于根目录
def index():
return render_template('index.html', title='Welcome')
@main.route('/user/<regex("[a-z]{3}"):user_id>') # 正则表达式验证url
def user(user_id):
return 'User {0}'.format(user_id)
# 关于页面
@main.route('/about')
def about():
return render_template('about.html')
# 自己定义一个错误页面传入错误代码,如果不是蓝图就是用errorhandler
@main.app_errorhandler(404)
def page_not_found(error):
return render_template('404.html', title='404'), 404
# 发表页面
@main.route('/edit', methods=['GET', 'POST'])
@main.route('/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def edit(id=0):
form = PostForm()
# 新增发表
if id == 0:
if form.validate_on_submit():
# autchor是User模型的backref的参数,autchor存储一个User对象ORM层将会知道怎么完成author_id字段,所以这里只需要传入当前的用户对象。
new_post = Post(
title=form.title.data, body=form.body.data, author=current_user
)
tag = Tag.query.filter_by(title=form.tag.data).first() # 拿到tag对象
# 判断是否有这个tag没有就新建一个
if tag == None:
tag = Tag(title=form.tag.data)
new_post.tags = [tag] # 关联Tag的标签
db.session.add(new_post)
db.session.commit()
return redirect(url_for('main.posts', id=new_post.id))
# 重新编辑页面
else:
# 查询POST模型中的id返回模型对象
post = Post.query.get_or_404(id)
if form.validate_on_submit():
post.title = form.title.data
post.body = form.body.data
# 关联标签
tag = Tag.query.filter_by(title=form.tag.data).first()
if tag == None:
tag = Tag(title=form.tag.data)
post.tags = [tag]
db.session.add(post)
db.session.commit()
return redirect(url_for('main.posts', id=post.id))
# 给前端传入数据库保存的数据(这样就可以在原文的基础上编辑)
form.title.data = post.title
form.body.data = post.body
form.tag.data = post.tags[0].title # 得到一个tag列表
return render_template('new.html', form=form, title="发表文章")
# 发表后的显示页面
@main.route('/posts/<int:id>', methods=['GET', 'POST'])
def posts(id):
form = CommentForm() # 表单对象
# 获取文章的ID对象没有就返回404
post = Post.query.get_or_404(id)
# 提交评论表单
if form.validate_on_submit():
# 这里的post=post是关联文章的Post数据库模型的backref的post对象==当前文章的变量post存放的文章id对象
comment = Comment(body=form.body.data, post=post)
db.session.add(comment)
db.session.commit()
return redirect(url_for('main.posts', id=post.id))
# form对象传到前端模版,post对象传到前端模版(前端使用的变量名字 = views中定义的对象)
return render_template('post.html', form=form, post=post)
# 显示博客文章列表页面
@main.route('/blog', methods=['GET', 'POST'])
def blog():
search = request.args.get('search')
page_idnex = request.args.get("page", 1, type=int) #获取url中get请求的参数
#搜索功能
if search:
value = "%{0}%".format(search)
query = Post.query.filter(Post.title.like(value))
pagination = query.paginate(page_idnex, per_page=2, error_out=False)
post = pagination.items
count = len(query.all())
return render_template('blog_search.html', posts=post, pagination=pagination, display_search=True,num=count)
else:
query = Post.query.order_by(Post.created.desc()) # order_by是升序 .desc()是降序,这里做一个反向排序
pagination = query.paginate(page_idnex, per_page=5, error_out=False)
post = pagination.items
return render_template('blog.html', posts=post, pagination=pagination, display_search=True)
# 文章的标签页面
@main.route('/tag/<tag>', methods=['GET', 'POST'])
def tag(tag):
page_idnex = request.args.get("page", 1, type=int)
tag = Tag.query.filter_by(title=tag).first_or_404()
query = tag.posts # backref拿到post的所有对象
pagination = query.paginate(page_idnex, per_page=5, error_out=False)
post = pagination.items
search_post = tag.posts.all()
count = len(search_post)
return render_template('tag.html', num=count, tag=tag, posts=post, pagination=pagination)
# 实现博客的管理编辑删除页面
@main.route('/bloglists', methods=['GET', 'POST'])
@login_required
def bloglists():
search = request.args.get("search")
page_idnex = request.args.get("page", 1, type=int)
if search:
value = "%{0}%".format(search)
query = Post.query.filter(Post.title.like(value))
pagination = query.paginate(page_idnex, per_page=5, error_out=False)
post = pagination.items
return render_template('bloglists.html', posts=post, pagination=pagination)
else:
query = Post.query.order_by(Post.created.desc()) # 先升序再降序
pagination = query.paginate(page_idnex, per_page=10, error_out=False)
post = pagination.items
return render_template('bloglists.html', posts=post, pagination=pagination)
# 实现文章删除功能
@main.route('/posts/<int:id>/delete', methods=['GET', 'POST'])
@login_required
def post_delete(id):
# 创建一个res的json对象
response = {
'status': 200,
'message': 'success'
}
# 查询文章ID拿到数据对象
post = Post.query.filter_by(id=id).first()
# 如果数据库没有这个文章ID,post就是空列表
if not post:
response['status'] = 404
response['message'] = 'Post Not Found'
return jsonify(response)
else:
# 提交删除
db.session.delete(post)
db.session.commit()
return jsonify(response)
# API接口测试
@main.route('/test/api', methods=["GET"])
def test():
post_name = request.args.get("post_name")
value = "%{0}%".format(post_name)
post = Post.query.filter(Post.title.like(value)).all()
str_name = []
for i in post:
str_name.append(i.title)
print(str_name)
res = {
"resultcode":200,
"message":"Search successd"
}
if post :
res["result"] = str_name
return jsonify(res)
else:
res["resultcode"] = 404
res["message"] = "Search error"
res["result"] = None
return jsonify(res)
# 编辑器上传图片
@main.route('/upload/', methods=["POST"])
def upload():
check_path = path.isdir(basepath)
if check_path is False:
pass
if request.method == "POST":
file = request.files.get("editormd-image-file") # 拿到前端编辑器上传name标签
if not file:
res = {
'success': 0,
'message': "上传失败"
}
return jsonify(res)
else:
ex = path.splitext(file.filename)[1] # 把文件名分成文件名称和扩展名,拿到后缀
filename = datetime.now().strftime('%Y%m%d%H%M%S') + ex
try:
file.save(path.join(basepath, filename))
except:
res = {
'success': 0,
'message': "upload路径出错或者保存不了图片"
}
else:
res = {
'success': 1,
'mess age': "上传成功",
'url': url_for('.image', filename=filename)
}
return jsonify(res)
# 上传文件访问服务
@main.route('/image/<filename>')
def image(filename):
return send_from_directory(basepath, filename)
| [
"850482461@qq.com"
] | 850482461@qq.com |
85c68399114fdf7fa68f0e31b70251da36f55c0e | cd11c6a68a58581c06f609cfc0f2c2df149460ec | /py/cpp_py_reciever.py | d7c32877bba7eef7567f62d6b717004ed2978610 | [] | no_license | Chufan1990/communication_test | 4ec3ec1327b065c358cca0e0f0b5bc7036057134 | dcb2f3af3ffd7a8dd7079a52f586cdbf6c6d58d1 | refs/heads/master | 2021-05-07T07:17:02.672969 | 2017-11-01T09:45:30 | 2017-11-01T09:45:30 | 109,113,904 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 433 | py | import socket
import time
HOST = ''
PORT = 54377
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
a = [x for x in range(1,100)]
while True:
# conn, addr = s.accept()
data = conn.recv(1024)
print(data)
a = [x + 1 for x in a]
string = str(a)
conn.sendall(bytes(string,encoding = "utf8"))
# print(s)
time.sleep(1)
conn.close()
socket.close() | [
"Chufan1990@Gmail.com"
] | Chufan1990@Gmail.com |
cb4b97b896fc5683599a57fe012bcc1fe716bb96 | b49e7e1fb8557f21280b452b2d5e29668613fe83 | /leonardo/module/web/widget/feedreader/models.py | e2b9999d1a451c50e6f88b523b571787e8d75ef2 | [
"BSD-2-Clause"
] | permissive | pombredanne/django-leonardo | 6e03f7f53391c024cfbfd9d4c91bd696adcb361d | dcbe6c4a0c296a03c3a98b3d5ae74f13037ff81b | refs/heads/master | 2021-01-17T10:24:09.879844 | 2016-04-06T19:30:05 | 2016-04-06T19:30:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,619 | py | # -#- coding: utf-8 -#-
import datetime
import feedparser
from django.db import models
from django.template.context import RequestContext
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from leonardo.module.web.models import Widget, ContentProxyWidgetMixin
from leonardo.module.web.widgets.mixins import ListWidgetMixin
TARGET_CHOICES = (
('modal', _('Modal window')),
('blank', _('Blank window')),
)
class FeedReaderWidget(Widget, ContentProxyWidgetMixin, ListWidgetMixin):
max_items = models.IntegerField(_('max. items'), default=5)
class Meta:
abstract = True
verbose_name = _("feed reader")
verbose_name_plural = _('feed readers')
def render_content(self, options):
if self.is_obsolete:
self.update_cache_data()
context = RequestContext(options.get('request'), {
'widget': self,
})
return render_to_string(self.get_template_name(), context)
def update_cache_data(self, save=True):
feed = feedparser.parse(self.link)
entries = feed['entries'][:self.max_items]
context = {
'widget': self,
'link': feed['feed']['link'],
'entries': entries,
}
self.cache_data = render_to_string(
'widget/feedreader/_content.html', context)
self.cache_update = datetime.datetime.now()
if save:
self.save()
def save(self, *args, **kwargs):
self.update_cache_data(False)
super(FeedReaderWidget, self).save(*args, **kwargs)
| [
"6du1ro.n@gmail.com"
] | 6du1ro.n@gmail.com |
8127e141b92c22dbd820909101e7385b9efb77fb | 0b543112c893ec250b68d30f935901a802da37f2 | /task1/src/baseline1-BN-no-missing-AdamW/plot.py | b423232cf3f5f235ad4e26c99bbe7aafc1038081 | [] | no_license | KUAN-HSUN-LI/Missing-Feature-Learning | 3badbef77581270169f4353e4deb21713cdcd2f9 | e17d89ba61adc866f13c36cbc27bd71148de7ec4 | refs/heads/master | 2023-02-21T11:34:57.608183 | 2021-01-23T11:47:24 | 2021-01-23T11:47:24 | 223,157,013 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,972 | py | import matplotlib.pyplot as plt
import json
from sklearn.metrics import confusion_matrix
import numpy as np
def plot_box(data, y_ticks=False, save_path=None):
"""
Args:
data (list): shape = (number of features, data's length)
"""
length = len(data)
fig, ax = plt.subplots(1, length)
for idx, d in enumerate(data):
ax[idx].boxplot(d)
ax[idx].set_xticks([])
ax[idx].set_xlabel(str(idx+1))
if not y_ticks:
ax[idx].set_yticks([])
else:
plt.subplots_adjust(wspace=1.5, hspace=1)
if save_path is not None:
plt.savefig(save_path, dpi=300)
plt.show()
def plot_confusion_matrix(y_true, y_pred, classes,
normalize=False,
title=None,
cmap=plt.cm.Blues,
save_path=None):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if not title:
if normalize:
title = 'Normalized confusion matrix'
else:
title = 'Confusion matrix, without normalization'
# Compute confusion matrix
cm = confusion_matrix(y_true, y_pred)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
plt.figure(figsize=[11, 11])
fig, ax = plt.subplots()
im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
ax.figure.colorbar(im, ax=ax)
ax.set(xticks=np.arange(cm.shape[1]),
yticks=np.arange(cm.shape[0]),
xticklabels=classes, yticklabels=classes,
title=title,
ylabel='True label',
xlabel='Predicted label')
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), ha="right",
rotation_mode="anchor")
# Loop over data dimensions and create text annotations.
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i in range(cm.shape[0]):
for j in range(cm.shape[1]):
ax.text(j, i, format(cm[i, j], fmt),
ha="center", va="center",
color="white" if cm[i, j] > thresh else "black", fontsize=6)
fig.tight_layout()
if save_path:
plt.savefig(save_path, dpi=300)
plt.show()
def plot_history(history_path, plot_acc=True):
"""
Ploting training process
"""
with open(history_path, 'r') as f:
history = json.loads(f.read())
train_loss = [l['loss'] for l in history['train']]
valid_loss = [l['loss'] for l in history['valid']]
plt.figure(figsize=(7, 5))
plt.title('Loss')
plt.plot(train_loss, label='train')
plt.plot(valid_loss, label='valid')
plt.legend()
plt.savefig("result/training_loss.png", dpi=300)
plt.show()
print('Lowest Loss ', min([[l['loss'], idx + 1] for idx, l in enumerate(history['valid'])]))
if plot_acc:
train_f1 = [l['acc_fixed'] for l in history['train']]
train_f1_fadding = [l['acc-fadding'] for l in history['train']]
valid_f1 = [l['acc_fixed'] for l in history['valid']]
valid_f1_fadding = [l['acc-fadding'] for l in history['valid']]
plt.figure(figsize=(7, 5))
plt.title('Acc')
plt.plot(train_f1, label='train')
plt.plot(train_f1_fadding, label='train_fadding')
plt.plot(valid_f1, label='valid')
plt.plot(valid_f1_fadding, label='valid_fadding')
plt.legend()
plt.savefig("result/training_acc.png", dpi=300)
plt.show()
print('Best acc', max([[l['acc_fixed'], idx + 1]
for idx, l in enumerate(history['valid'])]))
print('Best training acc', max([[l['acc_fixed'], idx + 1]
for idx, l in enumerate(history['train'])]))
| [
"b06209027@ntu.edu.tw"
] | b06209027@ntu.edu.tw |
f22577938fc54158f83a3dc1f43cd18d5cfa7cea | 4a7ede06edbe66f9d1eb485261f94cc3251a914b | /test/pyaz/webapp/config/ssl/__init__.py | b8b893c526afb4dff9fd44ab4dc16187a35ffb19 | [
"MIT"
] | permissive | bigdatamoore/py-az-cli | a9e924ec58f3a3067b655f242ca1b675b77fa1d5 | 54383a4ee7cc77556f6183e74e992eec95b28e01 | refs/heads/main | 2023-08-14T08:21:51.004926 | 2021-09-19T12:17:31 | 2021-09-19T12:17:31 | 360,809,341 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,010 | py | import json, subprocess
from .... pyaz_utils import get_cli_name, get_params
def upload(resource_group, name, certificate_password, certificate_file, slot=None):
params = get_params(locals())
command = "az webapp config ssl upload " + params
print(command)
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = output.stdout.decode("utf-8")
stderr = output.stderr.decode("utf-8")
if stdout:
return json.loads(stdout)
print(stdout)
else:
raise Exception(stderr)
print(stderr)
def list(resource_group):
params = get_params(locals())
command = "az webapp config ssl list " + params
print(command)
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = output.stdout.decode("utf-8")
stderr = output.stderr.decode("utf-8")
if stdout:
return json.loads(stdout)
print(stdout)
else:
raise Exception(stderr)
print(stderr)
def show(resource_group, certificate_name):
params = get_params(locals())
command = "az webapp config ssl show " + params
print(command)
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = output.stdout.decode("utf-8")
stderr = output.stderr.decode("utf-8")
if stdout:
return json.loads(stdout)
print(stdout)
else:
raise Exception(stderr)
print(stderr)
def bind(resource_group, name, certificate_thumbprint, ssl_type, slot=None):
params = get_params(locals())
command = "az webapp config ssl bind " + params
print(command)
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = output.stdout.decode("utf-8")
stderr = output.stderr.decode("utf-8")
if stdout:
return json.loads(stdout)
print(stdout)
else:
raise Exception(stderr)
print(stderr)
def unbind(resource_group, name, certificate_thumbprint, slot=None):
params = get_params(locals())
command = "az webapp config ssl unbind " + params
print(command)
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = output.stdout.decode("utf-8")
stderr = output.stderr.decode("utf-8")
if stdout:
return json.loads(stdout)
print(stdout)
else:
raise Exception(stderr)
print(stderr)
def delete(resource_group, certificate_thumbprint):
params = get_params(locals())
command = "az webapp config ssl delete " + params
print(command)
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = output.stdout.decode("utf-8")
stderr = output.stderr.decode("utf-8")
if stdout:
return json.loads(stdout)
print(stdout)
else:
raise Exception(stderr)
print(stderr)
def import_(resource_group, name, key_vault, key_vault_certificate_name):
params = get_params(locals())
command = "az webapp config ssl import " + params
print(command)
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = output.stdout.decode("utf-8")
stderr = output.stderr.decode("utf-8")
if stdout:
return json.loads(stdout)
print(stdout)
else:
raise Exception(stderr)
print(stderr)
def create(resource_group, name, hostname, slot=None):
params = get_params(locals())
command = "az webapp config ssl create " + params
print(command)
output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = output.stdout.decode("utf-8")
stderr = output.stderr.decode("utf-8")
if stdout:
return json.loads(stdout)
print(stdout)
else:
raise Exception(stderr)
print(stderr)
| [
"“bigdatamoore@users.noreply.github.com”"
] | “bigdatamoore@users.noreply.github.com” |
55472b0c5f983145ad94b3ad71b426983dfc08c4 | b7eed26cf8a0042a61f555eed1e9bf0a3227d490 | /students/synowiec_krzysztof/lesson_05_lists/swap_the_columns.py | b736f8344827fe5b3c90bd3b1073ba5e4b319f6b | [] | no_license | jedzej/tietopythontraining-basic | e8f1ac5bee5094c608a2584ab19ba14060c36dbe | a68fa29ce11942cd7de9c6bbea08fef5541afa0f | refs/heads/master | 2021-05-11T11:10:05.110242 | 2018-08-20T12:34:55 | 2018-08-20T12:34:55 | 118,122,178 | 14 | 84 | null | 2018-08-24T15:53:04 | 2018-01-19T12:23:02 | Python | UTF-8 | Python | false | false | 564 | py | def main():
rows, columns = [int(x) for x in input().split()]
matrix = [[int(y) for y in input().split()] for x in range(rows)]
i, j = [int(x) for x in input().split()]
matrix = swap_columns(matrix, i, j)
for row in matrix:
for column in row:
print(column, end=" ")
print()
def swap_columns(matrix, i, j):
tmp_column = [row[i] for row in matrix]
for x in range(len(matrix)):
matrix[x][i] = matrix[x][j]
matrix[x][j] = tmp_column[x]
return matrix
if __name__ == '__main__':
main()
| [
"synulewar@gmail.com"
] | synulewar@gmail.com |
722d9751fdfb30121aa44cbdf95d987200b1f104 | de1acc80671e1dbf5ac7292756eda1a4dc2ae01b | /arena.py | 2a90e7d9c752a1791931516897b76f9d43de7eaf | [] | no_license | aibrockmann/Fire-Emblem-Arena-Probabilities | d701b9881c619f6cf0c72e153d7ad4d70c22dd7c | ee0c7ec4928321649555e3d9809d4eded47c1fff | refs/heads/master | 2020-03-25T22:25:41.052968 | 2018-08-10T02:49:42 | 2018-08-10T02:49:42 | 144,222,635 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 21,981 | py | #!/usr/bin/python3
"""
arena.py
Tkinter app which computes the probability of victory in Fire Emblem arena battles.
Author: Andrew Brockmann
Completion Date: August 8, 2018
Last Modified: August 8, 2018
"""
from fractions import Fraction
from math import ceil
try:
from tkinter import *
from tkinter import messagebox
except ImportError:
# Modules need to be imported a little differently if running on Python 2
from Tkinter import *
import tkMessageBox as messagebox
###############################################################################
############################### True Hit Data #################################
###############################################################################
# True hit table for FE 1-5 (1RN, displayed hit is accurate)
# Given displayed hit x, hit probability is _1RN[x]/100
_1RN_games = ["Fire Emblem 1", "Gaiden", "Mystery of the Emblem", "Genealogy of the Holy War", "Thracia 776"]
_1RN = range(101)
# True hit table for FE 6-13 (2RN)
# Given displayed hit x, hit probability is _2RN[x]/10000
_2RN_games = ["Binding Blade", "Blazing Sword", "Sacred Stones", "Path of Radiance", "Radiant Dawn", \
"Shadow Dragon", "New Mystery of the Emblem", "Awakening"]
_2RN = [0, 3, 10, 21, 36, 55, 78, 105, 136, 171, 210, 253, 300, 351, 406, 465, 528, 595, 666, 741, 820, 903, 990, 1081, 1176, 1275, 1378, 1485, 1596, 1711, 1830, 1953, 2080, 2211, 2346, 2485, 2628, 2775, 2926, 3081, 3240, 3403, 3570, 3741, 3916, 4095, 4278, 4465, 4656, 4851, 5050, 5247, 5440, 5629, 5814, 5995, 6172, 6345, 6514, 6679, 6840, 6997, 7150, 7299, 7444, 7585, 7722, 7855, 7984, 8109, 8230, 8347, 8460, 8569, 8674, 8775, 8872, 8965, 9054, 9139, 9220, 9297, 9370, 9439, 9504, 9565, 9622, 9675, 9724, 9769, 9810, 9847, 9880, 9909, 9934, 9955, 9972, 9985, 9994, 9999, 10000]
# True hit table for FE Fates (1RN / weighted 2RN hybrid)
# Hit rates below 50 seem to be accurate, while 50 and above seem to use a weighted 2RN formula
# Given displayed hit x, hit probability is Fates[x]/10000
Fates = [0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900, 2000, 2100, 2200, 2300, 2400, 2500, 2600, 2700, 2800, 2900, 3000, 3100, 3200, 3300, 3400, 3500, 3600, 3700, 3800, 3900, 4000, 4100, 4200, 4300, 4400, 4500, 4600, 4700, 4800, 4900, 5050, 5183, 5317, 5450, 5583, 5717, 5850, 5983, 6117, 6250, 6383, 6517, 6650, 6783, 6917, 7050, 7183, 7317, 7450, 7583, 7717, 7850, 7983, 8117, 8250, 8383, 8512, 8635, 8753, 8866, 8973, 9075, 9172, 9263, 9349, 9430, 9505, 9575, 9640, 9699, 9753, 9802, 9845, 9883, 9916, 9943, 9965, 9982, 9993, 9999, 10000]
###############################################################################
############################### Tooltip Class #################################
###############################################################################
# Copied with negligible changes from:
# https://stackoverflow.com/questions/3221956/how-do-i-display-tooltips-in-tkinter
# Comments from the original file:
""" tk_ToolTip_class101.py
gives a Tkinter widget a tooltip as the mouse is above the widget
tested with Python27 and Python34 by vegaseat 09sep2014
www.daniweb.com/programming/software-development/code/484591/a-tooltip-class-for-tkinter
Modified to include a delay time by Victor Zaccardo, 25mar16
"""
class CreateToolTip(object):
"""
create a tooltip for a given widget
"""
def __init__(self, widget, text='widget info'):
self.waittime = 500 #miliseconds
self.wraplength = 180 #pixels
self.widget = widget
self.text = text
self.widget.bind("<Enter>", self.enter)
self.widget.bind("<Leave>", self.leave)
self.widget.bind("<ButtonPress>", self.leave)
self.id = None
self.tw = None
def enter(self, event=None):
self.schedule()
def leave(self, event=None):
self.unschedule()
self.hidetip()
def schedule(self):
self.unschedule()
self.id = self.widget.after(self.waittime, self.showtip)
def unschedule(self):
id = self.id
self.id = None
if id:
self.widget.after_cancel(id)
def showtip(self, event=None):
x = y = 0
x, y, cx, cy = self.widget.bbox("insert")
x += self.widget.winfo_rootx() + 25
y += self.widget.winfo_rooty() + 20
# creates a toplevel window
self.tw = Toplevel(self.widget)
# Leaves only the label and removes the app window
self.tw.wm_overrideredirect(True)
self.tw.wm_geometry("+%d+%d" % (x, y))
label = Label(self.tw, text=self.text, justify='left',
background="#ffffff", relief='solid', borderwidth=1,
wraplength = self.wraplength)
label.pack(ipadx=1)
def hidetip(self):
tw = self.tw
self.tw= None
if tw:
tw.destroy()
###############################################################################
####################### Functions called by the GUI ###########################
###############################################################################
def clearAll():
""" Function called by the "Clear All" button. """
pHit.delete(0, END)
pDmg.delete(0, END)
pCrit.delete(0, END)
pHP.delete(0, END)
eHit.delete(0, END)
eDmg.delete(0, END)
eCrit.delete(0, END)
eHP.delete(0, END)
numEntry.delete(0, END)
denEntry.delete(0, END)
perEntry.delete(0, END)
def isInt(entry):
""" Given string input, checks whether it represents an integer value. """
try:
x = int(entry)
if str(x) == entry:
return True
else:
return False
except ValueError:
return False
def inputCheck():
""" Checks input values for problems, fills in default values as necessary, and creates error
messages. Returns True if the program can run with the given input. """
Hit = [pHit.get(), eHit.get()]
Dmg = [pDmg.get(), eDmg.get()]
Crit = [pCrit.get(), eCrit.get()]
HP = [pHP.get(), eHP.get()]
# Error for game not selected
if RNG.get() == "Choose game":
messagebox.showerror("Selection error", "Select game from the dropdown menu.")
return False
# Errors for missing mandatory values
missing = []
if Dmg[0] == "": missing += ["Player Dmg"]
if Dmg[1] == "": missing += ["Enemy Dmg"]
if HP[0] == "": missing += ["Player HP"]
if HP[1] == "": missing += ["Enemy HP"]
if len(missing) > 0:
errorMessage = "Mandatory field(s) missing:"
for field in missing:
errorMessage += "\n-" + field
messagebox.showerror("Input error", errorMessage)
return False
# Errors for non-integer input values
notInt = []
if not isInt(Hit[0]) and Hit[0] != "": notInt += ["Player Hit"]
if not isInt(Hit[1]) and Hit[1] != "": notInt += ["Enemy Hit"]
if not isInt(Dmg[0]): notInt += ["Player Dmg"]
if not isInt(Dmg[1]): notInt += ["Enemy Dmg"]
if not isInt(Crit[0]) and Crit[0] != "": notInt += ["Player Crit"]
if not isInt(Crit[1]) and Crit[1] != "": notInt += ["Enemy Crit"]
if not isInt(HP[0]): notInt += ["Player HP"]
if not isInt(HP[1]): notInt += ["Enemy HP"]
if len(notInt) > 0:
errorMessage = "All input fields must have whole number numeric values. The following fields do not:"
for field in notInt:
errorMessage += "\n-" + field
messagebox.showerror("Input error", errorMessage)
return False
# Warnings for missing Hit/Crit values
if Hit[0] == "":
missing += ["Player Hit"]
pHit.insert(0, "100")
Hit[0] = "100"
if Hit[1] == "":
missing += ["Enemy Hit"]
eHit.insert(0, "100")
Hit[1] = "100"
if Crit[0] == "":
missing += ["Player Crit"]
pCrit.insert(0, "0")
Crit[0] = "0"
if Crit[1] == "":
missing += ["Enemy Crit"]
eCrit.insert(0, "0")
Crit[1] = "0"
if len(missing) > 0:
warning = "Optional fields are missing and have been filled in with their default values:"
for field in missing:
warning += "\n-" + field
messagebox.showwarning("Warning", warning)
Hit = [int(Hit[0]), int(Hit[1])]
Dmg = [int(Dmg[0]), int(Dmg[1])]
Crit = [int(Crit[0]), int(Crit[1])]
HP = [int(HP[0]), int(HP[1])]
# Hit/Crit out of range errors:
invalid = []
if Hit[0] < 0 or Hit[0] > 100: invalid += ["Player Hit"]
if Hit[1] < 0 or Hit[1] > 100: invalid += ["Enemy Hit"]
if Crit[0] < 0 or Crit[0] > 100: invalid += ["Player Crit"]
if Crit[1] < 0 or Crit[1] > 100: invalid += ["Enemy Crit"]
if len(invalid) > 0:
errorMessage = "Hit and Crit must be values between 0 and 100 (inclusive)."
errorMessage += " The following values are out of range:"
for field in invalid:
errorMessage += "\n-" + field
messagebox.showerror("Input error", errorMessage)
return False
# Dmg/HP out of range errors:
if Dmg[0] < 0: invalid += ["Player Dmg"]
if Dmg[1] < 0: invalid += ["Enemy Dmg"]
if HP[0] < 0: invalid += ["Player HP"]
if HP[1] < 0: invalid += ["Enemy HP"]
if len(invalid) > 0:
errorMessage = "Dmg and HP values must not be negative. The following values are out of range:"
for field in invalid:
errorMessage += "\n-" + field
messagebox.showerror("Input error", errorMessage)
return False
# Endless battle error
if (Hit[0] == 0 or Dmg[0] == 0) and (Hit[1] == 0 or Dmg[1] == 0):
messagebox.showerror("Error", "This battle will never end.")
return False
return True
# This method will be used to access elements from the DP table without worrying about negative indices.
# Based on my research and timing tests, passing a large list to a Python method repeatedly won't slow
# things down - the method won't recreate the list from scratch with each call.
def A(DP, x, y):
return DP[max(x, 0)][max(y, 0)]
# The following function is a hack introduced to deal with the case where the player attacks twice per turn
def B(x, y):
if x <= 0 and y > 0:
return 0
else:
return 1
# Function that determines the victory probability when player and enemy each attack once per round.
# All inputs except m and n should be passed as Fraction objects:
# m: Number of (non-crit) hits needed to defeat the player
# n: Number of hits needed to defeat the enemy
# p1: Player true hit rate
# p2: Enemy true hit
# c1: Player critical hit rate
# c2: Enemy crit rate
def DP_1_1(m, n, p1, p2, c1, c2):
DP = [x[:] for x in [[Fraction(0)] * (n+1)] * (m+1)]
# The values DP[0][j] for j > 0 are already initialized to 0
for i in range(m+1):
DP[i][0] = Fraction(1)
# Initialization of DP table is now complete
# Compute other values with the recurrence relation
for i in range(1, m+1):
for j in range(1, n+1):
r = Fraction(0)
r += p1 * (1 - p2) * ( c1 * A(DP, i, j-3) + (1 - c1) * A(DP, i, j-1) )
r += (1 - p1) * p2 * ( c2 * A(DP, i-3, j) + (1 - c2) * A(DP, i-1, j) )
r += p1 * p2 * ( c1 * c2 * A(DP, i-3, j-3) + c1 * (1 - c2) * A(DP, i-1, j-3) \
+ (1 - c1) * c2 * A(DP, i-3, j-1) + (1 - c1) * (1 - c2) * A(DP, i-1, j-1) )
DP[i][j] = r / (p1 + p2 - p1 * p2)
return DP[m][n]
# Function that determines the victory probability when enemy attacks twice per round
def DP_1_2(m, n, p1, p2, c1, c2):
DP = [x[:] for x in [[Fraction(0)] * (n+1)] * (m+1)]
# The values DP[0][j] for j > 0 are already initialized to 0
for i in range(m+1):
DP[i][0] = Fraction(1)
# Initialization of DP table is now complete
# Compute other values with the recurrence relation
for i in range(1, m+1):
for j in range(1, n+1):
r = Fraction(0)
r += p1 * (1 - p2) ** 2 * ( c1 * A(DP, i, j-3) + (1 - c1) * A(DP, i, j-1) )
r += 2 * (1 - p1) * p2 * (1 - p2) * ( c2 * A(DP, i-3, j) + (1 - c2) * A(DP, i-1, j) )
r += 2 * p1 * p2 * (1 - p2) * ( c1 * c2 * A(DP, i-3, j-3) + c1 * (1 - c2) * A(DP, i-1, j-3) \
+ (1 - c1) * c2 * A(DP, i-3, j-1) \
+ (1 - c1) * (1 - c2) * A(DP, i-1, j-1) )
r += (1 - p1) * p2 ** 2 * ( c2 ** 2 * A(DP, i-6, j) + 2 * c2 * (1 - c2) * A(DP, i-4, j) \
+ (1 - c2) ** 2 * A(DP, i-2, j) )
r += p1 * p2 ** 2 * ( c1 * c2 ** 2 * A(DP, i-6, j-3) + (1 - c1) * c2 ** 2 * A(DP, i-6, j-1) \
+ 2 * c1 * c2 * (1 - c2) * A(DP, i-4, j-3) \
+ 2 * (1 - c1) * c2 * (1 - c2) * A(DP, i-4, j-1) \
+ c1 * (1 - c2) ** 2 * A(DP, i-2, j-3) \
+ (1 - c1) * (1 - c2) ** 2 * A(DP, i-2, j-1) )
DP[i][j] = r / (p1 + 2 * p2 - 2 * p1 * p2 - p2 ** 2 + p1 * p2 ** 2)
return DP[m][n]
# Function that determines the victory probability when player attacks twice per round
def DP_2_1(m, n, p1, p2, c1, c2):
DP = [x[:] for x in [[Fraction(0)] * (n+1)] * (m+1)]
# The values DP[0][j] for j > 0 are already initialized to 0
for i in range(m+1):
DP[i][0] = Fraction(1)
# Initialization of DP table is now complete
# Compute other values with the recurrence relation
for i in range(1, m+1):
for j in range(1, n+1):
r = Fraction(0)
r += 2 * p1 * (1 - p1) * (1 - p2) * ( c1 * A(DP, i, j-3) + (1 - c1) * A(DP, i, j-1) )
r += p1 ** 2 * (1 - p2) * ( c1 ** 2 * A(DP, i, j-6) + 2 * c1 * (1 - c1) * A(DP, i, j-4) \
+ (1 - c1) ** 2 * A(DP, i, j-2) )
r += (1 - p1) ** 2 * p2 * ( c2 * A(DP, i-3, j) + (1 - c2) * A(DP, i-1, j) )
r += p1 * (1 - p1) * p2 * ( c1 * c2 * A(DP, i-3, j-3) + c1 * (1 - c2) * A(DP, i-1, j-3) \
+ (1 - c1) * c2 * A(DP, i-3, j-1)
+ (1 - c1) * (1 - c2) * A(DP, i-1, j-1) )
r += (1 - p1) * p1 * p2 * ( c1 * c2 * B(i-3, j) * A(DP, i-3, j-3) \
+ c1 * (1 - c2) * B(i-1, j) * A(DP, i-1, j-3) \
+ (1 - c1) * c2 * B(i-3, j) * A(DP, i-3, j-1) \
+ (1 - c1) * (1 - c2) * B(i-1, j) * A(DP, i-1, j-1) )
r += p1 ** 2 * p2 * c1 * ( (1 - c2) * (1 - c1) * B(i-1, j-3) * A(DP, i-1, j-4) \
+ (1 - c2) * c1 * B(i-1, j-3) * A(DP, i-1, j-6) \
+ c2 * (1 - c1) * B(i-3, j-3) * A(DP, i-3, j-4) \
+ c2 * c1 * B(i-3, j-3) * A(DP, i-3, j-6) )
r += p1 ** 2 * p2 * (1 - c1) * ( (1 - c2) * (1 - c1) * B(i-1, j-1) * A(DP, i-1, j-2) \
+ (1 - c2) * c1 * B(i-1, j-1) * A(DP, i-1, j-4) \
+ c2 * (1 - c1) * B(i-3, j-1) * A(DP, i-3, j-2) \
+ c2 * c1 * B(i-3, j-1) * A(DP, i-3, j-4) )
DP[i][j] = r / (p2 + 2 * p1 - 2 * p1 * p2 - p1 ** 2 + p1 ** 2 * p2)
return DP[m][n]
def calculate():
""" Top level function called by the "Calculate" button. """
if inputCheck():
# Clear the output fields
numEntry.delete(0, END)
denEntry.delete(0, END)
perEntry.delete(0, END)
# Read input values
hit1, hit2 = int(pHit.get()), int(eHit.get())
dmg1, dmg2 = int(pDmg.get()), int(eDmg.get())
crit1, crit2 = int(pCrit.get()), int(eCrit.get())
hp1, hp2 = int(pHP.get()), int(eHP.get())
# If the player can't hit/damage the enemy, then the enemy will win
if hit1 == 0 or dmg1 == 0:
numEntry.insert(0, 0)
denEntry.insert(0, 1)
perEntry.insert(0, 0)
return
# ...and likewise if the enemy can't hit/damage
if hit2 == 0 or dmg2 == 0:
numEntry.insert(0, 1)
denEntry.insert(0, 1)
perEntry.insert(0, 100)
return
# Having checked the cases above, we won't encounter any division by 0 errors
m, n = int(ceil(float(hp1)/dmg2)), int(ceil(float(hp2)/dmg1))
# Construct the other inputs to the dynamic program as fractions
c1, c2 = Fraction(crit1, 100), Fraction(crit2, 100)
# True hit tables needed for the hit rates
game = RNG.get()
if game in _1RN_games:
p1, p2 = Fraction(_1RN[hit1], 100), Fraction(_1RN[hit2], 100)
elif game in _2RN_games:
p1, p2 = Fraction(_2RN[hit1], 10000), Fraction(_2RN[hit2], 10000)
else:
p1, p2 = Fraction(Fates[hit1], 10000), Fraction(Fates[hit2], 10000)
# Call the appropriate dynamic program depending on which combatant, if either, can follow-up
if followup.get() == "Neither":
victory = DP_1_1(m, n, p1, p2, c1, c2)
numEntry.insert(0, victory.numerator)
denEntry.insert(0, victory.denominator)
perEntry.insert(0, float(100 * victory))
elif followup.get() == "Player":
victory = DP_2_1(m, n, p1, p2, c1, c2)
numEntry.insert(0, victory.numerator)
denEntry.insert(0, victory.denominator)
perEntry.insert(0, float(100 * victory))
else:
victory = DP_1_2(m, n, p1, p2, c1, c2)
numEntry.insert(0, victory.numerator)
denEntry.insert(0, victory.denominator)
perEntry.insert(0, float(100 * victory))
###############################################################################
################################ GUI creation #################################
###############################################################################
window = Tk()
window.title("Fire Emblem Arena Probability Calculator")
window.geometry('600x340')
# Player and Enemy stat labels
pLbl = Label(window, text="Player", font=("Arial Bold", 14), fg="blue")
pLbl.grid(column=1, row=0, pady=10)
eLbl = Label(window, text="Enemy", font=("Arial Bold", 14), fg="red")
eLbl.grid(column=2, row=0)
HitLbl = Label(window, text="Hit", font=("Arial Bold", 14))
HitLbl.grid(column=0, row=1)
Hit_ttp = CreateToolTip(HitLbl, "Displayed Player/Enemy hit rate")
DmgLbl = Label(window, text="Dmg", font=("Arial Bold", 14))
DmgLbl.grid(column=0, row=2)
Dmg_ttp = CreateToolTip(DmgLbl, "Damage dealt by Player/Enemy with each strike")
CritLbl = Label(window, text="Crit", font=("Arial Bold", 14))
CritLbl.grid(column=0, row=3)
Crit_ttp = CreateToolTip(CritLbl, "Player/Enemy critical hit rate")
HPLbl = Label(window, text="HP", font=("Arial Bold", 14))
HPLbl.grid(column=0, row=4)
HP_ttp = CreateToolTip(HPLbl, "Player/Enemy HP at the start of the battle")
# Player and enemy stat entries
pHit = Entry(window, width=10)
pHit.grid(column=1, row=1, padx=10)
pDmg = Entry(window, width=10)
pDmg.grid(column=1, row=2)
pCrit = Entry(window, width=10)
pCrit.grid(column=1, row=3)
pHP = Entry(window, width=10)
pHP.grid(column=1, row=4)
eHit = Entry(window, width=10)
eHit.grid(column=2, row=1, padx=9)
eDmg = Entry(window, width=10)
eDmg.grid(column=2, row=2)
eCrit = Entry(window, width=10)
eCrit.grid(column=2, row=3)
eHP = Entry(window, width=10)
eHP.grid(column=2, row=4)
# Game selection menu
gameLbl = Label(window, text="Game", font=("Arial Bold", 14))
gameLbl.grid(column=3, row=0)
game_ttp = CreateToolTip(gameLbl, 'Displayed hit rates are only accurate in some Fire Emblem games - '
'search "Fire Emblem true hit" for more information')
RNG = StringVar()
RNG.set("Choose game")
gameList = _1RN_games + _2RN_games + ["Fates"]
gameMenu = OptionMenu(window, RNG, *gameList)
gameMenu.config(width=22)
gameMenu.grid(column=3, row=1, padx=50)
# Follow-up attack radio button
followupLbl = Label(window, text="Follow-Up Attacks", font=("Arial Bold", 14))
followupLbl.grid(column=3, row=3)
followup_ttp = CreateToolTip(followupLbl, 'Select "Player" (or "Enemy") if the player (respectively, enemy) '
'is fast enough to attack twice per round')
followup = StringVar()
followup.set("Neither")
nFollowup = Radiobutton(window, text="Neither", value="Neither", variable=followup)
nFollowup.grid(column=3, row=4, sticky="w", padx=75)
pFollowup = Radiobutton(window, text="Player", value="Player", variable=followup)
pFollowup.grid(column=3, row=5, sticky="w", padx=75)
eFollowup = Radiobutton(window, text="Enemy", value="Enemy", variable=followup)
eFollowup.grid(column=3, row=6, sticky="w", padx=75)
# Buttons
clear = Button(window, text="Clear All", width=10, command=clearAll)
clear.grid(column=1, row=6, columnspan=2)
calc = Button(window, text="Calculate", width=10, command=calculate)
calc.grid(column=1, row=7, columnspan=2, pady=15)
# Output labels
numLbl = Label(window, text="numerator", font=("Arial Bold", 12))
numLbl.grid(column=0, row=8, sticky="e")
num_ttp = CreateToolTip(numLbl, "Player victory probability is numerator/denominator")
denLbl = Label(window, text="denominator", font=("Arial Bold", 12))
denLbl.grid(column=0, row=9, sticky="e")
den_ttp = CreateToolTip(denLbl, "Player victory probability is numerator/denominator")
perLbl = Label(window, text="%", font=("Arial Bold", 12))
perLbl.grid(column=0, row=10, sticky="e")
# Output entries
numEntry = Entry(window, width=23)
numEntry.grid(column=1, row=8, columnspan=2)
denEntry = Entry(window, width=23)
denEntry.grid(column=1, row=9, columnspan=2)
perEntry = Entry(window, width=23)
perEntry.grid(column=1, row=10, columnspan=2)
window.mainloop()
| [
"noreply@github.com"
] | noreply@github.com |
b3752302cc01762f86cc7f21d67ad17c50c31944 | 917130bcf189fa8721513ebbc586f92bbc203cba | /projectmini/ebook/booking/models.py | cc927a80ae4122220b36777c2627d673182bfefe | [] | no_license | thitiwut00897/minipro61070088 | bb52a8be057a5216c2a398db1152160b30866cf5 | 26c4422c96c0f1df13f2cc4d50bad8635c359f8e | refs/heads/master | 2021-03-07T04:07:30.744377 | 2020-12-20T10:49:53 | 2020-12-20T10:49:53 | 246,244,833 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,154 | py | from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Rooms(models.Model):
name = models.CharField(max_length=50)
open_time = models.TimeField((""), auto_now=False, auto_now_add=False)
close_time = models.TimeField((""), auto_now=False, auto_now_add=False)
capacity = models.IntegerField()
class Users(models.Model):
username = models.CharField(max_length=50)
password = models.CharField(max_length=50)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(max_length = 254)
class Booking(models.Model):
roomid = models.ForeignKey(Rooms, on_delete=models.CASCADE)
date = models.DateField()
start_time = models.TimeField("", auto_now=False, auto_now_add=False)
end_time = models.TimeField("", auto_now=False, auto_now_add=False)
description = models.TextField()
status = models.BooleanField(default=False)
status_remark = models.TextField('')
bookby = models.ForeignKey(Users, on_delete=models.CASCADE)
bookdate = models.DateField(auto_now=True, auto_now_add=False)
| [
"61070088@kmitl.ac.th"
] | 61070088@kmitl.ac.th |
0cb8fe31319034d1b0d7e1d5d9511de51d466943 | 781e2692049e87a4256320c76e82a19be257a05d | /all_data/exercism_data/python/anagram/1d85ad5d39ab4551a2af68f5a6bd2b21.py | 1bbc9ad83b17ae2c9371525d8394a6a6641fbf73 | [] | no_license | itsolutionscorp/AutoStyle-Clustering | 54bde86fe6dbad35b568b38cfcb14c5ffaab51b0 | be0e2f635a7558f56c61bc0b36c6146b01d1e6e6 | refs/heads/master | 2020-12-11T07:27:19.291038 | 2016-03-16T03:18:00 | 2016-03-16T03:18:42 | 59,454,921 | 4 | 0 | null | 2016-05-23T05:40:56 | 2016-05-23T05:40:56 | null | UTF-8 | Python | false | false | 529 | py | def detect_anagrams(word, anagrams):
real_anagrams = []
for candidate in anagrams:
# Case insensitive
lower_word = word.lower()
lower_candidate = candidate.lower()
for char in lower_word:
if char in lower_candidate:
lower_candidate = lower_candidate.replace(char, "", 1)
if not lower_candidate and len(candidate) == len(word):
if candidate.lower() != lower_word:
real_anagrams.append(candidate)
return real_anagrams
| [
"rrc@berkeley.edu"
] | rrc@berkeley.edu |
7e8576889db7bc42d394affeabbf4d0b2b0f1a9b | acc8ad05dad610d9c10652e0e80234e82f4640da | /PythonLearning/scpPython.py | ab9f88910287f84b72aff41572e842a0c73cfbfc | [] | no_license | anoopsingh/PerlPractice | 93071e355fa10e0f891e7a228661cfedf8386f21 | ebff8dcf9f9066d26c8ecb2b838dffe9d9c71f9b | refs/heads/master | 2021-01-02T08:51:48.672994 | 2015-09-29T06:02:03 | 2015-09-29T06:02:03 | 33,689,358 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,080 | py | import pexpect
IP = '172.23.54.205'
scriptPath = ':/root/test.xlsx'
localPath = 'demo.txt'
password = 'By2GYH'
ssh_newkey='Are you sure you want to continue connecting'
def login(p):
print "\n Sending Password to sit net machine..."
p.sendline(password)
print "\nPassword Sent."
p.expect(['.*#',pexpect.EOF])
def scpScripts():
try:
print "\nDoing scp of load data spreadsheet"
child=pexpect.spawn('scp -rq '+localPath+' root@'+IP+scriptPath,timeout=120)
i=child.expect(['Password:','.*[#/$]',pexpect.EOF],timeout=300)
if i==0:
login(child)
if i==1:
pass
if i==3:
print "\nI either got key or connection timeout"
except Exception ,e:
print "\n Not able to login and do the Upgrade configuration "
print"\n",str(e)
print "\n Exiting the Script"
print "\n SCP Complete."
child.terminate
if __name__ == "__main__":
scpScripts()
| [
"anoop1186@gmail.com"
] | anoop1186@gmail.com |
2552cbf53d0d75e66f28671d25befa0cfa574aff | c1cbdf51c1d7a44ac0391f042370a23e9888d415 | /discussion_board/migrations/0002_auto_20210409_1548.py | cf6d7d57d8582430cb901bde550a93184caf3e9c | [
"MIT"
] | permissive | Archana90663/badger-buddy | 4ddab3ac43268224422b704aa582031553f8a184 | ceba081bb81467b0e5fa5ac1ea292be8d1724de6 | refs/heads/main | 2023-07-08T23:51:47.185558 | 2021-08-23T15:32:05 | 2021-08-23T15:32:05 | 399,155,527 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 542 | py | # Generated by Django 3.1.7 on 2021-04-09 20:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('discussion_board', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='post',
name='anonymous',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='reply',
name='anonymous',
field=models.BooleanField(default=False),
),
]
| [
"noreply@github.com"
] | noreply@github.com |
4e4c07311b235504f423c8a1b0f6499bad4c3b37 | 12edc67a35250d059c9853d7bccb7ef422e87d2c | /processes/nested_process.py | 6087ca38030876c3195cc9e2c94ec137f89ed07e | [] | no_license | MaxymHybalo/serial_bot | 50e1364ee9d329cba21a702ef3bd9481e659c39e | 118928db49c9a8d6ad56e204d44c1d9db91afd0a | refs/heads/master | 2021-05-13T18:16:47.999623 | 2020-09-27T18:00:15 | 2020-09-27T18:00:15 | 116,856,072 | 0 | 0 | null | 2020-10-29T17:57:45 | 2018-01-09T18:44:58 | Python | UTF-8 | Python | false | false | 278 | py |
class NestedProcessor:
def __init__(self, instruction):
self.nested = instruction
self.process = 'nested'
def handle(self):
from processors import InstructionProcessor
queue = InstructionProcessor(self.nested)
queue.process()
| [
"keepass.log@gmail.com"
] | keepass.log@gmail.com |
62ea2be7fc66c3171790c5ad021dad5000e6a6dd | 9819a85dec2b79d3b29d7b377c8726c1f2d1f906 | /ISS_flies.py | f04710c562923e27113690ffbdf16d6ac4f51d57 | [] | no_license | Koluw/wix | 5f6d373d9b758db313da5b3934d21d6a1aec6d26 | 4e1b59bda9a169101a8278b4814cd7b283ebc25b | refs/heads/master | 2022-10-30T11:29:52.920503 | 2020-06-16T15:22:13 | 2020-06-16T15:22:13 | 269,417,763 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,387 | py | import time
import json
from os import path, getcwd, sep
import pymysql
import requests
def read_cities_json():
"""
check the file with geo_points and cities.
rearrange the data to dictionary for next iterations
:return: jsonData => dict with cities [id, name, latitude, longitude]
"""
jsonData = {}
currentDirectory = getcwd()
buf = False
# if we're needed to enter fileName manually
"""
while not buf:
fileName = 'cities'
# fileName = input("Enter file_name of json's cities storage: ")
if ".json" not in fileName:
fileName += '.json'
buf = path.exists(currentDirectory + sep + fileName)
"""
fileName = 'cities.json'
try:
buf = path.exists(currentDirectory + sep + fileName)
if buf:
with open(currentDirectory + sep + fileName, 'r') as sf:
jsonLoad = json.load(sf)
for key in jsonLoad['cities']:
jsonData[key['cityName']] = {'lat': key['lat'], 'lon': key['lon']}
del jsonLoad
else:
raise FileNotFoundError
except FileNotFoundError:
jsonData["error"] = "FileNotExists"
return jsonData
def collect_json(citiesDict, steps=5):
"""
collect the whole json for send to DB(with changed timestamp to UTC)
:param citiesDict: Dict with city's geo_points
:param steps: how many appearance of ISS we want to check
:return: jsonData
"""
jsonData = {}
for city in citiesDict:
jsonData[city] = read_url_json(citiesDict[city]['lat'], citiesDict[city]['lon'], steps)
return jsonData
def read_url_json(lat, lon, steps=2):
"""
get json from API f"http://api.open-notify.org/iss-pass.json?
:param lat: latitude
:param lon: longitude
:param steps: how many appearance above one point is interesting for us
:return: jsonData['response'] with {"risetime": TIMESTAMP, "duration": DURATION}
"""
jsonAPI = f"http://api.open-notify.org/iss-pass.json?lat={lat}&lon={lon}&alt=20&n={steps}".format(lat, lon, steps)
try:
jsonData = requests.get(jsonAPI).json()['response']
except:
jsonData["error"] = "API_BadResponse"
for row in jsonData:
row['UTC'] = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(row['risetime']))
return jsonData
def read_conn_string():
"""
read connection string parameters
:return: jsonData => dict with parameters [host, port, user, pass]
"""
jsonData = {}
currentDirectory = getcwd()
buf = False
fileName = 'conn_string_localhost.json'
try:
buf = path.exists(currentDirectory + sep + fileName)
if buf:
with open(currentDirectory + sep + fileName, 'r') as sf:
jsonLoad = json.load(sf)
for key in jsonLoad:
jsonData[key] = jsonLoad[key]
del jsonLoad
else:
raise FileNotFoundError
except FileNotFoundError:
jsonData["error"] = "FileConnectionNotExists"
return jsonData
def sop(someDict):
"""
function to create table view of collected Data
and put it to MySQL
:param someDict: dictionary with all interested Data
:return:
"""
# Connect to the database
conn_string = read_conn_string()
try:
connection = pymysql.connect(host=conn_string['host'],
port=conn_string['port'],
user=conn_string['user'],
password=conn_string['pass'],
db=conn_string['db'],
charset='utf8',
cursorclass=pymysql.cursors.DictCursor)
for city in someDict:
final_str = ''
for row in someDict[city]:
final_str += "('{0}', {1}, '{2}', '{3}'),".format(city, row['duration'], row['risetime'], row['UTC'])
final_str = final_str[:-1]
with connection.cursor() as cursor:
sql = "INSERT INTO interview.orbital_data_stanley (city_name, duration, UNIX, UTC) VALUES {}".format(final_str)
# print(sql)
cursor.execute(sql)
connection.commit()
print('{0} has been added to DB'.format(city))
except :
print("there was a problem during connection")
finally:
connection.close()
print('insert was successfuly finished')
def step_by_step():
"""
call of all needed functions in correct order
:return: nothing, just call another functions
"""
errors = [
"there were few mistakes during reading file with cities", # during reading file cities
"there were errors during API's work"
]
i = 0
while True:
cities = read_cities_json()
if 'error' in cities:
print(errors[i])
break
i += 1
orbital_data_stanley = collect_json(cities, 1)
if 'error' in orbital_data_stanley:
print(errors[i])
break
# sop(orbital_data_stanley)
for city in orbital_data_stanley:
final_str = ''
for row in orbital_data_stanley[city]:
final_str += "('{0}', {1}, '{2}', '{3}'),".format(city, row['duration'], row['risetime'], row['UTC'])
final_str = final_str[:-1]
print(final_str)
break
# print(orbital_data_stanley)
# orbital_data_stanley = {'Haifa': [{'duration': 245, 'risetime': 1591279496, 'UTC': '2020-06-04 14:04:56'}, {'duration': 437, 'risetime': 1591285312, 'UTC': '2020-06-04 15:41:52'}],
# 'Tel_Aviv': [{'duration': 426, 'risetime': 1591273487, 'UTC': '2020-06-04 12:24:47'}, {'duration': 169, 'risetime': 1591279531, 'UTC': '2020-06-04 14:05:31'}],
# 'Beer_Sheva': [{'duration': 372, 'risetime': 1591285352, 'UTC': '2020-06-04 15:42:32'}, {'duration': 619, 'risetime': 1591291094, 'UTC': '2020-06-04 17:18:14'}],
# 'Eilat': [{'duration': 281, 'risetime': 1591285410, 'UTC': '2020-06-04 15:43:30'}, {'duration': 605, 'risetime': 1591291121, 'UTC': '2020-06-04 17:18:41'}]}
# sop(orbital_data_stanley) # test call
# print(read_url_json('32.085300', '34.781769')) # test call
if __name__ == '__main__':
step_by_step()
| [
"semenov.stan@gmail.com"
] | semenov.stan@gmail.com |
70a701bc5cf1cd1ac9d4ac6d0363562e3c83398d | c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c | /cases/synthetic/tree-big-2951.py | fa63609bcdcdfb979fea5d777ccafaefcce4369d | [] | no_license | Virtlink/ccbench-chocopy | c3f7f6af6349aff6503196f727ef89f210a1eac8 | c7efae43bf32696ee2b2ee781bdfe4f7730dec3f | refs/heads/main | 2023-04-07T15:07:12.464038 | 2022-02-03T15:42:39 | 2022-02-03T15:42:39 | 451,969,776 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 23,286 | py | # Binary-search trees
class TreeNode(object):
value:int = 0
left:"TreeNode" = None
right:"TreeNode" = None
def insert(self:"TreeNode", x:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode(x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode(x)
return True
else:
return self.right.insert(x)
return False
def contains(self:"TreeNode", x:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
class TreeNode2(object):
value:int = 0
value2:int = 0
left:"TreeNode2" = None
left2:"TreeNode2" = None
right:"TreeNode2" = None
right2:"TreeNode2" = None
def insert(self:"TreeNode2", x:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode2(x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode2(x, x)
return True
else:
return self.right.insert(x)
return False
def insert2(self:"TreeNode2", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode2(x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode2(x, x)
return True
else:
return self.right.insert(x)
return False
def contains(self:"TreeNode2", x:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains2(self:"TreeNode2", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
class TreeNode3(object):
value:int = 0
value2:int = 0
value3:int = 0
left:"TreeNode3" = None
left2:"TreeNode3" = None
left3:"TreeNode3" = None
right:"TreeNode3" = None
right2:"TreeNode3" = None
right3:"TreeNode3" = None
def insert(self:"TreeNode3", x:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode3(x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode3(x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert2(self:"TreeNode3", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode3(x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode3(x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert3(self:"TreeNode3", x:int, x2:int, x3:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode3(x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode3(x, x, x)
return True
else:
return self.right.insert(x)
return False
def contains(self:"TreeNode3", x:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains2(self:"TreeNode3", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains3(self:"TreeNode3", x:int, x2:int, x3:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
class TreeNode4(object):
value:int = 0
value2:int = 0
value3:int = 0
value4:int = 0
left:"TreeNode4" = None
left2:"TreeNode4" = None
left3:"TreeNode4" = None
left4:"TreeNode4" = None
right:"TreeNode4" = None
right2:"TreeNode4" = None
right3:"TreeNode4" = None
right4:"TreeNode4" = None
def insert(self:"TreeNode4", x:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode4(x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode4(x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert2(self:"TreeNode4", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode4(x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode4(x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert3(self:"TreeNode4", x:int, x2:int, x3:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode4(x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode4(x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert4(self:"TreeNode4", x:int, x2:int, x3:int, x4:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode4(x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode4(x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def contains(self:"TreeNode4", x:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains2(self:"TreeNode4", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains3(self:"TreeNode4", x:int, x2:int, x3:int) -> bool:
if x < $Member:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains4(self:"TreeNode4", x:int, x2:int, x3:int, x4:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
class TreeNode5(object):
value:int = 0
value2:int = 0
value3:int = 0
value4:int = 0
value5:int = 0
left:"TreeNode5" = None
left2:"TreeNode5" = None
left3:"TreeNode5" = None
left4:"TreeNode5" = None
left5:"TreeNode5" = None
right:"TreeNode5" = None
right2:"TreeNode5" = None
right3:"TreeNode5" = None
right4:"TreeNode5" = None
right5:"TreeNode5" = None
def insert(self:"TreeNode5", x:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode5(x, x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode5(x, x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert2(self:"TreeNode5", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode5(x, x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode5(x, x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert3(self:"TreeNode5", x:int, x2:int, x3:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode5(x, x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode5(x, x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert4(self:"TreeNode5", x:int, x2:int, x3:int, x4:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode5(x, x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode5(x, x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def insert5(self:"TreeNode5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool:
if x < self.value:
if self.left is None:
self.left = makeNode5(x, x, x, x, x)
return True
else:
return self.left.insert(x)
elif x > self.value:
if self.right is None:
self.right = makeNode5(x, x, x, x, x)
return True
else:
return self.right.insert(x)
return False
def contains(self:"TreeNode5", x:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains2(self:"TreeNode5", x:int, x2:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains3(self:"TreeNode5", x:int, x2:int, x3:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains4(self:"TreeNode5", x:int, x2:int, x3:int, x4:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
def contains5(self:"TreeNode5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool:
if x < self.value:
if self.left is None:
return False
else:
return self.left.contains(x)
elif x > self.value:
if self.right is None:
return False
else:
return self.right.contains(x)
else:
return True
class Tree(object):
root:TreeNode = None
size:int = 0
def insert(self:"Tree", x:int) -> object:
if self.root is None:
self.root = makeNode(x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def contains(self:"Tree", x:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
class Tree2(object):
root:TreeNode2 = None
root2:TreeNode2 = None
size:int = 0
size2:int = 0
def insert(self:"Tree2", x:int) -> object:
if self.root is None:
self.root = makeNode2(x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert2(self:"Tree2", x:int, x2:int) -> object:
if self.root is None:
self.root = makeNode2(x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def contains(self:"Tree2", x:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains2(self:"Tree2", x:int, x2:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
class Tree3(object):
root:TreeNode3 = None
root2:TreeNode3 = None
root3:TreeNode3 = None
size:int = 0
size2:int = 0
size3:int = 0
def insert(self:"Tree3", x:int) -> object:
if self.root is None:
self.root = makeNode3(x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert2(self:"Tree3", x:int, x2:int) -> object:
if self.root is None:
self.root = makeNode3(x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert3(self:"Tree3", x:int, x2:int, x3:int) -> object:
if self.root is None:
self.root = makeNode3(x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def contains(self:"Tree3", x:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains2(self:"Tree3", x:int, x2:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains3(self:"Tree3", x:int, x2:int, x3:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
class Tree4(object):
root:TreeNode4 = None
root2:TreeNode4 = None
root3:TreeNode4 = None
root4:TreeNode4 = None
size:int = 0
size2:int = 0
size3:int = 0
size4:int = 0
def insert(self:"Tree4", x:int) -> object:
if self.root is None:
self.root = makeNode4(x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert2(self:"Tree4", x:int, x2:int) -> object:
if self.root is None:
self.root = makeNode4(x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert3(self:"Tree4", x:int, x2:int, x3:int) -> object:
if self.root is None:
self.root = makeNode4(x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert4(self:"Tree4", x:int, x2:int, x3:int, x4:int) -> object:
if self.root is None:
self.root = makeNode4(x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def contains(self:"Tree4", x:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains2(self:"Tree4", x:int, x2:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains3(self:"Tree4", x:int, x2:int, x3:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains4(self:"Tree4", x:int, x2:int, x3:int, x4:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
class Tree5(object):
root:TreeNode5 = None
root2:TreeNode5 = None
root3:TreeNode5 = None
root4:TreeNode5 = None
root5:TreeNode5 = None
size:int = 0
size2:int = 0
size3:int = 0
size4:int = 0
size5:int = 0
def insert(self:"Tree5", x:int) -> object:
if self.root is None:
self.root = makeNode5(x, x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert2(self:"Tree5", x:int, x2:int) -> object:
if self.root is None:
self.root = makeNode5(x, x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert3(self:"Tree5", x:int, x2:int, x3:int) -> object:
if self.root is None:
self.root = makeNode5(x, x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert4(self:"Tree5", x:int, x2:int, x3:int, x4:int) -> object:
if self.root is None:
self.root = makeNode5(x, x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def insert5(self:"Tree5", x:int, x2:int, x3:int, x4:int, x5:int) -> object:
if self.root is None:
self.root = makeNode5(x, x, x, x, x)
self.size = 1
else:
if self.root.insert(x):
self.size = self.size + 1
def contains(self:"Tree5", x:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains2(self:"Tree5", x:int, x2:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains3(self:"Tree5", x:int, x2:int, x3:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains4(self:"Tree5", x:int, x2:int, x3:int, x4:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def contains5(self:"Tree5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool:
if self.root is None:
return False
else:
return self.root.contains(x)
def makeNode(x: int) -> TreeNode:
b:TreeNode = None
b = TreeNode()
b.value = x
return b
def makeNode2(x: int, x2: int) -> TreeNode2:
b:TreeNode2 = None
b2:TreeNode2 = None
b = TreeNode2()
b.value = x
return b
def makeNode3(x: int, x2: int, x3: int) -> TreeNode3:
b:TreeNode3 = None
b2:TreeNode3 = None
b3:TreeNode3 = None
b = TreeNode3()
b.value = x
return b
def makeNode4(x: int, x2: int, x3: int, x4: int) -> TreeNode4:
b:TreeNode4 = None
b2:TreeNode4 = None
b3:TreeNode4 = None
b4:TreeNode4 = None
b = TreeNode4()
b.value = x
return b
def makeNode5(x: int, x2: int, x3: int, x4: int, x5: int) -> TreeNode5:
b:TreeNode5 = None
b2:TreeNode5 = None
b3:TreeNode5 = None
b4:TreeNode5 = None
b5:TreeNode5 = None
b = TreeNode5()
b.value = x
return b
# Input parameters
n:int = 100
n2:int = 100
n3:int = 100
n4:int = 100
n5:int = 100
c:int = 4
c2:int = 4
c3:int = 4
c4:int = 4
c5:int = 4
# Data
t:Tree = None
t2:Tree = None
t3:Tree = None
t4:Tree = None
t5:Tree = None
i:int = 0
i2:int = 0
i3:int = 0
i4:int = 0
i5:int = 0
k:int = 37813
k2:int = 37813
k3:int = 37813
k4:int = 37813
k5:int = 37813
# Crunch
t = Tree()
while i < n:
t.insert(k)
k = (k * 37813) % 37831
if i % c != 0:
t.insert(i)
i = i + 1
print(t.size)
for i in [4, 8, 15, 16, 23, 42]:
if t.contains(i):
print(i)
| [
"647530+Virtlink@users.noreply.github.com"
] | 647530+Virtlink@users.noreply.github.com |
8107640d66d0dd58eb2d0351d0559824dc3a2c98 | c29763f930c7c00b435a9b25dddf7f6e2e8548a1 | /Atividades disciplinas/6 periodo/IA/algoritmo de dijkstra/test.py | 6417af691864735fbf0325a743f03bdf7e10a868 | [] | no_license | jadsonlucio/Faculdade | f94ae6e513bb783f01c72dcb52479ad4bb50dc03 | 2ca553e8fa027820782edc56fc4eafac7eae5773 | refs/heads/master | 2020-07-06T20:34:10.087739 | 2019-12-07T20:45:55 | 2019-12-07T20:45:55 | 203,131,862 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,172 | py | import numpy as np
from map.location import Location, calc_distance
from map.map import Map
COORDINATES_MAP_TEST_1 = {
"latitude_min" : 0,
"latitude_max" : 10,
"longitude_min" : 0,
"longitude_max" : 10
}
CIDADES_ALAGOAS = list(open("tests/cidades_alagoas.txt", "r").readlines())[:10]
def generate_random_sample(locations_names, latitude_min, latitude_max,
longitude_min, longitude_max):
locations = []
for location_name in locations_names:
latitude = np.random.uniform(latitude_min + 1, latitude_max - 1)
longitude = np.random.uniform(longitude_min + 1, longitude_max - 1)
locations.append(Location(location_name, latitude,longitude))
for i in range(len(locations)):
for j in range(i + 1, len(locations), 1):
if np.random.random() > 0.7:
cost = calc_distance(*locations[i].real_pos, *locations[j].real_pos)
locations[i].add_conection(locations[j], cost)
return locations
def get_map_test_1():
locations = generate_random_sample(CIDADES_ALAGOAS, **COORDINATES_MAP_TEST_1)
return Map(locations, **COORDINATES_MAP_TEST_1) | [
"jadsonaluno@hotmail.com"
] | jadsonaluno@hotmail.com |
4759c10925bd4a63b1dd754e5e6ed81b3d284496 | 2f766f5e8af11bf35796978145c46847d64d3ded | /cppy/test/processor_test.py | 993ab5c6e0ce785b01f61dc7334b358cd698e245 | [
"MIT"
] | permissive | quantosauros/cppyProject | c8bb4d23326499241dd7925952a8ca2fd23c6d51 | 5c8bbb9830c4254f44473e9f35229c2ca142901b | refs/heads/master | 2021-01-15T08:31:19.382486 | 2016-08-21T00:27:52 | 2016-08-21T00:27:52 | 65,473,982 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,279 | py | # coding=utf-8
from cppy.adaptor import CpRqRpClass, CpSubPubClass
from cppy.processor import EventProcessor
evntproc = None
@CpRqRpClass('CpSysDib.StockChart')
class StkChart(object):
def __init__(self):
self.itm_cod = itm_cod
def setInputValue(self, inputType, inputValue):
self.inputType = inputType
self.inputValue = inputValue
def request(self, com_obj):
com_obj.SetInputValue(0, self.itm_cod)
com_obj.SetInputValue(1, ord('2'))
com_obj.SetInputValue(4, 100)
com_obj.SetInputValue(5, [0,5,8,9])
com_obj.SetInputValue(6, ord('D'))
com_obj.Request()
def response(self, com_obj):
cnt = com_obj.GetHeaderValue(3) # 수신개수
for i in range(cnt):
if i == 98:
# 98번째에 show_series라는 키를 전달
evntproc.push('show_series', self.itm_cod)
if i == 0:
evntproc.push('show_start', 'start')
# 키와 값을 인자로 하여 이벤트처리기에 전달
evntproc.push(self.itm_cod + '_clpr', com_obj.GetDataValue(0,i))
def echo(serieses, key, dat):
print ('key:%s, dat:%s'%(key, dat))
def show_series(serieses, key, dat):
if dat == 'start':
print ('start')
if dat == 'A003540':
for val in serieses['A003540_clpr']:
print (val)
# 윈도우의 경우 multiprocessing 사용시 (EventProcessor)
# if __name__ == "__main__" 에서 사용해야함
# https://docs.python.org/2/library/multiprocessing.html
if __name__ == "__main__":
itm_cod = "A005930"
# 이벤트처리기 구동
evntproc = EventProcessor()
# 옵저버를 등록함, A003540으로 시작하는 키가 도착하면 echo 를 수행함
evntproc.add_observer([itm_cod + '*'], echo)
# 옵저버를 등록함, show으로 시작하는 키가 도착하면 show_series를 수행
evntproc.add_observer(['show*'], show_series)
evntproc.start()
# 차트 데이터 요청 (비동기)
stkchart = StkChart()
stkchart.request()
import pythoncom, time
while True:
pythoncom.PumpWaitingMessages()
time.sleep(0.01)
| [
"Jay@DESKTOP-2NATO2G"
] | Jay@DESKTOP-2NATO2G |
f017ec6bfa09c5911b89cbadbbaa324ad90d63b7 | 0c1525f26d552aa9985abbc68984dee0cf4bd082 | /basic3.py | 1994531c57294fa5483893324e555ae1226993a7 | [] | no_license | junpei-oyama/kadai-N | 8c51fc2072acd8091bc7968af63e999fae93852a | f4be36bc713efc3d7b83fd6d43f2b493c2a1da96 | refs/heads/master | 2020-08-08T07:55:25.069459 | 2019-10-11T00:40:09 | 2019-10-11T00:40:09 | 213,785,665 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 544 | py | import torch
def main():
"""
代入や要素の指定
"""
t = torch.tensor([[1, 2, 3], [4, 5, 6]])
print(t)
print(t.dtype)
# 特定の要素
print(t[0, 2])
# スライス
print(t[:, 1])
# 再代入
t[0, 0] = 11
print(t)
# 再代入
t[1] = 22 # 複数要素に再代入される点に注意!
print(t)
# スライス利用の再代入
t[:, 1] = 33
print(t)
# ブールインデックス参照
print(t[t < 20])
if __name__ == '__main__':
main()
| [
"junpei.oyama.ai@gmail.com"
] | junpei.oyama.ai@gmail.com |
251411a9333fbd7da3a0557d59516ffd7672af6c | f6d8f211bd87b47b511ac0b6599806ab3131999f | /04-case-study-interface-design/ex_4_12_5.py | 937b06979b4f78846f3bdcb3f460fea8fed15b30 | [] | no_license | csu-xiao-an/think-python | 6cea58da4644cd1351112560e75de150d3731ce9 | 8177b0506707c903c3d4d9a125c931aba890cc0c | refs/heads/master | 2020-07-26T19:35:38.919702 | 2019-09-16T03:33:15 | 2019-09-16T03:33:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,746 | py | """This module contains a code for ex.5 related to ch.4.12.
Think Python, 2nd Edition
by Allen Downey
http://thinkpython2.com
"""
import math
import turtle
def polyline(t, n, length, angle):
"""Draws n line segments.
:param t: Turtle object
:param n: number of line segments
:param length: length of each segments
:param angle: degrees between segments
"""
for i in range(n):
t.fd(length)
t.lt(angle)
def arc(t, r, angle):
"""Draws an arc with the given radius and angle
:param t: Turtle object
:param r: radius of the arc
:param angle: angle subtended by the arc, in degrees
"""
arc_length = 2 * math.pi * r * abs(angle) / 360
n = int(arc_length / 4) + 3
step_length = arc_length / n
step_angle = float(angle) / n
polyline(t, n, step_length, step_angle)
def arch_spiral(t, n, length=4):
"""Draws an Archimedian spiral.
:param t: Turtle object
:param n: number of line segments
:param length: length of each segment
https://en.wikipedia.org/wiki/Archimedean_spiral
"""
a = 0.01 # how loose the initial spiral starts out (larger is looser)
b = 0.0002 # how loosly coiled the spiral is (larger is looser)
theta = 0.0
for i in range(n):
t.fd(length)
dtheta = 1 / (a + b * theta)
t.lt(dtheta)
theta += dtheta
def fib_spiral(t, n):
"""Draws a Fibonacсi spiral.
:param t: Turtle object
:param n: length of sequence
"""
a, b = 0, 1
for i in range(n):
arc(t, a, 90)
a, b = b, a+b
if __name__ == '__main__':
bob = turtle.Turtle()
# arch_spiral(bob, 200)
fib_spiral(bob, 15)
bob.hideturtle()
turtle.mainloop()
| [
"cccp2006_06@mail.ru"
] | cccp2006_06@mail.ru |
654cc90332c09abc4bdcbd210bb7af7224f65258 | f2557d3a984cd4a8295d8cb71b1ccacccdadeae5 | /2016-2017/unzip.py | 2ed29b7cafa0751711346f7a287dede9408fafbd | [] | no_license | fridayhub/exercise | 6780c9e08d42139e5ec46aeb6cbc3369bac76140 | 3ff44f3fd4b7b2f88ab6d08845013c2150163562 | refs/heads/master | 2021-06-19T02:46:28.353282 | 2017-07-11T03:13:06 | 2017-07-11T03:13:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 534 | py | #!/usr/bin/evn python
#-*- coding: utf-8 -*-
import os
import sys
import zipfile
print "Processing File " + sys.argv[1]
file=zipfile.ZipFile(sys.argv[1],"r")
for name in file.namelist():
utf8name=name.decode('gbk')
print "Extracting " + utf8name
pathname = os.path.dirname(utf8name)
if not os.path.exists(pathname) and pathname != "":
os.makedirs(pathname)
data = file.read(name)
if not os.path.exists(utf8name):
fo = open(utf8name, "w")
fo.write(data)
fo.close
file.close()
| [
"liujinghang@tandatech.com"
] | liujinghang@tandatech.com |
fb18817c77ca05588928bd7ba6e85114aa0e0db5 | f40da1aaadbc9b2eee464964f41b03131db50489 | /tapd_req/xls.py | 1677a14088ac7354d7dfcf2c2e3cbd7956295e1d | [] | no_license | BensonMax/Tapd | a8231d090a045613cd8601d7edc596286b04cfb0 | 7eb908182a6e6c1dfed530e7957f0ab58109ec40 | refs/heads/master | 2020-04-15T20:03:04.045651 | 2018-10-11T15:20:30 | 2018-10-11T15:20:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,901 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import xlwt
from config import XlsFormatConfig
from xlutils.copy import copy
import xlrd
DEFAULT_STYTLE = xlwt.Style.easyxf(XlsFormatConfig.DEFAULT_FORMAT)
ABNORMAL_STYTLE = xlwt.Style.easyxf(XlsFormatConfig.ABNORMAL_FORMAT)
# use open_xls(filepath) to open the file named *.xls, and it will return a excel workbook, you can use it to write data.
# use write_xls(workbook, sheet, row, col, string, style) to write data:
# The workbook was returned by open_xls(filepath), and the default cell style is: [fontname: YaHei, fontsize: 11, and with border]
# use save_xls(filepath, workbook) to save *.xls. Don't forget call it after you write the data into file.
def open_xls(filepath):
r""" 通过 excel表路径 打开excel表,返回一个excel工作表对象,用于写入excel数据 """
rb = xlrd.open_workbook(filepath, formatting_info = True)
wbk = copy(rb)
return wbk
def write_xls(wbk, sheet, row, col, str1, styl = DEFAULT_STYTLE):
r""" 写入excel表, 参数分别为: 工作表对象(通过open_xls()得到、写入的分页名、写入行、写入列、写入格式), 此函数用默认格式"""
ws = wbk.get_sheet(sheet)
ws.write(row, col, str1, styl)
def write_abnromal_xls(wbk, sheet, row, col, str1, styl = ABNORMAL_STYTLE):
r""" 写入excel表, 参数分别为: 工作表对象(通过open_xls()得到、写入的分页名、写入行、写入列、写入格式), 此函数用异常格式"""
ws = wbk.get_sheet(sheet)
ws.write(row, col, str1, styl)
def save_xls(filepath, wbk):
r""" 报错excel表, 将 wbk(工作表对象) 保存到给定的路径中"""
wbk.save(filepath)
if __name__ == '__main__':
wb = open_xls('test.xls')
write_abnromal_xls(wb, u'甘芳琳;', 10, 10, u'中文啊啊啊阿萨德吉tetw是点分解fooooo')
save_xls('test.xls', wb)
| [
"stcnchenxin@163.com"
] | stcnchenxin@163.com |
47637c1fadc412f5bf100a0f462a63cc7d789865 | d2d926e6113e5cb78f0cd0c6f7b045d6c0c18672 | /Socket_Programming/Read_Write_Server/client.py | 0da15992d76570d0bb69b39acb7219a3c1df0286 | [] | no_license | Saipadmesh/networking | a23706a923b38c34b46e45f0e6cb0a022d93e303 | 608773d6985f44ed2c1ad5762f65684a1747bcf6 | refs/heads/main | 2023-07-09T23:33:44.194037 | 2021-08-05T13:18:44 | 2021-08-05T13:18:44 | 390,595,667 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 747 | py | import socket
import os
SEPARATOR = "<SEPARATOR>"
BUFFER_SIZE = 4096
filename = "test.txt"
filesize = os.path.getsize(filename)
# -------------------------
uname = input("Enter username: ")
pw = input("Enter password: ")
with open(filename, 'w') as file:
file.write(uname+" "+pw)
# -------------------------
HOST = '127.0.0.1' # Server's hostname or IP address
PORT = 8800 # Port used by server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
print('Connected...')
s.send(f"{filename}{SEPARATOR}{filesize}".encode())
# bufsize argument of recv() is 1024, which is max amount of data that can be received at once
data = s.recv(BUFFER_SIZE)
print('Received: ', repr(data))
| [
"saipadmesh@gmail.com"
] | saipadmesh@gmail.com |
55d41b48f828532f110cd17acc09ff642715c97a | 8053816d8f8681718312bc907603ddfbe7d6c888 | /Drunkard’sWalk.py | b8034ff092beadb9aae9bc98a198ab6c781c053f | [] | no_license | MalachiStoll/MIS3640 | cce994ec6bff8b96960bbbe0cc5ec58a83a9af38 | f43e77544db2e2064233fc13a08de9f4a686bdd2 | refs/heads/master | 2021-01-25T16:53:46.148146 | 2017-12-02T04:06:36 | 2017-12-02T04:06:36 | 102,031,020 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 634 | py | import turtle
import random
def drunkards_walk_turtle (n):
x = 0
y = 0
t = turtle.Turtle()
direction = (1,2,3,4)
for i in range(n):
walk = random.choice(direction)
if walk == 1:
t.fd(25)
y += 1
if walk == 2:
t.rt(90)
t.fd(25)
x += 1
if walk == 3:
t.lt(-25)
y -= 1
if walk == 4:
t.lt(270)
t.fd(25)
x -= 1
distance = (x+y)
print("The Distance between start and end is %d Blocks " %(distance))
turtle.mainloop()
drunkards_walk_turtle(6)
| [
"mstoll2@babson.edu"
] | mstoll2@babson.edu |
69ae9638c27d0ecc84ac41bbef0eda6ecc436c64 | 2fbc642cb0fe985d7308f3b59a1452862ad12a26 | /castle/testgen.py | 943eca21927a12527b61400dd66117ebda13baab | [] | no_license | saribekyan/rau-sp14-contest | 553ff0a291581c97fad489f4240bf57edf99699c | 26b515b9ff45951d326c2c54a65c7e1e1768afd6 | refs/heads/master | 2021-01-23T16:37:25.770261 | 2014-04-07T16:59:24 | 2014-04-07T16:59:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,348 | py | num = 1
def puttest(d, find_num):
f = open('tests/' + str(num).zfill(3), 'w')
f.write(str(len(d)) + ' ' + str(find_num) + '\n')
for x in d:
f.write(str(x[0]) + ' ' + str(x[1]) + '\n')
f.close()
f = open('tests/' + str(num).zfill(3) + '.a', 'w')
if find_num in [x[0] for x in d]:
f.write('YES\n')
else:
f.write('NO\n')
f.close()
print 'test', num, 'done'
global num
num += 1
INF = 1000000000
import random
def gen_rand(n, M = INF):
while True:
v = list(set([random.randint(-M, M) for i in xrange(n)]))
if len(v) != 1:
break
n = len(v)
v = sorted(v)
p = range(n)
random.shuffle(p)
d = [0 for i in xrange(n)]
for i in xrange(n):
d[p[i]] = ((v[i], p[(i+1)%n] + 1))
return d
# small manual tests
puttest([(1, 1)], 2)
puttest([(1, 1)], 1)
puttest([(1, 2), (3, 1)], 2)
puttest([(1, 2), (3, 1)], 3)
n = 100000
puttest([(i, (i+1)%n + 1) for i in xrange(n)], n / 2) # 1...n test, exists
puttest([(i, (i+1)%n + 1) for i in xrange(n)], -1) # 1...n test, does not exist
N = [100, 1000, 5000, 100000, 100000, 100000]
# exist
for n in N:
d = gen_rand(n)
n = len(d)
puttest(d, d[random.randint(0, n-1)][0])
# may not exist
for n in N:
d = gen_rand(n)
puttest(d, random.randint(-INF, INF))
| [
"hayks@mit.edu"
] | hayks@mit.edu |
93523af3b7e2fe2d9ea4252cd1aa19c57212c422 | 01ced2a383aca0371c936dadab32d4dd722127df | /shiritori.py | 2a14b64d6d25b6b8f91ca8773161fab54d4b0ec6 | [] | no_license | lamboxd/ListManipulation | 98105816b66e2e8e9828d4590cf1e981a912caed | fe28355d1346caa0b969c7eb7869856b1b78fc45 | refs/heads/master | 2020-04-02T11:31:13.447656 | 2018-10-23T21:07:27 | 2018-10-23T21:07:27 | 154,393,171 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,747 | py | def Shiritori():
#read from file and store in lines list
text_file = open("word_list.txt", "r")
lines = file.read(text_file).splitlines()
#get the first word.
first_word = raw_input("Please type a word: ")
#The first word can throw one error: word not found in list.
while first_word not in lines:
print "You didn't type a word found in word_list.txt"
first_word = raw_input("Please type a word: ")
#store the first word in used words list
used_words = []
used_words.append(first_word)
#store the last letter of the first word
previous_letter = first_word[-1:]
#continue playing the game
while True:
current_word = raw_input("Please type a word: ")
#check if first letter of current word is the same as last letter of previous word.
#if not, throw error
first_letter = current_word[0]
if first_letter is not previous_letter:
print "You didn't type a word starting with '" + str(previous_letter) + "'."
continue
#check if current word not in used words
#if used before, throw error.
if current_word in used_words:
print "You typed a word that has been typed before."
continue
#check if current word is in lines
#if not, throw error.
if current_word not in lines:
print "You didn't type a word found in word_list.txt"
continue
#update used words to store current_word and previous letter to be current word's last letter.
previous_letter = current_word[-1:]
used_words.append(current_word)
text_file.close()
Shiritori() | [
"clare.yip.2015@smu.edu.sg"
] | clare.yip.2015@smu.edu.sg |
49dbafb4ad1aeaf9119acdede9c7aa71c786d66a | 727f1bc2205c88577b419cf0036c029b8c6f7766 | /out-bin/py/google/fhir/models/model_test.runfiles/pypi__tensorflow_1_12_0/tensorflow-1.12.0.data/purelib/tensorflow/python/layers/utils.py | 19fe50abb25751952deed4e3e7c7ae32c95d8ff6 | [
"Apache-2.0"
] | permissive | rasalt/fhir | 55cf78feed3596a3101b86f9e9bbf6652c6ed4ad | d49883cc4d4986e11ca66058d5a327691e6e048a | refs/heads/master | 2020-04-13T00:16:54.050913 | 2019-01-15T14:22:15 | 2019-01-15T14:22:15 | 160,260,223 | 0 | 0 | Apache-2.0 | 2018-12-03T22:07:01 | 2018-12-03T22:07:01 | null | UTF-8 | Python | false | false | 174 | py | /home/rkharwar/.cache/bazel/_bazel_rkharwar/c4bcd65252c8f8250f091ba96375f9a5/external/pypi__tensorflow_1_12_0/tensorflow-1.12.0.data/purelib/tensorflow/python/layers/utils.py | [
"ruchika.kharwar@gmail.com"
] | ruchika.kharwar@gmail.com |
33459eb19aaa987578d5674720df2bada6140882 | 3161173491d34339140265e4f6810e688aff1034 | /sw-tm4c-2.1.4.178/third_party/ptpd-1.1.0/tools/ptp_plot.py | a4d547cc846e993d259c2dd8b67144b3286b8565 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer",
"ISC"
] | permissive | ti-cortex-m4/tm4c1294ncpdt | 853aaed9b7cb39c489568ae8023ed4bd64ba8d76 | 629defb60af370595d7c33917ee8459642d3b62e | refs/heads/master | 2023-07-25T06:14:03.666763 | 2023-07-23T14:24:03 | 2023-07-23T14:24:03 | 28,406,657 | 5 | 3 | null | 2022-08-28T07:21:38 | 2014-12-23T16:03:26 | C | UTF-8 | Python | false | false | 6,283 | py | #! /usr/bin/env python2.6
# Copyright (c) 2010, Neville-Neil Consulting
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# Neither the name of Neville-Neil Consulting nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Author: George V. Neville-Neil
#
# Description:
"""ptp_plot.py -- Plot PTP delays reported by the slave.
This program takes a ptp log file generated by the slave
and plots various times on a graph
This program requires at least python2.6 as well as numpy
and gnuplot support.
"""
import csv
import datetime
import subprocess
import sys
import tempfile
from numpy import *
import Gnuplot, Gnuplot.funcutils
def usage():
sys.exit()
def main():
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-a", "--all", dest="all", default=0,
help="show all entries")
parser.add_option("-t", "--type", dest="type", default="delay",
help="plot the delay or offset")
parser.add_option("-l", "--logfile", dest="logfile", default=None,
help="logfile to use")
parser.add_option("-s", "--start", dest="start", default="09:30:00",
help="start time")
parser.add_option("-e", "--end", dest="end", default="16:30:00",
help="end time")
parser.add_option("-r", "--roll", dest="roll", type=int, default=0,
help="number of days to roll at the start")
parser.add_option("-p", "--print", dest="png", default=None,
help="file to print the graph to")
parser.add_option("-y", "--ymin", dest="ymin", default="0.000000",
help="minimum y value")
parser.add_option("-Y", "--ymax", dest="ymax", default="0.001000",
help="maximum y value")
parser.add_option("-S", "--save", dest="save", default=None,
help="save file name")
(options, args) = parser.parse_args()
if ((options.type != "delay") and (options.type != "offset")):
print "You must choose either delay or offset."
usage()
try:
logfile = csv.reader(open(options.logfile, "rb"))
except:
print "Could not open %s" % options.logfile
sys.exit()
#
# This is an ugly hack, but it turns out that gnuplot
# is better able to plot time data if we write it out
# in the familiar format to a temporary file and
# then plot from the file rather than building up
# arrays of data.
#
tmpfile = tempfile.NamedTemporaryFile()
savefile = None
if (options.save != None):
savefile = open(options.save, "w")
first = True
for line in logfile:
# Split off the microseconds
try:
dt = line[0].rpartition(':')[0]
except:
continue
now = datetime.datetime.strptime(dt, "%Y-%m-%d %H:%M:%S")
if (first == True):
if (options.all == 0):
start = datetime.datetime.strptime(options.start, "%H:%M:%S")
else:
start = now
start = start.replace(year=now.year, month=now.month,
day=now.day + options.roll)
end = datetime.datetime.strptime(options.end, "%H:%M:%S")
end = end.replace(year=now.year, month=now.month,
day=now.day + options.roll)
first = False
if ((now > end) and (options.all == 0)):
break
if ((now > start) or (options.all != 0)):
if (options.type == "delay"):
tmpfile.write("%s %f\n" % (dt, float(line[3])))
if (savefile != None):
savefile.write("%s %f\n" % (dt, float(line[3])))
else:
tmpfile.write("%s %f\n" % (dt, float(line[4])))
if (savefile != None):
savefile.write("%s %f\n" % (dt, float(line[4])))
plotter = Gnuplot.Gnuplot(debug=1)
plotter('set data style dots')
if (options.type == "delay"):
plotter.set_range('yrange', [options.ymin, options.ymax])
plotter.ylabel('Seconds\\nOne Way Delay')
else:
plotter.set_range('yrange', [options.ymin, options.ymax])
plotter.ylabel('Seconds\\nOffset')
if (options.all == 0):
plotter.xlabel(options.logfile + " " + options.start + " - " + options.end)
else:
plotter.xlabel(options.logfile + " " + str(start) + " - " + str(now))
plotter('set xdata time')
plotter('set timefmt "%Y-%m-%d %H:%M:%S"')
tmpfile.flush()
plotter.plot(Gnuplot.File(tmpfile.name, using='1:3'))
if (options.png != None):
plotter.hardcopy(options.logfile + "-" + options.type + ".png", terminal='png')
raw_input('Press return to exit')
else:
raw_input('Press return to exit')
if __name__ == "__main__":
main()
| [
"ti.cortex.m4@gmail.com"
] | ti.cortex.m4@gmail.com |
91b39b07deb15abbeac4e2fe4abcfb62145fcab9 | 01e72d1c14068175b6052cbd30f7087c6dc2d73a | /steganography_jpeg.py | d44839b4bef4cc939dee65e31bbb3b6507559e47 | [] | no_license | CrazyUmka/EncryptMessage | 1b00e60edc1e873b5c0177bdf10495d04dbae56e | 94ccb799fc4d5d14994e2167557e35b4e2337c22 | refs/heads/master | 2016-08-07T07:41:31.011015 | 2014-05-24T23:23:59 | 2014-05-24T23:23:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,099 | py | __author__ = 'Grigory'
#coding:utf8
import os
from Crypto.Cipher import AES
import base64
from pksc7 import PKCS7Encoder
class DecryptError(Exception):
pass
class Encryptions(object):
@staticmethod
def decrypt_message(image):
index = image.rfind('\\') + 1
if image == -1:
name_file = image
else:
name_file = image[index:]
file_load = open(image, 'rb')
data_file = file_load.read().decode('cp866')
file_load.close()
index = data_file.rfind(u'_') + 1
if index == 1:
raise DecryptError(u'Файл не возможно расшифровать, проверьте его целостность!')
size_file = int(data_file [index : ])
message = data_file [size_file : index - 1]
message_decrypt = Encryptions.run_aes(name_file, message, u'Decode')
print u'Расшифрованно новое сообщение:\n\t' + message_decrypt
@staticmethod
def run_aes(key, text=u'', user_IV=u'magic_great_dead_or_alive', type_aes=u'Encode'):
block_size = 32
password = ""
IV = ""
# padding = '{'
# Pad = lambda s: s + (block_size - len(s) % block_size) * padding
# EncodeAES = lambda c, s: base64.b64encode(c.encrypt(Pad(s)))
# DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(padding)
Pad = lambda s: PKCS7Encoder().encode(s)
if len(key) != 32:
while True:
password += key
if len(password) > 32:
password = password[:32]
break
if len(user_IV) != 16:
while True:
IV += user_IV
if len(IV) > 16:
IV = IV[:16]
break
encoder = PKCS7Encoder()
chiper = AES.new(password, AES.MODE_CBC, IV)
if type_aes in u'Encode':
# return EncodeAES(chiper, text)
encode_text = encoder.encode(text)
return base64.b64encode(chiper.encrypt(encode_text))
else:
result = chiper.decrypt(base64.b64decode(text))
return encoder.decode(result)
# return DecodeAES(chiper, text)
class JpegDecode(Encryptions):
def __init__(self, image=u'17014.jpg', message=u'Privet lol, kak dela?'):
self.image_shifr = image
self.message_shifr = message
def decode_jpeg(self):
file_image = open(self.image_shifr, 'rb')
size = str(os.path.getsize(self.image_shifr))
data_image = file_image.read().decode('cp866')
file_image.close()
# dir_file = self.image_shifr[: self.image_shifr.rfind(u'\\') + 1]
name_rec_file = self.image_shifr[self.image_shifr.rfind(u'\\') + 1: self.image_shifr.rfind(u'.')]
name_rec_file += u'_last.jpg'
message = JpegDecode.run_aes(name_rec_file, self.message_shifr)
data_image += message + u'_' + size.decode('utf8')
file_rec = open(name_rec_file, 'wb')
file_rec.write(data_image.encode('cp866'))
file_rec.close()
print u'End Decode Successful'
return name_rec_file
class Mp3Decode(Encryptions):
def __init__(self, mp3_file, message):
self.file_decode = mp3_file
self.message = message
def decode_mp3(self):
file_mp3 = open(self.file_decode, 'rb')
size_file = os.path.getsize(self.file_decode)
data = file_mp3.read()
file_mp3.close()
data += self.message + u'_' + size_file
name_rec_file = self.file_decode[self.file_decode.rfind(u'\\') + 1: self.file_decode.rfind(u'.') - 1]
name_rec_file += u'last.jpg'
file_rec = open(name_rec_file, 'wb').write(data)
file_rec.close()
if __name__ in '__main__':
result = Encryptions.run_aes('12345',
'Привет',
)
print result
| [
"grigoryvydrin@gmail.com"
] | grigoryvydrin@gmail.com |
b24ecd6b7da4cd1f2cfad9598bcfcbe2905ee9a3 | 0c9c63ea2e9416edea44bd9a1a9b20727073e8c2 | /app/tests/test_cred.py | 122aa6399ee1bf6b76ae6f6a473398844f147dcb | [
"Apache-2.0"
] | permissive | cetaciemat/im-dashboard | b5764b3598c2ca77b309c4ab1fe03dd41b054b9e | ada22a016ebeff12f5474b5715dec865865c7a55 | refs/heads/master | 2023-02-23T05:16:10.064713 | 2021-01-26T09:07:25 | 2021-01-26T09:07:25 | 297,939,772 | 0 | 1 | Apache-2.0 | 2020-12-11T11:44:12 | 2020-09-23T10:53:16 | HTML | UTF-8 | Python | false | false | 1,958 | py | #! /usr/bin/env python
#
# IM - Infrastructure Manager
# Copyright (C) 2011 - GRyCAP - Universitat Politecnica de Valencia
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import unittest
import os
from app.cred import Credentials
class TestCredentials(unittest.TestCase):
"""Class to test the Credentials class."""
def tearDown(self):
os.unlink('/tmp/creds.db')
def test_get_cred(self):
creds = Credentials("sqlite:///tmp/creds.db")
res = creds._get_creds_db()
str_data = '{"project": "project_name"}'
res.execute("replace into credentials (data, userid, serviceid) values (%s, %s, %s)",
(str_data, "user", "serviceid"))
res.close()
res = creds.get_cred("serviceid", "user")
self.assertEquals(res, {'project': 'project_name'})
def test_write_creds(self):
creds = Credentials("sqlite:///tmp/creds.db")
creds.write_creds("serviceid", "user", {"project": "new_project"})
res = creds.get_cred("serviceid", "user")
self.assertEquals(res, {"project": "new_project"})
def test_delete_creds(self):
creds = Credentials("sqlite:///tmp/creds.db")
creds.delete_cred("serviceid", "user")
res = creds.get_cred("serviceid", "user")
self.assertEquals(res, {})
if __name__ == '__main__':
unittest.main()
| [
"micafer1@upv.es"
] | micafer1@upv.es |
2bd0039bf55ddcf9f83d04a00689bb71f881d33f | 35852273318e44367c56fb32802dcc57b618af68 | /django-admin | 517431b026d0c05668533c9e1b488232a81ad044 | [] | no_license | saturn94/my-first-blog | a9fe5a7b96c5afd73e3218b09d0d2e117fe5de39 | 4fafab5cb3d7283bfc15b7c2ac74e8eb3ab4ee60 | refs/heads/master | 2021-01-01T03:57:25.617602 | 2016-04-28T00:06:07 | 2016-04-28T00:06:07 | 57,252,540 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 280 | #!/home/saturn/site2/bin/python3
# -*- 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())
| [
"saturn.94@mail.ru"
] | saturn.94@mail.ru | |
38829ed63b06279a2b3b97763569d6cf48565c0b | ffcf03784f08aa5798433438db7087ce820bd592 | /interview_prep/array_manipulation.py | 5f0779473be2acc5d45be91583399f0992181412 | [] | no_license | k18a/algorithms | 0681b3c876dd4e9e3199243ec21a3ea7221da12d | 4624913a6ad6b570720734dd797306fe4f219734 | refs/heads/master | 2023-01-02T04:33:00.898969 | 2020-10-23T08:17:01 | 2020-10-23T08:17:01 | 301,701,112 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,021 | py | #!/bin/python3
# Complete the arrayManipulation function below.
def arrayManipulation(n, queries):
# initialize operations_array with 1 extra value
operations_array = [0]*(n+1)
# loop through queries to update operations array
for query in queries:
# all values after first index will be added by value
operations_array[query[0]-1] += query[2]
# all values after second index will be subtracted by value
operations_array[query[1]] -= query[2]
# initialize temp and max values
temp_value = 0
max_value = -99999999
# loop through array
for value in operations_array:
# add array value to temp_value to get value that would have been
temp_value += value
# update max value if necessary
if temp_value > max_value:
max_value = temp_value
return max_value
if __name__ == '__main__':
n = int(5)
queries = [[1,2,100],[2,5,100],[3,4,100]]
result = arrayManipulation(n, queries)
print(result) | [
"k.arunachalam@ed.ac.uk"
] | k.arunachalam@ed.ac.uk |
f2186a23aef4cd044099610d9bfd64c0d45659b7 | 358f98d2ef482903c7657c572d8498654b1b1c6d | /ref_code/4-3__withsessionfeed.py | 4779370150274a1f72eebdd0e7deb721848cf46c | [] | no_license | wssunn/deep_learning_tensorflow | 8ebcd0afd63851afb275ca9b236537731e1b9a07 | 104b6fea59e2ff71caa3da5519e7b851ee28ac32 | refs/heads/master | 2022-07-03T05:09:36.407989 | 2020-05-15T01:42:48 | 2020-05-15T01:42:48 | 263,839,338 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 362 | py | # -*- coding: utf-8 -*-
import tensorflow as tf
a = tf.placeholder(tf.int16)
b = tf.placeholder(tf.int16)
add = tf.add(a, b)
mul = tf.multiply(a, b)
with tf.Session() as sess:
# Run every operation with variable input
print ("相加: %i" % sess.run(add, feed_dict={a: 3, b: 4}))
print ("相乘: %i" % sess.run(mul, feed_dict={a: 3, b: 4}))
| [
"sunning@sunningdeMacBook-Pro.local"
] | sunning@sunningdeMacBook-Pro.local |
f6759c7327f79c3894884cd7a6487d13cc7ade46 | f1150ba464725672be66227d9eb29d13eb81a385 | /untitled/Velocimetro Con Movimiento/Velocimetro2.py | 78a0fda229286dd4bd96483011edc7454af44bde | [] | no_license | jocade1/DIN | 6573ee4a50e28665e16dd4c0660d53444e7c7c9c | 52e3219656bd826700684ef26723969f4fabab45 | refs/heads/master | 2020-12-22T05:19:17.344454 | 2020-02-21T10:53:08 | 2020-02-21T10:53:08 | 236,679,857 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 247 | py | from tkinter import *
from tkinter import ttk
from Speedodom import Speedodom
root = Tk()
f = ttk.Frame()
f.pack()
spd = Speedodom(f, width=400, height=400)
spd.grid(row=0, column=0)
for v in (0,240,0.1):
spd.setspedd(v)
root.mainloop()
| [
"josealberto1407@gmail.com"
] | josealberto1407@gmail.com |
74b5b828f3763b47c0928d9ef000736bbb8defdc | 5c71d64db74c4c39b6e9adb70036a56e197f111c | /amsterdam-airbnb/CV_LinearRegression_selectedfeatures.py | 7bf77d7e9d82ecfe3d6a251211a286ad6095989d | [] | no_license | sebkeil/Group20-VU | 3e70f1e464bb9873c8e8125ae190a52f08c85804 | 38f80d80944583e1ac48c6219130de69c0c60242 | refs/heads/master | 2021-05-18T03:15:15.671035 | 2020-09-06T15:00:10 | 2020-09-06T15:00:10 | 251,079,102 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,035 | py | from sklearn.model_selection import cross_validate
from sklearn.linear_model import LinearRegression
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
# read in files
X_train = pd.read_csv('train.csv')
y_train = pd.read_csv('y_train.csv', names=['price'])
# drop features
X_train = X_train.drop(['bathrooms', 'bedrooms','guests_included','host_listings_count','instant_bookable_f','room_type_Private room'],axis=1)
# standardize data
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
# Create a linear regression object: reg
reg = LinearRegression()
# Compute 5-fold cross-validation scores: cv_scores
cv_scores = cross_validate(reg, X_train, y_train, cv=5, scoring=('r2', 'neg_root_mean_squared_error'))
# Print the 5-fold cross-validation scores
#print(cv_scores)
print("Average 5-Fold CV Score (R2): {}".format(round(np.mean(cv_scores['test_r2']),4)))
print("Average 5-Fold CV Score (RMSE): {}".format(round(np.mean(cv_scores['test_neg_root_mean_squared_error']),2)))
| [
"basti.keil@hotmail.de"
] | basti.keil@hotmail.de |
8dca1271759ee7e83227a510a85cae83c7c18567 | 1c390cd4fd3605046914767485b49a929198b470 | /PE/73.py | 605024f5c153e5bca66a554ce755b76a2d0b1973 | [] | no_license | wwwwodddd/Zukunft | f87fe736b53506f69ab18db674311dd60de04a43 | 03ffffee9a76e99f6e00bba6dbae91abc6994a34 | refs/heads/master | 2023-01-24T06:14:35.691292 | 2023-01-21T15:42:32 | 2023-01-21T15:42:32 | 163,685,977 | 7 | 8 | null | null | null | null | UTF-8 | Python | false | false | 148 | py | from fractions import gcd
z=0
for i in range(12001):
print i
for j in range(i):
if gcd(i,j)==1 and 2*j<=i and 3*j>=i:
z+=1
print z-2
| [
"wwwwodddd@gmail.com"
] | wwwwodddd@gmail.com |
4e4fc20a8d55917ef9fc9e7af6bfed7a26c28383 | ee038dd0069fa0f4e2bc189744b789d4058b3ae9 | /FirstAttempt/app02.py | 60bb2a517fa71eea65de57f0145919721f26df5e | [] | no_license | JIAWea/Hello_Tornado | c15893d79f5b0282b64f373cde0b94bb24f08ac7 | 7609bf7b799cae29041fc52394f65e74c2f804a5 | refs/heads/master | 2020-04-30T20:09:03.096080 | 2019-03-25T17:07:11 | 2019-03-25T17:07:11 | 177,057,974 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,660 | py | import tornado.ioloop
import tornado.web
import time,hashlib
from controllers.account import LoginHandler
from controllers.home import HomeHandler
container = {}
# container = { '随机字符串或者cookie':{'uuuu':'root','k1':'v1'}, }
class Session(object):
def __init__(self,handler):
self.handler = handler
self.random_str = None # 随机字符串,也有可能是cookie
self.client_random_str = self.handler.get_cookie('session_id')
if not self.client_random_str:
"""新用户,没有cookie的"""
# 1. 生成随机字符串当作session中的key,保存在大字典container中,用户每次访问都到里面找是否有该值
self.random_str = self.create_random_str()
container[self.random_str] = {} # 保存在大字典
else:
if self.client_random_str in container:
"""老用户,在container大字典里面了"""
self.random_str = self.client_random_str
print('老用户',container)
else:
"""非法用户,伪造的cookie"""
self.random_str = self.create_random_str()
container[self.random_str] = {}
# 2. 生成cookie,必须调用LoginHandler才能使用set_cookie()
timeOut = time.time()
self.handler.set_cookie('session_id',self.random_str,expires=timeOut+1800)
# 3. 写入缓存或数据库 ==> 后面用户自己调用session['uuuu'] = 'root'
def create_random_str(self):
now = str(time.time())
m = hashlib.md5()
m.update(bytes(now,encoding='utf-8'))
return m.hexdigest()
def __setitem__(self, key, value):
# print(key,value) # key 就是用户自己设置session['uuuu']='root'中的uuuu,value就是root
container[self.random_str][key] = value
# print('setitem',container)
def __getitem__(self, item):
# print(item) # uuuu
# print('getitem',container)
return container[self.random_str].get(item)
def __delitem__(self, key):
pass
def open(self):
pass
def cloes(self):
pass
class Foo(object):
def initialize(self):
# print(self) # <__main__.LoginHandler object at 0x00000000038702E8>
self.session = Session(self)
super(Foo, self).initialize() # 执行RequestHandler中的initialize
class HomeHandler(Foo,tornado.web.RequestHandler):
def get(self):
print('session',self.session)
user = self.session['uuuu'] # 调用Session类中的__getitem__方法, 获取value
print('user',user)
if not user:
self.write('不是合法登录')
else:
self.write(user)
class LoginHandler(Foo,tornado.web.RequestHandler):
def get(self):
# self.session['uuuu'] # 调用Session类中的__getitem__方法, 获取value
# del self.session['uuuu'] # 调用Session类中的__delitem__方法, 删除
self.session['uuuu'] = "root" # 调用Session类中的__setitem__方法,在session里面设置了uuuu
self.write("Hello, world")
print(container)
self.redirect('/home')
application = tornado.web.Application([
# (r"/index", MainHandler),
(r"/login", LoginHandler),
(r"/home", HomeHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start() | [
"ray@126.com"
] | ray@126.com |
7e068848c2db8d48c618b980d83f78aef0d05d2d | f037f737d14311dc182eae31a74388440c7a68a1 | /pytorch_practice/hello.py | 512f88b693d621ad448624c456b13cd3971c7c72 | [] | no_license | llzxo/python_practice | a5c9897fa13548f2fe30a846bfc979459c859861 | 48c78799d68cb1620a3d6e22d00b40de2255ba1f | refs/heads/master | 2021-01-21T11:22:41.977747 | 2017-05-11T05:30:38 | 2017-05-11T05:30:38 | 83,558,632 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,914 | py | import torch
import torchvision
import torchvision.transforms as transforms
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import time
import torch.optim as optim
transform = transforms.Compose(
[transforms.ToTensor(),transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))]
)
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=2)
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'trunk')
class Net(nn.Module):
def __init__(self):
super(Net,self).__init__()
self.conv1 = nn.Conv2d(3,10,5)
self.pool = nn.MaxPool2d(2,2)
self.conv2 = nn.Conv2d(10,16,5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84,10)
def forward(self,x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
net = net.cuda()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
start1 = time.clock()
start2 = time.time()
for epoch in range(2):
running_loss = 0.0
for i,data in enumerate(trainloader,0):
inputs, labels = data
# inputs,labels = Variable(inputs),Variable(labels)
inputs,labels = Variable(inputs.cuda()),Variable(labels.cuda())
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs,labels)
loss.backward()
optimizer.step()
running_loss += loss.data[0]
if i%2000 ==1999:
print('[%d,%5d] loss:%.3f' %(epoch + 1, i + 1, running_loss/2000 ))
running_loss = 0.0
print('Finished Training')
imsize = 256
loader = transforms.Compose([transforms.Scale(imsize), transforms.ToTensor()])
def image_loader(image_name):
image = Image.open(image_name)
image = loader(image).float()
image = Variable(image, requires_grad = True)
image = './plane.jpg'
out = net(Variable(image).cuda())
_,predicted = torch.max(out.data, 1)
print(classes[predicted[0]])
# correct = 0
# total = 0
# for data in testloader:
# images, labels = data
# labels = labels.cuda()
# outputs = net(Variable(images))
# outputs = net(Variable(images).cuda())
# _, predicted = torch.max(outputs.data,1)
# total += labels.size(0)
# correct += (predicted == labels).sum()
#
# print('Accuracy is %d %%'%(100 * correct / total))
#
# class_correct = list(0. for i in range(10))
# class_total = list(0. for i in range(10))
# for data in testloader:
# images, labels = data
# labels = labels.cuda()
# outputs = net(Variable(images))
# outputs = net(Variable(images.cuda()))
# _, predicted = torch.max(outputs.data, 1)
# c = (predicted == labels).squeeze()
# for i in range(4):
# label = labels[i]
# class_correct[label] += c[i]
# class_total[label] += 1
#
# for i in range(10):
# print('accuracy of %s is %d %%' %(classes[i], 100 * class_correct[i] / class_total[i]))
#
# end1 = time.clock()
# end2 = time.time()
#
# print("cpu clock time duration:%s" % (end1 - start1))
# print("time duration:%s" % (end2 - start2))
# on cpu
# cpu clock time duration:694.808074
# time duration:133.895688057
# on gpu
# cpu clock time duration:48.632438
# time duration:54.9926979542 | [
"llzxp0614@gmail.com"
] | llzxp0614@gmail.com |
ff82d23d75ee9801afdbf94c951bef41edcef33d | bcf9bed1d94d952f020faf99e4a9ce85b3eb84a9 | /MF_BPR/main.py | 62644747257c9e81370ce8d8d685fc0ab24bf90b | [] | no_license | rlqja1107/Graduation_Paper | c79b00e88877d375dd2a12c5e159f4d604ed5288 | a09614ca97572ec989dec147a9dd11081220b15c | refs/heads/main | 2023-05-31T16:04:31.475121 | 2021-06-18T08:36:54 | 2021-06-18T08:36:54 | 352,487,445 | 3 | 2 | null | null | null | null | UTF-8 | Python | false | false | 3,032 | py | from dataset import load_data
from model import BPR
from metric import auc_score, getHitRatio, getNDCG
from multiprocessing import Pool, Manager
import time
import sys
dataset = ['epinion82', 'epinion91', 'librarything82', 'librarything91'][3]
X_train, X_test, num_users_test, items_list_test, users_list_test = load_data(dataset)
n_iters_list = [10, 50, 100, 200, 500, 1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900, 2000]
lr_list = [1e-2, 1e-3, 1e-4]
batch_list = [64, 1024]
def bpr_returns(epoch):
bpr_params = {'learning_rate': lr,
'batch_size': batch,
'n_iters': epoch,
'n_factors': 64,
'reg': 1e-4}
bpr = BPR(**bpr_params)
bpr.fit(X_train)
start = time.time()
top10 = bpr.recommend(X_train, N = 10)
print('Time for recommend:', time.time() - start)
top10_item = top10[users_list_test,:]
top10_test = {}
for i in range(len(users_list_test)):
user_index = users_list_test[i]
top10_test[user_index] = list(top10_item[i])
HR_dict[epoch] = top10_test
ndcg_list_top10 = []
for i in range(num_users_test):
ndcg_list_top10.append(getNDCG(top10[i], items_list_test[i], 10))
hit_list_top10 = []
for i in range(num_users_test):
hit_list_top10.append(getHitRatio(top10[i], items_list_test[i]))
print('------------')
print('Epoch:', epoch)
print('ndcg@10:', sum(ndcg_list_top10) / num_users_test)
print('hit@10:', sum(hit_list_top10) / num_users_test)
HR_list.append(sum(hit_list_top10) / num_users_test)
print()
HR_best = {}
models = {}
for i in range(len(lr_list)):
lr = lr_list[i]
for j in range(len(batch_list)):
batch = batch_list[j]
with Manager() as manager:
HR_list = manager.list()
HR_dict = manager.dict()
sys.stdout = open('./MF_BPR/results/' + dataset + '/lr_' + str(lr) + '_batch_' + str(batch) +'.txt', "w")
start_time = time.time()
pool = Pool(processes=20)
pool.map(bpr_returns, n_iters_list)
pool.close()
pool.join()
print('Done in:', time.time() - start_time, 'sec')
sys.stdout.close()
epoch_index = HR_list.index(max(HR_list))
best_epoch = n_iters_list[epoch_index]
best_model_top10 = HR_dict[best_epoch]
HR_best[max(HR_list)] = (lr, batch, best_epoch)
models[(lr, batch, best_epoch)] = best_model_top10
optimal_setting = HR_best[max(HR_best.keys())]
best_model = models[optimal_setting]
with open('./result/' + dataset + '/BPR_dataset_' + dataset + '_lr_' + str(optimal_setting[0]) + '_batch_size_' + str(optimal_setting[1]) + '_epoch_' + str(optimal_setting[2]) +'.txt', "w") as f:
for k, v in best_model.items():
string = ""
string += str(k)
for i in v:
string += " "
string += str(i)
string += '\n'
f.write(string)
| [
"rlqja1107@hanyang.ac.kr"
] | rlqja1107@hanyang.ac.kr |
0023937f5c12f7a15fd54083090d66e26fe0887a | f2cacb05d20e2e699e64035b6bee9a8bed3d3b8e | /atm/__init__.py | 4d85ea4f53cca492fe01cc6e8f66cf043c77030a | [
"BSD-3-Clause"
] | permissive | moeyensj/atm | 31e54e93c0881307770ab0d7815b9c4678f9f2e6 | 0523600cf44423a1ef72ca40fff29bbfbe1281a8 | refs/heads/master | 2022-08-13T05:33:54.131701 | 2021-03-03T23:38:02 | 2021-03-03T23:38:02 | 196,091,171 | 9 | 2 | BSD-3-Clause | 2021-03-03T23:38:03 | 2019-07-09T22:16:20 | Python | UTF-8 | Python | false | false | 289 | py | from .version import __version__
from .config import *
from .constants import *
from .frames import *
from .helpers import *
from .functions import *
from .models import *
from .obs import *
from .analysis import *
from .data_processing import *
from .fit import *
from .plotting import *
| [
"moeyensj@gmail.com"
] | moeyensj@gmail.com |
9b0e6e18151779ef2c05e047ba28042259e4bdb8 | 4ab83ae9b3320e423116579a2de14600aeda16e0 | /46_孩子们的游戏(圆圈中最后剩下的数).py | 15ab243f7034126827dcc0951c5356c320a720dc | [] | no_license | yaodalu/JZOffer | a4e8d6611cbff686dbbdd95226caeb5614945f9c | ede5f500f45b865058352b0c37629d7f2254a4d6 | refs/heads/master | 2020-05-21T17:10:09.705926 | 2019-09-10T01:05:55 | 2019-09-10T01:05:55 | 186,118,657 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,083 | py | # -*- coding:utf-8 -*-
class Solution:
def LastRemaining_Solution(self, n, m):
"""单向循环链表解法"""
if n == 0: #特殊情况,没有小朋友
return -1
if n == 1: #特殊情况,只有一个小朋友
return 1
if m == 1: #特殊情况,每次第一个小朋友退出
return n-1
myList = MyList(n)
while not myList.judgeOneElem():
myList.pop(m)
return myList.judgeOneElem().val
class Node():
def __init__(self,val):
self.val = val
self.next = None
class MyList():
"""尾指针指向头节点的单向循环链表"""
def __init__(self,n): #n>=2
self.__head = Node(0)
cur = self.__head
for i in range(1,n-1): #退出循环时,cur指向倒数第二个节点
cur.next = Node(i)
cur = cur.next
cur.next = Node(n-1)
cur = cur.next
cur.next = self.__head
def judgeOneElem(self):
"""判断链表是否只有一个节点"""
if self.__head and self.__head.next == self.__head:
return self.__head #如果链表只有一个节点,则返回该节点
return False
def pop(self,m):
"""遍历"""
if self.__head is None:
return
cur,count = self.__head,0
while count != m-2 : #退出循环的时候,指针指向需要删除的节点的前一个节点
cur = cur.next
count += 1
self.__head = cur.next.next #头节点指向删除节点的后一个节点
cur.next = self.__head
if __name__ == "__main__":
print Solution().LastRemaining_Solution(5,3)
| [
"648672371@qq.com"
] | 648672371@qq.com |
6ee3ea530a68859c892de4828e80f71f3ab09489 | 7b37b27bd9be95195fe4b6384b6af49cc133de84 | /posts/2019/link_header_jsonld.py | e4122d3cef019ba486e7eee66ecc51b220cbb76d | [] | no_license | OnroerendErfgoed/oeblog | 0a122ac0de7a3b62d25d5b34c57aa4cd32e57e6a | f2095f8e8ff1cd4aa3808622139f5fc945c2cc31 | refs/heads/master | 2023-04-07T04:20:08.427321 | 2023-03-15T10:33:44 | 2023-03-15T10:33:44 | 70,043,835 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,761 | py | # -*- coding: utf-8 -*-
import requests
from pyld import jsonld
import json
# Our endpoints
INVENTARIS = 'https://inventaris.onroerenderfgoed.be'
AFBEELDINGEN = 'https://beeldbank.onroerenderfgoed.be/images'
ERFGOEDOBJECTEN = INVENTARIS + '/erfgoedobjecten'
AANDUIDINGSOBJECTEN = INVENTARIS + '/aanduidingsobjecten'
THEMAS = INVENTARIS + '/themas'
def get_data(url, parameters):
'''
Fetch all data from a url until there are no more `next` urls in the Link
header.
:param str url: The url to fetch from
:param dict parameters: A dict of query string parameters
:rtype: dict
'''
data = []
headers = {'Accept': 'application/json'}
res = requests.get(url, params=parameters, headers=headers)
data.extend(res.json())
while 'next' in res.links:
res = requests.get(res.links['next']['url'], headers=headers)
data.extend(res.json())
return data
def add_type(collection, rtype):
"""
Add the resource type to a resource
:param list collection: Collection of resources to add a type to
:param str rtype: The type of all resources in this collection
:rtype: list
"""
for c in collection:
c.update({'@type': rtype})
def add_locatie_samenvatting(afbeeldingen):
"""
Summarize the location of an image
:param list afbeeldingen: Collection of afbeeldingen to summarize
:rtype: list
"""
for a in afbeeldingen:
s = ''
hnr = a.get('location', {}).get('housenumber', {}).get('name')
straat = a.get('location', {}).get('street', {}).get('name')
gemeente = a.get('location', {}).get('municipality', {}).get('name')
prov = a.get('location', {}).get('province', {}).get('name')
if straat and hnr:
s = '{} {} ({})'.format(straat, hnr, gemeente)
elif straat:
s = '{} ({})'.format(straat, gemeente)
else:
s = '{} ({})'.format(gemeente, prov)
a.update({'locatie_samenvatting': s})
# Determine the CRAB ID for the gemeente you want
# https://loc.geopunt.be/v4/Location?q=knokke-heist
MUNICIPALITY_ID = 191
# Fetch all data
afbeeldingen = get_data(AFBEELDINGEN, {'municipality': MUNICIPALITY_ID})
erfgoedobjecten = get_data(ERFGOEDOBJECTEN, {'gemeente': MUNICIPALITY_ID})
aanduidingsobjecten = get_data(AANDUIDINGSOBJECTEN, {'gemeente': MUNICIPALITY_ID})
themas = get_data(THEMAS, {'gemeente': MUNICIPALITY_ID})
# Add everything together and transform to linked data
inventaris_context = {
"dct": "http://purl.org/dc/terms/",
"naam": "dct:title",
"korte_beschrijving": "dct:description",
"locatie_samenvatting": "dct:spatial",
"uri": "@id",
"Thema": "https://id.erfgoed.net/vocab/ontology#Thema",
"Erfgoedobject": "https://id.erfgoed.net/vocab/ontology#Erfgoedobject",
"Aanduidingsobject": "https://id.erfgoed.net/vocab/ontology#Aanduidingsobject"
}
beeldbank_context = {
"dct": "http://purl.org/dc/terms/",
"title": "dct:title",
"description": "dct:description",
"locatie_samenvatting": "dct:spatial",
"uri": "@id",
"Afbeelding": "https://purl.org/dc/dcmiType/Image"
}
# Add types to all datasets and location summary to images
add_type(erfgoedobjecten, "Erfgoedobject")
erfgoedobjecten = jsonld.expand(erfgoedobjecten, {'expandContext':inventaris_context})
add_type(aanduidingsobjecten, "Aanduidingsobject")
aanduidingsobjecten = jsonld.expand(aanduidingsobjecten, {'expandContext':inventaris_context})
add_type(themas, "Thema")
themas = jsonld.expand(themas, {'expandContext':inventaris_context})
add_type(afbeeldingen, "Afbeelding")
add_locatie_samenvatting(afbeeldingen)
afbeeldingen = jsonld.expand(afbeeldingen, {'expandContext':beeldbank_context})
# Add all datasets together
stuff = erfgoedobjecten + aanduidingsobjecten + themas + afbeeldingen
# Compact all data to simplify the keys we're working with
dct_context = {
"dct": "http://purl.org/dc/terms/",
"title": "dct:title",
"description": "dct:description",
"spatial": "dct:spatial",
"uri": "@id",
"type": "@type",
"Thema": "https://id.erfgoed.net/vocab/ontology#Thema",
"Erfgoedobject": "https://id.erfgoed.net/vocab/ontology#Erfgoedobject",
"Aanduidingsobject": "https://id.erfgoed.net/vocab/ontology#Aanduidingsobject",
"Afbeelding": "https://purl.org/dc/dcmiType/Image"
}
compactstuff = jsonld.compact(stuff, dct_context)
# Print all records to the screen
for s in compactstuff['@graph']:
h = '{}'.format(s['title'])
print(h)
print(len(h)*'=')
print('Type: {}'.format(s['type']))
print('URI: {}'.format(s['uri']))
print('Location: {}'.format(s['spatial']))
if 'description' in s and s['description']:
print(s['description'])
print()
| [
"koen_van_daele@telenet.be"
] | koen_van_daele@telenet.be |
15a860f8bc4c092e866e5ee2784958d676c664fb | a98bc8906c3fbe4d388442d24cbeed06d06686f9 | /Codechef 2019/sept Long 2019/chefinsq.py | a3cdcb3f34a5e9ed032f62cfec6c69d944f9028e | [] | no_license | Arrowheadahp/Contests-Challenges-and-Events | 1ac4f1b2067276fa669e86ecfdb685d95ba663fd | fc156e5ae49b3074a9dbd56acd4fdc2af25c6a3f | refs/heads/master | 2022-12-13T19:50:38.041410 | 2020-08-22T14:16:23 | 2020-08-22T14:16:23 | 197,886,111 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 342 | py | def fact(k):
f = 1
while k:
f*=k
k-=1
return f
for _ in range(input()):
n, k = map(int, raw_input().split())
A = map(int, raw_input().split())
A.sort()
x = A[k-1]
s = A[:k].count(x)
t = A.count(x)
#print s, t
print fact(t)/(fact(s)*fact(t-s))
'''
2
4 2
1 2 3 4
4 2
1 2 2 2
'''
| [
"prasunbhuin.pkb@gmail.com"
] | prasunbhuin.pkb@gmail.com |
47511dde0ae975520d65f3037883eb7db5a50e64 | 4d097442bc14f913da366bb93d07d59a056d2bed | /models/resnet18_cifar_lp.py | e7e5da38a058c490449e1f28de40120b2d5faf4f | [
"MIT"
] | permissive | mengjian0502/BNFusionTrain | 9db3da50b1affb5284562d9453461ca4de8db572 | 2cfb4a3dceb4dc468bbee88a1f65a66b29ee4de4 | refs/heads/main | 2023-07-19T07:07:37.222841 | 2021-09-06T23:13:13 | 2021-09-06T23:13:13 | 335,213,933 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,247 | py | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
import torch
from torch.nn import init
from .modules import QConv2d, QLinear
__all__ = ['resnet18_Q']
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1, wbit=4, abit=4):
super(BasicBlock, self).__init__()
self.conv1 = QConv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False, wbit=wbit, abit=abit)
self.bn1 = nn.BatchNorm2d(planes)
self.relu1 = nn.ReLU(inplace=True)
self.conv2 = QConv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False, wbit=wbit, abit=abit)
self.bn2 = nn.BatchNorm2d(planes)
self.relu2 = nn.ReLU(inplace=True)
self.shortcut = nn.Sequential()
if stride != 1 or in_planes != self.expansion*planes:
self.shortcut = nn.Sequential(
QConv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False, wbit=wbit, abit=abit),
nn.BatchNorm2d(self.expansion*planes)
)
def forward(self, x):
out = self.conv1(x)
out = self.relu1(self.bn1(out))
out = self.conv2(out)
out = self.bn2(out)
out += self.shortcut(x)
out = self.relu2(out)
return out
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, in_planes, planes, stride=1):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,
stride=stride, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, self.expansion *
planes, kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(self.expansion*planes)
self.shortcut = nn.Sequential()
if stride != 1 or in_planes != self.expansion*planes:
self.shortcut = nn.Sequential(
nn.Conv2d(in_planes, self.expansion*planes,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(self.expansion*planes)
)
def forward(self, x):
out = F.relu(self.bn1(self.conv1(x)))
out = F.relu(self.bn2(self.conv2(out)))
out = self.bn3(self.conv3(out))
out += self.shortcut(x)
out = F.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, num_blocks, num_classes=10, wbit=4, abit=4, channel_wise=0):
super(ResNet, self).__init__()
self.in_planes = 64
self.conv1 = QConv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False, wbit=wbit, abit=abit)
self.bn1 = nn.BatchNorm2d(64)
self.relu0 = nn.ReLU(inplace=True)
self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1, wbit=wbit, abit=abit)
self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2, wbit=wbit, abit=abit)
self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2, wbit=wbit, abit=abit)
self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2, wbit=wbit, abit=abit)
self.linear = QLinear(512*block.expansion, num_classes, wbit=wbit, abit=abit)
def _make_layer(self, block, planes, num_blocks, stride, wbit=4, abit=4):
strides = [stride] + [1]*(num_blocks-1)
layers = []
for stride in strides:
layers.append(block(self.in_planes, planes, stride, wbit=wbit, abit=abit))
self.in_planes = planes * block.expansion
return nn.Sequential(*layers)
def forward(self, x):
out = self.conv1(x)
out = self.relu0(self.bn1(out))
out = self.layer1(out)
out = self.layer2(out)
out = self.layer3(out)
out = self.layer4(out)
out = F.avg_pool2d(out, 4)
out = out.view(out.size(0), -1)
out = self.linear(out)
return out
class resnet18_Q:
base = ResNet
args = list()
kwargs = {'block': BasicBlock, 'num_blocks': [2, 2, 2, 2]} | [
"jmeng15@asu.edu"
] | jmeng15@asu.edu |
474a17360b5598c946e3ee7efe26064f88440f0a | 4116dc4681a9ea321d35f65a0588ef556e7e413d | /app/aplicaciones/principal/migrations/0015_delete_usuario.py | a8206d04998a2449d3484098916dd937933835fe | [] | no_license | MarcheloJacome/ingWeb | 6eba0cdb172a3a46ab9b7fe5b3bf85e0878d11d0 | 1624ae59c9dea5eec741e664f275969db00e9f8d | refs/heads/main | 2023-06-04T00:28:16.115738 | 2021-06-18T14:55:02 | 2021-06-18T14:55:02 | 374,448,949 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 287 | py | # Generated by Django 3.1.7 on 2021-05-18 22:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('principal', '0014_usuario'),
]
operations = [
migrations.DeleteModel(
name='Usuario',
),
]
| [
"marcelo.jacome@hotmail.com"
] | marcelo.jacome@hotmail.com |
16009b9bc2f62ef2290310fb4dfc596101cfe04e | 6afc34982545160506a9acb7f644ba877e4fbe97 | /day19.py | a606ca20ee394300d39f23f1017f272c6465b086 | [] | no_license | AnsgarKlein/AdventOfCode2020 | 8bd2e8e918afe611bea9e9850ceb44722eb8de34 | 137be7bf34603068ec5987a99426669807c3fb42 | refs/heads/main | 2023-03-21T08:09:43.158060 | 2020-12-29T13:19:28 | 2020-12-29T13:19:28 | 323,086,157 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,210 | py | #!/usr/bin/env python3
import re
def read_input_file(filename):
rules = []
inputs = []
with open(filename, 'r') as input_file:
content = input_file.read().split('\n')
# Rules
for i, line in enumerate(content):
if line.strip() == '':
content = content[i+1:]
break
rules.append(line.strip())
# Input
for line in content:
inputs.append(line.strip())
return rules, inputs
def rules_to_array(rules):
arr = {}
for rule in rules:
rule_index = int(rule.split(':')[0])
rule_body = rule.split(':')[1]
arr[rule_index] = rule_body
return arr
def rule_to_regex(rules, rule, index):
# Check if rule is a loop
is_loop_rule = False
if index in [ int(x) for x in rule.split(' ') if x.isdigit() ]:
is_loop_rule = True
# Hardcode loop rule 8
if is_loop_rule and index == 8:
return '(' + rule_to_regex(rules, rules[42], 42) + ')+'
# Hardcode loop rule 11
if is_loop_rule and index == 11:
result42 = rule_to_regex(rules, rules[42], 42)
result31 = rule_to_regex(rules, rules[31], 31)
txt = '('
for i in range(10):
# (42){i}
txt += '({}){{{}}}'.format(result42, i + 1)
# (42){i}
txt += '({}){{{}}}'.format(result31, i + 1)
txt += '|'
txt = txt[:-1]
txt += ')'
return txt
# Handle non-hardcoded, non-loop rules
# Rule contains XOR
if '|' in rule:
half1 = rule.split('|')[0].strip()
half2 = rule.split('|')[1].strip()
half1_result = rule_to_regex(rules, half1, index)
half2_result = rule_to_regex(rules, half2, index)
return '(' + half1_result +'|' + half2_result + ')'
# Rule contains literal
if '"' in rule:
match = re.match('"(.*)"', rule.strip())
return match.group(1)
# Rule contains concatenation of rules (or just one rule)
result = ''
for member in rule.strip().split(' '):
result += rule_to_regex(rules, rules[int(member)].strip(), int(member))
return result
def main():
# Read input file
rules_str, inputs = read_input_file('day19_input.txt')
rules = rules_to_array(rules_str)
############ PART ONE ############
# Convert rules to regex
regex = '^' + rule_to_regex(rules, rules[0], 0) + '$'
# Count input lines matching regex
count = 0
for line in inputs:
match = re.match('^' + regex + '$', line)
matched = (match is not None)
if matched:
count += 1
print('Part One: {}'.format(count))
############ PART TWO ############
# Change rules 8 and 11 (-> loop)
rules[8] = '42 | 42 8'
rules[11] = '42 31 | 42 11 31'
# Convert to regex again
regex = '^' + rule_to_regex(rules, rules[0], 0) + '$'
# Count input lines matching regex
count = 0
for line in inputs:
match = re.match(regex, line)
matched = (match is not None)
if matched:
count += 1
print('Part Two: {}'.format(count))
if __name__ == '__main__':
main()
| [
"AnsgarKlein@users.noreply.github.com"
] | AnsgarKlein@users.noreply.github.com |
844fd7640e35207a398b570c7d71e27fb7b2de5f | 70734c75951d1349a4a4f66ba82a24f4726aa968 | /smartrecruiters_python_client/models/source_types.py | 6e69f1629ccd49872df29317f8a45592265c7bfa | [
"MIT"
] | permissive | yogasukmawijaya/smartrecruiters-python-client | 0f044847ef76bbe57a3a922e7b0adb4f98c0917f | 6d0849d173a3d6718b5f0769098f4c76857f637d | refs/heads/master | 2020-04-09T16:45:41.703240 | 2017-07-08T19:59:25 | 2017-07-08T19:59:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,002 | py | # coding: utf-8
"""
Unofficial python library for the SmartRecruiters API
The SmartRecruiters API provides a platform to integrate services or applications, build apps and create fully customizable career sites. It exposes SmartRecruiters functionality and allows to connect and build software enhancing it.
OpenAPI spec version: 1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class SourceTypes(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, total_found=None, content=None):
"""
SourceTypes - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'total_found': 'int',
'content': 'list[SourceTypesContent]'
}
self.attribute_map = {
'total_found': 'totalFound',
'content': 'content'
}
self._total_found = total_found
self._content = content
@property
def total_found(self):
"""
Gets the total_found of this SourceTypes.
:return: The total_found of this SourceTypes.
:rtype: int
"""
return self._total_found
@total_found.setter
def total_found(self, total_found):
"""
Sets the total_found of this SourceTypes.
:param total_found: The total_found of this SourceTypes.
:type: int
"""
if total_found is None:
raise ValueError("Invalid value for `total_found`, must not be `None`")
self._total_found = total_found
@property
def content(self):
"""
Gets the content of this SourceTypes.
:return: The content of this SourceTypes.
:rtype: list[SourceTypesContent]
"""
return self._content
@content.setter
def content(self, content):
"""
Sets the content of this SourceTypes.
:param content: The content of this SourceTypes.
:type: list[SourceTypesContent]
"""
if content is None:
raise ValueError("Invalid value for `content`, must not be `None`")
self._content = content
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, SourceTypes):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| [
"kris@dataservices.pro"
] | kris@dataservices.pro |
214d0a8872c4d01fd211501cec534ddb1f14dd25 | 5ca88629f8e84da4c04ee89294f840936f2d17b2 | /blog/migrations/0001_initial.py | 3cac720f83f757134826fdc6de16253d97a55bfa | [] | no_license | Josie0130/my-first-blog | 60731eff60d0257634b5f7fec608c7cf37b909b7 | cf3b5cbddbb30c62ffd90251a66a1d5f66c8d4a2 | refs/heads/master | 2021-07-11T03:49:08.990258 | 2017-10-07T19:15:15 | 2017-10-07T19:15:15 | 106,119,997 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,051 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-07 16:45
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('text', models.TextField()),
('created_date', models.DateTimeField(default=django.utils.timezone.now)),
('published_date', models.DateTimeField(blank=True, null=True)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"jpeacock@attatec.com"
] | jpeacock@attatec.com |
6aed44e75731659d8dae37ecd1661907fcaa93b3 | 16eaa032c4bbaa95b8b0d053eb7c60881e97b3bc | /itmcfg_1.6.py | a6648ebcab100fd14a35b6c365965cdb4877b6fd | [] | no_license | haowells/ITM-Silent-Config-Script | 53184e443ff2ab9de1314ed270e765f24dd17d67 | cecfde37a96c3ccaae789b80bc0839be21f1ef54 | refs/heads/master | 2021-01-21T02:28:16.276090 | 2014-07-18T04:05:38 | 2014-07-18T04:05:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 20,441 | py | #!/usr/bin/env python
import os
import re
import sys
import argparse
from subprocess import Popen,PIPE,getoutput,check_call,CalledProcessError
import logging
ver='1.6'
'''
v1.1 2011-7-19
a./startagent.sh and /stopagent.sh missed quote mark at the end of each line
b.modify auto start script /etc/rc.itm .copy from /startagent.sh
v1.2 2011-08-04
a.change method chg_permission from setperm to secureMain
v1.3 2012-7-18
a. change itmcmd config for UD( runitmcmd method ) ,use -o option to set instance name
v1.4 2012-8-1
a. add second connect ip parameter -sectms
v1.5 2014-3-24
a. add pre and post script check and fix action
v1.6 2014-05-22
a. remove prescript and postscript dependency (create instance first)
'''
hostname = os.uname()[1]
logger = logging.getLogger('itmcfg')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('itmcfg.log')
fh.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
fh_fmter = logging.Formatter('%(asctime)s|%(funcName)-12s %(lineno)-4d: %(levelname)-8s %(message)s')
ch_fmter = logging.Formatter('%(levelname)-8s %(message)s')
fh.setFormatter(fh_fmter)
ch.setFormatter(ch_fmter)
logger.addHandler(fh)
logger.addHandler(ch)
def ipaddress(string):
value = str(string)
result = re.match('^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$',value)
if not result:
msg = '{0} is not a valid ip address'.format(value)
raise argparse.ArgumentTypeError(msg)
return value
def itmarg_par():
parser = argparse.ArgumentParser(
prog = 'itmcfg',
description='Example:itmcfg -prescript /opt/itm6/bcitmcfg/prescript.sh -rtms 182.248.56.61 -secrtms 182.248.56.60 -pclist ux ul um px mq ud -isha Yes -qmgr q1 q2 -inst db2inst1 db2inst2 -postscript /opt/itm6/bcitmcfg/postscript.sh',
epilog='BOCOM DC ITM6 Manual Configuration Script.. Author:linhaolh@cn.ibm.com')
parser.add_argument('-prescript',help='pre scripts such as checking and fix action')
parser.add_argument('-postscript',help='post scripts such as checking and fix action')
parser.add_argument('-rtms',required=True,type=ipaddress,help='ip address for first remote tems')
parser.add_argument('-secrtms',required=True,type=ipaddress,help='ip address for second remote tems')
parser.add_argument('-pclist',nargs='+',required=True,metavar='pc',help='production codes like ux,ul,um')
parser.add_argument('-isha',required=True,choices={'Yes','No'},help='wheter this OS running on HACMP or Not')
parser.add_argument('-ch',nargs='?',const='/opt/itm6',default='/opt/itm6',metavar='CANDLEHOME',help='candle home')
parser.add_argument('-version', action='version', version='%(prog)s ' + ver)
parser.add_argument('-qmgr',nargs='*',metavar='qmgrN',help='mq qmgr name')
parser.add_argument('-inst',nargs='*',metavar='instN',help='db2 instance name')
return parser.parse_args()
#print(args)
class UsageExc(Exception):
mydic = dict(mq='-qmgr',ud='-inst')
def __init__(self,pc):
self.pc = pc
msg = 'pc list include item:({0}),please use argument:({1})'.format(self.pc,self.mydic[self.pc])
print('-'*len(msg))
print(msg)
print('-'*len(msg))
parser.print_usage()
def __str__(self):
return 'Error argument!!!'
class TemaCfg:
strscripts = os.path.join('/','startagent.sh')
stpscripts = os.path.join('/','stopagent.sh')
def __init__(self,args,hostname=None):
self.rtms = args.rtms
self.secrtms = args.secrtms
self.pclist=args.pclist
self.isha=args.isha
self.candlehome=args.ch
self.qmgr=args.qmgr
self.inst=args.inst
self.prescript=args.prescript
self.postscript=args.postscript
self.hostname=hostname
autostr = os.path.join(self.candlehome,'registry','AutoStart')
with open(autostr) as myfile:
filenum = myfile.read().strip()
self.rcitmx = '/etc/rc.itm' + filenum
def modify_ini(self):
logger.info('starting modify pc.ini...')
for pc in self.pclist:
logger.info('start processing {0}.ini ...'.format(pc))
ininame = pc + '.ini'
inifile = os.path.join(self.candlehome,'config',ininame)
self.cfg_ini_bak(inifile)
append_list=['CTIRA_HOSTNAME=' + self.hostname + '\n',
'CTIRA_SYSTEM_NAME=' + self.hostname + '\n'
]
if pc == 'ux':
append_list+=['CTIRA_HEARTBEAT=5\n'] ###add heartbeat for ux.ini
pat1 = re.compile(r'^CTIRA_HOSTNAME=')
pat2 = re.compile(r'^CTIRA_SYSTEM_NAME=')
pat3 = re.compile(r'^CTIRA_HEARTBEAT=')
with open(inifile) as myfile:
ini_list = myfile.readlines()
del_list = [line for line in ini_list if pat1.match(line) or pat2.match(line) or pat3.match(line)]
for line in del_list:
ini_list.remove(line)
final_list=ini_list + append_list
with open(inifile,'w') as myfile:
myfile.writelines(final_list)
logger.info('ended process {0}.ini ...'.format(pc))
if pc == 'mq': self.modify_mq_cfg() ###add "SET AGENTNAME" for mq.cfg
logger.info('ended modify pc.ini')
def modify_mq_cfg(self):
logger.info('starting modify mq.cfg...')
mqcfg_file= os.path.join(self.candlehome,'config','mq.cfg')
self.cfg_ini_bak(mqcfg_file)
additem = 'SET AGENT NAME(' + self.hostname + ')' + '\n'
with open(mqcfg_file) as myfile:
mqcfg = myfile.readlines()
pat1 = re.compile(r'^SET MANAGER NAME')
pat2 = re.compile(r'^SET AGENT NAME')
del_list = [ x for x in mqcfg if pat2.match(x) ]
for line in del_list:
mqcfg.remove(line)
for i in range(len(mqcfg)):
if pat1.match(mqcfg[i]):
mqcfg.insert(i+1,additem)
with open(mqcfg_file,'w') as myfile:
myfile.writelines(mqcfg)
logger.info('ended modify mq.cfg')
def run_itmcmd(self):
logger.info('starting run itmcmd silent config command...')
file_silentcfg=os.path.join(self.candlehome,'silent_config.txt')
silent_cfg_tup = ('HOSTNAME=' + self.rtms,
'FTO=YES',
'MIRROR=' + self.secrtms,
'HSNETWORKPROTOCOL=ip.pipe'
)
silent_cfg='\n'.join(silent_cfg_tup)
logger.info('slient config file content')
logger.info('\n' + silent_cfg)
with open(file_silentcfg,'w') as myfile:
myfile.write(silent_cfg)
for pc in self.pclist:
logger.info('starting slient config {0}'.format(pc))
if pc == 'ud':
for inst in self.inst:
ret=Popen(['/opt/itm6/bin/itmcmd','config','-A','-h',self.candlehome,'-o',inst,'-p',file_silentcfg,pc],stdout=PIPE,stderr=PIPE)
boutput=ret.communicate()[0]
output=str(boutput,encoding='utf-8')
logger.info('\n' + output)
else:
ret=Popen(['/opt/itm6/bin/itmcmd','config','-A','-h',self.candlehome,'-p',file_silentcfg,pc],stdout=PIPE,stderr=PIPE)
boutput=ret.communicate()[0]
output=str(boutput,encoding='utf-8')
logger.info('\n' + output)
logger.info('ended run itmcmd silent config command')
def modify_kulconfig(self):
if 'ul' in self.pclist:
logger.info('starting modify kul_configfile for ulagent...')
kul_cfgfile = os.path.join(self.candlehome,'config','kul_configfile')
self.cfg_ini_bak(kul_cfgfile)
pat1=re.compile(r'^#/var/adm/ras/errlog')
pat2=re.compile(r'^/var/hacmp')
with open(kul_cfgfile) as myfile:
kul_cfgfile_list = myfile.readlines()
for i in range(len(kul_cfgfile_list)):
if pat1.match(kul_cfgfile_list[i]):
cfgerrpt=kul_cfgfile_list.pop(i)[1:]
kul_cfgfile_list.insert(i,cfgerrpt)
if self.isha == 'Yes':
del_item = [ x for x in kul_cfgfile_list if pat2.match(x) ]
for x in del_item:
kul_cfgfile_list.remove(x)
clcfg = [
'/var/hacmp/adm/cluster.log',
';n',
';u',
';a,"%s %d %d:%d:%d %s %s %[^:]: %[^:]: %[^\\n]" , month day hour minute second system type source class description']
clcfg = '\t'.join(clcfg)
kul_cfgfile_list.append(clcfg + '\n')
with open(kul_cfgfile,'w') as myfile:
myfile.writelines(kul_cfgfile_list)
logger.info('ended modify kul_configfile for ulagent')
def modify_inttab(self):
initab = '/etc/inittab'
if self.isha == 'Yes':
logger.info('This OS running on HACMP, delete autostart item from /etc/inittab')
self.cfg_ini_bak(initab)
ret=Popen(['/etc/lsitab','-a'], stdout=PIPE, stderr=PIPE)
b_iden=ret.stdout.readlines()
iden = list(map(lambda x: str(x,encoding='utf-8'), b_iden))
iden_del= [x.split(':')[0] for x in iden if re.match('rcitm',x)]
try:
for x in iden_del:
check_call(['/etc/rmitab', x])
except CalledProcessError as E:
logger.error('system command [{0}] return non-zero [{1}] code'.format(E.cmd,E.returncode))
logger.info('Auto start items (' + ','.join(iden_del) + ') has deleted!!')
def modify_startagent(self):
logger.info('starting modify manually start script /startagent.sh...')
startcont = ['#!/bin/ksh',
'start_all()',
'{',
'}',
'#'*10,
'if [ -f /opt/itm6/bin/CandleAgent ]',
'then',
' start_all',
'fi\n'
]
single_item = ['/usr/bin/su',
'-',
'itm6',
'-c',
'"',
'/opt/itm6/bin/itmcmd',
'agent',
'start',
'pc',
'>/dev/null',
'2>&1',
'"'
]
all_item=[]
for pc in self.pclist:
logger.debug('processing(' + pc + ') start item...')
all_item+=self.singel_pc_start(pc,single_item)
logger.debug('ended process(' + pc + ')start item')
for item in all_item:
startcont.insert(-6,item)
with open(self.strscripts,'w') as myfile:
myfile.write('\n'.join(startcont))
logger.info('ended modify manually start script /startagent.sh')
def modify_stopagent(self):
logger.info('starting modify manually stop script /stopagent.sh....')
start= open(self.strscripts)
stop=open(self.stpscripts,'w')
stop.write(start.read().replace('start','stop'))
start.close()
stop.close()
logger.info('ended modify manually stop script /stopagent.sh')
def modify_autostr(self): ###run after /startagent.sh has been creaed
if self.isha == 'No':
logger.info('starting modify autostart scripts /etc/rc.itm...')
self.cfg_ini_bak(self.rcitmx)
try:
check_call(['cp',self.strscripts,self.rcitmx])
except CalledProcessError as E:
logger.error('system command [{0}] return non-zero [{1}] code'.format(E.cmd,E.returncode))
logger.info('ended modify autostart scripts /etc/rc.itm...')
def singel_pc_start(self,pc,template):
if pc in ['ux','ul','um','px']:
retl = []
temp = template[:]
temp.pop(-4)
temp.insert(-3,pc)
retl.append(' '.join(temp))
return retl
elif pc == 'mq':
mqitem=[]
for qmgr in self.qmgr:
temp = template[:]
temp.pop(-4)
temp.insert(-3,'mq')
for x in ['-o',qmgr]:
temp.insert(-5,x)
mqitem.append(' '.join(temp))
return mqitem
elif pc == 'ud':
uditem=[]
for inst in self.inst:
temp = template[:]
temp.pop(2)
temp.insert(2,inst)
temp.pop(-4)
temp.insert(-3,'ud')
for x in ['-o',inst]:
temp.insert(-5,x)
uditem.append(' '.join(temp))
return uditem
def cfg_ini_bak(self,ininame):
bak_orig = ininame + '.orig'
try:
check_call(['cp','-p',ininame,bak_orig])
except CalledProcessError as E:
logger.error('system command [{0}] return non-zero [{1}] code'.format(E.cmd,E.returncode))
def chg_user_group(self):
if self.qmgr:
logger.info('starting add user account (itm6) into group (mqm)...')
try:
check_call(['chgrpmem','-m','+','itm6','mqm'])
except CalledProcessError as E:
logger.error('system command [{0}] return non-zero [{1}] code'.format(E.cmd,E.returncode))
logger.info('ended add user account (itm6) into group (mqm)')
if self.inst:
for inst in self.inst:
logger.info('starting add db2 inst user (' + inst + ') account into group (itmusers)...')
try:
check_call(['chgrpmem','-m','+',inst,'itmusers'])
except CalledProcessError as E:
logger.error('system command [{0}] return non-zero [{1}] code'.format(E.cmd,E.returncode))
logger.info('ended add db2 inst user (' + inst + ') account into group (itmusers)...')
def chg_permission(self):
logger.info('starting modify related files and directories permission...')
#setperm = os.path.join(self.candlehome,'bin','SetPerm')
secureMain = os.path.join(self.candlehome,'bin','secureMain')
try:
logger.info('change /startagent.sh and /stopagent.sh owner to itm6:itmusers')
check_call(['chown','itm6:itmusers',self.strscripts,self.stpscripts])
logger.info('change /startagent.sh and /stopagent.sh permissoin mode to 744')
check_call(['chmod','744',self.strscripts,self.stpscripts])
logger.info('change whole /opt/itm6 directory owner to itm6:itmusers')
check_call(['chown','-R','itm6:itmusers',self.candlehome])
#logger.info('change whole /opt/itm6 directory permission modeto o-rwx')
#check_call(['chmod','-R','o-rwx',self.candlehome])
#logger.info('run /opt/itm6/bin/SerPerm to set suid bit for itm6 binaries')
#check_call([setperm,'-a','-h',self.candlehome])
logger.info('run /opt/itm6/bin/secureMain lock to set necessary permission')
check_call([secureMain,'-h',self.candlehome,'-g','itmusers','lock'])
except CalledProcessError as E:
logger.error('system command [{0}] return non-zero [{1}] code'.format(E.cmd,E.returncode))
logger.info('ended modify related files and directories permission...')
def chk_output(self):
logger.info('-'*30 + 'OUTPUT RESULT' + '-'*30)
for pc in self.pclist:
ininame = pc + '.ini'
logger.info('-'*20 + ininame + '-'*20)
cmd = 'cat /opt/itm6/config/' + ininame + ' | grep -E "CTIRA_HOSTNAME|CTIRA_SYSTEM_NAME"'
output = getoutput(cmd)
logger.info('\n' + output)
logger.info('-'*20 + ininame + '-'*20)
if pc == 'mq':
logger.info('-'*20 + 'mq.cfg' + '-'*20)
cmd = 'cat /opt/itm6/config/mq.cfg | grep "SET AGENT NAME"'
output = getoutput(cmd)
logger.info('\n' + output)
logger.info('-'*20 + 'mq.cfg' + '-'*20)
if 'ul' in self.pclist:
logger.info('-'*20 + 'kul_configfile' + '-'*20)
cmd = "cat /opt/itm6/config/kul_configfile | grep -v '^#' | grep -v '^$' "
output = getoutput(cmd)
logger.info('\n' + output)
logger.info('-'*20 + '/etc/inittab' + '-'*20)
cmd = 'cat /etc/inittab | grep rcitm'
output = getoutput(cmd)
logger.info('\n' + output)
logger.info('-'*20 + '/startagent.sh' + '-'*20)
cmd = 'cat /startagent.sh'
output = getoutput(cmd)
logger.info('\n' + output)
logger.info('-'*20 + '/stopagent.sh' + '-'*20)
cmd = 'cat /stopagent.sh'
output = getoutput(cmd)
logger.info('\n' + output)
logger.info('-'*20 + self.rcitmx + '-'*20)
cmd = 'cat ' + self.rcitmx
output = getoutput(cmd)
logger.info('\n' + output)
if self.qmgr:
logger.info('-'*20 + 'mqm group info' + '-'*20)
cmd = 'cat /etc/group | grep mqm'
output = getoutput(cmd)
logger.info('\n' + output)
if self.inst:
logger.info('-'*20 + 'itmusers group info' + '-'*20)
cmd = 'cat /etc/group | grep itmusers'
output = getoutput(cmd)
logger.info('\n' + output)
logger.info('-'*20 + 'permission for /startagent.sh and /stopagent.sh' + '-'*20)
cmd = 'ls -l /startagent.sh /stopagent.sh'
output = getoutput(cmd)
logger.info('\n' + output)
logger.info('-'*20 + 'permission for /opt/itm6 directory' + '-'*20)
cmd = 'ls -ld /opt/itm6'
output = getoutput(cmd)
logger.info('\n' + output)
for pc in self.pclist:
logger.info('-'*20 + 'SetPerm result for ' + pc + '-'*20)
pattern = pc + '/bin'
kpc = 'k' + pc + '*'
for dirpath, dirnames, filenames in os.walk(self.candlehome):
if dirpath[-6:] == pattern:
cmd = 'ls -l ' + os.path.join(dirpath, kpc)
output = getoutput(cmd)
logger.info('\n' + output)
break
def call_prescript(prescript):
logger.info('start to execute pre scripts')
p=Popen(prescript,shell=True,stdout=PIPE,stderr=PIPE)
logger.info('-'*20 + 'pre script stdout' + '-'*20)
ret = p.wait()
logger.info(p.stdout.read().decode(encoding="utf-8"))
logger.info('-'*20 + 'pre script stdout' + '-'*20)
if ret==0:
logger.info('end of pre scripts, return code is {0}'.format(ret))
else:
logger.info('script return code is non-zero, it is {0}'.format(ret))
sys.exit(1)
def call_postscript(postscript):
logger.info('start to execute post scripts')
p=Popen(postscript,shell=True,stdout=PIPE,stderr=PIPE)
logger.info('-'*20 + 'post script stdout' + '-'*20)
ret = p.wait()
logger.info(p.stdout.read().decode(encoding="utf-8"))
logger.info('-'*20 + 'post script stdout' + '-'*20)
if ret==0:
logger.info('end of post scripts, return code is {0}'.format(ret))
else:
logger.info('script return code is non-zero, it is {0}'.format(ret))
sys.exit(1)
args = itmarg_par()
if 'mq' in args.pclist and not args.qmgr:
raise UsageExc('mq')
if 'ud' in args.pclist and not args.inst:
raise UsageExc('ud')
call_prescript(args.prescript)
cfgitem = TemaCfg(args,hostname)
cfgitem.modify_ini()
cfgitem.run_itmcmd()
cfgitem.modify_kulconfig()
cfgitem.modify_inttab()
cfgitem.modify_startagent()
cfgitem.modify_stopagent()
cfgitem.modify_autostr()
cfgitem.chg_user_group()
cfgitem.chg_permission()
cfgitem.chk_output()
call_postscript(args.postscript)
| [
"haowells@gmail.com"
] | haowells@gmail.com |
6de37ed69c4edf56df84c8abae61d811a36a3451 | 20bf6abf68d526f2f420ca47ee08ccf10e4a43bb | /diarySite/posts/migrations/0001_initial.py | bfa3d95dbaf24a31e784eb1b4f2b2475d6c1c095 | [] | no_license | JisunParkRea/django_diary | bd17f49677cdeeef897516384a33d124b6f30a35 | aefd3a3d53c7215ef5d01df2384543a36c09de29 | refs/heads/master | 2021-09-26T16:47:09.591470 | 2020-03-05T12:59:43 | 2020-03-05T12:59:43 | 245,157,300 | 0 | 0 | null | 2021-09-22T18:40:52 | 2020-03-05T12:27:37 | Python | UTF-8 | Python | false | false | 642 | py | # Generated by Django 3.0.3 on 2020-03-03 12:23
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title_text', models.CharField(max_length=100)),
('content_text', models.CharField(max_length=1000)),
('pub_date', models.DateTimeField(verbose_name='date published')),
],
),
]
| [
"fpdldk912@gmail.com"
] | fpdldk912@gmail.com |
ed96ae31acfcf92a18e26d9f50e1476cf7637433 | fab06d386097c7ecd6beb871d658dc5318a3c5bd | /contrib/st2/opensds/actions/get_bucket_migration.py | d1a2e46c8f29aaf568d069fffba810e277e9d6e8 | [
"Apache-2.0"
] | permissive | sodafoundation/orchestration | 98032df2d5c263ff6a74c51bfd54136409a1fa00 | 694832f6816217988e07f67c40bb7d6704879c6d | refs/heads/master | 2023-06-04T13:27:36.549994 | 2021-05-20T11:22:18 | 2021-05-20T11:22:18 | 181,059,410 | 5 | 4 | Apache-2.0 | 2021-05-20T11:22:19 | 2019-04-12T18:01:49 | Python | UTF-8 | Python | false | false | 1,150 | py | # Copyright 2019 The OpenSDS Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import requests
import time
from st2common.runners.base_action import Action
class GetMigrationAction(Action):
def run(self, url, auth_token):
headers = {
'x-auth-token': auth_token
}
while True:
r = requests.get(url=url, headers=headers)
r.raise_for_status()
resp = r.json()
status = resp["job"]["status"]
msg = 'Status of Bucket Migration is ' + status
print(msg)
if status == 'succeed':
break
time.sleep(2)
| [
"himanshuvar@gmail.com"
] | himanshuvar@gmail.com |
bdc4901a1f5a207c8b6ad1a084f62e9db064d3dd | a83349cd334786e0f555318a6979c4ec23ec8978 | /SteppMotorV2/include/Jugend_Forscht mit BLE mit Servo.py | 6119ee9dbaa3d95f342c89d5e3289bcd01f3e86c | [] | no_license | Suebaen/Jugendforscht-GitarrenTuner | 07a0b82a5230014750ed999709a9051d10863975 | 117a8550099f7da0f755598d0a4e7b3c982d098c | refs/heads/main | 2023-03-26T10:49:27.435700 | 2021-03-24T21:15:19 | 2021-03-24T21:15:19 | 306,705,184 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,990 | py | #! /usr/bin/env python
import numpy as np
import sys
import pyaudio
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.widget import Widget
import serial
import speech_recognition as s_r
print("Start")
port= "/dev/tty.HC-05-SPPDev" #dev/tty.HC-05-SPPDev tty.Bluetooth-Incoming-Port
# bluethooth= serial.Serial(port, 115200) # 9600) 115200
bluethooth = serial.Serial(port, 38400, timeout=0, parity=serial.PARITY_EVEN, rtscts=1)#38400
print ("connectied")
bluethooth.flushInput()
r = s_r.Recognizer()
my_mic = s_r.Microphone(device_index=1)
print(my_mic)
def DasBLESignal_Rechts():
bluethooth.write(b"N")
input_data = bluethooth.readline()
print(input_data.decode())
def DasBLESignal_Links():
bluethooth.write(b"F")
input_data = bluethooth.readline()
print(input_data.decode())
Das_ist_ein_A4 = ('A4.75', 0.003337767668014635)
Das_ist_ein_A4_Raute = ('A#4.833333333333333', -0.018885406668275095)
Das_ist_ein_C4 = ('C4.', 0 -0.08014706457605314)
Das_ist_ein_C4_Raute = ('C#4.083333333333333', 0.0035821878896484804)
Das_ist_ein_D4=('D4.166666666666667', -0.016212240985851167)
Das_ist_ein_D4_Raute= ('D#4.25', -0.013435641316277724)
Das_ist_ein_E4 = ('E4.333333333333333', 0.005231129721877892)
Das_ist_ein_F4 = ('F4.416666666666667', 0.000664601985590707)
Das_ist_ein_F4_Raute = ('F#4.5', 0.005029562635286311)
Das_ist_ein_G4 = ('G4.583333333333333', 0.013800740096982622)
Das_ist_ein_G4_Route = ('G#4.666666666666667', -0.004903988515962965)
gegen = "gegen den Uhrzeiger"
mit= "mit dem Uhrzeiger"
DieZeit = 1
PerfekteNote = 9
WieOftDieFlascheNoteGepsieltWerdenDamitSieEinSiganlAbgiebt = 0
A = 0
B = 0
C = 0
D = 0
E = 0
F = 0
G = 0
H = 0
I = 0
J = 0
K = 0
A1 = 0
A2 = 0
A1R = 0
A2R = 0
C1 = 0
C2 = 0
C1R = 0
C2R = 0
D1 = 0
D2 = 0
D1R = 0
D2R = 0
E1 = 0
E2 = 0
F1 = 0
F2 = 0
F1R = 0
F2R = 0
G1 = 0
G2 = 0
G1R = 0
G2R = 0
NOTE_MIN = 60 # C4
NOTE_MAX = 69 # A4
FSAMP = 22050 # Sampling frequency in Hz
FRAME_SIZE = 2048 # Wie viele samples pro frame
FRAMES_PER_FFT = 16 # FFT takes average across how many frames?
######################################################################
SAMPLES_PER_FFT = FRAME_SIZE*FRAMES_PER_FFT
FREQ_STEP = float(FSAMP)/SAMPLES_PER_FFT
######################################################################
NOTE_NAMES = 'C C# D D# E F F# G G# A A# B'.split()
######################################################################
# https://newt.phys.unsw.edu.au/jw/notes.html
def freq_to_number(f): return 69 + 12*np.log2(f/440.0)
def number_to_freq(n): return 440 * 2.0**((n-69)/12.0)
def note_name(n): return NOTE_NAMES[n % 12] + str(n/12 - 1)
######################################################################
def note_to_fftbin(n): return number_to_freq(n)/FREQ_STEP
imin = max(0, int(np.floor(note_to_fftbin(NOTE_MIN-1))))
imax = min(SAMPLES_PER_FFT, int(np.ceil(note_to_fftbin(NOTE_MAX+1))))
buf = np.zeros(SAMPLES_PER_FFT, dtype=np.float32) # Ursprügnlich war stand da ... .float32 (mit float16 gieng alles gut)
num_frames = 0
# Initialize audio
stream = pyaudio.PyAudio().open(format=pyaudio.paInt16,
channels=1,
rate=FSAMP,
input=True,
frames_per_buffer=FRAME_SIZE)
freq1 = 440.08
window = 0.5 * (1 - np.cos(np.linspace(0, 2*np.pi, SAMPLES_PER_FFT, False)))
# Print initial text
print ('sampling at', FSAMP, 'Hz with max resolution of', FREQ_STEP, 'Hz')
print
while stream.is_active():
buf[:-FRAME_SIZE] = buf[FRAME_SIZE:]
buf[-FRAME_SIZE:] = np.fromstring(stream.read(FRAME_SIZE, exception_on_overflow = False), np.int16)
fft = np.fft.rfft(buf * window)
freq = (np.abs(fft[imin:imax]).argmax() + imin) * FREQ_STEP
#sleep(DieZeit)
n = freq_to_number(freq)
n0 = int(round(n))
num_frames += 1
pyaudio.get_portaudio_version()
# auf 5 Kommastellen begrenzen
# freq = float("{0:.5f}".format(freq))
if num_frames >= FRAMES_PER_FFT:
print ('freq: {:9.4f} Hz note: {:>3s} {:+.2f}'.format(
freq, note_name(n0), n-n0))
# A4
if (note_name(n0), n-n0) < (Das_ist_ein_A4):
print (mit)
print(A)
DasBLESignal_Rechts() #BLE Signal
elif (note_name(n0), n-n0) > (Das_ist_ein_A4):
print (gegen)
print(A)
DasBLESignal_Links() #BLE Signal
else:
A += 1
print('Super das ist ein Perfektes A')
print(A)
if A <= PerfekteNote:
print (note_name(n0), n-n0)
print(A)
else:
break
# # A4#
if (note_name(n0), n-n0) < (Das_ist_ein_A4_Raute):
print (mit)
DasBLESignal_Rechts() #BLE Signal
elif (note_name(n0), n-n0) > (Das_ist_ein_A4_Raute):
print (gegen)
DasBLESignal_Links() #BLE Signal
else:
B += 1
print('Super das ist ein Perfektes A#')
if B <= PerfekteNote:
print (note_name(n0), n-n0)
print(B)
else:
break
# # C4
if (note_name(n0), n-n0) < (Das_ist_ein_C4):
print (mit)
DasBLESignal_Rechts() #BLE Signal
elif (note_name(n0), n-n0) > (Das_ist_ein_C4):
print (gegen)
DasBLESignal_Links() #BLE Signal
else:
C += 1
print('Super das ist ein Perfektes C')
if C <= PerfekteNote:
print (note_name(n0), n-n0)
else:
break
# # C4#
if (note_name(n0), n-n0) < (Das_ist_ein_C4_Raute):
print (mit)
DasBLESignal_Rechts()#BLE Signal
elif (note_name(n0), n-n0) > (Das_ist_ein_C4_Raute):
print (gegen)
DasBLESignal_Links() #BLE Signal
else:
D += 1
print('Super das ist ein Perfektes C#')
if D <= PerfekteNote:
print (note_name(n0), n-n0)
else:
print("jetzt raus bei C4")
break
# # D4
if (note_name(n0), n-n0) < (Das_ist_ein_D4):
print (mit)
DasBLESignal_Rechts()
elif (note_name(n0), n-n0) > (Das_ist_ein_D4):
print (gegen)
DasBLESignal_Links() #BLE Signal
else:
E += 1
print('Super das ist ein Perfektes D')
if E <= PerfekteNote:
print (note_name(n0), n-n0)
else:
break
# # D4#
if (note_name(n0), n-n0) < (Das_ist_ein_D4_Raute):
print (mit)
# von hier muss das BLE Signal gesendet werden
# D1R += 1
# if (D1R == WieOftDieFlascheNoteGepsieltWerdenDamitSieEinSiganlAbgiebt):
DasBLESignal_Rechts()
# #sleep(DieZeit)
elif (note_name(n0), n-n0) > (Das_ist_ein_D4_Raute):
print (gegen)
# von hier muss das BLE Signal gesendet werden
# D2R += 1
# if (D2R == WieOftDieFlascheNoteGepsieltWerdenDamitSieEinSiganlAbgiebt):
DasBLESignal_Links()
# #sleep(DieZeit)
else:
F += 1
print('Super das ist ein Perfektes D#')
if F <= PerfekteNote:
print (note_name(n0), n-n0)
else:
break
# # E4
if (note_name(n0), n-n0) < (Das_ist_ein_E4):
print (mit)
# von hier muss das BLE Signal gesendet werden
# E1 += 1
# if (E1 == WieOftDieFlascheNoteGepsieltWerdenDamitSieEinSiganlAbgiebt):
DasBLESignal_Rechts()
# #sleep(DieZeit)
elif (note_name(n0), n-n0) > (Das_ist_ein_E4):
print (gegen)
# von hier muss das BLE Signal gesendet werden
# E2 += 1
# if (E2== WieOftDieFlascheNoteGepsieltWerdenDamitSieEinSiganlAbgiebt):
DasBLESignal_Links()
# #sleep(DieZeit)
else:
G += 1
print('Super das ist ein Perfektes E')
if G <= PerfekteNote:
print (note_name(n0), n-n0)
else:
break
# # F4
if (note_name(n0), n-n0) < (Das_ist_ein_F4):
print (mit)
# von hier muss das BLE Signal gesendet werden
# F1 += 1
# if (F1 == WieOftDieFlascheNoteGepsieltWerdenDamitSieEinSiganlAbgiebt):
DasBLESignal_Rechts()
# #sleep(DieZeit)
elif (note_name(n0), n-n0) > (Das_ist_ein_F4):
print (gegen)
# von hier muss das BLE Signal gesendet werden
# G2 += 1
# if (G2 == WieOftDieFlascheNoteGepsieltWerdenDamitSieEinSiganlAbgiebt):
DasBLESignal_Links()
# #sleep(DieZeit)
else:
H += 1
print('Super das ist ein Perfektes F')
if H <= PerfekteNote:
print (note_name(n0), n-n0)
else:
# derBesondereBreak()
break
# # F4#
if (note_name(n0), n-n0) < (Das_ist_ein_F4_Raute):
print (mit)
# von hier muss das BLE Signal gesendet werden
# F1R += 1
# if (F1R == WieOftDieFlascheNoteGepsieltWerdenDamitSieEinSiganlAbgiebt):
DasBLESignal_Rechts()
#sleep(DieZeit)
elif (note_name(n0), n-n0) > (Das_ist_ein_F4_Raute):
print (gegen)
# von hier muss das BLE Signal gesendet werden
# F2R += 1
# if (F2R == WieOftDieFlascheNoteGepsieltWerdenDamitSieEinSiganlAbgiebt):
DasBLESignal_Links()
#sleep(DieZeit)
else:
I += 1
print('Super das ist ein Perfektes F#')
if I <= PerfekteNote:
print (note_name(n0), n-n0)
else:
break
# G
if (note_name(n0), n-n0) < (Das_ist_ein_G4):
print (mit)
# von hier muss das BLE Signal gesendet werden
# G1 += 1
# if (G1 == WieOftDieFlascheNoteGepsieltWerdenDamitSieEinSiganlAbgiebt):
DasBLESignal_Rechts()
#sleep(DieZeit)
elif (note_name(n0), n-n0) > (Das_ist_ein_G4):
print (gegen)
# von hier muss das BLE Signal gesendet werden
# G2 += 1
# if (G2 == WieOftDieFlascheNoteGepsieltWerdenDamitSieEinSiganlAbgiebt):
DasBLESignal_Links()
#sleep(DieZeit)
else:
J += 1
print('Super das ist ein Perfektes G')
if J <= PerfekteNote:
print (note_name(n0), n-n0)
else:
break
# G#
if (note_name(n0), n-n0) < (Das_ist_ein_G4_Route):
print (mit)
# von hier muss das BLE Signal gesendet werden
# G1R += 1
# if (G1R == WieOftDieFlascheNoteGepsieltWerdenDamitSieEinSiganlAbgiebt):
DasBLESignal_Rechts()
#sleep(DieZeit)
elif (note_name(n0), n-n0) > (Das_ist_ein_G4_Route):
print (gegen)
# von hier muss das BLE Signal gesendet werden
# G2R+= 1
# if (G2R == WieOftDieFlascheNoteGepsieltWerdenDamitSieEinSiganlAbgiebt):
DasBLESignal_Links()
#sleep(DieZeit)
else:
K += 1
print('Super das ist ein Perfektes G#')
if K <= PerfekteNote:
print (note_name(n0), n-n0)
else:
break
| [
"noreply@github.com"
] | noreply@github.com |
21c351a8fe2fc37d56c8ee1bc4ffb02f12c1c5cf | 04803c70bb97012b7d500a177ac0240fb2ddbe38 | /4chpd/pdep/network556_1.py | 2b8da0c07c0a5631e9d783dabeb7fa796d2e24f7 | [] | no_license | shenghuiqin/chpd | 735e0415f6688d88579fc935459c1b0f53596d1d | 396ba54629036e3f2be0b3fabe09b78c90d56939 | refs/heads/master | 2023-03-01T23:29:02.118150 | 2019-10-05T04:02:23 | 2019-10-05T04:02:23 | 192,084,217 | 0 | 0 | null | 2019-06-18T18:33:13 | 2019-06-15T13:52:28 | HTML | UTF-8 | Python | false | false | 93,703 | py | species(
label = 'C=C[CH]C(C)O[CH]C(2302)',
structure = SMILES('C=C[CH]C(C)O[CH]C'),
E0 = (69.8904,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1380,1390,370,380,2900,435,3000,3050,390,425,1340,1360,335,370,2950,3100,1380,975,1025,1650,3010,987.5,1337.5,450,1655,2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,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),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.672656,0.0957605,-8.24922e-05,3.6976e-08,-6.69666e-12,8579.82,31.2676], Tmin=(100,'K'), Tmax=(1315.44,'K')), NASAPolynomial(coeffs=[18.8206,0.0364849,-1.48996e-05,2.71977e-09,-1.86197e-13,3451.42,-68.1203], Tmin=(1315.44,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(69.8904,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(457.296,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(Cs-CsCsOsH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(C=CCJCO) + radical(CCsJOCs)"""),
)
species(
label = 'C=CC=CC(381)',
structure = SMILES('C=CC=CC'),
E0 = (57.8956,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2800,2850,1350,1500,750,1050,1375,1000,2950,3100,1380,975,1025,1650,2995,3010,3025,975,987.5,1000,1300,1337.5,1375,400,450,500,1630,1655,1680,180],'cm^-1')),
HinderedRotor(inertia=(0.831076,'amu*angstrom^2'), symmetry=1, barrier=(19.1081,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.833175,'amu*angstrom^2'), symmetry=1, barrier=(19.1563,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (68.117,'amu'),
collisionModel = TransportData(shapeIndex=2, epsilon=(3140.68,'J/mol'), sigma=(5.4037,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0, comment="""Epsilon & sigma estimated with Tc=490.57 K, Pc=45.16 bar (from Joback method)"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.00727,0.0328459,1.55855e-05,-4.25745e-08,1.84259e-11,7044.82,16.9534], Tmin=(100,'K'), Tmax=(972.32,'K')), NASAPolynomial(coeffs=[11.2869,0.0212416,-7.50361e-06,1.3618e-09,-9.72233e-14,3984.25,-34.0139], Tmin=(972.32,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(57.8956,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(299.321,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-Cds(Cds-Cds)H) + group(Cds-Cds(Cds-Cds)H) + group(Cds-CdsHH)"""),
)
species(
label = 'CH3CHO(52)',
structure = SMILES('CC=O'),
E0 = (-178.765,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2800,2850,1350,1500,750,1050,1375,1000,180,1305.64,1305.66,1305.67,3976.84],'cm^-1')),
HinderedRotor(inertia=(0.136163,'amu*angstrom^2'), symmetry=1, barrier=(3.13064,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (44.0526,'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=[4.72946,-0.00319329,4.75349e-05,-5.74586e-08,2.19311e-11,-21572.9,4.10302], Tmin=(200,'K'), Tmax=(1000,'K')), NASAPolynomial(coeffs=[5.40411,0.0117231,-4.22631e-06,6.83725e-10,-4.09849e-14,-22593.1,-3.48079], Tmin=(1000,'K'), Tmax=(6000,'K'))], Tmin=(200,'K'), Tmax=(6000,'K'), E0=(-178.765,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(153.818,'J/(mol*K)'), label="""CH3CHO""", comment="""Thermo library: FFCM1(-)"""),
)
species(
label = '[CH2]C1[CH]C(C)OC1C(3810)',
structure = SMILES('[CH2]C1[CH]C(C)OC1C'),
E0 = (100.754,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.05457,0.0429246,6.83606e-05,-1.25698e-07,5.48853e-11,12244.5,26.7473], Tmin=(100,'K'), Tmax=(900.209,'K')), NASAPolynomial(coeffs=[17.0446,0.0297095,-5.98931e-06,7.31272e-10,-4.5941e-14,7022.18,-61.7305], Tmin=(900.209,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(100.754,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(469.768,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(Cs-CsCsCsH) + group(Cs-CsCsOsH) + group(Cs-CsCsOsH) + group(Cs-CsCsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + ring(Tetrahydrofuran) + radical(CCJCO) + radical(Isobutyl)"""),
)
species(
label = 'H(19)',
structure = SMILES('[H]'),
E0 = (211.792,'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,25472.7,-0.459566], Tmin=(100,'K'), Tmax=(3459.6,'K')), NASAPolynomial(coeffs=[2.5,9.20456e-12,-3.58608e-15,6.15199e-19,-3.92042e-23,25472.7,-0.459566], Tmin=(3459.6,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(211.792,'kJ/mol'), Cp0=(20.7862,'J/(mol*K)'), CpInf=(20.7862,'J/(mol*K)'), label="""H""", comment="""Thermo library: BurkeH2O2"""),
)
species(
label = 'C=CC=C(C)O[CH]C(3811)',
structure = SMILES('C=CC=C(C)O[CH]C'),
E0 = (18.4008,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2950,3100,1380,975,1025,1650,2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,3025,407.5,1350,352.5,350,440,435,1725,2995,3025,975,1000,1300,1375,400,500,1630,1680,200,800,1200,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 = 2,
opticalIsomers = 1,
molecularWeight = (111.162,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.760161,0.0904933,-6.20578e-05,4.69667e-09,7.81107e-12,2397.25,29.882], Tmin=(100,'K'), Tmax=(969.439,'K')), NASAPolynomial(coeffs=[23.2212,0.0234865,-7.80361e-06,1.37545e-09,-9.74342e-14,-3753.46,-92.8118], Tmin=(969.439,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(18.4008,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(436.51,'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-CdsCsOs) + group(Cds-Cds(Cds-Cds)H) + group(Cds-Cds(Cds-Cds)H) + group(Cds-CdsHH) + radical(CCsJOC(O))"""),
)
species(
label = 'C=C[CH]C(C)OC=C(3812)',
structure = SMILES('C=C[CH]C(C)OC=C'),
E0 = (-24.7917,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1380,1390,370,380,2900,435,3025,407.5,1350,352.5,2950,3000,3050,3100,1330,1430,900,1050,1000,1050,1600,1700,2995,3025,975,1000,1300,1375,400,500,1630,1680,2750,2800,2850,1350,1500,750,1050,1375,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),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 2,
opticalIsomers = 1,
molecularWeight = (111.162,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.534319,0.0787576,-1.59677e-05,-4.7868e-08,2.72276e-11,-2799.48,29.02], Tmin=(100,'K'), Tmax=(957.022,'K')), NASAPolynomial(coeffs=[25.1838,0.0220849,-6.79384e-06,1.22813e-09,-9.22084e-14,-10049.3,-106.084], Tmin=(957.022,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-24.7917,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(436.51,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(Cs-CsCsOsH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + group(Cds-CdsHH) + group(Cds-CdsHH) + radical(C=CCJCO)"""),
)
species(
label = 'C=C=CC(C)O[CH]C(3813)',
structure = SMILES('C=C=CC(C)O[CH]C'),
E0 = (114.904,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([540,610,2055,3025,407.5,1350,352.5,3010,987.5,1337.5,450,1655,2950,3100,1380,975,1025,1650,1380,1390,370,380,2900,435,2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,200,800,1200,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 = 2,
opticalIsomers = 1,
molecularWeight = (111.162,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.310802,0.088366,-7.57669e-05,3.37793e-08,-6.08475e-12,13980.2,32.2937], Tmin=(100,'K'), Tmax=(1321.76,'K')), NASAPolynomial(coeffs=[17.7324,0.033762,-1.37991e-05,2.52388e-09,-1.73009e-13,9210.52,-59.7877], Tmin=(1321.76,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(114.904,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(436.51,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + group(Cdd-CdsCds) + radical(CCsJOCs)"""),
)
species(
label = '[CH2]C=C[CH]C(377)',
structure = SMILES('[CH2]C=C[CH]C'),
E0 = (240.064,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2800,2850,1350,1500,750,1050,1375,1000,3000,3100,440,815,1455,1000,2995,3025,975,1000,1300,1375,400,500,1630,1680,3025,407.5,1350,352.5,180],'cm^-1')),
HinderedRotor(inertia=(0.0180055,'amu*angstrom^2'), symmetry=1, barrier=(19.7234,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(1.34503,'amu*angstrom^2'), symmetry=1, barrier=(119.627,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.0180001,'amu*angstrom^2'), symmetry=1, barrier=(19.7225,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (68.117,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.18178,0.0283568,2.70949e-05,-5.14684e-08,2.05693e-11,28948.9,17.5848], Tmin=(100,'K'), Tmax=(990.212,'K')), NASAPolynomial(coeffs=[10.2369,0.0240425,-9.12514e-06,1.70243e-09,-1.22294e-13,25969.9,-28.1844], Tmin=(990.212,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(240.064,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(295.164,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-(Cds-Cds)CsHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + radical(Allyl_P) + radical(Allyl_S)"""),
)
species(
label = 'CH3(34)',
structure = SMILES('[CH3]'),
E0 = (136.188,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([604.263,1333.71,1492.19,2836.77,2836.77,3806.92],'cm^-1')),
],
spinMultiplicity = 2,
opticalIsomers = 1,
molecularWeight = (15.0345,'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=[3.65718,0.0021266,5.45839e-06,-6.6181e-09,2.46571e-12,16422.7,1.67354], Tmin=(200,'K'), Tmax=(1000,'K')), NASAPolynomial(coeffs=[2.97812,0.00579785,-1.97558e-06,3.07298e-10,-1.79174e-14,16509.5,4.72248], Tmin=(1000,'K'), Tmax=(6000,'K'))], Tmin=(200,'K'), Tmax=(6000,'K'), E0=(136.188,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(83.1447,'J/(mol*K)'), label="""CH3""", comment="""Thermo library: FFCM1(-)"""),
)
species(
label = 'C=CC=CO[CH]C(3814)',
structure = SMILES('C=CC=CO[CH]C'),
E0 = (60.1923,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2800,2850,1350,1500,750,1050,1375,1000,3025,407.5,1350,352.5,2950,3100,1380,975,1025,1650,2995,3010,3025,975,987.5,1000,1300,1337.5,1375,400,450,500,1630,1655,1680,180,180,180,180],'cm^-1')),
HinderedRotor(inertia=(0.965138,'amu*angstrom^2'), symmetry=1, barrier=(22.1904,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.963416,'amu*angstrom^2'), symmetry=1, barrier=(22.1508,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.965386,'amu*angstrom^2'), symmetry=1, barrier=(22.1961,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.963081,'amu*angstrom^2'), symmetry=1, barrier=(22.1431,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 2,
opticalIsomers = 1,
molecularWeight = (97.1351,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.112572,0.0714945,-2.17543e-05,-4.20115e-08,2.68296e-11,7405.09,25.5545], Tmin=(100,'K'), Tmax=(925.225,'K')), NASAPolynomial(coeffs=[25.6278,0.00928354,-4.52553e-07,-3.63748e-11,-1.3952e-15,541.59,-107.978], Tmin=(925.225,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(60.1923,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(365.837,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cds-Cds(Cds-Cds)H) + group(Cds-Cds(Cds-Cds)H) + group(Cds-CdsOsH) + group(Cds-CdsHH) + radical(CCsJOC(O))"""),
)
species(
label = 'C=CC[C](C)O[CH]C(3815)',
structure = SMILES('C=CC[C](C)O[CH]C'),
E0 = (133.678,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3025,407.5,1350,352.5,2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,2950,3100,1380,975,1025,1650,360,370,350,2750,2850,1437.5,1250,1305,750,350,3010,987.5,1337.5,450,1655,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),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.19918,0.0981604,-0.000109576,7.3549e-08,-2.08823e-11,16223.7,32.3302], Tmin=(100,'K'), Tmax=(842.758,'K')), NASAPolynomial(coeffs=[10.1903,0.0488487,-2.18079e-05,4.1198e-09,-2.86482e-13,14472.6,-16.0157], Tmin=(842.758,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(133.678,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(457.296,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(Cs-CsCsOsH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(C2CsJOCs) + radical(CCsJOCs)"""),
)
species(
label = '[CH2]COC(C)[CH]C=C(3816)',
structure = SMILES('[CH2]COC(C)[CH]C=C'),
E0 = (101.023,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3025,407.5,1350,352.5,3010,987.5,1337.5,450,1655,2950,3100,1380,975,1025,1650,1380,1390,370,380,2900,435,3000,3100,440,815,1455,1000,2750,2800,2850,1350,1500,750,1050,1375,1000,2750,2850,1437.5,1250,1305,750,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),
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 = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.328941,0.0916726,-7.53041e-05,3.24753e-08,-5.75653e-12,12308.9,31.2194], Tmin=(100,'K'), Tmax=(1321.64,'K')), NASAPolynomial(coeffs=[16.5572,0.0405664,-1.73013e-05,3.21747e-09,-2.22172e-13,7845.37,-54.9554], Tmin=(1321.64,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(101.023,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(457.296,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(Cs-CsCsOsH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(C=CCJCO) + radical(CJCO)"""),
)
species(
label = 'C=[C]CC(C)O[CH]C(3817)',
structure = SMILES('C=[C]CC(C)O[CH]C'),
E0 = (190.815,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3025,407.5,1350,352.5,1685,370,2950,3100,1380,975,1025,1650,1380,1390,370,380,2900,435,2750,2850,1437.5,1250,1305,750,350,2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,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),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.116875,0.0920235,-8.42613e-05,4.28703e-08,-9.11656e-12,23096.8,32.5505], Tmin=(100,'K'), Tmax=(1108.61,'K')), NASAPolynomial(coeffs=[13.2829,0.0436758,-1.88451e-05,3.53229e-09,-2.45596e-13,20125.8,-33.4773], Tmin=(1108.61,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(190.815,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(457.296,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(Cs-CsCsOsH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(CCsJOCs) + radical(Cds_S)"""),
)
species(
label = 'C=C[CH][C](C)OCC(3818)',
structure = SMILES('[CH2][CH]C=C(C)OCC'),
E0 = (60.3895,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.241916,0.0805121,-4.48186e-05,1.20008e-09,5.07182e-12,7426.86,32.0078], Tmin=(100,'K'), Tmax=(1057.2,'K')), NASAPolynomial(coeffs=[17.8313,0.0354302,-1.39126e-05,2.55712e-09,-1.78652e-13,2303.4,-62.3483], Tmin=(1057.2,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(60.3895,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(457.296,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsOs) + group(Cds-CdsCsH) + radical(Allyl_S) + radical(RCCJ)"""),
)
species(
label = '[CH2]C(CC=C)O[CH]C(3819)',
structure = SMILES('[CH2]C(CC=C)O[CH]C'),
E0 = (163.484,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3025,407.5,1350,352.5,3010,987.5,1337.5,450,1655,2950,3100,1380,975,1025,1650,1380,1390,370,380,2900,435,3000,3100,440,815,1455,1000,2750,2800,2850,1350,1500,750,1050,1375,1000,2750,2850,1437.5,1250,1305,750,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),
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 = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.476514,0.100614,-0.000104239,5.97469e-08,-1.40617e-11,19822,33.124], Tmin=(100,'K'), Tmax=(1019.28,'K')), NASAPolynomial(coeffs=[14.4489,0.0420412,-1.80417e-05,3.36892e-09,-2.33728e-13,16779.4,-39.1673], Tmin=(1019.28,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(163.484,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(457.296,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(Cs-CsCsOsH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(CCsJOCs) + radical(CJC(C)OC)"""),
)
species(
label = '[CH]=CCC(C)O[CH]C(3820)',
structure = SMILES('[CH]=CCC(C)O[CH]C'),
E0 = (200.07,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.310273,0.0928,-8.28024e-05,3.97954e-08,-7.8573e-12,24219.7,33.1694], Tmin=(100,'K'), Tmax=(1200.49,'K')), NASAPolynomial(coeffs=[15.5654,0.0399021,-1.6706e-05,3.08966e-09,-2.13273e-13,20408,-46.322], Tmin=(1200.49,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(200.07,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(457.296,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(Cs-CsCsOsH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(Cds_P) + radical(CCsJOCs)"""),
)
species(
label = '[CH2]C=CC([CH2])OCC(3772)',
structure = SMILES('[CH2]C([CH]C=C)OCC'),
E0 = (99.9445,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3025,407.5,1350,352.5,3010,987.5,1337.5,450,1655,2950,3100,1380,975,1025,1650,1380,1390,370,380,2900,435,3000,3100,440,815,1455,1000,2750,2800,2850,1350,1500,750,1050,1375,1000,2750,2850,1437.5,1250,1305,750,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),
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 = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.298874,0.0964724,-8.91655e-05,4.51931e-08,-9.54898e-12,12173.7,30.2367], Tmin=(100,'K'), Tmax=(1115.57,'K')), NASAPolynomial(coeffs=[14.0838,0.0449018,-1.98234e-05,3.75425e-09,-2.62508e-13,8964.76,-40.7243], Tmin=(1115.57,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(99.9445,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(457.296,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(Cs-CsCsOsH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(C=CCJCO) + radical(CJC(C)OC)"""),
)
species(
label = '[CH2][CH]OC(C)CC=C(3821)',
structure = SMILES('[CH2][CH]OC(C)CC=C'),
E0 = (164.563,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3025,407.5,1350,352.5,3010,987.5,1337.5,450,1655,2950,3100,1380,975,1025,1650,1380,1390,370,380,2900,435,2750,2850,1437.5,1250,1305,750,350,2750,2800,2850,1350,1500,750,1050,1375,1000,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),
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 = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.406804,0.094678,-8.66438e-05,4.25818e-08,-8.55409e-12,19952.9,33.7467], Tmin=(100,'K'), Tmax=(1185.45,'K')), NASAPolynomial(coeffs=[16.0774,0.0390565,-1.62638e-05,3.00204e-09,-2.07117e-13,16044.6,-48.5844], Tmin=(1185.45,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(164.563,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(457.296,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(Cs-CsCsOsH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(CJCO) + radical(CCsJOCs)"""),
)
species(
label = 'C=[C][CH]C(C)OCC(3822)',
structure = SMILES('C=[C][CH]C(C)OCC'),
E0 = (127.276,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3025,407.5,1350,352.5,1685,370,2950,3100,1380,975,1025,1650,1380,1390,370,380,2900,435,2750,2850,1437.5,1250,1305,750,350,2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,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),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.0212198,0.0883855,-7.10432e-05,3.07396e-08,-5.60672e-12,15450,29.8016], Tmin=(100,'K'), Tmax=(1261.27,'K')), NASAPolynomial(coeffs=[13.5439,0.0454995,-2.00399e-05,3.78083e-09,-2.63145e-13,12038.9,-38.5764], Tmin=(1261.27,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(127.276,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(457.296,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(Cs-CsCsOsH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(C=CCJCO) + radical(Cds_S)"""),
)
species(
label = '[CH]=C[CH]C(C)OCC(3823)',
structure = SMILES('[CH]C=CC(C)OCC'),
E0 = (128.528,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1380,1390,370,380,2900,435,2750,2850,1437.5,1250,1305,750,350,2995,3025,975,1000,1300,1375,400,500,1630,1680,2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,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),
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 = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.277184,0.0839529,-5.35869e-05,1.70314e-08,-2.20242e-12,15620.6,34.8068], Tmin=(100,'K'), Tmax=(1761.18,'K')), NASAPolynomial(coeffs=[19.1277,0.0398808,-1.60509e-05,2.82284e-09,-1.85533e-13,8785.4,-69.7938], Tmin=(1761.18,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(128.528,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(457.296,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + radical(AllylJ2_triplet)"""),
)
species(
label = 'C[CH][O](2420)',
structure = SMILES('C[CH][O]'),
E0 = (157.6,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2800,2850,1350,1500,750,1050,1375,1000,3025,407.5,1350,352.5,1642.51],'cm^-1')),
HinderedRotor(inertia=(0.123965,'amu*angstrom^2'), symmetry=1, barrier=(2.85019,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (44.0526,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[3.65562,0.0114444,2.34936e-06,-4.83164e-09,1.17966e-12,18963.9,10.3625], Tmin=(100,'K'), Tmax=(1718.65,'K')), NASAPolynomial(coeffs=[6.06294,0.0136322,-6.35953e-06,1.18407e-09,-7.90642e-14,16985.9,-5.90233], Tmin=(1718.65,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(157.6,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(199.547,'J/(mol*K)'), comment="""Thermo library: FFCM1(-) + radical(CCsJOH) + radical(CCOJ)"""),
)
species(
label = 'C[CH]OC(C)C1[CH]C1(3824)',
structure = SMILES('C[CH]OC(C)C1[CH]C1'),
E0 = (204.659,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.0842848,0.077934,-4.33036e-05,3.40071e-09,3.49607e-12,24771.9,33.105], Tmin=(100,'K'), Tmax=(1090.26,'K')), NASAPolynomial(coeffs=[16.4392,0.0372404,-1.47348e-05,2.69719e-09,-1.87009e-13,19984.5,-53.4712], Tmin=(1090.26,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(204.659,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(461.453,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(Cs-CsCsCsH) + group(Cs-CsCsOsH) + group(Cs-CsCsHH) + group(Cs-CsCsHH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + ring(Cyclopropane) + radical(cyclopropane) + radical(CCsJOCs)"""),
)
species(
label = 'CC1[CH][CH]CC(C)O1(3825)',
structure = SMILES('CC1[CH][CH]CC(C)O1'),
E0 = (77.3515,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.30204,0.0422985,5.4693e-05,-9.69592e-08,4.02792e-11,9416.05,26.6635], Tmin=(100,'K'), Tmax=(925.907,'K')), NASAPolynomial(coeffs=[11.84,0.0402369,-1.23789e-05,2.03102e-09,-1.37274e-13,5601.57,-33.4253], Tmin=(925.907,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(77.3515,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(473.925,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(Cs-CsCsOsH) + group(Cs-CsCsOsH) + group(Cs-CsCsHH) + group(Cs-CsCsHH) + group(Cs-CsCsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + ring(Oxane) + radical(RCCJCC) + radical(CCJCO)"""),
)
species(
label = 'C=CC=C(C)OCC(3826)',
structure = SMILES('C=CC=C(C)OCC'),
E0 = (-175.527,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.399998,0.0811753,-3.54254e-05,-1.76681e-08,1.41407e-11,-20938.6,29.1159], Tmin=(100,'K'), Tmax=(981.346,'K')), NASAPolynomial(coeffs=[20.8197,0.0297981,-1.05685e-05,1.90842e-09,-1.35414e-13,-26794.3,-81.4725], Tmin=(981.346,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-175.527,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(461.453,'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-CdsCsOs) + group(Cds-Cds(Cds-Cds)H) + group(Cds-Cds(Cds-Cds)H) + group(Cds-CdsHH)"""),
)
species(
label = 'C=CCC(C)OC=C(3827)',
structure = SMILES('C=CCC(C)OC=C'),
E0 = (-141.708,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.319971,0.0748521,-8.40801e-06,-5.14369e-08,2.74884e-11,-16869.8,31.0514], Tmin=(100,'K'), Tmax=(959.372,'K')), NASAPolynomial(coeffs=[23.0721,0.0260737,-8.36718e-06,1.50372e-09,-1.1023e-13,-23601.7,-92.5246], Tmin=(959.372,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-141.708,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(461.453,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(Cs-CsCsOsH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + group(Cds-CdsHH) + group(Cds-CdsHH)"""),
)
species(
label = 'C=C=CC(C)OCC(3828)',
structure = SMILES('C=C=CC(C)OCC'),
E0 = (-65.5517,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.0777533,0.0820083,-5.81638e-05,2.09623e-08,-3.08141e-12,-7731.24,32.02], Tmin=(100,'K'), Tmax=(1571.44,'K')), NASAPolynomial(coeffs=[17.5735,0.037078,-1.5276e-05,2.76762e-09,-1.86814e-13,-13278.8,-61.1154], Tmin=(1571.44,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-65.5517,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(461.453,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + group(Cdd-CdsCds)"""),
)
species(
label = 'CH2(S)(40)',
structure = SMILES('[CH2]'),
E0 = (418.921,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1358.21,2621.43,3089.55],'cm^-1')),
],
spinMultiplicity = 1,
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.19331,-0.00233105,8.15676e-06,-6.62986e-09,1.93233e-12,50366.2,-0.746734], Tmin=(200,'K'), Tmax=(1000,'K')), NASAPolynomial(coeffs=[3.13502,0.00289594,-8.16668e-07,1.13573e-10,-6.36263e-15,50504.1,4.06031], Tmin=(1000,'K'), Tmax=(6000,'K'))], Tmin=(200,'K'), Tmax=(6000,'K'), E0=(418.921,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(58.2013,'J/(mol*K)'), label="""CH2(S)""", comment="""Thermo library: FFCM1(-)"""),
)
species(
label = 'C=C[CH]CO[CH]C(3798)',
structure = SMILES('C=C[CH]CO[CH]C'),
E0 = (104.222,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2950,3100,1380,975,1025,1650,2750,2800,2850,1350,1500,750,1050,1375,1000,2750,2850,1437.5,1250,1305,750,350,3010,987.5,1337.5,450,1655,3000,3050,390,425,1340,1360,335,370,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 = 3,
opticalIsomers = 1,
molecularWeight = (98.143,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.173995,0.0808482,-7.1645e-05,3.35054e-08,-6.38097e-12,12675.4,26.3274], Tmin=(100,'K'), Tmax=(1247.9,'K')), NASAPolynomial(coeffs=[15.226,0.0326005,-1.36504e-05,2.52289e-09,-1.74037e-13,8918.7,-49.6235], Tmin=(1247.9,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(104.222,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(386.623,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsOsHH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(CCsJOCs) + radical(C=CCJCO)"""),
)
species(
label = 'C=CC(C)[CH]O[CH]C(3829)',
structure = SMILES('C=CC(C)[CH]O[CH]C'),
E0 = (136.009,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1380,1390,370,380,2900,435,3000,3050,390,425,1340,1360,335,370,2950,3100,1380,975,1025,1650,3010,987.5,1337.5,450,1655,2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,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),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.705444,0.0978297,-9.22448e-05,4.60842e-08,-9.25128e-12,16532.3,33.7292], Tmin=(100,'K'), Tmax=(1201.05,'K')), NASAPolynomial(coeffs=[18.2013,0.0348619,-1.36034e-05,2.43249e-09,-1.65063e-13,11990.7,-60.9484], Tmin=(1201.05,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(136.009,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(457.296,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(Cs-(Cds-Cds)CsCsH) + group(Cs-CsOsHH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(CCsJOCs) + radical(CCsJOCs)"""),
)
species(
label = 'C=CC1C(C)OC1C(2310)',
structure = SMILES('C=CC1C(C)OC1C'),
E0 = (-96.9159,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.795345,0.0502791,4.76034e-05,-1.02536e-07,4.56333e-11,-11522.1,25.4134], Tmin=(100,'K'), Tmax=(912.959,'K')), NASAPolynomial(coeffs=[17.1677,0.0312619,-7.76378e-06,1.14184e-09,-7.64101e-14,-16708.5,-64.1144], Tmin=(912.959,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-96.9159,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(469.768,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(Cs-(Cds-Cds)CsCsH) + group(Cs-CsCsOsH) + group(Cs-CsCsOsH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + ring(Oxetane)"""),
)
species(
label = 'CHCH3(T)(359)',
structure = SMILES('[CH]C'),
E0 = (343.893,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2800,2850,1350,1500,750,1050,1375,1000,592.414,4000],'cm^-1')),
HinderedRotor(inertia=(0.00438699,'amu*angstrom^2'), symmetry=1, barrier=(26.7685,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (28.0532,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[3.82363,-0.000909515,3.2138e-05,-3.7348e-08,1.3309e-11,41371.4,7.10948], Tmin=(100,'K'), Tmax=(960.812,'K')), NASAPolynomial(coeffs=[4.30487,0.00943069,-3.27559e-06,5.95121e-10,-4.27307e-14,40709.1,1.84202], Tmin=(960.812,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(343.893,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(128.874,'J/(mol*K)'), label="""CHCH3(T)""", comment="""Thermo library: DFT_QCI_thermo"""),
)
species(
label = 'C=C[CH]C(C)[O](3162)',
structure = SMILES('C=C[CH]C(C)[O]'),
E0 = (134.505,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1380,1390,370,380,2900,435,3025,407.5,1350,352.5,2950,3100,1380,975,1025,1650,3010,987.5,1337.5,450,1655,2750,2800,2850,1350,1500,750,1050,1375,1000,384.942,384.942,384.943],'cm^-1')),
HinderedRotor(inertia=(0.253012,'amu*angstrom^2'), symmetry=1, barrier=(26.6048,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.253012,'amu*angstrom^2'), symmetry=1, barrier=(26.6048,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.253012,'amu*angstrom^2'), symmetry=1, barrier=(26.6048,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (84.1164,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.09655,0.0540352,-2.42723e-05,-6.88289e-09,6.2884e-12,16290.2,22.111], Tmin=(100,'K'), Tmax=(1040.9,'K')), NASAPolynomial(coeffs=[13.895,0.0243842,-9.68902e-06,1.80337e-09,-1.27382e-13,12567.8,-45.2296], Tmin=(1040.9,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(134.505,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(320.107,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(Cs-CsCsOsH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(CC(C)OJ) + radical(C=CCJCO)"""),
)
species(
label = '[CH]=C[CH2](321)',
structure = SMILES('[CH]C=C'),
E0 = (376.654,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([3010,987.5,1337.5,450,1655,2950,3100,1380,975,1025,1650,229.711,230.18,230.787],'cm^-1')),
HinderedRotor(inertia=(1.33306,'amu*angstrom^2'), symmetry=1, barrier=(50.5153,'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.31912,0.00817959,3.34736e-05,-4.36194e-08,1.58213e-11,45331.5,10.6389], Tmin=(100,'K'), Tmax=(983.754,'K')), NASAPolynomial(coeffs=[5.36755,0.0170743,-6.35108e-06,1.1662e-09,-8.2762e-14,44095,-3.44606], Tmin=(983.754,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(376.654,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(203.705,'J/(mol*K)'), comment="""Thermo library: DFT_QCI_thermo + radical(AllylJ2_triplet)"""),
)
species(
label = 'C[CH]O[CH]C(3586)',
structure = SMILES('C[CH]O[CH]C'),
E0 = (87.5391,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,3000,3050,390,425,1340,1360,335,370,309.381,309.385,309.388],'cm^-1')),
HinderedRotor(inertia=(0.00176209,'amu*angstrom^2'), symmetry=1, barrier=(0.119627,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.189248,'amu*angstrom^2'), symmetry=1, barrier=(12.8422,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.189124,'amu*angstrom^2'), symmetry=1, barrier=(12.8416,'kJ/mol'), semiclassical=False),
HinderedRotor(inertia=(0.188973,'amu*angstrom^2'), symmetry=1, barrier=(12.8424,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (72.1057,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[1.10245,0.0618091,-6.3831e-05,3.5455e-08,-7.88959e-12,10634.5,19.5849], Tmin=(100,'K'), Tmax=(1091.38,'K')), NASAPolynomial(coeffs=[12.1588,0.0212864,-8.13614e-06,1.43372e-09,-9.63813e-14,8221.2,-34.7223], Tmin=(1091.38,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(87.5391,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(291.007,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(Cs-CsOsHH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + radical(CCsJOCs) + radical(CCsJOCs)"""),
)
species(
label = '[CH2][CH]C1C(C)OC1C(3830)',
structure = SMILES('[CH2][CH]C1C(C)OC1C'),
E0 = (174.021,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.715198,0.0578901,1.44284e-05,-5.97178e-08,2.81082e-11,21061.3,29.5339], Tmin=(100,'K'), Tmax=(925.275,'K')), NASAPolynomial(coeffs=[14.0021,0.0371761,-1.15292e-05,1.88222e-09,-1.2599e-13,17030.4,-42.0314], Tmin=(925.275,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(174.021,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(465.61,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(Cs-CsCsCsH) + group(Cs-CsCsOsH) + group(Cs-CsCsOsH) + group(Cs-CsCsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + ring(Oxetane) + radical(RCCJ) + radical(Cs_S)"""),
)
species(
label = 'C[C]=CC(C)O[CH]C(3769)',
structure = SMILES('C[C]=CC(C)O[CH]C'),
E0 = (176.142,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1380,1390,370,380,2900,435,3025,407.5,1350,352.5,1685,370,3010,987.5,1337.5,450,1655,2750,2762.5,2775,2787.5,2800,2812.5,2825,2837.5,2850,1350,1380,1410,1440,1470,1500,700,750,800,1000,1050,1100,1350,1375,1400,900,1000,1100,200,800,1200,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),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.0315203,0.0892071,-7.73261e-05,3.66213e-08,-7.24809e-12,21329.6,32.7109], Tmin=(100,'K'), Tmax=(1182.63,'K')), NASAPolynomial(coeffs=[13.6727,0.042855,-1.85343e-05,3.47916e-09,-2.41984e-13,18088.2,-35.7025], Tmin=(1182.63,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(176.142,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(457.296,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + radical(CCsJOCs) + radical(Cds_S)"""),
)
species(
label = 'C[CH]OC(C)[C]=CC(3767)',
structure = SMILES('C[CH]OC(C)[C]=CC'),
E0 = (176.142,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1380,1390,370,380,2900,435,3025,407.5,1350,352.5,1685,370,3010,987.5,1337.5,450,1655,2750,2762.5,2775,2787.5,2800,2812.5,2825,2837.5,2850,1350,1380,1410,1440,1470,1500,700,750,800,1000,1050,1100,1350,1375,1400,900,1000,1100,200,800,1200,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),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.0315203,0.0892071,-7.73261e-05,3.66213e-08,-7.24809e-12,21329.6,32.7109], Tmin=(100,'K'), Tmax=(1182.63,'K')), NASAPolynomial(coeffs=[13.6727,0.042855,-1.85343e-05,3.47916e-09,-2.41984e-13,18088.2,-35.7025], Tmin=(1182.63,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(176.142,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(457.296,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + radical(CCsJOCs) + radical(Cds_S)"""),
)
species(
label = '[CH2]C=[C]C(C)OCC(3831)',
structure = SMILES('[CH2]C=[C]C(C)OCC'),
E0 = (147.185,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,1685,370,1380,1390,370,380,2900,435,3000,3100,440,815,1455,1000,3010,987.5,1337.5,450,1655,2750,2850,1437.5,1250,1305,750,350,200,800,1200,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),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.00793185,0.0829089,-6.04027e-05,2.26745e-08,-3.50278e-12,17850.5,33.4619], Tmin=(100,'K'), Tmax=(1490.7,'K')), NASAPolynomial(coeffs=[16.276,0.0392141,-1.6435e-05,3.01133e-09,-2.05112e-13,12995.6,-51.5996], Tmin=(1490.7,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(147.185,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(457.296,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + radical(Allyl_P) + radical(Cds_S)"""),
)
species(
label = 'C[CH]O[C](C)C=CC(3764)',
structure = SMILES('C[CH]C=C(C)O[CH]C'),
E0 = (49.0705,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.640108,0.0891297,-6.12361e-05,1.18108e-08,2.87524e-12,6080.09,30.4291], Tmin=(100,'K'), Tmax=(1033.24,'K')), NASAPolynomial(coeffs=[20.3276,0.0315903,-1.20135e-05,2.18895e-09,-1.53071e-13,485.628,-77.5184], Tmin=(1033.24,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(49.0705,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(457.296,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsOs) + group(Cds-CdsCsH) + radical(CCsJOC(O)) + radical(Allyl_S)"""),
)
species(
label = '[CH2]C(C=CC)O[CH]C(2304)',
structure = SMILES('[CH2]C(C=CC)O[CH]C'),
E0 = (148.81,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1380,1390,370,380,2900,435,3025,407.5,1350,352.5,3000,3100,440,815,1455,1000,2995,3025,975,1000,1300,1375,400,500,1630,1680,2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,200,800,1200,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),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
collisionModel = TransportData(shapeIndex=2, epsilon=(3603.64,'J/mol'), sigma=(6.47245,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0, comment="""Epsilon & sigma estimated with Tc=562.88 K, Pc=30.16 bar (from Joback method)"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.366291,0.0974918,-9.62082e-05,5.20847e-08,-1.16087e-11,18053.8,33.1965], Tmin=(100,'K'), Tmax=(1070.7,'K')), NASAPolynomial(coeffs=[14.5818,0.0416478,-1.79736e-05,3.37249e-09,-2.3478e-13,14852.8,-39.9407], Tmin=(1070.7,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(148.81,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(457.296,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + radical(CCsJOCs) + radical(CJC(C)OC)"""),
)
species(
label = '[CH2][CH]OC(C)C=CC(3770)',
structure = SMILES('[CH2][CH]OC(C)C=CC'),
E0 = (149.889,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1380,1390,370,380,2900,435,3025,407.5,1350,352.5,3000,3100,440,815,1455,1000,2995,3025,975,1000,1300,1375,400,500,1630,1680,2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,200,800,1200,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),
HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False),
],
spinMultiplicity = 3,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.355725,0.0922259,-8.08084e-05,3.75408e-08,-7.11925e-12,18187.2,34.0329], Tmin=(100,'K'), Tmax=(1250.86,'K')), NASAPolynomial(coeffs=[16.5784,0.0380741,-1.58711e-05,2.93153e-09,-2.02187e-13,13950.7,-51.4551], Tmin=(1250.86,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(149.889,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(457.296,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + radical(CJCO) + radical(CCsJOCs)"""),
)
species(
label = 'C=COC(C)C=CC(3776)',
structure = SMILES('C=COC(C)C=CC'),
E0 = (-154.29,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.224767,0.0718746,-7.51271e-07,-5.87491e-08,2.98301e-11,-18385.7,31.1801], Tmin=(100,'K'), Tmax=(962.241,'K')), NASAPolynomial(coeffs=[23.0736,0.0259156,-8.43997e-06,1.54149e-09,-1.14178e-13,-25225.4,-92.5665], Tmin=(962.241,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-154.29,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(461.453,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + group(Cds-CdsOsH) + group(Cds-CdsHH)"""),
)
species(
label = 'CC1C=CCC(C)O1(2305)',
structure = SMILES('CC1C=CCC(C)O1'),
E0 = (-198.986,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
molecularWeight = (112.17,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.905611,0.0441047,6.69373e-05,-1.19665e-07,4.97254e-11,-23799.2,23.5039], Tmin=(100,'K'), Tmax=(946.16,'K')), NASAPolynomial(coeffs=[17.9393,0.0323207,-9.86314e-06,1.72557e-09,-1.25577e-13,-29718.4,-71.9773], Tmin=(946.16,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-198.986,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(473.925,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(Cs-CsCsOsH) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-(Cds-Cds)CsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsCsH) + ring(36dihydro2hpyran)"""),
)
species(
label = 'CH2(T)(33)',
structure = SMILES('[CH2]'),
E0 = (381.08,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([971.045,2816.03,3444.23],'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=[3.71758,0.00127391,2.17347e-06,-3.48858e-09,1.65209e-12,45872.4,1.75298], Tmin=(200,'K'), Tmax=(1000,'K')), NASAPolynomial(coeffs=[3.14632,0.00303671,-9.96474e-07,1.50484e-10,-8.57336e-15,46041.3,4.72342], Tmin=(1000,'K'), Tmax=(6000,'K'))], Tmin=(200,'K'), Tmax=(6000,'K'), E0=(381.08,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(58.2013,'J/(mol*K)'), label="""CH2(T)""", comment="""Thermo library: FFCM1(-)"""),
)
species(
label = '[CH]=CC(C)O[CH]C(3832)',
structure = SMILES('[CH]=CC(C)O[CH]C'),
E0 = (221.422,'kJ/mol'),
modes = [
HarmonicOscillator(frequencies=([1380,1390,370,380,2900,435,3025,407.5,1350,352.5,3120,650,792.5,1650,3010,987.5,1337.5,450,1655,2750,2770,2790,2810,2830,2850,1350,1400,1450,1500,700,800,1000,1100,1350,1400,900,1100,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 = 3,
opticalIsomers = 1,
molecularWeight = (98.143,'amu'),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.112798,0.0779437,-6.72043e-05,2.99661e-08,-5.35848e-12,26777.1,30.3184], Tmin=(100,'K'), Tmax=(1339.63,'K')), NASAPolynomial(coeffs=[16.9371,0.0277067,-1.09518e-05,1.9713e-09,-1.33982e-13,22269.5,-55.7679], Tmin=(1339.63,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(221.422,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(386.623,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(Cs-(Cds-Cds)CsOsH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cds-CdsCsH) + group(Cds-CdsHH) + radical(CCsJOCs) + radical(Cds_P)"""),
)
species(
label = 'N2',
structure = SMILES('N#N'),
E0 = (-8.69489,'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="""PrimaryTransportLibrary"""),
energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85),
thermo = NASA(polynomials=[NASAPolynomial(coeffs=[3.61263,-0.00100893,2.49898e-06,-1.43376e-09,2.58636e-13,-1051.1,2.6527], Tmin=(100,'K'), Tmax=(1817.04,'K')), NASAPolynomial(coeffs=[2.9759,0.00164141,-7.19722e-07,1.25378e-10,-7.91526e-15,-1025.84,5.53757], Tmin=(1817.04,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-8.69489,'kJ/mol'), Cp0=(29.1007,'J/(mol*K)'), CpInf=(37.4151,'J/(mol*K)'), label="""N2""", comment="""Thermo library: BurkeH2O2"""),
)
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"""),
)
transitionState(
label = 'TS1',
E0 = (69.8904,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS2',
E0 = (100.754,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS3',
E0 = (241.483,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS4',
E0 = (193.461,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS5',
E0 = (342.512,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS6',
E0 = (97.1854,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS7',
E0 = (223.155,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS8',
E0 = (255.307,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS9',
E0 = (259.387,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS10',
E0 = (391.012,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS11',
E0 = (227.624,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS12',
E0 = (282.728,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS13',
E0 = (338.084,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS14',
E0 = (186.553,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS15',
E0 = (223.976,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS16',
E0 = (279.821,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS17',
E0 = (273.713,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS18',
E0 = (397.665,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS19',
E0 = (295.826,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS20',
E0 = (96.2496,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS21',
E0 = (133.291,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS22',
E0 = (109.115,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS23',
E0 = (78.2584,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS24',
E0 = (523.142,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS25',
E0 = (330.774,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS26',
E0 = (78.1747,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS27',
E0 = (478.398,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS28',
E0 = (464.193,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS29',
E0 = (174.021,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS30',
E0 = (277.622,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS31',
E0 = (338.063,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS32',
E0 = (191.494,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS33',
E0 = (179.469,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS34',
E0 = (204.457,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS35',
E0 = (213.068,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS36',
E0 = (94.8636,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS37',
E0 = (77.4216,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
transitionState(
label = 'TS38',
E0 = (602.501,'kJ/mol'),
spinMultiplicity = 1,
opticalIsomers = 1,
)
reaction(
label = 'reaction1',
reactants = ['C=C[CH]C(C)O[CH]C(2302)'],
products = ['C=CC=CC(381)', 'CH3CHO(52)'],
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 = ['C=C[CH]C(C)O[CH]C(2302)'],
products = ['[CH2]C1[CH]C(C)OC1C(3810)'],
transitionState = 'TS2',
kinetics = Arrhenius(A=(187000,'s^-1'), n=1.48, Ea=(30.8638,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(2500,'K'), comment="""Estimated using an average for rate rule [R6;doublebond_intra_2H_pri;radadd_intra_csHNd]
Euclidian distance = 0
family: Intra_R_Add_Exocyclic
Ea raised from 23.9 to 30.9 kJ/mol to match endothermicity of reaction."""),
)
reaction(
label = 'reaction3',
reactants = ['H(19)', 'C=CC=C(C)O[CH]C(3811)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS3',
kinetics = Arrhenius(A=(170.641,'m^3/(mol*s)'), n=1.56204, Ea=(11.2897,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [Cds_Cds;HJ] for rate rule [Cds-OsCs_Cds;HJ]
Euclidian distance = 1.0
family: R_Addition_MultipleBond"""),
)
reaction(
label = 'reaction4',
reactants = ['H(19)', 'C=C[CH]C(C)OC=C(3812)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS4',
kinetics = Arrhenius(A=(6.67e+12,'cm^3/(mol*s)'), n=0.1, Ea=(6.4601,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(2000,'K'), comment="""From training reaction 2816 used for Cds-HH_Cds-OsH;HJ
Exact match found for rate rule [Cds-HH_Cds-OsH;HJ]
Euclidian distance = 0
family: R_Addition_MultipleBond"""),
)
reaction(
label = 'reaction5',
reactants = ['H(19)', 'C=C=CC(C)O[CH]C(3813)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS5',
kinetics = Arrhenius(A=(5.46e+08,'cm^3/(mol*s)'), n=1.64, Ea=(15.8155,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1500,'K'), comment="""From training reaction 2714 used for Ca_Cds-CsH;HJ
Exact match found for rate rule [Ca_Cds-CsH;HJ]
Euclidian distance = 0
family: R_Addition_MultipleBond"""),
)
reaction(
label = 'reaction6',
reactants = ['CH3CHO(52)', '[CH2]C=C[CH]C(377)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS6',
kinetics = Arrhenius(A=(4e+09,'cm^3/(mol*s)'), n=1.39, Ea=(35.8862,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(2000,'K'), comment="""Estimated using template [Od_CO-CsH;YJ] for rate rule [Od_CO-CsH;CJ]
Euclidian distance = 1.0
family: R_Addition_MultipleBond"""),
)
reaction(
label = 'reaction7',
reactants = ['CH3(34)', 'C=CC=CO[CH]C(3814)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS7',
kinetics = Arrhenius(A=(0.0063345,'m^3/(mol*s)'), n=2.46822, Ea=(26.7748,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [Cds_Cds;CsJ-HHH] for rate rule [Cds-OsH_Cds;CsJ-HHH]
Euclidian distance = 1.0
family: R_Addition_MultipleBond"""),
)
reaction(
label = 'reaction8',
reactants = ['C=CC[C](C)O[CH]C(3815)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS8',
kinetics = Arrhenius(A=(20108.5,'s^-1'), n=2.606, Ea=(121.63,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R2H_S;C_rad_out_NonDe;Cs_H_out_H/Cd] for rate rule [R2H_S;C_rad_out_NDMustO;Cs_H_out_H/Cd]
Euclidian distance = 1.0
Multiplied by reaction path degeneracy 2.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction9',
reactants = ['[CH2]COC(C)[CH]C=C(3816)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS9',
kinetics = Arrhenius(A=(3.7e+13,'s^-1','+|-',2), n=-0.1, Ea=(158.364,'kJ/mol'), T0=(1,'K'), Tmin=(700,'K'), Tmax=(1800,'K'), comment="""From training reaction 347 used for R2H_S;C_rad_out_2H;Cs_H_out_H/NonDeO
Exact match found for rate rule [R2H_S;C_rad_out_2H;Cs_H_out_H/NonDeO]
Euclidian distance = 0
Multiplied by reaction path degeneracy 2.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction10',
reactants = ['C=[C]CC(C)O[CH]C(3817)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS10',
kinetics = Arrhenius(A=(1.9054e+11,'s^-1'), n=0.853, Ea=(200.196,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [R2H_S;Cd_rad_out_Cd;Cs_H_out_H/(NonDeC/Cs)]
Euclidian distance = 0
Multiplied by reaction path degeneracy 2.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction11',
reactants = ['C=C[CH]C(C)O[CH]C(2302)'],
products = ['C=C[CH][C](C)OCC(3818)'],
transitionState = 'TS11',
kinetics = Arrhenius(A=(1.2544e+06,'s^-1'), n=1.86276, Ea=(157.734,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R3H_SS;C_rad_out_H/NonDeC;XH_out] for rate rule [R3H_SS_O;C_rad_out_H/NonDeC;XH_out]
Euclidian distance = 1.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction12',
reactants = ['[CH2]C(CC=C)O[CH]C(3819)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS12',
kinetics = Arrhenius(A=(25000,'s^-1'), n=2.28, Ea=(119.244,'kJ/mol'), T0=(1,'K'), comment="""From training reaction 85 used for R3H_SS_Cs;C_rad_out_2H;Cs_H_out_H/Cd
Exact match found for rate rule [R3H_SS_Cs;C_rad_out_2H;Cs_H_out_H/Cd]
Euclidian distance = 0
Multiplied by reaction path degeneracy 2.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction13',
reactants = ['C=C[CH]C(C)O[CH]C(2302)'],
products = ['[CH]=CCC(C)O[CH]C(3820)'],
transitionState = 'TS13',
kinetics = Arrhenius(A=(8.32e+10,'s^-1'), n=0.77, Ea=(268.194,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1500,'K'), comment="""From training reaction 195 used for R3H_SD;C_rad_out_H/NonDeC;Cd_H_out_singleH
Exact match found for rate rule [R3H_SD;C_rad_out_H/NonDeC;Cd_H_out_singleH]
Euclidian distance = 0
Multiplied by reaction path degeneracy 2.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction14',
reactants = ['[CH2]C=CC([CH2])OCC(3772)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS14',
kinetics = Arrhenius(A=(6.44e+09,'s^-1'), n=0.13, Ea=(86.6088,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1500,'K'), comment="""From training reaction 131 used for R4H_SSS;C_rad_out_2H;Cs_H_out_H/NonDeC
Exact match found for rate rule [R4H_SSS;C_rad_out_2H;Cs_H_out_H/NonDeC]
Euclidian distance = 0
Multiplied by reaction path degeneracy 2.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction15',
reactants = ['[CH2][CH]OC(C)CC=C(3821)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS15',
kinetics = Arrhenius(A=(62296.1,'s^-1'), n=1.86, Ea=(59.4128,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R5Hall;C_rad_out_2H;Cs_H_out_H/Cd] for rate rule [R5HJ_1;C_rad_out_2H;Cs_H_out_H/Cd]
Euclidian distance = 1.0
Multiplied by reaction path degeneracy 2.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction16',
reactants = ['C=[C][CH]C(C)OCC(3822)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS16',
kinetics = Arrhenius(A=(2.54505e+10,'s^-1'), n=0.959062, Ea=(152.545,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [RnH;Cd_rad_out_Cd;Cs_H_out_H/NonDeC] for rate rule [R5HJ_1;Cd_rad_out_Cd;Cs_H_out_H/NonDeC]
Euclidian distance = 2.0
Multiplied by reaction path degeneracy 2.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction17',
reactants = ['[CH]=C[CH]C(C)OCC(3823)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS17',
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 [RnH;Cd_rad_out_singleH;Cs_H_out_H/NonDeC] for rate rule [R6HJ_2;Cd_rad_out_singleH;Cs_H_out_H/NonDeC]
Euclidian distance = 2.0
Multiplied by reaction path degeneracy 2.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction18',
reactants = ['[CH2]C=C[CH]C(377)', 'C[CH][O](2420)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS18',
kinetics = Arrhenius(A=(7.35017e+06,'m^3/(mol*s)'), n=0.0284742, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [Y_rad;Y_rad]
Euclidian distance = 0
family: R_Recombination
Ea raised from -14.4 to 0 kJ/mol."""),
)
reaction(
label = 'reaction19',
reactants = ['C=C[CH]C(C)O[CH]C(2302)'],
products = ['C[CH]OC(C)C1[CH]C1(3824)'],
transitionState = 'TS19',
kinetics = Arrhenius(A=(1.05e+08,'s^-1'), n=1.192, Ea=(225.936,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R3_D;doublebond_intra_pri;radadd_intra_cs] for rate rule [R3_D;doublebond_intra_pri_2H;radadd_intra_csHCs]
Euclidian distance = 2.2360679775
family: Intra_R_Add_Endocyclic"""),
)
reaction(
label = 'reaction20',
reactants = ['C=C[CH]C(C)O[CH]C(2302)'],
products = ['CC1[CH][CH]CC(C)O1(3825)'],
transitionState = 'TS20',
kinetics = Arrhenius(A=(487000,'s^-1'), n=1.17, Ea=(26.3592,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(2500,'K'), comment="""Estimated using an average for rate rule [R6_linear;doublebond_intra_pri_2H;radadd_intra_csHCs]
Euclidian distance = 0
family: Intra_R_Add_Endocyclic"""),
)
reaction(
label = 'reaction21',
reactants = ['C=C[CH]C(C)O[CH]C(2302)'],
products = ['C=CC=C(C)OCC(3826)'],
transitionState = 'TS21',
kinetics = Arrhenius(A=(7.437e+08,'s^-1'), n=1.045, Ea=(63.4002,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R3radExo;Y_rad_NDe;XH_Rrad] for rate rule [R3radExo;Y_rad_NDe;XH_Rrad_De]
Euclidian distance = 1.0
family: Intra_Disproportionation"""),
)
reaction(
label = 'reaction22',
reactants = ['C=C[CH]C(C)O[CH]C(2302)'],
products = ['C=CCC(C)OC=C(3827)'],
transitionState = 'TS22',
kinetics = Arrhenius(A=(5.55988e+09,'s^-1'), n=0.137, Ea=(39.225,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R5;Y_rad_De;XH_Rrad] for rate rule [R5radEndo;Y_rad_De;XH_Rrad]
Euclidian distance = 1.0
Multiplied by reaction path degeneracy 3.0
family: Intra_Disproportionation"""),
)
reaction(
label = 'reaction23',
reactants = ['C=C[CH]C(C)O[CH]C(2302)'],
products = ['C=C=CC(C)OCC(3828)'],
transitionState = 'TS23',
kinetics = Arrhenius(A=(3.21e+09,'s^-1'), n=0.137, Ea=(8.368,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1500,'K'), comment="""Estimated using template [R5;Y_rad_NDe;XH_Rrad] for rate rule [R5radEndo;Y_rad_NDe;XH_Rrad]
Euclidian distance = 1.0
family: Intra_Disproportionation"""),
)
reaction(
label = 'reaction24',
reactants = ['CH2(S)(40)', 'C=C[CH]CO[CH]C(3798)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS24',
kinetics = Arrhenius(A=(143764,'m^3/(mol*s)'), n=0.444, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [carbene;R_H]
Euclidian distance = 0
Multiplied by reaction path degeneracy 2.0
family: 1,2_Insertion_carbene
Ea raised from -5.1 to 0 kJ/mol."""),
)
reaction(
label = 'reaction25',
reactants = ['C=CC(C)[CH]O[CH]C(3829)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS25',
kinetics = Arrhenius(A=(5.59192e+09,'s^-1'), n=1.025, Ea=(194.765,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [cCs(-HC)CJ;CsJ;CH3]
Euclidian distance = 0
family: 1,2_shiftC"""),
)
reaction(
label = 'reaction26',
reactants = ['C=C[CH]C(C)O[CH]C(2302)'],
products = ['C=CC1C(C)OC1C(2310)'],
transitionState = 'TS26',
kinetics = Arrhenius(A=(1.62e+12,'s^-1'), n=-0.305, Ea=(8.28432,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R4_SSS;C_rad_out_single;Cpri_rad_out_single] for rate rule [R4_SSS;C_rad_out_H/NonDeC;Cpri_rad_out_H/OneDe]
Euclidian distance = 2.82842712475
family: Birad_recombination"""),
)
reaction(
label = 'reaction27',
reactants = ['CHCH3(T)(359)', 'C=C[CH]C(C)[O](3162)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS27',
kinetics = Arrhenius(A=(54738.4,'m^3/(mol*s)'), n=0.884925, Ea=(0,'kJ/mol'), T0=(1,'K'), Tmin=(303.03,'K'), Tmax=(2000,'K'), comment="""Estimated using an average for rate rule [O_rad/NonDe;Birad]
Euclidian distance = 0
family: Birad_R_Recombination
Ea raised from -2.9 to 0 kJ/mol."""),
)
reaction(
label = 'reaction28',
reactants = ['[CH]=C[CH2](321)', 'C[CH]O[CH]C(3586)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS28',
kinetics = Arrhenius(A=(4.4725e+06,'m^3/(mol*s)'), n=0.36814, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [Y_rad;Birad] for rate rule [C_rad/H/CsO;Birad]
Euclidian distance = 4.0
Multiplied by reaction path degeneracy 2.0
family: Birad_R_Recombination
Ea raised from -1.7 to 0 kJ/mol."""),
)
reaction(
label = 'reaction29',
reactants = ['C=C[CH]C(C)O[CH]C(2302)'],
products = ['[CH2][CH]C1C(C)OC1C(3830)'],
transitionState = 'TS29',
kinetics = Arrhenius(A=(4.73e+06,'s^-1'), n=1.31, Ea=(104.13,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(2500,'K'), comment="""Estimated using an average for rate rule [R5_SS_D;doublebond_intra;radadd_intra_csHNd]
Euclidian distance = 0
family: Intra_R_Add_Exocyclic
Ea raised from 98.9 to 104.1 kJ/mol to match endothermicity of reaction."""),
)
reaction(
label = 'reaction30',
reactants = ['C=C[CH]C(C)O[CH]C(2302)'],
products = ['C[C]=CC(C)O[CH]C(3769)'],
transitionState = 'TS30',
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 = 'reaction31',
reactants = ['C[CH]OC(C)[C]=CC(3767)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS31',
kinetics = Arrhenius(A=(7.74e+09,'s^-1'), n=1.08, Ea=(161.921,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1500,'K'), comment="""From training reaction 198 used for R3H_DS;Cd_rad_out_Cs;Cs_H_out_2H
Exact match found for rate rule [R3H_DS;Cd_rad_out_Cs;Cs_H_out_2H]
Euclidian distance = 0
Multiplied by reaction path degeneracy 3.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction32',
reactants = ['[CH2]C=[C]C(C)OCC(3831)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS32',
kinetics = Arrhenius(A=(74200,'s^-1'), n=2.23, Ea=(44.3086,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R4H_RSS;Cd_rad_out;Cs_H_out_1H] for rate rule [R4H_SSS;Cd_rad_out_Cd;Cs_H_out_H/NonDeC]
Euclidian distance = 2.44948974278
Multiplied by reaction path degeneracy 2.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction33',
reactants = ['C=C[CH]C(C)O[CH]C(2302)'],
products = ['C[CH]O[C](C)C=CC(3764)'],
transitionState = 'TS33',
kinetics = Arrhenius(A=(1.86e+10,'s^-1'), n=0.58, Ea=(109.579,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R4H;C_rad_out_2H;Cs_H_out_NonDe] for rate rule [R4H_SDS;C_rad_out_2H;Cs_H_out_NDMustO]
Euclidian distance = 2.2360679775
family: intra_H_migration"""),
)
reaction(
label = 'reaction16',
reactants = ['[CH2]C(C=CC)O[CH]C(2304)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS34',
kinetics = Arrhenius(A=(121000,'s^-1'), n=1.9, Ea=(55.6472,'kJ/mol'), T0=(1,'K'), comment="""From training reaction 92 used for R5H_SSMS;C_rad_out_2H;Cs_H_out_2H
Exact match found for rate rule [R5H_SSMS;C_rad_out_2H;Cs_H_out_2H]
Euclidian distance = 0
Multiplied by reaction path degeneracy 3.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction35',
reactants = ['[CH2][CH]OC(C)C=CC(3770)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS35',
kinetics = Arrhenius(A=(64.2,'s^-1'), n=2.1, Ea=(63.1784,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R7Hall;C_rad_out_2H;Cs_H_out_2H] for rate rule [R7HJ_1;C_rad_out_2H;Cs_H_out_2H]
Euclidian distance = 1.0
Multiplied by reaction path degeneracy 3.0
family: intra_H_migration"""),
)
reaction(
label = 'reaction36',
reactants = ['C=C[CH]C(C)O[CH]C(2302)'],
products = ['C=COC(C)C=CC(3776)'],
transitionState = 'TS36',
kinetics = Arrhenius(A=(6.37831e+09,'s^-1'), n=0.137, Ea=(24.9733,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R7;Y_rad;XH_Rrad] for rate rule [R7radEndo;Y_rad;XH_Rrad]
Euclidian distance = 1.0
Multiplied by reaction path degeneracy 3.0
family: Intra_Disproportionation"""),
)
reaction(
label = 'reaction37',
reactants = ['C=C[CH]C(C)O[CH]C(2302)'],
products = ['CC1C=CCC(C)O1(2305)'],
transitionState = 'TS37',
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;C_rad_out_1H;Cpri_rad_out_2H] for rate rule [R6_SSSDS;C_rad_out_H/NonDeC;Cpri_rad_out_2H]
Euclidian distance = 1.0
family: Birad_recombination"""),
)
reaction(
label = 'reaction38',
reactants = ['CH2(T)(33)', '[CH]=CC(C)O[CH]C(3832)'],
products = ['C=C[CH]C(C)O[CH]C(2302)'],
transitionState = 'TS38',
kinetics = Arrhenius(A=(2.23625e+06,'m^3/(mol*s)'), n=0.36814, Ea=(0,'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
Ea raised from -1.7 to 0 kJ/mol."""),
)
network(
label = '556',
isomers = [
'C=C[CH]C(C)O[CH]C(2302)',
],
reactants = [
('C=CC=CC(381)', 'CH3CHO(52)'),
],
bathGas = {
'N2': 0.5,
'Ne': 0.5,
},
)
pressureDependence(
label = '556',
Tmin = (300,'K'),
Tmax = (2000,'K'),
Tcount = 8,
Tlist = ([302.47,323.145,369.86,455.987,609.649,885.262,1353.64,1896.74],'K'),
Pmin = (0.01,'bar'),
Pmax = (100,'bar'),
Pcount = 5,
Plist = ([0.0125282,0.0667467,1,14.982,79.8202],'bar'),
maximumGrainSize = (0.5,'kcal/mol'),
minimumGrainCount = 250,
method = 'modified strong collision',
interpolationModel = ('Chebyshev', 6, 4),
activeKRotor = True,
activeJRotor = True,
rmgmode = True,
)
| [
"qin.she@husky.neu.edu"
] | qin.she@husky.neu.edu |
873ef7519fe5ab23bc29586a5ff39fde227b9ee8 | 6ef5161fff46ad6d5982b2e24175ff7fca06f2c5 | /mainFlask.py | 6b1b762760550bad28f2a2d07641fa50cabc5417 | [] | no_license | critopadolf/GPT2_Discord_Voice_Bot | 9438d87d1a1f43f4f4feb5fd75f9518e29dbee61 | ecca6896a7dab1cd778b71dbf1a9f969891ec8d9 | refs/heads/main | 2023-05-02T07:55:59.972238 | 2021-05-14T19:15:33 | 2021-05-14T19:15:33 | 367,455,787 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 710 | py | from flask import Flask
from flask import request
import gpt2_run
from multiprocessing import Process, Queue
app = Flask(__name__)
outStr = Queue()
str1 = Queue()
p = Process(target=gpt2_run.run,args=(str1,outStr,))
@app.route('/gather', methods=['POST'])
def gather():
#gin = request.values['SpeechResult']
#server = request.json['server_key']
print(request.values)
str1.put(request.values)
return "thanks"
@app.route('/p',methods=['POST'])
def pl():
print(request)
g = request.json['GPT2_RESULT']
print("g:",g)
return "p"
if __name__ == "__main__":
print("starting process")
p.start()
print("process started")
app.run(debug=True)
#dial_numbers(DIAL_NUMBERS) | [
"noreply@github.com"
] | noreply@github.com |
2060b51ab978bb8cf382cabd4423a50c97cdea4d | a9284aca96474e2561a6c1bf5d509be294bcfad4 | /model.py | bf56cf034044d9d31b35095419bdfad9b141c0d0 | [] | no_license | Dream7-Kim/minimize | 66f890ad261ecb1cd345c77b6dcab646effcea2d | 200aee7205a31d02238c3ab278d1f8bdccb1fb22 | refs/heads/master | 2020-09-09T08:16:08.037337 | 2019-11-13T07:26:32 | 2019-11-13T07:26:32 | 221,396,969 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,614 | py | import matplotlib.pyplot as plt
import numpy as onp
import jax.numpy as np
import os
import jax
import time
import scipy.optimize as opt
import seaborn as sns
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
i = complex(
0,
1,
)
def read(string):
lines = open(string).readlines()
row = int(len(lines)/4)
lists = []
for line in lines:
str = line.replace('[', '')
str = str.replace(']', '')
str = str.strip()
tmp = float(str)
lists.append(tmp)
array = onp.array(lists).reshape(row, 4)
return array
def BW(mass, width, Pb, Pc):
Pbc = Pb + Pc
_Pbc = Pbc * np.array([-1, -1, -1, 1])
Sbc = onp.sum(Pbc * _Pbc, axis=1)
return 1 / (mass**2 - Sbc - i * mass * width)
def phase(theta, rho):
return rho * np.exp(theta*i)
phif001 = read('data/phif001MC.txt')
phif021 = read('data/phif021MC.txt')
Kp = read('data/KpMC.txt')
Km = read('data/KmMC.txt')
Pip = read('data/PipMC.txt')
Pim = read('data/PimMC.txt')
def modelf0(var, phif001, phif001MC, phif021, phif021MC, Kp, Km, Pip, Pim, KpMC, KmMC, PipMC, PimMC):
up_phif001 = phif001.T * BW(var[0], var[1], Kp,
Km) * BW(var[2], var[3], Pip, Pim)
up_phif021 = phif021.T * BW(var[0], var[1], Kp,
Km) * BW(var[2], var[3], Pip, Pim)
# print(up_phif001.shape)
up_1 = (up_phif001 + up_phif021)
# print(up_1.shape)
up_2 = np.vstack([up_1[0, :], up_1[1, :]])
# print(up_2.shape)
conj_up_2 = np.conj(up_2)
up_3 = np.real(np.sum(up_2 * conj_up_2, axis=0))/2
# print(up_3.shape)
low_phif001 = phif001MC.T * \
BW(var[0], var[1], KpMC, KmMC) * BW(var[2], var[3], PipMC, PimMC)
low_phif021 = phif021MC.T * \
BW(var[0], var[1], KpMC, KmMC) * BW(var[2], var[3], PipMC, PimMC)
low_1 = (low_phif001 + low_phif021)
low_2 = np.vstack([low_1[0, :], low_1[1, :]])
conj_low_2 = np.conj(low_2)
low_3 = np.real(np.sum(low_2 * conj_low_2, axis=0))/2
# print(low_3.shape)
dim = (low_3.shape)[0]
# print(dim)
low_4 = np.sum(low_3)/dim
return up_3 / low_4
def model(var, phif001, phif001MC, phif021, phif021MC, Kp, Km, Pip, Pim, KpMC, KmMC, PipMC, PimMC, weight):
up_phif001 = phif001.T * BW(var[0], var[1], Kp,
Km) * BW(var[2], var[3], Pip, Pim)
up_phif021 = phif021.T * BW(var[0], var[1], Kp,
Km) * BW(var[2], var[3], Pip, Pim)
# print(up_phif001.shape)
up_1 = (up_phif001 + up_phif021)
# print(up_1.shape)
up_2 = np.vstack([up_1[0, :], up_1[1, :]])
# print(up_2.shape)
conj_up_2 = np.conj(up_2)
up_3 = np.real(np.sum(up_2 * conj_up_2, axis=0))/2
# print(up_3.shape)
low_phif001 = phif001MC.T * \
BW(var[0], var[1], KpMC, KmMC) * BW(var[2], var[3], PipMC, PimMC)
low_phif021 = phif021MC.T * \
BW(var[0], var[1], KpMC, KmMC) * BW(var[2], var[3], PipMC, PimMC)
low_1 = (low_phif001 + low_phif021)
low_2 = np.vstack([low_1[0, :], low_1[1, :]])
conj_low_2 = np.conj(low_2)
low_3 = np.real(np.sum(low_2 * conj_low_2, axis=0))/2
# print(low_3.shape)
dim = (low_3.shape)[0]
# print(dim)
low_4 = np.sum(low_3)/dim
return -np.sum(np.log(up_3/low_4)*weight)
var_weight = np.array([1.02, 0.004, 1.37, 0.35])
weight_ = modelf0(var_weight, phif001[:50000], phif001[50000:5000000], phif021[:50000], phif021[50000:5000000], Kp[:50000],
Km[:50000], Pip[:50000], Pim[:50000], Kp[50000:5000000], Km[50000:5000000], Pip[50000:5000000], Pim[50000:5000000]) | [
"ddrr716@163.com"
] | ddrr716@163.com |
dfa8bfc9662c0ea80d0f1a5c4833aaf4c4443764 | 5a295e26ec9e8dff954c6ec0d88f8c348c2b4b17 | /venv/Scripts/pip3-script.py | e6db81d57ef232ced1d11b7d995bf08af9910ad2 | [] | no_license | galaschi/dotatimer | d07fbc724eb6dad55d70f01af6f727dc5760d93a | efe451cd2c42c5cccfb0cd6bd35f9cfd6708cd0b | refs/heads/master | 2021-06-27T12:30:54.662679 | 2019-11-25T19:52:48 | 2019-11-25T19:52:48 | 223,814,804 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 412 | py | #!C:\Users\Victor\PycharmProjects\timer\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')()
)
| [
"victorgalaschi@hotmail.com"
] | victorgalaschi@hotmail.com |
f497f86195d3bc12f46e34a657680f15b0f28836 | 106a226d39c3bdfd292ea6f612c806fe2780f990 | /manage.py | 53b30a6587cac01573f80cf88094870eb3632fe5 | [
"Unlicense"
] | permissive | rdegges/django-twilio | 519c5c91c065c2ac3641d84c186c2778c5b94084 | 67bce5be124a28d0ccdff067be052c29f2f66e36 | refs/heads/master | 2023-08-05T09:59:14.545195 | 2023-06-13T14:26:20 | 2023-06-13T14:26:20 | 1,954,013 | 221 | 88 | Unlicense | 2023-06-13T14:22:20 | 2011-06-25T23:22:08 | Python | UTF-8 | Python | false | false | 336 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_project.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| [
"danieldhawkins@gmail.com"
] | danieldhawkins@gmail.com |
bc2d0f2db40155e38111225ec1a81a2861d65746 | 6586768eb0701350b90daa5b6a278518376819fb | /peak/mapper/multi.py | d4b1451988a50844e3fdb04e23c8f3646023dd95 | [] | no_license | cdonovick/peak | c0ed8496b405f25b61336bf1f4e10c0d3ce9b5f4 | 7846f13c32877472e01bfbc5221fc19c041d207c | refs/heads/master | 2023-05-28T00:50:59.060837 | 2022-12-09T19:44:52 | 2022-12-09T19:44:52 | 159,844,296 | 18 | 2 | null | 2022-12-09T19:44:54 | 2018-11-30T15:43:14 | Python | UTF-8 | Python | false | false | 12,099 | py | import itertools
from functools import reduce
from types import SimpleNamespace
from hwtypes import strip_modifiers
from peak import family as peak_family, family_closure, Peak, Const
from .mapper import aadt_product_to_dict, external_loop_solve
from .index_var import IndexVar, OneHot, Binary
from .mapper import _get_peak_cls, _create_free_var, create_and_set_bb_outputs, wrap_outputs, is_valid, get_bb_inputs
from .utils import _sort_by_t, pretty_print_binding, solved_to_bv, Unbound
from .formula_constructor import And, Or, Implies
import pysmt.shortcuts as smt
from pysmt.logics import BV
def create_bindings(inputs, outputs, use_unbound=True):
inputs_by_t = _sort_by_t(inputs)
outputs_by_t = _sort_by_t(outputs)
#check early out
if (not use_unbound) and (not all((o_t in inputs_by_t) for o_t in outputs_by_t)):
raise ValueError("No matching Bindings")
#inputs = ir, outputs = arch
possible_matching = []
for o_path, o_T in outputs.items():
poss = []
if use_unbound:
poss.append(Unbound)
if o_T in inputs_by_t:
poss += inputs_by_t[o_T]
possible_matching.append(poss)
assert all(len(p)>0 for p in possible_matching)
bindings = []
for l in itertools.product(*possible_matching):
binding = list(zip(l, outputs.keys()))
bindings.append(binding)
return bindings
#This will Solve a multi-rewrite rule N instructions
def Multi(arch_fc, ir_fc, N: int, family=peak_family, IVar: IndexVar = Binary, use_real = True, use_split_instr = False):
def parse_peak_fc(peak_fc):
if not isinstance(peak_fc, family_closure):
raise ValueError(f"family closure {peak_fc} needs to be decorated with @family_closure")
Peak_cls = _get_peak_cls(peak_fc(family.SMTFamily()))
try:
input_t = Peak_cls.input_t
output_t = Peak_cls.output_t
except AttributeError:
raise ValueError("Need to use gen_input_t and gen_output_t")
stripped_input_t = strip_modifiers(input_t)
stripped_output_t = strip_modifiers(output_t)
input_aadt_t = family.SMTFamily().get_adt_t(stripped_input_t)
output_aadt_t = family.SMTFamily().get_adt_t(stripped_output_t)
const_dict = {field: T for field, T in input_t.field_dict.items() if issubclass(T, Const)}
non_const_dict = {field: T for field, T in input_t.field_dict.items() if not issubclass(T, Const)}
return SimpleNamespace(
input_aadt=input_aadt_t,
stripped_input_t=stripped_input_t,
input_t = input_t,
stripped_output_t = stripped_output_t,
output_t = output_t,
output_aadt=output_aadt_t,
cls=Peak_cls,
const_dict=const_dict,
non_const_dict=non_const_dict,
)
ir_info = parse_peak_fc(ir_fc)
arch_info = parse_peak_fc(arch_fc)
if len(ir_info.const_dict) != 0:
raise NotImplementedError()
if len(arch_info.const_dict) != 1:
raise NotImplementedError()
def run_peak(obj, output_aadt, input_dict, bb_prefix):
bb_outputs = create_and_set_bb_outputs(obj, family=family, prefix=bb_prefix)
outputs = obj(**input_dict)
output = wrap_outputs(outputs, output_aadt)
#output_dict = {(k,): v for k, v in aadt_product_to_dict(output).items()}
output_dict = aadt_product_to_dict(output)
bb_inputs = get_bb_inputs(obj)
return output_dict, bb_inputs, bb_outputs
ir_inputs = {field: _create_free_var(ir_info.input_aadt[field], f"II_{field}") for field in ir_info.stripped_input_t.field_dict}
ir_obj = ir_info.cls()
ir_outputs, ir_bb_inputs, ir_bb_outputs = run_peak(ir_obj, ir_info.output_aadt, ir_inputs, bb_prefix=f"IR_")
#This contains the 'input binding' for a particular instruction. Indexed by instruction index
block_info = []
pysmt_forall_vars = [v.value for v in ir_inputs.values()]
valid_conds = []
def translate(path, use_real=True):
if path[0] == "IR_in":
assert len(path) == 2
val = ir_inputs[path[1]]
elif path[0] == "IR_out":
assert len(path) == 2
val = ir_outputs[path[1]]
elif path[0] == "Arch_in":
assert len(path) == 3
val = block_info[path[1]].arch_inputs[path[2]]
elif path[0] == "Arch_out":
assert len(path) == 3
j = path[1]
assert len(block_info) > j
if use_real:
val = block_info[j].real_arch_outputs[path[2]]
else:
val = block_info[j].free_arch_outputs[path[2]]
else:
assert 0
return val
#only output
def do_bindings(inputs, outputs, name):
bindings = create_bindings(inputs, outputs, use_unbound=False)
bind_var = IVar(len(bindings), name=name)
valid_conds.append(bind_var.is_valid())
impl_conds = []
# Will be Ored
for b, binding in enumerate(bindings):
b_match = bind_var.match_index(b)
# TO be anded
bind_conds = [b_match]
for ipath, opath in binding:
ival = translate(ipath, use_real=True)
oval = translate(opath, use_real=True)
bind_conds.append(ival == oval)
impl_conds.append(And(bind_conds))
return bindings, bind_var, Or(impl_conds)
for i in range(N):
arch_obj = arch_info.cls()
input_aadt = arch_info.input_aadt
output_aadt = arch_info.output_aadt
arch_inputs = {field:_create_free_var(input_aadt[field], f"ArchIn_I{i}_{field}") for field in arch_info.stripped_input_t.field_dict}
free_arch_outputs = {field:_create_free_var(output_aadt[field], f"ArchOut_I{i}_{field}") for field in arch_info.output_t.field_dict}
real_arch_outputs, bb_inputs, bb_outputs = run_peak(arch_obj, output_aadt, arch_inputs, bb_prefix=f"{i}.BB.{arch_info.cls.__name__}")
pysmt_forall_vars += [v.value for field, v in arch_inputs.items() if field in arch_info.non_const_dict]
pysmt_forall_vars += [v.value for v in bb_outputs.values()]
#Creating i'th binding
#Consisting of the ir_inputs, arch_inputs, Arch_output[N-1 ... 1])
inputs = {
**{("IR_in", field):T for field, T in ir_info.input_t.field_dict.items()},
#**{(f"Arch_in", i, field):T for field, T in arch_info.non_const_dict.items()},
}
for j in range(i):
inputs = {
**inputs,
**{("Arch_out", j, field):T for field, T in arch_info.output_t.field_dict.items()},
}
outputs = {(f"Arch_in", i, field):T for field, T in arch_info.non_const_dict.items()}
bindings = create_bindings(inputs, outputs, use_unbound=True)
block_info.append(SimpleNamespace(
arch_inputs=arch_inputs,
free_arch_outputs=free_arch_outputs,
real_arch_outputs=real_arch_outputs,
obj=arch_obj,
bb_outputs=bb_outputs,
bb_inputs=bb_inputs,
bindings=bindings
))
#Out of the cross product of the bindings, filter out everything that does not use all the ir inputs
ir_paths = [("IR_in", field) for field in ir_info.input_t.field_dict]
all_bindings = [block.bindings for block in block_info]
orig_bindings = reduce(lambda x, y: x*y, [len(b) for b in all_bindings])
def filt(x):
bind = [b[x[j]] for j, b in enumerate(all_bindings)]
found = [0 for _ in ir_paths]
for j, p in enumerate(ir_paths):
for binding in bind:
for input, _ in binding:
if input == p:
found[j] += 1
return all(f in (1,) for f in found)
valid_bindings = list(filter(filt, itertools.product(*[range(len(bindings)) for bindings in all_bindings])))
if len(valid_bindings) == 0:
raise ValueError("There are no valid Bindings")
bind_var = IVar(len(valid_bindings), "bind_in")
valid_conds.append(bind_var.is_valid())
# Will be Ored
impl_conds = []
for b, bind_indices in enumerate(valid_bindings):
assert len(bind_indices) == N
b_match = bind_var.match_index(b)
# TO be anded
bind_conds = [b_match]
for bind_index, block in zip(bind_indices, block_info):
binding = block.bindings[bind_index]
for ipath, opath in binding:
if ipath is Unbound:
ipath = opath
ival = translate(ipath, use_real=use_real)
oval = translate(opath, use_real=use_real)
bind_conds.append(ival == oval)
impl_conds.append(And(bind_conds))
#set fake to real except for the last one
if not use_real:
if N==1:
free_repl = family.SMTFamily().Bit(True)
else:
free_repl = []
for i in range(N-1):
real = block_info[i].real_arch_outputs
fake = block_info[i].free_arch_outputs
for vr, vf in zip(real.values(), fake.values()):
pysmt_forall_vars.append(vf.value)
free_repl.append(vf==vr)
free_repl = And(free_repl)
#Output bindings
#This assumes that the output bindings will only be a function of the outputs of the last instruction
#Might not hold true if IR node is computing multiple things (ie i64.Add)
inputs = {
**{(f"Arch_out", N-1, field):T for field, T in arch_info.output_t.field_dict.items()},
}
outputs = {(f"IR_out", field):T for field, T in ir_info.output_t.field_dict.items()}
out_bindings, bind_out_var, out_conds = do_bindings(inputs, outputs, f"bind_out")
block_info.append(SimpleNamespace(
bindings=out_bindings,
bind_var=bind_out_var,
impl_conds=out_conds
))
if use_split_instr:
#This will use an SMT Form instruction instead of a raw instruction. Might be faster
raise NotImplementedError()
else:
for i in range(N):
arch_inputs = block_info[i].arch_inputs
# Make sure instruction is valid
for field in arch_info.const_dict:
valid_conds.append(is_valid(arch_inputs[field]))
valid_cond = And(valid_conds)
if use_real:
impl_cond = Or(impl_conds)
else:
impl_cond = And([free_repl, Or(impl_conds)])
F = out_conds
formula = And([valid_cond, Implies(impl_cond, F)])
formula = formula.to_hwtypes()
forall_vars = pysmt_forall_vars
formula_wo_forall = formula.value
formula = smt.ForAll(pysmt_forall_vars, formula.value)
info = SimpleNamespace(
N=N,
block_info=block_info,
arch_info=arch_info,
bind_var=bind_var,
valid_bindings=valid_bindings,
)
def solve(maxloops=20, logic=BV, solver_name="z3"):
return external_loop_solve(forall_vars, formula_wo_forall, logic=logic, maxloops=maxloops, solver_name=solver_name, rr_from_solver=RR, irmapper=info)
return solve
#Definititely a bit hacked. Really should contain a verify function and better pretty printers
def RR(solver, info):
if solver is None:
return None
def get_info():
N = info.N
block_info = info.block_info
arch_info = info.arch_info
bind_var = info.bind_var
bind_val = bind_var.decode(int(solved_to_bv(bind_var.var, solver)))
print(bind_var.var.value, bind_val)
binding_indices = info.valid_bindings[bind_val]
for i in range(N):
print("*"*100)
print(f"Instruction {i}")
binding = block_info[i].bindings[binding_indices[i]]
pretty_print_binding(binding)
instrs = [block_info[i].arch_inputs[field] for field in arch_info.const_dict]
ivals = [solved_to_bv(instr._value_,solver) for instr in instrs]
print(ivals)
return info
return get_info
| [
"rdaly525@stanford.edu"
] | rdaly525@stanford.edu |
880889547dde4dbef94e8f232b96df99bb26d088 | fef1c15bd0ffc2c7297e6bc9d030fcd86c478269 | /Python/Shorts/likes.py | 34644b8e9ddd4b82e5dd1ceaa411baa3ba7a9824 | [] | no_license | RicardoCuevasR/Codeacademy | 64fabba0d0bca8c353cffe1cab862b32a0b9b8ee | 4c2a3238e3bb66c70da5f255deb02ca0157c167c | refs/heads/master | 2021-05-23T14:36:51.705744 | 2020-04-13T11:33:45 | 2020-04-13T11:33:45 | 253,343,303 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 716 | py | def likes(names):
#your code here
if len(names) == 0:
print("no one likes this")
elif len(names) ==1:
print(names[0]+' likes this')
elif len(names) == 2:
print(names[0]+' and ' + names[1]+' like this')
elif len(names) == 3:
print(names[0]+', ' + names[1]+' and '+ names[2]+' like this')
else:
print(names[0]+', ' + names[1]+' and '+str(len(names)-2)+' others like this')
likes([]), 'no one likes this'
likes(['Peter']), 'Peter likes this'
likes(['Jacob', 'Alex']), 'Jacob and Alex like this'
likes(['Max', 'John', 'Mark']), 'Max, John and Mark like this'
likes(['Alex', 'Jacob', 'Mark', 'Max']), 'Alex, Jacob and 2 others like this' | [
"ricardocuevas@outlook.com"
] | ricardocuevas@outlook.com |
c3a7a2e33f162ea0ed680b8f444db06637fa2ce5 | bcd0062c83e451f6288026e5818d74167d2b7f60 | /1.basic/ver_6/run.py | 68ffd129d27b33b942fcfc4294872f0532813d68 | [] | no_license | mthrok/Step-By-Step-NN | 4aaa65db005feb453b2821ad7ca2b3d34d393ab2 | 6f8fbb0ef75641b7464d69f190f22ad45828ad82 | refs/heads/master | 2021-01-10T20:59:35.687197 | 2015-03-03T06:16:38 | 2015-03-03T06:16:38 | 31,582,272 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,578 | py | import subprocess, os, sys, argparse
def run(n_hids, lrs, mcs, n_epochs, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for n_hid in n_hids:
for lr in lrs:
for mc in mcs:
output = os.path.join(\
output_dir,
("n_hid_{}_lr_{}_nag_{}_mb_ReL.npz").format(n_hid, lr, mc))
cmd = ['python', 'back_propagation_v6.py',
'-hu', str(n_hid),
'-l', str(lr),
'-m', str(mc),
'-e', str(n_epochs),
'-i', output,
'-o', output]
print(*cmd)
with subprocess.Popen(cmd) as p:
try:
p.wait(timeout=None)
except KeyboardInterrupt:
sys.exit(0)
if __name__=="__main__":
# Parse command line arguments
parser = argparse.ArgumentParser(\
description='Run backpropagation for the given hyperparameters.')
parser.add_argument('-hu', '--hidden_units', type=int, nargs='+',
default=[10, 20, 30], help='The numbers of hidden units')
parser.add_argument('-l', '--learning_rates', type=float, nargs='+',
default=[0.1, 0.3, 0.6], help='Learning rates')
parser.add_argument('-e', '--epochs', type=int,
default=50, help='The number of maximum epoch')
parser.add_argument('-m', '--momentum_coefficients', type=float, nargs='+',
default=[0.3, 0.6, 0.9], help='Momentum coefficients')
#parser.add_argument('-b', '--batches', type=int, default=10,
# help='The number of mini-batches')
parser.add_argument('-o', '--output-dir', type=str,
default="./result")
parser.add_argument('-p', '--parameter-sets', type=float, nargs=3, action='append',
help='The set of parameters (n_hid, lr, mc)')
args = parser.parse_args()
if args.parameter_sets:
for p_set in args.parameter_sets:
run(n_hids = [int(p_set[0])],
lrs = [p_set[1]],
mcs = [p_set[2]],
n_epochs = args.epochs,
output_dir = args.output_dir)
else:
run(n_hids = args.hidden_units,
lrs = args.learning_rates,
mcs = args.momentum_coefficients,
n_epochs = args.epochs,
output_dir = args.output_dir)
| [
"mthrok@gmail.com"
] | mthrok@gmail.com |
458f4cacbc7324d341bf4de07eefea4e4a38cf54 | 2f442a2761e81977dc72c947120de7b89ea4a9fb | /venv/lib/python3.6/_collections_abc.py | 58968374e253bdff890143af1518e7f3b165322a | [] | no_license | 7552-2C-2018/App-Server | 00440e72fc4f592b6ad8385f355d1194b50c7498 | bc5fff691339064fde4711745e0bec55ae4a116c | refs/heads/master | 2022-12-13T13:00:22.877709 | 2018-12-13T19:23:41 | 2018-12-13T19:23:41 | 146,044,186 | 0 | 0 | null | 2022-11-22T00:22:15 | 2018-08-24T22:07:59 | Python | UTF-8 | Python | false | false | 57 | py | /home/charlie/anaconda3/lib/python3.6/_collections_abc.py | [
"carlosfurnari@gmail.com"
] | carlosfurnari@gmail.com |
968c93a69a7de0760697499a3d94302bbb76ff91 | d775ae87eac01b1b7dcdca2cd1b4e9d699d70a97 | /arithmetic_arranger.py | b11d2d34ce558742c043771ab78c1886be4b9c7e | [] | no_license | pkro/fcc_arithmetic_arranger | 144f0bd2dde0c7beb8373647304f50b4ffd79023 | 667c6f268f1f95f0f1b69dcba2cc49a8267989d7 | refs/heads/main | 2023-01-30T04:02:13.324311 | 2020-12-13T15:13:08 | 2020-12-13T15:13:08 | 320,610,878 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,733 | py | import re
not_numeric = re.compile(r"[^\d]")
ops = {'+': (lambda op1, op2: int(op1) + int(op2)),
'-': (lambda op1, op2: int(op1) - int(op2))}
def pad_left(str, padlength=4):
padding = " "*padlength
return f"{padding}{str}"
def arithmetic_arranger(problems, solve=False):
if len(problems) > 5:
return "Error: Too many problems."
arranged_problems = ""
row1, row2, row3, solution_row = "", "", "", ""
allowed_ops = ops.keys()
for idx, problem in enumerate(problems):
(op1, operator, op2) = problem.split(" ")
# Error handling
if not_numeric.search(op1) or not_numeric.search(op2):
return "Error: Numbers must only contain digits."
if len(op1) > 4 or len(op2) > 4:
return "Error: Numbers cannot be more than four digits."
if operator not in allowed_ops:
return "Error: Operator must be '" + ("' or '".join(allowed_ops)) + "'."
longest_op = max(len(op1), len(op2))
pad = ((lambda s: s) if idx == 0 else (lambda s: pad_left(s)))
r2_item = operator + (" " * (longest_op+1-len(op2))) + op2
row2 = row2 + pad(r2_item)
r3_item = "-" * len(r2_item)
row3 = row3 + pad(r3_item)
r1_item = pad_left(op1, len(r3_item)-len(op1))
row1 = row1 + pad(r1_item)
# optional solve
if solve:
operation_func = ops[operator]
result = str(operation_func(op1, op2))
result = pad_left(result, len(r3_item)-len(result))
solution_row = solution_row + pad(result)
arranged_problems = [row1, row2, row3]
if solve:
arranged_problems.append(solution_row)
return "\n".join(arranged_problems)
| [
"pkrombach@web.de"
] | pkrombach@web.de |
73212a3bbdf86b3e69b9610f8daa544a8d040b45 | 708c3055bf23103d30b26ca43348570aa9ba8542 | /app/request.py | 81c16ec56f7e69b256dbc78a1f61535700875fef | [
"MIT"
] | permissive | Caiseyann/blog | 10774fef95e48cf03166d871d4ac09e259da1ff8 | 879864304db099e3338e171d493271dc0d439c37 | refs/heads/master | 2022-12-25T14:27:28.460317 | 2020-09-30T17:31:20 | 2020-09-30T17:31:20 | 298,567,883 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 630 | py | import os
import urllib.request,json
from .models import Quote
def get_quote():
'''
Function to get random quote
'''
quote_url = 'http://quotes.stormconsultancy.co.uk/random.json'
with urllib.request.urlopen(quote_url) as url:
quote_data = url.read()
quote_response = json.loads(quote_data)
quote_result = None
if quote_response:
author = quote_response.get('author')
quote = quote_response.get('quote')
permalink = quote_response.get('permalink')
quote_result = Quote(author, quote, permalink)
return quote_result | [
"caiseyann4@gmail.com"
] | caiseyann4@gmail.com |
c6adb1d9469a5adfe8a767e63e40fbd9ab028c03 | 8df1237388352d29c894403feaf91e800edef6bf | /Algorithms/141.linked-list-cycle/141.linked-list-cycle.py | 255c09e7e984294aef20caa856189c3b49b66f31 | [
"MIT"
] | permissive | GaLaPyPy/leetcode-solutions | 8cfa5d220516683c6e18ff35c74d84779975d725 | 40920d11c584504e805d103cdc6ef3f3774172b3 | refs/heads/master | 2023-06-19T22:28:58.956306 | 2021-07-19T00:20:56 | 2021-07-19T00:20:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 272 | py | class Solution:
def hasCycle(self, head: ListNode) -> bool:
fast = slow = head
while slow and fast and fast.next:
slow = slow.next
fast = fast.next
if slow is fast:
return True
return False
| [
"zoctopus@qq.com"
] | zoctopus@qq.com |
734222744177ba9b4b567229c0c42a7e3e563b04 | 71b11008ab0455dd9fd2c47107f8a27e08febb27 | /04、 python编程/day01/3-code/算数运算符.py | 449a9baa4ca2b1ae2202b8fdd1968229b4f48c70 | [] | no_license | zmh19941223/heimatest2021 | 49ce328f8ce763df0dd67ed1d26eb553fd9e7da4 | 3d2e9e3551a199bda9945df2b957a9bc70d78f64 | refs/heads/main | 2023-08-25T17:03:31.519976 | 2021-10-18T05:07:03 | 2021-10-18T05:07:03 | 418,348,201 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 112 | py | print(3 + 2)
print(3 - 2)
print(3 * 2)
print(3 / 2)
print(3 // 2)
print(3 % 2)
print(3 ** 2)
print("hello" * 3) | [
"1780858508@qq.com"
] | 1780858508@qq.com |
423102cb18157f992cd1e12aafb3efc36871ceed | f646239204a616065de400448c2b1e61df3e3b94 | /nlp/rnnlm/test_rnnml.py | 8a1812d4dcbe2c7686f5fd6bb3c94f53888ee1fc | [] | no_license | re53min/TOHO_AI | 4249e1241b79251821f896b0ee70e6b52a3902e6 | bb64be4d4d3dd38424ae5e79347df886c0b55e12 | refs/heads/master | 2021-01-17T13:38:47.330538 | 2018-08-08T08:35:36 | 2018-08-08T08:35:38 | 60,419,106 | 7 | 0 | null | null | null | null | UTF-8 | Python | false | false | 841 | py | #!/usr/bin/env python
# -*- coding: utf_8 -*-
import io
import sys
import pickle
from nlp.utils import mecab_wakati, make_vocab
import numpy as np
from chainer import Variable
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
def main():
with open('./dataset/train.pickle', 'rb') as f:
x = pickle.load(f)
vocab = make_vocab(x)
tmp_vocab = {}
for c, i in vocab.items():
tmp_vocab[i] = c
with open("./rnnlm_50.model", mode='rb') as f:
model = pickle.load(f)
word = 'EOS'
in_x = Variable(np.array([vocab.get(word, vocab['UNK'])], dtype='int32'))
for index in model.predict(in_x, max_length=1000):
if index == vocab['EOS']:
print()
else:
print(tmp_vocab[index], end='')
print()
if __name__ == "__main__":
main()
| [
"matsudate.wataru.hx@mynavi.jp"
] | matsudate.wataru.hx@mynavi.jp |
3ccdffbd3e03718f073ee961f759bee970250d79 | a7e31b0999da9808cc11b428c400edbc6d6cf593 | /poll/admin.py | 3f4106ecb9d827e098f8e9010192789e8a74a5e3 | [] | no_license | abhisekdas4/Django-Poll-App | 09edf3689fb854db8c0dc77dd2c98a7799dcdfc7 | 10da8a1cf72b8236edb8218773cf7c8d05749011 | refs/heads/main | 2023-04-01T02:31:24.065397 | 2021-04-06T12:54:16 | 2021-04-06T12:54:16 | 355,187,683 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 125 | py | from django.contrib import admin
from .models import PollModel
admin.site.register(PollModel)
# Register your models here.
| [
"abhisek.das4@gmail.com"
] | abhisek.das4@gmail.com |
912dedc16026588dc3a1a08a17457e32719be1ce | 1b8ec671c42b664e0b483d52ae398e2b3169ffe9 | /AES128/utils.py | d77019a85bb86cfd9c167e6ed9f365b6d6458672 | [] | no_license | vinguyen-cs-project/others | 0983bbc6847535e6accf2c1ef2c5883f9088156a | 6f90f9c2176964448bcc9e98484f96e2ee44c4b9 | refs/heads/master | 2023-07-24T05:23:08.030084 | 2021-08-23T21:18:21 | 2021-08-23T21:18:21 | 395,365,783 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,481 | py | import json
from base64 import b64encode, b64decode
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import time
import argparse
from random import randint
# This is the encryption function. It gets a plaintext a key and returns the ciphertext and nonce.
def encryptor_CTR(message, key, nonce=None):
cipher = AES.new(key, AES.MODE_CTR)
ct = cipher.encrypt(message)
nonce = cipher.nonce
return nonce, ct
# This is the decryption funtion. It gets a ciphertext, a nonce and a key and returns the plaintext.
def decryptor_CTR(ctxt, nonce, key):
try:
cipher = AES.new(key, AES.MODE_CTR, nonce=nonce)
pt = cipher.decrypt(ctxt)
return pt
except ValueError as KeyError:
return None
# Converting string to bytes.
def string_to_bytes(string_value):
return bytearray(string_value, encoding="utf-8")
def read_file(fn):
f = open(fn, "r")
value = f.read()
f.close()
return value
def read_bytes(fn):
f = open(fn, "rb")
value = f.read()
f.close()
return value
def write_file(fn, value):
f = open(fn, "w")
f.write(value)
f.close()
def write_bytes(fn, value):
f = open(fn, "wb")
f.write(value)
f.close()
def bitstring_to_bytes(s):
v = int(s, 2)
b = bytearray()
while v:
b.append(v & 0xFF)
v >>= 8
return bytes(b[::-1])
# convert binary to hex
def bit_to_hex(s):
v = int(s, 2)
h = hex(v)
return h
| [
"vinguyen6@my.unt.edu"
] | vinguyen6@my.unt.edu |
b545b08f626b6f368b161bd1c276b2f051c6ba2a | 7724f908b73b446494503e58753797c79ea3b301 | /dlclouds/util.py | 221a9480322c9344d9337a60fd8db8e0284b4730 | [
"Apache-2.0"
] | permissive | constantineg1/dlclouds | 19500766fcff9dc85d1d5e4274e6b7be95f1a77b | d341b7387d3bc1a61de6df190480ae3550912b4f | refs/heads/master | 2021-01-12T11:50:36.562456 | 2016-11-27T19:37:21 | 2016-11-27T19:37:21 | 70,155,545 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,076 | py | import fnmatch
import json
import os
import requests
import shutil
import stat
def copytree(src, dst, symlinks=False, ignore=None):
"""
This is a contributed re-implementation of 'copytree' that
should work with the exact same behavior on multiple platforms.
"""
if not os.path.exists(dst):
os.makedirs(dst)
shutil.copystat(src, dst)
lst = os.listdir(src)
if ignore:
excl = ignore(src, lst)
lst = [x for x in lst if x not in excl]
for item in lst:
s = os.path.join(src, item)
d = os.path.join(dst, item)
if symlinks and os.path.islink(s): # pragma: no cover
if os.path.lexists(d):
os.remove(d)
os.symlink(os.readlink(s), d)
try:
st = os.lstat(s)
mode = stat.S_IMODE(st.st_mode)
os.lchmod(d, mode)
except:
pass # lchmod not available
elif os.path.isdir(s):
copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s, d) | [
"constantine.gurnov@gmail.com"
] | constantine.gurnov@gmail.com |
c3d115ed26b5945d42e7446b23761ab132d9b4cc | 031c3088de602e4254c8050a1f354abc66bf512e | /MachineLearning/10lackingdata_encode.py | 6dc6a9f11d1c5249ffed4371e94d081fad782708 | [] | no_license | monado3/HAIT | 8652cad9f0ee948d3313d05ee14c26aee4c573c6 | ff7283891e6e7e73286ddf92622d1600a3053df4 | refs/heads/master | 2021-03-30T23:49:51.964063 | 2018-10-23T03:01:51 | 2018-10-23T03:01:51 | 124,752,616 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,077 | py | # In[]
import numpy as np
import pandas as pd
from numpy import nan
# In[]
df = pd.DataFrame({'DATE': [20170801, 20170801, 20170802, 20170802, 20170803, 20170803, 20170803, 20170805, 20170805, 20170805],
'NECK': [41, nan, 38, 46, nan, 37, nan, 38, nan, 42],
'BODY': [84, 92, nan, 90, nan, 64, 78, 74, 82, 86],
'SIZE': ['L', 'XL', 'L', 'XL', 'M', 'S', 'M', 'L', 'L', 'XL'],
'COLOR': ['BL', 'RD', 'Y', 'GR', 'GR', 'RD', 'BL', 'Y', 'BL', 'GR'],
'class': ['A', 'C', 'B', 'B', 'C', 'A', 'A', 'A', 'C', 'C']},
columns=['DATE', 'NECK', 'BODY', 'SIZE', 'COLOR', 'class'])
df
df.isnull().sum()
df.dropna()
df.dropna(subset=['BODY'])
df.dropna(thresh=5)
df.fillna(df.mean())
df.fillna(0)
ip = df.interpolate(method='linear')
ip
size_mapping={'S':1,'M':2,'L':3,'XL':4}
df['SIZE']=df['SIZE'].map(size_mapping)
df
pd.get_dummies(df['COLOR'])
class_mapping = {'A':0,'B':1,'C':2}
class_mapping
df['class']=df['class'].map(class_mapping)
df
| [
"monade.kk@gmail.com"
] | monade.kk@gmail.com |
be805a383b87ec9134e44f3e000e0493de9606f8 | dbb6d52439b43fc658a50f2d7203dca7b7db1148 | /final_project/helper.py | 40a9b50a05d3a61634c4313d2db58702065f726c | [] | no_license | yhbyhb/data_analyst_nanodegree_p4 | c10ed8b0916b24f4cf81e44512ec37dbf59f53f0 | 9291b422ca3dbc240aa5aef3fed22c8070e60f9b | refs/heads/master | 2016-08-08T19:33:05.071681 | 2015-11-14T05:20:17 | 2015-11-14T05:20:17 | 45,790,363 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,298 | py | #!/usr/bin/python
'''
helper functions for identifying person of interest
'''
import sys
import pickle
sys.path.append("../tools/")
from feature_format import featureFormat, targetFeatureSplit
import numpy as np
from sklearn.feature_selection import SelectKBest
from sklearn.cross_validation import StratifiedShuffleSplit
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import *
def count_valid_values(data_dict):
'''
counts the number of valid values for each feature
returns dictionary that has key : each feature, value : valid count
'''
valid_counts = {}
for record in data_dict:
person = data_dict[record]
for feature in person:
if person[feature] != 'NaN':
try:
valid_counts[feature] += 1
except Exception, e:
valid_counts[feature] = 1
return valid_counts
def get_k_best_features(data_dict, features_list, k):
'''
Using SelectKBest, find k best features.
returns list of features and list of scores
'''
data = featureFormat(data_dict, features_list)
labels, features = targetFeatureSplit(data)
k_best = SelectKBest(k=k)
k_best.fit(features, labels)
unsorted_pair_list = zip(features_list[1:], k_best.scores_)
# print unsorted_dict_list
sorted_pair_list = sorted(unsorted_pair_list, key=lambda x: x[1], reverse=True)
# print sorted_dict_list
k_best_features = [pair[0] for pair in sorted_pair_list]
k_best_scores = [pair[1] for pair in sorted_pair_list]
return k_best_features[:k], k_best_scores[:k]
def remove_outliers(data_dict, outliers):
'''
remove a list of outliers from data_dict
'''
for outlier in outliers:
data_dict.pop(outlier, None)
def add_custum_features(data_dict, features_list):
'''
Add custom features to data_dict.
total_income : salary + bonus + exercised_stock_options + total_stock_value
ratio_poi_email : (from_poi_to_this_person + from_this_person_to_poi) / (to_messages + from_messages)
'''
mail_features = ['from_poi_to_this_person', 'from_this_person_to_poi',
'to_messages', 'from_messages']
total_income_features = ['salary', 'bonus',
'exercised_stock_options', 'total_stock_value']
for key in data_dict:
has_nan = False
record = data_dict[key]
total_income = 0
for feature in total_income_features:
if record[feature] != 'NaN':
total_income += record[feature]
record['total_income'] = total_income
for feature in mail_features:
if record[feature] == 'NaN':
has_nan = True
if has_nan == False:
record['ratio_poi_email'] = \
(record['from_poi_to_this_person'] + record['from_this_person_to_poi']) / \
float((record['to_messages'] + record['from_messages']))
else:
record['ratio_poi_email'] = 'NaN'
features_list += ['total_income', 'ratio_poi_email']
def find_best_parameters(pipeline, parameters, score_func, dataset,
feature_list, test_size=0.2, n_iter=10):
"""
find best parameter by using GridSearchCV with given scoring function.
returns GridSearchCV object that has best parameters.
"""
data = featureFormat(dataset, feature_list)
labels, features = targetFeatureSplit(data)
cv = StratifiedShuffleSplit(labels, 1, test_size=test_size, random_state = 42)
for train_idx, test_idx in cv:
features_train = []
features_test = []
labels_train = []
labels_test = []
for ii in train_idx:
features_train.append( features[ii] )
labels_train.append( labels[ii] )
for jj in test_idx:
features_test.append( features[jj] )
labels_test.append( labels[jj] )
sss = StratifiedShuffleSplit(labels_train, n_iter=n_iter , test_size=test_size, random_state=42)
clf = GridSearchCV(pipeline, parameters, scoring=score_func, cv=sss, n_jobs=-1)
clf.fit(features_train, labels_train)
return clf
def validation(clf, dataset, feature_list, test_size=0.2, n_iter=1000):
'''
validate given classifier with using stratifie shuffle split cross validation.
returns average precision and recall
'''
data = featureFormat(dataset, feature_list)
labels, features = targetFeatureSplit(data)
precision = []
recall = []
cv = StratifiedShuffleSplit(labels, n_iter, test_size=test_size, random_state = 42)
for train_idx, test_idx in cv:
features_train = []
features_test = []
labels_train = []
labels_test = []
for ii in train_idx:
features_train.append( features[ii] )
labels_train.append( labels[ii] )
for jj in test_idx:
features_test.append( features[jj] )
labels_test.append( labels[jj] )
clf.fit(features_train, labels_train)
predictions = clf.predict(features_test)
precision.append(precision_score(labels_test, predictions))
recall.append(recall_score(labels_test, predictions))
return np.mean(precision), np.mean(recall)
| [
"hanbyul.yang@gmail.com"
] | hanbyul.yang@gmail.com |
75064e292e05382e99850d607d597cfb30bde890 | 4617a711ecd6492f542323de88fdb01927c59480 | /studentregformpro/studentregformpro/urls.py | d3e3c2c328b81a1e9a449907b92ece3386f9add2 | [] | no_license | saikiranshiva/RemoteRepository3 | 309093a48533f04f81e0efbc64a5875744ebdbd5 | e13dbc96a7d358a01cf8fc6fefcd906a5c639649 | refs/heads/main | 2023-02-15T21:52:01.256185 | 2021-01-04T10:46:03 | 2021-01-04T10:46:03 | 326,652,141 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 835 | py | """studentregformpro URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.conf.urls import url
from studentregformapp import views
urlpatterns = [
url('admin/', admin.site.urls),
url(r'^$',views.studentreg_view)
]
| [
"raju.alakuntla1998@gmail.com"
] | raju.alakuntla1998@gmail.com |
fca9851130cffe0346df049170c360c93e6c1e25 | d309e821ed80a17cc1636b88115e029f8439d290 | /src/00_sly_tutor.py | 468fae52c8a0fdd32f8bc974c264f0b820a48a40 | [] | no_license | crhan/python_talk_2020 | 7e3ac026b0a1fe162d04577490b8ffff9a8a69d7 | 0d12bf83dac76ff8240c56abac434710c5b1740a | refs/heads/master | 2022-04-11T13:58:44.391259 | 2020-03-29T03:39:21 | 2020-03-29T03:39:21 | 250,255,584 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,684 | py | #%%
from sly import Lexer, Parser
class CalcLexer(Lexer):
tokens = { NAME, NUMBER }
ignore = ' \t'
literals = { '=', '+', '-', '*', '/', '(', ')' }
# Tokens
NAME = r'[a-zA-Z_][a-zA-Z0-9_]*'
@_(r'\d+')
def NUMBER(self, t):
t.value = int(t.value)
return t
@_(r'\n+')
def newline(self, t):
self.lineno += t.value.count('\n')
def error(self, t):
print("Illegal character '%s'" % t.value[0])
self.index += 1
class CalcParser(Parser):
tokens = CalcLexer.tokens
precedence = (
('left', '+', '-'),
('left', '*', '/'),
('right', 'UMINUS'),
)
def __init__(self):
self.names = { }
@_('NAME "=" expr')
def statement(self, p):
self.names[p.NAME] = p.expr
@_('expr')
def statement(self, p):
print(p.expr)
@_('expr "+" expr')
def expr(self, p):
return p.expr0 + p.expr1
@_('expr "-" expr')
def expr(self, p):
return p.expr0 - p.expr1
@_('expr "*" expr')
def expr(self, p):
return p.expr0 * p.expr1
@_('expr "/" expr')
def expr(self, p):
return p.expr0 / p.expr1
@_('"-" expr %prec UMINUS')
def expr(self, p):
return -p.expr
@_('"(" expr ")"')
def expr(self, p):
return p.expr
@_('NUMBER')
def expr(self, p):
return p.NUMBER
@_('NAME')
def expr(self, p):
try:
return self.names[p.NAME]
except LookupError:
print("Undefined name '%s'" % p.NAME)
return 0
#%%
lexer = CalcLexer()
parser = CalcParser()
parser.parse(lexer.tokenize("3+2*2"))
# %%
| [
"crhan123@gmail.com"
] | crhan123@gmail.com |
a29a8dcbda3a7cb7ffa0c956135c5200a9c3d9cf | b744dfea2f4fd754a0933d3c31992484a336ef00 | /canny_edge_detection_in_opencv.py | 93fcce82744dd0bfc97ce72180bbdf9e7213232d | [] | no_license | aman2575/Canny_edge_detection | 3babb57c0c7f5d0c63f78cc67922f453d9d984ce | 745b81261e236125ec9dd4230887691c40c1a4fe | refs/heads/main | 2023-06-25T18:29:04.679132 | 2021-07-31T06:47:52 | 2021-07-31T06:47:52 | 391,277,423 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 388 | py | import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('image3.jpg', 0)
canny = cv2.Canny(img, 100, 200) #Threshold1= 100 and Threshold2 =200
titles = ['image', 'canny']
images = [img, canny]
for i in range(2):
plt.subplot(1, 2, i+1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show() | [
"noreply@github.com"
] | noreply@github.com |
a321cdabdb97ccc86dbc1a71e6e74201cf0a7bc8 | 6bec22a47a19f933b73607d6b406006131364a20 | /users/migrations/0001_initial.py | 7869fe656b62c1aa52196479d5c35cb321e305aa | [] | no_license | codertjay/LMS | 9ec2985d3c62e9c662aa9f8d5532da5d9dd60070 | 33c34ff1f8104b7ed4a8bf389ed24af96394b280 | refs/heads/master | 2023-09-03T12:56:18.535097 | 2021-05-27T20:48:19 | 2021-05-27T20:48:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,067 | py | # Generated by Django 3.1.5 on 2021-01-29 10:22
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),
('courses', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Contact',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('contact_name', models.CharField(max_length=50)),
('contact_email', models.EmailField(max_length=50)),
('contact_subject', models.CharField(max_length=50)),
('contact_message', models.TextField()),
],
),
migrations.CreateModel(
name='Profile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('user_type', models.CharField(choices=[('Student', 'Student'), ('Instructor', 'Instructor')], default='Student', max_length=20)),
('profile_pics', models.ImageField(default='profile_pics/profile.jpg', upload_to='profile_pics')),
('twitter_url', models.URLField(blank=True, null=True)),
('instagram_url', models.URLField(blank=True, null=True)),
('github_url', models.URLField(blank=True, null=True)),
('linkedin_url', models.URLField(blank=True, null=True)),
('timestamp', models.DateTimeField(auto_now_add=True)),
('about', models.TextField()),
('status', models.CharField(max_length=200)),
('applied_courses', models.ManyToManyField(blank=True, related_name='applied_courses', to='courses.Course')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"codertjay@gmail.com"
] | codertjay@gmail.com |
b7b7b5f1230aa89fc419396b380bb456bbb59f8a | 7ead627866c85cf0c28ca8cd062b695c4ab849c3 | /heatmapping_script/heatmapper.py | 46ca451be402d32d5bba4a42dfe9fca0c79cfc5b | [] | no_license | dylanuys/MoocVisualization | a9e29bda067eef9600a9b0da75d70d5de225df98 | 79d32a732a70fd5e4443efc9da349e4086372bfd | refs/heads/master | 2020-04-08T17:09:51.480765 | 2018-12-04T19:40:42 | 2018-12-04T19:40:42 | 159,554,092 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,838 | py | from heatmappy import Heatmapper
from heatmappy import VideoHeatmapper
from PIL import Image
import numpy as np
import argparse
import os
import sys
import csv
''
class ClickMapper():
def __init__(self, video_in_path, data_path, video_out_path, test_mode=False):
'''
Class to add a heatmap to a video.
Parameters:
video_in_path (str) -- Filepath to video to add the heatmap to
video_out_path (str) -- Filepath to write heatmapped video to
data_path (str) -- Filepath to csv file containing coordinates
and times at which to add points for the
heatmap. Each line of data in the file should
be formatted (x, y, milliseconds, count). The
first three elements dictate where the point
will be added in the video, and count
specifies how many random augmented points
to add around that location and time.
'''
self.video_path = video_in_path
self.data_path = data_path
self.out_path = video_out_path
self.test_mode = test_mode
# to write to video
self.heat_points = []
# to export distribution points without missing values
self.distributions = []
self.load_data()
def load_data(self):
'''
Loads the data found in self.data_path into self.heat_points. A line in
the data file looks like this: (x,y,millisecond,count). Each line is
passed to self.add_point_distribution, which creates a gaussian
distribution of "count" many points. For x and y, the default standard
deviation used is 15. For the milliseconds, the default is 1000. All
of these defaults can be changed by setting the optional fields in the
data file. See self.add_point_distribution for details.
Takes no arguments and returns nothing, populates self.heat_points.
'''
def is_int(s):
try:
int(s)
return True
except ValueError:
return False
with open(self.data_path, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
next(reader) # header
for l in reader:
bad_format = np.any([e != '' and not is_int(e) for e in l])
if len(l) < 4: continue
elif bad_format: continue
self.add_point_distribution(l)
def add_point_distribution(self, line):
'''
Creates gaussian distributions using values from the line argument.
Line contains (x,y,ms,count,[duration,x_std_dev,y_std_dev]), where
the last three fields are optional. A distribution is created for each
of x, y and ms, using count to define the number of samples.
'''
x_std = int(line[4]) if len(line) > 4 and len(line[4]) > 0 else 15
y_std = int(line[5]) if len(line) > 5 and len(line[5]) > 0 else 15
ms_std = int(line[6]) if len(line) > 6 and len(line[6]) > 0 else 1500
# convert to ints after using string properties above
line = [int(e) if len(e) > 0 else e for e in line]
x, y, ms, num_points = line[0], line[1], line[2], line[3]
if self.test_mode: num_points //= 10
x_gaus = np.random.normal(x, x_std, num_points)
y_gaus = np.random.normal(y, y_std, num_points)
ms_gaus = np.random.normal(ms, ms_std, num_points)
distr = (line[0], line[1], line[2], ms_std, x_std, y_std)
self.distributions.append(distr)
for i in range(num_points):
point = (x_gaus[i], y_gaus[i], ms_gaus[i])
self.heat_points.append(point)
def apply_heatmap(self):
'''
Uses the heatmappy library to add points from self.heat_points to the
video in self.video_path. Takes no args and returns nothing, but creates
a video with an overlaid heatmap at self.out_path.
'''
header = ['x','y','ms','x_std','y_std','ms_std']
self.export_data('distributions.csv', self.distributions, header)
self.export_data('samples.csv', self.heat_points, header[:3])
img_hm = Heatmapper()
video_hm = VideoHeatmapper(img_hm)
video_out = video_hm.heatmap_on_video_path(video_path=self.video_path,
points=self.heat_points)
video_out.write_videofile(self.out_path, bitrate="5000k", fps=24)
def export_data(self, out_path, data, header=None, verbose=True):
'''
Writes a list of data points to a file. This is called to write
the fully populated distributions and their corresponding samples
to their own files for later reference.
Parameters:
data -- List of lists or tuples to write to csv file
out_path -- filepath to write to
'''
if verbose: print('Exporting data to', out_path,'...',)
with open(out_path, 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
if header is not None: writer.writerow(header)
for point in data:
p = [p for p in point] # in case of tuple
writer.writerow(p)
if verbose: print('done.\n' + '-'*50)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--video', metavar='v', default='kmeans.mp4',
help='Path to input video file (default: kmeans.mp4)',
dest='video')
parser.add_argument('--data', metavar='d', default='data.csv',
help='Path to data file (default: data.csv)',
dest='data')
parser.add_argument('--mode', metavar='m', default='prod',
help='Set to "test" to use less points and execute '\
'faster (default: prod)',
dest='mode')
args = parser.parse_args()
video_path = args.video
data_path = args.data
test_mode = True if args.mode == 'test' else False
out_path = video_path[:video_path.index('.')] + '_heatmapped.mp4'
print('-'*50)
print('Video in: {}\nData file: {}\nOutput file:{}'.format(video_path,
data_path,
out_path))
print('-'*50)
heatmapper = ClickMapper(video_path, data_path, out_path, test_mode)
heatmapper.apply_heatmap()
| [
"duys@ucsd.edu"
] | duys@ucsd.edu |
58e3f57af71f1bca86917ea9775c7ebf04546a90 | a34256f1590ccac077bb7c29601cf28b8bcc7fb1 | /portfolio/views.py | 872ae7f78e8700d9491fcc90dee6349083a825a0 | [] | no_license | silverwing2003/django3-personal-portfolio | 7ba28b678875ba24ca0efab5349bfd00a5b6fab7 | fff4a06e4d1a9c00d8c79c8545c093d51e29d5c7 | refs/heads/master | 2022-12-16T17:17:42.700560 | 2020-04-04T20:12:29 | 2020-04-04T20:12:29 | 252,366,277 | 0 | 0 | null | 2022-12-08T03:59:10 | 2020-04-02T05:44:37 | Python | UTF-8 | Python | false | false | 248 | py | from django.shortcuts import render
from .models import Project
# Create your views here.
def home(request):
projects = Project.objects.all() #database project objects
return render(request, 'portfolio/home.html', {'projects':projects})
| [
"nsuguitan@gmail.com"
] | nsuguitan@gmail.com |
5b47d39363b966b6fd8208f0f5a184dedf934ca4 | c9642233f1de71f1a61ae28c695c2d9228825156 | /echecs_espoir/service/mahjong/models/hutype/two/siguiyi.py | 63d95ac314dad7a3b187dc3c09ab0befe8eacee5 | [
"AFL-3.0"
] | permissive | obespoir/echecs | d8314cffa85c8dce316d40e3e713615e9b237648 | e4bb8be1d360b6c568725aee4dfe4c037a855a49 | refs/heads/master | 2022-12-11T04:04:40.021535 | 2020-03-29T06:58:25 | 2020-03-29T06:58:25 | 249,185,889 | 16 | 9 | null | null | null | null | UTF-8 | Python | false | false | 2,763 | py | # coding=utf-8
import time
from service.mahjong.models.hutype.basetype import BaseType
from service.mahjong.constants.carddefine import CardType, CARD_SIZE
from service.mahjong.models.card.hand_card import HandCard
from service.mahjong.models.card.card import Card
from service.mahjong.models.utils.cardanalyse import CardAnalyse
class SiGuiYi(BaseType):
"""
4) 四归一:胡牌时,牌里有4张相同的牌归于一家的顺、刻子、对、将牌中(不包括杠牌) 。
"""
def __init__(self):
super(SiGuiYi, self).__init__()
def is_this_type(self, hand_card, card_analyse):
used_card_type = [CardType.WAN] # 此游戏中使用的花色
union_card = hand_card.union_card_info
gang_lst = []
gang_lst.extend(hand_card.dian_gang_card_vals)
gang_lst.extend(hand_card.bu_gang_card_vals)
gang_lst.extend(hand_card.an_gang_card_vals)
ret = [] # 手里有4张的牌集
for i, count in enumerate(union_card[CardType.WAN]):
if i == 0 and count < 4:
return False
if count == 4 and Card.cal_card_val(CardType.WAN, i) not in gang_lst:
ret.append(Card.cal_card_val(CardType.WAN, i))
if not ret:
return False
gang_lst = self.get_gang_lst(hand_card)
for i in ret:
if i in gang_lst:
return False
return True
def get_gang_lst(self, hand_card):
ret = []
for i in hand_card.dian_gang_card_vals: # 点杠的牌
ret.append(i[0])
for i in hand_card.bu_gang_card_vals: # 补杠的牌
ret.append(i[0])
for i in hand_card.an_gang_card_vals: # 暗杠的牌
ret.append(i[0])
return ret
if __name__ == "__main__":
pass
card_analyse = CardAnalyse()
hand_card = HandCard(0)
# hand_card.hand_card_info = {
# 1: [9, 1, 1, 1, 1, 1, 1, 1, 1, 1], # 万
# 2: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 条
# 3: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 饼
# 4: [2, 2, 0, 0, 0], # 风
# 5: [3, 3, 0, 0], # 箭
# }
hand_card.hand_card_info = {
1: [9, 1, 1, 4, 1, 1, 1, 1, 1, 1], # 万
2: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 条
3: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 饼
4: [2, 2, 0, 0, 0], # 风
5: [0, 0, 0, 0], # 箭
}
hand_card.handle_hand_card_for_settle_show()
hand_card.union_hand_card()
print("hand_card =", hand_card.hand_card_vals)
test_type = SiGuiYi()
start_time = time.time()
print(test_type.is_this_type(hand_card, card_analyse))
print("time = ", time.time() - start_time) | [
"jamonhe1990@gmail.com"
] | jamonhe1990@gmail.com |
66fd9ab589205e9cc3c65373bda895c4bf9ed452 | 9858acce5d06c2a8286837051d115055a519d916 | /api/migrations/0001_initial.py | b5cbeeecb70da7fa35c87b9c5cb04b86579bf58d | [] | no_license | DUGASANI-ROJA/hotel | a553e71b3325aaa50273bb0a5fb119b7192bdaa4 | 3e741f79de202ee2a7e2c378ca93026caa5b664a | refs/heads/master | 2022-12-22T09:56:34.575681 | 2020-09-13T16:19:38 | 2020-09-13T16:19:38 | 295,184,914 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,622 | py | # Generated by Django 2.2 on 2020-09-13 12:18
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),
]
operations = [
migrations.CreateModel(
name='Customer',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50, unique=True)),
('mobile_number', models.CharField(max_length=10)),
('check_in', models.DateField()),
('check_out', models.DateField()),
('no_of_rooms', models.IntegerField(default=1)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Room',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('occupancy', models.CharField(choices=[('occupied', 'occupied'), ('not occupied', 'not occupied')], max_length=20)),
('room_number', models.CharField(max_length=3)),
('room_type', models.CharField(max_length=10)),
('customer', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='api.Customer')),
],
),
]
| [
"rojareddyrosee@gmail.com"
] | rojareddyrosee@gmail.com |
f4f3c5018852e7326cf49de99a2a20de72afe0c3 | 53bcd58b84ee7a6ec944d288a16bf54a843d045e | /setup.py | 61551d0183e374a3a4086a3d4a3e87a8bd4c3099 | [
"MIT"
] | permissive | ssi-dk/dash-scroll-up | 7746831e129e80ffe41f8c05375863d838398c1d | 297554a842592335b244b23a5392c32b99bace0b | refs/heads/master | 2022-12-09T08:22:46.810866 | 2019-12-06T07:53:33 | 2019-12-06T07:53:33 | 139,981,313 | 1 | 0 | MIT | 2022-12-08T06:40:21 | 2018-07-06T12:21:13 | Python | UTF-8 | Python | false | false | 362 | py | from setuptools import setup
exec (open('dash_scroll_up/version.py').read())
setup(
name='dash_scroll_up',
version=__version__,
author='martinbaste',
packages=['dash_scroll_up'],
include_package_data=True,
license='MIT',
description='Dash component to add custom button to scroll to the top of the page.',
install_requires=[]
)
| [
"martinbaste@gmail.com"
] | martinbaste@gmail.com |
a2415b771f03b5097657f3584941194ed780f778 | 6f1609aac9e32f19975bcd50b4cff73abeab62de | /uygulama05.py | 340316b37b712b9f195e9fc2c84004e5484dfa57 | [] | no_license | meryemozdogan/Bby162 | 26c62411c4ef33544bcdd01f7a3307f42274b6da | 3c8659272c68eb73eed495f4f9cab3061210e242 | refs/heads/master | 2021-09-14T16:55:39.778030 | 2018-05-16T08:29:33 | 2018-05-16T08:29:33 | 123,169,967 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 771 | py | print("Adam Asmaca Oyununa Hoşgeldin!\nToplam 5 hakkın var, bol şans.\n ")
import random
kalanHak = 5
i = 0
kelime = random.choice(['zeus','afrodit','athena','poseidon','hades'])
harfHavuzu = []
for islem in kelime:
harfHavuzu.append("_")
print(harfHavuzu)
while kalanHak > 0:
yazılanHarf = input("Bir harf giriniz:").lower()
if yazılanHarf in kelime:
for kontrol in kelime:
if kelime[i] == yazılanHarf:
harfHavuzu[i] = yazılanHarf
i+=1
print(harfHavuzu)
i=0
else:
i=0
kalanHak -= 1
print("Kalan can " + str(kalanHak) )
if kalanHak == 0:
print('Öldün çık. Doğru kelime "{}" idi.\n'.format(kelime))
break
| [
"noreply@github.com"
] | noreply@github.com |
19633deb63a2ad3fc7c6c4cf27556287f82554d9 | ce705c1d18ecae07f4ecd4a2684301333560fbf6 | /model/efficientnet.py | 8050a446143135a3fcfbc9e1493bb0aacbcd4934 | [] | no_license | tmlr-group/dsnet | 2bf6ef2887a9c90803edc1a639385413965fa13c | 3b6059a86c5c639dc3fdd79bed6b5edebc2c6b3b | refs/heads/main | 2023-07-01T03:35:25.580396 | 2021-08-01T02:23:53 | 2021-08-01T02:23:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,566 | py | import math
import mlconfig
import torch
from torch import nn
from collections import OrderedDict
import numpy as np
# from utils import count_parameters
# from .utils import load_state_dict_from_url
try:
from torch.hub import load_state_dict_from_url
except ImportError:
from torch.utils.model_zoo import load_url as load_state_dict_from_url
model_urls = {
'efficientnet_b0': 'https://www.dropbox.com/s/9wigibun8n260qm/efficientnet-b0-4cfa50.pth?dl=1',
'efficientnet_b1': 'https://www.dropbox.com/s/6745ear79b1ltkh/efficientnet-b1-ef6aa7.pth?dl=1',
'efficientnet_b2': 'https://www.dropbox.com/s/0dhtv1t5wkjg0iy/efficientnet-b2-7c98aa.pth?dl=1',
'efficientnet_b3': 'https://www.dropbox.com/s/5uqok5gd33fom5p/efficientnet-b3-bdc7f4.pth?dl=1',
'efficientnet_b4': 'https://www.dropbox.com/s/y2nqt750lixs8kc/efficientnet-b4-3e4967.pth?dl=1',
'efficientnet_b5': 'https://www.dropbox.com/s/qxonlu3q02v9i47/efficientnet-b5-4c7978.pth?dl=1',
'efficientnet_b6': None,
'efficientnet_b7': None,
}
params = {
'efficientnet_b0': (1.0, 1.0, 224, 0.2),
'efficientnet_b1': (1.0, 1.1, 240, 0.2),
'efficientnet_b2': (1.1, 1.2, 260, 0.3),
'efficientnet_b3': (1.2, 1.4, 300, 0.3),
'efficientnet_b4': (1.4, 1.8, 380, 0.4),
'efficientnet_b5': (1.6, 2.2, 456, 0.4),
'efficientnet_b6': (1.8, 2.6, 528, 0.5),
'efficientnet_b7': (2.0, 3.1, 600, 0.5),
}
# class Swish(nn.Module):
# def __init__(self, *args, **kwargs):
# super(Swish, self).__init__()
# def forward(self, x):
# return x * torch.sigmoid(x)
# A memory-efficient implementation of Swish function
class SwishImplementation(torch.autograd.Function):
@staticmethod
def forward(ctx, i):
result = i * torch.sigmoid(i)
ctx.save_for_backward(i)
return result
@staticmethod
def backward(ctx, grad_output):
i = ctx.saved_tensors[0]
sigmoid_i = torch.sigmoid(i)
return grad_output * (sigmoid_i * (1 + i * (1 - sigmoid_i)))
class Swish(nn.Module):
def forward(self, x):
return SwishImplementation.apply(x)
class ConvBNReLU(nn.Sequential):
def __init__(self, in_planes, out_planes, kernel_size, stride=1, groups=1):
# super(ConvBNReLU, self).__init__()
padding = self._get_padding(kernel_size, stride)
super(ConvBNReLU, self).__init__(
OrderedDict([
('zeropad', nn.ZeroPad2d(padding)),
('conv1', nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding=0, groups=groups, bias=False)),
('bn1', nn.BatchNorm2d(out_planes)),
('swish', Swish())
])
)
def _get_padding(self, kernel_size, stride):
p = max(kernel_size - stride, 0)
return [p // 2, p - p // 2, p // 2, p - p // 2]
class SqueezeExcitation(nn.Module):
def __init__(self, in_planes, reduced_dim):
super(SqueezeExcitation, self).__init__()
self.pool = nn.AdaptiveAvgPool2d(1)
self.conv1 = nn.Conv2d(in_planes, reduced_dim, 1)
self.swish = Swish()
self.conv2 = nn.Conv2d(reduced_dim, in_planes, 1)
self.sigmoid = nn.Sigmoid()
self.se = nn.Sequential(
self.pool,
self.conv1,
self.swish,
self.conv2,
self.sigmoid
)
def forward(self, x):
return x * self.se(x)
class MBConvBlock(nn.Module):
def __init__(self,
in_planes,
out_planes,
expand_ratio,
kernel_size,
stride,
reduction_ratio=4,
drop_connect_rate=0.2):
super(MBConvBlock, self).__init__()
self.drop_connect_rate = drop_connect_rate
self.use_residual = in_planes == out_planes and stride == 1
assert stride in [1, 2]
assert kernel_size in [3, 5]
hidden_dim = in_planes * expand_ratio
reduced_dim = max(1, int(in_planes / reduction_ratio))
layers = []
# pw
self.pre_layer = ConvBNReLU(in_planes, hidden_dim, 1)
if in_planes != hidden_dim:
layers += [
self.pre_layer
]
# dw
self.dw = ConvBNReLU(hidden_dim, hidden_dim, kernel_size, stride=stride, groups=hidden_dim)
# se
self.se = SqueezeExcitation(hidden_dim, reduced_dim)
# pw-linear
self.linear = nn.Conv2d(hidden_dim, out_planes, 1, bias=False)
self.bn1 = nn.BatchNorm2d(out_planes)
layers += [
self.dw,
self.se,
self.linear,
self.bn1
]
self.conv = nn.Sequential(*layers)
self.bn_final = nn.BatchNorm2d(out_planes)
def _drop_connect(self, x):
if not self.training:
return x
keep_prob = 1.0 - self.drop_connect_rate
batch_size = x.size(0)
random_tensor = keep_prob
random_tensor += torch.rand(batch_size, 1, 1, 1, device=x.device)
binary_tensor = random_tensor.floor()
return x.div(keep_prob) * binary_tensor
def forward(self, x):
if self.use_residual:
# import ipdb; ipdb.set_trace()
return self.bn_final(x + self._drop_connect(self.conv(x)))
else:
return self.bn_final(self.conv(x))
def _make_divisible(value, divisor=8):
new_value = max(divisor, int(value + divisor / 2) // divisor * divisor)
if new_value < 0.9 * value:
new_value += divisor
return new_value
def _round_filters(filters, width_mult):
if width_mult == 1.0:
return filters
return int(_make_divisible(filters * width_mult))
def _round_repeats(repeats, depth_mult):
if depth_mult == 1.0:
return repeats
return int(math.ceil(depth_mult * repeats))
def count_parameters_in_MB(model):
# import ipdb; ipdb.set_trace()
return np.sum(np.prod(v.size()) for name, v in model.named_parameters() if 'graph_bn' not in name and 'GCN' not in name and 'transformation' not in name) / 1e6
@mlconfig.register
class EfficientNet(nn.Module):
def __init__(self, width_mult=1.0, depth_mult=1.0, dropout_rate=0.2, num_classes=1000):
super(EfficientNet, self).__init__()
# yapf: disable
settings = [
# t, c, n, s, k
[1, 16, 1, 1, 3], # MBConv1_3x3, SE, 112 -> 112
[6, 24, 2, 2, 3], # MBConv6_3x3, SE, 112 -> 56
[6, 40, 2, 2, 5], # MBConv6_5x5, SE, 56 -> 28
[6, 80, 3, 2, 3], # MBConv6_3x3, SE, 28 -> 14
[6, 112, 3, 1, 5], # MBConv6_5x5, SE, 14 -> 14
[6, 192, 4, 2, 5], # MBConv6_5x5, SE, 14 -> 7
[6, 320, 1, 1, 3] # MBConv6_3x3, SE, 7 -> 7
]
# yapf: enable
out_channels = _round_filters(32, width_mult)
features = [ConvBNReLU(3, out_channels, 3, stride=2)]
in_channels = out_channels
for t, c, n, s, k in settings:
out_channels = _round_filters(c, width_mult)
repeats = _round_repeats(n, depth_mult)
for i in range(repeats):
stride = s if i == 0 else 1
features += [MBConvBlock(in_channels, out_channels, expand_ratio=t, stride=stride, kernel_size=k)]
in_channels = out_channels
last_channels = _round_filters(1280, width_mult)
features += [ConvBNReLU(in_channels, last_channels, 1)]
self.features = nn.Sequential(*features)
self.classifier = nn.Sequential(
nn.Dropout(dropout_rate),
nn.Linear(last_channels, num_classes),
)
# weight initialization
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out')
if m.bias is not None:
nn.init.zeros_(m.bias)
elif isinstance(m, nn.BatchNorm2d):
nn.init.ones_(m.weight)
nn.init.zeros_(m.bias)
elif isinstance(m, nn.Linear):
fan_out = m.weight.size(0)
init_range = 1.0 / math.sqrt(fan_out)
nn.init.uniform_(m.weight, -init_range, init_range)
if m.bias is not None:
nn.init.zeros_(m.bias)
def forward(self, x):
x = self.features(x)
x = x.mean([2, 3])
x = self.classifier(x)
return x
def _efficientnet(arch, pretrained, progress, **kwargs):
width_mult, depth_mult, _, dropout_rate = params[arch]
model = EfficientNet(width_mult, depth_mult, dropout_rate, **kwargs)
if pretrained:
state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)
if 'num_classes' in kwargs and kwargs['num_classes'] != 1000:
del state_dict['classifier.1.weight']
del state_dict['classifier.1.bias']
model.load_state_dict(state_dict, strict=False)
return model
@mlconfig.register
def efficientnet_b0(pretrained=False, progress=True, **kwargs):
return _efficientnet('efficientnet_b0', pretrained, progress, **kwargs)
@mlconfig.register
def efficientnet_b1(pretrained=False, progress=True, **kwargs):
return _efficientnet('efficientnet_b1', pretrained, progress, **kwargs)
@mlconfig.register
def efficientnet_b2(pretrained=False, progress=True, **kwargs):
return _efficientnet('efficientnet_b2', pretrained, progress, **kwargs)
@mlconfig.register
def efficientnet_b3(pretrained=False, progress=True, **kwargs):
return _efficientnet('efficientnet_b3', pretrained, progress, **kwargs)
@mlconfig.register
def efficientnet_b4(pretrained=False, progress=True, **kwargs):
return _efficientnet('efficientnet_b4', pretrained, progress, **kwargs)
@mlconfig.register
def efficientnet_b5(pretrained=False, progress=True, **kwargs):
return _efficientnet('efficientnet_b5', pretrained, progress, **kwargs)
@mlconfig.register
def efficientnet_b6(pretrained=False, progress=True, **kwargs):
return _efficientnet('efficientnet_b6', pretrained, progress, **kwargs)
@mlconfig.register
def efficientnet_b7(pretrained=False, progress=True, **kwargs):
return _efficientnet('efficientnet_b7', pretrained, progress, **kwargs)
if __name__ == '__main__':
layer = MBConvBlock(512, 512, expand_ratio=6, stride=1, kernel_size=5)
input = torch.rand(1, 512, 32, 32)
output = layer(input)
print(count_parameters_in_MB(layer))
import ipdb; ipdb; ipdb.set_trace() | [
"d12306@github.com"
] | d12306@github.com |
fbf08d8efccfafb01a6d89254354da5728fc07a1 | f89b72bc46005ccaaa0ac83609db2fbac9c89b94 | /Day_5_49_Interactive_Coding_Exercise_Average_Height/__init__.py | 5b445fec52afade23ea67bc43648e0a47c15a847 | [] | no_license | swiftandquick/100-Days-of-Code-The-Complete-Python-Pro-Bootcamp-for-2021 | 3b27e744951ef58301efe9fb14af289013e3be6c | a47dbf9b0d3feab9529aab33b145f63756a4c507 | refs/heads/master | 2023-06-15T11:34:52.881130 | 2021-06-28T17:31:04 | 2021-06-28T17:31:04 | 381,111,792 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 432 | py | # 🚨 Don't change the code below 👇
student_heights = input("Input a list of student heights ").split()
for n in range(0, len(student_heights)):
student_heights[n] = int(student_heights[n])
# 🚨 Don't change the code above 👆
#Write your code below this row 👇
# sum of the heights divide by number of entries give us the average.
average = int(round(sum(student_heights) / len(student_heights)))
print(f"{average}")
| [
"chenyMA16@gmail.com"
] | chenyMA16@gmail.com |
56c2adbfffabb89ea6c69a685d01c01d8098d791 | 235de1014c7aa9b05ee3c9cce2e7557c6406f800 | /Rationale_Analysis/experiments/hyperparam_search.py | d61afcd61a83d2afaa5a437ea45f96894e5a8e2c | [
"MIT"
] | permissive | yuvalpinter/rationale_analysis | b07336142e7de932238a3cc07c656e6616c0e717 | 2b25c6027d4459fc27e0f6793da6fee695e409a9 | refs/heads/master | 2020-09-11T08:16:15.031620 | 2019-11-17T23:25:11 | 2019-11-17T23:25:11 | 222,000,886 | 0 | 0 | MIT | 2019-11-15T20:48:41 | 2019-11-15T20:48:41 | null | UTF-8 | Python | false | false | 1,617 | py | import argparse
import os
import json
import subprocess
import hyperopt
from hyperopt import hp
import numpy as np
np.exp = lambda x : 10**x
parser = argparse.ArgumentParser()
parser.add_argument("--exp-name", type=str, required=True)
parser.add_argument("--search-space-file", type=str, required=True)
parser.add_argument("--dry-run", dest="dry_run", action="store_true")
parser.add_argument("--cluster", dest="cluster", action="store_true")
parser.add_argument('--run-one', dest='run_one', action='store_true')
parser.add_argument('--num-searches', type=int, required=True)
def main(args):
global_exp_name = args.exp_name
search_space_config = json.load(open(args.search_space_file))
hyperparam_space = {k:eval(v['type'])(k, **v['options']) for k, v in search_space_config.items()}
for i in range(args.num_searches) :
new_env = os.environ.copy()
hyperparam_vals = hyperopt.pyll.stochastic.sample(hyperparam_space)
for k, v in hyperparam_vals.items():
new_env[k] = str(v)
print(hyperparam_vals)
exp_name = os.path.join(global_exp_name, "search_" + str(i))
new_env["EXP_NAME"] = exp_name
cmd = ["bash", "Rationale_Analysis/commands/model_a_train_script.sh"]
if args.cluster:
cmd = ["sbatch", "Cluster_scripts/multi_gpu_sbatch.sh"] + cmd
print("Running ", cmd, " with exp name ", exp_name)
if not args.dry_run:
subprocess.run(cmd, check=True, env=new_env)
if args.run_one :
break
if __name__ == "__main__":
args = parser.parse_args()
main(args)
| [
"successar@gmail.com"
] | successar@gmail.com |
9125b313dd19c955c4e4c723fd0e6a63d05a1619 | 5aa3c9fb0a736fae3550e0d010f27bd974c66a06 | /code/L05/catch/catch_Q_test.py | b654a0ffa0e65dca9ac18b7f071744cd4946b610 | [] | no_license | rivkms/2019_omoc_ai | ffb691f8ba2716d1632aa9cf1ab0cf09401d4307 | 114d20a84bddc477488af6b97a1cfc5949852b11 | refs/heads/main | 2023-05-13T21:28:34.931488 | 2021-06-01T02:02:34 | 2021-06-01T02:02:34 | 371,994,669 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,765 | py | import os; os.environ['TF_CPP_MIN_LOG_LEVEL']='3' # disable TF logging
import numpy as np
from catch_MDP import MDP_transition, MDP_initial_state, num_actions, num_row, num_col
import tkinter as tk
import time as time # sleep for updating graphics
num_states = (num_row-1) * num_col * (num_col-2) # 720
#####################################################################
def to_scalar(state):
fruit_row, fruit_col, basket = state
i = (fruit_row-1)*num_col + (fruit_col-1)
j = basket-2
s = (num_col-2)*i + j
return s
#####################################################################
def test_Q_table(canvas):
Q = np.zeros([num_states, num_actions])
f = open("Q_table.txt", "r")
for i in range(num_states):
for j in range(num_actions):
Q[i][j] = float(f.readline().strip())
num_test = 5000
num_wins = 0
for ep in range(num_test):
state = MDP_initial_state()
canvas.update(state[0], state[1], state[2])
while True:
state_scalar = to_scalar(state)
# select action according to the learned Q value
action = Q[state_scalar].argmax()
r, state_next, terminate = MDP_transition(state, action)
canvas.update(state_next[0], state_next[1], state_next[2])
if terminate:
if r > 0: num_wins += 1
break
state = state_next
print ("Episode %d: %s" %(ep, ("wins" if r > 0 else "lose")))
return float(num_wins)/num_test
#####################################################################
class Canvas:
def __init__(self):
self.canvas = tk.Canvas(width=400, height=400, bg='white')
self.canvas.pack(expand=tk.YES, fill=tk.BOTH)
self.fruit_row = 1
self.fruit_col = 1
self.basket_col = 2
self.fruit = self.canvas.create_rectangle(0,0,40,40, fill="red")
self.basket = self.canvas.create_rectangle(0,360,120,400, fill="blue")
def update(self, fruit_row, fruit_col, basket_col):
drow = fruit_row - self.fruit_row
dcol = fruit_col - self.fruit_col
self.canvas.move(self.fruit, 40*dcol, 40*drow)
self.canvas.move(self.basket, 40*(basket_col-self.basket_col), 0)
self.fruit_row = fruit_row
self.fruit_col = fruit_col
self.basket_col = basket_col
self.canvas.update()
time.sleep(0.03)
def loop(self): self.canvas.mainloop()
#####################################################################
def run():
canvas = Canvas()
win_prob = test_Q_table(canvas)
print ("Winning probability with the trained Q table: ", win_prob)
run()
| [
"kminsung030120@gmail.com"
] | kminsung030120@gmail.com |
afc614636a168d512fd7a9da31c0dc42b2a9191f | afc4e63338fcb6538117ab2da3ebeb7b6d485399 | /campoapp/cedis/urls.py | 7b9a3a3c63a8bfbeeffb7c13b8791bc8046c038a | [] | no_license | alrvivas/cedis-erp | 7531108ba4dd2212788cb6d108ccacdce42d4b37 | aa7d3c5d844473b72786ee6168f9b3a71be349f2 | refs/heads/master | 2022-11-25T14:21:40.365438 | 2018-09-28T18:06:41 | 2018-09-28T18:06:41 | 146,667,529 | 0 | 0 | null | 2022-11-22T02:52:27 | 2018-08-29T22:52:30 | JavaScript | UTF-8 | Python | false | false | 725 | py | from django.conf.urls import url
from django.urls import path,re_path
from .views import (
CedisView,
CedisCreation,
RouteCedis,
RouteCreation,
ClientRoute,
)
app_name = 'cedis'
urlpatterns = [
path('', CedisView.as_view(), name='cedis'),
re_path(r'^nuevo$', CedisCreation.as_view(), name='new'),
path('<slug:slug>/', RouteCedis.as_view(), name='cedis_detail'),
#re_path(r'^nueva-ruta$', RouteCreation.as_view(), name='new_route'),
re_path(r'^(?P<slug>[\w-]+)/nueva-ruta/$', RouteCreation.as_view(), name='new_route'),
path('route/<slug:slug>/', ClientRoute.as_view(), name='route_detail'),
#re_path(r'^(?P<slug:slug>[-\w]+)/$', RouteCedis.as_view(), name='cedis_detail'),
] | [
"alr.vivas@gmail.com"
] | alr.vivas@gmail.com |
fcc48edcfdd4d1fc34b4b877308b372de722ad40 | 8eab8ab725c2132bb8d090cdb2d23a5f71945249 | /virt/Lib/site-packages/win32comext/shell/demos/create_link.py | 354561b7c50d6342a359a3c4e10a1c066bef399a | [
"MIT"
] | permissive | JoaoSevergnini/metalpy | 6c88a413a82bc25edd9308b8490a76fae8dd76ca | c2d0098a309b6ce8c756ff840bfb53fb291747b6 | refs/heads/main | 2023-04-18T17:25:26.474485 | 2022-09-18T20:44:45 | 2022-09-18T20:44:45 | 474,773,752 | 3 | 1 | MIT | 2022-11-03T20:07:50 | 2022-03-27T22:21:01 | Python | UTF-8 | Python | false | false | 2,329 | py | # link.py
# From a demo by Mark Hammond, corrupted by Mike Fletcher
# (and re-corrupted by Mark Hammond :-)
from win32com.shell import shell
import pythoncom, os
class PyShortcut:
def __init__(self):
self._base = pythoncom.CoCreateInstance(
shell.CLSID_ShellLink,
None,
pythoncom.CLSCTX_INPROC_SERVER,
shell.IID_IShellLink,
)
def load(self, filename):
# Get an IPersist interface
# which allows save/restore of object to/from files
self._base.QueryInterface(pythoncom.IID_IPersistFile).Load(filename)
def save(self, filename):
self._base.QueryInterface(pythoncom.IID_IPersistFile).Save(filename, 0)
def __getattr__(self, name):
if name != "_base":
return getattr(self._base, name)
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
print(
"Usage: %s LinkFile [path [, args[, description[, working_dir]]]]\n\nIf LinkFile does not exist, it will be created using the other args"
)
sys.exit(1)
file = sys.argv[1]
shortcut = PyShortcut()
if os.path.exists(file):
# load and dump info from file...
shortcut.load(file)
# now print data...
print(
"Shortcut in file %s to file:\n\t%s\nArguments:\n\t%s\nDescription:\n\t%s\nWorking Directory:\n\t%s\nItemIDs:\n\t<skipped>"
% (
file,
shortcut.GetPath(shell.SLGP_SHORTPATH)[0],
shortcut.GetArguments(),
shortcut.GetDescription(),
shortcut.GetWorkingDirectory(),
# shortcut.GetIDList(),
)
)
else:
if len(sys.argv) < 3:
print(
"Link file does not exist\nYou must supply the path, args, description and working_dir as args"
)
sys.exit(1)
# create the shortcut using rest of args...
data = map(
None,
sys.argv[2:],
("SetPath", "SetArguments", "SetDescription", "SetWorkingDirectory"),
)
for value, function in data:
if value and function:
# call function on each non-null value
getattr(shortcut, function)(value)
shortcut.save(file)
| [
"joao.a.severgnini@gmail.com"
] | joao.a.severgnini@gmail.com |
be76c18f61aea5aa12cc8b9ac59cdf56e372a1f9 | 937246f0282edb3c9f16bd850c32a4ddad4e61b2 | /segmentation/unet.py | af3786d0f6a073a21fb69e46ee9562bd4dabd9ca | [] | no_license | fibremint/cm-software_segmentation-predict | feaadb8ecf3e2ff1c6bba4b83102e417ed550a51 | abaca533b82c48677611aec4b9153f7e377815d6 | refs/heads/master | 2022-10-06T08:50:05.547096 | 2021-01-08T02:39:02 | 2021-01-08T02:39:02 | 216,708,502 | 2 | 1 | null | 2022-09-23T22:50:12 | 2019-10-22T02:42:05 | Python | UTF-8 | Python | false | false | 4,955 | py | '''
* @author [Zizhao Zhang]
* @email [zizhao@cise.ufl.edu]
* @create date 2017-05-25 02:21:13
* @modify date 2017-05-25 02:21:13
* @desc [description]
'''
import tensorflow as tf
from tensorflow import keras
Model = keras.models.Model
layers = keras.layers
K = keras.backend
def preprocess_input(x):
with tf.name_scope('preprocess_input'):
x /= 255.
x -= 0.5
x *= 2.
return x
class UNet:
def __init__(self):
pass
def get_crop_shape(self, target, refer):
# width, the 3rd dimension
cw = (target.get_shape()[2] - refer.get_shape()[2]).value
assert (cw >= 0)
if cw % 2 != 0:
cw1, cw2 = int(cw/2), int(cw/2) + 1
else:
cw1, cw2 = int(cw/2), int(cw/2)
# height, the 2nd dimension
ch = (target.get_shape()[1] - refer.get_shape()[1]).value
assert (ch >= 0)
if ch % 2 != 0:
ch1, ch2 = int(ch/2), int(ch/2) + 1
else:
ch1, ch2 = int(ch/2), int(ch/2)
return (ch1, ch2), (cw1, cw2)
def create_model(self, img_shape, num_class, rate, input_tensor=None):
print ('create a Unet model (drop_rate=%.2f)'%(rate))
concat_axis = 3
if input_tensor is None:
inputs = layers.Input(shape=img_shape)
else:
inputs = layers.Input(tensor=input_tensor)
conv1 = layers.Conv2D(32, (3, 3), activation='relu', padding='same', name='conv1_1')(inputs)
if rate > 0: conv1 = layers.Dropout(rate)(conv1)
conv1 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(conv1)
pool1 = layers.MaxPooling2D(pool_size=(2, 2))(conv1)
conv2 = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(pool1)
if rate > 0:conv2 = layers.Dropout(rate)(conv2)
conv2 = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(conv2)
pool2 = layers.MaxPooling2D(pool_size=(2, 2))(conv2)
conv3 = layers.Conv2D(128, (3, 3), activation='relu', padding='same')(pool2)
if rate > 0:conv3 = layers.Dropout(rate)(conv3)
conv3 = layers.Conv2D(128, (3, 3), activation='relu', padding='same')(conv3)
pool3 = layers.MaxPooling2D(pool_size=(2, 2))(conv3)
conv4 = layers.Conv2D(256, (3, 3), activation='relu', padding='same')(pool3)
if rate > 0:conv4 = layers.Dropout(rate)(conv4)
conv4 = layers.Conv2D(256, (3, 3), activation='relu', padding='same')(conv4)
pool4 = layers.MaxPooling2D(pool_size=(2, 2))(conv4)
conv5 = layers.Conv2D(512, (3, 3), activation='relu', padding='same')(pool4)
if rate > 0:conv5 = layers.Dropout(rate)(conv5)
conv5 = layers.Conv2D(512, (3, 3), activation='relu', padding='same')(conv5)
up_conv5 = layers.UpSampling2D(size=(2, 2))(conv5)
ch, cw = self.get_crop_shape(conv4, up_conv5)
crop_conv4 = layers.Cropping2D(cropping=(ch,cw))(conv4)
up6 = layers.concatenate([up_conv5, crop_conv4], axis=concat_axis)
conv6 = layers.Conv2D(256, (3, 3), activation='relu', padding='same')(up6)
if rate > 0:conv6 = layers.Dropout(rate)(conv6)
conv6 = layers.Conv2D(256, (3, 3), activation='relu', padding='same')(conv6)
up_conv6 = layers.UpSampling2D(size=(2, 2))(conv6)
ch, cw = self.get_crop_shape(conv3, up_conv6)
crop_conv3 = layers.Cropping2D(cropping=(ch,cw))(conv3)
up7 = layers.concatenate([up_conv6, crop_conv3], axis=concat_axis)
conv7 = layers.Conv2D(128, (3, 3), activation='relu', padding='same')(up7)
if rate > 0:conv7 = layers.Dropout(rate)(conv7)
conv7 = layers.Conv2D(128, (3, 3), activation='relu', padding='same')(conv7)
up_conv7 = layers.UpSampling2D(size=(2, 2))(conv7)
ch, cw = self.get_crop_shape(conv2, up_conv7)
crop_conv2 = layers.Cropping2D(cropping=(ch,cw))(conv2)
up8 = layers.concatenate([up_conv7, crop_conv2], axis=concat_axis)
conv8 = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(up8)
if rate > 0:conv8 = layers.Dropout(rate)(conv8)
conv8 = layers.Conv2D(64, (3, 3), activation='relu', padding='same')(conv8)
up_conv8 = layers.UpSampling2D(size=(2, 2))(conv8)
ch, cw = self.get_crop_shape(conv1, up_conv8)
crop_conv1 = layers.Cropping2D(cropping=(ch,cw))(conv1)
up9 = layers.concatenate([up_conv8, crop_conv1], axis=concat_axis)
conv9 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(up9)
if rate > 0: conv9 = layers.Dropout(rate)(conv9)
conv9 = layers.Conv2D(32, (3, 3), activation='relu', padding='same')(conv9)
ch, cw = self.get_crop_shape(inputs, conv9)
conv9 = layers.ZeroPadding2D(padding=((ch[0], ch[1]), (cw[0], cw[1])))(conv9)
conv10 = layers.Conv2D(num_class, (1, 1))(conv9)
model = Model(inputs=inputs, outputs=conv10)
return model
| [
"fibremint@gmail.com"
] | fibremint@gmail.com |
2bb0272ff16b5ec3b71d3beaad08ec031e12036a | 37288344f906430f7ef44184df805f743de64667 | /Django/urls.py | 2537adf771137ae1ed5d734e774a43fe7875fe73 | [] | no_license | LoreinZhong/Django | 5db9c0997f1a4c7ac9cdd3921962b35b2956486a | e560d1ebc313068383bca39f5a9b6665f94694ba | refs/heads/master | 2016-09-05T22:13:19.758778 | 2015-03-12T12:10:14 | 2015-03-12T12:10:14 | 32,072,743 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 690 | py | from django.conf.urls import patterns, include, url
from django.contrib.auth.views import login,logout
#from django.contrib import admin
#from Django.view import time
from atm import views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'Django.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
#(r'^admin/',include(admin.site.urls)),
#(r'^contact_form/$',views.contact_form),
#(r'^search_form/$',views.search_form),
#(r'search/$',views.search),
(r'^login_page',views.login_page),
(r'^login/$',views.login),
(r'^transfer/$',views.transfer),
(r'^save/$',views.save),
(r'^query/$',views.query),
(r'^draw/$',views.draw),
(r'^exit/$',views.exit),
)
| [
"laylarzhong@gmail.com"
] | laylarzhong@gmail.com |
a06314802075fb526c385787fd3b9a881c27ea21 | 8a94ed3ae996f0c8e780dd78b91ad2269363575d | /midterm 2562-1/If1.py | 0012654f6cb7136303978a226d73042bca8dceae | [] | no_license | thitimon171143/MyPython | 30fd44d571005d5f979c34c7356cd755eead760f | d1be644a703e211f14c138179ab79890a7095ecd | refs/heads/master | 2022-08-16T14:53:01.006440 | 2019-09-17T09:01:22 | 2019-09-17T09:01:22 | 192,525,122 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 235 | py | score1 = int(input('First Test Score : '))
score2 = int(input('Second Test Score : '))
score3 = int(input('Third Test Score : '))
average = (score1+score2+score3)/3
print('Average = ',average)
if average > 95:
print('Congratulate') | [
"Python@Admins-iMac-5.local"
] | Python@Admins-iMac-5.local |
0e7cfaaa195066b4e3e8173bb18b4e60539f1cf0 | 55ef03ff18712d052c3278f0bb81cad04ceec415 | /tests/test_retrieve_octocat_list.py | 5c41046097f54d8ef4e27d97f837f889c519b8f2 | [] | no_license | Ethik-69/Flask_API | 3fa41de59dee9f2c5afcb50cfa71c6865abffdf7 | b0cfdd6fb33277e4ae04c73f173870e1cb144770 | refs/heads/master | 2021-02-18T11:33:29.321474 | 2020-03-05T14:58:36 | 2020-03-12T13:46:54 | 245,191,082 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,386 | py | """Test cases for GET requests sent to the api.octocat_list API endpoint."""
from http import HTTPStatus
from tests.util import (
ADMIN_EMAIL,
login_user,
create_octocat,
retrieve_octocat_list,
)
NAMES = [
"octocat1",
"second_octocat",
"octocat-thrice",
"tetraWIDG",
"PENTA-widg-GON-et",
"hexa_octocat",
"sep7",
]
URLS = [
"http://www.one.com",
"https://www.two.net",
"https://www.three.edu",
"http://www.four.dev",
"http://www.five.io",
"https://www.six.tech",
"https://www.seven.dot",
]
AGES = [
3,
4,
5,
6,
7,
1,
2,
]
def test_retrieve_paginated_octocat_list(client, db, admin):
response = login_user(client, email=ADMIN_EMAIL)
assert "access_token" in response.json
access_token = response.json["access_token"]
# ADD SEVEN octocat INSTANCES TO DATABASE
for i in range(0, len(NAMES)):
response = create_octocat(
client, access_token, octocat_name=NAMES[i], url=URLS[i], age=AGES[i],
)
assert response.status_code == HTTPStatus.CREATED
# REQUEST PAGINATED LIST OF OCTOCATS: 5 PER PAGE, PAGE #1
response = retrieve_octocat_list(client, access_token, page=1, per_page=5)
assert response.status_code == HTTPStatus.OK
# VERIFY PAGINATION ATTRIBUTES FOR PAGE #1
assert "has_prev" in response.json and not response.json["has_prev"]
assert "has_next" in response.json and response.json["has_next"]
assert "page" in response.json and response.json["page"] == 1
assert "total_pages" in response.json and response.json["total_pages"] == 2
assert "items_per_page" in response.json and response.json["items_per_page"] == 5
assert "total_items" in response.json and response.json["total_items"] == 7
assert "items" in response.json and len(response.json["items"]) == 5
# VERIFY ATTRIBUTES OF OCTOCATS #1-5
for i in range(0, len(response.json["items"])):
item = response.json["items"][i]
assert "name" in item and item["name"] == NAMES[i]
assert "url" in item and item["url"] == URLS[i]
assert "age" in item and item["age"] == AGES[i]
# REQUEST PAGINATED LIST OF OCTOCATS: 5 PER PAGE, PAGE #2
response = retrieve_octocat_list(client, access_token, page=2, per_page=5)
assert response.status_code == HTTPStatus.OK
# VERIFY PAGINATION ATTRIBUTES FOR PAGE #2
assert "has_prev" in response.json and response.json["has_prev"]
assert "has_next" in response.json and not response.json["has_next"]
assert "page" in response.json and response.json["page"] == 2
assert "total_pages" in response.json and response.json["total_pages"] == 2
assert "items_per_page" in response.json and response.json["items_per_page"] == 5
assert "total_items" in response.json and response.json["total_items"] == 7
assert "items" in response.json and len(response.json["items"]) == 2
# VERIFY ATTRIBUTES OF OCTOCATS #6-7
for i in range(5, response.json["total_items"]):
item = response.json["items"][i - 5]
assert "name" in item and item["name"] == NAMES[i]
assert "url" in item and item["url"] == URLS[i]
assert "age" in item and item["age"] == AGES[i]
# REQUEST PAGINATED LIST OF OCTOCATS: 10 PER PAGE, PAGE #1
response = retrieve_octocat_list(client, access_token, page=1, per_page=10)
assert response.status_code == HTTPStatus.OK
# VERIFY PAGINATION ATTRIBUTES FOR PAGE #1
assert "has_prev" in response.json and not response.json["has_prev"]
assert "has_next" in response.json and not response.json["has_next"]
assert "page" in response.json and response.json["page"] == 1
assert "total_pages" in response.json and response.json["total_pages"] == 1
assert "items_per_page" in response.json and response.json["items_per_page"] == 10
assert "total_items" in response.json and response.json["total_items"] == 7
assert "items" in response.json and len(response.json["items"]) == 7
# VERIFY ATTRIBUTES OF OCTOCATS #1-7
for i in range(0, len(response.json["items"])):
item = response.json["items"][i]
assert "name" in item and item["name"] == NAMES[i]
assert "url" in item and item["url"] == URLS[i]
assert "age" in item and item["age"] == AGES[i]
# REQUEST PAGINATED LIST OF OCTOCATS: DEFAULT PARAMETERS
response = retrieve_octocat_list(client, access_token)
assert response.status_code == HTTPStatus.OK
# VERIFY PAGINATION ATTRIBUTES FOR PAGE #1
assert "has_prev" in response.json and not response.json["has_prev"]
assert "has_next" in response.json and not response.json["has_next"]
assert "page" in response.json and response.json["page"] == 1
assert "total_pages" in response.json and response.json["total_pages"] == 1
assert "items_per_page" in response.json and response.json["items_per_page"] == 10
assert "total_items" in response.json and response.json["total_items"] == 7
assert "items" in response.json and len(response.json["items"]) == 7
# VERIFY ATTRIBUTES OF OCTOCATS #1-7
for i in range(0, len(response.json["items"])):
item = response.json["items"][i]
assert "name" in item and item["name"] == NAMES[i]
assert "url" in item and item["url"] == URLS[i]
assert "age" in item and item["age"] == AGES[i]
| [
"ethan.chamik.external@airbus.com"
] | ethan.chamik.external@airbus.com |
097ffe889ecca6ba681f647340800b9ee5807fde | 4f0d9dbbf1a870b661870ebb1f4ac2306e6e3802 | /apps/main/models.py | ccc30a23e7cb0441f0aa491fb824e23c663e04a4 | [] | no_license | ItEngine/ItEngine | a5d13af8ae6fc4ebcb4633d0e12e8e7e90a10c63 | 2932f31f33140b3e066d8108235398276500092e | refs/heads/master | 2020-12-03T02:30:36.385719 | 2016-07-23T00:58:04 | 2016-07-23T00:58:04 | 45,215,270 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,385 | py | import datetime
from flask import Blueprint
from sqlalchemy import event
from sqlalchemy.event import listens_for
from werkzeug.security import generate_password_hash
from app import db, login_manager
class User(db.Model):
"""
Model User
"""
__tablename__ = 'Users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(30), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(120), nullable=False)
first_name = db.Column(db.String(120), nullable=False)
last_name = db.Column(db.String(120), nullable=False)
date_join = db.Column(
db.DateTime, nullable=False,
default=datetime.datetime.utcnow
)
is_active = db.Column(
db.Boolean, default=True
)
is_admin = db.Column(
db.Boolean, default=False
)
@property
def is_authenticated(self):
return True
def get_id(self):
try:
return self.id
except AttributeError:
raise NotImplementedError('No `id` attribute - override `get_id`')
def __repr__(self):
return '<User %r>' % (self.username)
def hash_password(target, value, oldvalue, initiator):
if value is not None:
return generate_password_hash(value)
# Setup listener on User attribute password
event.listen(User.password, 'set', hash_password, retval=True)
@login_manager.user_loader
def load_user(id):
"""
For flask-login get user id
"""
return User.query.get(int(id))
class Site(db.Model):
"""
Model Site
"""
__tablename__ = 'Sites'
id = db.Column(db.Integer, primary_key=True)
company = db.Column(db.String(120), nullable=False)
descrip = db.Column(db.String(500), nullable=False)
type_company = db.Column(db.String(50), nullable=False)
site_company = db.Column(db.String(120), nullable=False)
photo = db.Column(db.Unicode(128))
class Portfolio(db.Model):
"""
Model Portfolio
"""
__tablename__ = 'Portfolios'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(120), nullable=False)
descrip = db.Column(db.String(500), nullable=False)
tecnologies = db.Column(db.String(50), nullable=False)
site_url = db.Column(db.String(120), nullable=False)
photo = db.Column(db.Unicode(128))
| [
"martinpeveri@gmail.com"
] | martinpeveri@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.