seq_id string | text string | repo_name string | sub_path string | file_name string | file_ext string | file_size_in_byte int64 | program_lang string | lang string | doc_type string | stars int64 | dataset string | pt string | api list |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1655512886 | import random
from turtle import Screen
from display import DisplaySet
from paddle import Paddle
from ball import Ball
from score import Score
import time
screen = Screen()
screen.title('PONG')
screen.bgcolor('black')
screen.setup(height=600, width=800)
screen.tracer(0)
set_game_field = DisplaySet()
game_on = True
ball = Ball()
score = Score()
score_p1 = Score()
score_p2 = Score()
paddle_1 = Paddle()
paddle_2 = Paddle()
paddle_1.paddle_position(-350)
score_p1.score_position(-120)
paddle_2.paddle_position(350)
score_p2.score_position(100)
screen.listen()
screen.onkey(paddle_1.paddle_up, 'q')
screen.onkey(paddle_1.paddle_down, 'a')
screen.onkey(paddle_2.paddle_up, 'Up')
screen.onkey(paddle_2.paddle_down, 'Down')
while game_on:
time.sleep(ball.ball_speed)
screen.update()
ball.ball_on_the_run()
tilt_angle = random.randrange(4, 8)
if ball.ycor() > 280 or ball.ycor() < -280:
new_angle = 360 - ball.heading()
ball.setheading(new_angle)
elif ball.distance(paddle_1) < 50 and ball.xcor() < -330:
new_angle = 360 - (ball.heading() * 2 - tilt_angle)
ball.setheading(new_angle)
elif ball.distance(paddle_2) < 50 and ball.xcor() > 330:
new_angle = 180 - (ball.heading() * 2 + tilt_angle)
ball.setheading(new_angle)
elif ball.xcor() > 370:
ball.p1_score_set()
score_p1.score_count()
elif ball.xcor() < -370:
ball.p2_score_set()
score_p2.score_count()
if score_p1.score == 10 or score_p2.score == 10:
score.end_game()
game_on = False
screen.exitonclick()
| wojtekgajda/pong_game | main.py | main.py | py | 1,600 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "turtle.Screen",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "display.DisplaySet",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "ball.Ball",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "score.Score",
"line_num... |
34023408707 | import cv2
import os
from ultralytics import YOLO
from datetime import datetime, timedelta
# Load the YOLOv8 model
modelo_pt = r'Modelos\Deploys_Ultralytics_Hub\detector_de_placas_yolov8_nano.pt'
model = YOLO(f'{modelo_pt}')
# Open the video file
video_path = r"Video\Video_teste.mp4"
cap = cv2.VideoCapture(video_path)
# Certifique-se de que o diretório de saída existe, senão crie-o
save_path_cortadas = r"Resultado_de_dados\imagens_cortadas"
if not os.path.exists(save_path_cortadas):
os.makedirs(save_path_cortadas)
save_path_inteiras = r"Resultado_de_dados\imagens_inteiras"
if not os.path.exists(save_path_inteiras):
os.makedirs(save_path_inteiras)
# Defina manualmente o horário de início da gravação IMPORTANTISSIMO!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
start_time = datetime(2023, 10, 30, 17, 35, 9)
# Loop through the video frames
file_num = 0
unique_id = set()
# Define a nova largura e altura desejada
new_width, new_height = 1100, 600
while cap.isOpened():
# Read a frame from the video
success, frame = cap.read()
if success:
# Resize the frame to 640x640
frame = cv2.resize(frame, (new_width, new_height))
# Run YOLOv8 inference on the frame
results = model.track(frame, persist=True, conf=0.95, save_txt=True)
#results = model.predict(frame, conf=0.95, save_txt=True)
if results[0].boxes.id is not None:
boxes = results[0].boxes.xyxy.cpu().numpy().astype(int)
ids = results[0].boxes.id.cpu().numpy().astype(int)
for box, id in zip(boxes, ids):
int_id = int(id)
if int_id not in unique_id:
unique_id.add(int_id)
box = box[:4]
# Crop the image using the bounding box coordinates
cropped_img = frame[box[1]:box[3], box[0]:box[2]]
class_id = int(id)
# Calcular o horário de detecção somando os segundos desde o início do vídeo ao horário de início
seconds_elapsed = cap.get(cv2.CAP_PROP_POS_FRAMES) / cap.get(cv2.CAP_PROP_FPS)
detection_time = start_time + timedelta(seconds=seconds_elapsed)
# Salvar a imagem recortada com o horário relativo
filename = f"imagem_destacada_do_id_{int_id}_horario_{detection_time.strftime('%H-%M-%S')}.jpg"
filepath = os.path.join(save_path_cortadas, filename)
cv2.imwrite(filepath, cropped_img)
filename_inteira = f"foto_inteira_do_id_{int_id}_horario_{detection_time.strftime('%H-%M-%S')}.jpg"
filepath_inteira = os.path.join(save_path_inteiras, filename_inteira)
cv2.imwrite(filepath_inteira, frame)
frame = results[0].plot()
# Display the annotated frame
cv2.imshow(f"Detectando pelo modelo: {modelo_pt}", frame)
# Break the loop if 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord("q"):
break
else:
# Break the loop if the end of the video is reached
break
# Release the video capture object and close the display window
cap.release()
cv2.destroyAllWindows() | DevJoaoPedroGiancoli/BrazilTrafficSignsDetector | Detector/detector_com_ids.py | detector_com_ids.py | py | 3,255 | python | pt | code | 0 | github-code | 36 | [
{
"api_name": "ultralytics.YOLO",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "cv2.VideoCapture",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "os.path.exists",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_n... |
43205799120 |
import pandas as pd
import numpy as np
import sqlite3
from datetime import timedelta
import matplotlib.pyplot as plt
import pandas as pd
from copy import deepcopy
from ipywidgets import IntProgress
import warnings
warnings.filterwarnings(action='ignore', category=FutureWarning) # setting ignore as a parameter and further adding category
def percentile(n):
'''Calculate n - percentile of data'''
def percentile_(x):
return np.percentile(x, n)
percentile_.__name__ = 'pctl%s' % n
return percentile_
def fill_missing_dates(x, date_col):
min_date, max_date = x[date_col].min(), x[date_col].max()
groupby_day = x.groupby(pd.PeriodIndex(x[date_col], freq='D'))
results = groupby_day.sum(min_count=1).sort_values(by=date_col)
return results
idx = pd.period_range(min_date, max_date)
results = results.reindex(idx, fill_value=np.nan)
results.index.rename(date_col, inplace=True)
return results
def calc_preag_fill(data, group_col, date_col, target_cols, preagg_method):
## calc preaggregation
data_preag = data.groupby(group_col).agg(
preagg_method)[target_cols].reset_index().sort_values(by=date_col)
## fill missing dates
data_preag_filled = data_preag.groupby(group_col[:-1]).apply(
fill_missing_dates, date_col=date_col).drop(group_col[:-1],
axis=1).reset_index()
## return DataFrame with calculated preaggregation and filled missing dates
return data_preag_filled
def calc_ewm(data_preag_filled, group_col, date_col, span):
## calc ewm stats
lf_df_filled = data_preag_filled.groupby(group_col[:-1]). apply(lambda x: x.set_index(date_col).ewm(span=span).mean()).drop(group_col[:-1], axis=1)
## return DataFrame with rolled columns from target_vars
return lf_df_filled
def shift(lf_df_filled, group_col, date_col, lag):
lf_df = lf_df_filled.groupby(
level=group_col[:-1]).apply(lambda x: x.shift(lag)).reset_index()
lf_df[date_col] = pd.to_datetime(lf_df[date_col].astype(str))
## return DataFrame with following columns: filter_col, id_cols, date_col and shifted stats
return lf_df
def calc_rolling(data_preag_filled, group_col, date_col, method, w):
## calc rolling stats
lf_df_filled = data_preag_filled.groupby(group_col[:-1]). apply(lambda x: x.set_index(date_col).rolling(window=w, min_periods=1).agg(method)).drop(group_col[:-1], axis=1)
## return DataFrame with rolled columns from target_vars
return lf_df_filled
def day_features(result2):
result2["weekday"] = result2.period_dt.dt.weekday
result2["monthday"] = result2.period_dt.dt.day
result2['is_weekend'] = result2.weekday.isin([5,6])*1
return result2
def generate_lagged_features(
data: pd.DataFrame,
target_cols: list = ['Demand'],
id_cols: list = ['SKU_id', 'Store_id'],
date_col: str = 'Date',
lags: list = [7, 14, 21, 28],
windows: list = ['7D', '14D', '28D', '56D'],
preagg_methods: list = ['mean'],
agg_methods: list = ['mean', 'median', percentile(10), pd.Series.skew],
dynamic_filters: list = ['weekday', 'Promo'],
ewm_params: dict = {'weekday': [14, 28], 'Promo': [14, 42]}) -> pd.DataFrame:
'''
data - dataframe with default index
target_cols - column names for lags calculation
id_cols - key columns to identify unique values
date_col - column with datetime format values
lags - lag values(days)
windows - windows(days/weeks/months/etc.),
calculation is performed within time range length of window
preagg_methods - applied methods before rolling to make
every value unique for given id_cols
agg_methods - method of aggregation('mean', 'median', percentile, etc.)
dynamic_filters - column names to use as filter
ewm_params - span values(days) for each dynamic_filter
'''
data = data.sort_values(date_col)
out_df = deepcopy(data)
dates = [min(data[date_col]), max(data[date_col])]
total = len(target_cols) * len(lags) * len(windows) * len(preagg_methods) * len(agg_methods) * len(dynamic_filters)
progress = IntProgress(min=0, max=total)
display(progress)
for filter_col in dynamic_filters:
group_col = [filter_col] + id_cols + [date_col]
for lag in lags:
for preagg in preagg_methods:
data_preag_filled = calc_preag_fill(data, group_col, date_col,
target_cols, preagg)
## add ewm features
for alpha in ewm_params.get(filter_col, []):
#print("%s %s %s %s" % (filter_col, lag, preagg, alpha))
ewm_filled = calc_ewm(data_preag_filled, group_col,
date_col, alpha)
ewm = shift(ewm_filled, group_col, date_col, lag)
new_names = {x: "{0}_lag{1}d_alpha{2}_{3}". format(x, lag, alpha, filter_col) for x in target_cols}
out_df = pd.merge(out_df,
ewm.rename(columns=new_names),
how='outer',
on=group_col)
## add rolling features
for w in windows:
for method in agg_methods:
rolling_filled = calc_rolling(data_preag_filled,
group_col, date_col,
method, w)
## lf_df - DataFrame with following columns: filter_col, id_cols, date_col, shifted rolling stats
rolling = shift(rolling_filled, group_col, date_col,
lag)
method_name = method.__name__ if type(
method) != str else method
new_names = {x: "{0}_lag{1}d_w{2}_{3}". format(x, lag, w, filter_col) for x in target_cols}
out_df = pd.merge(out_df,
rolling.rename(columns=new_names),
how='outer',
on=group_col)
progress.value += 1
return out_df
def preABT_modification(data : pd.DataFrame) -> (pd.DataFrame):
target_cols = ['TGT_QTY']
id_cols = ['PRODUCT_ID', 'LOCATION_ID']
date_col = 'PERIOD_DT'
built_in_funcs = [pd.Series.kurtosis, pd.Series.skew]
# flts = {'Promo': {'oprm':'>0', 'npromo':'==0', 'aprm':'>-1'}, 'weekday' : {'md':'==0', 'tue':'==1', 'wd':'==2', 'th':'==3', 'fr':'==4', 'sa':'==5', 'su':'==6', 'anyday':'>-1'}}
data['NoFilter'] = 1
data_lagged_features = generate_lagged_features(data
, target_cols = target_cols
, id_cols = id_cols
, date_col = date_col
, lags = [22, 28, 35]
, windows = ['14D', '21D', '28D', '56D']
, preagg_methods = ['sum'] # ['mean', 'count']
, agg_methods = ['mean'] #, percentile(10), percentile(90)]
, dynamic_filters = ['PROMO_FLG', 'NoFilter']
, ewm_params={'NoFilter': [14, 28], 'PROMO_FLG': [14, 28]}
)
return data_lagged_features
| MaksimSavinov/demand_forecasting_pipeline | Pipeline/preABT.py | preABT.py | py | 7,729 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "warnings.filterwarnings",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "numpy.percentile",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "pandas.PeriodIndex",
"line_number": 27,
"usage_type": "call"
},
{
"api_name": "pandas.pe... |
19293482431 | """Parameter Store Loader
Use (setting_name, cast function) or setting_name as lookup value.
If no cast function is passed, the parameter will be stored as retrieved
from Parameter Store, typically string or stringList.
Usage:
from awstanding.parameter_store import load_parameters
LOOKUP_DICT = {
'/my/parameter/path': 'NEW_VARIABLE'
}
load_parameters(LOOKUP_DICT)
# Now NEW_VARIABLE can be obtained from environment variables.
"""
import os
from typing import Union, Iterable
import boto3
from boto3.exceptions import Boto3Error
from botocore.exceptions import BotoCoreError, ClientError
from .exceptions import ParameterNotFoundException
_ssm_client = boto3.client(service_name='ssm')
def load_parameters(lookup_dict: dict, allow_invalid=True) -> dict:
"""
Loads each parameter defined in the lookup_dict as env. variables.
The lookup_dict should look like this:
{
'/path/to/parameter1': 'PARAMETER_AS_ENV_VAR_1',
'/path/to/parameter2': 'PARAMETER_AS_ENV_VAR_2',
...
'/path/to/parameterN': 'PARAMETER_AS_ENV_VAR_N',
}
The values (Env. variables names) could be anything you want.
It returns the loaded parameters for debugging purposes
"""
paginated_keys = (list(lookup_dict.keys())[i:i+10] for i in range(0, len(lookup_dict), 10))
parameters_ps = []
invalid_parameters = []
for keys in paginated_keys:
parameters_page = _ssm_client.get_parameters(Names=keys, WithDecryption=True)
parameters_ps += parameters_page['Parameters']
invalid_parameters += parameters_page['InvalidParameters']
if invalid_parameters and not allow_invalid:
raise ParameterNotFoundException(invalid_parameters)
parameters_ps = {param['Name']: param['Value'] for param in parameters_ps}
# Override configuration for requested keys
for key in parameters_ps:
if isinstance(lookup_dict[key], (tuple, list)):
setting_name, cast = lookup_dict[key]
os.environ[setting_name] = cast(parameters_ps[key])
elif isinstance(lookup_dict[key], str):
os.environ[lookup_dict[key]] = parameters_ps[key]
return parameters_ps
def load_path(*paths: Union[Iterable[str], str]) -> dict:
"""
Loads each parameter behind `paths` recursively as env. variables.
It returns the loaded parameters for debugging purposes
"""
all_parameters = {}
for path in paths:
parameters_page = _ssm_client.get_parameters_by_path(Path=path, Recursive=True)
parameters_ps = parameters_page['Parameters']
while parameters_page.get('NextToken'):
parameters_page = _ssm_client.get_parameters_by_path(Path=path, Recursive=True, NextToken=parameters_page.get('NextToken'))
parameters_ps += parameters_page['Parameters']
parameters_ps = {param['Name']: param['Value'] for param in parameters_ps}
all_parameters.update(**parameters_ps)
# Override configuration for requested keys
for key in parameters_ps:
os.environ[key.strip('/')
.replace('/', '_')
.replace('-', '_')
.upper()
] = parameters_ps[key]
return all_parameters
class DynamicParameter(object):
@property
def _value(self):
try:
parameter_page = _ssm_client.get_parameter(Name=self.key, WithDecryption=True)
except (ClientError, Boto3Error, BotoCoreError):
if self.fail_on_boto_error:
raise
else:
return ''
else:
return parameter_page['Parameter']['Value']
def __init__(self, key, fail_on_boto_error=True, *args, **kwargs):
super().__init__()
self.key = key
self.fail_on_boto_error = fail_on_boto_error
def __eq__(self, other):
return self._value == other
def __len__(self, other):
return len(self._value)
def __add__(self, other):
return self._value + other
def __radd__(self, other):
return other + self._value
def __unicode__(self):
return str(self._value)
def __str__(self):
return str.__str__(self._value)
def __repr__(self):
return str.__repr__(self._value)
| jiss2891/awstanding | src/awstanding/parameter_store.py | parameter_store.py | py | 4,272 | python | en | code | 13 | github-code | 36 | [
{
"api_name": "boto3.client",
"line_number": 27,
"usage_type": "call"
},
{
"api_name": "exceptions.ParameterNotFoundException",
"line_number": 53,
"usage_type": "call"
},
{
"api_name": "os.environ",
"line_number": 61,
"usage_type": "attribute"
},
{
"api_name": "os... |
2123056410 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 7 20:18:11 2018
@author: tanthanhnhanphan
MECH2700: Assignment 2
"""
import matplotlib.pyplot as plt
from numpy import *
from math import *
D = 100*10**3 #Dynamic Pressure
Ly = 1 #m
Lx = 5 #m
a = 20*pi/180
E = 70*10**9 #Young's Modulus
S = 96.5#Fatigue strength Mpa
Izz = 5*10**-5 #m4
ymax = 0.05 #m
FOS = 1.2
def q(i, n):
load = D*Ly*sin(a)*(1-(i*Lx/n)**2/Lx**2)
return load
"""
def x(n):
for i in range(n+1):
xx = i*Lx/n
print(xx)
print(x(7))
"""
"""
A = array([[7, -4, 1, 0, 0, 0, 0],
[-4, 6, -4, 1, 0, 0, 0],
[1, -4, 6, -4, 1, 0, 0],
[0, 1, -4, 6, -4, 1, 0],
[0, 0, 1, -4, 6, -4, 1],
[0, 0, 0, 1, -4, 5, -2],
[0, 0, 0, 0, 2, -4, 2]], float)
"""
#trial
"""
def s(n):
space = Lx/n
return space
h = s(7)
"""
#c = array([[q(1,7), q(2,7), q(3,7), q(4,7), q(5,7), q(6,7), q(7,7)]])*h**4/(E*Izz)
#b
#print(linspace(0,5,7))
def rhs(n):
h= Lx/n
q_1 = D*Ly*sin(a)*(1-(Lx/n)**2/Lx**2)*h**4/(E*Izz)
load = array([[q_1]])
#print(D*Ly*sin(a)*(1-(Lx/n)**2/Lx**2))
for i in range(2, n+1):
q_i = D*Ly*sin(a)*(1-(i*Lx/n)**2/Lx**2)*h**4/(E*Izz)
#print(D*Ly*sin(a)*(1-(i*Lx/n)**2/Lx**2))
#print(i*Lx/n)
load = vstack((load, [[q_i]]))
return load
"""
def rhs_1(n):
h = Lx/n
x = linspace(1,5,n)
q_1 = D*Ly*sin(a)*(1-(x[1]**2/Lx**2)*h**4/(E*Izz))
load = array([[q_1]])
print(load)
print(x)
#for i in range(n+1):
q_i = D*Ly*sin(a)*(1-x**2/Lx**2)*h**4/(E*Izz)
print(q_i)
#load = vstack((load, [[q_i]]))
#load = vstack((load, q_i))
return load
"""
#print("RHS",rhs(7))
#b = c.transpose()
def deflection(n):
w = zeros((n,n))
w[0,0] = 7
w[n-2, n-2] = 5
w[n-2, n-1] = -2
w[n-1, n-3] = 2
w[n-1, n-1] = 2
for k in range(0,n-1):
w[k+1, k] = -4
for k in range(0, n-3):
w[k+1,k+1] = 6
for k in range(0, n-2):
w[k, k+2] = 1
for k in range(0, n-3):
w[k+2,k] = 1
for k in range(0, n-2):
w[k, k+1] = -4
return w
#print(deflection((7)))
#print("~~~~")
#print(b)
#Direct Solver Gauss-Jordan Elimination
def solve(A,b, testmode = True):
"""
Input:
A: nxn matrix of coefficients
b: nx1 matrix of rhs values
Output:
x: solutions of Ax=b
"""
nrows, ncols = A.shape
c = hstack([A,b])
#print(c)
for j in range(0, nrows):
p = j
for i in range(j+1, nrows):
#Select pivot
if abs(c[i,j]) > abs(c[p,j]): p = i
#Swap the rows
c[p,:], c[j,:] = c[j,:].copy(), c[p,:].copy()
#Elimination
c[j,:] = c[j,:]/c[j,j]
for i in range(0,nrows):
if i!=j:
c[i,:] = c[i,:] - c[i,j]*c[j,:]
I, x = c[:,nrows], c[:,-1]
return x
Alist = []
Blist = []
Clist = []
Dlist = []
Elist = []
rhslist = []
def solve_optimise(A,b):
nrows, ncols = A.shape
c = hstack([A,b])
print(b)
#b.tolist()
#print(b)
#print(c)
for i in range(n-2):
Alist.append(A[i, i+2])
for i in range(n-1):
Blist.append(A[i, i+1])
for i in range(n):
Clist.append(A[i,i])
for i in range(n-1):
Dlist.append(A[i+1, i])
for i in range(n-2):
Elist.append(A[i+2, i])
for i in range(n):
rhslist.append(b[i,0])
rhslistcopy = rhslist.copy()
"""
alpha = []
mu = []
gamma = []
beta = []
z = []
mu_1 = Clist[0]
alpha_1 = Blist[0]/mu_1
beta_1 = Alist[0]/mu_1
z_1 = rhslist[0]/mu_1
gamma_2 = Dlist[0]
mu_2 = Clist[1] - alpha_1*gamma_2
alpha_2 = (Blist[1]-beta_1*gamma_2)/mu_2
beta_2 = Alist[1]/mu_2
z_2 = (rhslist[1]-z_1*gamma_2)/mu_2
alpha_minus2 = alpha_1
alpha.append(alpha_1)
alpha.append(alpha_2)
mu.append(mu_1)
mu.append(mu_2)
gamma.append(gamma_2)
beta.append(beta_1)
z.append(z_1)
z.append(z_2)
print(gamma)
for i in range(3, n-3):
gamma_i = Dlist[i-2] - alpha[i-3]*Elist[i-3]
mu_i = Clist[i-2] - beta[i-3]*Elist[i-3] - alpha[i-2]*gamma[i-2]
beta_i = Alist[i-2]/mu_i
gamma.append(gamma_i)
beta.append(beta_i)
z_i = (rhslist[i-1]-z[i-3])
"""
print(Alist)
print(Blist)
print(Clist)
print(Dlist)
print(Elist)
print(rhslist)
for i in range(n-1):
multiplier_1 = Dlist[i]/Clist[i]
#print('multi ',multiplier_1)
#print(multiplier_1)
#Dlist[i] = Dlist[i] - multiplier_1*Clist[i]
#print('before ', rhslist[i+1])
#rhslist[i+1] = rhslistcopy[i+1] - multiplier_1*rhslistcopy[i]
#print('after', rhslist[i+1])
#print(rhslist)
#print(rhslistcopy)
#print('~~~')
for i in range(n-2):
multiplier_2 = Elist[i]/Clist[i]
#print('multi ', multiplier_2)
#print(multiplier_2)
Elist[i] = Elist[i] - multiplier_2*Clist[i]
#print('Before ',rhslist[i+2])
#rhslist[i+2] = rhslist[i+2] - multiplier_2*rhslistcopy[i]
#print('After ', rhslist[i+2])
print(Dlist)
print(Elist)
#print(rhslist)
#print(Clist[n-1])
#x_n = rhslist[n-1]/Clist[n-1]
#print(x_n)
#for i in reversed(range(n)):
#print(i)
#for i in range(n-1):
#print(multiplier_1)
#print(Alist)
return
solve_optimise(deflection(n), rhs(n))
#print(A)
#print(c)
#print(x)
#print(solve(deflection(280),rhs(280)))
for i in [7,14,28,280]:
A = deflection(i)
b = rhs(i)
x = solve(A,b)
xx= append(0, x)
position = []
for j in range(0,i+1):
position.append(j*Lx/i)
#print(position)
plt.plot(position, xx, label=i)
plt.xlabel('x(m)')
plt.ylabel('Deflection (m)')
plt.legend()
plt.show()
space = []
free_end_deflection = []
node = []
n = 280
#print(deflection(n))
#print(rhs(n))
sol = solve(deflection(n),rhs(n))
#print(sol)
sol_free_end = sol[[n-1]]
#print("Solution",sol_free_end)
for i in range(7, 50):
A = deflection(i)
b = rhs(i)
x = solve(A,b)
xx = x[[i-1]]
free_end_deflection.append(xx)
node.append(i)
h = Lx/i
space.append(h)
if abs(xx - sol_free_end) < 0.1/100*sol_free_end:
print(i)
break
#print(xx)
#print(h)
#print(space)
plt.plot(space, free_end_deflection)
plt.show()
def moment_stress(n):
A = deflection(n)
b = rhs(n)
x = solve(A,b)
h = Lx/n
#M_0 = E*Izz/(h**2)*(x[1]-2*x[0])
M_1 = E*Izz/(h**2)*(x[1] - 2*x[0])
#M = array([M_0])
#M = hstack((M, [M_1]))
M = array([M_1])
#Stress
#sigma_0 = M_0*ymax/Izz*10**-6
sigma_1 = M_1*ymax/Izz*10**-6
#sigma = array([sigma_0])
#sigma = hstack((sigma, sigma_1))
sigma = array([sigma_1])
#print(M)
for i in range(1,n-1):
M_i = E*Izz/(h**2)*(x[[i+1]]- 2*x[i] + x[i-1])
sigma_i = M_i*ymax/Izz*10**-6
#print(M_i)
M = hstack((M, M_i))
sigma = hstack((sigma, sigma_i))
#load = vstack((load, [[q_i]]))
M = hstack((M, [0]))
sigma = hstack((sigma, [0]))
position = []
for j in range(1, n+1):
position.append(j*Lx/n)
print(max(sigma))
#print(sigma[1])
print(len(position))
print(len(M))
Izz_new = max(M)*ymax*FOS/(S*10**6)*10**5
print("Izz hey baby cum at me",Izz_new)
plt.plot(position, M)
plt.title('Bending moment vs. length')
plt.xlabel('x (m)')
plt.ylabel('Bending moment (Nm)')
plt.show()
plt.plot(position, sigma)
plt.title('Bending stress vs. length')
plt.xlabel('x (m)')
plt.ylabel('Bending stress (MPa)')
plt.show()
#print(M)
return
moment_stress(17)
#print('RHS: ',rhs(7))
#print('RHS 1: "',rhs_1(7))
#print(rhs(7))
"""
#First line of matrix
import time
A = deflection(n)
b = rhs(n)
##################Computation time using optimised solver######################
start_op = time.time()
deflect_op = solve(A, b)
end_op = time.time()
compute_time_op = end_op - start_op
print("Computation time using optimised solver:", compute_time_op)
###############Computation time using numpy in-built solver#####################
start = time.time()
deflect = np.linalg.solve(A, b)
end = time.time()
compute_time = end - start
print("Computation time using numpy in-built solver:", compute_time)
###############Computation time using Gauss-Jordan solver#######################
start_g = time.time()
deflect_g = solve(A, b)
end_g = time.time()
compute_time_g = end_g - start_g
print("Computation time using Gauss-Jordan solver:", compute_time_g)
print("Does the solver work? \n", check(deflect_op, deflect))
"""
| oncernhan/MECH2700 | assignment2.py | assignment2.py | py | 8,879 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "matplotlib.pyplot.plot",
"line_number": 263,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot",
"line_number": 263,
"usage_type": "name"
},
{
"api_name": "matplotlib.pyplot.xlabel",
"line_number": 264,
"usage_type": "call"
},
{
"api_name": "... |
75312916265 | """
Usage:
trajectory.py <path> <start_time> <resolution> <x0> <y0> <z0> <t0> [<output_path>]
trajectory.py (-h | --help)
Arguments:
<path>
<start_time>
<resolution>
Options:
-h --help
Show this screen.
"""
import datetime
import warnings
import numpy as np
from twinotter.util.scripting import parse_docopt_arguments
from pylagranto import caltra
from pylagranto.datasets import MetUMStaggeredGrid
from moisture_tracers import grey_zone_forecast
trajectory_filename = "{start_time}_{resolution}_{x0}E_{y0}N_{z0}{units}_" \
"T+{lead_time:02d}.pkl"
# Inner-domain centre: x0=302.5, y0=13.5, t0=48
# HALO: x0=302.283, y0=13.3
# Ron Brown (2nd Feb): x0=305.5, y0=13.9
# 24th Jan Case study:
# x0=302.5, y0=11.75, t0=T+24h
# x0=310.0, y0=15.0, t0=T+48h
def _command_line_interface(path, start_time, resolution, x0, y0, z0, t0, output_path="./"):
forecast = grey_zone_forecast(
path, start_time, resolution=resolution, grid=None, lead_times=range(1, 48 + 1)
)
traout = calculate_trajectory(
forecast, float(x0), float(y0), float(z0), int(t0), "height_above_reference_ellipsoid"
)
traout.save(
output_path + trajectory_filename.format(
start_time=forecast.start_time.strftime("%Y%m%d"),
resolution=resolution,
x0=format_float_for_file(x0),
y0=format_float_for_file(y0),
z0=format_float_for_file(z0),
t0=t0,
units="m",
)
)
def calculate_trajectory(forecast, x0, y0, z0, t0, zcoord):
levels = (zcoord, [z0])
trainp = np.array([[x0, y0, z0]])
times = list(forecast._loader.files)
datasource = MetUMStaggeredGrid(forecast._loader.files, levels=levels)
time_traj = forecast.start_time + datetime.timedelta(hours=t0)
if time_traj == times[0]:
traout = caltra.caltra(
trainp, times, datasource, tracers=["x_wind", "y_wind"]
)
elif time_traj == times[-1]:
traout = caltra.caltra(
trainp, times, datasource, fbflag=-1, tracers=["x_wind", "y_wind"]
)
else:
times_fwd = [time for time in times if time <= time_traj]
traout_fwd = caltra.caltra(
trainp, times_fwd, datasource, tracers=["x_wind", "y_wind"]
)
times_bck = [time for time in times if time >= time_traj]
traout_bck = caltra.caltra(
trainp, times_bck, datasource, fbflag=-1, tracers=["x_wind", "y_wind"]
)
traout = traout_bck + traout_fwd
return traout
def format_float_for_file(x):
# Replace decimal point with a p (copying what was done for the UM files)
return str(x).replace(".", "p")
if __name__ == "__main__":
warnings.filterwarnings("ignore")
parse_docopt_arguments(_command_line_interface, __doc__)
| leosaffin/moisture_tracers | moisture_tracers/trajectory.py | trajectory.py | py | 2,859 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "moisture_tracers.grey_zone_forecast",
"line_number": 40,
"usage_type": "call"
},
{
"api_name": "numpy.array",
"line_number": 63,
"usage_type": "call"
},
{
"api_name": "pylagranto.datasets.MetUMStaggeredGrid",
"line_number": 66,
"usage_type": "call"
},
{... |
1412530570 | from flask import Flask,render_template,flash,redirect,session,url_for,logging,request,Blueprint,json,session
from flask_json import FlaskJSON, JsonError, json_response, as_json
from smartiot.bin.config.db_config import mysql
from smartiot.routes.route_Permissions.userPermissions import getPermissions
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
import time
iot_ultraSonic_bp = Blueprint(
'iot_ultra-sonic_bp',
__name__
)
#define led oin
led_pin = 7
@iot_ultraSonic_bp.route("/ultra",methods=['POST'])
def ultraSonic():
try:
content = request.get_json()
action = content['action']
userid = content['userId']
endpoint = content['endPoint']
except:
#response
return json_response(
message="Internal server error",
status = 500
)
permissions = getPermissions(userid,endpoint)
print(str(permissions))
if permissions is "granted":
print('granted')
if action == "measure":
#mysql
#execute query
sql ="INSERT INTO logs(info,value,dataType,deviceName,deviceId,userId) VALUES('',%s,%s,%s,'2',%s)"
#print(str(sql))
#get data from sensor
distance = measure()
d=round(distance ,2)
distance_cm = format(d)
# print( "Distance : {0} cm".distance_cm)
#create a cursur
cur = mysql.connection.cursor()
result = cur.execute(sql,(distance_cm,"proximity",endpoint,userid))
#commit to Datebase
mysql.connection.commit()
return json_response(
distance = distance,
message = "Distance in cm",
status =200
)
if action == "":#other fuctions
#mysql
#execute query
sql ="INSERT INTO logs(info,value,dataType,deviceName,deviceId,userId) VALUES('',%s,%s,%s,'1',%s)"
print(str(sql))
#create a cursur
cur = mysql.connection.cursor()
result = cur.execute(sql,("on","state",endpoint,userid))
#commit to Datebase
mysql.connection.commit()
#close connection
cur.close()
GPIO.cleanup()
return
print('granted')
if permissions is "denied":
#mysql
#execute query
sql ="INSERT INTO logs(info,value,dataType,deviceName,deviceId,userId) VALUES(%s,'','',%s,'1',%s)"
print(str(sql))
#create a cursur
cur = mysql.connection.cursor()
result = cur.execute(sql,("Permission Denied",endpoint,userid))
#commit to Datebase
mysql.connection.commit()
#close connection
cur.close()
#response
return json_response(
distance = "",
message="Permission denied for this user",
status = 403
)
print('denied')
# measure distance
def measure():
GPIO.setmode(GPIO.BCM)
TRIG = 4
ECHO = 18
GPIO.setup(TRIG , GPIO.OUT)
GPIO.setup(ECHO , GPIO.IN)
GPIO.output(TRIG , True)
time.sleep(0.0001)
GPIO.output(TRIG , False)
while GPIO.input(ECHO) == False:
start = time.time();
while GPIO.input(ECHO) == True:
end = time.time();
sig_time = end-start
#cm:
dis = sig_time/0.000058
print('Dist : {} cm'.format(dis))
GPIO.cleanup()
return dis
def measure_average():
# This function takes 3 measurements and
# returns the average.
distance1=measure()
time.sleep(0.1)
distance2=measure()
time.sleep(0.1)
distance3=measure()
distance = distance1 + distance2 + distance3
distance_avg = distance / 3
return distance_avg
| Singh-Kiran-P/smart-iot-python-api | smartiot/routes/iot/ultraSonic.py | ultraSonic.py | py | 3,894 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "flask.Blueprint",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "flask.request.get_json",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "flask.request",
"line_number": 20,
"usage_type": "name"
},
{
"api_name": "flask_json.json_r... |
75263426665 | """
@Time : 30/03/2023
@Author : qinghua
@Software: PyCharm
@File : process_data.py
"""
import os.path
import pickle
import lgsvl
import pandas as pd
import json
from config import Config
from tqdm import tqdm
"""Processing deep scenario data"""
def get_ds_data(runner):
"""pair paths of scenarios and scenario attributes"""
scene_attr_path_pairs = []
for root, dirs, files in os.walk(Config.scenario_dir):
depth = root.count(os.path.sep)
if depth == 4:
scenario_dirs = sorted([os.path.join(root, name) for name in os.listdir(root) if not name.endswith(".csv")])
attribute_fnames = sorted([os.path.join(root, name) for name in os.listdir(root) if name.endswith(".csv")])
scene_attr_path_pairs += list(zip(scenario_dirs, attribute_fnames))
"""
pair contents of scenarios and scenario attributes by each run
Output Example:
[
# run 0
[
# timestep 0
(
# variables
[1.2,2.1,...]
# attribute
{"ttc":xxx,"tto":xxx}
)
# timestep 1
....
]
# run 1
....
]
"""
print(scene_attr_path_pairs)
greedy_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
"greedy-strategy" in scene_dir]
random_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
"random-strategy" in scene_dir]
rl_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
"rl_based-strategy" in scene_dir]
dto_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
"reward-dto" in scene_dir]
jerk_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
"reward-jerk" in scene_dir]
ttc_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
"reward-ttc" in scene_dir]
greedy_ttc_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
"greedy-strategy" in scene_dir and "reward-ttc" in scene_dir]
random_ttc_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
"random-strategy" in scene_dir and "reward-ttc" in scene_dir]
rl_ttc_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
"rl_based-strategy" in scene_dir and "reward-ttc" in scene_dir]
r1_ttc_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
"road1" in scene_dir and "reward-ttc" in scene_dir]
r2_ttc_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
"road2" in scene_dir and "reward-ttc" in scene_dir]
r3_ttc_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
"road3" in scene_dir and "reward-ttc" in scene_dir]
r4_ttc_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
"road4" in scene_dir and "reward-ttc" in scene_dir]
all_runs = get_all_runs(scene_attr_path_pairs)
greedy_runs = get_all_runs(greedy_pairs)
random_runs = get_all_runs(random_pairs)
rl_runs = get_all_runs(rl_pairs)
dto_runs = get_all_runs(dto_pairs)
jerk_runs = get_all_runs(jerk_pairs)
ttc_runs = get_all_runs(ttc_pairs)
greedy_ttc_runs = get_all_runs(greedy_ttc_pairs)
random_ttc_runs = get_all_runs(random_ttc_pairs)
rl_ttc_runs = get_all_runs(rl_ttc_pairs)
r1_ttc_runs = get_all_runs(r1_ttc_pairs)
r2_ttc_runs = get_all_runs(r2_ttc_pairs)
r3_ttc_runs = get_all_runs(r3_ttc_pairs)
r4_ttc_runs = get_all_runs(r4_ttc_pairs)
return all_runs, greedy_runs, random_runs, rl_runs, dto_runs, jerk_runs, ttc_runs, greedy_ttc_runs, random_ttc_runs, rl_ttc_runs, r1_ttc_runs, r2_ttc_runs, r3_ttc_runs, r4_ttc_runs
def get_all_runs(scene_attr_path_pairs):
all_runs = []
clean_key = lambda k: k.replace("Attribute[", "").replace("]", "")
for scene_dir, attr_path in tqdm(scene_attr_path_pairs):
runs = [[] for _ in range(20)]
# get scenario attributes
attr_pdf = pd.read_csv(attr_path)
for row_id, row in attr_pdf.iterrows():
run_id = int(row["Execution"])
scene_fname = row["ScenarioID"] + ".deepscenario"
attrs = row.to_dict()
attrs = {clean_key(k): v for k, v in attrs.items()}
runner.load_scenario_file(os.path.join(scene_dir, scene_fname))
for i in range(1, 7):
timeframe = runner.get_scene_by_timestep(timestep=i)
timeframe = json.loads(timeframe)
runs[run_id].append([timeframe, attrs])
all_runs += runs
return all_runs
class Vocab:
def __init__(self):
super(Vocab, self).__init__()
self.id2str = []
self.str2id = {}
def add_if_not_exist(self, s):
if s not in self.str2id:
self.str2id[s] = len(self.id2str)
self.id2str.append(s)
def tokenize(self, s):
return self.str2id[s]
def size(self):
return len(self.id2str)
def build_vocab(str_list):
vocab = Vocab()
for s in str_list:
vocab.add_if_not_exist(s)
return vocab
"""Process elevator data"""
def get_ele_passenger_profiles(fname):
"""
Arrival Time; Arrival Floor; Destination Floor; Mass; Capacity;Loading time; Unloading time;Placeholder
:param fname:
:return:
"""
colnames = ["arrival_time", "arrival_floor", "destination_floor", "mass", "capacity", "loading_time",
"unloading_time", "placeholder"]
pdf = pd.read_csv(fname, header=None, names=colnames, index_col=False)
pdf = pdf[colnames[:-1]] # remove last column
pdf["arrival_time"] = pdf["arrival_time"].astype("float")
pdf["arrival_floor"] = pdf["arrival_floor"].astype("int")
pdf["destination_floor"] = pdf["destination_floor"].astype("int")
return pdf
def get_ele_simulator_result(fname):
"""
Document;Passenger;Source;Destination;ArrivalTime;LiftArrivalTime;DestinationArrivalTime
"""
colnames = ["document", "id", "arrival_floor", "destination_floor", "arrival_time", "lift_arrival_time",
"lift_destination_time"]
pdf = pd.read_csv(fname, names=colnames, delimiter=";", skiprows=1)
pdf = pdf[colnames[2:-1]]
pdf["arrival_time"] = pdf["arrival_time"].astype("float")
pdf["arrival_floor"] = pdf["arrival_floor"].astype("int")
pdf["destination_floor"] = pdf["destination_floor"].astype("int")
return pdf
def get_ele_data(dispatcher, peak_type):
"""
:param dispatcher: list of integers
:param peak_type: ["lunchpeak","uppeak"]
:return: joined data of profiles and results
"""
print(dispatcher, peak_type)
peak_type = "LunchPeak" if "lunch" in peak_type.lower() else "Uppeak"
profile_dir = Config.lunchpeak_profile_dir if peak_type == "LunchPeak" else Config.uppeak_profile_dir
dispatcher_name = "Dispatch_00" if dispatcher == 0 else "Dispatch_M{:2d}".format(dispatcher)
result_dir = os.path.join(Config.result_dir, dispatcher_name)
if not os.path.exists(result_dir):
return False
result_pdfs = []
for i in range(10):
n_variable = "4" if peak_type == "LunchPeak" else "Four"
profile_fname = "{}_mass_capacity_loading_unloading(CIBSE-office-{}){}.txt".format(n_variable, peak_type, i)
result_fname = "{}_mass_capacity_loading_unloading(CIBSE-office-{}){}.csv".format(n_variable, peak_type, i)
profile_pdf = get_ele_passenger_profiles(os.path.join(profile_dir, profile_fname))
result_pdf = get_ele_simulator_result(os.path.join(result_dir, result_fname))
result_pdf = profile_pdf.merge(result_pdf, how="right",
on=["arrival_time", "arrival_floor", "destination_floor"])
result_pdfs.append(result_pdf)
result_pdf = pd.concat(result_pdfs)
result_fname = "Dispatcher_{:2d}_{}.pkl".format(dispatcher, peak_type)
pickle.dump(result_pdf,
open( os.path.join(Config.elevator_save_dir, result_fname),"wb")
)
return result_pdf
if __name__ == '__main__':
"""collect data by runs"""
# runner = lgsvl.scenariotoolset.ScenarioRunner()
# all_runs, greedy_runs, random_runs, rl_runs, dto_runs, jerk_runs, ttc_runs, greedy_ttc_runs, random_ttc_runs, rl_ttc_runs, r1_ttc_runs, r2_ttc_runs, r3_ttc_runs, r4_ttc_runs = get_ds_data(
# runner)
# pickle.dump(all_runs, open(Config.all_runs_pkl_path, "wb"))
# pickle.dump(greedy_runs, open(Config.greedy_runs_pkl_path, "wb"))
# pickle.dump(random_runs, open(Config.random_runs_pkl_path, "wb"))
# pickle.dump(rl_runs, open(Config.rl_runs_pkl_path, "wb"))
# pickle.dump(dto_runs, open(Config.dto_runs_pkl_path, "wb"))
# pickle.dump(jerk_runs, open(Config.jerk_runs_pkl_path, "wb"))
# pickle.dump(rl_runs, open(Config.rl_runs_pkl_path, "wb"))
# pickle.dump(random_ttc_runs, open(Config.random_ttc_runs_pkl_path, "wb"))
# pickle.dump(greedy_ttc_runs, open(Config.greedy_ttc_runs_pkl_path, "wb"))
# pickle.dump(rl_ttc_runs, open(Config.rl_ttc_runs_pkl_path, "wb"))
# pickle.dump(r1_ttc_runs, open(Config.r1_ttc_runs_pkl_path, "wb"))
# pickle.dump(r2_ttc_runs, open(Config.r2_ttc_runs_pkl_path, "wb"))
# pickle.dump(r3_ttc_runs, open(Config.r3_ttc_runs_pkl_path, "wb"))
# pickle.dump(r4_ttc_runs, open(Config.r4_ttc_runs_pkl_path, "wb"))
# process elevator data
ele_names = ["dispatch_00_lunchpeak", "dipatcher_00_uppeak"]
ele_names += ["dispatcher_{:02d}_lunchpeak_variant".format(i) for i in range(1, 100)]
ele_names += ["dispatcher_{:02d}_uppeak_variant".format(i) for i in range(1, 100)]
peak_types = ["lunchpeak", "uppeak"]
for i in range(100):
for peak_type in peak_types:
pdf = get_ele_data(i, peak_type)
| qhml/ppt | process_data.py | process_data.py | py | 10,320 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "os.path.walk",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 23,
"usage_type": "name"
},
{
"api_name": "config.Config.scenario_dir",
"line_number": 23,
"usage_type": "attribute"
},
{
"api_name": "config.Config",
... |
523657887 | #REGINALD HUEY TAN IAN JAY (S10239913) - IT01 (P01)
#============================== IMPORTING RESOURCES ===============================
import random, math, time
import os, asyncio
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide" #hide pygame initialisation message
from pygame import mixer
from S10239913E_Assignment_gameData import game_vars, defender_list, monster_list, defenders, monsters, alphabet, field, turnEvents
#=============================== GAME FUNDAMENTALS ================================
def initialize_game(): #Initializes all the game variables for a new game
game_vars['turn'] = 1
game_vars['monster_kill_target'] = 20
game_vars['monsters_killed'] = 0
game_vars['num_monsters'] = 0
game_vars['gold'] = 10
game_vars['threat'] = 10
game_vars['max_threat'] = 10
game_vars['danger_level'] = 1
def show_main_menu(): #Displays the main menu & all of its options
print()
print(f'{" MAIN MENU ":-^55}') #f-formatting to show header of main menu
print("1. Start new game 2. Load saved game")
print("3. Alter game options 4. Show unit information")
print("5. Timed Game Mode 6. Quit game")
print('-' * 55) #f-formatting to end start of main menu
def show_combat_menu(game_vars, back): #Displays the main menu & all of its options
if back == False:
print(f' Turn {game_vars.get("turn")} \t Threat = {threat_bar(game_vars)} \t Danger Level = {game_vars.get("danger_level")}') #Displays game status: Turn, Threat Metre, Danger Level
print(f' Gold = {game_vars.get("gold")} \t Monsters killed = {game_vars.get("monsters_killed")}/{game_vars.get("monster_kill_target")}') #Displays game status: Gold, Number of Monster Kills out of the Target Monster Kills
print()
print(f'{" COMBAT MENU ":-^55}') #f-formatting to show header of combat menu
print("1. Buy unit 2. End turn")
print("3. Upgrade Archers 4. Upgrade Walls")
print("5. Save game 6. Quit")
print('-'*55) #f-formatting to show end of combat menu
def alter_game_options(): #function to display alter game options menu
print(f'{" ALTER GAME OPTIONS ":-^55}') # f-formatting to show header of alter game options menu
print("1. Field Size 2. Defender Spawn Area")
print("3. Number of Kills to Win 4. Gold Increase per Turn")
print('-' * 55) # f-formatting to end start of alter game options menu
def draw_field(field): #Draws the field of play
columnHeader, divisor = '', ' +'
for i in range(game_vars.get('defender_spawn_boundary', 3)): columnHeader += f'{i+1:6}' #concatenates a string to be the headers for the columns (1,2,3)
fieldLength, fieldWidth = len(field[0]), len(field) #declaring dimensions of field
for j in range(fieldLength): divisor += '-----+' #for loop to concatenate a string to be the horizontal divisor
print(f'{columnHeader}\n{divisor}') #outputs the column headers and 1 horizontal divisor
for lane in range(fieldWidth): #iterates through field with iterator, lane
nameLane, hpLane = f'{alphabet[lane]} |', f' |' #declares 2 strings, one for unit name, and one for unit hp
for tile in range(fieldLength): #nested loop to iterate through lane with iterator, tile
if field[lane][tile] == [None, None]: #checks that tile is emptyr
nameLane += f'{"":5}|' #adds 5 blank spaces to unit name string since tile is empty
hpLane += f'{"":5}|' #adds 5 blank spaces to unit hp string since tile is empty
else: #tile is not empty
nameLane += f'{field[lane][tile][0]:5}|' #adds name to unit name string using f-formatting to centralise name in string
hpLane += f'{field[lane][tile][1]:^5}|' #adds hp to unit hp string using f-formatting to centralise hp in string
print(f'{nameLane}\n{hpLane}\n{divisor}') #outputs the unit name string, creates a new line, outputs the unit hp string, creates a new line, outputs 1 horizontal divisor
def quit_game():
#Function prints a default message whenever game is quit
print('\nTHANKS FOR PLAYING! :)')
print('CLOSING GAME', end='')
time.sleep(0.25)
for i in range(3): #loop to add a . to "CLOSING GAME" every 0.25s, gives a sense of progression
print('.', end='')
time.sleep(0.25)
print()
quit() #Exits code in interpreter
#================================ GAME SAVE & LOAD ================================
def save_game(): #Saves the game in the file 'save.txt'
save_file = open("save.txt", "w")
save_file.write(f'{game_vars["turn"]+1}\n') #stores game variable "turn" in 'save.text'
save_file.write(f'{game_vars["monster_kill_target"]}\n') #stores game variable "monster_kill_target" in 'save.text'
save_file.write(f'{game_vars["monsters_killed"]}\n') #stores game variable "monsters_killed" in 'save.text'
save_file.write(f'{game_vars["num_monsters"]}\n') #stores game variable "num_monsters" in 'save.text'
save_file.write(f'{game_vars["gold"]}\n') #stores game variable "gold" in 'save.text'
save_file.write(f'{game_vars["threat"]}\n') #stores game variable "threat" in 'save.text'
save_file.write(f'{game_vars["max_threat"]}\n') #stores game variable "max_threat" in 'save.text'
save_file.write(f'{game_vars["danger_level"]}\n') #stores game variable "danger_level" in 'save.text'
for lane in range(len(field)): #for loop that iterates through each tile in field, saving the tile data in a specified format
for tile in range(len(field[0])):
if field[lane][tile] is not None:
save_file.write(f'{lane}|{tile}|{field[lane][tile][0]}|{field[lane][tile][1]}')
save_file.write('\n')
save_file.close()
print("GAME SAVED")
def load_game(game_vars): #Loads the game data from 'save.txt'
filename = 'save.txt'
save_file = open(filename, "r")
firstLine = save_file.readline() #stores first line of file in case it needs to be used multiple times
if firstLine == '': #check if file is empty
print(f'FILE <{filename}> IS EMPTY')
quit_game()
else:
print('LOADING SAVED GAME', end='')
time.sleep(0.25)
for i in range(3): #loop to add a . to "LOADING SAVED GAME" every 0.25s, gives a sense of progression
print('.', end='')
time.sleep(0.25)
print()
game_vars["turn"] = int(firstLine) #stores game variable "turn" in game_vars dictionary
game_vars["monster_kill_target"] = int(save_file.readline()) #stores game variable "monster_kill_target" in game_vars dictionary
game_vars["monsters_killed"] = int(save_file.readline()) #stores game variable "monsters_killed" in game_vars dictionary
game_vars["num_monsters"] = int(save_file.readline()) #stores game variable "num_monsters" in game_vars dictionary
game_vars["gold"] = int(save_file.readline()) #stores game variable "gold" in game_vars dictionary
game_vars["threat"] = int(save_file.readline()) #stores game variable "threat" in game_vars dictionary
game_vars["max_threat"] = int(save_file.readline()) #stores game variable "max_threat" in game_vars dictionary
game_vars["danger_level"] = int(save_file.readline()) #stores game variable "danger_level" in game_vars dictionary
for line in save_file: #nested loop that iterates line by line through save.txt and obtains field data
line = line.strip("\n")
item = line.split("|")
if [item[2], item[3]] == ['None', 'None']:
field[int(item[0])][int(item[1])] = [None, None]
else:
field[int(item[0])][int(item[1])] = [item[2], item[3]]
save_file.close()
#=================================== GAME LOGIC ===================================
def navigate_main_menu(choice, field): #Function to navigate main menu
if choice == 1: #check to start new game
initialize_game() #reset the game variables data to ensure a new game
run_game(game_vars, field, monster_list, turnEvents) #begin the game, incrememnting by turns and ending when the monsters killed is equal to the monster kills target
elif choice == 2: #load most recent saved game
load_game(game_vars)
run_game(game_vars, field, monster_list, turnEvents) #begin the game, incrememnting by turns and ending when the monsters killed is equal to the monster kills target
elif choice == 3:
alter_game_options()
while True:
choice = get_input('alter-game-settings')
if choice == 1: #change field size
field = change_field_size()
draw_field(field)
elif choice == 2: game_vars['defender_spawn_boundary'] = get_input('defender-spawn-area') #change defender spawn boundary
elif choice == 3: game_vars['monster_kill_target'] = get_input('kills-to-win') #change number of kills required to win
elif choice == 4: game_vars['gold_increase_by_turn'] = get_input('gold_increase_by_turn') #change the gold increase every turn
playGame = get_input('play-game')
if playGame == True: break #start game or alter more settings
if playGame == False: alter_game_options()
run_game(game_vars, field, monster_list, turnEvents) #begin the game, incrememnting by turns and ending when the monsters killed is equal to the monster kills target
elif choice == 4: unit_information(defenders, monsters)
elif choice == 5:
game_vars['timed'] = get_input('timed')
if game_vars['timed'] == True: print('TIMED MODE - ON')
else: print('TIMED MODE - OFF')
elif choice == 6: quit_game() #quit game
def navigate_combat_menu(choice): #Function to navigate combat menu
if choice == 1: buy_unit() #allows player to choose which unit they want to buy and where to place it
elif choice == 3: upgrade_archers(game_vars, field, turnEvents)
elif choice == 4: upgrade_walls(game_vars, field, turnEvents)
elif choice == 5:
save_game() # saves game progress in 'save.txt'
quit_game() # calls function to close game
elif choice == 6: quit_game() # calls function to close game
elif choice == 2: pass # end turn
def check_spawn(game_vars): #function to check spawn requirements
if game_vars.get('threat') >= game_vars.get('max_threat'): #checks if the threat level is greater than the maximum threat level
game_vars['threat'] -= game_vars.get('max_threat')
return True #returns True, which is used to confirm the spawn of monsters when function is called
elif game_vars['num_monsters'] == 0: return True #returns True, which is used to confirm the spawn of monsters when function is called
else: return False #returns False, which prevents the spawn of monsters when function is called
def check_place(field, placement):
selectedLane, selectedTile = alphabet.index(placement[0]), int(placement[1]) #obtains data on placement argument
if field[selectedLane][selectedTile-1] == [None, None]: return True #checks if the placement tile is empty
else: return False
def buy_unit(): #function to handle the purchasing
i = 0
for unit, info in defenders.items(): # loop to iterate through defenders dictionary
print(
f'{i + 1}. {info.get("name").capitalize():6} {"-" * 15} {info.get("price")} Gold') # outputs unit number, unit name, and unit cost
i += 1 # counts for unit number
print(
f"{i + 1}. Don't Purchase") # outputs a 'cancel' option that allows user to not purchase anything and skip the turn
choice = get_input('buy-unit') # obtains validated input on which unit to buy
flag = True
while True:
if choice <= len(defender_list) and flag is True: # checks if user purchased a defender
unitName = defender_list[choice - 1]
if game_vars["gold"] < defenders[unitName].get("price"):
print('NOT ENOUGH GOLD') # validates if there is enough gold
show_combat_menu(game_vars, True)
else:
game_vars["gold"] -= defenders[unitName].get("price")
for unit, info in defenders.items(): # loop to obtain unit name and max hp for placing
if unitName == unit:
hp = f"{info.get('maxHP')}/{info.get('maxHP')}"
break
place_unit(field, unitName, hp)
break
elif choice == len(
defender_list) + 1: # changes option number for dont purchase depending on number of defenders
print('NO PURCHASE') # checks if user cancelled purchase
show_combat_menu(game_vars, True) # displays combat menu again
flag = False
choice = get_input('combat') # obtains validated input on combat menu navigation
if choice == 2: break # special exception for end turn
navigate_combat_menu(choice) # calls function to navigate combat menu
def place_unit(field, unitName, hp): #function to check if user-chosen placement space is available
while True:
placement = get_input('place-unit') # obtains validated input on where to place unit
if check_place(field, placement) == True: # if True, defender will be placed there
selectedLane, selectedTile = alphabet.index(placement[0]), int(placement[1])
field[selectedLane][selectedTile - 1] = [unitName, hp] # changes placement tile data
break
else:
print('POSITION ERROR: POSITION ALREADY OCCUPIED') # outputs error message if the placement tile is already occupied
def spawn_monster(field, monster_list, turnEvents): #function to spawn in monsters
while True: #infinite loop to check if position is empty
spawnPosition = random.randint(0,len(field)-1) #generates a random number within the number of lanes
placement = f'{alphabet[spawnPosition]}{len(field[0])}'
if check_place(field, placement) == True: #calls function, check_place(), to verify that placement tile is empty
selectedLane = alphabet.index(placement[0])
monsterName = monster_list[random.randint(0,len(monster_list)-1)] #generates a monster from monster_list
hp = f"{monsters[monsterName].get('maxHP')}/{monsters[monsterName].get('maxHP')}" #generates the monster at full HP
field[selectedLane][-1] = [monsterName, hp] #replaces the placement tile with randomly generated monster name and monster HP
break
game_vars['num_monsters'] += 1 #adds to the total number of monsters alive on the field
turnEvents += [f'A monster has spawned in Lane {alphabet[selectedLane]}'] #adds string to turnEvents to be output as a turn event
def monster_advance(field, turnEvents): #function that advances monster & deals damage
for lane in field: #iterates through field
for tile in lane:
if tile[0] in monster_list:
speed = monsters[tile[0]].get('moves') #obtains how many tiles a monster can move at once from monsters dictionary
monsterPosition = tile
i, j = lane.index(tile) - speed, lane.index(tile) #intended tile to advance to, current tile
flag = False
for index in range(j-i):
if lane[i + index][0] in defender_list:
flag = True
break
if flag is False and i < 0:
game_vars['game_lost'] = True
game_vars['monster_end_game'] = monsters[tile[0]].get("name")
for index in range(j - i):
if lane[i + index][0] in defender_list:
monsterDamage = random.randint(monsters[tile[0]].get('min_damage'), monsters[tile[0]].get('max_damage'))
if tile[0] == 'ZOMBI': #special string for zombies, as they bite
turnEvents += [f'{monsters[tile[0]].get("name")} on {alphabet[field.index(lane)]}{lane.index(monsterPosition)+1} bites {defenders[lane[i][0]].get("name")} for {monsterDamage} damage!'] #adds string to turnEvents to be output as a turn event
else:
turnEvents += [f'{monsters[tile[0]].get("name")} on {alphabet[field.index(lane)]}{lane.index(monsterPosition) + 1} hits {defenders[lane[i+index][0]].get("name")} for {monsterDamage} damage!'] #adds string to turnEvents to be output as a turn event
unitTotalHp = lane[i+index][1].split('/')
unitHp = int(unitTotalHp[0])
unitHp -= monsterDamage
if unitHp <= 0: #checks if the defender died to monster
turnEvents += [f'{defenders[lane[i+index][0]].get("name")} on {alphabet[field.index(lane)]}{lane.index(monsterPosition) + 1} was slain by {monsters[tile[0]].get("name")}'] #adds string to turnEvents to be output as a turn event
lane[i+index] = [None, None] #resets the tile
lane[i+index], lane[j] = lane[j], lane[i+index] # swaps tiles to advance monster
else: #change the defender HP after being attacked
unitTotalHp = f'{unitHp}/{defenders[lane[i+index][0]].get("maxHP")}'
lane[i+index][1] = unitTotalHp
elif lane[i][0] in monster_list and lane[j][0] in monster_list: #monster is blocked by a monster in front
if lane[i + index][0] is None:
lane[i + index], lane[j] = lane[j], lane[i + index] # swaps tiles to advance monster
turnEvents += [f'{monsters[tile[0]].get("name")} on {alphabet[field.index(lane)]}{lane.index(monsterPosition) + 1} is blocked from advancing!'] # adds string to turnEvents to be output as a turn event
break
else: #advance monster by speed
if lane[i][0] in monster_list and lane[j][0] in monster_list: #checks if the unit in tiles are monsters
turnEvents += [f'{monsters[tile[0]].get("name")} on {alphabet[field.index(lane)]}{lane.index(monsterPosition) + 1} is blocked from advancing'] #adds string to turnEvents to be output as a turn event
else: #monster can advance
if monsters[tile[0]].get("moves") > 1:
turnEvents += [f'{monsters[tile[0]].get("name")} on {alphabet[field.index(lane)]}{lane.index(monsterPosition)+1} advances by {monsters[tile[0]].get("moves")} spaces!'] #adds string to turnEvents to be output as a turn event
else:
turnEvents += [f'{monsters[tile[0]].get("name")} on {alphabet[field.index(lane)]}{lane.index(monsterPosition) + 1} advances!'] #adds string to turnEvents to be output as a turn event
lane[i + index], lane[j] = lane[j], lane[i + index] # swaps tiles to advance monster
break
def defender_attack(field, turnEvents): #function to handle the attacks of the defenders
for lane in field: #iterates through field
defenderName, damageDealt = '', 0 #protects code from crashes due to undeclared variables
for defenderTile in lane[:game_vars.get('defender_spawn_boundary', 3)]: #iterates through the defenders spawn area
if defenderTile[0] in defender_list: #checks if the iterated tile is a defender
if defenderTile[0] == 'CANON':
defenderName = defenders[defenderTile[0]].get('name')
damageDealt = random.randint(defenders[defenderTile[0]].get('min_damage'), defenders[defenderTile[0]].get('max_damage'))
for monsterTile in lane: #iterates through lane to detect first monster
if monsterTile[0] in monster_list: # checks if the iterated tile is a monster
if damageDealt != 0 and defenderName != '': # prevents turn events that show 0 damage was done
if defenderName == 'Cannon':
turnEvents += [f'{defenderName} in Lane {alphabet[field.index(lane)]} shot a cannonball at {monsters[monsterTile[0]].get("name")} for {damageDealt} damage!'] # adds string to turnEvents to be output as a turn event
if game_vars.get('turn') % 2 == 0:
hp = monsterTile[1].split('/') # obtains the HP of unit
monsterHp = int(hp[0]) - damageDealt # subtracts damage dealt from unit HP
if monsterHp <= 0: # MONSTER DIES
turnEvents += [f'{defenderName} in Lane {alphabet[field.index(lane)]} slays {monsters[monsterTile[0]].get("name")} on {alphabet[field.index(lane)]}{lane.index(monsterTile) + 1}!']
turnEvents += [f'You gain {monsters[monsterTile[0]].get("reward")} gold for slaying a {monsters[monsterTile[0]].get("name")}!']
game_vars['monsters_killed'] += 1 # increases monsters_killed game variable by 1 every time a monster is killed
game_vars['gold'] += monsters[monsterTile[0]].get('reward') # increases gold game variable by monster reward every time a monster is killed
game_vars['threat'] += monsters[monsterTile[0]].get('reward') # increases threat level game variable by monster reward every time a monster is killed
spawn_monster(field, monster_list, turnEvents) # spawns a new monster to compensate for death of monster
game_vars['num_monsters'] -= 1 # decreases total number of monsters by 1 every time a monster is killed
monsterTile[0], monsterTile[1] = None, None # resets the tile to be empty
else:
monsterTile[1] = f'{str(monsterHp)}/{hp[1]}' # changes the tile data to show the monster HP after being damaged
chance = random.randint(0,1)
if chance == 1: #knockback monsters in lane by 1
for index in range(len(lane)):
if lane[index][0] in monster_list and lane[index+1][0] is None:
lane[index+1] = lane[index]
lane[index] = [None, None]
break
break
else:
defenderName = defenders[defenderTile[0]].get('name')
damageDealt = random.randint(defenders[defenderTile[0]].get('min_damage'), defenders[defenderTile[0]].get('max_damage'))
for monsterTile in lane: #iterates through lane to detect first monster
if monsterTile[0] in monster_list: #checks if the iterated tile is a monster
if damageDealt != 0 and defenderName != '': #prevents turn events that show 0 damage was done
if defenderName == 'Archer': turnEvents += [f'{defenderName} in Lane {alphabet[field.index(lane)]} fires an arrow at {monsters[monsterTile[0]].get("name")} for {damageDealt} damage!'] #adds string to turnEvents to be output as a turn event
elif defenderName == 'Ninja': turnEvents += [f'{defenderName} in Lane {alphabet[field.index(lane)]} throws a shuriken at {monsters[monsterTile[0]].get("name")} for {damageDealt} damage!'] #adds string to turnEvents to be output as a turn event
else: turnEvents += [f'{defenderName} in Lane {alphabet[field.index(lane)]} deals {damageDealt} damage to {monsters[monsterTile[0]].get("name")}!'] #adds string to turnEvents to be output as a turn event
hp = monsterTile[1].split('/') #obtains the HP of unit
monsterHp = int(hp[0]) - damageDealt #subtracts damage dealt from unit HP
if monsterHp <= 0: # MONSTER DIES
turnEvents += [f'{defenderName} in Lane {alphabet[field.index(lane)]} slays {monsters[monsterTile[0]].get("name")} on {alphabet[field.index(lane)]}{lane.index(monsterTile) + 1}!']
turnEvents += [f'You gain {monsters[monsterTile[0]].get("reward")} gold for slaying a {monsters[monsterTile[0]].get("name")}!']
game_vars['monsters_killed'] += 1 #increases monsters_killed game variable by 1 every time a monster is killed
game_vars['gold'] += monsters[monsterTile[0]].get('reward') #increases gold game variable by monster reward every time a monster is killed
game_vars['threat'] += monsters[monsterTile[0]].get('reward') #increases threat level game variable by monster reward every time a monster is killed
spawn_monster(field, monster_list, turnEvents) #spawns a new monster to compensate for death of monster
game_vars['num_monsters'] -= 1 #decreases total number of monsters by 1 every time a monster is killed
monsterTile[0], monsterTile[1] = None, None #resets the tile to be empty
else: monsterTile[1] = f'{str(monsterHp)}/{hp[1]}' #changes the tile data to show the monster HP after being damaged
break
def run_game(game_vars, field, monster_list, turnEvents): #runs game, each iteration counts as 1 turn
while True: #infinite loop, each iteration of the loop counts as 1 turn
if game_vars.get('game_lost') is True: #checks if game has been lost
print(f'A {game_vars["monster_end_game"]} has reached the city! All is lost!')
print('You have lost the game :(')
quit_game() #calls function to close game
if game_vars['timed'] is True:
start_time = time.time()
if check_spawn(game_vars) is True: spawn_monster(field, monster_list, turnEvents) #spawns a monster if spawn conditions are met
defender_attack(field, turnEvents) #defenders attack monsters
game_transcript(turnEvents) #outputs all of the events that occured over the turn
if game_vars.get('monsters_killed') >= game_vars.get('monster_kill_target'): #checks if game has been won
print('You have protected the city! You win!')
quit_game() #calls function to close game
draw_field(field) #displays updated field
show_combat_menu(game_vars, False) #displays combat menu
choice = get_input('combat') #obtains validated user input to use for combat menu navigation
navigate_combat_menu(choice) #calls function to navigate combat menu
monster_advance(field, turnEvents)
if game_vars['timed'] is True:
end_time = time.time()
if timer(start_time, end_time) > 12.5:
if game_vars.get('time_out_chance') == 0:
print('You ran out of time!')
print('You have lost the game :(')
quit_game() # calls function to close game
else:
game_vars['time_out_chance'] -= 1
print('You ran out of time!')
print(f'{game_vars.get("time_out_chance")} chances left!')
game_vars['turn'] += 1 #increases game variable 'turn' by 1
game_vars['gold'] += game_vars.get('gold_increase_by_turn') #increases game variable 'gold' by the game variable 'gold_increase_by_turn'
game_vars['threat'] += random.randint(1, game_vars.get('danger_level')) #increases threat level by a random number between 1 and danger level (inclusive)
if (game_vars.get('turn') % 12) == 0 and (game_vars.get('turn') != 0): #checks if conditions are met for a danger level increase
danger_level_increase(game_vars, turnEvents)
#=========================== EXTRA & ADVANCED FUNCTIONS ===========================
def timer(start, end): #function to record time taken for something (can only be used one at a time as there is no threading)
sec = math.floor(end - start)
return sec
def change_field_size(): #changes number of lanes and number of tiles per lane
field = []
dimensions = get_input('change-field-size') #return as a list instead of string in case of double digit dimensions
fieldWidth, fieldLength = dimensions[0], dimensions[1]
for i in range(fieldWidth): #iterates the number of times the player defined the number of lanes in field
row = [] #declares an empty lane for every iteration of a lane
for j in range(fieldLength): row.append([None, None]) #iterates the number of times the player defined the length of each lane
field.append(row) #adds the updated lane for every iteration of a lane
return field #outputs the new player-defined field
def threat_bar(game_vars): #concatenates strings to form the threat bar used in combat menu game status
threatLevel = '['
threatLevel += '-' * game_vars.get('threat', 0) #.get() second parameter to handle data file errors
threatLevel += ' ' * (game_vars.get('max_threat', 10) - game_vars.get('threat', 0)) #.get() second parameter to handle data file errors
threatLevel += ']'
return threatLevel
def upgrade_archers(game_vars, field, turnEvents): #function to upgrade archers
if game_vars['gold'] >= defenders['ARCHR']['upgrade_cost']:
game_vars['gold'] -= defenders['ARCHR']['upgrade_cost']
defenders['ARCHR']['maxHP'] += 1
defenders['ARCHR']['min_damage'] += 1
defenders['ARCHR']['max_damage'] += 1
defenders['ARCHR']['upgrade_cost'] += 2
defenders['ARCHR']['level'] += 1
turnEvents += [f"Archers upgraded to Level {defenders['ARCHR'].get('level', 1)}!"] # adds string to turnEvents to be output as a turn event
for lane in field:
for tile in lane:
if tile[0] == 'ARCHR':
unitHp = tile[1].split('/')
tile[1] = f'{int(unitHp[0])+1}/{defenders["ARCHR"].get("maxHP")}'
else:
print('NOT ENOUGH GOLD')
show_combat_menu(game_vars, True)
def upgrade_walls(game_vars, field, turnEvents): #function to upgrade walls
if game_vars['gold'] >= defenders['WALL']['upgrade_cost']:
game_vars['gold'] -= defenders['WALL']['upgrade_cost']
defenders['WALL']['maxHP'] += 5
defenders['WALL']['upgrade_cost'] += 2
defenders['WALL']['level'] += 1
turnEvents += [f"Walls upgraded to Level {defenders['WALL'].get('level', 1)}!"] # adds string to turnEvents to be output as a turn event
for lane in field:
for tile in lane:
if tile[0] == 'WALL':
unitHp = tile[1].split('/')
tile[1] = f'{int(unitHp[0]) + 5}/{defenders["WALL"].get("maxHP")}'
else:
print('NOT ENOUGH GOLD')
show_combat_menu(game_vars, True)
def unit_information(defenders, monsters): #function to output all information on both defenders and monsters
print(f'{"Defenders":~^55}', end='')
for unit, unitInfo in defenders.items():
print()
print(f'Name: {unitInfo.get("name")}')
print(f'CodeName: {unit}')
print(f'Full HP: {unitInfo.get("maxHP")}')
print(f'Min-Max Damage: {unitInfo.get("min_damage")}-{unitInfo.get("max_damage")} ')
print(f'Price: {unitInfo.get("price")}')
print(f'{"Monsters":~^55}', end ='')
for unit, unitInfo in monsters.items():
print()
print(f'Name: {unitInfo.get("name")}')
print(f'CodeName: {unit}')
print(f'Full HP: {unitInfo.get("maxHP")}')
print(f'Min-Max Damage: {unitInfo.get("min_damage")}-{unitInfo.get("max_damage")} ')
print(f'Speed: {unitInfo.get("moves")}')
print(f'Rewards: {unitInfo.get("rewards")}')
print('~' * 55)
def get_input(menuClass): #function to obtain input and validate it, menuClass parameter identifies which input it is obtaining and validating accordingly, depending on function arguments
x = 1
while True: #input loop
if menuClass == 'main' or menuClass == 'combat': choice = input('>>> Your choice: ')
elif menuClass == 'buy-unit': choice = input('>>> Unit to Purchase: ')
elif menuClass == 'place-unit': choice = input('>>> Position to Place Unit: ')
elif menuClass == 'alter-game-settings': choice = input('>>> Your choice: ')
elif menuClass == 'change-field-size':
while True:
fieldWidth = input('>>> Number of Lanes: ')
if fieldWidth.isnumeric() is not True: print('INPUT TYPE ERROR: NUMBER OF LANES SHOULD BE A NUMBER')
elif int(fieldWidth) == 0: print('RANGE ERROR: NUMBER OF LANES CANNOT BE 0')
elif int(fieldWidth) < 3: print('RANGE ERROR: NUMBER OF LANES CANNOT BE LESS THAN 3')
elif int(fieldWidth) > 26: print('RANGE ERROR: NUMBER OF LANES CANNOT BE GREATER THAN 26')
else: break
while True:
fieldLength = input('>>> Number of Tiles in Each Lane: ')
if fieldLength.isnumeric() is not True: print('INPUT TYPE ERROR: NUMBER OF TILES PER LANE SHOULD BE A NUMBER')
elif int(fieldLength) == 0: print('RANGE ERROR: NUMBER OF TILES PER LANE CANNOT BE 0')
elif int(fieldLength) < 5: print('RANGE ERROR: NUMBER OF TILES PER LANE CANNOT BE LESS THAN 5') #CHANGE LATER
else: break
elif menuClass == 'defender-spawn-area': boundary = input('>>> New Furthest Tile for Defender Spawn: ')
elif menuClass == 'kills-to-win': kills = input('>>> New Monster Kills Target: ')
elif menuClass == 'gold_increase_by_turn': gold = input('>>> New Gold Increase per Turn: ')
elif menuClass == 'play-game': choice = input('>>> Start Game? [Y/n]: ')
elif menuClass == 'timed': time = input('>>> Timed Mode? [On/Off]: ')
else: #in case function is called with an incorrect menuClass, prevents crashes with expansion of program
print('PROGRAM ERROR: "menuClass" VARIABLE UNDETECTED')
menuClass = input('>>> PLEASE MANUALLY INPUT "menuClass" VARIABLE: ')
if x == 3:
print('\nGAME SHUT DOWN DUE TO REPEATED ERROR', end='')
quit_game()
x += 1
if menuClass == 'main': #data validation for main menu
if not choice.isnumeric():
print('TYPE ERROR: PLEASE ENTER A NUMBER')
continue #prevents a ValueError because of the type casting on the next line
choice = int(choice)
if not (choice >= 1 and choice <= 6): print('RANGE ERROR: PLEASE ENTER A NUMBER BETWEEN 1 TO 6')
else:
output = choice
break
elif menuClass == 'combat': #data validation for combat menu
if not choice.isnumeric(): # check for number
print('INPUT TYPE ERROR: PLEASE ENTER A NUMBER')
continue #prevents a ValueError because of the type casting on the next line
choice = int(choice)
if not (choice >= 1 and choice <= 6): print('RANGE ERROR: PLEASE ENTER A NUMBER BETWEEN 1 TO 6')
else:
output = choice
break
elif menuClass == 'buy-unit': #data validation for purchasing defenders
if choice.isalpha() is True:
defenderFullName = []
for unit, info in defenders.items(): defenderFullName += [info.get('name').upper()] #loop to iterate through defenders dictionary and obtain names, capitalise them, and add them to the list, defenderFullName
if choice.upper() in defenderFullName:
output = defenderFullName.index(choice.upper()) + 1
break
else: print("INPUT ERROR: PLEASE ENTER UNIT NAME CORRECTLY")
elif choice.isnumeric():
output = int(choice)
if output <= len(defender_list): break
elif output == len(defender_list)+1: break
else: print("INPUT ERROR: PLEASE ENTER UNIT NUMBER CORRECTLY")
elif menuClass == 'place-unit': # data validation for placing of purchased defenders
if not choice.isalnum():
print('TYPE ERROR: PLEASE ENTER ALPHANUMERIC CHARACTERS')
else:
choice = choice.capitalize()
if len(choice) != 2:
print('LENGTH ERROR: PLEASE INPUT USING THE FOLLOWING FORMAT: LaneColumn (e.g. A1)')
elif (not choice[0].isalpha()) and (not choice[1].isnumeric()):
print('FORMAT ERROR: PLEASE INPUT USING THE FOLLOWING FORMAT: LaneColumn (e.g. A1)')
elif alphabet.index(choice[0]) >= alphabet.index(alphabet[len(field)]):
print(f'RANGE ERROR: PLEASE ENSURE LANE LETTER COMES BETWEEN A & {alphabet[len(field)-1]}')
elif int(choice[1]) > game_vars.get('defender_spawn_boundary', 3):
print(f'RANGE ERROR: PLEASE ENSURE SELECTED TILE IS BETWEEN 1 & {game_vars.get("defender_spawn_boundary", 3)} (INCLUSIVE)')
else:
output = choice
break
elif menuClass == 'alter-game-settings':
if not choice.isnumeric():
print('TYPE ERROR: PLEASE ENTER A NUMBER')
continue #prevents a ValueError because of the type casting on the next line
choice = int(choice)
if not (choice >= 1 and choice <= 4): print('RANGE ERROR: PLEASE ENTER A NUMBER BETWEEN 1 TO 4')
else:
output = choice
break
elif menuClass == 'change-field-size':
output = [int(fieldWidth), int(fieldLength)]
break
elif menuClass == 'defender-spawn-area':
if not boundary.isnumeric():
print('INPUT TYPE ERROR: PLEASE ENTER A NUMBER')
continue #prevents a ValueError because of the type casting on the next line
elif int(boundary) == 0: print('RANGE ERROR: DEFENDER SPAWN BOUNDARY CANNOT BE 0')
elif int(boundary) < 3: print('RANGE ERROR: DEFENDER SPAWN BOUNDARY CANNOT BE LESS THAN 3')
else:
output = int(boundary)
break
elif menuClass == 'kills-to-win':
if kills.isnumeric() is not True: print('INPUT TYPE ERROR: PLEASE INPUT A NUMBER')
elif int(kills) == 0:
print('RANGE ERROR: MONSTER KILLS TARGET CANNOT BE 0')
elif int(kills) < 5:
print('RANGE ERROR: MONSTER KILLS TARGET CANNOT BE LESS THAN 5')
else:
output = int(kills)
break
elif menuClass == 'gold_increase_by_turn':
if gold.isnumeric() is not True: print('INPUT TYPE ERROR: PLEASE INPUT A NUMBER')
elif int(gold) == 0: print('RANGE ERROR: GOLD INCREASE PER TURN CANNOT BE 0')
else:
output = int(gold)
break
elif menuClass == 'play-game':
if choice.isalpha() is not True: print('INPUT TYPE ERROR: PLEASE INPUT "YES" OR "NO"')
elif choice.upper() == 'YES' or choice.upper() == 'Y':
output = True
break
elif choice.upper() == 'NO' or choice.upper() == 'N':
output = False
break
else: print('INPUT ERROR: PLEASE INPUT "YES" OR "NO"')
elif menuClass == 'timed':
if time.isalpha() is not True: print('INPUT TYPE ERROR: PLEASE INPUT "ON" OR "OFF"')
elif time.upper() == 'ON':
output = True
break
elif time.upper() == 'NO':
output = False
break
else: print('INPUT ERROR: PLEASE INPUT "ON" OR "OFF"')
return output #returns user input after validation
def game_transcript(turnEvents): #outputs all the events that occured in a single turn
header = f' TURN {game_vars.get("turn")} EVENTS: ' #f-formatting to make the header for each time function is called
print(f'{header:~^55}') #f-formatting to show header of turn events
while turnEvents != []: #iterates through turnEvents while removing elements
print(turnEvents[0])
turnEvents.pop(0)
print('~' * 55) #f-formatting to show end of main menu
def danger_level_increase(game_vars, turnEvents): #changes game data every time danger level increases
game_vars['danger_level'] += 1 #increases game variable 'danger_level' by 1 every time the function is called
turnEvents += ['The evil grows stronger!'] #adds string to turnEvents to be output as a turn event
for mob in monster_list: #iterates through monster_list to obtain each element inside
monsters[mob]['maxHP'] += 1 #increases every monsters maximum HP by 1 every time the function is called
monsters[mob]['min_damage'] += 1 #increases every monsters minimum damage by 1 every time the function is called
monsters[mob]['max_damage'] += 1 #increases every monsters maximum damage by 1 every time the function is called
monsters[mob]['reward'] += 1 #increases every monsters reward by 1 every time the function is called
async def play_music(): #asynchronous function to play background music 'evolution.mp3'
mixer.init()
mixer.music.load("evolution.mp3")
mixer.music.set_volume(0.15)
mixer.music.play(10)
#================================= START PROGRAM ==================================
asyncio.run(play_music()) #running the asynchronous function for background music
print(f'{"="*55}\n{"Desperate Defenders":^55}\n{"Defend the city from undead monsters!":^55}\n{"="*55}') #display start of game header
while True:
show_main_menu() # show start menu options
choice = get_input('main') #obtain validated input to use as navigation
navigate_main_menu(choice, field)
#==================================== CREDITS =====================================
#Music I Used: https://www.bensound.com/free-music-for-videos
| klystrn/Tower-Defence-Game | towerDefence.py | towerDefence.py | py | 42,879 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "os.environ",
"line_number": 6,
"usage_type": "attribute"
},
{
"api_name": "S10239913E_Assignment_gameData.game_vars",
"line_number": 12,
"usage_type": "name"
},
{
"api_name": "S10239913E_Assignment_gameData.game_vars",
"line_number": 13,
"usage_type": "name... |
73712141864 | from typing import Dict, Any
from argus.processors.post_processors.utils import post_process as pp
from h2o_docai_scorer.post_processors.post_processor_supply_chain import PostProcessor as PostProcessorSupplyChain
class PostProcessor(PostProcessorSupplyChain):
"""Represents a last step in pipeline process that receives all pipeline intermediate
results and translates them into a final json structure that will be returned to user.
"""
def get_pages(self) -> Dict[int, Any]:
return super().get_pages()
def get_entities(self):
if not self.has_labelling_model:
return []
docs = pp.post_process_predictions(
model_preds=self.label_via_predictions,
top_n_preds=self.label_top_n,
token_merge_type="MIXED_MERGE",
token_merge_xdist_regular=1.0,
label_merge_x_regular="ALL",
token_merge_xydist_regular=1.0,
label_merge_xy_regular="address",
token_merge_xdist_wide=1.5,
label_merge_x_wide="phone|fax",
output_labels="INCLUDE_O",
verbose=True,
)
df_list = []
for doc in docs:
predictions = docs[doc]
predictions = predictions.round(decimals=4)
for idx, row in predictions.iterrows():
df_list.append(row.to_dict())
return df_list
'''
Converting the dictionary to a dataframe
import pandas as pd
import json
f = open('result.json')
dict_data = json.load(f)
df = pd.DataFrame(dict_data['entities'])
df.to_csv('result.csv')
'''
| h2oai/docai-recipes | post_processor/v0.6/post_processor_4.py | post_processor_4.py | py | 1,636 | python | en | code | 4 | github-code | 36 | [
{
"api_name": "h2o_docai_scorer.post_processors.post_processor_supply_chain.PostProcessor",
"line_number": 6,
"usage_type": "name"
},
{
"api_name": "typing.Dict",
"line_number": 11,
"usage_type": "name"
},
{
"api_name": "typing.Any",
"line_number": 11,
"usage_type": "name... |
28888308996 | '''
https://www.codewars.com/kata/52efefcbcdf57161d4000091/
The main idea is to count all the occurring characters in a string. If you have a string like aba, then the result should be {'a': 2, 'b': 1}.
What if the string is empty? Then the result should be empty object literal, {}.
'''
# my solution
def count(str):
dict = {}
for i in str:
if i in dict:
dict[i] += 1
else:
dict[i] = 1
return dict
#! alternative-solution
from collections import Counter
def count(string):
return Counter(string)
# been seeing is Counter() all around lately. And I have the feeling this
# is more pythonic way to count a key-value | MSKose/Codewars | 6 kyu/Count characters in your string.py | Count characters in your string.py | py | 694 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "collections.Counter",
"line_number": 25,
"usage_type": "call"
}
] |
23111168251 | from mixer.auto import mixer
from rest_framework.test import APITestCase, APIClient
from stock_setup_info.factory import IndustryFactory
from stock_setup_info.models import Industry
# Create your tests here.
class BaseViewTest(APITestCase):
client = APIClient()
@staticmethod
def create_industry(name="", exchange_code="", sync_flag="", logo=""):
if name != "" and exchange_code != "":
Industry.objects.create(
name=name, exchange_code=exchange_code, sync_flag=sync_flag, logo=logo
)
def setUp(self):
self.create_industry("Agriculture", "AG", "0", "0")
self.create_industry("Finance", "AG", "0", "0")
self.industry = IndustryFactory()
class AllModelCreatedTest(BaseViewTest):
def test_model_can_create_list_of_industry(self):
"""
This test ensures that all the industries added in the setup method exists
"""
new_count = Industry.objects.count()
self.assertNotEqual(0, new_count)
def test_model_via_mixer(self):
obj = mixer.blend("stock_setup_info.models.Industry")
assert obj.pk > 1, "Should create an Industry Instance"
| Maxcutex/stockman_project | stock_setup_info/tests/test_models/test_industry_model.py | test_industry_model.py | py | 1,184 | python | en | code | 2 | github-code | 36 | [
{
"api_name": "rest_framework.test.APITestCase",
"line_number": 11,
"usage_type": "name"
},
{
"api_name": "rest_framework.test.APIClient",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "stock_setup_info.models.Industry.objects.create",
"line_number": 17,
"usage... |
1947313325 | import unittest
import pathlib
import typing
import kclvm.compiler.parser.parser as parser
import kclvm.tools.docs.doc_parser as doc_parser
import kclvm.kcl.types.checker as type_checker
import kclvm.api.object as obj_pkg
import kclvm.tools.docs.model_pb2 as model
_DIR_PATH = pathlib.Path(__file__).parent.joinpath("doc_data") / "source_files"
def resolve(kcl_file: str) -> typing.List[model.SchemaDoc]:
prog = parser.LoadProgram(kcl_file)
type_checker.ResolveProgramImport(prog)
checker = type_checker.TypeChecker(prog, type_checker.CheckConfig())
checker.check_import(prog.MAIN_PKGPATH)
checker.init_global_types()
schemas = prog.pkgs[prog.MAIN_PKGPATH][0].GetSchemaList()
schema_docs: typing.List[model.SchemaDoc] = []
for schema in schemas:
schema_obj_type = checker.scope_map[prog.MAIN_PKGPATH].elems[schema.name].type
assert isinstance(schema_obj_type, obj_pkg.KCLSchemaDefTypeObject)
schema_docs.append(
doc_parser.SchemaDocParser(
schema=schema,
schema_type=schema_obj_type.schema_type,
root=prog.root,
).doc
)
return schema_docs
class KCLDocCheckerTest(unittest.TestCase):
def test_simple_case(self) -> None:
docs = resolve(_DIR_PATH / "simple.k")
assert len(docs) == 1
doc = docs[0]
assert doc.doc.startswith("Person is a simple schema")
assert doc.attributes[0].name == "name"
assert doc.attributes[0].type.type_str == "str"
assert doc.attributes[0].is_optional is False
assert doc.attributes[0].default_value == '"Default"'
assert doc.attributes[0].doc.startswith("A Normal attribute named 'name'")
assert doc.attributes[1].name == "age"
assert doc.attributes[1].type.type_str == "int"
assert doc.attributes[1].is_optional is True
assert doc.attributes[1].default_value == "18"
assert doc.attributes[1].doc.startswith("A Normal attribute named 'age'")
assert doc.examples.startswith("person = Person {")
if __name__ == "__main__":
unittest.main(verbosity=2)
| kcl-lang/kcl-py | test/test_units/test_kclvm/test_tools/test_doc/test_checker.py | test_checker.py | py | 2,149 | python | en | code | 8 | github-code | 36 | [
{
"api_name": "pathlib.Path",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "kclvm.compiler.parser.parser.LoadProgram",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "kclvm.compiler.parser.parser",
"line_number": 16,
"usage_type": "name"
},
{
... |
26755841181 | from Crypto.Cipher import AES
from base64 import b64decode
import os
def main():
key = 'YELLOW SUBMARINE'
cipher = AES.new(key, AES.MODE_ECB)
file_path = os.path.expanduser('~/Downloads/7.txt')
with open(file_path, 'r') as f:
data = f.read()
data = b64decode(data)
msg = cipher.decrypt(data).decode('utf-8')
print(msg)
if __name__ == "__main__":
main()
| dominicle8/cryptopals | 1_7.py | 1_7.py | py | 398 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "Crypto.Cipher.AES.new",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "Crypto.Cipher.AES",
"line_number": 8,
"usage_type": "name"
},
{
"api_name": "Crypto.Cipher.AES.MODE_ECB",
"line_number": 8,
"usage_type": "attribute"
},
{
"api_name": "... |
22968912977 | from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session
from components.auth.logics import AuthLogic
from config.settings import get_db
from framework.api_response import ApiResponse
from framework.decorators import default_api_response, classview
from components.auth.schemas import (
LoginRequestSchema, LoginResponseSchema
)
router = APIRouter(prefix="/auth")
@classview(router)
class LoginView:
session: Session = Depends(get_db)
@router.post("/login")
@default_api_response
async def login(self, request: Request,
login: LoginRequestSchema):
return ApiResponse(
request=request,
request_schema=LoginRequestSchema,
response_schema=LoginResponseSchema,
method=AuthLogic(self.session).login,
body=login
)
| minhhh-0927/cookiecutter-fastapi-sun-asterisk | {{cookiecutter.project_slug}}/components/auth/routers.py | routers.py | py | 857 | python | en | code | 13 | github-code | 36 | [
{
"api_name": "fastapi.APIRouter",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "sqlalchemy.orm.Session",
"line_number": 19,
"usage_type": "name"
},
{
"api_name": "fastapi.Depends",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "config.setti... |
7662718828 | import sqlite3
import urllib
from bs4 import BeautifulSoup
from datetime import datetime
conn = sqlite3.connect('pftcrawlerdb.sqlite')
cur = conn.cursor()
# Setup database
cur.executescript('''
DROP TABLE IF EXISTS Podcasts;
DROP TABLE IF EXISTS Appearances;
CREATE TABLE Podcasts (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT UNIQUE
);
CREATE TABLE Appearances (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
podcast_id INTEGER,
episode INTEGER,
title STRING,
date DATETIME,
link TEXT UNIQUE)
''')
url = raw_input('Enter - ')
if len(url) == 0 : url = 'http://www.earwolf.com/person/paul-f-tompkins/'
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html, 'lxml')
divTags = soup("div", {"class":"ep-description"})
# comment out when not debugging
# i = int(raw_input('Enter iterations to run: '))
for dtag in divTags:
# comment out when not debugging
# if i == 0: break
# i -= 1
# clear title and link list vars
eptitle = ''
eplink = ''
podcast = ''
epnum = ''
epdatestr = ''
epdate = datetime
# get ep title
eptitle = (dtag.parent.h1.text).replace(':', ' - ')
# get ep link
eplink = dtag.a.get('href', None)
# parse text in span texts to a list & convert to ascii
spanTags = dtag.find_all('span')
tagTexts = []
for tag in spanTags : tagTexts.append((tag.text).encode('ascii', 'ignore'))
# get podcast name
podcast = tagTexts[0].split('#')[0].strip()
# get episode number
epnum = tagTexts[0].split('#')[1].strip()
# get episode date or assign earliest date if date string not parsable
epdatestr = tagTexts[1].strip()
try:
epdate = datetime.strptime(epdatestr, '%B %d, %Y')
except:
epdate = datetime.min
# write values to database
cur.execute('''INSERT OR IGNORE INTO Podcasts (name)
VALUES ( ? )''', ( podcast, ) )
cur.execute('SELECT id FROM Podcasts WHERE name = ? ', (podcast, ))
pod_id = cur.fetchone()[0]
cur.execute('''INSERT OR REPLACE INTO Appearances
(podcast_id, episode, title, date, link) VALUES ( ?, ?, ?, ?, ? )''',
( pod_id, epnum, eptitle, epdate, eplink ) )
conn.commit()
# print alleps
#
#
# if len(titleerror) != 0: print 'There were title errors: ', titleerror
#
# if len(linkerror) != 0: print 'There were link errors: ', linkerror
#
#
# for key, value in alleps.items(): print value[0]
| astewa13/PFTCrawler | ScrapeEarwolf.py | ScrapeEarwolf.py | py | 2,589 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "sqlite3.connect",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "urllib.urlopen",
"line_number": 30,
"usage_type": "call"
},
{
"api_name": "bs4.BeautifulSoup",
"line_number": 32,
"usage_type": "call"
},
{
"api_name": "datetime.datetime",
... |
15936612595 | import os
import atexit
import asyncio
import aiohttp
import requests
from scraper import scrape
from models import db, Movie
from flask import Flask, jsonify, request, abort
from apscheduler.schedulers.background import BackgroundScheduler
app = Flask(__name__)
# SQLAlchemy configurations
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI', '')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
TMDB_API_KEY = os.environ.get('TMDB_API_KEY', '')
@app.route('/', methods=['GET'])
def index():
# return app.send_static_file('index.html')
return jsonify({'success': True, 'message': 'Connected to server'}), 200
@app.route('/api/all-releases', methods=['GET'])
def all_releases():
if request.method != "GET":
abort(404)
try:
movies = [dict(movie) for movie in db.session.query(Movie).all()]
return jsonify({'success': True, 'message': 'Query processed', 'query_results': movies}), 200
except Exception as e:
print(f"Error: {e}", flush=True)
return jsonify({'success': False, 'message': 'Error processing query'}), 400
finally:
db.session.close()
@app.route('/api/this-weeks-releases', methods=['GET'])
def this_week():
if request.method != "GET":
abort(404)
return jsonify({ 'success': True, 'message': 'Query processed', 'query_results': get_by_week('this week') }), 200
@app.route('/api/last-weeks-releases', methods=['GET'])
def last_week():
if request.method != "GET":
abort(404)
return jsonify({ 'success': True, 'message': 'Query processed', 'query_results': get_by_week('last week') }), 200
@app.route('/api/next-weeks-releases', methods=['GET'])
def next_week():
if request.method != "GET":
abort(404)
return jsonify({ 'success': True, 'message': 'Query processed', 'query_results': get_by_week('next week') }), 200
"""
Get all movies in the database whose release week matches the given query.
"""
def get_by_week(week):
with app.app_context():
try:
movies = Movie.query.filter(Movie.release_week.like(f"%{week}%")).all()
return [dict(movie) for movie in movies]
except Exception as e:
print(f"Error: {e}", flush=True)
return []
finally:
db.session.close()
"""
An application factory for tethering a database to SQLAlchemy models.
For use in initialization or updates.
In practice:
Load in environment variables
Navigate to the backend directory
Import this function and run through a Python interactive session
1. >>> from app import create_app
2. >>> from models import db
3. >>> db.create_all(app=create_app())
"""
def create_app():
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI', '')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
return app
"""
Perform a fetch request to the TMDb API, gathering information for a film by its IMDb ID.
Then place this film, along with its release week and IMDb ID, in the database.
"""
async def fetch(session, release_week, imdb_id):
url = f"https://api.themoviedb.org/3/find/{imdb_id}?api_key={TMDB_API_KEY}&language=en-US&external_source=imdb_id"
async with session.get(url) as response:
data = await response.json()
movie_results = data['movie_results']
tv_results = data['tv_results']
if len(movie_results) != 0:
movie = movie_results[0]
with app.app_context():
try:
db.session.add(Movie(imdb_id,
movie['id'],
movie['title'],
movie['poster_path'],
movie['overview'],
movie['vote_average'],
release_week))
db.session.commit()
except Exception as e:
print(f"Error: {e}", flush=True)
finally:
db.session.close()
elif len(tv_results) !=0:
show = tv_results[0]
with app.app_context():
try:
db.session.add(Movie(imdb_id,
show['id'],
show['name'],
show['poster_path'],
show['overview'],
show['vote_average'],
release_week))
db.session.commit()
except Exception as e:
print(f"Error: {e}", flush=True)
finally:
db.session.close()
else:
pass
"""
Gather all fetch requests to the TMDb API as tasks to be performed at once.
Then perform tasks.
"""
async def get_tmdb_data(movies):
async with aiohttp.ClientSession() as session:
with app.app_context():
db.session.query(Movie).delete()
db.session.commit()
tasks = [fetch(session, release_week, imdb_id) for release_week, imdb_id in movies]
await asyncio.gather(*tasks)
"""
Perform a webscrape and organize data into a list of tuples containing the release week and IMDb ID for each movie.
Then for each tuple, using asyncio, retrieve all film's TMDb information at once.
"""
def scrape_n_save():
movies = [(week['release_week'], movie['imdb_id']) for week in scrape() for movie in week['movies']]
asyncio.get_event_loop().run_until_complete(get_tmdb_data(movies))
# Create schedule for mailing status report
scheduler = BackgroundScheduler()
scheduler.start()
scheduler.add_job(func=scrape_n_save, id='cron_scrape_n_save', name='Update DB with new releases every hour', trigger='cron', hour='*')
# Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())
if __name__ == "__main__":
scrape_n_save()
app.run(debug=True, host='0.0.0.0')
| Joseph-Villegas/JS-New-DVD-Releases | backend/app.py | app.py | py | 6,279 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "flask.Flask",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "os.environ.get",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "os.environ",
"line_number": 15,
"usage_type": "attribute"
},
{
"api_name": "models.db.init_app",
"... |
2530109965 | from typing import Tuple
from pricer.pricer import Offer, Basket, Catalogue
def multibuy(item: str, buy: int, get: int) -> Offer:
def offer(basket: Basket, catalogue: Catalogue) -> Tuple[float, Basket]:
basket = basket.copy()
if item not in basket or item not in catalogue:
return 0, basket
if basket[item] >= buy + get:
basket[item] -= (buy + get)
return buy * catalogue[item], basket
else:
return 0, basket
return offer
def discount(item: str, percent: int) -> Offer:
def offer(basket: Basket, catalogue: Catalogue) -> Tuple[float, Basket]:
basket = basket.copy()
if item not in basket or item not in catalogue:
return 0, basket
if basket[item] == 1:
basket.pop(item)
else:
basket[item] -= 1
return catalogue[item] * (100 - percent) / 100, basket
return offer
| zamkot/basket_pricer | pricer/offers.py | offers.py | py | 950 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pricer.pricer.Basket",
"line_number": 8,
"usage_type": "name"
},
{
"api_name": "pricer.pricer.Catalogue",
"line_number": 8,
"usage_type": "name"
},
{
"api_name": "typing.Tuple",
"line_number": 8,
"usage_type": "name"
},
{
"api_name": "pricer.pricer.... |
41068976001 | from matplotlib import pyplot as plt
from matplotlib import font_manager
# 设置中文
# !本字体路径为本机一款字体路径,运行时可任意替换为系统中的一款中文字体路径,必须为中文字体,系统不限:Windows/macOS/Linux
my_font = font_manager.FontProperties(
fname='C:\Windows\Fonts\STFANGSO.TTF')
# 设置图片大小
plt.figure(figsize=(20, 8), dpi=80)
# 数据
x_3 = range(1, 32)
x_10 = range(51, 82)
y_1 = [11, 17, 16, 11, 12, 11, 12, 6, 6, 7, 8, 9, 12, 15, 14, 17, 18,
21, 16, 17, 20, 14, 15, 15, 15, 19, 21, 22, 22, 22, 23] # 3月份
y_2 = [26, 26, 28, 19, 21, 17, 16, 19, 18, 20, 20, 19, 22, 23, 17, 20,
21, 20, 22, 15, 11, 15, 5, 13, 17, 10, 11, 13, 12, 13, 6] # 10月份
# 设置坐标刻度
_x = list(x_3)+list(x_10) # 将两个横坐标转化为列表相加,列表的值刚好中间缺少值,形成和坐标点的对应
_xticks_ = ['3月{}日'.format(i) for i in range(1, 32)]
_xticks_ += ['10月{}日'.format(i) for i in range(1, 32)]
plt.xticks(_x[::3], _xticks_[::3], fontproperties=my_font,
rotation=45) # _xticks_和_x一一对应 坐标刻度太密集可以将列表取步长
# 设置坐标轴描述
plt.xlabel("时间", fontproperties=my_font)
plt.ylabel("温度(℃)", fontproperties=my_font)
plt.title("3月和10月温度比较图", fontproperties=my_font)
# 绘图
plt.scatter(x_3, y_1, label="3月", color='r')
plt.scatter(x_10, y_2, label="10月")
# ?添加图例 添加图例必须在画图之后!!!!!!
plt.legend(prop=my_font, loc='upper left')
# 展示
plt.show() | XiongZhouR/python-of-learning | matplotlib/scatter.py | scatter.py | py | 1,563 | python | zh | code | 1 | github-code | 36 | [
{
"api_name": "matplotlib.font_manager.FontProperties",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "matplotlib.font_manager",
"line_number": 5,
"usage_type": "name"
},
{
"api_name": "matplotlib.pyplot.figure",
"line_number": 8,
"usage_type": "call"
},
{
... |
34400546796 | from pages.courses.register_course_page import RegisterCoursePage
from utilities.test_status import TestStatus
from pages.home.login_page import LoginPage
import unittest
import pytest
from ddt import ddt, data, unpack
import time
from pages.home.navigation_page import NavigationPage
@pytest.mark.usefixtures("oneTimeSetUp", "setUp")
@ddt
class RegisterCourseTests(unittest.TestCase):
@pytest.fixture(autouse=True)
def objectSetup(self, oneTimeSetUp):
self.courses = RegisterCoursePage(self.driver)
self.ts = TestStatus(self.driver)
self.lp = LoginPage(self.driver)
self.nav = NavigationPage(self.driver)
def set_up(self):
self.nav.navigate_to_all_courses()
@pytest.mark.run(order = 1)
@data (("JavaScript for beginners", "10", "1220", "10"), ("Learn Python 3 from scratch", "20", "1220", "20"))
@unpack
def test_invalid_enrollment(self, courseName, ccNum, ccExp, ccCVV):
self.lp.login("test@email.com", "abcabc")
self.courses.enter_search_field(courseName)
self.courses.click_search_button()
self.courses.select_course()
time.sleep(4)
self.courses.enroll_course(num=ccNum, exp=ccExp, cvv=ccCVV)
result = self.courses.verify_enroll_failed()
self.ts.mark_final("test_invalid_enrollment", result,
"Enrollment Verification")
self.courses.click_all_courses_link()
| dragosavac/Testing_Framework | tests/courses/course_test.py | course_test.py | py | 1,440 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "unittest.TestCase",
"line_number": 13,
"usage_type": "attribute"
},
{
"api_name": "pages.courses.register_course_page.RegisterCoursePage",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "utilities.test_status.TestStatus",
"line_number": 19,
"usage... |
37351904509 | # This file is part of avahi.
#
# avahi is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# avahi is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with avahi; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA.
# Some definitions matching those in avahi-common/defs.h
import dbus
SERVER_INVALID, SERVER_REGISTERING, SERVER_RUNNING, SERVER_COLLISION, SERVER_FAILURE = range(0, 5)
ENTRY_GROUP_UNCOMMITED, ENTRY_GROUP_REGISTERING, ENTRY_GROUP_ESTABLISHED, ENTRY_GROUP_COLLISION, ENTRY_GROUP_FAILURE = range(0, 5)
DOMAIN_BROWSER_BROWSE, DOMAIN_BROWSER_BROWSE_DEFAULT, DOMAIN_BROWSER_REGISTER, DOMAIN_BROWSER_REGISTER_DEFAULT, DOMAIN_BROWSER_BROWSE_LEGACY = range(0, 5)
PROTO_UNSPEC, PROTO_INET, PROTO_INET6 = -1, 0, 1
IF_UNSPEC = -1
PUBLISH_UNIQUE = 1
PUBLISH_NO_PROBE = 2
PUBLISH_NO_ANNOUNCE = 4
PUBLISH_ALLOW_MULTIPLE = 8
PUBLISH_NO_REVERSE = 16
PUBLISH_NO_COOKIE = 32
PUBLISH_UPDATE = 64
PUBLISH_USE_WIDE_AREA = 128
PUBLISH_USE_MULTICAST = 256
LOOKUP_USE_WIDE_AREA = 1
LOOKUP_USE_MULTICAST = 2
LOOKUP_NO_TXT = 4
LOOKUP_NO_ADDRESS = 8
LOOKUP_RESULT_CACHED = 1
LOOKUP_RESULT_WIDE_AREA = 2
LOOKUP_RESULT_MULTICAST = 4
LOOKUP_RESULT_LOCAL = 8
LOOKUP_RESULT_OUR_OWN = 16
LOOKUP_RESULT_STATIC = 32
SERVICE_COOKIE = "org.freedesktop.Avahi.cookie"
SERVICE_COOKIE_INVALID = 0
DBUS_NAME = "org.freedesktop.Avahi"
DBUS_INTERFACE_SERVER = DBUS_NAME + ".Server"
DBUS_PATH_SERVER = "/"
DBUS_INTERFACE_ENTRY_GROUP = DBUS_NAME + ".EntryGroup"
DBUS_INTERFACE_DOMAIN_BROWSER = DBUS_NAME + ".DomainBrowser"
DBUS_INTERFACE_SERVICE_TYPE_BROWSER = DBUS_NAME + ".ServiceTypeBrowser"
DBUS_INTERFACE_SERVICE_BROWSER = DBUS_NAME + ".ServiceBrowser"
DBUS_INTERFACE_ADDRESS_RESOLVER = DBUS_NAME + ".AddressResolver"
DBUS_INTERFACE_HOST_NAME_RESOLVER = DBUS_NAME + ".HostNameResolver"
DBUS_INTERFACE_SERVICE_RESOLVER = DBUS_NAME + ".ServiceResolver"
DBUS_INTERFACE_RECORD_BROWSER = DBUS_NAME + ".RecordBrowser"
def byte_array_to_string(s):
r = ""
for c in s:
if c >= 32 and c < 127:
r += "%c" % c
else:
r += "."
return r
def txt_array_to_string_array(t):
l = []
for s in t:
l.append(byte_array_to_string(s))
return l
def string_to_byte_array(s):
r = []
for c in s:
r.append(dbus.Byte(ord(c)))
return r
def string_array_to_txt_array(t):
l = []
for s in t:
l.append(string_to_byte_array(s))
return l
def dict_to_txt_array(txt_dict):
l = []
for k,v in txt_dict.items():
l.append(string_to_byte_array("%s=%s" % (k,v)))
return l
| RMerl/asuswrt-merlin | release/src/router/avahi-0.6.31/avahi-python/avahi/__init__.py | __init__.py | py | 3,082 | python | en | code | 6,715 | github-code | 36 | [
{
"api_name": "dbus.Byte",
"line_number": 94,
"usage_type": "call"
}
] |
41730576127 | # Create the grid
import numpy as np
import pygame
grid_size = 20
# The abstract representation of the grid.
# A nxn grid
grid = np.zeros((grid_size, grid_size))
pygame.init()
screen_width, screen_height = 600, 600
screen = pygame.display.set_mode((screen_width, screen_height))
clock = pygame.time.Clock()
class ClickableTile(pygame.sprite.Sprite):
def __init__(self, pos, size, state, position):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((size, size))
self.state = state
self.position = position
if self.state == 0:
self.image.fill('darkgrey')
else:
self.image.fill('white')
self.rect = self.image.get_rect(topleft=pos)
def on_click(self):
if self.state == 0:
self.image.fill('white')
self.state = 1
elif self.state == 1:
self.image.fill('darkgrey')
self.state = 0
class GridGenerator:
def __init__(self):
self.grid = np.zeros((grid_size, grid_size))
self.grid[-10:, :] = 1
self.setup_grid()
def setup_grid(self):
self.palette_group = pygame.sprite.Group()
p_tile = screen_width // grid_size
for i in range(grid_size):
for j in range(grid_size):
state = self.grid[i][j]
tile = ClickableTile(((j * p_tile), (i * p_tile)), p_tile - 1, state, position=(i, j))
self.palette_group.add(tile)
def update_grid(self):
for sprite in self.palette_group.sprites():
self.grid[sprite.position[0]][sprite.position[1]] = sprite.state
def print_grid(self):
print(self.grid)
def save_grid(self):
np.save('grid.npy', self.grid)
gridgenerator = GridGenerator()
# Define colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
pos = pygame.mouse.get_pos()
for sprite in gridgenerator.palette_group.sprites():
if sprite.rect.collidepoint(pos):
sprite.on_click()
gridgenerator.update_grid()
# print(gridgenerator.print_grid())
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
print("saved")
gridgenerator.save_grid()
gridgenerator.palette_group.draw(screen)
# Update the display
pygame.display.update()
clock.tick(30)
pygame.display.flip()
# Quit the game
pygame.quit()
| crimsondevi/PathThroughDestruction | grid.py | grid.py | py | 2,736 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "numpy.zeros",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "pygame.init",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "pygame.display.set_mode",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "pygame.display",
... |
20591380597 | from django.contrib.auth.models import AbstractUser
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from api_yamdb.settings import ADMIN, MODERATOR, ROLE_CHOICES, USER
from .validators import validate_year
class User(AbstractUser):
"""Модель пользователя, добавлено поле bio и role,
так же поле email теперь должно быть уникальным и не может быть пустым """
bio = models.TextField(max_length=500, blank=True)
role = models.CharField(
choices=ROLE_CHOICES,
blank=True, max_length=50,
default=USER)
email = models.EmailField(
unique=True, blank=False, max_length=254, verbose_name='email address')
confirmation_code = models.CharField(max_length=50, blank=True)
data_confirmation_code = models.DateTimeField(
auto_now_add=True,)
class Meta:
ordering = ['role']
verbose_name = 'Пользователь'
verbose_name_plural = 'Пользователи'
@property
def is_admin(self):
return self.role == ADMIN
@property
def is_user(self):
return self.role == USER
@property
def is_moderator(self):
return self.role == MODERATOR
# Categories, genres, titles
class Category(models.Model):
"""Category model"""
name = models.CharField(
max_length=256,
verbose_name="Category name",
)
slug = models.SlugField(
max_length=50,
unique=True,
verbose_name="Category slug",
)
class Meta:
verbose_name = 'Категория'
verbose_name_plural = 'Категории'
ordering = ['slug']
def __str__(self):
return self.slug
class Genre(models.Model):
"""Genre model"""
name = models.CharField(
max_length=256,
verbose_name="Genre name",
)
slug = models.SlugField(
max_length=50,
unique=True,
verbose_name="Genre slug",
)
class Meta:
verbose_name = 'Жанр'
verbose_name_plural = 'Жанры'
ordering = ['slug']
def __str__(self):
return self.slug
class Title(models.Model):
"""Title model"""
name = models.CharField(
max_length=100,
verbose_name="Product name",
)
year = models.PositiveSmallIntegerField(
verbose_name="The year of publishing",
validators=[validate_year],
)
category = models.ForeignKey(
Category,
blank=True,
null=True,
on_delete=models.SET_NULL,
related_name="titles",
verbose_name="Product category",
)
genre = models.ManyToManyField(
Genre,
blank=True,
related_name="titles",
verbose_name="Product genre",
)
description = models.CharField(
max_length=100,
blank=True,
null=True,
verbose_name="Product Description",
)
class Meta:
verbose_name = 'Произведение'
verbose_name_plural = 'Произведения'
ordering = ['name']
def __str__(self):
return self.name
class Review(models.Model):
title = models.ForeignKey(
Title,
verbose_name='Произведение',
on_delete=models.CASCADE,
related_name='reviews'
)
text = models.TextField(
verbose_name='Текст',
)
author = models.ForeignKey(
User,
verbose_name='Автор',
on_delete=models.CASCADE,
related_name='reviews',
)
score = models.PositiveSmallIntegerField(
verbose_name='Рейтинг',
validators=[MinValueValidator(1), MaxValueValidator(10)]
)
pub_date = models.DateTimeField(
verbose_name='Дата публикации',
auto_now_add=True,
db_index=True
)
class Meta:
verbose_name = 'Отзыв'
verbose_name_plural = 'Отзывы'
ordering = ['pub_date']
constraints = [
models.UniqueConstraint(
fields=['title', 'author'],
name='unique_review'
),
]
class Comment(models.Model):
review = models.ForeignKey(
Review,
verbose_name='Отзыв',
on_delete=models.CASCADE,
related_name='comments'
)
text = models.TextField(
verbose_name='Текст',
)
author = models.ForeignKey(
User,
verbose_name='Пользователь',
on_delete=models.CASCADE,
related_name='comments'
)
pub_date = models.DateTimeField(
verbose_name='Дата публикации',
auto_now_add=True,
db_index=True
)
class Meta:
verbose_name = 'Комментарий'
verbose_name_plural = 'Комментарии'
ordering = ['pub_date']
| QBC1/api_yamdb | api_yamdb/reviews/models.py | models.py | py | 4,957 | python | en | code | 2 | github-code | 36 | [
{
"api_name": "django.contrib.auth.models.AbstractUser",
"line_number": 9,
"usage_type": "name"
},
{
"api_name": "django.db.models.TextField",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "django.db.models",
"line_number": 13,
"usage_type": "name"
},
{
... |
12484573322 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path
from urllib.parse import urlparse
from urllib.request import urlretrieve
from sklearn.metrics import roc_auc_score
def download(url):
"""Downloads a file if it doesn't already exist.
Args:
url: string or Path
Returns: string filename
"""
pr = urlparse(url)
path = Path(pr.path)
filename = path.name
if not Path(filename).exists():
local_filename, headers = urlretrieve(url, filename)
assert local_filename == filename
print(f"Downloaded {filename}")
return filename
def download_data_files():
path = "https://raw.githubusercontent.com/drivendataorg/tutorial-flu-shot-learning/main/data/"
filenames = [
"training_set_features.csv",
"training_set_labels.csv",
"test_set_features.csv",
"submission_format.csv",
]
for filename in filenames:
url = f"{path}/{filename}"
download(url)
def decorate(**options):
"""Decorate the current axes.
Call decorate with keyword arguments like
decorate(title='Title',
xlabel='x',
ylabel='y')
The keyword arguments can be any of the axis properties
https://matplotlib.org/api/axes_api.html
"""
ax = plt.gca()
ax.set(**options)
handles, labels = ax.get_legend_handles_labels()
if handles:
ax.legend(handles, labels)
plt.tight_layout()
def crosstab(x, y):
"""Make a cross tabulation and normalize the columns as percentages.
Args:
x: sequence of values that go in the index
y: sequence of values that go in the columns
returns: DataFrame
"""
return pd.crosstab(x, y, normalize="columns") * 100
def value_counts(seq, **options):
"""Version of value_counts that works with any sequence type.
Args:
seq: sequence
options: passed to pd.Series.value_counts
Returns: pd.Series
"""
return pd.Series(seq).value_counts(**options)
def score_model(model, features_df, labels_df):
"""Compute the average AUC score for the two labels.
Args:
model: fitted Scikit-learn model
features_df: DataFrame of features
labels_df: DataFrame of labels
Returns: float AUC score
"""
pred1, pred2 = model.predict_proba(features_df)
y_pred1 = pred1.T[1]
score1 = roc_auc_score(labels_df["h1n1_vaccine"], y_pred1)
y_pred2 = pred2.T[1]
score2 = roc_auc_score(labels_df["seasonal_vaccine"], y_pred2)
return (score1 + score2) / 2
def make_submission(model, test_features_df):
"""Make a DataFrame ready for submission to the competition.
Args:
model: fitted Scikit-learn model
test_features_df: DataFrame of features
Returns: DataFrame of predicted probabilities
"""
pred1, pred2 = model.predict_proba(test_features_df)
d = dict(h1n1_vaccine=pred1.T[1], seasonal_vaccine=pred2.T[1])
return pd.DataFrame(d, index=test_features_df.index)
| drivendataorg/tutorial-flu-shot-learning | utils.py | utils.py | py | 3,053 | python | en | code | 2 | github-code | 36 | [
{
"api_name": "urllib.parse.urlparse",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "pathlib.Path",
"line_number": 21,
"usage_type": "call"
},
{
"api_name": "pathlib.Path",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "urllib.request.urlret... |
36953625709 | __all__ = [
'MatchesException',
'Raises',
'raises',
]
import sys
from testtools.compat import (
classtypes,
_error_repr,
isbaseexception,
istext,
)
from ._basic import MatchesRegex
from ._higherorder import AfterPreproccessing
from ._impl import (
Matcher,
Mismatch,
)
class MatchesException(Matcher):
"""Match an exc_info tuple against an exception instance or type."""
def __init__(self, exception, value_re=None):
"""Create a MatchesException that will match exc_info's for exception.
:param exception: Either an exception instance or type.
If an instance is given, the type and arguments of the exception
are checked. If a type is given only the type of the exception is
checked. If a tuple is given, then as with isinstance, any of the
types in the tuple matching is sufficient to match.
:param value_re: If 'exception' is a type, and the matchee exception
is of the right type, then match against this. If value_re is a
string, then assume value_re is a regular expression and match
the str() of the exception against it. Otherwise, assume value_re
is a matcher, and match the exception against it.
"""
Matcher.__init__(self)
self.expected = exception
if istext(value_re):
value_re = AfterPreproccessing(str, MatchesRegex(value_re), False)
self.value_re = value_re
expected_type = type(self.expected)
self._is_instance = not any(issubclass(expected_type, class_type)
for class_type in classtypes() + (tuple,))
def match(self, other):
if type(other) != tuple:
return Mismatch('%r is not an exc_info tuple' % other)
expected_class = self.expected
if self._is_instance:
expected_class = expected_class.__class__
if not issubclass(other[0], expected_class):
return Mismatch('%r is not a %r' % (other[0], expected_class))
if self._is_instance:
if other[1].args != self.expected.args:
return Mismatch('%s has different arguments to %s.' % (
_error_repr(other[1]), _error_repr(self.expected)))
elif self.value_re is not None:
return self.value_re.match(other[1])
def __str__(self):
if self._is_instance:
return "MatchesException(%s)" % _error_repr(self.expected)
return "MatchesException(%s)" % repr(self.expected)
class Raises(Matcher):
"""Match if the matchee raises an exception when called.
Exceptions which are not subclasses of Exception propogate out of the
Raises.match call unless they are explicitly matched.
"""
def __init__(self, exception_matcher=None):
"""Create a Raises matcher.
:param exception_matcher: Optional validator for the exception raised
by matchee. If supplied the exc_info tuple for the exception raised
is passed into that matcher. If no exception_matcher is supplied
then the simple fact of raising an exception is considered enough
to match on.
"""
self.exception_matcher = exception_matcher
def match(self, matchee):
try:
result = matchee()
return Mismatch('%r returned %r' % (matchee, result))
# Catch all exceptions: Raises() should be able to match a
# KeyboardInterrupt or SystemExit.
except:
exc_info = sys.exc_info()
if self.exception_matcher:
mismatch = self.exception_matcher.match(exc_info)
if not mismatch:
del exc_info
return
else:
mismatch = None
# The exception did not match, or no explicit matching logic was
# performed. If the exception is a non-user exception (that is, not
# a subclass of Exception on Python 2.5+) then propogate it.
if isbaseexception(exc_info[1]):
del exc_info
raise
return mismatch
def __str__(self):
return 'Raises()'
def raises(exception):
"""Make a matcher that checks that a callable raises an exception.
This is a convenience function, exactly equivalent to::
return Raises(MatchesException(exception))
See `Raises` and `MatchesException` for more information.
"""
return Raises(MatchesException(exception))
| mongodb/mongo | src/third_party/wiredtiger/test/3rdparty/testtools-0.9.34/testtools/matchers/_exception.py | _exception.py | py | 4,567 | python | en | code | 24,670 | github-code | 36 | [
{
"api_name": "_impl.Matcher",
"line_number": 23,
"usage_type": "name"
},
{
"api_name": "_impl.Matcher.__init__",
"line_number": 40,
"usage_type": "call"
},
{
"api_name": "_impl.Matcher",
"line_number": 40,
"usage_type": "name"
},
{
"api_name": "testtools.compat.i... |
16253007713 | #!/usr/bin/env python3
"""
Database Aggregator from a Kafka Consumer.
Author: Santhosh Balasa
Email: santhosh.kbr@gmail.com
Date: 18/May/2021
"""
import sys
import logging
import psycopg2
from kafka import KafkaConsumer
logging.basicConfig(
format=f"%(asctime)s %(name)s %(levelname)-8s %(message)s",
level=logging.INFO,
datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger(__name__)
# Global
BOOTSRAP_SERVER = "kafka-48ac8c2-santee-fabb.aivencloud.com:12059"
KAFKA_TOPIC = "website_checker"
DATABASE_NAME = "metrics_aggregator"
SERVICE_URI = f"postgres://avnadmin:caerdfvhm59zfn7b@pg-1f19cc97-santee-fabb.aivencloud.com:12057/{DATABASE_NAME}?sslmode=require"
# Kafka Consumer
consumer = KafkaConsumer(
KAFKA_TOPIC,
bootstrap_servers=BOOTSRAP_SERVER,
security_protocol="SSL",
ssl_cafile="kafkaCerts/ca.pem",
ssl_certfile="kafkaCerts/service.cert",
ssl_keyfile="kafkaCerts/service.key",
)
# PostgreSQL
try:
db_conn = psycopg2.connect(SERVICE_URI)
cursor = db_conn.cursor()
cursor.execute("SELECT current_database()")
result = cursor.fetchone()
logger.info(f"Successfully connected to Database: {result[0]}")
except:
logger.error(f"Failed to connect Database: {DATABASE_NAME}")
sys.exit(-1)
# SQL Tables
cursor.execute(
"""CREATE TABLE KEYS(
ID INT PRIMARY KEY NOT NULL,
DATETIME TEXT NOT NULL
);"""
)
cursor.execute(
"""CREATE TABLE VALUES(
ID INT PRIMARY KEY NOT NULL,
URL TEXT NOT NULL,
STATUS TEXT NOT NULL,
ELAPSED_TIME DOUBLE PRECISION NOT NULL
);"""
)
def main():
"""
Main function to consume from Kafka topic and aggregate it to Postgres SQL.
"""
logger.info("Connecting to Aiven PostgreSQL...")
logger.info("Kafka Consumption Begins...")
key_id = 1
for c in consumer:
print(
c.key.decode("utf-8"),
"->",
c.value.decode("utf-8"),
)
key = eval(c.key.decode("utf-8"))["time"] # Evaluate str to a dict
values = eval(c.value.decode("utf-8"))
url = values.get("url", "")
status = values.get("status", "")
elapsed_time = values.get("elapsed_time", 0)
cursor.execute(
f"""INSERT INTO KEYS (ID, DATETIME) \
VALUES ({key_id}, '{key}');"""
)
cursor.execute(
f"""INSERT INTO VALUES (ID, URL, STATUS, ELAPSED_TIME) \
VALUES ({key_id}, '{url}', '{status}', {elapsed_time});"""
)
cursor.execute("""SELECT * FROM VALUES""")
logger.info(cursor.fetchall())
key_id += 1
consumer.close()
if __name__ == "__main__":
main()
| sbalasa/WebMonitor | db_aggregator.py | db_aggregator.py | py | 2,697 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "logging.basicConfig",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "logging.INFO",
"line_number": 18,
"usage_type": "attribute"
},
{
"api_name": "logging.getLogger",
"line_number": 21,
"usage_type": "call"
},
{
"api_name": "kafka.KafkaCo... |
36777613557 | from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
driver = webdriver.Chrome()
driver.get('https://www.dummyticket.com/dummy-ticket-for-visa-application/')
driver.maximize_window()
driver.find_element(By.XPATH,"//span[@id='select2-billing_country-container']").click()
country_list = driver.find_elements(By.XPATH,"//span[@class='select2-results']/ul/li")
print(len(country_list))
for country in country_list:
if country.text == 'Australia' :
print(country.text)
country.click()
break | blessycheriyan/Selenium_From_Scratch | part-13/bootstrap.py | bootstrap.py | py | 651 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "selenium.webdriver.Chrome",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "selenium.webdriver",
"line_number": 6,
"usage_type": "name"
},
{
"api_name": "selenium.webdriver.common.by.By.XPATH",
"line_number": 10,
"usage_type": "attribute"
},
{
... |
12507519121 | # BFS
# 이모티콘
from collections import deque
s = int(input())
q = deque([(1, 0, 0)]) # 만들어진 이모티콘, 시간
visited = [[False] * 1001 for _ in range(1001)]
visited[1][0] = True
while q:
now, copy, sec = q.popleft()
if now == s:
print(sec)
break
for i in ((now, now), (now+copy, copy), (now-1, copy)):
now2, copy2 = i
if 0 < now2 <= 1000 and 0 < copy2 <= 1000:
if not visited[now2][copy2]:
q.append((now2, copy2, sec+1))
visited[now2][copy2] = True
| Hong-Jinseo/Algorithm | baekjoon/14226.py | 14226.py | py | 565 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "collections.deque",
"line_number": 7,
"usage_type": "call"
}
] |
71760950503 | """module for containing the code that produces charts"""
import os
from bokeh.charts import Bar, output_file, show, Line
from bokeh.models import HoverTool
# bar chart showing total response by HH group split by digital/paper
def bar_response(results_list, output_path):
output_dir = os.path.join(output_path, "charts")
if os.path.isdir(output_dir) is False:
os.mkdir(output_dir)
tools = "pan,wheel_zoom,box_zoom,reset,hover,save"
for df in results_list:
print(df)
p = Bar(df, label='hh_type', values='perc_res', stack='digital', title="a_title",
legend='top_right', tools=tools)
hover = p.select_one(HoverTool)
hover.point_policy = "follow_mouse"
hover.tooltips = [
("count", "@height"),
]
output_file_path = os.path.join(output_dir, 'test bar.html')
output_file(output_file_path)
show(p)
def line_response(results_list, output_path):
# as http://bokeh.pydata.org/en/0.10.0/docs/gallery/line_chart.html
# create df in correct format...
pass | ONSdigital/FOCUS | create_graphs.py | create_graphs.py | py | 1,086 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "os.path.join",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 10,
"usage_type": "attribute"
},
{
"api_name": "os.path.isdir",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": ... |
3855782251 | # %%
from sklearn.datasets import load_sample_image
import matplotlib.pyplot as plt
import seaborn as sns
with sns.axes_style('dark'):
img = load_sample_image('china.jpg')
plt.imshow(img)
# %%
print (img.shape)
# Rescacle the color so that they lie btw 0 and 1, then reshape the array to be
# a typical scikit-learn input
img_r = (img / 255).reshape(-1,3)
print (img_r.shape)
# %%
from sklearn.cluster import KMeans
import numpy as np
k_colors = KMeans(n_clusters=3).fit(img_r)
y_pred = k_colors.predict(img_r)
centers = k_colors.cluster_centers_
labels = k_colors.labels_
new_img = k_colors.cluster_centers_[k_colors.labels_]
new_img = np.reshape(new_img, (img.shape))
# %%
fig = plt.figure(figsize=(10,10))
ax=fig.add_subplot(1,2,1,xticks=[],yticks=[],title='Original Image')
ax.imshow(img)
ax=fig.add_subplot(1,2,2,xticks=[],yticks=[],
title='Color Compressed Image using K-Means')
ax.imshow(new_img)
plt.show()
# %%
# %%
# %%
# %%
| haininhhoang94/wqu | MScFE650/Kmean_image.py | Kmean_image.py | py | 962 | python | en | code | 21 | github-code | 36 | [
{
"api_name": "seaborn.axes_style",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "sklearn.datasets.load_sample_image",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot.imshow",
"line_number": 7,
"usage_type": "call"
},
{
"api_n... |
74901731943 | import time
import numpy as np
from librosa import load, stft, istft, resample
from librosa.output import write_wav
from sklearn.cluster import MiniBatchKMeans, FeatureAgglomeration
from sklearn import datasets
import warnings
# import matplotlib.pyplot as plt
import mir_eval
import corpus
from scipy.io import loadmat
class beta_NTF(object):
def __init__(self, W, H, X, A, sigma_b, Q, V, K_partition,
epochs=20, debug=False, beta=0):
super(beta_NTF, self).__init__()
# np.seterr(all='warn')
#
# warnings.filterwarnings('error')
self._epochs = epochs
self._debug = debug
self._V = V
self._W = W
self._H = H
self._A = A
self._Q = Q
self._sigma_b = sigma_b
self._Xb = X
self._K_partition = K_partition
self.I, self.F, self.T = X.shape
self.K = W.shape[1]
self.J = Q.shape[0]
self.IJ = self.I*self.J
self.O = np.ones((1,self.T))
self.source_ind = []
for j in range(self.J):
self.source_ind.append(np.arange(0,self.K/self.J)+(j*(self.K/self.J)))
def train(self):
for epoch in range(self._epochs):
# print(epoch)
sigma_ss = np.zeros((self.I,self.J,self.F,self.T))
for i in range(self.I):
sigma_ss[i,:,:,:] = self._V[:,:,:]
sigma_ss = sigma_ss.reshape((self.IJ, self.F, self.T))
sigma_x = np.zeros((self.I,self.I,self.F,self.T), dtype=complex)
inv_sigma_x = np.zeros((self.I,self.I,self.F,self.T), dtype=complex)
Gs = np.zeros((self.I,self.IJ,self.F,self.T), dtype=complex)
s_hat = np.zeros((self.IJ, self.F, self.T), dtype=complex)
bar_Rxs = np.zeros((self.I, self.IJ, self.F, self.T), dtype=complex)
bar_Rss_full = np.zeros((self.IJ, self.IJ, self.F, self.T), dtype=complex)
bar_Rxx = np.zeros((self.I, self.I, self.F, self.T), dtype=complex)
bar_P = np.zeros((self.J, self.F, self.T))
bar_A = np.zeros((self.I, self.F, self.K))
Vc = np.zeros((self.F, self.T, self.K))
W_prev = self._W
H_prev = self._H
A_prev = self._A
sig_b_prev = self._sigma_b
sigma_x[0,0,:,:] = np.matmul(self._sigma_b, self.O)
sigma_x[1,1,:,:] = np.matmul(self._sigma_b, self.O)
for ij in range(self.IJ):
sigma_x[0,0,:,:] = sigma_x[0,0,:,:] + np.multiply(np.matmul(np.power(np.abs(self._A[0,ij,:].reshape((self.F, 1))), 2), self.O), sigma_ss[ij,:,:])
sigma_x[0,1,:,:] = sigma_x[0,1,:,:] + np.multiply(np.matmul(np.multiply(self._A[0,ij,:], np.conj(self._A[1,ij,:])).reshape((self.F, 1)), self.O), sigma_ss[ij,:,:])
sigma_x[1,0,:,:] = np.conj(sigma_x[0,1,:,:])
sigma_x[1,1,:,:] = sigma_x[1,1,:,:] + np.multiply(np.matmul(np.power(np.abs(self._A[1,ij,:].reshape((self.F, 1))), 2), self.O), sigma_ss[ij,:,:])
try:
det_sigma_x = np.multiply(sigma_x[0, 0, :, :], sigma_x[1,1,:,:]) - np.power(np.abs(sigma_x[0,1,:,:]),2)
inv_sigma_x [0,0,:,:] = np.divide(sigma_x[1,1,:,:], det_sigma_x)
inv_sigma_x [0,1,:,:] = np.negative(np.divide(sigma_x[0,1,:,:], det_sigma_x))
inv_sigma_x [1,0,:,:] = np.conj(inv_sigma_x [0,1,:,:])
inv_sigma_x [1,1,:,:] = np.divide(sigma_x[0,0,:,:], det_sigma_x)
except Warning:
scale = np.sum(self._W, axis=0)
print(scale)
# print(self._H)
print(det_sigma_x)
#correct till here
for ij in range(self.IJ):
Gs[0,ij,:,:] = np.multiply(np.multiply(np.matmul(np.conj(self._A[0,ij,:].reshape((self.F, 1))), self.O), inv_sigma_x [0,0,:,:]) + \
np.multiply(np.matmul(np.conj(self._A[1,ij,:].reshape((self.F, 1))), self.O), inv_sigma_x [1,0,:,:]),
sigma_ss[ij,:,:])
Gs[1,ij,:,:] = np.multiply(np.multiply(np.matmul(np.conj(self._A[0,ij,:].reshape((self.F, 1))), self.O), inv_sigma_x [0,1,:,:]) + \
np.multiply(np.matmul(np.conj(self._A[1,ij,:].reshape((self.F, 1))), self.O), inv_sigma_x [1,1,:,:]),
sigma_ss[ij,:,:])
s_hat[ij,:,:] = np.multiply(Gs[0,ij,:,:], self._Xb[0,:,:]) + np.multiply(Gs[1,ij,:,:], self._Xb[1,:,:])
bar_Rxs[0, ij, :, :] = np.multiply(self._Xb[0,:,:], np.conj(s_hat[ij,:,:]))
bar_Rxs[1, ij, :, :] = np.multiply(self._Xb[1,:,:], np.conj(s_hat[ij,:,:]))
# correct till here
for j1 in range(self.IJ):
for j2 in range(self.IJ):
bar_Rss_full[j1, j2, :, :] = np.multiply(s_hat[j1, :, :], np.conj(s_hat[j2, :, :])) - \
np.multiply(np.multiply(Gs[0, j1, :, :], np.matmul(self._A[0,j2,:].reshape((self.F, 1)), self.O)) + \
np.multiply(Gs[1, j1, :, :], np.matmul(self._A[1,j2,:].reshape((self.F, 1)), self.O)),
sigma_ss[j2,:,:])
bar_Rss_full[j1,j1,:,:] = bar_Rss_full[j1,j1,:,:] + sigma_ss[j1,:,:]
# need to check bar_Rss_full calculation very carefully there is a tiny error
for j in range(self.J):
start_index = (j*self.I)
end_index = (j+1) * self.I
temp_P = np.zeros((self.I, self.F, self.T))
P_i = 0
for i in range(start_index, end_index):
temp_P[P_i, :, :] = np.real(bar_Rss_full[i,i,:,:])
P_i = P_i + 1
bar_P[j, :, :] = np.mean(temp_P, axis=0)
# correct till here
bar_Rxx[0,0,:,:] = np.power(np.abs(self._Xb[0,:,:]),2)
bar_Rxx[0,1,:,:] = np.multiply(self._Xb[0,:,:], np.conj(self._Xb[1,:,:]))
bar_Rxx[1,0,:,:] = np.conj(bar_Rxx[0,1,:,:])
bar_Rxx[1,1,:,:] = np.power(np.abs(self._Xb[1,:,:]),2)
# outers are correct middle has a small error
for f in range(self.F):
self._A[:,:,f] = np.matmul(np.mean(bar_Rxs[:,:,f,:], axis=2),np.linalg.inv(np.mean(bar_Rss_full[:,:,f,:], axis=2)))
for f in range(self.F):
self._sigma_b[f] = 0.5 * np.real(np.trace(np.mean(bar_Rxx[:,:,f,:],axis=2) - \
np.matmul(self._A[:,:,f], np.conj(np.transpose(np.mean(bar_Rxs[:,:,f,:],axis=2)))) - \
np.matmul(np.mean(bar_Rxs[:,:,f,:],axis=2), np.conj(np.transpose(self._A[:,:,f]))) + \
np.matmul(np.matmul(self._A[:,:,f], np.mean(bar_Rss_full[:,:,f,:],axis=2)),
np.conj(np.transpose(self._A[:,:,f])))))
# correct till here
self.calculate_V()
VP_neg = np.multiply(np.power(self._V, -2), bar_P)
V_pos = np.power(self._V, -1)
WoH = np.zeros((self.F, self.T, self.K))
for k in range(self.K):
W_k = self._W[:,k].reshape(-1,1)
H_k = self._H[k,:].reshape(1,-1)
WoH[:,:,k] = np.matmul(W_k, H_k)
Q_num = np.matmul(VP_neg.reshape((self.J, self.F*self.T)), WoH.reshape((self.F*self.T, self.K)))
Q_den = np.matmul(V_pos.reshape((self.J, self.F*self.T)), WoH.reshape((self.F*self.T, self.K)))
self._Q = np.multiply(self._Q, np.divide(Q_num, Q_den))
QoH = self.calculate_V()
VP_neg = np.multiply(np.power(self._V, -2), bar_P)
V_pos = np.power(self._V, -1)
W_num = np.matmul(np.moveaxis(VP_neg, 1, 0).reshape((self.F, self.J*self.T)), QoH.reshape((self.J*self.T, self.K)))
W_den = np.matmul(np.moveaxis(V_pos, 1, 0).reshape((self.F, self.J*self.T)), QoH.reshape((self.J*self.T, self.K)))
self._W = np.multiply(self._W, np.divide(W_num, W_den))
QoW = np.zeros((self.J, self.F, self.K))
for k in range(self.K):
Q_k = self._Q[:,k].reshape((-1, 1))
W_k = self._W[:,k].reshape((1,-1))
QoW[:,:,k] = np.matmul(Q_k, W_k)
self.calculate_V()
VP_neg = np.multiply(np.power(self._V, -2), bar_P)
V_pos = np.power(self._V, -1)
H_num = np.matmul(VP_neg.reshape((self.J*self.F,self.T)).transpose(), QoW.reshape((self.J*self.F, self.K)))
H_den = np.matmul(V_pos.reshape((self.J*self.F,self.T)).transpose(), QoW.reshape((self.J*self.F, self.K)))
self._H = np.multiply(self._H, np.divide(H_num, H_den).transpose())
# small error in V and H
for j in range(self.J):
nonzero_f_ind = np.nonzero(self._A[0, j, :])
self._A[1, j, nonzero_f_ind] = np.divide(self._A[1, j, nonzero_f_ind], self.sign(self._A[0,j,nonzero_f_ind]))
self._A[0, j, nonzero_f_ind] = np.divide(self._A[0, j, nonzero_f_ind], self.sign(self._A[0,j,nonzero_f_ind]))
A_scale = np.power(np.abs(self._A[0,j,:]),2) + np.power(np.abs(self._A[1,j,:]),2)
self._A[:, j,:] = np.divide(self._A[:, j,:], np.tile(np.sqrt(A_scale).reshape(1,-1),(self.I,1)))
self._W[:,self.source_ind[j]] = np.multiply(self._W[:,self.source_ind[j]], np.matmul(A_scale.reshape(-1,1),np.ones((1,len(self.source_ind[j])))))
#
# print(self._A[0,0,0])
# print(self._A[0,1,1])
# print(self._A[1,0,0])
# print(self._A[1,1,1])
scale = np.sum(self._Q, axis=0)
self._Q = np.multiply(self._Q, np.tile(np.power(scale,-1),(self.J,1)))
self._W = np.multiply(self._W, np.tile(scale,(self.F,1)))
scale = np.sum(self._W, axis=0).reshape(1,-1)
self._W = np.multiply(self._W, np.tile(np.power(scale,-1),(self.F,1)))
self._H = np.multiply(self._H, np.tile(scale.transpose(),(1,self.T)))
#
self.calculate_V()
# print(self._V[0,0,0])
# print(self._V[0,1,1])
# print(self._V[1,0,0])
# print(self._V[1,1,1])
criterion = np.sum(np.divide(bar_P, self._V) - np.log(np.divide(bar_P, self._V))) - self.J*self.F*self.T
def sign(self, x):
return np.divide(x,np.abs(x))
def calculate_V(self):
QoH = np.zeros((self.J, self.T, self.K))
for k in range(self.K):
Q_k = self._Q[:,k].reshape((-1, 1))
H_k = self._H[k,:].reshape((1,-1))
QoH[:,:,k] = np.matmul(Q_k, H_k)
self._V = np.zeros((self.J, self.F, self.T))
for j in range(self.J):
self._V[j, :, :] = np.matmul(self._W, QoH[j,:,:].reshape((self.T, self.K)).transpose())
return QoH
def reconstruct(self):
Y = np.zeros((self.I,self.J,self.F,self.T), dtype=complex)
for t in range(self.T):
for f in range(self.F):
RV = np.zeros((self.I, self.I))
for j in range(self.J):
start_index = (j*self.I)
end_index = (j+1) * self.I
RV = RV + (np.matmul(self._A[:,start_index:end_index,f],np.conj(np.transpose(self._A[:,start_index:end_index,f]))) * self._V[j,f,t])
for j in range(self.J):
start_index = (j*self.I)
end_index = (j+1) * self.I
R = np.matmul(self._A[:,start_index:end_index,f],np.conj(np.transpose(self._A[:,start_index:end_index,f])))
Y[:,j,f,t] = np.matmul(np.matmul((R * self._V[j,f,t]), np.linalg.inv(RV)), self._Xb[:,f,t])
return Y
def getAV(self):
return self._A, self._V
if __name__ == '__main__':
# I = 2
# F = 50
# T = 200
# J = 2
# IJ = I * J
# K_partition = np.asarray([20,20])
# K = np.sum(K_partition)
# X = np.random.randn(I,F,T)
# V = np.random.rand(I,F,T)
# mix_psd = 0.5 * (np.mean(np.power(np.abs(X[0,:,:]),2) + np.power(np.abs(X[1,:,:]),2),axis=1))
# mix_psd = mix_psd.reshape((-1, 1))
# A = 0.5 * np.multiply(1.9 * np.abs(np.random.randn(I,IJ,F)) + 0.1 * np.ones((I,IJ,F)),np.sign(np.random.randn(I,IJ,F) + 1j *np.random.randn(I,IJ,F)))
# W = 0.5 * np.multiply(np.abs(np.random.randn(F,K)) + np.ones((F,K)), np.matmul(mix_psd, np.ones((1,K))))
# H = 0.5 * np.abs(np.random.randn(K,T)) + np.ones((K,T))
# Q = 0.5 * np.abs(np.random.randn(J,K)) + np.ones((J,K))
# sigma_b = mix_psd / 100
#
# QoH = np.zeros((J, T, K))
# for k in range(K):
# Q_k = Q[:,k].reshape((-1, 1))
# H_k = H[k,:].reshape((1,-1))
# QoH[:,:,k] = np.matmul(Q_k, H_k)
#
# V = np.zeros((J, F, T))
# for j in range(J):
# V[j, :, :] = np.matmul(W, QoH[j,:,:].reshape((K, T)))
K_partition = np.asarray([20,20,20])
A = loadmat('mat_files/saveA.mat')['A']
W = loadmat('mat_files/saveW.mat')['W']
H = loadmat('mat_files/saveH.mat')['H']
Q = loadmat('mat_files/saveQ.mat')['Q']
V = loadmat('mat_files/saveV.mat')['V']
X = loadmat('mat_files/saveX.mat')['x']
sigma_b = loadmat('mat_files/saveSig_b.mat')['sig_b']
bn = beta_NTF(W, H, X, A, sigma_b, Q, V, K_partition, epochs=22)
bn.train()
bn.reconstruct()
| TeunKrikke/SourceSeparationNMF | CovNTF/beta_ntf_np.py | beta_ntf_np.py | py | 13,598 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "numpy.ones",
"line_number": 41,
"usage_type": "call"
},
{
"api_name": "numpy.arange",
"line_number": 44,
"usage_type": "call"
},
{
"api_name": "numpy.zeros",
"line_number": 49,
"usage_type": "call"
},
{
"api_name": "numpy.zeros",
"line_number": ... |
71607160424 | import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
import pyximport
pyximport.install()
import heat_solver
def coeff_dis(x):
alpha2 = np.zeros(len(x))
for i in range(len(x)):
if x[i] > 0.5:
alpha2[i]= 10
elif x[i]< 0.3:
alpha2[i]= 5
else:
alpha2[i] = 1
return alpha2
def coeff_step(x):
alpha2 = np.zeros(len(x))
for i in range(len(x)):
if x[i] < 0.5:
alpha2[i]= 10
else:
alpha2[i] = 1
return alpha2
hinv = 10
kinv = 600
time600 = np.linspace(0,1,num=kinv+1)
x = np.linspace(0,1,num = hinv+1 )
alpha = coeff_dis(x)
u_600 = heat_solver.heat_solver_nl(hinv,kinv, alpha)
hinv = 20
kinv = 2400
x = np.linspace(0,1,num = hinv+1 )
time2400 = np.linspace(0,1,num=kinv+1)
alpha = coeff_dis(x)
u_2400 = heat_solver.heat_solver_nl(hinv,kinv, alpha)
hinv = 40
kinv = 9600
x = np.linspace(0,1,num = hinv+1 )
alpha = coeff_dis(x)
time9600 = np.linspace(0,1,num=kinv+1)
u_9600 = heat_solver.heat_solver_nl(hinv,kinv, alpha)
hinv = 80
kinv = 9600*4
x = np.linspace(0,1,num = hinv+1 )
alpha = coeff_dis(x)
time1000 = np.linspace(0,1,num=kinv+1)
u_1000 = heat_solver.heat_solver_nl(hinv,kinv, alpha)
x = np.linspace(0,1,num=11)
x21 = np.linspace(0,1,num = 21)
u_24 = interpolate.interp1d(x21,u_2400[1,:])
x41 = np.linspace(0,1,num=41)
u_96 = interpolate.interp1d(x41,u_9600[1,:])
x81 = np.linspace(0,1,num = 81 )
u_10 = interpolate.interp1d(x81,u_1000[1,:])
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
ax1.plot(x,u_600[1,:], label = 'h=1/10')
ax1.plot(x21,u_2400[1,:], label = 'h=1/20')
ax1.plot(x41,u_9600[1,:], label ='h=1/40')
ax1.plot(x81,u_1000[1,:], label ='h=1/80')
ax1.set_title('u at t=1 with $\\alpha$ discontinuous')
ax1.set_xlabel('x')
ax1.set_ylabel('u')
ax1.legend()
plt.savefig('unl_convdis2.pdf', bbox_inches=0)
p_space = np.log((u_600[1,1:10]-u_24(x[1:10]))/(u_24(x[1:10])-u_96(x[1:10])))/np.log(2.)
#print 'spatial convergence order for lambda = 1/6 is ', p_space
p_time = np.log((u_600[1,1:10]-u_24(x[1:10]))/(u_24(x[1:10])-u_96(x[1:10])))/np.log(4.)
#print 'temporal convergence order for lambda = 1/6 is ', p_time
f3, ((ax3,ax4,ax5)) = plt.subplots(3, sharex=True)
ax3.plot(x[1:10],p_space, label = 'space')
ax4.plot(x[1:10],p_time, label = 'time')
ax3.set_title('order of convergence for discontinuous $\\alpha$')
ax3.set_ylabel('p')
ax4.set_ylabel('p')
ax3.legend()
ax4.legend()
ax5.plot(x,1./20*coeff_dis(x), label='$\\alpha\lambda$', marker = 'o')
ax5.set_title('$\\alpha\lambda$ for constant k nonlinear case, $\\alpha$ discontinuous')
ax5.set_xlabel('x')
ax5.set_ylabel('$\\alpha\lambda$')
ax5.set_ylim(bottom=0, top= 0.6)
ax5.legend()
plt.savefig('unl_orderconvdis2.pdf', bbox_inches=0) | jedman/numerics | src1/heat_nl_dis.py | heat_nl_dis.py | py | 2,702 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pyximport.install",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "numpy.zeros",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "numpy.zeros",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "numpy.linspace",
"line_nu... |
4109177627 | import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd
import pickle
import json
import dash_table
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
"""load model"""
with open("/Users/Arsal/examples/raltime_anomaly/model_svm.pkl", 'rb+') as f:
model = pickle.load(f)
"""read_test_data"""
with open("/Users/Arsal/examples/raltime_anomaly/test_df.json", 'r') as myfile:
data = json.load(myfile)
to= pd.DataFrame.from_dict(data[0].values()).T
prediction = model.predict(to)
"""read_columns"""
with open("/Users/Arsal/examples/raltime_anomaly/model_columns.pkl", 'rb+') as col:
cols= pickle.load(col)
# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df = pd.DataFrame({
"Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
"Amount": [4, 1, 2, 2, 4, 5],
"City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})
fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group")
app.layout = html.Div(children=[
html.H1(children='Hello Dash'),
html.Div(children='''
Dash: A web application framework for Python.
'''),
# dcc.Graph(
# id='example-graph',
# figure=fig
# ),
dcc.ConfirmDialog(id="table_anomaly")
])
app.layout = dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in df.columns],
data=df.to_dict('records'),
)
if __name__ == '__main__':
app.run_server(debug=True) | arsalhuda24/credit_card_fraud_detection | fraud_detection/dash-app/app.py | app.py | py | 1,654 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "dash.Dash",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "pickle.load",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "json.load",
"line_number": 22,
"usage_type": "call"
},
{
"api_name": "pandas.DataFrame.from_dict",
"lin... |
35862373343 | import logging
import time
from aiogram import F, Router
from aiogram.fsm.context import FSMContext
from aiogram.types import CallbackQuery, InlineKeyboardMarkup, Message
from sqlalchemy.orm import Session
from keyboards.keyboards import (
back_keyboard,
pagination_keyboard,
yes_no_keyboard,
)
from keyboards.methodist_keyboards import (
add_category_keyboard,
category_keyboard_methodist,
confirm_category_keyboard,
edit_category_keyboard,
methodist_profile_keyboard,
)
from lexicon.lexicon import BUTTONS, LEXICON
from utils.db_commands import (
category_deleting,
create_category,
get_all_categories,
select_user,
set_category_param,
)
from utils.pagination import PAGE_SIZE
from utils.states_form import AddCategory, CategoryList, EditCategory
from utils.utils import generate_categories_list, get_category_info
logger = logging.getLogger(__name__)
methodist_category_router = Router()
# Обработчики добавления категории
@methodist_category_router.message(
F.text.in_(
[
BUTTONS["RU"]["add_category"],
BUTTONS["TT"]["add_category"],
BUTTONS["EN"]["add_category"],
]
)
)
async def add_category(message: Message, session: Session):
"""Обработчик кнопки Добавить категорию."""
try:
user = select_user(session, message.from_user.id)
language = user.language
lexicon = LEXICON[language]
await message.answer(
lexicon["add_category"],
reply_markup=add_category_keyboard(language),
)
except KeyError as err:
logger.error(f"Ошибка в ключе при добавлении категории в базу: {err}")
except Exception as err:
logger.error(f"Ошибка при добавлении категории в базу: {err}")
@methodist_category_router.callback_query(F.data == "ready_category")
async def start_add_category(
query: CallbackQuery, state: FSMContext, session: Session
):
"""Начинает сценарий добавления категории в базу."""
try:
await query.answer()
await state.clear()
user = select_user(session, query.from_user.id)
language = user.language
lexicon = LEXICON[language]
await state.update_data(language=language)
await state.set_state(AddCategory.name)
await query.message.answer(lexicon["send_category_name"])
await query.message.delete()
except KeyError as err:
logger.error(f"Ошибка в ключе при запросе названия категории: {err}")
except Exception as err:
logger.error(f"Ошибка при запросе названия категории: {err}")
@methodist_category_router.message(AddCategory.name)
async def process_add_category_name(
message: Message, state: FSMContext, session: Session
):
"""Обработчик принимает имя категории, сохраняет категорию в БД.
Просит прислать сообщение.
Отправляет собранные данные для подтверждения корректности
или для перехода к редактированию.
"""
try:
data = await state.get_data()
await state.clear()
language = data["language"]
lexicon = LEXICON[language]
data["name"] = message.text
category_created = create_category(session, data)
if not category_created:
await message.answer(
lexicon["error_adding_category"],
reply_markup=methodist_profile_keyboard(language),
)
return
category_info = get_category_info(data["name"], lexicon, session)
info = category_info["info"]
category_id = category_info["id"]
# Собираем пагинацию для списка категорий, если пользователь
# перейдет к редактированию созданной категории
categories = get_all_categories(session)
page_info = generate_categories_list(
categories=categories,
lexicon=lexicon,
current_page=0,
page_size=PAGE_SIZE,
)
categories_ids = page_info["categories_ids"]
new_current_page = page_info["current_page"]
query_id = None
for key in categories_ids.keys():
if categories_ids[key] == categories_ids:
query_id = key
await state.set_state(EditCategory.confirm_task)
await state.update_data(
category_id=category_id,
query_id=query_id,
current_page=new_current_page,
task_info=page_info,
language=language,
)
# Сообщаем пользователю, что сейчас покажем, что получилось
await message.answer(lexicon["confirm_adding_category"])
time.sleep(2)
# Показываем, что получилось
await message.answer(
info, reply_markup=confirm_category_keyboard(language)
)
except KeyError as err:
logger.error(
f"Ошибка в ключе при запросе подтверждения категории: {err}"
)
except Exception as err:
logger.error(f"Ошибка при запросе подтверждения категории: {err}")
@methodist_category_router.callback_query(F.data == "edit_category")
async def process_edit_category(query: CallbackQuery, state: FSMContext):
"""Обарботчик инлайн кнопки Редактировать категорию.
Начинает сценарий внесения изменений в базу.
"""
try:
await query.answer()
data = await state.get_data()
language = data["language"]
query_id = data["query_id"]
lexicon = LEXICON[language]
await query.message.answer(
lexicon["start_edit_category"],
reply_markup=edit_category_keyboard(language, cd=query_id),
)
await query.message.delete()
except KeyError as err:
logger.error(
f"Ошибка в ключе при начале редактирования категории: {err}"
)
except Exception as err:
logger.error(f"Ошибка при начале редактирования категории: {err}")
@methodist_category_router.callback_query(F.data == "edit_category_name")
async def edit_category_name(query: CallbackQuery, state: FSMContext):
"""Обработчик создает состояние для смены названия категории.
Просит прислать сообщение.
"""
try:
await query.answer()
data = await state.get_data()
await state.set_state(EditCategory.name)
language = data["language"]
lexicon = LEXICON[language]
await query.message.answer(lexicon["edit_category_name"])
await query.message.delete()
except KeyError as err:
logger.error(
"Ошибка в ключевом слове при запросе нового "
f"названия категории: {err}"
)
except Exception as err:
logger.error(f"Ошибка при запросе нового названия категории: {err}")
@methodist_category_router.message(EditCategory.name)
async def process_edit_name(
message: Message, state: FSMContext, session: Session
):
"""Обрабатывает сообщение для изменения названия категории."""
try:
data = await state.get_data()
language = data["language"]
query_id = data["query_id"]
lexicon = LEXICON[language]
category_saved = set_category_param(
session, category_id=data["category_id"], name=message.text
)
if not category_saved:
await message.answer(
lexicon["error_adding_category"],
reply_markup=methodist_profile_keyboard(language),
)
return
await message.answer(
lexicon["category_edited"],
reply_markup=edit_category_keyboard(language, cd=query_id),
)
except KeyError as err:
logger.error(
f"Ошибка в ключевом слове при изменении названия категории: {err}"
)
except Exception as err:
logger.error(f"Ошибка при изменении названия категории: {err}")
@methodist_category_router.callback_query(
F.data.in_({"back_to_category_list", "category:next", "category:previous"})
)
async def show_category_list_callback(query: CallbackQuery, state: FSMContext):
"""Обарботчик кнопки Посмотреть/редактировать категории.
Показывает все созданные категории с пагинацией.
"""
try:
await query.answer()
data = await state.get_data()
categories = data["task_info"]["categories"]
current_page = data["current_page"]
language = data["language"]
lexicon = LEXICON[language]
if query.data == "category:next":
current_page += 1
elif query.data == "category:previous":
current_page -= 1
page_info = generate_categories_list(
categories=categories,
lexicon=lexicon,
current_page=current_page,
page_size=PAGE_SIZE,
methodist=True,
)
msg = page_info["msg"]
first_item = page_info["first_item"]
final_item = page_info["final_item"]
new_current_page = page_info["current_page"]
lk_button = {
"text": BUTTONS[language]["lk"],
"callback_data": "profile",
}
await state.set_state(CategoryList.categories)
await state.update_data(
categories=categories,
current_page=new_current_page,
task_info=page_info,
)
if query.data == "back_to_category_list":
# Возвращаемся со страницы категории,
# текст нельзя редактировать
await query.message.answer(
msg,
reply_markup=pagination_keyboard(
buttons_count=len(categories),
start=first_item,
end=final_item,
cd="category",
page_size=PAGE_SIZE,
extra_button=lk_button,
),
)
await query.message.delete()
return
await query.message.edit_text(
msg,
reply_markup=pagination_keyboard(
buttons_count=len(categories),
start=first_item,
end=final_item,
cd="category",
page_size=PAGE_SIZE,
extra_button=lk_button,
),
)
except KeyError as err:
logger.error(f"Ошибка в ключе при просмотре списка категорий: {err}")
except Exception as err:
logger.error(f"Ошибка при просмотре списка категорий: {err}")
@methodist_category_router.callback_query(
F.data.startswith("back_to_category:") | F.data.startswith("category:")
)
@methodist_category_router.callback_query(F.data == "no:delete_category")
async def show_category(
query: CallbackQuery, state: FSMContext, session: Session
):
"""Обработчик кнопок выбора отдельной категории.
Получаем условный id категории из callback_data, достаем реальный id из
состояние Data и получаем полную инфу о категории из базы данных.
"""
try:
await query.answer()
data = await state.get_data()
if not data:
user = select_user(session, query.from_user.id)
await query.message.answer(
LEXICON[user.language]["error_getting_category"],
reply_markup=InlineKeyboardMarkup(
inline_keyboard=category_keyboard_methodist(user.language)
),
)
return
language = data["language"]
lexicon = LEXICON[language]
# Достаем id категории из состояния и делаем запрос к базе
if "category_id" in data:
category_id = data["category_id"]
elif ("category_ids" in data) and query.data.startswith("category:"):
category_ids = int(query.data.split(":")[-1])
category_id = data["category_ids"][category_ids]
elif ("categories_ids" in data) and query.data.startswith("category:"):
category_ids = int(query.data.split(":")[-1])
category_id = data["categories_ids"][category_ids]
category_info = get_category_info(category_id, lexicon, session)
info = category_info["info"]
msg = f"{lexicon['category_chosen']}\n\n" f"{info}\n\n"
await state.set_state(EditCategory.category_id)
await state.update_data(category_id=category_id, query_id=category_id)
await query.message.answer(
msg, reply_markup=category_keyboard_methodist(language)
)
await query.message.delete()
except KeyError as err:
logger.error(f"Ошибка в ключевом слове при получении категории: {err}")
except Exception as err:
logger.error(f"Ошибка при получении категории: {err}")
@methodist_category_router.callback_query(
EditCategory.confirm_task, F.data == "confirm"
)
async def process_saving_category_to_db(
query: CallbackQuery, state: FSMContext
):
"""Обработчик кнопки Подтверждаю."""
try:
await query.answer()
data = await state.get_data()
await state.clear()
language = data["language"]
lexicon = LEXICON[language]
await query.message.answer(
lexicon["category_added"],
reply_markup=methodist_profile_keyboard(language),
)
await query.message.delete()
except KeyError as err:
logger.error(f"Ошибка в ключе при добавлении категории: {err}")
except Exception as err:
logger.error(f"Ошибка при добавлении категории: {err}")
@methodist_category_router.message(
F.text.in_(
[
BUTTONS["RU"]["category_list"],
BUTTONS["TT"]["category_list"],
BUTTONS["EN"]["category_list"],
]
)
)
async def show_category_list(
message: Message, state: FSMContext, session: Session
):
"""Обарботчик кнопки Посмотреть/редактировать категории.
Показывает все созданные категории с пагинацией.
"""
try:
await state.clear()
user = select_user(session, message.from_user.id)
language = user.language
lexicon = LEXICON[language]
categories = get_all_categories(session)
if not categories:
await message.answer(
lexicon["no_categories_yet"],
reply_markup=add_category_keyboard(language),
)
return
current_page = 1
page_info = generate_categories_list(
categories=categories,
lexicon=lexicon,
current_page=current_page,
page_size=PAGE_SIZE,
methodist=True,
)
msg = page_info["msg"]
category_ids = page_info["categories_ids"]
first_item = page_info["first_item"]
final_item = page_info["final_item"]
lk_button = {
"text": BUTTONS[language]["lk"],
"callback_data": "profile",
}
await state.set_state(CategoryList.categories)
await state.update_data(
categories=categories,
category_ids=category_ids,
current_page=current_page,
task_info=page_info,
language=language,
)
await message.answer(
msg,
reply_markup=pagination_keyboard(
buttons_count=len(categories),
start=first_item,
end=final_item,
cd="category",
page_size=PAGE_SIZE,
extra_button=lk_button,
),
)
except KeyError as err:
logger.error(f"Ошибка в ключе при просмотре списка категорий: {err}")
except Exception as err:
logger.error(f"Ошибка при просмотре списка категорий: {err}")
@methodist_category_router.callback_query(F.data == "delete_category")
async def delete_category(
query: CallbackQuery, state: FSMContext, session: Session
):
"""Кнопка "Удалить" в разделе редактирования категории."""
try:
await query.answer()
data = await state.get_data()
language = data["language"]
lexicon = LEXICON[language]
await query.message.edit_text(
lexicon["delete_confirmation"],
reply_markup=yes_no_keyboard(
language, "delete_category", "delete_category"
),
)
except Exception as err:
logger.error(f"Ошибка при получении категории: {err}")
@methodist_category_router.callback_query(F.data == "yes:delete_category")
async def category_deletion_confirmation(
query: CallbackQuery, state: FSMContext, session: Session
):
"""Подтверждение удаления категории."""
try:
await query.answer()
data = await state.get_data()
language = data["language"]
lexicon = LEXICON[language]
category_id = data["category_id"]
await category_deleting(session, category_id)
categories = get_all_categories(session)
if not categories:
await query.message.edit_text(
lexicon["no_categories_yet"],
reply_markup=add_category_keyboard(language),
)
return
page_info = generate_categories_list(
categories=categories,
lexicon=lexicon,
page_size=PAGE_SIZE,
methodist=True,
)
category_ids = page_info["categories_ids"]
await state.set_data({})
await state.update_data(
categories=categories,
category_ids=category_ids,
task_info=page_info,
language=language,
current_page=1,
)
await query.message.edit_text(
lexicon["category_deleting"],
reply_markup=back_keyboard(
language, "back_to_category_list", "back_to_category_list"
),
)
except Exception as err:
logger.error(f"Ошибка при удалении категории: {err}")
| Studio-Yandex-Practicum/EdGame_bot | handlers/methodist_categories_handlers.py | methodist_categories_handlers.py | py | 19,739 | python | ru | code | 0 | github-code | 36 | [
{
"api_name": "logging.getLogger",
"line_number": 33,
"usage_type": "call"
},
{
"api_name": "aiogram.Router",
"line_number": 35,
"usage_type": "call"
},
{
"api_name": "aiogram.types.Message",
"line_number": 48,
"usage_type": "name"
},
{
"api_name": "sqlalchemy.orm... |
40294597567 | import requests
import json
from urllib.parse import urlencode, quote_plus
def getBusInterval() :
api_key = 'g2B7EooEAgEwa++yErKYAhIk93i7tdYXP/3i5nOrRMN0Fmt78AnTzkaJUGqdsIUcqd7ITge5nUX0dAK/luCmFg=='
serviceKey = requests.utils.unquote(api_key)
api_url = 'http://ws.bus.go.kr/api/rest/busRouteInfo/getRouteInfo'
params ={'serviceKey' : api_key, 'busRouteId' : '100100124' }
response = requests.get(api_url, params=params)
print(response.content)
def countRouteId():
with open('bus_router_edge_with_transfer.json', 'r', encoding='utf-8') as f:
bus_route_list = json.load(f)
unique_route_ids = set(edge['route_id'] for edge in bus_route_list)
print("고유한 route_id의 개수:", len(unique_route_ids))
countRouteId() | CSID-DGU/2023-2-OSSP1-Idle-3 | data/graphDataProcessing/bus_data_processing/intervalTime/getBusInterval.py | getBusInterval.py | py | 771 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "requests.utils.unquote",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "requests.utils",
"line_number": 8,
"usage_type": "attribute"
},
{
"api_name": "requests.get",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "json.load",
... |
31757113296 | from django.db import models, transaction
from django.contrib.auth.models import AbstractUser
from django.core.exceptions import ValidationError
from django.db.models import JSONField
from django.db.models.signals import post_save
from django.dispatch import receiver
USER_TYPE_CHOICES = (
("customer", "Customer"),
("admin", "Admin"),
("shop_owner", "Shop Owner"),
)
# extend the user model
class Custom_User(AbstractUser):
userType = models.CharField(
max_length=20,
default="customer",
choices=USER_TYPE_CHOICES,
verbose_name="User Type",
)
shopId = models.ForeignKey(
"shop.Shop",
verbose_name="Shop ID",
on_delete=models.CASCADE,
null=True,
blank=True,
)
def save(self, *args, **kwargs):
if self.userType == "admin":
self.shopId = None
super().save(*args, **kwargs)
class Shop(models.Model):
shopId = models.AutoField(primary_key=True)
shopName = models.CharField(
max_length=100,
unique=True,
verbose_name=("Shop Name"),
error_messages={
"unique": "This shop name is already taken.",
"required": "This field is required.",
},
)
description = models.CharField(
max_length=100,
verbose_name=("Description"),
error_messages={"required": "This field is required."},
)
shopOwner = models.ForeignKey(
"shop.Custom_User", verbose_name=("Shop Owner"), on_delete=models.CASCADE
)
def __str__(self):
return self.shopName
class Meta:
verbose_name = "Shop"
verbose_name_plural = "Shops"
class ShopProps(models.Model):
shopPropsId = models.AutoField(primary_key=True)
shopId = models.ForeignKey(
"shop.Shop",
verbose_name=("Shop ID"),
on_delete=models.CASCADE,
error_messages={"required": "This field is required."},
)
props = models.JSONField(
default=dict,
verbose_name=("Shop Properties"),
error_messages={"required": "This field is required."},
blank=True,
null=True,
)
class Meta:
verbose_name = "Shop Property"
verbose_name_plural = "Shop Properties"
class Category(models.Model):
categoryId = models.AutoField(primary_key=True)
name = models.CharField(
max_length=100,
unique=True,
verbose_name=("Category Name"),
error_messages={
"unique": "This category name is already taken.",
"required": "This field is required.",
},
)
description = models.CharField(
max_length=100,
verbose_name=("Description"),
error_messages={"required": "This field is required."},
)
shopId = models.ForeignKey(
"shop.Shop", verbose_name=("Shop ID"), on_delete=models.CASCADE
)
def __str__(self):
return self.name
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
class Product(models.Model):
productId = models.AutoField(primary_key=True, verbose_name=("Product ID"))
name = models.CharField(
max_length=100,
verbose_name=("Product Name"),
error_messages={"required": "name field is required."},
)
description = models.CharField(
max_length=100,
verbose_name=("Description"),
error_messages={"required": "description field is required."},
)
price = models.DecimalField(
max_digits=10,
decimal_places=2,
verbose_name=("Price"),
error_messages={"required": "price field is required."},
)
poster_image_url = models.URLField(
max_length=200,
verbose_name=("Poster Image URL"),
error_messages={"required": "poster_image_url field is required."},
blank=True,
null=True,
)
image_urls = models.JSONField(
default=list, verbose_name=("Image URLs"), blank=True, null=True
)
shopId = models.ForeignKey(
"shop.Shop", verbose_name=("Shop ID"), on_delete=models.CASCADE
)
categoryId = models.ForeignKey(
"shop.Category",
verbose_name=("Category ID"),
on_delete=models.CASCADE,
null=True,
blank=True,
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Meta:
verbose_name = "Product"
verbose_name_plural = "Products"
def clean(self):
if self.price <= 0:
raise ValidationError("Price must be greater than zero.")
class Cart(models.Model):
products = JSONField(default=list, blank=True)
userId = models.ForeignKey(
"shop.Custom_User", verbose_name=("User ID"), on_delete=models.CASCADE
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.userId) + " Cart"
class Meta:
verbose_name = "Cart"
verbose_name_plural = "Carts"
def clean(self):
for product in self.products:
if product["quantity"] <= 0:
raise ValidationError("Quantity must be greater than zero.")
# Signal to create a new cart for a new customer user
@receiver(post_save, sender=Custom_User)
def create_cart_for_new_customer(sender, instance, created, **kwargs):
print("Signal called")
if created and instance.userType == "customer":
cart = Cart.objects.create(userId=instance)
cart.save()
# # Signal to create a new shop for a new shop owner user
# @receiver(post_save, sender=Custom_User)
# def create_shop_for_new_shop_owner(sender, instance, created, **kwargs):
# if created and instance.userType == 'shop_owner':
# with transaction.atomic():
# shop = Shop.objects.create(shopOwner=instance)
# instance.shopId = shop.shopId
# instance.save()
# signal to update the shopId of the shop owner user when a new shop is created
@receiver(post_save, sender=Shop)
def update_shopId_for_shop_owner(sender, instance, created, **kwargs):
print("Shop Signal called")
if created:
user = Custom_User.objects.get(id=instance.shopOwner.id)
user.shopId = instance
user.save()
| A7med3365/Project4-Backend | shop/models.py | models.py | py | 6,379 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "django.contrib.auth.models.AbstractUser",
"line_number": 16,
"usage_type": "name"
},
{
"api_name": "django.db.models.CharField",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "django.db.models",
"line_number": 17,
"usage_type": "name"
},
{
... |
35864159569 | # Import dependencies
import numpy as np
from keras.models import Sequential
from keras.layers import Activation, Dropout, UpSampling2D, Conv2D, Conv2DTranspose, MaxPooling2D
from keras.layers.normalization import BatchNormalization
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
import pickle, cv2, sys
# Set system settings
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# Constants
train_data_filename = "train_images_hq.p"
train_labels_filename = "train_labels_hq.p"
INDEX_RANGE_RATE = 1
TEST_SIZE = 1
BATCH_SIZE = 32
EPOCHS = 8
# Load training images and labels from pickle file, return as NumPy array
print("Loading training data/images...")
train_images = np.array(pickle.load(open(train_data_filename, 'rb')))
print("Loading training labels...")
train_labels = np.array(pickle.load(open(train_labels_filename, 'rb')))
# Shuffle data
print("Shuffling training data...")
train_images, train_labels = shuffle(train_images, train_labels)
# Log
print(train_images[0].shape, "->", train_labels[0].shape)
# Show example
blank = np.zeros_like(train_labels[0])
ex = np.dstack((train_labels[0], blank, blank)).astype(np.uint8)
img_ex = cv2.addWeighted(train_images[0], 1, ex, 1, 0)
cv2.imshow("", img_ex)
cv2.waitKey(0)
# Only use limited amount of training data samples
print("Limiting data range to", int(train_images.shape[0] * INDEX_RANGE_RATE), "out of", train_images.shape[0], "samples...")
train_images = train_images[0:int(train_images.shape[0] * INDEX_RANGE_RATE)]
train_labels = train_labels[0:int(train_labels.shape[0] * INDEX_RANGE_RATE)]
# Normalize labels
print("Normalizing training data labels...")
train_labels = train_labels / 255
# Split training data into training and test data (test_size is amount as percentage)
print("Splitting training data into training and testing data...")
X_train, X_val, y_train, y_val = train_test_split(train_images, train_labels, test_size=TEST_SIZE)
input_shape = X_train.shape[1:]
# Define neural network architecture
print("Defining model structure...")
# Use sequential architecture
model = Sequential()
# Add layers
model.add(BatchNormalization(input_shape=input_shape))
model.add(Conv2D(1, (3, 3), padding='valid', strides=(1, 1), activation='relu'))
model.add(Dropout(0.25))
model.add(Conv2D(1, (3, 3), padding='valid', strides=(1, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(8, (3, 3), padding='valid', strides=(1, 1), activation='relu'))
model.add(Dropout(0.25))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(16, (3, 3), padding='valid', strides=(1, 1), activation='relu'))
model.add(Dropout(0.25))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (3, 3), padding='valid', strides=(1, 1), activation='relu'))
model.add(Dropout(0.25))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(UpSampling2D(size=(2, 2)))
model.add(Conv2DTranspose(32, (3, 3), padding='valid', strides=(1, 1), activation='relu'))
model.add(Dropout(0.25))
model.add(UpSampling2D(size=(2, 2)))
model.add(Conv2DTranspose(16, (3, 3), padding='valid', strides=(1, 1), activation='relu'))
model.add(Dropout(0.25))
model.add(UpSampling2D(size=(2, 2)))
model.add(Conv2DTranspose(8, (3, 3), padding='valid', strides=(1, 1), activation='relu'))
model.add(Dropout(0.25))
model.add(UpSampling2D(size=(2, 2)))
model.add(Conv2DTranspose(1, (3, 3), padding='valid', strides=(1, 1), activation='relu'))
model.add(Dropout(0.25))
model.add(Conv2DTranspose(1, (3, 3), padding='valid', strides=(1, 1), activation='relu'))
# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')
# Train model
model.fit(
X_train, y_train,
batch_size=BATCH_SIZE,
epochs=EPOCHS,
verbose=1,
validation_data=(X_val, y_val)
)
# Store model
model.save('model.h5')
# Show summary of model
model.summary()
# Evaluate model
print(model.evaluate(X_val, y_val, batch_size=BATCH_SIZE)) | codeXing8/LaneRecognition | keras-cnn/train.py | train.py | py | 3,943 | python | en | code | 2 | github-code | 36 | [
{
"api_name": "os.environ",
"line_number": 12,
"usage_type": "attribute"
},
{
"api_name": "numpy.array",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "pickle.load",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "numpy.array",
"line_numbe... |
42095536498 | from subprocess import call
import win32api
import win32gui
import win32con
import win32com.client
from enum import Enum
import sounddevice as sd
from scipy.io.wavfile import read
import requests
import json
import numpy as np
from settings import Settings
from logging import debug, warning, error
class MixerCommand(Enum):
MIC_MUTE = 0
SOUND_MUTE = 1
PLAY_FILE = 2
MUSIC_TOGGLE_PLAY = 3
MUSIC_NEXT_TRACK = 4
MUSIC_PREV_TRACK = 5
MUSIC_TOGGLE_MUTE = 6
class MusicService(Enum):
VOLUMIO_LOCAL = 0
SPOTIFY = 1
class SoundMixer():
def __init__(self, settings: Settings):
self.WM_APPCOMMAND = 0x319
self.APPCOMMAND_MICROPHONE_VOLUME_MUTE = 0x180000
self.APPCOMMAND_SYSTEM_VOLUME_MUTE = 0x80000
self.IsMuted = False
self.IsSoundMuted = False
self.prev_volume = 20 # default 'not-muted' volume
self.output_volume = 0.1
def setup_sound_device(self, playbackDeviceName: str) -> None:
debug(sd.query_devices())
if playbackDeviceName != "default":
for idx, elem in enumerate(sd.query_devices()):
if playbackDeviceName.lower() in elem['name'].lower():
sd.default.device = idx
break
def send_input_hax(self, hwnd, msg):
for c in msg:
if c == "\n":
win32api.SendMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
win32api.SendMessage(hwnd, win32con.WM_KEYUP, win32con.VK_RETURN, 0)
else:
win32api.SendMessage(hwnd, win32con.WM_CHAR, ord(c), 0)
def toggleMic(self):
"""
https://stackoverflow.com/questions/50025927/how-mute-microphone-by-python
"""
shell = win32com.client.Dispatch("WScript.Shell")
shell.AppActivate("Discord")
shell.SendKeys("^m", 0)
hwnd_active = win32gui.GetForegroundWindow()
win32api.SendMessage(hwnd_active, self.WM_APPCOMMAND, None, self.APPCOMMAND_MICROPHONE_VOLUME_MUTE)
def toggleSystemSound(self):
hwnd_active = win32gui.GetForegroundWindow()
win32api.SendMessage(hwnd_active, self.WM_APPCOMMAND, None, self.APPCOMMAND_SYSTEM_VOLUME_MUTE)
pass
def playFile(self, filepath):
if filepath is not None:
try:
a = read(filepath)
except Exception as e:
warning(f"Exception occured while reading file {filepath}, {e}")
return False
array = np.array(a[1], dtype=int)
scaled =np.int16(array/np.max(np.abs(array)) * int(32767 * self.output_volume))
try:
sd.play(scaled, a[0])
sd.wait()
sd.stop()
except Exception as e:
error(f"Exception occured while playing file {filepath}, {e}")
return False
return True
def togglePlayMusic(self, service):
if service == MusicService.VOLUMIO_LOCAL.name:
r = requests.get("http://volumio.local/api/v1/commands/?cmd=toggle")
if r.status_code != 200:
warning(f"failed to toggle music, reason: {r.reason}")
else:
warning("Service not implemented")
def playNextTrack(self, service):
if service == MusicService.VOLUMIO_LOCAL.name:
r = requests.get("http://volumio.local/api/v1/commands/?cmd=next")
if r.status_code != 200:
warning(f"failed to skip to next track, reason: {r.reason}")
else:
warning("Service not implemented")
def playPreviousTrack(self, service):
if service == MusicService.VOLUMIO_LOCAL.name:
requests.get("http://volumio.local/api/v1/commands/?cmd=prev")
r = requests.get("http://volumio.local/api/v1/commands/?cmd=prev")
if r.status_code != 200:
warning(f"failed to skip to previous track, reason: {r.reason}")
else:
warning("Service not implemented")
def toggleMuteMusic(self, service):
if service == MusicService.VOLUMIO_LOCAL.name:
newVol = self.prev_volume
currVol = self.getMusicServiceVolume(service)
if currVol > 0:
newVol = 0
self.prev_volume = currVol
r = requests.get(f"http://volumio.local/api/v1/commands/?cmd=volume&volume={newVol}")
if r.status_code != 200:
warning(f"failed to toggle mute music, reason: {r.reason}")
else:
warning("Service not implemented")
def getMusicServiceVolume(self, service=MusicService.VOLUMIO_LOCAL.name):
if service == MusicService.VOLUMIO_LOCAL.name:
r = requests.get("http://volumio.local/api/v1/getState")
j_response = json.loads(r.content.decode())
return j_response["volume"]
def isMusicMuted(self):
return False if self.getMusicServiceVolume() > 0 else True
def isMusicPlaying(self, service=MusicService.VOLUMIO_LOCAL.name):
if service == MusicService.VOLUMIO_LOCAL.name:
r = requests.get("http://volumio.local/api/v1/getState")
j_response = json.loads(r.content.decode())
return True if j_response["status"] == "play" else False
def execCommand(self, action, callback=None):
command = action['command']
if command == MixerCommand.MIC_MUTE.name:
self.toggleMic()
self.IsMuted = not self.IsMuted
elif command == MixerCommand.SOUND_MUTE.name:
self.toggleSystemSound()
self.IsSoundMuted = not self.IsSoundMuted
elif command == MixerCommand.MUSIC_TOGGLE_PLAY.name:
self.togglePlayMusic(action['service'])
elif command == MixerCommand.MUSIC_TOGGLE_MUTE.name:
self.toggleMuteMusic(action['service'])
elif command == MixerCommand.MUSIC_NEXT_TRACK.name:
self.playNextTrack(action['service'])
elif command == MixerCommand.MUSIC_PREV_TRACK.name:
self.playPreviousTrack(action['service'])
elif command == MixerCommand.PLAY_FILE.name:
filepath = action['filepath']
debug(f"Started to play file '{filepath}'")
successful = self.playFile(filepath)
debug("Played file '{0}' successfully: {1}".format(filepath, successful))
if callback is not None:
callback() | schms27/raspi.pico.collection | pico.hid.service/sound_mixer.py | sound_mixer.py | py | 6,492 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "enum.Enum",
"line_number": 16,
"usage_type": "name"
},
{
"api_name": "enum.Enum",
"line_number": 25,
"usage_type": "name"
},
{
"api_name": "settings.Settings",
"line_number": 31,
"usage_type": "name"
},
{
"api_name": "logging.debug",
"line_numbe... |
11998084066 | import htcondor
import classad
import time
def get_existing_resources(self, group):
"""
Get list of worker nodes
"""
try:
coll = htcondor.Collector()
results = coll.query(htcondor.AdTypes.Startd,
'PartitionableSlot=?=True',
["TotalCpus", "Cpus", "TotalMemory", "Memory", "TotalDisk", "ProminenceCloud", "Start"])
except:
return None
workers = []
for result in results:
if group in str(result['Start']) or 'ProminenceGroup' not in str(result['Start']):
capacity = {'cpus': int(result["TotalCpus"]), 'memory': int(result["TotalMemory"]/1024.0)}
free = {'cpus': int(result["Cpus"]), 'memory': int(result["Memory"]/1024.0)}
worker = {'capacity': capacity, 'free': free, 'site': result["ProminenceCloud"]}
workers.append(worker)
# Sort by free CPUs descending
workers = sorted(workers, key=lambda x: x['free']['cpus'], reverse=True)
data = {'existing': workers}
return data
| prominence-eosc/prominence | prominence/backend/resources.py | resources.py | py | 1,061 | python | en | code | 2 | github-code | 36 | [
{
"api_name": "htcondor.Collector",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "htcondor.AdTypes",
"line_number": 12,
"usage_type": "attribute"
}
] |
9824574989 | """
Classes related to OpenAPI-defined operations and their arguments and parameters.
"""
from __future__ import print_function
import argparse
import json
def parse_boolean(value):
"""
A helper to allow accepting booleans in from argparse. This is intended to
be passed to the `type=` kwarg for ArgumentParser.add_argument.
"""
if value.lower() in ('yes', 'true', 'y', '1'):
return True
if value.lower() in ('no', 'false', 'n', '0'):
return False
raise argparse.ArgumentTypeError('Expected a boolean value')
def parse_dict(value):
"""
A helper function to decode incoming JSON data as python dicts. This is
intended to be passed to the `type=` kwarg for ArgumentParaser.add_argument.
"""
if not isinstance(value, str):
print("not a string :(")
raise argparse.ArgumentTypeError('Expected a JSON string')
try:
return json.loads(value)
except:
raise argparse.ArgumentTypeError('Expected a JSON string')
TYPES = {
"string": str,
"integer": int,
"boolean": parse_boolean,
"array": list,
"object": parse_dict,
"number": float,
}
class CLIArg:
"""
An argument passed to the CLI with a flag, such as `--example value`. These
are defined in a requestBody in the api spec.
"""
def __init__(self, name, arg_type, description, path):
self.name = name
self.arg_type = arg_type
self.description = description.replace('\n', '').replace('\r', '')
self.path = path
self.arg_item_type = None # populated during baking for arrays
self.required = False # this is set during baking
class URLParam:
"""
An argument passed to the CLI positionally. These are defined in a path in
the OpenAPI spec, in a "parameters" block
"""
def __init__(self, name, param_type):
self.name = name
self.param_type = param_type
class CLIOperation:
"""
A single operation described by the OpenAPI spec. An operation is a method
on a path, and should have a unique operationId to identify it. Operations
are responsible for parsing their own arguments and processing their
responses with the help of their ResponseModel
"""
def __init__(self, method, url, summary, args, response_model,
params):
self.method = method
self.url = url
self.summary = summary
self.args = args
self.response_model = response_model
self.params = params
def parse_args(self, args):
"""
Given sys.argv after the operation name, parse args based on the params
and args of this operation
"""
# build an argparse
parser = argparse.ArgumentParser(description=self.summary)
for param in self.params:
parser.add_argument(param.name, metavar=param.name,
type=TYPES[param.param_type])
if self.method == "get":
# build args for filtering
for attr in self.response_model.attrs:
if attr.filterable:
parser.add_argument('--'+attr.name, metavar=attr.name)
elif self.method in ("post", "put"):
# build args for body JSON
for arg in self.args:
if arg.arg_type == 'array':
# special handling for input arrays
parser.add_argument('--'+arg.path, metavar=arg.name,
action='append', type=TYPES[arg.arg_item_type])
else:
parser.add_argument('--'+arg.path, metavar=arg.name,
type=TYPES[arg.arg_type])
parsed = parser.parse_args(args)
return parsed
def process_response_json(self, json, handler):
if self.response_model is None:
return
if 'pages' in json:
json = json['data']
else:
json = [json]
handler.print(self.response_model, json)
| rovaughn/linode-cli | linodecli/operation.py | operation.py | py | 4,061 | python | en | code | null | github-code | 36 | [
{
"api_name": "argparse.ArgumentTypeError",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "argparse.ArgumentTypeError",
"line_number": 29,
"usage_type": "call"
},
{
"api_name": "json.loads",
"line_number": 31,
"usage_type": "call"
},
{
"api_name": "argp... |
40513708895 | import sys
from textblob import TextBlob
import redis
import json
from multiprocessing import Pool
import signal
import logging
import cPickle
import sys
sys.path.insert(0, '../NLP/Wrapper/')
sys.path.insert(0, '../NLP/')
sys.path.insert(0, '../NLP/NaiveBayes')
sys.path.insert(0, '../NLP/MaximumEntropy')
sys.path.insert(0, '../NLP/StochasticGradientDescent')
sys.path.insert(0, '../NLP/SupportVectorMachine')
from wrapper import classifier_wrapper, tweetclass
from trend_utils import getTrends, classifyTrending
import time
from dateutil import parser
import urllib
# Log everything, and send it to stderr.
logging.basicConfig(level=logging.DEBUG)
TWEET_QUEUE_KEY = 'tweet_queue'
TRENDING_TOPICS_KEY = 'trending_keys'
ALL_SENTIMENTS_KEY = 'sentiment_stream'
PERMANENT_TOPICS_KEY = 'permanent_topics'
TOPIC_SENTIMENTS_KEY_PREFIX = 'topic_sentiment_stream:'
MAX_SENTIMENTS = 10000
UPDATE_INT = 40 # seconds. Update interval for trending topics
def signal_handler(signum = None, frame = None):
logging.debug("Recieved signal " + str(signum))
logging.debug("Stopping tweet consumer.")
exit(0)
def main():
logging.debug("Starting tweet consumer.")
#for sig in [signal.SIGTERM, signal.SIGINT, signal.SIGHUP, signal.SIGQUIT]:
# On Windows, signal() can only be called with SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, or SIGTERM.
# A ValueError will be raised in any other case.
for sig in [signal.SIGTERM, signal.SIGINT]:
signal.signal(sig, signal_handler)
r = redis.Redis('localhost')
f = open("../NLP/Wrapper/test.txt", 'rb')
p = cPickle.load(f)
f.close()
last_updated = None
sentiment_queue_size = r.zcard(ALL_SENTIMENTS_KEY)
while True:
try:
# Update topics and trends every UPDATE_INT seconds
if last_updated is None or time.time() - last_updated > UPDATE_INT:
permanent_topics_json = r.get(PERMANENT_TOPICS_KEY)
if permanent_topics_json:
permanent_topics = json.loads(permanent_topics_json)
else:
permanent_topics = []
all_trending_keywords = r.zrange(TRENDING_TOPICS_KEY, 0, -1)
trending_keywords = all_trending_keywords[-12:]
removing_trending_keywords = all_trending_keywords[:-12]
r.delete(*[TOPIC_SENTIMENTS_KEY_PREFIX + topic for topic in removing_trending_keywords])
last_updated = time.time()
for topic in permanent_topics:
r.zremrangebyscore(TOPIC_SENTIMENTS_KEY_PREFIX + topic, "-inf", last_updated - 86400)
for topic in trending_keywords:
r.zremrangebyscore(TOPIC_SENTIMENTS_KEY_PREFIX + topic, "-inf", last_updated - 86400)
# Get tweet
tweet_json = r.rpop(TWEET_QUEUE_KEY)
if not tweet_json:
time.sleep(1)
continue
tweet = json.loads(tweet_json)
# Get Sentiment
sentiment_classification = p.classify(tweet['text'], "naive_bayes", 0.5)
if sentiment_classification == "positive":
sentiment = 1
elif sentiment_classification == "negative":
sentiment = -1
else:
sentiment = 0
# Format sentiment point correctly and put into correct queue
if sentiment != 0:
# Get coordinates
if tweet['geo'] is not None:
latitude, longitude = tweet['geo']['coordinates']
else:
latitude, longitude = None, None
# Get topic
topics = None
for trend in trending_keywords:
trend_decoded = urllib.unquote(trend).decode('utf8')
if (trend in tweet['text']) or (trend_decoded in tweet['text']):
if topics is None:
topics = []
topics.append(trend_decoded)
for topic in permanent_topics:
for topic_keyword in permanent_topics[topic]:
topic_keyword_decoded = urllib.unquote(topic_keyword).decode('utf8')
if (topic_keyword in tweet['text']) or (topic_keyword_decoded in tweet['text']):
if topics is None:
topics = []
topics.append(topic)
break
# Format sentiment point
sentiment_point_timestamp = time.time()
sentiment_point = {'topic': None, 'latitude': latitude, 'longitude': longitude, 'sentiment': sentiment, 'timestamp': sentiment_point_timestamp}
# Put into general sentiment queue
if sentiment_queue_size >= MAX_SENTIMENTS:
r.zremrangebyrank(ALL_SENTIMENTS_KEY, 0, 0)
sentiment_queue_size -= 1
r.zadd(ALL_SENTIMENTS_KEY, json.dumps(sentiment_point), sentiment_point_timestamp)
sentiment_queue_size += 1
# Belongs to topics? Put into correct queue
if topics is not None:
for topic in topics:
sentiment_point['topic'] = topic
r.zadd(TOPIC_SENTIMENTS_KEY_PREFIX + topic, json.dumps(sentiment_point), sentiment_point_timestamp)
except Exception as e:
logging.exception("Something awful happened!")
if __name__ == '__main__':
main()
| archanl/thetweetrises | backend/tweet_categorize.py | tweet_categorize.py | py | 5,629 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "sys.path.insert",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "sys.path",
"line_number": 10,
"usage_type": "attribute"
},
{
"api_name": "sys.path.insert",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "sys.path",
"line_nu... |
2465805518 | import glob
import os
import statistics
from .pid_data_evaluator import PidDataEvaluator
class OcrEvaluator:
def __init__(self, options):
# set properties
self.correct_line_ocr_log = options.correct_line_ocr_log
self.eval_main_text_only = options.eval_main_text_only
self.eval_annotation_line_order = options.eval_annotation_line_order
self.ocr_edit_distance_list = []
self.line_order_edit_distance_list = []
self.output_root_dir = options.output_root_dir
# create list of PidDataEvaluator
self.pid_data_evaluator_list = []
if (options.pred_single_xml is not None) and (options.gt_single_xml is not None):
pid_string, _ = os.path.splitext(os.path.basename(options.gt_single_xml))
single_pid_evaluator = PidDataEvaluator(self.output_root_dir, pid_string, options.pred_single_xml, options.gt_single_xml, options)
self.pid_data_evaluator_list.append(single_pid_evaluator)
else:
self.pid_data_evaluator_list = self._create_pid_evaluator_list(options)
def do_evaluation(self):
# create PID dir pair list
for pid_data_evaluator in self.pid_data_evaluator_list:
pid_data_evaluator.load_page_evaluators()
pid_data_evaluator.do_evaluation()
self.ocr_edit_distance_list.append(pid_data_evaluator.get_line_ocr_edit_distance_average())
self.line_order_edit_distance_list.append(pid_data_evaluator.get_line_order_edit_distance_average())
def get_ocr_edit_distance_average(self):
if len(self.ocr_edit_distance_list) <= 0:
print('ocr_edit_distance_list is empty')
return -1
return sum(self.ocr_edit_distance_list) / len(self.ocr_edit_distance_list)
def get_ocr_edit_distance_median(self):
line_ocr_edit_distance_list = []
line_ocr_edit_distance_dict = {}
for pid_data_evaluator in self.pid_data_evaluator_list:
line_ocr_edit_distance_dict[pid_data_evaluator.pid_string] = pid_data_evaluator.get_line_ocr_edit_distance_list()
line_ocr_edit_distance_list.extend(pid_data_evaluator.get_line_ocr_edit_distance_list())
ocr_edit_distance_median_low = statistics.median_low(line_ocr_edit_distance_list)
ocr_edit_distance_median_high = statistics.median_high(line_ocr_edit_distance_list)
ocr_edit_distance_median = (ocr_edit_distance_median_low + ocr_edit_distance_median_high) / 2
median_pid_list = []
for pid, single_edit_distance_list in line_ocr_edit_distance_dict.items():
if ocr_edit_distance_median_low in single_edit_distance_list:
median_pid_list.append(pid)
break
for pid, single_edit_distance_list in line_ocr_edit_distance_dict.items():
if ocr_edit_distance_median_high in single_edit_distance_list:
median_pid_list.append(pid)
break
if median_pid_list[0] == median_pid_list[1]:
median_pid_list.pop()
return median_pid_list, ocr_edit_distance_median
def get_line_order_edit_distance_average(self):
if len(self.line_order_edit_distance_list) <= 0:
print('line_order_edit_distance_list is empty')
return -1
return sum(self.line_order_edit_distance_list) / len(self.line_order_edit_distance_list)
def get_line_order_edit_distance_median(self):
line_order_edit_distance_list = []
line_order_edit_distance_dict = {}
for pid_data_evaluator in self.pid_data_evaluator_list:
line_order_edit_distance_dict[pid_data_evaluator.pid_string] = pid_data_evaluator.get_line_order_edit_distance_list()
line_order_edit_distance_list.extend(pid_data_evaluator.get_line_order_edit_distance_list())
line_order_edit_distance_median_low = statistics.median_low(line_order_edit_distance_list)
line_order_edit_distance_median_high = statistics.median_high(line_order_edit_distance_list)
line_order_edit_distance_median = (line_order_edit_distance_median_low + line_order_edit_distance_median_high) / 2
median_pid_list = []
for pid, single_edit_distance_list in line_order_edit_distance_dict.items():
if line_order_edit_distance_median_low in single_edit_distance_list:
median_pid_list.append(pid)
break
for pid, single_edit_distance_list in line_order_edit_distance_dict.items():
if line_order_edit_distance_median_high in single_edit_distance_list:
median_pid_list.append(pid)
break
if median_pid_list[0] == median_pid_list[1]:
median_pid_list.pop()
return median_pid_list, line_order_edit_distance_median
def _create_pid_evaluator_list(self, options):
pid_evaluator_list = []
# get full PID directory list
pred_pid_data_dir_list = [pid_dir for pid_dir in glob.glob(os.path.join(options.pred_data_root_dir, '*')) if os.path.isdir(pid_dir)]
# check if there is xml directory in PID directory, and there is only 1 xml file inside
for pred_pid_data_dir in pred_pid_data_dir_list:
pid_string = os.path.basename(pred_pid_data_dir)
gt_pid_data_dir = os.path.join(options.gt_data_root_dir, pid_string)
try:
# input data validation check
for id, pid_dir in enumerate([pred_pid_data_dir, gt_pid_data_dir]):
# input directory check
if not os.path.isdir(pid_dir):
raise FileNotFoundError('pid directory {0} not found.'.format(pid_dir))
# xml file check
xml_dir = os.path.join(pid_dir, 'xml')
if not os.path.isdir(xml_dir):
raise FileNotFoundError('xml directory not found in {0}.'.format(pid_dir))
if id == 0:
xml_file_list = glob.glob(os.path.join(xml_dir, '*.sorted.xml'))
else:
xml_file_list = glob.glob(os.path.join(xml_dir, '*.xml'))
if len(xml_file_list) != 1:
raise FileNotFoundError('xml file must be only one in each xml directory. : {0}'.format(xml_file_list))
# set instance properties
pred_xml_dir = os.path.join(pred_pid_data_dir, 'xml')
pred_xml_file_list = glob.glob(os.path.join(pred_xml_dir, '*.sorted.xml'))
pred_xml_file_path = pred_xml_file_list[0]
gt_xml_dir = os.path.join(gt_pid_data_dir, 'xml')
gt_xml_file_list = glob.glob(os.path.join(gt_xml_dir, '*.xml'))
gt_xml_file_path = gt_xml_file_list[0]
pid_data_evaluator = PidDataEvaluator(self.output_root_dir, pid_string, pred_xml_file_path, gt_xml_file_path, options)
except FileNotFoundError as err:
print(err)
continue
pid_evaluator_list.append(pid_data_evaluator)
return pid_evaluator_list
| ndl-lab/ndlocr_cli | submodules/ocr_line_eval_script/ocr_evaluator/ocr_evaluator.py | ocr_evaluator.py | py | 7,152 | python | en | code | 325 | github-code | 36 | [
{
"api_name": "os.path.splitext",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 20,
"usage_type": "attribute"
},
{
"api_name": "os.path.basename",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "pid_data_evaluator.Pid... |
9689098423 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase, RequestFactory, Client
from app.tests.mixins import AuthRouteTestingWithKwargs
from app.tests.mixins import Pep8ViewsTests
import app.views as views
performance = views.user_performance_views
class PasswordResetPep8Tests(TestCase, Pep8ViewsTests):
def setUp(self):
self.path = 'app/views/users/performance/'
# /users/:user_id/performance(.:format) only accepts GET and POST
class UserPerformanceIndexRoutingTests(TestCase, AuthRouteTestingWithKwargs):
def setUp(self):
self.factory = RequestFactory()
self.client = Client()
self.route_name = 'app:user_performance_index'
self.route = '/users/10/performance'
self.view = performance.user_performance_index
self.responses = {
'exists': 200,
'GET': 200,
'POST': 200,
'PUT': 405,
'PATCH': 405,
'DELETE': 405,
'HEAD': 405,
'OPTIONS': 405,
'TRACE': 405
}
self.kwargs = {'user_id': 10}
self.expected_response_content = 'Performance History Visualization'
AuthRouteTestingWithKwargs.__init__(self)
| Contrast-Security-OSS/DjanGoat | app/tests/views/test_users_performance.py | test_users_performance.py | py | 1,247 | python | en | code | 69 | github-code | 36 | [
{
"api_name": "app.views.user_performance_views",
"line_number": 8,
"usage_type": "attribute"
},
{
"api_name": "app.views",
"line_number": 8,
"usage_type": "name"
},
{
"api_name": "django.test.TestCase",
"line_number": 11,
"usage_type": "name"
},
{
"api_name": "ap... |
30280424346 | import requests
def get_random_wiki_article_link():
WIKI_RANDOM_LINK_API_URL = "https://en.wikipedia.org/w/api.php?action=query&list=random&rnnamespace=0&rnlimit=1&format=json"
response = requests.get(WIKI_RANDOM_LINK_API_URL)
if response.status_code == 200:
random_article_data = response.json()['query']['random']
random_article_title = random_article_data[0]['title']
return random_article_title
else:
print("Something went wrong! Please try again!")
def main():
article_base_url = "https://en.wikipedia.org/wiki/"
while True:
random_article = get_random_wiki_article_link()
user_response = input(f"Would you like to read `{random_article}` (Y/N): ")
if user_response.lower() == 'y':
print(f"{article_base_url}{'_'.join(random_article.split())}")
break
if __name__ == '__main__':
main() | hafeezulkareem/python_scripts | get_random_wiki_article_link.py | get_random_wiki_article_link.py | py | 905 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "requests.get",
"line_number": 7,
"usage_type": "call"
}
] |
25464205303 | from django import forms
from .models import Event
from django.core.exceptions import ValidationError
from django.utils import timezone
tz = timezone.get_default_timezone()
class EventForm(forms.ModelForm):
date_date = forms.CharField(max_length=40, required=True, widget=forms.TextInput(attrs={'class': 'form-control'}))
date_time = forms.CharField(max_length=40, required=True, widget=forms.TextInput(attrs={'class': 'form-control'}))
class Meta:
model = Event
fields = ['title', 'abstract', 'description', 'date_date', 'date_time', 'duration', 'language', 'persons', 'room', 'track', 'url', 'remotevideofile', 'videofile']
def __init__(self, *args, initial={}, **kwargs):
if 'instance' in kwargs:
initial["date_date"] = kwargs['instance'].date.astimezone(tz).strftime("%Y-%m-%d")
initial["date_time"] = kwargs['instance'].date.astimezone(tz).strftime("%H:%M")
self.new = False
self.video_url = kwargs['instance'].video_url()
else:
self.new = True
forms.ModelForm.__init__(self, *args, **kwargs, initial=initial)
| voc/voctoimport | event/forms.py | forms.py | py | 1,135 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "django.utils.timezone.get_default_timezone",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "django.utils.timezone",
"line_number": 5,
"usage_type": "name"
},
{
"api_name": "django.forms.ModelForm",
"line_number": 7,
"usage_type": "attribute"
},
... |
42578251551 | from tkinter import StringVar, Tk
from tkinter.ttk import Frame
import pytest
from pyDEA.core.gui_modules.data_frame_gui import DataFrame
from tests.test_gui_data_tab_frame import ParamsFrameMock
class ParentMock(Frame):
def __init__(self, parent):
super().__init__(parent)
self.progress_bar = {'value': 100}
@pytest.fixture
def data_book(request):
parent = Tk()
current_categories = []
data_book = DataFrame(ParentMock(parent), ParamsFrameMock(parent),
current_categories,
StringVar(master=parent), StringVar(master=parent))
request.addfinalizer(parent.destroy)
return data_book
def test_change_solution_tab_name(data_book):
new_name = 'New solution name'
data_book.change_solution_tab_name(new_name)
assert data_book.tab(1, option='text') == new_name
def test_reset_progress_bar(data_book):
data_book.reset_progress_bar()
assert data_book.parent.progress_bar['value'] == 0
| araith/pyDEA | tests/test_gui_data_frame.py | test_gui_data_frame.py | py | 998 | python | en | code | 38 | github-code | 36 | [
{
"api_name": "tkinter.ttk.Frame",
"line_number": 10,
"usage_type": "name"
},
{
"api_name": "tkinter.Tk",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "pyDEA.core.gui_modules.data_frame_gui.DataFrame",
"line_number": 21,
"usage_type": "call"
},
{
"api_... |
4714548611 | """
Write simple languoid stats to build/languoids.json.
This is to allow comparison between two branches of the repos.
Intended usage:
```
git checkout master
glottolog-admin writelanguoidstats
git checkout <OTHER_BRANCH>
glottolog-admin check --old-languoids
```
"""
try:
from git import Repo
except ImportError: # pragma: no cover
Repo = None
from clldutils import jsonlib
def run(args): # pragma: no cover
if Repo:
assert str(Repo(str(args.repos.repos)).active_branch) == 'master', \
'Command should be run on master branch'
res = {'language': [], 'family': [], 'dialect': []}
for lang in args.repos.languoids():
res[lang.level.name].append(lang.id)
jsonlib.dump(res, args.repos.build_path('languoids.json'))
| glottolog/pyglottolog | src/pyglottolog/admin_commands/writelanguoidstats.py | writelanguoidstats.py | py | 772 | python | en | code | 20 | github-code | 36 | [
{
"api_name": "git.Repo",
"line_number": 17,
"usage_type": "name"
},
{
"api_name": "git.Repo",
"line_number": 23,
"usage_type": "name"
},
{
"api_name": "git.Repo",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "clldutils.jsonlib.dump",
"line_number"... |
16764769514 | import dns.resolver
import sys
'''
Returns the dns records specified in rtypes, if you want to change this script feel free to do it. :)
To run this script just type --> python3 dnsenum.py <domain name> e.g domain name <example.com>
For the first import install dnspython using pip3 install dnspython
'''
def main():
try:
domain = sys.argv[1]
except:
print('SYNTAX ERROR ---- python3 dnsenum.py <domain name>')
exit()
rtypes = ['A','AAAA', 'NS','MX', 'TXT', 'SOA', 'PTR','CNAME']
for records in rtypes:
try:
target = dns.resolver.resolve(qname=domain,rdtype=records)
print('/' + '*'*10 + '/')
print(f'{records} records')
print('-'*100)
for e in target:
print(e.to_text() + '\n')
except dns.resolver.NoAnswer:
print('No records found for ' + f'{records}')
except dns.resolver.NXDOMAIN:
print('ERROR ---- The DNS query name does not exist')
exit()
except dns.resolver.NoNameservers:
print('ERROR ---- All nameservers failed to answer the query or you mistyped the domain name')
exit()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
exit() | Gl4uc0m4/InformationGatheringTools | dnsenum.py | dnsenum.py | py | 1,299 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "sys.argv",
"line_number": 16,
"usage_type": "attribute"
},
{
"api_name": "dns.resolver.resolver.resolve",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "dns.resolver.resolver",
"line_number": 24,
"usage_type": "attribute"
},
{
"api_name":... |
2114660989 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
class MyUser(models.Model):
id = models.IntegerField(primary_key=True, verbose_name='ID')
username = models.CharField(max_length=255)
@classmethod
def get_sharding_table(cls, id=None):
piece = id % 2 + 1
return cls._meta.db_table + str(piece)
@classmethod
def sharding_get(cls, id=None, **kwargs):
assert isinstance(id, int), 'id must be integer!'
table = cls.get_sharding_table(id)
sql = "SELECT * FROM %s" % table
kwargs['id'] = id
condition = ' AND '.join([k + '=%s' for k in kwargs])
params = [str(v) for v in kwargs.values()]
where = " WHERE " + condition
try:
return cls.objects.raw(sql + where, params=params)[0] # 这里应该模仿Queryset中get的处理方式
except IndexError:
# 其实应该抛Django的那个DoesNotExist异常
return None
class Meta:
db_table = 'user_'
# class User1(MyUser):
# class Meta:
# db_table = 'user_1'
# class User2(MyUser):
# class Meta:
# db_table = 'user_2'
| the5fire/django-sharding-demo | sharding_demo/app/models.py | models.py | py | 1,189 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "django.db.models.Model",
"line_number": 7,
"usage_type": "attribute"
},
{
"api_name": "django.db.models",
"line_number": 7,
"usage_type": "name"
},
{
"api_name": "django.db.models.IntegerField",
"line_number": 8,
"usage_type": "call"
},
{
"api_name"... |
11909593894 | from pprint import pprint
import boto3
import openpyxl
import time
import csv
def put_object(fileHash, request='', today = int(time.time()), dynamodb=None):
if not dynamodb:
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('image-reuse-image-hash-dev')
response = table.put_item(
Item={
'fileHash': fileHash,
'createdOn': today,
'requests': request,
'updatedOn': today
}
)
return response
def addtocsv(data):
file = open('final_test.csv', 'a+', newline ='')
# with file:
# write = csv.writer(file)
# write.writerows(data)
writer = csv.writer(file)
for key, value in data.items():
writer.writerow([key, value])
file.close()
dict1 = {}
def append_to_dict(fileHash, request):
if fileHash in dict1:
a = dict1[fileHash]
a = a + request
dict1[fileHash]= a
else:
dict1[fileHash]= request
if __name__ == '__main__':
today = int(time.time())
wb= openpyxl.load_workbook('final_db_data.xlsx')
print('Workbook loaded!')
sh1 = wb['Sheet1']
for i in range (2,640901):
fileHash = sh1.cell(i,1).value
request= [
{
"sourceElementId": sh1.cell(i,2).value,
"clientId": "BACKFILL",
"subLob": sh1.cell(i,4).value,
"sourceSystem": "ICAN",
"createdOn": today,
"lob": "motor"
}
]
append_to_dict(fileHash,request)
#output = put_object(fileHash, request, today)
print("Put object succeeded for item",i, fileHash)
#pprint(output, sort_dicts=False)
#print(dict1)
addtocsv(dict1)
| shakazi/aws_essential_scripts | upload_to_db.py | upload_to_db.py | py | 1,821 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "time.time",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "boto3.resource",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "csv.writer",
"line_number": 27,
"usage_type": "call"
},
{
"api_name": "time.time",
"line_number": 44,
... |
35802251836 | import os
import config
from dotenv import load_dotenv
import neuronet
import markups as nav
import actions
import constants
import paths
import user_settings as settings
from utils import set_default_commands
import markovify
import logging
from gtts import gTTS
import asyncio
from aiogram import Bot, types, Dispatcher, executor
"""ENV"""
dotenv_path = os.path.join(os.path.dirname(__file__), ".env")
bot_token = ''
if os.path.exists(dotenv_path):
load_dotenv(dotenv_path)
bot_token = os.getenv("API_TOKEN")
if bot_token == '': bot_token = config.API_TOKEN
"""Log level"""
logging.basicConfig(format = "%(asctime)s - %(levelname)s - %(message)s", level = logging.INFO)
logger = logging.getLogger(__name__)
"""Bot init"""
bot = Bot(token = bot_token)
dp = Dispatcher(bot)
"""Startup function"""
async def on_startup(dp):
await set_default_commands(dp)
"""Voice answer generation"""
def generate(text, out_file):
tts = gTTS(text, lang = "ru")
tts.save(out_file)
"""Get text model"""
def get_model(filename):
with open(filename, encoding = "utf-8") as f: text = f.read()
return markovify.Text(text)
"""Get compliment"""
async def get_compliment():
generator = get_model(paths.PATH_FEMALE_TEXT_MODEL_ANSWER)
statement = True
while statement:
text = generator.make_sentence()
if text is not None: statement = False
return text
"""Start function"""
@dp.message_handler(commands = ["start", "hi", "hello"])
async def start(message: types.Message, commands = "start"):
await bot.send_chat_action(message.from_user.id, types.chat.ChatActions.TYPING)
await asyncio.sleep(1)
await message.answer(f"{actions.ANSWER_HI} {message.from_user.full_name}!",
reply_markup = nav.greet_markup)
"""Error function"""
@dp.errors_handler()
async def error(self):
await logger.warning('update "%s" casused error "%s"', self.exception_name, self.exception_message)
"""On photo"""
@dp.message_handler(content_types = ["photo"])
async def photo(message: types.Message):
filename = "settings_" + str(message.from_user.id) + ".txt"
settings_path = paths.PATH_USER_DATA + filename
is_text = await settings.get_user_settings_text(settings_path)
tmp_pic_file = paths.PATH_USER_DATA + str(message.from_user.id) + ".jpg"
await message.photo[-1].download(destination_file=tmp_pic_file)
result = neuronet.resolve(tmp_pic_file)
os.remove(tmp_pic_file)
if is_text == False:
tmp_audio_file = paths.PATH_USER_DATA + str(message.from_user.id) + ".mp3"
if len(result[0]) == 0:
text = actions.ANSWER_UNDEFINED
if is_text == False:
generate(text, tmp_audio_file)
await bot.send_chat_action(message.chat.id, types.chat.ChatActions.TYPING)
await asyncio.sleep(1)
if is_text == False:
await message.answer_audio(audio = open(tmp_audio_file, "rb"))
os.remove(tmp_audio_file)
return
else:
await message.answer(text)
return
text = result[1][0] + ", на мой скромный взгляд."
if result[0][0] == constants.IS_FEMALE: text = f'{actions.ANSWER_FEMALE} {text}'
elif result[0][0] == constants.IS_MALE: text = f'{actions.ANSWER_MALE} {text}'
print(text)
await bot.send_chat_action(message.from_user.id, types.chat.ChatActions.TYPING)
await asyncio.sleep(1)
if is_text == False:
generate(text, tmp_audio_file)
await message.answer_audio(audio = open(tmp_audio_file, "rb"))
os.remove(tmp_audio_file)
else: await message.answer(text)
text = ""
if result[0][0] == constants.IS_FEMALE: text = await get_compliment()
elif result[0][0] == constants.IS_MALE: text = actions.ANSWER_MALE_WITHOUT_MODEL
print(text)
await bot.send_chat_action(message.from_user.id, types.chat.ChatActions.TYPING)
await asyncio.sleep(1)
if is_text == False:
generate(text, tmp_audio_file)
await message.answer_audio(audio = open(tmp_audio_file, "rb"))
os.remove(tmp_audio_file)
else:
await message.answer(text)
@dp.message_handler()
async def answers(message: types.Message):
filename = "settings_" + str(message.from_user.id) + ".txt"
settings_path = paths.PATH_USER_DATA + filename
if message.text == actions.QUERY_GREETING:
await message.answer(actions.ANSWER_GREETING, reply_markup = nav.main_markup)
elif message.text == actions.QUERY_SETTINGS:
await message.answer(actions.ANSWER_SETTINGS, reply_markup = nav.settings_markup)
elif message.text == actions.QUERY_TEXT_ANSWER:
is_text = True
await settings.set_user_settings_text(settings_path, is_text)
await message.answer(actions.ANSWER_TEXT_ANSWER)
elif message.text == actions.QUERY_VOICE_ANSWER:
is_text = False
await settings.set_user_settings_text(settings_path, is_text)
await message.answer(actions.ANSWER_VOICE_ANSWER)
elif message.text == actions.QUERY_MAIN_MENU:
await message.answer(actions.ANSWER_MAIN_MENU, reply_markup = nav.main_markup)
elif message.text == actions.QUERY_GET_COMPLIMENT:
is_text = await settings.get_user_settings_text(settings_path)
if is_text:
text = await get_compliment()
print(text)
await bot.send_chat_action(message.from_user.id, types.chat.ChatActions.TYPING)
await asyncio.sleep(1)
await message.answer(text)
else:
tmp_audio_file = paths.PATH_USER_DATA + str(message.from_user.id) + ".mp3"
text = await get_compliment()
print(text)
await bot.send_chat_action(message.from_user.id, types.chat.ChatActions.TYPING)
await asyncio.sleep(1)
generate(text, tmp_audio_file)
await message.answer_audio(audio = open(tmp_audio_file, "rb"))
os.remove(tmp_audio_file)
elif message.text == actions.QUERY_START_AUTO_COMPLIMENTS:
is_run = True
await settings.set_user_settings_text(settings_path, is_run)
await asyncio.sleep(1)
await message.answer(actions.ANSWER_START_AUTO_COMPLIMENTS,
reply_markup = nav.auto_compliments_markup)
while is_run == True:
is_run = await settings.get_user_settings_text(settings_path)
text = await get_compliment()
print(text)
await bot.send_chat_action(message.from_user.id, types.chat.ChatActions.TYPING)
await asyncio.sleep(3)
await message.answer(text)
elif message.text == actions.QUERY_STOP_AUTO_COMPLIMENTS:
is_run = False
await settings.set_user_settings_text(settings_path, is_run)
await bot.send_chat_action(message.from_user.id, types.chat.ChatActions.TYPING)
await asyncio.sleep(1)
await message.answer(actions.ANSWER_STOP_AUTO_COMPLIMENTS,
reply_markup = nav.main_markup)
"""Exit function"""
@dp.message_handler(commands = ["exit", "cancel", "bye"])
async def exit(message: types.Message, commands = "exit"):
await bot.send_chat_action(message.from_user.id, types.chat.ChatActions.TYPING)
await asyncio.sleep(1)
await message.answer(f"{actions.ANSWER_BYE} {message.from_user.full_name}!")
"""Run long-polling"""
def main():
executor.start_polling(dp, on_startup=on_startup, skip_updates = True)
if __name__ == "__main__": main()
| Lucifer13Freeman/Sunny-Telegram-Bot | bot.py | bot.py | py | 7,710 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "os.path.join",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 24,
"usage_type": "attribute"
},
{
"api_name": "os.path.dirname",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "os.path.exists",
"line_... |
5834016480 | import pygame, time
from math import pi, cos, sin
from random import randrange, random
WIDTH = 900
HEIGHT = 900
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
class Branch:
tree = []
random_seed = []
def __init__(self, startPoint, angle, size, width):
self.width = width
self.size = size
self.start = startPoint
self.angle = angle
self.end = self.findEndPoint()
Branch.tree.append(self)
def findEndPoint(self):
x = self.size*cos(pi/2-self.angle)
y = self.size*sin(pi/2-self.angle)
endpoint = (self.start[0] + x, self.start[1] - y)
return endpoint
def show(self):
if self.width<=0:
self.width = 1
pygame.draw.line(screen, (200, 200, 200), (self.start[0], self.start[1]), (self.end[0], self.end[1]), self.width)
def grow_branch(branch, angle):
if branch.size<5:
return "LOL"
if random()>0.1:
B_1 = Branch(branch.end, branch.angle + (angle+ 0.2*angle*randrange(-1,2)), branch.size*(randrange(45,101)/100), branch.width-1)
grow_branch(B_1, angle)
if random()>0.1:
B_2 = Branch(branch.end, branch.angle - (angle+ 0.4*angle*randrange(-1,2)), branch.size*(randrange(45,101)/100), branch.width-1)
grow_branch(B_2, angle)
if random()>0.5:
B_3 = Branch(branch.end, branch.angle - (angle+ 0.6*angle*randrange(-1,2)), branch.size*(randrange(50,101)/100), branch.width-1)
grow_branch(B_3, angle)
B = Branch((WIDTH/2, HEIGHT), 0, 100, 10)
grow_branch(B, pi/9)
screen.fill((30, 30, 30))
for branche in Branch.tree:
branche.show()
pygame.display.flip()
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == 32:
screen.fill((30, 30, 30))
Branch.tree = []
B = Branch((WIDTH/2, HEIGHT), 0, 100, 10)
grow_branch(B, pi/9)
for branche in Branch.tree:
branche.show()
pygame.display.flip() | YohannPardes/Fractal-tree | Versions/Tree_generator.py | Tree_generator.py | py | 2,195 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pygame.init",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "pygame.display.set_mode",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "pygame.display",
"line_number": 10,
"usage_type": "attribute"
},
{
"api_name": "math.cos",
... |
751441711 | import torch
from torch import nn
import torch.nn.functional as F
#Useful for nn.Sequential
class Flatten(nn.Module):
def forward(self, input):
return input.view(input.size(0), -1)
#Picked from Udacity's PyTorch course
class CIFARNet(nn.Module):
def __init__(self, z_dim):
super(CIFARNet, self).__init__()
# convolutional layer (sees 32x32x3 image tensor)
self.conv1 = nn.Conv2d(3, 16, 3, padding=1)
self.conv2 = nn.Conv2d(16, 32, 3, padding=1)
self.conv3 = nn.Conv2d(32, 64, 3, padding=1)
self.pool = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(64 * 4 * 4, 500)
self.fc2 = nn.Linear(500, 10)
self.g = nn.Linear(10, z_dim)
self.dropout = nn.Dropout(0.25)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = self.pool(F.relu(self.conv3(x)))
x = x.view(-1, 64 * 4 * 4)
#x = self.dropout(x)
x = F.relu(self.fc1(x))
#x = self.dropout(x)
x = F.relu(self.fc2(x))
x = self.g(x)
return x
class CIFARNet2(nn.Module):
def __init__(self, z_dim):
super(CIFARNet2, self).__init__()
# convolutional layer (sees 32x32x3 image tensor)
self.conv1 = nn.Conv2d(3, 16, 3, padding=1)
self.conv2 = nn.Conv2d(16, 32, 3, padding=1)
self.conv3 = nn.Conv2d(32, 64, 3, padding=1)
self.pool = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(64 * 4 * 4, 500)
self.g = nn.Sequential(nn.Linear(500, 100),
nn.ReLU(),
nn.Linear(100, z_dim))
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = self.pool(F.relu(self.conv3(x)))
x = x.view(-1, 64 * 4 * 4)
x = F.relu(self.fc1(x))
x = self.g(x)
return x | guptv93/saycam-metric-learning | model/cifar_model.py | cifar_model.py | py | 1,929 | python | en | code | 8 | github-code | 36 | [
{
"api_name": "torch.nn.Module",
"line_number": 6,
"usage_type": "attribute"
},
{
"api_name": "torch.nn",
"line_number": 6,
"usage_type": "name"
},
{
"api_name": "torch.nn.Module",
"line_number": 11,
"usage_type": "attribute"
},
{
"api_name": "torch.nn",
"line... |
2735470039 | # 3rdpartyimports
import math
from sklearn.model_selection import (
cross_val_score, KFold, train_test_split, GridSearchCV, RepeatedKFold)
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import (OneHotEncoder, StandardScaler,
PolynomialFeatures)
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import (accuracy_score, confusion_matrix,
classification_report, mean_squared_error,
mean_absolute_error)
from sklearn.linear_model import (LinearRegression, LassoCV, Lasso, RidgeCV, Ridge,
ElasticNetCV, ElasticNet, BayesianRidge,
LogisticRegression, SGDRegressor)
from numpy import absolute, mean, std
from scipy.stats import poisson
import numpy as np
import pandas as pd
def create_model(X, y): # generate opposition variables
"""a function that takes in our player averages, last ten averages, opponent and other predictors to generate
a model to predict FTA per 36 value for player. y=historical fta/36"""
dummies = pd.get_dummies(X['MATCHUP'])
X = X.drop('MATCHUP', axis=1)
X = pd.concat([X, dummies], axis=1)
X = X.drop(['FT_PCTlastxgames', 'FG_PCTlastxgames', 'FG3_PCTlastxgames', 'FG_PCT', 'FG3_PCT', 'FT_PCT'], axis=1)
X = X.fillna(0)
X=X.values
y = [0 if math.isnan(x) else x for x in y]
y=y.values
model = Lasso(alpha=1.0)
cv = RepeatedKFold(n_splits=10, n_repeats=3, random_state=1) # pretty typical numbers,can mess around later
scores = cross_val_score(model, X, y, cv=cv, n_jobs=1)
scores = absolute(scores)
print('Mean MAE: %.3f (%.3f)' % (mean(scores), std(scores)))
model.fit(X, y)
return model
def propbet(X, y):
scaler = StandardScaler()
dummies = pd.get_dummies(X['MATCHUP'])
X = X.drop('MATCHUP', axis=1)
X = pd.concat([X, dummies], axis=1)
X = X.drop(['FT_PCTlastxgames', 'FG_PCTlastxgames', 'FG3_PCTlastxgames', 'FG_PCT', 'FG3_PCT', 'FT_PCT'], axis=1)
X = X.fillna(0)
print(X)
y = [0 if math.isnan(x) else x for x in y]
X_train_val, X_test, y_train_val, y_test = train_test_split(
X, y, test_size=.2, random_state=1)
X_train, X_val, y_train, y_val = train_test_split(
X_train_val, y_train_val, test_size=.25, random_state=2)
X_train_scaled = scaler.fit_transform(X_train.values)
X_val_scaled = scaler.fit_transform(X_val.values)
alphavec = 10 ** np.linspace(-2, 2, 200)
lasso_cv = LassoCV(alphas=alphavec, cv=5)
lasso_cv.fit(X_train_scaled, y_train)
lasso_cv.alpha_
for col, coef in zip(X_train.columns, lasso_cv.coef_):
print(f"{col:<16}: {coef:>12,.7f}")
print(
f'R2 for LassoCV Model on train set: {lasso_cv.score(X_train_scaled, y_train)}')
val_set_preds = lasso_cv.predict(X_val_scaled)
print(
f'R2 for LassoCV Model on validation set: {lasso_cv.score(X_val_scaled, y_val)}')
mae = mean_absolute_error(y_val, val_set_preds)
print(f'Mean absolute error for LassoCV model on validation set: {mae}')
alpha = np.logspace(-4, 2, 100) # np.logspace(-4, -.1, 20)
param_grid = dict(alpha=alpha)
grid_en = GridSearchCV(ElasticNet(), param_grid=param_grid,
scoring='neg_mean_absolute_error', cv=5)
grid_result_en = grid_en.fit(X_train, y_train)
print(f'Best Score: {grid_result_en.best_score_}')
print(f'Best Param: {grid_result_en.best_params_}')
elastic_cv = ElasticNetCV(
alphas=[0.0021544346900318843], cv=5, random_state=0)
elastic_cv.fit(X_train, y_train)
print(
f'ElasticNet Mean R Squared Score on training data: {elastic_cv.score(X_train, y_train)}')
print(
f'ElasticNet Mean R Squared Score on validation data: {elastic_cv.score(X_val, y_val)}')
val_set_preds = elastic_cv.predict(X_val)
mae = mean_absolute_error(y_val, val_set_preds)
print(f'Mean absolute error for ElasticNet model on validation set: {mae}')
rmse = mean_squared_error(y_val, val_set_preds, squared=False)
print(
f'Root mean squared error for ElasticNet model on validation set: {rmse}')
for col, coef in zip(X_test.columns, elastic_cv.coef_):
print(f"{col:<16}: {coef:>12,.7f}")
elastic_preds = elastic_cv.predict(X)
X['Model Predictions'] = elastic_preds
return elastic_cv
def predictandpoisson(X, ftpercent, model, line):
"""taking our created model and x values for upcoming games output our projected FTA/36 and use
last ten games minutes average to get a final FTA number for the game, then use poisson to create distribution"""
yhat = model.predict(X)
yhat = yhat * X[0][0]/36 #convert out of per36
yhat = float(yhat * ftpercent)
print("projected makes", yhat)
line=float(line)
drawodds= poisson.pmf(line,yhat)
overodds = 1 - poisson.cdf(line, yhat)
underodds = poisson.cdf(line, yhat)
print("On a line of ",line, " Over odds are: ", overodds, "Draw odds are: ",drawodds, " and Under odds are ", underodds-drawodds)
return [line,overodds,drawodds,underodds-drawodds,yhat]
| chadk94/FreeThrowProjections | model.py | model.py | py | 5,208 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pandas.get_dummies",
"line_number": 26,
"usage_type": "call"
},
{
"api_name": "pandas.concat",
"line_number": 28,
"usage_type": "call"
},
{
"api_name": "math.isnan",
"line_number": 32,
"usage_type": "call"
},
{
"api_name": "sklearn.linear_model.Lass... |
10841211976 | import logging
import pathlib
from flask import Blueprint, g, request, make_response
from flask_restplus import Resource, Namespace, fields, abort
from photos.model import SourceFolder
from photos.scanner import scan_source_folder
log = logging.getLogger(__name__)
sources_blueprint = Blueprint("sources", __name__)
ns = Namespace("sources")
folder_fields = ns.model("SourceFolder", {"folder": fields.String, "stats": fields.Raw})
@ns.route("/_scan")
class Scan(Resource):
def post(self):
counts = dict()
for source in g.session.query(SourceFolder):
n_photos = scan_source_folder(g.session, source)
counts[source.folder] = n_photos
return counts
def normalize_folder(f):
return str(pathlib.Path(f))
@ns.route("/", defaults={"folder": None})
@ns.route("/<string:folder>")
class SourceFolders(Resource):
@ns.expect(folder_fields, validate=True)
def post(self, folder):
folder = normalize_folder(folder or request.get_json()["folder"])
g.session.add(SourceFolder(folder=folder))
response = make_response("", 201)
return response
@ns.marshal_with(folder_fields)
def get(self, folder):
if folder:
f = g.session.query(SourceFolder).get(folder)
if f is None:
abort(404, "Folder not found.")
else:
return g.session.query(SourceFolder).all()
| sebbegg/photos | photos/web/resources/scanner.py | scanner.py | py | 1,419 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "logging.getLogger",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "flask.Blueprint",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "flask_restplus.Namespace",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "flask_rest... |
72242760743 | from django.shortcuts import render
from django.http.request import QueryDict
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.views.generic.base import TemplateView
from six.moves.urllib.parse import urlparse
from rest_framework.renderers import JSONRenderer
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework.viewsets import GenericViewSet as DRFGenericViewset
from rest_framework.mixins import CreateModelMixin, ListModelMixin, RetrieveModelMixin, UpdateModelMixin, \
DestroyModelMixin
from .renderers import PrepairAPIRenderer
from api.flightplan_client import FlightPlanAPIClient
from accounts.models import Member
def index(request):
user = request.user
data = {}
if request.POST:
icao = request.POST.get('icao', None)
client = FlightPlanAPIClient()
response = client.get(icao=icao.lower())
if response.get('pk'):
pk = response.get('pk')
return HttpResponseRedirect(reverse('dashboard') + '/?airportpk={}'.format(pk))
else:
error_code = response.get('error')
if error_code == 429:
return render(request, 'index.html', {'over_limit': True})
elif not error_code:
general_error = 'An Unknown error has occurred. Contact site Admin.'
return render(request, 'index.html', {'error_code': general_error, 'icao': icao})
else:
return render(request, 'index.html', {'error_code': error_code, 'icao': icao})
if user.id:
try:
member = Member.objects.get(user=user)
if member.home_airport:
home_airport_pk = member.home_airport.pk
home_airport_icao = member.home_airport.icao
data = {'home_airport_pk': home_airport_pk, 'home_airport_icao': home_airport_icao}
except Member.DoesNotExist:
pass # Data error, do not return empty dictionary
except Member.MultipleObjectsReturned:
pass # Data error, do not return empty dictionary
return render(request, 'index.html', data)
class DashboardTemplateView(TemplateView):
template_name = 'dashboard.html'
def get_context_data(self, **kwargs):
context = super(DashboardTemplateView, self).get_context_data(**kwargs)
airport_pk = self.request.GET.get('airportpk', 0)
user_id = self.request.user.id if self.request.user.id else 0
if urlparse(self.request.path).path == '/dashboard/':
base_redirect = 1
else:
base_redirect = 0
context['airport_pk'] = airport_pk
context['user_id'] = user_id
context['base_redirect'] = base_redirect
return context
class PrepairViewSet(CreateModelMixin,
ListModelMixin,
RetrieveModelMixin,
UpdateModelMixin,
DestroyModelMixin,
DRFGenericViewset):
"""
Base DRF Viewset for all objects
Default CRUD Methods are all inherited through DRF Mixins
"""
prepair_browsable = ['get', 'head', 'options']
renderer_classes = (JSONRenderer, PrepairAPIRenderer)
permission_classes = (IsAuthenticatedOrReadOnly,)
# These values are set within the subclass Model Viewsets
prepair_model_class = None
queryset = None
serializer_class = None
filter_fields = tuple()
iexact_filter_fields = tuple()
def filter_queryset(self, queryset=None, is_list_call=False):
request_params = self.request.query_params
filter_kwargs = {}
for filter_field in self.filter_fields:
if filter_field in request_params:
initial_filter_field = filter_field
if isinstance(request_params, QueryDict):
values_list = request_params.getlist(filter_field)
else:
values_list = request_params.get(filter_field)
# Django ORM does not support iexact__in, so must choose one or the other
if isinstance(values_list, list) and len(values_list) > 1:
filter_kwargs[filter_field + '__in'] = values_list
else:
if filter_field in self.iexact_filter_fields:
filter_field += '__iexact'
filter_kwargs[filter_field] = request_params[initial_filter_field]
return self.prepair_model_class.objects.filter(**filter_kwargs)
| bfolks2/django-aviation | prepair/views.py | views.py | py | 4,566 | python | en | code | 2 | github-code | 36 | [
{
"api_name": "api.flightplan_client.FlightPlanAPIClient",
"line_number": 26,
"usage_type": "call"
},
{
"api_name": "django.http.HttpResponseRedirect",
"line_number": 31,
"usage_type": "call"
},
{
"api_name": "django.urls.reverse",
"line_number": 31,
"usage_type": "call"
... |
3640835274 | import torch
import torch.nn as nn
import torch.optim as optim
from torchtext.legacy.datasets import Multi30k
from torchtext.legacy.data import Field, BucketIterator
import spacy
import numpy as np
import random
import math
import time
from model import Seq2Seq, Encoder, Decoder
def train(model, iterator, optimizer, criterion, clip):
model.train()
epoch_loss = 0
for i, batch in enumerate(iterator):
src = batch.src
trg = batch.trg
optimizer.zero_grad()
output = model(src, trg)
# trg = [trg len, batch size]
# output = [trg len, batch size, output dim]
output_dim = output.shape[-1]
output = output[1:].view(-1, output_dim)
trg = trg[1:].view(-1)
# trg = [(trg len - 1) * batch size]
# output = [(trg len - 1) * batch size, output dim]
loss = criterion(output, trg)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), clip)
optimizer.step()
epoch_loss += loss.item()
return epoch_loss / len(iterator)
def evaluate(model, iterator, criterion):
model.eval()
epoch_loss = 0
with torch.no_grad():
for i, batch in enumerate(iterator):
src = batch.src
trg = batch.trg
output = model(src, trg, 0) # turn off teacher forcing
# trg = [trg len, batch size]
# output = [trg len, batch size, output dim]
output_dim = output.shape[-1]
output = output[1:].view(-1, output_dim)
trg = trg[1:].view(-1)
# trg = [(trg len - 1) * batch size]
# output = [(trg len - 1) * batch size, output dim]
loss = criterion(output, trg)
epoch_loss += loss.item()
return epoch_loss / len(iterator)
def init_weights(m):
for name, param in m.named_parameters():
nn.init.uniform_(param.data, -0.08, 0.08)
spacy_de = spacy.load("de_core_news_sm")
spacy_en = spacy.load("en_core_web_sm")
def tokenize_de(text):
"""
Tokenizes German text from a string into a list of strings (tokens) and reverses it
"""
return [tok.text for tok in spacy_de.tokenizer(text)][::-1]
def tokenize_en(text):
"""
Tokenizes English text from a string into a list of strings (tokens)
"""
return [tok.text for tok in spacy_en.tokenizer(text)]
def epoch_time(start_time, end_time):
elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
return elapsed_mins, elapsed_secs
SEED = 1234
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)
torch.backends.cudnn.deterministic = True
N_EPOCHS = 10
CLIP = 1
SRC = Field(tokenize=tokenize_de, init_token="<sos>", eos_token="<eos>", lower=True)
TRG = Field(tokenize=tokenize_en, init_token="<sos>", eos_token="<eos>", lower=True)
train_data, valid_data, test_data = Multi30k.splits(
exts=(".de", ".en"), fields=(SRC, TRG)
)
SRC.build_vocab(train_data, min_freq=2)
TRG.build_vocab(train_data, min_freq=2)
INPUT_DIM = len(SRC.vocab)
OUTPUT_DIM = len(TRG.vocab)
ENC_EMB_DIM = 256
DEC_EMB_DIM = 256
HID_DIM = 512
N_LAYERS = 2
ENC_DROPOUT = 0.5
DEC_DROPOUT = 0.5
BATCH_SIZE = 128
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
train_iterator, valid_iterator, test_iterator = BucketIterator.splits(
(train_data, valid_data, test_data), batch_size=BATCH_SIZE, device=device
)
enc = Encoder(INPUT_DIM, ENC_EMB_DIM, HID_DIM, N_LAYERS, ENC_DROPOUT)
dec = Decoder(OUTPUT_DIM, DEC_EMB_DIM, HID_DIM, N_LAYERS, DEC_DROPOUT)
model = Seq2Seq(enc, dec, device).to(device)
model.apply(init_weights)
optimizer = optim.Adam(model.parameters())
TRG_PAD_IDX = TRG.vocab.stoi[TRG.pad_token]
criterion = nn.CrossEntropyLoss(ignore_index=TRG_PAD_IDX)
best_valid_loss = float("inf")
for epoch in range(N_EPOCHS):
start_time = time.time()
train_loss = train(model, train_iterator, optimizer, criterion, CLIP)
valid_loss = evaluate(model, valid_iterator, criterion)
end_time = time.time()
epoch_mins, epoch_secs = epoch_time(start_time, end_time)
if valid_loss < best_valid_loss:
best_valid_loss = valid_loss
torch.save(model.state_dict(), "tut1-model.pt")
print(f"Epoch: {epoch+1:02} | Time: {epoch_mins}m {epoch_secs}s")
print(f"\tTrain Loss: {train_loss:.3f} | Train PPL: {math.exp(train_loss):7.3f}")
print(f"\t Val. Loss: {valid_loss:.3f} | Val. PPL: {math.exp(valid_loss):7.3f}")
model.load_state_dict(torch.load("tut1-model.pt"))
test_loss = evaluate(model, test_iterator, criterion)
print(f"| Test Loss: {test_loss:.3f} | Test PPL: {math.exp(test_loss):7.3f} |")
| HallerPatrick/two_hot_encoding | multihot/seq2seq/train.py | train.py | py | 4,787 | python | en | code | 6 | github-code | 36 | [
{
"api_name": "model.train",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "torch.nn.utils.clip_grad_norm_",
"line_number": 47,
"usage_type": "call"
},
{
"api_name": "torch.nn",
"line_number": 47,
"usage_type": "attribute"
},
{
"api_name": "model.parame... |
41629760399 | from django.shortcuts import render, redirect
import smtplib
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from .forms import editForm
def home(request):
if request.user.is_authenticated:
title = 'Account'
else:
title = 'Login'
return render(request, 'votesite/home.html', {'title' : title})
def handler404(request, exception):
return render(request, 'votesite/404.html', status=404)
def contact(request):
if request.method == "POST":
firstname = request.POST['firstname']
lastname = request.POST['lastname']
email = request.POST['email']
subject = request.POST['subject']
message = request.POST['message']
uid = request.POST['uid']
msg = firstname + ' ' + lastname + '\n' + 'ID: ' + uid + '\n' + email + '\n' + subject + ': ' + message
connection = smtplib.SMTP('smtp.gmail.com', 587)
connection.ehlo()
connection.starttls()
connection.ehlo()
username = settings.EMAIL_HOST_USER
passw = settings.EMAIL_HOST_PASSWORD
connection.login(username, passw)
connection.sendmail(
email,
[settings.EMAIL_HOST_USER],
msg
)
return render(request, 'votesite/messagesent.html', {'firstname': firstname})
else:
return render(request, 'votesite/contact.html', {})
@login_required
def profile(request):
username = request.user.first_name
return render(request, 'votesite/profile.html', {'username': username})
@login_required
def update(request):
if request.method == 'POST':
form = editForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
username = request.user.first_name
return render(request, 'votesite/profile.html', {'message' : "Form Submitted Successfully!", 'username': username})
else:
form = editForm(instance=request.user)
return render(request, 'votesite/update.html', {'form' : form}) | nrking0/votesite | votesite/views.py | views.py | py | 2,346 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "django.shortcuts.render",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "django.shortcuts.render",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "smtplib.SMTP",
"line_number": 36,
"usage_type": "call"
},
{
"api_name": "django.c... |
21119814957 | from typing import List
class Solution:
def vowelStrings(self, words: List[str], left: int, right: int) -> int:
s = set()
s.add('a'); s.add('e'); s.add('i'); s.add('o'); s.add('u')
ans = 0
i = 0
for word in words:
if left<=i<=right:
if word[0] in s and word[len(word)-1] in s:
ans += 1
i += 1
return ans
if __name__ == '__main__':
words = ["are","amy","u"]
left = 0
right = 2
words = ["hey","aeo","mu","ooo","artro"]
left = 1
right = 4
rtn = Solution().vowelStrings(words, left, right)
print(rtn) | plattanus/leetcodeDAY | python/6315. 统计范围内的元音字符串数.py | 6315. 统计范围内的元音字符串数.py | py | 648 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "typing.List",
"line_number": 5,
"usage_type": "name"
}
] |
17211879792 | from datetime import date
atual = date.today().year
totmaior = 0
totmenor = 0
for c in range(1, 8):
nasc = int(input(f'Em que ano a {c}° pessoa nasceu? '))
idade = atual - nasc
if idade >= 18:
totmaior += 1
else:
totmenor += 1
print(f'No total contamos {totmaior} maior de idade e {totmenor} menor de idade.')
| GRSFFE/PythonExercicios | ex054.py | ex054.py | py | 344 | python | pt | code | 0 | github-code | 36 | [
{
"api_name": "datetime.date.today",
"line_number": 2,
"usage_type": "call"
},
{
"api_name": "datetime.date",
"line_number": 2,
"usage_type": "name"
}
] |
74157473702 | from django.urls import path
from . import views
app_name = "core"
urlpatterns = [
path('author/', views.AuthorList.as_view(), name='list-author'),
path('author/<int:pk>/', views.AuthorDetail.as_view(), name='detail-author'),
path('book/', views.BookList.as_view(), name='list-book'),
path('book/<int:pk>/', views.BookDetail.as_view(), name='detail-book'),
]
| PauloGuillen/library | libraryapi/core/urls.py | urls.py | py | 377 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "django.urls.path",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "django.urls.path",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "django.urls.path",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "django.urls.path",
... |
42149656698 | from PIL import Image
import numpy as np
import cv2
img = Image.open('back_img.jpg')
size = img.size
x_length = size[0]
print('x_length:', x_length)
y_length = size[1]
print('y_length:', y_length)
im_num = np.array(img)
img_blur = cv2.GaussianBlur(im_num, (5, 5), 0)
img_gray = cv2.cvtColor(img_blur, cv2.COLOR_BGR2GRAY)
img_canny = cv2.Canny(img_gray, 100, 200)
cv2.imwrite('back_img_func.jpg', img_canny)
cv2.imshow('image', img_canny)
cv2.waitKey(0)
| magicnian/neteasy | myTest.py | myTest.py | py | 463 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "PIL.Image.open",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "PIL.Image",
"line_number": 5,
"usage_type": "name"
},
{
"api_name": "numpy.array",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "cv2.GaussianBlur",
"line_numbe... |
216104646 |
from ast import Add
from flask import render_template, session, request, url_for, flash, redirect
from loja.produtos.models import Addproduto, Marca, Categoria
from loja import app, db, bcrypt
from .formulario import LoginFormulario, RegistrationForm
from .models import User
import os
@app.route('/admin')
def admin():
if "email" not in session:
flash('Faça seu login!', 'danger')
return redirect(url_for('login'))
produtos = Addproduto.query.all()
return render_template('admin/index.html', tittle='Pagina Ferronorte', produtos=produtos)
@app.route('/marcas')
def marcas():
if "email" not in session:
flash('Faça seu login!', 'danger')
return redirect(url_for('login'))
marcas = Marca.query.order_by(Marca.id.desc()).all()
return render_template('admin/marca.html', tittle='Pagina Marcas', marcas=marcas)
@app.route('/categorias')
def categorias():
if "email" not in session:
flash('Faça seu login!', 'danger')
return redirect(url_for('login'))
categorias = Categoria.query.order_by(Categoria.id.desc()).all()
return render_template('admin/marca.html', tittle='Pagina Categoria', categorias=categorias)
@app.route('/registrar', methods=['GET', 'POST'])
def registrar():
form = RegistrationForm(request.form)
if request.method == 'POST' and form.validate():
user = User(name=form.name.data, username=form.username.data, email=form.email.data,
password=form.password.data)
db.session.add(user)
db.session.commit()
flash(f'Obrigado {form.name.data} por registrar!', 'success')
return redirect(url_for('login'))
return render_template('admin/registrar.html', form=form, tittle="Pagina de Registros")
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginFormulario(request.form)
if request.method == "POST" and form.validate():
user = User.query.filter_by(email=form.email.data).first()
if user:
session['email'] = form.email.data
flash(f'Olá {form.email.data} !', 'success')
return redirect(request.args.get('next') or url_for('admin'))
else:
flash('Nao foi possivel entrar no sistema!', 'danger')
return render_template('admin/login.html', form=form, tittle='Pagina Login')
| ReinierSoares/SiteFlask | loja/admin/rotas.py | rotas.py | py | 2,351 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "flask.session",
"line_number": 15,
"usage_type": "name"
},
{
"api_name": "flask.flash",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "flask.redirect",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "flask.url_for",
"line_nu... |
8247731797 | import cvxopt
import cvxopt.solvers
from cvxopt.solvers import lp
from numpy import array
cvxopt.solvers.options['show_progress'] = False # disable cvxopt output
try:
import cvxopt.glpk
GLPK_IF_AVAILABLE = 'glpk'
# GLPK is the fastest LP solver I could find so far:
# <https://scaron.info/blog/linear-programming-in-python-with-cvxopt.html>
# ... however, it's verbose by default, so tell it to STFU:
cvxopt.solvers.options['glpk'] = {'msg_lev': 'GLP_MSG_OFF'} # cvxopt 1.1.8
cvxopt.solvers.options['msg_lev'] = 'GLP_MSG_OFF' # cvxopt 1.1.7
cvxopt.solvers.options['LPX_K_MSGLEV'] = 0 # previous versions
except ImportError:
# issue a warning as GLPK is the best LP solver in practice
print("CVXOPT import: GLPK solver not found")
GLPK_IF_AVAILABLE = None
def cvxopt_matrix(M):
if isinstance(M, cvxopt.matrix):
return M
return cvxopt.matrix(M)
def cvxopt_solve_lp(c, G, h, A=None, b=None, solver=GLPK_IF_AVAILABLE):
"""
Solve a linear program defined by:
minimize
c.T * x
subject to
G * x <= h
A * x == b
using the LP solver from `CVXOPT <http://cvxopt.org/>`_.
Parameters
----------
c : array, shape=(n,)
Linear-cost vector.
G : array, shape=(m, n)
Linear inequality constraint matrix.
h : array, shape=(m,)
Linear inequality constraint vector.
A : array, shape=(meq, n), optional
Linear equality constraint matrix.
b : array, shape=(meq,), optional
Linear equality constraint vector.
solver : string, optional
Solver to use, default is GLPK if available
Returns
-------
x : array, shape=(n,)
Optimal (primal) solution of the LP, if one exists.
Raises
------
ValueError
If the LP is not feasible.
"""
args = [cvxopt_matrix(c), cvxopt_matrix(G), cvxopt_matrix(h)]
if A is not None:
args.extend([cvxopt_matrix(A), cvxopt_matrix(b)])
sol = lp(*args, solver=solver)
if 'optimal' not in sol['status']:
raise ValueError("LP optimum not found: %s" % sol['status'])
return array(sol['x']).reshape((array(c).shape[0],))
| furiiibond/Tinder | venv/Lib/site-packages/lpsolvers/cvxopt_.py | cvxopt_.py | py | 2,213 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "cvxopt.solvers",
"line_number": 8,
"usage_type": "attribute"
},
{
"api_name": "cvxopt.solvers",
"line_number": 16,
"usage_type": "attribute"
},
{
"api_name": "cvxopt.solvers",
"line_number": 17,
"usage_type": "attribute"
},
{
"api_name": "cvxopt.sol... |
23413088374 | # -*- coding: utf-8 -*-
"""
A disk cache layer to store url and its html.
"""
from __future__ import print_function
import os
import zlib
import diskcache
class CompressedDisk(diskcache.Disk): # pragma: no cover
"""
Serialization Layer. Value has to be bytes or string type, and will be
compressed using zlib before stored to disk.
- Key: str, url.
- Value: str or bytes, html or binary content.
"""
def __init__(self,
directory,
compress_level=6,
value_type_is_binary=False,
**kwargs):
self.compress_level = compress_level
self.value_type_is_binary = value_type_is_binary
if value_type_is_binary is True:
self._decompress = self._decompress_return_bytes
self._compress = self._compress_bytes
elif value_type_is_binary is False:
self._decompress = self._decompress_return_str
self._compress = self._compress_str
else:
msg = "`value_type_is_binary` arg has to be a boolean value!"
raise ValueError(msg)
super(CompressedDisk, self).__init__(directory, **kwargs)
def _decompress_return_str(self, data):
return zlib.decompress(data).decode("utf-8")
def _decompress_return_bytes(self, data):
return zlib.decompress(data)
def _compress_str(self, data):
return zlib.compress(data.encode("utf-8"), self.compress_level)
def _compress_bytes(self, data):
return zlib.compress(data, self.compress_level)
def get(self, key, raw):
data = super(CompressedDisk, self).get(key, raw)
return self._decompress(data)
def store(self, value, read, **kwargs):
if not read:
value = self._compress(value)
return super(CompressedDisk, self).store(value, read, **kwargs)
def fetch(self, mode, filename, value, read):
data = super(CompressedDisk, self). \
fetch(mode, filename, value, read)
if not read:
data = self._decompress(data)
return data
def create_cache(directory,
compress_level=6,
value_type_is_binary=False,
**kwargs):
"""
Create a html cache. Html string will be automatically compressed.
:type directory: str
:param directory: path for the cache directory.
:type compress_level: int
:param compress_level: 0 ~ 9, 9 is slowest and smallest.
:type value_type_is_binary: bool
:param value_type_is_binary: default False.
:param kwargs: other arguments.
:rtype: diskcache.Cache
:return: a `diskcache.Cache()`
"""
cache = diskcache.Cache(
directory,
disk=CompressedDisk,
disk_compress_level=compress_level,
disk_value_type_is_binary=value_type_is_binary,
**kwargs
)
return cache
def create_cache_here(this_file: str,
compress_level: int = 6,
value_type_is_binary: bool = False,
**kwargs) -> diskcache.Cache:
"""
Create a disk cache at the current directory. Cache file will be stored at
``here/.cache`` dir.
:param this_file: always __file__.
:param compress_level: compress level 1 is minimal, 9 is maximum compression.
:param value_type_is_binary: if True, the value expected to be binary.
otherwise string.
:param kwargs: additional keyword arguments
:return: a ``diskcache.Cache`` object
"""
return create_cache(
directory=os.path.join(os.path.dirname(this_file), ".cache"),
compress_level=compress_level,
value_type_is_binary=value_type_is_binary,
**kwargs
)
| MacHu-GWU/crawlib-project | crawlib/cache.py | cache.py | py | 3,738 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "diskcache.Disk",
"line_number": 15,
"usage_type": "attribute"
},
{
"api_name": "zlib.decompress",
"line_number": 43,
"usage_type": "call"
},
{
"api_name": "zlib.decompress",
"line_number": 46,
"usage_type": "call"
},
{
"api_name": "zlib.compress",
... |
30024110320 | from itertools import combinations
from scipy.optimize import fsolve
from copy import copy
from pdb import set_trace
INFT = float(10**10)
class Bound(object):
def __init__(self,x,y,r):
self.x , self.y , self.r = x , y , r
def fit(self,another_bound):
if another_bound.x == INFT :
return self.x + self.r <= 1.0
elif another_bound.x == - INFT :
return self.x - self.r >= 0.0
elif another_bound.y == INFT :
return self.y + self.r <= 1.0
elif another_bound.y == - INFT :
return self.y - self.r >= 0.0
else:
return (self.r + another_bound.r)**2 <= (self.x - another_bound.x)**2 + (self.y - another_bound.y)**2
# return (self.r + another_bound.r)**2 <= (self.x - another_bound.x)**2 + (self.y - another_bound.y)**2
def fit_all(self,bounds):
for i in bounds:
if not self.fit(i):
return False
return True
# bound( x , y , r )
bound_set0 = [
Bound( -INFT , 0.0 , INFT ),
Bound( INFT , 0.0 , INFT ),
Bound( 0.0, -INFT, INFT ),
Bound( 0.0, INFT, INFT ),
Bound( 0.5, 0.5, 0)
]
def find(bound_set):
new_bound_set = copy(bound_set)
max_r = 0
for selected_3_bound in list(combinations(bound_set, 3)):
new_bound = Bound(solve(selected_3_bound)[0],solve(selected_3_bound)[1],solve(selected_3_bound)[2])
# set_trace()
if new_bound.fit_all(new_bound_set) and new_bound.r > max_r:
max_r = new_bound.r
max_bound = new_bound
new_bound_set.append(max_bound)
return new_bound_set
def solve(three_bounds):
def fi(solution,bound):
if bound.x == INFT :
return solution[0] + solution[2] - 1.0
elif bound.x == - INFT :
return solution[0] - solution[2] - 0.0
elif bound.y == INFT :
return solution[1] + solution[2] - 1.0
elif bound.y == - INFT :
return solution[1] - solution[2] - 0.0
else:
return -(solution[2] + bound.r)**2 + (solution[0] - bound.x)**2 + (solution[1] - bound.y)**2
# return -(solution[2] + bound.r)**2 + (solution[0] - bound.x)**2 + (solution[1] - bound.y)**2
f = lambda x :[
fi(x,three_bounds[0]),
fi(x,three_bounds[1]),
fi(x,three_bounds[2])
]
return fsolve(f,[0.5,0.5,0.0])
# test:
for x in find(find(find(find(find(find(bound_set0))))))[len(bound_set0):]:
print(x.x)
print(x.y)
print(x.r)
print('---')
| ElderTrump/ball_in_box | ball_in_box/key_function.py | key_function.py | py | 2,583 | python | en | code | null | github-code | 36 | [
{
"api_name": "copy.copy",
"line_number": 36,
"usage_type": "call"
},
{
"api_name": "itertools.combinations",
"line_number": 38,
"usage_type": "call"
},
{
"api_name": "scipy.optimize.fsolve",
"line_number": 64,
"usage_type": "call"
}
] |
1437749316 | from django.urls import path, include
from . import views
from django.contrib.auth.views import auth_login
urlpatterns = [
path('', views.index, name='main_home'),
path('login', views.index, name='main_login'),
path('account/', views.account, name='main_account'),
path('feed/', views.feed, name='main_feed'),
path('search/', views.search, name='main_search'),
path('message/', views.message, name='main_message'),
path('master/', views.master, name='main_master'),
path('organization/', views.organization, name='main_organization'),
]
| chavkin94/YouDeo | main/urls.py | urls.py | py | 570 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "django.urls.path",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "django.urls.path",
"line_number": 7,
"usage_type": "call"
},
{
"api_name": "django.urls.path",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "django.urls.path",
... |
27452373548 | import json
import os
import re
import sys
class Request(object):
def __init__(self, getenv=os.getenv):
self.getenv_ = getenv
self.populate_options_()
self.populate_args_()
if sys.stdin.isatty() == False:
self.input = json.load(sys.stdin)
else:
self.input = {}
self.service_key = self.getenv_("COG_SERVICE_TOKEN")
self.step = self.getenv_("COG_INVOCATION_STEP", None)
def populate_options_(self):
names = self.getenv_("COG_OPTS")
if names is None:
self.options = None
return
names = re.sub(r'(^"|"$)', r'', names)
names = names.split(",")
self.options = {}
for name in names:
name = name.upper()
# Options that have a list value will have a
# COG_OPT_<NAME>_COUNT environment variable set,
# indicating how many values there are. Scalar values will
# have no such environment variable
count = self.getenv_("COG_OPT_%s_COUNT" % name)
if count is None:
self.options[name] = self.getenv_("COG_OPT_%s" % name)
else:
count = int(count)
values = []
for i in range(count):
values.append(self.getenv_("COG_OPT_%s_%d" % (name, i)))
self.options[name] = values
def populate_args_(self):
arg_count = int(self.getenv_("COG_ARGC", "0"))
if arg_count == 0:
self.args = None
return
self.args = []
for i in range(arg_count):
self.args.append(self.getenv_("COG_ARGV_%d" % i))
def get_optional_option(self, name):
if name in self.options.keys():
return self.options[name]
return None
| operable/pycog3 | cog/request.py | request.py | py | 1,830 | python | en | code | 3 | github-code | 36 | [
{
"api_name": "os.getenv",
"line_number": 7,
"usage_type": "attribute"
},
{
"api_name": "sys.stdin.isatty",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "sys.stdin",
"line_number": 11,
"usage_type": "attribute"
},
{
"api_name": "json.load",
"line_n... |
23741088080 | #! /Users/tianranmao/Projects/so1.0/venv/bin/python
import requests
from bs4 import BeautifulSoup
import datetime
import pytz
import time
import re
import os
# --------------------------------------------------------------------
# Main Function
# --------------------------------------------------------------------
def scrape_web(url):
try:
source = requests.get(url, timeout=20).text
except Exception as e:
print(e)
return None
soup = BeautifulSoup(source, 'lxml')
paragraph = soup.find('p').text
print(paragraph)
print()
return paragraph
if __name__ == "__main__":
week_day_dict = {
0 : 'Monday',
1 : 'Tuesday',
2 : 'Wednesday',
3 : 'Thursday',
4 : 'Friday',
5 : 'Saturday',
6 : 'Sunday'
}
#url_510300_jan = "http://yunhq.sse.com.cn:32041//v1/sho/list/tstyle/510300_01?callback=jQuery112402078220234177265_1577088059316&select=contractid%2Clast%2Cchg_rate%2Cpresetpx%2Cexepx&order=contractid%2Cexepx%2Case&_=1577088059323"
#url_510300_feb = "http://yunhq.sse.com.cn:32041//v1/sho/list/tstyle/510300_02?callback=jQuery112402078220234177265_1577088059316&select=contractid%2Clast%2Cchg_rate%2Cpresetpx%2Cexepx&order=contractid%2Cexepx%2Case&_=1577088059351"
url_510300_mar = "http://yunhq.sse.com.cn:32041//v1/sho/list/tstyle/510300_03?callback=jQuery112402078220234177265_1577088059318&select=contractid%2Clast%2Cchg_rate%2Cpresetpx%2Cexepx&order=contractid%2Cexepx%2Case&_=1577088059356"
url_510300_apr = "http://yunhq.sse.com.cn:32041//v1/sho/list/tstyle/510300_04?callback=jQuery112409417454011549969_1582766597079&select=contractid%2Clast%2Cchg_rate%2Cpresetpx%2Cexepx&order=contractid%2Cexepx%2Case&_=1582766597086"
url_510300_jun = "http://yunhq.sse.com.cn:32041//v1/sho/list/tstyle/510300_06?callback=jQuery112402078220234177265_1577088059336&select=contractid%2Clast%2Cchg_rate%2Cpresetpx%2Cexepx&order=contractid%2Cexepx%2Case&_=1577088059360"
url_510300_sep = "http://yunhq.sse.com.cn:32041//v1/sho/list/tstyle/510300_09?callback=jQuery11240028350739831281335_1579742947846&select=contractid%2Clast%2Cchg_rate%2Cpresetpx%2Cexepx&order=contractid%2Cexepx%2Case&_=1579742947854"
url_510300 = "http://yunhq.sse.com.cn:32041//v1/sh1/line/510300?callback=jQuery1124083017185515941_1577089469213&begin=0&end=-1&select=time%2Cprice%2Cvolume&_=1577089469215"
#url_510050_jan = "http://yunhq.sse.com.cn:32041/v1/sho/list/tstyle/510050_01?callback=jQuery112408090383939976182_1574904018122&select=contractid%2Clast%2Cchg_rate%2Cpresetpx%2Cexepx&_=1574904018127"
#url_510050_feb = "http://yunhq.sse.com.cn:32041//v1/sho/list/tstyle/510050_02?callback=jQuery112407089919710187241_1577321533000&select=contractid%2Clast%2Cchg_rate%2Cpresetpx%2Cexepx&order=contractid%2Cexepx%2Case&_=1577321533005"
url_510050_mar = "http://yunhq.sse.com.cn:32041/v1/sho/list/tstyle/510050_03?callback=jQuery111206287606767948288_1564018683263&select=contractid%2Clast%2Cchg_rate%2Cpresetpx%2Cexepx&_=1564018683268"
url_510050_apr = "http://yunhq.sse.com.cn:32041//v1/sho/list/tstyle/510050_04?callback=jQuery112409417454011549969_1582766597079&select=contractid%2Clast%2Cchg_rate%2Cpresetpx%2Cexepx&order=contractid%2Cexepx%2Case&_=1582766597082"
url_510050_jun = "http://yunhq.sse.com.cn:32041/v1/sho/list/tstyle/510050_06?callback=jQuery111209494863322515489_1571879875297&select=contractid%2Clast%2Cchg_rate%2Cpresetpx%2Cexepx&_=1571879875304"
url_510050_sep = "http://yunhq.sse.com.cn:32041//v1/sho/list/tstyle/510050_09?callback=jQuery11240028350739831281335_1579742947844&select=contractid%2Clast%2Cchg_rate%2Cpresetpx%2Cexepx&order=contractid%2Cexepx%2Case&_=1579742947849"
url_510050 = "http://yunhq.sse.com.cn:32041/v1/sh1/line/510050?callback=jQuery111208396578891098054_1563195335181&begin=0&end=-1&select=time%2Cprice%2Cvolume & _ =1563195335188"
url_list = [url_510300, url_510300_mar, url_510300_apr, url_510300_jun, url_510300_sep, url_510050, url_510050_mar, url_510050_apr, url_510050_jun, url_510050_sep]
while True:
now_shanghai = datetime.datetime.now(tz=pytz.timezone('Asia/Shanghai'))
file_name = f"./txt/{now_shanghai.strftime('%Y-%m-%d')}.txt"
if not os.path.exists(file_name):
with open(file_name, 'w') as f:
pass
for url in url_list:
paragraph = scrape_web(url)
if paragraph!=None:
pattern_date = re.compile('"date":(\d+),')
match_date = re.search(pattern_date, paragraph)
webdate = int(match_date.group(1))
realdate = int(now_shanghai.strftime('%Y%m%d'))
# print("web date is: {}".format(webdate))
# print("real date is: {}".format(realdate))
pattern_time = re.compile('"time":(\d+),')
match_time = re.search(pattern_time, paragraph)
webtime = int(match_time.group(1))
realTimeString = now_shanghai.strftime('%H%M%S')
realTime = int(realTimeString)
# print("web time is: {}".format(webtime))
# print("real time is: {}".format(realTime))
weekday = now_shanghai.weekday()
workday = weekday != 5 and weekday != 6 and webdate==realdate
time_start = 93000
time_break = 113000
time_restart = 130000
time_stop = 150000
time_near = 91500
market_open = workday and ((webtime >= time_start and realTime < time_break) or (webtime >= time_restart and realTime <= time_stop))
nearly_open = workday and ((time_break <= realTime and webtime < time_restart) or (time_near < webtime < time_start))
if market_open:
with open(file_name, 'a') as f:
try:
f.write(paragraph)
f.write('\n')
print('writing to file...')
except Exception as e:
print(e)
if market_open:
print('{} {}{}:{}{}:{}{} markets open'.format(week_day_dict[weekday], realTimeString[0],realTimeString[1],
realTimeString[2],realTimeString[3],
realTimeString[4],realTimeString[5]))
#print('waiting for 5 seconds')
#time.sleep(5)
elif nearly_open:
print('{} {}{}:{}{}:{}{} markets opening soon'.format(week_day_dict[weekday], realTimeString[0],realTimeString[1],
realTimeString[2],realTimeString[3],
realTimeString[4],realTimeString[5]))
print('waiting for 10 seconds')
time.sleep(10)
else:
print('{} {}{}:{}{}:{}{} markets closed'.format(week_day_dict[weekday], realTimeString[0],realTimeString[1],
realTimeString[2],realTimeString[3],
realTimeString[4],realTimeString[5]))
print('waiting for 10 minutes')
time.sleep(600)
| timmao78/so1.0 | get_txt.py | get_txt.py | py | 7,564 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "requests.get",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "bs4.BeautifulSoup",
"line_number": 22,
"usage_type": "call"
},
{
"api_name": "datetime.datetime.now",
"line_number": 76,
"usage_type": "call"
},
{
"api_name": "datetime.datetim... |
13145223871 | #!/usr/bin/env python3
import argparse
import configparser
import json
import os
import tempfile
import shutil
import subprocess
import stat
import time
import dateutil
import dateutil.parser
import urllib.parse
from submitty_utils import dateutils, glob
import grade_items_logging
import write_grade_history
import insert_database_version_data
# these variables will be replaced by INSTALL_SUBMITTY.sh
SUBMITTY_INSTALL_DIR = "__INSTALL__FILLIN__SUBMITTY_INSTALL_DIR__"
SUBMITTY_DATA_DIR = "__INSTALL__FILLIN__SUBMITTY_DATA_DIR__"
HWCRON_UID = "__INSTALL__FILLIN__HWCRON_UID__"
INTERACTIVE_QUEUE = os.path.join(SUBMITTY_DATA_DIR, "to_be_graded_interactive")
BATCH_QUEUE = os.path.join(SUBMITTY_DATA_DIR, "to_be_graded_batch")
USE_DOCKER = False
WRITE_DATABASE = True
# ==================================================================================
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("next_directory")
parser.add_argument("next_to_grade")
parser.add_argument("which_untrusted")
return parser.parse_args()
def get_queue_time(next_directory,next_to_grade):
t = time.ctime(os.path.getctime(os.path.join(next_directory,next_to_grade)))
t = dateutil.parser.parse(t)
t = dateutils.get_timezone().localize(t)
return t
def get_submission_path(next_directory,next_to_grade):
queue_file = os.path.join(next_directory,next_to_grade)
if not os.path.isfile(queue_file):
grade_items_logging.log_message("ERROR: the file does not exist " + queue_file)
raise SystemExit("ERROR: the file does not exist",queue_file)
with open(queue_file, 'r') as infile:
obj = json.load(infile)
return obj
def add_permissions(item,perms):
if os.getuid() == os.stat(item).st_uid:
os.chmod(item,os.stat(item).st_mode | perms)
# else, can't change permissions on this file/directory!
def touch(my_file):
with open(my_file,'a') as tmp:
os.utime(my_file, None)
def add_permissions_recursive(top_dir,root_perms,dir_perms,file_perms):
for root, dirs, files in os.walk(top_dir):
add_permissions(root,root_perms)
for d in dirs:
add_permissions(os.path.join(root, d),dir_perms)
for f in files:
add_permissions(os.path.join(root, f),file_perms)
def get_vcs_info(top_dir, semester, course, gradeable, userid, teamid):
form_json_file = os.path.join(top_dir, 'courses', semester, course, 'config', 'form', 'form_'+gradeable+'.json')
with open(form_json_file, 'r') as fj:
form_json = json.load(fj)
course_ini_file = os.path.join(top_dir, 'courses', semester, course, 'config', 'config.ini')
with open(course_ini_file, 'r') as open_file:
course_ini = configparser.ConfigParser()
course_ini.read_file(open_file)
is_vcs = form_json["upload_type"] == "repository"
# PHP reads " as a character around the string, while Python reads it as part of the string
# so we have to strip out the " in python
vcs_type = course_ini['course_details']['vcs_type'].strip('"')
vcs_base_url = course_ini['course_details']['vcs_base_url'].strip('"')
vcs_subdirectory = form_json["subdirectory"] if is_vcs else ''
vcs_subdirectory = vcs_subdirectory.replace("{$gradeable_id}", gradeable)
vcs_subdirectory = vcs_subdirectory.replace("{$user_id}", userid)
vcs_subdirectory = vcs_subdirectory.replace("{$team_id}", teamid)
return is_vcs, vcs_type, vcs_base_url, vcs_subdirectory
# copy the files & directories from source to target
# it will create directories as needed
# it's ok if the target directory or subdirectories already exist
# it will overwrite files with the same name if they exist
def copy_contents_into(source,target,tmp_logs):
if not os.path.isdir(target):
grade_items_logging.log_message("ERROR: the target directory does not exist " + target)
raise SystemExit("ERROR: the target directory does not exist '", target, "'")
if os.path.isdir(source):
for item in os.listdir(source):
if os.path.isdir(os.path.join(source,item)):
if os.path.isdir(os.path.join(target,item)):
# recurse
copy_contents_into(os.path.join(source,item),os.path.join(target,item),tmp_logs)
elif os.path.isfile(os.path.join(target,item)):
grade_items_logging.log_message("ERROR: the target subpath is a file not a directory '" + os.path.join(target,item) + "'")
raise SystemExit("ERROR: the target subpath is a file not a directory '", os.path.join(target,item), "'")
else:
# copy entire subtree
shutil.copytree(os.path.join(source,item),os.path.join(target,item))
else:
if os.path.exists(os.path.join(target,item)):
with open(os.path.join(tmp_logs,"overall.txt"),'a') as f:
print ("\nWARNING: REMOVING DESTINATION FILE" , os.path.join(target,item),
" THEN OVERWRITING: ", os.path.join(source,item), "\n", file=f)
os.remove(os.path.join(target,item))
try:
shutil.copy(os.path.join(source,item),target)
except:
raise SystemExit("ERROR COPYING FILE: " + os.path.join(source,item) + " -> " + os.path.join(target,item))
# copy files that match one of the patterns from the source directory
# to the target directory.
def pattern_copy(what,patterns,source,target,tmp_logs):
with open(os.path.join(tmp_logs,"overall.txt"),'a') as f:
print (what," pattern copy ", patterns, " from ", source, " -> ", target, file=f)
for pattern in patterns:
for my_file in glob.glob(os.path.join(source,pattern),recursive=True):
# grab the matched name
relpath = os.path.relpath(my_file,source)
# make the necessary directories leading to the file
os.makedirs(os.path.join(target,os.path.dirname(relpath)),exist_ok=True)
# copy the file
shutil.copy(my_file,os.path.join(target,relpath))
print (" COPY ",my_file,
" -> ",os.path.join(target,relpath), file=f)
# give permissions to all created files to the hwcron user
def untrusted_grant_rwx_access(which_untrusted,my_dir):
subprocess.call([os.path.join(SUBMITTY_INSTALL_DIR,"bin","untrusted_execute"),
which_untrusted,
"/usr/bin/find",
my_dir,
"-user",
which_untrusted,
"-exec",
"/bin/chmod",
"o+rwx",
"{}",
";"])
# ==================================================================================
# ==================================================================================
def just_grade_item(next_directory,next_to_grade,which_untrusted):
my_pid = os.getpid()
# verify the hwcron user is running this script
if not int(os.getuid()) == int(HWCRON_UID):
grade_items_logging.log_message("ERROR: must be run by hwcron")
raise SystemExit("ERROR: the grade_item.py script must be run by the hwcron user")
# --------------------------------------------------------
# figure out what we're supposed to grade & error checking
obj = get_submission_path(next_directory,next_to_grade)
submission_path = os.path.join(SUBMITTY_DATA_DIR,"courses",obj["semester"],obj["course"],
"submissions",obj["gradeable"],obj["who"],str(obj["version"]))
if not os.path.isdir(submission_path):
grade_items_logging.log_message("ERROR: the submission directory does not exist" + submission_path)
raise SystemExit("ERROR: the submission directory does not exist",submission_path)
print("pid", my_pid, "GRADE THIS", submission_path)
is_vcs, vcs_type, vcs_base_url, vcs_subdirectory = get_vcs_info(SUBMITTY_DATA_DIR,
obj["semester"],
obj["course"],
obj["gradeable"],
obj["who"],
obj["team"])
is_batch_job = next_directory == BATCH_QUEUE
is_batch_job_string = "BATCH" if is_batch_job else "INTERACTIVE"
queue_time = get_queue_time(next_directory,next_to_grade)
queue_time_longstring = dateutils.write_submitty_date(queue_time)
grading_began = dateutils.get_current_time()
waittime = int((grading_began-queue_time).total_seconds())
grade_items_logging.log_message(is_batch_job,which_untrusted,submission_path,"wait:",waittime,"")
# --------------------------------------------------------
# various paths
provided_code_path = os.path.join(SUBMITTY_DATA_DIR,"courses",obj["semester"],obj["course"],"provided_code",obj["gradeable"])
test_input_path = os.path.join(SUBMITTY_DATA_DIR,"courses",obj["semester"],obj["course"],"test_input",obj["gradeable"])
test_output_path = os.path.join(SUBMITTY_DATA_DIR,"courses",obj["semester"],obj["course"],"test_output",obj["gradeable"])
custom_validation_code_path = os.path.join(SUBMITTY_DATA_DIR,"courses",obj["semester"],obj["course"],"custom_validation_code",obj["gradeable"])
bin_path = os.path.join(SUBMITTY_DATA_DIR,"courses",obj["semester"],obj["course"],"bin")
checkout_path = os.path.join(SUBMITTY_DATA_DIR,"courses",obj["semester"],obj["course"],"checkout",obj["gradeable"],obj["who"],str(obj["version"]))
results_path = os.path.join(SUBMITTY_DATA_DIR,"courses",obj["semester"],obj["course"],"results",obj["gradeable"],obj["who"],str(obj["version"]))
# grab a copy of the current history.json file (if it exists)
history_file = os.path.join(results_path,"history.json")
history_file_tmp = ""
if os.path.isfile(history_file):
filehandle,history_file_tmp = tempfile.mkstemp()
shutil.copy(history_file,history_file_tmp)
# get info from the gradeable config file
json_config = os.path.join(SUBMITTY_DATA_DIR,"courses",obj["semester"],obj["course"],"config","form","form_"+obj["gradeable"]+".json")
with open(json_config, 'r') as infile:
gradeable_config_obj = json.load(infile)
# get info from the gradeable config file
complete_config = os.path.join(SUBMITTY_DATA_DIR,"courses",obj["semester"],obj["course"],"config","complete_config","complete_config_"+obj["gradeable"]+".json")
with open(complete_config, 'r') as infile:
complete_config_obj = json.load(infile)
checkout_subdirectory = complete_config_obj["autograding"].get("use_checkout_subdirectory","")
checkout_subdir_path = os.path.join(checkout_path,checkout_subdirectory)
# --------------------------------------------------------------------
# MAKE TEMPORARY DIRECTORY & COPY THE NECESSARY FILES THERE
tmp = os.path.join("/var/local/submitty/autograding_tmp/",which_untrusted,"tmp")
shutil.rmtree(tmp,ignore_errors=True)
os.makedirs(tmp)
# switch to tmp directory
os.chdir(tmp)
# make the logs directory
tmp_logs = os.path.join(tmp,"tmp_logs")
os.makedirs(tmp_logs)
# grab the submission time
with open (os.path.join(submission_path,".submit.timestamp")) as submission_time_file:
submission_string = submission_time_file.read().rstrip()
submission_datetime = dateutils.read_submitty_date(submission_string)
# --------------------------------------------------------------------
# CHECKOUT THE STUDENT's REPO
if is_vcs:
# is vcs_subdirectory standalone or should it be combined with base_url?
if vcs_subdirectory[0] == '/' or '://' in vcs_subdirectory:
vcs_path = vcs_subdirectory
else:
if '://' in vcs_base_url:
vcs_path = urllib.parse.urljoin(vcs_base_url, vcs_subdirectory)
else:
vcs_path = os.path.join(vcs_base_url, vcs_subdirectory)
with open(os.path.join(tmp_logs, "overall.txt"), 'a') as f:
print("====================================\nVCS CHECKOUT", file=f)
print('vcs_base_url', vcs_base_url, file=f)
print('vcs_subdirectory', vcs_subdirectory, file=f)
print('vcs_path', vcs_path, file=f)
print(['/usr/bin/git', 'clone', vcs_path, checkout_path], file=f)
# cleanup the previous checkout (if it exists)
shutil.rmtree(checkout_path,ignore_errors=True)
os.makedirs(checkout_path, exist_ok=True)
subprocess.call(['/usr/bin/git', 'clone', vcs_path, checkout_path])
os.chdir(checkout_path)
# determine which version we need to checkout
what_version = subprocess.check_output(['git', 'rev-list', '-n', '1', '--before="'+submission_string+'"', 'master'])
what_version = str(what_version.decode('utf-8')).rstrip()
if what_version == "":
# oops, pressed the grade button before a valid commit
shutil.rmtree(checkout_path, ignore_errors=True)
else:
# and check out the right version
subprocess.call(['git', 'checkout', '-b', 'grade', what_version])
os.chdir(tmp)
subprocess.call(['ls', '-lR', checkout_path], stdout=open(tmp_logs + "/overall.txt", 'a'))
# --------------------------------------------------------------------
# START DOCKER
container = None
if USE_DOCKER:
container = subprocess.check_output(['docker', 'run', '-t', '-d',
'-v', tmp + ':' + tmp,
'ubuntu:custom']).decode('utf8').strip()
# --------------------------------------------------------------------
# COMPILE THE SUBMITTED CODE
with open(os.path.join(tmp_logs, "overall.txt"), 'a') as f:
print("====================================\nCOMPILATION STARTS", file=f)
# copy submitted files to the tmp compilation directory
tmp_compilation = os.path.join(tmp,"TMP_COMPILATION")
os.mkdir(tmp_compilation)
os.chdir(tmp_compilation)
gradeable_deadline_string = gradeable_config_obj["date_due"]
patterns_submission_to_compilation = complete_config_obj["autograding"]["submission_to_compilation"]
pattern_copy("submission_to_compilation",patterns_submission_to_compilation,submission_path,tmp_compilation,tmp_logs)
if is_vcs:
pattern_copy("checkout_to_compilation",patterns_submission_to_compilation,checkout_subdir_path,tmp_compilation,tmp_logs)
# copy any instructor provided code files to tmp compilation directory
copy_contents_into(provided_code_path,tmp_compilation,tmp_logs)
subprocess.call(['ls', '-lR', '.'], stdout=open(tmp_logs + "/overall.txt", 'a'))
# copy compile.out to the current directory
shutil.copy (os.path.join(bin_path,obj["gradeable"],"compile.out"),os.path.join(tmp_compilation,"my_compile.out"))
# give the untrusted user read/write/execute permissions on the tmp directory & files
add_permissions_recursive(tmp_compilation,
stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP,
stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP,
stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP)
add_permissions(tmp,stat.S_IROTH | stat.S_IXOTH)
add_permissions(tmp_logs,stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
with open(os.path.join(tmp_logs,"compilation_log.txt"), 'w') as logfile:
if USE_DOCKER:
compile_success = subprocess.call(['docker', 'exec', '-w', tmp_compilation, container,
os.path.join(tmp_compilation, 'my_compile.out'), obj['gradeable'],
obj['who'], str(obj['version']), submission_string], stdout=logfile)
else:
compile_success = subprocess.call([os.path.join(SUBMITTY_INSTALL_DIR,"bin","untrusted_execute"),
which_untrusted,
os.path.join(tmp_compilation,"my_compile.out"),
obj["gradeable"],
obj["who"],
str(obj["version"]),
submission_string],
stdout=logfile)
if compile_success == 0:
print ("pid",my_pid,"COMPILATION OK")
else:
print ("pid",my_pid,"COMPILATION FAILURE")
grade_items_logging.log_message(is_batch_job,which_untrusted,submission_path,"","","COMPILATION FAILURE")
#raise SystemExit()
untrusted_grant_rwx_access(which_untrusted,tmp_compilation)
# remove the compilation program
os.remove(os.path.join(tmp_compilation,"my_compile.out"))
# return to the main tmp directory
os.chdir(tmp)
# --------------------------------------------------------------------
# make the runner directory
with open(os.path.join(tmp_logs,"overall.txt"),'a') as f:
print ("====================================\nRUNNER STARTS", file=f)
tmp_work = os.path.join(tmp,"TMP_WORK")
os.makedirs(tmp_work)
os.chdir(tmp_work)
# move all executable files from the compilation directory to the main tmp directory
# Note: Must preserve the directory structure of compiled files (esp for Java)
patterns_submission_to_runner = complete_config_obj["autograding"]["submission_to_runner"]
pattern_copy("submission_to_runner",patterns_submission_to_runner,submission_path,tmp_work,tmp_logs)
if is_vcs:
pattern_copy("checkout_to_runner",patterns_submission_to_runner,checkout_subdir_path,tmp_work,tmp_logs)
patterns_compilation_to_runner = complete_config_obj["autograding"]["compilation_to_runner"]
pattern_copy("compilation_to_runner",patterns_compilation_to_runner,tmp_compilation,tmp_work,tmp_logs)
# copy input files to tmp_work directory
copy_contents_into(test_input_path,tmp_work,tmp_logs)
subprocess.call(['ls', '-lR', '.'], stdout=open(tmp_logs + "/overall.txt", 'a'))
# copy runner.out to the current directory
shutil.copy (os.path.join(bin_path,obj["gradeable"],"run.out"),os.path.join(tmp_work,"my_runner.out"))
# give the untrusted user read/write/execute permissions on the tmp directory & files
add_permissions_recursive(tmp_work,
stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH,
stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH,
stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH)
# raise SystemExit()
# run the run.out as the untrusted user
with open(os.path.join(tmp_logs,"runner_log.txt"), 'w') as logfile:
print ("LOGGING BEGIN my_runner.out",file=logfile)
logfile.flush()
try:
if USE_DOCKER:
runner_success = subprocess.call(['docker', 'exec', '-w', tmp_work, container,
os.path.join(tmp_work, 'my_runner.out'), obj['gradeable'],
obj['who'], str(obj['version']), submission_string], stdout=logfile)
else:
runner_success = subprocess.call([os.path.join(SUBMITTY_INSTALL_DIR,"bin","untrusted_execute"),
which_untrusted,
os.path.join(tmp_work,"my_runner.out"),
obj["gradeable"],
obj["who"],
str(obj["version"]),
submission_string],
stdout=logfile)
logfile.flush()
except Exception as e:
print ("ERROR caught runner.out exception={0}".format(str(e.args[0])).encode("utf-8"),file=logfile)
logfile.flush()
print ("LOGGING END my_runner.out",file=logfile)
logfile.flush()
killall_success = subprocess.call([os.path.join(SUBMITTY_INSTALL_DIR,"bin","untrusted_execute"),
which_untrusted,
os.path.join(SUBMITTY_INSTALL_DIR,"bin","killall.py")],
stdout=logfile)
print ("KILLALL COMPLETE my_runner.out",file=logfile)
logfile.flush()
if killall_success != 0:
msg='RUNNER ERROR: had to kill {} process(es)'.format(killall_success)
print ("pid",my_pid,msg)
grade_items_logging.log_message(is_batch_job,which_untrusted,submission_path,"","",msg)
if runner_success == 0:
print ("pid",my_pid,"RUNNER OK")
else:
print ("pid",my_pid,"RUNNER FAILURE")
grade_items_logging.log_message(is_batch_job,which_untrusted,submission_path,"","","RUNNER FAILURE")
untrusted_grant_rwx_access(which_untrusted,tmp_work)
untrusted_grant_rwx_access(which_untrusted,tmp_compilation)
# --------------------------------------------------------------------
# RUN VALIDATOR
with open(os.path.join(tmp_logs,"overall.txt"),'a') as f:
print ("====================================\nVALIDATION STARTS", file=f)
# copy results files from compilation...
patterns_submission_to_validation = complete_config_obj["autograding"]["submission_to_validation"]
pattern_copy("submission_to_validation",patterns_submission_to_validation,submission_path,tmp_work,tmp_logs)
if is_vcs:
pattern_copy("checkout_to_validation",patterns_submission_to_validation,checkout_subdir_path,tmp_work,tmp_logs)
patterns_compilation_to_validation = complete_config_obj["autograding"]["compilation_to_validation"]
pattern_copy("compilation_to_validation",patterns_compilation_to_validation,tmp_compilation,tmp_work,tmp_logs)
# remove the compilation directory
shutil.rmtree(tmp_compilation)
# copy output files to tmp_work directory
copy_contents_into(test_output_path,tmp_work,tmp_logs)
# copy any instructor custom validation code into the tmp work directory
copy_contents_into(custom_validation_code_path,tmp_work,tmp_logs)
subprocess.call(['ls', '-lR', '.'], stdout=open(tmp_logs + "/overall.txt", 'a'))
# copy validator.out to the current directory
shutil.copy (os.path.join(bin_path,obj["gradeable"],"validate.out"),os.path.join(tmp_work,"my_validator.out"))
# give the untrusted user read/write/execute permissions on the tmp directory & files
add_permissions_recursive(tmp_work,
stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH,
stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH,
stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH)
add_permissions(os.path.join(tmp_work,"my_validator.out"),stat.S_IROTH | stat.S_IXOTH)
# validator the validator.out as the untrusted user
with open(os.path.join(tmp_logs,"validator_log.txt"), 'w') as logfile:
if USE_DOCKER:
validator_success = subprocess.call(['docker', 'exec', '-w', tmp_work, container,
os.path.join(tmp_work, 'my_validator.out'), obj['gradeable'],
obj['who'], str(obj['version']), submission_string], stdout=logfile)
else:
validator_success = subprocess.call([os.path.join(SUBMITTY_INSTALL_DIR,"bin","untrusted_execute"),
which_untrusted,
os.path.join(tmp_work,"my_validator.out"),
obj["gradeable"],
obj["who"],
str(obj["version"]),
submission_string],
stdout=logfile)
if validator_success == 0:
print ("pid",my_pid,"VALIDATOR OK")
else:
print ("pid",my_pid,"VALIDATOR FAILURE")
grade_items_logging.log_message(is_batch_job,which_untrusted,submission_path,"","","VALIDATION FAILURE")
untrusted_grant_rwx_access(which_untrusted,tmp_work)
# grab the result of autograding
grade_result = ""
with open(os.path.join(tmp_work,"grade.txt")) as f:
lines = f.readlines()
for line in lines:
line = line.rstrip('\n')
if line.startswith("Automatic grading total:"):
grade_result = line
# --------------------------------------------------------------------
# MAKE RESULTS DIRECTORY & COPY ALL THE FILES THERE
with open(os.path.join(tmp_logs,"overall.txt"),'a') as f:
print ("====================================\nARCHIVING STARTS", file=f)
subprocess.call(['ls', '-lR', '.'], stdout=open(tmp_logs + "/overall.txt", 'a'))
os.chdir(bin_path)
# save the old results path!
if os.path.isdir(os.path.join(results_path,"OLD")):
shutil.move(os.path.join(results_path,"OLD"),
os.path.join(tmp,"OLD_RESULTS"))
# clean out all of the old files if this is a re-run
shutil.rmtree(results_path,ignore_errors=True)
# create the directory (and the full path if it doesn't already exist)
os.makedirs(results_path)
# bring back the old results!
if os.path.isdir(os.path.join(tmp,"OLD_RESULTS")):
shutil.move(os.path.join(tmp,"OLD_RESULTS"),
os.path.join(results_path,"OLD"))
os.makedirs(os.path.join(results_path,"details"))
patterns_work_to_details = complete_config_obj["autograding"]["work_to_details"]
pattern_copy("work_to_details",patterns_work_to_details,tmp_work,os.path.join(results_path,"details"),tmp_logs)
if not history_file_tmp == "":
shutil.move(history_file_tmp,history_file)
# fix permissions
ta_group_id = os.stat(results_path).st_gid
os.chown(history_file,int(HWCRON_UID),ta_group_id)
add_permissions(history_file,stat.S_IRGRP)
grading_finished = dateutils.get_current_time()
shutil.copy(os.path.join(tmp_work,"results.json"),results_path)
shutil.copy(os.path.join(tmp_work,"grade.txt"),results_path)
# -------------------------------------------------------------
# create/append to the results history
gradeable_deadline_datetime = dateutils.read_submitty_date(gradeable_deadline_string)
gradeable_deadline_longstring = dateutils.write_submitty_date(gradeable_deadline_datetime)
submission_longstring = dateutils.write_submitty_date(submission_datetime)
seconds_late = int((submission_datetime-gradeable_deadline_datetime).total_seconds())
# note: negative = not late
grading_began_longstring = dateutils.write_submitty_date(grading_began)
grading_finished_longstring = dateutils.write_submitty_date(grading_finished)
gradingtime = int((grading_finished-grading_began).total_seconds())
write_grade_history.just_write_grade_history(history_file,
gradeable_deadline_longstring,
submission_longstring,
seconds_late,
queue_time_longstring,
is_batch_job_string,
grading_began_longstring,
waittime,
grading_finished_longstring,
gradingtime,
grade_result)
#---------------------------------------------------------------------
# WRITE OUT VERSION DETAILS
if WRITE_DATABASE:
insert_database_version_data.insert_to_database(
obj["semester"],
obj["course"],
obj["gradeable"],
obj["user"],
obj["team"],
obj["who"],
True if obj["is_team"] else False,
str(obj["version"]))
print ("pid",my_pid,"finished grading ", next_to_grade, " in ", gradingtime, " seconds")
grade_items_logging.log_message(is_batch_job,which_untrusted,submission_path,"grade:",gradingtime,grade_result)
with open(os.path.join(tmp_logs,"overall.txt"),'a') as f:
f.write("FINISHED GRADING!")
# save the logs!
shutil.copytree(tmp_logs,os.path.join(results_path,"logs"))
# --------------------------------------------------------------------
# REMOVE TEMP DIRECTORY
shutil.rmtree(tmp)
# --------------------------------------------------------------------
# CLEAN UP DOCKER
if USE_DOCKER:
subprocess.call(['docker', 'rm', '-f', container])
# ==================================================================================
# ==================================================================================
if __name__ == "__main__":
args = parse_args()
just_grade_item(args.next_directory,args.next_to_grade,args.which_untrusted)
| alirizwi/Submitty | bin/grade_item.py | grade_item.py | py | 29,887 | python | en | code | null | github-code | 36 | [
{
"api_name": "os.path.join",
"line_number": 25,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 25,
"usage_type": "attribute"
},
{
"api_name": "os.path.join",
"line_number": 26,
"usage_type": "call"
},
{
"api_name": "os.path",
"line_number": 2... |
32191704409 | import time
from threading import Timer
import xmlrpc.client
from .edit import Edit
from .utils import firmwareWarning
import json
import os
import base64
class Session(object):
"""
Session object
"""
def __init__(self, sessionURL, mainAPI, autoHeartbeat=True, autoHeartbeatInterval=10):
self.url = sessionURL
self.mainAPI = mainAPI
self.defaultAutoHeartbeatInterval = autoHeartbeatInterval
self.rpc = xmlrpc.client.ServerProxy(self.url)
self.connected = True
self._edit = None
if autoHeartbeat:
self.rpc.heartbeat(autoHeartbeatInterval)
self.autoHeartbeatInterval = autoHeartbeatInterval
self.autoHeartbeatTimer = Timer(autoHeartbeatInterval - 1, self.doAutoHeartbeat)
self.autoHeartbeatTimer.start()
else:
self.rpc.heartbeat(300)
def __del__(self):
self.cancelSession()
@property
def OperatingMode(self):
"""
Get the current operation mode for the session.
:return: (int)
0: run mode
1: edit mode
"""
result = int(self.mainAPI.getParameter("OperatingMode"))
return result
@property
def edit(self) -> Edit:
"""
Requesting an Edit object with this property. If the edit mode is False at the moment,
the edit mode will be activated with this request with the function setOperationMode(1).
:return: Edit object
"""
if not self.OperatingMode:
return self.setOperatingMode(mode=1)
else:
self._edit = Edit(editURL=self.url + 'edit/',
sessionAPI=self,
mainAPI=self.mainAPI)
return self._edit
def startEdit(self) -> Edit:
"""
Starting the edit mode and requesting an Edit object.
:return:
"""
self.rpc.setOperatingMode(1)
self._edit = Edit(editURL=self.url + 'edit/',
sessionAPI=self,
mainAPI=self.mainAPI)
return self._edit
def stopEdit(self) -> None:
"""
Stopping the edit mode.
:return: None
"""
self.rpc.setOperatingMode(0)
self._edit = None
def heartbeat(self, heartbeatInterval: int) -> int:
"""
Extend the live time of edit-session If the given value is outside the range of "SessionTimeout",
the saved default timeout will be used.
:param heartbeatInterval: (int) requested timeout-interval till next heartbeat, in seconds
:return: (int) the used timeout-interval, in seconds
"""
result = self.rpc.heartbeat(heartbeatInterval)
return result
def doAutoHeartbeat(self) -> None:
"""
Auto Heartbeat Timer for automatic extending the live time of edit-session.
If the given value is outside the range of "SessionTimeout", the saved default timeout will be used.
:return: None
"""
newHeartbeatInterval = self.heartbeat(self.autoHeartbeatInterval)
self.autoHeartbeatInterval = newHeartbeatInterval
# schedule event a little ahead of time
self.autoHeartbeatTimer = Timer(self.autoHeartbeatInterval - 1, self.doAutoHeartbeat)
self.autoHeartbeatTimer.start()
def cancelSession(self) -> None:
"""
Explicit stopping this session If an application is still in edit-mode, it will implicit do the same
as "stopEditingApplication". If an import or export is still being processed, the session is kept alive
until the import/export has finished, although the method returns immediately.
:return: None
"""
if self.autoHeartbeatTimer:
self.autoHeartbeatTimer.cancel()
self.autoHeartbeatTimer.join()
self.autoHeartbeatTimer = None
if self.connected:
self.rpc.cancelSession()
self.connected = False
def exportConfig(self) -> bytearray:
"""
Exports the whole configuration of the sensor-device and stores it at the desired path.
:return: (bytearray) configuration as one data-blob :binary/base64
"""
# increase heartbeat interval which will prevent a closed session after the "long" export progress
self.heartbeat(heartbeatInterval=30)
config = self.rpc.exportConfig()
config_bytes = bytearray()
config_bytes.extend(map(ord, str(config)))
while self.getExportProgress() < 1.0:
time.sleep(1)
self.cleanupExport()
self.mainAPI.waitForConfigurationDone()
return config_bytes
def importConfig(self, config: str, global_settings=True, network_settings=False, applications=True) -> None:
"""
Import whole configuration, with the option to skip specific parts.
:param config: (str) The config file (*.o2d5xxcfg) as a Binary/base64 data
:param global_settings: (bool) Include Globale-Configuration (Name, Description, Location, ...)
:param network_settings: (bool) Include Network-Configuration (IP, DHCP, ...)
:param applications: (bool) Include All Application-Configurations
:return: None
"""
# This is required due to the long import progress which may take longer than 10 seconds (default)
self.heartbeat(heartbeatInterval=30)
if global_settings:
self.rpc.importConfig(config, 0x0001)
if network_settings:
self.rpc.importConfig(config, 0x0002)
if applications:
self.rpc.importConfig(config, 0x0010)
while self.getImportProgress() < 1.0:
time.sleep(1)
self.mainAPI.waitForConfigurationDone()
def exportApplication(self, applicationIndex: int) -> bytearray:
"""
Exports one application-config.
:param applicationIndex: (int) application index
:return: None
"""
config = self.rpc.exportApplication(applicationIndex)
application_bytes = bytearray()
application_bytes.extend(map(ord, str(config)))
while self.getExportProgress() < 1.0:
time.sleep(1)
else:
self.cleanupExport()
return application_bytes
def importApplication(self, application: str) -> int:
"""
Imports an application-config and creates a new application with it.
:param application: (str) application-config as one-data-blob: binary/base64
:return: (int) index of new application in list
"""
if not self.OperatingMode:
self.setOperatingMode(mode=1)
index = int(self.rpc.importApplication(application))
while self.getImportProgress() < 1.0:
time.sleep(1)
self.setOperatingMode(mode=0)
else:
index = int(self.rpc.importApplication(application))
while self.getImportProgress() < 1.0:
time.sleep(1)
self.mainAPI.waitForConfigurationDone()
return index
def getImportProgress(self) -> float:
"""
Get the progress of the asynchronous configuration import (yields 1.0 when the last import has finished).
Returns xmlrpc errors occurring during import.
:return: (float) progress (0.0 to 1.0)
"""
try:
result = self.rpc.getImportProgress()
return result
except xmlrpc.client.Fault as fault:
if fault.faultCode == 101107:
return 1.0
def getExportProgress(self) -> float:
"""
Returns the progress of the ongoing export (configuration or application). After the export is done
this method returns 1.0 until the cleanupExport() is called.
:return: (float) progress (0.0 to 1.0)
"""
try:
result = self.rpc.getExportProgress()
return result
except xmlrpc.client.Fault as fault:
if fault.faultCode == 101110:
return 1.0
finally:
self.cleanupExport()
def cleanupExport(self) -> None:
"""
Removes the exported configuration/application binary archive file from the device tmpfs.
Shall be called after the file is fully downloaded by the user with HTTP GET request.
:return: None
"""
self.rpc.cleanupExport()
def getApplicationDetails(self, applicationIndex: [int, str]) -> dict:
"""
The method returns details about the application line ApplicationType,
TemplateInfo and Models with Type and Name.
:param applicationIndex: (int) application Index
:return: (dict) json-string containing application parameters, models and image settings
"""
result = json.loads(self.rpc.getApplicationDetails(applicationIndex))
return result
def resetStatistics(self) -> None:
"""
Resets the statistic data of current active application.
:return: None
"""
self.rpc.resetStatistics()
self.mainAPI.waitForConfigurationDone()
@staticmethod
def writeApplicationConfigFile(applicationName: str, data: bytearray) -> None:
"""
Stores the application data as an o2d5xxapp-file in the desired path.
:param applicationName: (str) application name as str
:param data: (bytearray) application data
:return: None
"""
extension = ".o2d5xxapp"
filename, file_extension = os.path.splitext(applicationName)
if not file_extension == extension:
applicationName = filename + extension
with open(applicationName, "wb") as f:
f.write(data)
@staticmethod
def writeConfigFile(configName: str, data: bytearray) -> None:
"""
Stores the config data as an o2d5xxcfg-file in the desired path.
:param configName: (str) application file path as str
:param data: (bytearray) application data
:return: None
"""
extension = ".o2d5xxcfg"
filename, file_extension = os.path.splitext(configName)
if not file_extension == extension:
configName = filename + extension
with open(configName, "wb") as f:
f.write(data)
def readApplicationConfigFile(self, applicationFile: str) -> str:
"""
Read and decode an application-config file.
:param applicationFile: (str) application config file path
:return: (str) application data
"""
result = self.readConfigFile(configFile=applicationFile)
return result
@firmwareWarning
def readConfigFile(self, configFile: str) -> str:
"""
Read and decode a device-config file.
:param configFile: (str) config file path
:return: (str) config data
"""
if isinstance(configFile, str):
if os.path.exists(os.path.dirname(configFile)):
with open(configFile, "rb") as f:
encodedZip = base64.b64encode(f.read())
decoded = encodedZip.decode()
return decoded
else:
raise FileExistsError("File {} does not exist!".format(configFile))
def setOperatingMode(self, mode) -> [None, Edit]:
"""
Changes the operation mode of the device. Setting this to "edit" will enable the "EditMode"-object on RPC.
:param mode: 1 digit
0: run mode
1: edit mode
2: simulation mode (Not implemented!)
:return: None or Edit object
"""
if mode == 0: # stop edit mode
self.stopEdit()
elif mode == 1: # start edit mode
return self.startEdit()
else:
raise ValueError("Invalid operating mode")
def __getattr__(self, name):
# Forward otherwise undefined method calls to XMLRPC proxy
return getattr(self.rpc, name)
| ifm/o2x5xx-python | source/rpc/session.py | session.py | py | 12,153 | python | en | code | 3 | github-code | 36 | [
{
"api_name": "xmlrpc.client.client.ServerProxy",
"line_number": 20,
"usage_type": "call"
},
{
"api_name": "xmlrpc.client.client",
"line_number": 20,
"usage_type": "attribute"
},
{
"api_name": "xmlrpc.client",
"line_number": 20,
"usage_type": "name"
},
{
"api_name... |
18694457154 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 21 11:14:59 2023
@author: giamp
"""
import scipy
import logging
import numpy as np
import hcd
import matplotlib.pyplot as plt
from hppdWC import utils
from hppdWC import plots
def cutInTime(x, y, interval):
'''
Given x (time array), y (values), and interval, erases all the x,y pairs whose x is
before interval[0] and after interval[1]
Parameters
----------
x : np.array or list
time array.
y : np.array or list
correspoding values.
interval : list of 2 values [start finish]
DESCRIPTION.
Returns
-------
x : np.array or list
only the values after start and before stop.
y : np.array or list
only the corresponding values to x.
'''
start = interval[0]
stop = interval[1]
if start < stop:
# first cut signal and then time, time gives the condition
# cut the tails
y = y[x<=stop]
x = x[x<=stop]
# cut the heads
y = y[x>=start]
x = x[x>=start]
# reset the time
x = x - x[0]
else:
logging.warning('not cutting the arrays since stop is before start')
return x, y
def syncXcorr(signal1, signal2, time1, time2, step = 0.01, \
interval1 = [0, 0], interval2 = [0, 0]):
'''
Computes the delay of signal2 with respect to signal1 using cross correlation.
To do so, a similar pattern should be present in both signals.
"time1" and "time2" contain the relative time of the recording and should:
- be in the same measurement unit (eg: seconds)
- start both from 0
The returned value "delay" will be in the same measurement unit.
"signal1" is the one that gives the t=0, while the advance/delay in the
starting of the recording of "signal2" is computed.
The returned value is "delay", which expresses:
- the timing delay of signal2 wrt to signal1,
- the OPPOSITE (minus sign) of the timing delay in the recording
If the recording of 2 starts before 1, when plotting the two signals,
you see the event happening in 1 first and then in 2.
To graphically synchronize them, it's necessary to move 2 towards right
To timewise synchronize them, it's necessary to cut the first frames of 2
(the ones when 2 was already recording and 1 wasn't) and to reset the timer of 2
If "delay" is *POSITIVE*, then signal2 started to be recorded AFTER "delay" time.
To synchronize the two signals, it's necessary to add values in the head of
signal2
NOT SYNC SIGNALS
-----------****------- signal1
--------****------- signal2
delay = 3 -> signal2 started to be recorded 3 after
SYNC SIGNALS
-----------****------- signal1
add--------****------- signal2
If "delay" is *NEGATIVE*, then signal2 started to be recorded BEFORE "delay" time.
To synchronize the two signals, it's necessary to cut values from the head of
signal2
NOT SYNC SIGNALS
-----------****------- signal1
--------------****------- signal2
delay = -3 -> signal2 started to be recorded 3 before
SYNC SIGNALS
-----------****------- signal1
-----------****------- signal2
Parameters
----------
signal1 : array
Contains the y value of signal 1
signal2 : array
Contains the y value of signal 2
time1 : array
Contains the x value of signal 1
time2 : array
Contains the x value of signal 2
step : int, optional
To perform cross correlation, both signals should be at the same
frequency, it's necessary to resample them. The step should be in the
same measurement units of time1 and time2
The default is 0.01.
interval1 : list of 2 values: [startTime endTime], optional
Part of the signal1 that should be considered when executing the xcorr.
The default is [0, 0], which means the whole signal.
interval2 : list of 2 values: [startTime endTime], optional
Part of the signal2 that should be considered when executing the xcorr.
The default is [0, 0], which means the whole signal.
showPlot : bool, optional
If the function should display a plot regarding the execution.
The default is False.
device1 : string, optional
Name of device 1 in the plot.
The default is 'device 1'.
device2 : string, optional
Name of device 2 in the plot.
The default is 'device 2'.
userTitle : string, optional
To be added in the title
The default is ''.
Returns
-------
delay : float
Delay in the same temporal measurement unit of the two signals
If POSITIVE, signal2 started to be recorded AFTER signal1
If NEGATIVE, signal2 started to be recorded BEFORE signal1
maxError : float
maxError = step / 2
'''
# keeping sure that the variables are numpy.arrays
signal1, _ = utils.toFloatNumpyArray(signal1)
signal2, _ = utils.toFloatNumpyArray(signal2)
time1, _ = utils.toFloatNumpyArray(time1)
time2, _ = utils.toFloatNumpyArray(time2)
signal1 = fillNanWithInterp(signal1, time1)
signal2 = fillNanWithInterp(signal2, time2)
# # eventually cutting the signal1
# if interval1 != [0, 0]:
# time1, signal1 = cutInTime(time1, signal1, interval1)
# # eventually cutting the signal2
# if interval2 != [0, 0]:
# time2, signal2 = cutInTime(time2, signal2, interval2)
# user delay
# since the xcorrelation works on the y values only, the cutting of the
# signals should be taken into account as an additional delay
userDelay = interval1[0] - interval2[0]
# resampling both signals on the same frequency
y1, x1, _ = resampleWithInterp(signal1, time1, step, 'time step')
y2, x2, _ = resampleWithInterp(signal2, time2, step, 'time step')
# eventually cutting the signal1
if interval1 != [0, 0]:
x1, y1 = cutInTime(x1, y1, interval1)
# eventually cutting the signal2
if interval2 != [0, 0]:
x2, y2 = cutInTime(x2, y2, interval2)
# eventually remove last element from signal with more value
if len(x2)!=len(x1):
if len(x2)>len(x1):
x2=x2[0:-1]
y2=y2[0:-1]
else:
x1=x1[0:-1]
y1=y1[0:-1]
# putting the values around 0
y1 = y1 - np.mean(y1)
y2 = y2 - np.mean(y2)
# normalizing from -1 to 1
y1 = y1 / np.max(np.abs(y1))
y2 = y2 / np.max(np.abs(y2))
# compute correlation
corr = scipy.signal.correlate(y1, y2)
lags = scipy.signal.correlation_lags(len(y1), len(y2))
# where there is max correlation
index = np.argmax(corr)
delay = lags[index]*step
# adding the userDelay to the one computed on the signals
delay = delay + userDelay
maxError = step/2
results=[x1, y1, interval1, x2, y2, interval2, delay, lags, step, userDelay, maxError, corr, index]
return results
def plot_syncXcorr(results, device1, device2, userTitle = '', col1 = 'C0', col2 = 'C1'):
[x1,y1,interval1,x2,y2,interval2,delay,lags,step,userDelay,maxError,corr,index]=results
if delay > 0:
mainTitle = r"{} ({:.2f}-{:.2f}) started {:.3f} $\pm$ {:.3f} after {} ({:.2f}-{:.2f})".format(device2, interval2[0], interval2[1], np.absolute(delay), maxError, device1, interval1[0], interval1[1])
mainTitle = r"{} ({:.2f}-{:.2f}) started {:.3f} after {} ({:.2f}-{:.2f})".format(device2, interval2[0], interval2[1], np.absolute(delay), device1, interval1[0], interval1[1])
elif delay < 0:
mainTitle = r"{} ({:.2f}-{:.2f}) started {:.3f} $\pm$ {:.3f} before {} ({:.2f}-{:.2f})".format(device2, interval2[0], interval2[1], np.absolute(delay), maxError, device1, interval1[0], interval1[1])
mainTitle = r"{} ({:.2f}-{:.2f}) started {:.3f} before {} ({:.2f}-{:.2f})".format(device2, interval2[0], interval2[1], np.absolute(delay), device1, interval1[0], interval1[1])
else:
mainTitle = r"{} started at the same time of {}".format(device2, device1)
if userTitle != '':
mainTitle = mainTitle + ' - ' + userTitle
fig, ax = plots.drawInSubPlots(\
listXarrays = \
[[(x1 + interval1[0]).tolist(),(x2 + interval2[0]).tolist()],\
(lags*step + userDelay).tolist(), \
[(x1 + interval1[0]).tolist(),(x2 + interval2[0] +delay).tolist()]],\
listYarrays = \
[[y1.tolist(), y2.tolist()], \
corr,\
[y1.tolist(), y2.tolist()]], \
listOfTitles = \
['not synchronized signals', \
'correlation according to shift',\
'synchronized signals'], \
sharex = False, nrows = 3, mainTitle = mainTitle, listOfkwargs=[[{'color': col1},{'color': col2}],{'marker':''}], listOfLegends = [[device1, device2], ['']])
for this_ax in [ax[0], ax[2]]:
this_ax2 = this_ax.twinx()
this_ax.set_xlabel('time [s]')
this_ax.set_ylabel(device1, color = col1)
this_ax2.set_ylabel(device2, color = col2)
this_ax.set_xlim(np.min([np.min(x1 + interval1[0]), np.min(x2 + interval2[0]), np.min(x2 + interval2[0] + delay)]), np.max([np.max(x1 + interval1[0]), np.max(x2 + interval2[0]), np.max(x2 + interval2[0] + delay)]))
this_ax = ax[1]
this_ax.axvline(lags[index]*step + userDelay, color = 'r')
this_ax.set_xlabel('lag (time [s])')
this_ax.set_ylabel('correlation')
this_ax.set_xlim(np.min(lags*step + userDelay), np.max(lags*step + userDelay))
return fig, ax
#plots.syncXcorr(x1, y1, interval1, device1, x2, y2, interval2, device2, delay, lags, step, userDelay, maxError, corr, index, userTitle, col1 = col1, col2 = col2)
# plots.syncXcorrOld(x1, y1, interval1, device1, x2, y2, interval2, device2, delay, lags, step, userDelay, maxError, corr, index, userTitle = '', col1 = 'C0', col2 = 'C1')
def fillNanWithInterp(y, x = 0, mode = 'linear'):
'''
Given an array containing nans, fills it with the method specified in mode.
If x is given, the y values returned are the one corresponding to the x specified
If x is not given, y is assumed to be sampled at a fixed frequency
Parameters
----------
y : np.array
original array of values containing nans to be corrected
x : np.array, optional
time array of acquisition of signal y.
The default is 0, which assumes that y is sampled at a fixed frequency
mode : string, optional
kind of interpolation to be performed, passed to scipy.interpolate.interp1d(kind = )
Please refer to documentation
https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html
The default is 'linear'.
Returns
-------
yinterp : np.array
contains the data with nan replaced from interpolated value
'''
# keeping sure that the variables are numpy.arrays
x, _ = utils.toFloatNumpyArray(x)
y, _ = utils.toFloatNumpyArray(y)
# if x is not given, it's assumed that the y array is equally spaced
if np.array_equal(0, x):
x = np.arange(0, len(y), 1)
# find the indexes where y is not nan
notNanIndexes = ~np.isnan(y)
# if the first or the last value of y are nan, copy the closest value
if notNanIndexes[0] == False:
y[0] = y[notNanIndexes][0]
# y[0] = y[notNanIndexes[0]]
if notNanIndexes[-1] == False:
y[-1] = y[notNanIndexes][-1]
# y[-1] = y[notNanIndexes[-1]]
# find again the indexes where y is not nan
# now the first and the last value are not nan, and they're the extremes of
# the interpolation
notNanIndexes = ~np.isnan(y)
# considering only the not nan value
yClean = y[notNanIndexes]
xClean = x[notNanIndexes]
# feeding the interpolator with only the not nan values and obtaining a function
finterp = scipy.interpolate.interp1d(xClean, yClean, mode)
# computing the values of function on the original x
yinterp = finterp(x)
return yinterp
def resampleWithInterp(y, x = 0, xparam = 0.01, param = 'time step', mode = 'linear'):
'''
Given a signal y and his time array x, resamples it using interpolation
the three modes to use this function are:
- specifying the time *step*:
the output is resampled with the given step
- specifying the *frequency*:
the output is resampled with the given frequency
- specifying the *time array*:
the output is resampled on the given time array
If signal y has contains nan, they are filled with the function fillNanWithInterp()
Parameters
----------
y : np.array
original array of values
x : np.array, optional
time array of acquisition of signal y.
The default is 0, which assumes that y is sampled at a fixed frequency
xparam : float, integer or array, optional
if param == 'time step'
specifies the time step
if param == 'frequency'
specifies the frequency
if param == 'time array'
is equal to the time array where the resampling should be done.
The default is 0.01 and goes with 'time step' specified in param
param : string, optional
To specify if the resampling should be done on a signal computed on the
given time step, frequency or on the given time array.
The default is 'time step' and goes with '0.001' specified in xparam
mode : string, optional
kind of interpolation to be performed, passed to scipy.interpolate.interp1d(kind = )
Please refer to documentation
https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html
The default is 'linear'.
Returns
-------
yinterp : np.array
Values of the resampled signal
xinterp : np.array
Time array of the resampled signal
finterp : function
Interpolator function, only works between the extremities of x
'''
# keeping sure that the variables are numpy.arrays
x, _ = utils.toFloatNumpyArray(x)
y, _ = utils.toFloatNumpyArray(y)
xparam, _ = utils.toFloatNumpyArray(xparam)
# if x is not given, it's assumed that the y array is equally spaced
if np.array_equal(0, x):
if mode != 'time array':
x = np.arange(0, len(y), 1)
else:
logging.error('asking to resample on a given time array but not \
specifiying the input time array')
return None
# if y contains at least one nan, fill the space
if np.isnan(y).any():
logging.warning('nan values detected, filling them with ' + mode + ' method')
y = fillNanWithInterp(y, x, mode)
# the three modes to use this function are:
# - specifying the time *step*
# - specifying the *frequency*
# - specifying the *time array*
validParams = ['time step', 'frequency', 'time array']
if param == validParams[0]: # given step
step = xparam
xinterp = np.arange(np.min(x), np.max(x), step)
elif param == validParams[1]: # given freq
freq = xparam
step = 1/freq
xinterp = np.arange(np.min(x), np.max(x), step)
elif param == validParams[2]: # given time array
xinterp = xparam
# # eventually cutting the time array
# xinterp = xinterp[xinterp<=np.max(x)]
# xinterp = xinterp[xinterp>=np.min(x)]
# warning the user if the time array specified exceeds the limits
if (xinterp[0] < np.min(x) or xinterp[-1] > np.max(x)):
logging.warning('Using extrapolation: ' + \
'\nInterpolator has values between {:.2f} and {:.2f}'\
.format(np.min(x), np.max(x)) + \
' and computation between {:.2f} and {:.2f} is asked.'\
.format(xparam[0], xparam[-1]))
else:
logging.error('not valid param. Valid params are: ' + str(validParams))
return None
# feeding the interpolator with the input values and obtaining a function
finterp = scipy.interpolate.interp1d(x, y, kind = mode, fill_value = 'extrapolate')
# computing the values of the function on the xinterp
yinterp = finterp(xinterp)
return yinterp, xinterp, finterp
def syncCameraCapsleeve(led_data,cap_data):
capbump = hcd.capsleeve.find_first_bump(cap_data)
threshold = led_data['Red'].iloc[0:60].mean()
dev = led_data['Red'].iloc[0:60].std()
for i in range(len(led_data['Time(s)'])):
if i>59 and led_data.at[i,"Red"]>threshold+4*dev:
leddelay=led_data.at[i,"Time(s)"]
break
csini= capbump - leddelay
return csini
def plotSyncedCameraCapsleeve(cap_data,led_data,csini):
acceldata=cap_data["Accelerometer Y (g)"].to_numpy()
time=cap_data["Time (s)"].to_numpy()
reddata=led_data['Red'].to_numpy()
timeled=led_data['Time(s)'].to_numpy()
acceldata = acceldata - np.mean(acceldata)
reddata = reddata - np.mean(reddata)
# normalizing from -1 to 1
acceldata = acceldata / np.max(np.abs(acceldata))
reddata = reddata / np.max(np.abs(reddata))
if csini>0:
acceldata=acceldata[time>csini]
time=time[0:-(len(time)-len(acceldata))]
if csini<0:
reddata=reddata[timeled>csini]
plt.figure()
fig=plt.plot(time,acceldata)
plt.plot(timeled,reddata)
return fig
| mmtlab/wheelchair_contact_detection | hcd/xcorrelation.py | xcorrelation.py | py | 17,731 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "logging.warning",
"line_number": 53,
"usage_type": "call"
},
{
"api_name": "hppdWC.utils.toFloatNumpyArray",
"line_number": 156,
"usage_type": "call"
},
{
"api_name": "hppdWC.utils",
"line_number": 156,
"usage_type": "name"
},
{
"api_name": "hppdWC.... |
1488340313 | # Code you have previously used to load data
import pandas as pd
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
# Path of the file to read
file_path = './home-data-for-ml-course/train.csv'
data = pd.read_csv(file_path)
# Create target object and call it y
y = data.SalePrice
# Create X
features = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd']
X = data[features]
# Split into validation and training data
# train_X, val_X, train_y, val_y = train_test_split(X, y, random_state=1)
# Specify Model
model = RandomForestRegressor(random_state = 1)
# Fit Model
model.fit(X, y)
# Make validation predictions and calculate mean absolute error
val_predictions = model.predict(X)
val_mae = mean_absolute_error(val_predictions, y)
print("Validation MAE: {:,.0f}".format(val_mae))
# print(len(val_predictions))
# print(val_y.columns)
# print("******\n", val_X.columns)
# print(type(val_y))
# # Appying Test Datas
test_data_path = "./home-data-for-ml-course/test.csv"
test_data = pd.read_csv(test_data_path)
test_X = test_data[features]
val_test_predictions = model.predict(test_X)
# val_test_mae = mean_absolute_error(val_test_predictions, test_y)
# print("Validation MAE: {:,.0f}".format(val_test_mae))
# # Run the code to save predictions in the format used for competition scoring
output = pd.DataFrame({'Id': test_data.Id, 'SalePrice': val_test_predictions})
output.to_csv('submission.csv', index=False) | tyrl76/Kaggle | House Prices/main.py | main.py | py | 1,604 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pandas.read_csv",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "sklearn.ensemble.RandomForestRegressor",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "sklearn.metrics.mean_absolute_error",
"line_number": 29,
"usage_type": "call"
},... |
37597891395 | # -*- coding: utf-8 -*-
"""
Created on Thu May 23 20:49:32 2019
@author: 18443
"""
import os
import time
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as Data
from torch import optim
from torch.utils.data import DataLoader
import numpy as np
import argparse
#from convattcomb_dataset import MyDataset,PadCollate
from convattcomb_dataset import MyDataset,PadCollate
from dictionary import char_index_dictionary,index_char_dictionary
from Models.model_3single_1combineselfatt import FConvEncoder,CNN_ATT_decoder
use_cuda = torch.cuda.is_available() # pylint: disable=no-member
device = torch.device("cuda" if use_cuda else "cpu") # pylint: disable=no-member
parser = argparse.ArgumentParser()
parser.add_argument('--layer',
type=int, default=5,
help='layer of attention')
parser.add_argument('--PATH1',
default="/lustre/home/zyzhu/experiment2/traindata/CRNN/train108wtestin108w_88accinICDAR13.txt",
help='CRNN output txt')
parser.add_argument('--PATH2',
default="/lustre/home/zyzhu/experiment/traindata/overseg/all_result_100W_no_lm.txt",
help='overseg output txt')
parser.add_argument('--PATH3',
default="/lustre/home/zyzhu/experiment2/traindata/att/seed1006/train108wtestin108w_84accinICDAR13_seed1006.txt",
help='overseg output txt')
parser.add_argument('--testpath1',
default="/lustre/home/zyzhu/experiment2/traindata/CRNN/train108wtestincompetition_88accinICDAR13.txt",
help='CRNN testdataset output txt')
parser.add_argument('--testpath2',
default="/lustre/home/zyzhu/experiment/traindata/overseg/oversegment_testoutput_no_lm.txt",
help='overseg testdataset output txt')
parser.add_argument('--testpath3',
default="/lustre/home/zyzhu/experiment2/traindata/att/seed1006/train108wtestincompetition_84accinICDAR13_seed1006.txt",
help='overseg testdataset output txt')
parser.add_argument('--adam_lr', type=np.float32, default=0.0002,
help='learning rate')
parser.add_argument('--output_dir', default='./model_5layer_CNN64',
help='path to save model')
parser.add_argument('--batch_size', type=int, default=256,
help='size of one training batch')
parser.add_argument('--deviceID', type=list, default=[0,1],
help='deviceID')
parser.add_argument('--weight_decay', type=np.float32, default=0,
help='weight_decay')
parser.add_argument('--weight_clip', type=np.float32, default=0.1,
help='weight_decay')
opt = parser.parse_args()
encoder_a_path=""
encoder_b_path=""
encoder_c_path=""
decoder_path=""
def tensor2list(tensor):
l=[]
for i in tensor.squeeze():
index=int(i)
if (index!=0)and(index!=1)and(index!=2)and(index!=3):
l.append(index)
return l
def tensor2string(tensor,index2word):
string=[]
for i in tensor.squeeze():
index=int(i)
if (index!=0)and(index!=1)and(index!=2)and(index!=3):
string.append(index2word[index])
return ''.join(string)
def editDistance(r, h):
d = np.zeros((len(r)+1)*(len(h)+1), dtype=np.uint8).reshape((len(r)+1, len(h)+1))
for i in range(len(r)+1):
for j in range(len(h)+1):
if i == 0:
d[0][j] = j
elif j == 0:
d[i][0] = i
for i in range(1, len(r)+1):
for j in range(1, len(h)+1):
if r[i-1] == h[j-1]:
d[i][j] = d[i-1][j-1]
else:
substitute = d[i-1][j-1] + 1
insert = d[i][j-1] + 1
delete = d[i-1][j] + 1
d[i][j] = min(substitute, insert, delete)
return d
def evaluate(encoder_a,encoder_b,encoder_c, decoder, eval_data, index2word,savepath,batch_size,epoch,printiter):
data = DataLoader(dataset=eval_data, batch_size=batch_size, collate_fn=PadCollate(dim=0))
counter_correct=0
counter_number=0
for j, (batch_x, batch_y,batch_z, label) in enumerate(data):
batch_x=batch_x.to(device).long()
batch_y=batch_y.to(device).long()
batch_z=batch_z.to(device).long()
label=label.to(device).long()
current_time=time.time()
batch_size=batch_x.size()[0]
pre_buffer=torch.zeros(batch_size,50).fill_(char_index_dictionary['<pad>'])
pre_buffer[:,0]=char_index_dictionary['<s>']
# preoutput_list=[char_index_dictionary['<s>']]
encoder_a_output=encoder_a(batch_x)
encoder_b_output=encoder_b(batch_y)
encoder_c_output=encoder_c(batch_z)
for i in range(1,50):
# preoutput=torch.LongTensor(preoutput_list).unsqueeze(0).to(device)#list to tensor 1*length
preoutput=pre_buffer[:,:i].long()
output,_ =decoder(preoutput,encoder_out1=encoder_a_output,encoder_out2=encoder_b_output,encoder_out3=encoder_c_output)#B*T*7356
# output,_ =decoder(preoutput,combined_output)
_,prediction=torch.topk(output, 1)#B*T*1
# print(prediction.size())
prediction=prediction.squeeze(2)#B*T
# preoutput_list.append(int(prediction.squeeze(0)[-1]))
if all(prediction[:,-1]==char_index_dictionary['</s>']):
break
pre_buffer[:,i]=prediction[:,-1]
for one_predict_index in range(batch_size):
l_target=tensor2list(label[one_predict_index])
l_predict=tensor2list(pre_buffer[one_predict_index])
d=editDistance(l_target, l_predict)
counter_correct=counter_correct+d[len(l_target)][len(l_predict)]
counter_number=counter_number+len(l_target)
if j %printiter==0:
print(i)
print(j)
print('time used:%s'%(time.time()- current_time))
print(tensor2string(batch_x[one_predict_index],index_char_dictionary))
print(tensor2string(batch_y[one_predict_index],index_char_dictionary))
print(tensor2string(batch_z[one_predict_index],index_char_dictionary))
print(tensor2string(label[one_predict_index],index_char_dictionary))
print(tensor2string(prediction[one_predict_index],index_char_dictionary))
# print(l_target)
# print(l_predict)
result = float(d[len(l_target)][len(l_predict)]) / len(l_target) * 100
result = str("%.2f" % result) + "%"
print('WER:%s'%(result))
total_result=float(counter_correct) / counter_number * 100
total_result=str("%.2f" % total_result) + "%"
print(counter_correct)
print(counter_number)
print(' test WER of current time:%s'%(total_result))
print(counter_correct)
print(counter_number)
total_result=float(counter_correct) / counter_number * 100
total_result=str("%.2f" % total_result) + "%"
print('test WER:%s'%(total_result))
torch.save(encoder_a.state_dict(), savepath+'/encoder_a'+str(epoch)+'_acc'+str(total_result)+'.pth')
torch.save(encoder_b.state_dict(), savepath+'/encoder_b'+str(epoch)+'_acc'+str(total_result)+'.pth')
torch.save(encoder_c.state_dict(), savepath+'/encoder_c'+str(epoch)+'_acc'+str(total_result)+'.pth')
torch.save(decoder.state_dict(), savepath+'/decoder'+str(epoch)+'_acc'+str(total_result)+'.pth')
# return eval_loss.item()
def train(encoder_a,
encoder_b,
encoder_c,
decoder,
input_a,
input_b,
input_c,
preout_tensor,
target_tensor,
encoder_a_optimizer,
encoder_b_optimizer,
encoder_c_optimizer,
decoder_optimizer,
criterion,
weightclip
):
encoder_a_optimizer.zero_grad()
encoder_b_optimizer.zero_grad()
encoder_c_optimizer.zero_grad()
decoder_optimizer.zero_grad()
encoder_a_output=encoder_a(input_a)
encoder_b_output=encoder_b(input_b)
encoder_c_output=encoder_c(input_c)
output,_ =decoder(preout_tensor,encoder_out1=encoder_a_output,encoder_out2=encoder_b_output,encoder_out3=encoder_c_output)
output=output.transpose(1, 2).contiguous()
# print(output.size())
# print(target_tensor.size())
loss = criterion(output, target_tensor)
loss.backward()
torch.nn.utils.clip_grad_norm_(encoder_a.parameters(), weightclip)
torch.nn.utils.clip_grad_norm_(encoder_b.parameters(), weightclip)
torch.nn.utils.clip_grad_norm_(encoder_c.parameters(), weightclip)
torch.nn.utils.clip_grad_norm_(decoder.parameters(), weightclip)
encoder_a_optimizer.step()
encoder_b_optimizer.step()
encoder_c_optimizer.step()
decoder_optimizer.step()
return loss.item()
#PATH1="/lustre/home/zyzhu/CRNN64/sementic_85acc.txt"
#PATH2="/lustre/home/zyzhu/conv_att_combine/train_data/all_result_100W_no_lm.txt"
#
#testpath1="/lustre/home/zyzhu/CRNN64/competition_testoutput_85acc.txt"
#testpath2="/lustre/home/zyzhu/conv_att_combine/train_data/text_index_result_no_lm.txt"
##
def trainIters(encoder_a,encoder_b,encoder_c, decoder, n_iters, opt):
if not os.path.exists(opt.output_dir):
os.mkdir(opt.output_dir)
print('making folder')
encoder_a.num_attention_layers = sum(layer is not None for layer in decoder.attention1)+sum(layer is not None for layer in decoder.combine_attention)
encoder_b.num_attention_layers = sum(layer is not None for layer in decoder.attention2)+sum(layer is not None for layer in decoder.combine_attention)
encoder_c.num_attention_layers = sum(layer is not None for layer in decoder.attention3)+sum(layer is not None for layer in decoder.combine_attention)
encoder_a=torch.nn.DataParallel(encoder_a, device_ids=opt.deviceID).cuda()
encoder_b=torch.nn.DataParallel(encoder_b, device_ids=opt.deviceID).cuda()
encoder_c=torch.nn.DataParallel(encoder_c, device_ids=opt.deviceID).cuda()
decoder=torch.nn.DataParallel(decoder, device_ids=opt.deviceID).cuda()
#
encoder_a.load_state_dict(torch.load(encoder_a_path))
encoder_b.load_state_dict(torch.load(encoder_b_path))
encoder_c.load_state_dict(torch.load(encoder_c_path))
decoder.load_state_dict(torch.load(decoder_path))
encoder1_optimizer = optim.Adam(encoder_a.parameters(), lr=opt.adam_lr,betas=(0.5, 0.99),weight_decay=opt.weight_decay)
encoder2_optimizer = optim.Adam(encoder_b.parameters(), lr=opt.adam_lr,betas=(0.5, 0.99),weight_decay=opt.weight_decay)
encoder3_optimizer = optim.Adam(encoder_c.parameters(), lr=opt.adam_lr,betas=(0.5, 0.99),weight_decay=opt.weight_decay)
decoder_optimizer = optim.Adam(decoder.parameters(), lr=opt.adam_lr,betas=(0.5, 0.99),weight_decay=opt.weight_decay)
criterion = nn.CrossEntropyLoss().to(device)
dataset=MyDataset(opt.PATH1,opt.PATH3,opt.PATH2)
test_dataset=MyDataset(opt.testpath1,opt.testpath3,opt.testpath2)
print(len(test_dataset))
train_loader = DataLoader(dataset,shuffle=True,batch_size =opt.batch_size, collate_fn=PadCollate(dim=0))
# encoder_a.eval()
# encoder_b.eval()
# encoder_c.eval()
# decoder.eval()
# with torch.no_grad():
# evaluate(encoder_a,encoder_b,encoder_c, decoder, test_dataset, index_char_dictionary,savepath=opt.output_dir,batch_size=16,epoch=0,printiter=5)
#
# encoder_a.train()
# encoder_b.train()
# encoder_c.train()
# decoder.train()
#
print("start!")
for epoch in range( n_iters ):
#evaluate(encoder=encoder, decoder=decoder, train_data=train_data, max_length=50,index2word=index2word)
for i, (batch_x, batch_y, batch_z, label) in enumerate(train_loader):
batch_x=batch_x.cuda().long()
batch_y=batch_y.cuda().long()
batch_z=batch_z.cuda().long()
label=label.cuda().long()
# print(batch_x)
# print(batch_y.size())
target=label[:,1:]
preoutput=label[:,:-1]
# print(target)
# print(preoutput)
loss = train(encoder_a=encoder_a,encoder_b=encoder_b,encoder_c=encoder_c,
decoder=decoder,
input_a=batch_x,input_b=batch_y, input_c=batch_z,
preout_tensor=preoutput,target_tensor=target,
encoder_a_optimizer=encoder1_optimizer,encoder_b_optimizer=encoder2_optimizer,encoder_c_optimizer=encoder3_optimizer,
decoder_optimizer=decoder_optimizer,
criterion=criterion,weightclip=opt.weight_clip)
if i%20==0:
print('epoch:%d,iter:%d,train_loss:%f'% (epoch,i,loss))
# if (i%2000==0)and(i!=0):
encoder_a.eval()
encoder_b.eval()
encoder_c.eval()
decoder.eval()
with torch.no_grad():
evaluate(encoder_a,encoder_b,encoder_c, decoder, test_dataset, index_char_dictionary,savepath=opt.output_dir,batch_size=64,epoch=epoch,printiter=10)
encoder_a.train()
encoder_b.train()
encoder_c.train()
decoder.train()
encoder_a = FConvEncoder(dictionary=char_index_dictionary,attention_layer=opt.layer)
encoder_b = FConvEncoder(dictionary=char_index_dictionary,attention_layer=opt.layer)
encoder_c = FConvEncoder(dictionary=char_index_dictionary,attention_layer=opt.layer)
decoder = CNN_ATT_decoder(dictionary=char_index_dictionary,attention_layer=opt.layer)
trainIters(encoder_a,encoder_b,encoder_c, decoder, 100,opt)
| yudmoe/neural-combination-of-HCTR | threeinput_training.py | threeinput_training.py | py | 14,833 | python | en | code | 4 | github-code | 36 | [
{
"api_name": "torch.cuda.is_available",
"line_number": 25,
"usage_type": "call"
},
{
"api_name": "torch.cuda",
"line_number": 25,
"usage_type": "attribute"
},
{
"api_name": "torch.device",
"line_number": 26,
"usage_type": "call"
},
{
"api_name": "argparse.Argumen... |
74577237222 | import subprocess
from pathlib import Path
from typing import List
RESOURCE_PATH = Path("tests/resources")
def call_main(args: List[str]) -> List[str]:
root_path = Path("./")
filename = root_path / "rmsd/calculate_rmsd.py"
cmd = ["python", f"{filename}", *args]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout, stderr = proc.communicate()
if stderr is not None:
print(stderr.decode())
return stdout.decode().strip().split("\n")
| charnley/rmsd | tests/context.py | context.py | py | 510 | python | en | code | 431 | github-code | 36 | [
{
"api_name": "pathlib.Path",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "typing.List",
"line_number": 8,
"usage_type": "name"
},
{
"api_name": "pathlib.Path",
"line_number": 10,
"usage_type": "call"
},
{
"api_name": "subprocess.Popen",
"line_numb... |
2894349509 | from typing import Dict
from src.property.PropertyFactory import PropertyFactory
from src.storage.common.entity.Entity import Entity
from src.template.entity.EntityTemplate import EntityTemplate
class EntityFactory:
def __init__(self, entity_template: EntityTemplate):
self.entity_template = entity_template
def create(self, key: str, props_values: Dict[str, str]) -> Entity:
return Entity(
key,
PropertyFactory.create_from_template_and_dict(
self.entity_template.properties_templates,
props_values,
lambda prop_template_id: 'Property ' + prop_template_id + ' not found for entity ' + key
)
)
| andreyzaytsev21/MasterDAPv2 | src/storage/common/entity/EntityFactory.py | EntityFactory.py | py | 714 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "src.template.entity.EntityTemplate.EntityTemplate",
"line_number": 10,
"usage_type": "name"
},
{
"api_name": "typing.Dict",
"line_number": 13,
"usage_type": "name"
},
{
"api_name": "src.storage.common.entity.Entity.Entity",
"line_number": 14,
"usage_type": ... |
17076521686 | from fastapi import FastAPI, HTTPException, status
import uvicorn
import requests
app = FastAPI(debug=True)
BTCUSD=[]
@app.get('/')
def index():
return {'msg': 'VSETKO JE OK'}
@app.get('/usd2btc')
def USD_current_price():
re = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
if re.status_code == 200:
data = re.json()
USDATA = data['bpi']['USD']
BTCUSD.append({'key':USDATA['rate']})
print({'key':USDATA['rate']})
return {'key':USDATA['rate']}
else:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='DATA NOT FOUND')
@app.get('/gbp2btc')
def GBP_current_price():
re = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
if re.status_code == 200:
data = re.json()
GBDATA = data['bpi']['GBP']
# BTCUSD.append({'key':USDATA['rate']})
print({'key':GBDATA['rate']})
return {'key':GBDATA['rate']}
else:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='DATA NOT FOUND')
@app.get('/eur2btc')
def EUR_current_price():
re = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
if re.status_code == 200:
data = re.json()
EUDATA = data['bpi']['EUR']
# BTCUSD.append({'key':EUDATA['rate']})
print({'key':EUDATA['rate']})
return {'key':EUDATA['rate']}
else:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='DATA NOT FOUND') | fortisauris/PyDevJR_Course | FA02_FASTAPI_BTC/main.py | main.py | py | 1,498 | python | en | code | 2 | github-code | 36 | [
{
"api_name": "fastapi.FastAPI",
"line_number": 5,
"usage_type": "call"
},
{
"api_name": "requests.get",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "fastapi.HTTPException",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "fastapi.status.HTTP... |
27283966186 | import copy
import math
from pypaq.lipytools.printout import stamp, progress_
from pypaq.lipytools.pylogger import get_pylogger, get_child
from pypaq.mpython.mptools import Que, QMessage
from torchness.tbwr import TBwr
import random
import statistics
import time
from tqdm import tqdm
from typing import Dict, List, Tuple, Optional, Union
from envy import MODELS_FD, DMK_MODELS_FD, N_TABLE_PLAYERS, PyPoksException
from pologic.potable import QPTable
from podecide.dmk import FolDMK, HuDMK
from gui.gui_hdmk import GUI_HDMK
def stdev_with_none(values) -> Optional[float]:
if len(values) < 2:
return None
return statistics.stdev(values)
# separated factor for two results
def separated_factor(
a_wonH: Optional[float],
a_wonH_mean_stdev: Optional[float],
b_wonH: Optional[float],
b_wonH_mean_stdev: Optional[float],
n_stdev: float) -> float:
if a_wonH_mean_stdev is None or b_wonH_mean_stdev is None:
return 0.0
if a_wonH_mean_stdev + b_wonH_mean_stdev == 0:
return 1000
return abs(a_wonH - b_wonH) / (n_stdev * (a_wonH_mean_stdev + b_wonH_mean_stdev))
# prepares separation report
def separation_report(
dmk_results: Dict,
n_stdev: float,
sep_pairs: Optional[List[Tuple[str,str]]]= None,
max_nf: float= 1.1,
) -> Dict:
sep_nc = 0.0
sep_nf = 0.0
sep_pairs_nc = 0.0
sep_pairs_nf = 0.0
sep_pairs_stat = []
n_dmk = len(dmk_results)
# prepare separation data
dmk_sep = {}
for dn in dmk_results:
wonH_IV_stdev = stdev_with_none(dmk_results[dn]['wonH_IV'])
dmk_sep[dn] = {
'wonH_IV_stdev': wonH_IV_stdev,
'wonH_IV_mean_stdev': wonH_IV_stdev / math.sqrt(len(dmk_results[dn]['wonH_IV'])) if wonH_IV_stdev is not None else None,
'last_wonH_afterIV': dmk_results[dn]['wonH_afterIV'][-1] if dmk_results[dn]['wonH_afterIV'] else None}
# compute separated normalized count & normalized factor
for dn_a in dmk_sep:
dmk_sep[dn_a]['separated'] = n_dmk - 1
for dn_b in dmk_sep:
if dn_a != dn_b:
sf = separated_factor(
a_wonH= dmk_sep[dn_a]['last_wonH_afterIV'],
a_wonH_mean_stdev= dmk_sep[dn_a]['wonH_IV_mean_stdev'],
b_wonH= dmk_sep[dn_b]['last_wonH_afterIV'],
b_wonH_mean_stdev= dmk_sep[dn_b]['wonH_IV_mean_stdev'],
n_stdev= n_stdev)
if sf < 1:
dmk_sep[dn_a]['separated'] -= 1
sep_nf += min(sf, max_nf)
sep_nc += dmk_sep[dn_a]['separated']
n_max = (n_dmk - 1) * n_dmk
sep_nc /= n_max
sep_nf /= n_max
# same for given pairs
if sep_pairs:
for sp in sep_pairs:
sf = separated_factor(
a_wonH= dmk_sep[sp[0]]['last_wonH_afterIV'],
a_wonH_mean_stdev= dmk_sep[sp[0]]['wonH_IV_mean_stdev'],
b_wonH= dmk_sep[sp[1]]['last_wonH_afterIV'],
b_wonH_mean_stdev= dmk_sep[sp[1]]['wonH_IV_mean_stdev'],
n_stdev= n_stdev)
sep_pairs_stat.append(0 if sf<1 else 1)
if sf>=1: sep_pairs_nc += 1
sep_pairs_nf += min(sf, max_nf)
sep_pairs_nc /= len(sep_pairs)
sep_pairs_nf /= len(sep_pairs)
return {
'sep_nc': sep_nc, # <0.0;1.0> normalized count of separated
'sep_nf': sep_nf, # <0.0;1.1> normalized factor of separation
'sep_pairs_nc': sep_pairs_nc, # <0.0;1.0> normalized count of separated pairs
'sep_pairs_nf': sep_pairs_nf, # <0.0;1.1> normalized factor of pairs separation
'sep_pairs_stat': sep_pairs_stat} # [0,1, ..] each par marked as separated or not
# manages games of DMKs (at least QueDMKs)
class GamesManager:
def __init__(
self,
dmk_pointL: List[Dict], # points with eventually added 'dmk_type'
name: Optional[str]= None,
logger= None,
loglevel= 20,
debug_dmks= False,
debug_tables= False):
self.name = name or f'GM_{stamp()}'
if not logger:
logger = get_pylogger(
name= self.name,
folder= MODELS_FD,
level= loglevel)
self.logger = logger
self.debug_tables = debug_tables
self.logger.info(f'*** GamesManager : {self.name} *** starts..')
self.que_to_gm = Que() # here GM receives data from DMKs and Tables
dmk_pointL = copy.deepcopy(dmk_pointL) # copy to not modify original list
dmk_types = [point.pop('dmk_type',FolDMK) for point in dmk_pointL]
dmk_logger = get_child(self.logger, name='dmks_logger', change_level=-10 if debug_dmks else 10)
dmks = [dmk_type(logger=dmk_logger, **point) for dmk_type,point in zip(dmk_types, dmk_pointL)]
self.dmkD = {dmk.name: dmk for dmk in dmks} # Dict[str, dmk_type] INFO:is not typed because DMK may have diff types
for dmk in self.dmkD.values(): dmk.que_to_gm = self.que_to_gm # DMKs are build from folders, they need que to be updated then
self.families = set([dmk.family for dmk in self.dmkD.values()])
self.tbwr = TBwr(logdir=f'{DMK_MODELS_FD}/{self.name}')
self.tables = None
# starts DMKs (starts loops)
def _start_dmks(self):
self.logger.debug('> starts DMKs..')
idmk = tqdm(self.dmkD.values()) if self.logger.level<20 else self.dmkD.values()
for dmk in idmk: dmk.start()
self.logger.debug('> initializing..')
idmk = tqdm(self.dmkD) if self.logger.level < 20 else self.dmkD
for _ in idmk:
message = self.que_to_gm.get()
self.logger.debug(f'>> {message}')
self.logger.debug(f'> initialized {len(self.dmkD)} DMKs!')
message = QMessage(type='start_dmk_loop', data=None)
for dmk in self.dmkD.values(): dmk.que_from_gm.put(message) # synchronizes DMKs a bit..
for _ in self.dmkD:
message = self.que_to_gm.get()
self.logger.debug(f'>> {message}')
self.logger.debug(f'> started {len(self.dmkD)} DMKs!')
def _save_dmks(self):
self.logger.debug('> saves DMKs')
n_saved = 0
message = QMessage(type='save_dmk', data=None)
for dmk in self.dmkD.values():
dmk.que_from_gm.put(message)
n_saved += 1
for _ in range(n_saved):
self.que_to_gm.get()
self.logger.debug('> all DMKs saved!')
# stops DMKs loops
def _stop_dmks_loops(self):
self.logger.debug('Stopping DMKs loops..')
message = QMessage(type='stop_dmk_loop', data=None)
for dmk in self.dmkD.values(): dmk.que_from_gm.put(message)
idmk = tqdm(self.dmkD) if self.logger.level < 20 else self.dmkD
for _ in idmk:
self.que_to_gm.get()
self.logger.debug('> all DMKs loops stopped!')
# stops DMKs processes
def _stop_dmks_processes(self):
self.logger.debug('Stopping DMKs processes..')
message = QMessage(type='stop_dmk_process', data=None)
for dmk in self.dmkD.values(): dmk.que_from_gm.put(message)
idmk = tqdm(self.dmkD) if self.logger.level < 20 else self.dmkD
for _ in idmk:
self.que_to_gm.get()
self.logger.debug('> all DMKs exited!')
# creates new tables & puts players with random policy
def _put_players_on_tables(self):
self.logger.info('> puts players on tables..')
# build dict of lists of players (per family): {family: [(pid, que_to_pl, que_from_pl)]}
fam_ques: Dict[str, List[Tuple[str,Que,Que]]] = {fam: [] for fam in self.families}
for dmk in self.dmkD.values():
for k in dmk.queD_to_player: # {pid: que_to_pl}
fam_ques[dmk.family].append((k, dmk.queD_to_player[k], dmk.que_from_player))
# shuffle players in families
for fam in fam_ques:
random.shuffle(fam_ques[fam])
random.shuffle(fam_ques[fam])
quesLL = [fam_ques[fam] for fam in fam_ques] # convert to list of lists
### convert to flat list
# cut in equal pieces
min_len = min([len(l) for l in quesLL])
cut_quesLL = []
for l in quesLL:
while len(l) > 1.66*min_len:
cut_quesLL.append(l[:min_len])
l = l[min_len:]
cut_quesLL.append(l)
quesLL = cut_quesLL
random.shuffle(quesLL)
random.shuffle(quesLL)
quesL = [] # flat list
qLL_IXL = []
while quesLL:
if not qLL_IXL:
qLL_IXL = list(range(len(quesLL))) # fill indexes
random.shuffle(qLL_IXL) # shuffle them
qLL_IX = qLL_IXL.pop() # now take last index
quesL.append(quesLL[qLL_IX].pop()) # add last from list
if not quesLL[qLL_IX]:
quesLL.pop(qLL_IX) # remove empty list
qLL_IXL = list(range(len(quesLL))) # new indexes then
random.shuffle(qLL_IXL) # shuffle them
num_players = len(quesL)
if num_players % N_TABLE_PLAYERS != 0:
raise PyPoksException(f'num_players ({num_players}) has to be a multiple of N_TABLE_PLAYERS ({N_TABLE_PLAYERS})')
# put on tables
self.tables = []
table_ques = []
table_logger = get_child(self.logger, name='table_logger', change_level=-10) if self.debug_tables else None
while quesL:
table_ques.append(quesL.pop())
if len(table_ques) == N_TABLE_PLAYERS:
self.tables.append(QPTable(
name= f'tbl{len(self.tables)}',
que_to_gm= self.que_to_gm,
pl_ques= {t[0]: (t[1], t[2]) for t in table_ques},
logger= table_logger))
table_ques = []
# starts all tables
def _start_tables(self):
self.logger.debug('> starts tables..')
itbl = tqdm(self.tables) if self.logger.level < 20 else self.tables
for tbl in itbl: tbl.start()
for _ in itbl:
self.que_to_gm.get()
self.logger.debug(f'> tables ({len(self.tables)}) processes started!')
# stops tables
def _stop_tables(self):
self.logger.debug('> stops tables loops..')
message = QMessage(type='stop_table', data=None)
for table in self.tables: table.que_from_gm.put(message)
itbl = tqdm(self.tables) if self.logger.level < 20 else self.tables
for _ in itbl:
self.que_to_gm.get()
# INFO: tables now are just Process objects with target loop stopped
self.logger.debug('> tables loops stopped!')
# runs game, returns DMK results dictionary
def run_game(
self,
game_size= 10000, # number of hands for a game (per DMK)
sleep= 10, # loop sleep (seconds)
progress_report= True,
publish_GM= False,
sep_all_break: bool= False, # breaks game when all DMKs are separated
sep_pairs: Optional[List[Tuple[str,str]]]= None, # pairs of DMK names for separation condition
sep_pairs_factor: float= 0.9, # factor of separated pairs needed to break the game
sep_n_stdev: float= 2.0,
) -> Dict[str, Dict]:
"""
By now, by design run_game() may be called only once,
cause DMK processes are started and then stopped and process cannot be started twice,
there is no real need to change this design.
"""
# save of DMK results + additional DMK info
dmk_results = {
dn: {
'wonH_IV': [], # wonH (won $ / hand) of interval
'wonH_afterIV': [], # wonH (won $ / hand) after interval
'family': self.dmkD[dn].family,
'trainable': self.dmkD[dn].trainable,
'global_stats': None, # SM.global_stats, will be updated by DMK at the end of the game
} for dn in self._get_dmk_focus_names()}
# starts all subprocesses
self._put_players_on_tables()
self._start_tables()
self._start_dmks()
stime = time.time()
time_last_report = stime
n_hands_last_report = 0
self.logger.info(f'{self.name} starts a game..')
loop_ix = 0
while True:
time.sleep(sleep)
reports = self._get_reports({dn: len(dmk_results[dn]['wonH_IV']) for dn in dmk_results}) # actual DMK reports
for dn in reports:
dmk_results[dn]['wonH_IV'] += reports[dn]['wonH_IV']
dmk_results[dn]['wonH_afterIV'] += reports[dn]['wonH_afterIV']
# calculate game factor
n_hands = sum([reports[dn]['n_hands'] for dn in reports])
game_factor = n_hands / len(reports) / game_size
if game_factor >= 1: game_factor = 1
sr = separation_report(
dmk_results= dmk_results,
n_stdev= sep_n_stdev,
sep_pairs= sep_pairs)
sep_nc = sr['sep_nc']
sep_nf = sr['sep_nf']
sep_pairs_nc = sr['sep_pairs_nc']
sep_pairs_nf = sr['sep_pairs_nf']
if publish_GM:
self.tbwr.add(value=sep_nc, tag=f'GM/sep_nc', step=loop_ix)
self.tbwr.add(value=sep_nf, tag=f'GM/sep_nf', step=loop_ix)
if sep_pairs:
self.tbwr.add(value=sep_pairs_nc, tag=f'GM/sep_pairs_nc', step=loop_ix)
self.tbwr.add(value=sep_pairs_nf, tag=f'GM/sep_pairs_nf', step=loop_ix)
# INFO: progress relies on reports, and reports may be prepared in custom way (overridden) by diff GMs
if progress_report:
# progress
passed = (time.time()-stime)/60
left_nfo = ' - '
if game_factor > 0:
full_time = passed / game_factor
left = (1-game_factor) * full_time
left_nfo = f'{left:.1f}'
# speed
hdiff = n_hands-n_hands_last_report
hd_pp = int(hdiff / len(reports))
spd_report = f'{int(hdiff / (time.time()-time_last_report))}H/s (+{hd_pp}Hpp)'
n_hands_last_report = n_hands
time_last_report = time.time()
sep_report_pairs = f'::{sep_pairs_nc:.2f}[{sep_pairs_nf:.2f}]' if sep_pairs else ''
progress_(
current= game_factor,
total= 1.0,
prefix= f'GM: {passed:.1f}min left:{left_nfo}min',
suffix= f'{spd_report} -- SEP:{sep_nc:.2f}[{sep_nf:.2f}]{sep_report_pairs}',
length= 20)
# games break - factor condition
if game_factor == 1:
self.logger.info('> finished game (game factor condition)')
break
# games break - all DMKs separation condition
if sep_all_break and sep_nc == 1.0:
self.logger.info(f'> finished game (all DMKs separation condition), game factor: {game_factor:.2f})')
break
# games break - pairs separation breaking value condition
if sep_pairs and sep_pairs_nc >= sep_pairs_factor:
self.logger.info(f'> finished game (pairs separation factor: {sep_pairs_factor:.2f}, game factor: {game_factor:.2f})')
break
loop_ix += 1
self.tbwr.flush()
self._stop_tables()
self._stop_dmks_loops()
message = QMessage(type='send_global_stats', data=None)
for dn in dmk_results:
self.dmkD[dn].que_from_gm.put(message)
for _ in dmk_results:
message = self.que_to_gm.get()
data = message.data
dmk_name = data.pop('dmk_name')
dmk_results[dmk_name]['global_stats'] = data['global_stats']
self._save_dmks()
self._stop_dmks_processes()
taken_sec = time.time() - stime
taken_nfo = f'{taken_sec / 60:.1f}min' if taken_sec > 100 else f'{taken_sec:.1f}sec'
speed = n_hands / taken_sec
self.logger.info(f'{self.name} finished run_game, avg speed: {speed:.1f}H/s, time taken: {taken_nfo}')
loop_stats = {'speed': speed}
return {
'dmk_results': dmk_results,
'loop_stats': loop_stats}
# prepares list of DMK names GM is focused on while preparing dmk_results
def _get_dmk_focus_names(self) -> List[str]:
return list(self.dmkD.keys())
# asks DMKs to send reports, but only form given IV
def _get_reports(
self,
dmk_report_IV:Dict[str,int] # {dn: from_IV}
) -> Dict[str, Dict]:
reports: Dict[str, Dict] = {} # {dn: {n_hands, wonH_IV, wonH_afterIV}}
for dn,from_IV in dmk_report_IV.items():
message = QMessage(type='send_dmk_report', data=from_IV)
self.dmkD[dn].que_from_gm.put(message)
for _ in dmk_report_IV:
message = self.que_to_gm.get()
report = message.data
dmk_name = report.pop('dmk_name')
reports[dmk_name] = report
return reports
# GamesManager for Play & TRain concept for FolDMKs (some DMKs may play, some DMKs may train)
class GamesManager_PTR(GamesManager):
def __init__(
self,
dmk_point_PLL: Optional[List[Dict]]= None, # playable DMK list
dmk_point_TRL: Optional[List[Dict]]= None, # trainable DMK list
dmk_n_players: int= 60,
name: Optional[str]= None,
**kwargs):
"""
there are 3 possible scenarios:
1.playable & trainable:
dmk_point_PLLa & dmk_point_PLLb are merged together into dmk_point_PLL
dmk_n_players - sets number of players of one trainable DMK (dmk_point_TRL)
number of players of each playable DMK is equal: dmk_n_players * (N_TABLE_PLAYERS - 1)
(each trainable has one table full of playable)
2.only trainable:
dmk_n_players - sets number of players of one trainable DMK
number of tables = len(dmk)*dmk_n_players / N_TABLE_PLAYERS
3.only playable
if there are dmk_point_PLLa AND dmk_point_PLLb...
otherwise dmk_point_PLLa & dmk_point_PLLb are merged together into dmk_point_PLL
...
dmk_n_players - sets number of players of one playable DMK
number of tables = len(dmk)*dmk_n_players / N_TABLE_PLAYERS
TODO: edit this doc
"""
if not dmk_point_PLL: dmk_point_PLL = []
if not dmk_point_TRL: dmk_point_TRL = []
if not (dmk_point_PLL or dmk_point_TRL):
raise PyPoksException('playing OR training DMKs must be given')
n_tables = len(dmk_point_TRL) * dmk_n_players # default when there are both playable & trainable
if not dmk_point_PLL or not dmk_point_TRL:
dmk_dnaL = dmk_point_PLL or dmk_point_TRL
if (len(dmk_dnaL) * dmk_n_players) % N_TABLE_PLAYERS != 0:
raise PyPoksException('Please correct number of DMK players: n DMKs * n players must be multiplication of N_TABLE_PLAYERS')
n_tables = int((len(dmk_dnaL) * dmk_n_players) / N_TABLE_PLAYERS)
# override to train (each DMK by default is saved as a trainable - we set also trainable to have this info here for later usage, it needs n_players to be set)
for dmk in dmk_point_TRL:
dmk.update({
'n_players': dmk_n_players,
'trainable': True})
if dmk_point_PLL:
# both
if dmk_point_TRL:
n_rest_players = n_tables * (N_TABLE_PLAYERS-1)
rest_names = [dna['name'] for dna in dmk_point_PLL]
rest_names = random.choices(rest_names, k=n_rest_players)
for point in dmk_point_PLL:
point.update({
'n_players': len([nm for nm in rest_names if nm == point['name']]),
'trainable': False})
# only playable
else:
play_dna = {
'n_players': dmk_n_players,
'trainable': False}
for dmk in dmk_point_PLL:
dmk.update(play_dna)
self.dmk_name_PLL = [dna['name'] for dna in dmk_point_PLL]
self.dmk_name_TRL = [dna['name'] for dna in dmk_point_TRL]
nm = 'PL' if self.dmk_name_PLL else 'TR'
if self.dmk_name_PLL and self.dmk_name_TRL:
nm = 'TR+PL'
GamesManager.__init__(
self,
dmk_pointL= dmk_point_PLL + dmk_point_TRL,
name= name or f'GM_{nm}_{stamp()}',
**kwargs)
self.logger.info(f'*** GamesManager_PTR started with (PL:{len(dmk_point_PLL)} TR:{len(dmk_point_TRL)}) DMKs on {n_tables} tables')
for dna in dmk_point_PLL + dmk_point_TRL:
self.logger.debug(f'> {dna["name"]} with {dna["n_players"]} players, trainable: {dna["trainable"]}')
# creates new tables & puts players with PTR policy
def _put_players_on_tables(self):
# use previous policy
if not (self.dmk_name_PLL and self.dmk_name_TRL):
return GamesManager._put_players_on_tables(self)
self.logger.info('> puts players on tables with PTR policy..')
ques_PL = []
ques_TR = []
for dmk in self.dmkD.values():
ques = ques_TR if dmk.trainable else ques_PL
for k in dmk.queD_to_player: # {pid: que_to_pl}
ques.append((k, dmk.queD_to_player[k], dmk.que_from_player))
# shuffle players
random.shuffle(ques_PL)
random.shuffle(ques_TR)
# put on tables
self.tables = []
table_ques = []
table_logger = get_child(self.logger, name='table_logger', change_level=-10) if self.debug_tables else None
while ques_TR:
table_ques.append(ques_TR.pop())
while len(table_ques) < N_TABLE_PLAYERS: table_ques.append(ques_PL.pop())
random.shuffle(table_ques)
self.tables.append(QPTable(
name= f'tbl{len(self.tables)}',
que_to_gm= self.que_to_gm,
pl_ques= {t[0]: (t[1], t[2]) for t in table_ques},
logger= table_logger))
table_ques = []
assert not ques_PL and not ques_TR
# adds age update to dmk_results
def run_game(self, **kwargs) -> Dict:
# update trainable age - needs to be done before game, cause after game DMKs are saved
for dmk in self.dmkD.values():
if dmk.trainable: dmk.age += 1
rgd = GamesManager.run_game(self, **kwargs)
for dn in rgd['dmk_results']:
rgd['dmk_results'][dn]['age'] = self.dmkD[dn].age
return rgd
# at GamesManager_PTR we are focused on TRL (or PLL if not)
def _get_dmk_focus_names(self) -> List[str]:
return self.dmk_name_TRL or self.dmk_name_PLL
# manages DMKs for human games
class HuGamesManager(GamesManager):
def __init__(
self,
dmk_names: Union[List[str],str],
logger= None,
loglevel= 20):
if not logger:
logger = get_pylogger(level=loglevel)
if N_TABLE_PLAYERS != 3:
raise PyPoksException('HuGamesManage supports now only 3-handed tables')
logger.info(f'HuGamesManager starts with given dmk_names: {dmk_names}')
h_name = 'hm0'
hdna = {
'name': h_name,
'family': 'h',
'trainable': False,
'n_players': 1,
#'publish': False,
'fwd_stats_step': 10}
if type(dmk_names) is str: dmk_names = [dmk_names]
self.tk_gui = GUI_HDMK(players=[h_name]+dmk_names, imgs_FD='gui/imgs')
hdmk = HuDMK(tk_gui=self.tk_gui, **hdna)
if len(dmk_names) not in [1,2]:
raise PyPoksException('Number of given DMK names must be equal 1 or 2')
ddL = [{
'name': nm,
'trainable': False,
'n_players': N_TABLE_PLAYERS - len(dmk_names),
#'publish': False,
'fwd_stats_step': 10} for nm in dmk_names]
GamesManager.__init__(self, dmk_pointL=ddL, logger=logger)
# update/override with HuDMK
self.dmkD[hdna['name']] = hdmk
self.families.add(hdna['family'])
hdmk.que_to_gm = self.que_to_gm
# starts all subprocesses
def start_games(self):
self._put_players_on_tables()
self._start_tables()
self._start_dmks()
# an alternative way of stopping all subprocesses (dmks & tables)
def kill_games(self):
self.logger.info('HuGamesManager is killing games..')
for dmk in self.dmkD.values(): dmk.kill()
for table in self.tables: table.kill()
def run_tk(self): self.tk_gui.run_tk() | piteren/pypoks | podecide/games_manager.py | games_manager.py | py | 25,904 | python | en | code | 19 | github-code | 36 | [
{
"api_name": "statistics.stdev",
"line_number": 23,
"usage_type": "call"
},
{
"api_name": "typing.Optional",
"line_number": 20,
"usage_type": "name"
},
{
"api_name": "typing.Optional",
"line_number": 27,
"usage_type": "name"
},
{
"api_name": "typing.Optional",
... |
10058551191 | import numpy as np
from scipy.integrate import solve_ivp
class VanDerPolOscillator:
def __init__(self, epsilon):
self.epsilon = epsilon
def coupledEquation(self, t, x):
x1 = x[0]
x2 = x[1]
fx1 = x2
fx2 = -x1 - (self.epsilon * ((x1 ** 2) - 1) * x2)
return np.array([fx1, fx2], float)
def methodRK45(self, initialState, t0=0):
tSpan = [t0, (8 * np.pi)]
points = solve_ivp(self.coupledEquation, tSpan, initialState, method='RK45', first_step=0.01, max_step=0.01)
tPoints = points['t']
fx1Points = points['y'][0]
fx2Points = points['y'][1]
return tPoints, fx1Points, fx2Points
| MFournierQC/PhysiqueNumerique | TP3/VanDerPolOscillator.py | VanDerPolOscillator.py | py | 685 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "numpy.array",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "numpy.pi",
"line_number": 17,
"usage_type": "attribute"
},
{
"api_name": "scipy.integrate.solve_ivp",
"line_number": 18,
"usage_type": "call"
}
] |
75226770345 | from django.core.exceptions import ValidationError
from django.db import models
from django.urls import reverse
from django.utils.text import slugify
from django_resized import ResizedImageField
from .base import BaseModel
from .images import Images
def file_size(value):
limit = 6 * 1024 * 1024
if value.size > limit:
raise ValidationError("Plik który chcesz wrzucić jest większy niż 6MB.")
class Articles(BaseModel):
id = models.AutoField(primary_key=True)
category = models.ForeignKey(
"category", on_delete=models.CASCADE, verbose_name="Kategoria artykułu"
)
title = models.CharField(verbose_name="Tytyuł artykułu", max_length=256)
slug = models.SlugField(verbose_name="Slug", blank=True, null=True, max_length=256)
body = models.TextField(verbose_name="Treść artukułu")
image = ResizedImageField(
verbose_name="Zdjęcie główne",
size=[1280, 960],
upload_to="images/articles/",
validators=[file_size],
null=True,
blank=True,
)
image_alt = models.CharField(
verbose_name="Alternatywny text dla obrazka",
max_length=125,
blank=True,
null=True,
)
image_title = models.CharField(
verbose_name="Title dla obrazka", blank=True, null=True, max_length=70
)
meta_description = models.CharField(
verbose_name="Meta description dla artykułu", blank=True, null=True, max_length=160
)
meta_title = models.CharField(
verbose_name="Meta title dla artykułu", blank=True, null=True, max_length=60
)
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Articles, self).save()
def get_absolute_url(self):
return reverse(
"article_details",
kwargs={
"category": self.category.slug,
"title": self.slug,
"pk": self.id,
},
)
class Meta:
ordering = ("-created_time",)
verbose_name_plural = "Artykuły"
def images(self):
return Images.objects.filter(article_id=self)
def __str__(self):
return self.category.name + ", " + self.title
| KennyDaktyl/miktel_shop | web/models/articles.py | articles.py | py | 2,215 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "django.core.exceptions.ValidationError",
"line_number": 13,
"usage_type": "call"
},
{
"api_name": "base.BaseModel",
"line_number": 16,
"usage_type": "name"
},
{
"api_name": "django.db.models.AutoField",
"line_number": 17,
"usage_type": "call"
},
{
"... |
35658678468 | """The filtersets tests module."""
import pytest
from django.db.models.query import QuerySet
from django.http.request import HttpRequest
from communication.filtersets import (_get_interlocutors, _get_recipients,
_get_reviews, _get_senders)
pytestmark = pytest.mark.django_db
def test_get_reviews(reviews: QuerySet):
"""Should return the filtered list of reviews."""
assert not _get_reviews(None).count()
request = HttpRequest()
user = reviews[0].professional.user
request.user = user
result = _get_reviews(request)
assert result.count() == 1
assert result[0].professional.user == reviews[0].professional.user
def test_get_recipients(messages: QuerySet):
"""Should return recipients."""
assert not _get_recipients(None).count()
request = HttpRequest()
user = messages[0].sender
request.user = user
result = _get_recipients(request)
assert result.count() == 1
assert result[0] == messages[0].recipient
def test_get_senders(messages: QuerySet):
"""Should return senders."""
assert not _get_senders(None).count()
request = HttpRequest()
user = messages[0].recipient
request.user = user
result = _get_senders(request)
assert result.count() == 1
assert result[0] == messages[0].sender
def test_get_interlocutors(messages: QuerySet):
"""Should return interlocutors."""
assert not _get_interlocutors(None).count()
request = HttpRequest()
user = messages[0].recipient
request.user = user
result = _get_interlocutors(request)
assert result.count() == 1
assert result[0] == messages[0].sender
| webmalc/d8base-backend | communication/tests/filtersets_tests.py | filtersets_tests.py | py | 1,658 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pytest.mark",
"line_number": 9,
"usage_type": "attribute"
},
{
"api_name": "django.db.models.query.QuerySet",
"line_number": 12,
"usage_type": "name"
},
{
"api_name": "communication.filtersets._get_reviews",
"line_number": 14,
"usage_type": "call"
},
{
... |
15197021379 | import argparse
import socket
import sys
import json
import urllib.request
import redis
import base64
import re
import boto3
import os
import subprocess
from faker import Faker
import logging
logging.basicConfig(level=logging.DEBUG)
fake = Faker('en_US')
Faker.seed(1337)
kms_client = boto3.client('kms')
kms_key_id = os.environ.get('KMS_KEY_ID')
r = redis.Redis(unix_socket_path='/run/redis.sock')
for i in range(1,100):
name = fake.name()
r.set(name, 'bar{}'.format(i))
# Running server you have pass port the server will listen to. For Example:
# $ python3 /app/server.py server 5005
class VsockListener:
# Server
def __init__(self, conn_backlog=128):
self.conn_backlog = conn_backlog
def bind(self, port):
# Bind and listen for connections on the specified port
self.sock = socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM)
self.sock.bind((socket.VMADDR_CID_ANY, port))
self.sock.listen(self.conn_backlog)
def recv_data(self):
# Receive data from a remote endpoint
while True:
try:
logging.info("Let's accept stuff")
(from_client, (remote_cid, remote_port)) = self.sock.accept()
logging.info("Connection from " + str(from_client) + str(remote_cid) + str(remote_port))
query = json.loads(base64.b64decode(from_client.recv(4096).decode()).decode())
logging.info("Message received: {}".format(query))
query_type = list(query.keys())[0]
query = query[query_type]
logging.info("{} {}".format(query_type, query))
if query_type == 'get':
response = query_redis(query)
elif query_type == 'set':
response = put_in_redis(query)
else:
response = "Bad query type\n"
# Send back the response
from_client.send(str(response).encode())
from_client.close()
logging.info("Client call closed")
except Exception as ex:
logging.info(ex)
KMS_PROXY_PORT="8000"
def get_plaintext(credentials):
"""
prepare inputs and invoke decrypt function
"""
# take all data from client
access = credentials['access_key_id']
secret = credentials['secret_access_key']
token = credentials['token']
ciphertext= credentials['ciphertext']
region = credentials['region']
logging.info('ciphertext: {}'.format(ciphertext))
creds = decrypt_cipher(access, secret, token, ciphertext, region)
return creds
def decrypt_cipher(access, secret, token, ciphertext, region):
"""
use KMS Tool Enclave Cli to decrypt cipher text
"""
logging.info('in decrypt_cypher')
proc_params = [
"/app/kmstool_enclave_cli",
"decrypt",
"--region", region,
"--proxy-port", KMS_PROXY_PORT,
"--aws-access-key-id", access,
"--aws-secret-access-key", secret,
"--aws-session-token", token,
"--ciphertext", ciphertext,
]
logging.debug('proc_params: {}'.format(proc_params))
proc = subprocess.Popen(
proc_params,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
ret = proc.communicate()
logging.debug('proc: {}'.format(proc.communicate()))
if ret[0]:
logging.info('No KMS error')
logging.debug('ret[0]: {}'.format(ret[0]))
b64text = proc.communicate()[0].decode().split()[1]
logging.debug('b64text: {}'.format(b64text))
plaintext = base64.b64decode(b64text).decode()
return (0, plaintext)
else:
logging.info('KMS error')
return (1, "KMS Error. Decryption Failed.\n")
def server_handler(args):
server = VsockListener()
server.bind(args.port)
logging.info("Started listening to port : {}".format(args.port))
server.recv_data()
def put_in_redis(query):
status, query = get_plaintext(query)
if status:
logging.info(query)
return query
try:
query = json.loads(query)
except ValueError:
return 'Failed to put in data: Mot valid JSON\n'
for key in query.keys():
r.set(key, query[key])
return "Put the data in\n"
# Get list of current ip ranges for the S3 service for a region.
# Learn more here: https://docs.aws.amazon.com/general/latest/gr/aws-ip-ranges.html#aws-ip-download
def query_redis(query):
status, value = get_plaintext(query)
if status:
logging.info(value)
return value
value = r.get(value)
if value != None:
logging.info("Key exists")
return "The key exists\n"
elif value == None:
logging.info("Key doesn't exist")
return "They key does not exist\n"
else:
logging.info("In Else")
return "Somehow here with value: {}\n".format(value)
def main():
parser = argparse.ArgumentParser(prog='vsock-sample')
parser.add_argument("--version", action="version",
help="Prints version information.",
version='%(prog)s 0.1.0')
subparsers = parser.add_subparsers(title="options")
server_parser = subparsers.add_parser("server", description="Server",
help="Listen on a given port.")
server_parser.add_argument("port", type=int, help="The local port to listen on.")
server_parser.set_defaults(func=server_handler)
if len(sys.argv) < 2:
parser.print_usage()
sys.exit(1)
args = parser.parse_args()
args.func(args)
if __name__ == "__main__":
main()
| SMonaghan/nitro-enclave-with-redis | files/server.py | server.py | py | 5,032 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "logging.basicConfig",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "logging.DEBUG",
"line_number": 16,
"usage_type": "attribute"
},
{
"api_name": "faker.Faker",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "faker.Faker.seed",... |
41260980135 | from geometry_msgs.msg import Twist
import pyzbar.pyzbar as pyzbar
from datetime import datetime
import pyrealsense2 as rs
import numpy as np
import schedule
import rospy
import time
import cv2
frame_crop_x1 = 0
frame_crop_y1 = 120
frame_crop_x2 = 639
frame_crop_y2 = 479
minLineLength = 30
maxLineGap = 15
speed = 0
angle = 0
avr_x = 0
turn = -0.5
code_start = "start"
barcode_data_line_QR = []
text_0 = ""
text_1 = ""
## 동일한 qr코드 인식시 스피드 0 or 움직임
view_same_QR = 0
view_start_QR_and_no_product = 0
obstacle_view = 0
cap_0 = cv2.VideoCapture(2)
cap_1 = cv2.VideoCapture(4)
cap_1.set(cv2.CAP_PROP_FRAME_HEIGHT,180)
cap_1.set(cv2.CAP_PROP_FRAME_WIDTH,320)
def cam_0_read():
global retval_0, frame_0, original, gray_line_0, gray_line_1
retval_0, frame_0 = cap_0.read()
original = frame_0
gray_line_0 = cv2.cvtColor(frame_0, cv2.COLOR_BGR2GRAY)
gray_line_1 = cv2.cvtColor(frame_0, cv2.COLOR_BGR2GRAY)
def cam_1_read():
global retval_1, frame_1, gray_product_0
retval_1, frame_1 = cap_1.read()
gray_product_0 = cv2.cvtColor(frame_1, cv2.COLOR_BGR2GRAY)
def cam_0_use_line():
global retval_0, frame_0, original, theta
blurred = gray_line_0[frame_crop_y1:frame_crop_y2,frame_crop_x1:frame_crop_x2]
blurred = cv2.boxFilter(blurred, ddepth=-1, ksize=(31,31))
retval2 ,blurred = cv2.threshold(blurred, 100, 255, cv2.THRESH_BINARY)
edged = cv2.Canny(blurred, 85, 85)
lines = cv2.HoughLinesP(edged,1,np.pi/180,10,minLineLength,maxLineGap)
max_diff = 1000
final_x = 0
if ( lines is not None ):
if ( lines is not None ):
add_line = 0
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(original,(x1+frame_crop_x1,y1+frame_crop_y1),(x2+frame_crop_x1,y2+frame_crop_y1),(0,255,0),3)
mid_point = ( x1 + x2 ) / 2
diff = abs((640/2) - mid_point)
if ( max_diff > diff ) :
max_diff = diff
final_x = mid_point
add_line = add_line + final_x
average_x = add_line / len(lines)
if ( int(average_x) != 0 ) :
original = cv2.circle(original,(int(average_x),int((frame_crop_y1+frame_crop_y2)/2)),5,(0,0,255),-1)
original = cv2.rectangle(original,(int(frame_crop_x1),int(frame_crop_y1)),(int(frame_crop_x2),int(frame_crop_y2)),(0,0,255),1)
frame_0 = original
theta = int(( int(average_x) - 320.0 ) / 640.0 * 100)
if ( lines is None ):
theta = -50
def cam_0_use_qrcode():
global barcode_data_line_QR, barcode_type_line_QR
decoded_line_QR = pyzbar.decode(gray_line_1)
for _ in decoded_line_QR:
x, y, w, h = _.rect
barcode_data_line_QR = _.data.decode("utf-8")
barcode_type_line_QR = _.type
cv2.rectangle(frame_0, (x, y), (x + w, y + h), (0, 0, 255), 2)
text_0 = '%s (%s)' % (barcode_data_line_QR, barcode_type_line_QR)
cv2.putText(frame_0, text_0, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2, cv2.LINE_AA)
if decoded_line_QR == [] :
barcode_data_line_QR = "QR_X"
def cam_1_use_qrcode():
global barcode_data_product_QR, barcode_type_product_QR
decoded_product_QR = pyzbar.decode(gray_product_0)
for _ in decoded_product_QR:
a, b, c, d = _.rect
barcode_data_product_QR = _.data.decode("utf-8")
barcode_type_product_QR = _.type
cv2.rectangle(frame_1, (a, b), (a + c, b + d), (0, 0, 255), 2)
text_1 = '%s (%s)' % (barcode_data_product_QR, barcode_type_product_QR)
cv2.putText(frame_1, text_1, (a, b), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2, cv2.LINE_AA)
if decoded_product_QR == [] :
barcode_data_product_QR = "QR_X"
def cam_lidar_read():
global pipeline
pipeline = rs.pipeline()
config = rs.config()
config.enable_stream(rs.stream.depth, 320, 240, rs.format.z16, )
pipeline.start(config)
def cam_lidar_use():
global add_num, add_edge_num, add_edge_remain_num, image_all, left_view
frames = pipeline.wait_for_frames()
depth = frames.get_depth_frame()
coverage = [0]*32
image_all = []
add_num = 0
add_edge_num = 0
add_edge_remain_num = 0
for y in range(240):
for x in range(320):
dist = depth.get_distance(x, y)
if 0 < dist and dist < 1:
coverage[x//10] += 1
if y%20 is 19:
line = ""
for c in coverage:
line += " 12345678"[c//25]
coverage = [0]*32
image_all.append(line)
for a in range(1,32):
if line[a] == " " : add_num = add_num
else : add_num = add_num + int(line[a])
for a in range(1,2):
if line[a] == " " : add_edge_num = add_edge_num
else : add_edge_num = add_edge_num + int(line[a])
for a in range(3,32):
if line[a] == " " : add_edge_remain_num = add_edge_remain_num
else : add_edge_remain_num = add_edge_remain_num + int(line[a])
def speed_and_angle_make():
global angle, speed
angle = round((-theta) * (0.012), 2)
speed = 0.3 - abs(angle * 0.2)
def speed_and_angle_turn():
global angle, speed
speed = 0
angle = turn
def speed_and_angle_main():
global angle, speed, barcode_data_product_QR, barcode_data_line_QR, turn, obstacle_view, view_same_QR, view_start_QR_and_no_product
if barcode_data_line_QR == "right_turn" : turn = -0.5
if barcode_data_line_QR == "left_turn" : turn = 0.5
if view_same_QR == 0 and view_start_QR_and_no_product == 0 :
if obstacle_view == 0 :
if theta != -50:
if add_num <= 10 : speed_and_angle_make()
if add_num <= 10 and barcode_data_product_QR != "QR_X" and barcode_data_product_QR == barcode_data_line_QR : view_same_QR = 1
if add_num <= 10 and barcode_data_product_QR == "QR_X" and barcode_data_line_QR == "start" : view_start_QR_and_no_product = 1
if add_num > 10 :
speed = 0
obstacle_view = 1
if theta == -50 : speed_and_angle_turn()
if obstacle_view == 1 :
if add_num != 0 :
if add_edge_num > 0 and add_edge_remain_num == 0 : angle = -0.4
if add_edge_remain_num > 0 and add_edge_num == 0 : angle = -0.4
if add_edge_remain_num > 0 and add_edge_num > 0 : angle = -0.4
speed = 0.2
if add_num == 0 : angle = 0.4
if theta != -50 and add_num == 0 : obstacle_view = 0
if view_same_QR == 1 or view_start_QR_and_no_product == 1:
speed = 0
angle = 0
if view_same_QR == 1 and barcode_data_product_QR == "QR_X" : view_same_QR = 0
if view_start_QR_and_no_product == 1 and barcode_data_product_QR != "QR_X" : view_start_QR_and_no_product = 0
def talker():
global speed, angle
rospy.init_node("line_qr_sensor")
pub = rospy.Publisher("/cmd_vel", Twist, queue_size=10)
msg = Twist()
cam_lidar_read()
while not rospy.is_shutdown():
msg.linear.x = speed
msg.angular.z = angle
pub.publish(msg)
cam_0_read()
cam_0_use_line()
cam_0_use_qrcode()
cam_1_read()
cam_1_use_qrcode()
cam_lidar_use()
speed_and_angle_main()
for y in range(12):
print(image_all[y])
print(add_num)
print("장애물 : ", obstacle_view)
print("세타값 : ", theta)
print("턴값 : ", turn)
cv2.imshow('frame_0', frame_0)
cv2.imshow('frame_1', frame_1)
key = cv2.waitKey(25)
if key == 27: #ESC
break
if __name__ == "__main__":
try:
talker()
except rospy.ROSInterruptException:
pass | LEEJUNHO95/ROS_project | line_detect.py | line_detect.py | py | 8,101 | python | en | code | 5 | github-code | 36 | [
{
"api_name": "cv2.VideoCapture",
"line_number": 35,
"usage_type": "call"
},
{
"api_name": "cv2.VideoCapture",
"line_number": 36,
"usage_type": "call"
},
{
"api_name": "cv2.CAP_PROP_FRAME_HEIGHT",
"line_number": 38,
"usage_type": "attribute"
},
{
"api_name": "cv2.... |
3647124333 | import commands
import sys
sys.path.append('../../')
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
import django
django.setup()
path = os.getcwd()
pangu_info = "/".join([path,"mysite/config/ecs_pangu.txt"])
def parse_srv_status():
oss_srv_stat = {}
ret = []
pangu_srv_status = commands.getoutput("cat %s |grep -Ei \"normal|disconnected\""%pangu_info)
split_data = pangu_srv_status.split('\n')
for srv in split_data:
oss_srv_stat["status"] = srv.split()[1]
oss_srv_stat['ip'] = srv.split()[5].split('//')[1]
oss_srv_stat['hostname'] = srv.split()[6]
ret.append(dict(oss_srv_stat))
return ret
| luvensin/privateCloudMonitor | mysite/mysite/config/parse_data_ecs_pangu.py | parse_data_ecs_pangu.py | py | 689 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "sys.path.append",
"line_number": 4,
"usage_type": "call"
},
{
"api_name": "sys.path",
"line_number": 4,
"usage_type": "attribute"
},
{
"api_name": "os.environ.setdefault",
"line_number": 8,
"usage_type": "call"
},
{
"api_name": "os.environ",
"li... |
1065889096 | import numpy as np
import matplotlib.pyplot as plt
import sys
def h(X, theta):
return 1 / (1 + np.e ** -(X.dot(theta.T)))
def J(X, y, theta):
m = X.shape[0]
y_hat = h(X, theta)
erro = (-y * np.log(y_hat) - (1-y) * np.log(1-y_hat)).sum(0)
return erro / m
def GD(X, y, theta, alpha, niters):
m = X.shape[0]
cost = np.zeros((niters,1))
print('iteração:')
for k in range(0, niters):
print(' ',k,end='')
y_hat = h(X, theta)
erro = ((y_hat-y) *X).sum(0)/m
theta -= (alpha * (erro))
cost[k] = J(X, y, theta)
print('\r\r\r\r\r\r',end='')
return (cost, theta)
def featureScaling(X):
X=X-np.min(X,0)
den=np.max(X,0)-np.min(X,0)
return X/den
if len(sys.argv) < 5:
print('Usage %s <dataset> <# of iterations> <alpha> <delimiter>'%sys.argv[0])
f=sys.argv[1]
niters=int(sys.argv[2])
alpha=float(sys.argv[3])
delim=sys.argv[4]
## delete \n at the end of the string
data=np.genfromtxt(f,delimiter=delim)
## split the string into the values
# now data is a list of lists
X=data[:,:-1]
X=np.array(X,dtype=float)
#### Inicio da área que é permita alguma mudança
X=featureScaling(X)
X=np.insert(X,0,1,axis=1)
#### Fim da área que é permitida alguma mudança
y=data[:,-1]
y=np.reshape(np.array(y,dtype=int),(len(y),1))
Theta=np.zeros((1,X.shape[1]))
nsize=int(X.shape[0]*.7)
Xtr=X[:nsize,:]
Xte=X[nsize:,:]
ytr=y[:nsize]
yte=y[nsize:]
c,t=GD(Xtr,ytr,Theta,alpha,niters)
y_hat=np.round(h(Xtr,t))
print('Home made learner:')
print(' Taxa de acerto (treino):', np.mean(y_hat==ytr))
y_hat=np.round(h(Xte,t))
print(' Taxa de acerto (teste):', np.mean(y_hat==yte))
plt.plot(c)
plt.show()
#------------
from sklearn import linear_model
r=linear_model.LogisticRegression()
ytr=np.ravel(ytr)
r.fit(Xtr,ytr)
yte=np.ravel(yte)
y_hat=r.predict(Xtr)
print('Home made learner:')
print(' Taxa de acerto (treino):', np.mean(y_hat==ytr))
y_hat=r.predict(Xte)
print(' Taxa de acerto (teste):', np.mean(y_hat==yte))
| brunoprograma/machine_learning | aula_03/LRegression.py | LRegression.py | py | 1,934 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "numpy.e",
"line_number": 6,
"usage_type": "attribute"
},
{
"api_name": "numpy.log",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "numpy.zeros",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "numpy.min",
"line_number": 30,
... |
1900770945 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 5 21:43:03 2017
@author: ly
"""
import numpy as np
import pandas as pd
import os
import seaborn as sns # data visualization library
import matplotlib.pyplot as plt
import xgboost as xgb
import math
from sklearn import metrics
from sklearn.model_selection import KFold
from xgboost.sklearn import XGBClassifier
from sklearn.linear_model import Lasso
from sklearn.metrics import confusion_matrix
def prepare_data(filepath):
filepath=r"E:\workspace\Dementia\Q_DLB_nonDLB_after_removing_education_normalizion_0_to_1.csv"
dataset=pd.read_csv(filepath, index_col=None)
temp = dataset.copy()
DLB_count = 0
nonDLB_count = 0
for i in range(len(temp)):
if temp.loc[i,'Diagnosis'] == 'DLB':
temp.loc[i,'Diagnosis'] = 1
DLB_count+=1
else:
temp.loc[i,'Diagnosis'] = 0
nonDLB_count+=1
return temp,DLB_count,nonDLB_count
#filepath =r"E:\workspace\Dementia\Q_DLB_nonDLB_after_removing_education_normalizion_0_to_1.csv"
#temp,DLB_count,nonDLB_count = prepare_data(filepath)
#raw_target = list(temp.loc[:,'Diagnosis'] )
#Label_Array = temp.columns[:-1]
#import itertools
#combination = list(itertools.combinations(Label_Array,2))
def statistic(true,predict):
TP=0 #TP:正确的正例
TN=0 #TN:正确的负例
FP=0 #FP:错误的正例
FN=0 #FN:错误的负例
for i in range(len(true)):
if(true[i]==1):
if(predict[i]==1):
TP+=1 #真实为1,预测也为1
else :
FP+=1 #真实为1,预测为0
elif(predict[i]==1):
FN+=1 #真实为0,预测为1
else :
TN+=1 #真实为0,预测为0
return [TP,FP,TN,FN]
#统计准确率衡量的5个指标:Sn,Sp,Avc,Acc,Mcc
def assess(TP,FP,TN,FN):
Sn=Sp=Acc=Avc=Mcc=0 #评价分类器所用指标
if(TP+FN!=0):
Sn=TP*1.0/(TP+FN) #预测为1(正)的正确率
if(TN+FP!=0):
Sp=TN*1.0/(TN+FP) #预测为0(负)的正确率
Avc=(Sn+Sp)*1.0/2 #正负平均准确率
Acc=(TP+TN)*1.0/(TP+FP+TN+FN) #总体预测准确率
if((TP+FN)*(TP+FP)*(TN+FP)*(TN+FN)!=0):
Mcc=(TP*TN-FP*FN)*1.0/math.sqrt((TP+FN)*(TP+FP)*(TN+FP)*(TN+FN))
return [Sn,Sp,Acc,Avc,Mcc]
def kFoldTest(clf, raw_data, raw_target):
'''
十折交叉检验,clf是分类器,返回预测集
'''
predict=[]
kf = KFold(n_splits=10)
for train_index, test_index in kf.split(raw_data):
#print("TRAIN:", train_index, "TEST:", test_index)#查看如何分割数据
X_train, X_test = raw_data[[train_index]], raw_data[[test_index]]
#Y_test在这里没作用,为了数据变量对齐0.0
Y_train, Y_test = raw_target[:test_index[0]]+raw_target[test_index[-1]+1:], raw_target[test_index[0]:test_index[-1]+1]
clf.fit(X_train,Y_train)
test_target_temp=clf.predict(X_test)
predict.append(test_target_temp)
test_target = [i for temp in predict for i in temp]#将10次测试集展平
return test_target
def common_classier(raw_data, raw_target):
'''
使用常见的分类器进行分类
'''
from sklearn import neighbors
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import AdaBoostClassifier
df=pd.DataFrame(index=['Sn','Sp','ACC','AVC','MCC'])#该dataframe为了将正确率写入Excel
clf = SVC(kernel='linear', C=1)
value = statistic(raw_target,kFoldTest(clf, raw_data, raw_target))
df['SVM']=assess(value[0],value[1],value[2],value[3])
#用KNN
clf=neighbors.KNeighborsClassifier(n_neighbors = 3 )
value=statistic(raw_target,kFoldTest(clf, raw_data, raw_target))
df['KNN']=assess(value[0],value[1],value[2],value[3])
# #NB,pca的时候不能用
# clf=MultinomialNB(alpha=0.01)
# ACC,DLB,nonDLB=statistics(raw_target,kFoldTest(clf, ra
#Dtree
clf = DecisionTreeClassifier(random_state=0)
value=statistic(raw_target,kFoldTest(clf, raw_data, raw_target))
df['Dtree']=assess(value[0],value[1],value[2],value[3])
#随机森林
clf = RandomForestClassifier(n_estimators= 30, max_depth=13, min_samples_split=110,
min_samples_leaf=20,max_features='sqrt' ,oob_score=True,random_state=10)
value=statistic(raw_target,kFoldTest(clf, raw_data, raw_target))
df['RF']=assess(value[0],value[1],value[2],value[3])
#boosting
clf = AdaBoostClassifier(n_estimators=100)
value=statistic(raw_target,kFoldTest(clf, raw_data, raw_target))
df['adaboost']=assess(value[0],value[1],value[2],value[3])
return df
'''
filepath = r"E:\workspace\Dementia\Q_DLB_nonDLB_after_removing_education_normalizion_0_to_1.csv"
temp,DLB_count,nonDLB_count = prepare_data(filepath)
raw_data = temp.drop('Diagnosis',1).as_matrix(columns=None)
raw_label = list(temp.loc[:,'Diagnosis'])
df = common_classier(raw_data,raw_label)
temp_acc = max(list(df.loc['ACC',:] ))
Label_Array = temp.columns[:-1]
import itertools
combination = list(itertools.combinations(Label_Array,2))
writer = pd.ExcelWriter(r'E:\workspace\Dementia\acc.xlsx')
i = 0
max_acc = 0
for label_index in combination:
sheet = "combination" + str(i)
i += 1
raw_data = temp.loc[:,label_index].as_matrix(columns=None)
temp_df = common_classier(raw_data, raw_label)
temp_acc = max(list(temp_df.loc['ACC',:] ))
if temp_acc >= max_acc :
temp_df.to_excel(writer,sheet_name=sheet,index=True)
max_acc = temp_acc
writer.save()
'''
def Combination(temp, DLB_count, nonDLB_count, num):
'''
对数据集temp特征进行组合再进行分类
'''
raw_target = list(temp.loc[:,'Diagnosis'] )
Label_Array = temp.columns[:-1]
import itertools
combination = list(itertools.combinations(Label_Array,num))
writer = pd.ExcelWriter(r'E:\workspace\Dementia\acc.xlsx')
i = 0
max_acc = 0
for label_index in combination:
sheet = "combination" + str(i)
i += 1
raw_data = temp.loc[:,label_index].as_matrix(columns=None)
temp_df = common_classier(raw_data, raw_target)
temp_acc = max(list(temp_df.loc['ACC',:] ))
if temp_acc >= max_acc :
temp_df.to_excel(writer,sheet_name=sheet,index=True)
max_acc = temp_acc
writer.save()
if __name__ == '__main__':
filepath = r"E:\workspace\Dementia\Q_DLB_nonDLB_after_removing_education_normalizion_0_to_1.csv"
temp,DLB_count,nonDLB_count = prepare_data(filepath)
raw_data = temp.drop('Diagnosis',1).as_matrix(columns=None)
raw_label = list(temp.loc[:,'Diagnosis'])
Combination(raw_data, DLB_count, nonDLB_count, 2)
| LiuyangJLU/Dementia | 1205test.py | 1205test.py | py | 7,023 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pandas.read_csv",
"line_number": 25,
"usage_type": "call"
},
{
"api_name": "math.sqrt",
"line_number": 79,
"usage_type": "call"
},
{
"api_name": "sklearn.model_selection.KFold",
"line_number": 88,
"usage_type": "call"
},
{
"api_name": "pandas.DataFr... |
74574329062 | # -*- coding: utf-8 -*-
#
# Author: Ingelrest François (Francois.Ingelrest@gmail.com)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
import gtk, modules, os.path
from tools import consts, loadGladeFile, prefs
from gettext import gettext as _
MOD_INFO = ('Status Icon', _('Status Icon'), _('Add an icon to the notification area'), [], False, False)
class StatusIcon(modules.Module):
def __init__(self):
""" Constructor """
modules.Module.__init__(self, (consts.MSG_EVT_MOD_LOADED, consts.MSG_EVT_MOD_UNLOADED, consts.MSG_EVT_APP_STARTED,
consts.MSG_EVT_NEW_TRACK, consts.MSG_EVT_PAUSED, consts.MSG_EVT_UNPAUSED,
consts.MSG_EVT_STOPPED, consts.MSG_EVT_NEW_TRACKLIST, consts.MSG_EVT_TRACK_MOVED))
def install(self):
""" Install the Status icon """
self.tooltip = consts.appName
self.isPaused = False
self.popupMenu = None
self.isPlaying = False
self.icoNormal = None
self.mainWindow = prefs.getWidgetsTree().get_widget('win-main')
self.trackHasNext = False
self.trackHasPrev = False
self.emptyTracklist = True
self.isMainWinVisible = True
# The status icon does not support RGBA, so make sure to use the RGB color map when creating it
colormap = self.mainWindow.get_screen().get_rgb_colormap()
gtk.widget_push_colormap(self.mainWindow.get_screen().get_rgb_colormap())
self.statusIcon = gtk.StatusIcon()
gtk.widget_pop_colormap()
# GTK+ handlers
self.statusIcon.connect('activate', self.toggleWinVisibility)
self.statusIcon.connect('popup-menu', self.onPopupMenu)
self.statusIcon.connect('size-changed', self.renderIcons)
# Install everything
self.statusIcon.set_tooltip(consts.appName)
self.onNewTrack(None)
self.statusIcon.set_visible(True)
def uninstall(self):
""" Uninstall the Status icon """
self.statusIcon.set_visible(False)
self.statusIcon = None
if not self.isMainWinVisible:
self.mainWindow.show()
self.isMainWinVisible = True
def renderIcons(self, statusIcon, availableSize):
""" (Re) Create icons based the available tray size """
# Normal icon
if availableSize >= 48+2: self.icoNormal = gtk.gdk.pixbuf_new_from_file(consts.fileImgIcon48)
elif availableSize >= 32+2: self.icoNormal = gtk.gdk.pixbuf_new_from_file(consts.fileImgIcon32)
elif availableSize >= 24+2: self.icoNormal = gtk.gdk.pixbuf_new_from_file(consts.fileImgIcon24)
else: self.icoNormal = gtk.gdk.pixbuf_new_from_file(consts.fileImgIcon16)
# Paused icon
self.icoPause = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, self.icoNormal.get_width(), self.icoNormal.get_height())
self.icoPause.fill(0x00000000)
self.icoNormal.composite(self.icoPause, 0, 0, self.icoNormal.get_width(), self.icoNormal.get_height(), 0, 0, 1, 1, gtk.gdk.INTERP_HYPER, 100)
if self.icoNormal.get_width() == 16: pauseStock = self.mainWindow.render_icon(gtk.STOCK_MEDIA_PAUSE, gtk.ICON_SIZE_MENU)
else: pauseStock = self.mainWindow.render_icon(gtk.STOCK_MEDIA_PAUSE, gtk.ICON_SIZE_BUTTON)
diffX = self.icoPause.get_width() - pauseStock.get_width()
diffY = self.icoPause.get_height() - pauseStock.get_height()
pauseStock.composite(self.icoPause, 0, 0, pauseStock.get_width(), pauseStock.get_height(), diffX/2, diffY/2, 1, 1, gtk.gdk.INTERP_HYPER, 255)
# Use the correct icon
if self.isPaused: statusIcon.set_from_pixbuf(self.icoPause)
else: statusIcon.set_from_pixbuf(self.icoNormal)
def onNewTrack(self, track):
""" A new track is being played, None if none """
if track is None: self.tooltip = consts.appName
else: self.tooltip = '%s - %s' % (track.getArtist(), track.getTitle())
self.isPaused = False
self.isPlaying = track is not None
self.statusIcon.set_from_pixbuf(self.icoNormal)
self.statusIcon.set_tooltip(self.tooltip)
def onPause(self):
""" The current track has been paused """
self.isPaused = True
self.statusIcon.set_from_pixbuf(self.icoPause)
self.statusIcon.set_tooltip(_('%(tooltip)s [paused]') % {'tooltip': self.tooltip})
def onUnpause(self):
""" The current track has been unpaused """
self.isPaused = False
self.statusIcon.set_from_pixbuf(self.icoNormal)
self.statusIcon.set_tooltip(self.tooltip)
def toggleWinVisibility(self, statusIcon):
""" Show/hide the main window """
if not self.isMainWinVisible:
self.mainWindow.show()
self.isMainWinVisible = True
elif self.mainWindow.has_toplevel_focus():
self.mainWindow.hide()
self.isMainWinVisible = False
else:
self.mainWindow.hide()
self.mainWindow.show()
# --== Message handler ==--
def handleMsg(self, msg, params):
""" Handle messages sent to this module """
if msg == consts.MSG_EVT_PAUSED: self.onPause()
elif msg == consts.MSG_EVT_STOPPED: self.onNewTrack(None)
elif msg == consts.MSG_EVT_UNPAUSED: self.onUnpause()
elif msg == consts.MSG_EVT_NEW_TRACK: self.onNewTrack(params['track'])
elif msg == consts.MSG_EVT_MOD_LOADED: self.install()
elif msg == consts.MSG_EVT_TRACK_MOVED: self.trackHasNext, self.trackHasPrev = params['hasNext'], params['hasPrevious']
elif msg == consts.MSG_EVT_APP_STARTED: self.install()
elif msg == consts.MSG_EVT_MOD_UNLOADED: self.uninstall()
elif msg == consts.MSG_EVT_NEW_TRACKLIST: self.emptyTracklist = (len(params['tracks']) == 0)
# --== GTK handlers ==--
def onPopupMenu(self, statusIcon, button, time):
""" The user asks for the popup menu """
if self.popupMenu is None:
wTree = loadGladeFile('StatusIconMenu.glade')
self.menuPlay = wTree.get_widget('item-play')
self.menuStop = wTree.get_widget('item-stop')
self.menuNext = wTree.get_widget('item-next')
self.popupMenu = wTree.get_widget('menu-popup')
self.menuPause = wTree.get_widget('item-pause')
self.menuPrevious = wTree.get_widget('item-previous')
self.menuSeparator = wTree.get_widget('item-separator')
# Connect handlers
wTree.get_widget('item-quit').connect('activate', lambda btn: modules.postQuitMsg())
wTree.get_widget('item-preferences').connect('activate', lambda btn: modules.showPreferences())
self.menuPlay.connect('activate', lambda btn: modules.postMsg(consts.MSG_CMD_TOGGLE_PAUSE))
self.menuStop.connect('activate', lambda btn: modules.postMsg(consts.MSG_CMD_STOP))
self.menuNext.connect('activate', lambda btn: modules.postMsg(consts.MSG_CMD_NEXT))
self.menuPrevious.connect('activate', lambda btn: modules.postMsg(consts.MSG_CMD_PREVIOUS))
self.menuPause.connect('activate', lambda btn: modules.postMsg(consts.MSG_CMD_TOGGLE_PAUSE))
self.popupMenu.show_all()
# Enable only relevant menu entries
self.menuStop.set_sensitive(self.isPlaying)
self.menuNext.set_sensitive(self.isPlaying and self.trackHasNext)
self.menuPause.set_sensitive(self.isPlaying and not self.isPaused)
self.menuPrevious.set_sensitive(self.isPlaying and self.trackHasPrev)
self.menuPlay.set_sensitive((not (self.isPlaying or self.emptyTracklist)) or self.isPaused)
self.popupMenu.popup(None, None, gtk.status_icon_position_menu, button, time, statusIcon)
| gabrielmcf/biel-audio-player | src/modules/StatusIcon.py | StatusIcon.py | py | 8,708 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "gettext.gettext",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "modules.Module",
"line_number": 27,
"usage_type": "attribute"
},
{
"api_name": "modules.Module.__init__",
"line_number": 31,
"usage_type": "call"
},
{
"api_name": "modules.M... |
12198741928 | import pandas as pd
import streamlit as st
import fitz
from PIL import Image
from dataExtractor import DataExtractor
from image2 import Canvas
from firebase import FirebaseDB
import json
from st_keyup import st_keyup
json_data = {'Tear Down': ['cable', 'bomba', 'intake'],
'Production': ['simulacion', 'equipo'],
'Artificial Lift': ['cable', 'bomba', 'intake', 'motor', 'sensor', 'protector'],
'Efficiency': ['general', 'bomba', 'motor']}
st.write(f"Define a new extraction {st.session_state.user['nombre']}")
def read_pdf(uploaded):
file = fitz.open(stream=uploaded.read())
return file
def create_image_list_from_pdf(file):
images = []
for page_number in range(len(file)):
page = file.load_page(page_number)
pix = page.get_pixmap(matrix=fitz.Matrix(2, 2))
image = Image.frombytes("RGB", (pix.width, pix.height), pix.samples)
w, h = 700, 500
resized_image = image.resize((w, h))
images.append(resized_image)
return images
def replace_image_in_canvas(canvas, image, key):
new_image = image # Get the new image
new_key = key # Get the new key
canvas.reset_canvas(new_image, new_key) # Call the reset_canvas method of the canvas object
def load_canvas(image, page_number, draw_mode, update):
canvas = Canvas(image, draw_mode, update_streamlit=update)
canvas.create_canvas(page_number)
canvas.process_drawing()
return canvas
def store_scaled_coordinates(page_number, coordinates, delete_columns):
if coordinates is not None:
# Fill the 'page' column with the page_number value
coordinates['page'] = page_number
# Drop the specified columns
coordinates = coordinates.drop(delete_columns, axis=1)
return pd.DataFrame(coordinates)
def present_dataframe(dataframe, markdown):
if isinstance(dataframe, pd.DataFrame):
st.subheader(markdown)
st.dataframe(dataframe)
else:
st.write("No DataFrame was provided.")
def first_page():
st.subheader("PDF Document")
st.write("Upload and define attributes.")
file = st.file_uploader("Upload PDF", type=['pdf'])
if file is not None:
if "file" not in st.session_state:
st.session_state["file"] = file
if "regex" not in st.session_state:
st.session_state["regex"] = pd.DataFrame()
if "subject" not in st.session_state:
st.session_state["subject"] = None
def get_report_main_topics(report):
st.session_state.atributos_reporte = json_data[report]
def add_coordinates_to_firebase(dataframe, collection_name, subject):
firebase_db = FirebaseDB()
return firebase_db.add_coordinates(dataframe, collection_name, subject)
def selection():
# Usage example
subject_name = "testmail/test2"
#To upload a report
st.subheader("PDF Document Extraction")
uploaded_file = st.file_uploader("Upload PDF sample", type=['pdf'])
realtime_update = st.checkbox("Update in realtime", True)
st.write("Select between defining the area of the table (rect),"
"or modify a predefined area (transform)")
drawing_mode = st.selectbox("Drawing tool:", ["rect", "transform"])
if uploaded_file is not None:
if "compiled_scales" not in st.session_state:
st.session_state["compiled_scales"] = pd.DataFrame()
if "page_number" not in st.session_state:
st.session_state["page_number"] = 0
pdf = read_pdf(uploaded_file)
image_list = create_image_list_from_pdf(pdf)
canvas_obj = load_canvas(image_list[st.session_state["page_number"]],
st.session_state["page_number"],
drawing_mode, realtime_update)
st.caption("Note: This canvas version could define columns or cells with None values,"
" consider to select a table or area of it in order that the table extraction preview"
" contains the elements you want.")
present_dataframe(st.session_state["compiled_scales"], "All Scaled Coordinates")
objects_df = canvas_obj.get_objects_dataframe()
all_scaled_coordinates = None
if objects_df is not None and 'type' in objects_df.columns:
table_objects = objects_df.loc[objects_df['type'] == 'rect']
if len(table_objects) > 0:
difference = (len(st.session_state["atributos_reporte"])-len(st.session_state["compiled_scales"]))
#st.write(difference)
data = st.session_state["atributos_reporte"][-difference:] if difference > 0 else []
#st.write(data)
all_scaled_coordinates = canvas_obj.process_tables(table_objects,
pdf.load_page(st.session_state["page_number"]),
data)
if all_scaled_coordinates is not None:
st.markdown("### Scaled Page Coordinates")
st.table(all_scaled_coordinates)
st.markdown("### Extracted Page Tables")
table_count = 0
for _, row in all_scaled_coordinates.iterrows():
top = row['Top']
left = row['Left']
height = row['Final height']
width = row['Final width']
titles = row['Title']
data_extractor = DataExtractor(uploaded_file, st.session_state["page_number"] + 1, top, left,
width, height)
tables, title = data_extractor.extract_tables(titles)
if tables:
st.subheader(f"Table {titles}")
table_count += 1
for i in range(len(tables)):
st.dataframe(tables[i])
else:
st.write("No tables were extracted.")
else:
st.write("No rectangle selections found on the canvas.")
else:
st.write("No rectangle selections found on the canvas.")
canvas_element = st.empty() # Create an empty element to display the canvas
if "disabled" not in st.session_state:
st.session_state["disabled"] = False
next_button = st.button("Next", disabled=st.session_state["disabled"])
save_button = st.button("Save", disabled=not st.session_state["disabled"])
if next_button:
canvas_element.empty() # Clear the canvas element
st.session_state["page_number"] += 1
new_scaled_coordinates = store_scaled_coordinates(st.session_state["page_number"], all_scaled_coordinates,
["scaleX", "scaleY", "Width", "Height"])
if new_scaled_coordinates is not None:
st.session_state["compiled_scales"] = pd.concat([st.session_state["compiled_scales"],
new_scaled_coordinates], ignore_index=True)
if st.session_state["page_number"] >= len(image_list) - 1:
# st.session_state["page_number"] = 0
st.session_state["disabled"] = True
canvas_obj.reset_canvas(image_list[st.session_state["page_number"]], st.session_state["page_number"])
if st.session_state["disabled"]:
st.write("Before you save, define the mail subject for extraction (this implies how will be the subject"
" text when an email arrives to your inbox):")
subject_value = st_keyup("", value="Report_sample", key="subject")
st.write(f"Subject: {subject_value}")
subject = st.session_state.user['email'] + "/" + subject_value
subject_name = subject.replace(" ", "_")
st.write(f"Final parameters: {subject}")
if save_button:
st.session_state["page_number"] += 1
new_scaled_coordinates = store_scaled_coordinates(st.session_state["page_number"], all_scaled_coordinates,
["scaleX", "scaleY", "Width", "Height"])
if new_scaled_coordinates is not None:
st.session_state["compiled_scales"] = pd.concat([st.session_state["compiled_scales"],
new_scaled_coordinates], ignore_index=True)
present_dataframe(st.session_state["compiled_scales"], "Final Scaled Coordinates")
id_num = add_coordinates_to_firebase(st.session_state["compiled_scales"], "db_coord", subject_name)
st.markdown("Data saved with id " + str(id_num))
st.button("Finish", on_click= lambda : reset_all(uploaded_file))
canvas_obj.display_canvas()
else:
st.session_state["page_number"] = 0
st.session_state["disabled"] = False
st.session_state["compiled_scales"] = pd.DataFrame()
# Función para mostrar la pantalla dependiendo del botón seleccionado
def mostrar_pantalla():
# Inicializar el session state
if 'boton_seleccionado' not in st.session_state:
st.session_state.boton_seleccionado = None
if 'input_text' not in st.session_state:
st.session_state.input_text = False
if not st.session_state.user['imap']:
st.header("Additional process")
st.subheader("As this app works with email (IMAP), it is important to get access to your email account.")
input_text = st.text_input("Input you mail password", key='input_text_value')
if st.button("Save"):
firebasedb = FirebaseDB()
firebasedb.set_user_data(st.session_state.user['uid'], 'ek', input_text)
# Cambia el valor a True para mostrar los botones
st.session_state.user['imap'] = True
st.caption(":red[Gmail:] _For Gmail accounts, it is important to enable IMAP and input an app password, "
"for this you can look at the next link:_ https://support.google.com/mail/answer/185833?hl=es-419")
else:
# Mostrar el header dependiendo del botón seleccionado
if st.session_state.boton_seleccionado is not None:
if 'atributos_reporte' not in st.session_state:
st.session_state.atributos_reporte = []
st.header(f"Report type: {st.session_state.boton_seleccionado}")
print(st.session_state.boton_seleccionado)
get_report_main_topics(st.session_state.boton_seleccionado)
print(st.session_state.atributos_reporte)
st.write(st.session_state.atributos_reporte)
selection()
# Botones para seleccionar
if st.session_state.boton_seleccionado is None:
if st.button('Tear Down', key='button1',
on_click=lambda: st.session_state.update(boton_seleccionado="Tear Down")):
pass
if st.button('Production', key='button2',
on_click=lambda: st.session_state.update(boton_seleccionado="Production")):
pass
if st.button('Artificial Lift', key='button3',
on_click=lambda: st.session_state.update(boton_seleccionado="Artificial Lift")):
pass
if st.button('Efficiency', key='button4',
on_click=lambda: st.session_state.update(boton_seleccionado="Efficiency")):
pass
if st.session_state.boton_seleccionado is None:
st.write("Please, select a report type")
# Mostrar la pantalla
mostrar_pantalla()
def reset_all(file):
st.session_state.boton_seleccionado = None
st.session_state["page_number"] = 0
st.session_state["disabled"] = False
st.session_state["compiled_scales"] = pd.DataFrame()
file = None | gapastorv/st_rca_project | v2-incomplete/pages/Parsing.py | Parsing.py | py | 12,399 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "streamlit.write",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "streamlit.session_state",
"line_number": 16,
"usage_type": "attribute"
},
{
"api_name": "fitz.open",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "fitz.Matrix",
... |
5798683173 | import pygame
from SupportFuncs import load_image
class URadioButtons(pygame.sprite.Sprite):
def __init__(self, screen, coords, group):
super(URadioButtons, self).__init__(group)
self.coords = coords
self.buttons = []
self.checked_button = 0
self.font = pygame.font.Font('font/arial.ttf', 15)
self.screen = screen
self.draw()
def draw(self):
self.image = pygame.Surface((65 * len(self.buttons), 50), pygame.SRCALPHA)
self.rect = self.image.get_rect()
self.rect.x = self.coords[0]
self.rect.y = self.coords[1]
for i in range(len(self.buttons)):
color = (0, 0, 0)
image_name = 'ui_images/RadioButtonDefault.png'
if i == self.checked_button:
color = (255, 0, 0)
image_name = 'ui_images/RadioButtonChecked.png'
text_pg = self.font.render(self.buttons[i][0], True, color)
btn_img = pygame.transform.scale(load_image(image_name, colorkey=-1),
(50, 50))
self.image.blit(btn_img, (50 * i + 5 * (i + 1), 0))
self.image.blit(text_pg, (50 * i + 10 + 5 * (i + 1), 40 - text_pg.get_height()))
self.screen.blit(self.image, (self.coords[0], self.coords[1]))
def click_check(self, pos):
if pygame.sprite.collide_rect(pos, self):
cell_x = (pos.rect.x - 10) // 50 - self.coords[0] // 50
cell_y = (pos.rect.y - 10) // 50
if cell_x < 0 or cell_x >= len(self.buttons) or cell_y != 0:
return
self.checked_button = cell_x
self.buttons[cell_x][1]()
self.draw()
def hover_check(self, pos):
pass
def add_button(self, text, func):
self.buttons.append([text, func])
class ULineEdit(pygame.sprite.Sprite):
def __init__(self, screen, coords, group):
super(ULineEdit, self).__init__(group)
self.font = pygame.font.Font('font/arial.ttf', 15)
self.screen = screen
self.coords = coords
self.text = ''
self.en_to_ru = {'A': 'ф', 'B': 'и', 'C': 'с',
'D': 'в', 'E': 'у', 'F': 'а',
'G': 'п', 'H': 'р', 'I': 'ш',
'J': 'о', 'K': 'л', 'L': 'д',
'M': 'ь', 'N': 'т', 'O': 'щ',
'P': 'з', 'Q': 'й', 'R': 'к',
'S': 'ы', 'T': 'е', 'U': 'г',
'V': 'м', 'W': 'ц', 'X': 'ч',
'Y': 'н', 'Z': 'я', ',': 'б',
'.': 'ю', ';': 'ж', '\'': 'э',
'[': 'х', ']': 'ъ', '/': ','}
self.draw()
def draw(self):
self.image = pygame.Surface((200, 50), pygame.SRCALPHA)
self.rect = self.image.get_rect()
self.rect.x = self.coords[0]
self.rect.y = self.coords[1]
self.image.blit(pygame.transform.scale(load_image('ui_images/LineEdit.png', colorkey=-1), (200, 50)), (0, 0))
text_pg = self.font.render(self.text, True, (0, 0, 0))
self.image.blit(text_pg, (10, 40 - text_pg.get_height()))
self.screen.blit(self.image, (self.coords[0], self.coords[1]))
def click_check(self, pos):
pass
def hover_check(self, pos, event):
if pygame.sprite.collide_rect(pos, self):
if event.type == pygame.KEYDOWN:
key = pygame.key.name(event.key)
if key == 'backspace':
if len(self.text) >= 1:
self.text = self.text[:-1]
elif key in ['б', 'ю', 'ж', 'э', 'х', 'ъ']:
self.text += key
elif key.upper() in self.en_to_ru:
self.text += self.en_to_ru[key.upper()]
elif key.isdigit():
self.text += key
elif key == 'space':
self.text += ' '
def get_text(self):
return self.text
def set_text(self, text):
self.text = text
class UButton(pygame.sprite.Sprite):
def __init__(self, screen, coords, group, text, func, image_name='ui_images/ButtonBlue.png'):
super(UButton, self).__init__(group)
self.font = pygame.font.Font('font/arial.ttf', 15)
self.screen = screen
self.coords = coords
self.text = text
self.func = func
self.image_name = image_name
self.draw()
def draw(self):
self.image = pygame.Surface((70, 50), pygame.SRCALPHA)
self.rect = self.image.get_rect()
self.rect.x = self.coords[0]
self.rect.y = self.coords[1]
self.image.blit(pygame.transform.scale(load_image(self.image_name, colorkey=-1), (70, 50)), (0, 0))
text_pg = self.font.render(self.text, True, (0, 0, 0))
self.image.blit(text_pg, (10, 40 - text_pg.get_height()))
self.screen.blit(self.image, (self.coords[0], self.coords[1]))
def hover_check(self, pos):
pass
def click_check(self, pos):
if pygame.sprite.collide_rect(pos, self):
self.func()
class ULabel(pygame.sprite.Sprite):
def __init__(self, screen, coords, group, text, height=40, font_size=10):
super(ULabel, self).__init__(group)
self.font_size = font_size
self.font = pygame.font.Font('font/arial.ttf', self.font_size)
self.screen = screen
self.coords = coords
self.text = text
self.height = height
self.on_flag = True
self.draw()
def draw(self):
if self.on_flag:
self.image = pygame.Surface((len(self.text) * self.font_size * 0.55, self.height), pygame.SRCALPHA)
self.rect = self.image.get_rect()
self.rect.x = self.coords[0]
self.rect.y = self.coords[1]
self.image.blit(pygame.transform.scale(load_image('ui_images/Label.png', colorkey=-1),
(len(self.text) * self.font_size * 0.55, self.height)), (0, 0))
text_pg = self.font.render(self.text, True, (0, 0, 0))
self.image.blit(text_pg, (10, self.height - text_pg.get_height()))
self.screen.blit(self.image, (self.coords[0], self.coords[1]))
def set_text(self, text):
self.text = text
def off_on(self):
self.on_flag = not self.on_flag
| musaewullubiy/BigTaskMapAPI | UTINGAME.py | UTINGAME.py | py | 6,461 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "pygame.sprite",
"line_number": 5,
"usage_type": "attribute"
},
{
"api_name": "pygame.font.Font",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "pygame.font",
"line_number": 11,
"usage_type": "attribute"
},
{
"api_name": "pygame.Surface",
... |
28224798976 | """
Given a list of numbers, calculate another list in which
i_th element is the product of all numbers in the list except
the original i_th element.
"""
from functools import reduce
from typing import List
def solution_1(input_nums: List[int]) -> List[int]:
"""Calculate the result list via the first solution."""
result: List[int] = []
prod: int = reduce(lambda x, y: x * y, nums)
for num in input_nums:
try:
replacement = int(prod / num)
except ZeroDivisionError:
replacement = prod
result.append(replacement)
return result
def solution_2(input_nums: List[int]) -> List[int]:
"""Calculate the result list via the second solution."""
result: List[int] = [1] * len(input_nums)
prod = 1
for i, _ in enumerate(result):
result[i] *= prod
prod *= input_nums[i]
prod = 1
for i in range(len(result) - 1, -1, -1):
result[i] *= prod
prod *= input_nums[i]
return result
nums: List[int] = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(solution_1(nums))
print(solution_2(nums))
nums: List[int] = [2, 3, 4]
print(solution_1(nums))
print(solution_2(nums))
| HomayoonAlimohammadi/Training | DailyProblem/19_6_2022.py | 19_6_2022.py | py | 1,176 | python | en | code | 2 | github-code | 36 | [
{
"api_name": "typing.List",
"line_number": 11,
"usage_type": "name"
},
{
"api_name": "typing.List",
"line_number": 14,
"usage_type": "name"
},
{
"api_name": "functools.reduce",
"line_number": 15,
"usage_type": "call"
},
{
"api_name": "typing.List",
"line_numb... |
788517980 | import os, gtts, PIL, praw, PIL.Image, PIL.ImageDraw, PIL.ImageFont, moviepy.editor, shutil
class program: #the main class
class output: #the class for controlled stdout within the program
outputEnabled = True #controls whether or not to print controlled output lines
def print(string) -> None: #will only print if <program.output.outputEnabled == True>.
if (program.output.outputEnabled):
print (string)
class tts: #the class for text to speech stuff
def makeTTSFile(ttsText, language = 'en') -> str: #this outputs a .mp3 file and returns the path
try:
currentNumberCount = int(str(open('./tts-file-count-number.txt').read()))
except:
currentNumberCount = 1
file = open('./tts-file-count-number.txt', 'w')
file.write(str(currentNumberCount + 1))
file.close()
if ('tmp' not in os.listdir('.')):
os.mkdir('tmp')
filePath = './tmp/{}.mp3'.format(str(currentNumberCount))
textToSpeech = gtts.gTTS(text = str(ttsText), lang = language)
textToSpeech.save(filePath)
return filePath
class reddit: #the class that has the functions and data that has to do with reddit
reddit = praw.Reddit('bot1', user_agent = 'bot1 user agent')
def getRepliesFromTopPost() -> dict: #returns a list of the post's replies sorted by their score
comments = {}
sbmsn = None
for submission in program.reddit.reddit.subreddit('askreddit').hot(limit = 1):
sbmsn = submission
for comment in submission.comments:
try:
isAscii = True
normalChars = [ #I dont know any better way to do this so I had to hardcode it
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '`', '~', '!',
'@', '#', '$', '%', '^', '&', '*', '(', ')', '[', ']', '{', '}',
'|', '\\', '"', "'", ';', ':', ',', '<', '>', '.', '/', '?', ' ',
'-', '_', '+', '=', '\n'
]
for each in str(comment.body): #nested for loop paradise...
if (each.lower() in normalChars):
pass
else:
isAscii = False
if (isAscii):
comments[int(comment.score)] = str(comment.body)
except:
pass
return [comments, sbmsn]
class presets: #the class for the configuration variables
numberOfAskredditCommentsToShow = 10 #will show the top x amount of comments from the post.
class utils:
def asciitize(string):
normalChars = [ #I dont know any better way to do this so I had to hardcode it
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '`', '~', '!',
'@', '#', '$', '%', '^', '&', '*', '(', ')', '[', ']', '{', '}',
'|', '\\', '"', "'", ';', ':', ',', '<', '>', '.', '/', '?', ' ',
'-', '_', '+', '=', '\n'
]
newString = ''
for each in string:
if (each.lower() in normalChars):
pass
else:
each = '?'
newString += each
return newString
class images: #the class that has the functions for generating images
def generateImageWithTextOnIt(text, dimensions = [1920, 1080], bgcolor = 'white', fgcolor = 'black'): #generates an image that can later be stitched into the video
image = PIL.Image.new('RGB', (dimensions[0], dimensions[1]), bgcolor)
text = text.replace('\n', '')
newText = []
tmpText = ''
last = 1
lineWidthInChars = 50 #make the lines 50 characters long each
for each in text: #split the string into 50 characer long segments
last += 1
tmpText = str(tmpText) + str(each)
if (last >= lineWidthInChars):
last = 1
tmpText += '-'
newText.append(tmpText)
tmpText = ''
if (tmpText != ''):
newText.append(tmpText)
if ('tmp' not in os.listdir('.')):
os.mkdir('tmp')
try:
currentNumberCount = int(str(open('./image-file-count-number.txt').read()))
except:
currentNumberCount = 1
file = open('./image-file-count-number.txt', 'w')
file.write(str(currentNumberCount + 1))
file.close()
filePath = './tmp/{}.png'.format(str(currentNumberCount))
textTopYCoordinate = 0 #int(image.size[1] / 4) #there will be no text above this y coordinate
textHeight = int(image.size[1] - textTopYCoordinate)
textHeight /= len(newText)
if (textHeight > (image.size[0] / 30)):
textHeight = int(image.size[0] / 30)
font = PIL.ImageFont.truetype('./utils/default-font.ttf', int(textHeight))
draw = PIL.ImageDraw.Draw(image)
lastYCoord = textTopYCoordinate
for textLine in newText:
textSize = draw.textsize(textLine, font = font)
textCoords = [0, 0]
textCoords[0] = int((image.size[0] - textSize[0]) / 2)
textCoords[1] = int(lastYCoord)
lastYCoord += textSize[1]
if (lastYCoord % 2 == 0):
pass
else:
lastYCoord += 1
image = image.resize((dimensions[0], lastYCoord), PIL.Image.ANTIALIAS)
lastYCoord = textTopYCoordinate
font = PIL.ImageFont.truetype('./utils/default-font.ttf', int(textHeight))
draw = PIL.ImageDraw.Draw(image)
for textLine in newText:
textSize = draw.textsize(textLine, font = font)
textCoords = [0, 0]
textCoords[0] = int((image.size[0] - textSize[0]) / 2)
textCoords[1] = int(lastYCoord)
draw.text(textCoords, textLine, fgcolor, font = font)
lastYCoord += textSize[1]
newImage = PIL.Image.new('RGB', (dimensions[0], dimensions[1]), bgcolor)
'''if (image.size[1] > newImage.size[1]):
aspectRatio = image.size[0] / image.size[1]
newImageSize = [0, 0]
newImageSize[0] = int(newImage.size[0] * aspectRatio)
newImageSize[1] = int(newImage.size[1] / aspectRatio)
image = image.resize((*newImageSize), PIL.Image.ANTIALIAS)'''#fix the resizing method so that the image doesnt overflow on the y axis
newImageCoords = [int((newImage.size[0] - image.size[0]) / 2), int((newImage.size[1] - image.size[1]) / 2)]
newImage.paste(image, newImageCoords)
newImage.save(filePath)
return filePath
program.output.print('Program started.')
program.output.print('Getting the comments from the top askreddit post.')
askRedditCommentList = program.reddit.getRepliesFromTopPost()
commentUpvotesSorted = sorted(askRedditCommentList[0])
commentUpvotesSorted.reverse()
program.output.print(program.utils.asciitize('Found a post titled "{}" with {} upvotes that is in hot.'.format(askRedditCommentList[1].title, askRedditCommentList[1].score)))
if (program.presets.numberOfAskredditCommentsToShow > len(commentUpvotesSorted)):
program.output.print('The number of comments you chose to display was larger than the amount of available comments - <program.presets.numberOfAskredditCommentsToShow> was changed to the max amount of comments and nothing more.')
program.presets.numberOfAskredditCommentsToShow = len(commentUpvotesSorted)
topComments = {}
topCommentsUpvotesSorted = []
iterationStage = 0
while (iterationStage < program.presets.numberOfAskredditCommentsToShow):
topComments[commentUpvotesSorted[iterationStage]] = askRedditCommentList[0][commentUpvotesSorted[iterationStage]]
topCommentsUpvotesSorted.append(commentUpvotesSorted[iterationStage])
iterationStage += 1
ttsFilePathsInOrderOfTopCommentsSortedByUpvotes = [program.tts.makeTTSFile(askRedditCommentList[1].title)] #10/10 file naming :)
iterationStage = 0
for comment in topComments:
iterationStage += 1
program.output.print('Making TTS file {}/{}.'.format(str(iterationStage), str(len(topComments))))
commentText = topComments[comment]
ttsPath = program.tts.makeTTSFile(commentText)
ttsFilePathsInOrderOfTopCommentsSortedByUpvotes.append(ttsPath)
imageFilePathsInOrderOfTopCommentsSortedByUpvotes = [program.images.generateImageWithTextOnIt(askRedditCommentList[1].title, fgcolor = '#9494FF')] #sorry :)
iterationStage = 0
for comment in topComments:
iterationStage += 1
program.output.print('Making image file {}/{}.'.format(str(iterationStage), str(len(topComments))))
imagePath = program.images.generateImageWithTextOnIt(topComments[comment], fgcolor = '#ff4301')
imageFilePathsInOrderOfTopCommentsSortedByUpvotes.append(imagePath)
outputMp4List = []
for each in range(len(imageFilePathsInOrderOfTopCommentsSortedByUpvotes)):
program.output.print('Stitching together audio and video files ({}/{}).'.format(str(each + 1), str(len(imageFilePathsInOrderOfTopCommentsSortedByUpvotes))))
imagePath = imageFilePathsInOrderOfTopCommentsSortedByUpvotes[each]
audioPath = ttsFilePathsInOrderOfTopCommentsSortedByUpvotes[each]
os.system('ffmpeg.exe -loop 1 -i {} -i {} -c:v libx264 -tune stillimage -c:a aac -b:a 192k -pix_fmt yuv420p -shortest ./tmp/out{}.mp4'.format(imagePath, audioPath, str(each)))
outputMp4List.append('./tmp/out{}.mp4'.format(str(each)))
program.output.print('Stitching together the videos.')
videoFileList = []
for each in outputMp4List:
videoFileList.append(moviepy.editor.VideoFileClip(each))
finalVideo = moviepy.editor.concatenate_videoclips(videoFileList)
finalVideo.write_videofile('output.mp4')
program.output.print('Done!')
shutil.rmtree('tmp') | renamedquery/automatic-askreddit-video-maker | video-maker.py | video-maker.py | py | 10,898 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "os.listdir",
"line_number": 18,
"usage_type": "call"
},
{
"api_name": "os.mkdir",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "gtts.gTTS",
"line_number": 21,
"usage_type": "call"
},
{
"api_name": "praw.Reddit",
"line_number": 25,
... |
14918571499 | from pyspark import SparkConf, SparkContext
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
from cassandra.cluster import Cluster
import signal
# if (contents.length > 0 && !contents[0].equalsIgnoreCase("year") && !contents[18].equalsIgnoreCase("1")) {
# String origin = contents[15];
# int delay = (int) (Float.parseFloat(contents[14]));
# String destinationDelay = contents[8] + "_" + delay;
# context.write(new Text(origin), new Text(destinationDelay));
# }
top = []
top_airports_table = "TopAirlinesByAirport"
def get_airport_carrier_delay(content):
data = content[1].split(',')
try:
if len(data) > 0 and not data[0] == 'year' and not data[18] == '1\n':
origin_carrier = data[15] + "_" + data[8]
destination_delay = float(data[14])
return [(origin_carrier, (destination_delay, 1))]
except:
return []
def init_cassandra():
cluster = Cluster(['127.0.0.1'])
return cluster.connect('tp')
def top_complex_average(rdd):
global top
chandle = init_cassandra()
# iterate locally on driver (master) host
curr = rdd.toLocalIterator()
# concat top and curr values
top_dict = dict(top)
total = 0
for el in curr:
total += 1
key = el[0].split('-')[0]
subkey = el[0].split('-')[1]
if key in top_dict:
if subkey in top_dict[key]:
top_dict[key][subkey] = (top_dict[key][subkey][0] + el[1][0], top_dict[key][subkey][1] + el[1][1])
else:
top_dict[key][subkey] = el[1]
else:
top_dict[key] = {subkey: el[1]}
top = top_dict
prepared_stmt = chandle.prepare(
'INSERT INTO {} (airport_name,airline_name) values (?, ?, ?)'.format(top_airports_table))
for origin in top:
carriers = ' '.join(["%s=%0.2f" % (el[0], el[1][0] / el[1][1]) for el in
sorted(top[origin].items(), key=lambda el: el[1][0] / el[1][1])][10])
chandle.execute(prepared_stmt, (origin, carriers))
chandle.shutdown()
def stop_streaming():
global ssc
ssc.stop(stopSparkContext=True, stopGraceFully=True)
def stream_kafka():
global ssc
kstream = KafkaUtils.createDirectStream(ssc, topics=['2008'], kafkaParams={
"metadata.broker.list": 'ip-172-31-12-78.us-west-1.compute.internal:6667'})
contents = kstream.flatMap(get_airport_carrier_delay).reduceByKey(
lambda a, b: (a[0] + b[0], a[1] + b[1])).foreachRDD(top_complex_average)
ssc.start()
ssc.awaitTerminationOrTimeout(15000)
ssc.stop(stopSparkContext=True, stopGraceFully=True)
def main():
global ssc
conf = SparkConf()
conf.setAppName("TopAirports")
conf.set("spark.streaming.kafka.maxRatePerPartition", "0")
conf.set('spark.streaming.stopGracefullyOnShutdown', True)
sc = SparkContext(conf=conf)
ssc = StreamingContext(sc, 1) # Stream every 1 second
ssc.checkpoint("/tmp/checkpoint")
signal.signal(signal.SIGINT, stop_streaming)
stream_kafka()
if __name__ == "__main__":
main()
| karthikBG/AviationAnalytics | SparkStreaming/2.1.TopAirlinesByAirport.py | 2.1.TopAirlinesByAirport.py | py | 3,139 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "cassandra.cluster.Cluster",
"line_number": 31,
"usage_type": "call"
},
{
"api_name": "pyspark.streaming.kafka.KafkaUtils.createDirectStream",
"line_number": 77,
"usage_type": "call"
},
{
"api_name": "pyspark.streaming.kafka.KafkaUtils",
"line_number": 77,
"... |
75006697064 | from .models import TodoModel
from django import forms
class TodoForm(forms.ModelForm):
class Meta:
model = TodoModel
fields = '__all__'
labels ={
'subject':'',
'details':'',
}
widgets = {
'subject': forms.TextInput(attrs={'class': 'form-control bg-info rounded-5 p-3','rows': 2,'cols': 1,'placeholder': 'Enter Subjecct','id': 'id_content' }),
'details': forms.Textarea(attrs={'class': 'form-control bg-info border-0 p-3','rows': 3,'cols': 1,'placeholder': 'Write Details','id': 'id_content' })
} | SalmanMirSharin/Django-ToDo-App | todo/forms.py | forms.py | py | 611 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "django.forms.ModelForm",
"line_number": 5,
"usage_type": "attribute"
},
{
"api_name": "django.forms",
"line_number": 5,
"usage_type": "name"
},
{
"api_name": "models.TodoModel",
"line_number": 7,
"usage_type": "name"
},
{
"api_name": "django.forms.T... |
31012134032 | from django.db import connection
def ingredient_name_and_amount_query(receipt_id):
with connection.cursor() as cursor:
cursor.execute(f"SELECT ingredient_calories.ingredient_name, receipt_ingredient.amount, receipt_ingredient.amount_type \
FROM receipt_ingredient \
Inner Join ingredient_calories on \
receipt_ingredient.ingredient_name_frk_id = ingredient_calories.id \
where receipt_ingredient.recipe_frk_id = %s", (receipt_id,))
rows = cursor.fetchall()
ingredients_of_receipt = []
for row in rows:
ingredient = {"ingredient_name": row[0], "amount": row[1], "amount_type": row[2]}
ingredients_of_receipt.append(ingredient)
return ingredients_of_receipt
# total_receipt_cal_per_100gr:
def total_receipt_cal_per_100gr(receipt_id):
with connection.cursor() as cursor:
cursor.execute(f"select (COALESCE(SUM (ingredient_calories.ingredient_calories_per_100_gr_or_ml), 0) * 100)/COALESCE(SUM(receipt_ingredient.amount),0) \
from receipt_ingredient, ingredient_calories \
WHERE ingredient_calories.id = receipt_ingredient.ingredient_name_frk_id and \
receipt_ingredient.recipe_frk_id = %s \
group by receipt_ingredient.recipe_frk_id", (receipt_id,))
total_cal = cursor.fetchone()[0]
return total_cal
# search_recipe_by_category:
def search_recipe_by_category(category):
with connection.cursor() as cursor:
cursor.execute(f"SELECT recipe.id, recipe.recipe_name, recipe.pic_url \
FROM recipe \
where recipe.recipe_category = %s", (category,))
rows = cursor.fetchall()
all_recipes_by_category = []
for row in rows:
recipe_details = {"recipe_id": row[0], "recipe_name": row[1], "recipe_url": row[2]}
# all_recipes_by_category[row[0]] = recipe_details
all_recipes_by_category.append(recipe_details)
print(all_recipes_by_category)
return all_recipes_by_category
| ravityeho/recipes | recipes_and_more_app/custom_queries.py | custom_queries.py | py | 2,179 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "django.db.connection.cursor",
"line_number": 6,
"usage_type": "call"
},
{
"api_name": "django.db.connection",
"line_number": 6,
"usage_type": "name"
},
{
"api_name": "django.db.connection.cursor",
"line_number": 21,
"usage_type": "call"
},
{
"api_na... |
43418734139 | import findspark
findspark.init()
from operator import add
from pyspark import SparkContext
from pyspark.sql import SparkSession
from pyspark.sql.types import IntegerType
from pyspark.sql import *
if __name__ == "__main__":
spark = SparkSession \
.builder \
.appName("q4") \
.getOrCreate()
sc = SparkContext.getOrCreate()
business = spark.read.format("csv").option("delimiter", ":").load("C:/Users/psait/Desktop/bda/business.csv").toDF("business_id", "tempCol1", "full_address", "tempCol3", "categories").drop("tempCol1", "tempCol3")
review = spark.read.format("csv").option("delimiter", ":").load("C:/Users/psait/Desktop/bda/review.csv").toDF("review_id", "tempCol1", "user_id", "tempCol3", "business_id", "tempCol5", "stars").drop("tempCol1", "tempCol3", "tempCol5", "review_id")
review = review.withColumn("stars", review["stars"].cast(IntegerType()))
jf = business.join(review, "business_id").select("business_id", "full_address", "categories", "stars").groupBy("business_id",
"full_address",
"categories").avg(
"stars");
opframe = jf.toDF("business_id", "full_address", "categories", "avg_rating").sort("avg_rating",ascending = False).take(10)
op = sc.parallelize(list(opframe)).toDF()
final = op.rdd.map(lambda x :str(x[0]) + "\t" + str(x[1]) + "\t" + str(x[2]) + "\t" + str(x[3]))
final.repartition(1).saveAsTextFile("C:/Users/psait/Desktop/bda/q4.txt")
| saitejapeddi/pyspark | q4.py | q4.py | py | 1,671 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "findspark.init",
"line_number": 2,
"usage_type": "call"
},
{
"api_name": "pyspark.sql.SparkSession.builder.appName",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "pyspark.sql.SparkSession.builder",
"line_number": 11,
"usage_type": "attribute"
... |
70786900903 | import copy, re
from django.core import validators
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.utils.deconstruct import deconstructible
from django.utils.translation import gettext_lazy as _
__all__ = ['EmptyValidator', 'KeysValidator', 'MD5ChecksumValidator']
class EmptyValidator(validators.RegexValidator):
regex = r'\S+'
message = _('This field cannot be blank.')
code = 'blank'
@deconstructible
class KeysValidator(object):
"""
A validator designed for HStore to require, even restrict keys.
Code mostly borrowed from:
https://github.com/django/django/blob/master/django/contrib/postgres/validators.py
"""
messages = {
'missing_keys': _('Some keys were missing: %(keys)s'),
'extra_keys': _('Some unknown keys were provided: %(keys)s'),
}
strict = False
def __init__(self, required_keys=None, optional_keys=None, strict=False, messages=None):
self.required_keys = set(required_keys or [])
self.optional_keys = set(optional_keys or [])
if not self.required_keys and not self.optional_keys:
raise ImproperlyConfigured('You must set at least `required_keys` or `optional_keys`')
self.strict = strict
if messages is not None:
self.messages = copy.copy(self.messages)
self.messages.update(messages)
def __call__(self, value):
keys = set(value.keys())
if self.required_keys:
missing_keys = self.required_keys - keys
if missing_keys:
raise ValidationError(
self.messages['missing_keys'],
code='missing_keys',
params={'keys': ', '.join(missing_keys)})
if self.strict:
extra_keys = keys - self.required_keys - self.optional_keys
if extra_keys:
raise ValidationError(
self.messages['extra_keys'],
code='extra_keys',
params={'keys': ', '.join(extra_keys)})
def __eq__(self, other):
return (
isinstance(other, self.__class__)
and self.required_keys == other.required_keys
and self.optional_keys == other.optional_keys
and self.messages == other.messages
and self.strict == other.strict
)
def __ne__(self, other):
return not self == other
class MD5ChecksumValidator(validators.RegexValidator):
regex = re.compile(r'[0-9a-f]{32}')
| davidfischer-ch/pytoolbox | pytoolbox/django/core/validators.py | validators.py | py | 2,541 | python | en | code | 38 | github-code | 36 | [
{
"api_name": "django.core.validators.RegexValidator",
"line_number": 11,
"usage_type": "attribute"
},
{
"api_name": "django.core.validators",
"line_number": 11,
"usage_type": "name"
},
{
"api_name": "django.utils.translation.gettext_lazy",
"line_number": 13,
"usage_type"... |
27884844846 | import sys, os, string, random, psycopg2, sqlite3
from sqlalchemy import Column, ForeignKey, Integer, String, DateTime, Float, Boolean, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker, backref, scoped_session
from sqlalchemy import create_engine
from sqlalchemy.sql import func
from sqlalchemy.sql.sqltypes import TIMESTAMP
Base = declarative_base()
class Users(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key = True)
displayname = Column(String(80), nullable = False)
username = Column(String(80), nullable = False)
password = Column(String(80), nullable = False)
bio = Column(String(250), default = '')
icon_link = Column(String, default = '')
icon_id = Column(String, default = '')
date_created = Column(TIMESTAMP(timezone = True), server_default = func.now())
last_loggedin = Column(TIMESTAMP(timezone = True), server_default = func.now())
last_read_notifications = Column(TIMESTAMP(timezone = True), server_default = func.now())
@property
def serialize(self):
return {
'id': self.id,
'displayname': self.displayname,
'username': self.username,
'bio': self.bio,
'icon_link': self.icon_link,
'icon_id': self.icon_id,
'date_created': str(self.date_created),
'last_loggedin': str(self.last_loggedin),
'last_read_notifications': str(self.last_read_notifications),
}
class Follows(Base):
__tablename__ = 'follows'
id = Column(Integer, primary_key = True)
user_id = Column(Integer, ForeignKey('users.id'))
user_rel = relationship('Users', foreign_keys=[user_id])
follows_id = Column(Integer, ForeignKey('users.id'))
follows_rel = relationship('Users', foreign_keys=[follows_id])
date_created = Column(TIMESTAMP(timezone = True), server_default = func.now())
@property
def serialize(self):
# Returns Data Object In Proper Format
return {
'id': self.id,
'user': self.user_rel.serialize if self.user_rel else None,
'follows': self.follows_rel.serialize if self.follows_rel else None,
'date_created': str(self.date_created),
}
class Posts(Base):
__tablename__ = 'posts'
id = Column(Integer, nullable = False, primary_key = True)
owner_id = Column(Integer, ForeignKey('users.id'))
owner_rel = relationship('Users')
title = Column(String, nullable = False)
body = Column(Text, nullable = False)
hashtags = Column(String, default = '')
date_created = Column(TIMESTAMP(timezone = True), server_default = func.now())
last_updated = Column(TIMESTAMP(timezone = True), server_default = func.now(), onupdate = func.now())
@property
def serialize(self):
return {
'id': self.id,
'owner': self.owner_rel.serialize if self.owner_rel else None,
'title': self.title,
'body': self.body,
'hashtags': self.hashtags,
'hashtags_list': self.hashtags.split(',') if self.hashtags != '' else [],
'date_created': str(self.date_created),
'last_updated': str(self.last_updated),
}
class PostLikes(Base):
__tablename__ = 'post_likes'
id = Column(Integer, nullable = False, primary_key = True)
owner_id = Column(Integer, ForeignKey('users.id'))
owner_rel = relationship('Users')
post_id = Column(Integer, ForeignKey('posts.id'))
post_rel = relationship('Posts')
date_created = Column(TIMESTAMP(timezone = True), server_default = func.now())
@property
def serialize(self):
return {
'id': self.id,
'owner': self.owner_rel.serialize if self.owner_rel else None,
'post_id': self.post_id,
'date_created': str(self.date_created),
}
class Comments(Base):
__tablename__ = 'comments'
id = Column(Integer, nullable = False, primary_key = True)
owner_id = Column(Integer, ForeignKey('users.id'))
owner_rel = relationship('Users')
post_id = Column(Integer, ForeignKey('posts.id'))
post_rel = relationship('Posts')
body = Column(Text, nullable = False)
hashtags = Column(String(80), default = '')
date_created = Column(TIMESTAMP(timezone = True), server_default = func.now())
last_updated = Column(TIMESTAMP(timezone = True), server_default = func.now(), onupdate = func.now())
@property
def serialize(self):
return {
'id': self.id,
'owner': self.owner_rel.serialize if self.owner_rel else None,
'post_id': self.post_id,
'body': self.body,
'hashtags': self.hashtags,
'hashtags_list': self.hashtags.split(',') if self.hashtags != '' else [],
'date_created': str(self.date_created),
'last_updated': str(self.last_updated),
}
class CommentLikes(Base):
__tablename__ = 'comment_likes'
id = Column(Integer, nullable = False, primary_key = True)
owner_id = Column(Integer, ForeignKey('users.id'))
owner_rel = relationship('Users')
comment_id = Column(Integer, ForeignKey('comments.id'))
comment_rel = relationship('Comments')
date_created = Column(TIMESTAMP(timezone = True), server_default = func.now())
@property
def serialize(self):
return {
'id': self.id,
'owner': self.owner_rel.serialize if self.owner_rel else None,
'comment_id': self.comment_id,
'date_created': str(self.date_created),
}
class Messagings(Base):
__tablename__ = 'messagings'
id = Column(Integer, nullable = False, primary_key = True)
user_id = Column(Integer, ForeignKey('users.id'))
user_rel = relationship('Users', foreign_keys=[user_id])
sender_id = Column(Integer, ForeignKey('users.id'))
sender_rel = relationship('Users', foreign_keys=[sender_id])
date_created = Column(TIMESTAMP(timezone = True), server_default = func.now())
last_updated = Column(TIMESTAMP(timezone = True), server_default = func.now(), onupdate = func.now())
@property
def serialize(self):
return {
'id': self.id,
'user': self.user_rel.serialize if self.user_rel else None,
'sender': self.sender_rel.serialize if self.sender_rel else None,
'date_created': str(self.date_created),
'last_updated': str(self.last_updated),
}
class MessagingUserLastOpens(Base):
__tablename__ = 'messaging_user_last_opens'
id = Column(Integer, nullable = False, primary_key = True)
messaging_id = Column(Integer, ForeignKey('messagings.id'))
messaging_rel = relationship('Messagings', foreign_keys=[messaging_id])
user_id = Column(Integer, ForeignKey('users.id'))
user_rel = relationship('Users', foreign_keys=[user_id])
date_created = Column(TIMESTAMP(timezone = True), server_default = func.now())
user_last_opened = Column(TIMESTAMP(timezone = True), server_default = func.now())
@property
def serialize(self):
return {
'id': self.id,
'messaging': self.messaging_rel.serialize if self.messaging_rel else None,
'user_id': self.user_id,
'date_created': str(self.date_created),
'user_last_opened': str(self.user_last_opened),
}
class Messages(Base):
__tablename__ = 'messages'
id = Column(Integer, nullable = False, primary_key = True)
from_id = Column(Integer, ForeignKey('users.id'))
from_rel = relationship('Users', foreign_keys=[from_id])
to_id = Column(Integer, ForeignKey('users.id'))
to_rel = relationship('Users', foreign_keys=[to_id])
body = Column(Text, nullable = False)
read = Column(Boolean, default = False)
date_created = Column(TIMESTAMP(timezone = True), server_default = func.now())
@property
def serialize(self):
return {
'id': self.id,
'body': self.body,
"read": self.read,
'from': self.from_rel.serialize if self.from_rel else None,
'to': self.to_rel.serialize if self.to_rel else None,
'date_created': str(self.date_created),
}
class Notifications(Base):
__tablename__ = 'notifications'
id = Column(Integer, nullable = False, primary_key = True)
from_id = Column(Integer, ForeignKey('users.id'))
from_rel = relationship('Users', foreign_keys=[from_id])
to_id = Column(Integer, ForeignKey('users.id'))
to_rel = relationship('Users', foreign_keys=[to_id])
event = Column(String, nullable = False)
target_type = Column(String, nullable = False)
target_id = Column(String, nullable = False)
read = Column(Boolean, default = False)
date_created = Column(TIMESTAMP(timezone = True), server_default = func.now())
@property
def serialize(self):
return {
'id': self.id,
'from': self.from_rel.serialize if self.from_rel else None,
'to': self.to_rel.serialize if self.to_rel else None,
'event': self.event,
'target_type': self.target_type,
'target_id': self.target_id,
'read': self.read,
'date_created': str(self.date_created),
}
# --- Create Database Session --- #
sqlite_file = "sqlite:///database.db?check_same_thread=False"
db_string = os.environ.get('DATABASE_URL', sqlite_file)
app_state = ''
if db_string[:8] == 'postgres':
app_state = 'production'
print('--- production ---')
else:
app_state = 'development'
print('--- development ---')
engine = create_engine(db_string, echo=True)
Base.metadata.create_all(engine)
Base.metadata.bind = engine
DBSession = sessionmaker(bind = engine)
Scoped_Session = scoped_session(DBSession)
db_session = Scoped_Session()
| ryanwaite28/cmsc-495-project-backend | models.py | models.py | py | 10,173 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "sqlalchemy.ext.declarative.declarative_base",
"line_number": 12,
"usage_type": "call"
},
{
"api_name": "sqlalchemy.Column",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "sqlalchemy.Integer",
"line_number": 17,
"usage_type": "argument"
},
{
... |
73037033705 | import pathlib
import sys
import typing
import flash
import flash.image
import pytorch_lightning
import torch
import torchmetrics
import torchvision
import enpheeph
import enpheeph.injections.plugins.indexing.indexingplugin
CURRENT_DIR = pathlib.Path(__file__).absolute().parent
RESULTS_DIRECTORY = CURRENT_DIR / "results" / "alexnet-cifar10"
WEIGHTS_FILE = RESULTS_DIRECTORY / "weights" / "alexnet-cifar10.pt"
LOG_DIRECTORY = RESULTS_DIRECTORY / "injection_results"
WEIGHTS_FILE.parent.mkdir(parents=True, exist_ok=True)
LOG_DIRECTORY.mkdir(parents=True, exist_ok=True)
CIFAR_DIRECTORY = pathlib.Path("/shared/ml/datasets/vision/") / "CIFAR10"
class AlexNetLightningModule(pytorch_lightning.LightningModule):
def __init__(self, pretrained: bool = True, num_classes: int = 1000) -> None:
super().__init__()
self.num_classes = num_classes
self.pretrained = pretrained
self.model = torchvision.models.AlexNet(num_classes=num_classes)
if self.pretrained:
# must be accessed with sys.modules otherwise it uses the function
# which is imported from the sub-module
# we use type: ignore as mypy cannot check torchvision typings
# we have to split it otherwise black creates problems
mod = sys.modules["torchvision.models.alexnet"]
state_dict = torch.hub.load_state_dict_from_url(
mod.model_urls["alexnet"], # type: ignore[attr-defined]
progress=True,
)
# we must filter the mismatching keys in the state dict
# we generate the current model state dict
model_state_dict = self.model.state_dict()
filtered_state_dict = {
k: v_new
# we select the new value if the dimension is the same as with the old
# one
if v_new.size() == v_old.size()
# otherwise we use the initialized one from the model
else v_old
for (k, v_old), v_new in zip(
model_state_dict.items(),
state_dict.values(),
)
}
self.model.load_state_dict(filtered_state_dict, strict=False)
self.normalizer_fn = torch.nn.Softmax(dim=-1)
self.accuracy_fn = torchmetrics.Accuracy()
self.loss_fn = torch.nn.CrossEntropyLoss()
self.save_hyperparameters()
# we initialize the weights
self.init_weights()
def init_weights(self) -> None:
# this initialization is similar to the ResNet one
# taken from https://github.com/Lornatang/AlexNet-PyTorch/
# @ alexnet_pytorch/model.py#L63
for m in self.modules():
if isinstance(m, torch.nn.Conv2d):
torch.nn.init.kaiming_normal_(
m.weight, mode="fan_out", nonlinearity="relu"
)
if m.bias is not None:
torch.nn.init.constant_(m.bias, 0)
elif isinstance(m, torch.nn.BatchNorm2d):
torch.nn.init.constant_(m.weight, 1)
if m.bias is not None:
torch.nn.init.constant_(m.bias, 0)
elif isinstance(m, torch.nn.Linear):
torch.nn.init.normal_(m.weight, 0, 0.01)
if m.bias is not None:
torch.nn.init.constant_(m.bias, 0)
def forward(self, inpt: torch.Tensor) -> torch.Tensor:
return self.model(inpt)
def configure_optimizers(self) -> torch.optim.Optimizer:
optimizer = torch.optim.SGD(self.parameters(), lr=1e-2)
return optimizer
def inference(
self,
batch: typing.Union[
torch.Tensor,
typing.Dict[flash.core.data.data_source.DefaultDataKeys, torch.Tensor],
],
batch_idx: int,
) -> typing.Dict[str, torch.Tensor]:
# we need to check for the batch to be a flash batch or to be a standard tuple
# as otherwise it may not be compatible
if isinstance(batch, dict):
x = batch.get(flash.core.data.data_source.DefaultDataKeys.INPUT, None)
y = batch.get(flash.core.data.data_source.DefaultDataKeys.TARGET, None)
if x is None or y is None:
raise ValueError("Incompatible input for the batch")
else:
x, y = batch
output = self.forward(x)
return {
"loss": self.loss_fn(output, y),
"accuracy": self.accuracy_fn(self.normalizer_fn(output), y),
}
def training_step(
self,
batch: typing.Union[
torch.Tensor,
typing.Dict[flash.core.data.data_source.DefaultDataKeys, torch.Tensor],
],
batch_idx: int,
) -> torch.Tensor:
res = self.inference(batch, batch_idx)
self.log_dict(
{"train_loss": res["loss"], "train_accuracy": res["accuracy"]},
prog_bar=True,
on_step=True,
on_epoch=True,
logger=True,
)
return res["loss"]
def validation_step(
self,
batch: typing.Union[
torch.Tensor,
typing.Dict[flash.core.data.data_source.DefaultDataKeys, torch.Tensor],
],
batch_idx: int,
) -> None:
res = self.inference(batch, batch_idx)
self.log_dict(
{"val_loss": res["loss"], "val_accuracy": res["accuracy"]},
prog_bar=True,
on_step=True,
on_epoch=True,
logger=True,
)
def test_step(
self,
batch: typing.Union[
torch.Tensor,
typing.Dict[flash.core.data.data_source.DefaultDataKeys, torch.Tensor],
],
batch_idx: int,
) -> None:
res = self.inference(batch, batch_idx)
self.log_dict(
{"test_loss": res["loss"], "test_accuracy": res["accuracy"]},
prog_bar=True,
on_step=True,
on_epoch=True,
logger=True,
)
pytorch_lightning.seed_everything(seed=41, workers=True)
storage_plugin = enpheeph.injections.plugins.storage.SQLiteStoragePlugin(
db_url="sqlite:///" + str(LOG_DIRECTORY / "database.sqlite")
)
pytorch_mask_plugin = enpheeph.injections.plugins.NumPyPyTorchMaskPlugin()
pytorch_handler_plugin = enpheeph.handlers.plugins.PyTorchHandlerPlugin()
monitor_1 = enpheeph.injections.OutputPyTorchMonitor(
location=enpheeph.utils.data_classes.MonitorLocation(
module_name="model.features.0",
parameter_type=enpheeph.utils.enums.ParameterType.Activation,
dimension_index={
enpheeph.utils.enums.DimensionType.Tensor: ...,
enpheeph.utils.enums.DimensionType.Batch: ...,
},
bit_index=None,
),
enabled_metrics=enpheeph.utils.enums.MonitorMetric.StandardDeviation,
storage_plugin=storage_plugin,
move_to_first=False,
indexing_plugin=enpheeph.injections.plugins.indexing.indexingplugin.IndexingPlugin(
dimension_dict=enpheeph.utils.constants.PYTORCH_DIMENSION_DICT,
),
)
fault_1 = enpheeph.injections.OutputPyTorchFault(
location=enpheeph.utils.data_classes.FaultLocation(
module_name="model.features.0",
parameter_type=enpheeph.utils.enums.ParameterType.Weight,
parameter_name="weight",
dimension_index={
enpheeph.utils.enums.DimensionType.Tensor: (
...,
0,
0,
),
enpheeph.utils.enums.DimensionType.Batch: ...,
},
bit_index=[10, 16, 31],
bit_fault_value=enpheeph.utils.enums.BitFaultValue.StuckAtOne,
),
low_level_torch_plugin=pytorch_mask_plugin,
indexing_plugin=enpheeph.injections.plugins.indexing.indexingplugin.IndexingPlugin(
dimension_dict=enpheeph.utils.constants.PYTORCH_DIMENSION_DICT,
),
)
monitor_2 = enpheeph.injections.OutputPyTorchMonitor(
location=enpheeph.utils.data_classes.MonitorLocation(
module_name="model.features.0",
parameter_type=enpheeph.utils.enums.ParameterType.Activation,
dimension_index={
enpheeph.utils.enums.DimensionType.Tensor: ...,
enpheeph.utils.enums.DimensionType.Batch: ...,
},
bit_index=None,
),
enabled_metrics=enpheeph.utils.enums.MonitorMetric.StandardDeviation,
storage_plugin=storage_plugin,
move_to_first=False,
indexing_plugin=enpheeph.injections.plugins.indexing.indexingplugin.IndexingPlugin(
dimension_dict=enpheeph.utils.constants.PYTORCH_DIMENSION_DICT,
),
)
monitor_3 = enpheeph.injections.OutputPyTorchMonitor(
location=enpheeph.utils.data_classes.MonitorLocation(
module_name="model.classifier.1",
parameter_type=enpheeph.utils.enums.ParameterType.Activation,
dimension_index={
enpheeph.utils.enums.DimensionType.Tensor: (slice(10, 100),),
enpheeph.utils.enums.DimensionType.Batch: ...,
},
bit_index=None,
),
enabled_metrics=enpheeph.utils.enums.MonitorMetric.StandardDeviation,
storage_plugin=storage_plugin,
move_to_first=False,
indexing_plugin=enpheeph.injections.plugins.indexing.indexingplugin.IndexingPlugin(
dimension_dict=enpheeph.utils.constants.PYTORCH_DIMENSION_DICT,
),
)
fault_2 = enpheeph.injections.OutputPyTorchFault(
location=enpheeph.utils.data_classes.FaultLocation(
module_name="model.classifier.1",
parameter_type=enpheeph.utils.enums.ParameterType.Activation,
dimension_index={
enpheeph.utils.enums.DimensionType.Tensor: (slice(10, 100),),
enpheeph.utils.enums.DimensionType.Batch: ...,
},
bit_index=...,
bit_fault_value=enpheeph.utils.enums.BitFaultValue.StuckAtOne,
),
low_level_torch_plugin=pytorch_mask_plugin,
indexing_plugin=enpheeph.injections.plugins.indexing.indexingplugin.IndexingPlugin(
dimension_dict=enpheeph.utils.constants.PYTORCH_DIMENSION_DICT,
),
)
monitor_4 = enpheeph.injections.OutputPyTorchMonitor(
location=enpheeph.utils.data_classes.MonitorLocation(
module_name="model.classifier.1",
parameter_type=enpheeph.utils.enums.ParameterType.Activation,
dimension_index={
enpheeph.utils.enums.DimensionType.Tensor: (slice(10, 100),),
enpheeph.utils.enums.DimensionType.Batch: ...,
},
bit_index=None,
),
enabled_metrics=enpheeph.utils.enums.MonitorMetric.StandardDeviation,
storage_plugin=storage_plugin,
move_to_first=False,
indexing_plugin=enpheeph.injections.plugins.indexing.indexingplugin.IndexingPlugin(
dimension_dict=enpheeph.utils.constants.PYTORCH_DIMENSION_DICT,
),
)
injection_handler = enpheeph.handlers.InjectionHandler(
injections=[monitor_1, fault_1, monitor_2, monitor_3, fault_2, monitor_4],
library_handler_plugin=pytorch_handler_plugin,
)
callback = enpheeph.integrations.pytorchlightning.InjectionCallback(
injection_handler=injection_handler,
storage_plugin=storage_plugin,
)
trainer = pytorch_lightning.Trainer(
callbacks=[callback],
deterministic=True,
enable_checkpointing=False,
max_epochs=10,
# one can use gpu but some functions will not be deterministic, so deterministic
# must be set to False
accelerator="cpu",
devices=1,
# if one uses spawn or dp it will fail as sqlite connector is not picklable
# strategy="ddp",
)
model = AlexNetLightningModule(num_classes=10, pretrained=False)
# transform = torchvision.transforms.Compose(
# [
# #torchvision.transforms.ToTensor(),
# torchvision.transforms.Normalize(
# (0.5, 0.5, 0.5),
# (0.5, 0.5, 0.5),
# ),
# torchvision.transforms.RandomHorizontalFlip(),
# ]
# )
cifar_train = torchvision.datasets.CIFAR10(
str(CIFAR_DIRECTORY),
train=True,
download=True,
)
cifar_test = torchvision.datasets.CIFAR10(
str(CIFAR_DIRECTORY),
train=False,
download=True,
)
datamodule = flash.image.ImageClassificationData.from_datasets(
train_dataset=cifar_train,
test_dataset=cifar_test,
val_split=0.2,
num_workers=64,
batch_size=32,
)
if not WEIGHTS_FILE.exists():
trainer.fit(
model,
train_dataloaders=datamodule.train_dataloader(),
val_dataloaders=datamodule.val_dataloader(),
)
trainer.save_checkpoint(str(WEIGHTS_FILE))
model = model.load_from_checkpoint(str(WEIGHTS_FILE))
# no injections/monitors
print("\n\nBaseline, no injection or monitors\n")
trainer.test(
model,
dataloaders=datamodule.test_dataloader(),
)
# we enable only the monitors
# we use this as baseline, no injections
callback.injection_handler.activate([monitor_1, monitor_2, monitor_3, monitor_4])
print("\n\nBaseline, no injection, only monitors\n")
trainer.test(
model,
dataloaders=datamodule.test_dataloader(),
)
# we enable the faults
callback.injection_handler.activate([fault_1, fault_2])
print("\n\nWeight + activation injection\n")
trainer.test(
model,
dataloaders=datamodule.test_dataloader(),
)
# we disable the faults
callback.injection_handler.deactivate([fault_1, fault_2])
print("\n\nBaseline again, no injection, only monitors\n")
# we test again to reach same results as before injection
trainer.test(
model,
dataloaders=datamodule.test_dataloader(),
)
| Alexei95/enpheeph | papers/iros2022/comparisons/tensorfi2/alexnet-cifar10.py | alexnet-cifar10.py | py | 13,471 | python | en | code | 1 | github-code | 36 | [
{
"api_name": "pathlib.Path",
"line_number": 16,
"usage_type": "call"
},
{
"api_name": "pathlib.Path",
"line_number": 24,
"usage_type": "call"
},
{
"api_name": "pytorch_lightning.LightningModule",
"line_number": 27,
"usage_type": "attribute"
},
{
"api_name": "torc... |
9322300717 | # fit a second degree polynomial to the economic data
from numpy import arange,sin,log,tan
from pandas import read_csv
from scipy.optimize import curve_fit
from matplotlib import pyplot
# define the true objective function
def objective(x):
return 0.01006304431397636*sin(0.009997006528342673*x+0.010000006129223197)+0.3065914809778943*x+0.01033913912969194
# load the dataset
url = 'output.csv'
dataframe = read_csv(url, header=None)
data = dataframe.values
# choose the input and output variables
x, y = data[1:, 0], data[1:, -1]
# plot input vs output
pyplot.scatter(x, y)
#convert string to float
x=[float(i) for i in x]
# define a sequence of inputs between the smallest and largest known inputs
x_line = arange(min(x),max(x),1)
# calculate the output for the range
y_line = objective(x_line)
# create a line plot for the mapping function
pyplot.plot(x_line, y_line, color='red')
pyplot.show() | atul1503/curve-fitting | Custom_Function_Graph_Plotter_without_curve_fit.py | Custom_Function_Graph_Plotter_without_curve_fit.py | py | 907 | python | en | code | 0 | github-code | 36 | [
{
"api_name": "numpy.sin",
"line_number": 9,
"usage_type": "call"
},
{
"api_name": "pandas.read_csv",
"line_number": 14,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot.scatter",
"line_number": 19,
"usage_type": "call"
},
{
"api_name": "matplotlib.pyplot"... |
16159941777 | import asyncio
import atexit
import logging
import os
import signal
import subprocess
import time
import supriya.exceptions
logger = logging.getLogger("supriya.server")
class ProcessProtocol:
def __init__(self):
self.is_running = False
atexit.register(self.quit)
def boot(self, options, scsynth_path, port):
...
def quit(self):
...
class SyncProcessProtocol(ProcessProtocol):
### PUBLIC METHODS ###
def boot(self, options, scsynth_path, port):
if self.is_running:
return
options_string = options.as_options_string(port)
command = "{} {}".format(scsynth_path, options_string)
logger.info("Boot: {}".format(command))
self.process = subprocess.Popen(
command,
shell=True,
stderr=subprocess.STDOUT,
stdout=subprocess.PIPE,
start_new_session=True,
)
try:
start_time = time.time()
timeout = 10
while True:
line = self.process.stdout.readline().decode().rstrip()
if line:
logger.info("Boot: {}".format(line))
if line.startswith("SuperCollider 3 server ready"):
break
elif line.startswith("ERROR:"):
raise supriya.exceptions.ServerCannotBoot(line)
elif line.startswith(
"Exception in World_OpenUDP: bind: Address already in use"
):
raise supriya.exceptions.ServerCannotBoot(line)
elif (time.time() - start_time) > timeout:
raise supriya.exceptions.ServerCannotBoot(line)
self.is_running = True
except supriya.exceptions.ServerCannotBoot:
try:
process_group = os.getpgid(self.process.pid)
os.killpg(process_group, signal.SIGINT)
self.process.terminate()
self.process.wait()
except ProcessLookupError:
pass
raise
def quit(self):
if not self.is_running:
return
process_group = os.getpgid(self.process.pid)
os.killpg(process_group, signal.SIGINT)
self.process.terminate()
self.process.wait()
self.is_running = False
class AsyncProcessProtocol(asyncio.SubprocessProtocol, ProcessProtocol):
### INITIALIZER ###
def __init__(self):
ProcessProtocol.__init__(self)
asyncio.SubprocessProtocol.__init__(self)
self.boot_future = None
self.exit_future = None
### PUBLIC METHODS ###
async def boot(self, options, scsynth_path, port):
if self.is_running:
return
self.is_running = False
options_string = options.as_options_string(port)
command = "{} {}".format(scsynth_path, options_string)
logger.info(command)
loop = asyncio.get_running_loop()
self.boot_future = loop.create_future()
self.exit_future = loop.create_future()
_, _ = await loop.subprocess_exec(
lambda: self, *command.split(), stdin=None, stderr=None
)
def connection_made(self, transport):
self.is_running = True
self.transport = transport
def pipe_data_received(self, fd, data):
for line in data.splitlines():
logger.info(line.decode())
if line.strip().startswith(b"Exception"):
self.boot_future.set_result(False)
elif line.strip().startswith(b"SuperCollider 3 server ready"):
self.boot_future.set_result(True)
def process_exited(self):
self.is_running = False
self.exit_future.set_result(None)
if not self.boot_future.done():
self.boot_future.set_result(False)
def quit(self):
if not self.is_running:
return
if not self.boot_future.done():
self.boot_future.set_result(False)
if not self.exit_future.done():
self.exit_future.set_result
if not self.transport._loop.is_closed() and not self.transport.is_closing():
self.transport.close()
self.is_running = False
| MusicAsCode/supriya | supriya/realtime/protocols.py | protocols.py | py | 4,257 | python | en | code | null | github-code | 36 | [
{
"api_name": "logging.getLogger",
"line_number": 11,
"usage_type": "call"
},
{
"api_name": "atexit.register",
"line_number": 17,
"usage_type": "call"
},
{
"api_name": "subprocess.Popen",
"line_number": 36,
"usage_type": "call"
},
{
"api_name": "subprocess.STDOUT"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.