#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 18 13:13:13 2019

@author: antoineleblevec
"""

import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import fonctions as f1
from functools import reduce
#from statistics import mean

Re = 6371032
H = 250e3
lllat = 33.7; urlat = 43.7; lllon = 133.6; urlon = 150.6
elon = 142
elat = 38
epoque1 = 21183
epoque2 = 21883
station = []; df = []; lon_station = []; lat_station = []; lat = []; lon= [];
lon_sip_max = []; lat_sip_max = []; tec = []; vtec=[]; saq = []
df_el = pd.DataFrame(); df_az = pd.DataFrame(); df_tec = pd.DataFrame()

directory = os.path.join('/Users/antoineleblevec/Desktop/G26')
rep = os.path.abspath(os.path.expanduser(directory))
files = os.listdir(rep)
files.sort()
os.chdir(directory)

for i in range(len(files)):
    name = files[i].split('_')
    station.append(name[0])
    df.append(f1.read(files[i],epoque1,epoque2))
    df[i] = df[i].set_index("tsn")
    df[i].columns = ['el_{0}'.format(station[i]), 'az_{0}'.format(station[i]), 'tec_{0}'.format(station[i])]
    lon_station.append(f1.lecture_lon(files[i]))
    lat_station.append(f1.lecture_lat(files[i]))
dftot = reduce(lambda x, y: pd.merge(x, y, on = "tsn"), df)
df_lat_station = pd.DataFrame([lat_station])
df_lon_station = pd.DataFrame([lon_station])
for j in range(len(files)):
    df_el = df_el.append(dftot['el_{0}'.format(station[j])])
    df_az = df_az.append(dftot['az_{0}'.format(station[j])])
    df_tec = df_tec.append(dftot['tec_{0}'.format(station[j])])
df_el = np.radians(df_el).T
df_az = np.radians(df_az).T
df_tec = df_tec.T
df_tec = df_tec - df_tec.iloc[0]
df_x = np.arcsin((Re * np.cos(df_el)) / (Re + H))
df_ksi = (np.pi / 2) - (df_el.add((df_x), fill_value=0))
tplat = pd.np.multiply(np.sin(df_ksi),np.cos(df_az))
tplon = pd.np.multiply(np.sin(df_ksi),np.sin(df_az))
df_lat = np.arcsin(pd.np.multiply(np.cos(df_ksi),np.sin(df_lat_station)) +
                   pd.np.multiply(tplat,np.cos(df_lat_station)))
tpplon = np.arcsin(pd.np.divide(tplon,np.cos(df_lat)))
df_lon = pd.np.add(tpplon,df_lon_station)
df_vtec = pd.np.multiply(df_tec,np.cos(df_x))

## détection de l'indice, en partant de 0, de la première apparition de l'onde en regardant le VTEC
def detec_tid(station):
    a = df_vtec['tec_{0}'.format(station)]
    for i in range(len(a)):
        if abs(a.iloc[i+1]-a.iloc[i]) > 0.030 :
            break
    return i

def devtec(station, i):
    return df_vtec['tec_{0}'.format(station)].iloc[i]

def delon(station, i):
    return df_lon['el_{0}'.format(station)].iloc[i]

def delat(station, i):
    return df_lat['el_{0}'.format(station)].iloc[i]
#

for i in range (100):
    fig = plt.figure()
    for k in station :
        vtec.append(devtec(k, detec_tid(k)+i))
        lon_sip_max.append(delon(k, detec_tid(k)+i))
        lat_sip_max.append(delat(k, detec_tid(k)+i))

    m = f1.basic_japan_map(lllat, urlat, lllon, urlon, elon, elat)
    x, y = m(np.degrees(lon_sip_max), np.degrees(lat_sip_max))
    m.hexbin(x,
             y,
             C=vtec,
             reduce_C_function=np.mean,
             gridsize=20,
             cmap="plasma")
    plt.title('Max VTEC with Hion:{0} m {1}s après earthquake'.format(H,i+400))
    cbaxes = fig.add_axes([0.90, 0.1, 0.01, 0.8])
    cb = plt.colorbar(cax=cbaxes)
    m.colorbar()
    plt.gcf()
    fig.savefig(f"/Users/antoineleblevec/Desktop/frames/realtime_{i:04d}.png",
                frameon=False, pad_inches=0)
    cbaxes.clear()

# =============================================================================
# à utiliser si points aberrants
# =============================================================================
#for i,a in enumerate(saq) :
#    if abs(mean(saq)-a) > 30 :
#        saq.pop(i)
#        lon_sip_max.pop(i)
#        lat_sip_max.pop(i)
#        station.pop(i)
#        vtec.pop(i)


from fastapi import FastAPI, File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel

import uvicorn

from qa import qa

origins = [
    "*",
]

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class QAHuggingFace(BaseModel):
    question: str
    context: str

@app.get("/")
async def root():
    return {"message": "Hello World"}

@app.post("/qa")
async def root(qa_hf: QAHuggingFace):
    question = qa_hf.question
    context = qa_hf.context
    result = qa(question, context)
    return {"result": result}

if __name__ == "__main__":
    uvicorn.run("api:app", host="0.0.0.0", port=8000, reload=True)


from azure.mgmt.loadtestservice import LoadTestClient
from azure.mgmt.loadtestservice.models import LoadTestResource

# for managing authentication and authorization can be installed from pypi, follow:
# https://pypi.org/project/azure-identity/ using DefaultAzureCredentials, read more at:
# https://learn.microsoft.com/en-us/python/api/azure-identity/azure.identity.defaultazurecredential?view=azure-python
from azure.identity import DefaultAzureCredential

# importing os and dotenv for managing and loading environment variables
import os
from dotenv import load_dotenv

# Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables:
# AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, SUBSCRIPTION_ID, RESOURCE_GROUP

# loading dotenv file
load_dotenv()

SUBSCRIPTION_ID = os.environ["SUBSCRIPTION_ID"]
RESOURCE_GROUP = os.environ["RESOURCE_GROUP"]

# setting up management client
mgmt_client = LoadTestClient(
    credential=DefaultAzureCredential(),
    subscription_id=SUBSCRIPTION_ID
)

# creating a new loadtest resource
result = mgmt_client.load_tests.create_or_update(
    resource_group_name=RESOURCE_GROUP,
    load_test_name="new-loadtest-python-sdk",
    load_test_resource=LoadTestResource(
        location="eastus",
        description="New LoadTest Resource created via Python SDK"
    )
)

# getting dataplane url from loadtest
print(result.data_plane_uri)


import matplotlib.pylab as plt
import numpy as np

x = np.linspace(-2, 2, 200)
plt.plot(x, np.cosh(x))
plt.xlabel('Angle [rad]')
plt.ylabel('cosh(x)')
plt.axis('tight')
plt.show()


import pandas
import numpy as np
from sklearn.linear_model import LinearRegression
from scipy import stats

class regression():
	def __init__(self, FerData, Time):
		self.FerData = FerData
		self.Time = Time
		self.grate = 0
		self._P = 0
		self.sig_P = 0
		self.alpha = 0
		self._I = 0
		self.sig_I = 0

	def bootstrap(self):
		index = np.random.choice(len(self.FerData.iloc[:, 2]), len(self.FerData.iloc[:, 2]))
		self.FerData = self.FerData.iloc[index, :]

	def reg(self):
		y = np.log(self.FerData.iloc[:, 2]) - np.log(self.FerData.iloc[:, 1])
		y = y.values.reshape(-1, 1)
		X = np.array([self.Time for i in range(len(y))])
		X = X.reshape(-1, 1)
		clf = LinearRegression(fit_intercept=False)
		clf.fit(X, y)
		y_hat = clf.predict(X)
		self.grate = round(clf.coef_[0][0], 4)
		self.P = y - y_hat
		self.sig_P = round(np.std(self.P, ddof=1), 4)
		y2 = self.FerData.iloc[:, 3] / self.FerData.iloc[:, 2]
		y2 = y2.values.reshape(-1, 1)
		self.alpha = round(pow(np.prod(y2), 1.0 / len(y2)), 4)
		y_hat2 = self.FerData.iloc[:, 2] * self.alpha
		y_hat2 = y_hat2.values.reshape(-1, 1)
		exp_I = self.FerData.iloc[:, 3].values.reshape(-1, 1) / y_hat2
		self._I = np.log(exp_I)
		self.sig_I = round(np.std(self._I, ddof=1), 4)


import base64
import cv2
import math
import socket

SERVER_IP = '127.0.0.1'

def getVideoFrame():
    grabbed, frame = camera.read()  # grab the current frame
    frame = cv2.resize(frame, (640, 480))  # resize the frame
    encoded, buffer = cv2.imencode('.jpg', frame)
    jpg_as_text = base64.b64encode(buffer)
    return jpg_as_text  # output byte array

def generatePacket(data, seq_number):
    packet_dimension = 4096 - 8  # Byte dimension of packet
    # number of packet to be generated to contain all data
    packet_number = math.ceil(len(data)/packet_dimension)

    packets = []
    for i in range(0, packet_number):
        # Genrate packet header
        # Structure
        # |Sequence Number(2)|Packet Number(2)|Current Packet(2)|Data(packet_dimension - 8)|
        header = seq_number.to_bytes(
            2, "little", signed=False) + packet_number.to_bytes(
            2, "little", signed=False) + i.to_bytes(2, "little", signed=False)

        # Split data into packets
        start = i * packet_dimension
        end = start + packet_dimension
        packet = header + data[start:end]
        packets.append(packet)

        print("Header| " + " Seq: " + str(seq_number) + " | Total: " +
              str(packet_number) + " | Curr: " + str(i) + "|", end ='\r')

    return packets

# MAIN
# Init
camera = cv2.VideoCapture(0)  # init the camera
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
seq_number = 0
print("CLIENT STARTED")

# Loop
while True:
    img = getVideoFrame()
    data = generatePacket(img, seq_number)

    for i in data:
        clientsocket.sendto(i, (SERVER_IP, 7777))

    seq_number += 1


p=0.5

D = { (0,0) : 1 , (1,0) : 1 , (1,1) : p }

import numpy as np
import scipy.special
import scipy.integrate as integrate
import matplotlib.pyplot as plt
import numpy as np
from os import walk, system
from scipy import fft
import matplotlib
matplotlib.rcParams['text.usetex'] = True
from pickle import dumps, dump, load, loads
import pickle
import cv2
import sys, os
from numpy.lib import vectorize
sys.path.append(os.path.realpath(".."))
from lib.exp import Exp, FittedObj, gencolor, glabels, plotlabels, gColors, putlabel
import matplotlib
matplotlib.rcParams['text.usetex'] = True

def contrast( _path = "./mgyi/mgyi_1"):
    for dirpath, dirname, filenams in walk(_path):
        for filename in filter( lambda s : "tif" in s , filenams):
            print(filename)
            DIRname = dirpath.split("/")[-1]
            system( f"echo y | sh ./scripts/impr.sh {dirpath}/{filename} ./tif3/{DIRname}/{filename}")

def loadf(_path):
    print(_path)
    return cv2.imread(f'{_path}', cv2.IMREAD_GRAYSCALE).astype(np.float128)

def time (_path ):
    return int(_path.split('_')[1])

def norm(X):
    return np.linalg.norm(X, 'fro' )

def picklize():
    _path = "./tif/"
    _keyword = "YFP" #"Phasefast"
    _dict = {}

    for dirpath, dirname, filenams in walk(_path):
        DIRname = dirpath.split("/")[-1]
        _dict[DIRname] = [  ]
        for _filename in filter( lambda s : ("tif" in s ) and ( _keyword in s), filenams):
            __file = "{0}/{1}".format( dirpath, _filename )
            print(__file)
            _dict[DIRname].append( ( time(__file), norm(loadf( __file ))))
        print(_dict)

    with open(f"{_keyword}.pkl", 'wb') as handle:
        dump(_dict, handle, protocol=pickle.HIGHEST_PROTOCOL)

if __name__ == "__main__":

    contrast( _path = "./mgyi_3/" )

    exit(0)

    _keyword = "YFP"

    _dict = None
    with open(f"{_keyword}.pkl", 'rb') as handle:
        _dict = pickle.load(handle)
    # print(_dict)

    propb = np.zeros((50,250))
    # probexcpt = np.zeros((50,250))

    for _key, dictvec in _dict.items():
        print("----" + str( _key) + "-----")
        if len(dictvec) > 0:
            vec = (np.array( sorted( dictvec, key=lambda x: x[0]) )).T
            vec[1] /= vec[1][0]

            # print(vec.T)

            for timetick, mulsize in vec.T:
                if timetick < 110:
                    propb[int(mulsize)][int(timetick)] += 1

    from scipy.signal import find_peaks

    for _key, dictvec in _dict.items():
        print("----" + str( _key) + "-----")
        if len(dictvec) > 0:
            vec = (np.array( sorted( dictvec, key=lambda x: x[0]) )).T
            vec[1] /= vec[1][0]
            # print(vec.T)

            for timetick, mulsize in vec.T:
                peaks, _ = find_peaks(  propb[int(mulsize)] )
                np.diff(peaks)
                if len(peaks) > 1 :
                    if abs(timetick - peaks[-1]) < 3:
                    # if timetick > 2 *  np.average(propb[int(mulsize)]):
                        print( f" anomaloy :  {_key} , {timetick}, {mulsize}")

    print(propb[7])


from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.dispatcher import FSMContext
from aiogram import types
from aiogram.dispatcher.filters import Text

from main import dp, admins_id
from utils.db_api.db_quick_commands import add_contest

class FSMAdmin(StatesGroup):
    name = State()
    photo = State()
    description = State()
    price = State()

@dp.message_handler(state="*", text="Отмена")
@dp.message_handler(Text(equals="Отмена", ignore_case=True), state="*")
async def cancel_handler(message: types.Message, state: FSMContext):
    current_state = await state.get_state()
    if current_state is None:
        return
    await state.finish()
    await message.reply("Ввод отменен")

@dp.message_handler(content_types=types.ContentType.TEXT, text="Добавить конкурс")
async def start_command(message: types.Message, state: FSMContext):
    if str(message.from_user.id) in admins_id:
        await FSMAdmin.name.set()
        await message.reply("Введите название конкурса")

@dp.message_handler(state=FSMAdmin.name)
async def add_name(message: types.Message, state: FSMContext):
    if str(message.from_user.id) in admins_id:
        async with state.proxy() as data:
            data["name"] = message.text
        await FSMAdmin.next()
        await message.reply("Добавте фото конкурса")

@dp.message_handler(content_types=["photo"], state=FSMAdmin.photo)
async def add_photo(message: types.Message, state: FSMContext):
    if str(message.from_user.id) in admins_id:
        async with state.proxy() as data:
            data["photo"] = message.photo[0].file_id
        await FSMAdmin.next()
        await message.reply("Введите описание конкурса")

@dp.message_handler(state=FSMAdmin.description)
async def add_description(message: types.Message, state: FSMContext):
    if str(message.from_user.id) in admins_id:
        async with state.proxy() as data:
            data["description"] = message.text
        await FSMAdmin.next()
        await message.reply("Введите взнос")

@dp.message_handler(state=FSMAdmin.price)
async def add_price(message: types.Message, state: FSMContext):
    if str(message.from_user.id) in admins_id:
        async with state.proxy() as data:
            data["price"] = float(message.text.replace(",", "."))

        async with state.proxy() as data:
            if add_contest(data):
                await message.answer("Конкурс добавлен")
            else:
                await message.answer("Конкурс не добавлен.\nНе коррекртные данные")
        await state.finish()


import sqlite3
import os
from flask import Flask, render_template, request, url_for,redirect,flash,session
import datetime
from recommandation import recommandation
from werkzeug.utils import secure_filename
import time

app = Flask(__name__)

@app.context_processor
def handle_context():
    return dict(os=os)

app.config["SESSION_PERMANENT"]=False
app.config["SESSION_TYPE"]="file_system"
app.config["IMAGE_UPLOADS"] = "static/img/uploads"
app.config["ALLOWED_IMAGE_EXTENSIONS"] = ["JPEG", "JPG", "PNG", "GIF"]

app.secret_key=os.urandom(12)

#vérifie si le fichier fournis est une image
def allowed_image(filename):

    if not "." in filename:
        return False

    ext = filename.rsplit(".", 1)[1]

    if ext.upper() in app.config["ALLOWED_IMAGE_EXTENSIONS"]:
        return True
    else:
        return False

#vérifie si l'id du sub est valide
def test_id_sub(id):
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     cursor.execute(""" SELECT description FROM subs WHERE numéro_projet=?""",(id,))
     test=cursor.fetchall()
     db.close()
     if test!=[]:
          return True
     else:
          return False

#vérifie qu'un utilisateur est bien connecter
def test_login():
     if session.get("id")!=None:
          return True
     else:
          return False

#vérifie si l'utilisateurs est validé par un admin
def test_verif():
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     cursor.execute(""" SELECT niveau FROM utilisateurs WHERE id_user=?""",(str(session.get('id')),))
     test=cursor.fetchall()[0][0]
     db.close()
     if test=='B':
          return False
     else:
          return True

#vérifie si l'utilisateurs possède le sub connect
def is_owner(id,user):
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     cursor.execute(""" SELECT * FROM subs WHERE numéro_projet=? AND créé_par=?""",(id,user))
     test=cursor.fetchall()
     db.close()
     if test!=[]:
          return True
     else:
          return False

#verifie que l'id du commentaire existe
def com_existe(id):
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     cursor.execute(""" SELECT * FROM posts WHERE id_post=?""",(id,))
     test=cursor.fetchall()
     db.close()
     if test!=[]:
          return True
     else:
          return False

#verifie que l'id du post existe
def post_existe(id):
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     cursor.execute(""" SELECT * FROM commentaires WHERE id_commentaire=?""",(id,))
     test=cursor.fetchall()
     db.close()
     if test!=[]:
          return True
     else:
          return False

#verifie si l'utilisateur est abonné au sub donnée
def est_abonne(id,user):
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     cursor.execute(""" SELECT * FROM abonnements WHERE sub=? AND utilisateur=?""",(id,user))
     test=cursor.fetchall()
     db.close()
     if test!=[]:
          return True
     else:
          return False

#verifie si l'utilisateur participe au sub donnée
def est_participant(id,user):
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     cursor.execute(""" SELECT * FROM participants WHERE sub=? AND utilisateur=?""",(id,user))
     test=cursor.fetchall()
     db.close()
     if test!=[]:
          return True
     else:
          return False

#verifie si l'utilisateur a demandé à participer au sub donnée
def a_demande(id,user):
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     cursor.execute(""" SELECT * FROM demande_participation WHERE sub=? AND utilisateur=?""",(id,user))
     test=cursor.fetchall()
     db.close()
     if test!=[]:
          return True
     else:
          return False

#verifie que si l'utilisateurs connecté a deja liké le commentaire
def commentaire(id_com,user):
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     cursor.execute("SELECT id_voteur FROM Vote_com WHERE id_com=?",(id_com,))
     likeur=cursor.fetchall()
     if likeur!=[]:
          if (user,) not in likeur:
               db.close()
               return (True,True)
          else:
               cursor.execute("SELECT val FROM Vote_com WHERE id_com=? AND id_voteur=?",(id_com,str(user)))
               val=cursor.fetchall()
               db.close()
               if val[0][0]=='P':
                    return (False,True)
               else:
                    return (True,False)
     else:
          db.close()
          return (True,True)

#verifie que si l'utilisateurs connecté a deja liké le post
def likepost(id_post,user):
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     cursor.execute("SELECT id_voteur FROM Vote_post WHERE id_post=?",(id_post,))
     likeur=cursor.fetchall()
     if likeur!=[]:
          if (user,) not in likeur:
               db.close()
               return (True,True)
          else:
               cursor.execute("SELECT val FROM Vote_post WHERE id_post=? AND id_voteur=?",(id_post,str(user)))
               val=cursor.fetchall()
               db.close()
               if val[0][0]=='P':
                    return (False,True)
               else:
                    return (True,False)
     else:
          db.close()
          return (True,True)

#acceuil ou page de connexion
@app.route('/')
def login():
     if not session.get("id"):
          return render_template('login.html', message=1)
     else:
          return redirect('/accueil')

#Essaye de connecter avec les données rentrés
@app.route('/connect',methods=['post'])
def connect():
     form_data=request.form.to_dict()
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     cursor.execute(""" SELECT mdp FROM utilisateurs WHERE mail=?""",(str(form_data['username']),))
     verif=cursor.fetchall()
     if verif!=[]:
          if verif[0][0]==str(form_data['password']):
               cursor.execute(""" SELECT id_user,nom,prénom,mail FROM utilisateurs WHERE mail=?""",(str(form_data['username']),))
               id=cursor.fetchall()
               db.close()
               session['id']=id[0][0]
               session['nom']=id[0][1]
               session['prénom']=id[0][2]
               session['username']=id[0][3]
               session['password']=verif
               return redirect('/accueil')
          else:
               db.close()
               return render_template('login.html',message=str('Votre mail et/ou votre mot de passe sont erronés, veuillez réessayer'))
     else:
          db.close()
          return render_template('login.html',message=str('Votre mail et/ou votre mot de passe sont erronés, veuillez réessayer'))

#la age d'enregistrement
@app.route('/register')
def register():
     return render_template('register.html',message=1)

#rentre le nouvel utilisateur
@app.route('/enregistrement',methods=['get','post'])
def enregistre():
     if request.method == 'POST':
          form=request.form.to_dict()
          db = sqlite3.connect('database.db')
          cursor = db.cursor()
          cursor.execute(""" SELECT nom FROM utilisateurs WHERE mail=?""",(str(form['mail']),))
          verif=cursor.fetchall()
          if verif!=[]:
               db.close()
               return render_template('register.html',message='mail déjà utilisé')
          else:
               cursor.execute(""" INSERT INTO utilisateurs(nom,prénom,mail,mdp,Niveau) values(?,?,?,?,?)""",(str(form['nom']),str(form['prénom']),str(form['mail']),str(form['mdp']),'B'))
               db.commit()
               db.close()
               return redirect('/')
     else:
          return redirect('/')

# Route lié à la page d'accueil qui affiche le fil d'actualités
@app.route('/accueil')
def accueil():
     # Sélection des posts liés aux projets abonnés et créés par l'utilisateur, tri par ordre décroissant de date de création
     query = "SELECT DISTINCT nom,titre,posts.description,id_sub,posts.date_creation,id_post FROM subs JOIN posts JOIN abonnements WHERE Numéro_projet = id_sub AND (utilisateur=? AND sub=id_sub OR créé_par= ?) ORDER BY date_creation DESC"
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     id_user = session.get('id')
     cursor.execute(query,(id_user,id_user))
     L = cursor.fetchall()
     comments={}
     like={}
     for row in L:
          idpost=row[5]
          cursor.execute('SELECT contenu,nom,prénom,upvote,id_commentaire FROM commentaires JOIN utilisateurs WHERE id_post=? AND posté_par=id_user ORDER BY upvote DESC' ,(idpost,))
          données=cursor.fetchall()
          cursor.execute('''SELECT ratio FROM posts WHERE id_post=? ''',(idpost,))
          like[idpost]=[likepost(idpost,session.get('id')),cursor.fetchall()[0][0]]
          if données!=[]:
               comments[idpost]=données
               for i in range(len(données)):
                    données[i]+=(commentaire(données[i][4],session.get('id')),)
          else:
               comments[idpost]=[]
     db.close()
     os.path.isfile("static/img/uploads/")
     return render_template('accueil.html',data = L,comments=comments,like=like)

#form de création d'un sub
@app.route('/form')
def form():
     if test_verif:
          return render_template('sub.html')
     else:
          return render_template('erreur.html',message="Accès refusé",description="vous n'avez pas les droits d'accès nécessaires")

#app route de parcourir
@app.route('/parcourir')
def parcourir():
     db='database.db'
     con=sqlite3.connect(db)
     cur=con.cursor()
     cur.execute("SELECT * FROM subs ORDER BY création DESC;")
     L=cur.fetchall()
     con.close()
     return render_template('parcourir.html',data=L)

#rentre le sub dans la base de donnée et renvoie vers l'acceuil
@app.route('/post',methods=['post'])
def post():
     if test_login():
          if test_verif():
               form_data=request.form.to_dict()
               db = sqlite3.connect('database.db')
               cursor = db.cursor()
               id=session.get('id')
               cursor.execute("""
               INSERT INTO subs(nom,créé_par,mots_clés,description,création) values(?,?,?,?,?)""",(str(form_data['name']),id,str(form_data['domaine']),str(form_data['description']),datetime.date.today()))
               db.commit()
               db.close()
               return redirect('/')
          else:
               return render_template('erreur.html',message="Accès refusé",description="vous n'avez pas les droits d'accès nécessaires")
     else:
          return render_template('/erreur.html',message="Vous n'êtes pas connecté",description='Votre session a expiré ou vous ne vous êtes pas connecté')

#lance le form de recherche
@app.route('/search', methods=['GET', 'POST'])
def recherche():
    search = request.form.to_dict()
    if request.method == 'POST':
        return search_results(search)
    return render_template('resultat.html', form=search)

#lance l'algorithme de recherche
@app.route('/results')
def search_results(search):
     resultat = []
     search_str = search['Search']
     subs = sqlite3.connect('database.db')
     cursor = subs.cursor()
     cursor.execute("""SELECT * FROM subs""")
     contenu=cursor.fetchall()
     resultat=[]
     for row in contenu:
          if search_str in row[0] or search_str in row[3]:
               date=row[5].split('-')
               Y=int(date[0])
               M=int(date[1])
               D=int(date[2])
               resultat.append(row[:-1]+(str((datetime.date.today()-datetime.date(Y,M,D)).days)+' days ago',))

     subs.close()
     if not resultat:
         return render_template('resultat.html',resultat='')
     else:
         return render_template('resultat.html', resultat=resultat)

#lance et affiche le resultat de l'algorithme de recommandation
@app.route('/recommandation')
def recom():
     if test_login():
          if test_verif():
               db = sqlite3.connect('database.db')
               cursor = db.cursor()
               cursor.execute("SELECT sub FROM abonnements INNER JOIN subs ON abonnements.sub=subs.numéro_projet WHERE utilisateur=?",(str(session.get("id")),))
               abonnement=cursor.fetchall()
               cursor.execute("SELECT numéro_projet FROM subs WHERE créé_par=?",(str(session.get("id")),))
               abonnement+=cursor.fetchall()
               total={}
               for i in range(len(abonnement)):
                    abonnement[i]=abonnement[i][0]
               for i in range(len(abonnement)):
                    temp=recommandation(abonnement[i])
                    for j in range(len(temp)):
                         if temp[j][0] not in abonnement:
                              if temp[j][0] in total:
                                   total[temp[j][0]]+=temp[j][1]
                              else:
                                   total[temp[j][0]]=temp[j][1]
               result=list(sorted(total.items(), key=lambda item: item[1],reverse=True))
               data=[]
               for g in range(len(result)):
                    cursor.execute("SELECT * FROM subs WHERE numéro_projet=?",(result[g][0],))
                    data.append(cursor.fetchall()[0]+(result[g][1],g+1))
               db.close()
               return render_template('recommandation.html',data=data)
          else:
               return render_template('erreur.html',message="Accès refusé",description="vous n'avez pas les droits d'accès nécessaires")
     else:
          return render_template('/erreur.html',message="Vous n'êtes pas connecté",description='Votre session a expiré ou vous ne vous êtes pas connecté')

#lance la page du sub
@app.route('/sub/<id>')
def viewsub(id):
     if test_login():
          db = sqlite3.connect('database.db')
          cursor = db.cursor()
          if test_id_sub(id):
               # Récupération des données liées au projet (nom,description, créateur, nombre d'abonnés, participants...)
               cursor.execute("SELECT subs.nom,description,créé_par,utilisateurs.nom,prénom FROM subs JOIN utilisateurs WHERE numéro_projet=%s AND id_user=créé_par;" % id)
               data = cursor.fetchall()
               cursor.execute("SELECT COUNT(*) FROM abonnements WHERE sub=?",(id,))
               nb_abonnes = cursor.fetchall()[0]
               cursor.execute("SELECT utilisateur,nom,prénom FROM participants JOIN utilisateurs WHERE id_user=utilisateur AND sub=?",(id,))
               liste_participants=cursor.fetchall()
               user_id = session.get('id')
               # Définition de l'état de l'utilisateur vis-à-vis du projet
               owner = is_owner(id,user_id)
               abonne = est_abonne(id,user_id)
               participant = est_participant(id,user_id)
               demande = a_demande(id,user_id)
               db.close()
               return render_template('viewsub.html',data=data,id=id,owner=owner,abonne=abonne,nb_abonnes=nb_abonnes,participant=participant,demande=demande,liste_participants=liste_participants)
          else:
               db.close()
               return redirect('/')
     else:
          return render_template('/erreur.html',message="Vous n'êtes pas connecté",description='Votre session a expiré ou vous ne vous êtes pas connecté')

#Route lié au bouton s'abonner du projet de numéro 'id'
@app.route("/<id>/abonnement")
def abonnement(id):
     if test_login() :
          if test_verif():
               if test_id_sub(id):
                    user = session.get('id')
                    if not is_owner(id,user) and not est_abonne(id,user):
                         db = sqlite3.connect('database.db')
                         cursor = db.cursor()
                         cursor.execute("INSERT INTO abonnements(sub,utilisateur) VALUES (?,?);",(id,session.get('id')))
                         db.commit()
                         db.close()
                         return redirect(url_for('viewsub',id=id))
                    else:
                         return render_template('erreur.html',message="Impossible de s'abonner",description="Vous êtes déjà abonné ou bien alors c'est votre projet")
               else :
                    return redirect('/')
          else:
               return render_template('erreur.html',message="Accès refusé",description="Vous n'avez pas les droits d'accès nécessaires")
     else:
          return redirect('/')

# Route liée au bouton se désabonner du projet de numéro 'id'
@app.route('/<id>/desabonnement')
def desabonnement(id):
     if test_login():
          if test_verif():
               if test_id_sub(id):
                    user = session.get('id')
                    if est_abonne(id,user):
                         db = sqlite3.connect('database.db')
                         cursor = db.cursor()
                         cursor.execute("DELETE FROM abonnements WHERE sub=? AND utilisateur = ?;",(id,user))
                         if a_demande(id,user):
                              cursor.execute("DELETE FROM demande_participation WHERE sub=? AND utilisateur = ?;",(id,user))
                         elif est_participant(id,user):
                              cursor.execute("DELETE FROM participants WHERE sub=? AND utilisateur = ?;",(id,user))
                         db.commit()
                         db.close()
                         return redirect(url_for('viewsub',id=id))
                    else :
                         return render_template('erreur.html',message="Impossible de se désabonner",description="Vous n'êtes pas abonné ou bien c'est votre projet")

               else :
                    return redirect('/')
          else:
               return render_template('erreur.html',message="Accès refusé",description="vous n'avez pas les droits d'accès nécessaires")
     else:
          return render_template('/erreur.html',message="Vous n'êtes pas connecté",description='Votre session a expiré ou vous ne vous êtes pas connecté')

# Route liée au bouton Participer du projet n° 'id'
@app.route('/<id>/demande_participation')
def demande_participation(id):
     if test_login():
          if test_verif():
               if test_id_sub(id):
                    user = session.get('id')
                    if not a_demande(id,user) and not is_owner(id,user) and est_abonne(id,user):
                         db = sqlite3.connect('database.db')
                         cursor = db.cursor()
                         cursor.execute("INSERT INTO demande_participation(sub,utilisateur) VALUES (?,?)",(id,session.get('id')))
                         db.commit()
                         db.close()
                         return redirect(url_for('viewsub',id=id))
                    else:
                         return render_template('erreur.html',message="Impossible de demander à participer au projet",description="Vous n'êtes pas abonné ou bien c'est votre projet ou vous avez déjà fait une demande")

               else :
                    return redirect('/')
          else:
               return render_template('erreur.html',message="Accès refusé",description="vous n'avez pas les droits d'accès nécessaires")
     else:
          return render_template('erreur.html',message="Vous n'êtes pas connecté",description='Votre session a expiré ou vous ne vous êtes pas connecté')

# Route liée au bouton Ne plus participer du projet n° 'id'
@app.route('/<id>/annuler_participation')
def annuler_participation(id):
     if test_login():
          if test_verif():
               if test_id_sub(id):
                    user = session.get('id')
                    if est_participant(id,user):
                         db = sqlite3.connect('database.db')
                         cursor = db.cursor()
                         cursor.execute("DELETE FROM participants WHERE sub=? AND utilisateur=?",(id,user))
                         db.commit()
                         db.close()
                         return redirect(url_for('viewsub',id=id))
                    else :
                         return render_template('erreur.html',message="Impossible d'annuler sa participation au projet",description="Vous ne participez pas au projet ou bien c'est votre projet")

               else :
                    return redirect('/')
          else:
               return render_template('erreur.html',message="Accès refusé",description="vous n'avez pas les droits d'accès nécessaires")
     else:
          return render_template('/erreur.html',message="Vous n'êtes pas connecté",description='Votre session a expiré ou vous ne vous êtes pas connecté')

# Route liée à l'onglet Post du projet n° 'id'
@app.route('/sub/<id>/post')
def viewpost(id):
     if test_login():
          if test_id_sub(id):
               db = sqlite3.connect('database.db')
               cursor = db.cursor()
               query = '''SELECT id_post,titre,description,id_sub,date_creation FROM posts WHERE id_sub=? ORDER BY date_creation;'''
               cursor.execute(query,(id,))
               L =(cursor.fetchall(),id)
               comments={}
               like={}
               for row in L[0]:
                    idpost=row[0]
                    cursor.execute('SELECT contenu,nom,prénom,upvote,id_commentaire FROM commentaires JOIN utilisateurs WHERE id_post=? AND posté_par=id_user ORDER BY upvote DESC' ,(idpost,))
                    données=cursor.fetchall()
                    cursor.execute('''SELECT ratio FROM posts WHERE id_post=? ''',(idpost,))
                    like[idpost]=[likepost(idpost,session.get('id')),cursor.fetchall()[0][0]]
                    if données!=[]:
                         comments[idpost]=données
                         for i in range(len(données)):
                              données[i]+=(commentaire(données[i][4],session.get('id')),)
                    else:
                         comments[idpost]=[]
               db.close()
               user = session.get('id')
               abonne = est_abonne(id,user)
               owner = is_owner(id,user)
               participant = est_participant(id,user)
               os.path.isfile("static/img/uploads/")
               return render_template('viewpost.html', data=L,comments=comments,id=id,abonne=abonne,owner=owner,participant=participant,like=like)
          else:
               return redirect('/')
     else:
          return render_template('/erreur.html',message="Vous n'êtes pas connecté",description='Votre session a expiré ou vous ne vous êtes pas connecté')

# Route liée au bouton Créer un nouveau post dans l'onglet Post du projet n° 'id'
@app.route('/sub/<id>/creationpost')
def newpost(id):
     if test_verif():
          if test_id_sub(id):
               user = session.get('id')
               if is_owner(id,user) or est_participant(id,user):
                    return render_template('newpost.html',data=id)
               else:
                    return render_template('erreur.html',message="Impossible de créer un post",description="Vous ne participez pas au projet ni n'êtes son créateur")
          else:
               return redirect('/')
     else:
          return render_template('erreur.html',message="Accès refusé",description="vous n'avez pas les droits d'accès nécessaires")

# Route liée au form pour créer un nouveau post lié au projet n° 'id'
@app.route('/postsub/<id>',methods = ['GET','POST'])
def postsub(id):
     if test_verif():
          titre = request.form['titre']
          description = request.form['description']
          db = sqlite3.connect('database.db')
          cursor = db.cursor()
          if test_id_sub(id):
               if request.method=='POST':
                    cursor.execute("INSERT INTO posts(id_sub,titre,description,date_creation,ratio) values(?,?,?,?,?)",(id,titre,description,datetime.date.today(),0))
                    cursor.execute("SELECT max(id_post) FROM posts")
                    idpost=cursor.fetchall()
                    db.commit()
                    db.close()
                    if "image" in request.files:
                         image = request.files["image"]
                         split_tup = os.path.splitext(image.filename)
                         file_extension = split_tup[1]
                         if image.filename == "":
                              #"pas de nom"
                              return redirect('/sub/'+str(id)+'/creationpost')

                         if allowed_image(image.filename):
                              image.save(os.path.join(app.config["IMAGE_UPLOADS"], str(idpost[0][0])))
                              #"image sauvegardé"
                              return redirect('/sub/'+str(id)+'/creationpost')

                         else:
                              #"type de fichier non supporté"
                              return redirect('/sub/'+str(id)+'/creationpost')
                    return redirect('/sub/'+str(id)+'/creationpost')
               return render_template('newpost.html')
          else:
               db.close()
               return redirect('/')
     else:
          return render_template('erreur.html',message="Accès refusé",description="vous n'avez pas les droits d'accès nécessaires")

# Route liée au bouton Like sur un post d'id_post = 'id'
@app.route('/<id>/ajoutcompteur')
def updatecompteurpostpositif(id):
     if test_verif():
          db = sqlite3.connect('database.db')
          cursor = db.cursor()
          cursor.execute("SELECT id_sub FROM posts WHERE id_post= ?",(id,))
          id_sub = cursor.fetchall()[0][0]
          if test_id_sub(id_sub):
               cursor.execute("UPDATE posts SET ratio= ratio +1 WHERE id_post=?",(id,))
               db.commit()
               db.close()
               return redirect('/')
          else:
               db.close()
               return redirect('/')
     else:
          return render_template('erreur.html',message="Accès refusé",description="Vous n'avez pas les droits d'accès nécessaires")

# Route liée à l'onglet Demande de participation du projet n° 'id'
@app.route('/sub/<id>/demandes')
def demande(id):
     if test_verif():
          if test_id_sub(id):
               if is_owner(id,session.get('id')):
                    db = sqlite3.connect('database.db')
                    cursor = db.cursor()
                    cursor.execute("SELECT utilisateur,nom,prénom FROM demande_participation JOIN utilisateurs WHERE id_user=utilisateur AND sub = ?",(id,))
                    data=cursor.fetchall()
                    db.close()
                    return render_template("participants.html",id=id,data=data)
               else :
                    return render_template('erreur.html',message="Accès refusé",description="Vous n'êtes pas le créateur du projet")

          else:
               return redirect('/')
     else:
          return render_template('erreur.html',message="Accès refusé",description="Vous n'avez pas les droits d'accès nécessaires")

# Route liée au bouton Accepter la participation de 'user' dans l'onglet Demande de participations du projet n° 'id'
@app.route('/<id>/accepter/<user>')
def accepter(id,user):
     if test_verif():
          db = sqlite3.connect('database.db')
          cursor = db.cursor()
          if test_id_sub(id):
               cursor.execute("INSERT INTO participants(sub,utilisateur) VALUES (?,?)",(id,user))
               cursor.execute("DELETE FROM demande_participation WHERE sub=? AND utilisateur=?",(id,user))
               db.commit()
               db.close()
               return redirect(url_for('demande',id=id))
          else:
               db.close()
               return redirect('/')
     else:
          return render_template('erreur.html',message="Accès refusé",description="vous n'avez pas les droits d'accès nécessaires")

# Route liée au bouton Refuser la participation de 'user' dans l'onglet Demande de participations du projet n° 'id'
@app.route('/<id>/refuser/<user>')
def refuser(id,user):
     if test_verif():
          db = sqlite3.connect('database.db')
          cursor = db.cursor()
          if test_id_sub(id):
               cursor.execute("DELETE FROM demande_participation WHERE sub=? AND utilisateur=?",(id,user))
               db.commit()
               db.close()
               return redirect(url_for(demande,id=id))
          else:
               db.close()
               return redirect('/')
     else:
          return render_template('erreur.html',message="Accès refusé",description="vous n'avez pas les droits d'accès nécessaires")

# Route liée à l'onglet Mon Profil
@app.route('/profil')
def voirleprofil():
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     if test_login():
          id_user = session.get('id')
          cursor.execute("SELECT niveau FROM utilisateurs WHERE id_user=?",(id_user,))
          niveau=cursor.fetchall()[0][0]
          cursor.execute("SELECT nom, prénom, mail, mdp FROM utilisateurs WHERE id_user=?",(id_user,))
          L= cursor.fetchall()
          db.close()
          mdp=L[0][3]
          mdp2=''
          for i in range(len(mdp)):
               mdp2+='*'
          if niveau=='A':
               return render_template('profil.html',data='e',L=L,mdp=mdp2)
          else:
               return render_template('profil.html',data=1,L=L,mdp=mdp2)
     else:
          db.close()
          return render_template('/erreur.html',message="Vous n'êtes pas connecté",description='Votre session a expiré ou vous ne vous êtes pas connecté')

# Route liée au bouton Gérer les accès des utilisateurs (accesible uniquement pour les adminastrateurs)
@app.route('/validation')
def validation_utilisateur():
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     if test_login():
          cursor.execute("SELECT niveau FROM utilisateurs WHERE id_user=?",(session.get("id"),))
          niveau=cursor.fetchall()[0][0]
          if niveau=='A':
               cursor.execute('SELECT niveau,id_user,nom,prénom FROM utilisateurs')
               data=cursor.fetchall()
               db.close()
               return render_template('validation.html',data=data)
          else:
               db.close()
               return render_template('erreur.html',message="Accès refusé",description="Vous n'avez pas les droits d'accès nécessaires")
     else:
          db.close()
          return render_template('/erreur.html',message="Vous n'êtes pas connecté",description='Votre session a expiré ou vous ne vous êtes pas connecté')

# Route lié au bouton Mettre en 'niveau' l'utilisateur 'id' sur la page validation (pour gérer les niveaux des utilisateurs)
@app.route('/<id>/<niveau>')
def update_niveau(id,niveau):
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     cursor.execute("SELECT niveau FROM utilisateurs WHERE id_user=?",(id,))
     niv=cursor.fetchall()
     cursor.execute("SELECT niveau FROM utilisateurs WHERE id_user=?",(session.get('id'),))
     user=cursor.fetchall()[0][0]
     if user=='A' and niv!=[]:
          if niveau=='Admin':
               cursor.execute("UPDATE utilisateurs SET niveau='A' WHERE id_user=?",(id,))
               db.commit()
               db.close()
               return redirect('/validation')
          elif niveau=='Validé':
               cursor.execute("UPDATE utilisateurs SET niveau='V' WHERE id_user=?",(id,))
               db.commit()
               db.close()
               return redirect('/validation')
          else:
               return redirect('/')
     else:
          db.close()
          return render_template('erreur.html',message="Accès refusé",description="Vous n'avez pas les droits d'accès nécessaires")

# Route liée à l'ajout d'un commentaire sur le post
@app.route('/comment/<id>',methods=['post'])
def post_commentaire(id):
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     if test_login():
          if test_verif():
               content=request.form.to_dict()
               user=str(session.get("id"))
               if request.method=='POST':
                    cursor.execute('INSERT INTO commentaires(contenu,posté_par,id_post,upvote) VALUES (?,?,?,?)',(content['commentaire'],user,id,0))
                    db.commit()
               cursor.execute("SELECT id_sub FROM posts WHERE id_post = ?",(id,))
               id_sub = cursor.fetchall()[0][0]
               db.close()
               return redirect('/sub/'+str(id_sub)+'/post')
          else:
               db.close()
               return render_template('erreur.html',message="Accès refusé",description="vous n'avez pas les droits d'accès nécessaires")
     else:
          db.close()
          return render_template('/erreur.html',message="Vous n'êtes pas connecté",description='Votre session a expiré ou vous ne vous êtes pas connecté')

#affiche les abonnements de l'utilisateur connecté
@app.route('/mesabonnements')
def affichageabonnements():
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     if test_login():
          cursor.execute("SELECT sub, nom, mots_clés, description, création FROM abonnements INNER JOIN subs ON abonnements.sub=subs.numéro_projet WHERE utilisateur=?",(str(session.get("id")),))
          L=cursor.fetchall()
          db.close()
          return render_template('mesabonnements.html',data=L)
     else:
          db.close()
          return render_template('/erreur.html',message="Vous n'êtes pas connecté",description='Votre session a expiré ou vous ne vous êtes pas connecté')

#affiche les projets créés de l'utilisateur connecté
@app.route('/mesprojets')
def affichageprojets():
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     if test_login():
          cursor.execute("SELECT numéro_projet, nom, mots_clés, description, création FROM subs WHERE créé_par=?",(str(session.get("id")),))
          L=cursor.fetchall()
          db.close()
          return render_template('mesprojets.html',data=L)
     else:
          db.close()
          return render_template('/erreur.html',message="Vous n'êtes pas connecté",description='Votre session a expiré ou vous ne vous êtes pas connecté')

#upvote du commentaire donnée
@app.route('/upvote/<id_com>')
def upvote(id_com):
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     if test_login():
          if test_verif() and com_existe(id_com):
               cursor.execute("SELECT id_voteur FROM Vote_com WHERE id_com=?",(id_com,))
               likeur=cursor.fetchall()
               if likeur==[]:
                    cursor.execute("INSERT INTO Vote_com(id_com,id_voteur,val) VALUES(?,?,?)",(id_com,str(session.get('id')),'P'))
                    cursor.execute("UPDATE commentaires SET upvote=upvote+1 WHERE id_commentaire=?",(id_com,))
                    db.commit()
               elif (session.get('id'),) not in likeur:
                    cursor.execute("INSERT INTO Vote_com(id_com,id_voteur,val) VALUES(?,?,?)",(id_com,str(session.get('id')),'P'))
                    cursor.execute("UPDATE commentaires SET upvote=upvote+1 WHERE id_commentaire=?",(id_com,))
                    db.commit()
               elif (session.get('id'),) in likeur:
                    cursor.execute("UPDATE Vote_com SET val=? WHERE id_com=? AND id_voteur=?",('P',id_com,str(session.get('id'))))
                    cursor.execute("UPDATE commentaires SET upvote=upvote+1 WHERE id_commentaire=?",(id_com,))
                    db.commit()
               cursor.execute("SELECT id_sub FROM posts JOIN commentaires ON commentaires.id_post=posts.id_post WHERE commentaires.id_commentaire=?",(id_com,))
               id=cursor.fetchall()[0][0]
               db.close()
               return redirect('/sub/'+str(id)+'/post')
          else:
               db.close()
               return render_template('erreur.html',message="Accès refusé",description="vous n'avez pas les droits d'accès nécessaires")
     else:
          db.close()
          return render_template('/erreur.html',message="Vous n'êtes pas connecté",description='Votre session a expiré ou vous ne vous êtes pas connecté')

#downvote du commentaire donnée
@app.route('/downvote/<id_com>')
def downvote(id_com):
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     if test_login():
          if test_verif() and com_existe(id_com):
               cursor.execute("SELECT id_voteur FROM Vote_com WHERE id_com=?",(id_com,))
               likeur=cursor.fetchall()
               if likeur==[]:
                    cursor.execute("INSERT INTO Vote_com(id_com,id_voteur,val) VALUES(?,?,?)",(id_com,str(session.get('id')),'N'))
                    cursor.execute("UPDATE commentaires SET upvote=upvote-1 WHERE id_commentaire=?",(id_com,))
                    db.commit()
               elif (session.get('id'),) not in likeur:
                    cursor.execute("INSERT INTO Vote_com(id_com,id_voteur,val) VALUES(?,?,?)",(id_com,str(session.get('id')),'N'))
                    cursor.execute("UPDATE commentaires SET upvote=upvote-1 WHERE id_commentaire=?",(id_com,))
                    db.commit()
               elif (session.get('id'),) in likeur:
                    cursor.execute("UPDATE Vote_com SET val=? WHERE id_com=? AND id_voteur=?",('N',id_com,str(session.get('id'))))
                    cursor.execute("UPDATE commentaires SET upvote=upvote-1 WHERE id_commentaire=?",(id_com,))
                    db.commit()
               cursor.execute("SELECT id_sub FROM posts JOIN commentaires ON commentaires.id_post=posts.id_post WHERE commentaires.id_commentaire=?",(id_com,))
               id=cursor.fetchall()[0][0]
               db.close()
               return redirect('/sub/'+str(id)+'/post')
          else:
               db.close()
               return render_template('erreur.html',message="Accès refusé",description="vous n'avez pas les droits d'accès nécessaires")
     else:
          db.close()
          return render_template('/erreur.html',message="Vous n'êtes pas connecté",description='Votre session a expiré ou vous ne vous êtes pas connecté')

#uplike du commentaire donnée
@app.route('/like/<id_post>')
def uplike(id_post):
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     if test_login():
          if test_verif() and post_existe(id_post):
               cursor.execute("SELECT id_voteur FROM Vote_post WHERE id_post=?",(id_post,))
               likeur=cursor.fetchall()
               if likeur==[]:
                    cursor.execute("INSERT INTO Vote_post(id_post,id_voteur,val) VALUES(?,?,?)",(id_post,str(session.get('id')),'P'))
                    cursor.execute("UPDATE posts SET ratio=ratio+1 WHERE id_post=?",(id_post,))
                    db.commit()
               elif (session.get('id'),) not in likeur:
                    cursor.execute("INSERT INTO Vote_post(id_post,id_voteur,val) VALUES(?,?,?)",(id_post,str(session.get('id')),'P'))
                    cursor.execute("UPDATE posts SET ratio=ratio+1 WHERE id_post=?",(id_post,))
                    db.commit()
               elif (session.get('id'),) in likeur:
                    cursor.execute("UPDATE Vote_post SET val=? WHERE id_post=? AND id_voteur=?",('P',id_post,str(session.get('id'))))
                    cursor.execute("UPDATE posts SET ratio=ratio+1 WHERE id_post=?",(id_post,))
                    db.commit()
               cursor.execute("SELECT id_sub FROM posts WHERE  id_post=?",(id_post,))
               id=cursor.fetchall()[0][0]
               db.close()
               return redirect('/sub/'+str(id)+'/post')
          else:
               db.close()
               return render_template('erreur.html',message="Accès refusé",description="vous n'avez pas les droits d'accès nécessaires")
     else:
          db.close()
          return render_template('/erreur.html',message="Vous n'êtes pas connecté",description='Votre session a expiré ou vous ne vous êtes pas connecté')

#downlike du commentaire donnée
@app.route('/dislike/<id_post>')
def downlike(id_post):
     db = sqlite3.connect('database.db')
     cursor = db.cursor()
     if test_login():
          if test_verif() and post_existe(id_post):
               cursor.execute("SELECT id_voteur FROM Vote_post WHERE id_post=?",(id_post,))
               likeur=cursor.fetchall()
               if likeur==[]:
                    cursor.execute("INSERT INTO Vote_post(id_post,id_voteur,val) VALUES(?,?,?)",(id_post,str(session.get('id')),'N'))
                    cursor.execute("UPDATE posts SET ratio=ratio-1 WHERE id_post=?",(id_post,))
                    db.commit()
               elif (session.get('id'),) not in likeur:
                    cursor.execute("INSERT INTO Vote_post(id_post,id_voteur,val) VALUES(?,?,?)",(id_post,str(session.get('id')),'N'))
                    cursor.execute("UPDATE posts SET ratio=ratio-1 WHERE id_post=?",(id_post,))
                    db.commit()
               elif (session.get('id'),) in likeur:
                    cursor.execute("UPDATE Vote_post SET val=? WHERE id_post=? AND id_voteur=?",('N',id_post,str(session.get('id'))))
                    cursor.execute("UPDATE posts SET ratio=ratio-1 WHERE id_post=?",(id_post,))
                    db.commit()
               cursor.execute("SELECT id_sub FROM posts WHERE  id_post=?",(id_post,))
               id=cursor.fetchall()[0][0]
               db.close()
               return redirect('/sub/'+str(id)+'/post')
          else:
               db.close()
               return render_template('erreur.html',message="Accès refusé",description="vous n'avez pas les droits d'accès nécessaires")
     else:
          db.close()
          return render_template('/erreur.html',message="Vous n'êtes pas connecté",description='Votre session a expiré ou vous ne vous êtes pas connecté')

#chat du sub donné
@app.route("/sub/<numsub>/chat", methods=["GET","POST"])
def chat(numsub):
     if test_login():
          if test_verif():
               user = session.get('id')
               if is_owner(numsub,user) or est_participant(numsub,user):
                    db = sqlite3.connect('database.db')
                    cursor = db.cursor()
                    id_posteur=session.get('id')
                    cursor.execute("""SELECT nom,prénom,message,date FROM chat JOIN utilisateurs WHERE numsub = ? AND id_user=id_posteur ORDER BY date""",(numsub,))
                    data=cursor.fetchall()
                    if request.method=='POST':
                         now = time.localtime(time.time())
                         message = request.form['message']
                         cursor.execute("""
                         INSERT INTO chat(numsub,id_posteur,message,date) values(?,?,?,?)""",(numsub,id_posteur,str(message),time.strftime("%y/%m/%d %H:%M", now)))
                         db.commit()
                         db.close()
                    abonne = est_abonne(numsub,user)
                    owner = is_owner(numsub,user)
                    participant = est_participant(numsub,user)
                    return render_template('chat.html',data=data,numsub=numsub,abonne=abonne,owner=owner,participant=participant)
               else :
                    return render_template('erreur.html',message="Accès refusé au chat",description="Vous n'êtes ni le créateur du projet ni un participant")

          else:
               return render_template('erreur.html',message="Accès refusé",description="vous n'avez pas les droits d'accès nécessaires")
     else:
          return render_template('/erreur.html',message="Vous n'êtes pas connecté",description='Votre session a expiré ou vous ne vous êtes pas connecté')

if __name__=='__main__':
     app.run(debug=1)


from PIL import Image

fileName = "monMons.txt"
length = 3
base = Image.open("baseMon.png")
pool = []

class mon(object):
    def __init__(self, color):
        self.color = color # As a integer tupple of 3 numbers

def importMons(fileName):
    monsArray = []
    with open(fileName, 'r') as f:
        fileContent = f.readlines()
        for i in range(len(fileContent)):
            line = (fileContent[i].strip("\n")).split(",") # splits the line into the core components
            if line[0][0] == "#": continue #ignores comments (denoted by "#" at the start)

            if(len(line) == length):
                monsArray.append(mon((int(line[0]), int(line[1]), int(line[2]) )))
            else:
                print("Line ", i+1, " is invalid")
    return monsArray

def writeMon(monData):
    strMonData = []
    for i in range(len(monData)):
        strMonData.append(str(monData[i]))

    with open(fileName, "a") as f:
        f.write(",".join(strMonData) + "\n")

#Let's create some monMons! ---------------------------------------------------
def getParents():
    p1,p2 = randint(0,len(pool)-1),randint(0,len(pool)-1)
    #Gets rid of any duplicates. We can't have any babies being born out of 1 person
    while p1 == p2:
        p2 = randint(0,len(pool)-1)

    return [pool[p1],pool[p2]]

def createChild():
    parents = getParents()

    childData = [
        parents[randint(0,1)].color[0],
        parents[randint(0,1)].color[1],
        parents[randint(0,1)].color[2],
    ]

    #Mutation of the child
    for i in range(3):
        chance = randint(1,chanceOfMutation)
        if chance == 1:
            chance = randint(-2,2)
            childData[i] += chance

    writeMon(childData)
    return mon(*childData)

def createChildren(numOfChildren):
    #Creates new children for the pool
    newMons = []
    for i in range(numOfChildren):
        newMons.append(createChild())
    return newMons
# Let's create some townsfolk! ------------------------------------------------
def paintMon(mon):
    img = Image.open("baseMon.png")
    for y in range(img.height):
        for x in range(img.width):
            if img.getpixel((x, y)) == (0,0,0):
                img.putpixel((x, y), (mon.color[0], mon.color[1], mon.color[2]))
    return img

#Main program start -----------------------------------------------------------
pool = importMons(fileName)

for i in range(len(pool)):
    paintMon(pool[i]).save("images/{}.png".format(i))


# -*- coding: utf-8 -*-
import scrapy
from isbn.items import IsbnLoader

class AmazonSpider(scrapy.Spider):
    name = "amazon"
    allowed_domains = ["amazon.cn"]
    custom_settings = {
        'COOKIES_ENABLED': True,
        'COOKIES_DEBUG': True,
        'DOWNLOAD_DELAY': 1,
        'DOWNLOADER_MIDDLEWARES': {
            'isbn.middlewares.RandomUserAgentMiddleware': 300,
        }
    }

    def __init__(self, isbn_list, *args, **kwargs):
        super(AmazonSpider, self).__init__(*args, **kwargs)
        self.isbn_list = isbn_list

    def start_requests(self):
        for isbn in self.isbn_list:
            url = f'https://www.amazon.cn/s/field-keywords={isbn}'
            yield scrapy.Request(url, meta={'isbn': isbn}, callback=self.parse)

    def parse(self, response):
        for div in response.xpath("//div[@class='s-item-container']"):
            url = div.xpath(".//a[contains(@class, 's-color-twister-title-link')]/@href").extract_first()
            print("url", url)
            if url:
                yield scrapy.Request(url=url, meta=response.meta, callback=self.parse_book_page)

    def parse_book_page(self, response):
        import isbnlib
        il = IsbnLoader(selector=response)
        il.add_xpath('title', ".//span[@id='productTitle' or @id='ebooksProductTitle']/text()")
        il.add_xpath('author', ".//span[@class='author notFaded']/a/text()")
        il.add_value('isbn', isbnlib.mask(response.meta['isbn']))
        il.add_xpath('publish', "//li[b/text()='出版社:']/text()")
        item = il.load_item()
        yield item

def from_file(filename):
    with open(filename) as f:
        url_list = f.readlines()
    return url_list

def main():
    from scrapy.crawler import CrawlerProcess
    from scrapy.utils.project import get_project_settings
    import re

    url_list = [
        # QQ 扫码得到的链接
        # "http://qm.qq.com/cgi-bin/result?r=9787302444060&p=i&v=7.0.1.407",
    ]
    # or from file
    url_list = set(url_list + from_file('list.txt'))
    isbn_list = [re.search('r=(\d*)', url).group(1) for url in url_list]
    print(isbn_list)
    settings = {**get_project_settings(), 'FEED_FORMAT': 'csv', 'FEED_URI': 'books.csv'}
    process = CrawlerProcess(settings)
    process.crawl(AmazonSpider, isbn_list)
    process.start()
    process.stop()

if __name__ == '__main__':
    main()


from datetime import datetime
from app import db

class Bloque(db.Model):
    __tablename__ = "bloques"

    id_bloque = db.Column(
        db.Integer, db.Sequence("bloques_id_bloque_seq"), primary_key=True, unique=True
    )
    id_sesion = db.Column(
        db.Integer,
        db.ForeignKey("sesiones.id_sesion", ondelete="cascade"),
        nullable=False,
    )
    ejercicios = db.relationship(
        "EjercicioXBloque",
        lazy="subquery",
        backref=db.backref("bloques", lazy=True),
        order_by="EjercicioXBloque.num_ejercicio",
        cascade="all, delete-orphan",
    )
    num_bloque = db.Column(db.Integer)
    series = db.Column(db.Integer)
    creado_en = db.Column(db.DateTime, default=datetime.utcnow)
    actualizado_en = db.Column(db.DateTime, default=None)

    def __init__(self, ejercicios, num_bloque, series, id_sesion=None):
        self.id_sesion = id_sesion
        self.ejercicios = ejercicios
        self.num_bloque = num_bloque
        self.series = series

    def __repr__(self):
        return "<Bloque {}>".format(self.id_bloque)

    def to_json(self):
        return {
            "id": self.id_bloque,
            "ejercicios": [ejercicio.to_json() for ejercicio in self.ejercicios],
            "numBloque": self.num_bloque,
            "series": self.series,
            "creadoEn": self.creado_en,
            "actualizadoEn": self.actualizdo_en,
        }

class EjercicioXBloque(db.Model):
    __tablename__ = "ejerciciosxbloque"

    id_ejerciciosxbloque = db.Column(
        db.Integer,
        db.Sequence("ejerciciosxbloque_id_ejerciciosxbloque_seq"),
        primary_key=True,
        unique=True,
    )
    id_ejercicio = db.Column(db.Integer, db.ForeignKey("ejercicios.id_ejercicio"))
    id_bloque = db.Column(db.Integer, db.ForeignKey("bloques.id_bloque"))
    num_ejercicio = db.Column(db.Integer)
    ejercicio = db.relationship("Ejercicio", uselist=False)
    # bloque = db.relationship("Bloque", uselist=False)
    repeticiones = db.Column(db.Integer)
    carga = db.Column(db.Float)

    def __init__(self, num_ejercicio, ejercicio, repeticiones, carga):
        self.num_ejercicio = num_ejercicio
        self.ejercicio = ejercicio
        self.repeticiones = repeticiones
        self.carga = carga

    def __repr__(self):
        return "<EjercicioXBloque {}>".format(self.id_ejerciciosxbloque)

    def to_json(self):
        return {
            "id": self.id_ejerciciosxbloque,
            "num_ejercicio": self.num_ejercicio,
            "ejercicio": self.ejercicio.nombre,
            "patron": self.ejercicio.patron.nombre,
            "carga": self.carga,
            "repeticiones": self.repeticiones,
        }


from flask_restful import Resource

from app.util.reqargs import with_args, Argument
from app.util.abi_data import create_transaction
from app.util.types import address
from eth_utils import to_bytes

class TCRExit(Resource):
    path = "/tcr/<addr>/exit"

    @with_args(
        Argument("sender", type=address),
        Argument("dataHash", type=str, dest="data_hash"),
    )
    def post(self, addr, sender, data_hash):
        return create_transaction(
            sender,
            addr,
            "exit(address,bytes32)",
            ("address", sender),
            ("bytes32", to_bytes(hexstr=data_hash)),
        )


from django.shortcuts import render
from django.shortcuts import redirect
from django.http import HttpResponse
import pandas as pd
import plotly.graph_objs as go
import plotly as plotly1
from .models import Image
from .models import ProbedataSatellite,FnirsDeoxySatellite,FnirsOxySatellite
# Create your views here.
def dataprocess(request):
    if not request.session.get('is_login', None):
        return redirect("/login/")
    if request.method == "POST":
        experiment_id=  request.POST.get('Experimentid')
        if experiment_id=='1':
            return redirect('/TEST/experiment1/')
        else:
            return redirect('/TEST/experiment2/')
    return render(request, 'TEST/dataprocessing.html')

def experiment2(request):
    if not request.session.get('is_login', None):
        return redirect("/login/")
    if request.method == "POST":
        j=[]
        for i in range(11,54):
            j.append(str(i))
        patient_id=  request.POST.get('patient_id')
        session_id=int(request.POST.get('sessionid'))
        if(patient_id not in j):
            return HttpResponse("This patient ID does not exist in Experiment 2")
        querySet=Image.objects.filter(patientid=patient_id,sessionid=session_id).values()
        df = pd.DataFrame(querySet)
        columns=df['datatype']
        return render(request, 'TEST/fNIRsdatatype.html',  {'columns': columns,'patient_id':patient_id,'sessionid':session_id})
    return render(request,'TEST/experiment2.html')

def experiment1(request):
    if not request.session.get('is_login', None):
        return redirect("/login/")
    if request.method == "POST":
        j=[]
        for i in range(1,11):
            j.append(str(i))
        patient_id= request.POST.get('patient_id')
        datatype=request.POST.get('datatype')
        probetype=request.POST.get('probetype')
        if(patient_id not in j):
            return HttpResponse("This patient ID does not exist in Experiment 1 ")
        else:
            if(probetype=='MES'):
                querySet = ProbedataSatellite.objects.filter(patient_id=patient_id,stimuli_type=datatype).values()
            else:
                if(probetype=='oxy'):
                    querySet = FnirsOxySatellite.objects.filter(patient_id=patient_id, fnirs_type=datatype).values()
                else:
                    querySet = FnirsDeoxySatellite.objects.filter(patient_id=patient_id, fnirs_type=datatype).values()
            df = pd.DataFrame(list(querySet))
            length=df.shape[0]
            columns=df.columns.tolist ()
            column123=[]
            for i in columns:
                if 'ch' in i:
                    column123.append(i)
            columns=column123
            return render(request, 'TEST/probedataex.html',  {'columns': columns,'patient_id':patient_id,'datatype':datatype,'probetype':probetype,'length':length})
    return render(request,'TEST/experiment1.html')

def probedata(request):
    if not request.session.get('is_login', None):
        return redirect("/login/")
    return render(request, 'TEST/experiment2.html')

def fNIRs(request):
    if not request.session.get('is_login', None):
        return redirect("/login/")
    if request.method == "POST":
        patient_id = request.POST.get('patient_id')
        datatype = request.POST.get('datatype')
        session_id = request.POST.get('session_id')
        querySet = Image.objects.filter(patientid=patient_id, sessionid=session_id,datatype=datatype).values()
        df = pd.DataFrame(list(querySet))
        image_data=df['data']
        return HttpResponse(image_data, content_type="image/png")
    return redirect("/index/")

def plot(request):
    if not request.session.get('is_login', None):
        return redirect("/login/")
    if request.method == "POST":
        patient_id= request.POST.get('patient_id')
        datatype=request.POST.get('datatype')
        quantity1=int(request.POST.get('quantity1'))
        quantity2=int(request.POST.get('quantity2'))
        probetype=request.POST.get('probetype')
        if (probetype == 'MES'):
            querySet = ProbedataSatellite.objects.filter(patient_id=patient_id, stimuli_type=datatype).values()
        else:
            if (probetype == 'oxy'):
                querySet = FnirsOxySatellite.objects.filter(patient_id=patient_id, fnirs_type=datatype).values()
            else:
                querySet = FnirsDeoxySatellite.objects.filter(patient_id=patient_id, fnirs_type=datatype).values()
        df = pd.DataFrame(list(querySet))
        columns = df.columns.tolist()
        columnlist=[]
        for i in columns:
            c=request.POST.get(i)
            if(c=='1.1'):
                columnlist.append(i)
        listfin=[]
        listout=[]
        df=df.loc[quantity1:quantity2,columnlist]
        out=quantity2+1-quantity1
        for i in range(quantity1,quantity2+1):
            listfin.append(i)
        for j in range(out):
            listout.append(j)
        text = []
        for column in columnlist:
            x1=listfin
            y1=[k for k in df[column]]
            trace = go.Scatter(
                x=x1,
                y=y1,
                textposition='top center',
                mode='markers+text+lines',
                name=column,  # Style name/legend entry with html tags
                connectgaps=True  # 是否连接缺失值
            )
            text.append(trace)
        layout = go.Layout(
            autosize=False,
            width=3000,
            height=2000,
            xaxis=go.layout.XAxis(linecolor='black',
                                  linewidth=1,
                                  mirror=True),

            yaxis=go.layout.YAxis(linecolor='black',
                                  linewidth=1,
                                  mirror=True),

            margin=go.layout.Margin(
                l=50,
                r=50,
                b=100,
                t=100,
                pad=4
            )
        )
        fig = go.Figure(data=text, layout=layout)
        graph_div = plotly1.offline.plot(fig, auto_open = True, output_type="div")
        return render(request, 'TEST/probedataplot.html',{'graph_div':graph_div,'patient_id':patient_id,'datatype':datatype,'probetype':probetype})
    return render(request,'TEST/probedataplot.html')


import datetime
import logging

import math
import os
import pickle

from pytocl.analysis import DataLogWriter
from pytocl.car import State, Command, MPS_PER_KMH
from pytocl.controller import CompositeController, ProportionalController, IntegrationController, \
    DerivativeController

_logger = logging.getLogger(__name__)

class Driver:
    """Driving logic.

    Implement the driving intelligence in this class by processing the current car state as inputs
    creating car control commands as a response. The ``drive`` function is called periodically
    every 20ms and must return a command within 10ms wall time.
    """

    def __init__(self, logdata=True):
        self.steering_ctrl = CompositeController(
            ProportionalController(0.4),
            IntegrationController(0.2, integral_limit=1.5),
            DerivativeController(2)
        )
        self.acceleration_ctrl = CompositeController(
            ProportionalController(3.7),
        )
        self.data_logger = DataLogWriter() if logdata else None

    @property
    def range_finder_angles(self):
        """Iterable of 19 fixed range finder directions [deg].

        The values are used once at startup of the client to set the directions of range finders.
        During regular execution, a 19-valued vector of track distances in these directions is
        returned in ``state.State.tracks``.
        """
        return -90, -75, -60, -45, -30, -20, -15, -10, -5, 0, 5, 10, 15, 20, 30, 45, 60, 75, 90

    def on_shutdown(self):
        """Server requested driver shutdown.

        Optionally implement this event handler to clean up or write data before the application is
        stopped.
        """
        if self.data_logger:
            self.data_logger.close()
            self.data_logger = None

    def drive(self, carstate: State) -> Command:
        """Produces driving command in response to newly received car state.

        This is a dummy driving routine, very dumb and not really considering a lot of inputs. But
        it will get the car (if not disturbed by other drivers) successfully driven along the race
        track.
        """
        command = Command()
        self.steer(carstate, 0.0, command)

        #ACC_LATERAL_MAX = 6400 * 5
        #v_x = min(80, math.sqrt(ACC_LATERAL_MAX / abs(command.steering)))
        v_x = 80

        self.accelerate(carstate, v_x, command)

        if self.data_logger:
            self.data_logger.log(carstate, command)

        return command

    def accelerate(self, carstate, target_speed, command):
        # compensate engine deceleration, but invisible to controller to prevent braking:
        speed_error = 1.0025 * target_speed * MPS_PER_KMH - carstate.speed_x
        acceleration = self.acceleration_ctrl.control(speed_error, carstate.current_lap_time)

        # stabilize use of gas and brake:
        acceleration = math.pow(acceleration, 3)

        if acceleration > 0:
            if abs(carstate.distance_from_center) >= 1:
                # off track, reduced grip:
                acceleration = min(0.4, acceleration)

            command.accelerator = min(acceleration, 1)

            if carstate.rpm > 8000:
                command.gear = carstate.gear + 1

        #else:
        #    command.brake = min(-acceleration, 1)

        if carstate.rpm < 2500:
            command.gear = carstate.gear - 1

        if not command.gear:
            command.gear = carstate.gear or 1

    def steer(self, carstate, target_track_pos, command):
        steering_error = target_track_pos - carstate.distance_from_center
        command.steering = self.steering_ctrl.control(steering_error, carstate.current_lap_time)


import requests
import json
import os
import sys
import re

oldDir = input("enter Directory");

movieList=[]

apiUrl = 'http://www.omdbapi.com/?tomatoes=true&t='

try:
	movieList = os.listdir(oldDir)
except Exception as e:
	print('No such Directory found !')
	sys.exit(0)

def getExactMovieName(movie):
	# delete everything starting with (
	n_movie = re.sub(r'\(.*$', '', movie)
	n_movie = re.sub(r'\d.*$', '', n_movie)
	n_movie = re.sub(r'\.', ' ', n_movie)
	return n_movie;

for movie in movieList:
	try:
		n_movie = getExactMovieName(movie)
		print('requesting for '+n_movie)
		result = requests.get(apiUrl+n_movie)
		j_result = json.loads(result.text)
		if oldDir[-1] != '/':
			oldDir+='/'
		imdbRating = j_result['imdbRating']
		tomatoRating = j_result['tomatoRating']
		newDir = oldDir+'IMDB('+imdbRating+') TOMATO('+tomatoRating+') '+n_movie+'/'
		os.mkdir(newDir)
		os.rename(oldDir+movie , newDir+movie)
		with open(newDir+'info.txt', 'w+') as fp:
			fp.write(result.text)
		print('request completed for '+n_movie)
	except Exception as e:
		print("IMDB rating not found")


# -*- coding: utf-8 -*-
import datetime
from collections import namedtuple

import h5py

from dlgo import agent
from dlgo import scoring
from dlgo.goboard_fast import GameState, Player, Point

BOARD_SIZE = 19
COLS = 'ABCDEFGHJKLMNOPQRST'
STONE_TO_CHAR = {
    None: '.',
    Player.black: 'x',
    Player.white: 'o',
}

def avg(items):
    if not items:
        return 0.0
    return sum(items) / float(len(items))

def print_board(board):
    for row in range(BOARD_SIZE, 0, -1):
        line = []
        for col in range(1, BOARD_SIZE + 1):
            stone = board.get(Point(row=row, col=col))
            line.append(STONE_TO_CHAR[stone])
        print('%2d %s' % (row, ''.join(line)))
    print('   ' + COLS[:BOARD_SIZE])

class GameRecord(namedtuple('GameRecord', 'moves winner margin')):
    pass

def name(player):
    if player == Player.black:
        return 'B'
    return 'W'

def simulate_game(black_player, white_player):
    moves = []
    game = GameState.new_game(BOARD_SIZE)
    agents = {
        Player.black: black_player,
        Player.white: white_player,
    }
    while not game.is_over():
        next_move = agents[game.next_player].select_move(game)
        moves.append(next_move)
        # if next_move.is_pass:
        #    print('%s passes' % name(game.next_player))
        game = game.apply_move(next_move)

    print_board(game.board)
    game_result = scoring.compute_game_result(game)
    print(game_result)

    return GameRecord(
        moves=moves,
        winner=game_result.winner,
        margin=game_result.winning_margin,
    )

def main():
    # parser = argparse.ArgumentParser()
    # parser.add_argument('--agent1', required=True)
    # parser.add_argument('--agent2', required=True)
    # parser.add_argument('--num-games', '-n', type=int, default=10)
    #
    # args = parser.parse_args()
    #
    # agent1 = agent.load_policy_agent(h5py.File(args.agent1))
    # agent2 = agent.load_policy_agent(h5py.File(args.agent2))

    # ==================================================
    import os
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

    import tensorflow as tf
    config = tf.compat.v1.ConfigProto()
    config.gpu_options.per_process_gpu_memory_fraction = 0.95
    config.gpu_options.allow_growth = True
    config.log_device_placement = True
    sess = tf.compat.v1.Session(config=config)
    tf.compat.v1.keras.backend.set_session(sess)
    # ==================================================
    pth = '//home//nail//Code_Go//checkpoints//'
    num_games = int(input("Количество игр :"))
    agent1 = input('Игрок(агент) №1:')
    agent2 = input('Игрок(агент) №2:')
    agent1 = pth + agent1+".h5"
    agent2 = pth + agent2+".h5"
    agent1 = agent.load_policy_agent(h5py.File(agent1, "r"))
    agent2 = agent.load_policy_agent(h5py.File(agent2, "r"))

    wins = 0
    losses = 0
    color1 = Player.black

    for i in range(num_games):
        print('Симуляция игры %d/%d...' % (i + 1, num_games))  # args.num_games))
        if color1 == Player.black:
            black_player, white_player = agent1, agent2
            print('Агент №1 - играет Черными, Агент №2  - играет Белыми')
        else:
            white_player, black_player = agent1, agent2
            print('Агент №1 - играет Белыми, Агент №2  - играет Черными')
        game_record = simulate_game(black_player, white_player)
        if game_record.winner == color1:
            wins += 1
        else:
            losses += 1
        color1 = color1.other
    print('Agent 1 record: %d/%d' % (wins, wins + losses))

if __name__ == '__main__':
    main()


import sys
import os
import shutil

from pyspark.sql.types import *
from pyspark.sql import SparkSession
from pyspark.sql.types import *

def process_list_to_df(spark, csv_file, my_schema):
    """"
    :param spark: sparksession
    :param csv_file: data as csv file
    :param schema: schema
    :return:
    """
    data_df = spark.read.csv(csv_file, header=True, schema=my_schema)
    return data_df

def save_df_to_format(file_df, exp_format="parquet", save_path="./mnm_dataset.pq"):
    """"
    :param file_df: input dataframe
    :param exp_format: output format
    :param save_path: destination
    :return: None
    """
    file_df.write.format(exp_format).save(save_path)
    print(f"saved to the format : {exp_format} and @ : {save_path}")

if __name__ == '__main__':
    # schema definition
    my_file = sys.argv[1]
    my_schema = StructType([
        StructField("State", IntegerType(), False),
        StructField("Color", StringType(), False),
        StructField("Count", IntegerType(), False),
        ])

    spark = (SparkSession
             .builder
             .appName("exo5").getOrCreate())

    authors_df = process_list_to_df(spark, my_file, my_schema)
    out = "output.pq"
    if os.path.exists(out):
        shutil.rmtree(out)
    # save csv file to parquet format (it includes data format)
    save_df_to_format(authors_df, exp_format="parquet", save_path=out)


import json
import unittest

from bootstrap.create_content import create_content_handler

class TestCreateContent(unittest.TestCase):
    @staticmethod
    def get_base_event():
        """
        Sample event from https://docs.aws.amazon.com/lambda/latest/dg/lambda-services.html
        :return: dict
        """
        return {
            "requestContext": {
                "elb": {
                    "targetGroupArn": "arn:aws:elasticloadbalancing:us-east-2:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a"
                }
            },
            "httpMethod": "GET",
            "path": "/lambda",
            "queryStringParameters": {
                "query": "1234ABCD"
            },
            "headers": {
                "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
                "accept-encoding": "gzip",
                "accept-language": "en-US,en;q=0.9",
                "connection": "keep-alive",
                "host": "lambda-alb-123578498.us-east-2.elb.amazonaws.com",
                "upgrade-insecure-requests": "1",
                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
                "x-amzn-trace-id": "Root=1-5c536348-3d683b8b04734faae651f476",
                "x-forwarded-for": "72.12.164.125",
                "x-forwarded-port": "80",
                "x-forwarded-proto": "http",
                "x-imforwards": "20"
            },
            "body": "",
            "isBase64Encoded": False
        }

    def test_main(self):
        # given
        event = TestCreateContent.get_base_event()
        context = {"aws_request_id": 1111}  # https://docs.aws.amazon.com/lambda/latest/dg/python-context.html
        # when
        result = create_content_handler(event, context)
        # then
        self.assertEqual(json.loads(result["body"])["message"], "Hello 1234ABCD!")


from rest_framework import routers
from django.urls import path, include
from apps.managers.views import (
    TaskView,
    TaskDetailView,
    MyTaskView,
    CompletedTaskView,
    AssignTaskToUser,
    CompleteTaskView,
    # CommentAddView,
    # CommentView,
    TimeWorkView,
    TimeView,
    TaskMonthView,
    TopBiggestTimeTask,
)

router = routers.SimpleRouter()
router.register(r'work-time', TimeWorkView)
router.register(r'time', TimeView)
router.register(r'task', TaskView)

urlpatterns = [
    #path('task', TaskView.as_view(), name='create-task-view'),
    path('task/detail/<int:pk>', TaskDetailView.as_view(), name='task-info-view'),
    path('task/top-biggest-time-task', TopBiggestTimeTask.as_view(), name='task-time-log-view'),
    path('time-month', TaskMonthView.as_view(), name='task-time-log-view'),
    path('mytask', MyTaskView.as_view(), name='my-task-view'),
    path('complete', CompletedTaskView.as_view(), name='completed-task'),
    path('add-task-to-user/<int:pk>/', AssignTaskToUser.as_view(), name="add-task-to-user"),
    path('complete/<int:pk>', CompleteTaskView.as_view(), name="complete-task-view"),
    path('test/', include("apps.managers.GenericTest.urls"))

]
urlpatterns += router.urls


import threading
import json

class Session():
  def __init__(cls, session_id, client_socket):
    cls.session_id = session_id;
    cls.client_socket = client_socket;
    cls.context = dict();
    cls.context_lock = threading.Lock();

  # 세션 컨텍스트에 데이터 저장
  def add_context(cls, key, value):
    cls.context_lock.acquire();
    cls.context[key] = value;
    cls.context_lock.release();

  # 세션 컨텍스트에서 데이터 가져오기
  def get_context(cls, key):
    cls.context_lock.acquire();
    result = (False, None);
    if key in cls.context:
      result = (True, cls.context[key]);

    cls.context_lock.release();
    return result;

  # 명시적 소켓 종료
  def close_socket(cls):
    cls.client_socket.close();

  # 이 세션에 메시지 보내기
  def send_message(cls, message):
    msg = json.dumps(message);
    print("session_id:", cls.session_id, "send message=", msg);
    bytes = msg.encode();
    msg_len = len(bytes);

    cls.client_socket.sendall(msg_len.to_bytes(4, byteorder="little"));
    cls.client_socket.sendall(bytes);


from typing import Any, Dict, Mapping, Optional

from airbyte_cdk.config_observation import emit_configuration_as_airbyte_control_message
from airbyte_cdk.models import ConnectorSpecification
from airbyte_cdk.sources.file_based.file_based_source import FileBasedSource
from airbyte_cdk.utils import is_cloud_environment
from source_s3.source import SourceS3Spec
from source_s3.v4.legacy_config_transformer import LegacyConfigTransformer

_V3_DEPRECATION_FIELD_MAPPING = {
    "dataset": "streams.name",
    "format": "streams.format",
    "path_pattern": "streams.globs",
    "provider": "bucket, aws_access_key_id, aws_secret_access_key and endpoint",
    "schema": "streams.input_schema",
}

class SourceS3(FileBasedSource):
    def read_config(self, config_path: str) -> Mapping[str, Any]:
        """
        Used to override the default read_config so that when the new file-based S3 connector processes a config
        in the legacy format, it can be transformed into the new config. This happens in entrypoint before we
        validate the config against the new spec.
        """
        config = super().read_config(config_path)
        if not self._is_v4_config(config):
            parsed_legacy_config = SourceS3Spec(**config)
            converted_config = LegacyConfigTransformer.convert(parsed_legacy_config)
            emit_configuration_as_airbyte_control_message(converted_config)
            return converted_config
        return config

    def spec(self, *args: Any, **kwargs: Any) -> ConnectorSpecification:
        s3_spec = SourceS3Spec.schema()
        s4_spec = self.spec_class.schema()

        if s3_spec["properties"].keys() & s4_spec["properties"].keys():
            raise ValueError("Overlapping properties between V3 and V4")

        for v3_property_key, v3_property_value in s3_spec["properties"].items():
            s4_spec["properties"][v3_property_key] = v3_property_value
            s4_spec["properties"][v3_property_key]["airbyte_hidden"] = True
            s4_spec["properties"][v3_property_key]["order"] += 100
            s4_spec["properties"][v3_property_key]["description"] = (
                SourceS3._create_description_with_deprecation_prefix(_V3_DEPRECATION_FIELD_MAPPING.get(v3_property_key, None))
                + s4_spec["properties"][v3_property_key]["description"]
            )
            self._clean_required_fields(s4_spec["properties"][v3_property_key])

        if is_cloud_environment():
            s4_spec["properties"]["endpoint"].update(
                {
                    "description": "Endpoint to an S3 compatible service. Leave empty to use AWS. "
                    "The custom endpoint must be secure, but the 'https' prefix is not required.",
                    "pattern": "^(?!http://).*$",  # ignore-https-check
                }
            )

        return ConnectorSpecification(
            documentationUrl=self.spec_class.documentation_url(),
            connectionSpecification=s4_spec,
        )

    def _is_v4_config(self, config: Mapping[str, Any]) -> bool:
        return "streams" in config

    @staticmethod
    def _clean_required_fields(v3_field: Dict[str, Any]) -> None:
        """
        Not having V3 fields root level as part of the `required` field is not enough as the platform will create empty objects for those.
        For example, filling all non-hidden fields from the form will create a config like:
        ```
        {
          <...>
          "provider": {},
          <...>
        }
        ```

        As the field `provider` exists, the JSON validation will be applied and as `provider.bucket` is needed, the validation will fail
        with the following error:
        ```
          "errors": {
            "connectionConfiguration": {
              "provider": {
                "bucket": {
                  "message": "form.empty.error",
                  "type": "required"
                }
              }
            }
          }
        ```

        Hence, we need to make any V3 nested fields not required.
        """
        if "properties" not in v3_field:
            return

        v3_field["required"] = []
        for neste_field in v3_field["properties"]:
            SourceS3._clean_required_fields(neste_field)

    @staticmethod
    def _create_description_with_deprecation_prefix(new_fields: Optional[str]) -> str:
        if new_fields:
            return f"Deprecated and will be removed soon. Please do not use this field anymore and use {new_fields} instead. "
        return "Deprecated and will be removed soon. Please do not use this field anymore. "