import asyncio
import datetime
import json
import logging
import operator
import time
import re
import socket

import websockets
from unidecode import unidecode

from herobrain import networking
from herobrain.analysis import QuestionAnalyser

class GameHandler:
    MORE_LOGS = False

    def __init__(self, socket_addr, headers, interface):
        self._log = logging.getLogger(GameHandler.__name__)
        self._log.info("Initialising on %s" % socket_addr)

        self._socket_addr = socket_addr
        self._socket_headers = headers

        self._interface = interface
        self._event_loop = asyncio.get_event_loop()

    async def _on_new_round(self, question, choices, number, num_questions):
        start_time = time.time()
        self._interface.report_question(question, choices, number, num_questions)

        analyser = QuestionAnalyser(question, choices)
        self._interface.report_analysis(analyser.get_analysis(), number)

        # Find the probability of answers
        answers, analysis = await analyser.find_answers()
        speed = round(time.time() - start_time, 2)

        self._interface.report_prediction(number, answers, speed, analysis)

    async def _on_round_complete(self, answer_counts, correct_answer, eliminated, advancing):
        self._interface.report_round_end(answer_counts, correct_answer, eliminated, advancing)

    async def _handle_event(self, message):
        # New question
        if message["type"] == "question":
            # decode the question
            question_str = unidecode(message["question"])
            choices = [unidecode(ans["text"]) for ans in message["answers"]]

            question_num = message['questionNumber']
            num_questions = message['questionCount']

            await self._on_new_round(question_str, choices, question_num, num_questions)

        # Round is over
        elif message["type"] == "questionSummary":
            answer_counts ={}
            correct = ""
            for answer in message["answerCounts"]:
                ans_str = unidecode(answer["answer"])
                answer_counts[ans_str] = answer["count"]
                if answer["correct"]:
                    correct = ans_str

            advancing = message['advancingPlayersCount']
            eliminated = message['eliminatedPlayersCount']

            await self._on_round_complete(answer_counts, correct, eliminated, advancing)

        elif message["type"] == "interaction":
            pass

    def _is_ending_message(self, message):
        return message["type"] == "broadcastEnded" and "reason" not in message

    async def _keep_open(self, socket):
        self._log.debug("Keeping socket open, pinging every 5 seconds")
        while True:
            try:
                await socket.ping()
            except (websockets.ConnectionClosed, KeyboardInterrupt):
                break
            await asyncio.sleep(5)
        self._log.debug("Ping loop ended")

    async def _game_connection(self):
        self._log.debug("Starting game connection")
        async with websockets.connect(self._socket_addr, extra_headers=self._socket_headers) as socket:
            asyncio.ensure_future(self._keep_open(socket))

            async for msg in socket:
                # We received a new message, remove any weird characters and
                message_data = json.loads(re.sub(r"[\x00-\x1f\x7f-\x9f]", "", msg))

                if GameHandler.MORE_LOGS:
                    self._log.debug(str(message_data))

                # Ah. Not good
                if "error" in message_data and message_data["error"] == "Auth not valid":
                    self._log.debug(message_data)
                    raise RuntimeError("Bad token")

                yield message_data

    async def play(self):
        try:
            while True:
                # Stay in this loop until
                # we get a connection closed error
                async for message in self._game_connection():
                    if self._is_ending_message(message):
                        self._log.info(f"Game ending: {message}")
                        return
                    # Don't stop receiving messages while we wait for the question to be answered
                    # perform the analysis in another coroutine
                    asyncio.ensure_future(self._handle_event(message))

        except (websockets.ConnectionClosed, ConnectionResetError):
            self._log.warning("%s closed unexpectedly" % self._socket_addr)
        except (ConnectionRefusedError, socket.gaierror) as e:
            self._log.error("Could not connect to %s: %s" % (self._socket_addr, e))


from django.shortcuts import render
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from address.models import Address
from shop.models import Product
from cart.views import _cart_id
from cart.models import CartItem, Cart
from .models import Order, OrderItem

# @login_required()
def order_create(request):
    cart = Cart.objects.get(cart_id=_cart_id(request))
    cart_items = CartItem.objects.filter(cart=cart)
    address = Address.objects.get(
        customer=request.user, address_type='billing')
    customer = request.user
    billing_address1 = address.billing_address1
    billing_address2 = address.billing_address2
    phone = address.phone
    country = address.country
    state = address.state
    city = address.city
    post_code = address.post_code

    try:
        order = Order.objects.create(billing_address1=billing_address1, customer=customer, billing_address2=billing_address2,
                                     phone=phone, country=country, state=state, city=city, post_code=post_code)
        order.save()
# CHECK IF THERE IS A COUPON
# CHANGE .save(commit=Fale)
# THEN SAVE WITH COUPON
        for order_item in cart_items:
            oi = OrderItem.objects.create(
                product=order_item.product,
                price=order_item.product.price,
                quantity=order_item.quantity,
                order=order
            )
            oi.save()

            products = Product.objects.get(id=order_item.product.id)
            products.stock = int(
                order_item.product.stock - order_item.quantity)
            products.save()
            order_item.delete()
        request.session['order_id'] = order.id
    except ObjectDoesNotExist:
        pass

    return render(request, 'orders/create.html', {'cart': cart, 'order_item': order_item, 'customer': customer})


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov  8 10:57:33 2019

@author: gary
    """
import argparse
import torch
from torch.utils.data import DataLoader
import os
import random
import datetime
import csv

from libs.config_defaults import _C as cfg
from libs.data.dataset_builder import dataset_factory
from libs.train import train, evaluate, test
from libs.logger import trainingLogger
from libs.model_utils import check_model,build_model, checkpoint

def get_unique_name(cfg):

    #Build save details from config
    separator = '-'
    model_name = separator.join(cfg.MODEL.components)

    if len(cfg.DATASET.train) == 1:
        unique_name = cfg.DATASET.train[0] + "-" + cfg.NAME
    else:
        seperator = '_'
        unique_name = seperator.join(cfg.DATASET.train) + "-" + cfg.NAME

    cfg.DIR.logs =  os.path.join(cfg.DIR.parent, cfg.DIR.logs, "-".join([model_name,unique_name]))

    cfg.DIR.output =  os.path.join(cfg.DIR.parent, cfg.DIR.output, model_name, unique_name)
    cfg.DIR.ckpts =  os.path.join(cfg.DIR.output,cfg.DIR.ckpts)
    cfg.DIR.val_metrics =  os.path.join(cfg.DIR.parent, cfg.DIR.output,cfg.DIR.val_metrics)
    cfg.DIR.vis =  os.path.join(cfg.DIR.output,cfg.DIR.vis)
    return cfg

####################################################################################################################
# Main Code
####################################################################################################################

parser = argparse.ArgumentParser(description="PyTorch Semantic Segmentation Training")
parser.add_argument(
    "--cfg",
    default="test_seg.yaml",
    metavar="FILE",
    help="path to config file",
    type=str,
)
parser.add_argument(

    "opts",
    help="Modify config options using the command-line",
    default=None,
    nargs=argparse.REMAINDER,
)

args = parser.parse_args()
args.cfg = os.path.join("data","config", args.cfg)

#Load Config from file and extra command line
cfg.merge_from_file(args.cfg) #From yacs
cfg.merge_from_list(args.opts)

#Set parameters dependant upon mode
if cfg.MODE.upper() == "TRAIN":
    cfg.PARAMS = cfg.TRAIN
elif cfg.MODE.upper() == "EVAL":
    cfg.PARAMS = cfg.VAL
elif cfg.MODE.upper() == "TEST":
    cfg.PARAMS = cfg.TEST

cfg = get_unique_name(cfg)

# Output directory for experimnet
if not os.path.isdir(cfg.DIR.output):
   os.makedirs(cfg.DIR.output)
with open(os.path.join(cfg.DIR.output, 'config.yaml'), 'w') as f:
    f.write("{}".format(cfg))
if not os.path.isdir(cfg.DIR.ckpts):
   os.makedirs(cfg.DIR.ckpts)

#In cases classes are ignored
if cfg.TRAIN.criterion_ignore_index != -100:
    cfg.DATASET.shift_class_labels = abs(cfg.TRAIN.criterion_ignore_index)
else:
    cfg.DATASET.shift_class_labels = 0

cfg = check_model(cfg)

if cfg.MODE.upper() == "TRAIN":

    dataset, collator = dataset_factory(cfg.DATASET.train,cfg.MODE.upper(),cfg.DIR.datasets,cfg.DATASET,trainvis=True)
    dataloader_train = DataLoader(dataset["TRAIN"], batch_size=cfg.TRAIN.batch_size_per_gpu, shuffle=True, num_workers=0, collate_fn=collator["TRAIN"])
    dataloader_vis = DataLoader(dataset["TRAINVIS"], batch_size=1, shuffle=False, num_workers=0, collate_fn=collator["TRAINVIS"])
    cfg.DATASET.num_class = dataset["TRAIN"].class_num

    random.seed(cfg.TRAIN.seed)
    torch.manual_seed(cfg.TRAIN.seed)
    #Setup logging
    history = {'train': {'epoch': [], 'loss': [], 'acc': []}}

    #time_stamp = datetime.datetime.now()
    #time_stamp = time_stamp.strftime("%m_%d_%y_%H_%M_%S")
    #log_folder = os.getcwd() +"/logs/"+ dataset_name + "_" + time_stamp
    logger = trainingLogger(dataset["TRAIN"].name,logs_dir=cfg.DIR.logs, img_dir=cfg.DIR.vis)
    model, optimizers, nets = build_model(cfg)

    cfg.TRAIN.max_iters = cfg.TRAIN.epoch_iters * cfg.TRAIN.num_epoch
    cfg.TRAIN.running_lr = [None] * len(optimizers)
    for i in range(len(optimizers)):
        cfg.TRAIN.running_lr[i] = cfg.TRAIN.lr[i]

    for epoch in range(cfg.TRAIN.checkpoint, cfg.TRAIN.num_epoch):
        train(model, dataloader_train, optimizers, logger, epoch+1, cfg, vis_data=dataloader_vis)
        # checkpointing
        checkpoint(nets, history, cfg, epoch+1)

if cfg.MODE.upper() == "EVAL":
    for ds in cfg.DATASET.val:
        dataset, collator = dataset_factory(ds,cfg.MODE.upper(),cfg.DIR.datasets,cfg.DATASET)
        dataloader = DataLoader(dataset["VAL"], batch_size=1, shuffle=False, num_workers=0, collate_fn=collator["VAL"])
        cfg.DATASET.num_class = dataset["VAL"].class_num
        logger = trainingLogger(dataset["VAL"].name,logs_dir=cfg.DIR.logs, img_dir=cfg.DIR.vis)
        model, optimizers, nets = build_model(cfg)
        results = evaluate(model, dataloader, logger, cfg)

        RESULTS2 = results["IOU"].tolist()

        with open('testres.csv','w', newline='') as result_file:
            wr = csv.writer(result_file, dialect='excel')
            wr.writerows(RESULTS2)

if cfg.MODE.upper() == "TEST":
    for ds in cfg.DATASET.test:
        dataset, collator = dataset_factory(ds,cfg.MODE.upper(),cfg.DIR.datasets,cfg.DATASET)
        dataloader = DataLoader(dataset["TEST"], batch_size=1, shuffle=False, num_workers=0, collate_fn=collator["TEST"])
        cfg.DATASET.num_class = dataset["TEST"].class_num
        logger = trainingLogger(dataset["TEST"].name,logs_dir=cfg.DIR.logs, img_dir=cfg.DIR.vis)
        model, optimizers, nets = build_model(cfg)
        test(model, dataloader, logger, cfg)


import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import*
import random
from pygame import mixer

pygame.init()
textfont = pygame.font.SysFont("monospace",50)
class display:

    def __init__(self, width, height, window):
        self.width = width
        self.height = height
        self.window = window

    def update(self):
        pygame.display.flip()
        pygame.time.wait(10)

    def clear(self):
        glClearColor(0,0,0.1,1)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

screen = display(800, 400, pygame.display.set_mode((800, 400), DOUBLEBUF|OPENGL))
pygame.display.set_caption('Space Shooter 1v1')

#BGMUSIC########

index = 0
rages = True
bgmusiclist = ['bgmusic.mp3','low.mp3']
pygame.mixer.music.load(bgmusiclist[index])
mixer.music.play(-100)

bullet2_sound = mixer.Sound('blaster2.mp3')###
collide_sound = mixer.Sound('coolide.mp3')###
player_hitsound = mixer.Sound('playerhit.mp3')####
player_hitsound.set_volume(0.5)
bullet1_sound = mixer.Sound('blaster1.mp3')###
alarm = mixer.Sound('alarm.mp3')#####
end = mixer.Sound('end.mp3')#####

#BGMUSIC########

def rage_true():
        global index
        index = 1
        pygame.mixer.music.load(bgmusiclist[index])
        pygame.mixer.music.play(-100)
def rage_false():
        global index
        index = 0
        pygame.mixer.music.load(bgmusiclist[index])
        pygame.mixer.music.play(-100)

class player_one:
    def __init__(self, vertices, edges):
        self.vertices = vertices
        self.edges = edges
        self.pos = [-13,0,0]
        self.int = 0.02

    def move(self):
        self.k_press = pygame.key.get_pressed()
        if self.k_press[pygame.K_w]:
            if self.pos[1] < 6:
                self.pos[1] += self.int

        if self.k_press[pygame.K_s]:
            if self.pos[1] > -6:
                self.pos[1] -= self.int

        #if self.k_press[pygame.K_d]:
            #if self.pos[0] < -1.2:
          #      self.pos[0] += self.int

     #   if self.k_press[pygame.K_a]:
      #      if self.pos[0] > -13.8:
         #       self.pos[0] -= self.int

    def draw(self):
        glPushMatrix()
        glTranslatef(*self.pos)
        r = random.uniform(0,1)
        g = random.uniform(0,1)
        b = random.uniform(0,1)
        if one_health.int <= 5:
                glColor3f(r,g,b)
        #RAGEEEEEEE
        if one_health.int <= 5:
                if finish == False:
                        glColor3f(r,g,b)
                        self.int = 0.3
                        bullet_one.int = 0.8
                        rage = True

        else:
                glColor3f(1,1,1)

        glBegin(GL_LINES)
        glVertex2f(0,0)
        glVertex2f(0,1)

        glVertex2f(0,1)
        glVertex2f(1,0.0)

        glVertex2f(1,0)
        glVertex2f(0,-1.0)

        glVertex2f(0,-1.0)
        glVertex2f(0,0.0)
        glEnd()
        glPopMatrix()

    def draw_line(self):
        if finish == True:
                glColor3f(0,0,0)
        elif title == True:
                glColor3f(0,0,0)
        else:
                glColor3f(1,1,1)
        glPushMatrix()

        glBegin(GL_LINES)
        glVertex2f(0,8)
        glVertex2f(0,-8)
        glEnd()

        #player 1 bar
        glBegin(GL_LINES)
        glColor3f(1,1,1)
        glVertex2f(-13.62,5.3)
        glVertex2f(-3.05,5.3)

        glVertex2f(-3.05,5.3)
        glVertex2f(-3.05,6.67)

        glVertex2f(-3.05,6.67)
        glVertex2f(-13.62,6.67)

        glVertex2f(-13.62,6.67)
        glVertex2f(-13.62,5.3)
        glEnd()
        #player 2 bar
        glBegin(GL_LINES)
        glColor3f(1,1,1)
        glVertex2f(13.62,5.3)
        glVertex2f(3.05,5.3)

        glVertex2f(3.05,5.3)
        glVertex2f(3.05,6.67)

        glVertex2f(3.05,6.67)
        glVertex2f(13.62,6.67)

        glVertex2f(13.62,6.67)
        glVertex2f(13.62,5.3)
        glEnd()
        glPopMatrix()

    def random_stars(self):
        for i in range(10):
                glEnable(GL_POINT_SMOOTH)
                sizerandom = random.uniform(0.5,2.5)
                glPointSize(sizerandom)
                clockobject = pygame.time.Clock()
                starsX = random.uniform(-15.6,15.2)
                starsY = random.uniform(-15.2,12.4)
                rr = random.randint(0,1)
                gg = random.randint(0,1)
                bb = random.randint(0,1)
                glBegin(GL_POINTS)
                glColor3f(rr,gg,bb)
                glVertex3d(starsX,starsY,0)
                glEnd()

class one_health:
    def __init__(selfh, vertices, edges):
        selfh.vertices = vertices
        selfh.edges = edges
        selfh.pos = [-13,6.5,0]
        selfh.int = 15

    def draw(selfh,size,health_num):

            glPushMatrix()
            glTranslatef(*selfh.pos)
            rg = random.uniform(0.5,1)
            rb = random.uniform(0.5,0.5)
            rr = random.uniform(0.5,1)

            if selfh.int >= 10:
                glColor3f(0,rg,rb)
            if selfh.int <= 9:
                glColor3f(rr,rg,0)
            if selfh.int <= 5:
                glColor3f(rr,0,rb)

            glBegin(GL_QUADS)
            for i in range(selfh.int):

                glVertex2f(0+size,0)
                glVertex2f(-0.5+size,0)

                glVertex2f(-0.5+size,0)
                glVertex2f(-0.5+size,-1)

                glVertex2f(-0.5+size,-1)
                glVertex2f(0+size,-1.0)

                glVertex2f(0+size,-1)
                glVertex2f(0+size,0)

                size += 0.7

            glEnd()
            glPopMatrix()

class two_health:
    def __init__(selfh, vertices, edges):
        selfh.vertices = vertices
        selfh.edges = edges
        selfh.pos = [13,5.5,0]
        selfh.int = 15

    def draw(selfh,size,health_num):

            glPushMatrix()
            glTranslatef(*selfh.pos)
            glRotatef(180,0,0,0)
            rg = random.uniform(0.5,1)
            rb = random.uniform(0.5,0.5)
            rr = random.uniform(0.5,1)

            if selfh.int >= 10:
                glColor3f(0,rg,rb)
            if selfh.int <= 9:
                glColor3f(rr,rg,0)
            if selfh.int <= 5:
                glColor3f(rr,0,rb)

            glBegin(GL_QUADS)
            for i in range(selfh.int):

                glVertex2f(0+size,0)
                glVertex2f(-0.5+size,0)

                glVertex2f(-0.5+size,0)
                glVertex2f(-0.5+size,-1)

                glVertex2f(-0.5+size,-1)
                glVertex2f(0+size,-1.0)

                glVertex2f(0+size,-1)
                glVertex2f(0+size,0)

                size += 0.7

            glEnd()
            glPopMatrix()

class player_two:
    def __init__(selfs, vertices, edges):
        selfs.vertices = vertices
        selfs.edges = edges
        selfs.pos = [13,0,0]
        selfs.int = 0.02

    def move(selfs):
        selfs.k_press = pygame.key.get_pressed()
        if selfs.k_press[pygame.K_UP]:
            if selfs.pos[1] < 6:
                selfs.pos[1] += selfs.int

        if selfs.k_press[pygame.K_DOWN]:
            if selfs.pos[1] > -6:
                selfs.pos[1] -= selfs.int
        #if selfs.k_press[pygame.K_RIGHT]:
        #    if selfs.pos[0] < 13.8:
         #       selfs.pos[0] += selfs.int

        #if selfs.k_press[pygame.K_LEFT]:
          #  if selfs.pos[0] > 1.2:
             #   selfs.pos[0] -= selfs.int

    def draw(selfs):
        glPushMatrix()
        glTranslatef(*selfs.pos)
        r = random.uniform(0,1)
        g = random.uniform(0,1)
        b = random.uniform(0,1)
        #RAGEEEEEEE
        if two_health.int <= 5:
                if finish == False:
                        glColor3f(r,g,b)
                        selfs.int = 0.3
                        bullet_two.int = 0.8

        else:
                glColor3f(1,1,1)

        glBegin(GL_LINES)
        glVertex2f(0,0)
        glVertex2f(0,-1)

        glVertex2f(0,-1)
        glVertex2f(-1,0.0)

        glVertex2f(-1,0)
        glVertex2f(0,1.0)

        glVertex2f(0,1.0)
        glVertex2f(0,0.0)
        glEnd()
        glPopMatrix()

class bullet_one:
    def __init__(selfr, vertices, edges):
        selfr.vertices = vertices
        selfr.edges = edges
        selfr.pos = [-12,0,0]
        selfr.int = 0.009

    def draw(selfr):
        glPushMatrix()
        glTranslatef(*selfr.pos)
        glPointSize(20)
        rg = random.uniform(0.5,1)
        rb = random.uniform(1,0.5)
        rr = random.uniform(0.5,0.5)
        glColor3f(0,rg,rb)
        glBegin(GL_POINTS)
        glVertex2d(0,0)
        glEnd()
        glPopMatrix()

    def shoot(selfr):
        global rages
        selfr.pos[0] += selfr.int

        #bulletsound condition
        if selfr.pos[0] <= player_one.pos[0] + 0.8:
            if finish == False:
                bullet1_sound.set_volume(0.3)
                bullet1_sound.play()####

        if selfr.pos[0] > 16:
            selfr.pos[0] = player_one.pos[0]
            selfr.pos[1] = player_one.pos[1]

        if selfr.pos[0] >= (player_two.pos[0] -0.5):
            if selfr.pos[0] <= (player_two.pos[0] + 0.5):
                if selfr.pos[1] < (player_two.pos[1]+1):
                    if selfr.pos[1] > (player_two.pos[1]-1):
                        if finish == False:
                            selfr.pos[0] = player_one.pos[0]
                            selfr.pos[1] = player_one.pos[1]
                            player_hitsound.play()
                            two_health.int -= 1
                            print("player 1 hit")
                            if two_health.int == 5:
                                alarm.play()#####
                                rages = True

                                if rages == True:
                                    rage_true()
                                    rages = False

                            if two_health.int == 0:
                                rage_false()
                                end.play()#####

        if selfr.pos[0] >= bullet_two.pos[0]:
            if selfr.pos[1] < (bullet_two.pos[1]+ 0.5):
                if selfr.pos[1] > (bullet_two.pos[1]- 0.5):
                    if finish == False:
                        selfr.pos[0] = player_one.pos[0]
                        selfr.pos[1] = player_one.pos[1]
                        bullet_two.pos[0] = player_two.pos[0]
                        bullet_two.pos[1] = player_two.pos[1]
                        collide_sound.set_volume(0.5)
                        collide_sound.play()

class bullet_two:
    def __init__(selft, vertices, edges):
        selft.vertices = vertices
        selft.edges = edges
        selft.pos = [12,0,0]
        selft.int = 0.009

    def draw(selft):
        glPushMatrix()
        glTranslatef(*selft.pos)
        glPointSize(20)
        rg = random.uniform(0.5,1)
        rb = random.uniform(0,1)
        rr = random.uniform(0.5,1)
        glColor3f(rr,0,rb)
        glBegin(GL_POINTS)
        glVertex2d(0,0)
        glEnd()
        glPopMatrix()

    def shoot(selft):
        global rages
        selft.pos[0] -= selft.int

        #bulletsound condition
        if selft.pos[0] >= player_two.pos[0] - 0.8:
            if finish == False:

                bullet2_sound.set_volume(0.2)###
                bullet2_sound.play()####

        if selft.pos[0] < -16:
            selft.pos[0] = player_two.pos[0]
            selft.pos[1] = player_two.pos[1]

        if selft.pos[0] <= (player_one.pos[0]+0.5):
            if selft.pos[0] >= (player_one.pos[0] - 0.5):
                if selft.pos[1] < (player_one.pos[1] + 1):
                    if selft.pos[1] > (player_one.pos[1] - 1):
                        if finish == False:
                            selft.pos[0] = player_two.pos[0]
                            selft.pos[1] = player_two.pos[1]
                            print("player 2 hit")
                            player_hitsound.play()
                            one_health.int -= 1
                            if one_health.int == 5:
                                alarm.play()#####
                                rages = True
                                if rages == True:
                                    rage_true()
                                    rages = False

                            if one_health.int == 0:
                                rage_false()

                                end.play()#####

        if one_health.int <= 0:
            selft.int = 0.01
            bullet_one.int = 0.01
            player_one.int = 0.01
            player_two.int = 0.01

        if two_health.int <= 0:
            selft.int = 0.01
            bullet_one.int = 0.01
            player_one.int = 0.01
            player_two.int = 0.01

class GameOver:
        def __init__(selfg, vertices, edges):
                selft.vertices = vertices
                selft.edges = edges
                selft.pos = [0,0,0]

        def drawText(x, y, text):
                r = random.uniform(150,255)
                g = random.uniform(150,255)
                b = random.uniform(150,255)
                textSurface = font.render(text, True, (255, r, g, 255)).convert_alpha()
                textData = pygame.image.tostring(textSurface, "RGBA", True)
                glWindowPos2d(x, y)
                glDrawPixels(textSurface.get_width(), textSurface.get_height(), GL_RGBA, GL_UNSIGNED_BYTE, textData)

player_one = player_one(((1, -1)),((0, 0)))
player_two = player_two(((1, -1)),((0, 0)))
bullet_one = bullet_one(((1, -1)),((0, 0)))
bullet_two = bullet_two(((1, -1)),((0, 0)))
one_health = one_health(((1, -1)),((0, 0)))
two_health = two_health(((1, -1)),((0, 0)))

class main:

    def display_all():
        player_one.move()
        player_one.draw()
        one_health.draw(0,0)

        player_one.draw_line()
        player_one.random_stars()

        player_two.move()
        player_two.draw()
        two_health.draw(0,0)

        bullet_one.shoot()
        bullet_one.draw()

        bullet_two.shoot()
        bullet_two.draw()

glMatrixMode(GL_PROJECTION)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
gluPerspective(45, (screen.width/screen.height), 0.1, 50.0)
glMatrixMode(GL_MODELVIEW)
glTranslatef(0,0,-17)

game_over = False
finish = False
hideone = 1000
hidetwo = 1000
spacetext = 1000
hidetitle = 180
hidetitle2 = 120
title = True
coder = 0
hide1v1 = 260
rage = False

while not game_over:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            print('gameover')
            pygame.quit()

        if bullet_two.pos[0] <= bullet_one.pos[0]:
            if bullet_two.pos[1] < (bullet_one.pos[1] + 0.5):
                if bullet_two.pos[1] > (bullet_one.pos[1] - 0.5):
                   if finish == False:
                        bullet_two.pos[0] = player_two.pos[0]
                        bullet_two.pos[1] = player_two.pos[1]
                        bullet_one.pos[0] = player_one.pos[0]
                        bullet_one.pos[1] = player_one.pos[1]
                        collide_sound.play()
                        print('bullet collide')

        if one_health.int <=0:
            if two_health.int > one_health.int:
                print('PLAYER TWO WINS')
                hidetwo = 220
                spacetext = 150
                coder =0
                finish = True

        if two_health.int <=0:
            if one_health.int > two_health.int:
                print('PLAYER ONE WINS')
                hideone = 220
                spacetext = 150
                coder = 0
                finish = True

        if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                        if finish == True:
                                print(index)
                                if title == False:
                                    if index == 0:
                                        rage_false()
                                        print('restart')
                                        #player health
                                        one_health.int =15
                                        two_health.int = 15
                                        #reset movement speed and position p1
                                        player_one.int = 0.2
                                        player_one.pos[1] = 0
                                        player_one.pos[0] = -13
                                         #reset movement speed and position p2
                                        player_two.int = 0.2
                                        player_two.pos[1] = 0
                                        player_two.pos[0] = 13
                                        #bullet speed
                                        bullet_one.int = 0.5
                                        bullet_two.int = 0.5
                                        #bullet position reset Y
                                        bullet_one.pos[1] = 0
                                        bullet_two.pos[1] = 0
                                        #bullet position reset X
                                        bullet_one.pos[0] = -13
                                        bullet_two.pos[0] = 13

                                        hideone = 1000
                                        hidetwo = 1000
                                        spacetext = 1000
                                        coder =1000
                                        finish = False

                        if title == True:
                                print('Startgame')
                                #player health
                                one_health.int =15
                                two_health.int = 15
                                #reset movement speed and position p1
                                player_one.int = 0.2
                                player_one.pos[1] = 0
                                player_one.pos[0] = -13
                                #reset movement speed and position p2
                                player_two.int = 0.2
                                player_two.pos[1] = 0
                                player_two.pos[0] = 13
                                #bullet speed
                                bullet_one.int = 0.5
                                bullet_two.int = 0.5
                                #bullet position reset Y
                                bullet_one.pos[1] = 0
                                bullet_two.pos[1] = 0
                                #bullet position reset X
                                bullet_one.pos[0] = -13
                                bullet_two.pos[0] = 13

                                hideone = 1000
                                hidetwo = 1000
                                spacetext = 1000
                                hidetitle = 1000
                                hidetitle2 = 1000
                                hide1v1 = 1000
                                coder =1000

                                title = False

    screen.clear()
    main.display_all()
    font = pygame.font.SysFont('impact', 80)

    GameOver.drawText(120, hideone, "Player One Wins")
    GameOver.drawText(120, hidetwo, "Player Two Wins")
    font = pygame.font.SysFont('impact', 80)
    GameOver.drawText(351, hide1v1, "1v1")
    GameOver.drawText(140, hidetitle, "SPACE SHOOTER")
    font = pygame.font.SysFont('impact', 60)

    GameOver.drawText(225, hidetitle2, "SPACE to Start")
    GameOver.drawText(190, spacetext, "SPACE to Restart")
    font = pygame.font.SysFont('impact', 20)
    GameOver.drawText(0, coder, "Code by John Patrick Quintos - BT701")

    screen.update()


import pandas as pd
import seaborn as sns
from typing import Any
from .template import Processor, Settings

class PlotContigEnrichment(Processor):

    enrichment_csv: str

    df: pd.DataFrame
    ax: Any

    def __init__(self, settings: Settings):
        super().__init__(settings=settings)

    def main(self, enrichment_csv: str):
        self.enrichment_csv = enrichment_csv

        self.read_data()
        self.add_assembly_column()
        self.stripplot()
        self.config_and_save_fig()

    def read_data(self):
        data = pd.read_csv(self.enrichment_csv, header=0)
        self.df = pd.DataFrame(data)

    def add_assembly_column(self):
        self.df['assembly'] = ''
        for i in range(len(self.df)):
            contig_id = self.df.loc[i, 'contig_id']
            assembly = contig_id.split('assembly=')[1].split(';')[0] + '_contigs'
            self.df.loc[i, 'assembly'] = assembly

    def stripplot(self):
        self.ax = sns.stripplot(
            data=self.df,
            x=self.df['assembly'],
            y=self.df['enrichment'],
            order=['control_contigs', 'case_contigs'],
            jitter=True,
            alpha=0.5
        )

    def config_and_save_fig(self):
        self.ax.set_ylabel('Enrichment')
        self.ax.set_yscale('log')
        self.ax.set_ylim((0.0001, 10000))
        fig = self.ax.get_figure()
        fig.set_size_inches(w=5, h=5)
        fig.savefig(f'{self.outdir}/contig_enrichment.png', format='png', dpi=600)


import os
import sys
from fractions import Fraction
from os import remove, devnull as os_devnull, system
from random import randint
from subprocess import check_call

import numpy as np
import psutil
from numpy.linalg import svd
from sympy import Matrix

from ecmtool.mpi_wrapper import get_process_rank

def unique(matrix):
    unique_set = list({tuple(row) for row in matrix if np.count_nonzero(row) > 0})
    return np.vstack(unique_set) if len(unique_set) else to_fractions(np.ndarray(shape=(0, matrix.shape[1])))

def find_unique_inds(matrix, verbose=False, tol=1e-9):
    n_rays = matrix.shape[0]
    n_nonunique = 0
    original_inds_remaining = np.arange(n_rays)
    unique_inds = []
    counter = 0
    while matrix.shape[0] > 0:
        row = matrix[0, :]
        unique_inds.append(original_inds_remaining[0])
        if verbose:
            if counter % 100 == 0:
                mp_print("Find unique rows has tested %d of %d (%f %%). Removed %d non-unique rows." %
                         (counter, n_rays, counter / n_rays * 100, n_nonunique))
        counter = counter + 1
        equal_rows = np.where(np.max(np.abs(matrix - row), axis=1) < tol)[0]
        if len(equal_rows):
            n_nonunique = n_nonunique + len(equal_rows) - 1
            matrix = np.delete(matrix, equal_rows, axis=0)
            original_inds_remaining = np.delete(original_inds_remaining, equal_rows)
        else:  # Something is wrong, at least the row itself should be equal to itself
            mp_print('Something is wrong in the unique_inds function!!')

    return unique_inds

def relative_path(file_path):
    return os.path.join(os.path.dirname(__file__), file_path)

def open_relative(file_path, mode='r'):
    return open(relative_path(file_path), mode)

def remove_relative(file_path):
    return remove(relative_path(file_path))

def get_total_memory_gb():
    """
    Returns total system memory in GiB (gibibytes)
    :return:
    """
    return psutil.virtual_memory().total / 1024 ** 3

def get_min_max_java_memory():
    """
    Returns plausible starting and maximum virtual memory sizes in gibibytes
    for a java VM, as used to run e.g. Polco. Min is either 10% of system RAM
    or 1 gigabyte, whichever is larger. Max is 80% of system RAM.
    :return:
    """
    total = get_total_memory_gb()
    min = int(np.ceil(float(total) * 0.1))
    max = int(np.round(float(total) * 0.8))
    return min, max

def nullspace(N, symbolic=True, atol=1e-13, rtol=0):
    """
    Calculates the null space of given matrix N.
    Source: https://scipy-cookbook.readthedocs.io/items/RankNullspace.html
    :param N: ndarray
            A should be at most 2-D.  A 1-D array with length k will be treated
            as a 2-D with shape (1, k)
    :param symbolic: set to False to compute nullspace numerically instead of symbolically
    :param atol: float
            The absolute tolerance for a zero singular value.  Singular values
            smaller than `atol` are considered to be zero.
    :param rtol: float
            The relative tolerance.  Singular values less than rtol*smax are
            considered to be zero, where smax is the largest singular value.
    :return: If `A` is an array with shape (m, k), then `ns` will be an array
            with shape (k, n), where n is the estimated dimension of the
            nullspace of `A`.  The columns of `ns` are a basis for the
            nullspace; each element in numpy.dot(A, ns) will be approximately
            nullspace; each element in numpy.dot(A, ns) will be approximately
            zero.
    """
    if not symbolic:
        N = np.asarray(N, dtype='int64')
        u, s, vh = svd(N)
        tol = max(atol, rtol * s[0])
        nnz = (s >= tol).sum()
        ns = vh[nnz:].conj()
        return np.transpose(ns)
    else:
        nullspace_vectors = Matrix(N).nullspace()

        # Add nullspace vectors to a nullspace matrix as row vectors
        # Must be a sympy Matrix so we can do rref()
        nullspace_matrix = nullspace_vectors[0].T if len(nullspace_vectors) else None
        for i in range(1, len(nullspace_vectors)):
            nullspace_matrix = nullspace_matrix.row_insert(-1, nullspace_vectors[i].T)

        return to_fractions(
            np.transpose(np.asarray(nullspace_matrix.rref()[0], dtype='object'))) if nullspace_matrix \
            else np.ndarray(shape=(N.shape[0], 0))

def get_extreme_rays(equality_matrix=None, inequality_matrix=None, symbolic=True, verbose=False):
    rand = randint(1, 10 ** 6)

    if inequality_matrix is not None and inequality_matrix.shape[0] == 0:
        inequality_matrix = None

    if equality_matrix is not None and equality_matrix.shape[0] == 0:
        equality_matrix = None

    if inequality_matrix is None:
        if equality_matrix is not None:
            # inequality_matrix = np.identity(equality_matrix.shape[1])
            inequality_matrix = np.zeros(shape=(1, equality_matrix.shape[1]))
        else:
            raise Exception('No equality or inequality argument given')

    # if inequality_matrix.shape[1] < 50:
    #     if verbose:
    #         print('Using CDD instead of Polco for enumeration of small system')
    #     ineq = np.append(np.append(equality_matrix, -equality_matrix, axis=0), inequality_matrix, axis=0)
    #     for ray in get_extreme_rays_cdd(ineq):
    #         yield ray
    #     return

    # Write equalities system to disk as space separated file
    if verbose:
        print('Writing equalities to file')
    if equality_matrix is not None:
        with open_relative('tmp' + os.sep + 'eq_%d.txt' % rand, 'w') as file:
            for row in range(equality_matrix.shape[0]):
                file.write(' '.join([str(val) for val in equality_matrix[row, :]]) + '\n')

    # Write inequalities system to disk as space separated file
    if verbose:
        print('Writing inequalities to file')
    with open_relative('tmp' + os.sep + 'iq_%d.txt' % rand, 'w') as file:
        for row in range(inequality_matrix.shape[0]):
            file.write(' '.join([str(val) for val in inequality_matrix[row, :]]) + '\n')

    # Run external extreme ray enumeration tool
    min_mem, max_mem = get_min_max_java_memory()
    if verbose:
        print('Running polco (%d-%d GiB java VM memory)' % (min_mem, max_mem))

    equality_path = relative_path('tmp' + os.sep + 'eq_%d.txt' % rand)
    inequality_path = relative_path('tmp' + os.sep + 'iq_%d.txt' % rand)
    generators_path = relative_path('tmp' + os.sep + 'generators_%d.txt' % rand)
    with open(os_devnull, 'w') as devnull:
        polco_path = relative_path('polco' + os.sep + 'polco.jar')
        check_call(('java -Xms%dg -Xmx%dg ' % (min_mem, max_mem) +
                    '-jar %s -kind text -sortinput AbsLexMin ' % polco_path +
                    '-arithmetic %s ' % (' '.join(['fractional' if symbolic else 'double'] * 3)) +
                    '-zero %s ' % (' '.join(['NaN' if symbolic else '1e-10'] * 3)) +
                    ('' if equality_matrix is None else '-eq %s ' % equality_path) +
                    ('' if inequality_matrix is None else '-iq %s ' % inequality_path) +
                    '-out text %s' % generators_path).split(' '),
                   stdout=(devnull if not verbose else None), stderr=(devnull if not verbose else None))

    # Read resulting extreme rays
    if verbose:
        print('Parsing computed rays')
    with open(generators_path, 'r') as file:
        lines = file.readlines()
        rays = np.ndarray(shape=(0, inequality_matrix.shape[1]))

        if len(lines) > 0:
            number_lines = len(lines)
            number_entries = len(lines[0].replace('\n', '').split('\t'))
            rays = np.repeat(np.repeat(to_fractions(np.zeros(shape=(1, 1))), number_entries, axis=1), number_lines,
                             axis=0)

            for row, line in enumerate(lines):
                # print('line %d/%d' % (row+1, number_lines))
                for column, value in enumerate(line.replace('\n', '').split('\t')):
                    if value != '0':
                        rays[row, column] = Fraction(str(value))

    if verbose:
        print('Done parsing rays')

    # Clean up the files created above
    if equality_matrix is not None:
        remove(equality_path)

    remove(inequality_path)
    remove(generators_path)

    return rays

def binary_exists(binary_file):
    return any(
        os.access(os.path.join(path, binary_file), os.X_OK)
        for path in os.environ["PATH"].split(os.pathsep)
    )

def get_redund_binary():
    if sys.platform.startswith('linux'):
        if not binary_exists('redund'):
            raise EnvironmentError(
                'Executable "redund" was not found in your path. Please install package lrslib (e.g. apt install lrslib)')
        return 'redund'
    elif sys.platform.startswith('win32'):
        return relative_path('redund\\redund_win.exe')
    elif sys.platform.startswith('darwin'):
        return relative_path('redund/redund_mac')
    else:
        raise OSError('Unsupported operating system platform: %s' % sys.platform)

def redund(matrix, verbose=False):
    rank = str(get_process_rank())
    matrix = to_fractions(matrix)
    binary = get_redund_binary()
    matrix_path = relative_path('tmp' + os.sep + 'matrix' + rank + '.ine')
    matrix_nonredundant_path = relative_path('tmp' + os.sep + 'matrix_nored' + rank + '.ine')

    if matrix.shape[0] <= 1:
        return matrix

    with open(matrix_path, 'w') as file:
        file.write('V-representation\n')
        file.write('begin\n')
        file.write('%d %d rational\n' % (matrix.shape[0], matrix.shape[1] + 1))
        for row in range(matrix.shape[0]):
            file.write(' 0')
            for col in range(matrix.shape[1]):
                file.write(' %s' % str(matrix[row, col]))
            file.write('\n')
        file.write('end\n')

    system('%s %s > %s' % (binary, matrix_path, matrix_nonredundant_path))

    matrix_nored = np.ndarray(shape=(0, matrix.shape[1] + 1), dtype='object')

    with open(matrix_nonredundant_path) as file:
        lines = file.readlines()
        for line in [line for line in lines if line not in ['\n', '']]:
            # Skip comment and INE format lines
            if np.any([target in line for target in ['*', 'V-representation', 'begin', 'end', 'rational']]):
                continue
            row = [Fraction(x) for x in line.replace('\n', '').split(' ') if x != '']
            matrix_nored = np.append(matrix_nored, [row], axis=0)

    remove(matrix_path)
    remove(matrix_nonredundant_path)

    if verbose:
        print('Removed %d redundant rows' % (matrix.shape[0] - matrix_nored.shape[0]))

    return matrix_nored[:, 1:]

def to_fractions(matrix, quasi_zero_correction=False, quasi_zero_tolerance=1e-13):
    if quasi_zero_correction:
        # Make almost zero values equal to zero
        matrix[(matrix < quasi_zero_tolerance) & (matrix > -quasi_zero_tolerance)] = Fraction(0, 1)

    fraction_matrix = matrix.astype('object')

    for row in range(matrix.shape[0]):
        for col in range(matrix.shape[1]):
            # str() here makes Sympy use true fractions instead of the double-precision
            # floating point approximation
            fraction_matrix[row, col] = Fraction(str(matrix[row, col]))

    return fraction_matrix

def get_metabolite_adjacency(N):
    """
    Returns m by m adjacency matrix of metabolites, given
    stoichiometry matrix N. Diagonal is 0, not 1.
    :param N: stoichiometry matrix
    :return: m by m adjacency matrix
    """

    number_metabolites = N.shape[0]
    adjacency = np.zeros(shape=(number_metabolites, number_metabolites))

    for metabolite_index in range(number_metabolites):
        active_reactions = np.where(N[metabolite_index, :] != 0)[0]
        for reaction_index in active_reactions:
            adjacent_metabolites = np.where(N[:, reaction_index] != 0)[0]
            for adjacent in [i for i in adjacent_metabolites if i != metabolite_index]:
                adjacency[metabolite_index, adjacent] = 1
                adjacency[adjacent, metabolite_index] = 1

    return adjacency

def mp_print(*args, **kwargs):
    """
    Multiprocessing wrapper for print().
    Prints the given arguments, but only on process 0 unless
    named argument PRINT_IF_RANK_NONZERO is set to true.
    :return:
    """
    if get_process_rank() == 0:
        print(*args)
    elif 'PRINT_IF_RANK_NONZERO' in kwargs and kwargs['PRINT_IF_RANK_NONZERO']:
        print(*args)

def unsplit_metabolites(R, network):
    metabolite_ids = [metab.id for metab in network.metabolites]
    res = []
    ids = []

    processed = {}
    for i in range(R.shape[0]):
        metabolite = metabolite_ids[i].replace("_virtin", "").replace("_virtout", "")
        if metabolite in processed:
            row = processed[metabolite]
            res[row] += R[i, :]
        else:
            res.append(R[i, :].tolist())
            processed[metabolite] = len(res) - 1
            ids.append(metabolite)

    # remove all-zero rays
    res = np.asarray(res)
    res = res[:, [sum(abs(res)) != 0][0]]

    return res, ids

def print_ecms_direct(R, metabolite_ids):
    obj_id = -1
    if "objective" in metabolite_ids:
        obj_id = metabolite_ids.index("objective")
    elif "objective_virtout" in metabolite_ids:
        obj_id = metabolite_ids.index("objective_virtout")

    mp_print("\n--%d ECMs found--\n" % R.shape[1])
    for i in range(R.shape[1]):
        mp_print("ECM #%d:" % (i + 1))
        if np.max(R[:,
                  i]) > 1e100:  # If numbers become too large, they can't be printed, therefore we make them smaller first
            ecm = np.array(R[:, i] / np.max(R[:, i]), dtype='float')
        else:
            ecm = np.array(R[:, i], dtype='float')

        div = 1
        if obj_id != -1 and R[obj_id][i] != 0:
            div = ecm[obj_id]
        for j in range(R.shape[0]):
            if ecm[j] != 0:
                mp_print("%s\t\t->\t%.4f" % (metabolite_ids[j].replace("_in", "").replace("_out", ""), ecm[j] / div))
        mp_print("")

def normalize_columns(R, verbose=False):
    result = np.zeros(R.shape)
    number_rays = R.shape[1]
    for i in range(result.shape[1]):
        if verbose:
            if i % 10000 == 0:
                mp_print("Normalize columns is on ray %d of %d (%f %%)" %
                         (i, number_rays, i / number_rays * 100), PRINT_IF_RANK_NONZERO=True)
        largest_number = np.max(np.abs(R[:,i]))
        if largest_number > 1e100:  # If numbers are very large, converting to float might give issues, therefore we first divide by another int
            part_normalized_column = np.array(R[:, i] / largest_number, dtype='float')
            result[:, i] = part_normalized_column / np.linalg.norm(part_normalized_column)
        else:
            norm_column = np.linalg.norm(np.array(R[:, i], dtype='float'), ord=1)
            if norm_column != 0:
                result[:, i] = np.array(R[:, i], dtype='float') / norm_column
    return result

def find_remaining_rows(first_mat, second_mat, tol=1e-12, verbose=False):
    """Checks which rows (indices) of second_mat are still in first_mat"""
    remaining_inds = []
    number_rays = first_mat.shape[0]
    for ind, row in enumerate(first_mat):
        if verbose:
            if ind % 10000 == 0:
                mp_print("Find remaining rows is on row %d of %d (%f %%)" %
                         (ind, number_rays, ind / number_rays * 100))
        sec_ind = np.where(np.max(np.abs(second_mat - row), axis=1) < tol)[0]
        # for sec_ind, sec_row in enumerate(second_mat):
        #    if np.max(np.abs(row - sec_row)) < tol:
        #        remaining_inds.append(ind)
        #        continue
        if len(sec_ind):
            remaining_inds.append(sec_ind[0])
        else:
            mp_print('Warning: There are rows in the first matrix that are not in the second matrix')

    return remaining_inds

def normalize_columns_fraction(R, vectorized=False, verbose=True):
    if not vectorized:
        number_rays = R.shape[1]
        for i in range(number_rays):
            if verbose:
                if i % 10000 == 0:
                    mp_print("Normalize columns is on ray %d of %d (%f %%)" %
                             (i, number_rays, i / number_rays * 100), PRINT_IF_RANK_NONZERO=True)
            norm_column = np.sum(np.abs(np.array(R[:, i])))
            if norm_column!=0:
                R[:, i] = np.array(R[:, i]) / norm_column
    else:
        R = R / np.sum(np.abs(R), axis=0)
    return R


import requests
from bs4 import BeautifulSoup
from twilio.rest import Client
import time

# Your Twilio account SID and AUTH Token
account_sid = "enter account_sid"
auth_token = "enter auth_token"
client = Client(account_sid, auth_token)

while True:
    # Get the current time
    current_time = time.localtime()

    # Only send the message if it's 6:00 AM
    if current_time.tm_hour == 6 and current_time.tm_min == 00:
        # Send the SMS message
        try:
            # Scrape the latest world news headlines from CNN's website
            page = requests.get("https://www.cnn.com/business")
            soup = BeautifulSoup(page.content, "html.parser")
            headlines = soup.find_all("div", class_="container__headline container_lead-plus-headlines__headline")
            headlines = [headline.text.strip() for headline in headlines]
            print(headlines)

            # Format the message
            message_body = "Latest World News Headlines from CNN:\n\n" + "\n\n".join(headlines[:14]) + "..."

            # Send the message
            message1 = client.messages.create(
                to="enter your number",
                from_="enter twilio number",
                body=message_body
            )

            print("SMS sent successfully!")
        except:
            print("An error occurred while sending the SMS.")

    # Wait for 1 minute before checking the time again
    time.sleep(60)


import bpy
import bmesh
import operator
import math
from mathutils import Vector
from collections import defaultdict

from . import settings
from . import utilities_color
from . import utilities_bake

material_prefix = "TT_atlas_"
gamma = 2.2

class op(bpy.types.Operator):
	bl_idname = "uv.textools_texture_preview"
	bl_label = "Preview Texture"
	bl_description = "Preview the current UV image view background image on the selected object."
	bl_options = {'REGISTER', 'UNDO'}

	@classmethod
	def poll(cls, context):
		if not bpy.context.active_object:
			return False

		if len(settings.sets) == 0:
			return False

		# Only when we have a background image
		for area in bpy.context.screen.areas:
			if area.type == 'IMAGE_EDITOR':
				return area.spaces[0].image

		return False

	def execute(self, context):
		print("PREVIEW TEXTURE????")
		preview_texture(self, context)
		return {'FINISHED'}

def preview_texture(self, context):

	# Collect all low objects from bake sets
	objects = [obj for s in settings.sets for obj in s.objects_low if obj.data.uv_layers]

	# Get view 3D area
	view_area = None
	for area in bpy.context.screen.areas:
		if area.type == 'VIEW_3D':
			view_area = area

	# Exit existing local view
	# if view_area and view_area.spaces[0].local_view:
	# 	bpy.ops.view3d.localview({'area': view_area})
	# 	return

	# Get background image
	image = None
	for area in bpy.context.screen.areas:
		if area.type == 'IMAGE_EDITOR':
			image = area.spaces[0].image
			break

	if image:
		for obj in objects:
			print("Map {}".format(obj.name))

			bpy.ops.object.mode_set(mode='OBJECT')
			bpy.ops.object.select_all(action='DESELECT')
			obj.select = True
			bpy.context.scene.objects.active = obj

			for i in range(len(obj.material_slots)):
				bpy.ops.object.material_slot_remove()

			#Create material with image
			bpy.ops.object.material_slot_add()
			obj.material_slots[0].material = utilities_bake.get_image_material(image)
			obj.draw_type = 'TEXTURED'

		# Re-Select objects
		bpy.ops.object.select_all(action='DESELECT')
		for obj in objects:
			obj.select = True

		if view_area:
			#Change View mode to TEXTURED
			for space in view_area.spaces:
				if space.type == 'VIEW_3D':
					space.viewport_shade = 'MATERIAL'

			# Enter local view
			# bpy.ops.view3d.localview({'area': view_area})
			# bpy.ops.ui.textools_popup('INVOKE_DEFAULT', message="Object is in isolated view")


from typing import List
from collections import defaultdict, deque

class Set:
	def __init__(self, x):
		self.val = x
		self.rank = 1
		self.parent = self

	def __repr__(self):
		return f'SET[repr:{self.val}, rank:{self.rank}]'

class UnionFind:
	def __init__(self, lst):
		self.map = {n: Set(n) for n in lst}

	def __repr__(self):
		str = ''
		sets = defaultdict(list)
		for elem, value in self.map.items():
			sets[self.findSet(value).val].append(elem)
		for s in sets:
			str += f'{self.find(s)} : {sets[s]}\n'

		return str

	def union_by_rank(self, x: Set, y: Set):
		if x.rank == y.rank:
			x.parent = y
			y.rank += 1
		elif x.rank < y.rank:
			x.parent = y
		else:
			y.parent = x

	# path compression
	def findSet(self, x: Set):
		if x.parent != x:
			x.parent = self.findSet(x.parent)
		return x.parent

	## user facing
	def find(self, x):
		return self.findSet(self.map[x])

	def link(self, x, y):
		self.union_by_rank(self.find(x), self.find(y))

class Solution:
	def validTree(self, n, edges):
		if len(edges) != n-1:
			return False

		if n == 1:
			return True

		adjlist = defaultdict(set)
		for v1, v2 in edges:
			adjlist[v1].add(v2)
			adjlist[v2].add(v1)

		def hasCycleBFS(s):
			q = deque([s])
			discovered = {s}
			while q:
				top = q.pop()
				for nbr in adjlist[top]:
					if nbr not in discovered:
						adjlist[nbr].remove(top)
						discovered.add(nbr)
						q.appendleft(nbr)
					else:
						return False
			return True

		return hasCycleBFS(edges[0][0])

	def validTreeUnionFind(self, n: int, edges: List[List[int]]) -> bool:
		forest = UnionFind(range(n))
		print(forest)
		if len(edges) != n-1:
			return False

		for v1, v2  in edges:
			if forest.find(v1) == forest.find(v2):
				print(forest)
				return False
			forest.link(v1, v2)
		print(forest)

		return True

# print(Solution().validTree(5, [[0,1], [0,2], [0,3], [1,4]]))
print(Solution().validTree(5, [[0,1], [1,2], [2,3], [1,3]]))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Author: André Pacheco
E-mail: pacheco.comp@gmail.com

This file implements the CNN start phase
"""

import os
import torch
import torch.nn as nn
import torch.optim as optim
from tqdm import tqdm
from .checkpoints import load_model, save_model
from .eval import metrics_for_eval
from tensorboardX import SummaryWriter
from source.utils import AVGMetrics, TrainHistory, jaccard_coeff, dice_coeff
import logging
import time

def _config_logger(save_path, file_name):
    logger = logging.getLogger("Train-Logger")
    # Checking if the folder logs doesn't exist. If True, we must create it.
    if not os.path.isdir(save_path):
        os.makedirs(save_path)
    logger_filename = os.path.join(save_path, f"{file_name}_{str(time.time()).replace('.','')}.log")
    fhandler = logging.FileHandler(filename=logger_filename, mode='a')
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fhandler.setFormatter(formatter)
    logger.addHandler(fhandler)
    logger.setLevel(logging.INFO)
    return logger

def _train_epoch (model, optimizer, loss_fn, data_loader, c_epoch, t_epoch, device):

    model.train()

    print ("Training...")
    # Setting tqdm to show some information on the screen
    with tqdm(total=len(data_loader), ascii=True, desc='Epoch {}/{}: '.format(c_epoch, t_epoch), ncols=150) as t:

        # Variables to store the avg metrics
        loss_avg = AVGMetrics()
        jacc_avg = AVGMetrics()
        dice_avg = AVGMetrics()

        # Getting the data from the DataLoader generator
        for data in data_loader:

            imgs_batch, mask_batch = data[0].to(device), data[1].to(device)
            seg_pred = model(imgs_batch)

            # Computing loss function
            loss = loss_fn(seg_pred, mask_batch)
            jacc = jaccard_coeff(torch.sigmoid(seg_pred), mask_batch)
            dice = dice_coeff(torch.sigmoid(seg_pred), mask_batch)

            # Getting the avg metrics
            loss_avg.update(loss.item())
            jacc_avg.update(jacc.item())
            dice_avg.update(dice.item())

            # Zero the parameters gradient
            optimizer.zero_grad()

            # Computing gradients and performing the update step
            loss.backward()
            optimizer.step()

            # Updating tqdm
            t.set_postfix(loss='{:05.3f}'.format(loss_avg()), jacc='{:05.3f}'.format(jacc_avg()),
                          dice='{:05.3f}'.format(dice_avg()))
            t.update()

    return {"loss": loss_avg(), "jacc": jacc_avg(), "dice": dice_avg() }

def fit_model (model, train_data_loader, val_data_loader, optimizer=None, loss_fn=None, epochs=10,
               epochs_early_stop=None, save_folder=None, initial_model=None, device=None, schedule_lr=None,
               model_name="MyModel", resume_train=False, history_plot=True, min_metric_early_stop=None, best_metric="loss"):

    logger = _config_logger(save_folder, model_name)
    logger.info("Starting the training phase")

    if epochs_early_stop is not None:
        logger.info('Early stopping is set using the number of epochs without improvement')
    if min_metric_early_stop is not None:
        logger.info('Early stopping is set using the min loss as threshold')
    if epochs_early_stop is None and min_metric_early_stop is None:
        logger.info('No early stopping is set')

    if loss_fn is None:
        logger.info('Loss: `nn.BCELoss()` was set as default')
        loss_fn = nn.BCELoss()
    else:
        logger.info('Loss: {}'.format(loss_fn))

    if optimizer is None:
        logger.info('Optimizer: Adam with lr=0.001 was set as default')
        optimizer = optim.Adam(model.parameters(), lr=0.001)
    else:
        logger.info('Optimizer: {}'.format(optimizer))

    # Checking if we have a saved model. If we have, load it, otherwise, let's start the model from scratch
    epoch_resume = 0
    if initial_model is not None:
        logger.info("Loading the saved model in {} folder".format(initial_model))

        if resume_train:
            model, optimizer, loss_fn, epoch_resume = load_model(initial_model, model)
            logger.info("Resuming the training from epoch {} ...".format(epoch_resume))
        else:
            model = load_model(initial_model, model)

    else:
        logger.info("The model {} will be trained from scratch".format(model_name))

    # Setting the device(s)
    # If GPU is available, let's move the model to there. If you have more than one, let's use them!
    m_gpu = 0
    if device is None:
        if torch.cuda.is_available():
            device = torch.device("cuda")
            # device = torch.device("cuda:" + str(torch.cuda.current_device()))
            m_gpu = torch.cuda.device_count()
            if m_gpu > 1:
                print ("The training will be carry out using {} GPUs:".format(m_gpu))
                for g in range(m_gpu):
                    print (torch.cuda.get_device_name(g))
                    logger.info(torch.cuda.get_device_name(g))

                model = nn.DataParallel(model)
            else:
                logger.info("The training will be carry out using 1 GPU: {}".format(torch.cuda.get_device_name(0)))
        else:
            logger.info("The training will be carry out using CPU")
            device = torch.device("cpu")
    else:
        print("The training will be carry out using 1 GPU:")
        print(torch.cuda.get_device_name(device))
        logger.info("The training will be carry out using 1 GPU: {}".format(torch.cuda.get_device_name(device)))

    # Moving the model to the given device
    model.to(device)

    # setting a flag for the early stop
    early_stop_count = 0
    best_epoch = 0
    best_metric_value = 1000 if best_metric == 'loss' else 0
    best_flag = False

    # Train history
    history = TrainHistory()

    # writer is used to generate the summary files to be loaded at tensorboard
    writer = SummaryWriter (os.path.join(save_folder, 'summaries'))

    # Let's iterate for `epoch` epochs or a tolerance.
    # It always start from epoch resume. If it's set, it starts from the last epoch the training phase was stopped,
    # otherwise, it starts from 0
    epoch = epoch_resume
    while epoch < epochs:

        # Updating epoch
        epoch += 1

        # Training and getting the metrics for one epoch
        train_metrics = _train_epoch(model, optimizer, loss_fn, train_data_loader, epoch, epochs, device)

        # After each epoch, we evaluate the model for the training and validation data
        val_metrics = metrics_for_eval(model, val_data_loader, device, loss_fn)

        # Checking the schedule if applicable
        if isinstance(schedule_lr, torch.optim.lr_scheduler.ReduceLROnPlateau):
            schedule_lr.step(best_metric_value)
        elif isinstance(schedule_lr, torch.optim.lr_scheduler.MultiStepLR):
            schedule_lr.step(epoch)

        # Getting the current LR
        current_LR = None
        for param_group in optimizer.param_groups:
            current_LR = param_group['lr']

        # Writing metrics for tensorboard
        writer.add_scalars('Loss', {'val-loss': val_metrics['loss'], 'train-loss': train_metrics['loss']}, epoch)
        writer.add_scalars('Dice', {'val-dice': val_metrics['dice'], 'train-loss': train_metrics['dice']}, epoch)
        writer.add_scalars('Jacc', {'val-jacc': val_metrics['jacc'], 'train-jacc': train_metrics['jacc']}, epoch)

        history.update(train_metrics['loss'], val_metrics['loss'],
                       train_metrics['dice'], val_metrics['dice'],
                       train_metrics['jacc'], val_metrics['jacc'])

        # Getting the metrics to print on logger
        train_print = "-- Loss: {:.3f}\n-- Dice: {:.3f}\n-- Jacc: {:.3f}".format(train_metrics["loss"],
                                                                              train_metrics["dice"],
                                                                              train_metrics["jacc"])

        val_print = "-- Loss: {:.3f}\n-- Dice: {:.3f}\n-- Jacc: {:.3f}".format(val_metrics["loss"],
                                                                            val_metrics["dice"],
                                                                            val_metrics["jacc"])

        early_stop_count += 1
        new_best_print = None
        # Defining the best metric for validation
        if best_metric == 'loss':
            if val_metrics[best_metric] <= best_metric_value:
                best_metric_value = val_metrics[best_metric]
                new_best_print = '-- New best {}: {:.3f}'.format(best_metric, best_metric_value)
                best_flag = True
                best_epoch = epoch
                early_stop_count = 0
        else:
            if val_metrics[best_metric] >= best_metric_value:
                best_metric_value = val_metrics[best_metric]
                new_best_print = '-- New best {}: {:.3f}'.format(best_metric, best_metric_value)
                best_flag = True
                best_epoch = epoch
                early_stop_count = 0

        # Check if it's the best model in order to save it
        if save_folder is not None:
            print ('- Saving the model...')
            save_model(model, save_folder, epoch, optimizer, loss_fn, best_flag, multi_gpu=m_gpu > 1)

        best_flag = False

        # Updating the logger
        msg = "Metrics for epoch {} out of {}\n".format(epoch, epochs)
        msg += "- Train\n"
        msg += train_print + "\n"
        msg += "\n- Validation\n"
        msg += val_print + "\n"
        msg += "\n- Training info"
        msg += "\n-- Early stopping counting: {} max to stop is {}".format(early_stop_count, epochs_early_stop)
        msg += "\n-- Current LR: {}".format(current_LR)
        if new_best_print is not None:
            msg += new_best_print
        msg += "\n-- Best {} so far: {:.3f} on epoch {}".format(best_metric, best_metric_value, best_epoch)

        # Checking the early stop
        if epochs_early_stop is not None:
            if early_stop_count >= epochs_early_stop:
                logger.info(msg)
                logger.info("The early stop trigger was activated. The validation {} " .format(best_metric) +
                            "{:.3f} did not improved for {} epochs.".format(best_metric_value,
                                                                            epochs_early_stop) +
                            "The training phase was stopped.")

                break

        # Checking the early stop
        if min_metric_early_stop is not None:
            stop = False
            if best_metric == 'loss':
                if min_metric_early_stop >= best_metric_value:
                    stop = True
            else:
                if min_metric_early_stop <= best_metric_value:
                    stop = True

            if stop:
                logger.info(msg)
                logger.info("The early stop trigger was activated. The validation {} ".format(best_metric) +
                            "{:.3f} achieved the defined threshold {:.3f}.".format(best_metric_value,
                                                                            min_metric_early_stop) +
                            "The training phase was stopped.")
                break

        # Sending all message to the logger
        logger.info(msg)

    if history_plot:
        history.save_plot(save_folder)

    history.save(save_folder)
    print('\n')

    writer.close()


import pygame
pygame.init()
from random import randint

def move(snake, direction):
    if direction == 0:
        snake.append((snake[-1][0], snake[-1][1]+1))
    elif direction == 1:
        snake.append((snake[-1][0]+1, snake[-1][1]))
    elif direction == 2:
        snake.append((snake[-1][0], snake[-1][1]-1))
    elif direction == 3:
        snake.append((snake[-1][0]-1, snake[-1][1]))
    snake.pop(0)

def draw(surface, snake, tile_size, food):
    w,h = surface.get_size()
    for i in range(w//tile_size+1):
        pygame.draw.line(surface, (50,50,50), ((i+1)*tile_size,0), ((i+1)*tile_size, h))
    for i in range(h//tile_size):
        pygame.draw.line(surface, (50,50,50), (0,(i+1)*tile_size), (w,(i+1)*tile_size))

    prev_pos = snake[0]
    for s in snake:
        if s is prev_pos:
            pygame.draw.rect(surface, (0,150,0), ((s[0]*tile_size+1, s[1]*tile_size+1), (tile_size-1, tile_size-1)))
        else:
            if prev_pos[0] < s[0]:
                pygame.draw.rect(surface, (0,150,0), ((s[0]*tile_size, s[1]*tile_size+1), (tile_size, tile_size-1)))
            elif prev_pos[0] > s[0]:
                pygame.draw.rect(surface, (0,150,0), ((s[0]*tile_size+1, s[1]*tile_size+1), (tile_size, tile_size-1)))
            elif prev_pos[1] > s[1]:
                pygame.draw.rect(surface, (0,150,0), ((s[0]*tile_size+1, s[1]*tile_size+1), (tile_size-1, tile_size)))
            elif prev_pos[1] < s[1]:
                pygame.draw.rect(surface, (0,150,0), ((s[0]*tile_size+1, s[1]*tile_size), (tile_size-1, tile_size)))
        prev_pos = s
    pygame.draw.rect(surface, (150,0,0), ((food[0]*tile_size+1, food[1]*tile_size+1), (tile_size-1, tile_size-1)))

def update(snake, direction, sizex, sizey, food,m=True):
    if m:
        move(snake, direction)
    if snake[-1][0] == -1:
        return True
    if snake[-1][0] == sizex:
        return True
    if snake[-1][1] == -1:
        return True
    if snake[-1][1] == sizey:
        return True

    if snake.count(snake[-1]) != 1:
        return True
    if snake[-1] == food:
        return False
    return None

def new_food(snake, sizex, sizey):
    x, y = randint(0, sizex-1), randint(0, sizey-1)
    for i in range(20):
        if (x,y) not in snake:
            break
        x, y = randint(0, sizex-1), randint(0, sizey-1)
    return x,y

def game_loop():
    SCREEN = pygame.display.set_mode((800,600))

    direction = 0
    tile_size = 20
    sizex = SCREEN.get_width()//tile_size
    sizey = SCREEN.get_height()//tile_size
    snake = [(randint(0,sizex-5), randint(0,sizey-5))]

    food = new_food(snake, sizex, sizey)
    score = 0
    font = pygame.font.SysFont(None, 50)
    txt = font.render("0", True, (255,255,255))

    C = pygame.time.Clock()
    while True:
        SCREEN.fill((0,0,0))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return
                elif event.key == pygame.K_RIGHT:
                    direction = 1
                elif event.key == pygame.K_UP:
                    direction = 2
                elif event.key == pygame.K_DOWN:
                    direction = 0
                elif event.key == pygame.K_LEFT:
                    direction = 3

        a = update(snake, direction, sizex, sizey, food)
        if a:
            return
        elif a == False:
            snake.append(food)
            food = new_food(snake, sizex, sizey)
            score += 1
            txt = font.render(str(score), True, (255,255,255))
        draw(SCREEN, snake, tile_size, food)
        SCREEN.blit(txt, (sizex*tile_size-50,10))
        pygame.display.update()
        C.tick(10)

def generate_path(sizex, sizey):
    begin = (0,0)
    path = [begin]
    return path

def ia():
    SCREEN = pygame.display.set_mode((800,600))

    print(generate_path(20,20))

    direction = 0
    tile_size = 20
    sizex = SCREEN.get_width()//tile_size
    sizey = SCREEN.get_height()//tile_size
    snake = [(0,0) for i in range(1)]

    path = [(0,0)]

#     #sizex et sizey pairs
#     path.append((path[-1][0]+1, path[-1][1]))
#     path.append((path[-1][0], path[-1][1]+1))
#     for i in range((sizey//2)//2):
#         for x in range((sizex//2)-1):
#             path.append((path[-1][0]+1, path[-1][1]))
#             path.append((path[-1][0], path[-1][1]-1))
#             path.append((path[-1][0]+1, path[-1][1]))
#             path.append((path[-1][0], path[-1][1]+1))
#         for j in range(2):
#             path.append((path[-1][0], path[-1][1]+1))
#         for x in range((sizex//2)-1):
#             path.append((path[-1][0]-1, path[-1][1]))
#             path.append((path[-1][0], path[-1][1]-1))
#             path.append((path[-1][0]-1, path[-1][1]))
#             path.append((path[-1][0], path[-1][1]+1))
#         for j in range(2):
#             path.append((path[-1][0], path[-1][1]+1))
#     path.pop(len(path)-1)
#     path.pop(len(path)-1)
#     path.append((path[-1][0]-1, path[-1][1]))
#     for i in range(sizey-2):
#         path.append((0,sizey-2-i))
#         print(path[-1])

    for i in range(1,sizex):
        for j in range(0,sizey-1):
            if i % 2 == 0:
                path.append((i,sizey-j-2))
            else:
                path.append((i,j))
    for i in range(sizex):
        path.append((sizex-1-i,sizey-1))
    for i in range(sizey-2):
        path.append((0,sizey-2-i))

    step = 1

    food = new_food(snake, sizex, sizey)
    score = 0
    font = pygame.font.SysFont(None, 50)
    txt = font.render("0", True, (255,255,255))

    l = len(path)-1
    length = l+1
#     l = min(100, l)
    print(len(path),l)

    speed = 37464
    mode = True
    C = pygame.time.Clock()
    while True:
        SCREEN.fill((0,0,0))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return
                elif event.key == pygame.K_s:
                    mode = not mode
                    if speed == 37464:
                        speed = 20
                    else:
                        speed = 37464
#                 elif event.key == pygame.K_RIGHT:
#                     direction = 1
#                 elif event.key == pygame.K_UP:
#                     direction = 2
#                 elif event.key == pygame.K_DOWN:
#                     direction = 0
#                 elif event.key == pygame.K_LEFT:
#                     direction = 3

        snake.append(path[step])
        u = update(snake, direction, sizex, sizey, food,m=False)
        snake.pop(0)

        a,b = snake[-1]
        pos = None
        for i in range(l):
            x,y = path[(step+1+i)%length]
            if (x,y) in snake:
                break
            elif (x,y) == food:
                break
            if i > 0 and ((max(x,a)-min(x,a) == 1 and max(y,b)-min(y,b) == 0) or (max(x,a)-min(x,a) == 0 and max(y,b)-min(y,b) == 1)):
                for j in range(10):
                    if (path[(step+1+i+j)%length] in snake):
                        a = False
                if a:
                    pos = (step+i)%length#step = (step+i)%len(path)
                break
                #print((x,y),(a,b),food)
        if pos is not None:
            step = pos

        if u:
            return
        elif u == False:
            snake.insert(0, food)
            food = new_food(snake, sizex, sizey)
            score += 1
            txt = font.render(str(score), True, (255,255,255))
        if not mode or step%2==0:
            draw(SCREEN, snake, tile_size, food)
            SCREEN.blit(txt, (sizex*tile_size-50,10))
            pygame.display.update()
        C.tick(speed)
        step += 1
        step %= length

def main():
    SCREEN = pygame.display.set_mode((800,600))

    font = pygame.font.SysFont(None, 100)
    txt = font.render("Press a key ...", True, (255,255,255))

    x, y = SCREEN.get_rect().center
    w,h = txt.get_size()

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    quit()
                elif event.key == pygame.K_i:
                    ia()
                else:
                    game_loop()

        SCREEN.fill((0,0,0))
        SCREEN.blit(txt, (x-w/2, y-h/2))
        pygame.display.update()

if __name__ == "__main__":
    main()


import ROOT
import matplotlib.pyplot as plt
import numpy as np

# Αντικαταστήστε τα ακόλουθα μονοπάτια με τα δικά σας αρχεία
root_file_path1 = '0.913MeV_10^9_TiT_f=1_thin.root'
root_file_path2 = '0.913MeV_10^8_TiT_f=10_thin.root'
root_file_path3 = '0.913MeV_10^7_TiT_f=100_thin.root'
root_file_path4 = '0.913MeV_10^6_TiT_f=1000_thin.root'
root_file_path5 = '0.913MeV_10^5_TiT_f=10000_thin.root'

try:
    # Διάβασμα των 1D ιστογραμμάτων από τα αρχεία ROOT
    file1 = ROOT.TFile(root_file_path1)
    file2 = ROOT.TFile(root_file_path2)
    file3 = ROOT.TFile(root_file_path3)
    file4 = ROOT.TFile(root_file_path4)
    file5 = ROOT.TFile(root_file_path5)

    hist1 = file1.Get("Histo4")
    hist2 = file2.Get("Histo4")
    hist3 = file3.Get("Histo4")
    hist4 = file4.Get("Histo4")
    hist5 = file5.Get("Histo4")

    # Rebin:
    hist1.Rebin(128)
    hist2.Rebin(128)
    hist3.Rebin(128)
    hist4.Rebin(128)
    hist5.Rebin(128)

    energies1 = [hist1.GetBinCenter(i) for i in range(1, hist1.GetNbinsX() + 1)]
    energies2 = [hist2.GetBinCenter(i) for i in range(1, hist2.GetNbinsX() + 1)]
    energies3 = [hist3.GetBinCenter(i) for i in range(1, hist3.GetNbinsX() + 1)]
    energies4 = [hist4.GetBinCenter(i) for i in range(1, hist4.GetNbinsX() + 1)]
    energies5 = [hist5.GetBinCenter(i) for i in range(1, hist5.GetNbinsX() + 1)]

    counts1 = [hist1.GetBinContent(i) for i in range(1, hist1.GetNbinsX() + 1)]
    counts2 = [hist2.GetBinContent(i) for i in range(1, hist2.GetNbinsX() + 1)]
    counts3 = [hist3.GetBinContent(i) for i in range(1, hist3.GetNbinsX() + 1)]
    counts4 = [hist4.GetBinContent(i) for i in range(1, hist4.GetNbinsX() + 1)]
    counts5 = [hist5.GetBinContent(i) for i in range(1, hist5.GetNbinsX() + 1)]

    # Δημιουργία των κατάλληλων bins για τα ιστογράμματα
    bin_edges1 = np.linspace(min(energies1), max(energies1), len(energies1) + 1)
    bin_edges2 = np.linspace(min(energies2), max(energies2), len(energies2) + 1)
    bin_edges3 = np.linspace(min(energies3), max(energies3), len(energies3) + 1)
    bin_edges4 = np.linspace(min(energies4), max(energies4), len(energies4) + 1)
    bin_edges5 = np.linspace(min(energies5), max(energies5), len(energies5) + 1)

    # Δημιουργία του καμβά
    plt.figure(figsize=(15.2, 4.75))
    plt.subplot(1, 2, 1)
    plt.bar(energies1, counts1, width=np.diff(bin_edges1), align='edge',color="blue", edgecolor="black", alpha=0.40, label="Γεγονότα: 36264")
    plt.title(r"TiT, $E_{d}=0.91MeV$, $N_{d}=10^9$, $f_b=1$", fontsize=22)
    plt.xlabel("Βάθος στόχου [μm]", fontsize=22)
    plt.ylabel("Γεγονότα", fontsize=22)
    plt.legend(fontsize=22, handlelength=0)
    plt.xlim(0, 5)
    plt.ylim(bottom=0)
    plt.xticks(fontsize=18)
    plt.yticks(fontsize=18)
    plt.grid(True)

    plt.subplot(1, 2, 2)
    plt.bar(energies2, counts2, width=np.diff(bin_edges2), align='edge',color="blue", edgecolor="black", alpha=0.40, label="Γεγονότα: 36473")
    plt.title(r"TiT, $E_{d}=0.91MeV$, $N_{d}=10^8$, $f_b=10$", fontsize=22)
    plt.xlabel("Βάθος στόχου [μm]", fontsize=22)
    plt.ylabel("Γεγονότα", fontsize=22)
    plt.legend(fontsize=22, handlelength=0)
    plt.xlim(0, 5)
    plt.ylim(bottom=0)
    plt.xticks(fontsize=18)
    plt.yticks(fontsize=18)
    plt.grid(True)

    plt.tight_layout()
    plt.show()
    #--------------------------------------------------------------------------------

    plt.figure(figsize=(15.2, 4.75))
    plt.subplot(1, 2, 1)
    plt.bar(energies3, counts3, width=np.diff(bin_edges3), align='edge',color="blue", edgecolor="black", alpha=0.40, label="Γεγονότα: 36194")
    plt.title(r"TiT, $E_{d}=0.91MeV$, $N_{d}=10^7$, $f_b=100$", fontsize=22)
    plt.xlabel("Βάθος στόχου [μm]", fontsize=22)
    plt.ylabel("Γεγονότα", fontsize=22)
    plt.legend(fontsize=22, handlelength=0)
    plt.xlim(0, 5)
    plt.ylim(bottom=0)
    plt.xticks(fontsize=18)
    plt.yticks(fontsize=18)
    plt.grid(True)

    plt.subplot(1, 2, 2)
    plt.bar(energies4, counts4, width=np.diff(bin_edges4), align='edge',color="blue", edgecolor="black", alpha=0.40, label="Γεγονότα: 34318")
    plt.title(r"TiT, $E_{d}=0.91MeV$, $N_{d}=10^6$, $f_b=1000$", fontsize=22)
    plt.xlabel("Βάθος στόχου [μm]", fontsize=22)
    plt.ylabel("Γεγονότα", fontsize=22)
    plt.legend(fontsize=22, handlelength=0)
    plt.xlim(0, 5)
    plt.ylim(bottom=0)
    plt.xticks(fontsize=18)
    plt.yticks(fontsize=18)
    plt.grid(True)

    plt.tight_layout()
    plt.show()
    #----------------------------------------------------------------------------------

    # ΓΙΑ ΤΟΥΣ ΕΞΤΡΑ BIASING:
    # Δημιουργία του καμβά
    plt.figure(figsize=(15.2, 4.75))
    plt.subplot(1, 2, 1)
    plt.bar(energies5, counts5, width=np.diff(bin_edges5), align='edge',color="blue", edgecolor="black", alpha=0.40, label="Γεγονότα: 21536")
    plt.title(r"TiT, $E_{d}=0.91MeV$, $N_{d}=10^5$, $f_b=10000$", fontsize=22)
    plt.xlabel("Βάθος στόχου [μm]", fontsize=22)
    plt.ylabel("Γεγονότα", fontsize=22)
    plt.legend(fontsize=22, handlelength=0)
    plt.xlim(0, 5)
    plt.ylim(bottom=0)  # Ορίζουμε τον κατακόρυφο άξονα να ξεκινά από το 0.
    plt.xticks(fontsize=18)
    plt.yticks(fontsize=18)
    plt.grid(True)

    plt.tight_layout()
    plt.show()

    #RATIOS OF THE REGIONS A AND B:
    ratio_hist1 = hist1.Integral(0,7)   / hist1.Integral(8,15)
    ratio_hist2 = hist2.Integral(0,7)   / hist2.Integral(8,15)
    ratio_hist3 = hist3.Integral(0,14)  / hist3.Integral(15,22)
    ratio_hist4 = hist4.Integral(0,14)  / hist4.Integral(15,22)

    print(ratio_hist1)
    print(ratio_hist2)
    print(ratio_hist3)
    print(ratio_hist4)

except Exception as e:
    print(f'Προέκυψε σφάλμα: {e}')


import pygame
import sys
import os
from input_rect import InputRect
from button import Button
from world_screen import WorldScreen

class Menu:
    MENU_FONT = pygame.font.Font(None, 32)
    BACKGROUND = pygame.image.load(os.path.join('images/', 'background.png'))
    WIDTH, HEIGHT = 720, 720

    def __init__(self):
        self.screen = pygame.display.set_mode([self.WIDTH, self.HEIGHT])
        pygame.display.set_caption('Wirtualny Swiat')
        self.width_input = None
        self.height_input = None
        self.load_button = None
        self.button = None
        self.load_label = None
        self.load_file = "test.txt"

    def draw_menu(self):
        self.width_input = InputRect(32, (self.WIDTH / 2 - 70, 200, 300, 32), "20")
        self.height_input = InputRect(32, (self.WIDTH / 2 - 70, 300, 300, 32), "20")
        self.button = Button((self.WIDTH / 2 - 97, 380, 150, 50), (0, 0, 0), "NOWA GRA", 36)
        self.load_button = Button((self.WIDTH / 2 - 97, 450, 150, 50), (0, 0, 0), "  WCZYTAJ", 36)
        self.get_events()

    def draw_size_input_labels(self):
        self.height_input.draw_title_label(self.screen, "Podaj wysokosc planszy:", (0, 0, 0),
                                           pygame.font.Font(None, 25),
                                           (self.height_input.input_rect.x - 50, self.height_input.input_rect.y - 30))
        self.width_input.draw_title_label(self.screen, "Podaj szerokosc planszy:", (0, 0, 0),
                                          pygame.font.Font(None, 25),
                                          (self.width_input.input_rect.x - 50, self.width_input.input_rect.y - 30))

    def draw_file_input_labels(self):
        self.load_label.draw_title_label(self.screen, "Podaj nazwe pliku i zatwierdz przyciskiem 'ENTER'",
                                         (0, 0, 0), pygame.font.Font(None, 30),  (self.load_label.input_rect.x - 200, self.load_label.input_rect.y - 50))

    def update_world_size_input_hover(self):
        if self.width_input.is_active:
            self.width_input.color = self.width_input.color_active
        else:
            self.width_input.color = self.width_input.color_passive
        if self.height_input.is_active:
            self.height_input.color = self.height_input.color_active
        else:
            self.height_input.color = self.height_input.color_passive

    def update_file_input_hover(self):
        self.load_file = self.load_label.user_text
        if self.load_label.is_active:
            self.load_label.color = self.load_label.color_active
        else:
            self.load_label.color = self.load_label.color_passive

    def start_simulation(self):
        self.screen.fill((127, 127, 127))
        world = WorldScreen(int(self.width_input.user_text), int(self.height_input.user_text), self.screen)
        world.add_organisms()
        world.get_events()

    def load_simulation(self):
        self.screen.fill((127, 127, 127))
        with open(self.load_file, mode="r") as file:
            simulation_info = file.readline()
            simulation_info = simulation_info.split(";")
            simulation_info = simulation_info[:6]
            print(simulation_info)
            world = WorldScreen(int(simulation_info[0]), int(simulation_info[1]), self.screen)
            world.round_number = int(simulation_info[2])
            world.is_human_alive = bool(int(simulation_info[3]))
            world.is_human_ability_active = bool(int(simulation_info[4]))
            world.cooldown = int(simulation_info[5])
            print(world.is_human_alive)

            for line in file:
                line = line.split(";")
                line = line[:5]
                world.load_organism(line[0], int(line[1]), int(line[2]), int(line[3]), int(line[4]))

        world.get_events()

    def show_error_label(self):
        red_color = (255, 0, 0)
        text_surface = self.MENU_FONT.render("Wprowadz prawidlowe dane!", True, (255, 0, 0))
        self.screen.blit(text_surface, (self.button.surface.x - 100, self.button.surface.y - 50))

    def is_valid_world_size_input(self):
        try:
            int(self.width_input.user_text)
            int(self.height_input.user_text)
            if not 2 <= int(self.width_input.user_text) <= 30 or not 2 <= int(self.height_input.user_text) <= 30:
                return False
            else:
                return True
        except:
            return False

    def is_valid_load_file_input(self):
        if os.path.exists(self.load_file):
            return True
        return False

    def show_load_label(self):
        self.load_label = InputRect(40, (500 / 2 + 50, 300, 500, 40), "test.txt")
        self.load_label.is_active = True

    def get_events(self):
        clock = pygame.time.Clock()

        while True:
            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

                if event.type == pygame.MOUSEBUTTONDOWN:
                    if self.width_input.input_rect.collidepoint(event.pos):
                        self.width_input.is_active = True
                    else:
                        self.width_input.is_active = False

                    if self.height_input.input_rect.collidepoint(event.pos):
                        self.height_input.is_active = True
                    else:
                        self.height_input.is_active = False

                    if self.load_button.surface.collidepoint(event.pos):
                        self.show_load_label()

                    if self.button.surface.collidepoint(event.pos):
                        if self.is_valid_world_size_input():
                            self.start_simulation()

                if event.type == pygame.KEYDOWN:
                    if self.height_input.is_active:
                        if event.key == pygame.K_BACKSPACE:
                            self.height_input.user_text = self.height_input.user_text[:-1]
                        else:
                            self.height_input.user_text += event.unicode
                    elif self.width_input.is_active:
                        if event.key == pygame.K_BACKSPACE:
                            self.width_input.user_text = self.width_input.user_text[:-1]
                        else:
                            self.width_input.user_text += event.unicode
                    elif self.load_label.is_active:
                        if event.key == pygame.K_BACKSPACE:
                            self.load_label.user_text = self.load_label.user_text[:-1]
                        elif event.key == pygame.K_RETURN:
                            if self.is_valid_load_file_input():
                                print("ladujemy swiat")
                                self.load_simulation()

                        else:
                            self.load_label.user_text += event.unicode

            self.screen.fill((255, 255, 255))
            self.screen.blit(self.BACKGROUND, (0, 0))
            self.draw_size_input_labels()
            self.button.draw_button(self.screen)
            self.load_button.draw_button(self.screen)
            if not self.is_valid_world_size_input():
                self.show_error_label()

            self.update_world_size_input_hover()

            self.height_input.draw(self.screen)
            self.width_input.draw(self.screen)

            if self.load_label:
                self.screen.fill((127, 127, 127))
                self.draw_file_input_labels()
                self.load_label.draw(self.screen)
                self.update_file_input_hover()
            if self.load_label and not self.is_valid_load_file_input():

                self.show_error_label()
            pygame.display.flip()
            clock.tick(60)


import keras
from keras import layers
from keras import backend as K
import numpy as np

TRAIN_FILE = 'zip.train'
TEST_FILE = 'zip.test'

import numpy as np
X1 = np.loadtxt(TRAIN_FILE)
X2 = np.loadtxt(TEST_FILE)
X = np.vstack((X1, X2))

y = X[:, 0]
X = np.delete(X, 0, axis=1)

y[y != 1] = -1

from sklearn.decomposition import PCA
pca = PCA(n_components=2, svd_solver='full')
pca.fit(X)
X = pca.transform(X)

X = (X - np.min(X, axis = 0)) / (np.max(X, axis = 0) - np.min(X, axis = 0))

from sklearn.model_selection import train_test_split
X_test, X_train, y_test, y_train = train_test_split(X, y, test_size= 300 / X.shape[0])

model = keras.Sequential()
model.add(layers.Dense(10, activation= 'tanh'))
model.add(layers.Dense(1))

from keras.callbacks import EarlyStopping
es = EarlyStopping(monitor='val_loss', mode='min', verbose=1)
model.compile('adam', 'mean_squared_error')
history = model.fit(X_train, y_train, validation_split = 1/6, epochs = 10000, verbose=2, callbacks = [es])

preds = model.predict(X_test)
preds[preds > 0] = 1
preds[preds < 0] = -1
from sklearn.metrics import accuracy_score
print(1-accuracy_score(y_test, preds))

import matplotlib.pyplot as plt
plt.scatter(X[:, 0], X[:, 1], c = y)
x1, x2 = np.mgrid[-5:5:0.01, -5:5:0.01]
y_hat = model.predict(np.c_[x1.ravel(), x2.ravel()]).reshape((x1.shape[0], x2.shape[0]))
plt.contour(x1, x2, y_hat, [0])
plt.show()


import logging.config

logging.config.fileConfig("logging.ini", disable_existing_loggers=False)

log = logging.getLogger(__name__)

log.debug('DEBUG message')
log.info('INFO message')
log.warning('WARNING message')
log.error('ERROR message')
log.critical('CRITICAL message')


from app import ma

from app.models import *

from marshmallow import fields

class UserSchema(ma.TableSchema):
    class Meta:
        table = User.__table__

    #requests = fields.Nested('RequestSchema',  many=True, only=["id", "transactions", "other", "credit", "status"])
    #audits = fields.Nested('AuditLogSchema',  many=True, only=["id", "target_type", "target_id", "state_before", "state_after"])

class OtherSchema(ma.TableSchema):
    class Meta:
        table = Other.__table__

    requests = fields.Nested('RequestSchema',  many=True, only=["id", "user", "transactions", "credit", "status"])

class CatalogSchema(ma.TableSchema):
    class Meta:
        table = Catalog.__table__

class RequestResponseSchema(ma.TableSchema):
    class Meta:
        table = RequestResponse.__table__
    user = fields.Nested('UserSchema', only=["id", "email", "fullname", "role"])
    request = fields.Nested('RequestSchema', only=["id", "user", "other", "credit", "status"])

class RequestSchema(ma.TableSchema):
    class Meta:
        table = Request.__table__
    user_id = fields.Int()
    other_id = fields.Int()

    responses = fields.Nested("RequestResponseSchema", many=True, only=["id", "action", "comment", "user"])
    transactions = fields.Nested("TransactionSchema", many=True, only=["id", "stock", "amount"])
    user = fields.Nested('UserSchema', only=["id", "email", "fullname", "role"])
    other = fields.Nested('OtherSchema', only=["id", "fullname", "phone", "staff"])
    store = fields.Nested('StoreSchema')

class TransactionSchema(ma.TableSchema):
    class Meta:
        table = Transaction.__table__
    request_id = fields.Int()

    stock = fields.Nested('StockSchema', only=["id", "catalog", "amount", "store"])
    request = fields.Nested('RequestSchema', only=["id", "user", "other", "credit", "status"])
    store = fields.Nested('StoreSchema')

class StockReportSchema(ma.TableSchema):
    class Meta:
        table = StockReport.__table__
    stock_id = fields.Int()

class AuditLogSchema(ma.TableSchema):
    class Meta:
        table = AuditLog.__table__
    user_id = fields.Int()
    action = fields.String()

    user = fields.Nested('UserSchema', only=["id", "email", "fullname", "role"])

class StockSchema(ma.TableSchema):
    class Meta:
        table = Stock.__table__
    catalog_id = fields.Int()
    store_id = fields.Int()

    catalog = fields.Nested('StockSchema', only=["id", "name", "description", "unit"])
    store = fields.Nested('StoreSchema')

class StoreSchema(ma.TableSchema):
    class Meta:
        table = Store.__table__

class StoreTransferSchema(ma.TableSchema):
    class Meta:
        table = StoreTransfer.__table__

    sent_by = fields.Nested('UserSchema', only=["id", "email", "fullname", "role"])
    received_by = fields.Nested('UserSchema', only=["id", "email", "fullname", "role"])
    approved_by = fields.Nested('UserSchema', only=["id", "email", "fullname", "role"])

    from_store = fields.Nested('StoreSchema')
    to_store = fields.Nested('StoreSchema')

class TransferItemSchema(ma.TableSchema):
    class Meta:
        table = TransferItem.__table__

    store_transfer = fields.Nested('StoreTransferSchema')
    stock = fields.Nested('StockSchema', only=["id", "catalog", "amount", "store"])
    other_stock = fields.Nested('StockSchema', only=["id", "catalog", "amount", "store"])

class HoldItemSchema(ma.TableSchema):
    class Meta:
        table = HoldItem.__table__

    store = fields.Nested('StoreSchema')
    stock = fields.Nested('StockSchema', only=["id", "catalog", "amount"])


# csv_handler.py
import pandas as pd
import matplotlib.pyplot as plt
from .models import CsvData

def process_csv(file):
    pdf = pd.read_csv('media/'+file)
    # Save data to CsvData model
    avg_price_by_year = pdf.groupby('year')['price'].mean()

    # Create a line chart to visualize the average price by year
    plt.figure(figsize=(8, 6))
    plt.plot(avg_price_by_year.index, avg_price_by_year.values, marker='o', color='b', linestyle='-', linewidth=2, markersize=8)
    plt.title('Average Price by Year')
    plt.xlabel('Year')
    plt.ylabel('Average Price')
    plt.title('Price by Year')
    chart_path = 'media/sample_chart.png'  # Save the chart as an image
    plt.savefig(chart_path)
    plt.close()
    return chart_path