import json
import re
import requests
import argparse

var_re = re.compile('var (.+?) = (.+?);')

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('file', help='address file; one address per line')
    ap.add_argument('--coin', required=True, help='e.g. XPM')
    ap.add_argument('--ignore-no-tx', action='store_true')
    args = ap.parse_args()
    for line in open(args.file):
        line = line.strip()
        r = requests.get('https://bchain.info/%s/addr/%s' % (args.coin, line))
        if r.status_code == 404:
            continue
        vs = {}
        for m in var_re.finditer(r.text):
            key, value = m.groups()
            if key == 'startTime':
                continue
            try:
                value = json.loads(value.replace('\'', '"'))
            except json.JSONDecodeError:
                pass
            vs[key] = value
        if args.ignore_no_tx and vs['total_tx'] == 0:
            continue
        print(vs)

if __name__ == '__main__':
    main()


# coding: utf-8

### ---- THIS FILE WAS PRODUCED BY CONVERTING THE ORIGINAL GC-gna.ipynb NOTEBOOK TO PYTHON ----###
### ---- LINES THAT ADD STIMULATION AND PLOTS WERE COMMENTED OUT ---- ###

# In[1]:

from neuron import h,gui

import matplotlib.pyplot as plt
import numpy as np

# In[2]:

N_sections = 11
h.celsius=22
nlist=[]
gcci = [h.Section() for i in range(N_sections)]
nlist.append(gcci)
gccd = [h.Section() for i in range(N_sections)]
nlist.append(gccd)
gci = [h.Section() for i in range(N_sections)]
nlist.append(gci)
gcd = [h.Section() for i in range(N_sections)]
nlist.append(gcd)

# In[3]:

for i in range(N_sections-1):
    gcci[i+1].connect(gcci[i],1,0)
    gccd[i+1].connect(gccd[i],1,0)

for i in range(N_sections-1):
    gci[i+1].connect(gci[i],1,0)
for i in range(N_sections-1):
    gcd[i+1].connect(gcd[i],1,0)

# In[4]:

for i in nlist:
    i[0].diam=10
    i[0].L=10
    i[0].nseg=3

for i in range(1,N_sections):
    for j in nlist:
        j[i].nseg=3
        j[i].L=20
        j[i].Ra=100
    gcd[i].diam=2-(i-1)*0.088 #(2-1.2)/9
    gci[i].diam=2.7-(i-1)*0.166 #(2.7-1.2)/9

    gccd[i].diam=2-(i-1)*0.088 #(2-1.2)/9
    gcci[i].diam=2.7-(i-1)*0.166 #(2.7-1.2)/9

# In[5]:

for i in range(N_sections):
    for j in nlist:
        j[i].insert('pas')
        j[i].g_pas=0.0002
        j[i].insert('kfast')
        j[i].insert('nat')
        j[i].insert('nadp')
        j[i].TotalPump_nadp=0

gcd[0].gbar_nat=4.1
gcd[0].gbar_kfast=4.1/80

gcd[1].gbar_nat=4.1
gcd[1].gbar_kfast=4.1/80

gci[0].gbar_nat=2.0
gci[0].gbar_kfast=2.0/80

gci[1].gbar_nat=2.0
gci[1].gbar_kfast=2.0/80

gcina=[2,2]
gcdna=[4.1,4.1]

for i in range(2,N_sections):
    gci[i].gbar_nat=(gci[i-1].gbar_nat)+0.05*(gci[i-1].gbar_nat)
    gci[i].gbar_kfast=(gci[i-1].gbar_kfast)+0.05*(gci[i-1].gbar_kfast)
    gcina.append(round(gci[i].gbar_nat,5))

    gcd[i].gbar_nat=(gcd[i-1].gbar_nat)-0.12*(gcd[i-1].gbar_nat)
    gcd[i].gbar_kfast=(gcd[i-1].gbar_kfast)-0.12*(gcd[i-1].gbar_kfast)
    gcdna.append(round(gcd[i].gbar_nat,5))

avnared=2.2*((2.7+2.8+2.2+4.2)/4) #mM
avnablu=2.2*((6.5+6.3+7.2+11)/4) #mM

avnaredn=2.2*((2.7+2.8)/2) #mM
avnablun=2.2*((6.5+6.3+7.2)/3) #mM

# # In[6]:
#
#
# pulscd=h.Ipulse1(0.5,sec=gccd[0])
# pulscd.ton=5
# pulscd.toff=15
# pulscd.num=20
# pulscd.amp=1#na
#
# pulsci=h.Ipulse1(0.5,sec=gcci[0])
# pulsci.ton=5
# pulsci.toff=15
# pulsci.num=20
# pulsci.amp=1#na
#
# pulsd=h.Ipulse1(0.5,sec=gcd[0])
# pulsd.ton=5
# pulsd.toff=15
# pulsd.num=20
# pulsd.amp=1 #na
#
# pulsi=h.Ipulse1(0.5,sec=gci[0])
# pulsi.ton=5
# pulsi.toff=15
# pulsi.num=20
# pulsi.amp=1 #na
#
#
# # In[7]:
#
#
# time_h = h.Vector()
# time_h.record(h._ref_t)
#
# inareci=[h.Vector() for i in range(N_sections)]
# inarecd=[h.Vector() for i in range(N_sections)]
#
# vrec_0=h.Vector()
# vrec_1=h.Vector()
# vrec_2=h.Vector()
# vrec_3=h.Vector()
# vrec_4=h.Vector()
# vrec_5=h.Vector()
#
# vrec_p1=h.Vector()
# vrec_p2=h.Vector()
# vrec_p3=h.Vector()
#
# vrec_0.record(gcd[0](0.5)._ref_v)
# vrec_1.record(gci[0](0.5)._ref_v)
#
# vrec_p1.record(gccd[0](0.5)._ref_v)
#
# vrec_2.record(gcd[1](0.5)._ref_v)
# vrec_3.record(gci[1](0.5)._ref_v)
#
# vrec_p2.record(gccd[1](0.5)._ref_v)
#
# vrec_4.record(gcd[10](0.5)._ref_v)
# vrec_5.record(gci[10](0.5)._ref_v)
#
# vrec_p3.record(gccd[10](0.5)._ref_v)
#
# for i in range(N_sections):
#     inarecd[i].record(gcd[i](0.5)._ref_ina)
#     inareci[i].record(gci[i](0.5)._ref_ina)
#
#
# # In[8]:
#
#
# h.tstop =100
# h.run()
#
#
# # In[9]:
#
#
# plt.suptitle('Vm',fontsize=14)
#
# plt.subplot(321).set_title('decreasing pattern')
# plt.plot(time_h,vrec_0)
# plt.legend(['Soma'])
#
#
# plt.subplot(322).set_title('increasing pattern')
# plt.plot(time_h,vrec_1)
#
# plt.subplot(323)
# plt.plot(time_h,vrec_2)
# plt.legend(['Dend(0)'])
#
# plt.subplot(324)
# plt.plot(time_h,vrec_3)
#
# plt.subplot(325)
# plt.plot(time_h,vrec_4)
# plt.legend(['Dend(1)'])
#
# plt.subplot(326)
# plt.plot(time_h,vrec_5)
#
# plt.show()
#
#
# # In[10]:
#
#
# connai=[]
# for i in range(N_sections):
#    connai.append(round(gci[i](0.5).nai,3))
#
# connad=[]
# for i in range(N_sections):
#     connad.append(round(gcd[i](0.5).nai,3))
#
# connacd=[]
# for i in range(N_sections):
#     connacd.append(round(gccd[i](0.5).nai,3))
#
# connaci=[]
# for i in range(N_sections):
#     connaci.append(round(gcci[i](0.5).nai,3))
#
#
# # In[11]:
#
#
# plt.subplot(2,2,1).set_title('[Na] in decreasing density')
# plt.plot(connad,'b')
#
# plt.subplot(2,2,2).set_title('gnabar in decreasing pattern')
# plt.plot(gcdna,'b')
#
# plt.subplot(2,2,3).set_title('[Na] in increasing density')
# plt.plot(connai,'r')
#
# plt.subplot(2,2,4).set_title('gnabar in increasing pattern')
# plt.plot(gcina,'r')
#
# plt.show()
#
#
# # In[12]:
#
#
# for i in range(N_sections):
#     inareci[i]=np.asarray(inareci[i])
#     inarecd[i]=np.asarray(inarecd[i])
#
# Inabari=[]
# Inabard=[]
# for i in range(N_sections):
#     Inabarii=-1*round(np.mean(inareci[i]),3)
#     Inabari.append(Inabarii)
#     Inabardd=-1*round(np.mean(inarecd[i]),3)
#     Inabard.append(Inabardd)
#
# plt.subplot(211).set_title('Ina,Increasing, mA/cm2')
# plt.plot(Inabari,'r')
#
# plt.subplot(212).set_title('Ina,Decreasing, mA/cm2')
# plt.plot(Inabard,'b')
#
# plt.show()


# -*- coding: utf-8 -*-
# @Time    : 2020/8/3
# @Author  : Fred liuchuanhao
# @File    : .py
# @Role    :
import json
import os
import shlex
import subprocess
import time
from datetime import datetime
from urllib.request import urlopen
import shortuuid
import gitlab
from libs.web_logs import ins_log
from libs.db_context import DBContext
from models.git_secrets import GitProject, model_to_dict, GitScanResult
from settings import settings

git_url = settings.get("git").get("git_url")
git_token = settings.get("git").get("git_token")
path = settings.get("git").get("path")

class Gitlab:
    def __init__(self):
        self.url = git_url
        self.token = git_token

    #登录认证
    def login_gitlab(self):
        gl = gitlab.Gitlab(git_url, git_token, api_version='4')
        gl.auth()
        return gl

    #获取项目列表
    def get_project_list_by_jdk(self):
        gl = self.login_gitlab()
        projects = gl.projects.list()
        return projects

    # 获取项目列表
    def get_project_list_by_api(self):
        allProjects = urlopen("{}api/v4/projects?membership=true&private_token={}".format(git_url,git_token))
        allProjectsDict = json.loads(allProjects.read().decode())
        return allProjectsDict

    #克隆项目到本地
    def clone_projects_by_jdk(self):
        projects_list = self.get_project_list_by_jdk()
        for thisProject in projects_list:
            try:
                thisProjectURL = thisProject.attributes["http_url_to_repo"]
                name_with_namespace = thisProject.attributes["path_with_namespace"]
                command = shlex.split('git clone %s %s' % (thisProjectURL, '/root/gitClone/' + name_with_namespace))
                resultCode = subprocess.Popen(command)
            except Exception as e:
                print("Error on %s: %s" % (thisProjectURL, e.strerror))
            time.sleep(5)

    #克隆项目到本地
    def clone_projects_by_api(self):
        projects_list = self.get_project_list_by_api()
        with DBContext('w') as session:
            try:
                session.query(GitProject).delete()
                session.commit()
            except:
                session.rollback()

        if os.path.exists(path):
            os.system("rm -rf " + path)
        else:
            print('no such file:%s' % path)

        for thisProject in projects_list:
            try:
                thisProjectURL = thisProject['http_url_to_repo']
                name_with_namespace = thisProject['path_with_namespace']
                command = shlex.split('git clone http://oauth2:%s@%s %s' % (git_token,thisProjectURL.replace("http://",""), path + name_with_namespace))
                resultCode = subprocess.Popen(command)
            except Exception as e:
                print("Error on %s: %s" % (thisProjectURL, e.strerror))

            time.sleep(3)

            new_db = GitProject(id=shortuuid.uuid(),
                                name=thisProject['name'],
                                branch=thisProject['default_branch'],
                                project_team=thisProject['name_with_namespace'].replace(" ","").split("/")[0],
                                path = thisProject['name_with_namespace'].replace(" ",""),
                                source=thisProject['web_url'],
                                add_date=str(datetime.now()),
                                last_scan_time="未扫描")
            session.add(new_db)
        session.commit()
        ins_log.read_log('info', '项目克隆到本地')

def scan_project():
    with DBContext('w') as session:
        try:
            session.query(GitScanResult).delete()
            session.commit()
        except:
            session.rollback()
        data = session.query(GitProject).all()
        projects_data = [model_to_dict(e) for e in data]
        for project in projects_data:
            cmd = "git secrets --scan -r "+ path +  project["path"]
            result = subprocess.getstatusoutput(cmd)
            if "Matched one or more prohibited patterns" not in result[1]:
                result = "safe"
                risk_index = "low"
            else:
                result = result[1].splitlines()[0:-10]
                result = "----".join(result) if result else None
                risk_index = "high" if result else "low"
            new_db = GitScanResult(id=shortuuid.uuid(),
                                name=project['name'],
                                result=result,
                                risk_index=risk_index,
                                branch=project['branch'],
                                project_team=project["project_team"],
                                Last_scan_time=str(datetime.now()),
                                source=project["source"],)
            session.add(new_db)
        session.commit()
        ins_log.read_log('info', '把扫描结果添加到数据库')

def daily_scan_task():
    st_init = Gitlab()
    st_init.clone_projects_by_api()
    scan_project()

if __name__ == '__main__':
    st_init = Gitlab()
    st_init.clone_projects_by_api()
    scan_project()


import pyglet
from sprites.rect import Rect
import math
from pyglet import gl
import random
from pprint import pprint as print
BLACK = (0, 0, 0)

class Ray():
    def __init__(self, origin, x, y, color, opacity, RAYS_BATCH):
        self.origin = origin
        self.x = x
        self.y = y
        self.color = color
        self.opacity = opacity
        self.RAYS_BATCH = RAYS_BATCH

    def draw(self):
        # self.RAYS_BATCH.add(2, gl.GL_LINES, None, ('v2f/stream', (self.origin[0],self.origin[1], self.x,self.y)), ('c3B', (self.color[0],self.color[1],self.color[2] , self.color[0],self.color[1],self.color[2])))
        ray = pyglet.shapes.Line(
            self.origin[0], self.origin[1], self.x, self.y, 1, color=self.color, batch=self.RAYS_BATCH)
        ray.opacity = self.opacity
        # ray.draw()
        return ray
        # self.RAYS_LIST.append(ray)

class Player():
    def __init__(self, image, player_color, overlay, pos, width, show_vignete, screen):
        self.width = width
        self.Player_Sprite = image
        self.PLAYER_COLOR = player_color
        self.pos = pos
        self.cell_X, self.cell_Y = 0, 0

        self.finishX, self.finishY = 0, 0
        self.points_of_collision = []

        self.vignette = overlay
        self.vignette_rect = Rect(pos[0], pos[1], self.vignette)
        # self.vignette_rect = self.vignette.get_rect(center=self.pos)
        self.rect = Rect(pos[0], pos[1], self.Player_Sprite)
        # self.rect = self.Player_Sprite.get_rect(center=self.pos)
        self.SHAPE: str = 'CIRCLE'  # ! 'SQAURE' OR 'CIRCLE'
        self.SHOW_VIGNETEE: bool = show_vignete
        self.smooth_time: float = 1
        self.time: float = 0

        self.RENDERED_TEXT: bool = False
        self.BARS_BATCH = pyglet.graphics.Batch()
        self.TEXT_BATCH = pyglet.graphics.Batch()

        self.RAYS_BATCH = pyglet.graphics.Batch()
        self.RAYS_LIST = []

        self.TEXT_LIST: list = []

        self.TRAIL_POSTITIONS: list = []
        self.TRAIL_MAX_LENGTH: int = 25
        self.TRAIL_BATCH = pyglet.graphics.Batch()
        self.TRAIL_LINES: list = []
        # self.TAIL = self.LOAD_TRAIL(self.TRrangeAIL_IMAGE, self.PLAYER_COLOR)

        self.IS_MOVING: bool = False
        self.SPEED_BOOST: float = 1.05
        self.SPEED_BOOST_DURATION: float = 10
        self.MAX_SPEED_DURATION: float = 10

        self.health = 5
        self.MAX_HEALTH = 5
        self.screen_width, self.screen_height = screen

    def reset(self):
        self.health = self.MAX_HEALTH
        self.SPEED_BOOST_DURATION = self.MAX_SPEED_DURATION
        self.TRAIL_POSTITIONS.clear()
        self.TRAIL_BATCH = pyglet.graphics.Batch()

    def change_debugging_mode(self, dev_mode, maze_col):
        # NOTE DEBUGGING OR DEVELOPMENT ONLY
        self.DEVELOPER_MODE: bool = dev_mode
        self.ENABLE_MAZE_GOL: bool = maze_col

    def update(self, x, y, SHIFT, dt, cols, rows, grid, maze_cells_batch, screen_size):  # Update movements
        self.grid = grid
        self.rows = rows
        self.cols = cols
        if screen_size[0] > screen_size[1]:
            self.MAX_RAY_LENGTH = screen_size[0]
        else:
            self.MAX_RAY_LENGTH = screen_size[1]
        self.maze_cells_batch = maze_cells_batch
        self.rect.update(self.Player_Sprite.x, self.Player_Sprite.y)

        if len(self.TRAIL_POSTITIONS) >= self.TRAIL_MAX_LENGTH:
            if not self.IS_MOVING:
                self.TRAIL_POSTITIONS.append(
                    (self.Player_Sprite.x, self.Player_Sprite.y))
                try:
                    self.TRAIL_LINES.append(self.line)
                except:
                    pass
            self.TRAIL_POSTITIONS.pop(0)
            self.TRAIL_LINES.pop(0)
        else:
            self.TRAIL_POSTITIONS.append(
                (self.Player_Sprite.x, self.Player_Sprite.y))
            try:
                self.TRAIL_LINES.append(self.line)
            except:
                pass

        self.vignette_rect.update(self.Player_Sprite.x, self.Player_Sprite.y)
        self.vignette.x = self.rect.left()
        self.vignette.y = self.rect.bottom()
        testdist = dt // 5  # distance from the wall
        self.cell_X = int(self.rect.centerx() // self.width)
        self.cell_Y = int(self.rect.centery() // self.width)
        # min_X = self.rect.leftX() // self.width
        # max_X = self.rect.rightX() // self.width
        # min_Y = self.rect.topY() // self.width
        # max_Y = self.rect.bottomY() // self.width

        w, a, s, d = False, False, False, False
        if x > self.Player_Sprite.x:
            d = True
            a = False
        elif x < self.Player_Sprite.x:
            d = False
            a = True
        if y > self.Player_Sprite.y:
            w = True
            s = False
        elif y < self.Player_Sprite.y:
            w = False
            s = True

        if not w and not a and not s and not d:
            self.IS_MOVING = False
        else:
            self.IS_MOVING = True
        self.TRAIL_MAX_LENGTH = 25
        speed = 10
        if (
            self.time >= self.smooth_time
            and SHIFT
            and self.SPEED_BOOST_DURATION >= 0
            and self.IS_MOVING
        ):
            self.SPEED_BOOST_DURATION -= 0.03
            speed = 4
            self.TRAIL_MAX_LENGTH = 27
        if not self.IS_MOVING and self.SPEED_BOOST_DURATION <= self.MAX_SPEED_DURATION:
            self.SPEED_BOOST_DURATION += 0.03

        if self.ENABLE_MAZE_GOL:
            if w == True:  # UP
                self.time += 0.03
                next_Y = ((self.rect.top()-testdist) // self.width)
                is_wall = self.grid[self.cell_Y][self.cell_X].walls[2]
                if self.cell_Y == next_Y or (next_Y >= 0 and not is_wall):
                    self.Player_Sprite.y += speed
            elif s == True:  # DOWN
                self.time += 0.03
                next_Y = (
                    (self.rect.bottom()-(self.Player_Sprite.height)+testdist) // self.width)
                is_wall = self.grid[self.cell_Y][self.cell_X].walls[0]
                if self.cell_Y == next_Y or (next_Y < self.rows and not is_wall):
                    self.Player_Sprite.y -= speed
            if a == True:  # LEFT
                self.time += 0.03
                next_X = (
                    (self.rect.left()-(self.Player_Sprite.width)-testdist) // self.width)
                is_wall = self.grid[self.cell_Y][self.cell_X].walls[3]
                if self.cell_X == next_X or (next_X >= 0 and not is_wall):
                    self.Player_Sprite.x -= speed
            elif d == True:  # RIGHT
                self.time += 0.03
                next_X = ((self.rect.right()+testdist) // self.width)
                is_wall = self.grid[self.cell_Y][self.cell_X].walls[1]
                if self.cell_X == next_X or (next_X < self.cols and not is_wall):
                    self.Player_Sprite.x += speed
        else:
            self.Player_Sprite.x = x
            self.Player_Sprite.y = y
            # if w == True:
            #     self.Player_Sprite.y += 5
            # elif s == True:
            #     self.Player_Sprite.y -= 5
            # if a == True:
            #     self.Player_Sprite.x -= 5
            # elif d == True:
            #     self.Player_Sprite.x += 5
            # self.rotate(w, a, s, d)

    def draw(self):
        # gl stuff
        pyglet.gl.glEnable(pyglet.gl.GL_BLEND)
        pyglet.gl.glBlendFunc(pyglet.gl.GL_SRC_ALPHA,
                              pyglet.gl.GL_ONE_MINUS_SRC_ALPHA)
        pyglet.gl.glEnable(pyglet.gl.GL_LINE_SMOOTH)
        pyglet.gl.glHint(pyglet.gl.GL_LINE_SMOOTH_HINT, pyglet.gl.GL_DONT_CARE)

        self.RAYS_BATCH = pyglet.graphics.Batch()
        self.LEFT_BOTTOM_BATCH = pyglet.graphics.Batch()
        self.RIGHT_BOTTOM_BATCH = pyglet.graphics.Batch()
        self.LEFT_TOP_BATCH = pyglet.graphics.Batch()
        self.RIGHT_TOP_BATCH = pyglet.graphics.Batch()

        self.TOP_BATCH = pyglet.graphics.Batch()
        self.BOTTOM_BATCH = pyglet.graphics.Batch()
        self.RIGHT_BATCH = pyglet.graphics.Batch()
        self.LEFT_BATCH = pyglet.graphics.Batch()

        self.RAYS_LIST.clear()
        # x2 = math.cos(0) * 100 + self.Player_Sprite.x
        # y2 = math.sin(0) * 100 + self.Player_Sprite.y
        x3 = self.Player_Sprite.x
        y3 = self.Player_Sprite.y
        try:

            self.total_walls_in_cell = []
            points = []
            for y in range(self.rows):
                for x in range(self.cols):
                    wall_top: bool = self.grid[y][x].walls[0]
                    wall_right: bool = self.grid[y][x].walls[1]
                    wall_bottom: bool = self.grid[y][x].walls[2]
                    wall_left: bool = self.grid[y][x].walls[3]
                    if wall_top:
                        x1 = self.grid[y][x].top_wall_1[0]
                        y1 = self.grid[y][x].top_wall_1[1]
                        x2 = self.grid[y][x].top_wall_2[0]
                        y2 = self.grid[y][x].top_wall_2[1]
                        self.total_walls_in_cell.append([(x1, y1), (x2, y2)])
                        # self.total_walls_in_cell.append((x1, y1))
                        # self.total_walls_in_cell.append((x2, y2))
                    if wall_right:  # RIGHT
                        x1 = self.grid[y][x].right_wall_1[0]
                        y1 = self.grid[y][x].right_wall_1[1]
                        x2 = self.grid[y][x].right_wall_2[0]
                        y2 = self.grid[y][x].right_wall_2[1]
                        self.total_walls_in_cell.append([(x1, y1), (x2, y2)])
                        # self.total_walls_in_cell.append((x1, y1))
                        # self.total_walls_in_cell.append((x2, y2))
                    if wall_left:  # LEFT
                        x1 = self.grid[y][x].left_wall_1[0]
                        y1 = self.grid[y][x].left_wall_1[1]
                        x2 = self.grid[y][x].left_wall_2[0]
                        y2 = self.grid[y][x].left_wall_2[1]
                        self.total_walls_in_cell.append([(x1, y1), (x2, y2)])
                        # self.total_walls_in_cell.append((x1, y1))
                        # self.total_walls_in_cell.append((x2, y2))
                    if wall_bottom:  # BOTTOM
                        x1 = self.grid[y][x].bottom_wall_1[0]
                        y1 = self.grid[y][x].bottom_wall_1[1]
                        x2 = self.grid[y][x].bottom_wall_2[0]
                        y2 = self.grid[y][x].bottom_wall_2[1]
                        self.total_walls_in_cell.append([(x1, y1), (x2, y2)])
                        # self.total_walls_in_cell.append((x1, y1))
                        # self.total_walls_in_cell.append((x2, y2))
        except Exception as e:
            print(f'{e} 2')

        # for i in range(lines):
        for wall in self.total_walls_in_cell:
            x1 = wall[0][0]
            y1 = wall[0][1]
            x2 = wall[1][0]
            y2 = wall[1][1]
            points.append((x1, y1))
            points.append((x2, y2))
            # distance = math.hypot(x3 - x1, y3 - y1)
            # if distance > 200:
            # distance = math.hypot(x3 - x2, y3 - y2)
            # if distance < 200:
            # ray = Ray((x3, y3), x2, y2, (255,255,255), 40, self.RAYS_BATCH)
            # ray = ray.draw()
            # self.RAYS_LIST.append(ray)
        uniqueAngles = []
        for point in points:
            angle = math.atan2(point[1]-y3, point[0]-x3)
            uniqueAngles.append(angle-0.00001)
            uniqueAngles.append(angle)
            uniqueAngles.append(angle+0.00001)

        # Remove duplicats, this almost triples performance.
        print(f'Before: {len(uniqueAngles)}')
        uniqueAngles = list(set(uniqueAngles))
        print(f'After: {len(uniqueAngles)}')

        uniqueAngles.sort()
        self.points_of_collision.clear()
        self.points_of_collision.append((x3, y3))
        # self.points_of_collision.append(x3)
        # self.points_of_collision.append(y3)
        # self.points_of_collision.append(y3)

        # unique_line_angles = []
        # for wall in self.total_walls_in_cell:
        #     distance = math.hypot(x3 - wall[0][1], y3 - wall[0][0])
        #     if distance < 100:
        #         unique_line_angles.append([(x3, y3), (wall[0][1], wall[0][0])])
        first_point = None
        for angle in uniqueAngles:
            closest = None
            # FOR RAYCASTS
            x4 = math.cos(angle) * 100 + self.Player_Sprite.x
            y4 = math.sin(angle) * 100 + self.Player_Sprite.y
        #     has_intersection = Trueet current I
            for i, wall in enumerate(self.total_walls_in_cell):

                # ANOTHER RAYCASTING IMPLEMNTATION THAT DOESNT WORK
                r_px = x3
                r_py = y3
                r_dx = x4-x3
                r_dy = y4-y3

                s_px = wall[0][0]
                s_py = wall[0][1]
                s_dx = wall[1][0]-wall[0][0]
                s_dy = wall[1][1]-wall[0][1]

                r_mag = math.sqrt(r_dx*r_dx+r_dy*r_dy)
                s_mag = math.sqrt(s_dx*s_dx+s_dy*s_dy)
                try:
                    if(r_dx/r_mag == s_dx/s_mag and r_dy/r_mag == s_dy/s_mag):
                        continue
                    T2 = (r_dx*(s_py-r_py) + r_dy*(r_px-s_px)) / \
                        (s_dx*r_dy - s_dy*r_dx)
                    T1 = (s_px+s_dx*T2-r_px)/r_dx
                    if T1 < 0:
                        continue
                    if T2 < 0 or T2 > 1:
                        continue
                    if not closest or T1 < closest:
                        closest = T1
                except:
                    pass
            try:
                if not first_point:
                    first_point = (r_px+r_dx*closest, r_py+r_dy*closest)
                self.points_of_collision.append(
                    (r_px+r_dx*closest, r_py+r_dy*closest))
                # self.points_of_collision.append(r_px+r_dx*closest)
                # self.points_of_collision.append(r_py+r_dy*closest)
                # self.points_of_collision.sort()
                # ray = Ray((x3, y3), r_px+r_dx*closest, r_py+r_dy*closest,
                #         (255, 255, 255), 10, self.RAYS_BATCH)
                # ray = ray.draw()
                # self.RAYS_LIST.append(ray)
            except (UnboundLocalError, TypeError, IndexError):
                pass
        new_points_of_collision = []
        try:
            # This is to finish the polygon where we started
            # self.points_of_collision.append(first_point[0])
            # self.points_of_collision.append(first_point[1])
            self.points_of_collision.append((first_point))
            for index in range(len(self.points_of_collision)):
                index+1

                x1 = self.points_of_collision[index-1][0]
                y1 = self.points_of_collision[index-1][1]

                x2 = self.points_of_collision[index][0]
                y2 = self.points_of_collision[index][1]

                distance = math.hypot(x1 - x2, y1 - y2)
                if distance < self.MAX_RAY_LENGTH:
                    # print(distance)
                    # else:
                    # new_points_of_collision.append((x1,y1))
                    # new_points_of_collision.append((x2,y2))
                    new_points_of_collision.append(x2)
                    new_points_of_collision.append(y2)
            # Draw rays
            for i in range(len(new_points_of_collision)):
                i+1
                ray = Ray((x3, y3), new_points_of_collision[i-1], new_points_of_collision[i],
                          (255, 255, 255), 10, self.RAYS_BATCH)
                ray = ray.draw()
                self.RAYS_LIST.append(ray)
            # Draw polygon
            ec = int(len(new_points_of_collision)/2)
            self.RAYS_BATCH.add(ec, pyglet.gl.GL_POLYGON, None,
                                ("v2f/stream", new_points_of_collision),
                                ("c4B", (255, 255, 255, 10)*ec))
        except Exception as e:
            print(e)
            # RAYCAST IMPLEMENTATION
           #     x1 = wall[0][0]
           #     y1 = wall[0][1]
           #     x2 = wall[1][0]
           #     y2 = wall[1][1]

           #     denominator = ((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4))
           #     t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / denominator
           #     u = -((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / denominator
           #     # distance = math.sqrt(math.pow((x3-pt1),2)+math.pow((y3-pt2),2))
           #     # FOR RAYCASING
           #     if t > 0 and t < 1 and u > 0:
           #         pt1 = x1 + t * (x2 - x1);
           #         pt2 = y1 + t * (y2 - y1);
           #         distance = math.hypot(x3 - pt1, y3 - pt2)
           #         if distance < record:
           #             record = distance
           #             closest = (pt1, pt2)
           # if closest:
           #     self.points_of_collision.append((closest[0], closest[1]))
           #     # self.points_of_collision.append(closest[0])
           #     # self.points_of_collision.append(closest[1])
           #     ray = Ray((x3, y3), closest[0], closest[1], (255,255,255), 40, self.RAYS_BATCH)
           #     ray = ray.draw()
           #     self.RAYS_LIST.append(ray)
        # except Exception as e: print(f'{e} 2')
        # OLD VIGNETTE METHOD START -----
    #     init_bottom_left = False
    #     init_bottom_right = False
    #     init_top_left = False
    #     init_top_right = False

    #     record_left = 1000
    #     record_right = 0
    #     record_top = 0
    #     record_bottom = 1000
    #     # for i in range(lines):
    #     for index, _ in enumerate(self.points_of_collision):
    #         x1 = self.points_of_collision[index][0]
    #         y1 = self.points_of_collision[index][1]
    #         index + 1
    #         x2 = self.points_of_collision[index][0]
    #         y2 = self.points_of_collision[index][1]
    # #         # distance = math.hypot(x1 - x2, y1 - y2)
    # #         # self.RAYS_BATCH.add(2, gl.GL_LINE_LOOP, None, ('v2f', (x1,y1, x2, y2)), ('c3B', [(255)]*(3*2)))

    # #         #     print(distance)
    # #         #     if distance < record:
    # #         #         record = distance
    # #         #         shortest = (x2, y2)
    # #         # if x2 <= self.Player_Sprite.x and y2 <= self.Player_Sprite.y: # bottom left
    # #         #     if not init_bottom_left:
    # #         #         self.RAYS_BATCH.add(2, gl.GL_TRIANGLE_STRIP, None, ('v2f', (0,0, shortest[0],shortest[1])), ('c3B', [(255)]*(3*2)))
    # #         #         init_bottom_left = True
    # #         #     else:
    # #         #         self.RAYS_BATCH.add(2, gl.GL_TRIANGLE_STRIP, None, ('v2f', (x1,y1, shortest[0],shortest[1])), ('c3B', [(255)]*(3*2)))
    # #         # self.RAYS_BATCH.add(2, gl.GL_LINES, None, ('v2f', (self.points_of_collision[index-1][0],self.points_of_collision[index-1][1],self.points_of_collision[index][0],self.points_of_collision[index][1])), ('c3B', [(100)]*(3*2)))

    #         if x2 < record_left: record_left = x2
    #         if x2 > record_right: record_right = x2
    #         if y2 > record_top: record_top = y2
    #         if y2 < record_bottom: record_bottom = y2
    #         # if y2 > self.Player_Sprite.y and y2 < record_top and x2 >= (self.Player_Sprite.x-10) and x2 <= (self.Player_Sprite.x+10): record_top = y2 # shortest top positon

    #         if x2 <= self.Player_Sprite.x and y2 <= self.Player_Sprite.y: # bottom left
    #             if x1 <= self.Player_Sprite.x and y1 <= self.Player_Sprite.y: # bottom left
    #                 if not init_bottom_left:
    #                     self.LEFT_BOTTOM_BATCH.add(2, gl.GL_TRIANGLE_FAN, None, ('v2f', (0,0, x2,y2)), ('c3B', [(0)]*(3*2)))
    #                     init_bottom_left = True
    #                 else:
    #                     self.LEFT_BOTTOM_BATCH.add(2, gl.GL_TRIANGLE_FAN, None, ('v2f', (x1,y1, x2,y2)), ('c3B', [(0)]*(3*2)))
    #         if x2 <= self.Player_Sprite.x and y2 >= self.Player_Sprite.y: # top left
    #             if x1 <= self.Player_Sprite.x and y1 >= self.Player_Sprite.y:
    #                 if not init_top_left:
    #                     self.LEFT_TOP_BATCH.add(2, gl.GL_TRIANGLE_FAN, None, ('v2f', (0,self.screen_height, x2,y2)), ('c3B', [(0)]*(3*2)))
    #                     init_top_left = True
    #                 else:
    #                     self.LEFT_TOP_BATCH.add(2, gl.GL_TRIANGLE_FAN, None, ('v2f', (x1,y1, x2,y2)), ('c3B', [(0)]*(3*2)))

    #         if x2 >= self.Player_Sprite.x and y2 >= self.Player_Sprite.y: # top right
    #             if x1 >= self.Player_Sprite.x and y1 >= self.Player_Sprite.y: # top right
    #                 if not init_top_right:
    #                     self.RIGHT_TOP_BATCH.add(2, gl.GL_TRIANGLE_FAN, None, ('v2f', (self.screen_width,self.screen_height, x2,y2)), ('c3B', [(0)]*(3*2)))
    #                     init_top_right = True
    #                 else:
    #                     self.RIGHT_TOP_BATCH.add(2, gl.GL_TRIANGLE_FAN, None, ('v2f', (x1,y1, x2,y2)), ('c3B', [(0)]*(3*2)))
    #         if x2 >= self.Player_Sprite.x and y2 <= self.Player_Sprite.y: # bottom right
    #             if x1 >= self.Player_Sprite.x and y1 <= self.Player_Sprite.y: # bottom right
    #                 if not init_bottom_right:
    #                     self.RIGHT_BOTTOM_BATCH.add(2, gl.GL_TRIANGLE_FAN, None, ('v2f', (self.screen_width,0, x2,y2)), ('c3B', [(0)]*(3*2)))
    #                     init_bottom_right = True
    #                 else:
    #                     self.RIGHT_BOTTOM_BATCH.add(2, gl.GL_TRIANGLE_FAN, None, ('v2f', (x1,y1, x2,y2)), ('c3B', [(0)]*(3*2)))

    #             # if y2 > self.Player_Sprite.y and x2 >= (self.Player_Sprite.x) and x2 <= (self.Player_Sprite.x+11):
    #                 # self.TOP_BATCH.add(3, gl.GL_TRIANGLE_FAN, None, ('v2f', (0,self.screen_height, self.screen_width,self.screen_height, x2, y2)), ('c3B', [(170)]*(3*3)))
    #         # self.BOTTOM_BATCH.add(4, gl.GL_QUADS, None, ('v2f', (0,0, self.screen_width,0, self.screen_width, record_bottom, 0, record_bottom)), ('c3B', [(0)]*(3*4)))
    #         # self.LEFT_BATCH.add(4, gl.GL_QUADS, None, ('v2f', (0,0, 0,self.screen_height, record_left,self.screen_height, record_left,0)), ('c3B', [(0)]*(3*4)))
    #         # self.RIGHT_BATCH.add(4, gl.GL_QUADS, None, ('v2f', (self.screen_width,0, self.screen_width,self.screen_height, record_right,self.screen_height, record_right,0)), ('c3B', [(0)]*(3*4)))
        # OLD VIGNETTE METHOD END -----

        # pass
        # print(self.Player_Sprite.x,self.Player_Sprite.y)

        # print(self.rect.x, self.rect.y)s
        # self.Player_Sprite.x = x
        # self.Player_Sprite.y = y

        # print(self.Player_Sprite.x, s)

        # TAIL
        fade_amounts = self.get_fade_values(0, 255, len(self.TRAIL_POSTITIONS))
        size_amounts = self.get_fade_values(0, 7, len(self.TRAIL_POSTITIONS))
        for index, tail_pos in enumerate(self.TRAIL_POSTITIONS):
            try:
                # self.TRAIL_BATCH.addself.makeCircle(tail_pos[0],tail_pos[1],size_amounts[index],12, self.PLAYER_COLOR))
                #     print(index)
                # circle1 = pyglet.shapes.Circle(tail_pos[0], tail_pos[1], size_amounts[index]*10, color = self.PLAYER_COLOR, batch = self.TRAIL_BATCH)
                #     circle1.opacity = 100
                x1 = self.TRAIL_POSTITIONS[index-1][0]
                y1 = self.TRAIL_POSTITIONS[index-1][1]
                x2 = tail_pos[0]
                y2 = tail_pos[1]
                # pyglet.gl.glLineWidth(self.WALL_WIDTH)
                # self.TRAIL_BATCH.add(2, gl.GL_LINES, None, ('v2f', (x,y, self.Player_Sprite.x, self.Player_Sprite.y)), ('c3B', (self.PLAYER_COLOR[0],self.PLAYER_COLOR[1],self.PLAYER_COLOR[2] , self.PLAYER_COLOR[0],self.PLAYER_COLOR[1],self.PLAYER_COLOR[2])))
                self.line = pyglet.shapes.Line(
                    x1, y1, x2, y2, 3, color=self.PLAYER_COLOR, batch=self.TRAIL_BATCH)
                self.line.opacity = 127
                # self.line.opacity = fade_amounts[0]
                # print(fade_amounts)

                # changing opacity of the line2
                # opacity is visibility (0 = invisible, 255 means visible)
            except IndexError:
                # the reason we pass this exception is because at the first index of the list it tries to find the one before and thus crashes.
                pass

        #     pyglet.graphics.draw(4, pyglet.gl.GL_, ('v2f', [0,0,
        #                                                         self.screen_width,0,
        #                                                         self.screen_width,self.vignette_rect.bottom()-(self.vignette.height/2)+(self.Player_Sprite.height/2),
        #                                                         0, self.vignette_rect.bottom()-(self.vignette.height/2)+(self.Player_Sprite.height/2)]), ('c3B', (0,0,0 ,0,0,0 ,0,0,0 ,0,0,0)))
        #     self.TAIL.set_alpha(fade_amounts[index])
        #     finalImage = self.TAIL.copy()
        #     try: finalImage = pygame.transform.scale(finalImage, (size_amounts[index], size_amounts[index]))
        #     except: passsa
        self.TRAIL_BATCH.draw()
        self.RIGHT_BOTTOM_BATCH.draw()
        self.RIGHT_TOP_BATCH.draw()
        self.LEFT_TOP_BATCH.draw()
        self.LEFT_BOTTOM_BATCH.draw()
        # self.TOP_BATCH.draw()
        # self.BOTTOM_BATCH.draw()
        # self.RIGHT_BATCH.draw()
        # self.LEFT_BATCH.draw()
        self.RAYS_BATCH.draw()

        # TOP
        if self.SHOW_VIGNETEE:
            pyglet.graphics.draw(4, pyglet.gl.GL_QUADS, ('v2f', [0, 0,
                                                                 self.screen_width, 0,
                                                                 self.screen_width, self.vignette_rect.bottom()-(self.vignette.height/2)
                                                                 + (self.Player_Sprite.height/2),
                                                                 0, self.vignette_rect.bottom()-(self.vignette.height/2)+(self.Player_Sprite.height/2)]), ('c3B', (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)))

            # BOTTOM
            pyglet.graphics.draw(4, pyglet.gl.GL_QUADS, ('v2f', [0, self.screen_height,
                                                                 self.screen_width, self.screen_height,
                                                                 self.screen_width, self.vignette_rect.top()-(self.vignette.height/2)
                                                                 - (self.Player_Sprite.height/2),
                                                                 0, self.vignette_rect.top()-(self.vignette.height/2)-(self.Player_Sprite.height/2)]), ('c3B', (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)))

            # LEFT
            pyglet.graphics.draw(4, pyglet.gl.GL_QUADS, ('v2f', [0, self.vignette_rect.top()-(self.vignette.height/2)+(self.Player_Sprite.height/2),
                                                                 self.vignette_rect.left()-(self.vignette.width/2)+(self.Player_Sprite.width
                                                                                / 2), self.vignette_rect.bottom()+(self.vignette.height/2)+(self.Player_Sprite.height/2),
                                                                 self.vignette_rect.left()-(self.vignette.width/2)+(self.Player_Sprite.width
                                                                                / 2), self.vignette_rect.bottom()-(self.vignette.height/2)+(self.Player_Sprite.height/2),
                                                                 0, self.vignette_rect.bottom()-(self.vignette.height/2)+(self.Player_Sprite.height/2)]), ('c3B', (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)))
            # RIGHT
            pyglet.graphics.draw(4, pyglet.gl.GL_QUADS, ('v2f', [self.screen_width, self.vignette_rect.top()-(self.vignette.height/2)+(self.Player_Sprite.height/2),
                                                                 self.vignette_rect.right()-(self.vignette.width/2)-(self.Player_Sprite.width
                                                                                / 2), self.vignette_rect.bottom()+(self.vignette.height/2)+(self.Player_Sprite.height/2),
                                                                 self.vignette_rect.right()-(self.vignette.width/2)-(self.Player_Sprite.width
                                                                                / 2), self.vignette_rect.bottom()-(self.vignette.height/2)+(self.Player_Sprite.height/2),
                                                                 self.screen_width, self.vignette_rect.bottom()-(self.vignette.height/2)+(self.Player_Sprite.height/2)]), ('c3B', (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)))

            self.vignette.draw()
        self.Player_Sprite.draw()

        self.TEXT_BATCH = pyglet.graphics.Batch()  # RESET TEXT GRAPHICS
        if self.finishX * self.width <= 200 and self.finishY * self.width < 260:
            if self.vignette_rect.x >= self.screen_width-200 and self.vignette_rect.y <= 260:
                self.draw_bars((10, -110, 30, 120), (255, 255, 255), self.PLAYER_COLOR,
                               50, self.SPEED_BOOST_DURATION, self.MAX_SPEED_DURATION, 'BOOST')
                self.draw_bars((50, -110, 30, 120), (255, 255, 255),
                               (255, 75, 75), 50, self.health, self.MAX_HEALTH, 'HEALTH')
            else:
                self.draw_bars((self.screen_width-80, -110, 30, 120), (255, 255, 255),
                               self.PLAYER_COLOR, 50, self.SPEED_BOOST_DURATION, self.MAX_SPEED_DURATION, 'BOOST')
                self.draw_bars((self.screen_width-40, -110, 30, 120), (255, 255, 255),
                               (255, 75, 75), 50, self.health, self.MAX_HEALTH, 'HEALTH')
        else:
            if self.vignette_rect.x <= 200 and self.vignette_rect.y <= 260:
                self.draw_bars((self.screen_width-80, -110, 30, 120), (255, 255, 255),
                               self.PLAYER_COLOR, 50, self.SPEED_BOOST_DURATION, self.MAX_SPEED_DURATION, 'BOOST')
                self.draw_bars((self.screen_width-40, -110, 30, 120), (255, 255, 255),
                               (255, 75, 75), 50, self.health, self.MAX_HEALTH, 'HEALTH')
            else:
                self.draw_bars((10, -110, 30, 120), (255, 255, 255), self.PLAYER_COLOR,
                               50, self.SPEED_BOOST_DURATION, self.MAX_SPEED_DURATION, 'BOOST')
                self.draw_bars((50, -110, 30, 120), (255, 255, 255),
                               (255, 75, 75), 50, self.health, self.MAX_HEALTH, 'HEALTH')

        self.TEXT_BATCH.draw()
        self.RENDERED_TEXT = False
        # self.BARS_BATCH.draw()

    def draw_bars(self, rect, outline_color, fill_color, opacity, value, max_value, name, width=1):
        # pyglet.gl.glLineWidth(width)
        x, y, w, h = rect
        width = max(width, 1)  # Draw at least one rect.
        width = min(min(width, w//2), h//2)  # Don't overdraw.
        BAR_POSITON = (value/max_value)*h
        # pygame.gfxdraw.box(screen, pygame.Rect(x,y+BAR_POSITON+h-BAR_POSITON,w,h-(BAR_POSITON)-h), fill_color)# alpha level
        # pyglet.graphics.draw(4, pyglet.gl.GL_QUADS, ('v2f', [x,y,
        #                                                      x,y+(BAR_POSITON)-h,
        #                                                      x+w,y+h-(BAR_POSITON)-h,
        #                                                      x,y+w]), ('c3B', (fill_color[0],fill_color[1],fill_color[2],fill_color[0],fill_color[1],fill_color[2], fill_color[0],fill_color[1],fill_color[2], fill_color[0],fill_color[1],fill_color[2])))
        bar = pyglet.shapes.Rectangle(
            x, y+BAR_POSITON+h-BAR_POSITON, w, h+(BAR_POSITON)-h, color=fill_color, batch=self.BARS_BATCH)

        # self.BARS_BATCH.add(4, gl.GL_LINES, None, ('v2f', (x,y ,x,y-h, x+w,y-h ,x+w,y)), ('c3B', (outline_color[0],outline_color[1],outline_color[2] , outline_color[0],outline_color[1],outline_color[2],outline_color[0],outline_color[1],outline_color[2] , outline_color[0],outline_color[1],outline_color[2])))
        line_left = pyglet.shapes.Line(
            x, y+h, x, y+h*2, width, color=outline_color, batch=self.BARS_BATCH)
        line_right = pyglet.shapes.Line(
            x+w, y+h, x+w, y+h*2, width, color=outline_color, batch=self.BARS_BATCH)
        line_top = pyglet.shapes.Line(
            x, y+h*2, x+w, y+h*2, width, color=outline_color, batch=self.BARS_BATCH)
        line_bottom = pyglet.shapes.Line(
            x, y+h, x+w, y+h, width, color=outline_color, batch=self.BARS_BATCH)
        # changing opacity of the rect1
        # opacity is visibility (0 = invisible, 255 means visible)
        bar.opacity = opacity
        bar.draw()
        self.BARS_BATCH.draw()

        # myfont = pygame.font.SysFont('arial.ttf', 22)
        if not self.RENDERED_TEXT:
            space = -15
            for letter in name:
                play_text = pyglet.text.Label(letter, font_name="Arial", font_size=11, x=x+14, y=y+h+h+space,
                                              anchor_x='center', anchor_y='center', color=(255, 255, 255, 255), batch=self.TEXT_BATCH)
                self.TEXT_LIST.append(play_text)
                # textsurface = myfont.render(letter, True, (255, 255, 255))
                # screen.blit(textsurface,(x+10,y+space))
                space -= 17
        self.TEXT_LIST.clear()
        # This draws several smaller outlines inside the first outline. Invert
        # the direction if it should grow outwards.
        # for i in range(width):
        #     pygame.gfxdraw.rectangle(screen, (x+i, y+i, w-i*2, h-i*2), outline_color)

    def get_fade_values(self, start, max_value, amount_of_numbers):
        # NOTE TYPES
        numbers = []
        try:
            step = (max_value - start) / (amount_of_numbers - 1)
        except ZeroDivisionError:
            step = (max_value - start) / amount_of_numbers
        for i in range(amount_of_numbers):
            # In this case we want to start at 1, to simplify things.
            i = i + 1
            if i == 1:
                numbers.append(int(start))  # first number
            elif i == 2:
                numbers.append(int(start + step))  # second number
            if 3 <= i < amount_of_numbers:
                # everything in between
                numbers.append(int(start + (i - 1) * step))
            if i == amount_of_numbers:
                numbers.append(
                    int(start + (amount_of_numbers - 1) * step))  # end
        return numbers

    # def rotate(self, w, a, s, d):
    #     if a:
    #         self.Player_Sprite.rotation = -90
    #     elif d:
    #         self.Player_Sprite.rotation = 90
    #     if w:
    #         if a:
    #             self.Player_Sprite.rotation = -45
    #         elif d:
    #             self.Player_Sprite.rotation = 45
    #         else:
    #             self.Player_Sprite.rotation = 0
    #     elif s:
    #         if a:
    #             self.Player_Sprite.rotation = -135
    #         elif d:
    #             self.Player_Sprite.rotation = 135
    #         else:
    #             self.Player_Sprite.rotation = 180


"""Sphinx extension for SCXML visualization with Graphviz"""

from pathlib import Path

import docutils.parsers.rst
import docutils.statemachine

from hat import stc

def setup(app):
    app.add_directive('scxml', ScxmlDirective)

class ScxmlDirective(docutils.parsers.rst.Directive):

    required_arguments = 1

    def run(self):
        env = self.state.document.settings.env
        source = self.state_machine.input_lines.source(
            self.lineno - self.state_machine.input_offset - 1)

        path = Path(env.relfn2path(self.arguments[0])[1])
        states = stc.parse_scxml(path)
        dot = stc.create_dot_graph(states)
        text = ('.. graphviz::\n\n' +
                '\n'.join('   ' + i for i in dot.split('\n')))

        lines = docutils.statemachine.string2lines(text)
        self.state_machine.insert_input(lines, source)
        return []


from http import HTTPStatus
from logging import Logger

from flask.json import jsonify
from flask.wrappers import Request, Response

from pbench.server import PbenchServerConfig
from pbench.server.api.resources import (
    API_AUTHORIZATION,
    API_METHOD,
    API_OPERATION,
    APIAbort,
    ApiBase,
    ApiParams,
    ApiSchema,
    Parameter,
    ParamType,
    Schema,
)
from pbench.server.database.models.server_config import (
    ServerConfig,
    ServerConfigBadValue,
    ServerConfigError,
)

class ServerConfiguration(ApiBase):
    """
    API class to retrieve and mutate server configuration settings.
    """

    def __init__(self, config: PbenchServerConfig, logger: Logger):
        super().__init__(
            config,
            logger,
            ApiSchema(
                API_METHOD.PUT,
                API_OPERATION.UPDATE,
                uri_schema=Schema(
                    Parameter("key", ParamType.KEYWORD, keywords=ServerConfig.KEYS)
                ),
                # We aspire to be flexible about how a config option is
                # specified on a PUT. The value of a single config option can
                # be set using the "value" query parameter or the "value" JSON
                # body parameter. You can also specify one config option or
                # multiple config options by omitting the key name from the URI
                # and specifying the names and values in a JSON request body:
                #
                #   PUT /server/configuration/dataset-lifetime?value=2y
                #   PUT /server/configuration/dataset-lifetime
                #       {"value": "2y"}
                #   PUT /server/configuration
                #       {"dataset-lifetime": "2y"}
                query_schema=Schema(Parameter("value", ParamType.STRING)),
                body_schema=Schema(
                    Parameter("value", ParamType.JSON),
                ),
                authorization=API_AUTHORIZATION.ADMIN,
            ),
            ApiSchema(
                API_METHOD.GET,
                API_OPERATION.READ,
                uri_schema=Schema(
                    Parameter("key", ParamType.KEYWORD, keywords=ServerConfig.KEYS)
                ),
                authorization=API_AUTHORIZATION.NONE,
            ),
            always_enabled=True,
        )

    def _get(self, params: ApiParams, request: Request) -> Response:
        """
        Get the values of server configuration parameters.

        GET /api/v1/server/configuration/{key}
            return the value of a single configuration parameter

        or

        GET /api/v1/server/configuration
            return all configuration parameters

        Args:
            params: API parameters
            request: The original Request object containing query parameters

        Returns:
            HTTP Response object
        """

        key = params.uri.get("key")
        try:
            if key:
                s = ServerConfig.get(key)
                return jsonify({key: s.value if s else None})
            else:
                return jsonify(ServerConfig.get_all())
        except ServerConfigError as e:
            raise APIAbort(HTTPStatus.INTERNAL_SERVER_ERROR, str(e)) from e

    def _put_key(self, params: ApiParams) -> Response:
        """
        Implement the PUT operation when a system configuration setting key is
        specified on the URI as /system/configuration/{key}.

        A single system config setting is set by naming the config key in the
        URI and specifying a value using either the "value" query parameter or
        a "value" key in a JSON request body.

        We'll complain about JSON request body parameters that are "shadowed"
        by the "value" query parameter and might represent client confusion.
        We won't complain about unnecessary JSON request body keys if we find
        the "value" in the request body as those would normally have been
        ignored by schema validation.

        Args:
            params: API parameters
            request: The original Request object containing query parameters

        Returns:
            HTTP Response object
        """

        try:
            key = params.uri["key"]
        except KeyError:
            # This "isn't possible" given the Flask mapping rules, but try
            # to report it gracefully instead of letting the KeyError fly.
            raise APIAbort(
                HTTPStatus.INTERNAL_SERVER_ERROR,
                f"Found URI parameters {sorted(params.uri)} not including 'key'",
            )

        # If we have a key in the URL, then we need a "value" for it, which
        # we can take either from a query parameter or from the JSON
        # request payload.
        value = params.query.get("value")
        if value:
            # If we got the value from the query parameter, complain about
            # any JSON request body keys
            if params.body:
                raise APIAbort(
                    HTTPStatus.BAD_REQUEST,
                    "Redundant parameters specified in the JSON request body: "
                    f"{sorted(params.body.keys())!r}",
                )
        else:
            value = params.body.get("value")
            if not value:
                raise APIAbort(
                    HTTPStatus.BAD_REQUEST,
                    f"No value found for key system configuration key {key!r}",
                )

        try:
            ServerConfig.set(key=key, value=value)
        except ServerConfigBadValue as e:
            raise APIAbort(HTTPStatus.BAD_REQUEST, str(e)) from e
        except ServerConfigError as e:
            raise APIAbort(HTTPStatus.INTERNAL_SERVER_ERROR, str(e)) from e
        return jsonify({key: value})

    def _put_body(self, params: ApiParams) -> Response:
        """
        Allow setting the value of multiple system configuration settings with
        a single PUT by specifying a JSON request body with key/value pairs.

        Args:
            params: API parameters
            request: The original Request object containing query parameters

        Returns:
            HTTP Response object
        """
        badkeys = []
        for k, v in params.body.items():
            if k not in ServerConfig.KEYS:
                badkeys.append(k)

        if badkeys:
            raise APIAbort(
                HTTPStatus.BAD_REQUEST,
                f"Unrecognized configuration parameters {sorted(badkeys)!r} specified: valid parameters are {sorted(ServerConfig.KEYS)!r}",
            )

        failures = []
        response = {}
        fail_status = HTTPStatus.BAD_REQUEST
        for k, v in params.body.items():
            try:
                c = ServerConfig.set(key=k, value=v)
                response[c.key] = c.value
            except ServerConfigBadValue as e:
                failures.append(str(e))
            except ServerConfigError as e:
                fail_status = HTTPStatus.INTERNAL_SERVER_ERROR
                self.logger.warning(str(e))
                failures.append(str(e))
        if failures:
            raise APIAbort(fail_status, message=", ".join(failures))
        return jsonify(response)

    def _put(self, params: ApiParams, _) -> Response:
        """
        Set or modify the values of server configuration keys.

        PUT /api/v1/server/configuration
        {
            "dataset-lifetime": 10,
            "server-state": "running"
        }

        PUT /api/v1/server/configuration/dataset-lifetime?value=10

        PUT /api/v1/server/configuration/dataset-lifetime
        {
            "value": "10"
        }

        Args:
            params: API parameters
            request: The original Request object containing query parameters

        Returns:
            HTTP Response object
        """

        if params.uri:
            return self._put_key(params)
        else:
            return self._put_body(params)


import os
import shutil
from tempfile import TemporaryDirectory

import pandas as pd
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

from bs4 import BeautifulSoup
from constants import (BACKOFF_FACTOR, BASE_URL, SEC_CIK_TXT_URL,
                       STATUS_FORCELIST, TICKER_CIK_CSV_FPATH, TOTAL_RETRIES)
from excel_parsing_utils import (clean_excel,
                                 download_years_in_ticker_folder_from_s3,
                                 filter_s3_urls_to_send,
                                 get_existing_merged_fpaths,
                                 get_existing_years,
                                 get_fpaths_from_local_ticker,
                                 merge_excel_files_across_years,
                                 parse_inputs, upload_files_to_s3)
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from sec_downloader import (SECDownloader, download,
                            update_ticker_cik_df, http_download)

app = FastAPI()

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

sec_downloader = SECDownloader()

@app.get("/")
def home():
    return {"message":"Health Check Passed!"}

@app.get("/list_sec_filing_10k/")
async def get_list_sec_tickers(ticker):

    cik = sec_downloader.get_ticker_cik(ticker)

    params = {"action": "getcompany", "owner": "exclude",
              "output": "html", "CIK": cik, "type": "10-K"}

    data = http_download(BASE_URL, params)

    soup = BeautifulSoup(data, features="lxml")
    tables = soup.find_all("td")

    tables_10k = [table.text for table in tables if table.text == "10-K"]
    if tables_10k:
        is_ticker_filing_10k = True
    else:
        is_ticker_filing_10k = False

    return {"is_ticker_filing_10k": is_ticker_filing_10k}

@app.get("/list_sec/")
async def get_list_sec_tickers():

    update_ticker_cik_df()
    df_tickers = pd.read_csv(TICKER_CIK_CSV_FPATH)

    list_tickers = list(df_tickers["ticker"].dropna().values)

    return {"tickers": list_tickers}

@app.get("/params/")
async def download_10k(ticker, years, _10k, Proxy, Balance, Income, Cash):

    with TemporaryDirectory() as dirpath:
        s3_urls_to_send_to_user, _ = get_s3_urls_to_send_to_user(
            ticker, years, _10k, Proxy, Balance, Income, Cash, dirpath)

        return {"s3_urls": s3_urls_to_send_to_user}

@app.get("/params_web/")
async def download_10k_web(ticker, years, _10k, Proxy, Balance, Income, Cash):

    with TemporaryDirectory() as dirpath:
        _, ticker_folder = get_s3_urls_to_send_to_user(
            ticker, years, _10k, Proxy, Balance, Income, Cash, dirpath)

        shutil.make_archive(ticker, "zip", ticker_folder)
        response = FileResponse(path=ticker + ".zip",
                                filename=ticker + ".zip")
        return response

def get_s3_urls_to_send_to_user(ticker, years, _10k, Proxy,
                                Balance, Income, Cash, dirpath):

    raw_files_to_send, merged_files_to_send, years = parse_inputs(
        _10k, Proxy, Balance, Income, Cash, years)

    cik = sec_downloader.get_ticker_cik(ticker)

    ticker_folder = os.path.join(dirpath, ticker)
    os.makedirs(ticker_folder)

    existing_s3_urls = download_years_in_ticker_folder_from_s3(
        ticker,  ticker_folder, years)
    created_fpath = create_missing_files(ticker, ticker_folder, cik, years)
    s3_urls = upload_files_to_s3(created_fpath, existing_s3_urls,
                                 ticker, ticker_folder)

    s3_urls_to_send_to_user = filter_s3_urls_to_send(
        s3_urls, raw_files_to_send, merged_files_to_send)

    return s3_urls_to_send_to_user, ticker_folder

def create_missing_files(ticker, ticker_folder, cik, years):

    existing_years = get_existing_years(ticker_folder)
    missing_years = [year for year in years if year not in existing_years]

    if missing_years:
        excel_fpaths_to_clean, created_years = download(
            ticker, cik, missing_years, ticker_folder)
        for excel_fpath in excel_fpaths_to_clean:
            clean_excel(excel_fpath)
    else:
        created_years = []

    local_years = existing_years + created_years

    existing_merged_fpaths = get_existing_merged_fpaths(
        ticker, ticker_folder, local_years)
    if len(existing_merged_fpaths) == 3:
        merged_fpaths = existing_merged_fpaths
    else:
        merged_fpaths = merge_excel_files_across_years(ticker, ticker_folder, local_years)

    raw_fpaths = get_fpaths_from_local_ticker(ticker_folder, local_years)
    created_fpath = raw_fpaths + merged_fpaths

    return created_fpath


import numpy as np
from routines.base_routine import BaseRoutine
from maneuvers.front_flip_maneuver import FrontFlip
from utils.physics_data_object import PDO
from utils.simple_drive import drive
from rlbot.utils.structures.game_data_struct import GameTickPacket
from rlbot.utils.structures.bot_input_struct import PlayerInput
import utils.car as car_module
import utils.game_data as game_data

class ATBA(BaseRoutine):
    def __init__(self, car: car_module.Car, gd: game_data.GameData) -> None:
        super().__init__(car, gd)

    def update(self) -> PlayerInput:
        if self.maneuver and not self.maneuver.finished:
            return self.maneuver.update()
        target = PDO(
            np.array(
                [
                    self.gd.packet.game_ball.physics.location.x,
                    self.gd.packet.game_ball.physics.location.y,
                    self.gd.packet.game_ball.physics.location.z,
                ]
            )
        )
        controls = drive(target, self.car)
        if not self.car.super_sonic and self.car.on_surface and abs(controls.steer) < 0.1:

            if self.car.boost_level > 0:
                controls.boost = True
            elif self.car.current_speed > 1000:
                self.maneuver = FrontFlip(self.car, self.gd)
        return controls


import discord
from discord.ext import commands
from decimal import *

from ..DB import db
from ..Class.embed_form import embed_factory as ef

class mock_trans(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    async def mock_buy(self, ctx, stock_name, stock_count):
        BUY_FEE = Decimal('0.001') # 0.5%

        user_id = ctx.author.id
        #입력 오류
        if stock_name is None:
            await ctx.send("거래할 주식을 입력해주세요.")
            return
        if not (stock_count.isdigit() or stock_count in ('최대', '풀', '올인','반') or stock_count[-1] in ('%', '퍼', '원')):
            await ctx.send("수량에 숫자를 입력해주세요.")
            return

        serch_stock = self.bot.get_cog('serch_stock')

        serch_result = await serch_stock.serch_stock_by_bot(ctx, stock_name)

        stock_code = serch_result.stock_code
        stock_name = serch_result.stock_name
        alert_info = serch_result.alert_info

        if stock_code is None:
            await ctx.send("올바르지 않는 주식명")
            return

        stock_price = db.KRXRealData().read_price(stock_code)
        stock_price_include_fee = stock_price * (1+BUY_FEE)

        if stock_price is None or alert_info == '매매정지':
            await ctx.send("거래 정지 종목입니다.")
            return

        # 계좌의 돈을 불러온다
        krw_account = db.AccountTable().read(user_id,"KRW")
        if krw_account is None:
            await ctx.send("지원금을 받아주세요.")
            return
        krw_money = int(krw_account[1])

        # stock_count 계산
        if stock_count.isdigit():
            stock_count = int(stock_count)
        elif stock_count in ('최대', '풀', '올인'):
            stock_count = int(krw_money/stock_price_include_fee)
        elif stock_count in ('반',):
            stock_count = int(krw_money/2/stock_price_include_fee)
        elif stock_count[-1] in ('%', '퍼', '원'):
            input_int = stock_count[:-1]
            if not input_int.isdigit():
                await ctx.send("수 입력 오류")
                return
            real_input_int = int(input_int)

            if stock_count[-1] in ('%', '퍼'):
                base_price = krw_money * real_input_int // 100
            elif stock_count[-1] == '원':
                base_price = real_input_int

            if base_price < stock_price:
                await ctx.send("돈 부족")
                return

            stock_count = int(base_price/stock_price_include_fee)

        total_stock_price = stock_price * stock_count
        total_stock_fee = int(total_stock_price * BUY_FEE)

        # 돈이 없으면 취소
        if krw_money < total_stock_price or stock_count == 0:
            await ctx.send("돈 없음")
            await ctx.send(f"최대 {int(krw_money/stock_price_include_fee)}주 가능")
            return

        # 돈이 있으면 계좌 돈 감소, 주식 갯수 증가
        trade_result = db.MockTransection().buy(user_id, stock_code, stock_count, total_stock_price, total_stock_fee)

        if trade_result:
            input_variable={"guild_id" : ctx.guild.id, "channel_id" : ctx.channel.id,
                            "author_id" : ctx.author.id, "stock_code" : stock_code,
                            "stock_value" : stock_price
                            }

            try:
                db.LogTable().insert_mock_log(mock_type="매수",stock_count=stock_count,**input_variable)
            except:
                print("로그 저장 에러")

            await ctx.send(embed=ef("mock_buy", ctx.author, stock_name, stock_count, stock_price, total_stock_price, total_stock_fee).get)
        else:
            await ctx.send('오류 : 거래실패')

    async def mock_sell(self, ctx, stock_name, stock_count):
        SELL_FEE = Decimal('0.001')

        user_id = ctx.author.id
        #입력 오류
        if stock_name is None:
            await ctx.send("거래할 주식을 입력해주세요.")
            return
        if not (stock_count.isdigit() or stock_count in ('최대', '풀', '올인', '반') or stock_count[-1] in ('%', '퍼', '원')):
            await ctx.send("수량에 숫자를 입력해주세요.")
            return

        serch_stock = self.bot.get_cog('serch_stock')
        serch_result = await serch_stock.serch_stock_by_bot(ctx, stock_name)

        stock_code = serch_result.stock_code
        stock_name = serch_result.stock_name
        alert_info = serch_result.alert_info

        if stock_code is None:
            await ctx.send("올바르지 않는 주식명")
            return

        stock_price = db.KRXRealData().read_price(stock_code)

        if stock_price is None or alert_info == '매매정지':
            await ctx.send("거래 정지 종목입니다.")
            return

        # 계좌에 주식이 있는지 확인
        stock_account = db.AccountTable().read(user_id, stock_code)
        if stock_account is None:
            await ctx.send("팔고자 하는 주식이 없습니다.")
            return

        balance = int(stock_account[0])

        # stock_count 계산
        if stock_count.isdigit():
            stock_count = int(stock_count)
        elif stock_count in ('최대', '풀', '올인'):
            stock_count = balance
        elif stock_count in ('반',):
            stock_count = balance//2
        elif stock_count[-1] in ('%', '퍼', '원'):
            input_int = stock_count[:-1]
            if not input_int.isdigit():
                await ctx.send("수 입력 오류")
                return
            real_input_int = int(input_int)

            if stock_count[-1] in ('%', '퍼'):
                stock_count = balance*real_input_int//100
            elif stock_count[-1] == '원':
                stock_count = real_input_int//stock_price

                if stock_count>balance:
                    await ctx.send("수량 부족")
                    return

        total_stock_price = stock_price * stock_count
        total_stock_fee = int(total_stock_price * SELL_FEE)

        sum_value = stock_account[1]
        sell_sum_value = sum_value*stock_count/balance
        profit = total_stock_price - sell_sum_value - total_stock_fee

        # 보유 주식이 팔려는 갯수보다 적으면 취소
        if balance < stock_count:
            await ctx.send("팔고자 하는 주식이 적습니다")
            await ctx.send(f"최대 {balance}주 가능")
            return

        # 갯수가 충분하면 주식 갯수 감소, 계좌 돈 증가
        trade_result = db.MockTransection().sell(user_id, stock_code, stock_count, total_stock_price, total_stock_fee)

        if trade_result:
            input_variable={"guild_id" : ctx.guild.id, "channel_id" : ctx.channel.id,
                            "author_id" : ctx.author.id, "stock_code" : stock_code,
                            "stock_value" : stock_price
                            }

            try:
                db.LogTable().insert_mock_log(mock_type="매도",stock_count=stock_count,**input_variable)
            except:
                print("로그 저장 에러")

            await ctx.send(embed=ef("mock_sell", ctx.author, stock_name, stock_count, stock_price, total_stock_price, total_stock_fee, profit).get)
        else:
            await ctx.send('오류 : 거래실패, 거래가 취소되었습니다.')

    async def mock_sell_all(self, ctx):
        serch_stock = self.bot.get_cog('serch_stock')
        warn_result = await serch_stock.warn_send(ctx, '전량매도')

        if warn_result:
            SELL_FEE = Decimal('0.001')
            user_id = ctx.author.id

            stock_account = db.AccountTable().read_only_tradealbe_stock(self, user_id)

            if stock_account is None:
                await ctx.send("팔고자 하는 주식이 없습니다.")
                return

            trade_list = ['주식명 0주 : 판매금액(이익금)']

            for idx in stock_account.index:
                stock_name = stock_account.iat[idx, 3]
                stock_code = stock_account.iat[idx, 0]
                stock_count = int(stock_account.iat[idx, 1])
                all_buy_price = stock_account.iat[idx, 2]
                all_present_price = stock_account.iat[idx, 4]
                total_stock_fee = int(all_present_price * SELL_FEE)

                profit = all_present_price - all_buy_price - total_stock_fee

                trade_result = db.MockTransection().sell(user_id, stock_code, stock_count, all_present_price, total_stock_fee)

                if trade_result:
                    trade_list.append(f'{stock_name} {stock_count}주 : {all_present_price}({int(profit)})')
                else:
                    trade_list.append(f'{stock_name} {stock_count}주 : 거래실패')

            await ctx.send(embed=ef("mock_sell_all", ctx.author, trade_list).get)

def setup(bot):
    bot.add_cog(mock_trans(bot))


from stellar_sdk import TransactionEnvelope, Server, Keypair

def submit_quest_transaction(transaction: TransactionEnvelope, keypair: Keypair, server: Server) -> dict:
    """Submit a transaction to the Stellar network.

    Args:
        transaction: The transaction envelope to submit to the network.
        keypair: The keypair which should be used to sign the transaction.
        server: The server connection to be used.

    Returns:
        The response from the supplied Horizon server.
    """
    transaction.sign(keypair)
    print(f"Transaction XDR:\n{transaction.to_xdr()}\n")
    response = server.submit_transaction(transaction)
    print(f"Server Response:\n{response}")
    return response


import csv
import matplotlib.pyplot as plt
import glob
from glob import glob
import numpy as np

def chunkItAvg(seq, num):
    avg = len(seq) / float(num)
    out = []
    last = 0.0

    while last < len(seq):
        out.append(sum(seq[int(last):int(last + avg)])/len(seq[int(last):int(last + avg)]))
        last += avg

    return out
def chunkIt(seq, num):
    avg = len(seq) / float(num)
    out = []
    last = 0.0

    while last < len(seq):
        out.append(seq[int(last):int(last + avg)])
        last += avg

    return out

files = glob("outputs/*.csv")
print(files)
for f in files:
    X = []
    y = []
    with open(f, 'r') as csvf:
        reader = csv.reader(csvf,delimiter=',')
        for row in reader:
            X.append(int(row[0]))
            y.append(int(row[2]))
    x_avg = chunkIt(X,1000)
    y_avg = chunkItAvg(y,1000)
    plt.plot(X,y)
plt.xlabel('Number of Actions')
plt.ylabel('Average Score')
plt.title('Figure 1')
plt.legend(['Run 0', 'Run 1', 'Run 2', 'Run 3', 'Run 4','Run 5'],loc="best")
plt.show()


import logging
import numpy as np
import matplotlib.pyplot as plt
from sktensor import dtensor, cp_als

# Set logging to DEBUG to see CP-ALS information
logging.basicConfig(level=logging.DEBUG)

# Load Matlab data and convert it to dense tensor format
# mat = loadmat('/Users/monty/Julia/dNTF.py/brod.mat')

X = np.zeros((2, 10, 5))
X[:,0:2,0]=1
X[:,2:4,1]=1
X[:,4:6,2]=1
X[:,6:8,3]=1
X[:,8:10,4]=1

T = dtensor(X)

# Decompose tensor using CP-ALS
P, fit, itr, exectimes = cp_als(T, 5)

T_est = np.einsum('az,bz,cz->abc', P.U[0], P.U[1], P.U[2])

plt.imshow(T_est[:,:,0]);
plt.colorbar()
plt.show()


import pygame
import time

# Initialisierung von Pygame
pygame.init()

# Bildschirmgröße (nur die Breite wird benötigt)
screen_width = 200
screen_height = 30  # Höhe anpassen

# Erstelle das Overlay-Fenster mit transparentem Hintergrund
screen = pygame.display.set_mode((screen_width, screen_height), pygame.NOFRAME)  # Ohne Transparenz
pygame.display.set_caption("Overlay")

# Schriftart initialisieren
font = pygame.font.Font(None, 36)

def main():
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        # Aktuelle Zeit abrufen
        current_time = time.localtime()
        current_hour = current_time.tm_hour
        current_minute = current_time.tm_min
        current_second = current_time.tm_sec

        # Berechne die verbleibende Zeit bis zur nächsten viertel Stunde (15 oder 45)
        if current_minute < 15:
            target_minute = 15
        elif current_minute < 45:
            target_minute = 45
        else:
            target_minute = 15  # Nächste Stunde, nächstes Ziel ist 15

        remaining_minutes = (target_minute - current_minute) % 60
        remaining_seconds = 60 - current_second

        # Anzeige erstellen (Surface mit Transparenz)
        overlay_surface = pygame.Surface((screen_width, screen_height), pygame.SRCALPHA)

        # Zeige die aktuelle Uhrzeit und die verbleibende Restzeit an
        time_text = f"{current_hour:02d}:{current_minute:02d}:{current_second:02d}"
        rest_time_text = f"Restzeit: {remaining_minutes:02d}:{remaining_seconds:02d}"
        combined_text = f"{time_text} {rest_time_text}"

        text_render = font.render(combined_text, True, (255, 255, 255))
        overlay_surface.blit(text_render, (10, 0))

        # Setze die Transparenz des Overlays
        overlay_surface.set_alpha(200)  # Ein Wert von 0 bis 255 (0 = transparent, 255 = voll sichtbar)

        # Overlay auf den Bildschirm blitten
        screen.blit(overlay_surface, (0, 0))

        pygame.display.update()

        # Warte einen Moment, bevor die Schleife erneut durchlaufen wird
        pygame.time.wait(1000)

    pygame.quit()

if __name__ == "__main__":
    main()


import unittest

from policyuniverse import logger
from policyuniverse.arn import ARN

class ARNTestCase(unittest.TestCase):
    def test_from_arn(self):
        proper_arns = [
            "events.amazonaws.com",
            "cloudtrail.amazonaws.com",
            "arn:aws:iam::012345678910:root",
            "arn:aws:iam::012345678910:role/SomeTestRoleForTesting",
            "arn:aws:iam::012345678910:instance-profile/SomeTestInstanceProfileForTesting",
            "arn:aws:iam::012345678910:role/*",
            "arn:aws:iam::012345678910:role/SomeTestRole*",
            "arn:aws:s3:::some-s3-bucket",
            "arn:aws:s3:*:*:some-s3-bucket",
            "arn:aws:s3:::some-s3-bucket/some/path/within/the/bucket"
            "arn:aws:s3:::some-s3-bucket/*",
            "arn:aws:ec2:us-west-2:012345678910:instance/*",
            "arn:aws:ec2:ap-northeast-1:012345678910:security-group/*",
            "arn:aws-cn:ec2:ap-northeast-1:012345678910:security-group/*",
            "arn:aws-us-gov:ec2:gov-west-1:012345678910:instance/*",
            "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity EXXXXXXXXXXXXX",
            "arn:aws:iam::aws:policy/AlexaForBusinessDeviceSetup",
        ]

        # Proper ARN Tests:
        for arn in proper_arns:
            logger.info("Testing Proper ARN: {}".format(arn))
            arn_obj = ARN(arn)

            self.assertFalse(arn_obj.error)
            if "root" in arn:
                self.assertTrue(arn_obj.root)
            else:
                self.assertFalse(arn_obj.root)

            if ".amazonaws.com" in arn:
                self.assertTrue(arn_obj.service)
            else:
                self.assertFalse(arn_obj.service)

        bad_arns = [
            "arn:aws:iam::012345678910",
            "arn:aws:iam::012345678910:",
            "*",
            "arn:s3::::",
            "arn:arn:arn:arn:arn:arn",
        ]

        # Improper ARN Tests:
        for arn in bad_arns:
            logger.info("Testing IMPROPER ARN: {}".format(arn))
            arn_obj = ARN(arn)

            self.assertTrue(arn_obj.error)

    def test_from_account_number(self):
        proper_account_numbers = ["012345678912", "123456789101", "123456789101"]

        improper_account_numbers = [
            "*",
            "O12345678912",  # 'O' instead of '0'
            "asdfqwer",
            "123456",
            "89789456314356132168978945",
            "568947897*",
        ]

        # Proper account number tests:
        for accnt in proper_account_numbers:
            logger.info("Testing Proper Account Number: {}".format(accnt))
            arn_obj = ARN(accnt)

            self.assertFalse(arn_obj.error)

        # Improper account number tests:
        for accnt in improper_account_numbers:
            logger.info("Testing IMPROPER Account Number: {}".format(accnt))
            arn_obj = ARN(accnt)

            self.assertTrue(arn_obj.error)


#!/usr/bin/python
import json, re, sys, csv
from time import time
import spacy
import en_core_web_sm
# Spacy model setup (NOTE - change to lg to include vectors)
nlp = en_core_web_sm.load()

with open('train_data.json', 'r') as train_data:
    data = json.load(train_data)

##################################################################
def getLemmatizer():
    from spacy.lemmatizer import Lemmatizer
    from spacy.lang.en import LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES
    lemmatizer = Lemmatizer(LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES)
    return lemmatizer

def getTokens(doc):
    tokens = []
    for tok in doc:
        if not tok.is_stop:
            tokens.append({ 'word':tok.lemma_, 'pos':tok.pos_ })
    return tokens

def getEntities(doc):
    ents = {}
    for ent in doc.ents:
        if not ent.text.isspace():
            ents[ent.text] = ent.label_
    return ents

def clean(text):
    # spacing out special characters in preparation for abbreviations
    clean = re.sub('[\*\#\@]', ' ', text).lower().strip().lstrip()
    clean = re.sub(r'([\;\,\.\%\"\-\(\)\:\$\!\?])', r' \1', clean)
    # putting special characters back in place
    clean = re.sub(r' ([\;\,\.\%\"\-\(\)\:\$\!\?])', r'\1', clean)
    clean = re.sub(r'(\w+)/(\w+)', r'\1 \2', clean).capitalize()
    clean = re.sub('[\*\;\&\#\,\$\@\.\%\"\'\-\(\)\:\$\!\?\+\[\]\s+]',' ', clean)
    return clean

def preprocessing(data):
    for tweet in data:
        tweet['clean'] = clean(tweet['text'])
        doc = nlp(tweet['text'])
        tweet['entities'] = getEntities(doc) #marks target entity
        tweet['tokens'] = getTokens(doc)   #adds POS, removes stopwords, and lemmatizes
    return data
##################################################################

processedComments = preprocessing(data)

# writes new parameters into input file
with open("spacy_output.json", 'w') as outfile:
    json.dump(processedComments, outfile, sort_keys=True, indent=2, separators=(',', ': '))


# Demonstrates using a multiple inputs with a single test function.
import math
import pytest

# Note how it is possible to combine groupings with parametrize.
@pytest.mark.math
@pytest.mark.parametrize('i, o', [(25, 30), (9, 3)])
def test_param_sqrt(input, i, o):
    n = i
    assert math.sqrt(n) + input == o

@pytest.mark.others
@pytest.mark.parametrize('i, o', [(25, 49), (7, 49)])
def test_param_square(i, o):
    n = i
    assert pow(n, 2) == o


##########################################################################
####			Meniscus processing tool
####			Made by Ruslan Baynazarov in 2017
####			hocop@yandex.ru, vk.com/ruslanbain
##########################################################################

import numpy as np
import cv2
from math import *
import time
from os import listdir
from os.path import isfile, join
from appJar import gui

path = 'input/'

onlyfiles = [f for f in listdir(path) if isfile(join(path, f))]
onlyfiles.sort()

# get info
f0 = onlyfiles[0]
time0 = int(f0[6:8])*3600 + int(f0[8:10])*60 + int(f0[10:12])
img = cv2.imread(path+f0)
imgHeight, imgWidth, c = img.shape

# init arrays
times = []
heights = []

# apriori values
top = 0
bottom = imgHeight
left = 0
right = imgWidth
maxBlack = 50
rot = 0

def process(f):
	# get time from filename
	time = 0
	try:
		time = int(f[6:8])*3600 + int(f[8:10])*60 + int(f[10:12]) - time0
	except:
		global curFileNum
		time = curFileNum

	# read image
	img = cv2.imread(path+f)
	img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

	# rotate
	rows,cols = img.shape
	ROTM = cv2.getRotationMatrix2D((cols/2,rows/2),rot,1)
	img = cv2.warpAffine(img,ROTM,(cols,rows))

	# remove not interesting domains
	img[:top,:] = maxBlack + 1 + img[:top,:] * 0
	img[bottom:,:] = maxBlack + 1 + img[bottom:,:] * 0
	img[:,:left] = maxBlack + 1 + img[:,:left] * 0
	img[:,right:] = maxBlack + 1 + img[:,right:] * 0

	# make mask
	mask = cv2.inRange(img, 0, maxBlack)
	mask = cv2.erode(mask,None,iterations=4)
	mask = cv2.dilate(mask,None,iterations=8)
	mask = cv2.erode(mask,None,iterations=4)

	# find contours
	v2,cont,h=cv2.findContours(mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

	# extract coordinate
	height = -1
	if len(cont) == 1:
		M = cv2.moments(cont[0])
		height = M['m10'] / M['m00']

	# draw
	img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
		# green if ok, else red
	cv2.drawContours(img, cont, -1, (0,255,0)if len(cont)==1 else (0,0,255), 2)
	return img, time, height

# variables
curFileNum = 0
t, h = time0, -1

# button functions
def compAndShowLast():
	global t
	global h
	global curFileNum
	global top
	global bottom
	global left
	global right
	global maxBlack
	global rot
	top = app.getScale('Top')
	bottom = app.getScale('Bottom')
	left = app.getScale('Left')
	right = app.getScale('Right')
	maxBlack = app.getScale('Thresh')
	rot = app.getScale('Rot')

	img, t, h = process(onlyfiles[curFileNum])

	cv2.imshow('image', img)
	cv2.waitKey(30)

def press(button):
	global t
	global h
	global curFileNum
	global outfile
	if button == 'Submit':
		if h > 0:
			outfile.write('%f\t%f\n' % (t, h))
		else:
			outfile.write('%f\tnan\n' % t)
		curFileNum += 1
		if curFileNum == len(onlyfiles):
			exit()
	if button == 'Submit all':
		while True:
			press('Submit')
	if button == 'Skip':
		curFileNum += 1
	compAndShowLast()

# create window
app = gui('Meniscus processing', '400x400')

app.addLabel('title1','Set brightness threshold:')
app.addLabelScale("Thresh")
app.setScaleRange('Thresh', 0, 254, curr=None)
app.setScale('Thresh', maxBlack, callFunction=True)
app.setScaleChangeFunction('Thresh', press)
app.showScaleValue('Thresh',show=True)

app.addLabel('title2','Set rotation:')
app.addLabelScale("Rot")
app.setScaleRange('Rot', -90, 90, curr=None)
app.setScale('Rot', rot, callFunction=True)
app.setScaleChangeFunction('Rot', press)
app.showScaleValue('Rot',show=True)

app.addLabel('title3','Set margins:')

app.addLabelScale("Top")
app.setScaleRange('Top', 0, imgHeight, curr=None)
app.setScale('Top', top, callFunction=True)
app.setScaleChangeFunction('Top', press)

app.addLabelScale("Bottom")
app.setScaleRange('Bottom', 0, imgHeight, curr=None)
app.setScale('Bottom', bottom, callFunction=True)
app.setScaleChangeFunction('Bottom', press)

app.addLabelScale("Left")
app.setScaleRange('Left', 0, imgWidth, curr=None)
app.setScale('Left', left, callFunction=True)
app.setScaleChangeFunction('Left', press)

app.addLabelScale("Right")
app.setScaleRange('Right', 0, imgWidth, curr=None)
app.setScale('Right', right, callFunction=True)
app.setScaleChangeFunction('Right', press)

app.addButtons(['Skip','Submit','Submit all'], press)

# run
compAndShowLast()
outfile = open('output.txt','w')
outfile.write('time(sec)\theight(pixel)\n')
app.go()


import pandas as pd
import numpy as np
from sklearn import preprocessing

import time
import matplotlib.pyplot as plt
from numpy import newaxis

def load_data(data_path,P,step):
    num_logs = P+step
    df = pd.read_csv(data_path)

    data_np = np.zeros((len(df),num_logs))
    data_df_combined = pd.DataFrame(data_np)
    data_df_combined.loc[:,0] = df['Henry Hub Natural Gas Spot Price Dollars per Million Btu'].data

    for i in range(1, num_logs):
        data_df_combined.loc[:,i] = data_df_combined.shift(-i)

    data_df_combined_clean = data_df_combined.dropna()
    data_df_combined_clean = data_df_combined_clean.reset_index()
    data_df_combined_clean.drop('index',axis=1,inplace=True)
    data_combined_standardized = preprocessing.scale(data_df_combined_clean)

    train_split = round(0.8 * data_combined_standardized.shape[0])
    val_split = round(0.9 * data_combined_standardized.shape[0])
    print("all len",data_combined_standardized.shape[0])
    print("train_split",train_split)

    X = data_combined_standardized[:,:P]
    Y = data_combined_standardized[:,P:]

    X_train = X[:train_split]
    Y_train = Y[:train_split]
    X_test = X[train_split:]
    Y_test = Y[train_split:]

    X_train = X_train.reshape((X_train.shape[0],X_train.shape[1],1))
    Y_train = Y_train.reshape((Y_train.shape[0],Y_train.shape[1],1))
    X_test = X_test.reshape((X_test.shape[0],X_test.shape[1],1))
    Y_test = Y_test.reshape((Y_test.shape[0],Y_test.shape[1],1))

    return X_train,Y_train,X_test,Y_test,data_df_combined_clean


from collections import UserList
from typing import List

from .event import Event, EventKind

class Filter:
    """
    NIP-01 filtering.

    Explicitly supports "#e" and "#p" tag filters via `event_refs` and `pubkey_refs`.

    Arbitrary NIP-12 single-letter tag filters are also supported via `add_arbitrary_tag`.
    If a particular single-letter tag gains prominence, explicit support should be
    added. For example:
        # arbitrary tag
        filter.add_arbitrary_tag('t', [hashtags])

        # promoted to explicit support
        Filter(hashtag_refs=[hashtags])
    """

    def __init__(
        self,
        event_ids: List[str] = None,
        kinds: List[EventKind] = None,
        authors: List[str] = None,
        since: int = None,
        until: int = None,
        event_refs: List[
            str
        ] = None,  # the "#e" attr; list of event ids referenced in an "e" tag
        pubkey_refs: List[
            str
        ] = None,  # The "#p" attr; list of pubkeys referenced in a "p" tag
        limit: int = None,
    ) -> None:
        self.event_ids = event_ids
        self.kinds = kinds
        self.authors = authors
        self.since = since
        self.until = until
        self.event_refs = event_refs
        self.pubkey_refs = pubkey_refs
        self.limit = limit

        self.tags = {}
        if self.event_refs:
            self.add_arbitrary_tag("e", self.event_refs)
        if self.pubkey_refs:
            self.add_arbitrary_tag("p", self.pubkey_refs)

    def add_arbitrary_tag(self, tag: str, values: list):
        """
        Filter on any arbitrary tag with explicit handling for NIP-01 and NIP-12
        single-letter tags.
        """
        # NIP-01 'e' and 'p' tags and any NIP-12 single-letter tags must be prefixed with "#"
        tag_key = tag if len(tag) > 1 else f"#{tag}"
        self.tags[tag_key] = values

    def matches(self, event: Event) -> bool:
        if self.event_ids is not None and event.id not in self.event_ids:
            return False
        if self.kinds is not None and event.kind not in self.kinds:
            return False
        if self.authors is not None and event.public_key not in self.authors:
            return False
        if self.since is not None and event.created_at < self.since:
            return False
        if self.until is not None and event.created_at > self.until:
            return False
        if (self.event_refs is not None or self.pubkey_refs is not None) and len(
            event.tags
        ) == 0:
            return False

        if self.tags:
            e_tag_identifiers = set([e_tag[0] for e_tag in event.tags])
            for f_tag, f_tag_values in self.tags.items():
                # Omit any NIP-01 or NIP-12 "#" chars on single-letter tags
                f_tag = f_tag.replace("#", "")

                if f_tag not in e_tag_identifiers:
                    # Event is missing a tag type that we're looking for
                    return False

                # Multiple values within f_tag_values are treated as OR search; an Event
                # needs to match only one.
                # Note: an Event could have multiple entries of the same tag type
                # (e.g. a reply to multiple people) so we have to check all of them.
                match_found = False
                for e_tag in event.tags:
                    if e_tag[0] == f_tag and e_tag[1] in f_tag_values:
                        match_found = True
                        break
                if not match_found:
                    return False

        return True

    def to_json_object(self) -> dict:
        res = {}
        if self.event_ids is not None:
            res["ids"] = self.event_ids
        if self.kinds is not None:
            res["kinds"] = self.kinds
        if self.authors is not None:
            res["authors"] = self.authors
        if self.since is not None:
            res["since"] = self.since
        if self.until is not None:
            res["until"] = self.until
        if self.limit is not None:
            res["limit"] = self.limit
        if self.tags:
            res.update(self.tags)

        return res

class Filters(UserList):
    def __init__(self, initlist: "list[Filter]" = []) -> None:
        super().__init__(initlist)
        self.data: "list[Filter]"

    def match(self, event: Event):
        for filter in self.data:
            if filter.matches(event):
                return True
        return False

    def to_json_array(self) -> list:
        return [filter.to_json_object() for filter in self.data]