from django.shortcuts import render , get_object_or_404,redirect
from . models import Article , Category , Comment
from django.core.paginator import Paginator
from django.db.models import Q
from .forms import CommentForm ,CreateForm

def index(request):
    cat = Category.objects.all()
    breking = Article.objects.all().order_by("-id")

    fontlead = Article.objects.all().filter(lead=True).order_by("-id")
    paginator = Paginator(fontlead, 1)  # Show 25 contacts per page
    page = request.GET.get('page')
    pagfontlead = paginator.get_page(page)

    sidelead = Article.objects.all().filter(lead2=True).exclude(lead=True).order_by("-id")
    paginator = Paginator(sidelead, 2)  # Show 25 contacts per page
    page = request.GET.get('page')
    pagsidelead = paginator.get_page(page)

    ban = Article.objects.all().filter(category__id=1).exclude(lead3=True).order_by("-id")
    paginator = Paginator(ban, 3)  # Show 25 contacts per page
    page = request.GET.get('page')
    pagban = paginator.get_page(page)

    banlead = Article.objects.all().filter(category__id=1).filter(lead3=True).order_by("-id")
    paginator = Paginator(banlead, 1)  # Show 25 contacts per page
    page = request.GET.get('page')
    pagbanlead = paginator.get_page(page)

    inter = Article.objects.all().filter(category__id=2).order_by("-id")
    paginator = Paginator(inter, 5)  # Show 25 contacts per page
    page = request.GET.get('page')
    paginter = paginator.get_page(page)

    latest = Article.objects.all().order_by("-id")
    paginator = Paginator(latest, 5)  # Show 25 contacts per page
    page = request.GET.get('page')
    paglatest = paginator.get_page(page)

    sport = Article.objects.all().filter(category__id=3).order_by("-id")
    paginator = Paginator(sport, 6)  # Show 25 contacts per page
    page = request.GET.get('page')
    pagsport = paginator.get_page(page)

    tain = Article.objects.all().filter(category__id=4).exclude(lead3=True).order_by("-id")
    paginator = Paginator(tain, 3)  # Show 25 contacts per page
    page = request.GET.get('page')
    pagtain = paginator.get_page(page)

    tainlead = Article.objects.all().filter(category__id=4).filter(lead3=True).order_by("-id")
    paginator = Paginator(tainlead, 1)  # Show 25 contacts per page
    page = request.GET.get('page')
    pagtainlead = paginator.get_page(page)

    popular = Article.objects.all().order_by("-id")
    paginator = Paginator(popular, 4)  # Show 25 contacts per page
    page = request.GET.get('page')
    pagpopular = paginator.get_page(page)

    ict = Article.objects.all().filter(category__id=5).exclude(lead3=True).order_by("-id")
    paginator = Paginator(ict, 4)  # Show 25 contacts per page
    page = request.GET.get('page')
    pagict = paginator.get_page(page)

    ictlead = Article.objects.all().filter(category__id=5).filter(lead3=True).order_by("-id")
    paginator = Paginator(ictlead, 1)  # Show 25 contacts per page
    page = request.GET.get('page')
    pagictlead = paginator.get_page(page)

    life = Article.objects.all().filter(category__id=5).exclude(lead3=True).order_by("-id")
    paginator = Paginator(life, 4)  # Show 25 contacts per page
    page = request.GET.get('page')
    paglife = paginator.get_page(page)

    lifelead = Article.objects.all().filter(category__id=5).filter(lead3=True).order_by("-id")
    paginator = Paginator(lifelead, 1)  # Show 25 contacts per page
    page = request.GET.get('page')
    paglifelead = paginator.get_page(page)

    job = Article.objects.all().filter(category__id=5).exclude(lead3=True).order_by("-id")
    paginator = Paginator(job, 4)  # Show 25 contacts per page
    page = request.GET.get('page')
    pagjob = paginator.get_page(page)

    joblead = Article.objects.all().filter(category__id=5).filter(lead3=True).order_by("-id")
    paginator = Paginator(joblead, 1)  # Show 25 contacts per page
    page = request.GET.get('page')
    pagjoblead = paginator.get_page(page)

    search = request.GET.get("q")
    if search:
        breking=breking.filter(
            Q(title__icontains=search) |
            Q(body__icontains=search)
        )

    return render(request, "index.html", {
        "cat":cat,
        "breking":breking ,
        "ban":pagban,
        "inter":inter,
        "banlead":pagbanlead,
        "fontlead":pagfontlead,
        "sidelead":pagsidelead,
        "inter":paginter,
        "latest":paglatest,
        "sport":pagsport,
        "tain":pagtain,
        "tainlead":pagtainlead,
        "popular":pagpopular,
        "ict":pagict,
        "ictlead":pagictlead,
        "life":paglife,
        "lifelead":paglifelead,
        "job":pagjob,
        "joblead":pagjoblead,

        })

def singel(request, id):
    cat = Category.objects.all()
    breking = Article.objects.all().order_by("-id")
    post = get_object_or_404(Article, pk=id)

    latest = Article.objects.all().exclude(id=id).order_by("-id")
    paginator = Paginator(latest, 8)  # Show 25 contacts per page
    page = request.GET.get('page')
    paglatest = paginator.get_page(page)

    popular = Article.objects.all().order_by("-id")
    paginator = Paginator(popular, 4)  # Show 25 contacts per page
    page = request.GET.get('page')
    pagpopular = paginator.get_page(page)

    first = Article.objects.first()
    last = Article.objects.last()
    if True:
        if post.id > 1:
            firstpost = get_object_or_404(Article, pk=id-1)
        else:
            firstpost = get_object_or_404(Article, pk=id)
    if True:
        if post.id < last.id:
            lastpost = get_object_or_404(Article, pk=id+1)
        else:
            lastpost = get_object_or_404(Article, pk=id)
    com = Comment.objects.filter(post=id)
    form = CommentForm(request.POST or None)
    if form.is_valid():
        instance=form.save(commit=False)
        instance.post=post
        instance.save();

    return render(request, "single.html", {
        "cat":cat,
        "breking":breking,
        "post": post ,
        "latest":paglatest,
        "popular":pagpopular,
        "com":com,
        "form":form,
        "first":first,
        "last":last,
        "firstpost":firstpost,
        "lastpost":lastpost
     })

def topic(request, id):
    cat = Category.objects.all()
    breking = Article.objects.all().order_by("-id")

    popular = Article.objects.all().order_by("-id")
    paginator = Paginator(popular, 4)  # Show 25 contacts per page
    page = request.GET.get('page')
    pagpopular = paginator.get_page(page)

    cate = get_object_or_404(Category, pk=id)

    post = Article.objects.all().filter(category__id=id)
    paginator = Paginator(post, 8)  # Show 25 contacts per page
    page_number = request.GET.get('page')
    pagpost = paginator.get_page(page_number)

    latest = Article.objects.all().order_by("-id")
    paginator = Paginator(latest, 8)  # Show 25 contacts per page
    page = request.GET.get('page')
    paglatest = paginator.get_page(page)

    return render(request, "category.html", {
        "cat":cat,
        "breking":breking,
        "popular":pagpopular,
        "post":pagpost,
        "latest":paglatest,
        "cate":cate,

    })

def create(request):
    cat = Category.objects.all()
    breking = Article.objects.all().order_by("-id")
    if request.user.is_authenticated:
        form = CreateForm(request.POST or None, request.FILES or None)
        if form.is_valid():
            instance=form.save(commit=False)
            instance.save();
            return redirect('home')
    else:
        return redirect('home')
    return render(request, "create.html" , {"form":form,"cat":cat,"breking":breking })


# Python
import os, sys
from uuid import UUID

from sqlalchemy.orm import joinedload
# FastAPI
from fastapi import FastAPI, Depends, Body, Query, Path
from fastapi_pagination import Page, Params, paginate
from fastapi_sqlalchemy import DBSessionMiddleware, db

from .models import Property as ModelProperty
from .models import Owner as ModelOwner
from .schemas import Property as SchemaProperty
from .schemas import Owner as SchemaOwner
from dotenv import load_dotenv

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
load_dotenv(os.path.join(BASE_DIR, ".env"))
sys.path.append(BASE_DIR)

app = FastAPI()

app.add_middleware(DBSessionMiddleware, db_url=os.environ["DATABASE_URL"])

@app.get("/api/ping")
def home():
    return {"ping": "pong"}

@app.get("/api/properties", response_model=Page[SchemaProperty])
def get_properties(params: Params = Depends()):
    properties = db.session.query(ModelProperty).all()
    return paginate(properties, params)

@app.post("/api/properties", response_model=SchemaProperty)
def create_property(property: SchemaProperty):
    db_property = ModelProperty(
        bed = property.bed,
        bath = property.bath,
        parking_spots = property.parking_spots,
        size = property.size,
        price = property.price,
        type = property.type.value
    )
    db.session.add(db_property)
    db.session.commit()
    return db_property

@app.get("/api/owners", response_model=Page[SchemaOwner])
def get_owners(params: Params = Depends()):
    owners = db.session.query(ModelOwner).all()
    return paginate(owners, params)

@app.get("/api/owner/{owner_id}/properties", response_model=SchemaOwner)
def get_properties_by_owner(owner_id:UUID):
    db_owner = db.session.query(ModelOwner).options(joinedload(ModelOwner.properties)).where(ModelOwner.id == owner_id).one()
    return db_owner;


import pygame
import random

class Button:
    global mass
    def __init__(self, path, text, x, y):
        self.im = pygame.image.load(path)
        self.path = path
        self.text = text
        self.x = x
        self.y = y
        ger1 = self.im.get_rect(
        bottomright=(x, y))
        screen.blit(self.im, ger1)

class Button1(Button):
    def izobr(self):
        self.im = pygame.image.load(self.path)
        ger1 = self.im.get_rect(
        bottomright=(self.x, self.y))
        screen.blit(self.im, ger1)
    def delete(self):
        self.im = pygame.image.load("pr1.png")
        self.path = "pr1.png"
        ger1 = self.im.get_rect(
        bottomright=(self.x, self.y))
        screen.blit(self.im, ger1)

def igra(screen, s, n):
    global r, r1, r2, r3
    k = []
    k1 = []
    for i in range(37):
        k1.append(list(s[i]))
    for i in range(1, 36):
        for j in range(1, 36):
            x1 = []
            x1.append(s[i][j - 1])
            x1.append(s[i - 1][j])
            x1.append(s[i + 1][j])
            x1.append(s[i][j + 1])
            x1.append(s[i - 1][j + 1])
            x1.append(s[i + 1][j + 1])
            x1.append(s[i - 1][j - 1])
            x1.append(s[i + 1][j - 1])
            d = x1.count(n)
            d1 = x1.count(0)
            if (d1 == 5 or d1 == 6) and s[i][j] == n:
                k.append([i - 1, j - 1])
                k1[i][j] = n
            elif d >= 3 and s[i][j] != n:
                i1, j1 = i - 1, j - 1
                if s[i][j] == 1:
                    del r[r.index([i1, j1])]
                if s[i][j] == 2:
                    del r1[r1.index([i1, j1])]
                if s[i][j] == 3:
                    del r2[r2.index([i1, j1])]
                if s[i][j] == 4:
                    del r3[r3.index([i1, j1])]
                k.append([i - 1, j - 1])
                k1[i][j] = n
            elif s[i][j] == n:
                k1[i][j] = 0
    return k, k1

class Board:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.board = [[0] * width for _ in range(height)]
        self.left = 10
        self.k = 1
        self.top = 10
        self.s2 = []
        for i in range(height):
            self.s2.append([])
            for j in range(width):
                self.s2[i].append([])
        self.cell_size = 30

    def set_view(self, left, top, cell_size):
        self.left = left
        self.top = top
        self.cell_size = cell_size

    def render(self, screen):
        s = self.left
        s1 = self.top
        m = self.cell_size
        y = self.width
        y1 = self.height
        for i in range(y1):
            for j in range(y):
                pygame.draw.rect(screen, (255, 255, 255), (s, s1, m, m), 1)
                if self.k == 1:
                    self.s2[i][j] = [s, s1]
                s = s + m
            s = self.left
            s1 = s1 + m
        self.k = 0

    def click(self, screen, x):
        m = self.cell_size
        for i in range(self.height):
            for j in range(self.width):
                a = self.s2[i][j][0]
                a1 = self.s2[i][j][0] + m
                b = self.s2[i][j][1]
                b1 = self.s2[i][j][1] + m
                if x[0] > a and x[0] < a1 and x[1] > b and \
                   x[1] < b1:
                       return i, j

class Life(Board):
    def life(self, screen, r, r1, r2, r3):
        for i in range(len(r)):
            m = self.cell_size
            s = r[i][1] * m + 1
            s1 = r[i][0] * m + 1
            pygame.draw.rect(screen, (0, 255, 0), (s, s1, m - 2, m - 2))
        for i in range(len(r1)):
            m = self.cell_size
            s = r1[i][1] * m + 1
            s1 = r1[i][0] * m + 1
            pygame.draw.rect(screen, (0, 255, 255), (s, s1, m - 2, m - 2))
        for i in range(len(r2)):
            m = self.cell_size
            s = r2[i][1] * m + 1
            s1 = r2[i][0] * m + 1
            pygame.draw.rect(screen, (255, 255, 0), (s, s1, m - 2, m - 2))
        for i in range(len(r3)):
            m = self.cell_size
            s = r3[i][1] * m + 1
            s1 = r3[i][0] * m + 1
            pygame.draw.rect(screen, (255, 0, 0), (s, s1, m - 2, m - 2))

    def start(self, screen, s, n):
        k, k1 = igra(screen, s, n)
        return k, k1

pygame.init()
pygame.display.set_caption('Жизнь')
size = width, height = 940, 800
screen = pygame.display.set_mode(size)
board = Life(35, 35)
board.set_view(0, 0, 20)
k = 0
font = pygame.font.Font(None, 30)
font1 = pygame.font.Font(None, 60)
k1 = 0
clock = pygame.time.Clock()
s = [[0] * 37 for _ in range(37)]
running = True
r = []
dd = 0
hh = 0
fps = 500
t = 1
dd1 = []
t1 = 1
r1 = []
r2 = []
mass = []
r3 = []
pomoch = 0
koef = 0
ggg = 0
spisok = [1, 2, 3, 4]
pygame.display.flip()
vyhod = 0
colser = 0
ss = "Начните игру"
stav1 = 0
pobeda = 0
stav2 = 0
cpec = 0
ser = [1, 1, 1, -1, -1, -1]
i21 = Button1('pr2.png', '', 820, 680)
i22 = Button1('pr2.png', '', 860, 680)
i23 = Button1('pr2.png', '', 900, 680)
i11 = Button1('pr.png', '', 820, 150)
i12 = Button1('pr.png', '', 860, 150)
i13 = Button1('pr.png', '', 900, 150)
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and k1 == 0:
            k = 1
            if (event.pos[0] < 900) and (event.pos[1] < 60) and (event.pos[0] + 171 > 900) and (event.pos[1] + 47 > 60) and ggg == 0 and pomoch != 1:
                ss = "Начните игру"
                pob = -1
                posx1 = random.randint(1, 31)
                posy1 = random.randint(1, 31)
                pov1 = random.randint(1, 2)
                posx2 = posx1
                posy2 = posy1
                while ((posx2 > posx1 - 4) and (posx2 < posx1 + 4)) or ((posy2 > posy1 - 4) and (posy2 < posy1 + 4)):
                    posx2 = random.randint(1, 31)
                    posy2 = random.randint(1, 31)
                pov2 = random.randint(1, 2)
                posx3 = posx1
                posy3 = posy1
                while ((posx3 > posx1 - 4) and (posx3 < posx1 + 4)) or ((posy3 > posy1 - 4) and (posy3 < posy1 + 4)) or \
                      ((posx3 > posx2 - 4) and (posx3 < posx2 + 4)) or ((posy3 > posy2 - 4) and (posy3 < posy2 + 4)):
                    posx3 = random.randint(1, 31)
                    posy3 = random.randint(1, 31)
                pov3 = random.randint(1, 2)
                posx4 = posx1
                posy4 = posy1
                while ((posx4 > posx1 - 4) and (posx4 < posx1 + 4)) or ((posy4 > posy1 - 4) and (posy4 < posy1 + 4)) or \
                      ((posx4 > posx2 - 4) and (posx4 < posx2 + 4)) or ((posy4 > posy2 - 4) and (posy4 < posy2 + 4)) or \
                      ((posx4 > posx3 - 4) and (posx4 < posx3 + 4)) or ((posy4 > posy3 - 4) and (posy4 < posy3 + 4)):
                    posx4 = random.randint(1, 31)
                    posy4 = random.randint(1, 31)
                pov4 = random.randint(1, 2)
                aa = (posx1, posy1)
                r.append(list(aa))
                s[list(aa)[0]][list(aa)[1]] = 1
                if pov1 == 1:
                    for i in range(1, 4):
                        aa = (posx1 + i, posy1)
                        r.append(list(aa))
                        s[list(aa)[0]][list(aa)[1]] = 1
                else:
                    for i in range(1, 4):
                        aa = (posx1, posy1 + i)
                        r.append(list(aa))
                        s[list(aa)[0]][list(aa)[1]] = 1
                aa = (posx2, posy2)
                r1.append(list(aa))
                s[list(aa)[0]][list(aa)[1]] = 2
                if pov2 == 1:
                    for i in range(1, 4):
                        aa = (posx2 + i, posy2)
                        r1.append(list(aa))
                        s[list(aa)[0]][list(aa)[1]] = 2
                else:
                    for i in range(1, 4):
                        aa = (posx2, posy2 + i)
                        r1.append(list(aa))
                        s[list(aa)[0]][list(aa)[1]] = 2
                aa = (posx3, posy3)
                r2.append(list(aa))
                s[list(aa)[0]][list(aa)[1]] = 3
                if pov3 == 1:
                    for i in range(1, 4):
                        aa = (posx3 + i, posy3)
                        r2.append(list(aa))
                        s[list(aa)[0]][list(aa)[1]] = 3
                else:
                    for i in range(1, 4):
                        aa = (posx3, posy3 + i)
                        r2.append(list(aa))
                        s[list(aa)[0]][list(aa)[1]] = 3
                aa = (posx4, posy4)
                r3.append(list(aa))
                s[list(aa)[0]][list(aa)[1]] = 4
                if pov4 == 1:
                    for i in range(1, 4):
                        aa = (posx4 + i, posy4)
                        r3.append(list(aa))
                        s[list(aa)[0]][list(aa)[1]] = 4
                else:
                    for i in range(1, 4):
                        aa = (posx4, posy4 + i)
                        r3.append(list(aa))
                        s[list(aa)[0]][list(aa)[1]] = 4
                ggg = 1
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and ggg == 1:
            if (event.pos[0] < 750) and (event.pos[1] < 250) and (event.pos[0] + 32 > 750) and (event.pos[1] + 32 > 250) and (stav1 == 0) and (pomoch != 1):
                stav1 = 1
                if ser.count(1) == 3:
                    i13 = Button1('pr.png', '', 820, 250)
                elif ser.count(1) == 2:
                    i12 = Button1('pr.png', '', 820, 250)
                elif ser.count(1) == 1:
                    i11 = Button1('pr.png', '', 820, 250)
                elif ser.count(1) == 4:
                    i23 = Button1('pr2.png', '', 820, 250)
                elif ser.count(1) == 5:
                    i22 = Button1('pr2.png', '', 820, 250)
            if (event.pos[0] < 750) and (event.pos[1] < 350) and (event.pos[0] + 32 > 750) and (event.pos[1] + 32 > 350) and (stav1 == 0) and (pomoch != 1):
                stav1 = 2
                if ser.count(1) == 3:
                    i13 = Button1('pr.png', '', 820, 350)
                elif ser.count(1) == 2:
                    i12 = Button1('pr.png', '', 820, 350)
                elif ser.count(1) == 1:
                    i11 = Button1('pr.png', '', 820, 350)
                elif ser.count(1) == 4:
                    i23 = Button1('pr2.png', '', 820, 350)
                elif ser.count(1) == 5:
                    i22 = Button1('pr2.png', '', 820, 350)
            if (event.pos[0] < 750) and (event.pos[1] < 450) and (event.pos[0] + 32 > 750) and (event.pos[1] + 32 > 450) and (stav1 == 0) and (pomoch != 1):
                stav1 = 3
                if ser.count(1) == 3:
                    i13 = Button1('pr.png', '', 820, 450)
                elif ser.count(1) == 2:
                    i12 = Button1('pr.png', '', 820, 450)
                elif ser.count(1) == 1:
                    i11 = Button1('pr.png', '', 820, 450)
                elif ser.count(1) == 4:
                    i23 = Button1('pr2.png', '', 820, 450)
                elif ser.count(1) == 5:
                    i22 = Button1('pr2.png', '', 820, 450)
            if (event.pos[0] < 750) and (event.pos[1] < 550) and (event.pos[0] + 32 > 750) and (event.pos[1] + 32 > 550) and (stav1 == 0) and (pomoch != 1):
                stav1 = 4
                if ser.count(1) == 3:
                    i13 = Button1('pr.png', '', 820, 550)
                elif ser.count(1) == 2:
                    i12 = Button1('pr.png', '', 820, 550)
                elif ser.count(1) == 1:
                    i11 = Button1('pr.png', '', 820, 550)
                elif ser.count(1) == 4:
                    i23 = Button1('pr2.png', '', 820, 550)
                elif ser.count(1) == 5:
                    i22 = Button1('pr2.png', '', 820, 550)
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            if (event.pos[0] < 370) and (event.pos[1] < 760) and (event.pos[0] + 171 > 370) and (event.pos[1] + 47 > 760) and pomoch != 1:
                vyhod = 1
            if (event.pos[0] < 180) and (event.pos[1] < 760) and (event.pos[0] + 171 > 180) and (event.pos[1] + 47 > 760):
                pomoch = 1
            if (event.pos[0] < 900) and (event.pos[1] < 760) and (event.pos[0] + 171 > 900) and (event.pos[1] + 47 > 760) and pomoch == 1:
                pomoch = 0
            if (event.pos[0] < 900) and (event.pos[1] < 760) and (event.pos[0] + 171 > 900) and (event.pos[1] + 47 > 760) and pobeda != 0:
                cpec = 0
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 3 and k1 == 0 and k == 1:
            k1 += 1
        if event.type == pygame.KEYDOWN and k == 1 and k1 == 0:
            if event.key == pygame.K_SPACE and stav2 != 0:
                k1 += 1
                ss = "Идет игра..."
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 4 and k1 == 1:
            koef += 50
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 5 and k1 == 1:
            koef -= 50
    if pomoch != 1:
        screen.fill((10, 0, 0))
    if vyhod == 1:
        break
    if cpec == 0 and pobeda != 0:
        k1 = 0
        clock = pygame.time.Clock()
        s = [[0] * 37 for _ in range(37)]
        running = True
        r = []
        dd = 0
        hh = 0
        fps = 500
        t = 1
        dd1 = []
        t1 = 1
        r1 = []
        r2 = []
        mass = []
        r3 = []
        pomoch = 0
        koef = 0
        ggg = 0
        spisok = [1, 2, 3, 4]
        pygame.display.flip()
        vyhod = 0
        colser = 0
        ss = "Начните игру"
        stav1 = 0
        pobeda = 3
        stav2 = 0
        ser = [1, 1, 1, -1, -1, -1]
        i21 = Button1('pr2.png', '', 820, 680)
        i22 = Button1('pr2.png', '', 860, 680)
        i23 = Button1('pr2.png', '', 900, 680)
        i11 = Button1('pr.png', '', 820, 150)
        i12 = Button1('pr.png', '', 860, 150)
        i13 = Button1('pr.png', '', 900, 150)
        pobeda = 0
    if pobeda == 3 and cpec == 1:
        screen.fill((10, 0, 0))
        text = font1.render("Вы победили!", True, (255, 255, 255))
        screen.blit(text, [340, 380])
        i8 = Button('vyh.png', '', 900, 760)
        pygame.display.flip()
        continue
    if pobeda == 2 and cpec == 1:
        screen.fill((10, 0, 0))
        text = font1.render("Победа ИИ!", True, (255, 255, 255))
        screen.blit(text, [340, 380])
        i8 = Button('vyh.png', '', 900, 760)
        pygame.display.flip()
        continue
    if pomoch == 1:
        screen.fill((10, 0, 0))
        text = font.render("Правила игры", True, (255, 255, 255))
        text2 = font.render("Вы играете против ИИ. Сначала нажмите на кнопку random. Вам выпадет последователь-", True, (255, 255, 255))
        text3 = font.render("ность в которой вы должны будете выбрать цвет. За один цвет ставится одна жизнь.", True, (255, 255, 255))
        text4 = font.render("Нажмите на квадратик с цветом чтобы поставить (отменить нельзя) жизнь. После ход", True, (255, 255, 255))
        text5 = font.render("ИИ. Он ставит на любой другой цвет свою жизнь. Тот кто побеждает забирает жизни со-", True, (255, 255, 255))
        text6 = font.render("перника. Всего жизней три на каждого. Победит тот кто заберет все жизни себе.", True, (255, 255, 255))
        text7 = font.render("Если же никто из вас не победил, то жизни уходят обратно к вам. Мы уверяем вас в", True, (255, 255, 255))
        text8 = font.render("нашей честности, поэтому ИИ будет выбирать абсолютно рандомно, не зная до этого кто", True, (255, 255, 255))
        text9 = font.render("победит. Сердечки рядом с персонажем - это жизни. Нажмите на пробел чтобы начать", True, (255, 255, 255))
        text10 = font.render("Ваш персонаж - сверху, персонаж ИИ снизу. Желаем вам приятной игры!", True, (255, 255, 255))
        text11 = font.render("Просто стишок, для хорошего настроения ;)", True, (255, 255, 255))
        text12 = font.render("Если плох как математик,", True, (255, 255, 255))
        text13 = font.render("Это в общем не беда,", True, (255, 255, 255))
        text14 = font.render("Ведь хороший может физик", True, (255, 255, 255))
        text15 = font.render("Получиться из тебя!", True, (255, 255, 255))
        text16 = font.render("Если физик получился,", True, (255, 255, 255))
        text17 = font.render("Скажем прямо, неказист,", True, (255, 255, 255))
        text18 = font.render("Позже может получиться", True, (255, 255, 255))
        text19 = font.render("Очень классный программист!", True, (255, 255, 255))
        text20 = font.render("Программист хреновый вышел,", True, (255, 255, 255))
        text21 = font.render("Но остался шанс один,", True, (255, 255, 255))
        text22 = font.render("Что в конце концов отличный", True, (255, 255, 255))
        text23 = font.render("Из вас выйдет сисадмин!", True, (255, 255, 255))
        screen.blit(text, [10, 10])
        screen.blit(text2, [10, 40])
        screen.blit(text3, [10, 70])
        screen.blit(text4, [10, 100])
        screen.blit(text5, [10, 130])
        screen.blit(text6, [10, 160])
        screen.blit(text7, [10, 190])
        screen.blit(text8, [10, 220])
        screen.blit(text9, [10, 250])
        screen.blit(text10, [10, 280])
        screen.blit(text11, [10, 320])
        screen.blit(text12, [10, 350])
        screen.blit(text13, [10, 380])
        screen.blit(text14, [10, 410])
        screen.blit(text15, [10, 440])
        screen.blit(text16, [10, 480])
        screen.blit(text17, [10, 510])
        screen.blit(text18, [10, 540])
        screen.blit(text19, [10, 570])
        screen.blit(text20, [10, 610])
        screen.blit(text21, [10, 640])
        screen.blit(text22, [10, 670])
        screen.blit(text23, [10, 700])
        i8 = Button('vyh.png', '', 900, 760)
        pygame.display.flip()
        continue
    board.render(screen)
    Button('knop.png', '', 900, 60)
    i1 = Button('cv1.png', '', 750, 250)
    i2 = Button('cv2.png', '', 750, 350)
    i3 = Button('cv3.png', '', 750, 450)
    i4 = Button('cv4.png', '', 750, 550)
    Button('pom.png', '', 180, 760)
    Button('vyh.png', '', 370, 760)
    Button('12.png', '', 790, 200)
    i11.izobr()
    i12.izobr()
    i13.izobr()
    Button('mil.png', '', 770, 700)
    i21.izobr()
    i22.izobr()
    i23.izobr()
    if k == 1:
        board.life(screen, r, r1, r2, r3)
        if k1 == 1:
            random.shuffle(spisok)
            for i in spisok:
                if i == 1:
                    r, s = board.start(screen, s, 1)
                if i == 2:
                    r1, s = board.start(screen, s, 2)
                if i == 3:
                    r2, s = board.start(screen, s, 3)
                if i == 4:
                    r3, s = board.start(screen, s, 4)
            pygame.time.delay(fps + koef)
            if (r == []) and ('r' not in dd1):
                dd += 1
                dd1.append('r')
            if (r1 == []) and ('r1' not in dd1):
                dd += 1
                dd1.append('r1')
            if (r2 == []) and ('r2' not in dd1):
                dd += 1
                dd1.append('r2')
            if (r3 == []) and ('r3' not in dd1):
                dd += 1
                dd1.append('r3')
            if dd > 2:
                k1 = 3
        elif k1 == 2:
            k = 1
            koef = 0
            k1 = 0
            r1 = []
            dd = 0
            r = []
            k1 = 0
            ggg = 0
            r2 = []
            dd1 = []
            s = [[0] * 37 for _ in range(37)]
            r3 = []
            if pob == stav2:
                if ser.count(1) == 3:
                    ser[2] = -1
                    i23 = Button1('pr2.png', '', 900, 680)
                    i13 = Button1('pr.png', '', 900, 730)
                elif ser.count(1) == 2:
                    ser[1] = -1
                    i12 = Button1('pr.png', '', 860, 730)
                    i13 = Button1('pr.png', '', 900, 730)
                elif ser.count(1) == 1:
                    pobeda = 2
                    cpec = 1
                elif ser.count(1) == 4:
                    ser[3] = -1
                    i23 = Button1('pr2.png', '', 900, 680)
                    i22 = Button1('pr2.png', '', 860, 680)
                elif ser.count(1) == 5:
                    ser[4] = -1
                    i22 = Button1('pr2.png', '', 860, 680)
                    i21 = Button1('pr2.png', '', 820, 680)
            elif pob == stav1:
                if ser.count(1) == 3:
                    ser[3] = 1
                    i13 = Button1('pr.png', '', 900, 150)
                    i23 = Button1('pr2.png', '', 900, 200)
                elif ser.count(1) == 2:
                    ser[2] = 1
                    i12 = Button1('pr.png', '', 860, 150)
                    i13 = Button1('pr.png', '', 900, 150)
                elif ser.count(1) == 1:
                    ser[1] = 1
                    i11 = Button1('pr.png', '', 820, 150)
                    i12 = Button1('pr.png', '', 860, 150)
                elif ser.count(1) == 4:
                    ser[4] = 1
                    i23 = Button1('pr2.png', '', 900, 200)
                    i22 = Button1('pr2.png', '', 860, 200)
                elif ser.count(1) == 5:
                    pobeda = 3
                    cpec = 1
            else:
                if ser.count(1) == 3:
                    i13 = Button1('pr.png', '', 900, 150)
                    i23 = Button1('pr2.png', '', 900, 680)
                if ser.count(1) == 2:
                    i12 = Button1('pr.png', '', 860, 150)
                    i13 = Button1('pr.png', '', 900, 730)
                if ser.count(1) == 1:
                    i11 = Button1('pr.png', '', 820, 150)
                    i12 = Button1('pr.png', '', 860, 730)
                if ser.count(1) == 4:
                    i22 = Button1('pr2.png', '', 860, 680)
                    i23 = Button1('pr2.png', '', 900, 200)
                if ser.count(1) == 5:
                    i22 = Button1('pr2.png', '', 860, 200)
                    i21 = Button1('pr2.png', '', 820, 680)
            stav1 = 0
            stav2 = 0
        elif k1 == 3:
            if 'r' not in dd1:
                pob = 4
                ss = 'Победили зеленые'
            if 'r1' not in dd1:
                pob = 2
                ss = 'Победили голубые'
            if 'r2' not in dd1:
                pob = 3
                ss = 'Победили желтые'
            if 'r3' not in dd1:
                pob = 1
                ss = 'Победили красные'
            k1 = 2
        if stav1 != 0 and stav2 == 0:
            ran = [1, 2, 3, 4]
            del ran[ran.index(stav1)]
            random.shuffle(ran)
            stav2 = ran[0]
            if stav2 == 1:
                if ser.count(-1) == 3:
                    i23 = Button1('pr2.png', '', 820, 250)
                elif ser.count(-1) == 2:
                    i22 = Button1('pr2.png', '', 820, 250)
                elif ser.count(-1) == 1:
                    i21 = Button1('pr2.png', '', 820, 250)
                elif ser.count(-1) == 4:
                    i13 = Button1('pr.png', '', 820, 250)
                elif ser.count(-1) == 5:
                    i12 = Button1('pr.png', '', 820, 250)
            if stav2 == 2:
                if ser.count(-1) == 3:
                    i23 = Button1('pr2.png', '', 820, 350)
                elif ser.count(-1) == 2:
                    i22 = Button1('pr2.png', '', 820, 350)
                elif ser.count(-1) == 1:
                    i21 = Button1('pr2.png', '', 820, 350)
                elif ser.count(-1) == 4:
                    i13 = Button1('pr.png', '', 820, 350)
                elif ser.count(-1) == 5:
                    i12 = Button1('pr.png', '', 820, 350)
            if stav2 == 3:
                if ser.count(-1) == 3:
                    i23 = Button1('pr2.png', '', 820, 450)
                elif ser.count(-1) == 2:
                    i22 = Button1('pr2.png', '', 820, 450)
                elif ser.count(-1) == 1:
                    i21 = Button1('pr2.png', '', 820, 450)
                elif ser.count(-1) == 4:
                    i13 = Button1('pr.png', '', 820, 450)
                elif ser.count(-1) == 5:
                    i12 = Button1('pr.png', '', 820, 450)
            if stav2 == 4:
                if ser.count(-1) == 3:
                    i23 = Button1('pr2.png', '', 820, 550)
                elif ser.count(-1) == 2:
                    i22 = Button1('pr2.png', '', 820, 550)
                elif ser.count(-1) == 1:
                    i21 = Button1('pr2.png', '', 820, 550)
                elif ser.count(-1) == 4:
                    i13 = Button1('pr.png', '', 820, 550)
                elif ser.count(-1) == 5:
                    i12 = Button1('pr.png', '', 820, 550)
    text23 = font.render(ss, True, (255, 255, 255))
    screen.blit(text23, [600, 730])
    clock.tick(fps)
    pygame.display.flip()


import os
import tempfile
import unittest
from time import sleep

import pytest
import yaml

from cowbird.handlers.handler_factory import HandlerFactory
from cowbird.monitoring.fsmonitor import FSMonitor
from cowbird.monitoring.monitoring import Monitoring
from tests.utils import clear_handlers_instances, get_test_app

def file_io(filename, mv_filename):
    # Create
    with open(filename, "w", encoding="utf-8") as f:
        f.write("Hello")
    # Update
    with open(filename, "a", encoding="utf-8") as f:
        f.write(" world!")
    # Update on file permissions should also trigger a modified event
    os.chmod(filename, 0o777)
    # Should create a 'delete' and a 'create' event
    os.rename(filename, mv_filename)
    # Delete
    os.remove(mv_filename)

@pytest.mark.monitoring
class TestMonitoring(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.cfg_file = tempfile.NamedTemporaryFile(mode="w", suffix=".cfg", delete=False)  # pylint: disable=R1732
        with cls.cfg_file as f:
            f.write(yaml.safe_dump({"handlers": {"": {}}}))  # no specific handler required for these tests
        cls.app = get_test_app(settings={"cowbird.config_path": cls.cfg_file.name})
        # clear up monitor entries from db
        Monitoring().store.clear_services(drop=False)

    @classmethod
    def tearDownClass(cls):
        Monitoring().store.clear_services()
        clear_handlers_instances()
        os.unlink(cls.cfg_file.name)

    def test_register_unregister_monitor(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            test_file = os.path.join(tmpdir, "testfile")
            test_subdir = os.path.join(tmpdir, "subdir")
            test_subdir_file = os.path.join(test_subdir, "test_subdir_file")
            mv_test_file = os.path.join(test_subdir, "moved_testfile")
            mv_test_subdir_file = os.path.join(tmpdir, "moved_test_subdir_file")
            os.mkdir(test_subdir)

            # Test registering directly a callback instance
            mon = TestMonitor()
            internal_mon = Monitoring().register(tmpdir, False, mon)
            assert internal_mon.callback_instance == mon

            # Test registering a callback via class name
            internal_mon2 = Monitoring().register(tmpdir, True, TestMonitor2)
            mon2 = internal_mon2.callback_instance
            internal_mon3 = Monitoring().register(test_subdir, False, TestMonitor)
            mon3 = internal_mon3.callback_instance
            assert isinstance(mon2, TestMonitor2)
            assert isinstance(mon3, TestMonitor)

            # Test collision when 2 monitors are registered using the same path and class name
            assert not internal_mon3.recursive
            internal_mon4 = Monitoring().register(test_subdir, True, TestMonitor)
            assert internal_mon4 is internal_mon3
            assert internal_mon3.recursive  # Recursive should take precedence when a collision occurs

            # monitors first level is distinct path to monitor : (tmp_dir and test_subdir)
            assert len(Monitoring().monitors) == 2

            # monitors second level is distinct callback, for tmpdir : (TestMonitor and TestMonitor2)
            assert len(Monitoring().monitors[tmpdir]) == 2

            # Do some io operations that should be picked by the monitors
            file_io(test_file, mv_test_file)
            file_io(test_subdir_file, mv_test_subdir_file)
            sleep(1)

            # Root dir non-recursive
            assert len(mon.created) == 2
            assert mon.created[0] == test_file
            assert mon.created[1] == mv_test_subdir_file
            assert mon.created == mon.deleted
            assert sorted(set(mon.modified)) == [tmpdir, test_file]
            assert len(mon.modified) == 9

            # Root dir recursive
            assert len(mon2.created) == 4
            assert mon2.created[0] == test_file
            assert mon2.created[1] == mv_test_file
            assert mon2.created[2] == test_subdir_file
            assert mon2.created[3] == mv_test_subdir_file
            assert mon2.created == mon2.deleted
            assert sorted(set(mon2.modified)) == [tmpdir, test_subdir,
                                                  test_subdir_file, test_file]
            assert len(mon2.modified) == 18

            # Subdir
            assert len(mon3.created) == 2
            assert mon3.created[0] == mv_test_file
            assert mon3.created[1] == test_subdir_file
            assert mon3.created == mon3.deleted
            assert sorted(set(mon3.modified)) == [test_subdir,
                                                  test_subdir_file]
            assert len(mon3.modified) == 9

            # Validate cleanup
            Monitoring().unregister(tmpdir, mon)
            Monitoring().unregister(tmpdir, mon2)
            # Here we try to unregister a path with a bad class type
            assert not Monitoring().unregister(test_subdir, mon2)
            # Here we have the good class type
            Monitoring().unregister(test_subdir, mon3)
            assert len(Monitoring().monitors) == 0
            assert not Monitoring().unregister(tmpdir, mon)

            # Test registering a callback via a qualified class name string
            catalog_mon = \
                Monitoring().register(tmpdir, False, "cowbird.handlers.impl.catalog.Catalog").callback_instance
            assert catalog_mon == HandlerFactory().get_handler("Catalog")

class TestMonitor(FSMonitor):
    __test__ = False  # avoid invalid collect depending on specified input path/items to pytest

    def __init__(self):
        self.created = []
        self.deleted = []
        self.modified = []

    @staticmethod
    def get_instance():
        return TestMonitor()

    def on_created(self, path):
        self.created.append(path)

    def on_deleted(self, path):
        self.deleted.append(path)

    def on_modified(self, path):
        self.modified.append(path)

class TestMonitor2(TestMonitor):
    __test__ = False  # avoid invalid collect depending on specified input path/items to pytest

    # Allow a second full qualified class name to register as monitor
    @staticmethod
    def get_instance():
        return TestMonitor2()


import pandas as pd
import re
import jieba
import gensim
import pickle
import numpy as np

def main():
    training_set_path = "dataset/train.csv"
    test_set_path = "dataset/test.csv"
    training_set = dataset2vec(training_set_path, is_training_set=True)
    test_set = dataset2vec(test_set_path, is_training_set=False)

    with open("dataset/training_set.pkl", "wb") as file:
        pickle.dump(training_set, file)
    with open("dataset/test_set.pkl", "wb") as file:
        pickle.dump(test_set, file)

def dataset2vec(file_path, is_training_set):
    df = pd.read_csv(file_path)

    df.drop(axis=1, inplace=True, columns=["Unnamed: 0"])
    df = df.replace(re.compile(r'\[.*?\]'), " ", regex=True)  # [xxx] 表情符号
    df = df.replace(re.compile(r'@.*?:'), " ", regex=True)  # @xxx
    df = df.replace("\t", " ", regex=False)  # 转移符号
    df = df.replace("网页链接", " ", regex=False)  # 链接
    df['content'] = df['content'].str.strip()
    df = df.fillna(value=' ')  # 补充空值
    df['content'] = df['content'].apply(lambda x: ' '.join(sentence_segment(x)))
    df['comment_all'] = df['comment_all'].apply(lambda x: ' '.join(sentence_segment(x)))
    df = df.fillna(value=' ')

    content_seg_list = [x.split(' ') for x in df['content']]
    comment_seg_list = [x.split(' ') for x in df['comment_all']]
    wv_model = None
    wv_size = 50
    if is_training_set:
        wv_model = gensim.models.word2vec.Word2Vec(content_seg_list + comment_seg_list, vector_size=wv_size, min_count=1)
        with open('model/wv.model', 'wb') as outfile:
            pickle.dump(wv_model, outfile)
    else:
        with open('model/wv.model', 'rb') as infile:
            wv_model = pickle.load(infile)

    feature = []
    for i in range(len(content_seg_list)):
        feature_vec = np.zeros(shape=[0], dtype='float32')
        text_vec = np.zeros(shape=[wv_size], dtype='float32')
        count = 0
        for word in content_seg_list[i]:
            if wv_model.wv.has_index_for(word):
                text_vec += wv_model.wv[word]
                count += 1
        if count != 0:
            feature_vec = np.concatenate((feature_vec, text_vec / count))
        else:
            feature_vec = np.concatenate((feature_vec, text_vec))

        text_vec = np.zeros(shape=[wv_size], dtype='float32')
        count = 0
        for word in comment_seg_list[i]:
            if wv_model.wv.has_index_for(word):
                text_vec += wv_model.wv[word]
                count += 1
        if count != 0:
            feature_vec = np.concatenate((feature_vec, text_vec / count))
        else:
            feature_vec = np.concatenate((feature_vec, text_vec))
        feature.append(feature_vec.tolist())

    label = []
    for x in df['label']:
        label.append(x)
    return {'X': np.array(feature), 'y': np.array(label)}

def sentence_segment(sentence):
    pattern = re.compile("[^\u4e00-\u9fa5]+")
    sentence = pattern.sub('', sentence)
    stopwords_list = pd.read_table('dataset/cn_stopwords.txt', header=None).iloc[:, :].values
    seg_list = jieba.cut(sentence)
    filtered_words_list = []
    for word in seg_list:
        if word not in stopwords_list:
            filtered_words_list.append(word)
    return filtered_words_list

main()


#!/usr/bin/env python
import os
import sys
import numpy as np
import fitsio
import numpy_util

def make_im3shape_flags(config):
    """
    code to make im3shape flags

    People to bug if things are weird
    =================================

    Matthew Becker
    im3shape team

    Input Data
    ==========

    im3shape v97 - use to set the flags

    im3shape_flags
    ==============

    bit 2^bit   name              notes
    ----------------------------------------------------------------------
    2   4       NOTORBAD_MEAS     object is not in gold or does not meet required flags below

    Required Cuts
    --------------
    Any source which does not meet these cuts is not well measured in im3shape

    error_flag == 0
    info_flag == 0
    snr > 15
    mean_rgpp_rp > 1.2
    finite(psf_e1,psf_e1,nbc_m,nbc_c1,nbc_c2)
    """

    # first read in the data
    gold = fitsio.read(config['gold'],lower=True,columns=['coadd_objects_id'])
    im = fitsio.read(config['im3shape'])

    dflag = np.zeros(len(gold),dtype=[('im3shape_flags','i8')])

    #####################
    # do im3shape cuts
    tag = 'im3shape_flags'

    # find stuff in catalog
    gids = gold['coadd_objects_id']
    imids = im['coadd_objects_id']
    ginds,iminds = numpy_util.match(gids,imids)

    # flag stuff not in cat
    sginds = set(ginds)
    totginds = set(range(len(gold)))
    diffginds = totginds - sginds
    q = np.fromiter(diffginds,dtype=int,count=len(diffginds))
    if len(q) > 0:
        dflag[tag][q] |= 4

    # required cuts
    q, = np.where(~((im['error_flag'][iminds] == 0) &
                    (im['info_flag'][iminds] == 0) &
                    (im['snr'][iminds] > 15.0) &
                    (im['mean_rgpp_rp'][iminds] > 1.2) &
                    (np.isfinite(im['mean_psf_e1_sky'][iminds])) &
                    (np.isfinite(im['mean_psf_e2_sky'][iminds])) &
                    (np.isfinite(im['nbc_m'][iminds])) &
                    (np.isfinite(im['nbc_c1'][iminds])) &
                    (np.isfinite(im['nbc_c2'][iminds]))
                    ))
    if len(q) > 0:
        dflag[tag][ginds[q]] |= 4

    #write to disk
    fitsio.write(config['im3shape_flags'],dflag,clobber=True)

if __name__ == "__main__":
    import yaml
    with open(sys.argv[1],'r') as fp:
        config = yaml.load(fp)
    make_im3shape_flags(config)


from bot.utils.error import NoResultError
from discord.ext.commands.cooldowns import BucketType
from data.genshin.models import Artifact, DomainLevel
from discord.ext import commands
from sqlalchemy.sql import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
import discord

def query_artifact(session, name):
    stmt = select(Artifact).options(selectinload(Artifact.domains).selectinload(DomainLevel.domain)).filter(Artifact.name.like(f'%{name}%'))
    art = session.execute(stmt).scalars().first()
    return art

class Artifacts(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    @commands.max_concurrency(5, BucketType.guild, wait=True)
    async def artifact(self, ctx, *args):
        """Get Artifact Set Details"""
        if not args:
            raise commands.UserInputError

        name = ' '.join([w.capitalize() for w in args])
        async with AsyncSession(self.bot.get_cog('Query').engine) as s:
            art = await s.run_sync(query_artifact, name=name)
            if art:
                file = discord.File(art.icon_url, filename='image.png')
                embed = self.get_set_info_embed(art)
                await ctx.send(file=file, embed=embed)
            else:
                raise NoResultError

    def get_set_info_embed(self, art):
        embed = discord.Embed(title=f'{art.name} Set', color=discord.Colour.gold())
        embed.set_thumbnail(url='attachment://image.png')

        min_rar = ''
        max_rar = ''
        if art.min_rarity:
            for _ in range(art.min_rarity):
                min_rar += f'{self.bot.get_cog("Flair").get_emoji("Star")}'
        if art.max_rarity:
            for _ in range(art.max_rarity):
                max_rar += f'{self.bot.get_cog("Flair").get_emoji("Star")}'

        if min_rar and max_rar:
            embed.description = f'Min Rarity: {min_rar}\nMax Rarity: {max_rar}'
        elif min_rar:
            embed.description = f'Rarity: {min_rar}\n'

        if art.domains:
            dom_name = []
            for d in art.domains:
                if d.domain.name not in dom_name:
                    dom_name.append(d.domain.name)
            dom = '\u2022 '
            dom += '\n\u2022 '.join(dom_name)
            embed.add_field(name='Domains Dropped', value=dom, inline=False)

        if art.bonus_one:
            embed.add_field(name='1-Set Bonus', value=art.bonus_one, inline=False)
        if art.bonus_two:
            embed.add_field(name='2-Set Bonus', value=art.bonus_two, inline=False)
        if art.bonus_three:
            embed.add_field(name='3-Set Bonus', value=art.bonus_three, inline=False)
        if art.bonus_four:
            embed.add_field(name='4-Set Bonus', value=art.bonus_four, inline=False)
        if art.bonus_five:
            embed.add_field(name='5-Set Bonus', value=art.bonus_five, inline=False)

        return embed


from django.dispatch import receiver

from django.db.models.signals import post_save

# get_random_string 获取随机数的string
from django.utils.crypto import get_random_string

from .. import models

@receiver(post_save, sender=models.Survey)
def create_unique_code(**kwargs):
    """
    http://127.0.0.1:8000/admin/web/survey/重复创建Survey的时候，create字段会变为False
    {
        'signal': <django.db.models.signals.ModelSignal object at 0x10c5aa4a8>,
        'sender': <class 'web.models.Survey'>,
        'instance': <Survey: Survey object (1)>,
        'created': True,
        'update_fields': None,
        'raw': False,
        'using': 'default'
    }
    """
    created = kwargs.get("created", False)
    if not created:
        return

    instance = kwargs.get("instance")

    count = instance.count
    codes = []
    while count:
        _code = get_random_string(8)
        if models.SurveyCode.objects.filter(unique_code=_code).exists():
            continue
        # 将SurveyCode对象添加到一个列表中，便于后面批量创建
        codes.append(models.SurveyCode(unique_code=_code, survey=instance))
        count -= 1
    models.SurveyCode.objects.bulk_create(codes)


import numpy as np
import pytest

import pandas as pd
from pandas import Timedelta
import pandas._testing as tm
from pandas.core.arrays import TimedeltaArray

class TestTimedeltaArray:
    @pytest.mark.parametrize("dtype", [int, np.int32, np.int64, "uint32", "uint64"])
    def test_astype_int(self, dtype):
        arr = TimedeltaArray._from_sequence([Timedelta("1H"), Timedelta("2H")])
        with tm.assert_produces_warning(FutureWarning):
            # astype(int..) deprecated
            result = arr.astype(dtype)

        if np.dtype(dtype).kind == "u":
            expected_dtype = np.dtype("uint64")
        else:
            expected_dtype = np.dtype("int64")

        with tm.assert_produces_warning(FutureWarning):
            # astype(int..) deprecated
            expected = arr.astype(expected_dtype)

        assert result.dtype == expected_dtype
        tm.assert_numpy_array_equal(result, expected)

    def test_setitem_clears_freq(self):
        a = TimedeltaArray(pd.timedelta_range("1H", periods=2, freq="H"))
        a[0] = Timedelta("1H")
        assert a.freq is None

    @pytest.mark.parametrize(
        "obj",
        [
            Timedelta(seconds=1),
            Timedelta(seconds=1).to_timedelta64(),
            Timedelta(seconds=1).to_pytimedelta(),
        ],
    )
    def test_setitem_objects(self, obj):
        # make sure we accept timedelta64 and timedelta in addition to Timedelta
        tdi = pd.timedelta_range("2 Days", periods=4, freq="H")
        arr = TimedeltaArray(tdi, freq=tdi.freq)

        arr[0] = obj
        assert arr[0] == Timedelta(seconds=1)

    @pytest.mark.parametrize(
        "other",
        [
            1,
            np.int64(1),
            1.0,
            np.datetime64("NaT"),
            pd.Timestamp.now(),
            "invalid",
            np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9,
            (np.arange(10) * 24 * 3600 * 10 ** 9).view("datetime64[ns]"),
            pd.Timestamp.now().to_period("D"),
        ],
    )
    @pytest.mark.parametrize("index", [True, False])
    def test_searchsorted_invalid_types(self, other, index):
        data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
        arr = TimedeltaArray(data, freq="D")
        if index:
            arr = pd.Index(arr)

        msg = "|".join(
            [
                "searchsorted requires compatible dtype or scalar",
                "value should be a 'Timedelta', 'NaT', or array of those. Got",
            ]
        )
        with pytest.raises(TypeError, match=msg):
            arr.searchsorted(other)

class TestUnaryOps:
    def test_abs(self):
        vals = np.array([-3600 * 10 ** 9, "NaT", 7200 * 10 ** 9], dtype="m8[ns]")
        arr = TimedeltaArray(vals)

        evals = np.array([3600 * 10 ** 9, "NaT", 7200 * 10 ** 9], dtype="m8[ns]")
        expected = TimedeltaArray(evals)

        result = abs(arr)
        tm.assert_timedelta_array_equal(result, expected)

    def test_neg(self):
        vals = np.array([-3600 * 10 ** 9, "NaT", 7200 * 10 ** 9], dtype="m8[ns]")
        arr = TimedeltaArray(vals)

        evals = np.array([3600 * 10 ** 9, "NaT", -7200 * 10 ** 9], dtype="m8[ns]")
        expected = TimedeltaArray(evals)

        result = -arr
        tm.assert_timedelta_array_equal(result, expected)

    def test_neg_freq(self):
        tdi = pd.timedelta_range("2 Days", periods=4, freq="H")
        arr = TimedeltaArray(tdi, freq=tdi.freq)

        expected = TimedeltaArray(-tdi._data, freq=-tdi.freq)

        result = -arr
        tm.assert_timedelta_array_equal(result, expected)


import tkinter as tk
import requests as rq
import pandas as pd
import os
from tkinter import messagebox

# pyinstaller --onefile main.py

def iniciar_processo():
    data_inicio = entry_data_inicio.get()
    data_fim = entry_data_fim.get()

    path_name = "ContratoScrap.csv"
    BASE = "https://compras.dados.gov.br/comprasContratos/v1/contratos.json"
    response = rq.get(f"{BASE}?data_assinatura_max={data_fim}&data_assinatura_min={data_inicio}").json()["_embedded"]

    contratos_clean = [x for x in response["contratos"]]

    if os.path.exists(path_name):

        dados_antigos = pd.read_excel(path_name)["id"]

        contratos_novos = [x for x in contratos_clean if x["id"] not in dados_antigos]
        df = pd.DataFrame(contratos_novos)
        df.sort_values(by="id")
        df.to_csv(path_name, index=False)

    else:
        df = pd.DataFrame(contratos_clean)
        df.sort_values(by="id")
        df.to_csv(path_name, index=False)

    # Exemplo simples: Mostrar um diálogo com as datas selecionadas
    messagebox.showinfo("Sucesso!", "Os dados foram salvos no arquivo: ContratoScrap.csv")

# Criar a janela principal
root = tk.Tk()
root.title("Seleção de Datas")

# Adicionar um rótulo com o texto
label_texto = tk.Label(root, text="Coloque a data de inicio e de fim nesse modelo: ano-mês-dia")
label_texto.pack()

# Adicionar campos de entrada para data inicial e final
label_data_inicio = tk.Label(root, text="Data de Início:")
label_data_inicio.pack()
entry_data_inicio = tk.Entry(root)
entry_data_inicio.pack()

label_data_fim = tk.Label(root, text="Data de Fim:")
label_data_fim.pack()
entry_data_fim = tk.Entry(root)
entry_data_fim.pack()

# Adicionar um botão para iniciar o processo
botao_iniciar = tk.Button(root, text="Iniciar", command=iniciar_processo)
botao_iniciar.pack()

# Iniciar a interface gráfica
root.mainloop()