import numpy as np
import pandas as pd
from subprocess import check_output
#print(check_output(["ls", "../input"]).decode("utf8"))
import datetime
import time
destinations = pd.read_csv("../input/destinations.csv")
train1 = pd.read_csv("../input/train.csv", nrows=100000)
test1 = pd.read_csv("../input/test.csv", nrows = 100)
train2 = pd.read_csv("../input/train.csv", nrows=100000)
train3 = pd.read_csv("../input/train.csv", nrows=200002)
train4.info()
train4 = train3.ix[100001:200002,:]
train1["date_time"] = pd.to_datetime(train1["date_time"])
train1["year"] = train1["date_time"].dt.year
train1["month"] = train1["date_time"].dt.month
train1 = train1[train1.is_booking == True]
train4 = train4[train4.is_booking == True]
train4["date_time"] = pd.to_datetime(train4["date_time"])
train4["year"] = train4["date_time"].dt.year
train4["month"] = train4["date_time"].dt.month
from sklearn.decomposition import PCA
X = destinations.ix[:,1:150]
y = destinations.ix[:,0:1]
pca = PCA(n_components=3)
X_r = pca.fit(X).transform(X)
X_r1 = pd.DataFrame(X_r)
X_r1["srch_destination_id"] = destinations["srch_destination_id"]
print('explained variance ratio (first 3 components): %s' % str(pca.explained_variance_ratio_))
def calc_fast_features(df):
    df["date_time"] = pd.to_datetime(df["date_time"])
    df["srch_ci"] = pd.to_datetime(df["srch_ci"], format='%Y-%m-%d', errors="coerce")
    df["srch_co"] = pd.to_datetime(df["srch_co"], format='%Y-%m-%d', errors="coerce")

    props = {}
    for prop in ["month", "day", "hour", "minute", "dayofweek", "quarter"]:
        props[prop] = getattr(df["date_time"].dt, prop)

    carryover = [p for p in df.columns if p not in ["date_time", "srch_ci", "srch_co"]]
    for prop in carryover:
        props[prop] = df[prop]

    date_props = ["month", "day", "dayofweek", "quarter"]
    for prop in date_props:
        props["ci_{0}".format(prop)] = getattr(df["srch_ci"].dt, prop)
        props["co_{0}".format(prop)] = getattr(df["srch_co"].dt, prop)
    props["stay_span"] = (df["srch_co"] - df["srch_ci"]).astype('timedelta64[h]')

    ret = pd.DataFrame(props)

    ret = ret.join(X_r1, on="srch_destination_id", how='left', rsuffix="dest")
    ret = ret.drop("srch_destination_iddest", axis=1)
    return ret
df = calc_fast_features(train2)
df.fillna(-1, inplace=True)
predictors = [c for c in df.columns if c not in ["hotel_cluster"]]
from sklearn import cross_validation
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=10, min_weight_fraction_leaf=0.1)
scores = cross_validation.cross_val_score(clf, df[predictors], df['hotel_cluster'], cv=3)
scores
from sklearn.ensemble import RandomForestClassifier
from sklearn.cross_validation import KFold
from itertools import chain
all_probs = []
unique_clusters = df["hotel_cluster"].unique()
prediction_frame = pd.DataFrame(all_probs).T
prediction_frame.columns = unique_clusters
import ml_metrics as metrics
def find_top_5(row):
    return list(row.nlargest(5).index)
preds = [ ]
for index, row in prediction_frame.iterrows():
    preds.append(find_top_5(row))
metrics.mapk([[l] for l in train4["hotel_cluster"]], preds, k=5)
test1["srch_ci"] = pd.to_datetime(test1["srch_ci"], format='%Y-%m-%d', errors="coerce")
test1["srch_co"] = pd.to_datetime(test1["srch_co"], format='%Y-%m-%d', errors="coerce")
test1["stay_span"] = (test1["srch_co"] - test1["srch_ci"]).astype('timedelta64[D]')
test2 = pd.to_datetime(test1["date_time"])
test2 = pd.DataFrame(test2)
test1['year'] = test2['date_time'].dt.year
test1['month'] = test2['date_time'].dt.month
test1['day_of_week'] = test2['date_time'].dt.dayofweek
test1['day'] = test2['date_time'].dt.day
test1['hour'] = test2['date_time'].dt.hour
test1["date_time"] = pd.to_datetime(test1["date_time"], format='%Y-%m-%d', errors="coerce")
test1["srch_ci"] = pd.to_datetime(test1["srch_ci"], format='%Y-%m-%d', errors="coerce")
test1["search_span"] = (test1["srch_ci"] - test1["date_time"]).astype('timedelta64[D]')
test1.ix[(test1['hour'] >= 10) & (test1['hour'] < 18), 'hour'] = 1
test1.ix[(test1['hour'] >= 18) & (test1['hour'] < 22), 'hour'] = 2
test1.ix[(test1['hour'] >= 22) & (test1['hour'] == 24), 'hour'] = 3
test1.ix[(test1['hour'] >= 1) & (test1['hour'] < 10), 'hour'] = 3
test1 = test1.drop('srch_ci', axis=1)
test1 = test1.drop('srch_co', axis=1)
test1 = test1.drop('date_time', axis=1)
test1.fillna(-1, inplace=True)
test1.info()
metrics.mapk([[l] for l in test1["stay_span"]], preds, k=5)


#SUBS
def criarDatabase(nm):
    dicionario = {}
    dados = open(nm,"r",encoding="utf-8")
    for linha in dados:
        j = linha.strip("\n")
        x = [s for s in j.split("#")]
        dicionario[x[0]] = [float(x[1]),int(x[2]),int(x[3])]
    dados.close()
    return dicionario

def mostrar(produtos):
    print('Lendo produtos...')
    for key in produtos.keys():
        print(f'Código {key}: Preço = {produtos[key][0]} Quantidade = {produtos[key][1]}, Dias restantes de validade = {produtos[key][2]}')
        print('=' * (len(f'Código {key}: Preço = {produtos[key][0]} Quantidade = {produtos[key][1]}, Dias restantes de validade = {produtos[key][2]}')))
    print()

def produtosVencendo(produtos):
    print('Esses produtos irão vencer em menos de uma semana: ')
    for k, v in produtos.items():
        if v[2] < 7:
            print(f'Produto {k}')
    return None

def buscaProduto(nm_cliente, produtos):
    pedidos = open(nm_cliente, 'r')
    for linha in pedidos:
        pedido = linha.strip('\n')

        if pedido in produtos.keys():
            print('_-' * 10, f'Produto {pedido}:', '_-' * 10)
            print(f'R${float(produtos[pedido][0])}')
            print(f'{produtos[pedido][1]} unidades disponiveis.')
            print()
        else:
            print(f'Produto {pedido} INDISPONÍVEL.')
    pedidos.close

#PP
nome_arq = input('Digite o nome do arquivo contendo os produtos: ')
produtos = criarDatabase(nome_arq)

mostrar(produtos)
produtosVencendo(produtos)

nome_cliente = input('Digite o nome do arquivo contendo os pedidos: ')
buscaProduto(nome_cliente, produtos)
print()
print('PROGAMA FINALIZADO')

Laboratório de Resolução de Problemas/temp.py


# %%
from os import path
import struct
import png

from lief import PE

from utils import align, compile, windres

src_dir = path.dirname(__file__)

# %%
# compile origin demo program
compile(path.join(src_dir, 'example.c'), '-m32 -O2 -o example.exe')
binary = PE.parse('example.exe')
print('[+] compile origin demo program success.')

# %%
IMG_PATH = 'packer5-packed.png'
ROW_LEN = 256
with open('example.exe', 'rb') as f:
    arr = []
    content = f.read()
    content = struct.pack('<I', len(content))+content

    for i in range(len(content)//ROW_LEN):
        t = content[i*ROW_LEN:i*ROW_LEN+ROW_LEN]
        arr.append(t)

    img = png.from_array(arr, 'L').save(IMG_PATH)

# %%
windres(path.join(src_dir, 'rsrc.rc'), path.join(src_dir, 'rsrc.o'))
print('[+] compile resource success.')

# %%
# compile shifted loader program
cflags = [
    '-m32',
    '-O2',
    '-Wall',
    '-I.',
    '-Wl,--entry=__start',
    '-nodefaultlibs',
    '-nostartfiles',
    '-lkernel32',
    '-luser32',
    '-lmsvcrt',
    '-lpng',
    '-o',
    'packed.exe'
]
compile([path.join(src_dir, src) for src in ['loader.c', 'png_decode.c', 'rsrc.o']], cflags)
print('[+] compile loader with resource success.')


import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
import statsmodels.api as sm
from statsmodels.stats.outliers_influence import variance_inflation_factor
import scipy.stats as stats
import matplotlib.pyplot as plt
import seaborn as sns

#%% independent variables

path_csv = pd.read_csv('code/video_audio_paths.csv', index_col=0)
video_index = path_csv['orgPath_trun'].notna()
audio_index = path_csv['audio_path'].notna()

text_features = pd.read_csv('code/03-analysis_texts/analysis_texts_results.csv', index_col=0)
text_features['Text-Warmth'] = text_features['warmth'] / text_features['len_tokens']
text_features['Text-Ability'] = text_features['ability'] / text_features['len_tokens']
text_features['Text-Positive'] = text_features['positive'] / text_features['len_tokens']
text_features['Text-Negative'] = text_features['negative'] / text_features['len_tokens']

audio_features = pd.read_csv('code/02-analysis_audio/analysis_audio_results.csv', index_col=0)
audio_features.loc[audio_index, :] = audio_features.loc[audio_index, :].fillna(0)

video_features = pd.read_csv('code/01-analysis_video/analysis_video_results.csv', index_col=0)
video_features.loc[video_index, :] = video_features.loc[video_index, :].fillna(0)
video_features['Video-Positive'] = video_features['happy'] / 100
video_features['Video-Negative'] = video_features[['angry', 'sad', 'fear', 'disgust']].sum(axis=1) / 100

temp = pd.merge(text_features, audio_features, on='realpath')
ind_var = pd.merge(temp, video_features, on='realpath')
ind_var

#%% dependent variables

cover_info = pd.read_excel('kickstarter(total)/1cover&2advertising_page.xlsx')
update_info = pd.read_excel('kickstarter(total)/5update_page.xlsx')

# done_amount
amount = cover_info[['<realpath>', '已筹金额', '目标金额']].copy()
amount.columns = ['realpath', 'done_amount', 'goal_amount']
def remove_nonDigit(s):
    s_prime = ''
    for i in s:
        if i.isnumeric() is True:
            s_prime += i
    return s_prime
amount['done_amount'] = amount['done_amount'].apply(remove_nonDigit)
amount['goal_amount'] = amount['goal_amount'].apply(remove_nonDigit)
amount[['done_amount', 'goal_amount']] = amount[['done_amount', 'goal_amount']].astype(int)
amount['status'] = (amount['done_amount'] >= amount['goal_amount']).astype(int)

# investing population
population = cover_info[['<realpath>', '支持者人数']].copy()
population.columns = ['realpath', 'population']
population['population'] = population['population'].apply(remove_nonDigit)
population['population'] = population['population'].astype(int)

# posterior success
pos_url = cover_info[['<realpath>', '成功项目主页URL']].copy()
pos_url.columns = ['realpath', 'url']
pd.isna(pos_url.iloc[311, 1])
pos_url['pos_suc_url'] = (pos_url['url'].apply(pd.isna)).astype(int)

temp = pd.merge(amount, population, on='realpath')
dep_var = pd.merge(temp, pos_url, on='realpath')
dep_var.columns

#%% control variables

# founder info
founder_csv = pd.read_excel('kickstarter(total)/7founder_page.xlsx')
founder_hist = founder_csv[['<realpath>', '业绩']].copy()
def remove_split(s):
    s_list = s.split()
    nums = []
    for i in s_list:
        if i == 'First':
            nums.append(0)
            continue
        try:
            num = int(i)
            nums.append(num)
        except:
            continue
    return nums
founder_hist['nums'] = founder_hist.iloc[:,1].apply(remove_split)
founder_hist['created_num'] = founder_hist['nums'].apply(lambda x: x[0])
founder_hist['backed_num'] = founder_hist['nums'].apply(lambda x: x[1])
founder_hist = founder_hist.groupby('<realpath>').mean()

founder_coll = founder_csv[['<realpath>', '协作者']].copy()
founder_coll = founder_coll.groupby('<realpath>').count()
founder_coll.columns = ['coll_num']

founder_info = pd.merge(founder_hist, founder_coll, right_index=True, left_index=True)
founder_info = founder_info.reset_index()
founder_info.columns = ['realpath'] + list(founder_info.columns[1:])

# %% summary statistics
temp = pd.merge(dep_var, ind_var, on='realpath')
df_reg = pd.merge(temp, founder_info, on='realpath', how='left')
pitch_features = ['Text-Warmth', 'Text-Ability', 'Text-Positive', 'Text-Negative'
                 , 'Vocal-Arousal', 'Vocal-Valence', 'Vocal-Positive', 'Vocal-Negative'
                 , 'Video-Positive', 'Video-Negative'
                  # control
                 , 'backed_num', 'coll_num', 'len_tokens']
notna_index = ~ df_reg[pitch_features].isnull().T.any()
df_reg = df_reg.loc[notna_index]
with pd.option_context('display.max_rows', 10,
                       'display.max_columns', None,
                       'display.width', 1000,
                       'display.precision', 2,
                       'display.colheader_justify', 'left'):
    display(df_reg[list(dep_var.columns[1:])+pitch_features].describe())
print(df_reg[list(dep_var.columns[1:])+pitch_features].describe().T.to_latex(float_format="%.2f"))

# %% correaltion heatmap
temp = pd.merge(dep_var, ind_var, on='realpath')
df_reg = pd.merge(temp, founder_info, on='realpath', how='left')
pitch_features = ['Text-Warmth', 'Text-Ability', 'Text-Positive', 'Text-Negative'
                 , 'Vocal-Arousal', 'Vocal-Valence', 'Vocal-Positive', 'Vocal-Negative'
                 , 'Video-Positive', 'Video-Negative'
                  # control
                 , 'backed_num', 'coll_num', 'len_tokens']
notna_index = ~ df_reg[pitch_features].isnull().T.any()
df_reg = df_reg.loc[notna_index]

# max min standardization
for i in pitch_features+list(dep_var.columns[1:]):
    max_i = df_reg[i].max()
    min_i = df_reg[i].min()
    df_reg[i] = df_reg[i].apply(lambda x: (x - min_i) / (max_i - min_i))

# correlation
plt.subplots(figsize=(12,12),dpi=1080,facecolor='w')
fig=sns.heatmap(df_reg[pitch_features].corr(),annot=True, vmax=1, square=True, cmap="Blues", fmt='.2g')#annot为热力图上显示数据；fmt='.2g'为数据保留两位有效数字,square呈现正方形，vmax最大值为1
fig

#%% VIF
temp = pd.merge(dep_var, ind_var, on='realpath')
df_reg = pd.merge(temp, founder_info, on='realpath', how='left')
pitch_features = ['Text-Warmth', 'Text-Ability','Text-Positive', 'Text-Negative'
                 , 'Vocal-Valence', 'Vocal-Positive', 'Vocal-Negative'
                 , 'Video-Positive', 'Video-Negative'
                 # control
                 , 'backed_num', 'coll_num', 'len_tokens']
notna_index = ~ df_reg[pitch_features].isnull().T.any()
df_reg = df_reg.loc[notna_index]

# max min standardization
for i in pitch_features:
    max_i = df_reg[i].max()
    min_i = df_reg[i].min()
    df_reg[i] = df_reg[i].apply(lambda x: (x - min_i) / (max_i - min_i))

# multicollinearity
vif = [variance_inflation_factor(df_reg[pitch_features].values, df_reg[pitch_features].columns.get_loc(i)) for i in df_reg[pitch_features].columns]
vif

#%% ultimate dr_reg
temp = pd.merge(dep_var, ind_var, on='realpath')
df_reg = pd.merge(temp, founder_info, on='realpath', how='left')
pitch_features = ['Text-Ability','Text-Positive', 'Text-Negative'
                 , 'Vocal-Positive', 'Vocal-Negative'
                 , 'Video-Positive', 'Video-Negative'
                 # control
                 , 'backed_num', 'coll_num', 'len_tokens']
notna_index = ~ df_reg[pitch_features].isnull().T.any()
df_reg = df_reg.loc[notna_index]

# max min standardization
for i in pitch_features:
    max_i = df_reg[i].max()
    min_i = df_reg[i].min()
    df_reg[i] = df_reg[i].apply(lambda x: (x - min_i) / (max_i - min_i))

#%% OLS regression (status)
X = df_reg[pitch_features]
X_const = sm.add_constant(X)
Y = df_reg[['status']]
result = sm.OLS(Y, X_const).fit()
print(result.summary())
print(result.summary().as_latex())

# %% logistic regression (status)

model = sm.Logit(Y, X_const)
result = model.fit()

print(result.summary())
print(result.summary().as_latex())

#%% OLS regression (population)
X = df_reg[pitch_features]
X_const = sm.add_constant(X)
Y = df_reg[['population']]
result = sm.OLS(Y, X_const).fit()
print(result.summary())
print(result.summary().as_latex())

#%% OLS regression (posterior success)
X = df_reg[pitch_features]
X_const = sm.add_constant(X)
Y = df_reg[['pos_suc_url']]
result = sm.OLS(Y, X_const).fit()
print(result.summary())
print(result.summary().as_latex())

# %% logistic regression (posterior success)

model = sm.Logit(Y, X_const)
result = model.fit()

print(result.summary())
print(result.summary().as_latex())

#%% OLS regression (pledged amount)
X = df_reg[pitch_features]
X_const = sm.add_constant(X)
Y = df_reg[['done_amount']]
result = sm.OLS(Y, X_const).fit()
print(result.summary())
print(result.summary().as_latex())

#%% OLS regression (goal amount)
X = df_reg[pitch_features]
X_const = sm.add_constant(X)
Y = df_reg[['goal_amount']]
result = sm.OLS(Y, X_const).fit()
print(result.summary())
print(result.summary().as_latex())

# %%


def solve(n):
    global cnt, ans,sumv
    if cnt == N:        # 자릿수가 N과 같을시
        if sumv not in lst:     # 원소의 합이 중복되지 않도록 한다.
            lst.append(sumv)
            ans += 1
        return
    for i in range(n,4):
        cnt += 1
        sumv += arr[i]
        solve(i)
        sumv -= arr[i]
        cnt -= 1
N = int(input())    # 로마 숫자 N개 입력
arr=[1,5,10,50] # 로마숫자 배열
cnt = 0 # 함수 solve에서 자릿수가 증가할때마다 cnt를 세다가 cnt==N일 때
lst = []    # 배열 lst에 넣을 예정
sumv = 0 # 그런데 중복되는 값이 있을시엔 lst에 저장 안한다.
ans = 0 # 만들 수 있는 서로 다른 수의 개수 ans
solve(0)    # ans을 세는 함수 solve 실행
print(ans)  # 만들 수 있는 서로 다른 수의 개수 출력

로마 숫자 만들기.py


from collections import defaultdict
import json
from PIL import Image
from nonebot import on_command, on_message, on_notice, on_regex, get_driver
from nonebot.typing import T_State
from nonebot.adapters import Event, Bot
from nonebot.adapters.cqhttp import Message
from aiocqhttp import MessageSegment
import aiohttp, os
from src.libraries.tool import hash
from src.libraries.maimaidx_music import *
from src.libraries.image import *
from src.libraries.maimai_best_40 import generate
from src.zyj import *
import re
import time, datetime
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
import requests, json, time, math

def full(mode, bpitem, ID, module):
    global creator
    page = math.ceil(bpitem / 100)
    item = bpitem - (page - 1) * 100 - 1
    sect = time.time()
    if mode == 'Relax':
        var = 1
    else:
        var = 0

    url = 'http://akatsuki.pw/api/v1/users/scores/' + module + '?mode=0&p=' + str(page) + '&l=100&rx=1&id=' + str(ID)
    url2 = 'https://akatsuki.pw/api/v1/users/full?id=' + str(ID)
    try:
        r = requests.get(url ,timeout = 50)
        r2 = requests.get(url2 , timeout = 50)
    except Exception as e:
        print(e)
        return ("获取api超时，这破网站看脸，要么再来一次？")
    result = json.loads(r.text)
    result2 = json.loads(r2.text)
    scores = result['scores']
    name = result2['username']
    width = 900
    height = 300
    image = Image.new('RGB', (width, height), (255, 255, 255))
    image2 = Image.new('RGB', (900, 250), (0, 0, 0))
    font1 = ImageFont.truetype('akat/arial.ttf', 36)
    font11 = ImageFont.truetype('akat/arial.ttf', 24)
    font12 = ImageFont.truetype('akat/arial.ttf', 12)
    font2 = ImageFont.truetype(r'C:\Users\mercu\Desktop\Eurobot\src\plugins\akat\ARLRDBD.ttf', 150)
    font21 = ImageFont.truetype(r'C:\Users\mercu\Desktop\Eurobot\src\plugins\akat\ARLRDBD.ttf', 36)
    font22 = ImageFont.truetype(r'C:\Users\mercu\Desktop\Eurobot\src\plugins\akat\ARLRDBD.ttf', 24)
    font3 = ImageFont.truetype(r"C:\Users\mercu\Desktop\Eurobot\src\plugins\akat\digifaw.ttf", 32)
    # font4=ImageFont.truetype('GOTHIC.ttf',65)
    font41 = ImageFont.truetype(r"C:\Users\mercu\Desktop\Eurobot\src\plugins\akat\Torus SemiBold.otf", 50)
    url11 = 'https://assets.ppy.sh/beatmaps/'
    setid = str(scores[item]['beatmap']['beatmapset_id'])
    url12 = '/covers/cover.jpg'
    fullurl = url11 + setid + url12
    try:
        url3 = 'https://old.ppy.sh/api/get_beatmaps?k=41a40b9c34b5f28e51c588aa9cba1ea335f6cb24&b=' + str(
            scores[item]['beatmap']['beatmap_id'])
        r3 = requests.get(url3)
        result3 = json.loads(r3.text)
        songname = result3[0]['artist'] + ' - ' + result3[0]['title'] + ' [' + result3[0]['version'] + ']'
        maxcombomap = str(result3[0]['max_combo'])
    except IndexError:
        songname = scores[item]['beatmap']['song_name']
        maxcombomap = str(scores[item]['beatmap']['max_combo'])
    else:
        creator = ' (Beatmap by ' + result3[0]['creator'] + ')'

    try:
        response = requests.get(fullurl)
        response = response.content
        BytesIOOBj = BytesIO()
        BytesIOOBj.write(response)
        img = Image.open(BytesIOOBj)
    except OSError:
        image.paste(image2, (0, 50))
        draw = ImageDraw.Draw(image)
    else:
        img = Image.blend(img, image2, 0.7)
        image.paste(img, (0, 50))
        draw = ImageDraw.Draw(image)

    itemdes = ''
    if module == 'best':
        itemdes = 'Your BP' + str(bpitem) + ' is:'
    elif module == 'recent':
        itemdes = 'Your recent performance (' + str((page - 1) * 100 + item + 1) + ') is:'

    draw.text((10, 8), itemdes, font=font1, fill=(0, 0, 0))
    try:
        draw.text((815 - 9 * len(creator), 9), creator, font=font11, fill=(0, 0, 0))
    except NameError:
        pass
    else:
        pass

    maxcombo = str(scores[item]['max_combo']) + '/'
    count300 = 'x' + str(scores[item]['count_300'])
    count100 = 'x' + str(scores[item]['count_100'])
    count50 = 'x' + str(scores[item]['count_50'])
    countgeki = 'x' + str(scores[item]['count_geki'])
    countkatu = 'x' + str(scores[item]['count_katu'])
    countmiss = 'x' + str(scores[item]['count_miss'])
    playtime = 'Playtime: ' + scores[item]['time']
    acc = str(scores[item]['accuracy']) + '%'
    pp = str(round(scores[item]['pp'], 2)) + 'pp'
    rank = scores[item]['rank']
    beatmapid = 'Beatmap ID: ' + str(scores[item]['beatmap']['beatmap_id'])
    player = 'Player: ' + name
    mods = scores[item]['mods']
    sect2 = time.time() - sect

    if rank == 'A':
        draw.text((10, 100), rank, font=font2, fill=(0, 255, 0))
    elif rank == 'B':
        draw.text((10, 100), rank, font=font2, fill=(0, 0, 255))
    elif rank == 'C':
        draw.text((10, 100), rank, font=font2, fill=(199, 21, 133))
    elif rank == 'SS':
        draw.text((5, 100), 'S', font=font2, fill=(255, 255, 0))
        draw.text((20, 100), 'S', font=font2, fill=(255, 255, 0))
    elif rank == 'SSH':
        draw.text((5, 100), 'S', font=font2, fill=(245, 245, 220))
        draw.text((20, 100), 'S', font=font2, fill=(245, 245, 220))
    elif rank == 'S':
        draw.text((10, 100), 'S', font=font2, fill=(255, 255, 0))
    elif rank == 'SH':
        draw.text((10, 100), 'S', font=font2, fill=(245, 245, 220))
    elif rank == 'D':
        draw.text((10, 100), 'D', font=font2, fill=(255, 0, 0))

    draw.text((120, 55), songname, font=font11, fill=(255, 255, 255))
    draw.text((120, 90), '300', font=font3, fill=(0, 245, 255))
    draw.text((200, 100), count300, font=font11, fill=(255, 255, 255))
    draw.text((350, 90), 'geki', font=font3, fill=(0, 245, 255))
    draw.text((440, 100), countgeki, font=font11, fill=(255, 255, 255))
    draw.text((120, 120), '100', font=font3, fill=(0, 238, 0))
    draw.text((200, 130), count100, font=font11, fill=(255, 255, 255))
    draw.text((350, 120), 'katu', font=font3, fill=(0, 238, 0))
    draw.text((450, 130), countkatu, font=font11, fill=(255, 255, 255))
    draw.text((120, 150), '50', font=font3, fill=(255, 215, 0))
    draw.text((180, 160), count50, font=font11, fill=(255, 255, 255))
    draw.text((350, 150), 'X', font=font21, fill=(255, 0, 0))
    draw.text((380, 160), countmiss, font=font11, fill=(255, 255, 255))

    draw.text((120, 200), beatmapid, font=font11, fill=(255, 255, 255))
    draw.text((120, 230), player, font=font11, fill=(255, 255, 255))
    draw.text((120, 260), playtime, font=font22, fill=(255, 255, 255))

    draw.text((510, 100), acc, font=font41, fill=(255, 255, 255))
    draw.text((510, 200), pp, font=font41, fill=(255, 255, 255))
    draw.text((510, 150), maxcombo + maxcombomap, font=font41, fill=(255, 255, 255))

    if mode == 'Relax':
        modsafter = mods - 128
    else:
        modsafter = mods

    comb = [1, 2, 4, 8, 16, 32, 64, 256, 576, 1024, 4096, 16416]
    comc = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    imgdt = Image.open(r"C:\Users\mercu\Desktop\Eurobot\src\plugins\akat\DT.jpg")
    imgez = Image.open(r"C:\Users\mercu\Desktop\Eurobot\src\plugins\akat\EZ.jpg")
    imgfl = Image.open(r"C:\Users\mercu\Desktop\Eurobot\src\plugins\akat\FL.jpg")
    imghd = Image.open(r"C:\Users\mercu\Desktop\Eurobot\src\plugins\akat\HD.jpg")
    imghr = Image.open(r"C:\Users\mercu\Desktop\Eurobot\src\plugins\akat\HR.jpg")
    imght = Image.open(r"C:\Users\mercu\Desktop\Eurobot\src\plugins\akat\HT.jpg")
    imgnc = Image.open(r"C:\Users\mercu\Desktop\Eurobot\src\plugins\akat\NC.jpg")
    imgso = Image.open(r"C:\Users\mercu\Desktop\Eurobot\src\plugins\akat\SO.jpg")
    imgnf = Image.open(r"C:\Users\mercu\Desktop\Eurobot\src\plugins\akat\NF.png")
    imgtd = Image.open(r"C:\Users\mercu\Desktop\Eurobot\src\plugins\akat\TD.jpg")
    imgsd = Image.open(r"C:\Users\mercu\Desktop\Eurobot\src\plugins\akat\SD.png")
    imgpf = Image.open(r"C:\Users\mercu\Desktop\Eurobot\src\plugins\akat\PF.png")
    imgrx = Image.open(r"C:\Users\mercu\Desktop\Eurobot\src\plugins\akat\RX.png")
    term = 11
    while modsafter > 0:
        if modsafter < comb[term]:
            term -= 1
        else:
            modsafter -= comb[term]
            comc[term] += 1
            term -= 1

    n = 1
    if len(songname) >= 58:
        ycoor = 90
    else:
        ycoor = 50

    if comc[0] == 1:
        image.paste(imgnf, (810, ycoor))
        n += 1
    else:
        pass

    if comc[1] == 1:
        image.paste(imgez, (810 + (n - 1) % 2 * 45, ycoor + (n - 1) // 2 * 45))
        n += 1
    else:
        pass

    if comc[2] == 1:
        image.paste(imgtd, (810 + (n - 1) % 2 * 45, ycoor + (n - 1) // 2 * 45))
        n += 1
    else:
        pass

    if comc[3] == 1:
        image.paste(imghd, (810 + (n - 1) % 2 * 45, ycoor + (n - 1) // 2 * 45))
        n += 1
    else:
        pass

    if comc[4] == 1:
        image.paste(imghr, (810 + (n - 1) % 2 * 45, ycoor + (n - 1) // 2 * 45))
        n += 1
    else:
        pass

    if comc[5] == 1:
        image.paste(imgsd, (810 + (n - 1) % 2 * 45, ycoor + (n - 1) // 2 * 45))
        n += 1
    else:
        pass

    if comc[6] == 1:
        image.paste(imgdt, (810 + (n - 1) % 2 * 45, ycoor + (n - 1) // 2 * 45))
        n += 1
    else:
        pass

    if comc[7] == 1:
        image.paste(imght, (810 + (n - 1) % 2 * 45, ycoor + (n - 1) // 2 * 45))
        n += 1
    else:
        pass

    if comc[8] == 1:
        image.paste(imgnc, (810 + (n - 1) % 2 * 45, ycoor + (n - 1) // 2 * 45))
        n += 1
    else:
        pass

    if comc[9] == 1:
        image.paste(imgfl, (810 + (n - 1) % 2 * 45, ycoor + (n - 1) // 2 * 45))
        n += 1
    else:
        pass

    if comc[10] == 1:
        image.paste(imgso, (810 + (n - 1) % 2 * 45, ycoor + (n - 1) // 2 * 45))
        n += 1
    else:
        pass

    if comc[11] == 1:
        image.paste(imgpf, (810 + (n - 1) % 2 * 45, ycoor + (n - 1) // 2 * 45))
        n += 1
    else:
        pass

    if mode == 'Relax':
        image.paste(imgrx, (810 + (n - 1) % 2 * 45, ycoor + (n - 1) // 2 * 45))
    else:
        pass

    localtime = time.asctime(time.localtime(time.time()))
    stime = "ProcTime:" + str(int(sect2*1000)) + 'ms'
    draw.text((740, 280), localtime, font=font12, fill=(255, 255, 255))
    draw.text((740, 267), stime, font=font12, fill=(255, 255, 255))
    x = int(time.time())
    #image.save(f'{x}.png')
    image.save('result.png')
    return x

# 输出某玩家的bp xx #
def rbp(bpitem, ID):
    y = full('Relax', bpitem, ID, 'best')
    return y

# 输出某玩家的最近 xx 个成绩 #
def rrc(bpitem, ID):
    y = full('Relax', bpitem, ID, 'recent')
    return y

command_rrc = on_command("!rrc")

@command_rrc.handle()
async def _(bot: Bot, event: Event, state: T_State):
    argv = str(event.get_message()).strip().split(" ")
    if len(argv) != 1:
        await command_rrc.finish("指令有误，只能传一个参数 userid 哦！\n 例如 !rrc 4396")
    y = full('Relax', 1, argv[0], 'recent')
    img = Image.open("result.png").convert('RGBA')
    await command_rrc.finish([{
            "type": "image",
            "data": {
                "file": f"base64://{str(image_to_base64(img), encoding='utf-8')}"
            }
        }])

command_rbp = on_command("!rbp")

@command_rbp.handle()
async def _(bot: Bot, event: Event, state: T_State):
    argv = str(event.get_message()).strip().split(" ")
    if len(argv) != 2:
        await command_rbp.finish("指令有误，需要2个参数 <bp*> <userid> 哦！\n 例如 !rbp 1000 4396")
    y = full('Relax', int(argv[0]), int(argv[1]), 'best')
    try:
        img = Image.open("result.png").convert('RGBA')
    except Exception:
        await command_rbp.finish("看起来像是获取失败了哦")
    await command_rbp.finish([{
            "type": "image",
            "data": {
                "file": f"base64://{str(image_to_base64(img), encoding='utf-8')}"
            }
        }])

command_todaybp = on_command("!todaybp")

@command_todaybp.handle()
async def _(bot: Bot, event: Event, state: T_State):
    argv = str(event.get_message()).strip().split(" ")
    if len(argv) != 1:
        await command_rbp.finish("指令有误，需要1个参数 <userid> 哦！\n 例如 !todaybp 4396")
    url0 = 'http://akatsuki.pw/api/v1/users/scores/best?mode=0&p='
    page = 1
    pagestr = str(page)
    url1 = '&l=100&rx=1&id='
    url2 = argv[0]
    url = url0 + pagestr + url1 + url2
    r = requests.get(url)
    result = json.loads(r.text)
    scores = result['scores']
    ticks = int(time.time())
    item = 0
    information = ''
    acc = 0
    pp = 0
    max_combomap = 0
    max_comboyou = 0
    time_span = 86400*2
    f = ''
    f = f + f"在过去的 48h 内，你留了在BP { 100 * (page - 1) + 1} ~ { 100 * page} 之内的以下成绩：\n"
    while item < 100:
        timeset = scores[item]['time']
        timeArray = time.strptime(timeset, "%Y-%m-%dT%H:%M:%SZ")
        timeStamp = int(time.mktime(timeArray))
        if ticks - timeStamp <= time_span + 28800:
            information = scores[item]['beatmap']['song_name']
            acc = scores[item]['accuracy']
            pp = scores[item]['pp']
            max_combomap = scores[item]['beatmap']['max_combo']
            max_comboyou = scores[item]['max_combo']
            miss = scores[item]["count_miss"]
            f = f + f"#{item + 1 + 100 * (page - 1)} : {information} \n [ {acc} % / {max_comboyou}x / {miss} miss / {pp}pp ]\n"
            item += 1
        else:
            item += 1
    f = f + f"Generated By Eurobot & Murmurtwins @{datetime.datetime.now()}"
    await command_todaybp.finish(Message([{
            "type": "image",
            "data": {
                "file": f"base64://{str(image_to_base64(text_to_image(f)), encoding='utf-8')}"
                }
        }]))

def firstcount(ID):
	url = 'https://akatsuki.pw/api/v1/users/scores/first?mode=0&p=1&l=100&rx=1&id=' + str(ID)
	url2 = 'https://akatsuki.pw/api/v1/users/full?id=' + str(ID)
	r = requests.get(url)
	r2 = requests.get(url2)
	result = json.loads(r.text)
	result2 = json.loads(r2.text)
	totalcount = result['total']
	name = result2['username']
	if totalcount > 0:
		msg = '玩家 ' + name + ' 在 Akatsuki 服 RX 模式下目前有 ' + str(totalcount) + ' 个 #1'
	else:
		msg = '玩家 ' + name + ' 在 Akatsuki 服 RX 模式下目前没有 #1，继续努力吧少年'
	return msg

command_first = on_command("!first")

@command_first.handle()
async def _(bot: Bot, event: Event, state: T_State):
    argv = str(event.get_message()).strip().split(" ")
    if len(argv) != 1:
        await command_rbp.finish("指令有误，需要1个参数 <userid> 哦！\n 例如 !first 4396")
    f = firstcount(argv[0])
    await command_first.finish(f)

def search_user(username):
	url = 'https://akatsuki.pw/api/v1/users/whatid?name=' + str(username)
	r = requests.get(url)
	result = json.loads(r.text)
	code_num = result['code']
	if code_num == 404:
		msg = '没有符合查找条件的用户！'
		return msg
	elif code_num == 200:
		id = result['id']
		msg = '用户 ' + str(username) + ' 的 ID 为 ' + str(id)
		return msg

command_name = on_command("!name")

@command_name.handle()
async def _(bot: Bot, event: Event, state: T_State):
    argv = str(event.get_message()).strip().split(" ", 0)
    print(argv)
    id = search_user(argv[0])
    await command_name.finish(id)


import cProfile
import pstats

from random import randint
from time import sleep

def fibonacci(n):
    print('.', end='')
    if n < 0:
        print("Incorrect input")
    # First Fibonacci number is 0
    elif n == 1:
        return 0
    # Second Fibonacci number is 1
    elif n == 2:
        return 1
    else:
        return fibonacci(n - 1) + fibonacci(n - 2)

def calculate(n):
    print('In calculate')
    for _ in range(0, n):
        fibonacci(randint(10,30))
        sleep(0.5)
        print()
    print('Done calculate')

def main():
    print('In main')
    cProfile.run('calculate(5)')
    cProfile.run('calculate(5)', 'profile_results.profile')
    print('Done')

print('Running cProfile')
main()
print('Done profiling')

p = pstats.Stats('profile_results.profile')
p.strip_dirs().sort_stats('time').print_stats()


# # Linear Regression

# ## Importing the libraries

# In[61]:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import linear_model
import seaborn as sns
sns.set()
from sklearn.model_selection import train_test_split

# ## Importing the data and preprocessing

# In[62]:

# Importing the dataset
dataset = pd.read_csv('C:/Users/Harry/Desktop/Analytics/TSLA_stock.csv')
X = dataset.iloc[:, :1].values
y = dataset.iloc[:, 4:5].values

# Splitting the dataset into the Training set and Test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)

#View the data
dataset.head()

# ## Choosing the model

# In[63]:

from sklearn.linear_model import LinearRegression

regressor = linear_model.LinearRegression()

# ## Fitting the model and predicting the result

# In[79]:

# Fitting Simple Linear Regression to the Training set
regressor.fit(X_train, y_train)

# Predicting the Test set results
y_pred = regressor.predict(X_test)

# ## Checking the accuracy of the model

# In[80]:

acc = regressor.score(X_test, y_test)
print("Accuracy: " + str(acc))

# ## Plotting the graph

# In[83]:

plt.rcParams["figure.figsize"] = (20,8)
plt.scatter(X_train, y_train, color = 'red', label="Actual")
plt.plot(X_test,y_pred, color='blue', label="Linear Regression")

plt.title('Tesla Stock Prices 2015-Today')
plt.xlabel('Days')
plt.ylabel('Close Price')
plt.legend()
plt.show()


import csv
import datetime
import os.path
import json
from os import listdir

# directory of tsv files
inputdir = os.path.join(os.getcwd(), 'inputfiles')

# Input start date from the user
startDateInput = input("Enter start date in the format yyyy/mm/dd: ")
startDateInputArray = startDateInput.split("/")
startDate = datetime.datetime(int(startDateInputArray[0]), int(startDateInputArray[1]), int(startDateInputArray[2]))

# check if target directory exists, else create one
os.chdir('../mysite/dataengineering/static/dataengineering')
targetdir = os.getcwd()
if os.path.isdir(targetdir) is False:
    print("target directory does not exist.")
    exit(1)

last_day = 0
# create map of file names and the number of records
dict = {}
# read data from .tsv files
for filename in listdir(inputdir):
    print('Reading data from file', filename)
    tsv_file = open(os.path.join(inputdir, filename), 'r')
    read_tsv = csv.reader(tsv_file, delimiter="\t")

    # skip the headers
    next(read_tsv, None)
    for row in read_tsv:
        if row[2] is None:
            continue
        recordDate = datetime.datetime.strptime(row[2], '%d-%b-%y')
        diff = (recordDate - startDate).days + 1
        last_day = max(last_day, diff)
        count = dict.get(diff, 0)
        dict[diff] = count+1
    tsv_file.close()

print('Data Read Completed from tsv files. Comparing now with json files..')
for key in range(1, last_day+1):
    targetfile = os.path.join(targetdir, 'day' + str(key) + '.json')
    # read data from file in json format
    with open(targetfile, 'r') as jsonfile:
        j = json.load(jsonfile)
        records_in_json_file = len(j)
        records_in_tsv = dict.get(key, 0)
        if records_in_json_file != records_in_tsv:
            print("day {0} missing {1} records".format(key, abs(records_in_json_file - records_in_tsv)))

print("All Files checked successfully!")


from django.shortcuts import render
from main.models import Message
from django.contrib.auth.decorators import login_required, user_passes_test
from main.forms import MessageForm
from django.http import HttpResponse

import user_auth
from user_auth import is_admin

@login_required
def front(request):

    # posts = Post.objects.all().order_by('-date_posted')

    context = {}

    if request.method == 'POST':

        # id = request.POST.get('id')

        # if id:

        #     message = Message.objects.get(id=id)
        #     form = PostForm(request.POST, request.FILES, instance=post)

        # else:

        form = MessageForm(request.POST)

        if is_admin(request.user):
            context['permission'] = 'is_admin'

        if form.is_valid():
            message = form.save()
            context['result'] = 'Your post has been saved'
        else:
            context['result'] = form.errors

    return render(request, 'index.html', context)

@login_required
def all_messages(request):
    context = {}
    messages = Message.objects.all().order_by('-date_posted')
    context['messages'] = messages

    if is_admin(request.user):
            context['permission'] = 'is_admin'

    return render(request, 'all_messages.html', context)

def edit_message(request, id):

    if request.method == 'DELETE':

        if request.user.is_superuser or is_admin(request.user):

            Message.objects.get(id=id).delete()

            return HttpResponse(status=204)
        else:
            return HttpResponse(status=401)

    elif request.method == 'GET':
        message = Message.objects.get(id=id)

        return render(request, 'message.html', {'message': message})


from odoo import api, fields, models

class AccountPaymentMethod(models.Model):
    _inherit = "account.payment.method"

    code = fields.Char(
        string="Code (Do Not Modify)",
        help="This code is used in the code of the Odoo module that handles "
        "this payment method. Therefore, if you change it, "
        "the generation of the payment file may fail.",
    )
    active = fields.Boolean(default=True)
    bank_account_required = fields.Boolean(
        help="Activate this option if this payment method requires you to "
        "know the bank account number of your customer or supplier."
    )
    payment_mode_ids = fields.One2many(
        comodel_name="account.payment.mode",
        inverse_name="payment_method_id",
        string="Payment modes",
    )

    @api.depends("code", "name", "payment_type")
    def name_get(self):
        result = []
        for method in self:
            result.append(
                (
                    method.id,
                    "[{}] {} ({})".format(
                        method.code, method.name, method.payment_type
                    ),
                )
            )
        return result

    _sql_constraints = [
        (
            "code_payment_type_unique",
            "unique(code, payment_type)",
            "A payment method of the same type already exists with this code",
        )
    ]


# https://leetcode.com/problems/median-of-two-sorted-arrays/
# tags: #array, #binary_search, #divide_and_conquer
#
# Optimal solution (if you dare):
# https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2481/Share-my-O(log(min(mn)))-solution-with-explanation
#
# Solution: Find the median by traversing
# Time Complexity: O(m+n), Space complexity: O(1)
from typing import List

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        n, m = len(nums1), len(nums2)
        ia, ma, ib, mb = 0, 0, 0, 0

        for i in range((n + m) // 2 + 1):
            ma = mb

            if ia == n:
                mb = nums2[ib]
                ib += 1
            elif ib == m:
                mb = nums1[ia]
                ia += 1
            elif nums1[ia] < nums2[ib]:
                mb = nums1[ia]
                ia += 1
            else:  # nums1[ia] >= nums2[ib]
                mb = nums2[ib]
                ib += 1

        if (n + m) % 2 == 0:
            return (ma + mb) / 2

        return mb

if __name__ == "__main__":
    sol = Solution()
    print(sol.findMedianSortedArrays(nums1=[1, 2], nums2=[3, 4]))  # 2.5


f=open("complete.csv","r")
st={}
dict={}
for lines in f:
    data = lines.rstrip("\n").split(",")
    state=data[1]
    total=data[4]
    death=data[5]
    recover=data[6]
    if state not in st:
        st[state]={"state":state,"total":total,"death":death,"recover":recover}
def fetchData(**kwargs):
    state=kwargs["state"]
    dict={}
    re={}
    de={}
    totalconfirm=0
    totalrecovered=0
    totaldeath=0
    par=kwargs["param"]
    if state not in st:
        print("Doesnot exist")
    else:
        if state not in dict:
            dict[state] = total
        else:
            dict[state] = total
        for k, v in dict.items():
            totalconfirm = totalconfirm + int(v)
        print("Total confirmed Cases in ",state,"is",totalconfirm)
        if "param" in kwargs:
            if par=="recovered":
                if state in re:
                    re[state]=recover
                else:
                    re[state]=recover
                for k, v in re.items():
                    totalrecovered = totalrecovered + int(v)

                print("total recovered Cases:",totalrecovered)
            if par=="death":
                if state in de:
                    de[state]=death
                else:
                    de[state]=death
                for k, v in de.items():
                    totaldeath = totaldeath + int(v)
                print("Total Death in",state,"is",totaldeath)

fetchData(state="Kerala",param="death")


import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.config import Config
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.dropdown import DropDown
from kivy.uix.textinput import TextInput
from kivy.clock import Clock
from kivy.uix.popup import Popup
from kivy.uix.scrollview import ScrollView
import sqlite3

lijst_dagen = []
dagen_popup = []

#Verschillende schermen benoemen
class Navbar(Screen):
    pass
class Dashboard(Screen):
    pass
class Planning(Screen):
    pass
class Schoolwerk(Screen):
    def on_enter(self):
        pw_lijst = Scorro.show_proefwerken(self)
        self.ids.BoxHwPw.clear_widgets()
        for item in pw_lijst:
            replace = str(item).replace("(", "")
            replace = replace.replace(")", "")
            replace = replace.replace("'", "")
            button = Button(text=str(replace))
            self.ids.BoxHwPw.add_widget(button)

        hw_lijst = Scorro.show_huiswerk(self)
        for item in hw_lijst:
            replace = str(item).replace("(", "")
            replace = replace.replace(")", "")
            replace = replace.replace("'", "")
            button = Button(text=str(replace))
            self.ids.BoxHwPw.add_widget(button)

class PopupVak(Popup):
    def on_open(self):
        dagen_popup.clear()
        naam = self.title.split(" - ")[0]

        conn = sqlite3.connect('ScorroDB.db')
        c = conn.cursor()

        c.execute(f"SELECT * FROM vakken WHERE naam = '{naam}'")
        records = c.fetchall()

        conn.commit()
        conn.close()

        colour_selec = (0,1,0,1)
        colour_deselec = (1,0,0,1)

        try:
            dagen = records[0][1].replace("[", "").replace("]", "").replace(" ", "").replace("'", "").split(",")
            for dag in dagen:
                dagen_popup.append(dag)

            for dag in dagen_popup:
                self.ids[dag].background_color = colour_selec
        except:
            print("Geen dagen gevonden")

    def Savedag(self, dag):
        colour_selec = (0,1,0,1)
        colour_deselec = (1,0,0,1)
        if dag in dagen_popup:
            dagen_popup.remove(dag)
            self.ids[dag].background_color = colour_deselec
        else:
            dagen_popup.append(dag)
            self.ids[dag].background_color = colour_selec

    def OW_klas(self):
        text = self.ids.naam_vakAP.text
        old_name = self.title.split(" - ")[0]

        if dagen_popup != []:
            if text != "":
                conn = sqlite3.connect('ScorroDB.db')
                c = conn.cursor()

                dagen = str(dagen_popup)
                c.execute("""UPDATE vakken SET
                    naam = :naam,
                    dag = :dag
                    WHERE naam = :old_name""",
                    {
                    'naam': text,
                    'dag': str(dagen_popup),
                    'old_name': old_name,
                })

                conn.commit()
                conn.close()
                print("vak opgeslagen")

                dagen_popup.clear()

                vakken_screen = App.get_running_app().root.get_screen("vakken").ids.BoxVakken
                for vak in vakken_screen.children:
                    if vak.text == old_name:
                        vak.text = text

                sorted_buttons = sorted(vakken_screen.children, key=lambda x: x.text)
                vakken_screen.clear_widgets()
                for button in sorted_buttons:
                    vakken_screen.add_widget(button)
            else:
                print("Geen tekst")
        else:
            print("Geen dagen")

    def verwijderKlas(self):
        naam = self.title.split(" - ")[0]

        conn = sqlite3.connect('ScorroDB.db')
        c = conn.cursor()

        c.execute(f"DELETE FROM vakken WHERE naam = '{naam}'")

        conn.commit()
        conn.close()

        vakken_screen = App.get_running_app().root.get_screen("vakken").ids.BoxVakken

        for vak in vakken_screen.children:
            if vak.text == naam:
                vakken_screen.remove_widget(vak)

class Vakken(Screen):
    def popupVak(self, naam):
        popup = PopupVak(title=f"{naam} - vak aanpassen")
        popup.ids.naam_vakAP.text = naam
        popup.open()

    def on_enter(self):
        window_size = int(Window.size[1]) / 10
        vakken_lijst = Scorro.show_klassen(self)
        self.ids.BoxVakken.clear_widgets()

        for vak in vakken_lijst:
            button = Button(text=str(vak[0]), size_hint_y=None, height=window_size)
            button.bind(on_press=lambda button: self.popupVak(button.text))
            self.ids.BoxVakken.add_widget(button)

        sorted_buttons = sorted(self.ids.BoxVakken.children, key=lambda x: x.text)
        self.ids.BoxVakken.clear_widgets()
        for button in sorted_buttons:
            self.ids.BoxVakken.add_widget(button)

class Cijfers(Screen):
    def on_enter(self):
        print(Scorro.show_cijfers(self))

class NieuwHuiswerk(Screen):
    def spinnerHW_clicked(self):
        data = Scorro.show_klassen(self)
        spinner = self.ids.kiesvakHW
        spinner.values = [str(item[0]) for item in data]

class NieuwProefwerk(Screen):
    def spinnerPW_clicked(self):
        data = Scorro.show_klassen(self)
        spinner = self.ids.kiesvakPW
        spinner.values = [str(item[0]) for item in data]

class NieuwCijfer(Screen):
    def spinnerCF_clicked(self):
        data = Scorro.show_klassen(self)
        spinner = self.ids.kiesvakCF
        spinner.values = [str(item[0]) for item in data]

class NieuwVak(Screen):
    def on_enter(self):
        for item in lijst_dagen:
            lijst_dagen.remove(item)
        self.ids.maandag.background_color = (1,0,0,1)
        self.ids.dinsdag.background_color = (1,0,0,1)
        self.ids.woensdag.background_color = (1,0,0,1)
        self.ids.donderdag.background_color = (1,0,0,1)
        self.ids.vrijdag.background_color = (1,0,0,1)
        self.ids.zaterdag.background_color = (1,0,0,1)
        self.ids.zondag.background_color = (1,0,0,1)

    def hide_message(self):
        self.ids.BoxMessage.remove_widget(self.ids.BoxMessage.children[0])

    def SavedVak(self):
        text = self.ids.naam_vak.text
        if lijst_dagen != []:
            if text != "":
                message = Label(text="Vak opgeslagen!")
                self.ids.BoxMessage.add_widget(message)
                Clock.schedule_once(lambda x: self.hide_message(), 1.5)

    def Savedag(self, dag):
        colour_selec = (0,1,0,1)
        colour_deselec = (1,0,0,1)
        if dag in lijst_dagen:
            lijst_dagen.remove(dag)
            self.ids[dag].background_color = colour_deselec
        else:
            lijst_dagen.append(dag)
            self.ids[dag].background_color = colour_selec

class CijferBerekenen(Screen):
    pass

class WindowManager(ScreenManager):
    pass

class Scorro(App):
    def build(self):
        self.icon = "Images/Logo.png"

        conn = sqlite3.connect('ScorroDB.db')
        c = conn.cursor()

        c.execute("""CREATE TABLE if not exists vakken(
            naam text,
            dag text)
        """)

        c.execute("""CREATE TABLE if not exists cijfers(
            cijfer text,
            weging text,
            beschrijving text,
            vak text)
        """)

        c.execute("""CREATE TABLE if not exists proefwerken(
            naam text,
            datum text,
            beschrijving text,
            vak text)
        """)

        c.execute("""CREATE TABLE if not exists huiswerk(
            naam text,
            datum text,
            beschrijving text,
            vak text)
        """)

        conn.commit()
        conn.close()

        kv = Builder.load_file('testdl.kv')
        return kv

    #functies voor klassen
    def submit_klas(self):
        global lijst_dagen
        text = self.root.get_screen('nieuw vak').ids.naam_vak.text
        if lijst_dagen != []:
            if text != "":
                #connect to database
                conn = sqlite3.connect('ScorroDB.db')
                c = conn.cursor()

                c.execute("INSERT INTO vakken VALUES (:naam, :dag)",
                {
                    'naam': self.root.get_screen('nieuw vak').ids.naam_vak.text,
                    'dag': str(lijst_dagen),
                })

                conn.commit()
                conn.close()

                #reset buttons
                lijst_dagen = []
                self.root.get_screen('nieuw vak').ids.maandag.background_color = (1,0,0,1)
                self.root.get_screen('nieuw vak').ids.dinsdag.background_color = (1,0,0,1)
                self.root.get_screen('nieuw vak').ids.woensdag.background_color = (1,0,0,1)
                self.root.get_screen('nieuw vak').ids.donderdag.background_color = (1,0,0,1)
                self.root.get_screen('nieuw vak').ids.vrijdag.background_color = (1,0,0,1)
                self.root.get_screen('nieuw vak').ids.zaterdag.background_color = (1,0,0,1)
                self.root.get_screen('nieuw vak').ids.zondag.background_color = (1,0,0,1)

                self.root.get_screen('nieuw vak').ids.naam_vak.text = ''
                print("vak opgeslagen")

            else:
                print("Geen tekst")
        else:
            print("Geen dagen")

    def show_klassen(self):
        conn = sqlite3.connect('ScorroDB.db')
        c = conn.cursor()

        c.execute("SELECT * FROM vakken")
        records = c.fetchall()

        conn.commit()
        conn.close()

        return records

    #functies voor cijfers
    def submit_cijfer(self):
        naam = self.root.get_screen('nieuw cijfer').ids.welkCF.text
        weging = self.root.get_screen('nieuw cijfer').ids.wegingCF.text
        vak = self.root.get_screen('nieuw cijfer').ids.kiesvakCF.text
        if naam != "":
            if weging != "":
                if vak != "Selecteer een vak":
                    conn = sqlite3.connect('ScorroDB.db')
                    c = conn.cursor()

                    c.execute("INSERT INTO cijfers VALUES (:cijfer, :weging, :beschrijving, :vak)",
                    {
                        'cijfer': self.root.get_screen('nieuw cijfer').ids.welkCF.text,
                        'weging': self.root.get_screen('nieuw cijfer').ids.wegingCF.text,
                        'beschrijving': self.root.get_screen('nieuw cijfer').ids.infoCF.text,
                        'vak': self.root.get_screen('nieuw cijfer').ids.kiesvakCF.text,
                    })

                    self.root.get_screen('nieuw cijfer').ids.welkCF.text = ''
                    self.root.get_screen('nieuw cijfer').ids.wegingCF.text = ''
                    self.root.get_screen('nieuw cijfer').ids.infoCF.text = ''
                    self.root.get_screen('nieuw cijfer').ids.kiesvakCF.text = 'Selecteer een vak'

                    conn.commit()
                    conn.close()
                else:
                    print("Selecteer een vak")
            else:
                print("Geef je cijfer een weging")
        else:
            print("Geef je cijfer")

    def show_cijfers(self):
        conn = sqlite3.connect('ScorroDB.db')
        c = conn.cursor()

        c.execute("SELECT * FROM cijfers")
        records = c.fetchall()

        conn.commit()
        conn.close()
        return records

    #functies voor proefwerken
    def submit_proefwerk(self):
        naam = self.root.get_screen('nieuw proefwerk').ids.welkPW.text
        datum = self.root.get_screen('nieuw proefwerk').ids.datumPW.text
        vak = self.root.get_screen('nieuw proefwerk').ids.kiesvakPW.text
        if naam != "":
            if datum != "":
                if vak != "Selecteer een vak":
                    conn = sqlite3.connect('ScorroDB.db')
                    c = conn.cursor()

                    c.execute("INSERT INTO proefwerken VALUES (:naam, :datum, :beschrijving, :vak)",
                    {
                        'naam': self.root.get_screen('nieuw proefwerk').ids.welkPW.text,
                        'datum': self.root.get_screen('nieuw proefwerk').ids.datumPW.text,
                        'beschrijving': self.root.get_screen('nieuw proefwerk').ids.infoPW.text,
                        'vak': self.root.get_screen('nieuw proefwerk').ids.kiesvakPW.text,
                    })

                    self.root.get_screen('nieuw proefwerk').ids.welkPW.text = ''
                    self.root.get_screen('nieuw proefwerk').ids.datumPW.text = ''
                    self.root.get_screen('nieuw proefwerk').ids.infoPW.text = ''
                    self.root.get_screen('nieuw proefwerk').ids.kiesvakPW.text = 'Selecteer een vak'

                    conn.commit()
                    conn.close()
                else:
                    print("Selecteer een vak")
            else:
                print("Geef je proefwerk een datum")
        else:
            print("Geef je proefwerk een naam")

    def show_proefwerken(self):
        conn = sqlite3.connect('ScorroDB.db')
        c = conn.cursor()

        c.execute("SELECT * FROM proefwerken")
        records = c.fetchall()

        conn.commit()
        conn.close()
        return records

    #functies voor huiswerk
    def submit_huiswerk(self):
        naam = self.root.get_screen('nieuw huiswerk').ids.welkHW.text
        datum = self.root.get_screen('nieuw huiswerk').ids.datumHW.text
        vak = self.root.get_screen('nieuw huiswerk').ids.kiesvakHW.text
        if naam != "":
            if datum != "":
                if vak != "Selecteer een vak":
                    conn = sqlite3.connect('ScorroDB.db')
                    c = conn.cursor()

                    c.execute("INSERT INTO huiswerk VALUES (:naam, :datum, :beschrijving, :vak)",
                    {
                        'naam': self.root.get_screen('nieuw huiswerk').ids.welkHW.text,
                        'datum': self.root.get_screen('nieuw huiswerk').ids.datumHW.text,
                        'beschrijving': self.root.get_screen('nieuw huiswerk').ids.infoHW.text,
                        'vak': self.root.get_screen('nieuw huiswerk').ids.kiesvakHW.text,
                    })

                    self.root.get_screen('nieuw huiswerk').ids.welkHW.text = ''
                    self.root.get_screen('nieuw huiswerk').ids.datumHW.text = ''
                    self.root.get_screen('nieuw huiswerk').ids.infoHW.text = ''
                    self.root.get_screen('nieuw huiswerk').ids.kiesvakHW.text = 'Selecteer een vak'

                    conn.commit()
                    conn.close()
                else:
                    print("Selecteer een vak")
            else:
                print("Geef je toets een datum")
        else:
            print("Geef je toets een naam")

    def show_huiswerk(self):
        conn = sqlite3.connect('ScorroDB.db')
        c = conn.cursor()

        c.execute("SELECT * FROM huiswerk")
        records = c.fetchall()

        conn.commit()
        conn.close()
        return records

Window.size = (350, 600)

if __name__ == "__main__":
    Scorro().run()


from tkinter import *

import math

first_num=second_num=operater=None

#   Function of Digit
def get_digit(digit):
    current=result_label['text']
    new=current+str(digit)
    result_label.config(text=new)

#  Funtion of Clear Screen
def clear():
    result_label.config(text="")

#  Function of operaters
def get_operater(op):
    global first_num,operater
    first_num=int(result_label['text'])
    operater=op
    result_label.config(text="")

#   Function of Trignomatry
def get_func(trig):
    global operater,first_num
    first_num=result_label.config(text=trig)
    operater=trig
    result_label.config(text="")

#  Function of Result
def result():
    global first_num,operater,second_num
    second_num=int(result_label['text'])
    if operater=='+':
        result_label.config(text=(str(first_num+second_num)))
    elif operater=='-':
        result_label.config(text=(str(first_num-second_num)))
    elif operater=='*':
        result_label.config(text=(str(first_num*second_num)))
    elif operater=='/':
        if second_num==0:
            result_label.config(text="Error")
        else:
            result_label.config(text=(str(round(first_num/second_num,2))))
    elif operater=='tan':
        result_label.config(text=(str(round (math.tan(second_num),5))))
    elif operater=='atan':
        result_label.config(text=(str(round (math.atan(second_num),5))))
    elif operater=='sin':
        result_label.config(text=(str(round (math.sin(second_num),5))))
    elif operater=='asin':
        result_label.config(text=(str(round (math.asin(second_num),5))))
    elif operater=='cos':
        result_label.config(text=(str(round (math.cos(second_num),5))))
    elif operater=='acos':
        result_label.config(text=(str(round (math.acos(second_num),5))))
    elif operater=='log':
        result_label.config(text=(str(round (math.log(second_num),5))))
    elif operater=="Square":
        result_label.config(text=(str(second_num*second_num)))

root = Tk()
root.title("Calculater")
root.geometry("391x360")
root.resizable(0,0)
root.configure(bg="#0C090A")

result_label=Label(root,text="",bg="#0C090A",fg="white")
result_label.grid(row=0,column=0,columnspan=9,pady=(50,15),sticky="w")
result_label.config(font=("verdana",26,'bold'))

# Button of first row
btn7=Button(root,text="7",bg="#AA6C39",fg="white",width=5,height=2,command=lambda:get_digit(7))
btn7.grid(row=1,column=0)
btn7.config(font=("vardana",14))

btn8=Button(root,text="8",bg="#AA6C39",fg="white",width=5,height=2,command=lambda:get_digit(8))
btn8.grid(row=1,column=1)
btn8.config(font=("vardana",14))

btn9=Button(root,text="9",bg="#AA6C39",fg="white",width=5,height=2,command=lambda:get_digit(9))
btn9.grid(row=1,column=2)
btn9.config(font=("vardana",14))

btn_sum=Button(root,text="+",bg="#3B3131",fg="white",width=5,height=2,command=lambda:get_operater('+'))
btn_sum.grid(row=1,column=3)
btn_sum.config(font=("vardana",14))

btn_tan=Button(root,text="Tan",bg="#622F22",fg="white",width=5,height=2,command=lambda:get_func("tan"))
btn_tan.grid(row=1,column=4)
btn_tan.config(font=("vardana",14))

btn_atan=Button(root,text="ArcTan",bg="#622F22",fg="white",width=5,height=2,command=lambda:get_func("atan"))
btn_atan.grid(row=1,column=5)
btn_atan.config(font=("vardana",14))

# Button of Second row
btn4=Button(root,text="4",bg="#AA6C39",fg="white",width=5,height=2,command=lambda:get_digit(4))
btn4.grid(row=2,column=0)
btn4.config(font=("vardana",14))

btn5=Button(root,text="5",bg="#AA6C39",fg="white",width=5,height=2,command=lambda:get_digit(5))
btn5.grid(row=2,column=1)
btn5.config(font=("vardana",14))

btn6=Button(root,text="6",bg="#AA6C39",fg="white",width=5,height=2,command=lambda:get_digit(6))
btn6.grid(row=2,column=2)
btn6.config(font=("vardana",14))

btn_sub=Button(root,text="-",bg="#3B3131",fg="white",width=5,height=2,command=lambda:get_operater('-'))
btn_sub.grid(row=2,column=3)
btn_sub.config(font=("vardana",14))

btn_sin=Button(root,text="Sin",bg="#622F22",fg="white",width=5,height=2,command=lambda:get_func("sin"))
btn_sin.grid(row=2,column=4)
btn_sin.config(font=("vardana",14))

btn_asin=Button(root,text="ArcSin",bg="#622F22",fg="white",width=5,height=2,command=lambda:get_func("asin"))
btn_asin.grid(row=2,column=5)
btn_asin.config(font=("vardana",14))

# Button of Third row
btn1=Button(root,text="1",bg="#AA6C39",fg="white",width=5,height=2,command=lambda:get_digit(1))
btn1.grid(row=3,column=0)
btn1.config(font=("vardana",14))

btn2=Button(root,text="2",bg="#AA6C39",fg="white",width=5,height=2,command=lambda:get_digit(2))
btn2.grid(row=3,column=1)
btn2.config(font=("vardana",14))

btn3=Button(root,text="3",bg="#AA6C39",fg="white",width=5,height=2,command=lambda:get_digit(3))
btn3.grid(row=3,column=2)
btn3.config(font=("vardana",14))

btn_mul=Button(root,text="*",bg="#3B3131",fg="white",width=5,height=2,command=lambda:get_operater('*'))
btn_mul.grid(row=3,column=3)
btn_mul.config(font=("vardana",14))

btn_cos=Button(root,text="Cos",bg="#622F22",fg="white",width=5,height=2,command=lambda:get_func("cos"))
btn_cos.grid(row=3,column=4)
btn_cos.config(font=("vardana",14))

btn_acos=Button(root,text="ArcCos",bg="#622F22",fg="white",width=5,height=2,command=lambda:get_func("acos"))
btn_acos.grid(row=3,column=5)
btn_acos.config(font=("vardana",14))

# Button of Forth row
btn_clr=Button(root,text="C",bg="#C04000",fg="white",width=5,height=2,command=lambda :clear())
btn_clr.grid(row=4,column=0)
btn_clr.config(font=("vardana",14))

btn0=Button(root,text="0",bg="#AA6C39",fg="white",width=5,height=2,command=lambda:get_digit(0))
btn0.grid(row=4,column=1)
btn0.config(font=("vardana",14))

btn_res=Button(root,text="=",bg="#C04000",fg="white",width=5,height=2,command=lambda :result())
btn_res.grid(row=4,column=2)
btn_res.config(font=("vardana",14))

btn_dvi=Button(root,text="/",bg="#3B3131",fg="white",width=5,height=2,command=lambda:get_operater('/'))
btn_dvi.grid(row=4,column=3)
btn_dvi.config(font=("vardana",14))

btn_log=Button(root,text="Log",bg="#5C3317",fg="white",width=5,height=2,command=lambda:get_func("log"))
btn_log.grid(row=4,column=4)
btn_log.config(font=("vardana",14))

btn_Squ=Button(root,text="Square",bg="#5C3317",fg="white",width=5,height=2,command=lambda:get_func("Square"))
btn_Squ.grid(row=4,column=5)
btn_Squ.config(font=("vardana",14))

root.mainloop()


# https://leetcode.com/problems/contains-duplicate/

class Solution:
    def containsDuplicate(self, nums: list[int]) -> bool:
        prev = set()
        for n in nums:
            if n in prev:
                return True
            prev.add(n)
        return False


"""empty message

Revision ID: 34a42af4014a
Revises:
Create Date: 2023-09-06 17:37:29.581281

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql

# revision identifiers, used by Alembic.
revision = '34a42af4014a'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('user', schema=None) as batch_op:
        batch_op.drop_index('email')

    op.drop_table('user')
    op.drop_table('roles_users')
    with op.batch_alter_table('role', schema=None) as batch_op:
        batch_op.drop_index('name')

    op.drop_table('role')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('role',
    sa.Column('id', mysql.INTEGER(), autoincrement=True, nullable=False),
    sa.Column('name', mysql.VARCHAR(length=80), nullable=True),
    sa.Column('description', mysql.VARCHAR(length=255), nullable=True),
    sa.PrimaryKeyConstraint('id'),
    mysql_collate='utf8mb4_0900_ai_ci',
    mysql_default_charset='utf8mb4',
    mysql_engine='InnoDB'
    )
    with op.batch_alter_table('role', schema=None) as batch_op:
        batch_op.create_index('name', ['name'], unique=False)

    op.create_table('roles_users',
    sa.Column('user_id', mysql.INTEGER(), autoincrement=False, nullable=True),
    sa.Column('role_id', mysql.INTEGER(), autoincrement=False, nullable=True),
    sa.ForeignKeyConstraint(['role_id'], ['role.id'], name='roles_users_ibfk_2'),
    sa.ForeignKeyConstraint(['user_id'], ['user.id'], name='roles_users_ibfk_1'),
    mysql_collate='utf8mb4_0900_ai_ci',
    mysql_default_charset='utf8mb4',
    mysql_engine='InnoDB'
    )
    op.create_table('user',
    sa.Column('id', mysql.INTEGER(), autoincrement=True, nullable=False),
    sa.Column('email', mysql.VARCHAR(length=40), nullable=True),
    sa.Column('password', mysql.VARCHAR(length=200), nullable=True),
    sa.Column('name', mysql.VARCHAR(length=30), nullable=True),
    sa.Column('surname', mysql.VARCHAR(length=50), nullable=True),
    sa.PrimaryKeyConstraint('id'),
    mysql_collate='utf8mb4_0900_ai_ci',
    mysql_default_charset='utf8mb4',
    mysql_engine='InnoDB'
    )
    with op.batch_alter_table('user', schema=None) as batch_op:
        batch_op.create_index('email', ['email'], unique=False)

    # ### end Alembic commands ###


from PyAsoka.src.Core.Object import Object, ObjectMeta
from PyAsoka.src.Core.Signal import Signal

class PropMeta(ObjectMeta):
    def __new__(mcs, name, bases, attrs, **extra_kwargs):
        if name != 'Prop':
            if 'type' not in extra_kwargs:
                raise Exception('Не указан тип свойства')
            if 'default' not in extra_kwargs:
                raise Exception('Не указано значение свойства по умолчанию')

            attrs['_type_'] = extra_kwargs['type']
            attrs['_value_'] = extra_kwargs['default']
            attrs['changed'] = Signal(extra_kwargs['type'])
        return super().__new__(mcs, name, bases, attrs)

class Prop(Object, metaclass=PropMeta):
    def __init__(self, _type=None, initial_state=None, widget=None):
        super().__init__()

        name = self.__class__.__name__
        if name == 'Prop':
            if _type is None:
                raise Exception('Не указан тип свойства')
            if initial_state is None:
                raise Exception('Не указано значение свойства по умолчанию')

            self.type = _type
            self.value = initial_state
        else:
            self.type = self._type_
            self.value = self._value_

        self._widget_ = widget

    def __setter__(self, inst, value):
        self.setter(self._widget_, value)
        self.changed.emit(value)

    def __getter__(self, inst):
        return self.getter(self._widget_)

    def setter(self, widget, value):
        self.value = value

    def getter(self, widget):
        return self.value


hall_capacity = int(input())

total_money = 0
is_full = False
number_people = 0

command = input()
while command != "Movie time!":
    number = int(command)
    number_people += number
    if hall_capacity < number_people:
        is_full = True
        break

    total_money += number * 5
    if number % 3 == 0:
        total_money -= 5

    command = input()

diff = abs(hall_capacity - number_people)
if is_full:
    print(f"The cinema is full.")
else:
    print(f"There are {diff} seats left in the cinema.")

print(f"Cinema income - {total_money} lv.")

Programming basics with Python/Exam prep/3/cinema.py


'''
    I used Newspaper 3k for further scraping data from the URL's collected in the reddit post scraping.
    Newspaper 3k does a great job at scraping the relevant info from news articles.

    For more info on Newspaper 3k, check out this link:
    https://github.com/codelucas/newspaper

    This script primarily uses the URLs combined in data_merger.py to further scrape
    news websites for the content of the articles.

'''

import newspaper
from newspaper import Article
import pandas as pd
import time

def news_scraper(df):
    '''
        This function takes in a dataframe, takes the URL for each article, then scraps the news website for
        info on the article, including its text, post title, article title, date of publication and author.

        '''
    content = []
    for index, row in df.iterrows():
        url = row['URL']
        news=Article(url)
        try:
            # need to first download the article
            news.download()
            news.parse()
            content.append({'post_title': row['post_title'],'Article_Title':news.title, 'Text': news.text.replace('\n',' '),
                     'Date_of_pub':news.publish_date})
        except:
            print('could not download', news)
    return content

# importing dataset from merging.py
df = pd.read_csv('reddit_data.csv')
#scraping the newspapers
news_content = news_scraper(df)
#building newspaper dataframe to merge with reddit data
news_data = pd.DataFrame.from_dict(news_content)
# merging df with news content
all_reddit_data = pd.merge(df, news_data, how='inner', on=['post_title'])
#dropping duplicates
all_reddit_data = all_reddit_data.drop_duplicates('post_title')
#saving out CSV to use for classification
all_reddit_data.to_csv('clean_reddit_data.csv')


import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import seaborn as sn
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
import pandas as pd
from sklearn.utils import shuffle
#--------------------------One Vs All -----------------------------------------
def  OneVsAll(X_train, X_test, y_train, y_test ):
    classArray = []
    y_pred = []
    H_theta = []
    maxVal=0
    max = []
    Y = 0
    for i in range(len(y_train)):
        classArray.append(y_train[i][0]) if y_train[i][0] not in classArray else classArray
    newY = np.zeros(len(y_train))
    for i in range(len(X_test)):
        maxVal = 0
        for j in range(len(classArray)):
            newY = np.zeros(len(y_train))
            y = classArray[j]
            for k in range(len(y_train)):
                if y_train[k][0]==y:
                    newY[k] = 1
                elif y_train[j][0]!=y:
                    newY[k] =0
            model = LogisticRegression()
            newY = newY.astype('int')
            H_theta.append(model.fit(X_train, newY))
            maxV = H_theta[j].predict_proba(X_test[i].reshape(1, -1)).flatten()[1]
            if maxVal < maxV:
                maxVal=maxV
                Y= y
        y_pred.append(Y)

    y_pred = np.array(y_pred)
    confusion_matrix = pd.crosstab(y_test.flatten() , y_pred , rownames=['Actual'], colnames=['Predicted'])
    print(confusion_matrix)
    sn.heatmap(confusion_matrix, annot=True)
    print('Accuracy: ', metrics.accuracy_score(y_test, y_pred))
    plt.title("One Vs All")
    plt.show()

def OneVsOne(X_train, X_test, y_train, y_test):
    classArray   =[]
    for i in range(len(y_train)):
        classArray.append(y_train[i][0]) if y_train[i][0] not in classArray else classArray
    newY = np.zeros(len(y_train))
    matrixOneVSOne = np.zeros((6,6))
    """
    for i in range(matrixOneVSOne.shape[0]):
        matrixOneVSOne[i][0] = i
    """
    maxVal =0
    nameClass= 0
    y_pred = []
    print(classArray)
    for i in range(len(X_test)):
        for k  in  range(len(classArray)):
            theOne = classArray[k]
            for j  in range(k+1 , len(classArray)):
                # get only the y you need for two classes
                newDataY = y_train[(y_train == theOne) | (y_train == classArray[j])]
                # newDataY wil be 1 when  in place of theone and zero when other
                newDataY[newDataY == theOne] = 1
                newDataY[newDataY == classArray[j]] = 0
                # get only the X you need for the classes
                X = findXtrain(X_train , y_train , theOne , classArray[j])
                model = LogisticRegression()
                X = np.array(X)
                newDataY = newDataY.astype('int')
                a = model.fit(X , newDataY)
                # insert the predict  in matrix
                matrixOneVSOne[k][j] = a.predict_proba(X_test[i].reshape(1, -1)).flatten()[1]
                if k<6 and j <6 :
                    matrixOneVSOne[j][k] = 1 - a.predict_proba(X_test[i].reshape(1, -1)).flatten()[1]
        maxVal =0
        # get the max value on the matrix by sum of rows
        for l in range(matrixOneVSOne.shape[0]):
            if maxVal < np.sum(matrixOneVSOne[l]):
                maxVal = np.sum(matrixOneVSOne[l])
                nameClass =l
        # append the name of the class that give you the max
        y_pred.append(classArray[nameClass])

    y_pred = np.array(y_pred)
    confusion_matrix = pd.crosstab(y_test.flatten(), y_pred, rownames=['Actual'], colnames=['Predicted'])
    print(confusion_matrix)
    sn.heatmap(confusion_matrix, annot=True)
    print('Accuracy: ', metrics.accuracy_score(y_test, y_pred))
    plt.title("One Vs One")
    plt.show()

def findXtrain(Xtrain , Ytrain , name , name2):
    new_xtrain = []
    for i in range(len(X_train)):
        if Ytrain[i]==name or Ytrain[i]==name2:
            new_xtrain.append(Xtrain[i])
    return new_xtrain

if  __name__ == "__main__" :
    # -----------------------------------------------------------------------
    # read the excel file to data frame
    excel_data_df = pd.read_excel('BreastTissue (1).xlsx', sheet_name='Data')
    # get x and y
    x = excel_data_df[['I0', 'PA500', 'HFS', 'DA', 'Area', 'A/DA', 'Max IP', 'DR', 'P']]
    y = excel_data_df[['Class']]
    y = y.to_numpy()
    # normalized matrix x
    matrix_X = StandardScaler().fit_transform(x)

    X_train, X_test, y_train, y_test = train_test_split(matrix_X, y, test_size=0.33, random_state=42)

    OneVsAll(X_train, X_test, y_train, y_test )

    OneVsOne(X_train, X_test, y_train, y_test)


from flightradar24.api import FlightRadar24API

fr_api = FlightRadar24API()
airports = fr_api.get_airports()
airlines = fr_api.get_airlines()

flights = fr_api.get_flights(airline="RPB")
interested = flights[0]
flight_details = fr_api.get_flight_details(interested.id)

img_flight = '2ccf01ac'
next_flight = '2ce08df2'

img_flight_details = fr_api.get_flight_details(img_flight)
next_flight_details = fr_api.get_flight_details(next_flight)

print("DOne")


__author__       = "Mark Sattolo"
__author_email__ = "epistemik@gmail.com"
__created__ = "2021-01-21"
__updated__ = "2021-01-21"

import csv
import sys
from argparse import ArgumentParser
from datetime import datetime as dt
from cwLibWrappers import chadwick, cwlib
from cwTools import *

class PrintPlayerStats:
    def __init__(self, cwt:MyChadwickTools, logger:logging.Logger):
        self.cwtools = cwt
        self.lgr = logger
        self.lgr.warning(F" Start {self.__class__.__name__}")
        self.event_files = list()
        self.games = {}
        self.note_count = 0

    # void cwbox_print_header(CWGame *game, CWRoster *visitors, CWRoster *home)
    def print_header( self, p_game:pointer, p_vis:pointer, p_home:pointer ):
        self.lgr.info("print_header():\n----------------------------------")

        dn_code = "?"
        day_night = MyCwlib.game_info_lookup(p_game, b"daynight")
        if day_night:
            dn_code = "D" if day_night == "day" else "N" if day_night == "night" else day_night

        game_date = MyCwlib.game_info_lookup(p_game, b"date")
        self.lgr.info(F"game date = {game_date}")
        year, month, day = game_date.split('/')
        game_number = MyCwlib.game_info_lookup(p_game, b"number")
        self.lgr.info(F"game_number = {game_number}")
        game_number_str = "" if game_number == "0" else F", game #{game_number}"

        vis_city = p_vis.contents.city
        vis_city_text = c_char_p_to_str(vis_city)
        self.lgr.info(F"visitor = {vis_city_text}")

        home_city = p_home.contents.city
        home_city_text = c_char_p_to_str(home_city)
        self.lgr.info(F"home = {home_city_text}")

        print(F"\n\t\tGame of {month}/{day}/{year}{game_number_str} -- {vis_city_text} @ {home_city_text} ({dn_code})\n")

    # void cwbox_print_linescore(CWGame *game, CWBoxscore *boxscore, CWRoster *visitors, CWRoster *home)
    def print_linescore( self, p_game:pointer, p_box:pointer, p_vis:pointer, p_home:pointer ):
        self.lgr.info("print_linescore():\n----------------------------------")

        linescore = p_box.contents.linescore
        for t in range(0,2):
            runs = 0
            if t == 0:
                print(F"{c_char_p_to_str(p_vis.contents.city, 16):16}" if p_vis
                      else MyCwlib.game_info_lookup(p_game, b"visteam"), end = '')
            else:
                print(F"{c_char_p_to_str(p_home.contents.city, 16):16}" if p_home
                      else MyCwlib.game_info_lookup(p_game, b"hometeam"), end = '')

            for ix in range(1,32):
                if linescore[ix][t] >= 10:
                    print(F"({linescore[ix][t]})", end = '')
                    runs += linescore[ix][t]
                elif linescore[ix][t] >= 0:
                    print(F"{linescore[ix][t]}", end = '')
                    runs += linescore[ix][t]
                elif t == 0:
                    break
                elif linescore[ix][0] < 0:
                    break
                else:
                    print("x ", end = '')
                    break

                if ix % 3 == 0:
                    print(" ", end = '')

            print(F" -- {runs:2}")

        outs_at_end = p_box.contents.outs_at_end
        if outs_at_end != 3:
            if p_box.contents.walk_off:
                print(F"  {outs_at_end} out{'' if outs_at_end == 1 else 's'} when winning run scored.")
            else:
                print(F"  {outs_at_end} out{'' if outs_at_end == 1 else 's'} when game ended.")

    # void cwbox_print_text(CWGame *game, CWBoxscore *boxscore, CWRoster *visitors, CWRoster *home)
    def print_player_stats( self, p_game:pointer, p_box:pointer, p_vis:pointer, p_home:pointer ):
        self.lgr.info("print_game_summary():\n----------------------------------")

        self.note_count = 0
        slots = [1,1]
        players = list()
        ab = [0,0]
        r  = [0,0]
        h  = [0,0]
        bi = [0,0]
        pa = [0,0]
        bb = [0,0]
        so = [0,0]

        player0 = MyCwlib.box_get_starter(p_box, 0, 1)
        self.lgr.debug(F"type(player0) = {type(player0)}")
        players.insert(0, player0)
        player1 = MyCwlib.box_get_starter(p_box, 1, 1)
        self.lgr.debug(F"type(player1) = {type(player1)}")
        players.insert(1, player1)

        self.print_header(p_game, p_vis, p_home)

        vis_city = c_char_p_to_str(p_vis.contents.city) if p_vis else MyCwlib.game_info_lookup(p_game, b"visteam")
        home_city = c_char_p_to_str(p_home.contents.city) if p_home else MyCwlib.game_info_lookup(p_game, b"hometeam")

        print(F"  {vis_city:18} PA  AB   H  BB  SO  R RBI      {home_city:18} PA  AB   H  BB  SO  R RBI    ")

        while slots[0] <= 9 or slots[1] <= 9 :
            for t in range(0,2):
                if slots[t] <= 9:
                    self.cwtools.print_player(players[t], p_vis if (t == 0) else p_home)
                    # NOTE: misspelling 'battiing' in the python wrapper file
                    batting = players[t].contents.battiing.contents
                    ab[t] += batting.ab
                    r[t]  += batting.r
                    h[t]  += batting.h
                    bb[t] += batting.bb
                    pa[t] += batting.pa
                    so[t] += batting.so
                    if batting.bi != -1:
                        bi[t] += batting.bi
                    else:
                        bi[t] = -1
                    players[t] = players[t].contents.next
                    if not players[t]:
                        # In some National Association games, teams played with 8 players.
                        # This generalization allows for printing boxscores when some batting slots are empty.
                        while slots[t] <= 9 and not players[t]:
                            slots[t] += 1
                            if slots[t] <= 9:
                                players[t] = cwlib.cw_box_get_starter(p_box, t, slots[t])
                else:
                    print(F"{''.ljust(45)}", end = '')
                print("     ", end = ''),
            print("")

        print(F"{''.ljust(20)} --  --  --  --  -- -- -- {''.ljust(24)} --  --  --  --  -- -- --")
        print(F"{''.ljust(20)}{pa[0]:3}{ab[0]:4}{h[0]:4}{bb[0]:4}{so[0]:4}{r[0]:3}", end = '')
        print(F"{bi[0]:3} " if bi[0] >= 0 else "    ", end = '')
        print(F"{''.ljust(24)}{pa[1]:3}{ab[1]:4}{h[1]:4}{bb[1]:4}{so[1]:4}{r[1]:3}", end = '')
        print(F"{bi[1]:3} " if bi[1] >= 0 else "    ")
        print("")

        self.print_linescore(p_game, p_box, p_vis, p_home)
        print("")

        for t in range(0, 2):
            pitcher = MyCwlib.box_get_starting_pitcher(p_box, t)
            if t == 0:
                print(F"  {vis_city:18}   IP  H  R ER BB SO  TP TS GB FB")
            else:
                print(F"  {home_city:18}   IP  H  R ER BB SO  TP TS GB FB")
            while pitcher:
                self.cwtools.print_pitcher( p_game, pitcher, (p_vis if (t == 0) else p_home) )
                pitcher = pitcher.contents.next
            if t == 0:
                print("")

        self.cwtools.print_pitcher_apparatus(p_box)
        print("")

        self.cwtools.print_apparatus(p_game, p_box, p_vis, p_home)
        print("")

# END class PrintPlayerStats

def process_args():
    arg_parser = ArgumentParser(description="Print player combined stats from Retrosheet data for the specified years",
                                prog='main_chadwick_py3.py')
    # required arguments
    required = arg_parser.add_argument_group('REQUIRED')
    required.add_argument('-i', '--player_id', required=True, help="Retrosheet id for a player, e.g. aaroh101, bondb101")
    required.add_argument('-s', '--start', required=True, type=int, help="start year to find stats (yyyy)")
    required.add_argument('-e', '--end', required=True, type=int, help="end year to find stats (yyyy)")
    # optional arguments
    arg_parser.add_argument('-p', '--post', action="store_true", help="find postseason games instead of regular season")
    arg_parser.add_argument('-q', '--quiet', action="store_true", help="NO logging")
    arg_parser.add_argument('-l', '--level', default="INFO", help="set LEVEL of logging output")

    return arg_parser

def process_input_parameters(argx:list):
    args = process_args().parse_args(argx)
    loglevel = "CRITICAL" if args.quiet else args.level
    try:
        getattr( logging, loglevel.strip().upper() )
    except AttributeError as ae:
        print(F"Problem with log level: {repr(ae)}")
        loglevel = "INFO"

    logging.basicConfig(level = loglevel)
    logging.warning(F"process_input_parameters(): Level = {loglevel}\n--------------------------------------")
    logging.info(F"args = \n{args}")

    # TODO: process 'postseason' flag

    playid = args.player_id.strip() if len(args.player_id) >= 8 and \
         args.player_id[:5].isalpha() and args.player_id[5:8].isdecimal() else "maysw001"
    if len(playid) > 8:
        playid = playid[:8]
    logging.warning(F"id = {playid}")

    start = args.start if 1871 <= args.start <= 2020 else 1954
    logging.warning(F"start = {start}")

    end = args.end if 1871 <= args.end <= 2020 else 1955
    if args.end < args.start: end = start
    logging.warning(F"end = {end}")

    return playid, start, end, loglevel

def main_player_stats(args:list):
    lgr = logging.getLogger("PrintPlayerStats")

    playid, start, end, loglevel = process_input_parameters(args)

    lgr.setLevel(loglevel)
    lgr.debug( str(lgr.handlers) )
    lgr.warning(F" id = {playid}; years = {start}->{end}")

    cwtools = MyChadwickTools(lgr)
    player_stats = PrintPlayerStats(cwtools, lgr)
    need_name = True
    fam_name = playid
    giv_name = ""
    # TODO:
    #   get ALL the event files for the requested years
    #   go through each event line for the files and find where player == 'BAT_ID' and save these
    #   go through each file and look for the batting stats of the player and sum
    try:
        for year in range(start, end+1):
            # get the team files
            team_file_name = REGULAR_SEASON_FOLDER + "TEAM" + str(year)
            lgr.info(F"team file name = {team_file_name}")
            with open(team_file_name, newline = '') as team_csvfile:
                team_reader = csv.reader(team_csvfile)
                for trow in team_reader:
                    rteam = trow[0]
                    lgr.info(F"Found team {rteam}")
                    # get the rosters
                    if need_name:
                        roster_file = ROSTERS_FOLDER + rteam + str(year) + ".ROS"
                        lgr.debug(F"roster file name = {roster_file}")
                        if not os.path.exists(roster_file):
                            raise FileNotFoundError(F"CANNOT find roster file {roster_file}!")
                        with open(roster_file, newline = '') as roster_csvfile:
                            ros_reader = csv.reader(roster_csvfile)
                            for rrow in ros_reader:
                                if playid == rrow[0]:
                                    fam_name = rrow[1]
                                    giv_name = rrow[2]
                                    need_name = False
                                    break
                    # find and store the event file paths
                    event_file = REGULAR_SEASON_FOLDER + str(year) + rteam + ".EV" + trow[1]
                    if not os.path.exists(event_file):
                        raise FileNotFoundError(F"CANNOT find event file {event_file}!")
                    player_stats.event_files.append(event_file)

        lgr.info(F"name = {giv_name} {fam_name}")
        lgr.info(F"found {len(player_stats.event_files)} event files")
        for item in player_stats.event_files:
            lgr.debug(item)

        event_rows = 0
        # get all the games for the requested team in the supplied date range
        for evteam in player_stats.event_files:
            lgr.info(F"found events for team = {evteam}")
            cwgames = chadwick.games(evteam)
            for game in cwgames:
                game_id = game.contents.game_id.decode(encoding='UTF-8')
                game_date = game_id[3:11]
                lgr.debug(F" Found game id = {game_id}; date = {game_date}")

                events = chadwick.process_game(game)
                results = tuple(events)
                for row in results:
                    if row['BAT_ID'] == playid:
                        event_rows += 1
                        # player_stats.print_player_stats()
        lgr.info(F"found {event_rows} event rows for {giv_name} {fam_name} in {start} through {end}.")

    except Exception as ex:
        lgr.exception(F"Exception: {repr(ex)}")

if __name__ == "__main__":
    run_start_time = dt.now()
    if '-q' not in sys.argv:
        logging.critical(F"Run Start time = {run_start_time.strftime('%Y-%m-%d %H:%M:%S')}")
    main_player_stats(sys.argv[1:])
    if '-q' not in sys.argv:
        run_time = (dt.now() - run_start_time).total_seconds()
        logging.critical(F" Running time = {(run_time // 60)} minutes, {(run_time % 60):2.3} seconds")
    exit()


import torch
from torch.autograd import Variable
batch_n = 100
hidden_layer = 100
input_data = 1000
output_data = 10
x = Variable(torch.randn(batch_n, input_data),requires_grad = False)
y = Variable(torch.randn(batch_n, output_data),requires_grad = False)

# 使用Sequential自动生成和初始化对应维度的权重参数
# 是一种序列容器， 嵌套各种实现神经网络的中具体功能相关的类
# 参数会按照定义好的序列自动传递
# 模块加入的两种方式：
# 1.代码中直接嵌套。
# 2.以orderdict有序字典传入

# 直接嵌套
models = torch.nn.Sequential(
    torch.nn.Linear(input_data, hidden_layer),
    torch.nn.ReLU(),
    torch.nn.Linear(hidden_layer, output_data)
)
print(models)

# 以orderdict有序字典传入
from collections import OrderedDict

models = torch.nn.Sequential(OrderedDict([
    ("linear1", torch.nn.Linear(input_data, hidden_layer)),
    ("relu1", torch.nn.ReLU()),
    ("linear2", torch.nn.Linear(hidden_layer, output_data))
]))
print(models)

# Sequential(
#   (0): Linear(in_features=1000, out_features=100, bias=True)
#   (1): ReLU()
#   (2): Linear(in_features=100, out_features=10, bias=True)
# )
# Sequential(
#   (linear1): Linear(in_features=1000, out_features=100, bias=True)
#   (relu1): ReLU()
#   (linear2): Linear(in_features=100, out_features=10, bias=True)
# )

epoch_n = 10000
learning_rate = 1e-4
loss_fn = torch.nn.MSELoss()

# loss_fn = torch.nn.L1Loss()
# loss_fn = torch.nn.CrossEntropyLoss()

for epoch in range(epoch_n):
    y_pred = models(x)
    loss = loss_fn(y_pred, y)
    if epoch%1000==0:
        print("Epoch:{}, Loss:{:.4f}".format(epoch, loss.data.item()))
    models.zero_grad()

    loss.backward()

    for param in models.parameters():
        param.data -= param.grad.data*learning_rate
# 通过models.parameters()进行参数更新梯度


import pytest

from cygorithms.arrays import (
    OneDArray,
    DynamicOneDArray,
    selection_sort,
    merge_sort,
    quick_sort
)

@pytest.mark.parametrize(
    "array_type",
    [
        OneDArray,
        DynamicOneDArray
    ]
)
@pytest.mark.parametrize(
    "dtype, container, filler",
    [
        (
            int,
            [1, 2, 3, 4],
            5
        ),
        (
            str,
            ["a", "b", "c", "d"],
            "e"
        ),
        (
            tuple,
            [(1, 2, 3, 4), (1, 2, 3), (1, 2), (1,)],
            (0,)
        )
    ]
)
def test_arrays(array_type, dtype, container, filler):
    print(container)
    arr = array_type(dtype, 4, container)
    assert len(arr) == arr.size
    for el, check in zip(arr, container):
        assert el == check

    if "Dynamic" in array_type.__class__.__name__:
        arr.append(filler)
        assert arr[4] == filler
        arr.delete(2)
        assert arr[2] is None

@pytest.mark.parametrize(
    "array_type",
    [
        OneDArray,
        DynamicOneDArray
    ]
)
@pytest.mark.parametrize(
    "sort_alg",
    [
        selection_sort,
        merge_sort,
        quick_sort
    ]
)
@pytest.mark.parametrize(
    "dtype, container",
    [
        (
            int,
            [3, 1, 2, 5, 3, 2, 2, 1, 5, 6, 8, 1, 2, 4, 1]
        ),
        (
            str,
            ["c", "d", "a", "c", "ef", "f", "b", "ad", "dd", "e", "b"]
        )
    ]
)
@pytest.mark.parametrize(
    "comp",
    [
        None,
        lambda u, v: u >= v
    ]
)
def test_arrays_algs(array_type, sort_alg, dtype, container, comp):
    arr = array_type(dtype, container)
    if comp is None:
        sorted_container = sorted(container)
    else:
        sorted_container = sorted(container)[::-1]

    sort_alg(arr, comp=comp)

    for el, check in zip(sorted_container, arr):
        assert el == check


import github as gthb

inst = gthb.Github()

languages  = ['Python', 'Ruby', 'Javascript', 'Haskell']
extensions = ['.py', '.rb', '.js', '.hs']

with open('urls.txt','w') as f:

	for ind, lang in enumerate(languages):
		repos = inst.search_repositories(lang, language=lang, sort='stars', order='desc')

		size = 0
		i = 0
		while size < 1e6:

			url = repos[i].html_url
			size += repos[i].size
			i+=1

			f.write(lang+','+url+','+extensions[ind]+'\n')


import os
import json
import utils
import interfaces.terraform.hetzner_provider_mapper

from abc import ABC
from commands.command import Command
from commands.validators.command_validators import KubesprayPatchesValidator
from exceptions.exceptions import UnexpectedTerraformFailureException, CommandConfirmationException
from interfaces.ansible.kubespray_manager import KubesprayManager
from interfaces.terraform import hetzner_provider_mapper
from interfaces.terraform.terraform_interface import Terraform

class TerraformBaseCommand(Command, ABC):

    def __init__(self, context):
        super().__init__(context, context_validators=[KubesprayPatchesValidator])
        self.terraform_content = None
        self.tf = Terraform()

    def prepare_arena(self):
        self.terraform_content = self.context.terraform_config.package_manager.get_content()
        if not os.listdir(self.context.cluster_space.tf_plugins_directory):
            if not self.tf.providers_mirror(self.terraform_content, self.context.cluster_space.tf_plugins_directory):
                raise UnexpectedTerraformFailureException('Cannot prepare terraform needed plugins')

        if not self.tf.init(self.terraform_content, self.context.cluster_space.tf_plugins_directory):
            raise UnexpectedTerraformFailureException('Terraform infrastructure initialization has failed')

    def get_dumped_infra_settings(self):
        tf_vars_file = self.context.temporal_fs.get_temporal_file(ext='.tfvars.json')
        with open(tf_vars_file, 'w') as file:
            json.dump(self.context.terraform_config.infra_config, file)
        return tf_vars_file

    def get_state_resources(self):
        res_ok, current_state = self.tf.show(self.terraform_content,
                                             input_file=self.context.cluster_space.tf_state_file)
        if not res_ok:
            raise UnexpectedTerraformFailureException('Cannot obtain current terraform state')
        return interfaces.terraform.hetzner_provider_mapper.parse_state(current_state)

class CreateClusterCommand(TerraformBaseCommand):

    def __init__(self, context):
        super().__init__(context)

    def run(self):
        try:
            self.prepare_arena()
            infra_settings_file = self.get_dumped_infra_settings()

            tf_vars = {'ssh_public_key': self.context.ssh_key_manager.get_public_rsa_key_opnessh()}

            plan_file = self.context.temporal_fs.get_temporal_file()
            res, output = self.tf.plan(self.terraform_content, [infra_settings_file], tf_vars, True,
                                       state_file=self.context.cluster_space.tf_state_file, plan_file=plan_file)
            if res:
                # TODO Make some validations
                plan_changes = hetzner_provider_mapper.parse_plan(output)
                if plan_changes.create or plan_changes.destroy or plan_changes.update:
                    res = self.tf.apply(self.terraform_content, [infra_settings_file], tf_vars,
                                        state_file=self.context.cluster_space.tf_state_file, plan_file=plan_file)
                if res:
                    self.logger.info('Infrastructure successfully created')
                    spray = KubesprayManager(self.context, self.get_state_resources())
                    spray.create_cluster()

                else:
                    self.logger.info('Failed to create infrastructure')

        except UnexpectedTerraformFailureException as err:
            self.logger.error(err)
            # TODO Raise to end with a proper exit code

class DestroyClusterCommand(TerraformBaseCommand):

    def __init__(self, context):
        super().__init__(context)

    def run(self):

        try:
            if not utils.get_optional_arg(self.context.run_options, 'confirm'):
                raise CommandConfirmationException('Destroy command needs destruction confirmation flag')

            self.prepare_arena()
            infra_settings_file = self.get_dumped_infra_settings()

            tf_vars = {'ssh_public_key': self.context.ssh_key_manager.get_public_rsa_key_opnessh()}
            res = self.tf.destroy(self.terraform_content, [infra_settings_file], tf_vars,
                                  state_file=self.context.cluster_space.tf_state_file)

            if res:
                self.context.cluster_space.destroy_cluster_space()
                self.logger.info('Infrastructure successfully destroyed')
            else:
                self.logger.info('Failed to destroy infrastructure')
        except UnexpectedTerraformFailureException as err:
            self.logger.error(err)
            return False


from __future__ import annotations
from typing import Dict

class GameState:
    """
    This class represent game state.

    Attributes:
        current_scene (str): Id of the current scene in game
        variables (dict): Dictionary containing all the variables of the game. Default: {}
    """

    def __init__(
        self,
        current_scene: str,
        variables: Dict[str, bool] = {},
    ) -> None:
        """
        Initialize new GameState object.

        Params:
            current_scene (str): Id of the current scene in game
            variables (dict): Dictionary containing all the variables of the game. Default: {}
        """
        self.current_scene = current_scene
        self.variables = variables

    @classmethod
    def from_dict(cls, adict: dict) -> GameState:
        """
        Creates object from dictionary.

        Params:
            adict: A dictionary representing the object.

        Returns:
            Object of this class.
        """
        return cls(
            current_scene=adict["current_scene"],
            variables=adict["variables"],
        )

    def to_dict(self) -> dict:
        """
        Dumps object to dictionary.

        Returns:
           Dictionary representing this object.
        """
        return {
            "current_scene": self.current_scene,
            "variables": self.variables,
        }

    def __eq__(self, other: object) -> bool:
        """
        Compare equal method for object.

        Params:
            other: object to compare with

        Return:
            Compare result.
        """
        if not isinstance(other, GameState):
            raise NotImplementedError

        return self.to_dict() == other.to_dict()


'''
app 新建 urls.py 文件
'''

from django.conf.urls import url
import book.views as views

app_name = 'book' # 设置 app namespace
urlpatterns = [
    url(r'^index/$', views.index, name='index'), # url函数的name参数：设置 URL name

    # http://127.0.0.1:8000/book/分类id/书籍id/
    # http://127.0.0.1:8000/book/category_id/book_id/
    # 分组来获取正则中的数据
    # 1. 根据位置来获取 url中的参数
    url(r'^(\d+)/(\d+)/$', views.getid, name='getid'),
    # 2. 关键字参数--推荐大家使用关键字参数
    # url(r'^(?P<category_id>\d+)/(?P<book_id>\d+)/$', views.getid, name='getid'),
]