import os
import csv

# join paths
csvpath = os.path.join("resources", "budget_data.csv")

# set variables
counter = 0
net_profit = 0

# open/read csv
with open(csvpath, newline ="") as file_data:

# converting to readable data
    reader = csv.reader(file_data, delimiter=",")

# skip header row
    header = next(reader)

# create lists for storing profit and months
    p = []
    m = []

    for row in reader:
        counter = counter + 1
        net_profit = net_profit + int(row[1])
        p.append(int(row[1]))
        m.append(row[0])

    change = []

    for i in range(1, len(p)):
        change.append((int(p[i]) - int(p[i - 1])))

    average = sum(change) / len(change)

    increase = max(change)

    decrease = min(change)

    months = len(m)

    print("Analyis")
    print("........................................................")
    print("Total months: " + str(months))
    print("Total: $" + str(net_profit))
    print("Average change: $" + str(average))
    print("Greatest Increase in Profits: " + str(m[change.index(max(change))+1]) + " " + "$" + str(increase))
    print("Greatest Decrease in Profits: " + str(m[change.index(min(change))+1]))

file = open("exported_data.txt", "w")
file.write("Analyis")
file.write("\n--------------------------------------------------------------")
file.write("\nTotal months: " + str(months))
file.write("\nTotal: $" + str(net_profit))
file.write("\nAverage change: $" + str(average))
file.write("\nGreatest Increase in Profits: " + str(m[change.index(max(change))+1]) + " " + "$" + str(increase))
file.write("\nGreatest Decrease in Profits: " + str(m[change.index(min(change))+1]) + " " + "$" + str(decrease))
file.close()


import requests
import json
import random

URL = "http://localhost:5000"

r = requests.post(
    URL + "/new-move",
    data = {
        "round_id": 2,
        "user_id": 6,
        "content": "move: " + str(random.randrange(100,1000))
    })

print(r.json())


import os
import sys

import pytest

sys.path.append(os.path.realpath(os.path.dirname(__file__) + "../.."))
from send_email_function import main

@pytest.fixture
def mock_env(monkeypatch):
    """Setting mock environment variables"""
    monkeypatch.setenv("SIGNED_URL", "True")
    monkeypatch.setenv("FROM_EMAIL", "sender@gmail.com")
    monkeypatch.setenv("TO_EMAILS", "recepient@gmail.com")
    monkeypatch.setenv("EMAIL_SUBJECT", "BigQuery email export")
    monkeypatch.setenv("SENDGRID_API_KEY", "SG.key")
    monkeypatch.setenv("SIGNED_URL_EXPIRATION", "24")

def test_raise_exception():
    """Tests that KeyError exception is raised when no env vars are set"""
    with pytest.raises(KeyError):
        main.get_env('SIGNED_URL')

@pytest.mark.parametrize("test_input,expected",
                         [("SIGNED_URL", "True"),
                          ("FROM_EMAIL", "sender@gmail.com"),
                          ("TO_EMAILS", "recepient@gmail.com"),
                          ("EMAIL_SUBJECT", "BigQuery email export"),
                          ("SENDGRID_API_KEY", "SG.key"),
                          ("SIGNED_URL_EXPIRATION", "24")])
def test_get_env(mock_env, test_input, expected):
    """Tests reading of env vars"""
    assert main.get_env(test_input) == expected

@pytest.mark.parametrize(
    "test_input,expected",
    [("gs://bucket/object.txt",
      "https://storage.cloud.google.com/bucket/object.txt"),
     ("gs://bucket/dir/object.txt",
      "https://storage.cloud.google.com/bucket/dir/object.txt"),
     ("gs://bucket/dir/subdir/object.json",
      "https://storage.cloud.google.com/bucket/dir/subdir/object.json")])
def test_get_auth_url(test_input, expected):
    """Tests creation of authenticated GCS URL"""
    assert main.get_auth_url(test_input) == expected


import math

class Format:
    def __init__(self, number_of_decimal_places = 3, add_leading_zeros = 1, add_trailing_zeros = False, dp_wanted = True, add_plus = False, no_minus = False, round_down = False):
        self.number_of_decimal_places = number_of_decimal_places
        self.add_leading_zeros = add_leading_zeros # fill the start of the number with zeros, so there are at least this number of digits before the decimal point
        self.add_trailing_zeros = add_trailing_zeros # fill the end of the number with zeros, as defined by "number_of_decimal_places"
        self.dp_wanted = dp_wanted
        self.add_plus = add_plus
        self.no_minus = no_minus
        self.round_down = round_down

    def string(self, number):
        if number == None:
            return 'None'
        f = float(number) * math.pow(10, self.number_of_decimal_places)
        s = format(f, 'f')

        if self.round_down == False:
            if f < 0: f = f - .5
            else: f = f + .5
            s = format(float(number), 'f')

        if math.fabs(f) < 1.0:
            s = '0'

        minus = False
        if s[0] == '-':
            minus = True
            if self.no_minus:
                s = s[1:]

        dot = s.find('.')
        if dot == -1:
            before_dp = s
            after_dp = ''
        else:
            before_dp = s[0:dot]
            after_dp = s[dot + 1: dot + 1 + self.number_of_decimal_places]

        before_dp = before_dp.zfill(self.add_leading_zeros)
        if self.add_trailing_zeros:
            for i in range(0, self.number_of_decimal_places - len(after_dp)):
                after_dp += '0'
        else:
            after_dp = after_dp.rstrip('0')

        s = ''

        if minus == False:
            if self.add_plus == True:
                s += '+'
        s += before_dp
        if len(after_dp):
            if self.dp_wanted: s += '.'
            s += after_dp

        return s

class Address:
    def __init__(self, text, fmt = Format(), modal = True):
        self.text = text
        self.fmt = fmt
        self.modal = modal
        self.str = None
        self.previous = None

    def set(self, number):
        self.str = self.text + self.fmt.string(number)

    def write(self, writer):
        if self.str == None: return ''
        if self.modal:
            if self.str != self.previous:
                writer.write(writer.SPACE() + self.str)
                self.previous = self.str
        else:
            writer.write(writer.SPACE() + self.str)
        self.str = None

class AddressPlusMinus(Address):
    def __init__(self, text, fmt = Format(), modal = True):
        Address.__init__(self, text, fmt, modal)
        self.str2 = None
        self.previous2 = None

    def set(self, number, text_plus, text_minus):
        Address.set(self, number)
        if float(number) > 0.0:
            self.str2 = text_plus
        else:
            self.str2 = text_minus

    def write(self, writer):
        Address.write(self, writer)
        if self.str2 == None: return ''
        if self.modal:
            if self.str2 != self.previous2:
                writer.write(writer.SPACE() + self.str2)
                self.previous2 = self.str2
        else:
            writer.write(writer.SPACE() + self.str2)
        self.str2 = None


# Taking input from users
num1 = input ("Enter a number: ")
num2 = input ("Enter another number: ")

# Convert string input to int
n1 = int(num1)
n2 = int(num2)

#checking type
print(type(n1), type(n2))

#performing calculation
add=n1+n2
sub=n1-n2
div=n1/n2
mul=n1*n2

#Output
print("Sum of two numbers:", add, "\n" "Difference of two numbers:", sub, "\n"
	"Product of two numbers:", mul, "\n" "Division of two numbers:", div)


import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.layers import Conv2D, LeakyReLU, Flatten
from tensorflow.keras.layers import Dense, Conv2DTranspose
from tensorflow.keras.layers import Reshape, Activation
from tensorflow.keras import backend as K
from tensorflow.keras.callbacks import ModelCheckpoint

import os

# run params
SAVE_FOLDER = 'data'

if not os.path.exists(SAVE_FOLDER):
    os.mkdir(SAVE_FOLDER)
    os.mkdir(os.path.join(SAVE_FOLDER, 'weights'))

MODE =  'build' #'load' #
#MODE =  'load'

z_dim = 2

encoder_input = keras.Input(shape=(28, 28, 1), name='encoder_input')
x = Conv2D(32, 3, strides=1, padding="same", name='encoder_conv_0')(encoder_input)
x = LeakyReLU()(x)
x = Conv2D(64, 3, strides=2, padding="same", name='encoder_conv_1')(x)
x = LeakyReLU()(x)
x = Conv2D(64, 3, strides=2, padding="same", name='encoder_conv_2')(x)
x = LeakyReLU()(x)
x = Conv2D(64, 3, strides=1, padding="same", name='encoder_conv_3')(x)
x = LeakyReLU()(x)
shape_before_flattening = K.int_shape(x)[1:]
x = Flatten()(x)
encoder_output= Dense(z_dim, name='encoder_output')(x)
encoder = keras.Model(encoder_input, encoder_output, name='encoder')

decoder_input = keras.Input(shape=(z_dim,), name='decoder_input')
x = Dense(np.prod(shape_before_flattening))(decoder_input)
x = Reshape(shape_before_flattening)(x)
x = layers.Conv2DTranspose(64, 3, strides=1, padding="same", name='decoder_conv_t0')(x)
x = LeakyReLU()(x)
x = layers.Conv2DTranspose(64, 3, strides=2, padding="same", name='decoder_conv_t1')(x)
x = LeakyReLU()(x)
x = layers.Conv2DTranspose(32, 3, strides=2, padding="same", name='decoder_conv_t2')(x)
x = LeakyReLU()(x)
x = layers.Conv2DTranspose(1, 3, strides=1, padding="same", name='decoder_conv_t3')(x)
decoder_output = Activation('sigmoid')(x)
decoder = keras.Model(decoder_input, decoder_output, name="decoder")

class AutoEncoder(keras.Model):
    def __init__(self, encoder, decoder, **kwargs):
        super(AutoEncoder, self).__init__(**kwargs)
        self.encoder = encoder
        self.decoder = decoder
    def call(self,inputs):
        latent = self.encoder(inputs)
        return self.decoder(latent)

@tf.function
def r_loss(y_true, y_pred):
    return K.mean(K.square(y_true - y_pred), axis = [1,2,3])

LEARNING_RATE = 0.0005
BATCH_SIZE = 32
INITIAL_EPOCH = 0
EPOCHS = 10

save_folder = os.path.join(SAVE_FOLDER, 'weights')

ae = AutoEncoder(encoder, decoder)
ae.compile(optimizer=keras.optimizers.Adam(lr=LEARNING_RATE), loss=r_loss)

if MODE == 'build':
    x = np.random.rand(1,28,28,1)
    ae.predict(x)
    ae.save(save_folder)
else:
    #ae = keras.models.load_model(save_folder, custom_objects={'r_loss': r_loss})
    ae.load_weights(save_folder+'/'+'checkpoint')

# mnist 데이터 읽어오기
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
#mnist_digits = np.concatenate([x_train, x_test], axis=0)
#mnist_digits = x_train[:1000]
#print(mnist_digits.shape)
#print(mnist_digits.dtype)
# bad
#mnist_digits = np.expand_dims(mnist_digits, -1).astype("float32") / 255
# bad
#mnist_digits = np.expand_dims(mnist_digits, -1).astype("float64") / 255
#mnist_digits = mnist_digits/255.
#mnist_digits = np.expand_dims(mnist_digits, -1)
#mnist_digits = mnist_digits.reshape((-1, 28, 28, 1))
#print(mnist_digits.shape)
#print(mnist_digits.dtype)

print(x_train.shape)
print(x_train.dtype)
x_train = x_train/255.
x_test = x_test/255.
#x_train = x_train.reshape((60000, 28, 28, 1))
#x_train = x_train.reshape((-1, 28, 28, 1))
#x_train = x_train.reshape(x_train.shape+(1))
x_train = np.expand_dims(x_train, -1)
x_test = np.expand_dims(x_test, -1)
print(x_train.shape)
print(x_train.dtype)
import matplotlib.pyplot as plt
'''
plt.imshow(x_train[999].squeeze(), cmap='gray_r')
plt.colorbar()
plt.show()
plt.imshow(mnist_digits[999].squeeze(), cmap='gray_r')
plt.colorbar()
plt.show()
'''

# 매 epoch마다 모델 weights 저장
#lr_sched = step_decay_schedule(initial_lr=self.learning_rate, decay_factor=lr_decay, step_size=1)
#checkpoint = ModelCheckpoint(save_folder+'/'+'checkpoint', save_weights_only = False, verbose=1)
#callbacks_list = [checkpoint]

callbacks_list = []
ae.fit(x_train, x_train, epochs=EPOCHS, batch_size=BATCH_SIZE, callbacks=callbacks_list)
ae.save(save_folder)

import matplotlib.pyplot as plt
n_to_show = 10
example_idx = np.random.choice(range(len(x_test)), n_to_show)
example_images = x_test[example_idx]

z_points = ae.encoder.predict(example_images)

reconst_images = ae.decoder.predict(z_points)

fig = plt.figure(figsize=(15, 3))
fig.subplots_adjust(hspace=0.4, wspace=0.4)

for i in range(n_to_show):
    img = example_images[i].squeeze()
    ax = fig.add_subplot(2, n_to_show, i+1)
    ax.axis('off')
    ax.text(0.5, -0.35, str(np.round(z_points[i],1)), fontsize=10, ha='center', transform=ax.transAxes)
    ax.imshow(img, cmap='gray_r')

for i in range(n_to_show):
    img = reconst_images[i].squeeze()
    ax = fig.add_subplot(2, n_to_show, i+n_to_show+1)
    ax.axis('off')
    ax.imshow(img, cmap='binary')

plt.show()
'''
'''


def remove_even(lst):
    even_count = 0  # does not initilize another array
    for i in range(len(lst)):
        if lst[i] % 2 == 0:
            even_count += 1
        else:
            lst[i - even_count] = lst[i]
    return lst[0:len(lst)-even_count]

# can also use list comprehension but this allocates a new list but is nice

# return [number for number in lst if number % 2 != 0]

my_list = [1, 2, 4, 5, 10, 6, 3]  # my_list = [1,5,3]

print(remove_even(my_list))


class Solution:
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n < 1:
            return False
        while n > 1:
            if n % 3 != 0:
                return False
            n = n // 3
        return True

if __name__ == '__main__':
    solution = Solution()
    print(solution.isPowerOfThree(9))


from django.db import models
from mongoengine import connect,Document,StringField,DynamicField,DateTimeField
from cassandra.cqlengine import columns
from django_cassandra_engine.models import DjangoCassandraModel

connect(host="mongodb://192.168.57.119:27017/session")

class PgSession(models.Model):
    class Meta:
        db_table = 'session'
    token = models.CharField(max_length=512,primary_key=True)
    data = models.JSONField()
    expired_at = models.DateTimeField()

class MySession(models.Model):
    class Meta:
        db_table = 'my_session'

    token = models.CharField(max_length=512,primary_key=True)
    data = models.CharField(max_length=8192)
    expired_at = models.DateTimeField()

class MgSession(Document):
    token = StringField(primary_key=True)
    data = DynamicField()
    expired_at = DateTimeField()

class CaSession(DjangoCassandraModel):
    token = columns.Text(primary_key=True)
    data = columns.Text()
    expired_at = columns.DateTime()


"""
It is responsible for recommendation functionality, as also
providing the available filters that go along with the result

...

Methods
-------
get_documents(query_base_request, documents_deploy_request)
    Disables recommendation resource creation calls
"""
import cProfile
import pstats
import io
import os
import sys
import logging
from logging.handlers import TimedRotatingFileHandler
from time import perf_counter
from config import get_current_config

LEVEL = get_current_config().LOG_LEVEL

FORMATTER = logging.Formatter(
    "%(asctime)s - %(name)s - %(levelname)s - %(message)s")

def create_console_handler():
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setFormatter(FORMATTER)
    return console_handler

def create_file_handler(file_name: str):
    log_file_name = f'{file_name}.log'
    log_file_path = os.path.join(get_current_config().LOGS_PATH, log_file_name)

    try:
        file = open(log_file_path, 'r+')
    except FileNotFoundError:
        if not os.path.exists(os.path.join(get_current_config().LOGS_PATH)):
            os.makedirs(os.path.join(get_current_config().LOGS_PATH))
        file = open(log_file_path, 'w+')

    file.close()
    file_handler = TimedRotatingFileHandler(
        log_file_path, when='midnight', encoding='UTF-8')
    file_handler.setFormatter(FORMATTER)
    return file_handler

def get_logger(name='default', file_name='log'):
    log = logging.getLogger(name)
    log.setLevel(LEVEL)
    log.addHandler(create_console_handler())
    log.addHandler(create_file_handler(file_name))
    log.propagate = False
    return log

class Logger:
    def __init__(self):
        self.log = get_logger()
        self.__start = 0

    def info(self, msg):
        self.log.info(msg)

    def exception(self, error):
        self.log.exception(error)

class Chronometer:

    def __init__(self):
        self.__start = 0

    def start(self):
        self.__start = perf_counter()

    def end(self):
        result = perf_counter() - self.__start
        self.__start = 0
        return result

def profile(fnc):
    def inner(*arg, **kwargs):
        pr = cProfile.Profile()
        pr.enable()
        retval = fnc(*arg, **kwargs)
        pr.disable()
        s = io.StringIO()
        sortby = 'cumulative'
        ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
        ps.print_stats()
        log = get_logger()
        log.info(s.getvalue())
        return retval
    return inner

chrono = Chronometer()
logger = Logger()


deposit=input("item 1 price: ")
if float(deposit)>=50:
    Cost1=int(deposit)*0.12
    Item1=int(deposit)+Cost1
    print("the cost of item one is ${0:.2f}".format(Item1))
else:
    Cost1=int(deposit)*0.12
    Number1=int(deposit)+Cost1
    Final1=Number1+10
    print("The cost of item 1 including shipping is ${0:.2f}".format(Final1))


#coding:utf-8

from django.shortcuts import render
from django.shortcuts import render,HttpResponse
import json
from core import data_optimization
from core import data_processing
from monitor.chart_api import get_ladata_series_key_list
from monitor.controller.client_handler import ClientHandler
from django.views.decorators.csrf import csrf_exempt
from oms import settings
from cmdb import models
from utils import redis_conn
REDIS_OBJ = redis_conn.redis_conn(settings)

def client_configs(request,client_id):
    print("--->",client_id)
    config_obj = ClientHandler(client_id)
    config = config_obj.fetch_configs()

    if config:
        return HttpResponse(json.dumps(config))

def service_data_report(request):
    if request.method == 'POST':
        print("---->",request.POST)
        #REDIS_OBJ.set("test_alex",'hahaha')
        try:

            print('host=%s, service=%s' %(request.POST.get('client_id'),request.POST.get('service_name') ) )
            print
            data =  json.loads(request.POST['data'])
            #print(data)
            #StatusData_1_memory_latest
            client_id = request.POST.get('client_id')
            service_name = request.POST.get('service_name')
            data_saveing_obj = data_optimization.DataStore(client_id,service_name,data,REDIS_OBJ)

            #redis_key_format = "StatusData_%s_%s_latest" %(client_id,service_name)
            #data['report_time'] = time.time()
            #REDIS_OBJ.lpush(redis_key_format,json.dumps(data))

            #在这里同时触发监控
            host_obj = models.Server.objects.get(id=client_id)
            trigger_handler = data_processing.DataHandler(settings,REDIS_OBJ,host_obj)
            service_enable_triggers = trigger_handler.get_host_triggers()

            for trigger in service_enable_triggers:
                trigger_handler.load_service_data_and_calulating(trigger)
            print("service trigger::",service_enable_triggers)

        except IndexError as e:
            print('-->err:',e)

    return HttpResponse(json.dumps("---report success---"))

def display_chart(request):
    client_id = request.GET.get('client_id')
    server = models.Server.objects.get(id=client_id)
    templates = server.templates.select_related()
    templates_from_group = []
    for g in server.servergroup_set.all():
        templates_from_group.extend(g.templates.select_related())
    templates_from_group.extend(templates)

    services = []
    for t in  set(templates_from_group):
        services.extend(t.services.select_related())

    services = set(services)
    service_list = list(services)
    return render(request,'monitor/display_chart.html',{'server':server,'service_list':service_list})

@csrf_exempt
def get_latest(request):
    if request.method == 'GET':
        client_id = request.GET.get('client_id')
        service_name = request.GET.get('service_name')
        item_name = request.GET.get('item_name')
        data_type = request.GET.get('data_type')
        time_range = request.GET.get('time_range')
        if data_type == 'get_item_list':
            redis_key = "StatusData_%s_%s_%s" %(client_id,service_name,'latest')
            item_list = REDIS_OBJ.lrange(redis_key,-1,-1)

            return HttpResponse(json.dumps(json.loads(item_list[0])[0].keys()))
        elif data_type=='single_item_data':
            data_series_key_latest = "StatusData_%s_%s_%s" %(client_id,service_name,time_range)
            service_list = REDIS_OBJ.lrange(data_series_key_latest,0,-1)
            if time_range == 'latest':
                ret_list = []
                for i in service_list:
                    i = json.loads(i)
                    if i[0]:
                        ret_list.append([int(i[1]*1000),float(i[0][item_name])])
            else:
                ret_list = []
                for i in service_list:
                    i = json.loads(i)
                    if i[0]:
                        ret_list.append([int(i[1]*1000),float(i[0][item_name][0])])
            return HttpResponse(json.dumps(ret_list))
        elif data_type == 'get_latest_point':
            data_series_key_latest = "StatusData_%s_%s_%s" %(client_id,service_name,time_range)
            service_list = REDIS_OBJ.lrange(data_series_key_latest,-1,-1)
            if time_range == 'latest':
                ret_list = []
                for i in service_list:
                    i = json.loads(i)
                    if i[0]:
                        ret_list.append([int(i[1]*1000),float(i[0][item_name])])
            return HttpResponse(json.dumps(ret_list))

def monited_host(request):
    server_list = models.Server.objects.filter(templates=True)
    return render(request,'monitor/monited_host.html',{'server_list':server_list})

#def test(request):
#    add.delay(2, 2)
#    return HttpResponse('celery test')


from datetime import datetime

from mongoengine import (
    CASCADE,
    DateTimeField,
    DynamicField,
    EmbeddedDocument,
    EmbeddedDocumentListField,
    EnumField,
    GenericReferenceField,
    ListField,
    ReferenceField,
    StringField,
)

from core.audit.enum import ActivityTypesEnum
from core.auth.models.account import Account
from core.auth.models.role import Role
from core.auth.models.user import User
from core.basemodel import BaseModel

class DataRecord(EmbeddedDocument):
    field = StringField()
    old = DynamicField()
    new = DynamicField()

class Audit(BaseModel):
    meta = {
        "collection": "audits",
        "indexes": [
            {
                "fields": ["$message", "$source_user_agent", "$source_address"],
                "default_language": "english",
            }
        ],
    }
    created_by = ReferenceField(User, required=True, reverse_delete_rule=CASCADE)
    time = DateTimeField(default=datetime.utcnow)
    model = GenericReferenceField(
        choices=[User, Role, Account]
    )
    activity = EnumField(ActivityTypesEnum)
    model_name = StringField()
    source_address = StringField()
    source_user_agent = StringField()
    message = StringField()
    # the primitive parameters will be interpolated to the message directly as it is not
    # possible to define union types that might be scalar or object in GraphQL
    params = ListField(
        GenericReferenceField(
            choices=[User, Role, Account]
        )
    )
    data = EmbeddedDocumentListField(DataRecord)


import numpy as np
import cv2

#For more info about contours: https://docs.opencv.org/4.5.3/d3/d05/tutorial_py_table_of_contents_contours.html

im = np.zeros(shape =(400,400)).astype('uint8')
polygons = [np.array([[20,20],[120,50],[30,80]]),
            np.array([[200,200],[200,350],[350,350], [350,200] ]),
            np.array([[170, 350], [60, 170], [130, 140]])]
colors = [255,255,255]
cv2.fillPoly(im,polygons,colors)
im[250:340,250:340] = 0
im[270:300,290:320] = 255

contours,hierarchy = cv2.findContours(im, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
#try mode cv2.RETR_EXTERNAL and cv2.RETR_TREE
#try method cv2.CHAIN_APPROX_NONE and cv2.CHAIN_APPROX_SIMPLE

print('Types of contours:', type(contours))
print('Length of contours:', len(contours))

n = 0
print('Types of each contour:', type(contours[n]))
print('Shape of each contour:', contours[n].shape)
print('Each contour value (list of points):\n',contours[n])

out = np.zeros(shape =(400,400)).astype('uint8')
for pos in contours[n]:
    out[pos[0,1],pos[0,0]] = 255

#print('Hierarchy:\n', 'Left Right Child Parent\n', hierarchy)

cv2.imshow('im', im)
cv2.imshow('out', out)

cv2.waitKey()


def solution(numbers, hand):

    KEYPAD = {
        1:   (0, 0),   2: (0, 1), 3:   (0, 2),
        4:   (1, 0),   5: (1, 1), 6:   (1, 2),
        7:   (2, 0),   8: (2, 1), 9:   (2, 2),
        "*": (3, 0),   0: (3, 1), "#": (3, 2),
    }

    left, right, result = "*", "#",  ""

    for n in numbers:
        if n in {1, 4, 7}:
            result += "L"
            left = n
        elif n in {3, 6, 9}:
            result += "R"
            right = n
        else:
            (x1, y1), (x2, y2), (x3, y3) =\
                KEYPAD[left], KEYPAD[right], KEYPAD[n]
            left_distance = abs(x3-x1) + abs(y3-y1)
            right_distance = abs(x3-x2) + abs(y3-y2)

            result += "L"
            prev_left = left
            left = n
            if left_distance > right_distance or\
                    left_distance == right_distance and hand == "right":
                result = result[:-1] + "R"
                right = n
                left = prev_left
    return result

print(solution([1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5], "right"))
print(solution([7, 0, 8, 2, 8, 3, 1, 5, 7, 6, 2], "left"))
print(solution([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], "right"))


from torch.nn import Module
from torch import nn
import torch
# import model.transformer_base
import math
from model import GCN
import utils.util as util
import numpy as np
import torch.nn.functional as F

# torch.autograd.set_detect_anomaly(True)

#parameters

# input = 20
# input_attention = 40
# output_attention = 20
# key_frames = 10
# values_frames = 20
# query_frames = 10

class RNNAttModel(Module):

    def __init__(self, in_features=48, kernel_size=5, d_model=512, num_stage=2, dct_n=10):
        super(RNNAttModel, self).__init__()

        self.kernel_size = kernel_size
        self.d_model = d_model
        # self.seq_in = seq_in
        self.dct_n = dct_n
        # ks = int((kernel_size + 1) / 2)
        assert kernel_size == 10

        self.convQ = nn.Sequential(nn.Conv1d(in_channels=in_features, out_channels=d_model, kernel_size=6,
                                             bias=False),
                                   nn.ReLU(),
                                   nn.Conv1d(in_channels=d_model, out_channels=d_model, kernel_size=5,
                                             bias=False),
                                   nn.ReLU())

        self.convK = nn.Sequential(nn.Conv1d(in_channels=in_features, out_channels=d_model, kernel_size=6,
                                             bias=False),
                                   nn.ReLU(),
                                   nn.Conv1d(in_channels=d_model, out_channels=d_model, kernel_size=5,
                                             bias=False),
                                   nn.ReLU())

        self.gcn = GCN.GCN(input_feature=(dct_n) * 2, hidden_feature=d_model, p_dropout=0.3,
                           num_stage=num_stage,
                           node_n=in_features)

    def forward(self, src, memory, output_n=10, input_n=50, itera=1):
        """

        :param src: [batch_size,seq_len,feat_dim]
        :param output_n:
        :param input_n:
        :param frame_n:
        :param dct_n:
        :param itera:
        :return:
        """
        dct_n = self.dct_n #nb of dct components, here ? is the number of frames and 48 or 66 is the number of joints which is 16*3 or 22*3
        #src.shape = [32,?,66]
        src = src[:, :input_n]  # [bs,in_n=20,dim]
        input_sequence = src
        #input_sequence.shape = [32,N,66] = [32,in_n=20,66]
        bs = src.shape[0] #batch_size

        dct_m, idct_m = util.get_dct_matrix(self.kernel_size + output_n)
        dct_m = torch.from_numpy(dct_m).float().cuda()
        idct_m = torch.from_numpy(idct_m).float().cuda()
        #dct_m.shape = [M + T,M + T] = [20,20]

        #memory.shape = [32,20,66]
        past_memory1 = memory[:bs,:dct_n,:].clone()
        # past_memory2 = memory[:,dct_n:,:]
        #past_memory1.shape = [32,20,66]

        past_memory_idct = torch.matmul(idct_m[:, :dct_n].unsqueeze(dim=0),
                                        past_memory1)
        #past_memory_idct.shape = [32,20,66]

        # past_memory2_idct = torch.matmul(idct_m[:, :dct_n].unsqueeze(dim=0),
        #                                 past_memory2[:, :, :dct_n].transpose(1, 2))
        # past_memory = torch.cat([past_memory1_idct, past_memory2_idct], dim=2)
        #past_memory.shape = [32,66,40]

        attention_sequence = torch.cat([past_memory_idct, input_sequence], dim=1)        #attention_sequence.shape = [32,40,66]

        input_keys = attention_sequence.transpose(1, 2)
        #input_keys.shape = [32,66,50-T=40]

        concat_sequence = torch.cat([attention_sequence, input_sequence[:,10:,:]], dim=1)
        #concat_sequence.shape = [32,50,66]

        input_query = concat_sequence.transpose(1,2)[:, :, -self.kernel_size:]
        #input_query.shape = [32,66,M=10]

        vn = 50 - self.kernel_size - output_n + 1 #= N - T - M + 1 = 31, number of subsequences
        vl = self.kernel_size + output_n #= M + T = 20, length of each subsequence

        idx = np.expand_dims(np.arange(vl), axis=0) + \
              np.expand_dims(np.arange(vn), axis=1)

        values = concat_sequence[:, idx].reshape(
            [bs * vn, vl, -1])
        #concat_sequence[:, idx].shape = [32, 31, 20, 66]   #31 is the number of subsequences, 20 is the length of each subsequence
        #values.shape = [32*31, 20, 66] = [992, 20, 66]
        values_dct = torch.matmul(dct_m[:dct_n].clone().unsqueeze(dim=0), values).reshape(
            [bs, vn, dct_n, -1]).transpose(2, 3).reshape(
            [bs, vn, -1])
        #values_dct.shape = [32, vn, 66*20] = [32, 31, 1320]
        #the Values after being turned into dct components

        idx = list(range(-self.kernel_size, 0, 1)) + [-1] * output_n
        #idx is a list of 10 elements, each element is a number from -10 to -1 and then 10 times -1

        outputs = []

        keys = self.convK(input_keys / 1000.0).clone()
        #keys.shape = [32, 256, 31] 31 = N - M - T + 1 = 31, number of keys and values
        for i in range(itera):
            scaled_input_query = input_query / 1000.0
            query = self.convQ(scaled_input_query)
            #query.shape = [32,256,1]
            alignment_scores = torch.matmul(query.transpose(1, 2), keys) + 1e-15
            #alignment_scores.shape = [32,1,31]
            att_weights = alignment_scores / (torch.sum(alignment_scores, dim=2, keepdim=True))
            #att_weights.shape = [32,1,31]
            dct_att_output = torch.matmul(att_weights, values_dct)[:, 0].reshape(
                [bs, -1, dct_n])
            #torch.matmul(att_weights, values_dct).shape = [32, 1, 1320]
            #dct_att_output.shape = [32,66,20]
            if itera < 2 and memory.shape[0]==32:
                memory = dct_att_output.clone().transpose(1, 2).detach()
                #memory.shape = [32,20,66]
            input_gcn = input_sequence[:, idx] #the padded sequence of input frames
            #idx = [-T, ..., -4, -3, -2, -1, ..., -1]
            #input_gcn.shape = [32, M+T, 66] = [32, 20, 66]
            dct_input_gcn = torch.matmul(dct_m[:dct_n].unsqueeze(dim=0), input_gcn).transpose(1, 2) #convert input to dct components
            #dct_input_gcn.shape = [32,66,20]
            dct_input_gcn_concat = torch.cat([dct_input_gcn, dct_att_output], dim=-1) #concatenate the input and the values weighted by attention
            #dct_input_gcn_concat.shape = [32,66,40]
            dct_out_gcn = self.gcn(dct_input_gcn_concat)
            #dct_out_gcn.shape = [32,66,40]
            out_gcn = torch.matmul(idct_m[:, :dct_n].unsqueeze(dim=0),
                                   dct_out_gcn[:, :, :dct_n].transpose(1, 2)) #convert back to 3D coordinates (from frequency domain to space domain)
            #out_gcn.shape = [32,20,66]
            outputs.append(out_gcn.unsqueeze(2))
            if itera > 1:
                # update key-value query
                pred = out_gcn.clone()[:, 0 - output_n:] #the ten predicted frames
                #pred.shape = [32,T,66] = [32,10,66]
                attention_sequence = torch.cat([attention_sequence, pred], dim=1) #the whole sequence is updated with the predicted frames
                #attention_sequence.shape = [32,N + T,66] = [32,60,66]

                vn = 1 - 2 * self.kernel_size - output_n #= 1 - 2*M - T = 1 - 2*10 - 10 = -29
                #I think it should be:
                #vn = 1 - self.kernel_size - output_n
                vl = self.kernel_size + output_n #= M + T = 20

                idx_dct = np.expand_dims(np.arange(vl), axis=0) + \
                          np.expand_dims(np.arange(vn, -self.kernel_size - output_n + 1), axis=1)
                #idx_dct = np.expand_dims(np.arange(vl), axis=0) + \
                  #         np.expand_dims(np.arange(vn, - output_n + 1), axis=1)
                #idx_dct.shape = [10,20]

                new_input_keys = attention_sequence[:, idx_dct[0, :-1]].transpose(1, 2)
                #new_input_keys.shape = [32, 66, 19] 19 because after convK 19 -> 10 and the new N is N+10 so we want ten new keys (altough I don't agree with the way he chose the keys)

                new_keys = self.convK(new_input_keys / 1000.0).clone()
                #new_keys.shape = [32, 256, 10]
                #keys.shape = [32, 256, 31+(itera-1)*10]
                keys = torch.cat([keys, new_keys], dim=2)
                #keys.shape = [32, 256, 31+(itera)*10] these are the keys for the next iteration

                new_values = attention_sequence[:, idx_dct].clone().reshape(
                    [bs * self.kernel_size, vl, -1])
                new_values_dct = torch.matmul(dct_m[:dct_n].unsqueeze(dim=0), new_values).reshape(
                    [bs, self.kernel_size, dct_n, -1]).transpose(2, 3).reshape(
                    [bs, self.kernel_size, -1])
                values_dct = torch.cat([values_dct, new_values_dct], dim=1)
                #these are the values for the next iteration

                input_query = attention_sequence[:, -self.kernel_size:].transpose(1, 2)
                #this is the query for the next iteration, just the ten last frames

        outputs = torch.cat(outputs, dim=2)
        #outputs.shape = [32,20,itera=3,66]
        return outputs, memory


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

from sha import sha
from bencode import bencode, bdecode
from random import randint
def pieceGen(request):
        print('pieces: ', request)
        length = request[9:]
        print(length)
        count = 0
        for i in range(4):
            count <<= 8
            count += ord(length[i])
        print(count)
        data = ''
        for i in range(count):
            data += chr(randint(1, 255))
        data = '\x07' + request[1:9] + data
        count += 9
        length = ''
        for i in range(4):
            length = chr(count & 0xff) + length
            count >>= 8
        data = length + data
        return data

piece = '\x06\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00@\x00'

print(pieceGen(piece))


import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# file list
fileList = {
    "i_70_72": "CRD_scripts/files_for_python/70_72.ALLchr.module.merged.intersect.bed",
    "i_70_73": "CRD_scripts/files_for_python/70_73.ALLchr.module.merged.intersect.bed",
    "i_72_73": "CRD_scripts/files_for_python/72_73.ALLchr.module.merged.intersect.bed",
    "i_70_72_73": "CRD_scripts/files_for_python/70_72_73.ALLchr.module.merged.intersect.bed",

    "m_70": "CRD_scripts/files_for_python/EGAD00001002670.ALLchr.module.merged.bed",
    "m_72": "CRD_scripts/files_for_python/EGAD00001002672.ALLchr.module.merged.bed",
    "m_73": "CRD_scripts/files_for_python/EGAD00001002673.ALLchr.module.merged.bed"
}
# get nbr of bp per file and append in total_ bp
total_bp = pd.DataFrame(columns=['file', 'total_bp'])
T = {}
for file, filename in fileList.items():
    print(file)
    data = pd.read_csv(filename, sep="\t", header=None)
    data["bp"] = data[2] - data[1]
    total_bp_file = data["bp"].sum(axis=0)
    total_bp = total_bp.append({'file': file, 'total_bp': total_bp_file}, ignore_index=True)
    T[file] = total_bp_file

# matrix of overlap

overlap_array = ([[[1, T['i_70_72'] / T['m_70'], T['i_70_73'] / T['m_70']],
                   [T['i_70_72'] / T['m_72'], 1, T['i_72_73'] / T['m_72']],
                   [T['i_70_73'] / T['m_73'], T['i_72_73'] / T['m_73'], 1]]])

overlap_array = np.around(overlap_array, decimals=2)

# sns.heatmap(overlap_array)
# add empty diag and names and axes and title and round and size of rounds)

sns.set()
uniform_data = np.random.rand(3,3)
#ax = sns.heatmap(uniform_data, vmin=0, vmax=1,xticklabels=['NEUT','MONO','TCELL'], yticklabels=['NEUT','MONO','T-CELL'] )

ax = sns.heatmap(uniform_data, rasterized=False, annot=True, cmap="Blues", linewidths=4)
ax.set(xlabel='Query', ylabel='Reference', title='CRD Tissue Sharing')
plt.show()


print("Numero decimale")
decimale = int(input())
cifre = []
binario = ""
quoziente = decimale
if quoziente != 0:
    while quoziente != 0:
        resto = quoziente%2
        quoziente = int(quoziente/2)
        cifre.append(resto)
    cifre.reverse()
    for i in cifre:
        binario = binario + str(i)
else:
    binario = 0
print('Metodo Malavasi:',binario)
print("Metodo python:  ", bin(int(decimale))[2:])


import numpy as np
import matplotlib.pyplot as plt

def tanh_test(x, x0, L):
    return np.tanh((x-x0)/L)

if __name__ == "__main__":
    x = np.linspace(0, 10, 1000)
    LL = [0.01, 0.05, 0.1, 1]
    x0 = 5
    for L in LL:
        y = tanh_test(x, x0, L)
        plt.plot(x, y, label=f"L={L}")
    plt.legend()
    plt.show()


from django.conf.urls import url

from . import views

app_name = 'vjk'
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^student-intake', views.student_form, name='studentform'),
    url(r'^success', views.success, name='success')
]


a=list()
for i in range(3,361):
     b=180-(360/i)
     a.append(b)
c=int(input())
for j in range(0,c):
     d=float(input())
     if d in a:
          print("YES")
     else:
          print("NO")


#!/usr/bin/python3

import pygame
from pygame.locals import *

####################### Paramètres du jeu ##########################

title  = "Zelda Laby"
image_icone = "images/link_right.gif"
image_intro = "images/intro.jpg"
image_back = "images/back.jpg"
image_wall = "images/wall.gif"
image_start = "images/thumb_Hole.gif"
image_triforce = "images/triforce.gif"

nb_sprite = 15
sprite_size = 30
window_size = nb_sprite * sprite_size

####################### Classes du jeu #############################

class Map:
	def __init__(self, file):
		self.file = file
		self.structure = 0

	def create(self):
		with open(self.file, "r") as file:
			structure_map = []
			for line in file:
				map_line = []
				for sprite in line:
						map_line.append(sprite)
				structure_map.append(map_line)
			self.structure = structure_map

	def show(self, window):
		wall = pygame.image.load(image_wall).convert()
		start = pygame.image.load(image_start).convert()
		triforce = pygame.image.load(image_triforce).convert_alpha()

		nb_line = 0
		for line in self.structure:
			nb_pos = 0
			for sprite in line:
				x = nb_pos * sprite_size
				y = nb_line * sprite_size
				if sprite == 'W':
					window.blit(wall, (x,y))
				elif sprite == 'L':
					window.blit(start, (x,y))
				elif sprite == 'T':
					window.blit(triforce, (x,y))
				nb_pos = nb_pos + 1
			nb_line = nb_line + 1

class Perso:
	def __init__(self, right, left, up, down, map):
		self.right = pygame.image.load(right).convert_alpha()
		self.left = pygame.image.load(left).convert_alpha()
		self.up = pygame.image.load(up).convert_alpha()
		self.down = pygame.image.load(down).convert_alpha()

		self.case_x = 0
		self.case_y = 0
		self.x = 0
		self.y = 0

		self.direction = self.right
		self.map = map

	def move(self, direction):
		if direction == 'right':
			if self.case_x < (nb_sprite - 1):
				if self.map.structure[self.case_y][self.case_x+1] != 'W':
					self.case_x += 1
					self.x = self.case_x * sprite_size
			self.direction = self.right

		if direction == 'left':
			if self.case_x > 0:
				if self.map.structure[self.case_y][self.case_x-1] != 'W':
					self.case_x -= 1
					self.x = self.case_x * sprite_size
			self.direction = self.left

		if direction == 'up':
			if self.case_y > 0:
				if self.map.structure[self.case_y-1][self.case_x] != 'W':
					self.case_y -= 1
					self.y = self.case_y * sprite_size
			self.direction = self.up

		if direction == 'down':
			if self.case_y < (nb_sprite - 1):
				if self.map.structure[self.case_y+1][self.case_x] != 'W':
					self.case_y += 1
					self.y = self.case_y * sprite_size
			self.direction = self.down

################################## Début du jeu ################################

pygame.init()

window = pygame.display.set_mode((window_size, window_size))
icone = pygame.image.load(image_icone)
pygame.display.set_icon(icone)
pygame.display.set_caption(title)

loop = 1
while loop:
	intro = pygame.image.load(image_intro).convert()
	window.blit(intro, (0,0))

	pygame.display.flip()

	loop_intro = 1
	loop_game = 1

	while loop_intro:
		for event in pygame.event.get():
			if event.type == QUIT or event.type == KEYDOWN and event.key == K_ESCAPE:
				loop_intro = 0
				loop_game = 0
				loop = 0
				load_map = 0
			elif event.type == KEYDOWN:
                                if event.key == K_RETURN:
                                        loop_intro = 0
                                        load_map = 'LinkToThePast'

	if load_map != 0:
		back = pygame.image.load(image_back).convert()
		map = Map(load_map)
		map.create()
		map.show(window)
		link = Perso("images/link_right.gif", "images/link_left.gif",
		           "images/link_up.gif", "images/link_down.gif", map)

	while loop_game:
		for event in pygame.event.get():
			if event.type == QUIT:
				loop_game = 0
				loop = 0
			elif event.type == KEYDOWN:
				if event.key == K_ESCAPE:
					loop_game = 0
				elif event.key == K_RIGHT:
					link.move('right')
				elif event.key == K_LEFT:
					link.move('left')
				elif event.key == K_UP:
					link.move('up')
				elif event.key == K_DOWN:
					link.move('down')

		window.blit(back, (0,0))
		map.show(window)
		window.blit(link.direction, (link.x, link.y))
		pygame.display.flip()

		if map.structure[link.case_y][link.case_x] == 'T':
		        loop_game = 0


from django.shortcuts import render
from .forms import StudentForm
from .models import Studentmodel
from django.http import JsonResponse
# Create your views here.

def home(request):
    # if request.method == 'POST':
    form = StudentForm(request.POST)
    stud = Studentmodel.objects.all()
    return render (request,'enroll/home.html',{'form':form,'stud':stud})

def save_data(request):
    if request.method == 'POST':
        form = StudentForm(request.POST)
        if form.is_valid():
            sid = request.POST.get('stuid')
            name = request.POST['name']
            email = request.POST['email']
            desc = request.POST['desc']
            if(sid == ''):
                usr = Studentmodel(name=name , email = email , desc= desc)
            else:
                usr = Studentmodel(id =sid,name=name , email = email , desc= desc)
            usr.save()
            stud = Studentmodel.objects.values()
            # print(stud)
            student_data = list(stud)
            print(student_data)
            return JsonResponse({'status':'save','student_data':student_data})
        else:
            return JsonResponse({'status':0})

def delete_data(request):
    if request.method == 'POST':
        id = request.POST.get('sid')
        print(id)
        pi = Studentmodel.objects.get(pk=id)
        pi.delete()
        return JsonResponse({'status':1})
    else:
        return JsonResponse({'status':0})

def edit_data(request):
    if request.method == 'POST':
        id = request.POST.get('sid')
        print(id)
        student = Studentmodel.objects.get(pk=id)
        student_data = {'id':student.id,'name':student.name,'email':student.email,'desc':student.desc}
        return JsonResponse(student_data)


import os
import sys
import csv
import time
import operator

#Author: NRoot
#Purpose: for splitting up large UNSORTED CSV files based on a category.
#		For instance, if working with a file containing data on an entire state
#		you can run the data through this program and split it up based on county,
#		assuming you know which column that information is stored.
#
#Python version: 3.6
#
#How to run: if you have python 3 installed, you should be able to simply double click
#the file and the program prompts should initiate.
#
#Run time: When run on 4.5 GB CSV, splitting into about 20 or so files, program execution took around 15-20 minutes.
#
#Used code by jrivero at https://gist.github.com/jrivero/1085501 as initial reference material who in turn was based off of
#palewire's https://gist.github.com/palewire/596056/0f58641aba18979e9d5c1b918aeca623487fb599
#
#Date modified: July 2, 2019

def main():
	#Main provides the user interaction portion of the program and hands off data to the splitter function
	print(" ")
	print("Hello! I am going to sort your large CSV file into smaller individual CSV files. What is the file path?")
	print("[type \"exit\" to exit]")
	filepath = input("Filepath: ")
	if filepath == "exit":
		print("Exiting")
		time.sleep(.5)
		exit()
	print("Looking for your file now")

	#this section checks whether or not the user provided an actual file path
	inputType = whatismypath(filepath)
	if inputType == "dir":
		print("You entered a directory path, not a filepath.")
		time.sleep(2)
		main()
	elif inputType == "file":
		fNcomponents = str(filepath).split(".")
		if fNcomponents[len(fNcomponents)-1] !="csv":
			print("I cannot operate on a non-csv file. Please either double check the file path, convert the file to csv, OR modify this program to cope with non-csv file formats")
			print("You gave me a "+str(fNcomponents[len(fNcomponents)-1]))
			main()

		curDir =str(filepath[0:filepath.rfind("\\")])
		os.chdir(curDir)
		try:
			#creates a temporary directory to store split files
			os.mkdir("tempForSort")
		except:
			print("Tried to create a temporary directory and failed. A directory named tempForSort already exists in the same directory as the file you chose. Please delete or rename that directory and try again.")
			exit()

		#request user provide the column that will determine what to split the csv files up by
		sortColumn = input("\nFile Located! \nWhat Column would you like the data split up by? Enter any whole number 1 through the number of columns in the file to indicate the column. \nColumn Number: ")

		if sortColumn == "exit":
			#allow for user to exit using exit
			print("Exiting")
			time.sleep(.5)
			exit()
		else:
			#check that user provided an integer, then round and make sure that integer is positive
			try:
				sortColumn = abs(round(int(sortColumn)))-1
			except:
				print("User did not supply a valid input for the column number. System will now exit. Reload and try again.")
				time.sleep(4)
				exit()

		#call the splitter function
		filelist = splitter(filepath, str(curDir + "\\tempForSort"), ',',True, sortColumn)
		print("\n\nSplitting complete, the following files have been generated:")
		filelist = sorted(filelist)
		for fil in filelist:
			print(str(fil))
		t = input("\nHit enter to end program")

	elif inputType == "err":
		print("File Not Found")
		print("User wrote: " + str(filepath))
		time.sleep(2)
		main()

def splitter(filepath, output_path, delim=',', useHeaders = True, splitbycol = 0):
	#take a filepath, optional delimiter, output path,
	#whether to retain headers, and which column to split by (defaults to first)
	#Split it into different files based on the column identified.

	with open(filepath, 'r') as source:
		reader = csv.reader(source, delimiter=delim)
		header_row = next(reader)
		#creates the first file based on the first category in the column (e.g.
		#by county or by icecream flavor)
		current_category = "Unnamed"
		#checkExisting is used to keep track of which files have been created
		checkExisting=[]
		#start is used to check if the program is creating its first file
		start = 1
		for i, row in enumerate(reader):

			current_category = str(row[splitbycol])

			if start ==1:
				currentOutPath = output_path + "\\" + str(current_category) + ".csv"
				currentOutWrite = csv.writer(open(currentOutPath,'w',newline=''), delimiter = delim)
				start = 0
				checkExisting.append(current_category)
				if useHeaders:
					currentOutWrite.writerow(header_row)
					print("")
					print("")
					print("Creating: " + str(current_category) +".csv")

			elif current_category != prev_category:
				if current_category in checkExisting:
					#if the category is included in checkExisting, that means the file for this category already exists.
					#open the file in append mode and notify CMD what is being worked on
					currentOutPath = output_path + "\\" + str(current_category) + ".csv"
					currentOutWrite = csv.writer(open(currentOutPath,'a',newline=''), delimiter = delim)
					print("")
					print("")
					print("Now working on: " + str(current_category) +".csv")
				else:
					#if the category is not in checkExisting, then a new file needs to be opened in write mode
					#Determine if headers should be included
					#add the category to checkExisting
					currentOutPath = output_path + "\\" + str(current_category) + ".csv"
					currentOutWrite = csv.writer(open(currentOutPath,'w',newline=''), delimiter = delim)
					checkExisting.append(current_category)
					if useHeaders:
						currentOutWrite.writerow(header_row)
						print("")
						print("")
						print("Creating: " + str(current_category) +".csv")

			currentOutWrite.writerow(row)
			#status indicator, simply prints periods to the prompt screen to show that the program is working
			if i%800 == 0:
				print("    ",end ="\r", flush = True)
				print("    ",end ="\r", flush = True)
			elif i%200 == 0:
				print(".", end ="", flush = True)

			i += 1
			prev_category = current_category

	source.close()
	return checkExisting

def whatismypath(dirfilepath):
	# given a string representing a path, function returns
	# a str "dir" if directory
	# a str "file" if a file
	# and a str "err" if neither

	if os.path.isdir(dirfilepath) == True:
		return "dir"
	elif os.path.isfile(dirfilepath) == True:
		return "file"
	else:
		return "err"

#what to do when the program is initiated
main()


"""
A school is trying to take an annual photo of all the students. The students are asked to stand in a single file
line in non-decreasing order by height. Let this ordering be represented by the integer array expected where
expected[i] is the expected height of the ith student in line.

You are given an integer array heights representing the current order that the students
are standing in. Each heights[i] is the height of the ith student in line (0-indexed).

Return the number of indices where heights[i] != expected[i].
"""
from typing import List

def height_checker(heights: List[int]) -> int:
    not_in_order = 0
    sorted_height = sorted(heights)
    for i, j in zip(heights, sorted_height):
        if i != j:
            not_in_order += 1
    return not_in_order

if __name__ == '__main__':
    li_heights = [1, 2, 3, 4, 5]
    print(height_checker(li_heights))


from typing import Any
import eel
from electionguard_gui.eel_utils import eel_success
from electionguard_gui.components.component_base import ComponentBase
from electionguard_gui.services import (
    DecryptionService,
    ElectionService,
)
from electionguard_gui.services.plaintext_ballot_service import (
    get_plaintext_ballot_report,
)

class ViewTallyComponent(ComponentBase):
    """Responsible for functionality related to viewing a tally"""

    _decryption_service: DecryptionService
    _election_service: ElectionService

    def __init__(
        self, decryption_service: DecryptionService, election_service: ElectionService
    ) -> None:
        self._decryption_service = decryption_service
        self._election_service = election_service

    def expose(self) -> None:
        eel.expose(self.get_tally)

    def get_tally(self, decryption_id: str) -> dict[str, Any]:
        try:
            db = self._db_service.get_db()
            self._log.debug(f"retrieving decryption '{decryption_id}'")
            decryption = self._decryption_service.get(db, decryption_id)
            election = self._election_service.get(db, decryption.election_id)
            plaintext_tally = decryption.get_plaintext_tally()
            tally_report = get_plaintext_ballot_report(election, plaintext_tally)
            result = {
                "election_id": election.id,
                "election_name": election.election_name,
                "decryption_name": decryption.decryption_name,
                "report": tally_report,
            }
            return eel_success(result)
        # pylint: disable=broad-except
        except Exception as e:
            return self.handle_error(e)


from pathlib import Path
import sys

raw_data_folder = Path("W:\\swc\\branco\\Federico\\Locomotion\\raw")
local_raw_recordings_folder = Path(r"D:\recordings")
# ccm_matrices = Path(r"W:\swc\branco\Federico\Locomotion\raw\CMM_matrices")
ccm_matrices = Path(r"K:\CMM_matrices")

processed_tracking = Path(
    r"W:\swc\branco\Federico\Locomotion\processed\tracking"
)

probes_surgeries_metadata = Path(
    r"D:\Dropbox (UCL)\Rotation_vte\Locomotion\recordings_surgery_metadata.ods"
)

if sys.platform == "win32":
    analysis_folder = Path(
        r"D:\Dropbox (UCL)\Rotation_vte\Locomotion\analysis"
    )
else:
    analysis_folder = Path(
        "/Users/federicoclaudi/Dropbox (UCL)/Rotation_vte/Locomotion/analysis"
    )


#!/usr/bin/env python3
from __future__ import print_function

# Copyright (C) 2015 Vibhav Pant <vibhavp@gmail.com>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import json
import os
import shutil
from sys import stderr
import argparse

# Fix Python 2.x.
try: input = raw_input
except NameError: pass

def ask_user(prompt):
    valid = {"yes":True, 'y':True, '':True, "no":False, 'n':False}
    while True:
        print("{0} ".format(prompt),end="")
        choice = input().lower()
        if choice in valid:
            return valid[choice]
        else:
            print("Enter a correct choice.", file=stderr)

def create_directory(path):
    exp = os.path.expanduser(path)
    if (not os.path.isdir(exp)):
        print("{0} doesnt exist, creating.".format(exp))
        os.makedirs(exp)

def create_symlink(src, dest, replace):
    dest = os.path.expanduser(dest)
    src = os.path.abspath(src)
    broken_symlink = os.path.lexists(dest) and not os.path.exists(dest)
    if os.path.lexists(dest):
        if os.path.islink(dest) and os.readlink(dest) == src:
            print("Skipping existing {0} -> {1}".format(dest, src))
            return
        elif replace or ask_user("{0} exists, delete it? [Y/n]".format(dest)):
            if os.path.isfile(dest) or broken_symlink or os.path.islink(dest):
                os.remove(dest)
            else:
                shutil.rmtree(dest)
        else:
            return
    print("Linking {0} -> {1}".format(dest, src))
    try:
        os.symlink(src, dest)
    except AttributeError:
        import ctypes
        symlink = ctypes.windll.kernel32.CreateSymbolicLinkW
        symlink.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)
        symlink.restype = ctypes.c_ubyte
        flags = 1 if os.path.isdir(src) else 0
        symlink(dest, src, flags)

def copy_path(src, dest):
    dest = os.path.expanduser(dest)
    src = os.path.abspath(src)
    if os.path.exists(dest):
        if ask_user("{0} exists, delete it? [Y/n]".format(dest)):
            if os.path.isfile(dest) or os.path.islink(dest):
                os.remove(dest)
            else:
                shutil.rmtree(dest)
        else:
            return
    print("Copying {0} -> {1}".format(src, dest))
    if os.path.isfile(src):
        shutil.copy(src, dest)
    else:
        shutil.copytree(src, dest)

def run_command(command):
    os.system(command)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("config", help="the JSON file you want to use")
    parser.add_argument("-r", "--replace", action="store_true",
                        help="replace files/folders if they already exist")
    args = parser.parse_args()
    js = json.load(open(args.config))
    os.chdir(os.path.expanduser(os.path.abspath(os.path.dirname(args.config))))

    if 'directories' in js: [create_directory(path) for path in js['directories']]
    if 'link' in js: [create_symlink(src, dst, args.replace) for src, dst in js['link'].items()]
    if 'copy' in js: [copy_path(src, dst) for src, dst in js['copy'].items()]
    if 'install' in js and 'install_cmd' in js:
        packages = ' '.join(js['install'])
        run_command("{0} {1}".format(js['install_cmd'], packages))
    if 'commands' in js: [run_command(command) for command in js['commands']]
    print("Done!")

if __name__ == "__main__":
    main()


import ufora.FORA.python.ParseException as ParseException
import ufora.FORA.python.ForaValue as ForaValue
import ufora.native.FORA as ForaNative

def freshVarname(startingName, namesUsed):
    """pick a variant on 'startingName' that's not in namesUsed"""
    if startingName not in namesUsed:
        return startingName
    ix = 1
    while True:
        name = startingName + "_" + str(ix)
        if name not in namesUsed:
            return name
        ix = ix + 1

class NameExistsButDoesntParseException(object):
    def __init__(self, projectNode, name):
        self.projectNode = projectNode
        self.name = name

    @property
    def childrenWhoDontParse(self):
        return self.projectNode.childrenWhoDontParse

class Expression(object):
    """Represents a FORA expression."""
    def __init__(self, nativeExpression, codeDefinitionPoint):
        assert isinstance(nativeExpression, ForaNative.Expression)
        self.nativeExpression_ = nativeExpression
        self.codeDefinitionPoint_ = codeDefinitionPoint

    #returns a list of variables that are 'free' in the expression
    freeVariables = property(lambda self: self.nativeExpression_.freeVariables)

    #returns a list of variables that are mentioned anywhere in the expression
    mentionedVariables = property(lambda self: self.nativeExpression_.mentionedVariables)

    #returns a list of free variables that are assigned to by the expression
    assignedVariables = property(lambda self: self.nativeExpression_.assignedVariables)

    #returns a list of pairs of strings representing expressions like "x.y"
    #where "x" is a free variable and "y" is a member. used to rebind things in
    #the expression
    freeVariableMemberAccesses = property(lambda self:
                                        self.nativeExpression_.freeVariableMemberAccesses)

    def packAssignedVarsIntoTuple(self):
        """Return an expression that returns the value of the expression and also any assigned variables.

        If 'self' is 'e', this expression returns (e, (a1, a2, ...)) where the a's are assigned
        variables in the environment sorted alphabetically.

        If the expression throws an exception/stacktrace pair, the new expression throws

            (exception, (a1, a2, ...))

        from the same stacktrace.

        This function may not be called on an expression with return statements in it.
        """
        return Expression(self.nativeExpression_.packAssignedVarsIntoTuple(), self.codeDefinitionPoint_)

    def freeVariableUsePoints(self, varname):
        """return a list of CodeLocations where 'varname' is free"""
        return self.nativeExpression_.getFreeVariableRanges(varname)

    def getReturnStatementPoints(self):
        """return a list of CodeLocations where the expression has a 'return' statement"""
        return self.nativeExpression_.getReturnStatementRanges()

    def assignedVariableUsePoints(self, varname):
        """return a list of CodeLocations where a free variable 'varname' is assigned to"""
        return self.nativeExpression_.getAssignedVariableRanges(varname)

    def toFunction(self):
        """convert to a function with one argument per free variable"""
        return ForaValue.FORAValue(self.nativeExpression_.toFunctionImplval(False))

    def toFunctionAsImplval(self):
        """convert to a function with one argument per free variable"""
        return self.nativeExpression_.toFunctionImplval(False)

    def toFunctionAsImplvalWithPassthroughArgument(self):
        """convert to a function with one argument per free variable, plus an extra argument
            that gets added to the final result as a tuple."""
        return self.nativeExpression_.toFunctionImplvalWithPassthroughArgument(False)

    def rebindFreeVariableMemberAccess(self, varname, memberName, newName):
        """convert expressions like 'x.y' where 'x' is free to a new free
        variable"""
        return Expression(
            self.nativeExpression_.rebindFreeVariableMemberAccess(
                varname,
                memberName,
                newName
                ),
            self.codeDefinitionPoint_
            )

    def raiseParseException_(self, functionParseError):
        raise ParseException.ParseException(
            functionParseError,
            self.codeDefinitionPoint_
            )

    def raiseIfUsesUndefinedVariables(self, knownVariables):
        for variable in self.assignedVariables:
            self.checkVariableInKnownVariables(variable, knownVariables)

    def checkVariableInKnownVariables(self, variable, knownVariables):
        if variable not in knownVariables:
            assignmentLocations = self.assignedVariableUsePoints(variable)
            assert assignmentLocations, "Can't find assignment point for %s in '%s'." % (variable, str(self))

            self.raiseParseException_(
                ForaNative.FunctionParseError(
                    "can't assign to free variable " + variable,
                    assignmentLocations[0].range
                    )
                )

    def raiseParseErrorIfHasReturnStatements(self):
        getReturnStatementPoints = self.getReturnStatementPoints()
        if getReturnStatementPoints:
            self.raiseParseException_(
                ForaNative.FunctionParseError(
                    "can't use a return statement in a command-line expression",
                    getReturnStatementPoints[0].range
                    )
                )

    def specializeFreeVariableMapping(self,
                freeVariableMapping,
                specializationFunc,
                lookupFunc,
                finalVariableValueValidator
                ):
        """Allow an expression containing expressions like 'm.x' to be specialized.

        If we know what 'm' binds to, and

            specializationFunc(freeVariableMapping[m], 'x')

        produces a non-null value, we rebind the free variable to a new name with the result
        of specialzationFunc.

        Finally, we call 'finalVariableValueValidator' with the value each variable chain
        has been resolved to, along with a string of dot-separated identifiers. This function
        should return an error string if the intermediate value that has been bound is invalid.
        """
        done = False
        checkedNames = set()
        expr = self

        dotSequences = {}

        # Search through all the free variables and look up their values using the given lookup
        # function.
        for varname in self.freeVariables:
            dotSequences[varname] = varname
            if varname not in freeVariableMapping:
                varValue = lookupFunc(varname)

                if varValue is None:
                    codeLocations = self.freeVariableUsePoints(varname)

                    raise ParseException.ParseException(
                        ForaNative.FunctionParseError(
                            "Couldn't resolve free variable '%s'" % (varname,),
                            codeLocations[0].range
                            ),
                        self.codeDefinitionPoint_
                        )

                elif isinstance(varValue, NameExistsButDoesntParseException):
                    raise ParseException.ParseException(
                        ForaNative.FunctionParseError(
                            "Some modules did not parse correctly.",
                            self.freeVariableUsePoints(varname)[0].range
                            ),
                        self.codeDefinitionPoint_
                        )

                freeVariableMapping[varname] = varValue

        while not done:
            done = True
            #freeVariables = expr.freeVariables
            freeVariablesBound = expr.freeVariableMemberAccesses

            for varname, memberName in freeVariablesBound:
                if varname not in freeVariableMapping:
                    freeVariableMapping[varname] = lookupFunc(varname)
                mapsTo = freeVariableMapping[varname]
                if (mapsTo is not None and varname not in checkedNames):
                    subNode = specializationFunc(mapsTo, memberName)
                    if subNode is not None:
                        #we can bind this value to the node
                        newName = freshVarname(varname + "_" + memberName, set(expr.mentionedVariables))

                        dotSequences[newName] = dotSequences[varname] + "." + memberName

                        expr = expr.rebindFreeVariableMemberAccess(varname, memberName, newName)
                        freeVariableMapping[newName] = subNode
                        done = False
                    else:
                        checkedNames.add(varname)

        for var in expr.freeVariables:
            errString = finalVariableValueValidator(freeVariableMapping[var], dotSequences[var])

            if errString is not None:
                raise ParseException.ParseException(
                    ForaNative.FunctionParseError(
                        errString,
                        expr.freeVariableUsePoints(var)[0].range
                        ),
                    self.codeDefinitionPoint_
                    )

        return expr

    def returnFreeVariableValues(self, locals, importFunction):
        """Return arguments for the free variables in expression.

        importFunction = a function to call with free symbols that aren't in
            locals to look them up
        """
        boundVariables = []

        for freeVariable in self.freeVariables:
            if freeVariable in locals:
                boundVariables += [locals[freeVariable]]
            else:
                binding = importFunction(freeVariable)

                if binding is None:
                    raise ParseException.ParseException(
                        ForaNative.FunctionParseError(
                            "Couldn't resolve free variable '%s'" % freeVariable,
                            self.freeVariableUsePoints(freeVariable)[0].range
                            ),
                        self.codeDefinitionPoint_
                        )
                else:
                    boundVariables += [binding]

        return boundVariables

    @staticmethod
    def parse(textToParse, codeDefinitionPoint = None, nameScope = "<eval>", parseAsModule=False):
        """parse a string to an Expression object or throw a FunctionParseError.

        textToParse - a string containing the FORA expression
        parsePath - a list of strings containing the path to the
            code being parsed. this will show up in any stacktraces
            thrown by this expression or by code called by this expression
        nameScope - the name that functions and objects should descend from. If the
            expression is a simple 'fun' or 'object', this will be its name
        """

        if codeDefinitionPoint is None:
            codeDefinitionPoint = \
                ForaNative.CodeDefinitionPoint.ExternalFromStringList(
                    [nameScope]
                    )

        if parseAsModule:
            nativeExpressionOrParseError = \
                ForaNative.parseObjectDefinitionBodyToExpression(
                    textToParse,
                    ["Tsunami", nameScope + ".fora"],
                    False,
                    nameScope,
                    nameScope
                    )
        else:
            nativeExpressionOrParseError = \
                ForaNative.parseStringToExpression(
                    textToParse,
                    codeDefinitionPoint,
                    nameScope
                    )

        if isinstance(nativeExpressionOrParseError, ForaNative.FunctionParseError):
            raise ParseException.ParseException(
                nativeExpressionOrParseError,
                codeDefinitionPoint
                )

        return Expression(nativeExpressionOrParseError, codeDefinitionPoint)

    def __str__(self):
        return str(self.nativeExpression_)


List = [str(i) for i in range(0, 40)]
print(List)

length = len(List)
core = []
ccore = []
cccore = []
An = Bn = Cn = 0
rows = 5
columns = 4
page = 0
Next = "» Next"
Back = "« Back"
row, col = 0, 0
lock = False

while True:
    if page <= 0:
        if len(List) > rows*columns - (row // 1 * columns + col):
            if row + 1 == rows and col + 1 == columns:
                core.append("» Next")
                col += 1
            else:
                core.append(List[0])
                col += 1
                List = List[1:]
        else:
            core.append(List[0])
            col += 1
            List = List[1:]
    else:
        if len(List) > rows*columns - (row // 1 * columns + col):
            if row + 1 == rows and col == 0:
                core.append("« Back")
                col += 1
            elif row + 1 == rows and col + 1 == columns:
                core.append("» Next")
                col += 1
            else:
                core.append(List[0])
                col += 1
                List = List[1:]
        else:
            if (len(List) + (row // 1 * columns + col)) // columns == row and col == 0:
                core.append("« Back")
                col += 1
                core.extend(List)
                List = List[len(List):]
                lock = True
            else:
                core.append(List[0])
                col += 1
                List = List[1:]

    if len(core) == columns or len(List) == 0:
        ccore.append(core)
        row += 1
        col = 0
        core = []
        if lock == False and len(List) == 0:
            core.append(Back)
            ccore.append(core)
            core = []

    # now = (row//(rows+1)) * rows + col
    now = row // 1 * columns + col
    if now == rows*columns or len(List) == 0:
        cccore.append(ccore)
        ccore = []
        row, col = 0, 0
        page += 1
        if len(List) == 0:
            break
print(cccore)


# coding=utf-8
import world
import random

#debut du main
grid = world.Grid(world.nb_vcases, world.nb_hcases)

if False:
	for y in range(world.nb_vcases):
		for x in range(world.nb_hcases):
			case = Case(x-math.ceil(y/2),y)
			grid.cases.append(case)
	grid.draw()

"""tests = False

# tests
if tests:
	print("tests")
	if False:
		co = world.Cell("a a a a a a")
		co.move_to(grid.get_case_at(4,4))
		cu = world.Cell("b a a a a a")
		print("co case is:"+str(co.case.to_str()))
		cu.move_to(co.case.u)# ==> tester si la detection initiale de voisins fonctionne

	# postionnement de base
	# décrit un cercle autour de co, commencant par dr et tournant dans le sens des aiguilles d'une montre
	if True:
		[ox,oy]=[3,3]
		co = world.Cell("a a a a a a")
		co.move_to(grid.get_case_at(ox+0,oy+0))
		co.draw()
		root.update()
		time.sleep(0.2)

		cdr = world.Cell("b a a a a a")
		cdr.move_to(grid.get_case_at(ox+0,oy+1))
		cdr.draw()
		root.update()
		time.sleep(0.2)

		cr = world.Cell("c a a a a a")
		cr.move_to(grid.get_case_at(ox+1,oy+0))
		cr.draw()
		root.update()
		time.sleep(0.2)

		cu = world.Cell("d a a a a a")
		cu.move_to(grid.get_case_at(ox+1,oy-1))
		cu.draw()
		root.update()
		time.sleep(0.2)

		cul = world.Cell("e a a a a a")
		cul.move_to(grid.get_case_at(ox+0,oy-1))
		cul.draw()
		root.update()
		time.sleep(0.2)

		cl = world.Cell("f a a a a a")
		cl.move_to(grid.get_case_at(ox-1,oy+0))
		cl.draw()
		root.update()
		time.sleep(0.2)

		cd = world.Cell("a b a a a a")
		cd.move_to(grid.get_case_at(ox-1,oy+1))
		cd.draw()
		root.update()
		time.sleep(0.2)

		root.mainloop()

	if False:
		pattern = "a b b a b b"
		cell1 = world.Cell(pattern)
		cell1.move_to(grid.get_case_at(3,3))
		cell1.draw()
		cell2 = world.Cell(pattern)
		cell2.move_to(grid.get_case_at(3,4))
		cell2.draw()
		root.update()
		root.mainloop()

	#==> recup 2 cases proches l'une de l'autre"""

# main use
#if not tests:
print("main use")
for i in range(400):
	cell = world.Cell("a b a b c c")
	# on cherche une case libre dans la grills
	isFree=False
	while not isFree:
		case = random.choice(grid.cases)
		isFree = case.is_free()
	cell.move_to(case)
	cell.draw()
world.root.update()
world.root.mainloop()


'''
This is a file to run the ELden Ring Object Detection model

It used multiprocessing to split capturing, processing, and running the model into different
processes to speed things up.

'''

import torch
import time
from PIL import ImageGrab
import numpy as np
import cv2
import torch.multiprocessing as mp

class testDetector(mp.Process):

    def __init__(self, input_queue, output_queue):
        mp.Process.__init__(self, name="Test")
        self.input_queue = input_queue
        self.output_queue = output_queue

    def run(self):
        while True:
            # Get the next frame from the input queue
            frame = self.input_queue.get()

            # put the frame into the output queue
            self.output_queue.put(frame)

class ObjectDetector(mp.Process):
    """
    Class implements Yolo5 model to make inference on frames Opencv2.

    It is a multiprocess.Process to be used for multiprocessing code
    """

    def __init__(self, model_path, input_queue: mp.Queue,
                 output_queue: mp.Queue, threshold: float = 0.2):
        """
        Initializes the class with input and model path.
        """
        mp.Process.__init__(self, name="ObjectDetectorProcess")
        self.input_queue = input_queue
        self.output_queue = output_queue
        self.threshold = threshold
        self.model_path = model_path
        self.detection_model = self.load_model()
        self.classes = self.detection_model.names
        self.is_running = True

    def load_model(self):
        """
        Loads Yolo5 model from pytorch hub.
        :return: Trained Pytorch model.
        """
        model = torch.hub.load('ultralytics/yolov5',
                               'custom',
                               path=self.model_path)
        return model

    def score_frame(self, frame):
        """
        Takes a single frame as input, and scores the frame using yolo5 model.
        :param frame: input frame in numpy/list/tuple format.
        :return: Labels and Coordinates of objects detected by model in the frame.
        """

        results = self.detection_model(frame)
        labels, cord = results.xyxyn[0][:, -1], results.xyxyn[0][:, :-1]
        return labels, cord

    def class_to_label(self, x):
        """
        For a given label value, return corresponding string label.
        :param x: numeric label
        :return: corresponding string label
        """
        return self.classes[int(x)]

    def plot_boxes(self, results, frame):
        """
        Takes a frame and its results as input, and plots the bounding boxes and label on to the frame.
        :param results: contains labels and coordinates predicted by model on the given frame.
        :param frame: Frame which has been scored.
        :return: Frame with bounding boxes and labels ploted on it.
        """
        labels, cord = results
        n = len(labels)
        x_shape, y_shape = frame.shape[1], frame.shape[0]
        added_labels = []
        for i in range(n):
            if labels[i] in added_labels:
                continue
            else:
                added_labels.append(labels[i])

                row = cord[i]
                if row[4] >= self.threshold:
                    x1, y1, x2, y2 = int(row[0] * x_shape), int(
                        row[1] * y_shape), int(row[2] * x_shape), int(
                        row[3] * y_shape)
                    bgr = (0, 255, 0)
                    cv2.rectangle(frame, (x1, y1), (x2, y2), bgr, 2)
                    cv2.putText(frame,
                                self.class_to_label(labels[i]),
                                (x1, y1),
                                cv2.FONT_HERSHEY_SIMPLEX,
                                0.9,
                                bgr,
                                2)

        return frame

    def run(self):
        """
        This function is called when class (processes) is executed

        It take frames from the input_queue
        and detects the objects and buts the frames with
        the boxes in the output queue
        :return: void
        """

        while self.is_running:

            start_time =time.time()

            frame = self.input_queue.get()

            results = self.score_frame(frame)
            frame = self.plot_boxes(results, frame)

            end_time = time.time()
            fps = 1 / np.round(end_time - start_time, 2)
            # print(f"Frames Per Second : {fps}")

            cv2.putText(frame,
                        f'FPS: {int(fps)}',
                        (20, 70),
                        cv2.FONT_HERSHEY_SIMPLEX,
                        1.5,
                        (0, 255, 0),
                        2)

            self.output_queue.put(frame)

class FrameGetter(mp.Process):
    """
    Class that is used to get continuous screen grabs from the
    screen_coordinates provided
    """

    def __init__(self, output_queue: mp.Queue,
                 screen_coordinates : np.array = np.array([(0, 150), (0, 1120), (1424, 150), (1424, 1120)]),):

        self.screen_coordinates = screen_coordinates
        mp.Process.__init__(self, name="FrameGetterProcess")

        self.output_queue = output_queue
        self.is_running = True

    def make_region(self, screen_coordinates):
        '''
        Make a region from the corner coordinates

        Args:
            screen_coordinates: numpy of the corner coordinates

        Returns:
            numpy array of the region
        '''
        # Get the top left corner
        top_left = screen_coordinates[0]

        # Get the bottom right corner
        bottom_right = screen_coordinates[3]

        # Make the region
        region = (top_left[0], top_left[1],
                           bottom_right[0] - top_left[0],
                           bottom_right[1] - top_left[1])

        return region

    def get_frame(self, region):
        '''
        Get the  frame from the screen

        Returns:
            numpy array of the game frame
        '''

        # Get the game frame from the screen
        game_frame = ImageGrab.grab(bbox=region)

        # Return numpy array of it
        return np.array(game_frame)

    def run(self):
        """
        This function is called when class (processes) is executed

        It take frames from the input_queue
        and detects the objects and buts the frames with
        the boxes in the output queue
        :return: void
        """

        screen_region = self.make_region(self.screen_coordinates)

        while self.is_running:

            frame = self.get_frame(screen_region)

            self.output_queue.put(frame)

class FrameViewer(mp.Process):
    """
    Class that is used to display frames from the input queue in open cv
    """

    def __init__(self,
                 input_queue: mp.Queue ):
        """
        Initializes the class with input and model path.
        """
        mp.Process.__init__(self, name="FrameViewerProcess")
        self.is_running = True
        self.input_queue = input_queue

    def run(self):
        """
        This function is called when class (processes) is executed

        It take frames from the input_queue
        and detects the objects and buts the frames with
        the boxes in the output queue
        :return: void
        """

        while self.is_running:

            if len(self.input_queue.get()) > 0:

                frame = self.input_queue.get()

                cv2.imshow('YOLOv5 Detection', frame)

                if cv2.waitKey(1) == "q":
                    cv2.destroyAllWindows()
                    break

def runDetectionModel(model_path: str = "/Users/matthewbass/Documents/School_Colby/Colby/spring22/CS337-Operating-Systems/Projects/Proj9/EldenRingAi/yolov5/1024_m_elden_ring/exp/weights/best.pt",
                      threshold : float = 0.2,
                      screen_coordinates : np.array = np.array([(0, 150), (0, 1120), (1424, 150), (1424, 1120)]),
                      time_to_run : float = 100) -> None:
    '''
    This is a function to run the object detection model

    Args:
        model_path (str): path to the model
        threshold (float): threshold for the detection
        screen_coordinates (np.array): numpy array of the screen coordinates

    Returns:

    '''

    # Initialize the queues to connect the processes
    frame_to_detect_queue = mp.Queue()
    detect_to_view_queue = mp.Queue()

    # Initialize the processes
    object_detector = ObjectDetector(input_queue=frame_to_detect_queue,
                                   output_queue=detect_to_view_queue,
                                   model_path = model_path,
                                   threshold=threshold)

    # test_detector = testDetector(input_queue=frame_to_detect_queue,
    #                                output_queue=detect_to_view_queue)

    frame_getter = FrameGetter(output_queue = frame_to_detect_queue,
                               screen_coordinates=screen_coordinates)
    frame_viewer = FrameViewer(input_queue=detect_to_view_queue)

    procs = [frame_getter, object_detector,frame_viewer]

    # Start the processes
    print("Starting FrameGetter")
    frame_getter.start()

    print("Starting detector")

    object_detector.start()

    print("Starting viewer")
    frame_viewer.start()

    time.sleep(time_to_run)

    # Sleep for the time to run
    time.sleep(time_to_run)

    # Stop the processes
    for proc in procs:
        proc.is_running = False
        proc.join()

    print("Model finished")

    return

def main():
    runDetectionModel()
    return

if __name__ == "__main__":
    main()