seq_id stringlengths 4 11 | text stringlengths 113 2.92M | repo_name stringlengths 4 125 ⌀ | sub_path stringlengths 3 214 | file_name stringlengths 3 160 | file_ext stringclasses 18
values | file_size_in_byte int64 113 2.92M | program_lang stringclasses 1
value | lang stringclasses 93
values | doc_type stringclasses 1
value | stars int64 0 179k ⌀ | dataset stringclasses 3
values | pt stringclasses 78
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
38004828445 | import pandas as pd
import numpy as np
import geopandas as gpd
import sys
import time
import requests
import category_encoders as ce
from urllib.parse import quote_plus
import folium
from shapely.geometry import box, mapping, polygon, multipolygon, Point
CLIENT_ID = '' # your Foursquare ID
CLIENT_SECRET = '' # your Foursquare Secret
VERSION = '20180605' # Foursquare API version
# Define grid generator as inputs to foursquare venue search
def generate_square_grid(geometry, threshold=0.05):
"""
Adapted from https://snorfalorpagus.net/blog/2016/03/13/splitting-large-polygons-for-faster-intersections/
"""
bounds = geometry.bounds
geom = geometry
# Check if threshold is appropriate for bounding box
width = bounds[2] - bounds[0]
height = bounds[3] - bounds[1]
if width > 10 or height > 10:
# prevents too many grid items per city
threshold *= 10
print('adjusted threshold', threshold)
if width > 5 or height > 5:
# prevents too many grid items per city
threshold *= 4
print('adjusted threshold', threshold)
elif width > 2 or height > 2:
# prevents too many grid items per city
threshold *= 2
print('adjusted threshold', threshold)
x_min = int(bounds[0] // threshold)
x_max = int(bounds[2] // threshold)
y_min = int(bounds[1] // threshold)
y_max = int(bounds[3] // threshold)
grid = []
for i in range(x_min, x_max+1):
for j in range(y_min, y_max+1):
b = box(i*threshold, j*threshold, (i+1)*threshold, (j+1)*threshold)
g = geom.intersection(b)
if g.is_empty:
continue
is_polygon = isinstance(g, (polygon.Polygon, multipolygon.MultiPolygon))
if is_polygon:
grid.append(g)
return grid
# Define Foursquare `/venues/VENUE_ID/likes` helper
def fetch_venue_likes(venue_id):
url = "https://api.foursquare.com/v2/venues/{}/likes?client_id={}&client_secret={}&v={}".format(
venue_id,
CLIENT_ID,
CLIENT_SECRET,
VERSION
)
results = requests.get(url).json()
time.sleep(0.3)
if results["meta"]["code"] != 200:
print('Status', results["meta"]["code"])
return None
response = results["response"]
return response["likes"]["count"] or 0
# Define Foursquare `/search` helper
def search_city_venues(city_name='', grid_gdf=gpd.GeoDataFrame(), grid_interval=0.05):
"""
Searches city with grid. This approach of using /search should reduce the
duplication problem we were seeing with pagination.
grid -- list of Polygons
Returns
list of venues labeled with cityname
"""
grid_piece_venues = []
for i,g in grid_gdf.iterrows():
geom = g.geometry
is_polygon = isinstance(geom, (polygon.Polygon, multipolygon.MultiPolygon))
if is_polygon:
# create the API request URL
url = 'https://api.foursquare.com/v2/venues/search?&categoryId=4d4b7105d754a06374d81259&client_id={}&client_secret={}&v={}&sw={},{}&ne={},{}&intent=browse&limit=50'.format(
CLIENT_ID,
CLIENT_SECRET,
VERSION,
geom.bounds[1],
geom.bounds[0],
geom.bounds[3],
geom.bounds[2],
)
print('REQUESTED', city_name, i, geom.bounds)
results = requests.get(url).json()
time.sleep(0.3)
response = results["response"]
try:
if response:
items = response['venues']
if items and len(items)>0:
grid_items = []
for v in items:
lat = v['location']['lat'] if v['location'] else None
lng = v['location']['lng'] if v['location'] else None
p = Point(lng, lat)
if p and geom.contains(p):
grid_items.append({
'city': city_name,
'id': v['id'],
'name': v['name'],
'category': v['categories'][0]['name'] if v['categories'] and v['categories'][0] else None,
'location': p
})
if len(grid_items) == 50:
next_grid = generate_square_grid(geom, grid_interval/2)
next_grid_gdf = gpd.GeoDataFrame(geometry=next_grid)
next_venues = search_city_venues(city_name, next_grid_gdf, grid_interval/2)
[grid_piece_venues.append(v) for v in next_venues]
else:
[grid_piece_venues.append(gr) for gr in grid_items]
except:
print('Unable to parse venues/search response.')
break
return(grid_piece_venues)
# Define '/venues/categories' helper
def fetch_venue_categories():
url = 'https://api.foursquare.com/v2/venues/categories?client_id={}&client_secret={}&v={}'.format(
CLIENT_ID,
CLIENT_SECRET,
VERSION,
)
results = requests.get(url).json()["response"]
res = []
if results and results['categories']:
for r in results['categories']:
def append_categories(categories, category):
for c in categories:
subcategory = c['name']
nested = len(c['categories'])
if nested:
append_categories(c['categories'], category)
res.append({'name': subcategory, 'id': c['id'], 'category': category['name'], 'cat_id': category['id'] })
append_categories(r['categories'], r)
return res
| abcolb/Coursera_Capstone | foursquare.py | foursquare.py | py | 6,079 | python | en | code | 0 | github-code | 13 |
14727478338 | import requests
def get_luse(x_pos, y_pos):
# chatgpt_api_keys = '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'
url = f"https://lohas.taichung.gov.tw/arcgis/rest/services/Tiled3857/LandAdminNew3857/MapServer/2/query?f=json&geometry=%7B%22spatialReference%22%3A%7B%22wkid%22%3A4326%7D%2C%22x%22%3A{str(x_pos)}%2C%22y%22%3A{str(y_pos)}%7D&geometryPrecision=7&outFields=AA46%2CLUSE&geometryType=esriGeometryPoint&token=aVwX13YUhVcklKu0cfl565XRdT1XL5vJMmcNLfROJ07HG4NFdfLzwzAniYX3yJI_DSFp2a_LJ7GGygmmx4tO3g.."
headers = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7",
"Connection": "keep-alive",
"Host": "lohas.taichung.gov.tw",
"Origin": "https://mcgbm.taichung.gov.tw",
"Referer": "https://mcgbm.taichung.gov.tw/",
"sec-ch-ua": "\"Chromium\";v=\"112\", \"Google Chrome\";v=\"112\", \"Not:A-Brand\";v=\"99\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Windows\"",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-site",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36"
}
response = requests.get(url, headers=headers, verify=False)
# Check if the request was successful
if response.status_code == 200:
# Access the response data in JSON format
json_data = response.json()
# Process the JSON data as needed
# print(json_data)
else:
json_data = "None"
print("Error: Request failed with status code", response.status_code)
if json_data['features']:
return json_data['features'][0]['attributes']['LUSE']
else:
print("如未登錄或地籍分割合併中會查無資料")
return None
x = 120.679611
y = 24.188629
luse_result = get_luse(x, y)
print(f"the result is: {luse_result}")
| DonLiao1207/LandCrawler | get_luse.py | get_luse.py | py | 1,996 | python | en | code | 0 | github-code | 13 |
14971006737 | '''
多层感知机
含dropout
训练过程中,使用Dropout,其实就是对部分权重和偏置在某次迭代训练过程中,不参与计算和更新而已,
并不是不再使用这些权重和偏置了(预测和预测时,会使用全部的神经元,包括使用训练时丢弃的神经元)
'''
import numpy as np
import torch
from softmax.softmax_regress import loadData, get_fashion_mnist_labels, show_fashion_mnist
# 输入层 输出层 隐含层两层节点个数
inputsn, outputsn, hiddensn1, hiddensn2 = 784, 10, 256, 256
# 丢弃法概率
drop_prob1, drop_prob2 = 0.2, 0.5
# 激活函数 选relu函数 relu = max(0,x)
def relu(X):
return torch.max(X, other=torch.tensor(0.0))
def dropout(X, drop_prob):
X = X.float()
assert 0 <= drop_prob <= 1
keep_prob = 1 - drop_prob
# 这种情况下把全部元素都丢弃
if keep_prob == 0:
return torch.zeros_like(X)
mask = (torch.rand(X.shape) < keep_prob).float()
return mask * X / keep_prob
def model(X, params, bool_training=True):
X = X.view((-1, inputsn))
H1 = relu(torch.matmul(X, params[0]) + params[1])
if bool_training:
# 训练模型时才dropout
# 在第一层全连接后添加丢弃层
H1 = dropout(H1, drop_prob1)
H2 = (torch.matmul(H1, params[2]) + params[3]).relu()
if bool_training:
# 在第二层全连接后添加丢弃层
H2 = dropout(H2, drop_prob2)
return torch.matmul(H2, params[4]) + params[5]
def sgd(params, lr, batch_size):
for param in params:
# 注意这里更改param时用的param.data
param.data -= lr * param.grad / batch_size
def train(train_batch, test_batch, optimizer = None):
# 初始化参数
W1 = torch.tensor(np.random.normal(0, 0.01, (inputsn, hiddensn1)), dtype=torch.float)
b1 = torch.zeros(hiddensn1, dtype=torch.float)
W2 = torch.tensor(np.random.normal(0, 0.01, (hiddensn1, hiddensn2)), dtype=torch.float)
b2 = torch.zeros(hiddensn2, dtype=torch.float)
W3 = torch.tensor(np.random.normal(0, 0.01, (hiddensn2, outputsn)), dtype=torch.float)
b3 = torch.zeros(outputsn, dtype=torch.float)
# 参数列表
params = [W1, b1, W2, b2, W3, b3]
for param in params:
param.requires_grad_(requires_grad=True)
num_epochs, lr = 5, 100.0
# 交叉熵损失
loss = torch.nn.CrossEntropyLoss()
# optimizer = torch.optim.SGD(params, lr, batch_size)
for epoch in range(num_epochs):
train_loss_sum, train_acc_sum, train_n = 0.0, 0.0, 0
for trainX, trainy in train_batch:
# 构造softmax回归
trainy_pre = model(trainX, params)
l = loss(trainy_pre, trainy)
# 梯度清零
if optimizer is not None:
optimizer.zero_grad()
elif params is not None and params[0].grad is not None:
for param in params:
param.grad.data.zero_()
# 梯度后向传播
l.backward()
if optimizer is None:
sgd(params, lr, batch_size)
else:
optimizer.step()
train_loss_sum += l.item()
train_acc_sum += (trainy_pre.argmax(dim=1) == trainy).float().sum().item()
train_n += trainy.shape[0]
train_acc = train_acc_sum / train_n
# 测试集
test_acc_sum, test_n = 0, 0
for testX, testy in test_batch:
# 测试时不应该使用丢弃法
if isinstance(model, torch.nn.Module):
# 针对torch.nn.Module包定义好的模型
# 评估模式,关闭dropout
model.eval()
test_acc_sum += (model(testX, params).argmax(dim=1) == testy).float().sum().item()
# 改回训练模式
model.train()
else:
# 针对自定义模型
if("bool_training" in model.__code__.co_varnames):
# 如果模型中有bool_training这个参数
test_acc_sum += (model(testX, params, bool_training=False).argmax(dim=1) == testy).float().sum().item()
else:
test_acc_sum += (model(testX, params).argmax(dim=1) == testy).float().sum().item()
test_n += testy.shape[0]
test_acc = test_acc_sum / test_n
print('第%d轮的交叉熵损失: %.4f, 训练集acc: %.3f, 测试集acc: %.3f'
% (epoch + 1, train_loss_sum / train_n, train_acc, test_acc))
return model, params
def predict(model, params, test_batch):
predX, predy = iter(test_batch).next()
true_labels = get_fashion_mnist_labels(predy.numpy())
pred_labels = get_fashion_mnist_labels(model(predX, params, bool_training=False).argmax(dim=1).numpy())
titles = [true + '\n' + pred for true, pred in zip(true_labels, pred_labels)]
show_fashion_mnist(predX[0:9], titles[0:9])
if __name__ == "__main__":
batch_size = 256
train_batch, test_batch = loadData(batch_size)
model, params = train(train_batch, test_batch)
predict(model, params, test_batch)
| Money8888/pytorch_learn | MLP/MLP.py | MLP.py | py | 5,133 | python | en | code | 1 | github-code | 13 |
2196777967 | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# url = "http://news.ifeng.com/a/20190104/60223969_0.shtml"
url = 'http://taiwan.huanqiu.com/article/2018-12/13943256.html'
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get(url)
aa = driver.find_element_by_xpath(
'//span[@id="msgNumBottom"]/a|//b[@id="msgNumTop"]/a|//b[@id="msgNumBottom"]/a|//span[@class="participate"]/var[0]').text
print(aa)
| a289237642/companySpider | 1/hqw/hqw/test/3.py | 3.py | py | 625 | python | en | code | 0 | github-code | 13 |
1408134436 | import numpy as np
import neuralnetwork_ex9 as nn
# image = np.random.rand(32, 32)
# kernal = np.random.rand(5, 5)
# def subsample_layer(layer, pool_size, strides):
# layer_rows = ((layer.shape[0] - pool_size) / strides) + 1
# layer_cols = ((layer.shape[1] - pool_size) / strides) + 1
# feature_map = np.zeros((layer_rows,layer_cols))
# for row in range(layer_rows):
# for col in range(layer_cols):
# start_row = (strides * row)
# end_row = (start_row + pool_size)
# start_col = (strides * col)
# end_col = (start_col + pool_size)
# feature_unit = np.sum([layer[start_row:end_row, start_col:end_col]])
# feature_map[row, col] = feature_unit
# inputs
# filters
# kernel_shapes
# padding
# activations
# convnn = newnn(
# num_maps_layers=[32, 64],
# kernal_layers=[(5, 5), (5, 5)],
# kernal_strides=[(1,1), (1,1)],
# pooling_layers=[(2, 2), (2, 2)],
# pooling_strides=[(2, 2), (2, 2)],
# activation_layers=["relu", "relu"],
# padding_layers=["same", "same"]
# )
# for num_maps in num_maps_layers:
# for feature_map in range(num_maps):
def compute_activation_fn(num, string):
num = np.squeeze(num)
if num < 0:
return 0
else:
return num
def compute_activation_fn_deriv(num, string):
num = np.squeeze(num)
if num < 0:
return 0
else:
return 1
def pad_input_layer(input_layer, filter_layer, stride_size, padding_fn):
"""
``input_layer`` must be of shape (batch_size, in_height, in_width, in_channels)
``filter_layer`` must be of shape (batch_size, filter_height, filter_width, in_channels) or [filter_height, filter_width]
``stride_size`` must be of shape [stride_height, stride_width]
``padding_fn`` must be a string, "valid" or "same"
if padding_fn == "valid", returns output of shape that so that kernel and stride can easily stride across and fit
if padding_fn == "same", returns output padded with 0's so that the feature map will later be the same size as the original input.
"""
batch_size = input_layer.shape[0]
padded_input_layer = list()
for idx in range(batch_size):
inputs = input_layer[idx]
input_rows = inputs.shape[0]
input_cols = inputs.shape[1]
if type(filter_layer) == list:
filter_rows = filter_layer[0]
filter_cols = filter_layer[1]
else:
filter_rows = filter_layer[idx].shape[0]
filter_cols = filter_layer[idx].shape[1]
stride_rows = stride_size[0]
stride_cols = stride_size[1]
if padding_fn == "same":
width_padding = (input_cols * stride_cols) + filter_cols - input_cols - stride_cols
height_padding = (input_rows * stride_rows) + filter_rows - input_rows - stride_rows
row_padding_right = int(np.ceil(width_padding / 2))
row_padding_left = int(np.floor(width_padding / 2))
col_padding_bottom = int(np.ceil(height_padding / 2))
col_padding_top = int(np.floor(height_padding / 2))
padded_inputs = np.pad(inputs, [(col_padding_top, col_padding_bottom), (row_padding_left, row_padding_right), (0,0)], mode='constant')
elif padding_fn == "valid":
max_num_rows = (int)((input_rows - filter_rows) / stride_rows) + 1
max_num_cols = (int)((input_cols - filter_cols) / stride_cols) + 1
padded_inputs = inputs[:filter_rows + (stride_rows * (max_num_rows - 1)),:filter_cols + (stride_cols * (max_num_cols - 1))]
padded_input_layer.append(padded_inputs)
return np.array(padded_input_layer)
def convert_padded_derivs_layer(orig_input_layer, padded_derivs_layer, filter_layer, stride_size, padding_fn):
"""
``orig_input_layer`` must be of shape (batch_size, in_height, in_width, in_channels)
``padded_derivs_layer`` must be of shape (batch_size, in_height, in_width, in_channels)
``filter_layer`` must be of shape (batch_size, filter_height, filter_width, in_channels)
``stride_size`` must be of shape [stride_height, stride_width]
``padding_fn`` must be a string, "valid" or "same"
returns d of padded derivs w.r.t orig_inputs, return shape = (batch_size, orig_input_layer_in_width, orig_input_layer_in_height, orig_input_layer_in_channels)
"""
batch_size = orig_input_layer.shape[0]
converted_padded_derivs_layer = list()
for idx in range(batch_size):
orig_inputs, padded_derivs = orig_input_layer[idx], padded_derivs_layer[idx]
input_rows = orig_inputs.shape[0]
input_cols = orig_inputs.shape[1]
if type(filter_layer) == list:
filter_rows = filter_layer[0]
filter_cols = filter_layer[1]
else:
filter_rows = filter_layer[idx].shape[0]
filter_cols = filter_layer[idx].shape[1]
stride_rows = stride_size[0]
stride_cols = stride_size[1]
if padding_fn == "same":
width_padding = (input_cols * stride_cols) + filter_cols - input_cols - stride_cols
height_padding = (input_rows * stride_rows) + filter_rows - input_rows - stride_rows
row_padding_right = int(np.ceil(width_padding / 2))
row_padding_left = int(np.floor(width_padding / 2))
col_padding_bottom = int(np.ceil(height_padding / 2))
col_padding_top = int(np.floor(height_padding / 2))
converted_padded_derivs = padded_derivs[col_padding_top:-col_padding_bottom, row_padding_left:-row_padding_right]
elif padding_fn == "valid":
max_num_rows = (int)((input_rows - filter_rows) / stride_rows) + 1
max_num_cols = (int)((input_cols - filter_cols) / stride_cols) + 1
cut_bottom_rows = input_rows - (filter_rows + (stride_rows * (max_num_rows - 1)))
cut_right_cols = input_cols - (filter_cols + (stride_cols * (max_num_cols - 1)))
converted_padded_derivs = np.pad(padded_derivs, [(0, cut_bottom_rows), (0, cut_right_cols), (0, 0)], mode='constant')
converted_padded_derivs_layer.append(converted_padded_derivs)
return np.array(converted_padded_derivs_layer)
def generate_fmaps(input_layer, kernel_layer, bias_layer, stride_size, padding_fn, activation_fn, dx=None):
"""
``input_layer`` must be of shape (batch_size, in_height, in_width, in_channels)
``kernel_layer`` must be of shape (num_filters, filter_height, filter_width, in_channels)
(in_channels for ``input_layer`` and ``kernel_layer`` must be same size)
``bias_layer`` must be of shape (num_filters, 1, 1, 1)
``stride_size`` must be of shape [stride_height, stride_width]
``padding_fn`` must be a string, "valid" or "same"
``activation_fn`` must be a string, e.g. "relu" or "sigmoid"
``dx`` is default None, it can be set to "kernel_layer," "bias_layer," or "input_layer" --> then the return will be d output w.r.t dx, of shape (batch_size, dx_height, dx_width, dx_in_channels)
if ``dx`` is None, returns output of shape (batch_size, fmap_rows, fmap_cols, num_filters)
"""
batch_size = input_layer.shape[0]
num_filters = kernel_layer.shape[0]
kernel_rows = kernel_layer.shape[1]
kernel_cols = kernel_layer.shape[2]
if padding_fn == "same":
"""
fmap_rows == original input rows
fmap_cols == original input cols
"""
fmap_rows = input_layer.shape[1]
fmap_cols = input_layer.shape[2]
elif padding_fn == "valid":
"""
fmap_rows == ((in_height - filter_height)/stride_height) + 1
fmap_cols == ((in_width - filter_width)/stride_width) + 1
"""
fmap_rows = int(((input_layer.shape[1] - kernel_layer.shape[1]) / stride_size[0]) + 1)
fmap_cols = int(((input_layer.shape[2] - kernel_layer.shape[2]) / stride_size[1]) + 1)
fmaps_layer = np.zeros((batch_size, fmap_rows, fmap_cols, num_filters))
inputs = pad_input_layer(input_layer, kernel_layer, stride_size, padding_fn)
if dx == "input_layer":
dx_layer = np.zeros(inputs.shape)
elif dx == "kernel_layer":
dx_layer = np.zeros(kernel_layer.shape)
for inputs_idx in range(batch_size):
for kernel_idx in range(num_filters):
fmap = np.zeros((fmap_rows, fmap_cols))
for row in range(fmap_rows):
for col in range(fmap_cols):
cur_row = (stride_size[0] * row)
cur_col = (stride_size[1] * col)
image_section = inputs[inputs_idx, cur_row:(kernel_rows + cur_row), cur_col:(kernel_cols + cur_col)]
kernel = kernel_layer[kernel_idx]
bias = bias_layer[kernel_idx]
featureZ = np.sum(np.multiply(image_section, kernel)) + bias
featureA = compute_activation_fn(featureZ, activation_fn)
fmap[row, col] = np.squeeze(featureA)
if dx == "input_layer":
dx_layer[inputs_idx, cur_row:(kernel_rows + cur_row), cur_col:(kernel_cols + cur_col), :] += kernel * compute_activation_fn_deriv(featureZ, activation_fn)
elif dx == "kernel_layer":
dx_layer[kernel_idx, :, :, :] += image_section * compute_activation_fn_deriv(featureZ, activation_fn)
fmaps_layer[inputs_idx, :, :, kernel_idx] = fmap
if dx == "input_layer":
dx_layer = convert_padded_derivs_layer(input_layer, np.array(dx_layer), kernel_layer, [2,2], padding_fn)
return dx_layer
elif dx == "kernel_layer":
return dx_layer
elif dx == None:
return fmaps_layer
#print(generate_fmaps(np.random.rand(1,9,9,3), np.random.rand(2,2,2,3), np.random.rand(2,1,1,1), [2,2], "valid", "relu", dx="input_layer"))
def pool_fmaps(input_layer, pool_size, stride_size, pool_fn, padding_fn, dx=None, grad_ys=None):
"""
``input_layer`` must be of shape (batch_size, in_height, in_width, in_channels)
``pool_size`` must be of shape [pool_height, pool_width]
``stride_size`` must be of shape [stride_height, stride_width]
``pool_fn`` is the pool function used, a string that can be "max," "mean"
``padding_fn`` must be a string, "valid" or "same"
``dx`` is default None, it can be set to "input_layer" --> then the return will be d of output w.r.t dx, of shape (batch_size, dx_height, dx_width, dx_in_channels)
if ``dx`` is None, returns output of shape (batch_size, out_height, out_width, in_channels)
out_height = ((in_height - pool_height)/stride_height) + 1
out_width = ((in_width - pool_width)/stride_width) + 1
"""
batch_size = input_layer.shape[0]
in_channels = input_layer.shape[3]
if padding_fn == "same":
"""
pool_rows == original input rows
pool_cols == original input cols
"""
pool_rows = input_layer.shape[1]
pool_cols = input_layer.shape[2]
elif padding_fn == "valid":
"""
pool_rows == ((in_height - pool_height)/stride_height) + 1
pool_cols == ((in_width - pool_width)/stride_width) + 1
"""
pool_rows = int(((input_layer.shape[1] - pool_size[0]) / stride_size[0]) + 1)
pool_cols = int(((input_layer.shape[2] - pool_size[1]) / stride_size[1]) + 1)
pooled_input_layer = np.zeros((batch_size, pool_rows, pool_cols, in_channels))
padded_inputs = pad_input_layer(input_layer, pool_size, stride_size, padding_fn)
dx_layer = np.zeros(padded_inputs.shape)
for inputs_idx in range(batch_size):
for channel_idx in range(in_channels):
inputs = padded_inputs[inputs_idx, :, :, channel_idx]
pooled_inputs = np.zeros((pool_rows, pool_cols))
for row in range(pool_rows):
for col in range(pool_cols):
cur_row = (stride_size[0] * row)
cur_col = (stride_size[1] * col)
features = inputs[cur_row:(pool_size[0] + cur_row), cur_col:(pool_size[1] + cur_col)]
if pool_fn == "max":
pooled_inputs[row, col] = np.squeeze(np.amax(features))
if grad_ys == None:
np.put(dx_layer[inputs_idx, cur_row:(pool_size[0] + cur_row), cur_col:(pool_size[1] + cur_col), channel_idx], np.argmax(features), 1)
pooled_input_layer[inputs_idx,:,:, channel_idx] = pooled_inputs
if dx == "input_layer":
dx_layer = convert_padded_derivs_layer(input_layer, dx_layer, pool_size, stride_size, padding_fn)
return dx_layer
elif dx == None:
return pooled_input_layer
# # def conv_layer_backprop(kernel, delta, prev_layer, strides):
# # kernel_rows = kernel.shape[0]
# # kernel_cols = kernel.shape[1]
# # num_rows = delta.shape[0]
# # num_cols = delta.shape[1]
# # in_channels = delta.shape[2]
# # kernel_deriv = np.zeros(kernel.shape)
# # for row in range(num_rows):
# # for cols in range(num_cols):
# # cur_row = (strides[0] * row)
# # cur_col = (strides[1] * col)
# # kernel_deriv += (delta[row,col] * prev_layer[cur_row: (kernel_rows + cur_row), cur_col: (kernel_cols + cur_col)])
# # NNconv = neuralnetwork.ConvNeuralNetwork(
# # layers=["conv, pool, conv, pool"],
# # num_filters=[32, 64],
# # kernel_sizes=[[5, 5, 3], [5, 5, 32]],
# # stride_sizes=[[2, 2], [2, 2], [2, 2], [2, 2]],
# # pool_sizes=[[2, 2], [2, 2]],
# # pool_methods=["max", "mean"],
# # activations=["relu", "relu"],
# # paddings=["same", "same"]
# # )
# # NN = neuralnetwork.NeuralNetwork(sizes=[1, 512, 1], activations=["linear", "relu", "linear"], scale_method="normalize", optimizer="nadam", lr=0.001)
# inputs = np.random.rand(1, 9, 9, 1)
# kernels = np.random.rand(1, 2, 2, 1)
# biases = np.random.rand(1, 1, 1, 1)
# conv = generate_fmaps(inputs, kernels, biases, [2, 2], "valid", "relu", dx=None)
# pool = pool_fmaps(conv, [2,2], [2,2], "max", dx="input_layer")
# print(conv.shape)
# print(pool.shape)
# print(pool_fmaps(conv, [2,2], [2,2], "max"))
layer_names = ["conv", "pool", "conv", "pool"]
in_channels = [3, None, 32, None]
num_filters=[32, None, 4, None]
kernel_sizes=[[2, 2], None, [2, 2], None]
stride_sizes=[[2, 2], [2, 2], [2, 2], [2, 2]]
pool_sizes=[None, [2, 2], None, [2, 2]]
pool_fns=[None, "max", None, "max"]
activation_fns=["relu", None, "relu", None]
padding_fns = ["same", "valid", "same", "valid"]
kernel_layers = []
bias_layers = []
for layer_idx in range(len(layer_names)):
if (layer_names[layer_idx] == "conv"):
kernel_rows, kernel_cols, num_in_channels = kernel_sizes[layer_idx][0], kernel_sizes[layer_idx][1], in_channels[layer_idx]
layer_filters_num = num_filters[layer_idx]
kernel_layers.append(np.random.rand(layer_filters_num, kernel_rows, kernel_cols, num_in_channels))
bias_layers.append(np.random.rand(layer_filters_num, 1, 1, 1))
else:
kernel_layers.append(None)
bias_layers.append(None)
def conv_feedforward(input_layer, return_aLayers=True):
a = input_layer
for layer_name, kernel_layer, bias_layer, stride_size, pool_size, pool_fn, activation_fn, padding_fn in zip(layer_names, kernel_layers, bias_layers, stride_sizes, pool_sizes, pool_fns, activation_fns, padding_fns):
if layer_name == "conv":
a = generate_fmaps(a, kernel_layer, bias_layer, stride_size, padding_fn, activation_fn, dx=None)
elif layer_name == "pool":
a = pool_fmaps(a, pool_size, stride_size, pool_fn, padding_fn, dx=None)
return a
def conv_backprop(input_layer, dx="kernel_layer", dx_layer_num=1):
pools = []
kernels = []
aLayers = [input_layer]
a = input_layer
for layer_name, kernel_layer, bias_layer, stride_size, pool_size, pool_fn, activation_fn, padding_fn in zip(layer_names, kernel_layers, bias_layers, stride_sizes, pool_sizes, pool_fns, activation_fns, padding_fns):
if layer_name == "conv":
if len(aLayers) == dx_layer_num:
kernel = generate_fmaps(a, kernel_layer, bias_layer, stride_size, padding_fn, activation_fn, dx=dx)
else:
kernel = generate_fmaps(a, kernel_layer, bias_layer, stride_size, padding_fn, activation_fn, dx="input_layer")
a = generate_fmaps(a, kernel_layer, bias_layer, stride_size, padding_fn, activation_fn, dx=None)
kernels.append(kernel)
elif layer_name == "pool":
pool = pool_fmaps(a, pool_size, stride_size, pool_fn, padding_fn, dx="input_layer")
a = pool_fmaps(a, pool_size, stride_size, pool_fn, padding_fn, dx=None)
kernels.append(pool)
aLayers.append(a)
deltas = np.random.rand(1, 6, 6, 4)
#a = generate_fmaps(deltas, kernel_layers[-2], bias_layers[-2], stride_sizes[-2], padding_fns[-2], activation_fns[-2], dx=None)
for idx in range(1, len(kernels) + 1):
print(kernels[-idx].shape)
# if (layer_names[-idx] == "pool"):
# np.place(kernels[-idx], kernels[-idx] == 1, deltas)
# deltas = kernels[-idx]
# else:
# deltas = np.sum(deltas, 3)*np.sum(kernels[-idx],3)
# x = np.copy(pools[pool][:,:,0])
# after = np.place(pools[pool][:,:,0], pools[pool][:,:,0] == 1, np.random.rand)
# print(x, pools[pool][:,:,0])
print(deltas.shape)
return a
input_layer = np.random.rand(1, 24, 24, 3)
forward = conv_feedforward(input_layer)
backward = conv_backprop(input_layer, dx="kernel_layer", dx_layer_num=1)
#print(forward)
# def conv_backprop(inputs, delta):
# kernel_derivs = np.zeros((kernel_layers.shape))
# bias_derivs = np.zeros((bias_layers.shape))
# aLayers = conv_feedforward(inputs, return_aLayers=True)
# for l in range(1, len(layer_names)):
# if layer_names[-l] == "pool":
# delta *= pool_fmaps(aLayers[-l-1], return_input_derivs=True)
# inputs = np.random.rand(14, 28, 28, 3)
# kernel_layers = []
# biase_layers = []
# for num_filters, kernel_size, padding_method in zip(num_filters, kernel_sizes, paddings):
# kernel_size = kernel_size
# if padding_method == "same":
# bias_size
# for layer in num_filters:
# kernels = [[np.random.rand(kernel_size[0], kernel_size[1], kernel_size[2]) for _ in range(layer) for kernel_size in kernel_sizes] for layer in num_filters]
# biases = [[np.random.rand() for _ in range(layer)] for layer in num_filters]
# kernelsLayer1 = np.array([np.random.rand(5, 5, 3) for _ in range(32)])
# fmaps = generate_fmaps(inputs, kernelsLayer1, [1,1], "same")
# print(fmaps.shape)
# pooled_fmaps = pool_fmaps(fmaps, [2, 2], [2, 2])
# print(pooled_fmaps.shape)
| colinsteidtmann/EngineeringApplication | ApproximatingSine/ApproxSine/testnn9.py | testnn9.py | py | 19,009 | python | en | code | 1 | github-code | 13 |
17746481672 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by lenovo on 2019/5/13
import time
import matplotlib
from traditional.SAX.sax_variant import notify_result,esax,original_sax,sax_sd,sax_td,tsax
from traditional.SAX.sax_knn import sax
import os
from collections import Counter
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import roc_auc_score, precision_score, recall_score, f1_score, mean_squared_error
def result_write(name,best_win,precision,recall,f1,auc,error,t):
with open('../SAXresult/ESAX_result.txt','a') as result:
result.write('name: %s, win_size: %d, Precision: %f, Recall: %f, F1: %f, auc: %f, error: %f , time: %f' % \
(name, best_win, precision, recall, f1, auc, error, t))
result.write('\n')
def main():
filedir='../../data/UCRtwoclass/'
for name in os.listdir(filedir):
print(name)
data = np.loadtxt('../../data/UCRtwoclass/'+name, delimiter=',')
labels = data[:, 0]
c=Counter(labels)
print(c)
b = zip(c.values(), c.keys())
c = list(sorted(b))
labels = np.where(labels == c[1][1], 1, 0)
data = data[:, 1:]
rows, cols = data.shape
# parameters
k=3
alphabetSize = 3
max_auc = 0
#win_size是段中时间点的个数
for win_size in range(4,20):
trainBeginTime = time.clock()
raw_dist, pred = esax(data, win_size, alphabetSize, k, labels)
trainEndTime = time.clock()
preanomaly = list()
trueanomaly = list()
# for i in range(rows): #1为normal ,0 为abnormal
# if labels[i] != 1.0:
# labels[i] = 0
# trueanomaly.append(i)
# if pred[i] != 1.0:
# pred[i] = 0
# preanomaly.append(i)
# result
last_time = trainEndTime - trainBeginTime
auc = roc_auc_score(labels, pred)
if max_auc < auc:
max_auc = auc
best_win = win_size
precision = precision_score(labels, pred, average='macro')
recall = recall_score(labels, pred, average='macro')
f1 = f1_score(labels, pred, average='macro')
t = last_time
error = mean_squared_error(labels, pred)
print('name: %s, win_size: %d, Precision: %f, Recall: %f, F1: %f, auc: %f, error: %f , time: %f' % \
(name, best_win, precision, recall, f1, auc, error, t))
result_write(name, best_win, precision, recall, f1, auc, error, t)
if __name__ == '__main__':
# print('esax')
main() | inkky/FinalCode | traditional/SAX/sax_main.py | sax_main.py | py | 2,825 | python | en | code | 0 | github-code | 13 |
71182814419 | import glob
import sys
import numpy as np
sys.path.append('..')
from multivar_lstm.models import baseline_model
from multivar_lstm.lstm_data_generator import get_lstm_sub_data
import time
def main():
dirpath = sys.argv[1]
modelpath = 'movie_w2v_mincount_model.model'
file_list = glob.glob(dirpath+'/*')
model = baseline_model(shape=(1000, 10, 118), batch_size=1000)
epochs = int(sys.argv[2])
batch_size = 1000
rate = int(len(file_list)*0.6)
train_file_list = file_list[:rate]
test_file_list = file_list[rate:-1]
val_file = file_list[-1]
for epoch in range(epochs):
st = time.time()
for train_file in train_file_list:
print('{} / {} {}'.format(epoch, epochs, train_file))
train_X, train_y = get_lstm_sub_data(train_file, modelpath)
model.fit(train_X, train_y, batch_size=batch_size, epochs=1)
val_X, val_y = get_lstm_sub_data(val_file, modelpath)
print()
print(model.evaluate(val_X[:10000], val_y[:10000], batch_size=batch_size))
et = time.time()
print(epoch,'is done time needed ',et - st ,'sec')
test_results = []
for test_file in test_file_list:
test_X, test_y = get_lstm_sub_data(test_file, modelpath)
test_results.append(model.evaluate(test_X, test_y, batch_size=batch_size)[1])
print(np.mean(test_results))
model_json = model.to_json()
with open("model/model.json","w") as json_file:
json_file.write(model_json)
model.save_weights("model.h5")
print("saved model")
if __name__ == '__main__':
main()
| junwoopark92/2018-SK-TnB-CodeChallenge | multivar_lstm/04.train.py | 04.train.py | py | 1,616 | python | en | code | 1 | github-code | 13 |
42225949736 | ANSIBLE_METADATA = {'status': ['stableinterface'],
'supported_by': 'community',
'metadata_version': '1.1'}
DOCUMENTATION = '''
---
module: oneview_id_pools
short_description: Manage OneView Id Pools.
description:
- Provides an interface to manage Id pools. Can retrieve, update.
version_added: "2.4"
requirements:
- "python >= 3.4.2"
- "hpeOneView >= 6.0.0"
author: "Yuvarani Chidambaram(@yuvirani)"
options:
state:
description:
- Indicates the desired state for the ID Pools resource.
C(schema) will fetch the schema of the ID Pool
C(get_pool_type) will get ID pool
C(validate_id_pool) will validates the list of ID's from IPv4 Subnet.
C(generate) will generate random ID's list.
C(checkrangeavailability) will verify the available range of ID's list.
choices: ['schema', 'get_pool_type', 'validate_id_pool', 'generate', 'check_range_availability']
data:
description:
- dict with required params.
required: true
extends_documentation_fragment:
- oneview
- oneview.validateetag
'''
EXAMPLES = '''
- name: Get schema of the id pools
oneview_id_pools:
config: "{{ config }}"
state: schema
data:
description: 'ID pool schema'
delegate_to: localhost
- name: Generates a random range
oneview_id_pools:
config: "{{ config }}"
state: generate
data:
poolType: '{{ poolType }}'
delegate_to: localhost
- name: Get the ID Pools type
oneview_id_pools:
config: "{{ config }}"
state: get_pool_type
data:
poolType: '{{ poolType }}'
delegate_to: localhost
- debug: var=id_pool
- name: Checks the range availability in the ID pool
oneview_id_pools:
config: "{{ config }}"
state: check_range_availability
data:
poolType: '{{ poolType }}'
idList: '{{ id_pool["idList"] }}'
delegate_to: localhost
- name: Validates the list of ID's from IPv4 Subnet
oneview_id_pools:
config: "{{ config }}"
state: validate_id_pool
data:
poolType: 'ipv4'
idList: ['172.18.9.11']
delegate_to: localhost
'''
RETURN = '''
id_pool:
description: Has the facts about the Id Pools.
returned: On all states
type: dict
'''
from ansible.module_utils.oneview import OneViewModule
class IdPoolsFactsModule(OneViewModule):
def __init__(self):
argument_spec = dict(
state=dict(
required=True,
choices=['generate', 'validate_id_pool', 'check_range_availability', 'get_pool_type', 'schema']
),
data=dict(required=True, type='dict'),
)
super(IdPoolsFactsModule, self).__init__(additional_arg_spec=argument_spec, validate_etag_support=True)
self.set_resource_object(self.oneview_client.id_pools)
def execute_module(self):
ansible_facts, id_pool = {}, {}
poolType = self.data.pop('poolType', '')
idList = self.data.pop('idList', [])
if self.state == 'schema':
id_pool = self.resource_client.get_schema()
elif self.state == 'get_pool_type':
id_pool = (self.resource_client.get_pool_type(poolType))
elif self.state == 'generate':
id_pool = (self.resource_client.generate(poolType))
elif self.state == 'validate_id_pool':
id_pool = self.resource_client.validate_id_pool(poolType, idList)
elif self.state == 'check_range_availability':
id_pool = self.resource_client.get_check_range_availability(poolType, idList)
if type(id_pool) is not dict:
id_pool = id_pool.data
ansible_facts['id_pool'] = id_pool
return dict(changed=False, ansible_facts=ansible_facts)
def main():
IdPoolsFactsModule().run()
if __name__ == '__main__':
main()
| HewlettPackard/oneview-ansible | library/oneview_id_pools_facts.py | oneview_id_pools_facts.py | py | 3,898 | python | en | code | 103 | github-code | 13 |
16128788303 | #!/usr/bin/python
"""
Purpose:
"""
import turtle
def drawLight(T, S, c):
T.speed(1000)
S.clear()
T.penup()
T.setpos(0, 0)
T.pensize(12)
if c == 1:
T.color("black", "orange")
else:
T.color("black", "gray")
T.pendown()
T.begin_fill()
T.circle(50)
T.end_fill()
T.penup()
T.setpos(0, 210)
if c == 0:
T.color("black", "red")
else:
T.color("black", "gray")
T.pendown()
T.begin_fill()
T.circle(50)
T.end_fill()
T.penup()
T.setpos(0, -210)
if c == 2:
T.color("black", "green")
else:
T.color("black", "gray")
T.pendown()
T.begin_fill()
T.circle(50)
T.end_fill()
T.penup()
T.hideturtle()
S = turtle.Screen()
T = turtle.Turtle()
i = 1 # int(input("Enter color number\n"))
drawLight(T, S, i)
S.exitonclick()
| udhayprakash/PythonMaterial | python3/10_Modules/15_turtle_module/traffic_light2.py | traffic_light2.py | py | 865 | python | en | code | 7 | github-code | 13 |
28989882654 | '''
https://practice.geeksforgeeks.org/problems/longest-even-length-substring/0/
'''
testCases = int(input())
for case in range(testCases):
digits = input()
size = len(digits)
sslen = size if size%2==0 else size-1
#print(sslen)
while sslen > 1:
i = 0
while i+sslen <= size:
substring = digits[i:i+sslen]
leftSum = 0
rightSum = 0
for left in range(0,sslen//2,1): rightSum = rightSum + int(substring[left])
for right in range(sslen-1,(sslen//2)-1,-1): leftSum = leftSum + int(substring[right])
if rightSum == leftSum:
print(sslen)
sslen = 1
break
else:
i+=1
sslen-=2
if sslen == 0: print(0) | riddheshSajwan/data_structures_algorithm | strings/longestEvenLengthSubstring.py | longestEvenLengthSubstring.py | py | 784 | python | en | code | 1 | github-code | 13 |
12584048870 | #! /usr/bin/env python
import tsys01
from time import sleep
from sensor_connect.msg import sensor
import rospy
sensor_data = tsys01.TSYS01()
if not sensor_data.init():
print("Error initializing sensor")
exit(1)
pub = rospy.Publisher('data12',sensor,queue_size=20)
rospy.init_node('sender',anonymous=True)
rate = rospy.Rate(1)
while True:
if not sensor_data.read():
print("Error reading sensor")
exit(1)
data = sensor_data.temperature()
print("Temperature:",data)
sens =sensor()
sens.sensor1 = data
#print(type(sensor_data.temperature()))
pub.publish(sens)
sleep(2)
| pokasta/Thrustercontrol-via-python | ros.py | ros.py | py | 635 | python | en | code | 0 | github-code | 13 |
71067840978 | from win32com.client.gencache import EnsureDispatch, EnsureModule
from win32com.client import CastTo, constants
import os
import matplotlib.pyplot as plt
import numpy as np
# Notes
#
# The python project and script was tested with the following tools:
# Python 3.4.3 for Windows (32-bit) (https://www.python.org/downloads/) - Python interpreter
# Python for Windows Extensions (32-bit, Python 3.4) (http://sourceforge.net/projects/pywin32/) - for COM support
# Microsoft Visual Studio Express 2013 for Windows Desktop (https://www.visualstudio.com/en-us/products/visual-studio-express-vs.aspx) - easy-to-use IDE
# Python Tools for Visual Studio (https://pytools.codeplex.com/) - integration into Visual Studio
#
# Note that Visual Studio and Python Tools make development easier, however this python script should should run without either installed.
class PythonStandaloneApplication(object):
class LicenseException(Exception):
pass
class ConnectionException(Exception):
pass
class InitializationException(Exception):
pass
class SystemNotPresentException(Exception):
pass
def __init__(self):
# make sure the Python wrappers are available for the COM client and
# interfaces
EnsureModule('ZOSAPI_Interfaces', 0, 1, 0)
# Note - the above can also be accomplished using 'makepy.py' in the
# following directory:
# {PythonEnv}\Lib\site-packages\wind32com\client\
# Also note that the generate wrappers do not get refreshed when the
# COM library changes.
# To refresh the wrappers, you can manually delete everything in the
# cache directory:
# {PythonEnv}\Lib\site-packages\win32com\gen_py\*.*
self.TheConnection = EnsureDispatch("ZOSAPI.ZOSAPI_Connection")
if self.TheConnection is None:
raise PythonStandaloneApplication.ConnectionException("Unable to intialize COM connection to ZOSAPI")
self.TheApplication = self.TheConnection.CreateNewApplication()
if self.TheApplication is None:
raise PythonStandaloneApplication.InitializationException("Unable to acquire ZOSAPI application")
if self.TheApplication.IsValidLicenseForAPI == False:
raise PythonStandaloneApplication.LicenseException("License is not valid for ZOSAPI use")
self.TheSystem = self.TheApplication.PrimarySystem
if self.TheSystem is None:
raise PythonStandaloneApplication.SystemNotPresentException("Unable to acquire Primary system")
def __del__(self):
if self.TheApplication is not None:
self.TheApplication.CloseApplication()
self.TheApplication = None
self.TheConnection = None
def OpenFile(self, filepath, saveIfNeeded):
if self.TheSystem is None:
raise PythonStandaloneApplication.SystemNotPresentException("Unable to acquire Primary system")
self.TheSystem.LoadFile(filepath, saveIfNeeded)
def CloseFile(self, save):
if self.TheSystem is None:
raise PythonStandaloneApplication.SystemNotPresentException("Unable to acquire Primary system")
self.TheSystem.Close(save)
def SamplesDir(self):
if self.TheApplication is None:
raise PythonStandaloneApplication.InitializationException("Unable to acquire ZOSAPI application")
return self.TheApplication.SamplesDir
def ExampleConstants(self):
if self.TheApplication.LicenseStatus is constants.LicenseStatusType_PremiumEdition:
return "Premium"
elif self.TheApplication.LicenseStatus is constants.LicenseStatusType_ProfessionalEdition:
return "Professional"
elif self.TheApplication.LicenseStatus is constants.LicenseStatusType_StandardEdition:
return "Standard"
else:
return "Invalid"
if __name__ == '__main__':
zosapi = PythonStandaloneApplication()
value = zosapi.ExampleConstants()
if not os.path.exists(zosapi.TheApplication.SamplesDir + "\\Samples\\API\\Python"):
os.makedirs(zosapi.TheApplication.SamplesDir + "\\Samples\\API\\Python")
TheSystem = zosapi.TheSystem
TheApplication = zosapi.TheApplication
# Set up primary optical system
sampleDir = TheApplication.SamplesDir
file = "Double Gauss 28 degree field.zmx"
testFile = sampleDir + "\\Samples\\Sequential\\Objectives\\" + file
TheSystem.LoadFile(testFile, False)
#! [e22s01_py]
# Set up Batch Ray Trace
raytrace = TheSystem.Tools.OpenBatchRayTrace()
nsur = TheSystem.LDE.NumberOfSurfaces
max_rays = 30
normUnPolData = raytrace.CreateNormUnpol((max_rays + 1) * (max_rays + 1), constants.RaysType_Real, nsur)
#! [e22s01_py]
#! [e22s02_py]
# Define batch ray trace constants
hx = 0.0
max_wave = TheSystem.SystemData.Wavelengths.NumberOfWavelengths
num_fields = TheSystem.SystemData.Fields.NumberOfFields
hy_ary = np.array([0, 0.707, 1])
#! [e22s02_py]
# Initialize x/y image plane arrays
x_ary = np.empty((num_fields, max_wave, ((max_rays + 1) * (max_rays + 1))))
y_ary = np.empty((num_fields, max_wave, ((max_rays + 1) * (max_rays + 1))))
#! [e22s03_py]
# Determine maximum field in Y only
max_field = 0.0
for i in range(1, num_fields + 1):
if (TheSystem.SystemData.Fields.GetField(i).Y > max_field):
max_field = TheSystem.SystemData.Fields.GetField(i).Y
plt.rcParams["figure.figsize"] = (15, 4)
colors = ('b', 'g', 'r', 'c', 'm', 'y', 'k')
if TheSystem.SystemData.Fields.GetFieldType() == constants.FieldType_Angle:
field_type = 'Angle'
elif TheSystem.SystemData.Fields.GetFieldType() == constants.FieldType_ObjectHeight:
field_type = 'Height'
elif TheSystem.SystemData.Fields.GetFieldType() == constants.FieldType_ParaxialImageHeight:
field_type = 'Height'
elif TheSystem.SystemData.Fields.GetFieldType() == constants.FieldType_RealImageHeight:
field_type = 'Height'
#tic
for field in range(1, len(hy_ary) + 1):
plt.subplot(1, 3, field, aspect='equal').set_title('Hy: %.2f (%s)' % (hy_ary[field - 1] * max_field, field_type))
for wave in range(1, max_wave + 1):
#! [e22s04_py]
# Adding Rays to Batch, varying normalised object height hy
normUnPolData.ClearData()
waveNumber = wave
#for i = 1:((max_rays + 1) * (max_rays + 1))
for i in range(1, (max_rays + 1) * (max_rays + 1) + 1):
px = np.random.random() * 2 - 1
py = np.random.random() * 2 - 1
while (px*px + py*py > 1):
py = np.random.random() * 2 - 1
normUnPolData.AddRay(waveNumber, hx, hy_ary[field - 1], px, py, constants.OPDMode_None)
#! [e22s04_py]
baseTool = CastTo(raytrace, 'ISystemTool')
baseTool.RunAndWaitForCompletion()
#! [e22s05_m]
# Read batch raytrace and display results
normUnPolData.StartReadingResults()
output = normUnPolData.ReadNextResult()
while output[0]: # success
if ((output[2] == 0) and (output[3] == 0)): # ErrorCode & vignetteCode
x_ary[field - 1, wave - 1, output[1] - 1] = output[4] # X
y_ary[field - 1, wave - 1, output[1] - 1] = output[5] # Y
output = normUnPolData.ReadNextResult()
#! [e22s05_m]
temp = plt.plot(np.squeeze(x_ary[field - 1, wave - 1, :]), np.squeeze(y_ary[field - 1, wave - 1, :]), '.', ms = 1, color = colors[wave - 1])
#toc
plt.suptitle('Spot Diagram: %s' % (os.path.basename(testFile)))
plt.subplots_adjust(wspace=0.8)
plt.draw()
#! [e22s06_py]
# Spot Diagram Analysis Results
spot = TheSystem.Analyses.New_Analysis(constants.AnalysisIDM_StandardSpot)
spot_setting = spot.GetSettings()
baseSetting = CastTo(spot_setting, 'IAS_Spot')
baseSetting.Field.SetFieldNumber(0)
baseSetting.Wavelength.SetWavelengthNumber(0)
baseSetting.ReferTo = constants.ReferTo_Centroid
#! [e22s06_py]
#! [e22s07_py]
# extract RMS & Geo spot size for field points
base = CastTo(spot, 'IA_')
base.ApplyAndWaitForCompletion()
#spot_results = spot.GetResults()
spot_results = base.GetResults()
print('RMS radius: %6.3f %6.3f %6.3f' % (spot_results.SpotData.GetRMSSpotSizeFor(1, 1), spot_results.SpotData.GetRMSSpotSizeFor(2, 1), spot_results.SpotData.GetRMSSpotSizeFor(3, 1)))
print('GEO radius: %6.3f %6.3f %6.3f' % (spot_results.SpotData.GetGeoSpotSizeFor(1, 1), spot_results.SpotData.GetGeoSpotSizeFor(2, 1), spot_results.SpotData.GetGeoSpotSizeFor(3, 1)))
#! [e22s07_py]
# This will clean up the connection to OpticStudio.
# Note that it closes down the server instance of OpticStudio, so you for maximum performance do not do
# this until you need to.
del zosapi
zosapi = None
# place plt.show() after clean up to release OpticStudio from memory
plt.show() | eseguraca6/slacecodes | SAMPLES ZEMAX/ZOSAPI Help-2/Python/e22_seq_spot_diagram.py | e22_seq_spot_diagram.py | py | 9,467 | python | en | code | 2 | github-code | 13 |
13520698806 | from __future__ import absolute_import
import re
from datetime import date
from mozregression.errors import UnavailableRelease
from mozregression.network import retry_get
def releases():
"""
Provide the list of releases with their associated dates.
The date is a string formated as "yyyy-mm-dd", and the release an integer.
"""
# The dates comes from from https://wiki.mozilla.org/RapidRelease/Calendar,
# using the ones in the "beta" column (formerly "aurora"). This is because
# the merge date for beta corresponds to the last nightly for that
# release. See bug 996812.
releases = {
5: "2011-04-12",
6: "2011-05-24",
7: "2011-07-05",
8: "2011-08-16",
9: "2011-09-27",
10: "2011-11-08",
11: "2011-12-20",
12: "2012-01-31",
13: "2012-03-13",
14: "2012-04-24",
15: "2012-06-05",
16: "2012-07-16",
17: "2012-08-27",
18: "2012-10-08",
19: "2012-11-19",
20: "2013-01-07",
21: "2013-02-19",
22: "2013-04-01",
23: "2013-05-13",
24: "2013-06-24",
25: "2013-08-05",
26: "2013-09-16",
27: "2013-10-28",
28: "2013-12-09",
29: "2014-02-03",
30: "2014-03-17",
31: "2014-04-28",
32: "2014-06-09",
33: "2014-07-21",
34: "2014-09-02",
35: "2014-10-13",
36: "2014-11-28",
37: "2015-01-12",
38: "2015-02-23",
39: "2015-03-30",
40: "2015-05-11",
41: "2015-06-29",
42: "2015-08-10",
43: "2015-09-21",
44: "2015-10-29",
45: "2015-12-14",
46: "2016-01-25",
47: "2016-03-07",
48: "2016-04-25",
49: "2016-06-06",
50: "2016-08-01",
51: "2016-09-19",
52: "2016-11-14",
53: "2017-01-23",
54: "2017-03-06",
55: "2017-06-12",
56: "2017-08-02",
}
def filter_tags(tag_node):
match = re.match(r"^FIREFOX_NIGHTLY_(\d+)_END$", tag_node["tag"])
return int(match.group(1)) > 56 if match else False
def map_tags(tag_node):
release = {}
merge_date = date.fromtimestamp(tag_node["date"][0] + tag_node["date"][1])
ver_match = re.search(r"_(\d+)_", tag_node["tag"])
release[int(ver_match.group(1))] = merge_date.isoformat()
return release
tags_url = "https://hg.mozilla.org/mozilla-central/json-tags"
response = retry_get(tags_url)
if response.status_code == 200:
fetched_releases = list(map(map_tags, list(filter(filter_tags, response.json()["tags"]))))
for release in fetched_releases:
releases.update(release)
return releases
def date_of_release(release):
"""
Provide the date of a release.
"""
try:
return releases()[int(release)]
except (KeyError, ValueError):
raise UnavailableRelease(release)
def tag_of_release(release):
"""
Provide the mercurial tag of a release, suitable for use in place of a hash
"""
if re.match(r"^\d+$", release):
release += ".0"
if re.match(r"^\d+\.\d(\.\d)?$", release):
return "FIREFOX_%s_RELEASE" % release.replace(".", "_")
else:
raise UnavailableRelease(release)
def tag_of_beta(release):
"""
Provide the mercurial tag of a beta release, suitable for use in place of a
hash
"""
if re.match(r"^\d+\.0b\d+$", release):
return "FIREFOX_%s_RELEASE" % release.replace(".", "_")
elif re.match(r"^\d+(\.0)?$", release):
return "FIREFOX_RELEASE_%s_BASE" % release.replace(".0", "")
else:
raise UnavailableRelease(release)
def formatted_valid_release_dates():
"""
Returns a formatted string (ready to be printed) representing
the valid release dates.
"""
message = "Valid releases: \n"
for key, value in releases().items():
message += "% 3s: %s\n" % (key, value)
return message
| mozilla/mozregression | mozregression/releases.py | releases.py | py | 4,023 | python | en | code | 165 | github-code | 13 |
34949074622 | import socket
import sys
import os
import select
address = ("3.134.100.18", 9999)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
os.system("clear")
usrname = input("CloudChat v0.0.1\n\nenter a username: ")
sock.connect(address)
connectMsg = usrname + " has connected.\n"
sock.send(connectMsg.encode('ascii'))
while 1:
sockets = [sys.stdin, sock]
rsocks, wsock, errsock = select.select(sockets, [], [])
for rsock in rsocks:
if rsock==sock:
message = rsock.recv(2048).decode('ascii')
print(message)
else:
message = sys.stdin.readline()
sock.send((usrname + ": " + message).encode('ascii'))
sys.stdout.write("YOU: " + message)
sys.stdout.flush()
sock.close()
| rcparent17/Cloud-Computing | chat/client.py | client.py | py | 721 | python | en | code | 0 | github-code | 13 |
8804434596 | """
숫자 맞추기 게임
1 부터 100까지의 임의의 수를 생성하고 내가 수를 입력하면 그 숫자가 up or down을 알려줘서 몇번만에 맞추는지 점수를 얻는 게임
"""
# 책 없이 도전
import random
def Rand_Game():
Try = 0
n = random.randint(0,100)
while True:
try:
m = int(input("100 이하의 숫자를 입력하세요: "))
except:
print("숫자가 아닙니다")
Try = 0
break
Try += 1
if m == n:
break
elif m < n:
print("Up")
else:
print("Down")
return str(Try) + "점"
print(Rand_Game())
# 책에 있는 코드
random_number = random.randint(1,100)
game_count = 1
while True:
try:
my_number = int(input('1 ~ 100 사이의 숫자를 입력하세요: '))
if my_number > random_number:
print('다운')
elif my_number < random_number:
print('업')
elif my_number == random_number:
print(f" 축하합니다.{game_count}회 만에 맞췄습니다.")
break
game_count = game_count + 1
except:
print("에러가 발생하였습니다. 숫자를 입력하세요 ")
"""
생각보다 코드가 비슷해서 뿌듯.
물론 내가 def를 사용해서 그런것도 있지만 내 코드가 좀 더 너저분함을 느낌
""" | Chung-SungWoong/Practice_Python | Project1_RanNum.py | Project1_RanNum.py | py | 1,414 | python | ko | code | 0 | github-code | 13 |
70370149138 | import json
import boto3
import os
from aws_lambda_powertools import Logger
from aws_lambda_powertools.utilities.data_classes import APIGatewayProxyEvent
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
import tempfile
import joblib
s3 = boto3.client('s3')
logger = Logger(service="training")
BUCKET_NAME = os.environ['BUCKET_NAME']
model_name = 'model.joblib'
def _upload_model_to_s3(model, model_key):
with tempfile.TemporaryFile() as fp:
joblib.dump(model, fp)
fp.seek(0)
s3.upload_fileobj(fp, BUCKET_NAME, model_key)
def _train_regression_model(X_train, y_train):
# Create linear regression object
regr = linear_model.LinearRegression()
# Train the model using the training sets
regr.fit(X_train, y_train)
return regr
def _test_model(model, X_test, y_test):
# Make predictions using the testing set
y_pred = model.predict(X_test)
# calculate quality coefficients
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
return mse, r2
def _parse_input(event):
# extract input data from event
data = event.get('body')
d = json.loads(data)
print('data', d.get("data"))
logger.info(d)
X = d["data"]['X']
y = d["data"]['y']
# Split the data into training/testing sets
X_train = X[:-20]
X_test = X[-20:]
# Split the targets into training/testing sets
y_train = y[:-20]
y_test = y[-20:]
return X_train, X_test, y_train, y_test
# Lambda handler code
@logger.inject_lambda_context
def lambda_handler(event, _):
event = APIGatewayProxyEvent(event)
print(f'bucketname: {BUCKET_NAME}')
logger.info(event.__dict__)
# parse input event and split dataset
X_train, X_test, y_train, y_test = _parse_input(event)
# train regression model
regr = _train_regression_model(X_train, y_train)
# test model
mse, r2 = _test_model(regr, X_test, y_test)
logger.info({
"message": "model training successful",
'mean_squared_error': mse,
'r_squared': r2
})
# save trained model to s3
_upload_model_to_s3(regr, model_name)
logger.info({
"message": "model saved to s3",
'bucket_name': BUCKET_NAME,
'model_name': model_name
})
return {
'statusCode': 200,
'body': json.dumps(
{
'training': 'success',
'mean_squared_error': mse,
'r_squared': r2
}
)
}
| aws-samples/aws-lambda-docker-serverless-inference | online-machine-learning-aws-lambda/app/lambda_training/app.py | app.py | py | 2,530 | python | en | code | 87 | github-code | 13 |
40144992634 | from copy import deepcopy
from multiprocessing import Pool
from autode.transition_states.base import get_displaced_atoms_along_mode
from autode.transition_states.base import TSbase
from autode.transition_states.templates import TStemplate
from autode.input_output import atoms_to_xyz_file
from autode.calculation import Calculation
from autode.config import Config
from autode.exceptions import AtomsNotFound, NoNormalModesFound
from autode.geom import get_distance_constraints
from autode.geom import calc_heavy_atom_rmsd
from autode.log import logger
from autode.methods import get_hmethod
from autode.mol_graphs import set_active_mol_graph
from autode.mol_graphs import get_truncated_active_mol_graph
from autode.utils import requires_atoms, requires_graph
class TransitionState(TSbase):
@requires_graph()
def _update_graph(self):
"""Update the molecular graph to include all the bonds that are being
made/broken"""
if self.bond_rearrangement is None:
logger.warning('Bond rearrangement not set - molecular graph '
'updating with no active bonds')
active_bonds = []
else:
active_bonds = self.bond_rearrangement.all
set_active_mol_graph(species=self, active_bonds=active_bonds)
logger.info(f'Molecular graph updated with active bonds')
return None
def _run_opt_ts_calc(self, method, name_ext):
"""Run an optts calculation and attempt to set the geometry, energy and
normal modes"""
if self.bond_rearrangement is None:
logger.warning('Cannot add redundant internal coordinates for the '
'active bonds with no bond rearrangement')
bond_ids = None
else:
bond_ids = self.bond_rearrangement.all
self.optts_calc = Calculation(name=f'{self.name}_{name_ext}',
molecule=self,
method=method,
n_cores=Config.n_cores,
keywords=method.keywords.opt_ts,
bond_ids_to_add=bond_ids,
other_input_block=method.keywords.optts_block)
self.optts_calc.run()
if not self.optts_calc.optimisation_converged():
if self.optts_calc.optimisation_nearly_converged():
logger.info('Optimisation nearly converged')
self.calc = self.optts_calc
if self.could_have_correct_imag_mode():
logger.info('Still have correct imaginary mode, trying '
'more optimisation steps')
self.atoms = self.optts_calc.get_final_atoms()
self.optts_calc = Calculation(name=f'{self.name}_{name_ext}_reopt',
molecule=self,
method=method,
n_cores=Config.n_cores,
keywords=method.keywords.opt_ts,
bond_ids_to_add=bond_ids,
other_input_block=method.keywords.optts_block)
self.optts_calc.run()
else:
logger.info('Lost imaginary mode')
else:
logger.info('Optimisation did not converge')
try:
self.imaginary_frequencies = self.optts_calc.get_imaginary_freqs()
self.atoms = self.optts_calc.get_final_atoms()
self.energy = self.optts_calc.get_energy()
except (AtomsNotFound, NoNormalModesFound):
logger.error('Transition state optimisation calculation failed')
return
def _generate_conformers(self, n_confs=None):
"""Generate conformers at the TS """
from autode.conformers.conformer import Conformer
from autode.conformers.conf_gen import get_simanl_atoms
from autode.conformers.conformers import conf_is_unique_rmsd
n_confs = Config.num_conformers if n_confs is None else n_confs
self.conformers = []
distance_consts = get_distance_constraints(self)
with Pool(processes=Config.n_cores) as pool:
results = [pool.apply_async(get_simanl_atoms, (self, distance_consts, i))
for i in range(n_confs)]
conf_atoms_list = [res.get(timeout=None) for res in results]
for i, atoms in enumerate(conf_atoms_list):
conf = Conformer(name=f'{self.name}_conf{i}', charge=self.charge,
mult=self.mult, atoms=atoms,
dist_consts=distance_consts)
# If the conformer is unique on an RMSD threshold
if conf_is_unique_rmsd(conf, self.conformers):
conf.solvent = self.solvent
conf.graph = deepcopy(self.graph)
self.conformers.append(conf)
logger.info(f'Generated {len(self.conformers)} conformer(s)')
return None
@requires_atoms()
def print_imag_vector(self, mode_number=6, name=None):
"""Print a .xyz file with multiple structures visualising the largest
magnitude imaginary mode
Keyword Arguments:
mode_number (int): Number of the normal mode to visualise,
6 (default) is the lowest frequency vibration
i.e. largest magnitude imaginary, if present
name (str):
"""
assert self.optts_calc is not None
name = self.name if name is None else name
disp = -0.5
for i in range(40):
atoms = get_displaced_atoms_along_mode(calc=self.optts_calc,
mode_number=int(mode_number),
disp_magnitude=disp,
atoms=self.atoms)
atoms_to_xyz_file(atoms=atoms,
filename=f'{name}.xyz',
append=True)
# Add displacement so the final set of atoms are +0.5 Å displaced
# along the mode, then displaced back again
sign = 1 if i < 20 else -1
disp += sign * 1.0 / 20.0
return None
@requires_atoms()
def optimise(self, name_ext='optts'):
"""Optimise this TS to a true TS """
logger.info(f'Optimising {self.name} to a transition state')
self._run_opt_ts_calc(method=get_hmethod(), name_ext=name_ext)
# A transition state is a first order saddle point i.e. has a single
# imaginary frequency
if len(self.imaginary_frequencies) == 1:
logger.info('Found a TS with a single imaginary frequency')
return
if len(self.imaginary_frequencies) == 0:
logger.error('Transition state optimisation did not return any '
'imaginary frequencies')
return
if all([freq > -50 for freq in self.imaginary_frequencies[1:]]):
logger.warning('Had small imaginary modes - not displacing along')
return
# There is more than one imaginary frequency. Will assume that the most
# negative is the correct mode..
for disp_magnitude in [1, -1]:
logger.info('Displacing along second imaginary mode to try and '
'remove')
dis_name_ext = name_ext + '_dis' if disp_magnitude == 1 else name_ext + '_dis2'
atoms, energy, calc = deepcopy(self.atoms), deepcopy(self.energy), deepcopy(self.optts_calc)
self.atoms = get_displaced_atoms_along_mode(self.optts_calc,
mode_number=7,
disp_magnitude=disp_magnitude)
self._run_opt_ts_calc(method=get_hmethod(), name_ext=dis_name_ext)
if len(self.imaginary_frequencies) == 1:
logger.info('Displacement along second imaginary mode '
'successful. Now have 1 imaginary mode')
break
self.optts_calc = calc
self.atoms = atoms
self.energy = energy
self.imaginary_frequencies = self.optts_calc.get_imaginary_freqs()
return None
def calc_g_cont(self, method=None, calc=None, temp=None):
"""Calculate the free energy (G) contribution"""
return super().calc_g_cont(method=method, calc=self.optts_calc,
temp=temp)
def calc_h_cont(self, method=None, calc=None, temp=None):
"""Calculate the enthalpy (H) contribution"""
return super().calc_h_cont(method=method, calc=self.optts_calc,
temp=temp)
def find_lowest_energy_ts_conformer(self, rmsd_threshold=None):
"""Find the lowest energy transition state conformer by performing
constrained optimisations"""
logger.info('Finding lowest energy TS conformer')
atoms, energy = deepcopy(self.atoms), deepcopy(self.energy)
calc = deepcopy(self.optts_calc)
hmethod = get_hmethod() if Config.hmethod_conformers else None
self.find_lowest_energy_conformer(hmethod=hmethod)
# Remove similar TS conformer that are similar to this TS based on root
# mean squared differences in their structures
thresh = Config.rmsd_threshold if rmsd_threshold is None else rmsd_threshold
self.conformers = [conf for conf in self.conformers if
calc_heavy_atom_rmsd(conf.atoms, atoms) > thresh]
logger.info(f'Generated {len(self.conformers)} unique (RMSD > '
f'{thresh} Å) TS conformer(s)')
# Optimise the lowest energy conformer to a transition state - will
# .find_lowest_energy_conformer will have updated self.atoms etc.
if len(self.conformers) > 0:
self.optimise(name_ext='optts_conf')
if self.is_true_ts() and self.energy < energy:
logger.info('Conformer search successful')
return None
# Ensure the energy has a numerical value, so a difference can be
# evaluated
self.energy = self.energy if self.energy is not None else 0
logger.warning(f'Transition state conformer search failed '
f'(∆E = {energy - self.energy:.4f} Ha). Reverting')
logger.info('Reverting to previously found TS')
self.atoms = atoms
self.energy = energy
self.optts_calc = calc
self.imaginary_frequencies = calc.get_imaginary_freqs()
return None
def is_true_ts(self):
"""Is this TS a 'true' TS i.e. has at least on imaginary mode in the
hessian and is the correct mode"""
if self.energy is None:
logger.warning('Cannot be true TS with no energy')
return False
if len(self.imaginary_frequencies) > 0:
if self.has_correct_imag_mode(calc=self.optts_calc):
logger.info('Found a transition state with the correct '
'imaginary mode & links reactants and products')
return True
return False
def save_ts_template(self, folder_path=None):
"""Save a transition state template containing the active bond lengths,
solvent and charge in folder_path
Keyword Arguments:
folder_path (str): folder to save the TS template to
(default: {None})
"""
if self.bond_rearrangement is None:
raise ValueError('Cannot save a TS template without a bond '
'rearrangement')
logger.info(f'Saving TS template for {self.name}')
truncated_graph = get_truncated_active_mol_graph(self.graph)
for bond in self.bond_rearrangement.all:
truncated_graph.edges[bond]['distance'] = self.distance(*bond)
ts_template = TStemplate(truncated_graph, species=self)
ts_template.save(folder_path=folder_path)
logger.info('Saved TS template')
return None
def __init__(self, ts_guess):
"""
Transition State
Arguments:
ts_guess (autode.transition_states.ts_guess.TSguess):
"""
super().__init__(atoms=ts_guess.atoms,
reactant=ts_guess.reactant,
product=ts_guess.product,
name=f'TS_{ts_guess.name}',
charge=ts_guess.charge,
mult=ts_guess.mult)
self.bond_rearrangement = ts_guess.bond_rearrangement
self.conformers = None
self.optts_calc = None
self.imaginary_frequencies = []
self._update_graph()
def get_ts_object(ts_guess):
"""Creates TransitionState for the TSguess. If it is a SolvatedTSguess,
a SolvatedTransitionState is returned"""
if ts_guess.is_explicitly_solvated():
raise NotImplementedError
return TransitionState(ts_guess=ts_guess)
| Crossfoot/autodE | autode/transition_states/transition_state.py | transition_state.py | py | 13,375 | python | en | code | null | github-code | 13 |
7830888810 | from django.contrib.auth.models import User
from django.db import models
from cl.lib.model_helpers import make_path
from cl.lib.models import AbstractDateTimeModel, AbstractFile
from cl.lib.storage import IncrementingAWSMediaStorage, S3PrivateUUIDStorage
from cl.recap.constants import DATASET_SOURCES, NOO_CODES, NOS_CODES
from cl.search.models import Court, Docket, DocketEntry, RECAPDocument
class UPLOAD_TYPE:
DOCKET = 1
ATTACHMENT_PAGE = 2
PDF = 3
DOCKET_HISTORY_REPORT = 4
APPELLATE_DOCKET = 5
APPELLATE_ATTACHMENT_PAGE = 6
IA_XML_FILE = 7
CASE_REPORT_PAGE = 8
CLAIMS_REGISTER = 9
DOCUMENT_ZIP = 10
SES_EMAIL = 11
CASE_QUERY_PAGE = 12
APPELLATE_CASE_QUERY_PAGE = 13
CASE_QUERY_RESULT_PAGE = 14
APPELLATE_CASE_QUERY_RESULT_PAGE = 15
NAMES = (
(DOCKET, "HTML Docket"),
(ATTACHMENT_PAGE, "HTML attachment page"),
(PDF, "PDF"),
(DOCKET_HISTORY_REPORT, "Docket history report"),
(APPELLATE_DOCKET, "Appellate HTML docket"),
(APPELLATE_ATTACHMENT_PAGE, "Appellate HTML attachment page"),
(IA_XML_FILE, "Internet Archive XML docket"),
(CASE_REPORT_PAGE, "Case report (iquery.pl) page"),
(CLAIMS_REGISTER, "Claims register page"),
(DOCUMENT_ZIP, "Zip archive of RECAP Documents"),
(SES_EMAIL, "Email in the SES storage format"),
(CASE_QUERY_PAGE, "Case query page"),
(APPELLATE_CASE_QUERY_PAGE, "Appellate Case query page"),
(CASE_QUERY_RESULT_PAGE, "Case query result page"),
(APPELLATE_CASE_QUERY_RESULT_PAGE, "Appellate Case query result page"),
)
def make_recap_processing_queue_path(instance, filename):
return make_path("recap_processing_queue", filename)
def make_recap_data_path(instance, filename):
return make_path("recap-data", filename)
def make_recap_email_processing_queue_aws_path(instance, filename: str) -> str:
return f"recap-email/{filename}"
class PacerHtmlFiles(AbstractFile, AbstractDateTimeModel):
"""This is a simple object for holding original HTML content from PACER
We use this object to make sure that for every item we receive from users,
we can go back and re-parse it one day if we have to. This becomes
essential as we do more and more data work where we're purchasing content.
If we don't keep an original copy, a bug could be devastating.
"""
filepath = models.FileField(
help_text="The path of the original data from PACER.",
upload_to=make_recap_data_path,
storage=S3PrivateUUIDStorage(),
max_length=150,
)
upload_type = models.SmallIntegerField(
help_text="The type of object that is uploaded",
choices=UPLOAD_TYPE.NAMES,
)
class PROCESSING_STATUS:
ENQUEUED = 1
SUCCESSFUL = 2
FAILED = 3
IN_PROGRESS = 4
QUEUED_FOR_RETRY = 5
INVALID_CONTENT = 6
NEEDS_INFO = 7
NAMES = (
(ENQUEUED, "Awaiting processing in queue."),
(SUCCESSFUL, "Item processed successfully."),
(FAILED, "Item encountered an error while processing."),
(IN_PROGRESS, "Item is currently being processed."),
(QUEUED_FOR_RETRY, "Item failed processing, but will be retried."),
(INVALID_CONTENT, "Item failed validity tests."),
(NEEDS_INFO, "There was insufficient metadata to complete the task."),
)
class ProcessingQueue(AbstractDateTimeModel):
"""Where we store each RECAP upload."""
court = models.ForeignKey(
Court,
help_text="The court where the upload was from",
related_name="recap_processing_queue",
on_delete=models.RESTRICT,
)
uploader = models.ForeignKey(
User,
help_text="The user that uploaded the item to RECAP.",
related_name="recap_processing_queue",
# Normal accounts don't upload, so if you've been given access, for now
# at least, you don't get to delete your account.
on_delete=models.RESTRICT,
)
pacer_case_id = models.CharField(
help_text="The cased ID provided by PACER.",
max_length=100,
db_index=True,
blank=True,
)
pacer_doc_id = models.CharField(
help_text="The ID of the document in PACER.",
max_length=32, # Same as in RECAP
blank=True,
db_index=True,
)
document_number = models.BigIntegerField(
help_text="The docket entry number for the document.",
blank=True,
null=True,
)
attachment_number = models.SmallIntegerField(
help_text="If the file is an attachment, the number is the attachment "
"number on the docket.",
blank=True,
null=True,
)
filepath_local = models.FileField(
help_text="The path of the uploaded file.",
upload_to=make_recap_processing_queue_path,
storage=S3PrivateUUIDStorage(),
max_length=1000,
)
status = models.SmallIntegerField(
help_text="The current status of this upload. Possible values "
"are: %s"
% ", ".join(
["(%s): %s" % (t[0], t[1]) for t in PROCESSING_STATUS.NAMES]
),
default=PROCESSING_STATUS.ENQUEUED,
choices=PROCESSING_STATUS.NAMES,
db_index=True,
)
upload_type = models.SmallIntegerField(
help_text="The type of object that is uploaded",
choices=UPLOAD_TYPE.NAMES,
)
error_message = models.TextField(
help_text="Any errors that occurred while processing an item",
blank=True,
)
debug = models.BooleanField(
help_text="Are you debugging? Debugging uploads will be validated, "
"but not saved to the database.",
default=False,
)
# Post process fields
docket = models.ForeignKey(
Docket,
help_text="The docket that was created or updated by this request.",
null=True,
on_delete=models.SET_NULL,
)
docket_entry = models.ForeignKey(
DocketEntry,
help_text="The docket entry that was created or updated by this "
"request, if applicable. Only applies to PDFs uploads.",
null=True,
on_delete=models.SET_NULL,
)
recap_document = models.ForeignKey(
RECAPDocument,
help_text="The document that was created or updated by this request, "
"if applicable. Only applies to PDFs uploads.",
null=True,
on_delete=models.SET_NULL,
)
def __str__(self) -> str:
if self.upload_type in [
UPLOAD_TYPE.DOCKET,
UPLOAD_TYPE.DOCKET_HISTORY_REPORT,
UPLOAD_TYPE.APPELLATE_DOCKET,
UPLOAD_TYPE.DOCUMENT_ZIP,
]:
return "ProcessingQueue %s: %s case #%s (%s)" % (
self.pk,
self.court_id,
self.pacer_case_id,
self.get_upload_type_display(),
)
elif self.upload_type == UPLOAD_TYPE.PDF:
return "ProcessingQueue: %s: %s.%s.%s.%s (%s)" % (
self.pk,
self.court_id,
self.pacer_case_id or None,
self.document_number or None,
self.attachment_number or 0,
self.get_upload_type_display(),
)
else:
return f"ProcessingQueue: {self.pk} ({self.get_upload_type_display()})"
class Meta:
permissions = (
("has_recap_upload_access", "Can upload documents to RECAP."),
)
@property
def file_contents(self) -> str:
with open(self.filepath_local.path, "r") as f:
return f.read()
def print_file_contents(self) -> None:
print(self.file_contents)
class EmailProcessingQueue(AbstractDateTimeModel):
"""Where @recap.email emails go when received by the API"""
uploader = models.ForeignKey(
User,
help_text="The user that sent in the email for processing.",
related_name="recap_email_processing_queue",
# Normal users won't be uploading things to this API. ∴, if you've
# uploaded to it, your account is too special to delete.
on_delete=models.RESTRICT,
)
court = models.ForeignKey(
Court,
help_text="The court where the upload was from",
related_name="recap_email_processing_queue",
on_delete=models.RESTRICT,
)
message_id = models.TextField(
help_text="The S3 message identifier, used to pull the file in the processing tasks.",
default=None,
)
destination_emails = models.JSONField(
help_text="The emails that received the notification.", default=list
)
filepath = models.FileField(
help_text="The S3 filepath to the email and receipt stored as JSON text.",
upload_to=make_recap_email_processing_queue_aws_path,
storage=IncrementingAWSMediaStorage(),
max_length=300,
null=True,
)
status = models.SmallIntegerField(
help_text="The current status of this upload. Possible values "
"are: %s"
% ", ".join(
["(%s): %s" % (t[0], t[1]) for t in PROCESSING_STATUS.NAMES]
),
default=PROCESSING_STATUS.ENQUEUED,
choices=PROCESSING_STATUS.NAMES,
db_index=True,
)
status_message = models.TextField(
help_text="Any errors that occurred while processing an item",
blank=True,
)
recap_documents = models.ManyToManyField(
RECAPDocument,
related_name="recap_email_processing_queue",
help_text="Document(s) created from the PACER email, processed as a function of this queue.",
)
def __str__(self) -> str:
return f"EmailProcessingQueue: {self.pk} in court {self.court_id}"
class REQUEST_TYPE:
DOCKET = 1
PDF = 2
ATTACHMENT_PAGE = 3
NAMES = (
(DOCKET, "HTML Docket"),
(PDF, "PDF"),
(ATTACHMENT_PAGE, "Attachment Page"),
)
class PacerFetchQueue(AbstractDateTimeModel):
"""The queue of requests being made of PACER."""
date_completed = models.DateTimeField(
help_text="When the item was completed or errored out.",
db_index=True,
null=True,
blank=True,
)
user = models.ForeignKey(
User,
help_text="The user that made the request.",
related_name="pacer_fetch_queue_items",
# User accounts are not normally deleted; they're made into stubs. So,
# don't let these accounts get deleted either.
on_delete=models.RESTRICT,
)
status = models.SmallIntegerField(
help_text="The current status of this request. Possible values "
"are: %s"
% ", ".join(
["(%s): %s" % (t[0], t[1]) for t in PROCESSING_STATUS.NAMES]
),
default=PROCESSING_STATUS.ENQUEUED,
choices=PROCESSING_STATUS.NAMES,
db_index=True,
)
request_type = models.SmallIntegerField(
help_text="The type of object that is requested",
choices=REQUEST_TYPE.NAMES,
)
message = models.TextField(
help_text="Any messages that may help a user during or after "
"processing.",
blank=True,
)
#
# Shared request parameters (can be used across multiple request types)
#
court = models.ForeignKey(
Court,
help_text="The court where the request will be made",
related_name="pacer_fetch_queue_items",
on_delete=models.RESTRICT,
null=True,
)
# PDF and attachment pages use this
recap_document = models.ForeignKey(
RECAPDocument,
help_text="The ID of the RECAP Document in the CourtListener databae "
"that you wish to fetch or update.",
related_name="pacer_fetch_queue_items",
on_delete=models.SET_NULL,
null=True,
)
#
# Docket request parameters
#
docket = models.ForeignKey(
Docket,
help_text="The ID of an existing docket object in the CourtListener "
"database that should be updated.",
related_name="pacer_fetch_queue_items",
on_delete=models.SET_NULL,
null=True,
)
pacer_case_id = models.CharField(
help_text="The case ID provided by PACER for the case to update (must "
"be used in combination with the court field).",
max_length=100,
db_index=True,
blank=True,
)
docket_number = models.CharField(
help_text="The docket number of a case to update (must be used in "
"combination with the court field).",
max_length=50,
blank=True,
)
de_date_start = models.DateField(
help_text="Only fetch docket entries (de) newer than this date. "
"Default is 1 Jan. 1960. Timezone appears to be that of the "
"court.",
null=True,
blank=True,
)
de_date_end = models.DateField(
help_text="Only fetch docket entries (de) older than or equal to this "
"date. Timezone appears to be that of the court.",
null=True,
blank=True,
)
de_number_start = models.IntegerField(
help_text="Only fetch docket entries (de) >= than this value. "
"Warning: Using this parameter will not return numberless "
"entries.",
null=True,
blank=True,
)
de_number_end = models.IntegerField(
help_text="Only fetch docket entries (de) <= this value. "
"Warning: Using this parameter will not return numberless "
"entries.",
null=True,
blank=True,
)
show_parties_and_counsel = models.BooleanField(
help_text="Should we pull parties and counsel for a docket report?",
default=True,
)
show_terminated_parties = models.BooleanField(
help_text="Should we pull terminated parties and counsel as well?",
default=True,
)
show_list_of_member_cases = models.BooleanField(
help_text="Should we pull the list of member cases? This can add "
"considerable expense to each docket.",
default=False,
)
def __str__(self) -> str:
return f"{self.pk} ({self.get_request_type_display()})"
class FjcIntegratedDatabase(AbstractDateTimeModel):
"""The Integrated Database of PACER data as described here:
https://www.fjc.gov/research/idb
Most fields are simply copied across as chars, though some are normalized
if possible.
"""
ORIG = 1
REMOVED = 2
REMANDED = 3
REINSTATED = 4
TRANSFERRED = 5
MULTI_DIST = 6
APPEAL_FROM_MAG = 7
SECOND_REOPEN = 8
THIRD_REOPEN = 9
FOURTH_REOPEN = 10
FIFTH_REOPEN = 11
SIXTH_REOPEN = 12
MULTI_DIST_ORIG = 13
ORIGINS = (
(ORIG, "Original Proceeding"),
(
REMOVED,
"Removed (began in the state court, removed to the "
"district court)",
),
(
REMANDED,
"Remanded for further action (removal from court of appeals)",
),
(
REINSTATED,
"Reinstated/reopened (previously opened and closed, "
"reopened for additional action)",
),
(
TRANSFERRED,
"Transferred from another district(pursuant to 28 USC 1404)",
),
(
MULTI_DIST,
"Multi district litigation (cases transferred to this "
"district by an order entered by Judicial Panel on Multi "
"District Litigation pursuant to 28 USC 1407)",
),
(
APPEAL_FROM_MAG,
"Appeal to a district judge of a magistrate judge's decision",
),
(SECOND_REOPEN, "Second reopen"),
(THIRD_REOPEN, "Third reopen"),
(FOURTH_REOPEN, "Fourth reopen"),
(FIFTH_REOPEN, "Fifth reopen"),
(SIXTH_REOPEN, "Sixth reopen"),
(
MULTI_DIST_ORIG,
"Multi district litigation originating in the "
"district (valid beginning July 1, 2016)",
),
)
GOV_PLAIN = 1
GOV_DEF = 2
FED_Q = 3
DIV_OF_CITZ = 4
LOCAL_Q = 5
JURISDICTIONS = (
(GOV_PLAIN, "Government plaintiff"),
(GOV_DEF, "Government defendant"),
(FED_Q, "Federal question"),
(DIV_OF_CITZ, "Diversity of citizenship"),
(LOCAL_Q, "Local question"),
)
MANDATORY = "M"
VOLUNTARY = "V"
EXEMPT = "E"
YES = "Y"
ARBITRATION_CHOICES = (
(MANDATORY, "Mandatory"),
(VOLUNTARY, "Voluntary"),
(EXEMPT, "Exempt"),
(YES, "Yes, but type unknown"),
)
CLASS_ACTION_DENIED = 2
CLASS_ACTION_GRANTED = 3
CLASS_ACTION_STATUSES = (
(CLASS_ACTION_DENIED, "Denied"),
(CLASS_ACTION_GRANTED, "Granted"),
)
NO_COURT_ACTION_PRE_ISSUE_JOINED = 1
ORDER_ENTERED = 2
HEARING_HELD = 11
ORDER_DECIDED = 12
NO_COURT_ACTION_POST_ISSUE_JOINED = 3
JUDGMENT_ON_MOTION = 4
PRETRIAL_CONFERENCE_HELD = 5
DURING_COURT_TRIAL = 6
DURING_JURY_TRIAL = 7
AFTER_COURT_TRIAL = 8
AFTER_JURY_TRIAL = 9
OTHER_PROCEDURAL_PROGRESS = 10
REQUEST_FOR_DE_NOVO = 13
PROCEDURAL_PROGRESSES = (
(
"Before issue joined",
(
(
NO_COURT_ACTION_PRE_ISSUE_JOINED,
"No court action (before issue joined)",
),
(ORDER_ENTERED, "Order entered"),
(HEARING_HELD, "Hearing held"),
(ORDER_DECIDED, "Order decided"),
),
),
(
"After issue joined",
(
(
NO_COURT_ACTION_POST_ISSUE_JOINED,
"No court action (after issue joined)",
),
(JUDGMENT_ON_MOTION, "Judgment on motion"),
(PRETRIAL_CONFERENCE_HELD, "Pretrial conference held"),
(DURING_COURT_TRIAL, "During court trial"),
(DURING_JURY_TRIAL, "During jury trial"),
(AFTER_COURT_TRIAL, "After court trial"),
(AFTER_JURY_TRIAL, "After jury trial"),
(OTHER_PROCEDURAL_PROGRESS, "Other"),
(
REQUEST_FOR_DE_NOVO,
"Request for trial de novo after arbitration",
),
),
),
)
TRANSFER_TO_DISTRICT = 0
REMANDED_TO_STATE = 1
TRANSFER_TO_MULTI = 10
REMANDED_TO_AGENCY = 11
WANT_OF_PROSECUTION = 2
LACK_OF_JURISDICTION = 3
VOLUNTARILY_DISMISSED = 12
SETTLED = 13
OTHER_DISMISSAL = 14
DEFAULT = 4
CONSENT = 5
MOTION_BEFORE_TRIAL = 6
JURY_VERDICT = 7
DIRECTED_VERDICT = 8
COURT_TRIAL = 9
AWARD_OF_ARBITRATOR = 15
STAYED_PENDING_BANKR = 16
OTHER_DISPOSITION = 17
STATISTICAL_CLOSING = 18
APPEAL_AFFIRMED = 19
APPEAL_DENIED = 20
DISPOSITIONS = (
(
"Cases transferred or remanded",
(
(TRANSFER_TO_DISTRICT, "Transfer to another district"),
(REMANDED_TO_STATE, "Remanded to state court"),
(TRANSFER_TO_MULTI, "Multi-district litigation transfer"),
(REMANDED_TO_AGENCY, "Remanded to U.S. agency"),
),
),
(
"Dismissals",
(
(WANT_OF_PROSECUTION, "Want of prosecution"),
(LACK_OF_JURISDICTION, "Lack of jurisdiction"),
(VOLUNTARILY_DISMISSED, "Voluntarily dismissed"),
(SETTLED, "Settled"),
(OTHER_DISMISSAL, "Other"),
),
),
(
"Judgment on",
(
(DEFAULT, "Default"),
(CONSENT, "Consent"),
(MOTION_BEFORE_TRIAL, "Motion before trial"),
(JURY_VERDICT, "Jury verdict"),
(DIRECTED_VERDICT, "Directed verdict"),
(COURT_TRIAL, "Court trial"),
(AWARD_OF_ARBITRATOR, "Award of arbitrator"),
(STAYED_PENDING_BANKR, "Stayed pending bankruptcy"),
(OTHER_DISPOSITION, "Other"),
(STATISTICAL_CLOSING, "Statistical closing"),
(APPEAL_AFFIRMED, "Appeal affirmed (magistrate judge)"),
(APPEAL_DENIED, "Appeal denied (magistrate judge"),
),
),
)
NO_MONEY = 0
MONEY_ONLY = 1
MONEY_AND = 2
INJUNCTION = 3
FORFEITURE_ETC = 4
COSTS_ONLY = 5
COSTS_AND_FEES = 6
NATURE_OF_JUDGMENT_CODES = (
(NO_MONEY, "No monetary award"),
(MONEY_ONLY, "Monetary award only"),
(MONEY_AND, "Monetary award and other"),
(INJUNCTION, "Injunction"),
(FORFEITURE_ETC, "Forfeiture/foreclosure/condemnation, etc."),
(COSTS_ONLY, "Costs only"),
(COSTS_AND_FEES, "Costs and attorney fees"),
)
PLAINTIFF = 1
DEFENDANT = 2
PLAINTIFF_AND_DEFENDANT = 3
UNKNOWN_FAVORING = 4
JUDGMENT_FAVORS = (
(PLAINTIFF, "Plaintiff"),
(DEFENDANT, "Defendant"),
(PLAINTIFF_AND_DEFENDANT, "Both plaintiff and defendant"),
(UNKNOWN_FAVORING, "Unknown"),
)
PRO_SE_NONE = 0
PRO_SE_PLAINTIFFS = 1
PRO_SE_DEFENDANTS = 2
PRO_SE_BOTH = 3
PRO_SE_CHOICES = (
(PRO_SE_NONE, "No pro se plaintiffs or defendants"),
(PRO_SE_PLAINTIFFS, "Pro se plaintiffs, but no pro se defendants"),
(PRO_SE_DEFENDANTS, "Pro se defendants, but no pro se plaintiffs"),
(PRO_SE_BOTH, "Both pro se plaintiffs & defendants"),
)
dataset_source = models.SmallIntegerField(
help_text="IDB has several source datafiles. This field helps keep "
"track of where a row came from originally.",
choices=DATASET_SOURCES,
)
circuit = models.ForeignKey(
Court,
help_text="Circuit in which the case was filed.",
related_name="+",
on_delete=models.RESTRICT,
null=True,
blank=True,
)
district = models.ForeignKey(
Court,
help_text="District court in which the case was filed.",
related_name="idb_cases",
on_delete=models.RESTRICT,
db_index=True,
null=True,
blank=True,
)
office = models.CharField(
help_text="The code that designates the office within the district "
"where the case is filed. Must conform with format "
"established in Volume XI, Guide to Judiciary Policies and "
"Procedures, Appendix A. See: https://free.law/idb-facts/",
max_length=3,
blank=True,
)
docket_number = models.CharField(
# use a char field here because we need preceding zeros.
help_text="The number assigned by the Clerks' office; consists of 2 "
"digit Docket Year (usually calendar year in which the case "
"was filed) and 5 digit sequence number.",
blank=True,
max_length=7,
)
origin = models.SmallIntegerField(
help_text="A single digit code describing the manner in which the "
"case was filed in the district.",
choices=ORIGINS,
blank=True,
null=True,
)
date_filed = models.DateField(
help_text="The date on which the case was filed in the district.",
db_index=True,
null=True,
blank=True,
)
jurisdiction = models.SmallIntegerField(
help_text="The code which provides the basis for the U.S. district "
"court jurisdiction in the case. This code is used in "
"conjunction with appropriate nature of suit code.",
choices=JURISDICTIONS,
blank=True,
null=True,
)
nature_of_suit = models.IntegerField(
help_text="A three digit statistical code representing the nature of "
"suit of the action filed.",
choices=NOS_CODES,
blank=True,
null=True,
)
# Via email from FJC, title and section fields are alternative for "cause"
# field.
title = models.TextField(
help_text="No description provided by FJC.",
blank=True,
db_index=True,
)
section = models.CharField(
help_text="No description provided by FJC.",
max_length=200,
db_index=True,
blank=True,
)
subsection = models.CharField(
help_text="No description provided by FJC.",
max_length=200,
db_index=True,
blank=True,
)
diversity_of_residence = models.SmallIntegerField(
help_text="Involves diversity of citizenship for the plaintiff and "
"defendant. First position is the citizenship of the "
"plaintiff, second position is the citizenship of the "
"defendant. Only used when jurisdiction is 4",
blank=True,
null=True,
)
class_action = models.BooleanField(
help_text="Involves an allegation by the plaintiff that the complaint "
'meets the prerequisites of a "Class Action" as provided '
"in Rule 23 - F.R.CV.P. ",
null=True,
)
monetary_demand = models.IntegerField(
help_text="The monetary amount sought by plaintiff (in thousands). "
"Amounts less than $500 appear as 1, and amounts over $10k "
"appear as 9999. See notes in codebook.",
null=True,
blank=True,
)
county_of_residence = models.IntegerField(
help_text="The code for the county of residence of the first listed "
"plaintiff (see notes in codebook). Appears to use FIPS "
"code.",
null=True,
blank=True,
)
arbitration_at_filing = models.CharField(
help_text="This field is used only by the courts participating in "
"the Formal Arbitration Program. It is not used for any "
"other purpose.",
max_length=1,
choices=ARBITRATION_CHOICES,
blank=True,
)
arbitration_at_termination = models.CharField(
help_text="Termination arbitration code.",
max_length=1,
choices=ARBITRATION_CHOICES,
blank=True,
)
multidistrict_litigation_docket_number = models.TextField(
help_text="A 4 digit multi district litigation docket number.",
blank=True,
)
plaintiff = models.TextField(
help_text="First listed plaintiff. This field appears to be cut off "
"at 30 characters",
db_index=True,
blank=True,
)
defendant = models.TextField(
help_text="First listed defendant. This field appears to be cut off "
"at 30 characters.",
db_index=True,
blank=True,
)
date_transfer = models.DateField(
help_text="The date when the papers were received in the receiving "
"district for a transferred case.",
blank=True,
null=True,
)
transfer_office = models.CharField(
help_text="The office number of the district losing the case.",
max_length=3,
blank=True,
)
transfer_docket_number = models.TextField(
help_text="The docket number of the case in the losing district",
blank=True,
)
transfer_origin = models.TextField(
help_text="The origin number of the case in the losing district",
blank=True,
)
date_terminated = models.DateField(
help_text="The date the district court received the final judgment or "
"the order disposing of the case.",
null=True,
blank=True,
)
termination_class_action_status = models.SmallIntegerField(
help_text="A code that indicates a case involving allegations of "
"class action.",
choices=CLASS_ACTION_STATUSES,
null=True,
blank=True,
)
procedural_progress = models.SmallIntegerField(
help_text="The point to which the case had progressed when it was "
"disposed of. See notes in codebook.",
choices=PROCEDURAL_PROGRESSES,
null=True,
blank=True,
)
disposition = models.SmallIntegerField(
help_text="The manner in which the case was disposed of.",
choices=DISPOSITIONS,
null=True,
blank=True,
)
nature_of_judgement = models.SmallIntegerField(
help_text="Cases disposed of by an entry of a final judgment.",
choices=NATURE_OF_JUDGMENT_CODES,
null=True,
blank=True,
)
amount_received = models.IntegerField(
help_text="Dollar amount received (in thousands) when appropriate. "
"Field not used uniformally; see codebook.",
null=True,
blank=True,
)
judgment = models.SmallIntegerField(
help_text="Which party the cases was disposed in favor of.",
choices=JUDGMENT_FAVORS,
null=True,
blank=True,
)
pro_se = models.SmallIntegerField(
help_text="Which parties filed pro se? (See codebook for more "
"details.)",
choices=PRO_SE_CHOICES,
null=True,
blank=True,
)
year_of_tape = models.IntegerField(
help_text="Statistical year label on data files obtained from the "
"Administrative Office of the United States Courts. 2099 "
"on pending case records.",
blank=True,
null=True,
)
# Criminal fields
nature_of_offense = models.CharField(
help_text="The four digit D2 offense code associated with the filing "
"title/secion 1. These codes were created in FY2005 to "
"replace the AO offense codes.",
max_length=4,
choices=NOO_CODES,
blank=True,
)
version = models.IntegerField(
help_text="This field was created in FY 2012. It increments with each "
"update received to a defendant record.",
null=True,
blank=True,
)
def __str__(self) -> str:
return f"{self.pk}: {self.plaintiff} v. {self.defendant}"
class Meta:
verbose_name_plural = "FJC Integrated Database Entries"
indexes = [models.Index(fields=["district", "docket_number"])]
| freelawproject/courtlistener | cl/recap/models.py | models.py | py | 30,102 | python | en | code | 435 | github-code | 13 |
19563003613 | # Laboratorium 1 Zadanie 1.1 Klient w Pythonie
# Autorzy: Mateusz Brzozowski, Bartłomiej Krawczyk, Jakub Marcowski, Aleksandra Sypuła
# Data ukończenia: 27.11.2022
import socket
import sys
from typing import List, Tuple
import random
import string
# Klient wysyła a serwer odbiera datagramy o stałym, niewielkim rozmiarze (rzędu kilkudziesięciu bajtów).
# Datagramy mogą zawierać ustalony „na sztywno” lub generowany napis – np. „abcde….”, „bcdef…”, itd.
# Powinno być wysyłanych kilka datagramów, po czym klient powinien kończyć pracę.
# Serwer raz uruchomiony pracuje aż do zabicia procesu. Serwer wyprowadza na stdout adres klienta przysyłającego datagram.
DATA_GRAM_LENGTH = 60
DATA_GRAM_NUMBER = 10
def get_random_string(length: int) -> str:
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for _ in range(length))
def parse_arguments(args: List[str]) -> Tuple[str, int]:
if len(args) < 3:
print('No host or port defined, using localhost at 8080 as default')
host = 'localhost'
port = 8080
else:
host = sys.argv[1]
port = int(sys.argv[2])
host_address = socket.gethostbyname(host)
print(f'Will send to {host}:{port} at {host_address}:{port}')
return host_address, port
def connect_with_server(s: socket.socket, host: str, port: int) -> None:
try:
s.connect((host, port))
except socket.error as exception:
raise socket.error(
f'Error while connecting: {exception}'
)
def send_text(s: socket.socket, text: str) -> None:
print(f'Sending {text}')
try:
s.send(text.encode('ascii'))
except socket.error as exception:
print(f'Exception while sending data: {exception}')
except UnicodeEncodeError as exception:
print(f'Exception while encoding text to bytes: {exception}')
def receive(s: socket.socket) -> None:
try:
data = s.recv(512)
print(data.decode('ascii'))
except socket.error as exception:
print(f'Exception while receiving data: {exception}')
except UnicodeDecodeError as exception:
print(f'Exception while decoding text to bytes: {exception}')
def prepare_socket_and_start_sending_data(host: str, port: int) -> None:
data_grams: List[str] = [
get_random_string(DATA_GRAM_LENGTH)
for _ in range(DATA_GRAM_NUMBER)
]
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
connect_with_server(s, host, port)
for text in data_grams:
send_text(s, text)
# receive(s)
def main(args: List[str]) -> None:
try:
(host, port) = parse_arguments(args)
except socket.error as exception:
print(f'Get host by name raised an exception: {exception}')
return
except ValueError as exception:
print(f'Error while parsing arguments: {exception}')
return
try:
prepare_socket_and_start_sending_data(host, port)
except socket.error as exception:
print(f'Caught exception: {exception}')
print('Client finished.')
if __name__ == '__main__':
main(sys.argv)
| bartlomiejkrawczyk/PSI-22Z | lab_1/task_1/py/client.py | client.py | py | 3,174 | python | en | code | 1 | github-code | 13 |
33793345614 | import unittest
import pkg_resources
from os import chdir, path, getcwd, remove
from timus import OnlineJudje
class TestOnlineJudje(unittest.TestCase):
def setUp(self):
filename = pkg_resources.resource_filename('examples', 'example.py')
file_dir = path.dirname(path.abspath(filename))
self.defdir = getcwd()
chdir(file_dir)
def test_get_name(self):
self.assertEqual(OnlineJudje.get_name('86286AA'), "Shed")
def test_result_table(self):
# In table shoud be 9 cols.
self.assertEqual(len(OnlineJudje.result_table('86286AA')[0]), 9)
def test_send(self):
r = OnlineJudje.send('86286AA', '1000', 'example.c', 'gcc')
print(r)
print(r.url)
self.assertTrue(r.url.find('status.aspx') != -1)
def test_get_problem_data(self):
data = OnlineJudje.get_problem_data('1201')
self.assertEqual(data['problem_id'], '1201')
self.assertEqual(data['problem_desc'], 'Which Day Is It?')
tests = list(data['tests'])
self.assertEqual(tests[0][0], '16 3 2002\r\n')
self.assertEqual(tests[1][0], '1 3 2002\r\n')
def test_init(self):
OnlineJudje.init('1000', '86286AA', 'scala')
self.assertTrue(path.exists('1000.A+B_Problem.scala'))
self.assertTrue(path.exists('1000.A+B_Problem.tests'))
remove('1000.A+B_Problem.scala')
remove('1000.A+B_Problem.tests')
def tearDown(self):
chdir(self.defdir)
if __name__ == '__main__':
unittest.main()
| Shedward/timus | tests/OnlineJudje_test.py | OnlineJudje_test.py | py | 1,534 | python | en | code | 1 | github-code | 13 |
34995694912 | import sys
from datetime import datetime, time, timedelta
import numpy as np, matplotlib.pyplot as plt
from matplotlib.patches import Patch
from matplotlib.cm import ScalarMappable
from timetable import (load_timetable, sum_timetable, datetime_range)
if __name__ == '__main__':
# Parse commandline arguments and build a dictionary of calendar names and
# files.
calendar_files = {}
for arg in sys.argv[1:]:
if not '=' in arg:
print('Invalid argument %s' % arg)
sys.exit(1)
name, path = arg.split('=', 1)
calendar_files[name] = path
# Load timetable from calendar files.
start = None
end = datetime.now()
timetable = load_timetable(calendar_files, clip_start=start, clip_end=end)
# Select first and last date of the timetable.
start = min(timetable, key=lambda e: e[0])[0].date()
end = max(timetable, key=lambda e: e[1])[1].date()
end += timedelta(days=1)
days = list(datetime_range(datetime.combine(start, time()),
datetime.combine(end, time()), timedelta(days=1)))
daily_series = sum_timetable(timetable, days)
# Plot cumulative sums.
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
base_y = np.zeros(len(days))
handles = []
colormap = ScalarMappable(cmap='Paired')
colormap.set_clim(0, len(daily_series))
for idx, name in enumerate(sorted(daily_series)):
# Use a unique color based on the series index.
color = colormap.to_rgba(idx)
# Stack series cumulatively and plot them.
y = base_y + np.cumsum(daily_series[name]) / 3600
ax.fill_between(days, base_y, y, edgecolor='none', facecolor=color)
base_y = y
# Unfortunately fill_between() does not support labels. Create a proxy
# handle for the legend.
handles.append(Patch(color=color, label=name))
fig.autofmt_xdate()
ax.legend(loc='upper left', handles=handles)
plt.show()
| Ayan-Chowdhury/ComRade | venv/Lib/site-packages/timetable/plot/cumulative.py | cumulative.py | py | 1,973 | python | en | code | 1 | github-code | 13 |
3911849245 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import asyncio
import os
import re
import shutil
import sys
import Levenshtein
try:
import interval as itvl # https://pypi.python.org/pypi/pyinterval
except Exception as e:
print("pyinterval not installed. No coverage reports will be available", file=sys.stderr)
"""Misc utilitary garbage"""
def escape(s):
return s.replace('&', '&').replace('<', '<').replace('>', '>') # html.escape(s)
def escapen(s):
# not os.linesep to be more precise on length
return escape(s).replace('\n', '<br/>\n')
def escapecode(s, allow_space_wrap=False):
s = escapen(s)
# s = s.replace('\r', '') # should not be there already
if not allow_space_wrap:
s = s.replace(' ', ' ')
s = s.replace('\t', ' ')
return s
def write_variative_report(clones, candidates, report_file_name):
"""
Function to save extra reports
:param clones: clones module VariativeElement
:param candidates: list of clones.VariativeElement instances
:param report_file_name: HTML file to save everything
:return:
"""
target_dir = os.path.dirname(report_file_name)
cohtml = clones.VariativeElement.summaryhtml(candidates, clones.ReportMode.variative)
with open(report_file_name, 'w', encoding='utf-8') as htmlfile:
htmlfile.write(cohtml)
shutil.copyfile(
os.path.join(os.path.dirname(os.path.abspath(__file__)), 'js', 'interactivity.js'),
os.path.join(target_dir, "interactivity.js")
)
shutil.copyfile(
os.path.join(os.path.dirname(os.path.abspath(__file__)), 'js', 'jquery-2.0.3.min.js'),
os.path.join(target_dir, "jquery-2.0.3.min.js")
)
def transpose(a):
"""
Thanks, http://stackoverflow.com/a/21444360/539470
:param a: list of lists (say, lines of a matrix)
:return: list of lists (say, lines of transposed matrix)
"""
return [list(x) for x in zip(*a)]
def connected_slices(i: 'itvl.interval') -> 'list[tuple[int, int]]':
return [(int(t[0][0]), int(t[0][1])) for t in i.components]
def lratio(s1, s2):
return 1 - Levenshtein.distance(s1, s2) / max(len(s1), len(s2), 1)
def diratio(s1, s2):
import pattern_near_duplicate_search
return pattern_near_duplicate_search.di_similarity(s1, s2)
_wre = re.compile(r"\w+", re.UNICODE)
def tokens(text):
r = []
for m in _wre.finditer(text):
s = m.start()
e = m.end()
r.append((s, e, text[s:e]))
return r
def text_to_tokens_offsets(src: str) -> 'tuple[list[str], list[tuple[int, int]]]':
str_offs = [(src[fi.start():fi.end()], (fi.start(), fi.end())) for fi in _wre.finditer(src)]
return tuple([list(t) for t in zip(*str_offs)])
def tokenst(text):
return [s for b, e, s in tokens(text)]
def ctokens(text):
return ' '.join(tokenst(text))
def save_reformatted_file(fileName):
lines = []
with open(fileName, encoding='utf-8') as ifs:
for line in ifs:
# lst = line.rstrip() + '\n' # leave leading blanks + add separator (we do not need \r, so no os.linesep)
lst = line.replace('\r', '').replace('\n',
'') + '\n' # leave leading blanks + add separator (we do not need \r, so no os.linesep)
lst = lst.replace('\t', ' ') # Clone Miner is very brave to consider TAB equal to 4 spaces
lines.append(lst)
text = "".join(lines)
with open(fileName + ".reformatted", 'w+', encoding='utf-8', newline='\n') as ofs:
ofs.write(text)
def save_standalone_html(source_html, target_html):
with open(source_html, encoding='utf-8') as htmlsrc:
htmlcontent = htmlsrc.read()
def replace_ref_with_script(match): # want normal lambdas here...
jsfilename = os.path.join(
os.path.dirname(source_html), # html directory
match.group(1) + ".js"
)
with open(jsfilename) as jsfile:
js = jsfile.read()
return """<script>%s</script>""" % js
htmlcontent = re.sub("""<script src="(.*)\\.js"></script>""", replace_ref_with_script, htmlcontent)
with open(target_html, "w", encoding='utf-8') as ofl:
ofl.write(htmlcontent)
# asyncio stuff
def ready_future(result=None):
fut = asyncio.get_event_loop().create_future()
fut.set_result(result)
return fut
def set_asio_el(loop):
asyncio.set_event_loop(loop)
| ikonovalova/Editor | df_visual_report/util.py | util.py | py | 4,500 | python | en | code | 0 | github-code | 13 |
31933581832 | from __future__ import annotations
from typing import Optional
from spotterbase.records.record import Record, RecordInfo, AttrInfo
from spotterbase.model_core.oa import OA_PRED
from spotterbase.rdf.literal import Uri
from spotterbase.rdf.vocab import XSD
from spotterbase.model_core.sb import SB, SB_PRED
class SimpleTagBody(Record):
record_info = RecordInfo(
record_type=SB.SimpleTagBody,
attrs=[
AttrInfo('tag', SB_PRED.val),
]
)
tag: Uri
def __init__(self, tag: Optional[Uri] = None):
super().__init__(tag=tag)
class MultiTagBody(Record):
record_info = RecordInfo(
record_type=SB.MultiTagBody,
attrs=[
AttrInfo('tags', SB_PRED.val, multi_field=True),
]
)
tags: list[Uri]
def __init__(self, tags: Optional[list[Uri]] = None):
super().__init__(tags=tags)
class Tag(Record):
record_info = RecordInfo(
record_type=SB.Tag,
attrs=[
AttrInfo('belongs_to', SB_PRED.belongsTo),
AttrInfo('label', OA_PRED.label, literal_type=XSD.string),
AttrInfo('comment', SB_PRED.comment),
],
is_root_record=True
)
label: Optional[str] = None
belongs_to: Optional[Uri] = None
comment: Optional[str] = None
def __init__(self, uri: Optional[Uri] = None, label: Optional[str] = None, belongs_to: Optional[Uri] = None,
comment: Optional[str] = None):
super().__init__(uri=uri, label=label, belongs_to=belongs_to, comment=comment)
class TagSet(Record):
record_info = RecordInfo(
record_type=SB.TagSet,
attrs=[
AttrInfo('tags', SB_PRED.belongsTo_Rev, multi_field=True),
AttrInfo('label', OA_PRED.label, literal_type=XSD.string),
AttrInfo('comment', SB_PRED.comment),
],
is_root_record=True
)
# tags: list[Uri]
comment: Optional[str] = None
label: Optional[str] = None
tags: Optional[list[Uri]] = None
def __init__(self, uri: Optional[Uri] = None, label: Optional[str] = None, comment: Optional[str] = None):
super().__init__(uri=uri, label=label, comment=comment)
| jfschaefer/spotterbase | spotterbase/model_core/tag_body.py | tag_body.py | py | 2,195 | python | en | code | 0 | github-code | 13 |
9088670940 | #https://www.acmicpc.net/problem/2503
#백준 2503번 숫자 야구 (순열)
#import sys
#input = sys.stdin.readline
from itertools import permutations
n = int(input())
nums = []
for _ in range(n):
a,b,c = input().split()
nums.append([list(map(int, a)),int(b),int(c)])
result = 0
base = [i for i in range(1,10)]
for num in permutations(base,3):
flag = True
for i in range(n):
target, st, ball = nums[i]
a,b = 0, 0
for j in range(3):
if num[j] == target[j]:
a += 1
elif target[j] in num :
b += 1
if st != a or ball != b :
flag = False
break
if flag :
#print(num)
result += 1
print(result) | MinsangKong/DailyProblem | 08-27/1-1.py | 1-1.py | py | 738 | python | en | code | 0 | github-code | 13 |
43167600289 | from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from .models import ScrumyUser, ScrumyGoals, GoalStatus
from .forms import addUserForm, addTaskForm, changeTaskStatusForm
from django.contrib.auth import authenticate, login
from django.contrib.auth.hashers import make_password
# Create your views here.
def index(request):
users = ScrumyUser.objects.all()
return render(request, 'olufekoscrumy/index.html', {'users':users})
def add_user(request):
if(request.method == "POST"):
form = addUserForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.password = make_password(password)
user.save()
return HttpResponseRedirect('/')
else:
form = addUserForm()
else:
form = addUserForm()
return render(request, 'olufekoscrumy/add_user.html', {'form': form})
def get_users(request):
users = ScrumyUser.objects.all()
return render(request, 'olufekoscrumy/get_user.html', {'users': users})
def add_task(request):
if request.user.is_authenticated:
user = request.user.id
if(request.method == "POST"):
form = addTaskForm(request.POST)
if(int(user) == int(request.POST.get('user'))):
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
form = addTaskForm()
else:
return HttpResponse('you cannot add task for another user!')
else:
form = addTaskForm()
else:
return HttpResponse('you cannot access this page!, create an account to do so.')
return render(request, 'olufekoscrumy/add_task.html', {'form': form})
def change_status(request, id):
if request.user.is_authenticated:
user = request.user
user_group = user.groups.all()
if user_group:
if(request.method == "POST"):
form = changeTaskStatusForm(request.POST)
if form.is_valid():
newstatus = request.POST.get('status')
try:
scrumy_goal = ScrumyGoals.objects.get(id=id)
if scrumy_goal:
if str(user_group[0]) == 'Owner':
scrumy_goal.status = newstatus
scrumy_goal.save()
newform = form.save(commit=False)
newform.goal_id = id
newform.save
return HttpResponseRedirect('/')
elif str(user_group[0]) == 'Admin':
if int(newstatus) == 1 or int(newstatus) == 3:
scrumy_goal.status = newstatus
scrumy_goal.save()
newform = form.save(commit=False)
newform.goal_id = id
newform.save
return HttpResponseRedirect('/')
else:
return HttpResponse('You cannot do that!')
elif str(user_group[0]) == 'Quality Analyst':
if int(newstatus) in [1,3,4]:
scrumy_goal.status = newstatus
scrumy_goal.save()
newform = form.save(commit=False)
newform.goal_id = id
newform.save
return HttpResponseRedirect('/')
else:
return HttpResponse('You cannot do that!')
elif str(user_group[0]) == 'Developer':
if int(newstatus) == 2 or int(newstatus) == 1:
scrumy_goal.status = newstatus
scrumy_goal.save()
newform = form.save(commit=False)
newform.goal_id = id
newform.save
return HttpResponseRedirect('/')
else:
return HttpResponse('You cannot do that!')
else:
return HttpResponse('Goal not found!')
except ScrumyGoals.DoesNotExist:
raise Http404('There is no goal with that id!' + str(id))
else:
form = changeTaskStatusForm()
else:
return HttpResponse('user does not belong to any group')
else:
return HttpResponse('you cannot access this page!')
return render(request, 'olufekoscrumy/change_status.html', {'form': form, 'id':id})
| olufekosamuel/scrumy | olufekoscrumy/views.py | views.py | py | 3,936 | python | en | code | 0 | github-code | 13 |
4007833831 | import os
import json
from flask import Flask
from flask import render_template
from flask import request
from flask import Flask, render_template, request, redirect, url_for, flash, make_response,session, current_app, jsonify
from flask_wtf import FlaskForm
from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
from wtforms.validators import DataRequired
import git
from config import Config
from creator import get_decklist
from creator import make_deck_info_dict
from creator import create
import tmp
TEMP_DIR = Config.TEMP_DIR
app = Flask(__name__,)
app.config.from_object(Config)
HSSITE_MODE = app.config['HSSITE_MODE']
# HSSITE_MODE = 'production'
class SendCodeString(FlaskForm):
username = StringField('Codestrinf', validators=[DataRequired()])
submit = SubmitField('Submit')
@app.route('/', methods=['POST', 'GET'])
def index():
# form = SendCodeString()
if HSSITE_MODE == 'testing':
disable_ui_elements = ''
else:
disable_ui_elements = 'disabled'
return render_template('index.html', disabled=disable_ui_elements, HSSITE_MODE=HSSITE_MODE)
@app.route('/get_deck_info', methods=['GET', 'POST'])
def get_deck_info():
print('/get_deck_info')
if request.method == 'POST':
deckstring = request.form.get('block_send__input')
lang = request.form.get('options_LANG')
print(deckstring)
print(lang)
try:
if HSSITE_MODE == 'testing':
deck_info = make_deck_info_dict(deckstring, lang=lang, send_existing_files = True)
else:
deck_info = make_deck_info_dict(deckstring, lang=lang)
except:
deck_info = {'decklist': 0}
else:
deck_info = {'decklist': 0}
return json.dumps(deck_info)
# refresh css
@app.context_processor
def override_url_for():
return dict(url_for=dated_url_for)
def dated_url_for(endpoint, **values):
if endpoint == 'static':
filename = values.get('filename', None)
if filename:
file_path = os.path.join(app.root_path,
endpoint, filename)
values['q'] = int(os.stat(file_path).st_mtime)
return url_for(endpoint, **values)
@app.route('/update_server', methods=['POST', 'GET'])
def webhook():
if request.method == 'POST':
# repo = git.Repo('https://github.com/u5ergen/test.git')
repo = git.Repo('/home/viy04205/mysite')
origin = repo.remotes.origin
origin.pull('develop')
return 'Updated PythonAnywhere successfully', 200
else:
return 'Wrong event type', 400
@app.route('/test_flex')
def test_flex():
return render_template('test_color.html')
@app.route('/get_len', methods=['GET', 'POST'])
def get_len():
name = request.form.get('deck_string_form_input')
return json.dumps({'len': len(name)})
if __name__ == '__main__':
app.run(debug=True)
| u5ergen/test | main.py | main.py | py | 2,784 | python | en | code | 0 | github-code | 13 |
5886570181 | import sys
import random
random.seed()
T = 30
MINX = 1
MAXX = 512
MINY = 1
MAXY = 512
print(str(T))
for t in range(T):
n = random.randint(3, 512)
print( str(n) )
x, y = random.randint(MINX, MAXX), random.randint(MINY, MAXY)
print( str(x) + ' ' + str(y) )
for p in range(2, n):
x2, y2 = random.randint(MINX, MAXX), random.randint(MINY, MAXY)
print( str(x2) + ' ' + str(y2) )
print( str(x) + ' ' + str(y) )
if t < T-1:
print( str(-1) )
| eric7237cire/CodeJam | uva/681 - geometry convex hull/gen_data.py | gen_data.py | py | 459 | python | en | code | 7 | github-code | 13 |
36581213382 | import os
borderstyle = "║"
def drawboxtext(dat):
height = len(dat)
y = 0
while y < height:
dat[y] = " "+dat[y]+" "
y += 1
width = len(max(dat, key=len))+1
counter = 0
x = 0
line = "╔"
while x < width-1:
line = line + "═"
x += 1
line = line + "╗"
print(line)
while counter < height:
reqspaces = width -1- len(dat[counter])
xsp = ""
while reqspaces > 0:
xsp = xsp + " "
reqspaces -= 1
print(borderstyle+dat[counter]+xsp+borderstyle)
counter += 1
x = 0
line = "╚"
while x < width-1:
line = line + "═"
x += 1
line = line + "╝"
print(line)
print("Framed text generator by Julian Drake.\n")
print("")
while True:
print("Enter the items in the frame. (Leave blank to submit.)")
items=[]
i=0
while 1:
i+=1
item=input('Enter item %d: '%i)
if item=="":
break
items.append(item)
print("")
drawboxtext(items)
print("")
input("")
os.system('cls')
| hastagAB/Awesome-Python-Scripts | FramedText/FramedText.py | FramedText.py | py | 1,115 | python | en | code | 1,776 | github-code | 13 |
1398291815 | # Uses python3
import math
import sys
def binary_search(a, x, left=0, right=None):
if right is None:
right = len(a)-1
if left > right:
return -1
mid_key = math.floor(left + (right-left)/2)
if a[mid_key] == x:
return mid_key
elif a[mid_key] > x:
return binary_search(a, x, left=left, right=mid_key-1)
elif a[mid_key] < x:
return binary_search(a, x, left=mid_key+1, right=right)
return -1
def linear_search(a, x):
for i in range(len(a)):
if a[i] == x:
return i
return -1
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(int, input.split()))
n = data[0]
m = data[n + 1]
a = data[1 : n + 1]
values = data[n + 2:]
for x in values:
# replace with the call to binary_search when implemented
print(binary_search(a, x), end=' ')
| AlexEngelhardt-old/courses | Data Structures and Algorithms/01 Algorithmic Toolbox/Week 4 - Divide-and-Conquer/assignment/1-binary_search/1-binary_search.py | 1-binary_search.py | py | 887 | python | en | code | 2 | github-code | 13 |
32490083752 | ## ----------------------------------------
## Mixed utilities
## ----------------------------------------
##
## ----------------------------------------
## Author: Dennis Bontempi, Michele Svanera
## Version: 2.0
## Email: dennis.bontempi@glasgow.ac.uk
## Status: ready to use
## Modified: 20 Feb 19
## ----------------------------------------
import os
import shutil
import tensorflow as tf
from keras import backend as K
from keras.callbacks import TensorBoard
## -----------------------------------------------------------------------------------------------
## -----------------------------------------------------------------------------------------------
class TrainValTensorBoard(TensorBoard):
def __init__(self, model_name, log_dir, **kwargs):
# make the original `TensorBoard` log to a subdirectory 'training'
model_dir = os.path.join(log_dir, model_name[0:-3])
# if a tb log for the model exists already, remove it
if os.path.exists(model_dir):
shutil.rmtree(model_dir, ignore_errors=True)
training_log_dir = os.path.join(log_dir, model_name[0:-3], 'training')
super(TrainValTensorBoard, self).__init__(training_log_dir, **kwargs)
# Log the validation metrics to a separate subdirectory
self.val_log_dir = os.path.join(log_dir, model_name[0:-3], 'validation')
def set_model(self, model):
# Setup writer for validation metrics
self.val_writer = tf.summary.FileWriter(self.val_log_dir)
super(TrainValTensorBoard, self).set_model(model)
def on_epoch_end(self, epoch, logs=None):
# Pop the validation logs and handle them separately with
# `self.val_writer`. Also rename the keys so that they can
# be plotted on the same figure with the training metrics
logs = logs or {}
val_logs = {k.replace('val_', ''): v for k, v in logs.items() if k.startswith('val_')}
for name, value in val_logs.items():
summary = tf.Summary()
summary_value = summary.value.add()
summary_value.simple_value = value.item()
summary_value.tag = name
self.val_writer.add_summary(summary, epoch)
self.val_writer.flush()
# Pass the remaining logs to `TensorBoard.on_epoch_end`
logs = {k: v for k, v in logs.items() if not k.startswith('val_')}
super(TrainValTensorBoard, self).on_epoch_end(epoch, logs)
def on_train_end(self, logs=None):
super(TrainValTensorBoard, self).on_train_end(logs)
self.val_writer.close()
## -----------------------------------------------------------------------------------------------
## -----------------------------------------------------------------------------------------------
"""
Exploiting the list_local_devices function belonging to the TF device_lib, get the number of
GPUs currently available on the machine (useful to define the upper bound of the gpu argument
in both training and prediction phase scripts).
"""
from tensorflow.python.client import device_lib
def NumAvailableGPUs():
availableDevices = device_lib.list_local_devices()
# list_local_devices() returns the name of a device, the device type, the memory limit and a
# couple of other information. Both name and device_type contain the information we're searching
# for, but device_type can either be "CPU" or "GPU", so go for that.
return len([device.name for device in availableDevices if device.device_type == 'GPU'])
| denbonte/CER3BRUM | src/cer3brum_lib/utils.py | utils.py | py | 3,643 | python | en | code | 5 | github-code | 13 |
3133901334 | #!/usr/bin/env python
# coding: utf-8
# In[4]:
from qiskit import *
get_ipython().run_line_magic('matplotlib', 'inline')
from qiskit.tools.visualization import plot_histogram as hist
from qiskit.tools.monitor import job_monitor
import operator
IBMQ.load_account()
provider=IBMQ.get_provider('ibm-q')
def Xrot(circuit, length, amount):
i=0
while i<length:
circuit.rx(-2*amount,[i])
i+=1
def Zrot(cr, amount, a, b):
i=0
while i<6:
cr.rz(2*amount*a[i],[i])
i+=1
i=0
while i<6:
j=i+1
while j<6:
cr.cx([i],[6])
cr.cx([j],[6])
cr.rz(2*amount*b[6*i+j],[6])
cr.cx([i],[6])
cr.cx([j],[6])
j+=1
i+=1
cr.barrier()
cr.reset([6])
def Optimize(penalty,a,b,p,segmentCosts):
J=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
h=[0,0,0,0,0,0]
i=0
while i<6:
h[i]=4*penalty-0.5*segmentCosts[i]
i+=1
i=0
while i<36:
J[i]=2*penalty
i+=1
J[2]=penalty
J[9]=penalty
J[29]=penalty
circuit=QuantumCircuit(7,6)
circuit.h([0,1,2,3,4,5])
i=0
while i<p:
Zrot(circuit, b[i], h, J)
Xrot(circuit, 6, a[i])
i+=1
circuit.measure([0,1,2,3,4,5],[0,1,2,3,4,5])
circuit.reset([0,1,2,3,4,5])
return circuit
circuita=Optimize(20,[0.619,0.743,0.060,-1.569,-0.045],[3.182,-1.139,0.121,0.538,-0.417],5,[5,9,9,6,8,2])
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuita,backend = simulator, shots=4000).result()
total=result.get_counts(circuita)
datatype=type(total)
totaldict=dict(total)
type(totaldict)
print(totaldict)
maximum=0
bestkey=""
for key in totaldict:
if totaldict[key]>maximum:
bestkey=key
maximum=totaldict[key]
print(bestkey)
print(maximum)
| Spirit-Guardian/Wandering-Salesman-Problem | Hack-Q-Thon Project Copy Clean.py | Hack-Q-Thon Project Copy Clean.py | py | 1,906 | python | en | code | 0 | github-code | 13 |
42570936762 | start = True
while start:
# reading the file
data = open("reservation_StudentID.txt", "r").read()
print(data)
#this input is to hold the display til the user is done checking reservation
done = input()
#this part is for testing
list = []
list = data.split("\n")
list.pop(-1)
list.sort()
print(list)
start = False | kohisky/Prototype-Assignment | Display.py | Display.py | py | 370 | python | en | code | 0 | github-code | 13 |
21051004015 | from itertools import permutations
n = int(input())
nums = list(map(int, input().split()))
operators = []
a, b, c, d = map(int, input().split())
for i in range(a):
operators.append('+')
for i in range(b):
operators.append('-')
for i in range(c):
operators.append('x')
for i in range(d):
operators.append('/')
new_oper = list(set(list(permutations(operators, n-1))))
result = []
for y in range(len(new_oper)):
ans = nums[0]
for i in range(1, n):
if new_oper[y][i-1] == '+':
ans += nums[i]
elif new_oper[y][i-1] == '-':
ans -= nums[i]
elif new_oper[y][i-1] == 'x':
ans *= nums[i]
else:
ans = int(ans/nums[i])
result.append(ans)
result.sort()
print(result[-1])
print(result[0])
| jinho9610/py_algo | boj/14888.py | 14888.py | py | 790 | python | en | code | 0 | github-code | 13 |
71532342097 | from os import error
from Models import connection, record
from Schemas import schemas, record_schema
from flask import Flask, jsonify, request
#TODO calculate effective rate
app = Flask(__name__)
#setup and shortcut sqlalchemy models and db
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite+pysqlite:///interestapp.db'
db = connection.db
db.init_app(app)
record = record.Record
#setup and shortcut marshmallow schemas
schemas.ma.init_app(app)
record_schema = record_schema.record
def calc_final_sum(capital, rate, time, type_of_period):
rate = rate/100
if type_of_period == "annual":
final_sum = capital*((1+rate)**time)
elif type_of_period =="monthly":
final_sum = capital*((1+(rate/12))**(time*12))
elif type_of_period == "weekly":
final_sum = capital*((1+(rate/52))**(time*52))
elif type_of_period == "daily":
final_sum = capital*((1+(rate/365))**(time*365))
return final_sum
def correct_input_data(data):
clean_data = {
'initial_capital' : float(data.get('initial_capital', False)),
'name' : data.get('name', False)[0:20],
'number_of_periods' : int(data.get('number_of_periods', False)),
'rate' : float(data.get('rate', False)),
'type_of_period' : data.get('type_of_period', False)
}
return clean_data
@app.route('/', methods=['GET'])
def get_all():
rows = record.query.all()
row_arr = []
for row in rows:
row_arr.append(record_schema.dump(row))
return jsonify(row_arr)
@app.route('/insert', methods=['POST'])
def insert_record():
if request.method == 'POST':
data = request.form.to_dict()
input_values = correct_input_data(data)
missing = []
for key in input_values.keys():
if not input_values[key]:
missing.append(key)
if not missing:
if input_values['type_of_period'] in ['annual', 'monthly','weekly','daily']:
final_sum = calc_final_sum(input_values['initial_capital'], input_values['rate'], input_values['number_of_periods'],input_values['type_of_period'])
else:
return {'error': "type_of_period has an incorrect value, it should be 'annual', 'monthly', 'weekly' or 'daily' "}
row = record(final_sum=final_sum, initial_capital=input_values['initial_capital'], name=input_values['name'], number_of_periods=input_values['number_of_periods'], rate=input_values['rate'], type_of_period=input_values['type_of_period'])
db.session.add(row)
db.session.commit()
id = row.id
response_record = record.query.get(id)
response = record_schema.dump(response_record)
return response
else:
response = {}
error = ''
for el in missing:
error += el + ', '
response['error'] = error + 'is/are missing.'
return response
else:
return {'error': 'Incorrect HTTP method'}
@app.route('/delete/<int:id>', methods=['DELETE'])
def delete_record(id):
if request.method == 'DELETE':
row = record.query.get(id)
response_record = row
db.session.delete(row)
db.session.commit()
response = record_schema.dump(response_record)
return response
else:
return {'error': 'Incorrect HTTP method'}
@app.route('/edit/<int:id>', methods=['PUT'])
def edit_record(id):
if request.method == 'PUT':
row = record.query.get(id)
data = request.form.to_dict()
input_values = correct_input_data(data)
missing = []
for key in input_values.keys():
if not input_values[key]:
missing.append(key)
if not missing:
if input_values['type_of_period'] in ['annual', 'monthly','weekly','daily']:
row.final_sum = calc_final_sum(input_values['initial_capital'], input_values['rate'], input_values['number_of_periods'],input_values['type_of_period'])
else:
return {'error': "type_of_period has an incorrect value, it should be 'annual', 'monthly', 'weekly' or 'daily' "}
row.initial_capital = input_values['initial_capital']
row.name = input_values['name']
row.number_of_periods = input_values['number_of_periods']
row.rate = input_values['rate']
row.type_of_period = input_values['type_of_period']
db.session.commit()
response = record_schema.dump(row)
return response
else:
response = {}
error = ''
for el in missing:
error += el + ', '
response['error'] = error + 'is/are missing.'
return response
else:
return {'error': 'Incorrect HTTP method'}
if __name__ == "__main__":
app.run() | JuanpiCasti/InterestApp-API | interestapp_api/interestapp_api.py | interestapp_api.py | py | 4,990 | python | en | code | 0 | github-code | 13 |
2237563661 | import re
def Suffix(pattern, letter, word):
# letter: kaynaştırma harfi
# pattern: ekler
pattern = re.compile('('+pattern+')$', re.U)
if letter is None:
letterCheck = False
letterPattern = None
else:
letterCheck = True
letterPattern = re.compile('('+letter+')$', re.U)
if letterCheck:
match = letterPattern.search(word)
if match:
word = match.group()
word = pattern.sub('',word)
return word
# transition: class object
def AddTransitions(word, transitions, marked, suffixes):
for suffix in suffixes:
if suffix.Match(word):
transitions.append(NextState(suffix, word, marked))
# 2 of the same name function
def NextState(suffix):
raise NotImplementedError("Feature is not implemented.")
def similarTransitions(transitions,startState,nextState,word,marked):
for transition in transitions:
if (startState == transition.startState and
nextState == transition.nextState):
yield transition
# suffix functions according to word type
def derivational(word):
S1 = Suffix("lı|li|lu|lü", None, word)
VALUES = (S1)
return VALUES
def verb(word):
S11 = Suffix("casına|çasına|cesine|çesine",None, word)
S4 = Suffix("sınız|siniz|sunuz|sünüz", None, word)
S14 = Suffix("muş|miş|müş|mış","y", word)
S15 = Suffix("ken","y", word )
S2 = Suffix("sın|sin|sun|sün",None, word)
S5 = Suffix("lar|ler",None, word)
S9 = Suffix("nız|niz|nuz|nüz",None, word)
S10 = Suffix("tır|tir|tur|tür|dır|dir|dur|dür",None,word)
S3 = Suffix("ız|iz|uz|üz","y",word)
S1 = Suffix("ım|im|um|üm","y",word)
S12 = Suffix("dı|di|du|dü|tı|ti|tu|tü","y",word)
S13 = Suffix("sa|se","y",word)
S6 = Suffix("m",None, word)
S7 = Suffix("n",None, word)
S8 = Suffix("k",None, word)
# The order of the enum definition determines the priority of the suffix.
# For example, -(y)ken (S15 suffix) is checked before -n (S7 suffix).
VALUES = (S11,S4,S14,S15,S2,S5,S9,S10,S3,S1,S12,S13,S6,S7,S8)
return min(VALUES)
def noun(word):
S16 = Suffix("ndan|ntan|nden|nten",None,word)
S7 = Suffix("ları|leri",None,word)
S3 = Suffix("mız|miz|muz|müz","ı|i|u|ü",word)
S5 = Suffix("nız|niz|nuz|nüz","ı|i|u|ü",word)
S1 = Suffix("lar|ler",None,word)
S14 = Suffix("nta|nte|nda|nde",None,word)
S15 = Suffix("dan|tan|den|ten",None,word)
S17 = Suffix("la|le","y", word)
S10 = Suffix("ın|in|un|ün","n",word)
S19 = Suffix("ca|ce","n",word)
S4 = Suffix("ın|in|un|ün",None,word)
S9 = Suffix("nı|ni|nu|nü",None,word)
S12 = Suffix("na|ne",None,word)
S13 = Suffix("da|de|ta|te",None,word)
S18 = Suffix("ki",None,word)
S2 = Suffix("m","ı|i|u|ü", word)
S6 = Suffix("ı|i|u|ü","s",word)
S8 = Suffix("ı|i|u|ü","y",word)
S11 = Suffix("a|e","y",word)
# The order of the enum definition determines the priority of the suffix.
# For example, -(y)ken (S15 suffix) is checked before -n (S7 suffix).
VALUES = (S16,S7,S3,S5,S1,S14,S15,S17,S10,S19,S4,S9,S12,S13,S18,S2,S6,S8,S11)
return min(VALUES)
| noeldar/cmpe-561-project-1 | stmr.py | stmr.py | py | 3,234 | python | en | code | 0 | github-code | 13 |
43982697181 | from blues.moves import MoveEngine, RandomLigandRotationMove, SideChainMove
from blues.settings import Settings
from blues.simulation import *
from blues.utils import get_data_filename
def ligrot_example(yaml_file):
# Parse a YAML configuration, return as Dict
cfg = Settings(yaml_file).asDict()
structure = cfg['Structure']
#Select move type
ligand = RandomLigandRotationMove(structure, 'LIG')
#Iniitialize object that selects movestep
ligand_mover = MoveEngine(ligand)
#Generate the openmm.Systems outside SimulationFactory to allow modifications
systems = SystemFactory(structure, ligand.atom_indices, cfg['system'])
#Freeze atoms in the alchemical system to speed up alchemical calculation
systems.alch = systems.freeze_radius(structure, systems.alch, **cfg['freeze'])
#Generate the OpenMM Simulations
simulations = SimulationFactory(systems, ligand_mover, cfg['simulation'], cfg['md_reporters'],
cfg['ncmc_reporters'])
# Run BLUES Simulation
blues = BLUESSimulation(simulations, cfg['simulation'])
blues.run()
def sidechain_example(yaml_file):
# Parse a YAML configuration, return as Dict
cfg = Settings(yaml_file).asDict()
structure = cfg['Structure']
#Select move type
sidechain = SideChainMove(structure, [1])
#Iniitialize object that selects movestep
sidechain_mover = MoveEngine(sidechain)
#Generate the openmm.Systems outside SimulationFactory to allow modifications
systems = SystemFactory(structure, sidechain.atom_indices, cfg['system'])
#Generate the OpenMM Simulations
simulations = SimulationFactory(systems, sidechain_mover, cfg['simulation'], cfg['md_reporters'],
cfg['ncmc_reporters'])
# Run BLUES Simulation
blues = BLUESSimulation(simulations, cfg['simulation'])
blues.run()
#Analysis
import mdtraj as md
import numpy as np
traj = md.load_netcdf('vacDivaline-test/vacDivaline.nc', top='tests/data/vacDivaline.prmtop')
indicies = np.array([[0, 4, 6, 8]])
dihedraldata = md.compute_dihedrals(traj, indicies)
with open("vacDivaline-test/dihedrals.txt", 'w') as output:
for value in dihedraldata:
output.write("%s\n" % str(value)[1:-1])
ligrot_example(get_data_filename('blues', '../examples/rotmove_cuda.yml'))
#sidechain_example(get_data_filename('blues', '../examples/sidechain_cuda.yml'))
| MobleyLab/blues | blues/example.py | example.py | py | 2,468 | python | en | code | 31 | github-code | 13 |
36154347848 | #import sys
#print(sys.path)
#sys.path.append('/tmp/work/python-ftgl/build/lib.linux-armv7l-2.7')
#sys.path.append('/tmp/work/python-ftgl/build/lib.linux-armv7l-2.7/ftgl')
import ftgl
#from ftgl import ftgl
print(dir(ftgl))
#font = ftgl.FTGLPixmapFont("Arial.ttf")
font = ftgl.FTPixmapFont("/usr/share/fonts/truetype/vlgothic/VL-Gothic-Regular.ttf")
font.FaceSize(72)
font.Render("Hello World!")
| ytyaru/Build.python-ftgl.20200428161725 | src/main.py | main.py | py | 397 | python | fa | code | 1 | github-code | 13 |
7625929557 | import datetime
import subprocess
import time
from flask import jsonify
from flask.ext.login import current_user
import git_utils
import utils
from summer import db, app
from summer.models import Task, Record
def start_deploy(task_id):
if not task_id:
return jsonify(code=401, message='taskId必须填写')
task = Task.query.filter_by(id=task_id).one()
if task.user_id != current_user.id:
return jsonify(code=403, message="这个任务不属于你")
# 任务失败或者审核通过时可发起上线
if not (1, 4).__contains__(task.status):
return jsonify(code=500, message="任务不是失败或者审核通过状态")
# 清除历史记录
Record.query.filter_by(task_id=task_id).delete()
if task.action == 0:
make_version(task)
init_workspace(task)
pre_deploy(task)
revision_update(task)
post_deploy(task)
transmission(task)
update_remote_server(task)
clean_remote_server(task)
clean_local(task)
task.status = 3
task.ex_link_id = task.project.version
project = task.project
project.version = task.link_id
db.session.add(project)
db.session.add(task)
else:
update_remote_server(task)
task.status = 3
task.ex_link_id = task.project.version
project = task.project
project.version = task.link_id
db.session.add(project)
db.session.add(task)
db.session.commit()
jsonify(message="成功", code=0)
def make_version(task):
version = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
task.link_id = version
db.session.add(task)
def init_workspace(task):
from_time = int(1000 * time.time())
project = task.project
project_name = git_utils.get_project_name(project.repo_url)
build_path = "%s/%s-%s-%s" % (project.deploy_from, project_name, project.level, task.link_id)
# 拷贝本地文件
subprocess.Popen('cp -rf %s %s' % (git_utils.get_source_path(project), build_path), shell=True)
# 拷贝远程文件
for host in project.hosts.split('\n'):
version = '%s/%s/%s' % (project.release_library, project_name, task.link_id)
utils.command_with_result(hostname=host, command='mkdir -p %s' % version)
record = Record(user_id=current_user.id, task_id=task.id, action=24, duration=int(1000 * time.time()) - from_time)
db.session.add(record)
return
def pre_deploy(task):
project = task.project
from_time = int(1000 * time.time())
pre_deploy_split = task.project.pre_deploy.split('\n')
if pre_deploy_split is None:
return
cmd = ['. /etc/profile', 'cd %s' % project.get_deploy_workspace(task.link_id)]
for pre_deploy_cmd in pre_deploy_split:
if pre_deploy_cmd:
cmd.append(pre_deploy_cmd)
subprocess.Popen(' && '.join(cmd), shell=True, stdout=subprocess.PIPE)
record = Record(user_id=current_user.id,
task_id=task.id,
action=40,
duration=int(1000 * time.time()) - from_time,
command=' && '.join(cmd))
db.session.add(record)
db.session.commit()
return
def revision_update(task):
from_time = int(1000 * time.time())
cmd = git_utils.update_to_version(task)
record = Record(user_id=current_user.id,
task_id=task.id,
action=53,
duration=int(1000 * time.time()) - from_time,
command=cmd)
db.session.add(record)
db.session.commit()
return
def post_deploy(task):
from_time = int(1000 * time.time())
project = task.project
tasks = project.post_deploy.split('\n')
# 本地可能要做一些依赖环境变量的命令操作
cmd = ['. /etc/profile']
workspace = project.get_deploy_workspace(task.link_id)
# 简化用户切换目录,直接切换到当前部署空间:{deploy_from}/{env}/{project}-YYmmdd-HHiiss
cmd.append("cd %s" % workspace)
for task_command in tasks:
if task_command:
cmd.append(task_command.strip('\r\n'))
command = ' && '.join(cmd)
popen = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
popen.wait()
if popen.stderr:
app.logger.error(popen.stderr.readlines())
app.logger.info(popen.stdout.readlines())
db.session.commit()
record = Record(user_id=current_user.id,
task_id=task.id,
action=64,
duration=int(1000 * time.time()) - from_time,
command=command)
db.session.add(record)
return
def transmission(task):
from_time = int(1000 * time.time())
project = task.project
package_file_full_name = package_file(task)
remote_file_name = get_release_file(project, task)
for host in project.hosts.split('\n'):
utils.trans_data(hostname=host, remote_path=remote_file_name, local_path=package_file_full_name)
un_package_file(task)
record = Record(user_id=current_user.id,
task_id=task.id,
action=78,
duration=int(1000 * time.time()) - from_time,
command='scp ')
db.session.add(record)
db.session.commit()
def update_remote_server(task):
project = task.project
cmd = [get_remote_command(project.pre_release, task.link_id, project),
get_linked_command(task),
get_remote_command(project.post_release, task.link_id, project)]
from_time = int(1000 * time.time())
command = ' && '.join(cmd)
for host in project.hosts.split('\n'):
utils.command_with_result(hostname=host, command=command)
record = Record(user_id=current_user.id,
task_id=task.id,
action=100,
duration=int(1000 * time.time()) - from_time,
command=command)
db.session.add(record)
db.session.commit()
def clean_remote_server(task):
project = task.project
cmd = ['cd %s/%s/%s' % (project.release_library, git_utils.get_project_name(project.repo_url), task.link_id),
'rm -f %s/%s/*.tar.gz' % (
project.release_library, git_utils.get_project_name(project.repo_url)),
'ls -1 | sort -r | awk \'FNR > %d {printf("rm -rf %%s\n", $0);}\' | bash' % project.keep_version_num
]
for host in project.hosts.split('\n'):
utils.command_with_result(hostname=host, command=' && '.join(cmd))
def clean_local(task):
project = task.project
subprocess.Popen('rm -rf %s*' % project.get_deploy_workspace(task.link_id), shell=True)
return
def get_release_file(project, task):
return '%s/%s/%s.tar.gz' % (project.release_library, git_utils.get_project_name(project.repo_url), task.link_id)
def get_excludes(excludes):
excludes_cmd = ''
# 无论是否填写排除.git和.svn, 这两个目录都不会发布
excludes.append('.git')
excludes.append('.svn')
for exclude in excludes:
excludes_cmd += "--exclude=%s" % exclude.strip(' ')
return excludes_cmd
def package_file(task):
project = task.project
version = task.link_id
files = task.get_deploy_files()
excludes = project.excludes.split('\n ')
package_path = '%s.tar.gz' % project.get_deploy_workspace(version)
package_command = 'cd %s/ && tar -p %s -cz -f %s %s' % \
(project.get_deploy_workspace(version), get_excludes(excludes), package_path, files)
subprocess.Popen(package_command, shell=True, stdout=subprocess.PIPE)
return package_path
def un_package_file(task):
project = task.project
version = task.link_id
release_file = get_release_file(project, task)
web_root_path = project.release_to
release_path = '%s/%s/%s' % (project.release_library, git_utils.get_project_name(project.repo_url), version)
cmd = []
if task.file_transmission_mode == 2:
cmd.append('cp -arf %s/. %s' % web_root_path % release_path)
cmd.append(
'cd %s$s && tar --no-same-owner -pm -C %s$s -xz -f %s$s' % (release_path, release_path, release_file))
command = ' && '.join(cmd)
for host in project.hosts.split('\n'):
utils.command_with_result(hostname=host, command=command)
def get_remote_command(task, version, project):
task_split = task.split('\n')
cmd = ['. /etc/profile']
version1 = '%s/%s/%s' % (project.release_library, git_utils.get_project_name(project.repo_url), version)
cmd.append('cd %s' % version1)
for task in task_split:
cmd.append(task.strip('\r\n'))
return ' && '.join(cmd)
def get_linked_command(task):
project = task.project
release_user = project.release_user
project_name = git_utils.get_project_name(project.repo_url)
current_tmp = '%s/%s/current-%s.tmp' % (project.release_library, project_name, project_name)
linked_from = '%s/%s/%s' % (project.release_library, project_name, task.link_id)
cmd = ['ln -sfn %s %s' % (linked_from, current_tmp),
'chown -h %s %s' % (release_user, current_tmp),
'mv -fT %s %s' % (current_tmp, project.release_to)]
return ' && '.join(cmd)
| youpengfei/summer | summer/deploy.py | deploy.py | py | 9,276 | python | en | code | 4 | github-code | 13 |
5211998964 |
delay = 2
flashes = 5
entity_id = data.get('entity_id')
hass.services.call('light', 'turn_on', { 'entity_id': entity_id })
time.sleep(delay/2)
now_state = hass.states.get(entity_id)
logger.info('current %s' % now_state)
state = now_state.state
logger.info('state %s' % state)
my_data = {}
for k,v in data.items():
logger.info('adding %s,%s' % (k,v))
my_data[k] = v
current = {}
for k,v in now_state.attributes.items():
logger.info('adding to current %s,%s' % (k,v))
current[k] = v
logger.info('my_data %s' % my_data)
if 'delay' in my_data:
delay = my_data.get('delay')
del my_data['delay']
if 'flashes' in my_data:
flashes = my_data.get('flashes')
del my_data['flashes']
cache = { 'entity_id': entity_id }
logger.info('initial cache %s' % cache)
if 'brightness' in current:
cache['brightness'] = current.get('brightness')
if 'color_temp' in current:
cache['color_temp'] = current.get('color_temp')
if 'rgb_color' in current:
cache['rgb_color'] = current.get('rgb_color')
elif 'xy_color' in current:
cache['xy_color'] = current.get('xy_color')
logger.info('final cache %s' % cache)
for i in range(0, flashes):
logger.info('flash')
time.sleep(delay/2)
hass.services.call('light', 'turn_on', my_data )
time.sleep(delay/2)
hass.services.call('light', 'turn_off', { 'entity_id': entity_id })
logger.info('restore')
hass.services.call('light', 'turn_on', cache )
if state == 'off':
hass.services.call('light', 'turn_off', { 'entity_id': entity_id })
| jaredquinn/homeassistant-config | python_scripts/flash_light.py | flash_light.py | py | 1,538 | python | en | code | 22 | github-code | 13 |
29755836033 | import os
import argparse
import multiprocessing
import pandas as pd
import io
import progressbar
import time
flatten = lambda l: [item for sublist in l for item in sublist]
par = argparse.ArgumentParser()
par.add_argument("num",type=int)
par.add_argument("terrSize",type=int,nargs=2,metavar=("x","y"))
par.add_argument("gridSize",type=int,nargs=2,metavar=("x","y"))
par.add_argument("gw",type=int)
par.add_argument("relay",type=int)
par.add_argument("simTime",type=int)
par.add_argument("-s","--scale",type=int,help="Percentual value of scale, from 1% to 100%, default 15%")
par.add_argument("--visual",action="store_true")
args = par.parse_args()
xTerr,yTerr=args.terrSize
xGrid,yGrid=args.gridSize
def execute(i):
print(f"Started simulation #{i}")
if args.scale is None:
if args.visual:
#expRes.append(subprocess.run(["python" , f"simulator.py {xTerr} {yTerr} {xGrid} {yGrid} {args.gw} {args.relay} {args.simTime} --visual"], stdout=subprocess.PIPE).stdout.decode('utf-8'))
return os.popen(f"python simulator.py {xTerr} {yTerr} {xGrid} {yGrid} {args.gw} {args.relay} {args.simTime} --visual").read()
else:
#expRes.append(subprocess.run(["python" , f"simulator.py {xTerr} {yTerr} {xGrid} {yGrid} {args.gw} {args.relay} {args.simTime}"], stdout=subprocess.PIPE).stdout.decode('utf-8'))
return os.popen(f"python simulator.py {xTerr} {yTerr} {xGrid} {yGrid} {args.gw} {args.relay} {args.simTime}").read()
else:
if args.visual:
#expRes.append(subprocess.run(["python" , f"simulator.py {xTerr} {yTerr} {xGrid} {yGrid} {args.gw} {args.relay} {args.simTime} -s {args.scale} --visual"], stdout=subprocess.PIPE).stdout.decode('utf-8'))
return os.popen(f"python simulator.py {xTerr} {yTerr} {xGrid} {yGrid} {args.gw} {args.relay} {args.simTime} -s {args.scale} --visual").read()
else:
#expRes.append(subprocess.run(["python",f"simulator.py {xTerr} {yTerr} {xGrid} {yGrid} {args.gw} {args.relay} {args.simTime} -s {args.scale}"], stdout=subprocess.PIPE).stdout.decode('utf-8'))
return os.popen(f"python simulator.py {xTerr} {yTerr} {xGrid} {yGrid} {args.gw} {args.relay} {args.simTime} -s {args.scale}").read()
res=[]
process_pool = multiprocessing.Pool()
print(f"Starting {args.num} simulations")
bar = progressbar.ProgressBar(max_value=args.num)
res=process_pool.map_async(execute,list(range(args.num)))
process_pool.close()
process_pool.join()
expRes=res.get()
expRes.insert(0,"TS:T:G:Rel:S:R:MNoC:MNoS:NC")
df = pd.read_csv(io.StringIO('\n'.join(expRes)), sep=":")
if not os.path.exists('tests'):
os.makedirs('tests')
filename=r"tests/xs"+f"_{xTerr}_ys_{yTerr}_xg_{xGrid}_yg_{yGrid}_gw_{args.gw}_rel_{args.relay}_t_{args.simTime}.csv"
with open(filename, 'a') as f:
df.to_csv(f, mode='a', header=f.tell()==0,index=False)
#df.to_csv(r"test/xs"+f"_{xTerr}_ys_{yTerr}_xg_{xGrid}_yg_{yGrid}_gw_{args.gw}_rel_{args.relay}_t_{args.simTime}.csv", index = False)
#print(df)
#df = pd.DataFrame(expRes[0], sep=":")
print("Done.") | fedepaj/LoraWan-Multihop | run.py | run.py | py | 3,068 | python | en | code | 1 | github-code | 13 |
37203908034 | import warnings
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
import geomloss
from src.neighbour_op import pykeops_square_distance, cpu_square_distance
from emd import emdModule
from structural_losses import match_cost
# Chamfer Distance
def pykeops_chamfer(t1, t2):
# The following code is currently not supported for backprop
# return dist.min(axis = 2).mean(0).sum()\
# + dist.min(axis = 1).mean(0).sum()
# We use the retrieved index on torch
dist = pykeops_square_distance(t1, t2)
idx1 = dist.argmin(axis=1).expand(-1, -1, t1.shape[2])
m1 = t1.gather(1, idx1)
squared1 = ((t2 - m1) ** 2).sum(axis=(1, 2))
# augmented1 = torch.sqrt(((t2 - m1) ** 2).sum(-1)).mean(1)
idx2 = dist.argmin(axis=2).expand(-1, -1, t1.shape[2])
m2 = t2.gather(1, idx2)
squared2 = ((t1 - m2) ** 2).sum(axis=(1, 2))
# augmented2 = torch.sqrt(((t1 - m2) ** 2).sum(-1)).mean(1)
# forward + reverse
squared = squared1 + squared2
# augmented = torch.maximum(augmented1, augmented2)
return squared#, augmented
# Works with distance in torch
def cpu_chamfer(t1, t2):
dist = cpu_square_distance(t1, t2)
return torch.min(dist, dim=-1)[0].sum(1) + torch.min(dist, dim=-2)[0].sum(1)
def gaussian_ll(x, mean, log_var):
return -0.5 * (log_var + torch.pow(x - mean, 2) / torch.exp(log_var))
def kld_loss(mu, log_var, z, pseudo_mu, pseudo_log_var, d_mu=(), d_log_var=(), prior_log_var=(), **not_used):
posterior_ll = gaussian_ll(z, mu, log_var).sum(1) # sum dimensions
k = pseudo_mu.shape[0]
b = mu.shape[0]
z = z.unsqueeze(1).expand(-1, k, -1) # expand to each component
pseudo_mu = pseudo_mu.unsqueeze(0).expand(b, -1, -1) # expand to each sample
pseudo_log_var = pseudo_log_var.unsqueeze(0).expand(b, -1, -1) # expand to each sample
prior_ll = torch.logsumexp(gaussian_ll(z, pseudo_mu, pseudo_log_var).sum(2), dim=1)
kld = posterior_ll - prior_ll + np.log(k)
for d_mu, d_log_var, p_log_var in zip(d_mu, d_log_var, prior_log_var):
# d_mu = q_mu - p_mu
# d_logvar = q_logvar - p_logvar
kld_matrix = -1 - d_log_var + (d_mu ** 2) / p_log_var.exp() + d_log_var.exp()
kld += 0.5 * kld_matrix.sum(1)
return kld
# as a class because of the sinkhorn loss init
class ReconLoss:
c_rec = 1
def __init__(self, recon_loss_name, device):
self.recon_loss_name = recon_loss_name
self.device = device
self.sinkhorn = geomloss.SamplesLoss(loss='sinkhorn', p=2, blur=.001,
diameter=2, scaling=.9, backend='online')
# self.emd_dist = emdModule()
self.chamfer = pykeops_chamfer if device.type == 'cuda' else cpu_chamfer
def __call__(self, inputs, recon):
squared = self.chamfer(inputs, recon)
dict_recon = {'Chamfer': squared.sum(0)}
if self.recon_loss_name == 'Chamfer' or self.device.type == 'cpu':
recon_loss = squared.mean(0) # Sum over points, mean over samples
elif self.recon_loss_name == 'ChamferEMD':
#emd = torch.sqrt(self.emd_dist(inputs, recon, 0.005, 50)[0]).sum(1) # mean over samples
emd = match_cost(inputs.contiguous(), recon.contiguous())
recon_loss = emd.mean(0) + squared.mean(0) # Sum over points, mean over samples
dict_recon['EMD'] = emd.sum(0)
else:
assert self.recon_loss_name == 'Sinkhorn', f'Loss {self.recon_loss_name} not known'
sk_loss = self.sinkhorn(inputs, recon)
recon_loss = sk_loss.mean(0)
dict_recon['Sinkhorn'] = sk_loss.sum(0)
dict_recon['recon'] = recon_loss
return dict_recon
class AELoss(nn.Module):
def __init__(self, recon_loss_name, device, **not_used):
super().__init__()
self.recon_loss = ReconLoss(recon_loss_name, device)
def forward(self, outputs, inputs, targets):
ref_cloud = inputs[-2] # get input shape (resampled depending on the dataset)
recon = outputs['recon']
recon_loss_dict = self.recon_loss(ref_cloud, recon)
return {
'Criterion': recon_loss_dict.pop('recon'),
**recon_loss_dict
}
# VAE is only for the second encoding
# class VAELoss(AELoss):
# def __init__(self, get_recon_loss, get_reg_loss, c_reg):
# super().__init__(get_recon_loss)
# self.get_reg_loss = get_reg_loss
# self.c_kld = c_reg
#
# def forward(self, outputs, inputs, targets):
# recon_loss_dict = super().forward(outputs, inputs, targets)
# kld = kld_loss(*[outputs[key] for key in ['mu', 'log_var']])
# reg = self.c_kld * kld.mean(0)
# criterion = recon_loss_dict.pop('Criterion') + reg
# return {'Criterion': criterion,
# **recon_loss_dict,
# 'reg': reg,
# 'KLD': kld.sum(0),
# }
class VQVAELoss(AELoss):
def __init__(self, recon_loss_name, c_commitment, c_embedding, vq_ema_update, device, **not_used):
super().__init__(recon_loss_name, device)
self.c_commitment = c_commitment
self.c_embedding = c_embedding
self.vq_ema_update = vq_ema_update
def forward(self, outputs, inputs, targets):
recon_loss_dict = super().forward(outputs, inputs, targets)
if self.vq_ema_update or self.c_embedding == self.c_commitment:
commit_loss = F.mse_loss(outputs['cw_q'], outputs['cw_e'])
reg = self.c_commitment * commit_loss
else:
commit_loss = F.mse_loss(outputs['cw_q'], outputs['cw_e'].detach())
embed_loss = F.mse_loss(outputs['cw_q'].detach(), outputs['cw_e'])
reg = self.c_commitment * commit_loss + self.c_embedding * embed_loss
criterion = recon_loss_dict.pop('Criterion') + reg
return {'Criterion': criterion,
**recon_loss_dict,
'Embed Loss': commit_loss * outputs['cw_q'].shape[0] # embed_loss and commit_loss have same value
}
class CWEncoderLoss(nn.Module):
def __init__(self, c_kld, **not_used):
super().__init__()
self.c_kld = c_kld
def forward(self, outputs, inputs, targets):
kld = kld_loss(**outputs)
one_hot_idx = outputs['one_hot_idx'].clone()
sqrt_dist = torch.sqrt(outputs['cw_dist'])
cw_neg_dist = -sqrt_dist + sqrt_dist.min(2, keepdim=True)[0]
nll = -(cw_neg_dist.log_softmax(dim=2) * one_hot_idx).sum((1, 2))
criterion = nll.mean(0) + self.c_kld * kld.mean(0)
one_hot_predictions = F.one_hot(outputs['cw_dist'].argmin(2), num_classes=one_hot_idx.shape[2])
accuracy = (one_hot_idx * one_hot_predictions).sum(2).mean(1)
return {
'Criterion': criterion,
'KLD': kld.sum(0),
'NLL': nll.sum(0),
'Accuracy': accuracy.sum(0)
}
# Currently not used, replace VQVAE loo in get_ae_loss to use it
# class DoubleEncodingLoss(VQVAELoss):
# def __init__(self, recon_loss, c_commitment, c_embedding, c_kld, vq_ema_update, **not_used):
# super().__init__(recon_loss, c_commitment=c_commitment, c_embedding=c_embedding, vq_ema_update=vq_ema_update)
# self.cw_loss = CWEncoderLoss(c_kld)
#
# def forward(self, outputs, inputs, targets):
# dict_loss = super().forward(outputs, inputs, targets)
# second_dict_loss = self.cw_loss(outputs, [None, outputs['one_hot_idx']], targets)
# criterion = dict_loss.pop('Criterion') + second_dict_loss.pop('Criterion')
# return {'Criterion': criterion,
# **dict_loss,
# **second_dict_loss}
def get_ae_loss(model_head, **args):
return (AELoss if model_head in ('AE', 'Oracle') else VQVAELoss)( **args)
#return (AELoss if model_head in ('AE', 'Oracle') else DoubleEncodingLoss)(recon_loss, **other_args)
class AllMetrics:
def __init__(self, de_normalize):
self.de_normalize = de_normalize
# self.emd_dist = emdModule()
def __call__(self, outputs, inputs):
scale = inputs[0]
ref_cloud = inputs[-2] # get input shape (resampled depending on the dataset)
recon = outputs['recon']
if self.de_normalize:
scale = scale.view(-1, 1, 1).expand_as(recon)
recon *= scale
ref_cloud *= scale
return self.batched_pairwise_similarity(ref_cloud, recon)
@staticmethod
def batched_pairwise_similarity(clouds1, clouds2):
if clouds1.device.type == 'cpu':
squared = cpu_chamfer(clouds1, clouds2)
warnings.warn('Emd only supports cuda tensors', category=RuntimeWarning)
emd = torch.zeros(1, 1)
else:
squared = pykeops_chamfer(clouds1, clouds2)
emd = match_cost(clouds1.contiguous(), clouds2.contiguous())
# emd = torch.sqrt(self.emd_dist(clouds1, clouds2, 0.005, 50)[0]).mean(1)
if clouds1.shape == clouds2.shape:
squared /= clouds1.shape[1] # Chamfer is normalised by ref and recon number of points when equal
emd /= clouds1.shape[1] # Chamfer is normalised by ref and recon number of points when equal
dict_recon_metrics = {
'Chamfer': squared.sum(0),
'EMD': emd.sum(0)
}
return dict_recon_metrics
| nverchev/PCGen | src/loss_and_metrics.py | loss_and_metrics.py | py | 9,412 | python | en | code | 0 | github-code | 13 |
8424778749 | # -*- coding: utf-8 -*-
import pandas as pd
import os
import csv
from datetime import datetime
OpFolderPath = 'E:/Pycharm/data/option_data'
VolFolderPath = 'E:/Pycharm/data/option_vol'
AnalyzePath = 'E:/Pycharm/analyze'
FutureMap = pd.read_csv('E:/Pycharm/data/log/FutureMap.csv')
VolAnalyzePath = os.path.join(AnalyzePath, 'vol_analyze')
etfPricePath = os.path.join(VolAnalyzePath, 'etf_price.csv')
MapPath = os.path.join(OpFolderPath, 'map.csv')
MapDf = pd.read_csv(MapPath)
future_names = ['time', 'id', 'OpenPrice', 'HighestPrice', 'LowestPrice', 'LastPrice', 'PreClosePrice',
'PreSettlementPrice', 'SettlementPrice', 'Volume', '0.000000', 'AskPrice1', 'BidPrice1', 'AskVolume1',
'BidVolume1', 'UpdateTime', 'UpdateMillisec', 'OpenInterest']
ETF_names = ['time', 'id', 'time2', 'OpenPrice', 'HighestPrice', 'LowestPrice', 'LastPrice', 'PreclosePrice', 'Num',
'0.000000', 'AskPrice1', 'AskPrice2', 'AskPrice3', 'AskPrice4', 'AskPrice5', 'BidPrice1', 'BidPrice2',
'BidPrice3', 'BidPrice4', 'BidPrice5', 'AskVol1', 'AskVol2', 'AskVol3', 'AskVol4', 'AskVol5', 'BidVol1',
'BidVol2', 'BidVol3', 'BidVol4', 'BidVol5', 'signal', 'time3']
csv_path_list = [os.path.join(VolFolderPath, x) for x in os.listdir(VolFolderPath)]
Period = MapDf['date'].drop_duplicates().values
etf_price = pd.read_csv(etfPricePath, index_col=0)
# OptionMap = pd.DataFrame(columns=['expiry', 'date', 'strike', 'id', 'type', 'path'])
def create_map():
csv_path_list = [os.path.join(VolFolderPath, x) for x in os.listdir(VolFolderPath)]
OptionMap = {'expiry': [], 'date': [], 'strike': [], 'id': [], 'type': [], 'path': []}
for csv_file in csv_path_list:
if csv_file.find('副本') != -1: # 跳过副本
continue
DailyMap = {'expiry': [], 'date': [], 'strike': [], 'id': [], 'type': [], 'path': []}
with open(csv_file) as f:
reader = csv.reader(f)
for row in reader:
tmp_date = os.path.split(csv_file)[1][-12:-4]
if row[2] not in DailyMap['id']:
tmp_type = 'C' if row[22] == '1' else 'P'
DailyMap['expiry'].append(row[23])
strike = int(float(row[20])*1000)
DailyMap['date'].append(tmp_date)
DailyMap['strike'].append(strike)
DailyMap['id'].append(row[2])
DailyMap['type'].append(tmp_type)
DailyMap['path'].append(os.path.join(OpFolderPath, row[23], tmp_date, str(strike),
row[2]+tmp_type, row[2]+'vols_data.csv'))
for k, v in OptionMap.items():
OptionMap[k] += DailyMap[k]
print(csv_file)
MapDf = pd.DataFrame(OptionMap, columns=['expiry', 'date', 'strike', 'id', 'type', 'path'])
MapDf.to_csv(os.path.join(OpFolderPath, 'map.csv'))
def mkdir(path):
folder = os.path.exists(path)
if not folder:
os.makedirs(path)
return 1
return 0
def create_folder():
with open(MapPath) as f:
reader = csv.reader(f)
for row in reader:
if row[0]:
mkdir(os.path.join(OpFolderPath, row[1]))
mkdir(os.path.join(OpFolderPath, row[1], row[2]))
mkdir(os.path.join(OpFolderPath, row[1], row[2], row[3]))
mkdir(os.path.join(OpFolderPath, row[1], row[2], row[3], row[4]+row[5]))
print('Done')
return 0
names = ['timestamp', 'spot_price', 'id', 'OptionPrice', 'BidPrice', 'AskPrice', 'Sigma', 'BidSigma', 'AskSigma',
'Delta', 'Vega', 'Gamma', 'Theta', 'Rho', 'RhoB', 'Risk_free_rate', 'Borrow_rate', 'time2expiry',
'Delta_time_decay', 'Delta_time', 'strike', 'Z', 'type', 'expiry', 'etf_price']
def copy_file():
MapDf = pd.read_csv(MapPath)
csv_path_list = [os.path.join(VolFolderPath, x) for x in os.listdir(VolFolderPath)]
for csv_file in csv_path_list:
if csv_file.find('副本') != -1: # 跳过副本
continue
tmp_date = os.path.split(csv_file)[1][-12:-4]
daily_vol = pd.read_csv(csv_file, header=None, names=names)
daily_opt_id = MapDf[MapDf.date == int(tmp_date)]['id']
for opt_id in daily_opt_id:
to_csv_path = MapDf[MapDf.date == int(tmp_date)][MapDf.id == int(opt_id)]['path'].values[0] # 为什么这么麻烦?
daily_op_data = daily_vol[daily_vol.id == int(opt_id)].reset_index()
del daily_op_data['index']
daily_op_data.to_csv(to_csv_path)
print(csv_file)
def control(c_map=0, c_folder=0, c_file=0):
if c_map == 1:
create_map()
if c_folder == 1:
create_folder()
if c_file == 1:
copy_file()
# control(c_file=1)
| Lee052/huatai-intern | code/map_folder.py | map_folder.py | py | 4,825 | python | en | code | 0 | github-code | 13 |
70645888337 | import matplotlib.pyplot as plt
import numpy as np
def display_data():
data = []
file = open('data.txt', 'r')
for line in file.read().splitlines():
if line:
data.append(float(line))
file.close()
fig, ax = plt.subplots()
ax.plot(data, data, label='linear')
ax.plot(data, np.power(data,2), label='quadratic')
ax.plot(data, np.power(data,3), label='cubic')
plt.xlabel('Unknown Value')
plt.ylabel('Hash Difficulty')
ax.legend()
plt.savefig('chart.png')
plt.cla()
plt.clf()
plt.close('all')
| jaikejennison/pi-miner-universal | Python/display.py | display.py | py | 568 | python | en | code | 0 | github-code | 13 |
31709308568 | from tkinter import *
class startscreen():
'''Deze class betreft het opstartscherm waarbij de speler de keuze krijgt of hij/zij de code wil bedenken
of raden'''
playerchoice = None
def createscreen(self, windowwidth, windowheight, windowtitle, title, bgcolor):
'''Maakt een scherm aan en geeft die terug'''
root = Tk()
# De breedte en hoogte van het scherm ophalen
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
# De voorafgaande informatie gebruiken om de interface in het midden van het scherm te plaatsen
x_coordinate = int((screenwidth/2) - (windowwidth/2))
y_coordinate = int((screenheight/2) - (windowheight/2))
root.geometry('{}x{}+{}+{}'.format(windowwidth, windowheight, x_coordinate, y_coordinate))
root.configure(bg=bgcolor)
root.title(windowtitle)
root.resizable(False, False)
screentitle = Label(root,
text=title,
font=('',15,'bold'),
bg=bgcolor)
screentitle.place(relx=0.5, rely=0.15, anchor=CENTER)
return root
def createbuttons(self, root, buttoncolor, width, height, spacing):
'''Maakt de knoppen, zodat de gebruiker de keuze kan maken om de codemaster te zijn
of de code te raden'''
codemastercomputer = Button(root,
text='Guess the code',
bg=buttoncolor,
width=width,
height=height)
codemastercomputer.place(relx=0.5, rely=0.5-spacing, anchor=CENTER)
codemasterplayer = Button(root,
text='Make the code',
bg=buttoncolor,
width=width,
height=height)
codemasterplayer.place(relx=0.5, rely=0.5+spacing, anchor=CENTER)
return codemastercomputer, codemasterplayer
def gotoCMComputer(self, root):
'''Deze functie haalt het scherm weg en slaat de keuze 'Guess the code' op in een variabele'''
#playerchoice is False als de gebruiker wil dat de computer de codemaster is
startscreen.playerchoice = False
root.destroy()
def gotoCMPlayer(self, root):
'''Deze functie haalt het scherm weg en slaat de keuze 'Make the code' op in een variabele'''
#playerchoice is True als de gebruiker de codemaster wil zijn
startscreen.playerchoice = True
root.destroy()
class CodeMaster():
'''Deze class verzorgt alle grafische weergaves die nodig zijn om het spel Mastermin weer te geven'''
#algemene class variabelen om voorbij de functies te tracken
code = []
pins = []
step = 1
def creategameframe(self, root, width, side, bgcolor):
'''Deze functie maakt een frame waarin de game gespeeld kan worden en returnt die'''
mastergame = Frame(root,
width=width,
bg=bgcolor)
mastergame.pack(side=side, fill=Y, expand=True, anchor='w')
return mastergame
def placecolor(self, frame, color, bordercolor, bgcolor, x, y, width, height):
'''Deze functie maakt een rondje op basis van de bijgevoegde variabelen en returnt dan het
canvas object voor het gemaakte rondje'''
tempcanvas = Canvas(frame,
bg=bgcolor,
width=width,
height=height,
highlightthickness=0)
tempcanvas.place(relx=x, rely=y, anchor=CENTER)
tempcanvas.create_oval(0,0,width,height, width=2, fill=color, outline=bordercolor)
return tempcanvas
def placerow(self, frame, colors, bgcolor, x, xstep, y, width, height, bind, start, end):
'''Deze functie plaatst een hele lijst aan gekleurde rondjes op het scherm en kan
ook nog een gegeven functie laten uitvoeren als je op een rondje drukt die deze functie
maakt'''
for ind in range(start, end):
if colors[ind] == 'white':
bordercolor = 'black'
else:
bordercolor = colors[ind]
circle = self.placecolor(self, frame, colors[ind], bordercolor,
bgcolor, x+(ind-start)*xstep, y, width, height)
if bind is not None:
circle.bind('<1>', bind(self, ind))
def colorpick(self, frame, allcolors, bgcolor, title):
'''Deze functie laat de mogelijke kleuren zien waarop de speler een keuze kan maken'''
#deze variabele wordt gebruikt door de hoofdmodule om te detecteren of er een knop is ingedrukt
CodeMaster.goVar = IntVar()
choiceframe = CodeMaster.creategameframe(CodeMaster, frame, 400, RIGHT, 'white')
#deze if statements kijkt of de kleuren voor de code weergegeven moeten worden of de
#zwart/witte pinnen
if len(allcolors) > 2:
CodeMaster.code = []
results = CodeMaster.code
else:
CodeMaster.pins = []
results = CodeMaster.pins
x = 0.3
xstep = 0.2
#deze for-loop zal ervoor zorgen dat de gegeven kleuren op rijen worden geplaatst niet groter dan 3
for ind in range(0, len(allcolors), 3):
endindex = ind+3
#voorkomt dat er een indexerror komt voor lijsten die niet uit een veelvoud van 3 aantal
#items bestaan
if endindex > len(allcolors):
endindex = len(allcolors)
#deze if-statement kijkt of er een even aantal items in de lijst zitten en past zo de begin 'x' aan
#om ervoor te zorgen dat deze nog steeds in het midden van het scherm staan
if (endindex - ind) % 2 == 0:
x += (xstep / 2)
self.placerow(self, choiceframe, allcolors, bgcolor, x, xstep,
0.3 + ind/3*0.1, 50, 50,
lambda x, y:(lambda x:self.coloradd(x, y, choiceframe, allcolors, results)), ind, endindex)
#de algemene titel en de knop voor het bevestigen van de keuze
title = Label(choiceframe,
text=title,
font=('',15,'bold'),
bg=bgcolor)
title.place(relx=0.5, rely=0.2, anchor=CENTER)
confirm = Button(choiceframe,
text='Confirm',
bg='brown',
width=15,
height=2)
confirm.place(relx=0.5, rely=0.6, anchor=CENTER)
#de bevestigingsknop en frame die hiervoor gebruikt wordt worden gereturnd voor verder gebruik
return confirm, choiceframe
def coloradd(self, index, root, colors, result):
'''Deze functie voegt een kleur toe aan het rijtje van gekozen kleuren'''
#de lengte van de code kan maximaal 4 zijn
if len(result) < 4:
result.append(colors[index])
CodeMaster.colorshow(CodeMaster, root, result)
def colorshow(self, root, result):
'''Deze functie geeft de gekozen kleuren weer'''
#haalt frame weg en plaatst opnieuw, zodat weggehaalde kleuren verdwijnen
try:
self.colorframe.destroy()
except AttributeError:
pass
#maakt frame opnieuw, zodat de huidige gekozen kleuren hierin geplaatst kunnen worden
self.colorframe = Frame(root,
bg='white')
self.colorframe.place(rely=0.7, height=100, width=400)
self.placerow(self, self.colorframe, result, 'white', 0.15, 0.2, 0.5, 50, 50,
lambda x, y:(lambda x:self.colorremove(x, y, root, result)), 0, len(result))
def colorremove(self, index, root, result):
'''Deze functie verwijdert een kleur uit het rijtje van de gekozen kleuren'''
result.pop(index)
CodeMaster.colorshow(CodeMaster, root, result)
def codeconfirm(self, frame, placeframe, background):
'''Deze functie bevestigt het rijtje van gekozen kleuren voor de code'''
#functie wordt alleen uitgevoerd als de code uit 4 kleuren bestaat
if len(CodeMaster.code) == 4:
frame.destroy()
self.placerow(self, placeframe, CodeMaster.code, background, 0.2, 0.2, 0.92,
50, 50, None, 0, len(CodeMaster.code))
CodeMaster.goVar.set(1)
def pinconfirm(self, frame, placeframe, background, pins, totalguess, guessnumber):
'''Deze functie haalt het scherm waar de pins geselecteerd kunnen worden weg en
voert hierna een functie uit die de pinnen op het scherm plaatst'''
frame.destroy()
CodeMaster.goVar.set(1)
self.showpins(self, placeframe, background, pins, totalguess, guessnumber)
def showpins(self, placeframe, background, guess, totalguess, guessnumber):
'''Deze functie laat de zwart/witte pinnen die als feedback voortkomen uit de code zien
op het scherm'''
for index in range(0, len(guess), 2):
endindex = index + 2
if endindex > len(guess):
endindex = len(guess)
self.placerow(self, placeframe, guess, background, 0.85, 0.08, guessnumber/totalguess*0.8-0.02+index*0.02,
15, 15, None, index, endindex)
def showguess(self, frame, placeframe, background, colorguess, totalguess, guessnumber):
'''Deze functie laat de kleuren zien die zijn geraden op het scherm'''
if len(colorguess) == 4:
if frame != None:
frame.destroy()
CodeMaster.goVar.set(1)
self.placerow(self, placeframe, colorguess, background, 0.15, 0.16, guessnumber/totalguess*0.8,
40, 40, None, 0, len(colorguess))
def showendmessage(self, root, text):
'''Deze functie maakt een eindbericht als de game is afgelopen'''
endmessage = Label(root,
text=text,
font=('', 15, 'bold'),
bg='white')
endmessage.pack(side=RIGHT, padx=(0, 50)) | LukaHerrmann/ProjectC_Assignments | Mastermind/Graphical_Interface.py | Graphical_Interface.py | py | 10,294 | python | nl | code | 0 | github-code | 13 |
30842057947 | import copy
import os
import time
from ctypes import cdll
import numpy as np
import torch
from torch import device
from torch.utils.tensorboard import SummaryWriter
from option import args_parser
from utils import *
from models import MLP, CNNMnist, CNNFashion_Mnist, CNNCifar, MLPPurchase100, ResNetCifar
from proto_client import call_grpc_start, call_grpc_aggregate
from sampling import client_iid
from update import LocalUpdate, diff_weights, l2clipping, update_global_weights
if __name__ == '__main__':
# parse args
args = args_parser()
path_project = os.path.abspath('.')
logger = SummaryWriter(os.path.join(path_project, 'log'))
if args.gpu_id:
torch.cuda.set_device(args.gpu_id)
device = 'cuda' if args.gpu_id else 'cpu'
path_project = os.path.abspath('.')
train_dataset, test_dataset, user_groups, class_labels = get_dataset(
args, path_project, args.num_of_label_k, args.random_num_label)
if args.model == 'cnn':
# Convolutional neural network
if args.dataset == 'mnist':
global_model = CNNMnist(args=args)
elif args.dataset == 'fmnist':
global_model = CNNFashion_Mnist(args=args)
elif args.dataset == 'cifar10':
global_model = CNNCifar(args.num_classes)
elif args.dataset == 'cifar100':
global_model = ResNetCifar(args.num_classes)
else:
exit('Error: no dataset')
elif args.model == 'mlp':
if args.dataset == 'purchase100':
img_size = train_dataset[0][0].shape
len_in = 1
for x in img_size:
len_in *= x
global_model = MLPPurchase100(
dim_in=len_in,
dim_hidden=64,
dim_out=args.num_classes)
else:
# Multi-layer preceptron
img_size = train_dataset[0][0].shape
len_in = 1
for x in img_size:
len_in *= x
global_model = MLP(
dim_in=len_in,
dim_hidden=64,
dim_out=args.num_classes)
else:
exit('Error: unrecognized model')
# Set the model to train and send it to device.
global_model.to(device)
global_model.train()
if args.verbose:
print(global_model)
# copy weights
global_weights = global_model.state_dict()
print(global_model)
num_of_params = count_parameters(global_model)
print("num_of_params: ",num_of_params)
buffer_names = get_buffer_names(global_model)
# Training
train_loss, train_accuracy = [], []
test_loss_list = []
print_every = 20 # print training accuracy for each {print_every} epochs
print("args.sparse_ratio: ",args.sparse_ratio)
if args.sparse_ratio!=0:
num_of_sparse_params = int(args.sparse_ratio * num_of_params) # 稀疏聚合
else:
num_of_sparse_params = 0
for epoch in range(args.epochs):
print(f' | Global Training Round : {epoch + 1} |')
local_weights_diffs, local_losses = [], []
global_model.train()
idxs_users = client_iid(args.frac, args.num_users)
for idx in idxs_users:
local_model = LocalUpdate(
dataset=train_dataset,
idxs=user_groups[idx],
logger=logger,
device=device,
local_bs=args.local_bs,
optimizer=args.optimizer,
lr=args.lr,
local_ep=args.local_ep,
momentum=args.momentum,
verbose=args.verbose)
w, loss = local_model.update_weights(
model=copy.deepcopy(global_model), global_round=epoch
)
local_weights_diffs.append(diff_weights(global_weights, w))
print("loss: ", loss)
local_losses.append(copy.deepcopy(loss))
encrypted_parameters = []
for client_id, local_weights_diff in zip(idxs_users, local_weights_diffs):
# 非稀疏梯度聚合
if args.sparse_ratio==0:
#print("dense aggregation...")
bytes_local_weight = serialize_dense(local_weights_diff, buffer_names, num_of_params)
# print("len bytes_local_weight: ",len(bytes_local_weight))
# 稀疏梯度聚合
else:
#print("sparse aggregation...")
top_k_local_weights_diff, top_k_indices = zero_except_top_k_weights(local_weights_diff, buffer_names,num_of_sparse_params)
bytes_local_weight = serialize_sparse(top_k_local_weights_diff, buffer_names, top_k_indices)
#print("len bytes_local_weight: ", len(bytes_local_weight))
print(top_k_indices)
encrypted_local_weight = sgx_encrypt(bytes_local_weight)
encrypted_parameters.extend(encrypted_local_weight)
# 调用远程rpc聚合
print("call rpc...")
flattend_aggregated_weights, execution_time, secure_sampled_client_ids,_ = call_grpc_aggregate(
fl_id=1,
round=epoch,
encrypted_parameters=encrypted_parameters,
num_of_parameters=num_of_params, # 所有的参数个数
num_of_sparse_parameters=num_of_sparse_params, # 稀疏参数个数
client_ids=idxs_users,
aggregation_alg=3, # aggregation_alg=1 普通聚合 aggregation_alg=2 安全聚合
optimal_num_of_clients=2
)
learnable_parameters = get_learnable_parameters(global_weights, buffer_names)
aggregated_weights = recover_flattened(torch.Tensor(flattend_aggregated_weights), global_weights,learnable_parameters)
update_global_weights(global_weights, [aggregated_weights])
# 本地聚合
#update_global_weights(global_weights, local_weights_diffs)
| MJXXGPF/SecureAggregation_GPF | client/fl_main.py | fl_main.py | py | 5,876 | python | en | code | 0 | github-code | 13 |
3125433131 | from config import Config
from ibm_watson import AssistantV1
from ibm_watson import TextToSpeechV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson import IAMTokenManager
from ibm_cloud_sdk_core.authenticators import BearerTokenAuthenticator
class WatsonObjects:
def __init__(self, config):
self.config = config
def createTTS(self):
apikey = self.config.getValue("TextToSpeech", "apikey")
url = self.config.getValue("TextToSpeech", "service_url")
use_bearer_token = self.config.getBoolean("TextToSpeech", "use_bearer_token")
if use_bearer_token != True:
authenticator = IAMAuthenticator(apikey)
else:
iam_token_manager = IAMTokenManager(apikey=apikey)
bearerToken = iam_token_manager.get_token()
authenticator = BearerTokenAuthenticator(bearerToken)
text_to_speech = TextToSpeechV1(authenticator=authenticator)
text_to_speech.set_service_url(url)
text_to_speech.set_default_headers({'x-watson-learning-opt-out': "true"})
return text_to_speech
def createWA(self):
apikey = self.config.getValue("Assistant", "apikey")
url = self.config.getValue("Assistant", "service_url")
use_bearer_token = self.config.getBoolean("Assistant", "use_bearer_token")
if use_bearer_token != True:
authenticator = IAMAuthenticator(apikey)
else:
iam_token_manager = IAMTokenManager(apikey=apikey)
bearerToken = iam_token_manager.get_token()
authenticator = BearerTokenAuthenticator(bearerToken)
assistant = AssistantV1(authenticator=authenticator, version="2021-11-05")
assistant.set_service_url(url)
assistant.set_default_headers({'x-watson-learning-opt-out': "true"})
return assistant | IBM/watson-tts-python | watson_objects.py | watson_objects.py | py | 1,935 | python | en | code | 19 | github-code | 13 |
26692854081 | import json
import jwt
import os
import motorengine
import tornado.ioloop
import tornado.web
from models import Portfolio
class MainHandler(tornado.web.RequestHandler):
def get_user(self):
header = self.request.headers.get('Authorization')
try:
token = header.split()[1]
return jwt.decode(token, verify=False)['sub']
except:
return None
async def get(self):
user = self.get_user()
if user is None:
self.set_status(401)
return
portfolio = await Portfolio.objects.get(user=user)
if portfolio is None:
portfolio = await Portfolio.objects.create(user=user)
self.write(json.dumps(portfolio.serialize()))
async def post(self):
user = self.get_user()
if user is None:
self.set_status(401)
return
data = json.loads(self.request.body.decode("utf-8"))
portfolio = await Portfolio.objects.get(user=user)
if portfolio is None:
self.set_status(404, 'Portfolio not found!')
return
try:
action = data.get('action')
if action == 'reset':
await portfolio.reset()
else:
await portfolio.make_deal(data['sym'], data['units'], data['price'])
self.write(json.dumps(portfolio.serialize()))
except Exception as e:
self.write(str(e))
def main():
db_name = os.environ.get('DB_NAME', 'test')
db_host = os.environ.get('DB_HOST', '10.200.10.1')
db_port = os.environ.get('DB_PORT', '27017')
db_user = os.environ.get('DB_USER', '')
db_password = os.environ.get('DB_PASSWORD', '')
credentials = None if not db_user else '{0}:{1}@'.format(db_user, db_password)
if credentials is not None:
db_url = 'mongodb://{0}{1}:{2}/{3}'.format(credentials, db_host, db_port, db_name)
else:
db_url = 'mongodb://{0}:{1}/'.format(db_host, db_port)
app = tornado.web.Application([
(r"/", MainHandler),
])
app.listen(8003)
io_loop = tornado.ioloop.IOLoop.current()
motorengine.connect(db_name, host=db_url, io_loop=io_loop)
io_loop.start()
if __name__ == "__main__":
main()
| icpetcu/StockTrainer | portfolio/service/main.py | main.py | py | 2,268 | python | en | code | 1 | github-code | 13 |
74220695059 | #! /usr/bin/env python3
# coding: UTF-8
import random
import mysql.connector
from database import MyDatabase
"""
Make requests in the database.
"""
class Category(MyDatabase):
""" This class performs operations in the table : Category """
def insert_category(self, category):
""" Insert a category in the database and return its ID. """
self.cursor.execute("""
INSERT INTO Category (category)
VALUES (%s)
""", (category, ))
self.connection.commit()
# print("\nLa catégorie", category, "a été ajoutée avec succès.")
self.cursor.execute("""
SELECT id
FROM Category
WHERE category = '{}';""".format(category))
category_id = self.cursor.fetchone()
return category_id[0]
def show_categories(self):
""" Display categories. """
self.new_connection()
self.cursor.execute("""
SELECT id, category
FROM Category
ORDER BY id;""")
results = self.cursor.fetchall()
self.new_connection_close()
categories_id = []
for _id, _category in results:
categories_id.append(str(_id))
print("[", _id, "] -", _category)
return categories_id
class Save(MyDatabase):
""" This class performs operations in the table : Save """
def save_products(self, product_id, new_product_id):
""" Register products in the database. """
self.new_connection()
try:
self.cursor.execute("""
INSERT INTO Save (id_product, id_new_product)
VALUES (%s, %s)""",
(product_id, new_product_id))
self.connection.commit()
print("\nVotre choix est enregistré.")
except mysql.connector.errors.IntegrityError as e:
print("\nCe choix est déjà enregistré.")
self.new_connection_close()
def show_new_products(self):
""" Display the products registered in the database. """
self.new_connection()
self.cursor.execute("""
SELECT Product.name
FROM Product
INNER JOIN Save
ON Product.id = Save.id_product
WHERE Product.id = Save.id_product
ORDER BY Save.id;""")
products = self.cursor.fetchall()
self.cursor.execute("""
SELECT Product.name
FROM Product
INNER JOIN Save
ON Product.id = Save.id_new_product
WHERE Product.id = Save.id_new_product
ORDER BY Save.id;""")
new_products = self.cursor.fetchall()
self.new_connection_close()
if not products:
print("\nVous n'avez rien enregistré.")
else:
for p_name, n_name in zip(products, new_products):
print(p_name[0], "est remplacé par", n_name[0])
class Product(MyDatabase):
""" This class performs operations in the table : Product """
def insert_food(self, p_name, ingredients,
cat_id, store, url, nutriscore):
""" Insert products into the database. """
try:
self.cursor.execute("""
INSERT INTO Product (name, description, category,
store, url, nutrition_grade)
VALUES (%s, %s, %s, %s, %s, %s)""",
(p_name, ingredients, cat_id,
store, url, nutriscore))
self.connection.commit()
# print("Ajout :", p_name)
except mysql.connector.errors.IntegrityError as e:
# print("Erreur :", e)
pass
def show_products(self, category_id):
""" Display the products of a category. """
self.new_connection()
self.cursor.execute("""
SELECT category
FROM Category
WHERE id = {};""".format(category_id))
results = self.cursor.fetchone()
print("\nVoici les aliments de la catégorie :", results[0])
self.cursor.execute("""
SELECT id, name
FROM Product
WHERE category = '{}'
ORDER BY id;""".format(category_id))
results = self.cursor.fetchall()
self.new_connection_close()
products_id = []
for _id, _name in results:
products_id.append(str(_id))
print("[", _id, "] -", _name)
return products_id
def proposition(self, id_product, category_id):
""" Select a new product at random. """
self.new_connection()
self.cursor.execute("""
SELECT id, name, nutrition_grade
FROM Product
WHERE id = {};""".format(id_product))
product = self.cursor.fetchone()
# The nutriscore of the selected product.
self.nutriscore_selected = product[2]
search = self.select_by_nutriscore(category_id)
self.new_connection_close()
if search is False:
return False
i = 0
for _id, _name, _nutrition_grade, \
_description, _store, _url in search:
# If the selected product is in the list, it is deleted.
if int(id_product) == _id:
search.remove(search[i])
i += 1
propose = random.randrange(len(search))
print("\n->", product[1], "( nutriscore", product[2], ")")
print("peut être remplacé par :", search[propose][1],
"( nutriscore", search[propose][2], ")\n")
print("Description :", search[propose][3], "\n")
print("Magasin(s) :", search[propose][4], "\n")
print("Lien :", search[propose][5], "\n---")
my_proposition = search[propose][0]
return my_proposition
def select_by_nutriscore(self, category_id, nutriscore="a"):
""" Select new products by its nutriscore. """
while True:
self.cursor.execute("""
SELECT id, name, nutrition_grade, description, store, url
FROM Product
WHERE nutrition_grade = '{}'
AND category = '{}';""".format(nutriscore, category_id))
results = self.cursor.fetchall()
# If results is empty or if the selected product
# is the only one with this nutriscore.
if not results or \
(self.nutriscore_selected == nutriscore and
len(results) == 1):
print("Nous avons aucun substitut avec un nutriscore",
nutriscore.upper(),
"à vous proposer pour cet aliment.")
# Stop if the nutriscore = the nutriscore of the product
if self.nutriscore_selected == nutriscore:
return False
# letter + 1
c = ord(nutriscore[0]) + 1
nutriscore = chr(c)
else:
break
return results
| jeremy10000/API-OFF | tables.py | tables.py | py | 7,079 | python | en | code | 0 | github-code | 13 |
36529169764 | from . import endpoints
from ...api import _request_executor
def shard_data (service_platform,
api_key):
""" Get League of Legends status for the given shard.
References:
https://developer.riotgames.com/regional-endpoints.html
https://developer.riotgames.com/api-methods/#lol-status-v3/GET_getShardData
Arguments:
service_platform (str): The service platform that the request should be issued to.
api_key (str): The client's api key.
Returns:
dict: the details of the response to the issued http request.
"""
header_parameters = {
"X-Riot-Token": api_key
}
url = endpoints.v3["host"]["endpoint"].format(service_platform)
path = endpoints.v3["status"]["shard-data"]["endpoint"]
return _request_executor.get("".join([url, path]),
header_parameters=header_parameters) | Alex-Weatherhead/riot_api | riot_api/api/get/lol_status_v3.py | lol_status_v3.py | py | 917 | python | en | code | 0 | github-code | 13 |
3348452953 | """
User Interface module
This module exposes a number of tools and class definitions for
interacting with IDA's user interface. This includes things such
as getting the current state of user input, information about
windows that are in use as well as utilities for simplifying the
customization of the interface.
There are a few namespaces that are provided in order to get the
current state. The ``ui.current`` namespace allows for one to get
the current address, function, segment, window, as well as a number
of other things.
A number of namespaces defined within this module also allows a
user to interact with the different windows that are currently
in use. This can allow for one to automatically show or hide a
window that they wish to expose to the user.
"""
import six, builtins
import sys, os, operator, math, threading, time, functools, inspect, itertools
import logging, ctypes
import idaapi, internal
import database as _database, segment as _segment
## TODO:
# locate window under current cursor position
# pop-up a menu item
# pop-up a form/messagebox
# another item menu to toolbar
# find the QAction associated with a command (or keypress)
class application(object):
"""
This namespace is for getting information about the application user-interface.
"""
def __new__(cls):
'''Return the current instance of the application.'''
raise internal.exceptions.MissingMethodError
@classmethod
def window(cls):
'''Return the current window for the application.'''
raise internal.exceptions.MissingMethodError
@classmethod
def windows(cls):
'''Return all of the top-level windows for the application.'''
raise internal.exceptions.MissingMethodError
@classmethod
def beep(cls):
'''Beep using the application interface.'''
return idaapi.beep()
beep = internal.utils.alias(application.beep, 'application')
class ask(object):
"""
This namespace contains utilities for asking the user for some
particular type of information. These will typically require a
user-interface of some sort and will block while waiting for the
user to respond.
If the `default` parameter is specified to any of the functions
within this namespace, then its value will be used by default
in the inbox that is displayed to the user.
"""
@internal.utils.multicase()
def __new__(cls, **default):
'''Request the user choose from the options "yes", "no", or "cancel".'''
return cls(u'', **default)
@internal.utils.multicase(message=six.string_types)
def __new__(cls, message, **default):
'''Request the user choose from the options "yes", "no", or "cancel" using the specified `message` as the prompt.'''
return cls.yn(message, **default)
@internal.utils.multicase()
@classmethod
def yn(cls, **default):
'''Request the user choose from the options "yes", "no", or "cancel".'''
return cls.yn(u'', **default)
@internal.utils.multicase(message=six.string_types)
@classmethod
@internal.utils.string.decorate_arguments('message')
def yn(cls, message, **default):
"""Request the user choose from the options "yes", "no", or "cancel" using the specified `message` as the prompt.
If any of the options are specified as a boolean, then it is
assumed that this option will be the default. If the user
chooses "cancel", then this value will be returned instead of
the value ``None``.
"""
state = {'no': getattr(idaapi, 'ASKBTN_NO', 0), 'yes': getattr(idaapi, 'ASKBTN_YES', 1), 'cancel': getattr(idaapi, 'ASKBTN_CANCEL', -1)}
results = {state['no']: False, state['yes']: True}
if default:
keys = {item for item in default.keys()}
keys = {item.lower() for item in keys if default.get(item, False)}
dflt = next((item for item in keys), 'cancel')
else:
dflt = 'cancel'
res = idaapi.ask_yn(state[dflt], internal.utils.string.to(message))
return results.get(res, None)
@internal.utils.multicase()
@classmethod
def address(cls, **default):
'''Request the user provide an address.'''
return cls.address(u'', **default)
@internal.utils.multicase(message=six.string_types)
@classmethod
@internal.utils.string.decorate_arguments('message')
def address(cls, message, **default):
"""Request the user provide an address using the specified `message` as the prompt.
If the `valid` parameter is specified, then verify that the
address is within the bounds of the database. If the `bounds`
parameter is specified, then verify that the address chosen
by the user is within the provided bounds.
"""
dflt = next((default[k] for k in ['default', 'address', 'ea', 'addr'] if k in default), current.address())
# Ask the user for an address...
ea = idaapi.ask_addr(dflt, internal.utils.string.to(message))
# If we received idaapi.BADADDR, then the user gave us a bogus
# value that we need to return None for.
if ea == idaapi.BADADDR:
return None
# Grab the bounds that we'll need to compare the address to from
# the parameters or the database configuration.
bounds = next((default[k] for k in ['bounds'] if k in default), _database.config.bounds())
# If we were asked to verify the address, or we were given some
# boundaries to check it against..then do that here.
if default.get('verify', 'bounds' in default):
l, r = bounds
return ea if l <= ea < r else None
# Otherwise, we can just return the address here.
return ea
@internal.utils.multicase()
@classmethod
def integer(cls, **default):
'''Request the user provide an integer.'''
return cls.integer(u'', **default)
@internal.utils.multicase(message=six.string_types)
@classmethod
@internal.utils.string.decorate_arguments('message')
def integer(cls, message, **default):
'''Request the user provide an integer using the specified `message` as the prompt.'''
dflt = next((default[k] for k in ['default', 'integer', 'long', 'int'] if k in default), getattr(cls, '__last_integer__', 0))
# Ask the user for some kind of integer...
integer = idaapi.ask_long(dflt, internal.utils.string.to(message))
# If we actually received an integer, then cache it so that we can
# reuse it as the default the next time this function gets called.
if integer is not None:
cls.__last_integer__ = integer
return integer
@internal.utils.multicase()
@classmethod
def segment(cls, **default):
'''Request the user provide a segment.'''
return cls.segment(u'', **default)
@internal.utils.multicase(message=six.string_types)
@classmethod
@internal.utils.string.decorate_arguments('message')
def segment(cls, message, **default):
'''Request the user provide a segment using the specified `message` as the prompt.'''
res = current.segment()
dflt = next((default[k] for k in ['default', 'segment', 'seg'] if k in default), internal.interface.range.start(res) if res else idaapi.BADADDR)
ea = idaapi.ask_seg(dflt, internal.utils.string.to(message))
# Try and convert whatever it was that we were given into an actual segment.
try:
seg = _segment.by(ea)
# If we got an exception, then just set our result to None so that we can
# let the caller figure out how much they really want it.
except Exception:
return None
# Return the segment_t back to the caller.
return seg
@internal.utils.multicase()
@classmethod
def string(cls, **default):
'''Request the user provide a string.'''
return cls.string(u'', **default)
@internal.utils.multicase(message=six.string_types)
@classmethod
@internal.utils.string.decorate_arguments('message', 'default', 'text', 'string')
def string(cls, message, **default):
'''Request the user provide a string using the specified `message` as the prompt.'''
dflt = next((default[k] for k in ['default', 'text', 'string'] if k in default), None) or u''
# FIXME: we should totally expose the history id to the caller in some
# way.. but after some fiddling around with it, I can't seem to
# make it actually do anything.
result = idaapi.ask_str(internal.utils.string.to(dflt), idaapi.HIST_IDENT, internal.utils.string.to(message))
return internal.utils.string.of(result)
@internal.utils.multicase()
@classmethod
def note(cls, **default):
'''Request the user provide a multi-lined string.'''
return cls.note(u'', **default)
@internal.utils.multicase(message=six.string_types)
@classmethod
@internal.utils.string.decorate_arguments('message', 'default', 'text', 'string')
def note(cls, message, **default):
"""Request the user provide a multi-lined string using the specified `message` as the prompt.
If the `length` parameter is provided as an integer, then constrain
the length of the user's input to the integer that was specified.
"""
dflt = next((default[k] for k in ['default', 'text', 'string'] if k in default), None) or u''
length = next((default[k] for k in ['length', 'max', 'maxlength'] if k in default), 0)
result = idaapi.ask_text(length, internal.utils.string.to(dflt), internal.utils.string.to(message))
return internal.utils.string.of(result)
class current(object):
"""
This namespace contains tools for fetching information about the
current selection state. This can be used to get the state of
thigns that are currently selected such as the address, function,
segment, clipboard, widget, or even the current window in use.
"""
@classmethod
def address(cls):
'''Return the current address.'''
return idaapi.get_screen_ea()
@classmethod
def color(cls):
'''Return the color of the current item.'''
ea = cls.address()
return idaapi.get_item_color(ea)
@classmethod
def function(cls):
'''Return the current function.'''
ea = cls.address()
res = idaapi.get_func(ea)
if res is None:
raise internal.exceptions.FunctionNotFoundError(u"{:s}.function() : Unable to find a function at the current location.".format('.'.join([__name__, cls.__name__])))
return res
@classmethod
def segment(cls):
'''Return the current segment.'''
ea = cls.address()
return idaapi.getseg(ea)
@classmethod
def status(cls):
'''Return the IDA status.'''
# TODO: grab the current status and return it in some form
raise internal.exceptions.UnsupportedCapability(u"{:s}.status() : Unable to get the current disassembler status.".format('.'.join([__name__, cls.__name__])))
@classmethod
def symbol(cls):
'''Return the current highlighted symbol name or register.'''
if idaapi.__version__ < 7.0:
return idaapi.get_highlighted_identifier()
HIF_IDENTIFIER, HIF_REGISTER = getattr(idaapi, 'HIF_IDENTIFIER', 1), getattr(idaapi, 'HIF_REGISTER', 2)
# IDA 7.0 way of getting the currently selected text
viewer = idaapi.get_current_viewer()
identifier_and_flags = idaapi.get_highlight(viewer)
if identifier_and_flags is None:
return None
identifier, flags = identifier_and_flags
# If it wasn't a register, then we can just return the identifier as a string.
if flags & HIF_REGISTER == 0:
return identifier
# Otherwise we need to lookup our identifier in the current architecture.
import instruction
try:
res = instruction.architecture.by_name(identifier)
# If we got an exception, then only log a warning if the architecture is known.
except Exception as E:
if hasattr(instruction, 'architecture'):
architecture = instruction.architecture.__class__
logging.warning(u"{:s}.symbol(): Returning a string due to the returned identifier (\"{:s}\") not being available within the current architecture ({:s}).".format('.'.join([__name__, cls.__name__]), identifier, architecture.__name__))
return identifier
return res
@classmethod
def selection(cls):
'''Return the current address range of whatever is selected'''
view = idaapi.get_current_viewer()
ok, left, right = False, idaapi.twinpos_t(), idaapi.twinpos_t()
# If we were able to grab a selection, then return it.
newer = hasattr(idaapi.place_t, 'toea')
if newer and idaapi.read_selection(view, left, right):
pl_l, pl_r = left.place(view), right.place(view)
ok, ea_l, ea_r = True, pl_l.toea(), pl_r.toea()
# Older versions of the disassembler pack it all into the "read_selection" result.
elif not newer:
ok, ea_l, ea_r = idaapi.read_selection(view, left, right)
# If we successfully grabbed the selection, then return its boundaries.
if ok:
l, r = internal.interface.address.inside(ea_l, ea_r)
return internal.interface.bounds_t(l, r + 1)
# Otherwise we just use the current address for both sides.
ea = idaapi.get_screen_ea()
ea_l, ea_r = ea, ea
return internal.interface.bounds_t(ea_l, ea_r)
selected = internal.utils.alias(selection, 'current')
@classmethod
def operand(cls):
'''Return the currently selected operand number.'''
return idaapi.get_opnum()
opnum = internal.utils.alias(operand, 'current')
@classmethod
def widget(cls):
'''Return the current widget that is being used.'''
if hasattr(idaapi, 'get_current_widget'):
return idaapi.get_current_widget()
# XXX: there's probably a better way to do this rather than looking
# at the mouse cursor position
x, y = mouse.position()
return widget.at((x, y))
@classmethod
def window(cls):
'''Return the current window that is being used.'''
return application.window()
@classmethod
def viewer(cls):
'''Return the current viewer that is being used.'''
return idaapi.get_current_viewer()
class state(object):
"""
This namespace is for fetching or interacting with the current
state of IDA's interface. These are things such as waiting for
IDA's analysis queue, or determining whether the function is
being viewed in graph view or not.
"""
@classmethod
def graphview(cls):
'''Returns true if the current function is being viewed in graph view mode.'''
res = idaapi.get_inf_structure()
if idaapi.__version__ < 7.0:
return res.graph_view != 0
return res.is_graph_view()
@classmethod
def wait(cls):
'''Wait until IDA's autoanalysis queues are empty.'''
return idaapi.autoWait() if idaapi.__version__ < 7.0 else idaapi.auto_wait()
wait = internal.utils.alias(state.wait, 'state')
class message(object):
"""
This namespace is for displaying a modal dialog box with the different
icons that are available from IDA's user interface. The functions within
will block IDA from being interacted with while their dialog is displayed.
"""
def __new__(cls, message, **icon):
'''Display a modal information dialog box using the provided `message`.'''
if not idaapi.is_msg_inited():
raise internal.exceptions.DisassemblerError(u"{:s}({!r}{:s}) : Unable to display the requested modal dialog due to the user interface not yet being initialized.".format('.'.join([__name__, cls.__name__]), message, ", {:s}".format(internal.utils.string.kwargs(icon)) if icon else ''))
# because ida is fucking hil-ar-ious...
def why(F, *args):
name = '.'.join([F.__module__, F.__name__] if hasattr(F, '__module__') else [F.__name__])
raise internal.exceptions.DisassemblerError(u"{:s}({!r}{:s}) : Refusing to display the requested modal dialog with `{:s}` due it explicitly terminating the host application.".format('.'.join([__name__, cls.__name__]), message, ", {:s}".format(internal.utils.string.kwargs(icon)) if icon else '', name))
# these are all of the ones that seem to be available.
mapping = {
'information': idaapi.info, 'info': idaapi.info,
'warning': idaapi.warning, 'warn': idaapi.warning,
'error': functools.partial(why, idaapi.error), 'fatal': functools.partial(why, idaapi.error),
'nomem': functools.partial(why, idaapi.nomem), 'fuckyou': functools.partial(why, idaapi.nomem),
}
F = builtins.next((mapping[k] for k in icon if mapping.get(k, False)), idaapi.info)
# format it and give a warning if it's not the right type.
formatted = message if isinstance(message, six.string_types) else "{!s}".format(message)
if not isinstance(message, six.string_types):
logging.warning(u"{:s}({!r}{:s}) : Formatted the given message ({!r}) as a string ({!r}) prior to displaying it.".format('.'.join([__name__, cls.__name__]), message, ", {:s}".format(internal.utils.string.kwargs(icon)) if icon else '', message, formatted))
# set it off...
return F(internal.utils.string.to(formatted))
@classmethod
def information(cls, message):
'''Display a modal information dialog box using the provided `message`.'''
return cls(message, information=True)
info = internal.utils.alias(information, 'message')
@classmethod
def warning(cls, message):
'''Display a modal warning dialog box using the provided `message`.'''
return cls(message, warning=True)
warn = internal.utils.alias(warning, 'message')
@classmethod
def error(cls, message):
'''Display a modal error dialog box using the provided `message`.'''
return cls(message, error=True)
class appwindow(object):
"""
Base namespace used for interacting with the windows provided by IDA.
"""
@classmethod
def open(cls, *args):
'''Open or show the window belonging to the namespace.'''
global widget
res = cls.__open__(*args) if args else cls.__open__(*getattr(cls, '__open_defaults__', ()))
return widget.of(res)
@classmethod
def close(cls):
'''Close or hide the window belonging to the namespace.'''
res = cls.open()
return res.deleteLater()
class breakpoints(appwindow):
"""
This namespace is for interacting with the Breakpoints window.
"""
__open__ = staticmethod(idaapi.open_bpts_window)
__open_defaults__ = (idaapi.BADADDR, 0)
class calls(appwindow):
"""
This namespace is for interacting with the (Function) Calls window.
"""
__open__ = staticmethod(idaapi.open_calls_window)
__open_defaults__ = (idaapi.BADADDR, 0)
class disassembly(appwindow):
"""
This namespace is for interacting with the Disassembly window.
"""
__open__ = staticmethod(idaapi.open_disasm_window)
__open_defaults__ = ('Disassembly', )
@classmethod
def refresh(cls):
'''Refresh the main IDA disassembly view.'''
return idaapi.refresh_idaview_anyway()
disassembler = disassembly
class dump(appwindow):
"""
This namespace is for interacting with the (Hex) Dump window.
"""
__open__ = staticmethod(idaapi.open_hexdump_window)
__open_defaults__ = (idaapi.BADADDR, 0)
hexdump = dump
class enumerations(appwindow):
"""
This namespace is for interacting with the Enumerations window.
"""
__open__ = staticmethod(idaapi.open_enums_window)
__open_defaults__ = (idaapi.BADADDR, 0)
class exports(appwindow):
"""
This namespace is for interacting with the Exports window.
"""
__open__ = staticmethod(idaapi.open_exports_window)
__open_defaults__ = (idaapi.BADADDR, )
class frame(appwindow):
"""
This namespace is for interacting with the (Function) Frame window.
"""
__open__ = staticmethod(idaapi.open_frame_window)
__open_defaults__ = (idaapi.BADADDR, )
class functions(appwindow):
"""
This namespace is for interacting with the Functions window.
"""
__open__ = staticmethod(idaapi.open_funcs_window)
__open_defaults__ = (idaapi.BADADDR, )
class imports(appwindow):
"""
This namespace is for interacting with the Imports window.
"""
__open__ = staticmethod(idaapi.open_imports_window)
__open_defaults__ = (idaapi.BADADDR, )
class libraries(appwindow):
"""
This namespace is for interacting with the (Type) Libraries window.
"""
__open__ = staticmethod(idaapi.open_tils_window)
__open_defaults__ = (idaapi.BADADDR, )
tils = typelibraries = libraries
class modules(appwindow):
"""
This namespace is for interacting with the Modules window.
"""
__open__ = staticmethod(idaapi.open_modules_window)
__open_defaults__ = (idaapi.BADADDR, )
class names(appwindow):
"""
This namespace is for interacting with the Names window.
"""
__open__ = staticmethod(idaapi.open_names_window)
__open_defaults__ = (idaapi.BADADDR, )
@classmethod
def refresh(cls):
'''Refresh the names list.'''
return idaapi.refresh_lists() if idaapi.__version__ < 7.0 else idaapi.refresh_choosers()
@classmethod
def size(cls):
'''Return the number of elements in the names list.'''
return idaapi.get_nlist_size()
@classmethod
def contains(cls, ea):
'''Return whether the address `ea` is referenced in the names list.'''
return idaapi.is_in_nlist(ea)
@classmethod
def search(cls, ea):
'''Return the index of the address `ea` in the names list.'''
return idaapi.get_nlist_idx(ea)
@classmethod
def at(cls, index):
'''Return the address and the symbol name of the specified `index`.'''
ea, name = idaapi.get_nlist_ea(index), idaapi.get_nlist_name(index)
return ea, internal.utils.string.of(name)
@classmethod
def name(cls, index):
'''Return the name at the specified `index`.'''
res = idaapi.get_nlist_name(index)
return internal.utils.string.of(res)
@classmethod
def ea(cls, index):
'''Return the address at the specified `index`.'''
return idaapi.get_nlist_ea(index)
@classmethod
def iterate(cls):
'''Iterate through all of the address and symbols in the names list.'''
for idx in range(cls.size()):
yield cls.at(idx)
return
class notepad(appwindow):
"""
This namespace is for interacting with the Notepad window.
"""
__open__ = staticmethod(idaapi.open_notepad_window)
__open_defaults__ = ()
@classmethod
def open(cls, *args):
'''Open or show the notepad window and return its UI widget that can be used to modify it.'''
widget = super(notepad, cls).open(*args)
if isinstance(widget, PyQt5.QtWidgets.QPlainTextEdit):
return widget
elif hasattr(idaapi, 'is_idaq') and not idaapi.is_idaq():
if not widget:
raise internal.exceptions.UnsupportedCapability(u"{:s}.open({!s}) : Unable to open or interact with the notepad window when not running the Qt user-interface.".format('.'.join([__name__, cls.__name__]), ', '.join(map(internal.utils.string.repr, args))))
return widget
# We're running the PyQt UI, so we need to descend until we get to the text widget.
children = (item for item in widget.children() if isinstance(item, PyQt5.QtWidgets.QPlainTextEdit))
result = builtins.next(children, None)
if result is None:
raise internal.exceptions.ItemNotFoundError(u"{:s}.open({!s}) : Unable to locate the QtWidgets.QPlainTextEdit widget.".format('.'.join([__name__, cls.__name__]), ', '.join(map(internal.utils.string.repr, args))))
return result
@classmethod
def close(cls):
'''Close or hide the notepad window.'''
editor = cls.open()
widget = editor.parent()
return widget.deleteLater()
@classmethod
def get(cls):
'''Return the string that is currently stored within the notepad window.'''
editor = cls.open()
return editor.toPlainText()
@classmethod
def count(cls):
'''Return the number of lines that are currently stored within the notepad window.'''
editor = cls.open()
result = editor.toPlainText()
return result.count('\n') + (0 if result.endswith('\n') else 1)
@classmethod
def size(cls):
'''Return the number of characters that are currently stored within the notepad window.'''
editor = cls.open()
result = editor.toPlainText()
return len(result)
@internal.utils.multicase(string=six.string_types)
@classmethod
def set(cls, string):
'''Set the text that is currently stored within the notepad window to `string`.'''
editor = cls.open()
result, none = editor.toPlainText(), editor.setPlainText(string)
return result
@internal.utils.multicase(items=(builtins.list, builtins.tuple))
@classmethod
def set(cls, items):
'''Set each line that is currently stored within the notepad window to `items`.'''
return cls.set('\n'.join(items))
@internal.utils.multicase(string=six.string_types)
@classmethod
def append(cls, string):
'''Append the provided `string` to the current text that is stored within the notepad window.'''
editor = cls.open()
result, none = editor.toPlainText(), editor.appendPlainText(string)
return result.count('\n') + (0 if result.endswith('\n') else 1)
@internal.utils.multicase()
@classmethod
def cursor(cls):
'''Return the ``QtGui.QTextCursor`` used by the notepad window.'''
editor = cls.open()
return editor.textCursor()
@internal.utils.multicase()
@classmethod
def cursor(cls, cursor):
'''Set the ``QtGui.QTextCursor`` for the notepad window to `cursor`.'''
editor = cls.open()
return editor.setTextCursor(cursor)
class problems(appwindow):
"""
This namespace is for interacting with the Problems window.
"""
__open__ = staticmethod(idaapi.open_problems_window)
__open_defaults__ = (idaapi.BADADDR, )
class references(appwindow):
"""
This namespace is for interacting with the Cross-References window.
"""
__open__ = staticmethod(idaapi.open_xrefs_window)
__open_defaults__ = (idaapi.BADADDR, )
xrefs = references
class segments(appwindow):
"""
This namespace is for interacting with the Segments window.
"""
__open__ = staticmethod(idaapi.open_segments_window)
__open_defaults__ = (idaapi.BADADDR, )
class segmentregisters(appwindow):
"""
This namespace is for interacting with the Segments window.
"""
__open__ = staticmethod(idaapi.open_segments_window)
__open_defaults__ = (idaapi.BADADDR, )
segregs = segmentregisters
class selectors(appwindow):
"""
This namespace is for interacting with the Selectors window.
"""
__open__ = staticmethod(idaapi.open_selectors_window)
__open_defaults__ = (idaapi.BADADDR, )
class signatures(appwindow):
"""
This namespace is for interacting with the Signatures window.
"""
__open__ = staticmethod(idaapi.open_signatures_window)
__open_defaults__ = (idaapi.BADADDR, )
class stack(appwindow):
"""
This namespace is for interacting with the (Call) Stack window.
"""
__open__ = staticmethod(idaapi.open_stack_window)
__open_defaults__ = (idaapi.BADADDR, )
callstack = stack
class strings(appwindow):
"""
This namespace is for interacting with the Strings window.
"""
__open__ = staticmethod(idaapi.open_strings_window)
__open_defaults__ = (idaapi.BADADDR, idaapi.BADADDR, idaapi.BADADDR)
@classmethod
def __on_openidb__(cls, code, is_old_database):
if code != idaapi.NW_OPENIDB or is_old_database:
raise internal.exceptions.InvalidParameterError(u"{:s}.__on_openidb__({:#x}, {:b}) : Hook was called with an unexpected code or an old database.".format('.'.join([__name__, cls.__name__]), code, is_old_database))
config = idaapi.strwinsetup_t()
config.minlen = 3
config.ea1, config.ea2 = idaapi.cvar.inf.minEA, idaapi.cvar.inf.maxEA
config.display_only_existing_strings = True
config.only_7bit = True
config.ignore_heads = False
# aggregate all the string types for IDA 6.95x
if idaapi.__version__ < 7.0:
res = [idaapi.ASCSTR_TERMCHR, idaapi.ASCSTR_PASCAL, idaapi.ASCSTR_LEN2, idaapi.ASCSTR_UNICODE, idaapi.ASCSTR_LEN4, idaapi.ASCSTR_ULEN2, idaapi.ASCSTR_ULEN4]
# otherwise use IDA 7.x's naming scheme
else:
res = [idaapi.STRTYPE_TERMCHR, idaapi.STRTYPE_PASCAL, idaapi.STRTYPE_LEN2, idaapi.STRTYPE_C_16, idaapi.STRTYPE_LEN4, idaapi.STRTYPE_LEN2_16, idaapi.STRTYPE_LEN4_16]
config.strtypes = functools.reduce(lambda result, item: result | pow(2, item), res, 0)
if not idaapi.set_strlist_options(config):
raise internal.exceptions.DisassemblerError(u"{:s}.__on_openidb__({:#x}, {:b}) : Unable to set the default options for the string list.".format('.'.join([__name__, cls.__name__]), code, is_old_database))
return
#assert idaapi.build_strlist(config.ea1, config.ea2), "{:#x}:{:#x}".format(config.ea1, config.ea2)
@classmethod
def refresh(cls):
'''Refresh the strings list.'''
return idaapi.refresh_lists() if idaapi.__version__ < 7.0 else idaapi.refresh_choosers()
@classmethod
def size(cls):
'''Return the number of items available in the strings list.'''
return idaapi.get_strlist_qty()
@classmethod
def at(cls, index):
'''Return the ``idaapi.string_info_t`` for the specified `index` in the strings list.'''
si = idaapi.string_info_t()
if not idaapi.get_strlist_item(si, index):
raise internal.exceptions.DisassemblerError(u"{:s}.at({:d}) : The call to `idaapi.get_strlist_item({:d})` did not return successfully.".format('.'.join([__name__, cls.__name__]), index, index))
return si
@classmethod
def get(cls, index):
'''Return the address and its bytes representing the string at the specified `index`.'''
si = cls.at(index)
get_contents = idaapi.get_strlit_contents if hasattr(idaapi, 'get_strlit_contents') else idaapi.get_ascii_contents
string = get_contents(si.ea, si.length, si.type)
return si.ea, internal.utils.string.of(string)
@classmethod
def __iterate__(cls):
'''Iterate through all of the items in the strings list yielding the `(index, address, bytes)`.'''
for index in range(cls.size()):
ea, item = cls.get(index)
yield index, ea, item
return
@classmethod
def iterate(cls):
'''Iterate through all of the addresses and items in the strings list.'''
for _, ea, item in cls.__iterate__():
yield ea, item
return
class structures(appwindow):
"""
This namespace is for interacting with the Structures window.
"""
__open__ = staticmethod(idaapi.open_structs_window)
__open_defaults__ = (idaapi.BADADDR, 0)
class threads(appwindow):
"""
This namespace is for interacting with the Threads window.
"""
__open__ = staticmethod(idaapi.open_threads_window)
__open_defaults__ = (idaapi.BADADDR, )
class tracing(appwindow):
"""
This namespace is for interacting with the Tracing window.
"""
__open__ = staticmethod(idaapi.open_trace_window)
__open_defaults__ = (idaapi.BADADDR, )
trace = tracing
class types(appwindow):
"""
This namespace is for interacting with the Types window.
"""
__open__ = staticmethod(idaapi.open_loctypes_window)
__open_defaults__ = (idaapi.BADADDR, )
class timer(object):
"""
This namespace is for registering a python callable to a timer in IDA.
"""
clock = {}
@classmethod
def register(cls, id, interval, callable):
'''Register the specified `callable` with the requested `id` to be called at every `interval`.'''
if id in cls.clock:
idaapi.unregister_timer(cls.clock[id])
# XXX: need to create a closure that can terminate when signalled
cls.clock[id] = res = idaapi.register_timer(interval, callable)
return res
@classmethod
def unregister(cls, id):
'''Unregister the specified `id`.'''
raise internal.exceptions.UnsupportedCapability(u"{:s}.unregister({!s}) : A lock or a signal is needed here in order to unregister this timer safely.".format('.'.join([__name__, cls.__name__]), id))
idaapi.unregister_timer(cls.clock[id])
del(cls.clock[id])
@classmethod
def reset(cls):
'''Remove all the registered timers.'''
for id, clk in cls.clock.items():
idaapi.unregister_timer(clk)
del(cls.clock[id])
return
### updating the state of the colored navigation band
class navigation(object):
"""
This namespace is for updating the state of the colored navigation band.
"""
if all(not hasattr(idaapi, name) for name in ['show_addr', 'showAddr']):
__set__ = staticmethod(lambda ea: None)
else:
__set__ = staticmethod(idaapi.showAddr if idaapi.__version__ < 7.0 else idaapi.show_addr)
if all(not hasattr(idaapi, name) for name in ['show_auto', 'showAuto']):
__auto__ = staticmethod(lambda ea, t: None)
else:
__auto__ = staticmethod(idaapi.showAuto if idaapi.__version__ < 7.0 else idaapi.show_auto)
@classmethod
def set(cls, ea):
'''Set the auto-analysis address on the navigation bar to `ea`.'''
result, _ = ea, cls.__set__(ea)
return result
@classmethod
def auto(cls, ea, **type):
"""Set the auto-analysis address and type on the navigation bar to `ea`.
If `type` is specified, then update using the specified auto-analysis type.
"""
result, _ = ea, cls.__auto__(ea, type.get('type', idaapi.AU_NONE))
return result
@classmethod
def unknown(cls, ea): return cls.auto(ea, type=idaapi.AU_UNK)
@classmethod
def code(cls, ea): return cls.auto(ea, type=idaapi.AU_CODE)
@classmethod
def weak(cls, ea): return cls.auto(ea, type=idaapi.AU_WEAK)
@classmethod
def procedure(cls, ea): return cls.auto(ea, type=idaapi.AU_PROC)
@classmethod
def tail(cls, ea): return cls.auto(ea, type=idaapi.AU_TAIL)
@classmethod
def stackpointer(cls, ea): return cls.auto(ea, type=idaapi.AU_TRSP)
@classmethod
def analyze(cls, ea): return cls.auto(ea, type=idaapi.AU_USED)
@classmethod
def type(cls, ea): return cls.auto(ea, type=idaapi.AU_TYPE)
@classmethod
def signature(cls, ea): return cls.auto(ea, type=idaapi.AU_LIBF)
@classmethod
def final(cls, ea): return cls.auto(ea, type=idaapi.AU_FINAL)
### interfacing with IDA's menu system
# FIXME: add some support for actually manipulating menus
class menu(object):
"""
This namespace is for registering items in IDA's menu system.
"""
state = {}
@classmethod
def add(cls, path, name, callable, hotkey='', flags=0, args=()):
'''Register a `callable` as a menu item at the specified `path` with the provided `name`.'''
# check to see if our menu item is in our cache and remove it if so
if (path, name) in cls.state:
cls.rm(path, name)
# now we can add the menu item since everything is ok
# XXX: I'm not sure if the path needs to be utf8 encoded or not
res = internal.utils.string.to(name)
ctx = idaapi.add_menu_item(path, res, hotkey, flags, callable, args)
cls.state[path, name] = ctx
@classmethod
def rm(cls, path, name):
'''Remove the menu item at the specified `path` with the provided `name`.'''
res = cls.state[path, name]
idaapi.del_menu_item(res)
del cls.state[path, name]
@classmethod
def reset(cls):
'''Remove all currently registered menu items.'''
for path, name in cls.state.keys():
cls.rm(path, name)
return
### Qt wrappers and namespaces
class window(object):
"""
This namespace is for interacting with a specific window.
"""
def __new__(cls):
'''Return the currently active window.'''
# FIXME: should probably traverse the application windows to figure out the
# exact one that is in use so that we can cast it to a QWindow.
return application.window()
@internal.utils.multicase(xy=tuple)
def at(cls, xy):
'''Return the widget at the specified (`x`, `y`) coordinate within the `xy` tuple.'''
x, y = xy
return application.window(x, y)
class windows(object):
"""
This namespace is for interacting with any or all of the windows for the application.
"""
def __new__(cls):
'''Return all of the top-level windows.'''
return application.windows()
@classmethod
def refresh(cls):
'''Refresh all of lists and choosers within the application.'''
global disassembly
ok = idaapi.refresh_lists() if idaapi.__version__ < 7.0 else idaapi.refresh_choosers()
return ok and disassembly.refresh()
refresh = internal.utils.alias(windows.refresh, 'windows')
class widget(object):
"""
This namespace is for interacting with any of the widgets
associated with the native user-interface.
"""
@internal.utils.multicase()
def __new__(cls):
'''Return the widget that is currently being used.'''
return cls.of(current.widget())
@internal.utils.multicase(xy=tuple)
def __new__(cls, xy):
'''Return the widget at the specified (`x`, `y`) coordinate within the `xy` tuple.'''
res = x, y = xy
return cls.at(res)
@internal.utils.multicase(title=six.string_types)
def __new__(cls, title):
'''Return the widget that is using the specified `title`.'''
return cls.by(title)
@classmethod
def at(cls, xy):
'''Return the widget at the specified (`x`, `y`) coordinate within the `xy` tuple.'''
res = x, y = xy
global application
q = application()
return q.widgetAt(x, y)
@classmethod
def open(cls, widget, flags, **target):
'''Open the `widget` using the specified ``idaapi.WOPN_`` flags.'''
twidget = cls.form(widget) if cls.isinstance(widget) else widget
ok = idaapi.display_widget(twidget, flags)
# FIXME: rather than returning whether it succeeded or not, we should
# return what the widget was attached to in order to locate it.
return ok
@classmethod
def close(cls, widget, flags):
'''Close the `widget` using the specified ``idaapi.WCLS_`` flags.'''
twidget = cls.form(widget) if cls.isinstance(widget) else widget
ok = idaapi.close_widget(twidget, flags)
# FIXME: rather than returning whether it succeeded or not, we should
# return what the widget was attached to before we closed it.
return ok
@classmethod
def show(cls, widget):
'''Display the specified `widget` without putting it in focus.'''
twidget = cls.form(widget) if cls.isinstance(widget) else widget
res, ok = idaapi.get_current_widget(), idaapi.activate_widget(twidget, False)
return cls.of(res) if ok else None
@classmethod
def focus(cls, widget):
'''Activate the specified `widget` and put it in focus.'''
twidget = cls.form(widget) if cls.isinstance(widget) else widget
res, ok = idaapi.get_current_widget(), idaapi.activate_widget(twidget, True)
return cls.of(res) if ok else None
@classmethod
def type(cls, widget):
'''Return the ``idaapi.twidget_type_t`` for the given `widget`.'''
twidget = cls.form(widget) if cls.isinstance(widget) else widget
return idaapi.get_widget_type(twidget)
@classmethod
def title(cls, widget):
'''Return the window title for the given `widget`.'''
twidget = cls.form(widget) if cls.isinstance(widget) else widget
return idaapi.get_widget_title(twidget)
@internal.utils.multicase(title=six.string_types)
@classmethod
@internal.utils.string.decorate_arguments('title')
def by(cls, title):
'''Return the widget associated with the given window `title`.'''
res = idaapi.find_widget(internal.utils.string.to(title))
if res is None:
raise internal.exceptions.ItemNotFoundError(u"{:s}.by({!r}) : Unable to locate a widget with the specified title ({!r}).".format('.'.join([__name__, cls.__name__]), title, title))
return cls.of(res)
@classmethod
def of(cls, form):
'''Return the UI widget for the IDA `form` that is provided.'''
if hasattr(idaapi, 'is_idaq') and not idaapi.is_idaq():
return form
raise internal.exceptions.MissingMethodError
@classmethod
def form(cls, widget):
'''Return the IDA form for the UI `widget` that is provided.'''
if hasattr(idaapi, 'is_idaq') and not idaapi.is_idaq():
return widget
raise internal.exceptions.MissingMethodError
@classmethod
def isinstance(cls, object):
'''Return whether the given `object` is of the correct type for the UI.'''
if hasattr(idaapi, 'is_idaq') and not idaapi.is_idaq():
return True
raise internal.exceptions.MissingMethodError
class clipboard(object):
"""
This namespace is for interacting with the current clipboard state.
"""
def __new__(cls):
'''Return the current clipboard.'''
global application
clp = application()
return clp.clipboard()
class mouse(object):
"""
Base namespace for interacting with the mouse input.
"""
@classmethod
def buttons(cls):
'''Return the current mouse buttons that are being clicked.'''
global application
q = application()
return q.mouseButtons()
@classmethod
def position(cls):
'''Return the current `(x, y)` position of the cursor.'''
raise internal.exceptions.MissingMethodError
class keyboard(object):
"""
Base namespace for interacting with the keyboard input.
"""
@classmethod
def modifiers(cls):
'''Return the current keyboard modifiers that are being used.'''
global application
q = application()
return q.keyboardModifiers()
@classmethod
def __of_key__(cls, key):
'''Convert the normalized hotkey tuple in `key` into a format that IDA can comprehend.'''
Separators = {'-', '+'}
Modifiers = {'ctrl', 'shift', 'alt'}
# Validate the type of our parameter
if not isinstance(key, tuple):
raise internal.exceptions.InvalidParameterError(u"{:s}.of_key({!r}) : A key combination of an invalid type was provided as a parameter.".format('.'.join([__name__, cls.__name__]), key))
# Find a separator that we can use, and use it to join our tuple into a
# string with each element capitalized. That way it looks good for the user.
separator = next(item for item in Separators)
modifiers, hotkey = key
components = [item.capitalize() for item in modifiers] + [hotkey.capitalize()]
return separator.join(components)
@classmethod
def __normalize_key__(cls, hotkey):
'''Normalize the string `key` to a tuple that can be used to lookup keymappings.'''
Separators = {'-', '+', '_'}
Modifiers = {'ctrl', 'shift', 'alt'}
# First check to see if we were given a tuple or list. If so, then we might
# have been given a valid hotkey. However, we still need to validate this.
# So, to do that we'll concatenate each component together back into a string
# and then recurse so we can validate using the same logic.
if isinstance(hotkey, (tuple, list, set)):
try:
# If we were mistakenly given a set, then we need to reformat it.
if isinstance(hotkey, set):
raise ValueError
modifiers, key = hotkey
# If modifiers is not of the correct type, then still need to reformat.
if not isinstance(modifiers, (tuple, list, set)):
raise ValueError
# If the tuple we received was of an invalid format, then extract the
# modifiers that we can from it, and try again.
except ValueError:
modifiers = tuple(item for item in hotkey if item.lower() in Modifiers)
key = ''.join(item for item in hotkey if item.lower() not in Modifiers)
# Grab a separator, and join all our components together with it.
separator = next(item for item in Separators)
components = [item for item in modifiers] + [key]
return cls.__normalize_key__(separator.join(components))
# Next we need to normalize the separator used throughout the string by
# simply converting any characters we might consider a separator into
# a null-byte so we can split on it.
normalized = functools.reduce(lambda agg, item: agg.replace(item, '\0'), Separators, hotkey)
# Now we can split the normalized string so we can convert it into a
# set. We will then iterate through this set collecting all of our known
# key modifiers. Anything left must be a single key, so we can then
# validate the hotkey we were given.
components = { item.lower() for item in normalized.split('\0') }
modifiers = { item for item in components if item in Modifiers }
key = components ^ modifiers
# Now we need to verify that we were given just one key. If we were
# given any more, then this isn't a valid hotkey combination and we need
# to bitch about it.
if len(key) != 1:
raise internal.exceptions.InvalidParameterError(u"{:s}.normalize_key({!s}) : An invalid hotkey combination ({!s}) was provided as a parameter.".format('.'.join([__name__, cls.__name__]), internal.utils.string.repr(hotkey), internal.utils.string.repr(hotkey)))
res = next(item for item in key)
if len(res) != 1:
raise internal.exceptions.InvalidParameterError(u"{:s}.normalize_key({!s}) : The hotkey combination {!s} contains the wrong number of keys ({:d}).".format('.'.join([__name__, cls.__name__]), internal.utils.string.repr(hotkey), internal.utils.string.repr(res), len(res)))
# That was it. Now to do the actual normalization, we need to sort our
# modifiers into a tuple, and return the single hotkey that we extracted.
res, = key
return tuple(sorted(modifiers)), res
# Create a cache to store the hotkey context, and the callable that was mapped to it
__cache__ = {}
@classmethod
def list(cls):
'''Display the current list of keyboard combinations that are mapped along with the callable each one is attached to.'''
maxkey, maxtype, maxinfo = 0, 0, 0
results = []
for mapping, (capsule, closure) in cls.__cache__.items():
key = cls.__of_key__(mapping)
# Check if we were passed a class so we can figure out how to
# extract the signature.
cons = ['__init__', '__new__']
if inspect.isclass(closure):
available = (item for item in cons if hasattr(closure, item))
attribute = next((item for item in available if inspect.ismethod(getattr(closure, item))), None)
callable = getattr(closure, attribute) if attribute else None
information = '.'.join([closure.__name__, internal.utils.multicase.prototype(callable)]) if attribute else "{:s}(...)".format(closure.__name__)
else:
information = internal.utils.multicase.prototype(closure)
# Figure out the type of the callable that is mapped.
if inspect.isclass(closure):
ftype = 'class'
elif inspect.ismethod(closure):
ftype = 'method'
elif inspect.isbuiltin(closure):
ftype = 'builtin'
elif inspect.isfunction(closure):
ftype = 'anonymous' if closure.__name__ in {'<lambda>'} else 'function'
else:
ftype = 'callable'
# Figure out if there's any class-information associated with the closure
if inspect.ismethod(closure):
klass = closure.im_self.__class__ if closure.im_self else closure.im_class
clsinfo = klass.__name__ if getattr(klass, '__module__', '__main__') in {'__main__'} else '.'.join([klass.__module__, klass.__name__])
elif inspect.isclass(closure) or isinstance(closure, object):
clsinfo = '' if getattr(closure, '__module__', '__main__') in {'__main__'} else closure.__module__
else:
clsinfo = None if getattr(closure, '__module__', '__main__') in {'__main__'} else closure.__module__
# Now we can figure out the documentation for the closure that was stored.
documentation = closure.__doc__ or ''
if documentation:
filtered = [item.strip() for item in documentation.split('\n') if item.strip()]
header = next((item for item in filtered), '')
comment = "{:s}...".format(header) if header and len(filtered) > 1 else header
else:
comment = ''
# Calculate our maximum column widths inline
maxkey = max(maxkey, len(key))
maxinfo = max(maxinfo, len('.'.join([clsinfo, information]) if clsinfo else information))
maxtype = max(maxtype, len(ftype))
# Append each column to our results
results.append((key, ftype, clsinfo, information, comment))
# If we didn't aggregate any results, then raise an exception as there's nothing to do.
if not results:
raise internal.exceptions.SearchResultsError(u"{:s}.list() : Found 0 key combinations mapped.".format('.'.join([__name__, cls.__name__])))
# Now we can output what was mapped to the user.
six.print_(u"Found the following{:s} key combination{:s}:".format(" {:d}".format(len(results)) if len(results) > 1 else '', '' if len(results) == 1 else 's'))
for key, ftype, clsinfo, info, comment in results:
six.print_(u"Key: {:>{:d}s} -> {:<{:d}s}{:s}".format(key, maxkey, "{:s}:{:s}".format(ftype, '.'.join([clsinfo, info]) if clsinfo else info), maxtype + 1 + maxinfo, " // {:s}".format(comment) if comment else ''))
return
@classmethod
def map(cls, key, callable):
"""Map the specified `key` combination to a python `callable` in IDA.
If the provided `key` is being re-mapped due to the mapping already existing, then return the previous callable that it was assigned to.
"""
# First we'll normalize the hotkey that we were given, and convert it
# back into a format that IDA can understand. This way we can prevent
# users from giving us a sloppy hotkey combination that we won't be
# able to search for in our cache.
hotkey = cls.__normalize_key__(key)
keystring = cls.__of_key__(hotkey)
# The hotkey we normalized is now a tuple, so check to see if it's
# already within our cache. If it is, then we need to unmap it prior to
# re-creating the mapping.
if hotkey in cls.__cache__:
logging.warning(u"{:s}.map({!s}, {!r}) : Remapping the hotkey combination {!s} with the callable {!r}.".format('.'.join([__name__, cls.__name__]), internal.utils.string.repr(key), callable, internal.utils.string.repr(keystring), callable))
ctx, _ = cls.__cache__[hotkey]
ok = idaapi.del_hotkey(ctx)
if not ok:
raise internal.exceptions.DisassemblerError(u"{:s}.map({!s}, {!r}) : Unable to remove the hotkey combination {!s} from the list of current keyboard mappings.".format('.'.join([__name__, cls.__name__]), internal.utils.string.repr(key), callable, internal.utils.string.repr(keystring)))
# Pop the callable that was mapped out of the cache so that we can
# return it to the user.
_, res = cls.__cache__.pop(hotkey)
# If the user is mapping a new key, then there's no callable to return.
else:
res = None
# Verify that the user gave us a callable to use to avoid mapping a
# useless type to the specified keyboard combination.
if not builtins.callable(callable):
raise internal.exceptions.InvalidTypeOrValueError(u"{:s}.map({!s}, {!r}) : Unable to map the non-callable value {!r} to the hotkey combination {!s}.".format('.'.join([__name__, cls.__name__]), internal.utils.string.repr(key), callable, callable, internal.utils.string.repr(keystring)))
# Define a closure that calls the user's callable as it seems that IDA's
# hotkey functionality doesn't deal too well when the same callable is
# mapped to different hotkeys.
def closure(*args, **kwargs):
return callable(*args, **kwargs)
# Now we can add the hotkey to IDA using the closure that we generated.
# XXX: I'm not sure if the key needs to be utf8 encoded or not
ctx = idaapi.add_hotkey(keystring, closure)
if not ctx:
raise internal.exceptions.DisassemblerError(u"{:s}.map({!s}, {!r}) : Unable to map the callable {!r} to the hotkey combination {!s}.".format('.'.join([__name__, cls.__name__]), internal.utils.string.repr(key), callable, callable, internal.utils.string.repr(keystring)))
# Last thing to do is to stash it in our cache with the user's callable
# in order to keep track of it for removal.
cls.__cache__[hotkey] = ctx, callable
return res
@classmethod
def unmap(cls, key):
'''Unmap the specified `key` from IDA and return the callable that it was assigned to.'''
frepr = lambda hotkey: internal.utils.string.repr(cls.__of_key__(hotkey))
# First check to see whether we were given a callable or a hotkey. If
# we were given a callable, then we need to look through our cache for
# the actual key that it was. Once found, then we normalize it like usual.
if callable(key):
try:
hotkey = cls.__normalize_key__(next(item for item, (_, fcallback) in cls.__cache__.items() if fcallback == key))
except StopIteration:
raise internal.exceptions.InvalidParameterError(u"{:s}.unmap({:s}) : Unable to locate the callable {!r} in the current list of keyboard mappings.".format('.'.join([__name__, cls.__name__]), "{!r}".format(key) if callable(key) else "{!s}".format(internal.utils.string.repr(key)), key))
else:
logging.warning(u"{:s}.unmap({:s}) : Discovered the hotkey {!s} being currently mapped to the callable {!r}.".format('.'.join([__name__, cls.__name__]), "{!r}".format(key) if callable(key) else "{!s}".format(internal.utils.string.repr(key)), frepr(hotkey), key))
# We need to normalize the hotkey we were given, and convert it back
# into IDA's format. This way we can locate it in our cache, and prevent
# sloppy user input from interfering.
else:
hotkey = cls.__normalize_key__(key)
# Check to see if the hotkey is cached and warn the user if it isn't.
if hotkey not in cls.__cache__:
logging.warning(u"{:s}.unmap({:s}) : Refusing to unmap the hotkey {!s} as it is not currently mapped to anything.".format('.'.join([__name__, cls.__name__]), "{!r}".format(key) if callable(key) else "{!s}".format(internal.utils.string.repr(key)), frepr(hotkey)))
return
# Grab the keymapping context from our cache, and then ask IDA to remove
# it for us. If we weren't successful, then raise an exception so the
# user knows what's up.
ctx, _ = cls.__cache__[hotkey]
ok = idaapi.del_hotkey(ctx)
if not ok:
raise internal.exceptions.DisassemblerError(u"{:s}.unmap({:s}) : Unable to unmap the specified hotkey ({!s}) from the current list of keyboard mappings.".format('.'.join([__name__, cls.__name__]), "{!r}".format(key) if callable(key) else "{!s}".format(internal.utils.string.repr(key)), frepr(hotkey)))
# Now we can pop off the callable that was mapped to the hotkey context
# in order to return it, and remove the hotkey from our cache.
_, res = cls.__cache__.pop(hotkey)
return res
add, rm = internal.utils.alias(map, 'keyboard'), internal.utils.alias(unmap, 'keyboard')
@classmethod
def input(cls):
'''Return the current keyboard input context.'''
raise internal.exceptions.MissingMethodError
### PyQt5-specific functions and namespaces
## these can overwrite any of the classes defined above
try:
import PyQt5.Qt
from PyQt5.Qt import QObject, QWidget
class application(application):
"""
This namespace is for getting information about the application user-interface
that is based on PyQt.
"""
def __new__(cls):
'''Return the current instance of the PyQt Application.'''
q = PyQt5.Qt.qApp
return q.instance()
@internal.utils.multicase()
@classmethod
def window(cls):
'''Return the active main window for the PyQt application.'''
q = cls()
widgets = q.topLevelWidgets()
return next(widget for widget in widgets if isinstance(widget, PyQt5.QtWidgets.QMainWindow))
@internal.utils.multicase(x=six.integer_types, y=six.integer_types)
@classmethod
def window(cls, x, y):
'''Return the window at the specified `x` and `y` coordinate.'''
q = cls()
return q.topLevelAt(x, y)
@classmethod
def windows(cls):
'''Return all of the available windows for the application.'''
q = cls()
return q.topLevelWindows()
class mouse(mouse):
"""
This namespace is for interacting with the mouse input.
"""
@classmethod
def position(cls):
'''Return the current `(x, y)` position of the cursor.'''
qt = PyQt5.QtGui.QCursor
res = qt.pos()
return res.x(), res.y()
class keyboard(keyboard):
"""
This namespace is for interacting with the keyboard input.
"""
@classmethod
def input(cls):
'''Return the current keyboard input context.'''
raise internal.exceptions.MissingMethodError
class UIProgress(object):
"""
Helper class used to simplify the showing of a progress bar in IDA's UI.
"""
timeout = 5.0
def __init__(self, blocking=True):
self.object = res = PyQt5.Qt.QProgressDialog()
res.setVisible(False)
res.setWindowModality(blocking)
res.setAutoClose(True)
self.__evrunning = event = threading.Event()
res.canceled.connect(event.set)
pwd = _database.config.path() or os.getcwd()
path = os.path.join(pwd, _database.config.filename()) if _database.config.filename() else pwd
self.update(current=0, min=0, max=0, text=u'Processing...', tooltip=u'...', title=path)
# properties
canceled = property(fget=lambda self: self.object.wasCanceled(), fset=lambda self, value: self.object.canceled.connect(value))
maximum = property(fget=lambda self: self.object.maximum())
minimum = property(fget=lambda self: self.object.minimum())
current = property(fget=lambda self: self.object.value())
@property
def canceled(self):
return self.__evrunning.is_set()
@canceled.setter
def canceled(self, set):
event = self.__evrunning
event.set() if set else event.clear()
# methods
def open(self, width=0.8, height=0.1):
'''Open a progress bar with the specified `width` and `height` relative to the dimensions of IDA's window.'''
cls, app = self.__class__, application()
# XXX: spin for a second until main is defined because IDA seems to be racy with this api
ts, main = time.time(), getattr(self, '__appwindow__', None)
while time.time() - ts < self.timeout and main is None:
_, main = app.processEvents(), application.window()
if main is None:
logging.warning(u"{:s}.open({!s}, {!s}) : Unable to find main application window. Falling back to default screen dimensions to calculate size.".format('.'.join([__name__, cls.__name__]), width, height))
# figure out the dimensions of the window
if main is None:
# if there's no window, then assume some screen dimensions
w, h = 1024, 768
else:
w, h = main.width(), main.height()
# now we can calculate the dimensions of the progress bar
logging.info(u"{:s}.open({!s}, {!s}) : Using dimensions ({:d}, {:d}) for progress bar.".format('.'.join([__name__, cls.__name__]), width, height, int(w*width), int(h*height)))
fixedWidth, fixedHeight = map(math.trunc, [w * width, h * height])
self.object.setFixedWidth(fixedWidth), self.object.setFixedHeight(fixedHeight)
# calculate the center
if main is None:
# no window, so use the center of the screen
cx, cy = w * 0.5, h * 0.5
else:
center = main.geometry().center()
cx, cy = center.x(), center.y()
# ...and center it.
x, y = map(math.trunc, [cx - (w * width * 0.5), cy - (h * height * 1.0)])
logging.info(u"{:s}.open({!s}, {!s}) : Centering progress bar at ({:d}, {:d}).".format('.'.join([__name__, cls.__name__]), width, height, int(x), int(y)))
self.object.move(x, y)
# now everything should look good.
self.object.show(), app.processEvents()
def close(self):
'''Close the current progress bar.'''
event, app = self.__evrunning, application()
self.object.canceled.disconnect(event.set)
self.object.close(), app.processEvents()
def update(self, **options):
'''Update the current state of the progress bar.'''
application().processEvents()
minimum, maximum = options.get('min', None), options.get('max', None)
text, title, tooltip = (options.get(item, None) for item in ['text', 'title', 'tooltip'])
if minimum is not None:
self.object.setMinimum(minimum)
if maximum is not None:
self.object.setMaximum(maximum)
if title is not None:
self.object.setWindowTitle(internal.utils.string.to(title))
if tooltip is not None:
self.object.setToolTip(internal.utils.string.to(tooltip))
if text is not None:
self.object.setLabelText(internal.utils.string.to(text))
res = self.object.value()
if 'current' in options:
self.object.setValue(options['current'])
elif 'value' in options:
self.object.setValue(options['value'])
return res
if hasattr(idaapi, 'is_idaq') and not idaapi.is_idaq():
raise StopIteration
class widget(widget):
"""
This namespace is for interacting with any of the widgets
associated with the native PyQT5 user-interface.
"""
__cache__ = {}
@classmethod
def of(cls, form):
'''Return the PyQt widget for the IDA `form` that is provided.'''
ns = idaapi.PluginForm
iterable = (getattr(ns, attribute) for attribute in ['TWidgetToPyQtWidget', 'FormToPyQtWidget'] if hasattr(ns, attribute))
F = next(iterable, None)
if F is None:
raise internal.exceptions.UnsupportedVersion(u"{:s}.of({!s}) : Unable to return the PyQT widget from a plugin form due to it being unsupported by the current version of IDA.".format('.'.join([__name__, cls.__name__]), form))
result = F(form)
cls.__cache__[result] = form
return result
@classmethod
def form(cls, widget):
'''Return the IDA form for the PyQt `widget` that is provided.'''
ns = idaapi.PluginForm
if hasattr(ns, 'QtWidgetToTWidget'):
return ns.QtWidgetToTWidget(widget)
elif widget in cls.__cache__:
return cls.__cache__[widget]
raise internal.exceptions.UnsupportedVersion(u"{:s}.of({!s}) : Unable to return the plugin form from a PyQT widget due to it being unsupported by the current version of IDA.".format('.'.join([__name__, cls.__name__]), widget))
@classmethod
def isinstance(cls, widget):
'''Return whether the given `object` is a PyQt widget.'''
return isinstance(widget, QWidget)
except StopIteration:
pass
except ImportError:
logging.info(u"{:s}:Unable to locate `PyQt5.Qt` module.".format(__name__))
### PySide-specific functions and namespaces
try:
import PySide
import PySide.QtCore, PySide.QtGui
class application(application):
"""
This namespace is for getting information about the application user-interface
that is based on PySide.
"""
def __new__(cls):
'''Return the current PySide instance of the application.'''
res = PySide.QtCore.QCoreApplication
return res.instance()
@internal.utils.multicase()
@classmethod
def window(cls):
'''Return the active main window for the PySide application.'''
# Apparently PySide.QtCore.QCoreApplication is actually considered
# the main window for the application. Go figure...
return cls()
@internal.utils.multicase(x=six.integer_types, y=six.integer_types)
@classmethod
def window(cls, x, y):
'''Return the window at the specified `x` and `y` coordinate.'''
q = cls()
return q.topLevelAt(x, y)
@classmethod
def windows(cls):
'''Return all of the available windows for the application.'''
app = cls()
items = app.topLevelWidgets()
return [item for item in items if top.isWindow()]
class mouse(mouse):
"""
This namespace is for interacting with the mouse input.
"""
@classmethod
def position(cls):
'''Return the current `(x, y)` position of the cursor.'''
qt = PySide.QtGui.QCursor
res = qt.pos()
return res.x(), res.y()
class keyboard(keyboard):
"""
PySide keyboard interface.
"""
@classmethod
def input(cls):
'''Return the current keyboard input context.'''
return q.inputContext()
if hasattr(idaapi, 'is_idaq') and not idaapi.is_idaq():
raise StopIteration
class widget(widget):
"""
This namespace is for interacting with any of the widgets
associated with the native PySide user-interface.
"""
__cache__ = {}
@classmethod
def of(cls, form):
'''Return the PySide widget for the IDA `form` that is provided.'''
ns = idaapi.PluginForm
iterable = (getattr(ns, attribute) for attribute in ['TWidgetToPySideWidget', 'FormToPySideWidget'] if hasattr(ns, attribute))
F = next(iterable, None)
if F is None:
raise internal.exceptions.UnsupportedVersion(u"{:s}.of({!s}) : Unable to return the PySide widget from a plugin form due to it being unsupported by the current version of IDA.".format('.'.join([__name__, cls.__name__]), form))
result = F(form)
cls.__cache__[result] = form
return result
@classmethod
def form(cls, widget):
'''Return the IDA form for the PySide `widget` that is provided.'''
if widget in cls.__cache__:
return cls.__cache__[widget]
raise internal.exceptions.UnsupportedCapability(u"{:s}.of({!s}) : Unable to return the plugin form from a PySide widget due to it being unsupported by the current version of IDA.".format('.'.join([__name__, cls.__name__]), widget))
@classmethod
def isinstance(cls, object):
'''Return whether the given `object` is a PySide widget.'''
return isinstance(object, PySide.QtCore.QObject)
except StopIteration:
pass
except ImportError:
logging.info(u"{:s}:Unable to locate `PySide` module.".format(__name__))
### wrapper that uses a priorityhook around IDA's hooking capabilities.
class hook(object):
"""
This namespace exposes the ability to hook different parts of IDA.
There are 4 different event types in IDA that can be hooked. These
are available under the ``hook.idp``, ``hook.idb``, ``hook.ui``,
and ``hook.notification`` objects.
To add a hook for any of these event types, one can use
the `add(target, callable, priority)` method to associate a python
callable with the desired event. After the callable has been
attached, the `enable(target)` or `disable(target)` methods can be
used to temporarily enable or disable the hook.
Please refer to the documentation for the ``idaapi.IDP_Hooks``,
``idaapi.IDB_Hooks``, and ``idaapi.UI_Hooks`` classes for
identifying what event targets are available to hook. Similarly,
the documentation for ``idaapi.notify_when`` can be used to list
the targets available for notification hooks.
"""
@classmethod
def __start_ida__(ns):
import hooks
# Create an alias to save some typing and a table of the attribute
# name, the base hook class, and the supermethods we need to patch.
priorityhook, api = internal.interface.priorityhook, {
'idp': (idaapi.IDP_Hooks, hooks.supermethods.IDP_Hooks.mapping),
'idb': (idaapi.IDB_Hooks, hooks.supermethods.IDB_Hooks.mapping),
'ui': (idaapi.UI_Hooks, hooks.supermethods.UI_Hooks.mapping),
}
# Iterate through our table and use it to instantiate the necessary
# objects for each hook type whilst attaching the patched supermethods.
for attribute, (klass, supermethods) in api.items():
# If there's an instance already attached to us, then use it.
if hasattr(ns, attribute):
instance = getattr(ns, attribute)
# Otherwise instantiate the priority hooks for each hook type,
# and assign it directly into our class. We attach a supermethod
# mapping to patch the original supermethods of each hook where
# it can either have a completely different number of parameters
# or different types than what is listed within the documentation.
else:
instance = priorityhook(klass, supermethods)
setattr(ns, attribute, instance)
# Log some information about what we've just done.
logging.info(u"{:s} : Attached an instance of `{:s}` to `{:s}` which is now available at `{:s}`.".format('.'.join([__name__, ns.__name__]), instance.__class__.__name__, klass.__name__, '.'.join([__name__, ns.__name__, attribute])))
# If the idaapi.__notification__ object exists, then also
# assign it directly into our namespace.
if not hasattr(ns, 'notification') and hasattr(idaapi, '__notification__'):
instance = idaapi.__notification__
setattr(ns, 'notification', instance)
logging.info(u"{:s} : Attached an instance of `{:s}` to {:s} which is now accessible at `{:s}`.".format('.'.join([__name__, ns.__name__]), instance.__class__.__name__, 'notifications', '.'.join([__name__, ns.__name__, 'notification'])))
return
@classmethod
def __stop_ida__(ns):
for api in ['idp', 'idb', 'ui']:
# grab the individual class that was used to hook things
instance = getattr(ns, api)
# and then unhook it completely, because IDA on linux
# seems to still dispatch to those hooks...even when
# the language extension is unloaded.
instance.close()
return
# if there's a __notification__ attribute attached to IDA, then
# assign it to our namespace so it can be used.
if hasattr(idaapi, '__notification__'):
notification = idaapi.__notification__
hooks = hook # XXX: ns alias
### Helper classes to use or inherit from
# XXX: why was this base class implemented again??
class InputBox(idaapi.PluginForm):
"""
A class designed to be inherited from that can be used
to interact with the user.
"""
def OnCreate(self, form):
'''A method to overload to be notified when the plugin form is created.'''
self.parent = self.FormToPyQtWidget(form)
def OnClose(self, form):
'''A method to overload to be notified when the plugin form is destroyed.'''
pass
def Show(self, caption, options=0):
'''Show the form with the specified `caption` and `options`.'''
res = internal.utils.string.to(caption)
return super(InputBox, self).Show(res, options)
### Console-only progress bar
class ConsoleProgress(object):
"""
Helper class used to simplify the showing of a progress bar in IDA's console.
"""
def __init__(self, blocking=True):
self.__path__ = os.path.join(_database.config.path(), _database.config.filename())
self.__value__ = 0
self.__min__, self.__max__ = 0, 0
return
canceled = property(fget=operator.not_, fset=operator.eq)
maximum = property(fget=lambda self: self.__max__)
minimum = property(fget=lambda self: self.__min__)
current = property(fget=lambda self: self.__value__)
def open(self, width=0.8, height=0.1):
'''Open a progress bar with the specified `width` and `height` relative to the dimensions of IDA's window.'''
return
def close(self):
'''Close the current progress bar.'''
return
def update(self, **options):
'''Update the current state of the progress bar.'''
minimum, maximum = options.get('min', None), options.get('max', None)
text, title, tooltip = (options.get(item, None) for item in ['text', 'title', 'tooltip'])
if minimum is not None:
self.__min__ = minimum
if maximum is not None:
self.__max__ = maximum
res = self.__value__
if 'current' in options:
self.__value__ = options['current']
if 'value' in options:
self.__value__ = options['value']
if text is not None:
six.print_(internal.utils.string.of(text))
return res
### Fake progress bar class that instantiates whichever one is available
class Progress(object):
"""
The default progress bar in with which to show progress. This class will
automatically determine which progress bar (Console or UI) to instantiate
based on what is presently available.
"""
timeout = 5.0
def __new__(cls, *args, **kwargs):
'''Figure out which progress bar to use and instantiate it with the provided parameters `args` and `kwargs`.'''
if not all([idaapi.is_idaq(), 'UIProgress' in globals()]):
logging.warning(u"{:s}(...) : Using console-only implementation of the `ui.Progress` class.".format('.'.join([__name__, cls.__name__])))
return ConsoleProgress(*args, **kwargs)
# XXX: spin for a bit looking for the application window as IDA seems to be racy with this for some reason
ts, main = time.time(), getattr(cls, '__appwindow__', None)
while time.time() - ts < cls.timeout and main is None:
main = application.window()
# If no main window was found, then fall back to the console-only progress bar
if main is None:
logging.warning(u"{:s}(...) : Unable to find main application window. Falling back to console-only implementation of the `ui.Progress` class.".format('.'.join([__name__, cls.__name__])))
return ConsoleProgress(*args, **kwargs)
cls.__appwindow__ = main
return UIProgress(*args, **kwargs)
| arizvisa/ida-minsc | misc/ui.py | ui.py | py | 78,036 | python | en | code | 302 | github-code | 13 |
2604119197 | from flask import Flask, render_template, request
app = Flask(__name__)
CLASS = [
"24/01",
"24/02",
"24/03",
"24/04",
"24/05",
"24/06",
"24/07",
"24/08",
"24/09",
"24/10",
"24/11",
"24/12",
"24/13",
"24/14",
"24/15",
"24/16",
"24/17",
"24/18",
"24/19",
"24/20",
"24/21",
"24/22",
"24/23",
"24/24",
"24/25",
"24/26",
"24/27",
"24/28",
"24/29",
"24/30",
]
CCA = [
"Basketball",
"Football",
"Frisbee",
"Badminton",
"Hockey",
"Netball",
"Shooting",
"Table_Tennis",
"Taekwondo",
"Tennis",
"Touch Rugby",
"Volleyball",
"Chinese_Orchestra",
"Choir",
"Dance_Society",
"StageWorks",
"Guitar_Ensemble",
"Harmonica_Band",
"Symphonic_Band",
"Visual_Aids_Club",
"Chinese_LDDS",
"Debate",
"Community_Champions_Council",
"Outdoor_Activities_Club",
"Photographic_Society",
"Red_Cross_Youth",
"STEM",
"Strategist_Society",
"Students’_Council",
"Tamil_LDDS",
]
@app.route("/", methods=['GET', 'POST'])
def front():
return render_template("front.html")
@app.route("/index", methods=['GET', 'POST'])
def index():
return render_template("index.html", sport=CCA, clas=CLASS)
@app.route("/success", methods=['POST'])
def success():
name = None
cca = None
Class = None
improv = None
name = request.form.get("name")
cca = request.form.get("cca")
Class = request.form.get("class")
improv = request.form.get("improv")
with open('suggest.txt', 'a') as file:
file.write(name + ' ' + cca + ' ' + Class + ' ' + improv + ' \n')
return render_template("success.html")
@app.route("/cca", methods=['GET', 'POST'])
def cca():
return render_template("cca.html", sport=CCA, clas=CLASS)
@app.route("/register", methods=["POST"])
def register():
name = None
gender = None
Class = None
choice1 = None
choice2 = None
choice3 = None
name = request.form['name']
gender = request.form['gender']
Class = request.form['class']
choice1 = request.form['c1']
choice2 = request.form['c2']
choice3 = request.form['c3']
if choice1 == choice2 == choice3:
return render_template("failure1.html")
elif Class not in CLASS:
return render_template("failure3.html")
else:
with open('data.txt', 'a') as file:
file.truncate(0)
file.write(name + ' ' + gender + ' ' + Class + ' ' + "1." + ' ' + choice1 + ' ' + "ㅤ" + "2." + ' ' + choice2 + ' ' + "3." + ' ' + choice3 + ' \n')
return render_template("registered.html")
@app.route("/mycca", methods=['GET', 'POST'])
def mycca():
with open('data.txt', 'r') as f:
data = f.read()
if len(data) == 0:
choice = "(Unregistered)"
else:
data = data.split(" ")
choice = data[4]
return render_template("mycca.html", sport=CCA, clas=CLASS, choice=choice)
app.run(host='0.0.0.0', port=81)
| fishdrowned174/Savingtheworld1 | main.py | main.py | py | 3,044 | python | en | code | 0 | github-code | 13 |
30049029892 | import math
import sys
import random
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
import concurrent.futures
from id3alg import *
# Function takes votes from previous iterations of the bagging algorithm and adds on votes from the current tree
# the error is calculated and passed back out along with the updated votes
def bag_get_predictions_error(votes, predictions_new_tree, examples):
predictions_final = []
# getting rid of labels
examples_no_label = [z[:-1] for z in examples]
# going through every example
for row in range(len(examples_no_label)):
# Go through the new model and get its predictions
guess = predictions_new_tree[row]
if guess in votes[row]:
votes[row][guess] += 1
else:
votes[row][guess] = 1
highest_vote = 0
# determine which label had the highest vote total
for label in votes[row]:
if votes[row][label] >= highest_vote:
prediction = label
highest_vote = votes[row][label]
predictions_final.append(prediction)
# get the average error
true_value = [z[-1] for z in examples]
error_total = 0
for i in range(len(examples)):
if predictions_final[i] != true_value[i]:
error_total += 1
average_error = float(error_total)/len(examples)
return average_error, votes
# function to randomly sort the examples and process them
def process_trees(iteration, full_attributes, downsampled_att_num):
remain_attributes = full_attributes.copy()
# Creating a new set of examples that is random: uniform with replacement
np.random.seed()
rand_examples = []
rand_nums = np.random.choice(len(processed_train), len(processed_train))
for index in range(len(rand_nums)):
rand_examples.append(processed_train[rand_nums[index]])
print('Model: ', iteration)
# Randomly sample a very small subset of the attributes
# random choose attributes
np.random.seed()
rand_nums = np.random.choice(len(list(full_attributes.keys())), downsampled_att_num, replace=False)
downsampled_attributes = {}
for i in rand_nums:
downsampled_attributes[i] = full_attributes[i]
downsampled_remain_attributes = downsampled_attributes.copy()
new_tree = id3(rand_examples, rand_examples, downsampled_attributes, downsampled_remain_attributes, None, "entropy")
# get the predictions for the training set
examples_no_label = [z[:-1] for z in processed_train]
training_predictions = []
testing_predictions = []
for row in examples_no_label:
training_predictions.append(decision_tree_predictor(new_tree, row))
# get predictions for the testing set
examples_no_label = [z[:-1] for z in processed_test]
for row in examples_no_label:
testing_predictions.append(decision_tree_predictor(new_tree, row))
# Return the training and testing predictions for the given model
return training_predictions, testing_predictions
# Wrapper so that I can call process_trees from a concurrent.futures.ProcessPoolExecutor instance
def process_trees_wrapper(p):
return process_trees(*p)
def main(downsampled_attribute_num):
# getting all the attributes that are in examples
full_attributes = get_attributes(processed_train)
# number of iterations
num_models = 500
# Getting predictions from each individual model for testing and training and saving to these lists
# doing this rather than saving all the models will make getting average error faster and take less memory
testing_predictions = []
training_predictions = []
num_models_list = list(range(1, num_models + 1))
args = ((model_num, full_attributes, downsampled_attribute_num) for model_num in num_models_list)
with concurrent.futures.ProcessPoolExecutor() as executor:
results = executor.map(process_trees_wrapper, args)
for result in results:
training_predictions.append(result[0])
testing_predictions.append(result[1])
# Creating a dictionary to hold the votes as the models get added up
votes_train_dict = {}
for i in range(len(processed_train)):
votes_train_dict[i] = {}
votes_test_dict = {}
for i in range(len(processed_train)):
votes_test_dict[i] = {}
training_error_bag = []
testing_error_bag = []
# This loop gets the average error for both training and testing for each bagging algorithm.
# Saving votes allows me to pass information from previous iterations forward, so I don't need to recalc votes
for i in range(num_models):
average_error_train, votes = bag_get_predictions_error(votes_train_dict, training_predictions[i], processed_train)
average_error_test, votes = bag_get_predictions_error(votes_test_dict, testing_predictions[i], processed_test)
training_error_bag.append(average_error_train)
testing_error_bag.append(average_error_test)
print("Training Error:", training_error_bag)
print("Testing Error:", testing_error_bag)
plt.plot(training_error_bag, label='training')
plt.plot(testing_error_bag, label='testing')
plt.xlabel("iteration")
plt.ylabel("average error")
plt.title("Random Forest Error: " + str(downsampled_attribute_num) + " Attributes")
plt.legend()
plt.savefig('random_tree_' + str(downsampled_attribute_num) + 'att.png')
plt.show()
if __name__ == "__main__":
# Reading in the set of training examples
train = []
with open("bank/train.csv", 'r') as f:
for line in f:
train.append(line.strip().split(','))
processed_train, numerical_medians = numerical_train_data_preprocessing(train)
# Reading in the set of test examples
test = []
with open("bank/test.csv", 'r') as f:
for line in f:
test.append(line.strip().split(','))
processed_test = numerical_test_data_preprocessing(test, numerical_medians)
attribute_number = 2
main(attribute_number)
attribute_number = 4
main(attribute_number)
attribute_number = 6
main(attribute_number)
| danielwaldram/ml_6350 | EnsembleLearning/cs6350_hw2_p2d.py | cs6350_hw2_p2d.py | py | 6,174 | python | en | code | 0 | github-code | 13 |
12311186037 | from cProfile import label
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import datasets
from matplotlib import pyplot as plt
X, Y = datasets.make_regression(n_samples=100, n_features=1, noise=20, random_state=4)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=1234)
# fig = plt.figure(figsize=(8,6))
# plt.scatter(X[:, 0], Y, color='b', marker='o', s=30)
# plt.show()
# print(X_train.shape)
# print(Y_train.shape)
from linear_regression import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, Y_train)
predicted_values = regressor.predict(X_test)
def mse(y_true, y_pred):
return np.mean((y_true - y_pred)**2)
print(mse(Y_test, predicted_values))
regressor_2 = LinearRegression(n_iters=10000)
regressor_2.fit(X_train, Y_train)
predicted_vals = regressor_2.predict(X_test)
pred_line1 = regressor.predict(X)
pred_line2 = regressor_2.predict(X)
print(mse(Y_test, predicted_vals))
cmap = plt.get_cmap('viridis')
fig = plt.figure(figsize=(8,6))
m1 = plt.scatter(X_train, Y_train, color=cmap(0.9), s=10)
m2 = plt.scatter(X_test, Y_test, color=cmap(0.5), s=10)
plt.plot(X, pred_line1, color='black', linewidth=2, label='n_iters=1000')
plt.plot(X, pred_line2, color='red', linewidth=2, label='n_iters=10000')
plt.show()
| Malab12/MLMFS | Linear_Regression/linear_regression_tests.py | linear_regression_tests.py | py | 1,328 | python | en | code | 0 | github-code | 13 |
71401900819 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
import numpy as np
import argparse
import logging
import sklearn.decomposition
import matplotlib.pyplot as plt
logging.basicConfig(level=logging.INFO)
np.set_printoptions(precision=3)
def _parse_args():
"""parse command line arguments
Args:
:none
Returns:
namespace: (observations, correlation, volatility)
"""
_description = 'Simulate two correlated random variables. Compute sample covariance matrix and PCA'
parser = argparse.ArgumentParser(description=_description)
parser.add_argument('-o', '--observations', type=int, default=100, help='number of observations')
parser.add_argument('-c', '--correlation', type=float, default=0.5, help='correlation between the two variables')
parser.add_argument('-v', '--volatility', nargs=2, type=float, default=[0.2, 0.2],
help='volatility of the two variables')
args = parser.parse_args()
return args
def _compute_sample_vector(observations, volatility_vector, correlation):
"""compute a matrix of correlated random variables
Args:
observations(int): number of observations to generate
volatility_vector(list): volatility of each of the two random variables
correlation(float): correlation coefficient between the two random variables
Returns:
np.matrix: (observations, 2) matrix of correlated random variables
"""
std_norm_vector = np.random.randn(observations, 2)
correlated_array = std_norm_vector[:, 0] * correlation + np.sqrt(1 - correlation**2) * std_norm_vector[:, 1]
correlated_std_norm = np.column_stack((std_norm_vector[:, 0], correlated_array))
res = np.multiply(correlated_std_norm, volatility_vector)
return res
def main():
"""main entry point for function. compute sample covariance matrix and pca values
Args:
:none
Returns:
None
"""
args = _parse_args()
corr = args.correlation
vol_array = args.volatility
logging.info('volatility vector: {}, correlation: {}'.format(vol_array, corr))
theoretical_covariance = np.matrix([[vol_array[0]**2, vol_array[0]*vol_array[1]*corr],
[vol_array[0]*vol_array[1]*corr, vol_array[1]**2]])
logging.info('theoretical covariance:\n{}'.format(theoretical_covariance))
correlated_rvs = _compute_sample_vector(args.observations, args.volatility, args.correlation)
sample_covariance = np.cov(correlated_rvs, rowvar=False)
sample_correlation = np.corrcoef(correlated_rvs, rowvar=False)
logging.info('sample covariance:\n{}'.format(sample_covariance))
logging.info('sample correlation:\n{}'.format(sample_correlation))
pca = sklearn.decomposition.PCA()
pca.fit_transform(correlated_rvs)
eigenvectors = pca.components_
eigenvalues = pca.explained_variance_
logging.info('eigenvectors of PCA:\n{}'.format(eigenvectors))
logging.info('eigenvalues of PCA: {}'.format(eigenvalues))
np_eigenvalues, np_eigenvectors = np.linalg.eig(sample_covariance)
explained_var_ratio = [v / sum(np_eigenvalues) for v in np_eigenvalues]
scaled_eigenvectors = np.multiply(np_eigenvectors, explained_var_ratio)
logging.info('eigenvectors of covariance matrix:\n{}'.format(np_eigenvectors))
logging.info('eigenvalues of covariance matrix: {}'.format(np_eigenvalues))
logging.info('explained var ratio: {}'.format(explained_var_ratio))
fig = plt.figure()
ax = fig.add_subplot('111')
ax.scatter(correlated_rvs[:, 0], correlated_rvs[:, 1], s=20)
ax.plot([0, np_eigenvectors[0, 0]], [0, np_eigenvectors[1, 0]], color='b')
ax.plot([0, np_eigenvectors[0, 1]], [0, np_eigenvectors[1, 1]], color='b')
ax.plot([0, scaled_eigenvectors[0, 0]], [0, scaled_eigenvectors[1, 0]], color='g')
ax.plot([0, scaled_eigenvectors[0, 1]], [0, scaled_eigenvectors[1, 1]], color='g')
ax.set_title('Volatility Vector: {}, Correlation: {}\nNumber Observations: {}'.format(
vol_array, corr, args.observations)
)
max_val = np.max(np.array(list(map(abs, correlated_rvs))))
max_val = max(max_val, 1)
ax.set_xlim(-max_val, max_val)
ax.set_ylim(-max_val, max_val)
fig.tight_layout()
plt.show()
if __name__ == '__main__':
main()
| jplotkin21/examples | example_pca.py | example_pca.py | py | 4,317 | python | en | code | 0 | github-code | 13 |
30285887085 | from testclasses.classleaf import ClassLeaf
class ClassLoopOneMethodCall:
def doB(self, p1):
'''
This class is used to test the handling of the :seqdiag loop and
:seqdiag loop end tags with a loop inside which only one method
is called.
:param p1:
:return:
'''
c = ClassLeaf()
a = 0
for i in range(3):
c.doC1(p1) #:seqdiag_loop_start_end 3 times
a += 1 # dummy instruction
c.doC2(p1)
print(a) # another dummy instruction | Archanciel/seqdiagbuilder | testclasses/classlooponemethodcall.py | classlooponemethodcall.py | py | 548 | python | en | code | 2 | github-code | 13 |
43052758699 | from common.common import update_user_infor, add_new_account, user_exist, is_email, logged_in_user, update, fetch_user_infor, get_user_being_paid, add_transaction, get_transactions
import datetime
def deposit(email, amount):
if(amount.isdigit() and amount.isnumeric()):
user, index, users = update(email)
new_amount = str(int(user[5].strip()) + int(amount))
user[5] = " " + new_amount + '\n'
users[index] = ",".join(user)
update_user_infor(users)
add_transaction(transaction(user[0], "Deposited", amount))
return True
def transaction(account, transaction_message, amount):
current_date = datetime.datetime.now()
return account +", "+ transaction_message + ", "+amount +", "+ str(current_date) +'\n' | brit01flo/Bank-App-Password-Generator | Deposit/deposit.py | deposit.py | py | 818 | python | en | code | 1 | github-code | 13 |
35794751445 | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(S):
s_len = len(S)
if s_len == 0:
return 1
if s_len % 2 != 0 or S[0] not in '{([':
return 0
m = {
'{': '}'
, '}': '{'
, '[': ']'
, ']': '['
, '(': ')'
, ')': '('
}
stack = []
result = 1
for s in S:
if s in '{([':
stack.append(s)
else:
if len(stack) == 0 or s != m[stack.pop()]:
result = 0
break
if len(stack) != 0:
return 0
return result | whitebluecloud/padp_ko | whitebluecloud/codewars/codility_stack_1.py | codility_stack_1.py | py | 629 | python | en | code | 5 | github-code | 13 |
14764775386 |
import speech_recognition as sr
import os
import time
import random
import vocabulary
import tensorflow
import keras
session = {
"feeling": "init",
"Bad":"init",
"Sleep": "init",
"outside": "init",
"eat": "init",
"burnout": "init",
"State": "init"
}
intent = "yesFeedback"
def main():
print(motivationideas())
speech = speechtotext()
time.sleep(0.5)
#if 'ok' in speech:
os.system('say ' + welcome() + vocabulary.patientID["Vorname"])
speech = speechtotext()
if any(s in speech for s in vocabulary.positiveFeeling):
os.system('say ' + random.choice(vocabulary.positiveFeedback))
time.sleep(1)
os.system('say "Brauchst du sonst noch etwas wo ich helfen kann ?"')
session["feeling"]="Good"
session["State"]="Question 0 answered"
elif any(s in speech for s in vocabulary.negativeFeeling):
session["feeling"] = "Bad"
session["State"] = "Question 1 answered"
os.system('say ' + random.choice(vocabulary.negativeFeedback))
time.sleep(1)
os.system('say "Bist du heute aus dem Bett gekommen?"')
speech = speechtotext()
if "ja" in speech:
if session["feeling"] == "Good":
session["State"] = "motivation"
os.system('say "ok was kann ich für dich tun? Brauchst du eine weitere Motivationsidee?" ')
else:
session["State"] = "Question 2 answered"
session["Bad"] = "yes"
os.system('say ' "Das ist Prima.")
time.sleep(1)
os.system('say ' "Hast du Gestern gut geschlafen?")
elif "nein" or "ne" in speech:
if session["feeling"] == "Good":
os.system('say "ok auf Wiesderhören" ')
session["State"] = "end"
else:
session["State"] = "Question 2 answered"
session["Bad"] = "no"
os.system('say ' "Das ist Schlecht. Du kannst besser machen")
time.sleep(1)
os.system('say ' "Hast du Gestern gut geschlafen?")
speech = speechtotext()
if "ja" in speech and session["State"] == "motivation":
os.system('say ' + motivationideas())
time.sleep(0.5)
os.system('say ' + "Ich wünsche dir ein schönen Tag und bis sehr Bald.")
if session["State"] == "Question 2 answered":
if any(s in speech for s in vocabulary.sleepGoodYes):
session["State"] = "Question 3 answered"
session["Sleep"] = "yes"
os.system('say ' + "Super, Das freut mich zu hören.")
time.sleep(0.5)
os.system('say ' "Bist du die letzte Tage rausgegangen?")
else:
session["State"] = "Question 3 answered"
session["Sleep"] = "no"
os.system('say ' + "Schade. Versuche aber demnächst früher ins Bett zu gehen. ")
time.sleep(0.5)
os.system('say ' "Bist du die letzte Tage rausgegangen?")
speech=speechtotext()
if "ja" in speech:
os.system('say ' + "Das hast du sehr gut gemacht. Weiter so!")
session["outside"] = "yes"
else:
session["outside"] = "no"
os.system('say ' + "Das tut mir leid. Du solltest demnächst versuchen öfter rauszugehen und dich mit Freunde treffen!")
session["state"] = "end"
if session["Bad"] == "yes" and session["Sleep"] == "yes" and session["outside"] == "yes":
time.sleep(1)
text = "Gute Arbeit bei all diesen Dingen. Wenn Sie depressiv sind, können diese kleinen Dinge am schwierigsten sein"
os.system('say '+ text)
time.sleep(0.5)
os.system('say ' + "Mach weiter so"+ vocabulary.patientID["Vorname"]+ " .Habe de ehre")
elif session["Bad"] =="no" and session["Sleep"] == "no" or session["outside"]== "no":
time.sleep(1)
os.system('say ' + "Beim nächsten einchecken musst du besser machen. Das schaffst du schon. Da bin ich mir sicher")
time.sleep(0.5)
os.system('say ' + "Auf wiedersehen"+ vocabulary.patientID["Vorname"])
def speechtotext():
r = sr.Recognizer()
mic = sr.Microphone()
with mic as source:
r.adjust_for_ambient_noise(source, duration=0.5)
audio = r.listen(source)
s = r.recognize_google(audio, language="de-DE")
#s = r.recognize_sphinx(audio, language="en-US")
try:
print("Benutzer sagt:" + s)
except sr.UnknownValueError:
print("Audio input ist nicht verständlich")
except sr.RequestError as e:
print("Could not request results;{0}".format(e))
return s
# functions that will be called during the conversation
def welcome():
gruss = ["Hallo,", "Servus,", "Hi,",
"Habe die Ehre, ", "Guten Tag, ", "Grüß Gott, ","schön von dir zu hören, "]
anfrage=["Wie hast du dich die letzten Tage gefühlt?",
"Wie gehts dir Heute?", "Wie läuft dein Tag?", "wie ging es dir die letzte Tage?"]
welcome = (random.choice(gruss) + " " + (random.choice(anfrage)))
print("Willkomen text ist : " + welcome)
return welcome
def motivationideas():
ideas =[" Du kannst dir zum beispiel eine to do Liste für die Woche erstellen. Das hilft dir organisatorisch weiter",
"Du kannst zum beispiel eine neue rezept kochen",
"Du kannst deine lieblings Musik abspielen. Das macht dich immer gut gelaunt",
"Du kannst Yoga treiben. Das hilft dir körperlich und geistlich weiter",
"Geh eine runde spazieren und frische luft atmen."]
randIdea=random.choice(ideas)
return randIdea
if __name__ == "__main__":
main()
| BilelSaid87/INSPIRITED | functions/speechRecognition.py | speechRecognition.py | py | 5,632 | python | de | code | 0 | github-code | 13 |
8815442076 | # main
# version :
# new :
# structure :
# target :
# 1.
import sys
from os.path import join as pth
sys.path.insert(1,pth('..','..'))
from datetime import datetime as dtm
from datetime import timedelta as dtmdt
from lidar.dt_handle import *
from lidar.plot import plot
import numpy as n
from pandas import read_csv, date_range, DataFrame, concat, Series
from radio.reader import *
from matplotlib.pyplot import subplots, close, show
import pickle as pkl
# from ground import *
"""
"""
## time decorater
def __timer(func):
def __wrap():
print(f'\nPROGRAM : {__file__}\n')
__st = dtm.now().timestamp()
## main function
_out = func()
__fn = dtm.now().timestamp()
__run = (__fn-__st)/60.
print(f'\nProgram done\nrunning time = {int(__run):3d} min {(__run-int(__run))*60.:6.3f} s')
return _out
return __wrap
## (1) linear interpolate lidar data
# '''
start_dtm = dtm(2021,4,1,0,0,0)
final_dtm = dtm(2021,4,6,0,0,0)
path = pth('..','..','..','data','Lidar_NDU','use')
reader = NDU.reader(path,start_dtm,final_dtm)
dt = reader.get_data()
dt_u, dt_v = -n.sin(dt['wd']/180.*n.pi)*dt['ws'], -n.cos(dt['wd']/180.*n.pi)*dt['ws']
def height_inter(_df,inter_h):
key_lst = list(_df.keys())
inter_lst = n.arange(key_lst[0],key_lst[-1]+inter_h,inter_h).tolist()
add_lst = inter_lst.copy()
[ add_lst.remove(_) for _ in key_lst ]
for _ in add_lst: _df[_] = n.nan
return _df[inter_lst].interpolate(axis=1)
def uv2wswd(u,v):
return n.sqrt((u**2)+(v**2)), (n.arctan2(-u,-v)*180./n.pi)%360.
ws_inte, wd_inte = uv2wswd(height_inter(dt_u,50),height_inter(dt_v,50))
## plot
plot.plot_all({'nam':'inteNDU','ws':ws_inte,'wd':wd_inte,'z_ws':dt['z_ws']},pth('picture'),tick_freq='24h')
# '''
## (2) get ST at wanted time, plot height-time
from pathlib import Path
DATA_ROOT = Path('..') /Path('..') /Path('..') / "data"
ST_DATA = DATA_ROOT / "storm tracker"
METADATA = Path('..') /Path('..') /Path('.') / "radio"
def readSTLaunchMetaData():
ST_RootPath = Path('..') /Path('..') /Path('..') / "data" / "storm tracker"
ST_launchMetaDataFileName = "20210401_20210406.csv"
ST_rename = {"NO.":"no", "Time (yyyy/mm/dd HH:MM:SS)":"time"}
ST_launchMetaData = read_csv(ST_RootPath / ST_launchMetaDataFileName, parse_dates=['Time (yyyy/mm/dd HH:MM:SS)']).dropna(subset=['Time (yyyy/mm/dd HH:MM:SS)']).reset_index(drop=True)
ST_launchMetaData = ST_launchMetaData[['NO.','Time (yyyy/mm/dd HH:MM:SS)']].rename(columns=ST_rename).astype({'no': 'int32'})
return ST_launchMetaData
md = readSTLaunchMetaData()
cmap_no = n.linspace(0.,2.,md.size)
## ## plot ST [25, 26, 27] completed vertical profile
'''
fs = 13.
fig, ax = subplots(figsize=(8,6),dpi=150.)
# fig, ax = subplots()
first_tm = None
for _no in md.no.iloc[[30,31,32]]:
print(f'\n\nno.{_no}\n')
stObj = STreader(_no,L0DataPath=Path(ST_DATA / 'Level 0'),metaPath=METADATA)
_df = stObj.L0Reader()[0][['Z [m]','U [m/s]','V [m/s]']]
first_tm = first_tm if first_tm is not None else _df.index[0]
_df = _df[~_df.index.duplicated(keep='first').copy()]
_df = _df.reindex(_df.index.sort_values()).where(_df['Z [m]']>=150.)
# try:
# last_indx = _df.where(_df['Z [m]']>=1100.).dropna(subset=['Z [m]']).index[0]
# except:
# last_indx = _df['Z [m]'].idxmax()
# _df = _df.loc[_df.index[0]:last_indx]
# x_tick = date_range(_df.index[0].strftime('%Y-%m-%d'),_df.index[-1].strftime('%Y-%m-%d'),freq='3h')
# ax.plot(_df['Z [m]'],c='#4c79ff',marker='o',mfc='None',ms=4)
ax.plot(_df['Z [m]'],c='#26c9ff',marker='o',mfc='None',ms=4)
# final_tm = _df.index[-1]
x_tick = date_range('2021-04-02 21:00:00','2021-04-03 03:00:00',freq='3h')
ax.tick_params(which='major',direction='in',length=7,labelsize=fs-2.5)
ax.tick_params(which='minor',direction='in',length=4.5)
# [ ax.spines[axis].set_visible(False) for axis in ['right','top'] ]
ax.set(xlim=(x_tick[0],x_tick[-1]))
ax.set_xlabel('Time',fontsize=fs)
ax.set_ylabel('Height (m)',fontsize=fs)
ax.set_xticks(x_tick)
ax.set_xticklabels(x_tick.strftime('%Y-%m-%d %HLST'))
# ax.legend(framealpha=0,fontsize=fs-2.)
#ax.legend(handles=[],framealpha=0,fontsize=fs-2.)
# ax.set_title('',fontsize=fs)
fig.suptitle('ST below 1100 km',fontsize=fs+2.,style='italic')
fig.savefig(pth('picture',f'ST_height.png'))
# show()
close()
#'''
## plot ST and u v
'''
res = 0
if res:
df_all_u = []
df_all_v = []
first_tm = None
for _no, colr in zip(md.no,cmap_no):
print(f'\n\nno.{_no}\n')
stObj = STreader(_no,L0DataPath=Path(ST_DATA / 'Level 0'),metaPath=METADATA)
_df = stObj.L0Reader()[0][['Z [m]','U [m/s]','V [m/s]']]
first_tm = first_tm if first_tm is not None else _df.index[0]
_df = _df[~_df.index.duplicated(keep='first').copy()]
_df = _df.reindex(_df.index.sort_values())[_df['Z [m]']>=150.]
try:
last_indx = _df.where(_df['Z [m]']>=1100.).dropna(subset=['Z [m]']).index[0]
except:
last_indx = _df['Z [m]'].idxmax()
_df = _df.loc[_df.index[0]:last_indx]
## process data
_df['hh'] = _df.index.map(lambda _: dtm.strftime(_,'%h'))
_df = _df.where(_df['hh']==_df['hh'][-1])
u_dic = {}
v_dic = {}
for top, bot in zip(n.arange(200,1050,50),n.arange(150,1000,50)):
u_dic[top] = _df.where((_df['Z [m]']>bot)&(_df['Z [m]']<top))['U [m/s]'].mean()
v_dic[top] = _df.where((_df['Z [m]']>bot)&(_df['Z [m]']<top))['V [m/s]'].mean()
df_all_u.append(Series(u_dic))
df_all_v.append(Series(v_dic))
# if df_all_v.__len__() ==20: break
## plot
# ax.quiver(_df.index,_df.keys(),)
## get u, v dataframe
u_df = concat(df_all_u,axis=1).T.set_index(date_range(first_tm.strftime('%Y-%m-%d %H:00:00'),periods=df_all_u.__len__(),freq='1h'))
v_df = concat(df_all_v,axis=1).T.set_index(date_range(first_tm.strftime('%Y-%m-%d %H:00:00'),periods=df_all_u.__len__(),freq='1h'))
## save
with open(pth('u_ST.pkl'),'wb') as f:
pkl.dump(u_df,f,protocol=pkl.HIGHEST_PROTOCOL)
with open(pth('v_ST.pkl'),'wb') as f:
pkl.dump(v_df,f,protocol=pkl.HIGHEST_PROTOCOL)
## load
if not res:
print('read pickle')
with open(pth('u_ST.pkl'),'rb') as f:
u_df = pkl.load(f)
with open(pth('v_ST.pkl'),'rb') as f:
v_df = pkl.load(f)
# breakpoint()
x_tick = date_range('2021-04-01 00:00:00','2021-04-06 00:00:00',freq='24h')
## process u, v data
def uv2wswd(u,v):
return n.sqrt((u**2)+(v**2)), (n.arctan2(-u,-v)*180./n.pi)%360.
def wswd2uv(_ws,_wd):
return -n.sin(_wd/180.*n.pi)*_ws, -n.cos(_wd/180.*n.pi)*_ws
ws_ST, wd_ST = uv2wswd(u_df,v_df)
plot.plot_all({'nam':'ST','ws':ws_ST,'wd':wd_ST},pth('picture'),tick_freq='24h',input_tick=x_tick)
# '''
## plot ST horizontal distance
'''
from metpy.calc import lat_lon_grid_deltas as dist_calc
limit_h = 1100
limit_h = 500
limit_h = 200
res = 0
if res:
dist = []
for _no in md.no:
print(f'\n\nno.{_no}\n')
stObj = STreader(_no,L0DataPath=Path(ST_DATA / 'Level 0'),metaPath=METADATA)
_df = stObj.L0Reader()[0][['Z [m]','Lat [o]','Lon [o]']]
# first_tm = first_tm if first_tm is not None else _df.index[0]
_df = _df[~_df.index.duplicated(keep='first').copy()]
_df = _df.reindex(_df.index.sort_values())
try:
last_indx = _df.where(_df['Z [m]']>=limit_h).dropna(subset=['Z [m]']).index[0]
except:
last_indx = _df['Z [m]'].idxmax()
_df = _df.loc[_df.index[0]:last_indx][['Lat [o]','Lon [o]']].iloc[[0,-1]]
dx, dy = dist_calc(_df['Lon [o]'],_df['Lat [o]'])
dist.append(((dx[0]**2+dy[0,0]**2)**.5).m[0])
dist = n.array(dist)
## save
with open(pth(f'ST_dist_{limit_h}.pkl'),'wb') as f:
pkl.dump(dist,f,protocol=pkl.HIGHEST_PROTOCOL)
## load
if not res:
print('read pickle')
with open(pth(f'ST_dist_{limit_h}.pkl'),'rb') as f:
dist = pkl.load(f)
## parameter
fs = 13.
## plot
fig, ax = subplots(figsize=(8,6),dpi=150.)
ax.plot(dist,range(dist.size),c='#000000',marker='^',ms=8,ls='',mfc='None')
ax.tick_params(which='major',direction='in',length=7,labelsize=fs-2.5)
ax.tick_params(which='minor',direction='in',length=4.5)
[ ax.spines[axis].set_visible(False) for axis in ['right','top'] ]
ax.set(xlim=(0.,2200.))
ax.set_xlabel('Horizontal Distance (m)',fontsize=fs)
ax.set_ylabel('ST',fontsize=fs)
# ax.set_title('',fontsize=fs)
fig.suptitle(f'Horizontal Distance of each ST below {limit_h} m(height)',fontsize=fs+2.,style='italic')
fig.savefig(pth('picture',f'ST_hor_dist_{limit_h}.png'))
# show()
close()
# '''
## plot ST horizontal distance (multiple)
'''
print('read pickle')
dist = {}
for _h in [1100,500,200]:
with open(pth(f'ST_dist_{_h}.pkl'),'rb') as f:
dist[_h] = pkl.load(f)
## parameter
fs = 14.
# breakpoint()
## plot
fig, ax = subplots(figsize=(8,9),dpi=150.)
for _x, _y in zip(DataFrame(dist).values,n.arange(97)):
ax.plot(_x,[_y]*3,c='#777777',ls='--',lw=.4)
handle = []
for (_key, _val), colr, mk in zip(dist.items(),['#ff4c79','#26c9ff','#666666'],['o','*','^']):
sc = ax.scatter(_val,range(_val.size),marker=mk,fc='None',ec=colr,label=f'below {_key} m',zorder=_key)
handle.append(sc)
ax.tick_params(which='major',direction='in',length=7,labelsize=fs-2.5)
ax.tick_params(which='minor',direction='in',length=4.5)
[ ax.spines[axis].set_visible(False) for axis in ['right','top'] ]
ax.set(xlim=(0.,2200.))
ax.set_xlabel('Horizontal Distance (m)',fontsize=fs)
ax.set_ylabel('ST',fontsize=fs)
ax.legend(handles=handle,framealpha=0,fontsize=fs-2.)
# ax.set_title('',fontsize=fs)
fig.suptitle(f'Horizontal Distance of each ST below 1100, 500, 200 m(height)',fontsize=fs+2.,style='italic')
fig.savefig(pth('picture',f'ST_hor_dist_all.png'))
# show()
close()
# '''
'''
_mask = ws_ST.copy()<2.5
ws_ST.mask(_mask,n.nan,inplace=True)
ws_ST.replace(0.,n.nan,inplace=True)
_u, _v = wswd2uv(1.5,wd_ST)
(1) replace 0 as nan, process the by-product after interpolate
(2) get the mask below 2.5
(3) set the value as nan under mask
(4) get the mask out value, apply scatter plot
_index, _height =n.meshgrid(dt_ws.index,dt_ws.keys())
change ws, wd to u, v
get height as y axis and get x ticks
height = n.array(list(dt_ws.keys())).astype(float)
x_tick = dt_ws.asfreq(tick_freq).index
plot
sc = ax.scatter(_index[_mask.T],_height[_mask.T],s=15,fc='None',ec='#666666',label='< 2.5 m/s')
qv = ax.quiver(_u.index,height[::setting['sep']],_u.T[::setting['sep']],_v.T[::setting['sep']],dt_ws.T[::setting['sep']].values,
cmap=cmap,scale=50,clim=(setting['vmin'],setting['vmax']))
# '''
## (3)
## compair with lidar
## mean u v to 50m ?
| ChungChenWei/NDU_Sunsing_Lidar | function/yrr_project/ST_Lidar_comp/ST_Lidar.py | ST_Lidar.py | py | 10,478 | python | en | code | 1 | github-code | 13 |
36588226126 | class Solution:
def minMeetingRooms(self, intervals: List[List[int]]) -> int:
if len(intervals) < 2:
return len(intervals)
rooms = []
intervals.sort(key=lambda x: x[0])
for cur in intervals:
if rooms and cur[0] >= rooms[0]:
earliest_end_sameroom = cur[1]
heapq.heapreplace(rooms, earliest_end_sameroom)
else:
heapq.heappush(rooms, cur[1])
return len(rooms) | ysonggit/leetcode_python | 0253_MeetingRoomsII.py | 0253_MeetingRoomsII.py | py | 484 | python | en | code | 1 | github-code | 13 |
9255612258 | from admin import Admin
from manager import Manager
from user import User
from systemgui import System_Gui
class EstateSystem:
def __init__(self):
self.estates = []
self.thoroughfare = []
self.property = []
self.household = []
self.users = []
self.users.append(Admin(self, "Chris"))
self.users.append(Manager(self, "Luis"))
self.users.append(User(self, "Jordan"))
self.current_user = None
self.current_estate = None
self.current_thoroughfare = None
self.current_property = None
self.current_household = None
if __name__ == '__main__':
system = EstateSystem()
gui = System_Gui(system)
gui.mainloop() | cwilson98/projects | Estate Management System/estate_system.py | estate_system.py | py | 721 | python | en | code | 0 | github-code | 13 |
36933135133 | from karel.stanfordkarel import *
def main():
color_fill(GREEN)
white_fill()
color_fill(ORANGE)
def color_fill(color):
for i in range(4):
while front_is_clear():
paint_corner(color)
move()
paint_corner(color)
back_to_position()
next_stage()
def white_fill():
row5()
row6()
row7()
row8()
def row5():
color(8,WHITE)
color(2,BLUE)
color(8,WHITE)
back_to_position()
next_stage()
def row6():
color(7,WHITE)
color(1,BLUE)
color(1,WHITE)
color(2,BLUE)
color(7,WHITE)
back_to_position()
next_stage()
def row7():
color(7,WHITE)
color(2,BLUE)
color(1,WHITE)
color(1,BLUE)
color(7,WHITE)
back_to_position()
next_stage()
def row8():
row5()
def color(steps,color):
for i in range(steps):
paint_corner(color)
if front_is_clear():
move()
def back_to_position():
turn_around()
while front_is_clear():
move()
def next_stage():
turn_right()
if front_is_clear():
move()
turn_right()
else:
turn_right()
back_to_position()
def turn_right():
for i in range(3):
turn_left()
def turn_around():
for i in range(2):
turn_left()
if __name__=="__main__":
run_karel_program("18x12.w")
| imhariprakash/Courses | python/Code_In_Place-2021/INDIA.py | INDIA.py | py | 1,460 | python | en | code | 4 | github-code | 13 |
72833323219 | # written to test break points
import random
heads = 0
tails = 0
for i in range(1, 1001):
toss = random.randint(0,1)
if toss == 1:
heads = heads + 1
elif toss == 0:
tails = tails + 1
if i == 500:
print('Halfway done!')
print('Heads came up ' + str(heads) + ' times.')
print('Tails came up ' + str(tails) + ' times.')
| rodrickaheebwa/automate-the-boring-stuff | py/coinFlip.py | coinFlip.py | py | 379 | python | en | code | 0 | github-code | 13 |
17876978951 | # imports
# subroutines
def calculate_flashes(i, r, xs):
sx = len(xs)
c = 0
if xs[i] > 9:
xs[i] = 0
c += 1
if i+1 < sx:
xs[i+1] = xs[i+1] + 1
if i-1 > -1:
xs[i-1] = xs[i-1] + 1
if i+r < sx:
xs[i+r] = xs[i+r] + 1
if i-r > -1:
xs[i-r] = xs[i-r] + 1
if i+r+1 < sx:
xs[i+r+1] = xs[i+r+1] + 1
if i-r+1 > -1:
xs[i-r+1] = xs[i-r+1] + 1
if i-r-1 > -1:
xs[i-r-1] = xs[i-r-1] + 1
if i+r-1 < sx:
xs[i+r-1] = xs[i+r-1] + 1
return xs, c
# main
def solve_part1(input_ls: list) -> int:
r = 10
f = 0
xs = list()
for line in input_ls:
for char in line:
xs.append(int(char))
for _ in range(100):
for i in range(len(xs)):
xs[i] += 1
xs, c = calculate_flashes(i, r, xs)
f += c
return f
def solve_part2(input_ls: list) -> int:
return 0
def solve_day11(input_ls: list) -> list:
output = list()
part1 = solve_part1(input_ls)
output.append(part1)
part2 = solve_part2(input_ls)
output.append(part2)
return output
| rodfer0x80/aoc2021py | src/day11.py | day11.py | py | 1,209 | python | en | code | 0 | github-code | 13 |
71082162897 | from multiprocessing import Pool
from typing import Union, Tuple
from predictor.common.file_and_folder_operations import *
def convert_trainer_plans_config_to_identifier(
trainer_name, plans_identifier, configuration
):
return f"{trainer_name}__{plans_identifier}__{configuration}"
def convert_identifier_to_trainer_plans_config(identifier: str):
return os.path.basename(identifier).split("__")
def get_ensemble_name(model1_folder, model2_folder, folds: Tuple[int, ...]):
identifier = (
"ensemble___"
+ os.path.basename(model1_folder)
+ "___"
+ os.path.basename(model2_folder)
+ "___"
+ folds_tuple_to_string(folds)
)
return identifier
def convert_ensemble_folder_to_model_identifiers_and_folds(ensemble_folder: str):
prefix, *models, folds = os.path.basename(ensemble_folder).split("___")
return models, folds
def folds_tuple_to_string(folds: Union[List[int], Tuple[int, ...]]):
s = str(folds[0])
for f in folds[1:]:
s += f"_{f}"
return s
def folds_string_to_tuple(folds_string: str):
folds = folds_string.split("_")
res = []
for f in folds:
try:
res.append(int(f))
except ValueError:
res.append(f)
return res
def check_workers_alive_and_busy(
export_pool: Pool,
worker_list: List,
results_list: List,
allowed_num_queued: int = 0,
):
"""
returns True if the number of results that are not ready is greater than the number of available workers + allowed_num_queued
"""
alive = [i.is_alive() for i in worker_list]
if not all(alive):
raise RuntimeError("Some background workers are no longer alive")
not_ready = [not i.ready() for i in results_list]
if sum(not_ready) >= (len(export_pool._pool) + allowed_num_queued):
return True
return False
| weihuang-cs/nnUNet-Deploy | src/predictor/common/file_path_utilities.py | file_path_utilities.py | py | 1,877 | python | en | code | 1 | github-code | 13 |
26860432925 | import json
import boto3
from boto3.dynamodb.types import TypeDeserializer
from boto3.dynamodb.conditions import Key
import time
def lambda_handler(event, context):
startTime = time.time()
queryStr = event["queryStringParameters"]
type = queryStr["type"]
token = queryStr["token"]
cognito = boto3.client('cognito-idp')
username = cognito.get_user(AccessToken = token)
username = username['Username']
if type == "all":
entries = getEntries(username)
return {
'statusCode': 200,
'body': json.dumps(entries)
}
elif type == "single":
id = event["queryStringParameters"]["id"]
return {
'statusCode': 200,
'body': json.dumps(getEntry(username, id))
}
elif type == "benchmark":
entries = getEntries(username)
endTime = time.time() - startTime
return {
'statusCode': 200,
'body': json.dumps({"execution_time":endTime, "start_time": startTime, "count": len(entries)})
}
def getEntries(username):
client = boto3.resource('dynamodb')
table = client.Table('diary-associations')
response = table.query(
IndexName='username-index',
KeyConditionExpression=Key('username').eq(username)
)
lst = list(map(lambda x : decimalToFloat(x), response['Items']))
lst.sort(key=lambda x : getTimestamp(x['id']), reverse=True)
return lst
def getEntry(username, id):
s3 = boto3.client('s3')
res = s3.get_object(Bucket = 'diary-entries', Key = id)
resDict = {}
resDict['text'] = res['Body'].read().decode('utf-8')
return resDict
def decimalToFloat(item):
item['sentiment'] = dict(map(lambda kv: (kv[0], float(kv[1])), item['sentiment'].items()))
return item
def getTimestamp(id):
timestamp = id.split('/')[-1].replace('.txt', '')
return float(timestamp) | sentiment-analysis-cc/DiarAI | lambda/getDiaryEntrty.py | getDiaryEntrty.py | py | 1,928 | python | en | code | 0 | github-code | 13 |
14600704214 | # -*- coding: utf-8 -*-
"""
The Combat Maneuvers static maneuver table.
Classes:
CombatManeuversManeuverTable
"""
from __future__ import absolute_import
import sys
from maneuvers.static_maneuver_table import StaticManeuverTable
from maneuvers.static_maneuver_table import BLUNDER, ABSOLUTE_FAILURE, FAILURE
from maneuvers.static_maneuver_table import PARTIAL_SUCCESS, NEAR_SUCCESS, SUCCESS, ABSOLUTE_SUCCESS
from console.character.weapon_skills import \
SKILL_ADRENAL_DEFLECTING, SKILL_ADRENAL_EVASION, SKILL_ADRENAL_QUICKDRAW, SKILL_QUICKDRAW, \
SKILL_RAPID_FIRE, SKILL_SWASHBUCKLING
import trace_log as trace
sys.path.append('../')
class CombatManeuversManeuverTable(StaticManeuverTable):
"""
Combat Maneuvers static maneuver table.
Methods:
select_combat_maneuvers_table(maneuver_type)
setup_maneuver_table_frames(self, parent_frame)
table_bonus(self)
"""
MANEUVER_ADRENAL_DEFLECTING = "Adrenal Deflecting"
MANEUVER_ADRENAL_EVASION = "Adrenal Evasion"
MANEUVER_QUICKDRAW = "Quickdraw"
MANEUVER_RAPID_FIRE = "Rapid Fire"
MANEUVER_SWASHBUCKLING = "Swashbuckling"
maneuver_type_options = (
MANEUVER_ADRENAL_DEFLECTING, MANEUVER_ADRENAL_EVASION, MANEUVER_QUICKDRAW,
MANEUVER_RAPID_FIRE, MANEUVER_SWASHBUCKLING
)
maneuver_result_text = {
BLUNDER:
"Are you on drugs? Your opponent actually laughs as you fall all over "
"yourself, dealing yourself a +30 Fall/Crush attack and a ""Medium"" Bone "
"(-30 penalty) injury to a random location. You are stunned for two rounds. "
"You'd better hope this was just for show...",
ABSOLUTE_FAILURE:
"It's unfortunate that you didn't listen to your first instinct, which was "
"_not to try this!!_ You deal yourself an injury (i.e., Critical) appropriate "
"to the maneuver you were attempting (GM's discretion), and hopefully gain a "
"little wisdom.",
FAILURE:
"What do you think this is, a game? You're not capable of that kind of maneuver. "
"You fail.",
PARTIAL_SUCCESS:
"Well, perhaps practice will eventually make perfect. If not in combat, you may "
"abort your maneuver and try again next round. Otherwise, you're in for a pretty "
"hairy round of combat.",
NEAR_SUCCESS:
"You almost had it! An involuntary curse escapes your lips in frustration. If "
"appropriate, you may make another attempt next round with a +10 modification.",
SUCCESS:
"Your long training pays off as you step through your maneuver with an almost "
"instinctual ease.",
ABSOLUTE_SUCCESS:
"There's a rhythm to everything, and you have caught the rhythm of this maneuver. "
"You may operate at a modification of +20 (non-cumulative) to this skill until "
"you receive a result of Absolute Failure or Blunder on this table."
}
maneuver_result_stats = {
BLUNDER: (-50, 2, -30),
ABSOLUTE_FAILURE: (-25, 1.5, -15),
FAILURE: (0, 1, 0),
PARTIAL_SUCCESS: (20, 1.25, 5),
NEAR_SUCCESS: (80, 1, 10),
SUCCESS: (100, 1, 20),
ABSOLUTE_SUCCESS: (120, 0.75, 30)
}
@staticmethod
def select_combat_maneuvers_table(maneuver_type, parent_maneuver_table):
"""
Set the current combat maneuvers maneuver table to use.
:param maneuver_type: The type of maneuver selected.
:param parent_maneuver_table: The owning maneuver table.
:return: The maneuver table.
"""
# pylint: disable=import-outside-toplevel
# Avoid circular import problems
from .combat_maneuvers.adrenal_deflecting_maneuver_table import \
AdrenalDeflectingManeuverTable
from .combat_maneuvers.adrenal_evasion_maneuver_table import AdrenalEvasionManeuverTable
from .combat_maneuvers.quickdraw_maneuver_table import QuickdrawManeuverTable
from .combat_maneuvers.rapid_fire_maneuver_table import RapidFireManeuverTable
if maneuver_type == CombatManeuversManeuverTable.MANEUVER_ADRENAL_DEFLECTING:
trace.flow("Adrenal Deflecting maneuver")
return AdrenalDeflectingManeuverTable()
elif maneuver_type == CombatManeuversManeuverTable.MANEUVER_ADRENAL_EVASION:
trace.flow("Adrenal Evasion maneuver")
return AdrenalEvasionManeuverTable()
elif maneuver_type == CombatManeuversManeuverTable.MANEUVER_QUICKDRAW:
trace.flow("Quickdraw maneuver")
return QuickdrawManeuverTable()
elif maneuver_type == CombatManeuversManeuverTable.MANEUVER_RAPID_FIRE:
trace.flow("Rapid Fire maneuver")
return RapidFireManeuverTable(parent_maneuver_table)
else:
trace.flow("Combat maneuvers")
return CombatManeuversManeuverTable()
@staticmethod
def get_maneuver_preferred_skills(maneuver_type):
"""
Return a list of skills that are the preferred skills to use for this maneuver.
:param maneuver_type: The type of maneuver selected.
"""
maneuver_to_skills = {
CombatManeuversManeuverTable.MANEUVER_ADRENAL_DEFLECTING:
[SKILL_ADRENAL_DEFLECTING, ],
CombatManeuversManeuverTable.MANEUVER_ADRENAL_EVASION:
[SKILL_ADRENAL_EVASION, ],
CombatManeuversManeuverTable.MANEUVER_QUICKDRAW:
[SKILL_QUICKDRAW, SKILL_ADRENAL_QUICKDRAW],
CombatManeuversManeuverTable.MANEUVER_RAPID_FIRE:
[SKILL_RAPID_FIRE, ],
CombatManeuversManeuverTable.MANEUVER_SWASHBUCKLING:
[SKILL_SWASHBUCKLING, ]
}
skills_list = maneuver_to_skills.get(maneuver_type, [])
trace.detail("Maneuver type %s, skills list %r" % (maneuver_type, skills_list))
return skills_list
| AidanCopeland/merp | maneuvers/combat_maneuvers_maneuver_table.py | combat_maneuvers_maneuver_table.py | py | 6,037 | python | en | code | 1 | github-code | 13 |
33947606455 | #!/usr/bin/python3
import unittest
import datetime
import os
from models.base_model import BaseModel
from models import storage
class TestBaseModel(unittest.TestCase):
def setUp(self):
self.model = BaseModel()
def test_id_is_string(self):
self.assertIsInstance(self.model.id, str)
def test_created_at_is_datetime(self):
self.assertIsInstance(self.model.created_at, datetime.datetime)
def test_updated_at_is_datetime(self):
self.assertIsInstance(self.model.updated_at, datetime.datetime)
def test_str_method(self):
self.assertEqual(
str(self.model),
f"[BaseModel] ({self.model.id}) {self.model.__dict__}")
def test_save_method_updates_updated_at(self):
original_updated_at = self.model.updated_at
self.model.save()
self.assertNotEqual(original_updated_at, self.model.updated_at)
def test_to_dict_method(self):
model_dict = self.model.to_dict()
self.assertIsInstance(model_dict, dict)
self.assertEqual(model_dict['__class__'], 'BaseModel')
self.assertEqual(model_dict['created_at'],
self.model.created_at.isoformat())
self.assertEqual(model_dict['updated_at'],
self.model.updated_at.isoformat())
def test_new_instance_creates_new_entry_in_storage(self):
storage_count_before = len(storage.all())
new_model = BaseModel()
storage_count_after = len(storage.all())
self.assertEqual(storage_count_after, storage_count_before + 1)
def test_kwargs_constructor(self):
kwargs = {'id': 'test_id',
'created_at': '2023-08-10T12:00:00.000000', 'name': 'Test'}
model_with_kwargs = BaseModel(**kwargs)
self.assertEqual(model_with_kwargs.id, 'test_id')
self.assertEqual(model_with_kwargs.name, 'Test')
self.assertIsInstance(model_with_kwargs.created_at, datetime.datetime)
def test_new_instance_has_id_created_updated_attributes(self):
new_model = BaseModel()
self.assertTrue(hasattr(new_model, 'id'))
self.assertTrue(hasattr(new_model, 'created_at'))
self.assertTrue(hasattr(new_model, 'updated_at'))
def test_new_instance_with_id_kwarg(self):
kwargs_with_id = {'id': 'test_id'}
model_with_id = BaseModel(**kwargs_with_id)
self.assertEqual(model_with_id.id, 'test_id')
def test_new_instance_with_created_at_kwarg(self):
created_at_string = '2023-08-10T12:00:00.000000'
kwargs_with_created_at = {'created_at': created_at_string}
model_with_created_at = BaseModel(**kwargs_with_created_at)
expected_created_at = datetime.datetime.strptime(
created_at_string, "%Y-%m-%dT%H:%M:%S.%f")
self.assertEqual(model_with_created_at.created_at, expected_created_at)
def test_new_instance_without_args_or_kwargs(self):
new_model = BaseModel()
self.assertIsNotNone(new_model.id)
self.assertIsInstance(new_model.created_at, datetime.datetime)
self.assertIsInstance(new_model.updated_at, datetime.datetime)
def test_save_method_updates_storage(self):
storage_count_before = len(storage.all())
new_model = BaseModel()
new_model.save()
storage_count_after = len(storage.all())
self.assertEqual(storage_count_after, storage_count_before + 1)
def test_reload_method(self):
new_model = BaseModel()
new_model.save()
storage.save()
storage.reload()
reloaded_model = storage.all().get(
f"{BaseModel.__name__}.{new_model.id}")
self.assertIsNotNone(reloaded_model)
self.assertEqual(reloaded_model.id, new_model.id)
def test_reload_method_without_file(self):
# Remove the file before reloading
file_path = storage._FileStorage__file_path
if os.path.exists(file_path):
os.remove(file_path)
storage.reload()
# Check that __objects is an empty dictionary
self.assertEqual(len(storage.all()), 0)
def test_str_method_with_extra_attributes(self):
# Add extra attributes to the instance
self.model.extra_attr = "extra_value"
self.model.another_attr = "another_value"
str_output = str(self.model)
self.assertIn("extra_attr", str_output)
self.assertIn("another_attr", str_output)
def test_invalid_updated_at_string(self):
kwargs = {'updated_at': 'invalid_format'}
with self.assertRaises(ValueError):
BaseModel(**kwargs)
if __name__ == '__main__':
unittest.main()
| F1R3BLAZ3/AirBnB_clone | tests/test_models/test_base_model.py | test_base_model.py | py | 4,661 | python | en | code | 0 | github-code | 13 |
42873768899 | from flask import Flask,jsonify,request
app = Flask(__name__)
data = {
"1" : {
"username" : "rajeev",
"caption" : "Hello world rajeev"
},
"2" : {
"username" : "shashi",
"caption" : "Hello world shashi"
}
}
@app.route("/")
def hello_world():
return "Hello Instagram"
@app.route("/all")
def viewAllPosts():
return jsonify(data)
@app.route("/all/<id>")
def viewPostsById(id):
return jsonify(data.get(id))
@app.route("/add", method = 'POST')
def addPosts():
data["3"] = {
"username" : "aman",
"caption":"hello aman"
}
return "post added successfully"
if __name__ == "__main__":
app.run(debug=True)
| Raaz2/GenerativeAI | PythonProblemInterview/instagramapp/app.py | app.py | py | 698 | python | en | code | 0 | github-code | 13 |
41563948608 | from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
import hashlib
BUF_SIZE = 65536 # lets read stuff in 64kb chunks!
def generate_rsa_key():
key = RSA.generate(2048)
return key
def encrypt_rsa_private_key(passphrase: str, rsa_private_key: bytes):
# Encrypt RSA private key
# Using AES, passphrase = user input
## Get aes private key using hashed passphrase for encryption
aes_privatekey = AES.new(hashlib.sha256(passphrase.encode()).digest(), AES.MODE_EAX)
## Encrypt RSA private key
cipherkey, tag = aes_privatekey.encrypt_and_digest(rsa_private_key)
return cipherkey, tag, aes_privatekey.nonce
def concanate_cipherkey_tag_nonce(cipherkey: bytes, tag: bytes, nonce: bytes):
res = nonce + tag + cipherkey
return res
def slide_cipherkey_tag_nonce(cstr: bytes):
nonce, tag, cipherkey = cstr[0:16], cstr[16:32], cstr[32:]
return cipherkey, tag, nonce
def decrypt_rsa_private_key(passphrase: str, cipherkey: bytes, tag: bytes, nonce:bytes) -> bytes:
aes_privatekey = AES.new(hashlib.sha256(passphrase.encode()).digest(), AES.MODE_EAX, nonce)
private_key = aes_privatekey.decrypt_and_verify(cipherkey, tag)
return private_key
def encrypt_file(file_path: str, key: bytes):
with open(file_path, "rb") as file_in:
data = file_in.read()
#read public key from file
recipient_key = RSA.import_key(key)
#generate aes session key
session_key = get_random_bytes(16)
# Encrypt session key with the public RSA key
cipher_rsa = PKCS1_OAEP.new(recipient_key)
enc_session_key = cipher_rsa.encrypt(session_key)
# Encrypt data with the AES session key
# get key
cipher_aes = AES.new(session_key, AES.MODE_EAX)
# encrypt
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
# write to file
file_out = open(file_path+".bin", "wb")
[ file_out.write(x) for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext) ]
file_out.close()
return file_path+".bin"
def decrypt_file(file_path: str, key: bytes):
# open cipher text
file_in = open(file_path, "rb")
# read private key from file
private_key = RSA.import_key(key)
# read from file
enc_session_key, nonce, tag, ciphertext = \
[ file_in.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ]
file_in.close()
# Decrypt the session key with the private RSA key
cipher_rsa = PKCS1_OAEP.new(private_key)
session_key = cipher_rsa.decrypt(enc_session_key)
# Decrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
data = cipher_aes.decrypt_and_verify(ciphertext, tag)
# write to file
file_path = file_path.replace(".bin","")
file_out = open(file_path, "wb")
file_out.write(data)
file_out.close()
return file_path
def handle_uploaded_file(f):
with open('temp.txt', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
def sign_file(file_path: str, private_key:bytes):
sha256 = SHA256.new()
recipient_key = RSA.import_key(private_key)
signer = PKCS1_v1_5.new(recipient_key)
# cipher_rsa = PKCS1_OAEP.new(private_key)
with open(file_path, 'rb') as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
sha256.update(data)
with open(file_path+".sig",'wb') as sig_file:
sig_file.write(signer.sign(sha256))
return file_path+".sig"
def verify_sig(sig_file_path: str, plain_file_path:str, pub_key: bytes) -> bool:
sha256 = SHA256.new()
recipient_key = RSA.import_key(pub_key)
signer = PKCS1_v1_5.new(recipient_key)
with open(sig_file_path, 'rb') as sig_file, open(plain_file_path,'rb') as plain_file:
# hash plain_file
while True:
data = plain_file.read(BUF_SIZE)
if not data:
break
sha256.update(data)
# decrypt sig_file
sig_data = sig_file.read()
return signer.verify(sha256, sig_data)
| ImDoneWithThisUsername/PRJ1-Encryption | accounts/encryption.py | encryption.py | py | 4,080 | python | en | code | 1 | github-code | 13 |
23949573251 | import os
import logging
import message
import asyncio
import aioredis
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, MessageHandler, filters
from telegram.ext.filters import BaseFilter
BOT_TOKEN = os.getenv("BOT_TOKEN")
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
redis = aioredis.from_url("redis://localhost")
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
logger.info(
f"Message from chat #{update.effective_chat.id}"
f"Message from #{update.effective_user.first_name}"
)
await redis.lpush("chats", update.effective_chat.id)
await update.message.reply_text(
f"Hello {update.effective_user.first_name} ({update.effective_chat.id})"
)
async def message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
logger.info(
f"Message from chat #{update.effective_chat.id}"
f"Message from #{update.effective_user.first_name}"
)
await update.message.reply_text(
f"Hello {update.effective_user.first_name} ({update.effective_chat.id})"
)
if __name__ == "__main__":
app = ApplicationBuilder().token(BOT_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(~filters.COMMAND, message))
app.run_polling()
| akinfina-ulyana/sade22 | bot.py | bot.py | py | 1,373 | python | en | code | 0 | github-code | 13 |
38466838822 | import json
import os
import sys
from github import Github
fields_config = ['token', 'owner', 'repository', 'login']
def get_config():
config = {}
gh_proc = os.popen('gh api user')
for source in (os.environ['HOME'] + '/.push.json', gh_proc.name):
try:
config.update(json.loads(open(source).read()))
except:
pass
try:
owner, repository = os.popen('git config --get remote.origin.url')\
.read() \
.strip()[len('git@github.com:'):-len('.git')] \
.split('/')
config['owner'], config['repository'] = owner, repository
except:
pass
return {k: config.get(k) for k in fields_config}
def _main():
config = get_config()
token = config['token'] or input('Token: ')
owner = config['owner'] or input('Owner: ')
repository = config['repository'] or input('Repository: ')
assignee = config['login'] or input('Assignee: ')
no_signed = '--no-signed' in sys.argv
pr_number = int(input('PR number: '))
g = Github(token)
repo = g.get_repo('/'.join([owner, repository]))
pr = repo.get_pull(pr_number)
if not (pr.assignee and pr.assignee.login == assignee):
print("is the pull request yours?")
exit(1)
from_branch, to_branch = pr.head.ref, pr.base.ref
out = os.popen(f'cd /tmp '
f'&& rm -rf {repository} '
f'&& git clone {repo.ssh_url} '
f'&& cd {repository} '
f'&& git checkout origin/{to_branch} '
f'&& git diff origin/{to_branch} origin/{from_branch} | git apply '
f'&& git add . '
f'&& git commit {"" if no_signed else "-S"} -m {pr.title!r}').read()
if input(out + ' ok? ') == 'yes':
print(os.popen(f'cd /tmp/{repository} && git push origin HEAD:{from_branch} --force').read())
else:
print('cancelled')
def main():
try:
_main()
except KeyboardInterrupt:
exit(1)
| 1frag/ForcePusher | Sources/PythonForcePusher/force_push.py | force_push.py | py | 2,029 | python | en | code | 0 | github-code | 13 |
37677891224 | import chess
from definitions import INFINITE, MAX_PLY, MATE
from search.base import BaseSearch
def is_drawn(board: chess.Board):
return board.is_fivefold_repetition() \
or board.is_stalemate() \
or board.is_seventyfive_moves() \
or board.is_insufficient_material()
class MinimaxMixin(BaseSearch):
def search(self, depth, ply=0):
"""
Search `self.board` with the `self.evaluate` using the
minimax algorithm.
The implementation is in a Negamax arrangement.
-> Here, we try to avoid repeating code for the min and max nodes by
fixing a positive score for White and negative score for Black.
-> Consider the root node as a max-node.
-> When searching a min-node, we can simply maximize the negative score
to achieve the same effect as minimizing the score.
-> The score returned to the parent then needs to be negated to retrieve
the actual value.
:param depth: Remaining depth to search.
:param ply: Depth of the current node.
:return: (score, pv)
"""
if depth <= 0:
# This is a leaf node. So use plain evaluation or quiescence search.
return self.evaluate(), []
if ply >= MAX_PLY:
# Hard stop on search depth.
return self.evaluate(), []
if self.board.is_checkmate():
# Board is in checkmate, return a distance from mate score.
return -MATE + ply, []
if is_drawn(self.board):
# Five-fold repetition is a draw.
return 0, []
if ply > 0 and self.stop_signal():
# We met a stop condition, abort and return.
return 0, []
best_value = -INFINITE
pv = []
for move in self.board.legal_moves:
self.board.push(move)
search_value, child_pv = self.search(depth - 1, ply + 1)
search_value = -search_value
self.board.pop()
if ply > 0 and self.stop_signal():
# We got a stop signal either in the child node or now,
# continue unwinding by returning without updating any
# further.
return 0, []
if search_value > best_value:
best_value = search_value
pv = [move] + child_pv
return best_value, pv
| Mk-Chan/python-chess-engine-extensions | search/minimax.py | minimax.py | py | 2,423 | python | en | code | 13 | github-code | 13 |
27667933266 | import sys
import os
import json
import xml.etree.ElementTree as ET
import yaml
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QLabel, QLineEdit, QPushButton, QFileDialog, QMessageBox
class DataConverter(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Data Converter")
self.resize(300, 150)
self.input_file_path = None
self.output_file_path = None
self.layout = QVBoxLayout()
self.input_label = QLabel("Input File:")
self.layout.addWidget(self.input_label)
self.input_line_edit = QLineEdit()
self.layout.addWidget(self.input_line_edit)
self.input_button = QPushButton("Browse")
self.input_button.clicked.connect(self.browse_input_file)
self.layout.addWidget(self.input_button)
self.output_label = QLabel("Output File:")
self.layout.addWidget(self.output_label)
self.output_line_edit = QLineEdit()
self.layout.addWidget(self.output_line_edit)
self.output_button = QPushButton("Browse")
self.output_button.clicked.connect(self.browse_output_file)
self.layout.addWidget(self.output_button)
self.convert_button = QPushButton("Convert")
self.convert_button.clicked.connect(self.convert_data)
self.layout.addWidget(self.convert_button)
self.central_widget = QWidget()
self.central_widget.setLayout(self.layout)
self.setCentralWidget(self.central_widget)
def browse_input_file(self):
file_dialog = QFileDialog()
file_path, _ = file_dialog.getOpenFileName(self, "Select Input File")
self.input_line_edit.setText(file_path)
def browse_output_file(self):
file_dialog = QFileDialog()
file_path, _ = file_dialog.getSaveFileName(self, "Select Output File")
self.output_line_edit.setText(file_path)
def convert_data(self):
self.input_file_path = self.input_line_edit.text()
self.output_file_path = self.output_line_edit.text()
if not self.input_file_path or not self.output_file_path:
QMessageBox.warning(self, "Error", "Please select input and output files.")
return
input_extension = os.path.splitext(self.input_file_path)[1].lower()
output_extension = os.path.splitext(self.output_file_path)[1].lower()
try:
if input_extension == ".json":
with open(self.input_file_path, "r") as input_file:
data = json.load(input_file)
elif input_extension == ".xml":
tree = ET.parse(self.input_file_path)
root = tree.getroot()
data = self.xml_to_dict(root)
elif input_extension == ".yaml" or input_extension == ".yml":
with open(self.input_file_path, "r") as input_file:
data = yaml.safe_load(input_file)
else:
QMessageBox.warning(self, "Error", "Invalid input file format.")
return
if output_extension == ".json":
with open(self.output_file_path, "w") as output_file:
json.dump(data, output_file, indent=4)
elif output_extension == ".xml":
root = self.dict_to_xml(data)
tree = ET.ElementTree(root)
tree.write(self.output_file_path, encoding="utf-8", xml_declaration=True)
elif output_extension == ".yaml" or output_extension == ".yml":
with open(self.output_file_path, "w") as output_file:
yaml.safe_dump(data, output_file)
else:
QMessageBox.warning(self, "Error", "Invalid output file format.")
return
QMessageBox.information(self, "Success", "Data conversion completed.")
except Exception as e:
QMessageBox.warning(self, "Error", str(e))
def xml_to_dict(self, element):
data = {}
if element.attrib:
data["@attributes"] = element.attrib
if element.text:
data["text"] = element.text.strip()
for child in element:
child_data = self.xml_to_dict(child)
if child.tag in data:
if not isinstance(data[child.tag], list):
data[child.tag] = [data[child.tag]]
data[child.tag].append(child_data)
else:
data[child.tag] = child_data
return data
def dict_to_xml(self, data, parent=None):
if parent is None:
parent = ET.Element("root")
for key, value in data.items():
if key == "@attributes":
for attr_key, attr_value in value.items():
parent.set(attr_key, attr_value)
elif key == "text":
parent.text = value
elif isinstance(value, list):
for item in value:
element = ET.Element(key)
self.dict_to_xml(item, parent=element)
parent.append(element)
else:
element = ET.Element(key)
self.dict_to_xml(value, parent=element)
parent.append(element)
return parent
if __name__ == "__main__":
app = QApplication(sys.argv)
converter = DataConverter()
converter.show()
sys.exit(app.exec_())
| kkseniaaa/Narzedzia-w-branzy-IT | main.py | main.py | py | 5,581 | python | en | code | 0 | github-code | 13 |
86459024387 | import warnings
from abc import abstractmethod
from pathlib import Path
from typing import Union, List
import numpy as np
from tqdm import tqdm
import torch
from torch.utils.data.dataset import Dataset
from flair.datasets import DataLoader
from flair.datasets import SentenceDataset
import flair
flair.device = 'cuda:1'
from flair.data import DataPoint
from flair.training_utils import Result
import torch
import torch.nn as nn
import torch.nn.functional as F
from flair.embeddings import FlairEmbeddings
from flair.models import LanguageModel
from torch.nn.utils.rnn import pad_sequence
from torch.nn.utils.rnn import pack_padded_sequence
import torch.optim as optim
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
torch.manual_seed(1)
class LabeledString(DataPoint):
def __init__(self, string: str):
super().__init__()
self.string = string
def __str__(self) -> str:
# add Sentence labels to output if they exist
sentence_labels = f" − Labels: {self.annotation_layers}" if self.annotation_layers != {} else ""
return f'String: "{self.string}" {sentence_labels}'
def __repr__(self) -> str:
# add Sentence labels to output if they exist
sentence_labels = f" − Labels: {self.annotation_layers}" if self.annotation_layers != {} else ""
return f'String: "{self.string}" {sentence_labels}'
def argmax(vec):
# return the argmax as a python int
_, idx = torch.max(vec, 1)
return idx.item()
# Compute log sum exp in a numerically stable way for the forward algorithm
def log_sum_exp(vec):
max_score = vec[0, argmax(vec)]
max_score_broadcast = max_score.view(1, -1).expand(1, vec.size()[1])
return max_score + \
torch.log(torch.sum(torch.exp(vec - max_score_broadcast)))
class FlairTokenizer(flair.nn.Model):
def __init__(self,
letter_to_ix={}, # character dictionary
embedding_dim=4096,
hidden_dim=256,
num_layers=1,
use_CSE=False,
tag_to_ix={'B': 0, 'I': 1, 'E': 2, 'S': 3, 'X': 4},
learning_rate=0.1,
use_CRF=False,
dropout=0. #dropout: float = 0.
):
super(FlairTokenizer, self).__init__()
self.letter_to_ix = letter_to_ix
self.embedding_dim = embedding_dim
self.hidden_dim = hidden_dim
self.num_layers = num_layers
self.use_CSE = use_CSE
self.tag_to_ix = tag_to_ix
self.ix_to_tag = {y: x for x, y in self.tag_to_ix.items()}
self.learning_rate = learning_rate
self.use_CRF = use_CRF
self.dropout = dropout
if not self.use_CSE:
self.character_embeddings = nn.Embedding(len(letter_to_ix), embedding_dim)
self.embeddings = self.character_embeddings
elif self.use_CSE:
self.flair_embedding = FlairEmbeddings
self.lm_f: LanguageModel = self.flair_embedding('multi-forward').lm
self.lm_b: LanguageModel = self.flair_embedding('multi-backward').lm
self.embeddings = self.flair_embedding
if self.use_CRF:
self.START_TAG = '<START>'
self.STOP_TAG = '<STOP>'
self.tag_to_ix = {"B": 0, "I": 1, "E": 2, 'S': 3, 'X': 4, self.START_TAG: 5, self.STOP_TAG: 6}
self.ix_to_tag = {y: x for x, y in self.tag_to_ix.items()}
self.tagset_size = len(self.tag_to_ix)
# Matrix of transition parameters. Entry i,j is the score of
# transitioning *to* i *from* j.
self.transitions = nn.Parameter(
torch.randn(len(self.tag_to_ix), len(self.tag_to_ix), device=flair.device))
# These two statements enforce the constraint that we never transfer
# to the start tag and we never transfer from the stop tag
self.transitions.data[self.tag_to_ix[self.START_TAG], :] = -10000
self.transitions.data[:, self.tag_to_ix[self.STOP_TAG]] = -10000
self.lstm = nn.LSTM(embedding_dim, hidden_dim, num_layers, batch_first=False, bidirectional=True,dropout=self.dropout)
self.hidden2tag = nn.Linear(hidden_dim * 2, len(self.tag_to_ix))
self.loss_function = nn.NLLLoss()
self.to(flair.device)
def _forward_alg(self, feats): # feats = the output: lstm_features
# Do the forward algorithm to compute the partition function
init_alphas = torch.full((1, self.tagset_size), -10000., device=flair.device)
# START_TAG has all of the score.
init_alphas[0][self.tag_to_ix[self.START_TAG]] = 0.
# Wrap in a variable so that we will get automatic backprop
forward_var = init_alphas
# Iterate through the sentence
for feat in feats:
alphas_t = [] # The forward tensors at this timestep
for next_tag in range(self.tagset_size):
# broadcast the emission score: it is the same regardless of
# the previous tag
emit_score = feat[next_tag].view(1, -1).expand(1, self.tagset_size)
# the ith entry of trans_score is the score of transitioning to
# next_tag from i
trans_score = self.transitions[next_tag].view(1, -1)
# The ith entry of next_tag_var is the value for the
# edge (i -> next_tag) before we do log-sum-exp
next_tag_var = forward_var + trans_score + emit_score
# The forward variable for this tag is log-sum-exp of all the
# scores.
alphas_t.append(log_sum_exp(next_tag_var).view(1))
forward_var = torch.cat(alphas_t).view(1, -1)
terminal_var = forward_var + self.transitions[self.tag_to_ix[self.STOP_TAG]]
alpha = log_sum_exp(terminal_var)
return alpha
@abstractmethod
def _score_sentence(self, feats, tags):
# Gives the score of a provided tag sequence
score = torch.zeros(1, device=flair.device)
tags = torch.cat([torch.tensor([self.tag_to_ix[self.START_TAG]], dtype=torch.long, device=flair.device), tags])
for i, feat in enumerate(feats):
score = score + \
self.transitions[tags[i + 1], tags[i]] + feat[tags[i + 1]]
score = score + self.transitions[self.tag_to_ix[self.STOP_TAG], tags[-1]]
return score
def _viterbi_decode(self, feats):
backpointers = []
# Initialize the viterbi variables in log space
init_vvars = torch.full((1, self.tagset_size), -10000., device=flair.device)
init_vvars[0][self.tag_to_ix[self.START_TAG]] = 0
# forward_var at step i holds the viterbi variables for step i-1
forward_var = init_vvars
for feat in feats:
bptrs_t = [] # holds the backpointers for this step
viterbivars_t = [] # holds the viterbi variables for this step
for next_tag in range(self.tagset_size):
# next_tag_var[i] holds the viterbi variable for tag i at the
# previous step, plus the score of transitioning
# from tag i to next_tag.
# We don't include the emission scores here because the max
# does not depend on them (we add them in below)
next_tag_var = forward_var + self.transitions[next_tag]
best_tag_id = argmax(next_tag_var)
bptrs_t.append(best_tag_id)
viterbivars_t.append(next_tag_var[0][best_tag_id].view(1))
# Now add in the emission scores, and assign forward_var to the set
# of viterbi variables we just computed
forward_var = (torch.cat(viterbivars_t) + feat).view(1, -1)
backpointers.append(bptrs_t)
# Transition to STOP_TAG
terminal_var = forward_var + self.transitions[self.tag_to_ix[self.STOP_TAG]]
best_tag_id = argmax(terminal_var)
path_score = terminal_var[0][best_tag_id]
# Follow the back pointers to decode the best path.
best_path = [best_tag_id]
for bptrs_t in reversed(backpointers):
best_tag_id = bptrs_t[best_tag_id]
best_path.append(best_tag_id)
# Pop off the start tag (we dont want to return that to the caller)
start = best_path.pop()
assert start == self.tag_to_ix[self.START_TAG] # Sanity check
best_path.reverse()
return path_score, best_path
@abstractmethod
# def neg_log_likelihood(self, sentence, tags):
def neg_log_likelihood(self, feats, tags): # loss = self.neg_log_likelihood(lstm_feats,targets)
# feats = self.forward_loss(sentence)
forward_score = self._forward_alg(feats)
gold_score = self._score_sentence(feats, tags)
return forward_score - gold_score
def forward(self, data_points):
# Get the emission scores from the BiLSTM
loss, packed_sent, packed_tags, lstm_feats = self.forward_loss(data_points, foreval=True)
# Find the best path, given the features.
score, tag_seq = self._viterbi_decode(lstm_feats)
out_list = [self.ix_to_tag[int(o)] for o in tag_seq]
tag_seq_str = ''
for o in out_list:
tag_seq_str += o
return tag_seq_str
def prepare_cse(self, sentence, batch_size=1):
if (batch_size == 1) & (not isinstance(sentence, list)):
embeds_f = self.lm_f.get_representation([sentence], '\n', '\n')[1:-1, :, :]
embeds_b = self.lm_b.get_representation([sentence], '\n', '\n')[1:-1, :, :]
if (batch_size == 1) & (isinstance(sentence, list)):
embeds_f = self.lm_f.get_representation(sentence, '\n', '\n')[1:-1, :, :]
embeds_b = self.lm_b.get_representation(sentence, '\n', '\n')[1:-1, :, :]
else:
embeds_f = self.lm_f.get_representation(list(sentence), '\n', '\n')[1:-1, :, :]
embeds_b = self.lm_b.get_representation(list(sentence), '\n', '\n')[1:-1, :, :]
return torch.cat((embeds_f, embeds_b), dim=2)
@staticmethod
def prepare_batch(data_points_str, to_ix):
tensor_list = []
for seq in data_points_str:
idxs = [to_ix[w] for w in seq]
tensor = torch.tensor(idxs, dtype=torch.long, device=flair.device)
tensor_list.append(tensor)
sequence = pad_sequence(tensor_list, batch_first=False)
# print(sequence.size())
# batch_tensor = sequence.squeeze()
# print(batch_tensor.size())
# if len(batch_tensor.shape) == 1:
# return batch_tensor.view(-1, 1) # add batch_size = 1 as dimension
# else:
return sequence
@staticmethod
def find_token(sentence_str):
token = []
word = ''
for i, tag in enumerate(sentence_str[1]):
if tag == 'S':
token.append(sentence_str[0][i])
continue
if tag == 'X':
continue
if (tag == 'B') | (tag == 'I'):
word += sentence_str[0][i]
continue
if tag == 'E':
word += sentence_str[0][i]
token.append(word)
word = ''
return token
def prediction_str(self, input):
ix_to_tag = {y: x for x, y in self.tag_to_ix.items()}
output = [torch.argmax(i) for i in input]
out_list = [ix_to_tag[int(o)] for o in output]
out_str = ''
for o in out_list: out_str += o
return out_str
@abstractmethod
def forward_loss(
self,
data_points: Union[List[DataPoint], DataPoint],
foreval=False,
) -> torch.tensor:
"""Performs a forward pass and returns a loss tensor for backpropagation. Implement this to enable training."""
if isinstance(data_points,
LabeledString): # make sure data_points is a list, doesn't matter how many elements inside
data_points = [data_points] # FIXME: why is this not working?
input_sent, input_tags = [], []
for sent in data_points:
input_sent.append((sent.string))
input_tags.append(sent.get_labels('tokenization')[0].value)
batch_size = len(data_points)
batch_input_tags = self.prepare_batch(input_tags, self.tag_to_ix).to(flair.device)
if self.use_CSE:
embeds = self.prepare_cse(input_sent, batch_size=batch_size).to(flair.device)
else:
batch_input_sent = self.prepare_batch(input_sent, self.letter_to_ix)
embeds = self.character_embeddings(batch_input_sent)
out, _ = self.lstm(embeds)
tag_space = self.hidden2tag(out.view(embeds.shape[0], embeds.shape[1], -1))
tag_scores = F.log_softmax(tag_space, dim=2) # dim = (len(data_points),batch,len(tag))
length_list = []
for sentence in data_points:
length_list.append(len(sentence.string))
packed_sent, packed_tags = '', ''
for string in input_sent: packed_sent += string
for tag in input_tags: packed_tags += tag
packed_tag_space = torch.tensor([], dtype=torch.long, device=flair.device)
packed_tag_scores = torch.tensor([], dtype=torch.long, device=flair.device)
packed_batch_input_tags = torch.tensor([], dtype=torch.long, device=flair.device)
for i in np.arange(batch_size):
packed_tag_scores = torch.cat((packed_tag_scores, tag_scores[:length_list[i], i, :]))
packed_tag_space = torch.cat((packed_tag_space, tag_space[:length_list[i], i, :]))
packed_batch_input_tags = torch.cat((packed_batch_input_tags, batch_input_tags[:length_list[i], i]))
if not self.use_CRF:
tag_predict = self.prediction_str(packed_tag_scores)
loss = self.loss_function(packed_tag_scores, packed_batch_input_tags)
if foreval:
return loss, packed_sent, packed_tags, tag_predict
else:
return loss
else: # extract lstm_features for CRF layer
lstm_feats = packed_tag_space
loss = self.neg_log_likelihood(lstm_feats, packed_batch_input_tags)
if foreval:
return loss, packed_sent, packed_tags, lstm_feats
else:
return loss
@abstractmethod
def evaluate(
self,
sentences: Union[List[DataPoint], Dataset],
out_path: Path = None,
embedding_storage_mode: str = "none",
mini_batch_size: int = 32,
num_workers: int = 8,
) -> (Result, float):
"""Evaluates the model. Returns a Result object containing evaluation
results and a loss value. Implement this to enable evaluation.
:param data_loader: DataLoader that iterates over dataset to be evaluated
:param out_path: Optional output path to store predictions
:param embedding_storage_mode: One of 'none', 'cpu' or 'gpu'. 'none' means all embeddings are deleted and
freshly recomputed, 'cpu' means all embeddings are stored on CPU, or 'gpu' means all embeddings are stored on GPU
:return: Returns a Tuple consisting of a Result object and a loss float value
"""
if not isinstance(sentences, Dataset):
sentences = SentenceDataset(sentences)
data_loader = DataLoader(sentences, batch_size=mini_batch_size, num_workers=num_workers)
eval_loss = 0
with torch.no_grad():
error_sentence = []
R_score, P_score, F1_score = [], [], []
for batch in data_loader: # assume input of evaluate fct is the whole dataset, and each element is a batch
if self.use_CRF:
loss, packed_sent, packed_tags, lstm_feats = self.forward_loss(batch, foreval=True)
packed_tag_predict = self.forward(batch)
else:
loss, packed_sent, packed_tags, packed_tag_predict = self.forward_loss(batch, foreval=True)
reference = self.find_token((packed_sent, packed_tags))
candidate = self.find_token((packed_sent, packed_tag_predict))
inter = [c for c in candidate if c in reference]
if len(candidate) != 0:
R = len(inter) / len(reference)
P = len(inter) / len(candidate)
else:
R, P = 0, 0 # when len(candidate) = 0, which means the model fail to extract any token from the sentence
error_sentence.append((packed_sent, packed_tags, packed_tag_predict))
if (len(candidate) != 0) & ((R + P) != 0): # if R = P = 0, meaning len(inter) = 0, R+P = 0
F1 = 2 * R * P / (R + P)
else:
F1 = 0
if (packed_sent, packed_tags, packed_tag_predict) not in error_sentence:
error_sentence.append((packed_sent, packed_tags, packed_tag_predict))
R_score.append(R)
P_score.append(P)
F1_score.append(F1)
eval_loss += loss
detailed_result = (
"\nResults:"
f"\n- F1-score : {np.mean(F1_score)}"
f"\n- Precision-score : {np.mean(P_score)}"
f"\n- Recall-score : {np.mean(R_score)}"
)
# line for log file
log_header = "F1_score"
log_line = f"\t{np.mean(F1_score)}"
result = Result(
main_score=np.mean(F1_score),
log_line=log_line,
log_header=log_header,
detailed_results=detailed_result,
)
return (result, eval_loss)
def _get_state_dict(self):
model_state = {
"state_dict": self.state_dict(),
'letter_to_ix': self.letter_to_ix,
'embedding_dim': self.embedding_dim,
'hidden_dim': self.hidden_dim,
'num_layers': self.num_layers,
'use_CSE': self.use_CSE,
'tag_to_ix': self.tag_to_ix,
'learning_rate': self.learning_rate,
'use_CRF': self.use_CRF
}
return model_state
@staticmethod
def _init_model_with_state_dict(state):
model = FlairTokenizer(
letter_to_ix=state['letter_to_ix'],
embedding_dim=state['embedding_dim'],
hidden_dim=state['hidden_dim'],
num_layers=state['num_layers'],
use_CSE=state['use_CSE'],
tag_to_ix=state['tag_to_ix'],
learning_rate=state['learning_rate'],
use_CRF=state['use_CRF']
)
model.load_state_dict(state["state_dict"])
return model
@staticmethod
@abstractmethod
def _fetch_model(model_name) -> str:
return model_name
| wuqi0704/MasterThesis_Tokenization | flair/tokenizer_model.py | tokenizer_model.py | py | 19,063 | python | en | code | 0 | github-code | 13 |
11967395773 | '''
Computational Physics Project
A log-likelihood fit for extracting neutrino oscillation parameters
Part 2: 1D Minimisation
'''
# importing variables and functions from previous .py file
from The_Data import events, sim, p, x, np, plt
# defining NLL in 1D
def likelihood(theta):
'''Returns the Negative Log likelihood of the events for a given theta.
The other parameters (L, m_squared) are fixed.
Parameters
----------------
Theta (float) : The mixing angle
Returns
----------------
The Negative Log likelihood (float)
'''
L = 295 # fixed distance
m_sq = 2.4e-3 # fixed m_sauared in the 1-D case
nll = [] # initialise an empty list for nll
k = events # the events per bin from data
for i in range(200):
if k[i] > 0: # to avoid log(0)
lamb = sim[i] * p(theta, m_sq, L, x[i])
nll_i = lamb - k[i] + (k[i] * np.log( k[i] / lamb))
nll.append(nll_i)
if k[i] == 0: # ignore the log term
lamb_0 = sim[i] * p(theta, m_sq, L, x[i])
nll.append(lamb_0)
return sum(nll) # sum of the elements in the nll list
# plotting nll with respect to theta
thet = np.linspace(0, np.pi/2,1000)
ax6 = plt.figure(6).add_subplot(111)
ax6.set(title='NLL against $\Theta_{23}$ with a fixed $\Delta {m^2}_{23}$',
xlabel= r"$\theta_{23}$ (rad)",
ylabel='NLL')
plt.plot(thet, likelihood(thet), color = 'red')
plt.show()
#%%
#building a parabolic minimiser
def x_min(f,z):
'''Returns the minimum point of a parabolic function that contains the three
points in the list of z. This is to be used in minimiser() later.
Parameters
--------------------------
f : A function of 1 variable that returns f (float) at the three x's
z (list) : A list of three x values (float)
Returns
--------------------------
x_min (float) : The x that gives the minimum of a parabolic function
NOTE: f is not necessarily parabolic, but is nearly parabolic at its minimum
'''
x0 = z[0] # first x
y0 = f(x0) # f of first x
x1 = z[1] # second x
y1 = f(x1) # f of second x
x2 = z[2] # third x
y2 = f(x2) # f of third x
# using Langrage polynomials
x_min = (1/2) * ((x2**2 - x1**2) *y0 + (x0**2 - x2**2) *y1 + (x1**2 - x0**2) *y2) / ((x2 - x1) *y0 + (x0 - x2) *y1 + (x1 - x0) *y2)
return x_min
def minimiser(f, guess):
'''Returns the minimum of a function, f(x) along with the list of minimum of f
at each step of minimisation.
Parameters
-----------------------
f : A function of 1 variable, f(x)
guess (list) : The initial guess list of three x values (float)
Returns
-----------------------
x_min_ob (float) : The x that gives the minimum of f(x)
l_min_list (list) : The list of minimum values of f at each step of
minimisation.
'''
d = 0.5 # initial value for the difference in x_min
z0 = guess # redifining for simplicity
x_min_list = [] # initialising an empty list for x_min's
l_min_list = []
while d > 1e-5: # run until the differene is small enough
z_l = []
for i in z0: # for each x in guess, append its f(x)
z_l.append(f(i))
x_m_0 = x_min(f, z0) # minimise f using the guess
# replace the x that gives the highest f with the x_min
z0[z_l.index(max(z_l))] = x_min(f, z0)
d = abs(x_min(f, z0) - x_m_0) # find new x_min, then calculate the difference
x_min_list.append(x_min(f, z0)) # append the x_min's
l_min_list.append(f(x_min(f, z0))) # append the f(x_min)'s
#print('The x_min is',x_min(f, z0), 'and f(x_min) is', f(x_min(f, z0))) # prints x_min and f(x_min) at each step
# choose the x_min that gives the lowest f(x_min) in the list
x_min_ob = x_min_list[l_min_list.index(min(l_min_list))]
return x_min_ob, l_min_list
#checking the minimiser works with other function - using p_mod (modified)
def p_mod(E):
'''Returns the oscillation probability for a given E.
Modified the previous p to set to include only one variable
Parameters
----------------
E (float) : Energy of neutrino
Returns
----------------
The oscillation probability (float)
'''
theta = 0.785 # fixed
m_squared = 2.43e-3 # fixed
L = 295 # fixed
arg = 1.267 * m_squared * L / E
prob = 1 - ((np.sin(2 * theta))**2) * ((np.sin(arg))**2)
return prob
guess_test = [0.6, 0.7, 0.65] # initial guess
p_min, p_l = minimiser(p_mod, guess_test) # run the minimiser on P
p_l = [x*1e5 for x in p_l] # rescale for plotting
ax22 = plt.figure(7).add_subplot(111)
ax22.set(title='P against number of step',
xlabel= 'Number of step',
ylabel=r'P ($ \times 10^{-5}$)')
step2 = np.arange(0, len(p_l)) # x_range for steps
plt.plot(step2, p_l, 'r')
plt.show()
print('The min of p is', round(p_min, 5)) # prints the final answer
# to validate with scipy routine
#op.minimize(p_mod, 0.67, method='nelder-mead') ---> gives [0.57820215]
#it works as expected
#%%
# running the minimiser on the likelihood function, NLL
# first min
guess1 = [0.56, 0.7, 0.2] # initial guess for first min
theta_min, l_2 = minimiser(likelihood, guess1) # run the minimiser on NLL
# second min
guess2 = [0.850, 0.9, 0.975] # initial guess for first min
theta_min2, l_3 = minimiser(likelihood, guess2) # run the minimiser on NLL
# plotting loss after step for both min
ax23 = plt.figure(7).add_subplot(111)
ax23.set(title='NLL against $x_{min}$ after each step',
xlabel= 'Number of step',
ylabel=r'NLL')
step3 = np.arange(0, len(l_2))
plt.plot(step3, l_2, 'r', label = 'First minimum')
step4 = np.arange(0, len(l_3))
plt.plot(step4, l_3, 'b', label = 'Second minimum')
plt.legend()
plt.show()
print('The x_min_1 is', round(theta_min, 6))
print('The x_min_2 is', round(theta_min2, 6))
print(l_2)
#%%
# solving using scipy optimizer to check answer
import scipy.optimize as op
guess_sci = 0.66
res_p = op.minimize(likelihood, guess_sci , method='nelder-mead')
guess2_sci = 0.9
res_p_2 = op.minimize(likelihood, guess2_sci , method='nelder-mead')
#print(res_p, res_p_2) # x_min_1 = 0.66264258 , x_min_2 = 0.90817383
# it checks out
#%%
# accuracy of parameter, theta
# using 0.5 difference method from NLL eq.
# calculating for first minimum
thet_2 = np.linspace(0.61, 0.8,1000) # defining a list of theta with high density
l_min = likelihood(theta_min) # defining a list of nll(theta) for above theta's
l_plus = l_min + 0.5
err_list =[]
for i in thet_2: # find theta that gives l_plus
if (abs(likelihood(i) - l_plus) < 0.01):
err_list.append(theta_min - i)
err_plus = max(err_list) # max is the error in plus direction
theta_plus = theta_min + err_plus
err_minus = abs(min(err_list)) # min is the error in minus direction
theta_minus = theta_min - err_minus
print('The error_minus 1', err_minus, 'and error_plus 1', err_plus)
#checking for second min
thet2_2 = np.linspace(0.85, 0.95,1000) # covering the second minimum
l_min2 = likelihood(theta_min2)
l_plus2 = l_min2 + 0.5
err_list2 =[]
for i in thet2_2: # find theta that gives l_plus
if (abs(likelihood(i) - l_plus2) < 0.01):
err_list2.append(theta_min2 - i)
err_plus2 = max(err_list2)
theta_plus2 = theta_min2 + err_plus2
err_minus2 = abs(min(err_list2))
theta_minus2 = theta_min2 - err_minus2
print('The error_minus 2', err_minus2, 'and error_plus 2', err_plus2)
# next, using 0.5 difference method from parabolic eq.
# firstly need to find the last parabolic estimate
d = 0.5 # initialising difference d
z0 = [0.56, 0.7, 0.2] # initial guess for three points
while d > 1e-5: # run the same minimisation but this time,
# get the three points that give the final x_min
z_l = []
for i in z0:
z_l.append(likelihood(i))
x_m_0 = x_min(likelihood, z0)
z0[z_l.index(max(z_l))] = x_min(likelihood, z0)
d = abs(x_min(likelihood, z0) - x_m_0)
last_parab_list = z0 # the last parabolic estimate
def parabola(f, x, s):
'''Returns a parabolic function that fits three given points (x, f(x))
using Langrage Polynomials.
Parameters
----------------------
f : A function that gives f(x) at a given x
x (float) : Input variable for the parabolic function
s (list) : The list of three points to be fitted
Returns
---------------------
A parabolic function
'''
# defining each term for simplicity
a1 = (x - s[1]) * (x - s[2]) * f(s[0]) / ((s[0] - s[1]) * (s[0] - s[2]))
b1 = (x - s[0]) * (x - s[2]) * f(s[1]) / ((s[1] - s[0]) * (s[1] - s[2]))
c1 = (x - s[0]) * (x - s[1]) * f(s[2]) / ((s[2] - s[0]) * (s[2] - s[1]))
return a1 + b1 +c1
l_min_para = parabola(likelihood, theta_min, last_parab_list) # min value of parabola at x_min
l_plus_para = l_min_para + 0.5
err_list_para =[]
for i in thet_2: # same procedure as nll above
if (abs(parabola(likelihood, i, last_parab_list) - l_plus_para) < 0.01):
err_list_para.append(theta_min - i)
err_plus_para = max(err_list_para)
theta_plus_para = theta_min + err_plus_para
err_minus_para = abs(min(err_list_para))
theta_minus_para = theta_min - err_minus_para
print('The error from parabola for first min', err_minus_para, err_plus_para)
# it gives exactly same answer as NLL method
#%%
# defining automatic method to give uncertainty
def error(f, x_min):
'''Returns the error of a function at a given minimum point, x_min.
Parameters
-------------------
f : A function
x_min (float) : The minimum x of f(x)
Returns
----------------
std (float) : The standard deviation or the error
'''
x_range = np.linspace(x_min - 0.1, x_min + 0.1, 1000)
l_min = f(x_min) #using likelihood function
err_list = []
l_plus = l_min + 0.5
for i in x_range:
if (abs(f(i) - l_plus) < 0.01):
err_list.append(x_min - i)
err_plus = max(err_list)
err_minus = abs(min(err_list))
std = (err_minus + err_plus) /2 # taking the average
return std
std1 = error(likelihood, theta_min)
std2 = error(likelihood, theta_min2)
#quoting the full result
print('The first minimum of theta is', round(theta_min, 3), '+-', round(std1, 3))
print('The second minimum of theta is', round(theta_min2, 3), '+-', round(std2, 3))
| sk6817/Computational-Physics-2019 | Project/1D_Minimisation.py | 1D_Minimisation.py | py | 11,913 | python | en | code | 0 | github-code | 13 |
24690969446 | from flask import Flask, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from json import JSONEncoder
import json
import os
app = Flask(__name__, instance_relative_config=False)
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL")
app.config["SQLALCHEMY_ECHO"] = False
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
# db variable initialization
db = SQLAlchemy(app)
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(60))
surname = db.Column(db.String(60))
def __repr__(self):
return '<Person: {}>'.format(self.name)
db.init_app(app)
db.create_all() # Create sql tables for our data models
class PersonEncoder(JSONEncoder):
def default(self, o):
return o.__dict__
@app.route("/")
def main():
return render_template('index.html')
@app.route('/signUp',methods=['POST'])
def signUp():
# read the posted values from the UI
name = request.form['name']
surname = request.form['surname']
person = Person(name = name, surname = surname )
db.session.add(person)
db.session.flush()
pid = person.id
print(pid)
db.session.commit()
return jsonify({'pid':pid})
# # validate the received values
# if name and surname:
# return json.dumps({'html':'<span>All fields good !!</span>'})
# else:
# return json.dumps({'html':'<span>Enter the required fields</span>'})
@app.route('/view',methods=['POST'])
def view():
pid = request.json['pid']
print("The view pid: ", pid)
p1 = db.session.query(Person).get(pid)
print("The p1 person: ", p1)
print("The p1 person surname: ", p1.surname)
#person = Person.query.filter_by(name="Future")
#print("The view person: ", person)
#personJSONData = json.dumps(p1, indent=4, cls=PersonEncoder)
return jsonify({'name': p1.name, 'surname': p1.surname})
if __name__ == "__main__":
app.run() | ritza-co/demo-flask-mysql | app.py | app.py | py | 1,971 | python | en | code | 0 | github-code | 13 |
43031147343 | #sv-classifier.py
####
# This file identifies instances of Single Ventricle using the Levenshtein.
# Believe a simple tool like this could aid medical workers in finding the majority of cases in unstructured data.
import sys
import os
import pandas as pd
import math
import re
from pandas import ExcelFile
GOLD_STANDARD = f"SV-GoldStandard-Filtered.xlsx"
INPUT_FILE = f"txpl_project.xlsx"
OUTPUT_FILE = f"txpl_project_updated.xlsx"
print(f"Reading {GOLD_STANDARD}")
gold_df = pd.read_excel(GOLD_STANDARD)
print(f"Single Ventricle (SV) Gold Standard Shape: {gold_df.shape}")
print(f"Reading {INPUT_FILE}")
txpl_df = pd.read_excel(INPUT_FILE)
sv_gold = txpl_df['PATIENT_ID'].apply(lambda x: 1 if x in pd.to_numeric(gold_df['PTID']).unique() else 0)
def print_intersecting_patient_ids():
"""
Prints the patient ids for gold records already flagged. Used for double-checking work.
"""
for i, v in enumerate(zip(sv_gold, txpl_df['SV_GROUP'], txpl_df['PATIENT_ID'])):
if v[0] == 1 and v[1] == 1:
print(f"SV_GOLD & SV_GROUP == 1 for PATIENT_ID: {v[2]}")
# print_intersecting_patient_ids()
print(f"SV_GOLD Count: {sv_gold.sum()}" )
print(f"SV_GROUP Count: {txpl_df['SV_GROUP'].sum()}")
sv_combined = sv_gold | txpl_df['SV_GROUP']
sv_intersect = sv_gold & txpl_df['SV_GROUP']
print(f"Insection Count: {sv_intersect.sum()}")
print(f"Combined Count: {sv_combined.sum()}")
txpl_df['SV_GROUP'] = sv_combined
txpl_df.to_excel(OUTPUT_FILE, index=False)
print(f"Wrote Updated txpl_df to {OUTPUT_FILE}")
# match_idx = set()
# stk = StanfordTokenizer() #Dependencies in the lib folder, ADD IT TO YOUR `CLASSPATH` env variable
# for col_name in ["SPECOTH", "CHD_OTHSP"]:
# for index, item in enumerate(df[col_name]):
# if type(item) is str:
# if(matches_heterotaxy_words(stk.tokenize(item))):
# match_idx.add(index)
#
# print(f"Identified extra {len(match_idx)} cases of heterotaxy.")
#
# for i in match_idx:
# df.at[i, "HETEROTAXY"] = 1
#
# df.to_excel(OUTPUT_FILE) | uabinf/nlp-fall-2019-project-textmania | sv-add-gold.py | sv-add-gold.py | py | 2,008 | python | en | code | 1 | github-code | 13 |
1676397467 | import numpy as np
def binary_search(l, r, arr, val):
if r >= l:
m = (l+r) // 2
if arr[m] == val:
return m
elif val > arr[m]:
return binary_search(m+1, r, arr, val)
elif val < arr[m]:
return binary_search(l, m-1, arr, val)
else:
print('value '+str(val)+' not found')
def isUnique(list):
unique = True
for index,element in enumerate(list):
if binary_search(0, len(list), list, element) != index:
print(str(element)+' is not unique')
unique = False
if unique:
print('list elements are unique')
def main():
#if the list is sorted (if not sort by nlogn)
list = np.array([1,5,6,8,9,9,12, 12])
isUnique(list)
main() | farzan-dehbashi/toolkit | algorithms/interview_questions.py/array/item_is_unique_in_list.py | item_is_unique_in_list.py | py | 770 | python | en | code | 5 | github-code | 13 |
41880373500 | from phonenumbers import geocoder, carrier, timezone
#رساله ترحيبية
print(" Welcome to the phone data knowledge program \n BY Muhammad Alaa " "\n M.A" )
print ("""
░░█████████
░░▒▀█████▀░
░░▒░░▀█▀
░░▒░░█░
░░▒░█
░░░█
░░█░░░░███████
░██░░░██▓▓███▓██▒
██░░░█▓▓▓▓▓▓▓█▓████
██░░██▓▓▓(◐)▓█▓█▓█
███▓▓▓█▓▓▓▓▓█▓█▓▓▓▓█
▀██▓▓█░██▓▓▓▓██▓▓▓▓▓█
░▀██▀░░█▓▓▓▓▓▓▓▓▓▓▓▓▓█
░░░░▒░░░█▓▓▓▓▓█▓▓▓▓▓▓█
░░░░▒░░░█▓▓▓▓█▓█▓▓▓▓▓█
░▒░░▒░░░█▓▓▓█▓▓▓█▓▓▓▓█
░▒░░▒░░░█▓▓▓█░░░█▓▓▓█
░▒░░▒░░██▓██░░░██▓▓██
████████████████████████
█▄─▄███─▄▄─█▄─█─▄█▄─▄▄─█
██─██▀█─██─██─█─███─▄█▀█
▀▄▄▄▄▄▀▄▄▄▄▀▀▄▄▄▀▀▄▄▄▄▄▀
""")
#print (" *" , "\n * " , ' *') , print (" *" , "\n * " , ' *' )
# Enter Your Name
import phonenumbers
from phonenumbers import geocoder, carrier, timezone
#رساله ترحيبية
print(" Welcome to the phone data knowledge program \n BY Muhammad Alaa " "\n M.A" )
#print (" *" , "\n * " , ' *') , print (" *" , "\n * " , ' *' )
# Enter Your Name
q = str(input(" Enter Your Name : "))
print (" Welcome " + q)
#Enter Number
entered_num = str(input(" Please Enter a Phone Number , Write Numbers Only: "))
#لطبع كود الدولة مع الرقم المدخل
phone_numbers = phonenumbers.parse(entered_num, None)
##لطبع كود الدولة مع الرقم المدخل
print(phone_numbers)
#طبغ معلومات الموقع الجغرافي
print(geocoder.description_for_number(phone_numbers , "en"))
#معرفه نوع خط الرقم مثلا فودافون موبايلي زين ...،
print (carrier.name_for_number(phone_numbers , "ar"))
#طبع المنطقة الذي يوجد بها الرقم
print(timezone.time_zones_for_number(phone_numbers))
#يلزم ادخل مفتاح الدولة قبل كتابه الرقم
#ا#ذا لم تود ذلك ف ادخل بدلاً من كله
#None ادخل مكانها كود الدولة التي ترغب في البحث عن الرقم فيها
#The code is editable
#"en , ar " تعني لغه الكود الذي يظهر لك
# By Mohammed Alaa 4:05 of the time 2023 / 9 /6 of the dat
#يلزم ادخل مفتاح الدولة قبل كتابه الرقم
#ا#ذا لم تود ذلك ف ادخل بدلاً من كله
#None ادخل مكانها كود الدولة التي ترغب في البحث عن الرقم فيها
#The code is editable
#"en , ar " تعني لغه الكود الذي يظهر لك
# By Mohammed Alaa 4:05 of the time 2023 / 9 /6 of the date 📅
| DARKGITHUBPRO/Number | NUmber.py | NUmber.py | py | 3,253 | python | ar | code | 0 | github-code | 13 |
14818841691 | # implement hash tables
# we store data inside the hash map as Key : value pairs
## handling collisions in hash table using list
class HashTable:
def __init__(self):
"""initialization hash table"""
self.max = 20 #length of list
self.arr = [[None] for i in range(self.max)] # or [None]*self.size we only store the value here
def get_hash(self, key):
"""function to return the hash value using ASCII code"""
h = 0
for char in key:
h += ord(char)
hash_index= h % self.max
return hash_index
def addItem(self ,key ,value):
"""Function the store value in the key index of list"""
h = self.get_hash(key)
self.arr[h] = value
def getItem(self, key):
"""function that return the value stored in the key index"""
h = self.get_hash(key)
return self.arr[h]
def containsItem(self, key):
pass
def deleteItem(self , key):
"""function that set the value of key to None"""
h = self.get_hash(key)
self.arr[h] = None
if __name__ == "__main__":
table = HashTable()
print (table.get_hash("march 6"))
print(table.arr)
print("===============")
table.addItem('march 18' , 0)
table.addItem('march 19' , 100)
table.addItem('march 20' , 200)
table.addItem('march 10' , 300)
table.addItem('march 6' , 400)
# table.addItem('march 17' , 500)
print(table.getItem("march 6")) # O(1)
print(table.arr)
| saadoundhirat/data-structures-and-algorithms | python/code_challenges/hash-tables/hash_tables/demo.py | demo.py | py | 1,527 | python | en | code | 2 | github-code | 13 |
7712017627 | from flask_jwt import jsonify
from sqlalchemy.sql.functions import user
from flask_restful import Resource,reqparse
from models.pets_model import PetModel
from models.user_model import UserModel
from models.category_model import CategoryModel
class Pet(Resource):
parser = reqparse.RequestParser()
parser.add_argument(
'id',
type = int,
required = True,
help = "Pet ID cannot be blank"
)
parser.add_argument(
'pet_name',
type = str,
required = True,
help = "Pet Name cannot be blank"
)
parser.add_argument(
'info',
type = str,
required = True,
help = "Information cannot be blank"
)
parser.add_argument(
'price',
type = int,
required = True,
help = "Price cannot be blank"
)
parser.add_argument(
'user_id',
type = int,
required = True,
help = "User ID cannot be blank"
)
parser.add_argument(
'category_id',
type = int,
required = True,
help = "Category ID cannot be blank"
)
def post(self):
data = Pet.parser.parse_args()
pet = PetModel(**data)
if (PetModel.find_by_id(data['id'])):
return {"message" : "Pet Id is already exists!"}, 400
try:
pet.save_to_db()
return {'Massage' : "Pet Created Successfully"}, 200
except:
return {'Massage' : "Create Error"}, 500
def delete(self):
data = Pet.parser.parse_args()
pet = PetModel.find_by_id(data["id"])
if pet:
pet.delete_from_db()
return {"Massage" : "{} has been deleted".format(data["id"])}, 200
return {"Massage" : "Pet Not Found"}, 500
def put(self):
data = Pet.parser.parse_args()
pet = PetModel(**data)
if pet is None:
pet = PetModel(data["id"],data["pet_name"], data["info"], data["price"], data["user_id"], data["category_id"])
return {'Massage' : "Pet Created Successfully"}, 200
else:
pet.id = data["id"]
pet.pet_name = data["pet_name"]
pet.info = data["info"]
pet.price = data["price"]
pet.user_id = data["user_id"]
pet.category_id = data["category_id"]
pet.save_to_db()
return {'Massage' : "Pet Updated Successfully"}, 200
# id
# pet_name
# info
# price
# user_id
# category_id
class AllPets(Resource):
def get(self):
pets = PetModel.query.all()
return { "All Pets" : [ pet.json() for pet in pets ]} | HtetO2Ko/pet_shop | resource/pets_resource.py | pets_resource.py | py | 2,684 | python | en | code | 0 | github-code | 13 |
24660193049 | """Модуль запуска приложения."""
import uvicorn
from core.app import setup_app
app = setup_app()
if __name__ == "__main__":
uvicorn.run(
app=app, host=app.settings.host, port=app.settings.port, use_colors=True
)
| VIVERA83/derbit | external_service/main.py | main.py | py | 253 | python | en | code | 1 | github-code | 13 |
6441939399 | import pytest
import pytest_asyncio
import secret_wiki.schemas.wiki as schemas
from secret_wiki.models.wiki.section import Section, SectionPermission
from tests.resources.factories import UserFactory
@pytest_asyncio.fixture
async def other_user(db, fake):
user = UserFactory()
db.add(user)
await db.commit()
return user
@pytest.mark.asyncio
async def test_filters_is_secret(db, wikis, pages, user, other_user, sections):
# Can see by default
query = Section.filter(wiki_slug=wikis[0].slug, page_slug=pages[0].slug, user=user)
visible_sections = (await db.execute(query)).scalars().unique().all()
assert len(visible_sections) == 2
# Can't see is admin only
sections[0].is_secret = True
db.add(sections[0])
await db.commit()
visible_sections = (await db.execute(query)).scalars().unique().all()
assert sections[0] not in visible_sections
# Can't see is admin only when another user has access
await sections[0].set_permissions(
schemas.SectionPermission(user=str(other_user.id), level="edit")
)
visible_sections = (await db.execute(query)).scalars().unique().all()
assert sections[0] not in visible_sections
# CAN see is admin only when user has access
await sections[0].set_permissions(schemas.SectionPermission(user=str(user.id), level="edit"))
visible_sections = (await db.execute(query)).scalars().unique().all()
assert sections[0] in visible_sections
@pytest.mark.asyncio
async def test_for_page(db, pages, sections):
sections_for_page = sorted(
[s for s in sections if s.page_id == pages[0].id], key=lambda x: x.section_index
)
# Must have some data for valid test
assert sections_for_page
assert [s.id for s in await Section.for_page(page=pages[0])] == [
s.id for s in sections_for_page
]
assert [s.id for s in await Section.for_page(page_id=pages[0].id)] == [
s.id for s in sections_for_page
]
with pytest.raises(ValueError, match="specify one of"):
await Section.for_page()
| raymondberg/secret_wiki | tests/unit/models/test_section.py | test_section.py | py | 2,061 | python | en | code | 5 | github-code | 13 |
33060363753 | import argparse
import functools as ft
import itertools as it
import logging
import os
import re
import jsonschema
import pkg_resources
import yaml
from .. import util
class Plugin:
"""
Abstract base class for plugins.
"""
ENABLED = True
SCHEMA = {}
ORDER = None
COMMANDS = None
def __init__(self):
self.logger = logging.getLogger(self.__class__.__name__)
self.arguments = {}
def add_argument(self, parser, path, name=None, schema=None, **kwargs):
"""
Add an argument to the `parser` based on a schema definition.
Parameters
----------
parser : argparse.ArgumentParser
parser to add an argument to
path : str
path in the configuration document to add an argument for
name : str or None
name of the command line parameter (defaults to the name in the schema)
schema : dict
JSON schema definition (defaults to the schema of the plugin)
Returns
-------
arg :
command line argument definition
"""
schema = schema or self.SCHEMA
name = name or ('--%s' % os.path.basename(path))
self.arguments[name.strip('-')] = path
# Build a path to the help in the schema
path = util.split_path(path)
path = os.path.sep.join(
it.chain([os.path.sep], *zip(it.repeat("properties"), path)))
property_ = util.get_value(schema, path)
kwargs.setdefault('choices', property_.get('enum'))
kwargs.setdefault('help', property_.get('description'))
type_ = property_.get('type')
if type_:
kwargs.setdefault('type', util.TYPES[type_])
return parser.add_argument(name, **kwargs)
def add_arguments(self, parser):
"""
Add arguments to the parser.
Inheriting plugins should implement this method to add parameters to the command line
parser.
Parameters
----------
parser : argparse.ArgumentParser
parser to add arguments to
"""
pass
def apply(self, configuration, schema, args):
"""
Apply the plugin to the configuration.
Inheriting plugins should implement this method to add additional functionality.
Parameters
----------
configuration : dict
configuration
schema : dict
JSON schema
args : argparse.NameSpace
parsed command line arguments
Returns
-------
configuration : dict
updated configuration after applying the plugin
"""
# Set values from the command line
for name, path in self.arguments.items():
value = getattr(args, name.replace('-', '_'))
if value is not None:
util.set_value(configuration, path, value)
return configuration
@staticmethod
def load_plugins():
"""
Load all availabe plugins.
Returns
-------
plugin_cls : dict
mapping from plugin names to plugin classes
"""
plugin_cls = {}
for entry_point in pkg_resources.iter_entry_points('docker_interface.plugins'):
cls = entry_point.load()
assert cls.COMMANDS is not None, \
"plugin '%s' does not define its commands" % entry_point.name
assert cls.ORDER is not None, \
"plugin '%s' does not define its priority" % entry_point.name
plugin_cls[entry_point.name] = cls
return plugin_cls
def cleanup(self):
"""
Tear down the plugin and clean up any resources used.
Inheriting plugins should implement this method to add additional functionality.
"""
pass
class ValidationPlugin(Plugin):
"""
Validate the configuration document.
"""
COMMANDS = 'all'
ORDER = 990
def apply(self, configuration, schema, args):
super(ValidationPlugin, self).apply(configuration, schema, args)
validator = jsonschema.validators.validator_for(schema)(schema)
errors = list(validator.iter_errors(configuration))
if errors: # pragma: no cover
for error in errors:
self.logger.fatal(error.message)
raise ValueError("failed to validate configuration")
return configuration
class ExecutePlugin(Plugin):
"""
Base class for plugins that execute shell commands.
Inheriting classes should define the method :code:`build_command` which takes a configuration
document as its only argument.
"""
def build_command(self, configuration):
"""
Construct a command and return its parts.
Parameters
----------
configuration : dict
configuration
Returns
-------
args : list
sequence of command line arguments
"""
raise NotImplementedError
def apply(self, configuration, schema, args):
super(ExecutePlugin, self).apply(configuration, schema, args)
parts = self.build_command(configuration)
if parts:
configuration['status-code'] = self.execute_command(parts, configuration['dry-run'])
else:
configuration['status-code'] = 0
return configuration
def execute_command(self, parts, dry_run):
"""
Execute a command.
Parameters
----------
parts : list
Sequence of strings constituting a command.
dry_run : bool
Whether to just log the command instead of executing it.
Returns
-------
status : int
Status code of the executed command or 0 if `dry_run` is `True`.
"""
if dry_run:
self.logger.info("dry-run command '%s'", " ".join(map(str, parts)))
return 0
else: # pragma: no cover
self.logger.debug("executing command '%s'", " ".join(map(str, parts)))
status_code = os.spawnvpe(os.P_WAIT, parts[0], parts, os.environ)
if status_code:
self.logger.warning("command '%s' returned status code %d",
" ".join(map(str, parts)), status_code)
return status_code
class BasePlugin(Plugin):
"""
Load or create a default configuration and set up logging.
"""
SCHEMA = {
"title": "Declarative Docker Interface (DI) definition.",
"$schema": "http://json-schema.org/draft-04/schema",
"additionalProperties": False,
"required": ["workspace", "docker"],
"properties": {
"workspace": {
"type": "string",
"description": "Path defining the DI workspace (absolute or relative to the URI of this document). All subsequent path definitions must be absolute or relative to the `workspace`."
},
"docker": {
"type": "string",
"description": "Name of the docker CLI.",
"default": "docker"
},
"log-level": {
"type": "string",
"enum": ["debug", "info", "warning", "error", "critical", "fatal"],
"default": "info"
},
"dry-run": {
"type": "boolean",
"description": "Whether to just construct the docker command.",
"default": False
},
"status-code": {
"type": "integer",
"description": "status code returned by docker"
},
"plugins": {
"oneOf": [
{
"type": "array",
"description": "Enable the listed plugins and disable all plugins not listed.",
"items": {
"type": "string"
}
},
{
"type": "object",
"properties": {
"enable": {
"type": "array",
"description": "Enable the listed plugins.",
"items": {
"type": "string"
}
},
"disable": {
"type": "array",
"description": "Disable the listed plugins.",
"items": {
"type": "string"
}
}
},
"additionalProperties": False
}
]
}
}
}
def add_arguments(self, parser):
parser.add_argument('--file', '-f', help='Configuration file.', default='di.yml')
self.add_argument(parser, '/workspace')
self.add_argument(parser, '/docker')
self.add_argument(parser, '/log-level')
self.add_argument(parser, '/dry-run')
parser.add_argument('command', help='Docker interface command to execute.',
choices=['run', 'build'])
def apply(self, configuration, schema, args):
# Load the configuration
if configuration is None and os.path.isfile(args.file):
filename = os.path.abspath(args.file)
with open(filename) as fp: # pylint: disable=invalid-name
configuration = yaml.safe_load(fp)
self.logger.debug("loaded configuration from '%s'", filename)
dirname = os.path.dirname(filename)
configuration['workspace'] = os.path.join(dirname, configuration.get('workspace', '.'))
elif configuration is None:
raise FileNotFoundError(
"missing configuration; could not find configuration file '%s'" % args.file)
configuration = super(BasePlugin, self).apply(configuration, schema, args)
logging.basicConfig(level=configuration.get('log-level', 'info').upper())
return configuration
class SubstitutionPlugin(Plugin):
"""
Substitute variables in strings.
String values in the configuration document may
* reference other parts of the configuration document using :code:`#{path}`, where :code:`path`
may be an absolute or relative path in the document.
* reference a variable using :code:`${path}`, where :code:`path` is assumed to be an absolute
path in the :code:`VARIABLES` class attribute of the plugin.
By default, the plugin provides environment variables using the :code:`env` prefix. For example,
a value could reference the user name on the host using :code:`${env/USER}`. Other plugins can
provide variables for substitution by extending the :code:`VARIABLES` class attribute and should
do so using a unique prefix.
"""
REF_PATTERN = re.compile(r'#\{(?P<path>.*?)\}')
VAR_PATTERN = re.compile(r'\$\{(?P<path>.*?)\}')
COMMANDS = 'all'
ORDER = 980
VARIABLES = {
'env': dict(os.environ)
}
@classmethod
def substitute_variables(cls, configuration, value, ref):
"""
Substitute variables in `value` from `configuration` where any path reference is relative to
`ref`.
Parameters
----------
configuration : dict
configuration (required to resolve intra-document references)
value :
value to resolve substitutions for
ref : str
path to `value` in the `configuration`
Returns
-------
value :
value after substitution
"""
if isinstance(value, str):
# Substitute all intra-document references
while True:
match = cls.REF_PATTERN.search(value)
if match is None:
break
path = os.path.join(os.path.dirname(ref), match.group('path'))
try:
value = value.replace(
match.group(0), str(util.get_value(configuration, path)))
except KeyError:
raise KeyError(path)
# Substitute all variable references
while True:
match = cls.VAR_PATTERN.search(value)
if match is None:
break
value = value.replace(
match.group(0),
str(util.get_value(cls.VARIABLES, match.group('path'), '/')))
return value
def apply(self, configuration, schema, args):
super(SubstitutionPlugin, self).apply(configuration, schema, args)
return util.apply(configuration, ft.partial(self.substitute_variables, configuration))
class WorkspaceMountPlugin(Plugin):
"""
Mount the workspace inside the container.
"""
SCHEMA = {
"properties": {
"run": {
"properties": {
"workspace-dir": {
"type": "string",
"description": "Path at which to mount the workspace in the container.",
"default": "/workspace"
},
"workdir": {
"type": "string",
"default": "#{workspace-dir}"
}
},
"additionalProperties": False
}
},
"additionalProperties": False
}
COMMANDS = ['run']
ORDER = 500
def add_arguments(self, parser):
self.add_argument(parser, '/run/workspace-dir')
self.add_argument(parser, '/run/workdir')
def apply(self, configuration, schema, args):
super(WorkspaceMountPlugin, self).apply(configuration, schema, args)
configuration['run'].setdefault('mount', []).append({
'type': 'bind',
'source': '#{/workspace}',
'destination': util.get_value(configuration, '/run/workspace-dir')
})
return configuration
class HomeDirPlugin(Plugin):
"""
Mount a home directory placed in the current directory.
"""
ORDER = 520
COMMANDS = ['run']
def apply(self, configuration, schema, args):
super(HomeDirPlugin, self).apply(configuration, schema, args)
configuration['run'].setdefault('mount', []).append({
'destination': '#{/run/env/HOME}',
'source': '#{/workspace}/.di/home',
'type': 'bind',
})
configuration['run'].setdefault('env', {}).setdefault('HOME', '/${user/name}')
return configuration
| spotify/docker_interface | docker_interface/plugins/base.py | base.py | py | 14,861 | python | en | code | 34 | github-code | 13 |
70045596179 | # -*- coding: utf-8 -*-
# Import modules
from setuptools import find_packages, setup
with open("README.md", encoding="utf8") as readme_file:
readme = readme_file.read()
with open("requirements-lib.txt") as f:
requirements = f.read().splitlines()
with open("requirements-test.txt") as f:
test_requirements = f.read().splitlines()
setup (
name="pyconway",
version="0.1.0-beta",
description="Python Library Simulation of Conway's Game",
long_description=readme,
author="jelambrar96",
author_email="jelambrar@gmail.com",
url="https://github.com/jelambrar96/pyconway",
packages=find_packages(exclude=["docs", "tests"]),
include_package_data=True,
install_requires=requirements,
tests_require=test_requirements,
license="MIT license",
zip_safe=False,
keywords=["conway game", "game of life"],
test_suite="tests",
) | jelambrar96/pyconway | setup.py | setup.py | py | 888 | python | en | code | 1 | github-code | 13 |
40026939295 | # -*- coding: utf-8 -*-
"""
Advent of Code 2021
@author marc
"""
import numpy as np
with open("input-day25") as f:
lines = f.readlines()
lines = [l.split()[0] for l in lines]
grid = np.zeros((len(lines), len(lines[0])), dtype=int)
for row, l in enumerate(lines):
for col, c in enumerate(l):
grid[row, col] = 1 if c == '>' else (2 if c == 'v' else 0)
print(grid)
moves = 1
movecount = 0
while moves:
moves = 0
movecount += 1
rightidcs = np.where(grid == 1)
downidcs = np.where(grid == 2)
toMove = []
for k in range(rightidcs[0].shape[0]):
row = rightidcs[0][k]
col = rightidcs[1][k]
if col+1 < grid.shape[1]:
nextidx = col+1
else:
nextidx = 0
if grid[row, nextidx] == 0:
moves += 1
toMove.append([(row, col), (row, nextidx)])
for idcs in toMove:
grid[idcs[1]] = grid[idcs[0]]
grid[idcs[0]] = 0
toMove = []
for k in range(downidcs[0].shape[0]):
row = downidcs[0][k]
col = downidcs[1][k]
if row+1 < grid.shape[0]:
nextidx = row+1
else:
nextidx = 0
if grid[nextidx, col] == 0:
moves += 1
toMove.append([(row, col), (nextidx, col)])
for idcs in toMove:
grid[idcs[1]] = grid[idcs[0]]
grid[idcs[0]] = 0
print(grid)
print(f"\nTask 1: Number of moves: {movecount}") | masebs/adventOfCode2021 | day25.py | day25.py | py | 1,492 | python | en | code | 0 | github-code | 13 |
16637566639 | # -*- coding: utf-8 -*-
import os
import re
import random
import hashlib
import hmac
from string import letters
from time import strftime
from google.appengine.ext import db
import webapp2
import jinja2
import datetime
from handler import *
from user import *
from menu import *
from order import *
from personalorder import *
from store import *
from menugroup import *
from config import *
USER_RE = re.compile(r"^[a-zA-Z0-9_-]{6,10}$")
def valid_username(username):
return username and USER_RE.match(username)
PASS_RE = re.compile(r"^.{6,20}$")
def valid_password(password):
return password and PASS_RE.match(password)
class MainPage(Handler):
def get(self):
self.redirect('/login')
class Login(Handler):
def get(self):
self.render('login.html')
def post(self):
username = self.request.get('username')
password = self.request.get('password')
u = User.login(username, password)
if u:
self.login(u)
self.redirect('/welcome')
else:
msg = u'登入錯誤'
self.render('login.html', error = msg)
class Logout(Handler):
def get(self):
self.logout()
self.redirect('/')
class Welcome(Handler):
def get(self):
if self.user :
if not self.user.stop:
self.render('welcome.html', username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
class Signup(Handler):
def get(self):
if signup_open:
self.render("signup.html")
else:
self.redirect('/')
def post(self):
have_error = False
self.username = self.request.get('username')
self.password = self.request.get('password')
self.verify = self.request.get('verify')
self.admin=self.request.get("admin")
self.chinesename = self.request.get("chinesename")
agree=self.request.get('agree')
answer=self.request.get('answer')
self.Booladmin = False
params = dict(username = self.username)
if answer != invitation_code:
params['error_answer'] = u"錯誤"
have_error = True
if not valid_username(self.username):
params['error_username'] = u"請輸入帳號"
have_error = True
if not valid_password(self.password):
params['error_password'] = u"請輸入密碼"
have_error = True
if not self.chinesename:
params['error_chinesename'] = u"請輸入姓名"
have_error = True
if self.password != self.verify:
params['error_verify'] = u"密碼不一致"
have_error = True
if not agree:
params['error_agree'] = u"請同意以上事項"
have_error = True
if have_error:
self.render('signup.html', **params)
else:
self.done()
def done(self, *a, **kw):
raise NotImplementedError
class Register(Signup):
def done(self):
#make sure the user doesn't already exist
u = User.by_name(self.username)
if u:
msg = u'帳號已被註冊'
self.render('signup.html', error_username = msg)
else:
if self.admin == "on":
self.Booladmin = True
self.stop=False
self.stop_admin = ' '
u = User.register(self.username, self.password, self.chinesename , self.Booladmin, self.stop , self.stop_admin)
u.put()
self.login(u)
self.redirect('/welcome')
class ChangePassword(Handler):
def get(self):
if self.user :
if not self.user.stop:
self.render('changepassword.html',username = self.user.name , admin = self.user.admin ,chinesename = self.user.chinesename)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
def post(self):
changepassword = self.request.get('changepassword')
changeverify = self.request.get('changeverify')
have_error = False
params = dict()
params['username']=self.user.name
params['admin'] = self.user.admin
params['chinesename'] = self.user.chinesename
if not valid_password(changepassword):
params['error_password'] = u"請輸入密碼"
have_error = True
elif changepassword != changeverify:
params['error_verify'] = u"密碼不一致"
have_error = True
if have_error:
self.render('changepassword.html', **params)
else:
q = db.GqlQuery("SELECT * FROM User WHERE name = :username " ,username = self.user.name )
results = q.fetch(10)
db.delete(results)
self.Boolstop=False
self.stop_admin = ' '
u = User.register(self.user.name, changepassword, self.user.chinesename ,self.user.admin,self.Boolstop,self.stop_admin)
u.put()
self.login(u)
self.redirect('/changepasswordsuccessful')
class ChangePasswordSuccessful(Handler):
def get(self):
if self.user :
if not self.user.stop:
self.render('changepasswordsuccessful.html',username=self.user.name,admin = self.user.admin ,chinesename = self.user.chinesename)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
class NotAdmin(Handler):
def get(self):
if self.user :
if not self.user.stop:
self.render('notadmin.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
class AddMenu(Handler):
def get(self):
if self.user :
if not self.user.stop:
if self.user.admin:
menu_groupquery=MenuGroup.all()
menu_groups=menu_groupquery.fetch(None,0)
self.render('addmenu.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename , menu_groups = menu_groups)
else:
self.redirect('/notadmin')
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
def post(self):
store_name = self.request.get('store_name')
menu_group = self.request.get('menu_group_name')
menu_name = self.request.get('menu_name')
sprice = self.request.get('price')
if not store_name or not menu_group or not menu_name or not sprice or not sprice.isdigit() or len(menu_name)>15:
msg = u"請重試一遍"
menu_groupquery=MenuGroup.all()
menu_groups=menu_groupquery.fetch(None,0)
self.render('addmenu.html', error=msg,username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename , menu_groups = menu_groups)
else:
menu_store_name = menu_group.split(',')[0]
menu_group_name = menu_group.split(',')[1]
if menu_store_name != store_name:
msg = u'請重新選擇'
menu_groupquery=MenuGroup.all()
menu_groups=menu_groupquery.fetch(None,0)
self.render('addmenu.html', error=msg,username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename , menu_groups = menu_groups)
else:
u = Menu.by_menu_name(store_name ,menu_name)
if u:
msg = u'已有此飲料'
menu_groupquery=MenuGroup.all()
menu_groups=menu_groupquery.fetch(None,0)
self.render('addmenu.html', error=msg,username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename , menu_groups = menu_groups)
else:
price = int(sprice)
u = Menu.add_menu(store_name , menu_group_name,menu_name , price)
u.put()
self.redirect('/addmenusuccessful')
class AddMenuSuccessful(Handler):
def get(self):
if self.user :
if not self.user.stop:
if self.user.admin:
self.render('addmenusuccessful.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename)
else:
self.redirect('/notadmin')
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
class ViewMenu(Handler):
def get(self):
if self.user :
if not self.user.stop:
# menuquery = db.GqlQuery("SELECT * FROM Menu ")
# smenus=menuquery.fetch(None,0)
# menus = sorted(smenus, reverse=True , key=lambda smenus : smenus.store_name)
groupquery = db.GqlQuery("SELECT * FROM MenuGroup ")
sgroups=groupquery.fetch(None,0)
groups = sorted(sgroups, reverse=True , key=lambda sgroups : sgroups.store_name)
self.render('viewmenu.html', username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename,groups=groups)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
def post(self):
search = self.request.get('search')
if not search:
self.redirect('/viewmenu')
else:
store_name=search.split(',')[0]
menu_group_name =search.split(',')[1]
menuquery = db.GqlQuery("SELECT * FROM Menu WHERE store_name=:store_name and menu_group_name=:menu_group_name ",store_name=store_name,menu_group_name=menu_group_name)
smenus=menuquery.fetch(None,0)
menus = sorted(smenus, reverse=True , key=lambda smenus : smenus.menu_name)
groupquery = db.GqlQuery("SELECT * FROM MenuGroup ")
sgroups=groupquery.fetch(None,0)
groups = sorted(sgroups, reverse=True , key=lambda sgroups : sgroups.store_name)
self.render('viewmenu.html', username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename,menus = menus , groups=groups)
class AddStore(Handler):
def get(self):
if self.user:
if not self.user.stop:
if self.user.admin:
self.render('addstore.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename)
else:
self.redirect('/notadmin')
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
def post(self):
store_name = self.request.get('store_name')
phone = self.request.get('phone')
if not store_name or not phone or len(store_name)>8:
msg = u"請重試一遍"
self.render('addstore.html', error=msg,username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename)
else:
u = Store.by_store_name(store_name)
if u:
msg = u'已有此商店'
self.render('addstore.html', error = msg ,username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename)
else:
u = Store.add_store(store_name , phone)
u.put()
self.redirect('/addstoresuccessful')
class AddStoreSuccessful(Handler):
def get(self):
if self.user :
if not self.user.stop:
if self.user.admin:
self.render('addstoresuccessful.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename)
else:
self.redirect('/notadmin')
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
class ViewStore(Handler):
def get(self):
if self.user :
if not self.user.stop:
query=Store.all()
stores=query.fetch(None,0)
self.render('viewstore.html', username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename,stores = stores)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
def valid_year(year):
if year == 2014 or year == 2015:
return False
else:
return True
def valid_month(month):
if month >=1 and month <= 12:
return False
else:
return True
def valid_day(day):
if day >=1 and day <=31:
return False
else:
return True
def valid_hour(hour):
if hour >= 0 and hour <= 23:
return False
else:
return True
def valid_minute(minute):
if minute >=0 and minute <=59:
return False
else:
return True
class CreateOrder(Handler):
def get(self):
if self.user :
if not self.user.stop:
storequery=Store.all()
stores=storequery.fetch(None,0)
current_year = datetime.date.today().strftime("%Y")
current_month = datetime.date.today().strftime("%m")
current_day = datetime.date.today().strftime("%d")
sorder_name = "" + current_year + (current_month if current_month>=10 else "0"+current_month)+(current_day if current_day>=10 else "0"+current_day)
self.render('createorder.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename , order_name = sorder_name , stores = stores,order_name_len=order_name_len,current_year=current_year,current_month=current_month,current_day=current_day)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
def post(self):
sorder_name = self.request.get('order_name')
sdeadline_year = self.request.get('deadline_year')
sdeadline_month = self.request.get('deadline_month')
sdeadline_day = self.request.get('deadline_day')
sdeadline_hour = self.request.get('deadline_hour')
sdeadline_minute = self.request.get('deadline_minute')
store_name = self.request.get('store_name')
isopen = True
have_error = False
current_year = datetime.date.today().strftime("%Y")
current_month = datetime.date.today().strftime("%m")
current_day = datetime.date.today().strftime("%d")
if not sorder_name.isdigit() or not sdeadline_year.isdigit() or not sdeadline_month.isdigit() or not sdeadline_day.isdigit() or not sdeadline_hour.isdigit() or not sdeadline_minute.isdigit():
storequery=Store.all()
stores=storequery.fetch(None,0)
msg = u"請重試一遍"
self.render('createorder.html', error=msg,username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename, order_name = sorder_name ,stores=stores,order_name_len=order_name_len,current_year=current_year,current_month=current_month,current_day=current_day)
have_error = True
if not have_error:
deadline_year = int(sdeadline_year)
deadline_month = int(sdeadline_month)
deadline_day = int(sdeadline_day)
deadline_hour = int(sdeadline_hour)
deadline_minute = int(sdeadline_minute)
if len(sorder_name) != order_name_len or not store_name or not valid_year(sdeadline_year) or not valid_month(sdeadline_month) or not valid_day(sdeadline_day) or not valid_hour(sdeadline_hour) or not valid_minute(sdeadline_minute):
storequery=Store.all()
stores=storequery.fetch(None,0)
msg = u"請重試一遍"
self.render('createorder.html', error=msg,username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename,order_name = sorder_name ,stores=stores,order_name_len=order_name_len,current_year=current_year,current_month=current_month,current_day=current_day)
else:
order_name = int(sorder_name)
u = Order.by_order_name(order_name , self.user.name)
if u:
storequery=Store.all()
stores=storequery.fetch(None,0)
msg = u'已有此訂單'
self.render('createorder.html', error = msg ,username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename,order_name = sorder_name ,stores=stores,order_name_len=order_name_len,current_year=current_year,current_month=current_month,current_day=current_day)
else:
u = Order.create_order(order_name , deadline_year , deadline_month,deadline_day,deadline_hour,deadline_minute,self.user.name,store_name,isopen)
u.put()
self.redirect('/createordersuccessful')
class CreateOrderSuccessful(Handler):
def get(self):
if self.user :
if not self.user.stop:
self.render('createordersuccessful.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
class ViewOrder(Handler):
def get(self):
if self.user :
if not self.user.stop:
orderquery=Order.all()
sorders=orderquery.fetch(None,0)
orders = sorted(sorders, reverse=True , key=lambda sorders : sorders.order_name)
self.render('vieworder.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename,orders=orders)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
class ChooseOrderDrink(Handler):
def get(self):
if self.user :
if not self.user.stop:
orderquery=Order.all()
sorders=orderquery.fetch(None,0)
orders = sorted(sorders, reverse=True , key=lambda sorders : sorders.order_name)
self.render('chooseorderdrink.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename,orders = orders)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
def post(self):
order = self.request.get('order')
if not order:
self.redirect('/chooseorderdrink')
else:
order_name = order.split(',')[0]
create_user = order.split(',')[1]
if order_name :
self.redirect('/choosemenugroup?order=%s&create_user=%s' %(order_name,create_user))
else:
self.redirect('/chooseorderdrink')
class ChooseMenuGroup(Handler):
def get(self):
if self.user :
if not self.user.stop:
sorder_name = self.request.get('order')
create_user = self.request.get('create_user')
if not sorder_name.isdigit() or not create_user:
self.redirect('/chooseorderdrink')
else:
order_name = int(sorder_name)
orderquery = db.GqlQuery("SELECT * FROM Order WHERE order_name = :order_name " ,order_name = order_name)
sorders=orderquery.fetch(None,0)
if not sorders:
self.redirect('/chooseorderdrink')
else:
store_name = sorders[0].store_name
menugroupquery=db.GqlQuery("SELECT * FROM MenuGroup WHERE store_name = :store_name" , store_name = store_name)
menu_groups=menugroupquery.fetch(None,0)
self.render('choosemenugroup.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename,order_name = order_name ,create_user = create_user,store_name = store_name,menu_groups = menu_groups)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
def post(self):
order_name = self.request.get('order_name')
create_user = self.request.get('create_user')
menu_group_no = self.request.get('menu_group_no')
if not order_name or not create_user or not menu_group_no:
self.redirect('/chooseorderdrink')
else:
self.redirect('/orderdrink?order_name=%s&create_user=%s&menu_group_no=%s' %(order_name,create_user,menu_group_no))
class OrderDrink(Handler):
def get(self):
if self.user :
if not self.user.stop:
sorder_name = self.request.get('order_name')
create_user = self.request.get('create_user')
menu_group_no = self.request.get('menu_group_no')
if not sorder_name.isdigit() and not create_user or not menu_group_no:
self.redirect('/chooseorderdrink')
else:
order_name = int(sorder_name)
orderquery = db.GqlQuery("SELECT * FROM Order WHERE order_name = :order_name " ,order_name = order_name)
sorders=orderquery.fetch(None,0)
menu_groupquery = db.GqlQuery("SELECT * FROM MenuGroup WHERE menu_group_no = :menu_group_no " ,menu_group_no=menu_group_no)
menu_groups=menu_groupquery.fetch(None,0)
if not sorders or not menu_groups:
self.redirect('/chooseorderdrink')
else:
menu_group_name = menu_groups[0].menu_group_name
store_name = menu_groups[0].store_name
menuquery = db.GqlQuery("SELECT * FROM Menu WHERE store_name = :store_name and menu_group_name = :menu_group_name " ,store_name = store_name,menu_group_name=menu_group_name)
smenus=menuquery.fetch(None,0)
menus = sorted(smenus, reverse=True , key=lambda smenus : smenus.menu_name)
self.render('orderdrink.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename,order_name=order_name,store_name = store_name,create_user = create_user,menus = menus)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
def post(self):
sorder_name = self.request.get("order_name")
store_name = self.request.get("store_name")
order_drink = self.request.get("order_drink")
sorder_num = self.request.get("drink_num")
create_user = self.request.get("create_user")
hot_cold = self.request.get('hot_cold')
ice = self.request.get('ice')
sugar = self.request.get('sugar')
order_paid = False
have_error = False
if not sorder_num.isdigit() or not sorder_name.isdigit() or not store_name or not order_drink or not create_user or not hot_cold or not ice or not sugar:
self.redirect('/chooseorderdrink')
else:
if hot_cold!=u'冷' and hot_cold != u'熱':
self.redirect('/chooseorderdrink')
elif ice != u'正常' and ice !=u'少冰'and ice!=u'去冰':
self.redirect('/chooseorderdrink')
elif sugar != u'正常' and sugar !=u'少糖'and sugar!=u'無糖':
self.redirect('/chooseorderdrink')
else:
order_name = int(sorder_name)
orderquery = db.GqlQuery("SELECT * FROM Order WHERE order_name = :order_name and store_name = :store_name and create_user = :create_user " ,order_name = order_name , store_name = store_name,create_user = create_user)
orders=orderquery.fetch(None,0)
if not orders:
self.redirect('/chooseorderdrink')
else:
sdrink_price = order_drink.split(',')[1]
drink_name = order_drink.split(',')[0]
drink_price = int(sdrink_price)
order_num = int(sorder_num)
if order_num >= 4 or order_num < 1:
self.redirect('/chooseorderdrink')
else:
u = PersonalOrder.by_personalorder_name(order_name ,store_name,create_user , self.user.name,drink_name)
if u:
msg = u'已有此訂單'
menuquery = db.GqlQuery("SELECT * FROM Menu WHERE store_name = :store_name " ,store_name = store_name)
menus=menuquery.fetch(None,0)
self.render('orderdrink.html', error = msg ,username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename,order_name = order_name,store_name = store_name,create_user = create_user,menus = menus )
else:
total = drink_price * order_num
u = PersonalOrder.order_drink(self.user.name,self.user.chinesename,order_name,store_name,create_user,drink_name,drink_price,hot_cold,ice,sugar,order_num,total,order_paid)
u.put()
self.redirect('/orderdrinksuccessful')
class OrderDrinkSuccessful(Handler):
def get(self):
if self.user :
if not self.user.stop:
self.render('orderdrinksuccessful.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
class ManageOrder(Handler):
def get(self):
if self.user :
if not self.user.stop:
orderquery = db.GqlQuery("SELECT * FROM Order WHERE create_user = :username " ,username = self.user.name)
sorders=orderquery.fetch(None,0)
orders = sorted(sorders, reverse=True , key=lambda sorders : sorders.order_name)
self.render('manageorder.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename , orders = orders)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
def post(self):
orderquery = db.GqlQuery("SELECT * FROM Order WHERE create_user = :username " ,username = self.user.name)
sorders=orderquery.fetch(None,0)
orders = sorted(sorders, reverse=True , key=lambda sorders : sorders.order_name)
isopen = False
for order in orders:
order_name = str(order.order_name) + "isopen"
changeisopen = self.request.get(order_name)
if changeisopen == 'False' and order.isopen:
q = db.GqlQuery("SELECT * FROM Order WHERE order_name = :order_name and create_user = :username " ,order_name = order.order_name ,username = self.user.name )
results = q.fetch(10)
db.delete(results)
u = Order.create_order(order.order_name , order.deadline_year , order.deadline_month,order.deadline_day,order.deadline_hour,order.deadline_minute,self.user.name,order.store_name,isopen)
u.put()
self.redirect('/manageordersuccessful')
class ManageOrderSuccessful(Handler):
def get(self):
if self.user :
if not self.user.stop:
self.render('manageordersuccessful.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
class AccountOrder(Handler):
def get(self):
if self.user :
if not self.user.stop:
sorder_name = self.request.get('search')
if sorder_name.isdigit():
order_name = int(sorder_name)
haveorderquery = db.GqlQuery("SELECT * FROM Order WHERE order_name = :order_name " ,order_name = order_name)
haveorders=haveorderquery.fetch(None,0)
if not haveorders:
self.redirect('/')
else:
creatusername = haveorders[0].create_user
store_name = haveorders[0].store_name
orderquery = db.GqlQuery("SELECT * FROM PersonalOrder WHERE create_user = :username and order_name = :order_name " ,username = creatusername , order_name = order_name)
sperorders=orderquery.fetch(None,0)
perorders = sorted(sperorders, reverse=False , key=lambda sperorders : sperorders.order_user)
count_order_name = []
count_order_num = []
find = 0
all_total = 0
for perorder in perorders:
if perorder.hot_cold+' '+perorder.drink_name+' '+perorder.ice+' '+perorder.sugar not in count_order_name:
count_order_name.append(perorder.hot_cold+' '+perorder.drink_name+' '+perorder.ice+' '+perorder.sugar)
count_order_num.append(perorder.order_num)
elif perorder.hot_cold+' '+perorder.drink_name+' '+perorder.ice+' '+perorder.sugar in count_order_name:
find = count_order_name.index(perorder.hot_cold+' '+perorder.drink_name+' '+perorder.ice+' '+perorder.sugar)
count_order_num[find] += perorder.order_num
all_total += perorder.total
self.render('accountorder.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename,store_name = store_name,creatusername = creatusername,perorders = perorders , sorder_name = sorder_name , count_order_name = count_order_name , count_order_num = count_order_num , all_total = all_total)
else:
self.redirect('/')
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
def post(self):
sorder_name = self.request.get('search')
if sorder_name.isdigit():
order_name = int(sorder_name)
haveorderquery = db.GqlQuery("SELECT * FROM Order WHERE create_user = :username and order_name = :order_name " ,username = self.user.name , order_name = order_name)
haveorders=haveorderquery.fetch(None,0)
if not haveorders:
self.redirect('/notadmin')
else:
orderquery = db.GqlQuery("SELECT * FROM PersonalOrder WHERE create_user = :username and order_name = :order_name " ,username = self.user.name , order_name = order_name)
perorders=orderquery.fetch(None,0)
order_paid = True
for perorder in perorders:
perorder_name = perorder.drink_name + ',' + perorder.order_user+'order_paid'
change_order_paid = self.request.get(perorder_name)
if change_order_paid == 'True' and not perorder.order_paid:
q = db.GqlQuery("SELECT * FROM PersonalOrder WHERE create_user = :username and order_name = :order_name and order_user = :order_user and drink_name = :drink_name " ,username = self.user.name , order_name = order_name , order_user = perorder.order_user , drink_name = perorder.drink_name)
results = q.fetch(10)
db.delete(results)
u = PersonalOrder.order_drink(perorder.order_user,perorder.order_user_chinesename,perorder.order_name,perorder.store_name,perorder.create_user,perorder.drink_name,perorder.drink_price,perorder.hot_cold,perorder.ice,perorder.sugar,perorder.order_num,perorder.total,order_paid)
u.put()
self.redirect('/accountordersuccessful?search=%s' %order_name)
class AccountOrderSuccessful(Handler):
def get(self):
if self.user :
if not self.user.stop:
order_name = self.request.get('search')
self.render('accountordersuccessful.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename ,order_name = order_name)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
class About(Handler):
def get(self):
if self.user :
if not self.user.stop:
self.render('about.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
class SiteMap(Handler):
def get(self):
if self.user :
if not self.user.stop:
self.render('sitemap.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
class AddMenuGroup(Handler):
def get(self):
if self.user :
if not self.user.stop:
if self.user.admin:
storequery = db.GqlQuery("SELECT * FROM Store")
stores=storequery.fetch(None,0)
self.render('addmenugroup.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename ,stores=stores)
else:
self.redirect('/notadmin')
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
def post(self):
store_name = self.request.get('store_name')
storequery = db.GqlQuery("SELECT * FROM Store WHERE store_name=:store_name",store_name = store_name)
stores=storequery.fetch(None,0)
menu_group_name = self.request.get('menu_group_name')
if not stores or not menu_group_name or len(menu_group_name)>15:
storequery = db.GqlQuery("SELECT * FROM Store")
stores=storequery.fetch(None,0)
msg = u"請重試一遍"
self.render('addmenugroup.html', error=msg,username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename,stores=stores)
else:
u = MenuGroup.by_menu_group_name(store_name,menu_group_name)
if u:
storequery = db.GqlQuery("SELECT * FROM Store")
stores=storequery.fetch(None,0)
msg = u'已有此群組'
self.render('addmenugroup.html', error = msg ,username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename,stores=stores)
else:
menu_group_no = strftime(r'%Y%m%d%H%M%S')
u = MenuGroup.add_menu_group(store_name , menu_group_name , menu_group_no)
u.put()
self.redirect('/addmenugroupsuccessful')
class AddMenuGroupSuccessful(Handler):
def get(self):
if self.user :
if not self.user.stop:
self.render('addmenugroupsuccessful.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
class ViewMenuGroup(Handler):
def get(self):
if self.user :
if not self.user.stop:
menugroupquery=db.GqlQuery("SELECT * FROM MenuGroup")
smenugroups=menugroupquery.fetch(None,0)
menu_groups = sorted(smenugroups, reverse=True , key=lambda smenugroups : smenugroups.store_name)
self.render('viewmenugroup.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename,menu_groups = menu_groups)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
class Stop(Handler):
def get(self):
if self.user :
if self.user.stop:
self.render('stop.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename,stop_admin=self.user.stop_admin)
else:
self.redirect('/')
class AccountUser(Handler):
def get(self):
if self.user :
if not self.user.stop:
if self.user.admin:
userquery = db.GqlQuery("SELECT * FROM User ")
users=userquery.fetch(None,0)
self.render('accountuser.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename,users=users)
else:
self.redirect('/notadmin')
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
def post(self):
userquery=db.GqlQuery("SELECT * FROM User")
users=userquery.fetch(None,0)
for user in users:
change = self.request.get(user.name+',stop')
if not user.stop and change =='True':
userquery = db.GqlQuery("SELECT * FROM User WHERE name = :username",username = user.name)
results = userquery.fetch(10)
db.delete(results)
u = User.changeregister(user.name,user.pw_hash,user.chinesename,user.admin,True,self.user.name)
u.put()
elif user.stop and not change:
userquery = db.GqlQuery("SELECT * FROM User WHERE name = :username",username = user.name)
results = userquery.fetch(10)
db.delete(results)
u = User.changeregister(user.name,user.pw_hash,user.chinesename,user.admin,False,' ')
u.put()
self.redirect('/accountusersuccessful')
class AccountUserSuccessful(Handler):
def get(self):
if self.user :
if not self.user.stop:
if self.user.admin:
self.render('accountusersuccessful.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename)
else:
self.redirect('/notadmin')
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
class MyDrink(Handler):
def get(self):
if self.user :
if not self.user.stop:
drinkquery=db.GqlQuery("SELECT * FROM PersonalOrder WHERE order_user=:username",username = self.user.name)
sdrinks=drinkquery.fetch(None,0)
drinks = sorted(sdrinks, reverse=True , key=lambda sdrinks : sdrinks.order_name)
self.render('mydrink.html',username = self.user.name , admin = self.user.admin,chinesename = self.user.chinesename,drinks = drinks)
elif self.user.stop:
self.redirect('/stop')
else:
self.redirect('/')
app = webapp2.WSGIApplication([('/', MainPage),
('/login',Login),
('/welcome', Welcome),
('/signup',Register),
('/changepassword',ChangePassword),
('/changepasswordsuccessful',ChangePasswordSuccessful),
('/logout',Logout),
('/notadmin',NotAdmin),
('/addmenu',AddMenu),
('/addmenusuccessful',AddMenuSuccessful),
('/viewmenu',ViewMenu),
('/addstore',AddStore),
('/addstoresuccessful',AddStoreSuccessful),
('/viewstore',ViewStore),
('/createorder',CreateOrder),
('/createordersuccessful',CreateOrderSuccessful),
('/vieworder',ViewOrder),
('/chooseorderdrink',ChooseOrderDrink),
('/choosemenugroup',ChooseMenuGroup),
('/orderdrink',OrderDrink),
('/orderdrinksuccessful',OrderDrinkSuccessful),
('/manageorder',ManageOrder),
('/manageordersuccessful',ManageOrderSuccessful),
('/accountorder',AccountOrder),
('/accountordersuccessful' , AccountOrderSuccessful),
('/about' , About),
('/addmenugroup' , AddMenuGroup),
('/addmenugroupsuccessful',AddMenuGroupSuccessful),
('/viewmenugroup' , ViewMenuGroup),
('/stop',Stop),
('/accountuser',AccountUser),
('/accountusersuccessful',AccountUserSuccessful),
('/mydrink',MyDrink)
],
debug=debug) | WillyChen123/drinkorder | main.py | main.py | py | 42,562 | python | en | code | 0 | github-code | 13 |
13726588524 | import numpy as np
import torch
import pandas as pd
import atom_features
import molecule_features
import edge_features
import torch.utils.data
import util
from atom_features import to_onehot
class MoleculeDatasetMulti(torch.utils.data.Dataset):
def __init__(self, mols, pred_vals, whole_records,
MAX_N,
PRED_N = 1,
feat_vert_args = {},
feat_edge_args = {},
adj_args = {},
mol_args = {},
combine_mat_vect = None,
combine_mat_feat_adj = False,
combine_mol_vect = False,
extra_npy_filenames = [],
frac_per_epoch = 1.0,
shuffle_observations = False,
spect_assign = True,
extra_features = None,
allow_cache = True,
):
self.mols = mols
self.pred_vals = pred_vals
self.whole_records = whole_records
self.MAX_N = MAX_N
if allow_cache:
self.cache = {}
else:
self.cache = None
self.feat_vert_args = feat_vert_args
self.feat_edge_args = feat_edge_args
self.adj_args = adj_args
self.mol_args = mol_args
#self.single_value = single_value
self.combine_mat_vect = combine_mat_vect
self.combine_mat_feat_adj = combine_mat_feat_adj
self.combine_mol_vect = combine_mol_vect
#self.mask_zeroout_prob = mask_zeroout_prob
self.PRED_N = PRED_N
self.extra_npy_filenames = extra_npy_filenames
self.frac_per_epoch = frac_per_epoch
self.shuffle_observations = shuffle_observations
if shuffle_observations:
print("WARNING: Shuffling observations")
self.spect_assign = spect_assign
self.extra_features = extra_features
def __len__(self):
return int(len(self.mols) * self.frac_per_epoch)
def cache_key(self, idx, conf_idx):
return (idx, conf_idx)
def __getitem__(self, idx):
if self.frac_per_epoch < 1.0:
# randomly get an index each time
idx = np.random.randint(len(self.mols))
mol = self.mols[idx]
pred_val = self.pred_vals[idx]
whole_record = self.whole_records[idx]
conf_idx = 0
if self.cache is not None and self.cache_key(idx, conf_idx) in self.cache:
return self.cache[self.cache_key(idx, conf_idx)]
# mol features
f_mol = molecule_features.whole_molecule_features(whole_record,
**self.mol_args)
f_vect = atom_features.feat_tensor_atom(mol, conf_idx=conf_idx,
**self.feat_vert_args)
if self.combine_mol_vect:
f_vect = torch.cat([f_vect, f_mol.reshape(1, -1).expand(f_vect.shape[0], -1)], -1)
# process extra data arguments
for extra_data_config in self.extra_npy_filenames:
filename = extra_data_config['filenames'][idx]
combine_with = extra_data_config.get('combine_with', None)
if combine_with == 'vert':
npy_data = np.load(filename)
npy_data_flatter = npy_data.reshape(f_vect.shape[0], -1)
f_vect = torch.cat([f_vect, torch.Tensor(npy_data_flatter)], dim=-1)
elif combine_with is None:
continue
else:
raise NotImplementedError(f"the combinewith {combine_with} not working yet")
DATA_N = f_vect.shape[0]
vect_feat = np.zeros((self.MAX_N, f_vect.shape[1]), dtype=np.float32)
vect_feat[:DATA_N] = f_vect
f_mat = molecule_features.feat_tensor_mol(mol, conf_idx=conf_idx,
**self.feat_edge_args)
if self.combine_mat_vect:
MAT_CHAN = f_mat.shape[2] + vect_feat.shape[1]
else:
MAT_CHAN = f_mat.shape[2]
if MAT_CHAN == 0: # Dataloader can't handle tensors with empty dimensions
MAT_CHAN = 1
mat_feat = np.zeros((self.MAX_N, self.MAX_N, MAT_CHAN), dtype=np.float32)
# do the padding
mat_feat[:DATA_N, :DATA_N, :f_mat.shape[2]] = f_mat
if self.combine_mat_vect == 'row':
# row-major
for i in range(DATA_N):
mat_feat[i, :DATA_N, f_mat.shape[2]:] = f_vect
elif self.combine_mat_vect == 'col':
# col-major
for i in range(DATA_N):
mat_feat[:DATA_N, i, f_mat.shape[2]:] = f_vect
adj_nopad = molecule_features.feat_mol_adj(mol, **self.adj_args)
adj = torch.zeros((adj_nopad.shape[0], self.MAX_N, self.MAX_N))
adj[:, :adj_nopad.shape[1], :adj_nopad.shape[2]] = adj_nopad
if self.combine_mat_feat_adj:
adj = torch.cat([adj, torch.Tensor(mat_feat).permute(2, 0, 1)], 0)
### Simple one-hot encoding for reconstruction
adj_oh_nopad = molecule_features.feat_mol_adj(mol, split_weights=[1.0, 1.5, 2.0, 3.0],
edge_weighted=False, norm_adj=False, add_identity=False)
adj_oh = torch.zeros((adj_oh_nopad.shape[0], self.MAX_N, self.MAX_N))
adj_oh[:, :adj_oh_nopad.shape[1], :adj_oh_nopad.shape[2]] = adj_oh_nopad
## per-edge features
feat_edge_dict = edge_features.feat_edges(mol, )
# pad each of these
edge_edge_nopad = feat_edge_dict['edge_edge']
edge_edge = torch.zeros((edge_edge_nopad.shape[0], self.MAX_N, self.MAX_N))
# edge_edge[:, :edge_edge_nopad.shape[1],
# :edge_edge_nopad.shape[2]] = torch.Tensor(edge_edge_nopad)
edge_feat_nopad = feat_edge_dict['edge_feat']
edge_feat = torch.zeros((self.MAX_N, edge_feat_nopad.shape[1]))
# edge_feat[:edge_feat_nopad.shape[0]] = torch.Tensor(edge_feat_nopad)
edge_vert_nopad = feat_edge_dict['edge_vert']
edge_vert = torch.zeros((edge_vert_nopad.shape[0], self.MAX_N, self.MAX_N))
# edge_vert[:, :edge_vert_nopad.shape[1],
# :edge_vert_nopad.shape[2]] = torch.Tensor(edge_vert_nopad)
atomicnos, coords = util.get_nos_coords(mol, conf_idx)
coords_t = torch.zeros((self.MAX_N, 3))
coords_t[:len(coords), :] = torch.Tensor(coords)
# create mask and preds
pred_mask = np.zeros((self.MAX_N, self.PRED_N),
dtype=np.float32)
vals = np.ones((self.MAX_N, self.PRED_N),
dtype=np.float32) * util.PERM_MISSING_VALUE
#print(self.PRED_N, pred_val)
if self.spect_assign:
for pn in range(self.PRED_N):
if len(pred_val) > 0: # when empty, there's nothing to predict
atom_idx = [int(k) for k in pred_val[pn].keys()]
obs_vals = [pred_val[pn][i] for i in atom_idx]
# if self.shuffle_observations:
# obs_vals = np.random.permutation(obs_vals)
for k, v in zip(atom_idx, obs_vals):
pred_mask[k, pn] = 1.0
vals[k, pn] = v
else:
if self.PRED_N > 1:
raise NotImplementedError()
vals[:] = util.PERM_MISSING_VALUE # sentinel value
for k in pred_val[0][0]:
pred_mask[k, 0] = 1
for vi, v in enumerate(pred_val[0][1]):
vals[vi] = v
# input mask
input_mask = torch.zeros(self.MAX_N)
input_mask[:DATA_N] = 1.0
v = {'adj' : adj, 'vect_feat' : vect_feat,
'mat_feat' : mat_feat,
'mol_feat' : f_mol,
'vals' : vals,
'adj_oh' : adj_oh,
'pred_mask' : pred_mask,
'coords' : coords_t,
'input_mask' : input_mask,
'input_idx' : idx,
'edge_edge' : edge_edge,
'edge_vert' : edge_vert,
'edge_feat' : edge_feat}
## add on extra args
for ei, extra_data_config in enumerate(self.extra_npy_filenames):
filename = extra_data_config['filenames'][idx]
combine_with = extra_data_config.get('combine_with', None)
if combine_with is None:
## this is an extra arg
npy_data = np.load(filename)
## Zero pad
npy_shape = list(npy_data.shape)
npy_shape[0] = self.MAX_N
t_pad = torch.zeros(npy_shape)
t_pad[:npy_data.shape[0]] = torch.Tensor(npy_data)
v[f'extra_data_{ei}'] = t_pad
for k, kv in v.items():
assert np.isfinite(kv).all()
if self.cache is not None:
self.cache[self.cache_key(idx, conf_idx)] = v
return v
| stefhk3/nmrfilter | respredict/netdataio.py | netdataio.py | py | 9,071 | python | en | code | 1 | github-code | 13 |
35210660984 | # Uses python3
import sys
def get_max(a, b):
ab = a + b
ba = b + a
if int(ab) >= int(ba):
return a
elif int(ba) >= int(ab):
return b
def largest_number(a):
max_lis = []
l = len(a)
while len(max_lis) < l:
max = str(a[0])
for i in a:
max = get_max(i, max)
max_lis.append(max)
a.remove(max)
return int(''.join(max_lis))
if __name__ == '__main__':
input = sys.stdin.read()
data = input.split()
a = data[1:]
print(largest_number(a))
| vinaykudari/data-structures-and-algorithms | algorithmic-toolbox/week3_greedy_algorithms/7_maximum_salary/largest_number.py | largest_number.py | py | 543 | python | en | code | 0 | github-code | 13 |
27882971950 | #!/usr/bin/env python
# coding: utf-8
import pandas as pd
import numpy as np
import gc
import networkx as nx
import time
import pickle
import os
from sklearn.preprocessing import LabelEncoder
import seaborn as sns
import deepwalk as dw
pd.set_option('display.max_rows',1000)
pd.set_option('display.max_columns',100)
sns.set(style = 'white', context = 'notebook', palette = 'deep')
sns.set_style('white')
path1 = './data-firstround'
path2 = './data-secondround'
train_oper = pd.read_csv(path1 + '/operation_train_new.csv')
train_transac = pd.read_csv(path1 + '/transaction_train_new.csv')
test_oper_r1 = pd.read_csv(path1 + '/operation_round1_new.csv')
test_transac_r1 = pd.read_csv(path1 + '/transaction_round1_new.csv')
test_oper_r2 = pd.read_csv(path2 + '/test_operation_round2.csv')
test_transac_r2 = pd.read_csv(path2 + '/test_transaction_round2.csv')
oper_tran_grpuse_col = ['UID',"device1","mac1","ip1", "device_code1","device_code2","device_code3"]
oper_col = [ 'UID','ip','ip_sub','wifi']
tran_col = ['UID', 'merchant','acc_id1','acc_id2','acc_id3']
oper_tran_grpuse = pd.concat([ train_oper[oper_tran_grpuse_col],test_oper_r1[oper_tran_grpuse_col] , test_oper_r2[oper_tran_grpuse_col], train_transac[oper_tran_grpuse_col],test_transac_r1[oper_tran_grpuse_col],test_transac_r2[oper_tran_grpuse_col]])
oper_tran_grpuse['device_code']=oper_tran_grpuse['device_code1'].fillna(oper_tran_grpuse['device_code2'])
oper_tran_grpuse['device_code']=oper_tran_grpuse['device_code2'].fillna(oper_tran_grpuse['device_code3'])
train_oper['ip'] = train_oper['ip1'].fillna( train_oper['ip2'])
test_oper_r1['ip'] = test_oper_r1['ip1'].fillna( test_oper_r1['ip2'])
test_oper_r2['ip'] = test_oper_r2['ip1'].fillna( test_oper_r2['ip2'])
train_oper['ip_sub'] = train_oper['ip1_sub'].fillna( train_oper['ip2_sub'])
test_oper_r1['ip_sub'] = test_oper_r1['ip1_sub'].fillna( test_oper_r1['ip2_sub'])
test_oper_r2['ip_sub'] = test_oper_r2['ip1_sub'].fillna( test_oper_r2['ip2_sub'])
oper_use = pd.concat([ train_oper,test_oper_r1,test_oper_r2 ])
tran_use = pd.concat([ train_transac,test_transac_r1,test_transac_r2 ])
path3 = './edges/source/'
sourcedata = [{"usedata":oper_tran_grpuse,"useCol":oper_tran_grpuse_col},
{"usedata":oper_use,"useCol":oper_col},
{"usedata":tran_use,"useCol":tran_col}
]
def create_edgelist(useData, secNodeCol,col):
le = LabelEncoder()
datacp = useData[[col,secNodeCol]]
datacp = datacp[-datacp[secNodeCol].isnull()]
datacp = datacp[-datacp[col].isnull()]
datacp[secNodeCol] = le.fit_transform(datacp[secNodeCol])+ 1000000
each =datacp.groupby([col,secNodeCol])[col].agg({"trans_cnt":'count'}).reset_index()
total = each.groupby(secNodeCol)["trans_cnt"].agg({ 'trans_cnt_total' :"sum"}).reset_index()
gp = pd.merge(each,total,on=[secNodeCol])
del datacp,each,total
gp[ "ratio"] = gp['trans_cnt']/gp['trans_cnt_total']
gp = gp.drop(['trans_cnt','trans_cnt_total'],axis = 1)
savename = path3 +'{}_weighted_edglist_filytypeTxt.txt'.format(secNodeCol)
np.savetxt(savename, gp.values, fmt=['%d','%d','%f'])
gp = gp.drop("ratio",axis = 1)
savenameForDeepWalk = path3 + '{}_weighted_edglist_DeepWalk.txt'.format(secNodeCol)
np.savetxt(savenameForDeepWalk, gp.values, fmt=['%d','%d'])
del gp
# 一度关联
for spec in sourcedata:
for c in spec["useCol"]:
if c != "UID":
create_edgelist(spec["usedata"], c, 'UID','')
gc.collect()
def create_edgelist2(useData, secNodeCol,col,degreename):
le = LabelEncoder()
datacp = useData[['UID',col,secNodeCol]]
datacp = datacp[-datacp[secNodeCol].isnull()]
datacp = datacp[-datacp[col].isnull()]
datacp[secNodeCol] = le.fit_transform(datacp[secNodeCol])+ 1000000
datacp[col] = le.fit_transform(datacp[col])+ 10000000
each =datacp.groupby(['UID',col,secNodeCol])[col].agg({"trans_cnt":'count'}).reset_index()
total = each.groupby(secNodeCol)["trans_cnt"].agg({ 'trans_cnt_total' :"sum"}).reset_index()
gp = pd.merge(each,total,on=[secNodeCol])
del datacp,each,total
gp[ "ratio"] = gp['trans_cnt']/gp['trans_cnt_total']
temp=gp.groupby(col)['trans_cnt'].agg({'cnt2':'sum'}).reset_index()
gp = gp.merge(temp,on=[col],how='left')
gp['ratio2'] = gp['trans_cnt']/gp['cnt2']
gp = gp.drop(['trans_cnt','trans_cnt_total','cnt2'],axis = 1)
savename = path4 + degreename+ '{}_{}_weighted_edglist_filytypeTxt.txt'.format(secNodeCol,col)
np.savetxt(savename, gp.values, fmt=['%d','%d','%d','%f','%f'])
del gp
path4='./edges/2度关联/'
#二度关联
for x in ['acc_id2','acc_id3']:
create_edgelist2(tran_use, x, 'acc_id1','2degree')
for x in ['ip1','device_code','device1']:
create_edgelist2(oper_tran_grpuse, x, 'mac1','2degree')
def createEdgeFomat(fname):
G = nx.Graph()
f = open(fname,'r')
lines = f.readlines()
f.close()
lines =[line.replace("\n","").split(" ") for line in lines]
lines = [[int(x[0]),int(x[1]),float(x[2])] for x in lines]
edfname = fname.replace(".txt",".edgelist")
for edg in lines:
G.add_edge(edg[0], edg[1], weight=edg[2])
print("\n-------------------------------------\n")
print("saving fali name %s " % edfname)
print("\n-------------------------------------\n")
fh=open(edfname,'wb')
nx.write_edgelist(G, fh)
fh.close()
for f in os.listdir(path3):
if "DeepWalk" not in f:
print("creating %s edge format for node2vec embedding ... " % (f.replace( "_edglist_filytypeTxt.txt", "" )) )
createEdgeFomat(path3 + f)
print(f.split(".")[0],"finish")
def createEdgeFomat2(fname):
G = nx.Graph()
with open(fname,'r') as ff:
lines = ff.readlines()
lines =[line.replace("\n","").split(" ") for line in lines]
lines = [[int(x[0]),int(x[1]),int(x[2]),float(x[3]),float(x[4])] for x in lines]
edfname = fname.replace(".txt",".edgelist")
for edg in lines:
G.add_edge(edg[0], edg[1], weight=edg[4])
G.add_edge(edg[1], edg[2], weight=edg[3])
print("\n-------------------------------------\n")
print("saving fali name %s " % edfname)
print("\n-------------------------------------\n")
with open(edfname,'wb') as fh:
nx.write_edgelist(G, fh)
path4='./edges/2度关联/'
for f in os.listdir(path4):
print("creating %s edge format for node2vec embedding ... " % (f.replace( "_edglist_filytypeTxt.txt", "" )) )
createEdgeFomat2(path4 + f)
print(f.split(".")[0],"finish")
####node2vec
import networkx as nx
from node2vec import Node2Vec
import sys
def emb_graph_2vec(inputpath,dim):
print("input name will be ",inputpath)
emb_name = inputpath.replace("weighted_edglist_filytypeTxt.edgelist","")
print("emb_name will be ",emb_name)
savename =inputpath.replace("weighted_edglist_filytypeTxt.edgelist",".emb")
print("emb outfile name will be ",savename)
if os.path.exists(savename):
print("file alread exists in cache, please rename")
sys.exit(1)
graph = nx.read_edgelist(inputpath,create_using=nx.DiGraph())
# Precompute probabilities and generate walks - **ON WINDOWS ONLY WORKS WITH workers=1**
node2vec = Node2Vec(graph, dimensions=dim, walk_length=30, num_walks=200, workers=10)
# Embed nodes
print("training .... ")
model = node2vec.fit(window=10, min_count=1, batch_words=4)
print("training finished saving result... ")
print("saving %s file to disk "%savename)
# Save embeddings for later use
model.wv.save_word2vec_format(savename)
print("done")
# Save model for later use
import os
dataRoot = './edges/source/'
inputpath = dataRoot + "mac1_weighted_edglist_filytypeTxt.edgelist"
try:
emb_graph_2vec(inputpath,36)
except Exception as e:
print(e)
dataRoot = './edges/source/'
inputpath = dataRoot + "merchant_weighted_edglist_filytypeTxt.edgelist"
try:
emb_graph_2vec(inputpath,64)
except Exception as e:
print(e)
dataRoot = './edges/source/'
inputpath = dataRoot + "acc_id1_weighted_edglist_filytypeTxt.edgelist"
try:
emb_graph_2vec(inputpath,36)
except Exception as e:
print(e)
dataRoot = './edges/2度关联/'
filenames=[
'2degreeacc_id2_acc_id1_weighted_edglist_filytypeTxt.edgelist',
'2degreeacc_id3_acc_id1_weighted_edglist_filytypeTxt.edgelist',
'2degreedevice_code_mac1_weighted_edglist_filytypeTxt.edgelist',
'2degreedevice1_mac1_weighted_edglist_filytypeTxt.edgelist',
'2degreeip1_mac1_weighted_edglist_filytypeTxt.edgelist'
]
for filename in filenames:
inputpath = dataRoot + filename
try:
emb_graph_2vec(inputpath,36)
except Exception as e:
print(e)
| Susanna333/black-industry-recognition-based-on-user-behavior | graph_embedding.py | graph_embedding.py | py | 8,756 | python | en | code | 2 | github-code | 13 |
8163299989 | """
File: Leaderboard.py
Authors: Spencer Wheeler, Benjamin Paul, Troy Scites
Description: Provides a get method to retrieve leaderboard data
"""
import sqlite3
from sqlite3 import Error
from flask_restful import Resource, reqparse
#using reqparse despite its depreciated status
class leaderboard(Resource):
"""
Class provides API method GET leaderboard postiions
"""
'''
Table:
Position | Username | Game Level | Game_time | Game_Mode
'''
def get(self, game_mode, top_number):
'''
Descritpion: Returns top runs up to the passed number, not to exceed 100
Params
---------
game_mode: Str, None return all game modes
top_number: int, None returns all positions
'''
if top_number is None:
top_number = 100
try:
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
table_name = "{mode}_leaderboard".format(mode = game_mode.lower())
query = '''SELECT * FROM {table} ORDER BY position ASC'''.format(table = table_name)
rows = cursor.execute(query).fetchmany(top_number)
cursor.close()
return rows
except Error:
connection.close()
return Error
| benp23/Spazzle-clone | Spazzle/leaderboard.py | leaderboard.py | py | 1,431 | python | en | code | 0 | github-code | 13 |
71166501139 | #spatial smoothing helper file
import numpy as np
from scipy.stats import expon
import matplotlib.pyplot as plt
def SmoothArray(array, window_size = 27):
sigma = 0.1
mu = 0.5
window_size = 27
kernel = np.exp(-(np.linspace(0,1,window_size,endpoint = True) - mu) **2 / (sigma**2*2))
convolution = np.convolve(array,kernel, 'same')
convolution /= max(abs(convolution))
return convolution
def FourierTransform(InputArray):
'''takes time signal as input and transforms it into power spectrum, to show at which frequency perceptual blocks oscilate'''
sp = np.fft.fft(np.array(InputArray))
freq = np.fft.fftfreq(np.array(InputArray).shape[-1])
spAbs = np.absolute(sp) **2
whichPlot = (freq > 0 )*(freq < 0.03)
return (freq[whichPlot],spAbs[whichPlot])
def CalculateStability(ResponseArray,TimeArray, cutoff = 0):
'''Input Responsearray should contain the smoothed responses for each condition per subject.
TimeArray introduced the time when each response was given.
Cutoff represents the value which has to be reached by the responses in order get counted as such. (Lost dichotomy by smoothing)
Returns for each condition a list containing the duration of each stabilized percept and a list with an index for the number of which perceptual block it belongs to
'''
bias_list = []
level = 0
resp = 0
start_percept = 0
percep_block_index = 0
prelevel = 0
for trial in xrange(len(ResponseArray)):
if trial == len(ResponseArray)-1:
level = 2
elif ResponseArray[trial] > cutoff:
level = 1
elif ResponseArray[trial]< (-1 * cutoff):
level = -1
if level != prelevel:
percep_block_index += 1
resp = TimeArray[trial] - start_percept
start_percept = TimeArray[trial]
bias_list.append(resp)
prelevel = level
return bias_list
def expConvolve(arrays, window_size=27):
'''
Convolve input array with 2 exponential functions and normalizes them
Returns two arrays: 1) with positive weights, 2) negative weights
'''
array1 = np.array(arrays > 0, dtype = int)
array2 = np.array(arrays < 0, dtype = int)
kernel = expon.pdf(np.linspace(0,3, window_size), scale = 0.5)
kernel /= kernel.sum()
convolution1 = np.convolve(array1,kernel, 'same')
convolution2 = np.convolve(array2,kernel, 'same')
return convolution1, convolution2
def posInPercept(responses, response_times):
'''
converts the percept.block index of a timepoint in a session into its relative position (begin,middle,end) of one percep.block
returns a list with 1,2,3,4s corresponding to begin (25%), 2x middle (50%), end(25%) of trials and corresponding response times
'''
pos = 0
start = [0]
stop =[]
quartile_session = []
dur_quartile = []
pos_in_block = []
quartile_index = 1
for i in xrange(len(responses)):
if pos*responses[i]< 0:
stop.append(response_times[i])
start.append(response_times[i])
if i == len(responses)-1:
stop.append(response_times[i])
if responses[i]>0:
pos = 1
elif responses[i]<0:
pos = -1
for switchi in xrange(len(start)):
dur_quartile.append((stop[switchi]-start[switchi])/4)
for quarti in xrange(len(dur_quartile)):
for i in xrange(1,5):
quartile_session.append(start[quarti]+i*dur_quartile[quarti])
for time in response_times:
if time > quartile_session[quartile_index-1]:
quartile_index += 1
pos_in_block.append([quartile_index%4, time])
return pos_in_block
| eort/AMPM | analUtils.py | analUtils.py | py | 3,882 | python | en | code | 0 | github-code | 13 |
27806355288 | from django.shortcuts import render,redirect
from .models import User, Friend
from django.http import JsonResponse
# Create your views here.
def index(request):
user = User.objects.all().exclude(id = request.session['user_id'])
friend = Friend.objects.filter(user_id = request.session['user_id'])
if friend:
req_frd = friend[0].requested_frd.split(',')
req_frd = list(map(int, req_frd))
list_of_suggestions = []
for person in user:
if person.id not in req_frd:
list_of_suggestions.append(person)
return render(request, 'index.html', {'row': list_of_suggestions[::-1]})
else:
return render(request, 'index.html', {'row': user})
def viewRegister(request):
return render(request, 'register.html')
def register(request, image):
obj = User.objects.filter(email = request.POST['email'])
if obj:
return JsonResponse({'status': 1})
user = User()
user.name = request.POST['name']
user.email = request.POST['email']
user.password = request.POST['password']
user.image = image
user.save()
user = User.objects.get(email = request.POST['email'])
request.session['user_id'] = user.id
return JsonResponse({'status' : 0})
def loginPage(request):
return render(request, 'login.html', {'status': 0})
def checkLogin(request):
user = User.objects.filter(email = request.POST['email'])
if user:
if user[0].password == request.POST['pwd']:
request.session['user_id'] = user[0].id
return redirect("/index/")
else:
return render(request, 'login.html', {'status': 1})
else:
return redirect('/')
def editProfile(request, id):
obj = User.objects.get(id = id)
print(obj)
return render(request, 'editprofile.html', {'row':obj})
def profileUpdated(request, id):
user = User.objects.get(id = id)
user.name = request.POST['name']
user.email = request.POST['email']
user.save()
return redirect("/index/")
def sendRequest(request, id):
friend = Friend.objects.filter(user_id = id)
if friend:
reqfrd = friend[0].pending_frd.split(",")
requested_friends =list(map(int,reqfrd))
if request.session['user_id'] not in requested_friends:
friend[0].pending_frd += "," + str(request.session['user_id'])
friend[0].save()
else:
friend = Friend()
friend.user_id = id
friend.pending_frd = request.session['user_id']
friend.save()
friend = Friend.objects.filter(user_id = request.session['user_id'])
if friend:
reqfrd = friend[0].requested_frd.split(",")
requested_friends = list(map(int, reqfrd))
if id not in requested_friends:
friend[0].requested_frd += ',' + str(id)
friend[0].save()
else:
friend = Friend()
friend.user_id = request.session['user_id']
friend.requested_frd = id
friend.save()
return JsonResponse({'status': 'success'})
def showRequest(request):
friend = Friend.objects.filter(user_id = str(request.session['user_id']))
frd = friend[0].pending_frd
frd = frd.split(",")
print(frd)
return redirect("/index/")
def myProfile(request):
user = User.objects.get(id = request.session['user_id'])
print(user)
return render(request, 'myprofile.html', {'profile': user})
def pendingRequests(request):
friend = Friend.objects.filter(user_id = request.session['user_id'])
if friend:
reqfrd = friend[0].pending_frd.split(",")
requested_friends =list(map(int,reqfrd))
lst = []
for i in requested_friends:
user = User.objects.get(id = i)
lst.append(user)
return render(request, "reqfrd.html", {'reqfriend':lst})
def acceptRequest(request, id):
friend = Friend.objects.get(user_id = request.session['user_id'])
reqfrd = friend.pending_frd.split(",")
requested_friends = list(map(int, reqfrd))
if id in requested_friends:
requested_friends.remove(id)
friend.frd += str(id) + ','
requested_friends = list(map(str, requested_friends))
friend.pending_frd = ",".join(requested_friends)
friend.save()
return redirect("/index/")
def requestedFriends(request):
friend = Friend.objects.get(user_id = request.session['user_id'])
req_frd = friend.requested_frd.split(',')
list_of_frd = list(map(int, req_frd))
list_of_row = []
for i in list_of_frd:
list_of_row.append(User.objects.get(id = i))
return render(request, 'requested_friends.html', {'row': list_of_row})
| Sunil178/Laravel | fb/fbapp/views.py | views.py | py | 4,184 | python | en | code | 0 | github-code | 13 |
16179871215 | import tempfile, os
import numpy as np
import mdtraj as md
from mdtraj.formats import MDCRDTrajectoryFile
from mdtraj.testing import eq
fd, temp = tempfile.mkstemp(suffix='.mdcrd')
def teardown_module(module):
"""remove the temporary file created by tests in this file
this gets automatically called by pytest"""
os.close(fd)
os.unlink(temp)
def test_read_0(get_fn):
with MDCRDTrajectoryFile(get_fn('frame0.mdcrd'), n_atoms=22) as f:
xyz, box = f.read()
assert box is None
with MDCRDTrajectoryFile(get_fn('frame0.mdcrdbox'), n_atoms=22) as f:
xyz2, box = f.read()
eq(box.shape, (1002, 3))
eq(xyz, xyz2)
def test_read_1(get_fn):
with MDCRDTrajectoryFile(get_fn('frame0.mdcrd'), n_atoms=22) as f:
xyz, _ = f.read()
with MDCRDTrajectoryFile(get_fn('frame0.mdcrd'), n_atoms=22) as f:
xyz3, _ = f.read(stride=3)
eq(xyz[::3], xyz3)
def test_read_write_0():
xyz = 10 * np.random.randn(100, 11, 3)
with MDCRDTrajectoryFile(temp, mode='w') as f:
f.write(xyz)
with MDCRDTrajectoryFile(temp, n_atoms=11) as f:
xyz2, _ = f.read()
eq(_, None)
eq(xyz, xyz2, decimal=3)
def test_read_write_1():
xyz = 10 * np.random.randn(100, 11, 3)
box = np.random.randn(100, 3)
with MDCRDTrajectoryFile(temp, mode='w') as f:
f.write(xyz, box)
with MDCRDTrajectoryFile(temp, n_atoms=11) as f:
xyz2, box2 = f.read()
eq(box, box2, decimal=3)
eq(xyz, xyz2, decimal=3)
def test_read_write_2(get_fn):
pdb = md.load(get_fn('1bpi.pdb'))
pdb.save(temp)
t = md.load(temp, top=pdb.topology)
eq(t.xyz, pdb.xyz)
eq(t.unitcell_vectors, pdb.unitcell_vectors)
def test_multiread(get_fn):
reference = md.load(get_fn('frame0.mdcrd'), top=get_fn('native.pdb'))
with MDCRDTrajectoryFile(get_fn('frame0.mdcrd'), n_atoms=22) as f:
xyz0, box0 = f.read(n_frames=1)
xyz1, box1 = f.read(n_frames=1)
eq(reference.xyz[0], xyz0[0] / 10)
eq(reference.xyz[1], xyz1[0] / 10)
def test_seek(get_fn):
reference = md.load(get_fn('frame0.mdcrd'), top=get_fn('native.pdb'))
with MDCRDTrajectoryFile(get_fn('frame0.mdcrd'), n_atoms=22) as f:
f.seek(1)
eq(1, f.tell())
xyz1, box1 = f.read(n_frames=1)
eq(reference.xyz[1], xyz1[0] / 10)
f.seek(10)
eq(10, f.tell())
xyz10, box10 = f.read(n_frames=1)
eq(reference.xyz[10], xyz10[0] / 10)
eq(11, f.tell())
f.seek(-8, 1)
xyz3, box3 = f.read(n_frames=1)
eq(reference.xyz[3], xyz3[0] / 10)
f.seek(4, 1)
xyz8, box8 = f.read(n_frames=1)
eq(reference.xyz[8], xyz8[0] / 10)
def test_atom_indices_0(get_fn):
atom_indices = np.arange(10)
with MDCRDTrajectoryFile(get_fn('frame0.mdcrd'), n_atoms=22) as f:
xyz0, box0 = f.read(n_frames=1)
with MDCRDTrajectoryFile(get_fn('frame0.mdcrd'), n_atoms=22) as f:
xyz1, box1 = f.read(n_frames=1, atom_indices=atom_indices)
eq(xyz0[:, atom_indices], xyz1)
def test_atom_indices_1(get_fn):
atom_indices = np.arange(10)
top = md.load(get_fn('native.pdb'))
t0 = md.load(get_fn('frame0.mdcrd'), top=top)
t1 = md.load(get_fn('frame0.mdcrd'), top=top, atom_indices=atom_indices)
eq(t0.xyz[:, atom_indices], t1.xyz)
| mdtraj/mdtraj | tests/test_mdcrd.py | test_mdcrd.py | py | 3,348 | python | en | code | 505 | github-code | 13 |
5067806892 | import sys, os, time, datetime
import numpy as np
import pandas as pd
import folium
# https://mapsplatform.google.com/pricing/?_gl=1*1s4atal*_ga*MTQwMzE0MzgxOC4xNjY3NDgyMjQx*_ga_NRWSTWS78N*MTY2NzQ4MjI0MS4xLjEuMTY2NzQ4MjI0Ni4wLjAuMA..
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QTabWidget, QVBoxLayout, QLabel, QGridLayout, QLineEdit, \
QPushButton, QMessageBox, QTableView, QComboBox, QStyle, QSpacerItem, QSizePolicy
from PyQt5 import QtCore, QtWebEngineWidgets
from PyQt5.QtGui import QRegExpValidator
from PyQt5.QtCore import Qt, QSortFilterProxyModel, QSize, QRegExp
# Project #
# Creating the main window
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'Ellis Land Surveying'
self.left = 200
self.top = 200
self.width = 1300
self.height = 800
self.setGeometry(self.left, self.top, self.width, self.height)
self.setWindowTitle(self.title)
property_id = [12345, 9876]
street_number = [0, 7820]
street_name = ["Test Street", "Seawall Blvd"]
city = ["La La Land", "Galveston"]
zip = [98765, 77551]
state = ["Murica", "Tx"]
client_id = [99, 100]
lat = [None, 29.2578624]
long = [None, -94.84304617526199]
description = [None, "Oceanfront Loft Apartments"]
status = ["Finalized", "Field Work Complete"]
invoiceDate = ["2022-11-01", None]
lastChangedBy = ["kreed", "kreed"]
notes = ["Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed", ""]
propDF = pd.DataFrame({"property_id": property_id,
"street_number": street_number,
"street_name": street_name,
"city": city,
"zip": zip,
"state": state,
"lat": lat,
"long": long,
"description": description,
"status": status,
"notes": notes,
"client_id": client_id,
"invoice_date": invoiceDate,
"last_changed_by": lastChangedBy
})
client_id = [99, 100]
client_first_name = ["Jane", "Jack"]
client_last_name = ["Joe", "Doe"]
client_phone = ["xxx-xxx-xxxx", "864-789-4555"]
client_phone_2 = [None, "yyy-yyy-yyyy"]
client_email = ["na@na.com", None]
client_address_number = [12345, 0]
client_address_number_2 = [None, "#14"]
client_address_street = ["road street", "NASA Pkwy"]
client_address_city = ["Galveston", "Houston"]
client_address_state = ["Tx", "Tx"]
client_address_zip = [0000, 778888]
clientDF = pd.DataFrame({"client_id": client_id,
"client_first_name": client_first_name,
"client_last_name": client_last_name,
"client_phone": client_phone,
"client_phone_2": client_phone_2,
"client_email": client_email,
"client_address_number": client_address_number,
"client_address_2": client_address_number_2,
"client_address_street": client_address_street,
"client_address_city": client_address_city,
"client_address_state": client_address_state,
"client_address_zip": client_address_zip
})
propDF.sort_values('property_id', ascending=False, inplace=True)
self.tabWidget = QTabWidget()
self.clientManagementTab = ClientManagementTab(clientDF)
self.newJobTab = NewJobTab(propDF, clientDF)
self.jobManagementTab = JobManagementTab(propDF)
self.jobViewTab = JobViewTab(propDF)
self.tabWidget.addTab(self.newJobTab, "New Job")
self.tabWidget.addTab(self.clientManagementTab, "Client Management")
self.tabWidget.addTab(self.jobViewTab, "Job View")
self.tabWidget.addTab(self.jobManagementTab, "Job Management")
self.setCentralWidget(self.tabWidget)
self.clientManagementTab.submitClient.clicked.connect(self.updateClientData)
self.newJobTab.submitButton.clicked.connect(self.updatePropDataNewJob)
self.jobManagementTab.view.model().dataChanged.connect(self.updatePropDataUpdateJob)
self.show()
def updateClientData(self):
# print("Job Tab Client Update")
self.newJobTab.clientDF = self.clientManagementTab.clientDF
def updatePropDataNewJob(self):
# self.newJobTab.submitData()
self.jobViewTab.propDF = self.newJobTab.propDF
self.jobViewTab.createMap()
self.tabWidget.removeTab(3)
newDF = self.newJobTab.propDF
newDF.sort_values('property_id', ascending=False, inplace=True)
newDF.reset_index(inplace=True, drop=True)
self.jobManagementTab = JobManagementTab(newDF)
self.tabWidget.addTab(self.jobManagementTab, "Job Management")
self.jobManagementTab.view.model().dataChanged.connect(self.updatePropDataUpdateJob)
def updatePropDataUpdateJob(self):
# print("parent APP found the change")
self.jobViewTab.propDF = self.jobManagementTab.propDF
self.newJobTab.propDF = self.jobManagementTab.propDF
self.jobViewTab.createMap()
# Creating tab widgets
class NewJobTab(QMainWindow):
def __init__(self, propDF, clientDF):
super(NewJobTab, self).__init__()
self.clientSearch = None
self.clientID = None
self.updateData = None
self.geocodeMessage = ""
self.clientDF = clientDF
self.propDF = propDF
self.clientDF = clientDF
container = QWidget()
centralWidget = CentralWidget(container)
self.setCentralWidget(centralWidget)
self.layout = QGridLayout(container)
startRowProp = 1
self.propertyIDLab = QLabel()
self.propertyIDLab.setText("PropertyID:")
self.layout.addWidget(self.propertyIDLab, startRowProp, 0)
self.propertyIDInput = QLineEdit()
self.propertyIDInput.setMaximumWidth(200)
self.layout.addWidget(self.propertyIDInput, startRowProp, 1)
# Address Inputs
self.addNumInput = QLineEdit()
self.addNameInput = QLineEdit()
self.addCityInput = QLineEdit()
self.addZipInput = QLineEdit()
self.addStateInput = QLineEdit()
# Client Inputs
self.clientFirstNameValue = QLabel()
self.clientLastNameValue = QLabel()
self.clientPhoneValue = QLabel()
self.noteField = QLineEdit()
# Validators
# Validators
numericRegex = QRegExp("[0-9].+")
numericValidator = QRegExpValidator(numericRegex)
zipValidator = QRegExp("[0-9]{5}")
zipValidator = QRegExpValidator(zipValidator)
self.addNumInput.setValidator(numericValidator)
self.addNumInput.setValidator(numericValidator)
#self.addZipInput.setInputMask("99999")
self.addZipInput.setValidator(zipValidator)
self.addStateInput.setInputMask("AA")
#self.propertyIDInput.setValidator(numericValidator)
# ----Buttons----
self.propFindButton = QPushButton()
self.propFindButton.setText("Search for Property ID")
self.layout.addWidget(self.propFindButton, startRowProp, 2)
self.propFindButton.clicked.connect(self.propExitsts)
self.propertyIDInput.returnPressed.connect(self.propFindButton.click)
self.submitButton = QPushButton()
self.submitButton.clicked.connect(self.submitData)
def propExitsts(self):
print("searching for Prop")
if self.addStateInput.visibleRegion().isEmpty():
self.createFields()
try:
userInput = int(self.propertyIDInput.text())
except:
errorBox = QMessageBox()
errorBox.setWindowTitle("Invalid Property ID")
errorBox.setText("Property ID must contain only numbers")
errorBox.setIcon(QMessageBox.Critical)
e = errorBox.exec_()
self.clearFields()
if sum(self.propDF.property_id.astype('int') == userInput) > 0:
foundPropBox = QMessageBox()
foundPropBox.setWindowTitle("Property ID Exists!")
foundPropBox.setText(
"This Property ID has been found in your database already.\nWould you like to import this property information?\n\nNote: Declining this message and saving new data for this property ID will overwrite what is currently stored in the database")
foundPropBox.setIcon(QMessageBox.Question)
foundPropBox.setStandardButtons(QMessageBox.No | QMessageBox.Yes)
foundPropResp = foundPropBox.exec_() # 16384 = Yes , No = 65536
else:
foundPropResp = 0
if foundPropResp == 16384:
print("Importing Property Data")
foundPropSeries = self.propDF.loc[self.propDF.property_id.astype('int') == int(userInput)]
foundPropSeries = foundPropSeries.merge(self.clientDF, on="client_id")
foundPropSeries = foundPropSeries.iloc[0]
self.addNameInput.setText(foundPropSeries.street_name)
self.addNumInput.setText(str(foundPropSeries.street_number))
self.addCityInput.setText(foundPropSeries.city)
self.addZipInput.setText(str(foundPropSeries.zip))
self.addStateInput.setText(foundPropSeries.state)
self.clientFirstNameValue.setText(foundPropSeries.client_first_name)
self.clientLastNameValue.setText(foundPropSeries.client_last_name)
self.clientPhoneValue.setText(str(foundPropSeries.client_phone))
self.clientID = int(foundPropSeries.client_id)
else:
print("Doesn't Exist")
noPropBox = QMessageBox()
noPropBox.setWindowTitle("Property ID not in Database")
noPropBox.setText("Could not Find this Property ID in the Database. Please Enter new Data")
noPropBox.setIcon(QMessageBox.Information)
noPropBox.setStandardButtons(QMessageBox.Ok)
noPropBox.exec_()
currentID = self.propertyIDInput.text()
self.clearFields()
self.propertyIDInput.setText(currentID)
def findClient(self):
print("Searching for Client")
if self.clientSearch is None:
self.clientSearch = ClientSearchWindow(self.clientDF)
self.clientSearch.show()
self.clientSearch.selectButton.clicked.connect(self.importClientParent)
def submitData(self):
if self.clientID is not None and self.addNameInput != "":
try:
self.updateData = pd.DataFrame({"property_id": int(self.propertyIDInput.text()),
"street_number": int(self.addNumInput.text()),
"street_name": self.addNameInput.text(),
"city": self.addCityInput.text(),
"zip": int(self.addZipInput.text()),
"state": self.addStateInput.text(),
"lat": None,
"long": None,
"description": None,
"status": "Not Started",
"notes": self.noteField.text(),
"client_id": self.clientID,
"invoice_date": None,
"last_changed_by": os.getlogin()
}, index=[0])
#Geocode the property
self.geocodeProp()
if sum(self.propDF.property_id.astype('str') == str(self.propertyIDInput.text())) > 0:
print("Updating Existing Property Data...")
print(self.propDF.property_id == int(self.propertyIDInput.text()))
exInd = self.propDF[self.propDF.property_id == int(self.propertyIDInput.text())].index.item()
self.propDF.iloc[exInd] = self.updateData.iloc[0]
subMessage = "Existing Property Information has been Updated"
else:
print("Submitting New Property Data...")
self.propDF = pd.concat([self.propDF, self.updateData])
self.propDF.reset_index(drop=True, inplace=True)
subMessage = "New Property Information has been Entered"
self.clearFields()
except:
subMessage = "Failed to Submit Data. Please Ensure all Mandatory Fields are Filled In"
else:
subMessage = "Missing Data.\nPlease Ensure a client is associated with the property and all mandatory fields are filled in"
subPropBox = QMessageBox()
subPropBox.setWindowTitle("Submission Status")
subPropBox.setText(subMessage + self.geocodeMessage)
subPropBox.setStandardButtons(QMessageBox.Ok)
subPropBox.exec_()
def geocodeProp(self):
geocodeDF = self.updateData.astype('str')
geocodeDF[
"urlString"] = geocodeDF.street_number + " " + geocodeDF.street_name + ", " + geocodeDF.city + ", " + geocodeDF.state
address = geocodeDF.urlString[0]
# Limit one response per second. No repeated hits https://operations.osmfoundation.org/policies/nominatim/
# url = 'https://nominatim.openstreetmap.org/search/' + urllib.parse.quote(address) + '?format=json'
# response = requests.get(url).json()
lat = 29.2578624
lon = -94.84304617526199
display_name = "test"
try:
# self.updateData.lat = response[0]["lat"]
# self.updateData.long = response[0]["lon"]
# self.updateData.description = response[0]["display_name"]
self.updateData.lat = lat
self.updateData.long = lon
self.updateData.description = display_name
self.geocodeMessage = "\n\nGeocoding Success"
except:
self.geocodeMessage = "\n\nGeocoding Failed"
def importClientParent(self):
print("Client Search Initiated")
try:
print("Search Row Selected:", self.clientSearch.selectedRow)
selectedClientSeries = self.clientDF.iloc[self.clientSearch.selectedRow]
self.clientID = selectedClientSeries.client_id
self.clientFirstNameValue.setText(selectedClientSeries.client_first_name)
self.clientLastNameValue.setText(selectedClientSeries.client_last_name)
self.clientPhoneValue.setText(selectedClientSeries.client_phone)
except:
print("Client Search Error")
errorBox = QMessageBox()
errorBox.setWindowTitle("Invalid Selection")
errorBox.setText("Please ensure a row is selected before importing")
errorBox.setIcon(QMessageBox.Critical)
e = errorBox.exec_()
def clearFields(self):
self.propertyIDInput.setText("")
# Address Inputs
self.addNumInput.setText("")
self.addNameInput.setText("")
self.addCityInput.setText("")
self.addZipInput.setText("")
self.addStateInput.setText("Tx")
# Client Inputs
self.clientFirstNameValue.setText("")
self.clientLastNameValue.setText("")
self.clientPhoneValue.setText("")
self.noteField.setText("")
def createFields(self):
print("Creating Fields")
# Property Information
startRowAdd = 5
emptyRow1 = QLabel()
emptyRow1.setText(" ")
self.layout.addWidget(emptyRow1, startRowAdd - 3, 0)
addNumLab = QLabel()
addNumLab.setText("Street Number:")
self.layout.addWidget(addNumLab, startRowAdd, 0)
self.addNumInput.setMaximumWidth(100)
self.layout.addWidget(self.addNumInput, startRowAdd + 1, 0)
addNameLab = QLabel()
addNameLab.setText("Street Name:")
self.layout.addWidget(addNameLab, startRowAdd, 1)
self.addNameInput.setMaximumWidth(200)
self.layout.addWidget(self.addNameInput, startRowAdd + 1, 1)
addCityLab = QLabel()
addCityLab.setText("City:")
self.layout.addWidget(addCityLab, startRowAdd + 2, 0)
self.addCityInput.setMaximumWidth(200)
self.layout.addWidget(self.addCityInput, startRowAdd + 3, 0)
addZipLab = QLabel()
addZipLab.setText("Zip:")
self.layout.addWidget(addZipLab, startRowAdd + 2, 1)
self.addZipInput.setMaximumWidth(100)
self.layout.addWidget(self.addZipInput, startRowAdd + 3, 1)
addStateLab = QLabel()
addStateLab.setText("State:")
self.layout.addWidget(addStateLab, startRowAdd + 2, 2)
self.addStateInput.setMaximumWidth(50)
self.addStateInput.setText("TX")
self.layout.addWidget(self.addStateInput, startRowAdd + 3, 2)
# Client Information
startRowClient = startRowAdd + 7
emptyRow1 = QLabel()
emptyRow1.setText(" ")
self.layout.addWidget(emptyRow1, startRowClient - 2, 0)
clientFindButton = QPushButton()
clientFindButton.setText("Search for Client")
self.layout.addWidget(clientFindButton, startRowClient - 1, 0)
clientFindButton.clicked.connect(self.findClient)
clientFirstNameLab = QLabel()
clientFirstNameLab.setText("Client First Name:")
self.layout.addWidget(clientFirstNameLab, startRowClient, 0)
self.clientFirstNameValue.setMaximumWidth(300)
self.layout.addWidget(self.clientFirstNameValue, startRowClient + 1, 0)
clientLastNameLab = QLabel()
clientLastNameLab.setText("Client Last Name:")
self.layout.addWidget(clientLastNameLab, startRowClient, 1)
self.clientLastNameValue.setMaximumWidth(300)
self.layout.addWidget(self.clientLastNameValue, startRowClient + 1, 1)
clientPhoneLab = QLabel()
clientPhoneLab.setText("Client Phone Number:")
self.layout.addWidget(clientPhoneLab, startRowClient, 2)
self.clientPhoneValue.setMaximumWidth(100)
self.layout.addWidget(self.clientPhoneValue, startRowClient + 1, 2)
noteLabel = QLabel()
noteLabel.setText("Notes:")
self.layout.addWidget(noteLabel, startRowClient + 2, 1)
#noteField.setMinimumWidth(200)
#noteField.setMinimumHeight(150)
self.layout.addWidget(self.noteField, startRowClient + 3, 1)
# Submit New Data Button
self.submitButton.setText("Submit to Database")
self.submitButton.setStyleSheet("background-color : lightblue")
self.layout.addWidget(self.submitButton, startRowClient + 4, 3)
# Clear Data Button
clearButton = QPushButton()
clearButton.setText("Clear all Entries")
self.layout.addWidget(clearButton, 1, 4)
clearButton.clicked.connect(self.clearFields)
def updateParentData(self):
print("Updating App propDF from NewJobTab propDF")
class ClientSearchWindow(QWidget):
def __init__(self, clientDF):
# super().__init__()
QWidget.__init__(self)
self.left = 200
self.top = 200
self.width = 700
self.height = 300
self.setGeometry(self.left, self.top, self.width, self.height)
self.clientDF = clientDF.copy()
self.searchDF = self.clientDF
self.selectedRow = None
self.title = 'Client Lookup'
self.setWindowTitle(self.title)
self.layout = QVBoxLayout(self)
self.view = QTableView(self)
self.header = self.view.horizontalHeader()
# Search Bar
self.searchLabel = QLabel()
self.searchLabel.setText("Search:")
self.layout.addWidget(self.searchLabel)
self.clientSearchInput = QLineEdit()
self.layout.addWidget(self.clientSearchInput)
self.clientSearchInput.textChanged.connect(self.searchEvent)
# Table
self.view.resizeRowsToContents()
self.view.resizeColumnsToContents()
self.model = PandasModel(self.searchDF.head(100))
self.view.setModel(self.model)
self.view.setSelectionBehavior(QTableView.SelectRows)
self.view.setSelectionMode(QTableView.SingleSelection)
self.layout.addWidget(self.view)
# Select Button
self.selectButton = QPushButton()
self.selectButton.setText("Select Client")
self.layout.addWidget(self.selectButton)
# Button Functions
self.view.clicked.connect(self.rowClicked)
self.selectButton.clicked.connect(self.importClientChild)
def rowClicked(self):
self.selectedRow = self.view.currentIndex()
self.selectedRow = self.view.model().index(self.selectedRow.row(), 0).row()
def importClientChild(self):
self.destroy()
def searchEvent(self):
mask = np.column_stack(
[self.clientDF[col].astype('str').str.contains(self.clientSearchInput.text().lower(), na=False, case=False)
for col in self.clientDF])
self.searchDF = self.clientDF.loc[mask.any(axis=1)]
self.updateModel()
def updateModel(self):
self.model = PandasModel(self.searchDF.head(100))
self.view.setModel(self.model)
class ClientManagementTab(QWidget):
def __init__(self, clientDF):
# super().__init__()
QWidget.__init__(self)
self.clientDF = clientDF.copy()
self.searchDF = self.clientDF
self.selectedRow = None
self.selected_client_id = None
self.layout = QVBoxLayout(self)
self.view = QTableView(self)
self.header = self.view.horizontalHeader()
# Search Bar
self.searchLabel = QLabel()
self.searchLabel.setText("Search:")
self.layout.addWidget(self.searchLabel)
self.clientSearchInput = QLineEdit()
self.clientSearchInput.setStyleSheet("background-color : white")
self.clientSearchInput.setMinimumHeight(30)
self.clientSearchInput.textChanged.connect(self.searchEvent)
# New Client Button
self.newClientButton = QPushButton()
self.newClientButton.setText("New Client")
self.newClientButton.setStyleSheet("background-color : lightgreen")
self.newClientButton.clicked.connect(self.createEditLayout)
# Edit Client
self.clientEditButton = QPushButton()
self.clientEditButton.setText("Edit Client")
self.clientEditButton.setStyleSheet("background-color : lightblue")
self.clientEditButton.clicked.connect(self.editClient)
# Table
self.view.resizeRowsToContents()
self.view.resizeColumnsToContents()
self.model = PandasModel(self.searchDF.head(100))
self.view.setModel(self.model)
self.view.setSortingEnabled(True)
self.view.setSelectionBehavior(QTableView.SelectRows)
self.view.setSelectionMode(QTableView.SingleSelection)
self.view.resizeRowsToContents()
self.view.resizeColumnsToContents()
self.view.clicked.connect(self.rowClicked)
# Add Default Layout
self.resetLayout()
# Client Edit Labels
self.clientFirstNameLabel = QLabel()
self.clientFirstNameLabel.setText("First Name")
self.clientLastNameLabel = QLabel()
self.clientLastNameLabel.setText("Last Name")
self.clientPhoneLabel = QLabel()
self.clientPhoneLabel.setText("Primary Phone")
self.clientPhone2Label = QLabel()
self.clientPhone2Label.setText("Secondary Phone")
self.clientEmailLabel = QLabel()
self.clientEmailLabel.setText("Email Address")
self.emptySpace = QLabel()
self.emptySpace.setText(" ")
self.mailingLabel = QLabel()
self.mailingLabel.setText("Client Mailing Address Information:")
self.emptySpace2 = QLabel()
self.emptySpace2.setText(" ")
self.mailingLabel2 = QLabel()
self.clientAddNumLabel = QLabel()
self.clientAddNumLabel.setText("Street Number:")
self.clientAddNum2Label = QLabel()
self.clientAddNum2Label.setText("Street Number Extended:")
self.clientAddNameLabel = QLabel()
self.clientAddNameLabel.setText("Street Name:")
self.clientAddCityLabel = QLabel()
self.clientAddCityLabel.setText("City:")
self.clientAddStateLabel = QLabel()
self.clientAddStateLabel.setText("State:")
self.clientAddZipLabel = QLabel()
self.clientAddZipLabel.setText("Zip:")
# Client Input Fields
self.clientFirstNameInput = QLineEdit()
self.clientLastNameInput = QLineEdit()
self.clientPhoneInput = QLineEdit()
self.clientPhone2Input = QLineEdit()
self.clientEmailInput = QLineEdit()
self.clientAddNumInput = QLineEdit()
self.clientAddNum2Input = QLineEdit()
self.clientAddNameInput = QLineEdit()
self.clientAddCityInput = QLineEdit()
self.clientAddStateInput = QLineEdit()
self.clientAddZipInput = QLineEdit()
# Validators
numericRegex = QRegExp("[0-9].+")
numericValidator = QRegExpValidator(numericRegex)
self.clientAddNumInput.setValidator(numericValidator)
self.clientAddNumInput.setValidator(numericValidator)
self.clientAddZipInput.setInputMask("99999")
self.clientPhoneInput.setInputMask("(000) 000-0000")
self.clientAddStateInput.setInputMask("AA")
# Submit Button
self.submitClient = QPushButton()
self.submitClient.setText("Submit")
self.submitClient.setStyleSheet("background-color : lightblue")
self.submitClient.clicked.connect(self.enterClient)
# Cancel Button
self.cancelClient = QPushButton()
self.cancelClient.setText("Cancel")
self.cancelClient.setStyleSheet("background-color : red")
self.cancelClient.clicked.connect(self.resetLayout)
def clearFields(self):
self.clientFirstNameInput.setText("")
self.clientLastNameInput.setText("")
self.clientPhoneInput.setText("")
self.clientPhone2Input.setText("")
self.clientEmailInput.setText("")
self.clientAddNumInput.setText("")
self.clientAddNum2Input.setText("")
self.clientAddNameInput.setText("")
self.clientAddCityInput.setText("")
self.clientAddStateInput.setText("")
self.clientAddZipInput.setText("")
def resetLayout(self):
print("Resetting Layout")
# remove widgets
for i in reversed(range(self.layout.count())):
self.layout.itemAt(i).widget().setParent(None)
# Update Table
self.searchDF = self.clientDF
self.model = PandasModel(self.searchDF.head(100))
self.view.setModel(self.model)
# Add back in Widgets
self.layout.addWidget(self.clientSearchInput)
self.layout.addWidget(self.newClientButton)
self.layout.addWidget(self.clientEditButton)
self.layout.addWidget(self.view)
def rowClicked(self):
self.selectedRow = self.view.currentIndex()
self.selectedRow = self.view.model().index(self.selectedRow.row(), 0).row()
def searchEvent(self):
mask = np.column_stack(
[self.clientDF[col].astype('str').str.contains(self.clientSearchInput.text().lower(), na=False, case=False)
for col in self.clientDF])
self.searchDF = self.clientDF.loc[mask.any(axis=1)]
self.updateModel()
def updateModel(self):
self.model = PandasModel(self.searchDF.head(100))
self.view.setModel(self.model)
def editClient(self):
print("Edit Existing Client")
if self.selectedRow is None:
errorBox = QMessageBox()
errorBox.setWindowTitle("No Selection")
errorBox.setText("Please Select a Client to Edit by Clicking on a Row")
errorBox.setIcon(QMessageBox.Critical)
errorBox.exec_()
else:
selectedDat = self.clientDF.iloc[self.selectedRow].copy()
self.selected_client_id = selectedDat.client_id
selectedDat.fillna("", inplace=True)
selectedDat = selectedDat.astype('str')
self.createEditLayout()
self.clientFirstNameInput.setText(selectedDat.client_first_name)
self.clientLastNameInput.setText(selectedDat.client_last_name)
self.clientPhoneInput.setText(selectedDat.client_phone)
self.clientPhone2Input.setText(selectedDat.client_phone_2)
self.clientEmailInput.setText(selectedDat.client_email)
self.clientAddNumInput.setText(selectedDat.client_address_number)
self.clientAddNum2Input.setText(selectedDat.client_address_2)
self.clientAddNameInput.setText(selectedDat.client_address_street)
self.clientAddCityInput.setText(selectedDat.client_address_city)
self.clientAddStateInput.setText(selectedDat.client_address_state)
self.clientAddZipInput.setText(selectedDat.client_address_zip)
def enterClient(self):
# print(self.selected_client_id)
updateData = pd.DataFrame({"client_id": self.selected_client_id,
"client_first_name": self.clientFirstNameInput.text(),
"client_last_name": self.clientLastNameInput.text(),
"client_phone": self.clientPhoneInput.text(),
"client_phone_2": self.clientPhone2Input.text(),
"client_email": self.clientEmailInput.text(),
"client_address_number": self.clientAddNumInput.text(),
"client_address_2": self.clientAddNum2Input.text(),
"client_address_street": self.clientAddNameInput.text(),
"client_address_city": self.clientAddCityInput.text(),
"client_address_state": self.clientAddStateInput.text(),
"client_address_zip": self.clientAddZipInput.text()
}, index=[0])
emptyInputs = updateData.columns[updateData.isin([""]).any()].tolist()
mandatoryInputs = ["client_first_name", "client_last_name", "client_phone", "client_address_number",
"client_address_city", "client_address_state", "client_address_zip"]
if any(x in emptyInputs for x in mandatoryInputs):
print("Missing Client Data Error")
errorBox = QMessageBox()
errorBox.setWindowTitle("Missing Fields")
errorBox.setText("Please Ensure Client Name and Address are Filled")
errorBox.setIcon(QMessageBox.Critical)
errorBox.exec_()
else:
if self.selected_client_id is not None:
print("Updating Existing Client")
exInd = self.clientDF[self.clientDF.client_id == self.selected_client_id].index.item()
self.clientDF.iloc[exInd] = updateData.iloc[0]
else:
print("Creating New Client")
self.clientDF = pd.concat([self.clientDF, updateData])
self.clientDF.reset_index(drop=True, inplace=True)
self.clientDF.at[len(self.clientDF) - 1, "client_id"] = self.clientDF.client_id[
len(self.clientDF) - 2] + 1
self.clearFields()
self.resetLayout()
def createEditLayout(self):
startRow = 1
print("Creating Client Edit Layout")
for i in reversed(range(self.layout.count())):
self.layout.itemAt(i).widget().setParent(None)
# Add Labels and Input Fields
self.layout.addWidget(self.clientFirstNameLabel)
self.layout.addWidget(self.clientFirstNameInput)
self.layout.addWidget(self.clientLastNameLabel)
self.layout.addWidget(self.clientLastNameInput)
self.layout.addWidget(self.clientPhoneLabel)
self.layout.addWidget(self.clientPhoneInput)
self.layout.addWidget(self.clientPhone2Label)
self.layout.addWidget(self.clientPhone2Input)
self.layout.addWidget(self.clientEmailLabel)
self.layout.addWidget(self.clientEmailInput)
self.layout.addWidget(self.emptySpace)
self.layout.addWidget(self.mailingLabel)
self.layout.addWidget(self.emptySpace2)
self.layout.addWidget(self.clientAddNumLabel)
self.layout.addWidget(self.clientAddNumInput)
self.layout.addWidget(self.clientAddNum2Label)
self.layout.addWidget(self.clientAddNum2Input)
self.layout.addWidget(self.clientAddNameLabel)
self.layout.addWidget(self.clientAddNameInput)
self.layout.addWidget(self.clientAddCityLabel)
self.layout.addWidget(self.clientAddCityInput)
self.layout.addWidget(self.clientAddStateLabel)
self.layout.addWidget(self.clientAddStateInput)
self.layout.addWidget(self.clientAddZipLabel)
self.layout.addWidget(self.clientAddZipInput)
self.clientAddStateInput.setText("Tx")
# Include Buttons
self.layout.addWidget(self.submitClient)
self.layout.addWidget(self.cancelClient)
class JobViewTab(QWidget):
def __init__(self, propDF):
# super().__init__()
QWidget.__init__(self)
self.mapOutput = QtWebEngineWidgets.QWebEngineView()
self.layout = QVBoxLayout(self)
notStarted = QLabel()
notStarted.setText("Not Started")
notStarted.setStyleSheet('color: red')
self.layout.addWidget(notStarted)
quoted = QLabel()
quoted.setText("Quoted")
quoted.setStyleSheet('color: orange')
self.layout.addWidget(quoted)
invoiced = QLabel()
invoiced.setText("Invoiced")
invoiced.setStyleSheet('color: green')
self.layout.addWidget(invoiced)
preliminary = QLabel()
preliminary.setText("Preliminary")
preliminary.setStyleSheet('color: lightgreen')
self.layout.addWidget(preliminary)
fieldWorkReady = QLabel()
fieldWorkReady.setText("Field Work Ready")
fieldWorkReady.setStyleSheet('color: pink')
self.layout.addWidget(fieldWorkReady)
fieldWorkComp = QLabel()
fieldWorkComp.setText("Field Work Complete")
fieldWorkComp.setStyleSheet('color: purple')
self.layout.addWidget(fieldWorkComp)
drafted = QLabel()
drafted.setText("Drafted")
drafted.setStyleSheet('color: darkblue')
self.layout.addWidget(drafted)
finalized = QLabel()
finalized.setText("Finalized")
finalized.setStyleSheet('color: grey')
self.layout.addWidget(finalized)
spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
self.mapOutput.resize(200, 1000)
self.layout.addWidget(self.mapOutput)
self.layout.addItem(spacer)
self.propDF = propDF
self.map = folium.Map(location=[29.407786779390726, -94.9356243977614])
self.createMap()
def createMap(self):
# print("Creating Map")
# print(self.propDF)
mapDF = self.propDF[["lat", "long", "description", "status"]].copy()
mapDF["description"].fillna("", inplace=True)
mapDF.dropna(inplace=True)
colorDict = {"Not Started": "red",
"Quoted": "orange",
"Invoiced": "green",
"Preliminary": "lightgreen",
"Field Work Ready": "lightred",
"Field Work Complete": "purple",
"Drafted": "darkblue",
"Finalized": "lightgray"
}
self.map = folium.Map(location=[29.407786779390726, -94.9356243977614])
folium.Marker(
location=[29.407786779390726, -94.9356243977614], # coordinates for the marker
popup="Ellis Landsurveying Office (Where the most wonderful and sexy Land Surveyor can be Found most days)", # pop-up label for the marker
icon=folium.Icon(),
color="red"
).add_to(self.map)
# mapDF.apply(lambda row: folium.Marker(location=[row["lat"], row["long"]], color="green",
# radius=5, popup=row['description']).add_to(self.map), axis=1)
mapDF.apply(lambda row: folium.Marker([row["lat"], row["long"]],
popup=row["description"],
icon=folium.Icon(color=colorDict[row['status']])).add_to(self.map),
axis=1)
# folium.Marker([row[lat], row[lon]], popup=row("description), icon=folium.Icon(color=colorDict[row['status']))
# self.map.save('tempMap.html')
self.map.add_child(folium.ClickForMarker(popup=None))
self.mapOutput.setHtml(self.map._repr_html_())
class JobManagementTab(QWidget):
def __init__(self, propDF):
# super().__init__()
QWidget.__init__(self)
self.propDF = propDF
self.selectedRow = None
self.selected_client_id = None
self.layout = QVBoxLayout(self)
self.view = QTableView(self)
self.header = self.view.horizontalHeader()
# Search Bar
self.searchLabel = QLabel()
self.searchLabel.setText("Search:")
self.layout.addWidget(self.searchLabel)
self.propSearchInput = QLineEdit()
self.propSearchInput.setStyleSheet("background-color : white")
self.propSearchInput.setMinimumHeight(30)
# Table
self.model = PandasModel(self.propDF)
self.view.setSelectionBehavior(QTableView.SelectRows)
self.view.setSelectionMode(QTableView.SingleSelection)
self.view.clicked.connect(self.rowClicked)
# Update Table
self.proxyModel = QSortFilterProxyModel()
self.proxyModel.setFilterKeyColumn(-1)
self.proxyModel.setSourceModel(self.model)
self.view.setModel(self.proxyModel)
#self.view.setSortingEnabled(True)
# self.proxyModel.sort(0, Qt.DescendingOrder)
self.propSearchInput.textChanged.connect(self.proxyModel.setFilterFixedString)
self.propSearchInput.textChanged.connect(self.searchEvent)
#self.view.resizeRowsToContents()
self.view.resizeColumnsToContents()
self.view.setColumnWidth(self.propDF.columns.get_loc("notes"), 220)
self.view.setColumnWidth(self.propDF.columns.get_loc("status"), 150)
self.proxyModel.setFilterCaseSensitivity(False)
# Add back in Widgets
self.layout.addWidget(self.propSearchInput)
self.layout.addWidget(self.view)
self.setEditableFields(self.propDF.index.to_list())
def setEditableFields(self, rows):
for col in range(0, len(self.propDF.columns)):
for row in rows:
modelIndex = self.view.model().index(row, col)
if self.propDF.columns[col] == "status":
combo = QComboBox()
combo.addItems(["Not Started", "Quoted", "Invoiced", "Preliminary", "Field Work Ready", "Field Work Complete", "Drafted", "Finalized"])
combo.setCurrentText(self.propDF.status[row])
combo.currentTextChanged.connect(self.updateData)
self.view.setIndexWidget(self.view.model().index(row, col), combo)
self.view.model().setData(modelIndex, str(self.propDF.iloc[row][col]))
elif self.propDF.columns[col] in ["lat", "long", "description", "notes"]:
lineEdit = QLineEdit()
lineEdit.setText(str(self.propDF.iloc[row][col]))
lineEdit.returnPressed.connect(self.updateLineData)
self.view.setIndexWidget(self.view.model().index(row, col), lineEdit)
self.view.model().setData(modelIndex, str(self.propDF.iloc[row][col]))
else:
self.view.model().setData(modelIndex, str(self.propDF.iloc[row][col]))
def updateLineData(self):
rowChanged = self.view.currentIndex().row()
columnChanged = self.view.currentIndex().column()
widget = self.view.indexWidget(self.view.model().index(rowChanged, columnChanged))
widgetIndex = self.view.model().index(rowChanged, columnChanged)
text = widget.text()
errorBox = QMessageBox()
errorBox.setIcon(QMessageBox.Critical)
errorBox.setWindowTitle("Error")
errorBox.setText("Data Type Error. Ensure Lat and Long only contain numerical values")
confirmBox = QMessageBox()
confirmBox.setWindowTitle("Confirm Changes")
confirmBox.setText("Please Confirm Changes")
confirmBox.setIcon(QMessageBox.Question)
confirmBox.setStandardButtons(QMessageBox.Save | QMessageBox.Discard)
confirmBox.setDefaultButton(QMessageBox.Save)
confirmBoxResp = confirmBox.exec_()
if confirmBoxResp == 2048:
if self.propDF.columns[columnChanged] in ["lat", "long"]:
try:
float(text)
print('here')
except:
errorBox = QMessageBox()
errorBox.setIcon(QMessageBox.Critical)
errorBox.setWindowTitle("Error")
errorBox.setText("Data Type Error. Ensure Lat and Long only contain numerical values")
errorBox.exec_()
text = self.view.model().data(widgetIndex)
#---Change By User----
propModelIndex = self.view.model().index(rowChanged, 0)
propID = self.view.model().data(propModelIndex)
propDFIndex = self.propDF[self.propDF.property_id.astype('str') == str(propID)].index[0]
self.propDF.at[propDFIndex, self.propDF.columns[columnChanged]] = text
changeIndex = self.view.model().index(propDFIndex, columnChanged)
#print("propID:", propDFIndex)
#print("New Text: ", text)
self.view.model().setData(changeIndex, text)
#print("Model Status:", self.view.model().setData(changeIndex, text))
#print("Model Data:", self.view.model().data(changeIndex))
#---Updated Last Changed By Column---
changeByCol = self.propDF.columns.get_loc("last_changed_by")
self.propDF.at[propDFIndex, self.propDF.columns[changeByCol]] = os.getlogin()
changeByIndex = self.view.model().index(rowChanged, changeByCol)
print("old value:", self.view.model().data(changeByIndex))
self.view.model().setData(changeByIndex, os.getlogin())
print("New value:", self.view.model().data(changeByIndex))
self.searchEvent()
def updateData(self, text):
# Check if Invoice is Being Changed
if text == "Invoiced":
confirmBox = QMessageBox()
confirmBox.setWindowTitle("Confirm Changes")
confirmBox.setText("This will Update Invoice Date. Please Confirm Changes")
confirmBox.setIcon(QMessageBox.Question)
confirmBox.setStandardButtons(QMessageBox.Save | QMessageBox.Discard)
confirmBox.setDefaultButton(QMessageBox.Save)
confirmBoxResp = confirmBox.exec_()
else:
confirmBoxResp = 2048
if confirmBoxResp == 2048:
combobox = self.sender()
ix = self.view.indexAt(combobox.pos())
rowChanged = ix.row()
columnChanged = ix.column()
propModelIndex = self.view.model().index(rowChanged, 0)
propID = self.view.model().data(propModelIndex)
propDFIndex = self.propDF[self.propDF.property_id.astype('str') == str(propID)].index[0]
self.propDF.at[propDFIndex, self.propDF.columns[columnChanged]] = text
changeIndex = self.view.model().index(propDFIndex, columnChanged)
#print("propID:", propDFIndex)
#print("New Text: ", text)
self.view.model().setData(changeIndex, text)
#print("Model Status:", self.view.model().setData(changeIndex, text))
#print("Model Data:", self.view.model().data(changeIndex))
#Update User
# ---Updated Last Changed By Column---
changeByCol = self.propDF.columns.get_loc("last_changed_by")
self.propDF.at[propDFIndex, self.propDF.columns[changeByCol]] = os.getlogin()
changeByIndex = self.view.model().index(rowChanged, changeByCol)
#print("old value:", self.view.model().data(changeByIndex))
self.view.model().setData(changeByIndex, os.getlogin())
#print("New value:", self.view.model().data(changeByIndex))
#Update Invoice Date
if text == "Invoiced":
invoiceCol = self.propDF.columns.get_loc("invoice_date")
self.propDF.at[propDFIndex, self.propDF.columns[invoiceCol]] = str(datetime.date.today())
invoiceIndex = self.view.model().index(rowChanged, invoiceCol)
# print("old value:", self.view.model().data(changeByIndex))
self.view.model().setData(invoiceIndex, str(datetime.date.today()))
# print("New value:", self.view.model().data(changeByIndex))
self.searchEvent()
def rowClicked(self):
self.selectedRow = self.view.currentIndex()
self.selectedRow = self.view.model().index(self.selectedRow.row(), 0).row()
def searchEvent(self):
searchDF = self.propDF[
self.propDF.apply(lambda row: row.astype(str).str.contains(self.propSearchInput.text(), case=False).any(),
axis=1)]
self.setEditableFields(searchDF.index.to_list())
class CentralWidget(QWidget):
def __init__(self, widget):
super().__init__()
self._widget = widget
self.widget.setParent(self)
@property
def widget(self):
return self._widget
def resizeEvent(self, event):
super().resizeEvent(event)
size = min(self.width(), self.height())
r = QStyle.alignedRect(
Qt.LeftToRight, Qt.AlignLeft, QSize(size, 400), self.rect()
)
self.widget.setGeometry(r)
class PandasModel(QtCore.QAbstractTableModel):
"""
Class to populate a table view with a pandas dataframe
"""
def __init__(self, data, parent=None):
QtCore.QAbstractTableModel.__init__(self, parent)
self.dataDF = data.copy()
self._data = np.array(data.values)
self._cols = data.columns
self.r, self.c = np.shape(self._data)
def rowCount(self, parent=None):
return self.r
def columnCount(self, parent=None):
return self.c
def data(self, index, role=Qt.DisplayRole):
if (index.row() <= self.r) and (index.column() <= self.c):
if index.isValid():
if role == Qt.DisplayRole:
if str(self.dataDF.dtypes[index.column()]).find('int') != -1:
return int(self._data[index.row(), index.column()])
elif str(self.dataDF.dtypes[index.column()]).find('float') != -1:
return float(self._data[index.row(), index.column()])
else:
return str(self._data[index.row(), index.column()])
return None
def headerData(self, p_int, orientation, role):
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
return self._cols[p_int]
elif orientation == Qt.Vertical:
return p_int
return None
def setData(self, index, value, role=QtCore.Qt.EditRole):
if role == QtCore.Qt.EditRole:
row = index.row()
column = index.column()
self._data[row][column] = value
self.dataChanged.emit(index, index)
return True
return QtCore.QAbstractTableModel.setData(self, index, value, role)
# def sort(self, column, order=Qt.AscendingOrder):
# print('sort clicked col {} order {}'.format(column, order))
# self._data = self._data[self._data[:, column].argsort()][::-1] #order == Qt.AscendingOrder
# self.layoutAboutToBeChanged.emit()
# self.layoutChanged.emit()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
| PlaidDragon/Dashboards-GUIs | EllisGUI_v_0_7.py | EllisGUI_v_0_7.py | py | 50,719 | python | en | code | 0 | github-code | 13 |
20746455559 | #Usando parametro em uma função
nome = 'João'
def saudacao_com_parametro(nome_da_pessoa):
print(f'Olá {nome_da_pessoa}')
saudacao_com_parametro(nome)
###############################################################
#Condicional
#Verificar a idade se é possível dirigir
idade = 20
def verificaDirigir(idade_pessoa):
if idade_pessoa < 18:
print('Não é permitido dirigir')
else:
print('Permiti dirigir')
verificaDirigir(idade)
###############################################################
# Receber um valor dentro de uma função
def verificaDirigirsemParametro():
idade = input('Qual sua idade? ')
#Convertendo um tipo Int
idade = int(idade)
if idade < 18:
print(f'{idade} anos Não tem permissão para dirigir')
else:
print(f'{idade} Tem permissão para dirigir')
verificaDirigirsemParametro() | HenryJKS/Python | Conhecendo Python/Parâmetro.py | Parâmetro.py | py | 888 | python | pt | code | 0 | github-code | 13 |
10591194568 | from typing import List
class Solution:
def dfs(self, node: int, adj: dict[int, list], visited: List[bool]) -> int:
visited[node] = True
minimum = int(10 ** 9)
for road in adj[node]:
minimum = min(minimum, road[1])
if visited[road[0]]:
continue
minimum = min(minimum, self.dfs(road[0], adj, visited))
return minimum
def minScore(self, n: int, roads: List[List[int]]) -> int:
adj = dict()
visited = [False] * n
for road in roads:
if road[0] - 1 not in adj:
adj[road[0] - 1] = []
if road[1] - 1 not in adj:
adj[road[1] - 1] = []
adj[road[0] - 1].append([road[1] - 1, road[2]])
adj[road[1] - 1].append([road[0] - 1, road[2]])
for node in range(n):
if visited[node]:
continue
minimum = self.dfs(node, adj, visited)
if visited[n - 1]:
return minimum
return -1
| harshraj9988/LeetCode-solutions | Leetcode-solution-python/minimumScoreOfAPathBetweenTwoCities.py | minimumScoreOfAPathBetweenTwoCities.py | py | 1,039 | python | en | code | 0 | github-code | 13 |
22043901849 | from selenium import webdriver
import time
import requests as req
from bs4 import BeautifulSoup
import re
import os
import cv2
import numpy as np
def img_process(img_path, tags):
w_font, h_font = 22, 15
alpha = 0.3
img = cv2.imread(img_path)
w_img, h_img = (img.shape[1]*7, img.shape[0]*7)
img = cv2.resize(
img, (w_img, h_img), interpolation=cv2.INTER_CUBIC)
len_tags = len(tags)
font_pos = (int(w_img/2)-int(len_tags/2*w_font/2),
int(h_img/2)+int(h_font/2))
cv2.rectangle(img, (font_pos[0], font_pos[1]-h_font-5),
(int(font_pos[0]+len_tags*w_font/2)+30, font_pos[1]+5), (255, 255, 255), -1)
# for correction
# cv2.circle(img, (int(w_img/2), int(h_img/2)), 2, (0, 255, 0), -1)
cv2.putText(img, tags, font_pos,
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 1, cv2.LINE_AA)
cv2.imwrite(img_path, img)
def get_img(html):
soup = BeautifulSoup(html, 'lxml')
table = soup.find(attrs={'id': 'ConcurrentUsersRows'})
games = table.find_all('a')
for g in games:
img_url = g.find('img').get('src')
name = g.find(attrs={'class': 'tab_item_name'}).text
non_chinese = re.sub('[\u4E00-\u9FFF]+','?', name)
file_name = re.sub('^_|_$', '', re.sub('\W+', '_', non_chinese))
path_name = os.path.join('./img/steam', f'{file_name}.png')
print('--------------------------------')
print(file_name)
r_img = req.get(img_url, stream=True)
if r_img.status_code == 200:
with open(path_name, 'wb') as f:
for chunk in r_img:
f.write(chunk)
tags = g.find(attrs={'class': 'tab_item_top_tags'}).text
img_process(path_name, tags)
def main():
browser = webdriver.Firefox()
browser.get('https://store.steampowered.com/')
# browser.maximize_window()
browser.find_element_by_id('language_pulldown').click()
time.sleep(1)
browser.find_element_by_link_text('English(英文)').click()
time.sleep(2)
browser.find_element_by_link_text('Free to Play').click()
browser.find_element_by_id('tab_select_ConcurrentUsers').click()
for _ in range(4):
html = browser.page_source
get_img(html)
browser.find_element_by_id('ConcurrentUsers_btn_next').click()
time.sleep(3)
html = browser.page_source
get_img(html)
time.sleep(1)
browser.quit()
if __name__ == "__main__":
if not os.path.exists('.\img\steam'):
os.mkdir('.\img\steam')
main()
| TerryYeh54147/Python-Workshop | 0805/3.py | 3.py | py | 2,570 | python | en | code | 0 | github-code | 13 |
39131338671 | final_result = {}
# sales_sum 委托生成器 k 子生成器
def sales_sum(k):
total = 0
nums = []
while True:
x = yield
print(k + '销量:', x)
# 循环结束条件
if not x:
break
total += x
nums.append(x)
return total, nums
# middle 调用方
def middle(k):
while True:
final_result[k] = yield from sales_sum(k)
print(k + '销量统计完成!')
def main():
data_sets = {
'面膜': [1200, 1500, 3000],
'手机': [28, 55, 98, 108],
'服装': [280, 560, 778, 70],
}
for k, v in data_sets.items():
print('start key:', k)
m = middle(k)
next(m)
for d in v:
# send的值传入到了sales_sum中
m.send(d)
next(m)
print('final_result', final_result)
if __name__ == '__main__':
main()
| dsdcyy/python- | python进阶/生成器进阶/02-2 yelid_from.py | 02-2 yelid_from.py | py | 893 | python | en | code | 0 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.