from urllib.request import urlopen
from lxml import etree
import requests as request
from PyPDF2 import PdfFileReader, PdfFileWriter
from pdf2image import convert_from_path

local = 'https://www.sibsiu.ru/raspisanie/'                 # директория сайта с расписанием

response = urlopen(local)                                   # получение сайта через urlib (можно и через request)

htmlParser = etree.HTMLParser()                             # парс данных
tree = etree.parse(response, htmlParser)                    #

el = tree.xpath('//*[@id="inst10"]/ul/ul[6]/ul[6]/li/a')    # поиск в структуре нужного расписания через xpath

mainFileLink = str(el[0].attrib)[10:-22]                    # удаление лишних данных в строках
local = local[0:-12]                                        #
mainFileLink = mainFileLink.replace('\\\\', '/')            #

mainGoal = local + mainFileLink                             # получение полной ссылки с .pdf файлом расписания

res = request.get(mainGoal)                                 # получение сайта через request (можно и через urlib)

res.encoding = 'utf-8'                                      # установка кодировка файла

lastModified = res.headers['Last-Modified']                 # получение нужных данных из хедера (получаем дату последнего изменения файла)
                                                            # можно использовать для отслеживания актуального расписания

with open('main.pdf', 'wb') as f:                           # сохранения .pdf
    f.write(res.content)                                    #

popplerPath = "poppler-21.09.0\\Library\\bin"               #
images = convert_from_path('main.pdf',                      # конвертирование из .pdf в .png
                           300,                             # качество 300 dpi
                           poppler_path=popplerPath)        #

outputPath = 'raspisanie.png'                               # путь для сохранения .png
images[0].save(outputPath)                                  # сохранение первого листа .pdf (в моем случае) в .png в указанный путь


import functools

# Binary Search
def binary_search(a, x):
	half = len(a) // 2
	if half:
		if a[half] == x:
			return True
		elif a[half] > x:
			return binary_search(a[:half], x)
		else:
			return binary_search(a[half:], x)
	return False

print(binary_search([0, 1, 2, 4, 6, 8, 10], 8))

# Hanoi
def hanoi(n, s, t, a):
	if n > 0:
		hanoi(n-1, s, a, t)
		if s:
			t.append(s.pop())
		hanoi(n-1, a, t, s)

source, target, helper = [4, 3, 2, 1], [], []
hanoi(len(source), source, target, helper)
print(source, helper, target)

# Factorial
def fact(n):
	assert isinstance(n, int) and n >= 0, "n must be a positive integer"
	if n == 0:
		return 1
	else:
		return n * fact(n-1)

print(*[fact(n) for n in range(10)])

# Fibonacci
@functools.lru_cache()
def fibs(n):
	assert isinstance(n, int) and n > 0, "n must be a positive integer"
	if n == 1 or n == 2:
		return 1
	else:
		return fibs(n-1) + fibs(n-2)

print(*[fibs(x) for x in range(1, 100)])


import math

import pytest
import tomli

from tealc import StringTension

with open('./tests/data/string_data.toml', 'rb') as f:
    string_data = tomli.load(f)

material = []
pitch = []
gauge = []
tension = []
for m in string_data.keys():
    for p in string_data[m].keys():
        n = len(string_data[m][p]['gauge'])
        material.extend([m] * n)
        pitch.extend([p] * n)
        gauge.extend(string_data[m][p]['gauge'])
        tension.extend(string_data[m][p]['tension'])
guitar_data = list(zip(gauge, material, pitch, tension))

@pytest.mark.parametrize('test_g, test_m, test_p, expected', guitar_data)
def test_accuracy(test_g, test_m, test_p, expected):
    """Test calculations against mfr. charts."""
    calc = StringTension(test_g, test_m, test_p, length=25.5)
    assert math.isclose(calc.lb, expected, rel_tol=0.1)

with open('./tests/data/bass_string_data.toml', 'rb') as f:
    bass_string_data = tomli.load(f)

b_material = []
b_pitch = []
b_gauge = []
b_tension = []
for m in bass_string_data.keys():
    for p in bass_string_data[m].keys():
        n = len(bass_string_data[m][p]['gauge'])
        b_material.extend([m] * n)
        b_pitch.extend([p] * n)
        b_gauge.extend(bass_string_data[m][p]['gauge'])
        b_tension.extend(bass_string_data[m][p]['tension'])
bass_data = list(zip(b_gauge, b_material, b_pitch, b_tension))
print(bass_data)

@pytest.mark.parametrize('test_g, test_m, test_p, expected', bass_data)
def test_bass_accuracy(test_g, test_m, test_p, expected):
    """Test bass string calculations against mfr. charts."""
    calc = StringTension(test_g, test_m, test_p, length=34)
    assert math.isclose(calc.lb, expected, rel_tol=0.1)


import setuptools
from multisite.__version__ import VERSION

if __name__ == '__main__':
    with open("README.md", "r") as fh:
        long_description = fh.read()

    setuptools.setup(
        name="multisite",
        version=VERSION,
        author="Corey McCandless",
        author_email="crm1994@gmail.com",
        description=(
            "Host multiple standalone websites under a single site"
        ),
        long_description=long_description,
        long_description_content_type="text/markdown",
        url="https://github.com/cmccandless/multisite",
        packages=setuptools.find_packages(),
        classifiers=(
            "Programming Language :: Python :: 3",
            "License :: OSI Approved :: MIT License",
            "Operating System :: OS Independent",
        ),
        entry_points={
            'console_scripts': [
                'multisite = multisite.__main__:main'
            ],
        },
        install_requires=['argutil', 'GitPython', 'mistune'],
        include_package_data=True
    )


#!/usr/bin/env python

import argparse
import mwalib

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-m", "--metafits", required=True, help="Path to the metafits file."
    )
    parser.add_argument("gpuboxes", nargs="*", help="Paths to the gpubox files.")
    args = parser.parse_args()

    with mwalib.CorrelatorContext(args.metafits, args.gpuboxes) as context:
        print(context)


# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.3.3
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # s_checklist_historical_step04 [<img src="https://www.arpm.co/lab/icons/icon_permalink.png" width=30 height=30 style="display: inline;">](https://www.arpm.co/lab/redirect.php?code=s_checklist_historical_step04&codeLang=Python)
# For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=ex-vue-4-historical).

# +
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

from arpym.statistics.bootstrap_hfp import bootstrap_hfp
from arpym.tools.histogram_sp import histogram_sp
from arpym.tools.logo import add_logo
# -

# ## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_historical_step04-parameters)

m_ = 1  # number of days to project
j_ = 10000  # number of projection scenarios
d_plot = 1  # index of projected risk driver to plot

# ## [Step 0](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_historical_step04-implementation-step00): Load data

# +
path = '~/databases/temporary-databases/'

# Risk drivers identification
# market risk drivers
db_riskdrivers_series = pd.read_csv(path+'db_riskdrivers_series_historical.csv',
                                    index_col=0, parse_dates=True)
x = db_riskdrivers_series.values
risk_drivers_names = db_riskdrivers_series.columns

# risk driver information
db_riskdrivers_tools = pd.read_csv(path+'db_riskdrivers_tools_historical.csv')
d_ = int(db_riskdrivers_tools.d_.dropna())
t_now = np.datetime64(db_riskdrivers_tools.t_now[0], 'D')

# Quest for invariance
# invariant series
db_invariants_series = pd.read_csv(path+'db_invariants_series_historical.csv',
                                   index_col=0, parse_dates=True)
epsi = db_invariants_series.dropna().values
dates = db_invariants_series.dropna().index
t_, i_ = np.shape(epsi)

# next step models
db_invariants_nextstep = pd.read_csv(path+'db_invariants_nextstep_historical.csv')

# next step model parameters
db_invariants_garch_param = pd.read_csv(path+'db_invariants_garch_param.csv',
                                        index_col=0)

# Estimation
# flexible probabilities
db_estimation_flexprob = pd.read_csv(path+'db_estimation_flexprob.csv',
                                     index_col=0, parse_dates=True)
p = db_estimation_flexprob.loc[:, 'p'].values
# -

# ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_historical_step04-implementation-step01): Projection of invariants (bootstrap)

t_hor = np.busday_offset(t_now, m_)
epsi_proj = np.zeros((j_, m_, d_))
for m in range(m_):
    epsi_proj[:, m, :] = bootstrap_hfp(epsi, p, j_)
p_scenario = np.ones(j_)/j_  # projection scenario probabilities

# ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_historical_step04-implementation-step02): Projection of risk drivers

# +
dx_proj = np.empty((j_, m_+1, d_))
x_proj = np.empty((j_, m_+1, d_))
sig2_garch = np.empty((j_, m_+1, d_))

# risk drivers at time t_0=t_now
x_proj[:, 0, :] = x[-1, :]

# initialize parameters for GARCH(1,1) projection
d_garch = [d for d in range(d_)
           if db_invariants_nextstep.iloc[0, d] =='GARCH(1,1)']
for d in d_garch:
    a_garch = db_invariants_garch_param.loc['a'][d]
    b_garch = db_invariants_garch_param.loc['b'][d]
    c_garch = db_invariants_garch_param.loc['c'][d]
    mu_garch = db_invariants_garch_param.loc['mu'][d]
    sig2_garch[:, 0, d] = db_invariants_garch_param.iloc[-1, d]
    dx_proj[:, 0, d] = x[-1, d] - x[-2, d]

# project risk drivers
for m in range(1, m_+1):
    for d in range(d_):
        # risk drivers modeled as random walk
        if db_invariants_nextstep.iloc[0, d] == 'Random walk':
            x_proj[:, m, d] = x_proj[:, m-1, d] + epsi_proj[:, m-1, d]

        # risk drivers modeled as GARCH(1,1)
        elif db_invariants_nextstep.iloc[0, d] == 'GARCH(1,1)':
            a_garch = db_invariants_garch_param.loc['a'][d]
            b_garch = db_invariants_garch_param.loc['b'][d]
            c_garch = db_invariants_garch_param.loc['c'][d]
            mu_garch = db_invariants_garch_param.loc['mu'][d]
            sig2_garch[:, m, d] = c_garch + b_garch*sig2_garch[:, m-1, d] +\
                a_garch*(dx_proj[:, m-1, d] - mu_garch)**2
            dx_proj[:, m, d] = mu_garch +\
                np.sqrt(sig2_garch[:, m, d])*epsi_proj[:, m-1, d]
            x_proj[:, m, d] = x_proj[:, m-1, d] + dx_proj[:, m, d]
# -

# ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_checklist_historical_step04-implementation-step03): Save databases

# +
# projected risk drivers
out = pd.DataFrame({risk_drivers_names[d]:
                   x_proj[:, :, d].reshape((j_*(m_+1),))
                   for d in range(d_)})
out = out[list(risk_drivers_names[:d_].values)]
out.to_csv(path+'db_projection_bootstrap_riskdrivers.csv', index=None)
del out

# additional information
out = pd.DataFrame({'j_': pd.Series(j_),
                    't_hor': pd.Series(t_hor)})
out.to_csv(path+'db_projection_bootstrap_tools.csv', index=None)
del out

# projected scenario probabilities
out = pd.DataFrame({'p': pd.Series(p_scenario)})
out.to_csv(path+'db_scenario_probs_bootstrap.csv', index=None)
del out
# -

# ## Plots

# +
plt.style.use('arpm')

# marginal distributions
n_bins = 10 * np.log(t_)

# projected risk driver distribution
proj_dist = plt.figure(figsize=(1280.0/72.0, 720.0/72.0), dpi=72.0)
ax = proj_dist.add_subplot(111)
f_eps, x_eps = histogram_sp(x_proj[:, m_, d_plot-1],
                            p=p_scenario,
                            k_=n_bins)
bar_width = x_eps[1] - x_eps[0]
plt.bar(x_eps, f_eps.flatten(), width=bar_width, fc=[0.7, 0.7, 0.7],
        edgecolor=[0.5, 0.5, 0.5])

plt.title(db_riskdrivers_series.columns[d_plot-1] + \
          ' projected risk driver distribution',
         fontweight='bold', fontsize=20)
plt.xlabel('Projected risk driver', fontsize=17)
add_logo(proj_dist, location=1, set_fig_size=False)
proj_dist.tight_layout()


name = input("Enter name of employee : ")
Basic=int(input("Enter Baic payout : "))
if (Basic>=10000):
    DA=float(Basic*0.40)
    HRA=float(Basic*0.30)
    print("Grade 1")
elif (Basic==5000 or Basic<10000):
    DA=float(Basic*0.40)
    HRA=float(Basic*0.25)
    print("Grade 2")
elif (Basic>2000 or Basic<5000):
    DA=float(Basic*0.30)
    HRA=float(Basic*0.20)
    print("Grade 3")
elif (Basic<=2000):
    DA=float(Basic*0.30)
    HRA=float(Basic*0.15)
    print("Grade 4")
Salary= int(Basic+DA+HRA)
print("Basic : ",Basic)
print("DA : ",DA)
print("HRA : ",HRA)
print("Salary : ",Salary)
TaxApplicable=float((Salary-50000)*12*0.30)
if (TaxApplicable > 0):
    print("Monthly Taxable Ammount : ",TaxApplicable/12)
    print("Net Monthly Salary : ",(Salary-(TaxApplicable/12)))
else:
    print("Tax is not applicable")


import json
import sys
import os
config = None
exc_dir = os.path.dirname(os.path.abspath(__file__))
home_path = os.path.expanduser("~")

fn = '/home/den0/Programs/MSystem/BotNetwork1/configs/aws_clerk_config.json'

with open(fn, 'r') as f:
    config = json.loads(f.read())
os.chdir(config['lib_directory'])

sys.path.append( config['lib_directory'])
config['exc_dir'] = exc_dir

from slaves.WCV1.slave import WCV1

WCV1(config).start()


import os
files =  os.listdir()
userFileInput = input("please enter a filename eg hello.txt:" "\n")
BASE_PATH = os.path.dirname(os.path.abspath(__file__)) # Best practice

if userFileInput in files:
    print( "A) read file " "\n" "B) Delete the file and start over " "\n" "C) Append the file" "\n" )
    option = str(input("select A,B and C to specify action:\n" )).upper() # Make sure we strngify the user input to avoid edge cases
    if option == "A":
        f = os.path.join(BASE_PATH, userFileInput) # Best practice
        with open(f, "r") as selectedFile: # Always best practice to use context managers when handling files
            fileContent = selectedFile.read() # Reads the contends of the selected file
            print(fileContent)

    elif option == "B":
        os.remove(userFileInput) # Delete the file
        with open(userFileInput,"w") as newFile: # Create a new file with the same name as the deleted one
            newFileContent = input("enter text here:\n") # write some content to the file
            newFile.write(f"{newFileContent}\n")

    elif option == "C":
        with open(userFileInput,"a") as fileToAppend:
            appendContent = input("continue text here:\n")
            fileToAppend.write(f"{appendContent}\n")
            print("Appended successfully!!")

else:
     with open(userFileInput, "w") as createFile:
         createFileContent = input("enter the text to write to the file:\n")
         createFile.write(f"{createFileContent}\n")
         print("File created sucessfully")


import os
import sys
import keys
import json
import logging

from uuid import uuid4
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener

import settings

# Variables that contains the user credentials to access Twitter API
ACCESS_TOKEN = keys.ACCESS_TOKEN
ACCESS_TOKEN_SECRET = keys.ACCESS_TOKEN_SECRET
CONSUMER_KEY = keys.CONSUMER_KEY
CONSUMER_SECRET = keys.CONSUMER_SECRET

# Colors definition for output
COLORS = {'magenta': '35',
          'green': '32',
          'red': '33;1',
          'cyan': '36',
          'white': '37;1',
          'yellow': '33'}

# Format of attribute name created from hashtag
ATTR_COUNTER_FORMAT = '{0}_counter'

class Listener(StreamListener):
    """This is a basic listener that just prints received tweets."""
    def __init__(self, tracker, *args, **kwargs):
        self.tracker = tracker
        super(Listener, self).__init__(*args, **kwargs)

    def on_data(self, data):
        """
            What to do on the event of receiving data while listening

            Args:
                data: Response form twitter API with the tracked tweet
        """
        data = json.loads(data)
        hashtags = []
        if 'entities' in data and 'hashtags' in data['entities']:
            hashtags = data['entities']['hashtags']

        for h in hashtags:
            if h['text'] in self.tracker.hashtags:
                hashtag_name = h['text']
                # we add 1 to the actual counter
                hits = getattr(self.tracker, hashtag_name) + 1

                # we set the new value
                counter = ATTR_COUNTER_FORMAT.format(h['text'])
                setattr(self.tracker, counter, hits)
                # store it in database
                self.tracker.set_data(counter, hits)
                # create data to be published in channel
                data_to_publish = {}
                data_to_publish.update({'event': 'tweet'})
                data_to_publish.update({'hashtag': h['text']})
                data_to_publish.update(
                    {'text': data['text'].encode('utf-8')})
                user_data = {'id': data['user']['id_str'],
                             'name': data['user']['name'].encode('utf-8'),
                             'screen_name': data['user']['screen_name']
                             }
                data_to_publish.update({'user': user_data})
                # publish data
                self.tracker.publish_data(data_to_publish)
                if self.tracker.verbose:
                    self.tracker.print_table()
        return True

    def on_error(self, status):
        """
            Log if an error occurs when accessing the API

            Args:
                status (int): HTTP status code
        """
        logging.error("Listener had problems connecting. Status: {0}".format(
            status))

class Tracker():
    """
        Main class that handles most of our app.

        Attributes:
            redis (Redis): redis connection (settings)
            channel (str): channel unique identifier
            hashtags (list): hashtags to keep track of
            known_items (list): all known attributes of the class
            listener (Listener): Twitter StreamListener
            longest (int): length of longest hashtags (for output purposes)
            stream (Stream): Twitter authenticated stream of data
    """

    def __init__(self, verbose, hashtags=[]):
        """
            Args:
                hashtags (list, optional): hashtags entered as parameters
        """
        # Set all static attributes
        self.stream = None
        self.listener = None
        self.verbose = verbose
        self.hashtags = hashtags
        self.set_longest_hashtag()
        self.redis = settings.REDIS
        self.create_redis_channels()
        self.set_unique_redis_channel()

        # define vars needed for console output (also static)
        self.cell_size = (self.longest + 3)
        self.counter_whitespace = " " * ((self.cell_size - 6) / 2)
        self.border = "-" * ((self.cell_size * 2) + 1)

        # Set dynamic attributes (counters for each hashtag)
        for h in self.hashtags:
            setattr(self, "{0}_counter".format(h), 0)

    def __getattr__(self, name):
        """
        Access to attributes.

        As some attributes are created dynamically, depending on hashtags
        list passed into the constructor, this method allows to access
        them via hashtag name not the custom format of the attribute name.

        """
        try:
            counter = ATTR_COUNTER_FORMAT.format(name)
            return getattr(self, counter)
        except:
            raise AttributeError

    def create_redis_channels(self):
        """
            Creates 'channels' in redis if it doesn't exist
            'channels' is to keep track of existing publishing channels
        """
        if "channels" not in self.redis.keys():
            self.redis.set("channels", json.dumps({"channels": []}))

    def set_unique_redis_channel(self):
        """ Creates a unique channel id """
        channel_id = str(uuid4())
        used_channels = json.loads(self.redis.get("channels"))["channels"]
        if channel_id in used_channels:
            self.get_unique_redis_channel()
        else:
            self.channel = channel_id
            used_channels.append(channel_id)
            self.redis.set("channels", json.dumps({"channels": used_channels}))

    def set_data(self, key, value):
        """ Set a key/value pair in redis """
        self.redis.set(key, value)

    def publish_data(self, data):
        """

            Publish data/event in a channel

            Args:
                data: data to publish in redis
        """
        logging.debug("publishing to channel {0}".format(self.channel))
        self.redis.publish(self.channel, json.dumps(data))

    def authenticate(self):
        """
            Authenticate against the Twitter API

            Returns:
                Stream: <Twitter authenticated Stream object>
        """
        # Twitter authentication and connection to Twitter Streaming API
        self.listener = Listener(self)
        auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
        auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
        self.stream = Stream(auth, self.listener)
        return self.stream

    def set_longest_hashtag(self):
        """ Sets our longest_hashtag attribute """
        self.longest = 0
        for h in self.hashtags:
            if len(h) > self.longest:
                self.longest = len(h)

    def get_winning_hashtag(self):
        """
            Get currently winning hashtag

            Returns:
                str: <winner>
        """
        winner = {'hashtag': '', 'value': 0}
        for h in self.hashtags:
            hits = getattr(self, h)
            if hits > winner['value']:
                winner['hashtag'] = h
                winner['value'] = hits
        return winner['hashtag']

    def colorize(self, color, message):
        """
            Colorizes given message with given color

            Args:
                color (str): Parsed with global var COLORS
                message (str): message to be colorized

            Returns:
                str: message with requested color codes
        """
        return "\033[{0}m{1}\033[0m".format(COLORS[color], message)

    def print_table(self):
        """ Prints table with live results into console """
        # clear console
        os.system('clear')

        # Colorize table items!
        border = self.colorize('cyan', self.border)
        separator = self.colorize('cyan', '|')

        # print table top border
        sys.stderr.write(" {0} \n".format(border))

        # Grab all counters and print their value
        for hashtag in self.hashtags:
            # For better output we calculate the whitespace necessary
            # depending on each hashtag length
            hashtag_whitespace = " " * (self.longest - len(hashtag) + 3)

            # get number of hits for each hashtag
            hits = getattr(self, hashtag)

            # set winner banner and color for output
            winner_banner = ''
            color = 'yellow'

            # set different banner and different color for winning hashtag
            if hashtag is self.get_winning_hashtag():
                winner_banner = self.colorize('magenta', ' # WINNING #')
                color = 'green'

            # Colorize
            hashtag = self.colorize(color, hashtag)
            hits = self.colorize(color, str(hits).zfill(5))

            # output table contents
            sys.stderr.write('{0} {1}{2} {0}{3}{4}{3}{0}{5}\n'.format(
                separator,
                hashtag,
                hashtag_whitespace,
                self.counter_whitespace,
                hits,
                winner_banner))

        # print table bottom border
        sys.stderr.write(" {0} \n".format(border))


from flask import Flask, render_template
from data import get_data
import random
import os

app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0

@app.route('/')
def hello():
    #BLACKPINK, IU, EZ Kim, Heize
    artist_list = ['41MozSoPIsD1dJM0CLPjZF', '3HqSLMAZ3g3d5poNaI7GOU', '5WJOZ5N4iegy9XdltTo8os', '5dCvSnVduaFleCnyy98JMo']
    rand = random.randint(0, len(artist_list) - 1)

    info = get_data(artist_list[rand])

    return render_template(
        'index.html',
        songName = info[0],
        artistNames = info[1],
        albumImage = info[2],
        previewURL = info[3],
        spotifyURL = info[4],
        totalArtists = len(info[1])
    )
if __name__ == '__main__':
    app.run(
        debug = True,
        host = os.getenv('IP', '0.0.0.0'),
        port = int(os.getenv('PORT', 8080))
    )


import time
from collections import defaultdict
from typing import Union, Dict, AnyStr, Optional, Tuple
from metadrive.manager.record_manager import RecordManager
from metadrive.manager.replay_manager import ReplayManager
import gym
import numpy as np
from panda3d.core import PNMImage

from metadrive.component.vehicle.base_vehicle import BaseVehicle
from metadrive.constants import RENDER_MODE_NONE, DEFAULT_AGENT, REPLAY_DONE
from metadrive.engine.base_engine import BaseEngine
from metadrive.engine.engine_utils import initialize_engine, close_engine, \
    engine_initialized, set_global_random_seed
from metadrive.manager.agent_manager import AgentManager
from metadrive.obs.image_obs import ImageStateObservation
from metadrive.obs.observation_base import ObservationBase
from metadrive.obs.state_obs import LidarStateObservation
from metadrive.utils import Config, merge_dicts, get_np_random, concat_step_infos

BASE_DEFAULT_CONFIG = dict(

    # ===== agent =====
    random_agent_model=False,
    agent_policy=None,

    # ===== multi-agent =====
    num_agents=1,  # Note that this can be set to >1 in MARL envs, or set to -1 for as many vehicles as possible.
    is_multi_agent=False,
    allow_respawn=False,
    delay_done=0,  # How many steps for the agent to stay static at the death place after done.
    # Whether only return single agent-like observation and action space
    return_single_space=False,

    # ===== Action =====
    manual_control=False,
    controller="keyboard",  # "joystick" or "keyboard"
    decision_repeat=5,
    discrete_action=False,
    discrete_steering_dim=5,
    discrete_throttle_dim=5,

    # ===== Rendering =====
    use_render=False,  # pop a window to render or not
    debug=False,
    disable_model_compression=False,  # disable compression if you wish to launch the window quicker.
    cull_scene=True,  # only for debug use
    use_chase_camera_follow_lane=False,  # If true, then vision would be more stable.
    camera_height=1.8,
    camera_dist=6.0,
    prefer_track_agent=None,
    draw_map_resolution=1024,  # Drawing the map in a canvas of (x, x) pixels.
    top_down_camera_initial_x=0,
    top_down_camera_initial_y=0,
    top_down_camera_initial_z=200,  # height
    show_logo=True,

    # ===== Vehicle =====
    vehicle_config=dict(
        increment_steering=False,
        vehicle_model="default",
        show_navi_mark=True,
        extra_action_dim=0,
        enable_reverse=False,
        random_navi_mark_color=False,
        show_dest_mark=False,
        show_line_to_dest=False,
        use_special_color=False,

        # ===== use image =====
        image_source="rgb_camera",  # take effect when only when offscreen_render == True

        # ===== vehicle spawn and destination =====
        navigation_module=None,  # a class type for self-defined navigation
        need_navigation=True,
        spawn_lane_index=None,
        spawn_longitude=5.0,
        spawn_lateral=0.0,
        destination=None,
        spawn_position_heading=None,

        # ==== others ====
        overtake_stat=False,  # we usually set to True when evaluation
        action_check=False,
        random_color=False,
        random_agent_model=False,  # this will be overwritten by env.config["random_agent_model"]

        # ===== vehicle module config =====
        lidar=dict(
            num_lasers=240, distance=50, num_others=0, gaussian_noise=0.0, dropout_prob=0.0, add_others_navi=False
        ),
        side_detector=dict(num_lasers=0, distance=50, gaussian_noise=0.0, dropout_prob=0.0),
        lane_line_detector=dict(num_lasers=0, distance=20, gaussian_noise=0.0, dropout_prob=0.0),
        show_lidar=False,
        mini_map=(84, 84, 250),  # buffer length, width
        rgb_camera=(84, 84),  # buffer length, width
        depth_camera=(84, 84, True),  # buffer length, width, view_ground
        show_side_detector=False,
        show_lane_line_detector=False,

        # NOTE: rgb_clip will be modified by env level config when initialization
        rgb_clip=True,  # clip 0-255 to 0-1
        stack_size=3,  # the number of timesteps for stacking image observation
        rgb_to_grayscale=False,
        gaussian_noise=0.0,
        dropout_prob=0.0,
    ),

    # ===== Agent config =====
    target_vehicle_configs={DEFAULT_AGENT: dict(use_special_color=False, spawn_lane_index=None)},

    # ===== Engine Core config =====
    window_size=(1200, 900),  # or (width, height), if set to None, it will be automatically determined
    physics_world_step_size=2e-2,
    show_fps=True,
    global_light=False,
    # only render physics world without model, a special debug option
    debug_physics_world=False,
    # debug static world
    debug_static_world=False,
    # set to true only when on headless machine and use rgb image!!!!!!
    headless_machine_render=False,
    # turn on to profile the efficiency
    pstats=False,
    # if need running in offscreen
    offscreen_render=False,
    # accelerate the lidar perception
    _disable_detector_mask=False,
    # clip rgb to (0, 1)
    rgb_clip=True,
    # None: unlimited, number: fps
    force_render_fps=None,
    # if set to True all objects will be force destroyed when call clear()
    force_destroy=False,

    # ===== Others =====
    # The maximum distance used in PGLOD. Set to None will use the default values.
    max_distance=None,
    # Force to generate objects in the left lane.
    _debug_crash_object=False,
    horizon=None,  # The maximum length of each environmental episode. Set to None to remove this constraint
    max_step_per_agent=None,  # The maximum length of each agent episode. Raise max_step termination when reaches.
    show_interface_navi_mark=True,
    show_mouse=True,
    show_skybox=True,
    show_terrain=True,
    show_interface=True,

    # record/replay metadata
    record_episode=False,  # when replay_episode is not None ,this option will be useless
    replay_episode=None,  # set the replay file to enable replay
    only_reset_when_replay=False,  # Scenario will only be initialized, while future trajectories will not be replayed
)

class BaseEnv(gym.Env):
    # Force to use this seed if necessary. Note that the recipient of the forced seed should be explicitly implemented.
    _DEBUG_RANDOM_SEED = None
    DEFAULT_AGENT = DEFAULT_AGENT

    @classmethod
    def default_config(cls) -> "Config":
        return Config(BASE_DEFAULT_CONFIG)

    # ===== Intialization =====
    def __init__(self, config: dict = None):
        if config is None:
            config = {}
        merged_config = self._merge_extra_config(config)
        global_config = self._post_process_config(merged_config)
        self.config = global_config

        # agent check
        self.num_agents = self.config["num_agents"]
        self.is_multi_agent = self.config["is_multi_agent"]
        if not self.is_multi_agent:
            assert self.num_agents == 1
        assert isinstance(self.num_agents, int) and (self.num_agents > 0 or self.num_agents == -1)

        # observation and action space
        self.agent_manager = AgentManager(
            init_observations=self._get_observations(), init_action_space=self._get_action_space()
        )

        # lazy initialization, create the main vehicle in the lazy_init() func
        self.engine: Optional[BaseEngine] = None

        # In MARL envs with respawn mechanism, varying episode lengths might happen.
        self.dones = None
        self.episode_rewards = defaultdict(float)
        self.episode_lengths = defaultdict(int)

    def _merge_extra_config(self, config: Union[dict, "Config"]) -> "Config":
        """Check, update, sync and overwrite some config."""
        return config

    def _post_process_config(self, config):
        """Add more special process to merged config"""
        config["vehicle_config"]["random_agent_model"] = config["random_agent_model"]
        config["vehicle_config"]["rgb_clip"] = config["rgb_clip"]
        return config

    def _get_observations(self) -> Dict[str, "ObservationBase"]:
        raise NotImplementedError()

    def _get_observation_space(self):
        return {v_id: obs.observation_space for v_id, obs in self.observations.items()}

    def _get_action_space(self):
        if self.is_multi_agent:
            return {
                v_id: BaseVehicle.get_action_space_before_init(
                    self.config["vehicle_config"]["extra_action_dim"], self.config["discrete_action"],
                    self.config["discrete_steering_dim"], self.config["discrete_throttle_dim"]
                )
                for v_id in self.config["target_vehicle_configs"].keys()
            }
        else:
            return {
                DEFAULT_AGENT: BaseVehicle.get_action_space_before_init(
                    self.config["vehicle_config"]["extra_action_dim"], self.config["discrete_action"],
                    self.config["discrete_steering_dim"], self.config["discrete_throttle_dim"]
                )
            }

    def lazy_init(self):
        """
        Only init once in runtime, variable here exists till the close_env is called
        :return: None
        """
        # It is the true init() func to create the main vehicle and its module, to avoid incompatible with ray
        if engine_initialized():
            return
        self.engine = initialize_engine(self.config)
        # engine setup
        self.setup_engine()
        # other optional initialization
        self._after_lazy_init()

    def _after_lazy_init(self):
        pass

    # ===== Run-time =====
    def step(self, actions: Union[np.ndarray, Dict[AnyStr, np.ndarray]]):
        actions = self._preprocess_actions(actions)
        engine_info = self._step_simulator(actions)
        o, r, d, i = self._get_step_return(actions, engine_info=engine_info)
        return o, r, d, i

    def _preprocess_actions(self, actions: Union[np.ndarray, Dict[AnyStr, np.ndarray]]) \
            -> Union[np.ndarray, Dict[AnyStr, np.ndarray]]:
        if not self.is_multi_agent:
            actions = {v_id: actions for v_id in self.vehicles.keys()}
        else:
            if self.config["vehicle_config"]["action_check"]:
                # Check whether some actions are not provided.
                given_keys = set(actions.keys())
                have_keys = set(self.vehicles.keys())
                assert given_keys == have_keys, "The input actions: {} have incompatible keys with existing {}!".format(
                    given_keys, have_keys
                )
            else:
                # That would be OK if extra actions is given. This is because, when evaluate a policy with naive
                # implementation, the "termination observation" will still be given in T=t-1. And at T=t, when you
                # collect action from policy(last_obs) without masking, then the action for "termination observation"
                # will still be computed. We just filter it out here.
                actions = {v_id: actions[v_id] for v_id in self.vehicles.keys()}
        return actions

    def _step_simulator(self, actions):
        # Note that we use shallow update for info dict in this function! This will accelerate system.
        scene_manager_before_step_infos = self.engine.before_step(actions)
        # step all entities
        self.engine.step(self.config["decision_repeat"])
        # update states, if restore from episode data, position and heading will be force set in update_state() function
        scene_manager_after_step_infos = self.engine.after_step()
        return merge_dicts(
            scene_manager_after_step_infos, scene_manager_before_step_infos, allow_new_keys=True, without_copy=True
        )

    def reward_function(self, vehicle_id: str) -> Tuple[float, Dict]:
        """
        Override this func to get a new reward function
        :param vehicle_id: name of this base vehicle
        :return: reward, reward info
        """
        raise NotImplementedError()

    def cost_function(self, vehicle_id: str) -> Tuple[float, Dict]:
        raise NotImplementedError()

    def done_function(self, vehicle_id: str) -> Tuple[bool, Dict]:
        raise NotImplementedError()

    def render(self, mode='human', text: Optional[Union[dict, str]] = None, *args, **kwargs) -> Optional[np.ndarray]:
        """
        This is a pseudo-render function, only used to update onscreen message when using panda3d backend
        :param mode: 'rgb'/'human'
        :param text:text to show
        :return: when mode is 'rgb', image array is returned
        """
        if mode in ["top_down", "topdown", "bev", "birdview"]:
            ret = self._render_topdown(text=text, *args, **kwargs)
            return ret
        assert self.config["use_render"] or self.engine.mode != RENDER_MODE_NONE, \
            ("Panda Renderring is off now, can not render")
        self.engine.render_frame(text)
        if mode != "human" and self.config["offscreen_render"]:
            # fetch img from img stack to be make this func compatible with other render func in RL setting
            return self.vehicle.observations.img_obs.get_image()

        if mode == "rgb_array" and self.config["use_render"]:
            if not hasattr(self, "_temporary_img_obs"):
                from metadrive.obs.observation_base import ImageObservation
                image_source = "rgb_camera"
                assert len(self.vehicles) == 1, "Multi-agent not supported yet!"
                self.temporary_img_obs = ImageObservation(self.vehicles[DEFAULT_AGENT].config, image_source, False)
            else:
                raise ValueError("Not implemented yet!")
            self.temporary_img_obs.observe(self.vehicles[DEFAULT_AGENT].image_sensors[image_source])
            return self.temporary_img_obs.get_image()

        # logging.warning("You do not set 'offscreen_render' or 'offscreen_render' to True, so no image will be returned!")
        return None

    def reset(self, force_seed: Union[None, int] = None):
        """
        Reset the env, scene can be restored and replayed by giving episode_data
        Reset the environment or load an episode from episode data to recover is
        :param force_seed: The seed to set the env.
        :return: None
        """
        self.lazy_init()  # it only works the first time when reset() is called to avoid the error when render
        self._reset_global_seed(force_seed)
        if self.engine is None:
            raise ValueError(
                "Current MetaDrive instance is broken. Please make sure there is only one active MetaDrive "
                "environment exists in one process. You can try to call env.close() and then call "
                "env.reset() to rescue this environment. However, a better and safer solution is to check the "
                "singleton of MetaDrive and restart your program."
            )
        self.engine.reset()
        if self._top_down_renderer is not None:
            self._top_down_renderer.reset(self.current_map)

        self.dones = {agent_id: False for agent_id in self.vehicles.keys()}
        self.episode_rewards = defaultdict(float)
        self.episode_lengths = defaultdict(int)

        assert (len(self.vehicles) == self.num_agents) or (self.num_agents == -1)

        return self._get_reset_return()

    def _get_reset_return(self):
        ret = {}
        self.engine.after_step()
        for v_id, v in self.vehicles.items():
            self.observations[v_id].reset(self, v)
            ret[v_id] = self.observations[v_id].observe(v)
        return ret if self.is_multi_agent else self._wrap_as_single_agent(ret)

    def _get_step_return(self, actions, engine_info):
        # update obs, dones, rewards, costs, calculate done at first !
        obses = {}
        done_infos = {}
        cost_infos = {}
        reward_infos = {}
        rewards = {}
        for v_id, v in self.vehicles.items():
            rewards[v_id], reward_infos[v_id] = self.reward_function(v_id)
            done_function_result, done_infos[v_id] = self.done_function(v_id)
            _, cost_infos[v_id] = self.cost_function(v_id)
            done = done_function_result or self.dones[v_id]
            self.dones[v_id] = done
            o = self.observations[v_id].observe(v)
            obses[v_id] = o

        step_infos = concat_step_infos([engine_info, done_infos, reward_infos, cost_infos])

        # For extreme case only. Force to terminate all vehicles if the environmental step exceeds 5 times horizon.
        should_external_done = False
        if self.config["horizon"] is not None:
            should_external_done = self.episode_step > 5 * self.config["horizon"]
        if should_external_done:
            for k in self.dones:
                self.dones[k] = True

        dones = {k: self.dones[k] for k in self.vehicles.keys()}
        for v_id, r in rewards.items():
            self.episode_rewards[v_id] += r
            step_infos[v_id]["episode_reward"] = self.episode_rewards[v_id]
            self.episode_lengths[v_id] += 1
            step_infos[v_id]["episode_length"] = self.episode_lengths[v_id]

        if not self.is_multi_agent:
            return self._wrap_as_single_agent(obses), self._wrap_as_single_agent(rewards), \
                   self._wrap_as_single_agent(dones), self._wrap_as_single_agent(step_infos)
        else:
            return obses, rewards, dones, step_infos

    def close(self):
        if self.engine is not None:
            close_engine()

    def force_close(self):
        print("Closing environment ... Please wait")
        self.close()
        time.sleep(2)  # Sleep two seconds
        raise KeyboardInterrupt("'Esc' is pressed. MetaDrive exits now.")

    def capture(self):
        img = PNMImage()
        self.engine.win.getScreenshot(img)
        img.write("main_{}.png".format(time.time()))

    def for_each_vehicle(self, func, *args, **kwargs):
        return self.agent_manager.for_each_active_agents(func, *args, **kwargs)

    @property
    def vehicle(self):
        """A helper to return the vehicle only in the single-agent environment!"""
        assert len(self.vehicles) == 1, (
            "env.vehicle is only supported in single-agent environment!"
            if len(self.vehicles) > 1 else "Please initialize the environment first!"
        )
        ego_v = self.vehicles[DEFAULT_AGENT]
        return ego_v

    def get_single_observation(self, vehicle_config: "Config"):
        if self.config["offscreen_render"]:
            o = ImageStateObservation(vehicle_config)
        else:
            o = LidarStateObservation(vehicle_config)
        return o

    def _wrap_as_single_agent(self, data):
        return data[next(iter(self.vehicles.keys()))]

    def seed(self, seed=None):
        if seed is not None:
            set_global_random_seed(seed)

    @property
    def current_seed(self):
        return self.engine.global_random_seed

    @property
    def observations(self):
        """
        Return observations of active and controllable vehicles
        :return: Dict
        """
        return self.agent_manager.get_observations()

    @property
    def observation_space(self) -> gym.Space:
        """
        Return observation spaces of active and controllable vehicles
        :return: Dict
        """
        ret = self.agent_manager.get_observation_spaces()
        if (not self.is_multi_agent) or self.config["return_single_space"]:
            return next(iter(ret.values()))
        else:
            return gym.spaces.Dict(ret)

    @property
    def action_space(self) -> gym.Space:
        """
        Return observation spaces of active and controllable vehicles
        :return: Dict
        """
        ret = self.agent_manager.get_action_spaces()
        if (not self.is_multi_agent) or self.config["return_single_space"]:
            return next(iter(ret.values()))
        else:
            return gym.spaces.Dict(ret)

    @property
    def vehicles(self):
        """
        Return all active vehicles
        :return: Dict[agent_id:vehicle]
        """
        return self.agent_manager.active_agents

    @property
    def vehicles_including_just_terminated(self):
        """
        Return all vehicles that occupy some space in current environments
        :return: Dict[agent_id:vehicle]
        """
        ret = self.agent_manager.active_agents
        ret.update(self.agent_manager.just_terminated_agents)
        return ret

    def setup_engine(self):
        """
        Engine setting after launching
        """
        self.engine.accept("r", self.reset)
        self.engine.accept("p", self.capture)
        self.engine.register_manager("agent_manager", self.agent_manager)
        self.engine.register_manager("record_manager", RecordManager())
        self.engine.register_manager("replay_manager", ReplayManager())

    @property
    def current_map(self):
        return self.engine.current_map

    def _reset_global_seed(self, force_seed=None):
        current_seed = force_seed if force_seed is not None else get_np_random(None).randint(0, int(1e4))
        self.seed(current_seed)

    @property
    def maps(self):
        return self.engine.map_manager.maps

    def _render_topdown(self, text, *args, **kwargs):
        return self.engine.render_topdown(text, *args, **kwargs)

    @property
    def main_camera(self):
        return self.engine.main_camera

    @property
    def current_track_vehicle(self):
        return self.engine.current_track_vehicle

    @property
    def _top_down_renderer(self):
        return self.engine._top_down_renderer

    @property
    def episode_step(self):
        return self.engine.episode_step if self.engine is not None else 0


from flask import Blueprint, flash, render_template, request, url_for, redirect
from . import db
from .models import Expenses
from .forms import EditExpense
from flask_login import current_user, login_required
from datetime import date

views = Blueprint('views', __name__)

# CREATE
@views.route('/add_expense', methods=['GET', 'POST'])
@login_required
def adding_new_expenses():

    form = EditExpense(request.form)

    if form.validate_on_submit():
        new_expense = Expenses(
            type= form.type.data,
            description = form.description.data,
            date_purchase = form.date.data,
            amount = form.amount.data,
            user = current_user.email
        )
        db.session.add(new_expense)
        db.session.commit()

        return redirect(url_for("views.show_expenses"))

    return render_template("add_expense.html", form=form)

# READ
@views.route('/expenses')
@login_required
def show_expenses():

    expenses_user = Expenses.query.filter_by(user=current_user.email).all()

    total_amount = 0
    for expense in expenses_user:
        total_amount += expense.amount

    return render_template("expenses.html", expenses=expenses_user,
                           name_user=current_user.name, total=round(total_amount,2))

# UPDATE
@views.route('/mod_expense/<int:expense_id>', methods=['GET', 'POST'])
@login_required
def modifying_expenses(expense_id):

    expense = Expenses.query.filter(Expenses.user==current_user.email, Expenses.expense_id==expense_id).first()
    if not expense:
        flash('You do not have this expense.', category='error')
        return redirect(url_for("views.show_expenses"))

    form = EditExpense(request.form)

    if form.validate_on_submit():
        expense.type = form.type.data
        expense.description = form.description.data
        expense.date_purchase = form.date.data
        expense.amount = form.amount.data
        db.session.commit()

        return redirect(url_for("views.show_expenses"))

    else:
        if request.method == 'GET':
            form = EditExpense(
                data = {
                    "type": expense.type,
                    "description": expense.description,
                    "date": date(int(expense.date_purchase[:4]), int(expense.date_purchase[5:7]), int(expense.date_purchase[8:])),
                    "amount": expense.amount
                    }
                )
        return render_template("mod_expense.html", form=form)

# DELETE
@views.route('/del_expense', methods=['POST'])
@login_required
def deleting_expenses():

    expense = Expenses.query.filter(Expenses.user==current_user.email, Expenses.expense_id==request.form.get("id")).first()
    if expense:
        db.session.delete(expense)
        db.session.commit()

    return redirect(url_for("views.show_expenses"))


import random
from tkinter import *

class CallsignGenerator () :
    origFirst = ""
    origLast = ""

    firstList= ["Agile","Able","Proud","Just","Electric","Nimble","Swift","Silent","Saucy","Bold","Bold","Viscious","Icy"]
    lastList = ["Cobra","Badger","Bones","Dagger",]

    #methods
    def __init__(self,firstDate, lastDate):
        self.origFirst = firstDate
        self.origLast = lastDate

    def CreateName (self) :
        x= random.randint(0, len (self.firstList) -1)
        y=random.randint(0, len (self.lastList) -1)
        return self.firstList [x] + self.lastList [y]

def buttonClick():
    #get the info out of the boxes
    first = fText.get()
    last = lText.get()

    #Create an instance of our generator class
    mygen = CallsignGenerator(first, last)

    #run the generator
    cSign = mygen.CreateName()

    #show it on the screen
    output.config (text = cSign, image=Banner, compound = CENTER)

root = Tk()

Banner = PhotoImage(file="USAF_Symbol.gif")
Banner = Banner.subsample(4,4)

ft = "verdana 14"
title = Label (root, text= "what's your Aviator Callsign?", font="Verdana 20")
fLabel = Label(root, text="Month", font= ft)
fText = Entry(root, font="Verdana 14")
lLabel = Label(root, text="Day", font= ft)
lText = Entry(root, font="Verdana 14")
btn = Button(root, font = ft, text="generate name", command=buttonClick)
output = Label(root, image=Banner)

title.pack()
fLabel.pack()
fText.pack()
lLabel.pack()
lText.pack()
btn.pack()
output.pack()

root.mainloop()


import pandas as pd
import numpy as np
import torch
import torch.nn as nn
from torch.optim import Adam
import matplotlib.pyplot as plt

class RNN(nn.Module):
    def __init__(self, input_size, latent, n_class, batch_size):
        super(RNN, self).__init__()
        self.repeated_block = nn.Linear(input_size + latent, latent)
        self.activation = nn.Tanh()
        self.default_ini_h = torch.zeros((batch_size, latent))
        assert self.default_ini_h.requires_grad == False

        self.linear_classifier = nn.Linear(latent, n_class)

    def forward(self, x, h=None):
        """
        x:      length, batch, dim
        h:              batch, latent
        return: length, batch, latent
        """
        if h is None:
            h = self.default_ini_h

        for l in range(x.shape[0]):
            h = self.one_step(x[l], h)

        res = self.linear_classifier(h)
        return res

    def one_step(self, x, h):
        """
        x:      batch, dim
        h:      batch, latent
        return; batch, latent
        """
        # print("x", x.shape)
        # print("h", h.shape)
        concat = torch.cat((x.double().transpose(0, 1), h.double().transpose(0, 1)))
        concat = concat.transpose(0, 1)
        res = self.repeated_block(concat)
        res = self.activation(res)
        return res

# def train(rnn, loss, optim, temp, cities, epoch,):
    # for e in range(epoch):

def main_pred_city_from_temps(cities, temp):
    target = pd.Categorical(pd.Series(temp.columns[1:]))
    target = pd.get_dummies(target) # one hot encoder
    target = torch.tensor(target.values)

    # target = DataLoader(target)
    temp = temp.drop(columns="datetime")
    temp = temp.fillna(temp.median())
    # temp = temp.drop(axis=0)
    temp = torch.tensor(temp.values)
    # temp = DataLoader(temp)

    # print(target.shape)

    input_size = 1
    latent_size = 10
    batch_size = 8
    test_size = 100

    rnn = RNN(input_size, latent_size, batch_size=batch_size, n_class=30).double()
    loss = nn.CrossEntropyLoss()
    optim = Adam(rnn.parameters(), lr=1e-4)

    sequence_size = 10
    iter_max = 10000

    # création jeu de test
    test_indice = np.random.randint(temp.shape[0] - test_size , temp.shape[0] - sequence_size, batch_size)
    test_indice_ville = np.random.randint(0,len(target),batch_size)
    test_x = []
    test_y = []
    for indice,i in enumerate(test_indice):
        test_x.append(temp[i:i+sequence_size,test_indice_ville[indice]])
        test_y.append(np.argmax(target[test_indice_ville[indice]]))
    test_x = torch.stack(test_x).transpose(0, 1).unsqueeze(2)
    test_y = torch.stack(test_y).long()
    test_x.requires_grad = False
    test_y.requires_grad = False

    print(temp.shape)
    print(target.shape)
    list_loss = []
    for e in range(iter_max):
        indices_batch = np.random.randint(0, temp.shape[0] - test_size - sequence_size, batch_size)
        indice_ville = np.random.randint(0,len(target),batch_size)
        batch_x = []
        batch_y = []
        for indice,i in enumerate(indices_batch):
            batch_x.append(temp[i:i+sequence_size,indice_ville[indice]])
            batch_y.append(np.argmax(target[indice_ville[indice]]))
        batch_x = torch.stack(batch_x).transpose(0, 1).unsqueeze(2)
        batch_y = torch.stack(batch_y).long()

        test_y_pred = rnn(test_x)
        test_l = loss(test_y_pred, test_y)
        list_loss.append(test_l.item())

        optim.zero_grad()
        y_pred = rnn(batch_x)
        l = loss(y_pred, batch_y)/ sequence_size
        l.backward()
        optim.step()

        """
        if np.isnan(l.item()):
            print("batchx", batch_x)
            print(indices_batch)
            print(indice_ville)
            print(batch_y)
            print(y_pred)
            assert 0
        """

    #print(list_loss)
    plt.plot(list_loss)
    plt.show()

def main():
    cities = pd.read_csv("city_attributes.csv")
    temp = pd.read_csv("temp_train.csv")
    main_pred_city_from_temps(cities, temp)

if __name__ == '__main__':
    main()


#실습
#분류 -> eval_metric을 찾아서 추가
from sklearn import datasets
from xgboost import XGBRegressor,XGBRFRegressor
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.metrics import r2_score
from sklearn.preprocessing import MinMaxScaler, StandardScaler

#1. 데이터
dataset = load_diabetes()
x= dataset['data']
y = dataset['target']

print(x.shape, y.shape) #(506, 13) (506,)

from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test =train_test_split(
    x,y, train_size=0.8, random_state=66)

# scaler =MinMaxScaler()
scaler = StandardScaler()
# scaler.fit(x_train)
# x_train = scaler.transform(x_train)
# x_test = scaler.transform(x_test)

#2.모델
model = XGBRegressor(n_estimators=20, learning_rate=0.05, n_jobs=1)

'''
params = {
  'colsample_bynode': 0.8,
  'learning_rate': 1,
  'max_depth': 5,
  'num_parallel_tree': 100,
  'objective': 'binary:logistic',
  'subsample': 0.8,
  'tree_method': 'gpu_hist'
}

'''

#3. 훈련
model.fit(x_train, y_train,verbose=1,
eval_metric=['rmse','logloss']
,eval_set=[(x_train, y_train),(x_test, y_test)])

#4. 평가
results = model.score(x_test, y_test)
print("results:", results)

y_predict =model.predict(x_test)
r2 =r2_score(y_test, y_predict)
print("r2:", r2)

print("====================================")
hist = model.evals_result()
print(hist)

# A = hist['validation_0']
# B = hist['validation_1']

# histA = dict(A)
# histB = dict(B)

# print(type(hist))
# print(histA['rmse'].history)

# import matplotlib.pyplot as plt

# plt.figure(figsize=(12, 4))

# plt.subplot(1, 2, 1)
# plt.title('loss of XGBRegressor', fontsize= 15)
# plt.plot(histA['rmse'], 'b-', label='rmse')
# plt.plot(histB['rmse'],'r--', label='val_rmse')
# plt.xlabel('Epoch')
# plt.legend()

# plt.subplot(1, 2, 2)
# plt.title('accuracy of Bidirectional LSTM (model3) ', fontsize= 15)
# plt.plot(hist.history['mae'], 'g-', label='mae')
# plt.plot(hist.history['val_mae'],'k--', label='val_mae')
# plt.xlabel('Epoch')
# plt.legend()

print("--------------------------선생님 코드----------------")
import matplotlib.pyplot as plt

epochs = len(results['validation_0']['rmse'])
x_axis = range(0, epochs)

fig, ax = plt.subplots()
ax.plot(x_axis, results['validation_0']['logloss'], label='Train')
ax.plot(x_axis, results['validation_1']['logloss'], label='Test')
ax.legend()
plt.ylabel('Log Loss')
plt.title('XGBoost Log Loss')
# plt.show()

fig, ax = plt.subplots()
ax.plot(x_axis, results['validation_0']['rmse'], label='Train')
ax.plot(x_axis, results['validation_1']['rmse'], label='Test')
ax.legend()
plt.ylabel('Rmse')
plt.title('XGBoost RMSE')
plt.show()


from aiogram import types
from aiogram.dispatcher import FSMContext

from DB.models import Student

async def check_privilege_whose(message: types.message, state: FSMContext):
    whose = (await Student.filter(chat_id=message.chat.id).values_list('whose_schedule'))
    whose = whose[0][0]
    list_data: dict = (await state.get_data())
    print(list_data.get('captain_middleware'))
    print(f'whose: {whose}')
    if whose == 'g' and list_data.get('captain_middleware'):
        return 0
    elif whose == 'p':
        return 0
    else:
        await message.answer('Вы не староста и не можете менять расписание группы. Попросите у старосты права или '
                             'используйте персональное расписание.\n'
                             'Персональное расписание можно использовать по умолчанию, зайдя в '
                             '"Настройки аккаунта" -> "Тип расписания"')
        return 1


import cv2
import numpy as np
import os
import glob
import time
import timeit
cap = cv2.VideoCapture('out.mkv')
# net = cv2.dnn.readNet("yolov3-tiny-obj_3800.weights","yolov3.cfg")
def myfun(file1):
    net = cv2.dnn.readNet("/home/kankan/Documents/backup/yolov3_20000.weights", "/home/kankan/PycharmProjects/YoloTrafficSignal/yolov3.cfg")
    classes = []
    with open("coco.names","r") as f:
        classes = [line.strip() for line in f.readlines()]
        print(classes)
    layer_names = net.getLayerNames()
    outputlayers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]

    # colors= np.random.uniform(0,255,size=(len(classes),3))
    # img = cv2.imread("00000001.png")
    img = cv2.imread(file1)
    img = cv2.resize(img,None,fx=1,fy=1)
    height,width,channels = img.shape

    #detecting objects
    blob = cv2.dnn.blobFromImage(img,0.00392,(608,608),(0,0,0),True,crop=False)
    net.setInput(blob)
    outs = net.forward(outputlayers)
    # print(outs[1])

    # Showing info on screen/ get confidence score of algorithm in detecting an object in blob
    class_ids = []
    confidences = []
    boxes = []
    for out in outs:
        for detection in out:
            scores = detection[5:]
            class_id = np.argmax(scores)
            confidence = scores[class_id]
            if confidence > 0.1:
                # onject detected
                center_x = int(detection[0] * width)
                center_y = int(detection[1] * height)
                w = int(detection[2] * width)
                h = int(detection[3] * height)

                # cv2.circle(img,(center_x,center_y),10,(0,255,0),2)
                # rectangle co-ordinaters
                x = int(center_x - w / 2)
                y = int(center_y - h / 2)
                # cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)

                boxes.append([x, y, w, h])  # put all rectangle areas
                confidences.append(float(confidence))  # how confidence was that object detected and show that percentage
                class_ids.append(class_id)  # name of the object tha was detected

    indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.4, 0.6)
    print(class_ids)
    font = cv2.FONT_HERSHEY_PLAIN
    for i in range(len(boxes)):
        if i in indexes:
            x, y, w, h = boxes[i]
            label = str(classes[class_ids[i]])
            print("Value of i=",i)
            color = (255,0,0)
            cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
            cv2.putText(img, label, (x, y + 30), font, 1, (255, 255, 255), 2)
    # return img
    cv2.imshow("Image", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

# print(timeit.timeit(myfun,number=10)/10)
myfun("/home/kankan/carla/Dist/CARLA_Shipping_0.9.7-2-g73f91e0b/LinuxNoEditor/PythonAPI/examples/_out/00156202.png")

# while cap.isOpened():
#     ret, frame = cap.read()
#     # if frame is read correctly ret is True
#     if not ret:
#         print("Can't receive frame (stream end?). Exiting ...")
#         break
#     cv2.imshow('frame', myfun(frame))
#     if cv2.waitKey(1) == ord('q'):
#         break
# cap.release()
# cv2.destroyAllWindows()


import random
from sqlalchemy.orm import Session
from typing import List, Tuple
from models.models import CardPlayed, Player

# Define a function to create and return a deck of cards
def create_deck():
    ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"]
    suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
    deck = [[rank, suit] for rank in ranks for suit in suits]
    random.shuffle(deck)
    return deck

# Define a function to draw three cards
def deal_hand(deck):
    hand = deck[:3]
    del deck[:3]
    return hand

# define a function to get the rank values of cards
def rank_card(card_rank):
    rank_map = {
        "2": 2,
        "3": 3,
        "4": 4,
        "5": 5,
        "6": 6,
        "7": 7,
        "8": 8,
        "9": 9,
        "T": 10,
        "J": 11,
        "Q": 12,
        "K": 13,
        "A": 14,
    }
    return rank_map.get(card_rank, 0)  # Using the first character as the key, return 0 if not found.

# Define a funtion to rank hand
def rank_hand(hand):
    values = [rank_card(card[0]) for card in hand]
    suits = [card[1] for card in hand]
    value_count = {value: values.count(value) for value in values}

    for value, count in value_count.items():
        if count == 3:
            return 4, value
        if count == 2:
            return 3, value

    if all(values[i] + 1 == values[i + 1] for i in range(len(values) - 1)):
        if len(set(suits)) == 1:
            return 5, max(values)
        else:
            return 2, max(values)

    if len(set(suits)) == 1:
        return 1, max(values)

    return 0, max(values)

# function to get a player hand
def get_player_hand(
    db: Session, player_id: int, lobby_id: int
) -> List[Tuple[str, str]]:
    query = (
        db.query(CardPlayed.card_rank, CardPlayed.card_suite)
        .filter(CardPlayed.player_id == player_id, CardPlayed.lobby_id == lobby_id,entity='Player')
        .all()
    )

    if not query:
        return []  # Or some other default value, maybe raise an exception

    hand = [(card_rank, card_suite) for card_rank, card_suite in query]
    return hand

# function to update player balance
def update_player_balance(player_id, amount,db):
    player = db.query(Player).filter(Player.id == player_id).first()
    player.balance += amount

# hand = deal_hand(create_deck())

# # hand = [['K', 'Diamonds'], ['A', 'Diamonds'], ['K', 'Clubs']]
# print(hand)

# rank=(rank_hand(hand))
# print(rank)


import re
import subprocess
from dataclasses import dataclass
from typing import List

import chardet

__all__ = ["parse_table", "run_command"]

@dataclass
class RunCommand:
    stdout: str
    returncode: int

def split_by_whitespace(text: str) -> List[str]:
    return re.split(r"\s{2,}", text.strip())

def split_by_line(text: str) -> List[str]:
    return text.split("\n\n")

def parse_table(output) -> List[List[str]]:
    lines = split_by_line(output)
    lines = [split_by_whitespace(line) for line in lines]
    return lines

def detect_encoding(input: bytes) -> str:
    encoding = chardet.detect(input)["encoding"]

    if encoding is None:
        raise Exception("Could not detect encoding")

    return encoding

def run_command(command: str) -> RunCommand:
    output = subprocess.run(
        command, shell=True, capture_output=True, text=True
    )
    stdout = output.stdout
    decoded_output = stdout.replace("\x00", "")
    return RunCommand(decoded_output, output.returncode)


from collections import defaultdict
import heapq

def solution(N, road, K):
    answer = 0

    graph = defaultdict(list)
    for a, b, w in road:
        graph[a].append((b, w))
        graph[b].append((a, w))

    visited = [float('inf')] * (N+1)
    visited[1] = 0

    heap = [(1, 0)]

    while heap:
        n, dist = heapq.heappop(heap)

        if visited[n] < dist:
            continue

        for adj_n, adj_w in graph[n]:
            new_dist = dist + adj_w

            if visited[adj_n] > new_dist:
                visited[adj_n] = new_dist
                heapq.heappush(heap, (adj_n, new_dist))

    for idx in range(1, N+1):
        if visited[idx] <= K:
            answer += 1

    return answer


from logic import TruthTable

NextTable = TruthTable(['q -> r' ,'p -> (q -> r)'])
NextTable.display()
NextTable.latex()

TheTable = TruthTable(['p and q','(p and q) -> r'])
TheTable.display()
TheTable.latex()

NoTable = TruthTable(['q -> r', 'p -> (q -> r)'])
NoTable.display()
NoTable.latex()

YesTable = TruthTable(['p -> q', '(p -> q) -> r'])
YesTable.display()
YesTable.latex()


import cv2
import queue
import time
import threading
import os
import detect

q=queue.Queue()

def Receive():
    print("start Reveive")
    cap = cv2.VideoCapture("rtsp://admin:admin123@192.168.43.245:8554/unicast")
    ret, frame = cap.read()
    q.put(frame)
    while ret and p2.is_alive():
        ret, frame = cap.read()
        q.put(frame)
    cap.release()

def Display():
     print("Start Displaying")
     a = False
     while True:
        if q.empty() !=True:
            frame=q.get()
            if frame is not None:
                if a:
                    idxs, boxes, classIDs, confidences = detect.detect(frame)
                    frame2 = detect.draw_frame(idxs, boxes, classIDs, confidences, frame)
                    cv2.imshow("frame2", frame2)
                    a = False
                cv2.imshow("frame1", frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        if cv2.waitKey(1) == ord('x'):
            a = True

p1 = threading.Thread(target=Receive)
p2 = threading.Thread(target=Display)

if __name__=='__main__':

    p1.start()
    p2.start()


def solution(n, cores):
    if n <= len(cores):
        return n
    n -= len(cores)
    start, end = 0, max(cores) * n
    while start < end:
        mid = (start + end) // 2
        work = 0
        for i in range(len(cores)):
            work += mid // cores[i]
        if work >= n:
            end = mid
        else:
            start = mid + 1

    for c in cores:
        n -= (end - 1) // c

    for i in range(len(cores)):
        if end % cores[i] == 0:
            n -= 1
            if n == 0:
                return i + 1


#!/usr/bin/env python

import io
import json

from visualize import read_symbols

try:
    to_unicode = unicode
except NameError:
    to_unicode = str

with open("order.json") as f:
    order = json.load(f)

symbols = read_symbols()
perm = [symbols.index(el) for el in order]

with open('perm-manual.json', 'w', encoding='utf8') as outfile:
    str_ = json.dumps(perm,
                      indent=4, sort_keys=True,
                      separators=(',', ':'), ensure_ascii=False)
    outfile.write(to_unicode(str_))


from tkinter import *

root = Tk()
#Creating a widget
myLabel = Label(root, text="Please enter your prefered Temp")
#push it onto the screen
myLabel.pack(pady = 10)

#create entry field
setTemp = Entry(root, text="Enter temp Value")
setTemp.pack(pady=10)

#create button
setTemp_button = Button(root, text="Set Temp")
setTemp_button.pack(pady=10)

#create entry field
mainReply = Entry(root, text=" ")
mainReply.pack(pady=40)

root.mainloop()


# -*- coding: utf-8 -*
'''
9. 鸡尾酒排序(Cocktail sort)

原理

鸡尾酒排序也就是定向冒泡排序,
鸡尾酒搅拌排序, 搅拌排序 (也可以视作选择排序的一种变形), 涟漪排序,来回排序 or 快乐小时排序, 是冒泡排序的一种变形。
此算法与冒泡排序的不同处在于排序时是以双向在序列中进行排序。
数组中的数字本是无规律的排放，先找到最小的数字，把他放到第一位，然后找到最大的数字放到最后一位。
然后再找到第二小的数字放到第二位，再找到第二大的数字放到倒数第二位。以此类推，直到完成排序。

'''
def cocktail_sort(l):
    size = len(l)
    # 假如一趟来回没有交换任何数字,则表示该数组已经有序了,可以设置了个变量表示有没有交换过
    sign = True
    for i in range(size / 2):
        if sign:
            sign = False
            for j in range(i, size - 1 - i):
                if l[j] > l[j + 1]:
                    l[j], l[j + 1] = l[j + 1], l[j]
                    sign = True
            # print(l)
            for k in range(size - 2 - i, i, -1):
                if l[k] < l[k - 1]:
                    l[k], l[k - 1] = l[k - 1], l[k]
                    sign = True
            # print(l)
        else:
            break
    # return l
a = [3, 1, 5, 7, 2, 4, 9, 6, 8]
cocktail_sort(a)
print(a)


#!/usr/bin/env python

import sys
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtCore import Qt

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        self.label = QtWidgets.QLabel()
        canvas = QtGui.QPixmap(400, 300)
        canvas.fill(Qt.white)
        self.label.setPixmap(canvas)
        self.setCentralWidget(self.label)
        self.draw_something_line()
        self.draw_something_point()
        self.draw_something_rects()
        self.draw_something_rounded_rects()
        self.draw_something_ellipses()
        self.draw_something_text()

    def draw_something_line(self):
        pen = QtGui.QPen()
        pen.setWidth(15)
        pen.setColor(QtGui.QColor('blue'))
        painter = QtGui.QPainter(self.label.pixmap())
        painter.setPen(pen)
        painter.drawLine(10, 10, 300, 200)
        painter.end()

    def draw_something_point(self):
    #    painter = QtGui.QPainter(self.label.pixmap())
    #    painter.drawPoint(200, 150)
    #    painter.end()
    #def draw_something(self):
        painter = QtGui.QPainter(self.label.pixmap())
        pen = QtGui.QPen()
        pen.setWidth(40)
        pen.setColor(QtGui.QColor('red'))
        painter.setPen(pen)
        painter.drawPoint(200, 150)
        painter.end()

    def draw_something_rects(self):
        from random import randint
        painter = QtGui.QPainter(self.label.pixmap())
        pen = QtGui.QPen()
        pen.setWidth(3)
        pen.setColor(QtGui.QColor("#376F9F"))
        painter.setPen(pen)

        brush = QtGui.QBrush()
        brush.setColor(QtGui.QColor("#FFD141"))
        brush.setStyle(Qt.Dense1Pattern)
        painter.setBrush(brush)

        painter.drawRects(
            QtCore.QRect(50, 50, 100, 100),
            QtCore.QRect(60, 60, 150, 100),
            QtCore.QRect(70, 70, 100, 150),
            QtCore.QRect(80, 80, 150, 100),
            QtCore.QRect(90, 90, 100, 150),
        )
        painter.end()

    def draw_something_rounded_rects(self):
        from random import randint
        painter = QtGui.QPainter(self.label.pixmap())
        pen = QtGui.QPen()
        pen.setWidth(3)
        pen.setColor(QtGui.QColor("#376F9F"))
        painter.setPen(pen)
        painter.drawRoundedRect(40, 40, 100, 100, 10, 10)
        painter.drawRoundedRect(80, 80, 100, 100, 10, 50)
        painter.drawRoundedRect(120, 120, 100, 100, 50, 10)
        painter.drawRoundedRect(160, 160, 100, 100, 50, 50)
        painter.end()

    def draw_something_ellipses(self):
        from random import randint
        painter = QtGui.QPainter(self.label.pixmap())
        pen = QtGui.QPen()
        pen.setWidth(3)
        pen.setColor(QtGui.QColor(204,0,0))  # r, g, b
        painter.setPen(pen)

        painter.drawEllipse(10, 10, 100, 100)
        painter.drawEllipse(10, 10, 150, 200)
        painter.drawEllipse(10, 10, 200, 300)
        painter.end()

    def draw_something_text(self):
        from random import randint
        painter = QtGui.QPainter(self.label.pixmap())
        pen = QtGui.QPen()
        pen.setWidth(1)
        pen.setColor(QtGui.QColor('green'))
        painter.setPen(pen)
        font = QtGui.QFont()
        font.setFamily('Times')
        font.setBold(True)
        font.setPointSize(40)
        painter.setFont(font)
        painter.drawText(100, 100, 'Hello, world!')
        painter.end()

app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()


from gi.repository import Gdk, Gtk

def create_menuitem(text, icon):
    """ Create menu item with icon """
    icontheme = Gtk.IconTheme.get_default()
    pb = icontheme.load_icon(icon, 16, 0)
    img = Gtk.Image()
    img.set_from_pixbuf(pb)
    menuitem = Gtk.ImageMenuItem()
    menuitem.set_image(img)
    menuitem.set_label(text)
    return menuitem

def create_toolbutton(text, icon):
    """ Toolbar button """
    button = Gtk.ToolButton()
    button.set_icon_name(icon)
    button.set_tooltip_text(text)
    return button

def rgba_to_hex(rgba):
    """ Return #RRGGBB """
    r = int(rgba.red * 255)
    g = int(rgba.green * 255)
    b = int(rgba.blue * 255)
    return "#{0:02x}{1:02x}{2:02x}".format(r, g, b)

def hex_to_rgba(hex):
    """ Return RGBA """
    rgba = Gdk.RGBA()
    rgba.red = int(hex[1:3], 16) / 255
    rgba.green = int(hex[3:5], 16) / 255
    rgba.blue = int(hex[5:7], 16) / 255
    return rgba

def get_playback_label(play=True):
    """ Return text and icon for playback menu/button """
    if play:
        text = _("Play")
        icon = "media-playback-start"
    else:
        text = _("Stop")
        icon = "media-playback-stop"
    return text, icon

def get_record_label(record=True):
    """ Return text and icon for record menu/button """
    if record:
        text = _("Record program")
        icon = "media-record"
    else:
        text = _("Stop recording")
        icon = "media-playback-stop"
    return text, icon

def get_volume_label(muted=False):
    """ Return text and icon for volume button """
    if muted:
        text = _("Unmute")
        icon = "audio-volume-muted"
    else:
        text = _("Mute")
        icon = "audio-volume-high"
    return text, icon


import os, cv2
import torch
from pathlib import Path
from multiprocessing import freeze_support

def extract_frames(input_video_path, output_imgs_path):
    # Open the video file
    vidcap = cv2.VideoCapture(input_video_path)

    # Get the total number of frames in the video
    frame_count = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))

    # Create the output directory if it does not exist
    os.makedirs(output_imgs_path, exist_ok=True)

    # Extract the frames
    for i in range(frame_count):
        success, image = vidcap.read()
        if success:
            cv2.imwrite(os.path.join(output_imgs_path, f"frame{i}.png"), image)
    print(f"{frame_count} frames extracted and saved to {output_imgs_path}")

def video2humanmasks(input_frames_path, output_folder_path, output_type, fps):
    # freeze support is needed for video outputting
    freeze_support()

    # check if input path exists and is a directory
    if not os.path.exists(input_frames_path) or not os.path.isdir(input_frames_path):
        raise ValueError("Invalid input path: {}".format(input_frames_path))

    # check if output path exists and is a directory
    if not os.path.exists(output_folder_path) or not os.path.isdir(output_folder_path):
        raise ValueError("Invalid output path: {}".format(output_folder_path))

    # check if output_type is valid
    valid_output_types = ["video", "pngs", "both"]
    if output_type.lower() not in valid_output_types:
        raise ValueError("Invalid output type: {}. Must be one of {}".format(output_type, valid_output_types))

    # try to predict where torch cache lives, so we can try and fetch models from cache in the next step
    predicted_torch_model_cache_path = os.path.join(Path.home(), ".cache", "torch", "hub", "hithereai_RobustVideoMatting_master")
    predicted_rvm_cache_testilfe = os.path.join(predicted_torch_model_cache_path, "hubconf.py")

    # try to fetch the models from cache, and only if it can't be find, download from the internet (to enable offline usage)
    try:
        # Try to fetch the models from cache
        convert_video = torch.hub.load(predicted_torch_model_cache_path, "converter", source='local')
        model = torch.hub.load(predicted_torch_model_cache_path, "resnet50", source='local').cuda()
    except:
        # Download from the internet if not found in cache
        convert_video = torch.hub.load("hithereai/RobustVideoMatting", "converter")
        model = torch.hub.load("hithereai/RobustVideoMatting", "resnet50").cuda()

    output_alpha_vid_path = os.path.join(output_folder_path, "human_masked_video.mp4")
    # extract humans masks from the input folder' imgs.
    # in this step PNGs will be extracted only if output_type is set to PNGs. Otherwise a video will be made, and in the case of Both, the video will be extracted in the next step to PNGs
    convert_video(
    model,
    input_source=input_frames_path,  # full path of the folder that contains all of the extracted input imgs
    output_type='video' if output_type.upper() in ("VIDEO", "BOTH") else 'png_sequence',
    output_alpha=output_alpha_vid_path if output_type.upper() in ("VIDEO", "BOTH") else output_folder_path,
    output_video_mbps=4,
    output_video_fps=fps,
    downsample_ratio=None, # None for auto
    seq_chunk=12, # Process n frames at once for better parallelism
    progress=True # show extraction progress
    )

    if output_type.lower() == "both":
        extract_frames(output_alpha_vid_path, output_folder_path)


from enigma import *
from Screens.Screen import Screen
from Components.Button import Button
from Components.Label import Label
from Components.ActionMap import ActionMap

class AboutTeam(Screen):
    skin = """
    <screen name="AboutTeam" position="0,0" size="1280,720" title="About Team" flags="wfNoBorder" >
        <panel name="GenericLayoutLiteTemplate" />
        <widget name="about" font="Regular;24" position="65,80" size="680,490" halign="center" transparent="1" backgroundColor="background" />
    </screen>"""

    def __init__(self, session, args = 0):
        Screen.__init__(self, session)
        abouttxt = '\nAtemio4you Image Team:\n\n- ch3wb4kka (Developer)\n- satinfo (Developer)\n- skaman (Developer)\n- mmark (Graphics and Skin) \n\n-Betatesting:\n xionsenx, volatile, master\n\nFurther credits goes to:\n- Atemio4You Team\n- ProjectMan for his great support\n\n- OE-Alliance, openViX, openPLi'
        self['about'] = Label(abouttxt)
        self['actions'] = ActionMap(['OkCancelActions', 'ColorActions'], {'cancel': self.quit}, -2)

    def quit(self):
        self.close()


import sys, getopt
import os
from collections import defaultdict
import unicodedata
import random
import string
import time

NUM_REPETITIONS = 5

def letter_count(text):
    """function used to implement the basic counter algorithm"""
    counters = defaultdict(int)
    for char in text:
        if char.isalpha() and char != "":
            char = remove_accents(char)
            counters[char] += 1
    sorted_counters = sorted(counters.items(), key=lambda x: x[1], reverse=True)
    return sorted_counters

def MisraGriesAlgorithm(text, k):
    """frequent counter algorithm"""
    A = {}
    for j in text:
        if j.isalpha():
            j = remove_accents(j)
            if j in A:
                A[j] = A[j] + 1
            else:
                if len(A) < k - 1:
                    A[j] = 1
                else:
                    for i in list(A.keys()):
                        A[i] = A[i] - 1
                        if A[i] == 0:
                            del A[i]
    return sorted(A.items(), key=lambda x: x[1], reverse=True)

def incrementLetter(x, m):
    t = x // m
    while t > 0:
        if random.getrandbits(1) == 1:
            return x
        t -= 1
    return x + 1

def estimate_frequent_letters(text, threshold):
    """function used to implement the Csuros counter algorithm"""
    letter_count = {letter: 0 for letter in string.ascii_uppercase}

    for char in text:
        if char.isalpha():
            char = remove_accents(char)
            if char != "":
                letter_count[char] = incrementLetter(letter_count[char], threshold)

    csuros_counter = sorted(letter_count.items(), key=lambda x: x[1], reverse=True)
    return csuros_counter

# remove accents from a string
def remove_accents(letter):
    """function used to remove accents from a letter"""
    return unicodedata.normalize("NFD", letter).encode("ascii", "ignore").decode()

def remove_punctuation(text):
    """function used to remove punctuation from a text"""
    translator = str.maketrans("", "", string.punctuation)

    return text.translate(translator)

def getArgs(argv):
    folder = "collections/"
    K = 10
    opts, args = getopt.getopt(argv, "hf:k:", ["folder="])
    for opt, arg in opts:
        if opt == "-h":
            print("python3 frequent_count.py -f <folderToFiles> -k <number of K>")
            sys.exit()
        elif opt in ("-f", "--folder"):
            folder += arg
        elif opt == "-k":
            K = arg
    return (folder, int(K))

def getAllFiles(folder):
    all_files = []
    for root, dirs, files in os.walk(folder):
        for file in files:
            if file.endswith(".txt"):
                tmp = root + "/" + file
                all_files.append(tmp)
    return all_files

if __name__ == "__main__":

    folder, K = getArgs(sys.argv[1:])

    absoluteErrorCsurosCounterAvg = 0
    absoluteErrorFrequentCounterAvg = 0
    relativeErrorCsurosCounterAvg = 0
    relativeErrorFrequentCounterAvg = 0

    all_text_files = getAllFiles(folder)
    numFiles = len(all_text_files)

    if not os.path.isdir("results"):
        os.mkdir("results")

    for file in all_text_files:
        start = time.time()

        # abre o ficheiro de texto
        f = open(file, "r")
        # lê o ficheiro, remove espaços em branco e converte para maiúsculas
        text = f.read().strip().upper()
        # remove pontuação
        text = remove_punctuation(text)
        # converte o texto numa lista de palavras
        text = text.split(" ")

        # remove os \n e espaços em branco
        text = [word.replace("\n", "") for word in text if word != ""]
        # fecha o ficheiro
        f.close()

        # vê qual o idioma do ficheiro para abrir o ficheiro de stopwords correto
        name, language = file.split("/")[-1].split("_")
        language = language.replace(".txt", "")

        print(file.upper(), end="\r")
        # abre o ficheiro de stopwords
        f = open("stopwords/stopwords_" + language + ".txt", "r")
        # lê o ficheiro, remove espaços em branco, converte para maiúsculas e guarda numa lista
        stopWords = f.read().strip().upper().split("\n")

        # remove os espaços em branco
        stopWords = [word for word in text if word != ""]
        # fecha o ficheiro
        f.close()

        # remove as stopwords do texto
        for word in text:
            if word in stopWords:
                text.remove(word)

        text = " ".join(text)

        elapsedTimeTreatingFile = time.time() - start

        resultsFile = open(f"results/{name}_{language}.txt", "w")

        resultsFile.write("{:s}\n".format("Basic Counter"))

        # Exact counter
        startAlgorithm = time.time()
        exact_counter = letter_count(text)
        for letter, freq in exact_counter:
            resultsFile.write("%5s : %3d\n" % (letter, freq))

        totalElapsedTime = time.time() - startAlgorithm + elapsedTimeTreatingFile
        resultsFile.write(
            "{:s} : {:f}\n".format("Total Elapsed Time", totalElapsedTime)
        )
        #

        # Csuros counter
        startAlgorithm = time.time()
        resultsFile.write("\n{:s}\n".format("Csuros Counter"))
        csuros_counter = estimate_frequent_letters(text, 5000)
        for letter, freq in csuros_counter:
            resultsFile.write("%5s : %3d\n" % (letter, freq))

        totalElapsedTime = time.time() - startAlgorithm + elapsedTimeTreatingFile
        resultsFile.write(
            "{:s} : {:f}\n".format("Total Elapsed Time", totalElapsedTime)
        )
        #

        # Frequent counter
        startAlgorithm = time.time()
        resultsFile.write("\n{:s}\n".format("Frequent Counter"))
        frequent_counter = MisraGriesAlgorithm(text, K)

        for letter, freq in frequent_counter:
            resultsFile.write("%5s : %3d\n" % (letter, freq))

        totalElapsedTime = time.time() - startAlgorithm + elapsedTimeTreatingFile
        resultsFile.write(
            "{:s} : {:f}\n".format("Total Elapsed Time", totalElapsedTime)
        )

        # guarda os erros absolutos e relativos em dicionários
        absoluteErrorsCsurosCounter = {}
        absoluteErrorsFrequentCounter = {}
        relativeErrorsCsurosCounter = {}
        relativeErrorsFrequentCounter = {}

        exact_counter = dict(exact_counter)

        for letter, app_freq in csuros_counter:
            if letter in exact_counter:
                real_count = exact_counter[letter]
                if app_freq != real_count:
                    absoluteErrorsCsurosCounter[letter] = abs(real_count - app_freq)
                    relativeErrorsCsurosCounter[letter] = (
                        abs(real_count - app_freq)
                    ) / real_count

        for letter, app_freq in frequent_counter:
            if letter in exact_counter:
                real_count = exact_counter[letter]
                if app_freq != real_count:
                    absoluteErrorsFrequentCounter[letter] = abs(real_count - app_freq)
                    relativeErrorsFrequentCounter[letter] = (
                        abs(real_count - app_freq)
                    ) / real_count

        resultsFile.write("\n{:^s}\n".format("Absolute error csuros' counter"))
        for letter, freq in absoluteErrorsCsurosCounter.items():
            resultsFile.write("%5s : %3d\n" % (letter, freq))

        resultsFile.write("\n{:s}\n".format("Absolute error frequent counter"))
        for letter, freq in absoluteErrorsFrequentCounter.items():
            resultsFile.write("%5s : %3d\n" % (letter, freq))

        resultsFile.write("\n{:s}\n".format("Relative error csuros' counter"))
        for letter, freq in relativeErrorsCsurosCounter.items():
            resultsFile.write("%5s : %3f\n" % (letter, freq))

        resultsFile.write("\n{:s}\n".format("Relative error frequent counter"))
        for letter, freq in relativeErrorsFrequentCounter.items():
            resultsFile.write("%5s : %3f\n" % (letter, freq))

        # calcular o erro absoluto e relativo médio
        if len(absoluteErrorsCsurosCounter) > 0:
            absoluteErrorCsurosCounterAvg += sum(
                absoluteErrorsCsurosCounter.values()
            ) / len(absoluteErrorsCsurosCounter)

        if len(absoluteErrorsFrequentCounter) > 0:
            absoluteErrorFrequentCounterAvg += sum(
                absoluteErrorsFrequentCounter.values()
            ) / len(absoluteErrorsFrequentCounter)

        if len(relativeErrorsCsurosCounter) > 0:
            relativeErrorCsurosCounterAvg += sum(
                relativeErrorsCsurosCounter.values()
            ) / len(relativeErrorsCsurosCounter)

        if len(relativeErrorsFrequentCounter) > 0:
            relativeErrorFrequentCounterAvg += sum(
                relativeErrorsFrequentCounter.values()
            ) / len(relativeErrorsFrequentCounter)

        resultsFile.write(
            f"{dict(exact_counter).keys()} {dict(csuros_counter).keys()} {dict(frequent_counter).keys()}"
        )
        resultsFile.close()

    # calcular o erro absoluto e relativo médio de todos os ficheiros
    absoluteErrorCsurosCounterAvg = absoluteErrorCsurosCounterAvg / numFiles
    absoluteErrorFrequentCounterAvg = absoluteErrorFrequentCounterAvg / numFiles

    relativeErrorCsurosCounterAvg = relativeErrorCsurosCounterAvg / numFiles
    relativeErrorFrequentCounterAvg = relativeErrorFrequentCounterAvg / numFiles

    print(
        "\
        %3d : %s\n\
        %5f : %s\n\
        %5f : %s\n\
        %5f : %s\n\
        %5f : %s\
        "
        % (
            numFiles,
            "Number of files analysed",
            absoluteErrorCsurosCounterAvg,
            "Csuros' Counter Absolute Error",
            absoluteErrorFrequentCounterAvg,
            "Frequent Counter Absolute Error",
            relativeErrorCsurosCounterAvg,
            "Csuros' Counter Relative Error",
            relativeErrorFrequentCounterAvg,
            "Frequent Counter Relative Error",
        )
    )


from flask import Flask, render_template
app = Flask(__name__)

@app.route('/bmi/<int:weight>/<int:height>')
def bmi(weight, height):
    BMI = weight/(height/100)**2
    conclude = ''
    if BMI < 16:
        conclude = "Severely underweight"
    elif BMI <18.5:
        conclude =  "Underweight"
    elif BMI < 25:
        conclude =  "Normal"
    elif BMI < 30:
        conclude =  "Overweight"
    else:
        conclude =  "Obese"
    return render_template('bmi.html', BMI = BMI, weight = weight, height = height, conclude = conclude)
if __name__ == '__main__':
  app.run(debug=True)


from numpy import array, column_stack, dot, matrix, row_stack
from colorama import Fore
class Okl:
    def __init__(self, file) -> None:
        self.A = [] #matrix a0, ..., aN, bi
        self.Ar1 = []
        self.N = 0  #Count string NxN
        self.__ParsingFile(file)
        self.PrintMatrix(self.A, "Matrix A")
        self.Okl()

    def __ParsingFile(self, file):
        F = open(file, 'r')
        self.N = int(F.readline())
        for iLine in range(0, self.N):
            Line = F.readline()
            self.A.append([])
            TmpString = ""
            for i in range(0, len(Line)):
                if (Line[i] == " " and not TmpString.isspace()):
                    self.A[-1].append(float(TmpString))
                    TmpString = ""
                else:
                    TmpString += Line[i]
            self.A[-1].append(float(TmpString))

    def Okl(self):
        A = matrix(self.A)[:,:self.N]
        Ar1 = 1 / A[:1,:1]
        for k in range(1, self.N):
            V = A[k, : k]
            U = A[ : k, k]
            ak = (A[k, k] - dot(dot(V,Ar1), U))[0, 0]
            rk = dot(-1/ak, dot(Ar1, U))
            qk = dot(-1/ak,dot(V, Ar1))
            B = Ar1 - dot(dot(Ar1, U), qk)
            Ar1 = (row_stack(
                (column_stack((B, rk)),column_stack((qk, 1/ak)))
                ))
            print(Fore.RED + "Step: " + str(k) + Fore.WHITE)
            self.PrintMatrix(Ar1.tolist(), 'Ret matrix')
        self.Ar1 = Ar1.tolist()

    def CalcRoot(self):
        B = array(self.A)[:, self.N:]
        Ar1 = array(self.Ar1)
        return dot(Ar1, B)[:,0].tolist()

    def CheckOnTrue(self, root):
        F = True
        for i in range(0, self.N):
            Sum = 0.0
            for j in range(0, self.N):
                Sum += self.A[i][j] * root[j]
                print(str(self.A[i][j]) + " * " + str(root[j]), end="")
                if (j != self.N - 1):
                    print(" + ", end="")
            Rd = len(str(self.A[i][-1]))
            if (round(Sum, Rd) != self.A[i][-1]):
                F = False
                print(Fore.RED + "  : " + str(round(Sum, Rd)) + " : Ax === B: " + str(self.A[i][-1]) + Fore.WHITE)
            else:
                print(Fore.GREEN + "  : " + str(round(Sum, Rd)) + " : Ax === B: " + str(self.A[i][-1]) + Fore.WHITE)
        return F

    def CheckReturnMatrix(self, A, Ar1):
        A = array(A)[:, :self.N]
        Ar1 = array(Ar1)
        self.PrintMatrix(dot(A, Ar1), "Matrix A*A^1")
        self.PrintMatrix(dot(Ar1, A), "Matrix A^1*A")

    def PrintMatrix(self, M, caption = ""):
        Pading = 0
        for i in range(0, len(M)):
            for j in range(0, len(M[i])):
                if (len(str(M[i][j])) > Pading):
                    Pading = len(str(M[i][j]))
        print(Fore.GREEN + caption + Fore.WHITE)
        for i in range(0, len(M)):
            for j in range(0, len(M[i])):
                if (i == j):
                    print(Fore.YELLOW + str(round(M[i][j], 10)).center(Pading, ' ') + Fore.WHITE, end=" ")
                    continue
                if (j == self.N):
                    print(Fore.CYAN + str(round(M[i][j], 10)).center(Pading, ' ') + Fore.WHITE, end=" ")
                    continue
                print(str(round(M[i][j], 10)).center(Pading, ' '), end=" ")
            print()

def main():
    File = ["Okl.txt", "Testgs.txt", "Testkv.txt"]
    Matrix = Okl('O:\\Lesson\\FileLesson\\ВЫЧМАТ\\lab6\\' + File[1])
    Matrix.PrintMatrix(Matrix.A, 'Matrix')
    Matrix.PrintMatrix(Matrix.Ar1, 'Return Matrix')
    Matrix.CheckReturnMatrix(Matrix.A, Matrix.Ar1)
    Root = Matrix.CalcRoot()
    if (Root):
        print(Fore.GREEN + "Root X : " + Fore.WHITE)
        for i in range(0, len(Root)):
            print("x" + str(i + 1) + " = " + str(Root[i]))
    print(Fore.GREEN + "Check on True" + Fore.WHITE)
    if (Matrix.CheckOnTrue(Root)):
        print(Fore.GREEN + "Roots is true" + Fore.WHITE)
    else:
        print(Fore.RED + "Roots is False" + Fore.WHITE)

if __name__ == "__main__":
    main()


from flask import Flask, render_template
from flask_socketio import SocketIO
import time
import json
from gpiozero import LED

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
blue_led = LED(23)
red_led = LED(24)

@app.route('/')
def index():
    return render_template('index.html')

# @app.route('/blue/')
def blue():
    blue_led.on()
    time.sleep(1)
    blue_led.off()
    time.sleep(1)
    blue_led.on()
    time.sleep(1)
    blue_led.off()
    time.sleep(1)
    blue_led.on()
    time.sleep(1)
    blue_led.off()
    time.sleep(1)
    # return render_template('blue.html')

# @app.route('/red/')
def red():
    red_led.on()
    time.sleep(1)
    red_led.off()
    time.sleep(1)
    red_led.on()
    time.sleep(1)
    red_led.off()
    time.sleep(1)
    red_led.on()
    time.sleep(1)
    red_led.off()
    time.sleep(1)
    # return render_template('red.html')

def messageReceived(methods=['GET', 'POST']):
    print('Message received')

@socketio.on('hello')
def handle_event(json, methods=['GET', 'POST']):
    print('Received event: {0}'.format(json))
    socketio.emit('Hello', json, callback=messageReceived)

def serial_read(methods=['GET', 'POST']):
    print('Message received serial')

@socketio.on('connect2pi')
def handle_serial(json_data, methods=['GET', 'POST']):
    print('Connected from {0}'.format(json_data))
    data = {'message': 'Connected to serial'}
    socketio.emit('serial', json.dumps(data), callback=serial_read)

@socketio.on('led')
def handle_led(json_data, methods=['GET', 'POST']):
    print('Received event: {0}'.format(json))

    led = int(json_data['color'])

    if led == 23:
        blue()
    elif led == 24:
        red()
    else:
        print('Pin {0} is not being used'.format(led))

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', debug=True)


T = int(input())
for i in range(0,T):
	N = int(input())
	A = list(map(int,input().split()))
	left = 0
	right = 0
	L = []
	for j in range(0,N):
		if j%2==0:
			L.append(A[N-left-1])
			left+=1
		else:
			L.append(A[right])
			right+=1
	print(L)