from typing import Any, List, Mapping, MutableMapping, Tuple

import pendulum
import requests
from airbyte_cdk.sources import AbstractSource
from airbyte_cdk.sources.streams import Stream
from airbyte_cdk.sources.streams.http.requests_native_auth import Oauth2Authenticator

from .streams import ProcessedOrderDetails, ProcessedOrders, StockItems, StockLocationDetails, StockLocations

class LinnworksAuthenticator(Oauth2Authenticator):
    def __init__(
        self,
        token_refresh_endpoint: str,
        application_id: str,
        application_secret: str,
        token: str,
        token_expiry_date: pendulum.datetime = None,
        access_token_name: str = "Token",
        expires_in_name: str = "TTL",
        server_name: str = "Server",
    ):
        super().__init__(
            token_refresh_endpoint,
            application_id,
            application_secret,
            token,
            scopes=None,
            token_expiry_date=token_expiry_date,
            access_token_name=access_token_name,
            expires_in_name=expires_in_name,
        )

        self.application_id = application_id
        self.application_secret = application_secret
        self.token = token
        self.server_name = server_name

    def get_auth_header(self) -> Mapping[str, Any]:
        return {"Authorization": self.get_access_token()}

    def get_access_token(self):
        if self.token_has_expired():
            t0 = pendulum.now()
            token, expires_in, server = self.refresh_access_token()
            self._access_token = token
            self._token_expiry_date = t0.add(seconds=expires_in)
            self._server = server

        return self._access_token

    def get_server(self):
        if self.token_has_expired():
            self.get_access_token()

        return self._server

    def get_refresh_request_body(self) -> Mapping[str, Any]:
        payload: MutableMapping[str, Any] = {
            "applicationId": self.application_id,
            "applicationSecret": self.application_secret,
            "token": self.token,
        }

        return payload

    def refresh_access_token(self) -> Tuple[str, int]:
        try:
            response = requests.request(method="POST", url=self.token_refresh_endpoint, data=self.get_refresh_request_body())
            response.raise_for_status()
            response_json = response.json()
            return response_json[self.access_token_name], response_json[self.expires_in_name], response_json[self.server_name]
        except Exception as e:
            try:
                e = Exception(response.json()["Message"])
            except Exception:
                # Unable to get an error message from the response body.
                # Continue with the original error.
                pass
            raise Exception(f"Error while refreshing access token: {e}") from e

class SourceLinnworks(AbstractSource):
    def _auth(self, config):
        return LinnworksAuthenticator(
            token_refresh_endpoint="https://api.linnworks.net/api/Auth/AuthorizeByApplication",
            application_id=config["application_id"],
            application_secret=config["application_secret"],
            token=config["token"],
        )

    def check_connection(self, logger, config) -> Tuple[bool, any]:
        try:
            self._auth(config).get_auth_header()
        except Exception as error:
            return False, f"Unable to connect to Linnworks API with the provided credentials: {error}"
        return True, None

    def streams(self, config: Mapping[str, Any]) -> List[Stream]:
        auth = self._auth(config)
        return [
            StockLocations(authenticator=auth),
            StockLocationDetails(authenticator=auth),
            StockItems(authenticator=auth),
            ProcessedOrders(authenticator=auth, start_date=config["start_date"]),
            ProcessedOrderDetails(authenticator=auth, start_date=config["start_date"]),
        ]


import os, sys
sys.path.append(os.path.abspath('.'))

from mdl import read_corpus, corpus_names
import json

# obtain an analysis from a given corpus
def get_unigrams(corpus_name):
	words = read_corpus(corpus_name)

	unigrams = {'#': len(words)} # account for the word boundary
	for char in ''.join(words):
		unigrams.setdefault(char, 0)
		unigrams[char] += 1

	with open(f'unigrams/unigrams_{corpus_name}.json', 'w', encoding='utf-8') as outfile:
		json.dump(unigrams, outfile, separators=(',', ':'), ensure_ascii=False)

	with open(f'unigrams/unigrams_{corpus_name}.txt', 'w', encoding='utf-8') as outfile:
		outfile.write(' '.join(f'{key}{val}' for key, val in unigrams.items()))

if __name__ == '__main__':
	for n in corpus_names:
		get_unigrams(n)


import serial

PORT = '/dev/cu.usbmodem14101'
BAUDRATE = 9600

ON = '1'
OFF = '0'

if __name__ == "__main__":
	arduino = serial.Serial(PORT, BAUDRATE)
	if arduino.is_open:
		while True:
			state = int(input("Enter the state of the magnet (0 - off, 1 - on) or 9 to turn it off: "))
			if state == 9:
				arduino.close()
				break
			else:
				if state:
					arduino.write(str.encode(ON))
				else:
					arduino.write(str.encode(OFF))
	else:
		print("ERROR: Could not connect to port: " + PORT)


from django.contrib import admin
from django.urls import path, include

from django.contrib.auth import views as auth_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('orders.urls')),
    path('api-auth/', include('rest_framework.urls')),
    path('accounts/login/', auth_views.LoginView.as_view(redirect_authenticated_user=True), name='login'),
    path('accounts/', include('django.contrib.auth.urls')),
]


from unittest import TestCase
from unittest.mock import patch

import numpy as np
from pytest import raises

from aspire import __version__
from aspire.utils import get_full_version, powerset, utest_tolerance
from aspire.utils.misc import gaussian_1d, gaussian_2d, gaussian_3d

class UtilsTestCase(TestCase):
    def testGetFullVersion(self):
        """Test typical version string response is coherent with package."""

        self.assertTrue(get_full_version().startswith(__version__))

    @patch("os.path.isdir")
    def testGetFullVersionPath(self, d_mock):
        """Test not isdir case of get_full_version."""

        d_mock.return_value = False

        self.assertTrue(get_full_version() == __version__)

    @patch("subprocess.check_output")
    def testGetFullVersionSrc(self, p_mock):
        """Test subprocess exception case of get_full_version."""

        p_mock.side_effect = FileNotFoundError

        self.assertTrue(get_full_version() == __version__ + ".src")

    @patch("subprocess.check_output")
    def testGetFullVersionUnexpected(self, p_mock):
        """Test unexpected exception case of get_full_version."""

        p_mock.side_effect = RuntimeError

        self.assertTrue(get_full_version() == __version__ + ".x")

    def testPowerset(self):
        ref = sorted([(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)])
        s = range(1, 4)
        self.assertTrue(sorted(list(powerset(s))) == ref)

    def testGetTestTol(self):
        self.assertEqual(1e-8, utest_tolerance(np.float64))
        self.assertEqual(1e-5, utest_tolerance(np.float32))
        with raises(TypeError):
            utest_tolerance(int)

    def testGaussian2d(self):
        L = 100
        mu_x, mu_y = 7, -3
        s_x, s_y = 5, 6

        g = gaussian_2d(L, x0=mu_x, y0=mu_y, sigma_x=s_x, sigma_y=s_y)

        # The normalized sum across an axis should correspond to a 1d gaussian with appropriate mu, sigma, peak.
        g_x = np.sum(g, axis=1) / np.sum(g)
        g_y = np.sum(g, axis=0) / np.sum(g)

        # Corresponding 1d gaussians
        peak_x = 1 / np.sqrt(2 * np.pi * s_x**2)
        peak_y = 1 / np.sqrt(2 * np.pi * s_y**2)
        g_1d_x = gaussian_1d(L, mu=mu_x, sigma=s_x, peak=peak_x)
        g_1d_y = gaussian_1d(L, mu=mu_y, sigma=s_y, peak=peak_y)

        # Assert all-close
        self.assertTrue(np.allclose(g_x, g_1d_x))
        self.assertTrue(np.allclose(g_y, g_1d_y))

    def testGaussian3d(self):
        L = 100
        mu = (0, 5, 10)
        sigma = (5, 7, 9)

        G = gaussian_3d(L, mu, sigma)

        # The normalized sum across two axes should correspond to a 1d gaussian with appropriate mu, sigma, peak.
        G_x = np.sum(G, axis=(1, 2)) / np.sum(G)
        G_y = np.sum(G, axis=(0, 2)) / np.sum(G)
        G_z = np.sum(G, axis=(0, 1)) / np.sum(G)

        # Corresponding 1d gaussians
        peak_x = 1 / np.sqrt(2 * np.pi * sigma[0] ** 2)
        peak_y = 1 / np.sqrt(2 * np.pi * sigma[1] ** 2)
        peak_z = 1 / np.sqrt(2 * np.pi * sigma[2] ** 2)
        g_1d_x = gaussian_1d(L, mu=mu[0], sigma=sigma[0], peak=peak_x)
        g_1d_y = gaussian_1d(L, mu=mu[1], sigma=sigma[1], peak=peak_y)
        g_1d_z = gaussian_1d(L, mu=mu[2], sigma=sigma[2], peak=peak_z)

        # Assert all-close
        self.assertTrue(np.allclose(G_x, g_1d_x))
        self.assertTrue(np.allclose(G_y, g_1d_y))
        self.assertTrue(np.allclose(G_z, g_1d_z))


from stl import mesh
import numpy as np
import sys
from environment import write

f = open(sys.argv[1] + "_stl.txt", "w")

write(f)

object = mesh.Mesh.from_file("./" + sys.argv[1] + ".stl")
obj_vectors = object.vectors

points = np.around(np.unique(obj_vectors.reshape([int(obj_vectors.size/3), 3]), axis=0),2)

for triangle in obj_vectors:
    coord0 = str([triangle[0][0], triangle[0][1], triangle[0][2]]).replace("]", "").replace("[", "")
    coord1 = str([triangle[1][0], triangle[1][1], triangle[1][2]]).replace("]", "").replace("[", "")
    coord2 = str([triangle[2][0], triangle[2][1], triangle[2][2]]).replace("]", "").replace("[", "")
    f.write("P(" + coord0 + "," + coord1 + "," + coord2 + ")\n")

f.close()


__author__ = '芜疆'
#coding=utf-8
import time
import unittest
import HTMLReport
import os
import sys
os.chdir(sys.path[0])

#收集测试用例
def create_my_suit():
    my_suit=unittest.TestSuite()
    testdir="test_case"
    discover=unittest.defaultTestLoader.discover(testdir,pattern="*case.py",top_level_dir=None)
    for test_suit in discover:
        for test_case in  test_suit:
            my_suit.addTest(test_case)
    return my_suit

if __name__ == '__main__':
    #执行测试
    time=time.strftime("%y-%m-%d %H-%M-%S")
    mysuit=create_my_suit()
    runner = HTMLReport.TestRunner(report_file_name='report'+time,
                                   output_path='report',
                                   title='测试报告',
                                   description='测试描述',
                                   lang='cn'  # 支持中文与英文，默认中文
                                   )
    runner.run(mysuit)


from main import Session, engine, User
from sqlalchemy import select, desc

with Session(bind=engine) as session:
    users = session.query(User) \
        .order_by(User.name) \
        .all()  # querying all
    # .order_by(desc(User.name)) \
    # .filter(User.name == "Kannan") \
    # .first() # get one row

for user in users:
    print(user.name)


from collections import deque

dx, dy = [0, 1, 0, -1], [1, 0, -1, 0]

def bfs(start):
    cnt = 1
    q = deque()
    q.append(start)

    while q:
        x, y = q.pop()
        visited[x][y] = 1
        for i in range(4):
            nx, ny = x + dx[i], y + dy[i]
            if 0 <= nx < N and 0 <= ny < N:
                if MAP[nx][ny] == 1 and visited[nx][ny] == 0:
                    visited[nx][ny] = 1
                    cnt += 1
                    q.append([nx, ny])
    apt.append(cnt)

N = int(input())
MAP = [list(map(int, list(input()))) for i in range(N)]
visited = [[0]*N for i in range(N)]
apt = []
for i in range(N):
    for j in range(N):
        if MAP[i][j] == 1 and visited[i][j] == 0:
            bfs([i, j])
print(len(apt))
for i in sorted(apt):
    print(i)


# dictionaries are same as objects

user = {
    "name": "Aakarsh",
    "gender": "male",
    "age": 18,
    "hobbies": ["gaming", "coding", "travelling"],
    "education": "BTech'27"
}
# avoids error which we get if we use directly square brackets
print(user.get("status", "single"))

# creating dictionary with the function

user_two = dict(name = "Abhay", gender = "Male", age = 18)

print(user_two)

print(("name" in user_two) and ("name" in user))


file = open("input.txt", "r")
count = 0
arr = []
for line in file:
    if line != "\n":
        count += int(line.rstrip())
    else:
        arr.append(count)
        count = 0

### Part 1
print(max(arr))

### Part 2
arr.sort(reverse=True)
print(arr[0]+arr[1]+arr[2])


"""
grid.py

Reads in a pickle file mapping VQA-2 Image IDs to Feature IDX in an HDF5 File.

Hierarchy of HDF5 file:
    { 'spatial': num_images x feature_length x patch_sz x patch_sz
      'pool': num_images x feature_length }
"""
import os
import pickle

PATCH_SIZE = 7
FEATURE_LENGTH = 2048

def vqa2_create_grid_features(vqa2_g="data/VQA-Spatials"):
    """Load img2idx mappings from .pkl files"""
    print("\t[*] Loading Grid Img2Idx...")

    # Open and Load Pickle Files
    tid, vid = os.path.join(vqa2_g, "train101_img2idx.pkl"), os.path.join(vqa2_g, "val101_img2idx.pkl")
    with open(tid, "rb") as f:
        train_indices = pickle.load(f)

    with open(vid, "rb") as f:
        val_indices = pickle.load(f)

    return train_indices, val_indices


import setuptools

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

setuptools.setup(
    name="pwrols_bknight_test_2",
    version="0.0.1",
    author="Benjamin S. Knight",
    author_email="knight.benjamin@gmail.com",
    description="Python package for sample size estimation in the context of OLS.",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/b-knight/pwrols",
    install_requires=['scipy'],
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires='>=3.6',
)


from datadog import initialize, api
from settings import *
import chronos
from marathon import MarathonClient
import logging

def send_dd_event(title, text, tags, source_type, alert_type='info'):
    """Sends events to datadog"""

    options = {
        'api_key': DATADOG_API_KEY,
        'app_key': DATADOG_APP_KEY
    }

    initialize(**options)

    api.Event.create(title=title,
                     text=text,
                     tags=tags,
                     alert_type=alert_type,
                     source_type_name='chronos'),

def get_chronos_services_health(chronos_url):
    """Gets health of all services from chronos"""
    client = chronos.connect(chronos_url)
    for job in client.list():
        if job['errorsSinceLastSuccess'] is not 0:
            send_dd_event("Chronos task: {} failed".format(job['name']),
                          "Chronos Task Id: {}\nLast success: {}\nLast error: {}".format(job['name'], job['lastSuccess'], job['lastError']),
                          generate_tags('chronos', job['name']),
                          "chronos",
                          "error"
                         )
        else:
            send_dd_event("Chronos task: {} ran succesfully".format(job['name']),
                          "Chronos Task Id: {}\nLast success: {}\nLast error: {}".format(job['name'], job['lastSuccess'], job['lastError']),
                          generate_tags('chronos', job['name']),
                          "chronos",
                         )

def get_marathon_services_health(marathon_url):
    """Gets health of all services from marathon"""
    client = MarathonClient(marathon_url)
    for app in client.list_apps(embed_tasks=True):
        if app.tasks_unhealthy > 0:
            unhealthy_tasks = []
            for task in app.tasks:
                if task.state == "TASK_RUNNING" or task.state == "TASK_STAGING":
                    continue
                else:
                    unhealthy_tasks.append(task.id)
            send_dd_event("Marathon service: {} has failed tasks".format(app.id),
                          "Id: {}\nRunning Tasks: {}\nUnhealthy Tasks: {}\nUnhealthy Task IDs: {}\n".format(app.id, app.tasks_running, app.tasks_unhealthy, unhealthy_tasks),
                          generate_tags('marathon', app.id),
                          "marathon",
                          "error"
                         )
        else:
            send_dd_event("Marathon service: {} healthy".format(app.id),
                          "Id: {}\nRunning Tasks: {}\nUnhealthy Tasks: {}".format(app.id, app.tasks_running, app.tasks_unhealthy),
                          generate_tags('marathon', app.id),
                          "marathon",
                         )

def generate_tags(framework, task_name):
    """Generates tags to send to datadog"""
    return [framework, task_name]


import pygame, sys, time, random, math
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((800, 800))
pygame.display.set_caption("My First PyGame Windows")
mainLoop = True
x = 375
y = 550
isJump = False
jumpCount = 10
hp = 10
score = 0
flag_left = False
flag_right = False
animCount = 0
animCount2 = 0
animCount3 = 0
animCountLowLeft = 0
animCountLowRight = 0
isAttacking = False
turnToRight = False
turnToLeft = True
clock = pygame.time.Clock()
current_time = 0
k = 5000
koef = 1
playerIdleRight = pygame.image.load('sprites\idle2.png')
playerIdleLeft = pygame.image.load('sprites\idle_left.png')

playerJumpRight = pygame.image.load('sprites\jump2.png')
playerJumpLeft = pygame.image.load('sprites\jump_left.png')

enemyJumpRight = pygame.transform.scale(pygame.image.load(r'sprites\enemies\runningleft-5.png'), (130, 100))
enemyJumpLeft = pygame.transform.scale(pygame.image.load(r'sprites\enemies\runningright-5.png'), (130, 100))

enemyAttackRight = pygame.transform.scale(pygame.image.load(r'sprites\enemies\attackright.png'), (130, 100))
enemyAttackLeft = pygame.transform.scale(pygame.image.load(r'sprites\enemies\attackleft.png'), (130, 100))
enemyIdleRight = pygame.transform.scale(pygame.image.load(r'sprites\enemies\attackright-2.png'), (130, 100))
enemyIdleLeft = pygame.transform.scale(pygame.image.load(r'sprites\enemies\attackleft-2.png'), (130, 100))
enemyDead = pygame.transform.scale(pygame.image.load(r'sprites\enemies\enemy-dead.png'), (130, 100))

runRight = [pygame.image.load(r'sprites\running-1.png'), pygame.image.load(r'sprites\running-2.png'),
            pygame.image.load(r'sprites\running-3.png'),
            pygame.image.load(r'sprites\running-4.png'), pygame.image.load(r'sprites\running-5.png'),
            pygame.image.load(r'sprites\running-6.png')]
runLeft = [pygame.image.load(r'sprites\runningleft-1.png'), pygame.image.load(r'sprites\runningleft-2.png'),
           pygame.image.load(r'sprites\runningleft-3.png'),
           pygame.image.load(r'sprites\runningleft-4.png'), pygame.image.load(r'sprites\runningleft-5.png'),
           pygame.image.load(r'sprites\runningleft-6.png')]
attackRight = [pygame.image.load(r'sprites\attackright-1.png'), pygame.image.load(r'sprites\attackright-2.png'),
               pygame.image.load(r'sprites\attackright-3.png'),
               pygame.image.load(r'sprites\attackright-4.png'), pygame.image.load(r'sprites\attackright-5.png'),
               pygame.image.load(r'sprites\attackright-6.png')]
attackLeft = [pygame.image.load(r'sprites\attackleft-1.png'), pygame.image.load(r'sprites\attackleft-2.png'),
              pygame.image.load(r'sprites\attackleft-3.png'),
              pygame.image.load(r'sprites\attackleft-4.png'), pygame.image.load(r'sprites\attackleft-5.png'),
              pygame.image.load(r'sprites\attackleft-6.png')]
attackRightLow = [pygame.image.load(r'sprites\attackright_low-1.png'),
                  pygame.image.load(r'sprites\attackright_low-2.png'),
                  pygame.image.load(r'sprites\attackright_low-3.png'),
                  pygame.image.load(r'sprites\attackright_low-4.png'),
                  pygame.image.load(r'sprites\attackright_low-5.png'),
                  pygame.image.load(r'sprites\attackright_low-6.png')]
attackLeftLow = [pygame.image.load(r'sprites\attackleft_low-1.png'), pygame.image.load(r'sprites\attackleft_low-2.png'),
                 pygame.image.load(r'sprites\attackleft_low-3.png'),
                 pygame.image.load(r'sprites\attackleft_low-4.png'), pygame.image.load(r'sprites\attackleft_low-5.png'),
                 pygame.image.load(r'sprites\attackleft_low-6.png')]
enemyRightRun = [pygame.transform.scale(pygame.image.load(r'sprites\enemies\runningleft-1.png'), (130, 100)),
                 pygame.transform.scale(pygame.image.load(r'sprites\enemies\runningleft-2.png'), (130, 100)),
                 pygame.transform.scale(pygame.image.load(r'sprites\enemies\runningleft-3.png'), (130, 100)),
                 pygame.transform.scale(pygame.image.load(r'sprites\enemies\runningleft-4.png'), (130, 100)),
                 pygame.transform.scale(pygame.image.load(r'sprites\enemies\runningleft-5.png'), (130, 100)),
                 pygame.transform.scale(pygame.image.load(r'sprites\enemies\runningleft-6.png'), (130, 100)),
                 pygame.transform.scale(pygame.image.load(r'sprites\enemies\runningleft-7.png'), (130, 100)),
                 pygame.transform.scale(pygame.image.load(r'sprites\enemies\runningleft-8.png'), (130, 100))]
enemyLeftRun = [pygame.transform.scale(pygame.image.load(r'sprites\enemies\runningright-1.png'), (130, 100)),
                pygame.transform.scale(pygame.image.load(r'sprites\enemies\runningright-2.png'), (130, 100)),
                pygame.transform.scale(pygame.image.load(r'sprites\enemies\runningright-3.png'), (130, 100)),
                pygame.transform.scale(pygame.image.load(r'sprites\enemies\runningright-4.png'), (130, 100)),
                pygame.transform.scale(pygame.image.load(r'sprites\enemies\runningright-5.png'), (130, 100)),
                pygame.transform.scale(pygame.image.load(r'sprites\enemies\runningright-6.png'), (130, 100)),
                pygame.transform.scale(pygame.image.load(r'sprites\enemies\runningright-7.png'), (130, 100)),
                pygame.transform.scale(pygame.image.load(r'sprites\enemies\runningright-8.png'), (130, 100))]

bg = pygame.image.load(r'sprites\bgg2.jpg')

game_over = pygame.image.load(r'sprites\gameover.jpg')

enemies = []

def draw():
    global animCount, animCount2, animCount3, isAttacking
    if (hp > 0):
        screen.blit(bg, (0, 0))
        if animCount + 1 >= 30:
            animCount = 0
        if flag_left:
            if isJump:
                if isAttacking:
                    attack_to_left()
                else:
                    screen.blit(playerJumpLeft, (x, y))
            else:
                screen.blit(runLeft[animCount // 5], (x, y))
                animCount += 1
        elif flag_right:
            if isJump:
                if isAttacking:
                    attack_to_right()
                else:
                    screen.blit(playerJumpRight, (x, y))
            else:
                screen.blit(runRight[animCount // 5], (x, y))
                animCount += 1

        else:
            if isJump:
                if turnToRight:
                    if isAttacking:
                        attack_to_right()
                    else:
                        screen.blit(playerJumpRight, (x, y))
                elif turnToLeft:
                    if isAttacking:
                        attack_to_left()
                    else:
                        screen.blit(playerJumpLeft, (x, y))
            else:
                if turnToRight:
                    if isAttacking:
                        attack_to_right()
                    else:
                        screen.blit(playerIdleRight, (x, y))
                        animCount2 = 0
                        animCount3 = 0
                elif turnToLeft:
                    if isAttacking:
                        attack_to_left()
                    else:
                        screen.blit(playerIdleLeft, (x, y))
                        animCount2 = 0
                        animCount3 = 0
        for enemy in enemies:
            enemy.draw_enemy()

        draw_hp()
        draw_score()
    else:
        screen.blit(game_over, (0, 0))
        draw_score()
    pygame.display.update()

def attack_to_right():
    global animCount2, animCount3, isAttacking, animCountLowRight, score
    if isJump:
        animCount3 = 0
        if animCount2 + 1 >= 18:
            animCount2 = 0
            isAttacking = False

        screen.blit(attackRight[animCount2 // 3], (x, y))
        animCount2 += 1
    else:
        if animCountLowRight + 1 >= 18:
            animCountLowRight = 0
            isAttacking = False

        screen.blit(attackRightLow[animCountLowRight // 3], (x, y))
        animCountLowRight += 1

        for enemy in enemies:
            # print(math.fabs(enemy.y - y))
            if enemy.x - x < 100:
                if enemy.direction == "left":
                    enemy.hp -= 10
                    current_time = pygame.time.get_ticks()
                    if enemy.is_dead:
                        if current_time - enemy.start_time_death >= 250:
                            enemies.remove(enemy)
                            score += 1

def attack_to_left():
    global animCount3, animCount2, isAttacking, animCountLowLeft, score
    if isJump:
        animCount2 = 0
        if animCount3 + 1 >= 18:
            animCount3 = 0
            isAttacking = False
        screen.blit(attackLeft[animCount3 // 3], (x, y))
        animCount3 += 1
    else:
        if animCountLowLeft + 1 >= 18:
            animCountLowLeft = 0
            isAttacking = False

        screen.blit(attackLeftLow[animCountLowLeft // 3], (x, y))
        animCountLowLeft += 1
    for enemy in enemies:
        if x - enemy.x < 100:
            if enemy.direction == "right":
                enemy.hp -= 10
                current_time = pygame.time.get_ticks()
                if enemy.is_dead:
                    if current_time - enemy.start_time_death >= 250:
                        enemies.remove(enemy)
                        score += 1

class Enemy(object):

    def __init__(self):
        self.x = 0
        self.y = 605
        self.is_jumping = random.choice([True, False])
        self.is_jumping_now = False
        self.width = 130
        self.height = 100
        self.jumpCount = 10
        self.direction = random.choice(["left", "right"])
        self.animEnemyRightCount = 0
        self.animEnemyLeftCount = 0
        self.hp = 100
        self.start_time = 0
        self.start_time_death = 0
        self.current_time = 0
        self.flag = True
        self.is_dead = False
        self.is_first_attack = True
        if self.direction == "right":
            self.x = -50
        else:
            self.x = 700

    def run(self):
        global x
        if not self.is_jumping:
            if self.collides():
                if self.direction == "right":
                    self.x = x - 50
                else:
                    self.x = x + 50
            else:
                if self.direction == "right":
                    self.x += 7
                else:
                    self.x -= 7
        elif self.is_jumping:
            if self.direction == "right":
                if self.x + self.width >= x - 80:
                    self.jump()
                    if self.jumpCount <= -10:
                        self.is_jumping_now = False
                    else:
                        self.is_jumping_now = True
                else:
                    self.x += 7
            else:
                if self.x - self.width <= x + 50:
                    self.jump()
                    if self.jumpCount <= -10:
                        self.is_jumping_now = False
                    else:
                        self.is_jumping_now = True
                else:
                    self.x -= 7

    def draw_enemy(self):
        if self.direction == "right":
            if self.hp > 0:
                if self.is_jumping_now:
                    screen.blit(enemyJumpRight, (self.x, self.y))
                elif self.collides():
                    if self.flag:
                        self.start_time = pygame.time.get_ticks()
                        self.flag = False
                    self.attack()
                else:
                    if self.animEnemyRightCount + 1 >= 40:
                        self.animEnemyRightCount = 0
                    screen.blit(enemyRightRun[self.animEnemyRightCount // 5], (self.x, self.y))
                    self.animEnemyRightCount += 1
                self.run()
            else:
                screen.blit(enemyDead, (self.x, 630))
                if not self.is_dead:
                    self.start_time_death = pygame.time.get_ticks()
                    self.is_dead = True
        else:
            if self.hp > 0:
                if self.is_jumping_now:
                    screen.blit(enemyJumpLeft, (self.x, self.y))
                elif self.collides():
                    if self.flag:
                        self.start_time = pygame.time.get_ticks()
                        self.flag = False
                    self.attack()
                else:
                    if self.animEnemyLeftCount + 1 >= 40:
                        self.animEnemyLeftCount = 0
                    screen.blit(enemyLeftRun[self.animEnemyLeftCount // 5], (self.x, self.y))
                    self.animEnemyLeftCount += 1
                self.run()
            else:
                screen.blit(enemyDead, (self.x, 630))
                if not self.is_dead:
                    self.start_time_death = pygame.time.get_ticks()
                    self.is_dead = True

        # pygame.draw.rect(screen, (0, 0, 0), [self.x, self.y, self.width, self.height])

    def collides(self):
        global x
        if self.direction == "right":
            if self.x + self.width - 50 >= x:
                return True
            else:
                return False
        else:
            if self.x - self.width + 50 <= x:
                return True
            else:
                return False

    def jump(self):
        if self.jumpCount >= -10:
            if self.jumpCount < 0:
                self.y += (self.jumpCount ** 2) / 3
            else:
                self.y -= (self.jumpCount ** 2) / 3
            self.jumpCount -= 1
            if self.direction == "right":
                self.x += 7
            else:
                self.x -= 7

    def attack(self):
        global hp
        self.current_time = pygame.time.get_ticks()
        if self.current_time - self.start_time >= 800:
            if self.direction == "right":
                if self.x > x:
                    screen.blit(enemyAttackLeft, (self.x, self.y))
                else:
                    screen.blit(enemyAttackRight, (self.x, self.y))
            else:
                if self.x < x:
                    screen.blit(enemyAttackRight, (self.x, self.y))
                else:
                    screen.blit(enemyAttackLeft, (self.x, self.y))
            if self.current_time - self.start_time >= 1000:
                self.flag = True
                hp -= 1
                print(hp)
            self.is_first_attack = False
        else:
            if self.direction == "right":
                screen.blit(enemyIdleRight, (self.x, self.y))
            else:
                screen.blit(enemyIdleLeft, (self.x, self.y))

def draw_hp():
    w = 560
    h = 50
    r = 255
    g = 0
    b = 0
    for i in range(hp):
        if r == 255 and g < 255 and b == 0:
            g += 51
        elif r <= 255 and g == 255 and r > 0:
            r -= 51
        elif g == 255 and b <= 255:
            b += 51
        elif g <= 255 and b == 255 and g > 0:
            g -= 51
        rect_1_rect = Rect((w, h), (15, 30))
        rect_1_color = (r, g, b)

        pygame.draw.rect(screen, rect_1_color, rect_1_rect)

        w += 22

def draw_score():
    global score
    if not hp == 0:
        font = pygame.font.Font(None, 25)
        text = font.render("Score: " + str(score), True, (255, 255, 255))
        screen.blit(text, [20, 770])
    else:
        font = pygame.font.Font(None, 35)
        text = font.render("Score: " + str(score), True, (255, 70, 90))
        screen.blit(text, [350, 600])

while mainLoop:
    clock.tick(30)
    for event in pygame.event.get():
        if event.type == QUIT:
            mainLoop = False
    pressedList = pygame.key.get_pressed()
    if pressedList[pygame.K_ESCAPE]:
        gameOver = True

    if pressedList[pygame.K_a] and x > 300:
        x -= 5
        flag_left = True
        flag_right = False
        turnToLeft = True
        turnToRight = False
    elif pressedList[pygame.K_d] and x < 450:
        x += 5
        flag_left = False
        flag_right = True
        turnToRight = True
        turnToLeft = False
    else:
        flag_right = False
        flag_left = False
        animCount = 0
        animCount2 = 0
        animCount3 = 0

    if not isJump:
        if pressedList[pygame.K_w]:
            isJump = True
    else:
        if jumpCount >= -10:
            if jumpCount < 0:
                y += (jumpCount ** 2) / 3
            else:
                y -= (jumpCount ** 2) / 3
            jumpCount -= 1
        else:
            isJump = False
            isAttacking = False
            jumpCount = 10

    if pressedList[pygame.K_SPACE]:
        isAttacking = True

    draw()
    if pygame.time.get_ticks() >= k:
        enemies.append(Enemy())
        k += 5000 * koef
    koef -= 0.0001

pygame.quit()


import mysql.connector
from faker import Faker
import random

def create_car_model(db):

    cursor = db.cursor()

    # List of predefined vehicle models
    vehicle_models = [
        "Alto K10","Celerio","Ignis","Swift","Baleno","Dzire","Ciaz","Ertiga","XL6","Brezza","Grand Vitara","Fronx", "Jimny","Alto 800","Wagon R","S-Presso"
    ]

    cursor.execute("""
        CREATE TABLE IF NOT EXISTS CarModel (
            ModelID INT AUTO_INCREMENT PRIMARY KEY,
            ModelName VARCHAR(100),
            CategoryID INT,
            EngineID INT,
            ModelSpecifications TEXT,
            FOREIGN KEY (CategoryID) REFERENCES CarCategory(CategoryID)
            ON UPDATE CASCADE
            ON DELETE CASCADE,
            FOREIGN KEY (EngineID) REFERENCES CarEngine(EngineID)
            ON UPDATE CASCADE
            ON DELETE CASCADE
        )
    """)

    car_models = []
    fake = Faker()
    for model_name in vehicle_models:
        car_models.append((None, model_name, random.randint(1, 5), random.randint(1, 4), fake.sentence()))

    insert_query = "INSERT INTO CarModel (ModelID, ModelName, CategoryID, EngineID, ModelSpecifications) VALUES (%s, %s, %s, %s, %s)"
    cursor.executemany(insert_query, car_models)

    db.commit()
    cursor.close()

    print("CarModel table created and populated successfully.")


import numpy as np
import glob
import spams
import time
from skimage import io, color
# from sklearn.feature_extraction import image
import matplotlib.pyplot as plt
import dictlearn as dl
from pathlib import Path
import time

fname = str(Path.home()) + '/Imagens/720pMoria.png'

m11, m22 = (8,8)

if __name__ == "__main__":
    from skimage.measure import compare_psnr

    D = np.loadtxt('dltrainfiles/dl8_ycbcr_ds96_720pmoria.txt').T
    # D = np.zeros((192,64))
    # D[::3] = dl.dct_dict(64, 8)
    # D[1::3] = dl.dct_dict(64, 8)
    # D[2::3] = dl.dct_dict(64, 8)
    # np.savetxt('dct8_ds64.txt', D)
    # D = dl.dct_dict(64,12)
    # print(D.shape)
    # exit()

    image = io.imread(fname)
    if image.shape[-1] == 4:
        image = color.rgba2rgb(image)
    img_train = color.rgb2ycbcr(image) / 255.
    # img_train = image/255.
    # Duse = color.ycbcr2rgb(D)

    nl, nc, _= img_train.shape
    img4 = img_train
    t0 = time.monotonic()
    Ps = []
    for i in range(0, nl, m11):
        for j in range(0, nc, m22):
            if i + m11 <= nl and j + m22 <= nc:
                p = img4[i:(i+m11), j:(j+m22)]
                Ps.append(p)

    Ps = np.array(Ps).reshape(len(Ps), -1).T

    psnrs = []

    for i in range(1, int(Ps.shape[0])):
        mask = np.zeros(Ps.shape[0])
        choose = np.random.choice(Ps.shape[0], i, replace=False)
        # print(mask.shape)
        mask[choose] = 1
        # Dnew = np.asfortranarray((D * np.outer(mask, np.ones((1, D.shape[1])))),np.float)
        Dnew = np.asfortranarray(Duse[choose, :])
        Psnew = np.asfortranarray(Ps[choose, :])
        # res = np.array(dl.omp_mask(Ps, mask, D, 10, n_threads=4))
        res = spams.lasso(Psnew, Dnew, lambda1=0.000001, L=14).toarray()
        res = D.dot(res).T
        img1 = np.vstack((spl.reshape(-1,m11,m22,3).transpose(1,0,2,3).reshape(m11,-1,3) for spl in np.vsplit(res, int(nl / m11))))
        imgrgb = color.ycbcr2rgb(img1*255).clip(0,1)
        # imgrgb = (img1+1)/2
        psnrs.append(compare_psnr(image, imgrgb))
        print("%d: %.3f" % (i, psnrs[-1]))
    # dl.ps
    plt.subplot(2,1,1)
    plt.plot(psnrs, 'o-')

    print(imgrgb.min(), imgrgb.max())
    plt.subplot(2,1,2)
    plt.imshow(imgrgb)
    plt.show()


import numpy as np
from numba import jit
import networkx as nx
import random
from math import exp
from itertools import product
import copy
import torch
import csv
from family import *

def create_families(country,Family_num):
    with open('Houseshold.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        for row in csv_reader:
            if row[0]==country:
                family_size_percentage=row[5:9]
                break
        #1 member	2-3 members	4-5 members	6 or more members
        family_size=[1,3,5,6]
        family_size_percentage=[float(s)/100 for s in family_size_percentage]
        all_family_list=[]
        for i in range(Family_num):
            p=family_size_percentage[0]
            r=random.random()
            for j in range(len(family_size_percentage)):
                if r<p:
                    all_family_list.append(FamilyUnit(family_size[j],0))
                    break
                else:
                    p+=family_size_percentage[j+1]
    return all_family_list

def get_SIR_num(G):
    S_num=0
    I_num=0
    R_num=0
    for v in range(len(G)):
        if G.node[v]['state']==0:
            S_num+=1
        if G.node[v]['state']==1:
            I_num+=1
        if G.node[v]['state']==2:
            R_num+=1
    return S_num, I_num, R_num

def SIS_proc(G,beta,gamma):
    H=copy.deepcopy(G)
    for v in range(len(G)):
        if H.node[v]['state']==1:
            if random.random()<gamma:
                G.node[v]['state']=0
        else:
            infect_neighbor=0
            for u in G.neighbors(v):
                if H.node[u]['state']==1:
                    infect_neighbor+=1
            infect_prob=1-(1-beta)**infect_neighbor
            if random.random()<infect_prob:
                G.node[v]['state']=1

def SIR_proc(G,beta,gamma):
    H=copy.deepcopy(G)
    for v in range(len(G)):
        if H.node[v]['state']==0:
            infect_neighbor=0
            for u in G.neighbors(v):
                if H.node[u]['state']==1:
                    infect_neighbor+=1
            infect_prob=1-(1-beta)**infect_neighbor
            if random.random()<infect_prob:
                G.node[v]['state']=1
        elif H.node[v]['state']==1:
            if random.random()<gamma:
                G.node[v]['state']=2

def load_data_new(n, do_bootstrap=False, n_samples=1000):
    beta = np.loadtxt('tb_code_release-master/annBeta.csv', delimiter=',', skiprows=1)
    beta_full = np.zeros((n, n))
    for i in range(n):
        for j in range(n):
            i_idx = min((int(i/5), beta.shape[0]-1))
            j_idx = min((int(j/5), beta.shape[0]-1))
            beta_full[i, j] = beta[i_idx, j_idx]
    beta = torch.from_numpy(beta_full)

    a = np.loadtxt('tb_code_release-master/ann2018_alphaFastProb.csv.csv', delimiter=',', skiprows=1)
    num_samples = a.shape[0]

    alpha_fast = load_as_diag('tb_code_release-master/ann2018_alphaFastProb.csv.csv', num_samples, n)

    alpha_slow = load_as_diag('tb_code_release-master/ann2018_alphaSlowProb.csv.csv', num_samples, n)

    nu_sq = np.loadtxt('tb_code_release-master/ann2018_clearanceProb.csv.csv', delimiter=',', skiprows=1)
    nu_sq[np.isnan(nu_sq)] = 0
    nu_sq = nu_sq.mean(axis = 0)
    nu_sq = torch.from_numpy(nu_sq)

    d = load_as_diag('tb_code_release-master/ann2018_deathProb_TB.csv.csv', num_samples, n, oneminus=True)

    mu = load_as_diag('tb_code_release-master/ann2018_deathProb_nat.csv.csv', num_samples, n, oneminus=True)

    S = load_as_diag_time('tb_code_release-master/2018_hasHealthy.csv', num_samples, n)

    N = load_as_diag_time('tb_code_release-master/2018_N.csv', num_samples, n, invert=True)

    E = load_as_vec_time('tb_code_release-master/2018_haslatTB.csv', num_samples, n)

    I = load_as_vec_time('tb_code_release-master/2018_hasTB.csv', num_samples, n)

    if do_bootstrap == True:
        S_boot = torch.zeros(S.shape[0], n_samples, *S.shape[2:]).double()
        for t in range(S.shape[0]):
            S_boot[t] = bootstrap(S[t], n_samples)

        E_boot = torch.zeros(E.shape[0], n_samples, *E.shape[2:]).double()
        for t in range(E.shape[0]):
            E_boot[t] = bootstrap(E[t], n_samples)

        I_boot = torch.zeros(I.shape[0], n_samples, *I.shape[2:]).double()
        for t in range(I.shape[0]):
            I_boot[t] = bootstrap(I[t], n_samples)

        N_boot = torch.zeros(N.shape[0], n_samples, *N.shape[2:]).double()
        for t in range(N.shape[0]):
            N_boot[t] = bootstrap(N[t], n_samples)

        beta = beta.expand_as(mu)
        alpha_fast = bootstrap(alpha_fast, n_samples)
        alpha_slow = bootstrap(alpha_slow, n_samples)
        mu = bootstrap(mu, n_samples)
        d = bootstrap(d, n_samples)
        beta = bootstrap(beta, n_samples)

        S = S_boot
        E = E_boot
        I = I_boot
        N = N_boot

    return S, E, I, N, alpha_fast, alpha_slow, beta, mu, d, nu_sq

def load_as_diag(fname, num_samples, n, oneminus = False):
    a = np.loadtxt(fname, delimiter=',', skiprows=1, dtype=np.complex)
    a[np.isnan(a)] = 0
    a = np.real(a)
    a[np.isneginf(a)] = 0
    if oneminus:
        a = 1 - a
    mat = np.zeros((num_samples, n, n))
    for i in range(num_samples):
        mat[i] = np.diag(a[i])
    return torch.from_numpy(mat).double()

def load_as_diag_time(fname, num_samples, n, invert = False):
    a = np.loadtxt(fname, delimiter=',', skiprows=1, dtype=np.complex)
    #yearly: take every 12th row
    a = a[::12]
    a[np.isnan(a)] = 0
    a = np.real(a)
    a[np.isneginf(a)] = 0
    a = torch.from_numpy(a).double()
    mat = torch.zeros(a.shape[0], num_samples, n, n).double()
    for i in range(a.shape[0]):
        if not invert:
            mat[i] = torch.diag(a[i]).expand_as(mat[i])
        else:
            inverse = 1./a[i]
            inverse[torch.isinf(inverse)] = 1
            mat[i] = torch.diag(inverse).expand_as(mat[i])
    return mat.double()

def load_as_vec(fname, num_samples, n):
    E = np.loadtxt(fname, delimiter=',', skiprows=1, dtype=np.complex)
    E[np.isnan(E)] = 0
    E = np.real(E)
    E[np.isneginf(E)] = 0
    E = torch.from_numpy(E)
    E = E.view(num_samples, n, 1)
    return E.double()

def load_as_vec_time(fname, num_samples, n):
    E = np.loadtxt(fname, delimiter=',', skiprows=1, dtype=np.complex)
    E = E[::12]
    E[np.isnan(E)] = 0
    E = np.real(E)
    E[np.isneginf(E)] = 0
    E = torch.from_numpy(E)
    E_expand = torch.zeros(E.shape[0], num_samples, n, 1)
    for i in range(E.shape[0]):
        E_expand[i] = E[i].unsqueeze(1).expand_as(E_expand[i])
    return E_expand.double()

def bootstrap(A, n_samples):
    pop = list(range(A.shape[0]))
    indices = np.random.choice(pop, n_samples)
    indices = torch.tensor(indices).long()
    return A[indices]

def vector_to_diag(not_informed_fraction, beta):
    not_informed_fraction_diag = torch.zeros_like(beta)
    for s in range(beta.shape[0]):
        not_informed_fraction_diag[s] = torch.diag(not_informed_fraction[s].squeeze())
    return not_informed_fraction_diag

def run_seis_information_new(T, G, S, I, migration_I, migration_E, nu, mu, d, beta, N, alpha_fast, alpha_slow, E, beta_information, nu_max):
    '''
    Runs the linearized SEIS model, returning the total number of infected agents
    summed over all time steps.
    '''
    #read in for first period of F, informed
    #nu_sq = np.loadtxt('ann2018_clearanceProb.csv.csv', delimiter=',', skiprows=1)
    #nu_sq[np.isnan(nu_sq)] = 0
    #nu_sq = nu_sq.mean(axis = 0)
    #nu_sq = torch.from_numpy(nu_sq)

    #duplicate these variables along an additional axis to match the batch size
    beta = beta.expand_as(G)
    informed = nu.view(len(nu), 1)
    informed = informed.expand(beta.shape[0], *informed.shape)
    nu = torch.diag(1 - nu).expand_as(beta)
    num_samples = G.shape[0]
    #keep track of infected, latent, and informed at each time step
    all_I = torch.zeros(T, num_samples, beta.shape[1], 1).double()
    all_E = torch.zeros(T, num_samples, E.shape[1], E.shape[2]).double()
    all_F = torch.zeros_like(all_I).double()
    all_I[0] = I[0]
    all_E[0] = E[0]
    #all_I[0] = I[30]
    #all_E[0] = E[30]

    all_F[0] = informed

    #run the main loop for the linearized disease dynamics
    for t in range(1, T):
        #update nu with new information spread
        not_informed_fraction = 1 - informed
        not_informed_fraction_diag = vector_to_diag(not_informed_fraction, beta)
        #constant scaling the beta for information spread
        informed = not_informed_fraction_diag@beta_information@informed + informed
        #print('here is info beta mat')
        #print(beta_information)
        #print('here is informed')
        #print(informed)
        #debug sze
        nu = nu_max*informed
        nu = vector_to_diag(1 - nu, beta)

        #infections
        new_infections = S[t-1] @ mu @ beta @ N[t-1] @ I
        new_infections_active = alpha_fast @ new_infections
        new_infections_latent = new_infections - new_infections_active
        E = mu @ E
        activations = alpha_slow@E
        E = E - activations
        E += new_infections_latent
        E = G @ E + migration_E[t] #CHANGING TO USING THE LAST MIGRATION PERIOD
        #E = G @ E + migration_E[30]

        old_infections = nu @ d @ I
        I = new_infections_active + old_infections + activations
        I = G @ I + migration_I[t]   #CHANGING TO USING THE LAST MIGRATION PERIOD
        #I = G @ I + migration_I[30]

        #return E, I, F by time and age group
        #mean across samples
        all_I[t] = I
        all_E[t] = E
        all_F[t] = informed

    #print(all_I)
    return all_I, all_E, all_F

@jit
def categorical_sample(p):
    threshold = np.random.rand()
    current = 0
    for i in range(p.shape[0]):
        current += p[i]
        if current > threshold:
            return i
@jit
#def threshold_exponential(mean):
#    return 1 + np.round(np.random.exponential(mean-1))
def threshold_exponential(mean):
    return np.round(np.random.exponential(mean))

@jit
def threshold_log_normal(mean, sigma):
    x = np.random.lognormal(mean, sigma)
    if x <= 0:
        return 1
    else:
        return np.round(x)


from mara_schema.data_set import DataSet, Aggregation

from ..entities.seller import seller_entity

sellers_data_set = DataSet(entity=seller_entity, name='Sellers')

sellers_data_set.exclude_path([('Order', 'First order'), 'Customer'])

sellers_data_set.include_attributes(['Zip code'],
                                    ['Zip code', 'City', 'State'])

sellers_data_set.include_attributes(['Order'], ['Order date'])

sellers_data_set.add_simple_metric(
    name='# Orders (lifetime)',
    description='Number of orders with at-least one product fulfilled by this seller',
    aggregation=Aggregation.SUM,
    column_name='number_of_orders_lifetime')

sellers_data_set.add_simple_metric(
    name='# Order items (lifetime)',
    description='Number of products sold by this seller',
    aggregation=Aggregation.SUM,
    column_name='number_of_order_items_lifetime')

sellers_data_set.add_simple_metric(
    name='Revenue (lifetime)',
    description='The lifetime revenue generated from products sold by this seller',
    aggregation=Aggregation.SUM,
    column_name='revenue_lifetime',
    important_field=True)

sellers_data_set.add_composed_metric(
    name='AOV',
    description='The average revenue per order. Attention: not meaningful when split by product',
    formula='[Revenue (lifetime)] / [# Orders (lifetime)]')


wins = 0
draws = 0
losses = 0
count = 0

for _ in range(30):
    result = int(input("Enter the match result (0 for loss, 1 for draw, 3 for win): "))
    if result == 0:
        losses += 1
    elif result == 1:
        draws += 1
        count += result
    elif result == 3:
        wins += 1
        count += result
    else:
        print("Invalid input. Please enter 0, 1, or 3.")

print("Number of Wins:", wins)
print("Number of Draws:", draws)
print("Number of Losses:", losses)
print("Occurrences of 3:", count)


import time
import csv

class Action:
    """Action"""

    def __init__(self, nom, cout, benefice):
        self.nom = nom
        self.cout = cout
        self.benefice = benefice
        self.rendement = cout * benefice
        self.panier = 0

def somme_rendement(actions):
    """Rendement du panier d'action"""
    rendement = 0
    for i in range(0, len(actions)):
        rendement += actions[i].rendement * actions[i].panier
    return rendement

def somme_cout(actions):
    """Cout du panier d'action"""
    cout = 0
    for i in range(0, len(actions)):
        cout += actions[i].cout * actions[i].panier
    return cout

def generer_panier(actions, panier):
    """Reporter la représentation binaire du panier dans la liste des actions"""
    k = len(actions)-1
    for j in range(len(panier) - 1, 1, -1):
        actions[k].panier = int(panier[j])
        k -= 1
    for j in range(0, k + 1):
        actions[j].panier = 0
    return

def extraire_panier(actions):
    """Extraire la représentation binaire du panier à partir de la liste des actions choisies"""
    panier = "0b"
    for i in range(len(actions)):
        panier += str(actions[i].panier)
    return panier

def afficher_panier(actions):
    """Liste des actions du panier d'action"""
    page = "Liste des actions à acquérir :\n"
    for i in range(0, len(actions)):
        if actions[i].panier != 0:
            page += f"- {actions[i].panier}x {actions[i].nom} {actions[i].cout}\n"
    return page

def afficher_resultat(actions, meilleur_panier, meilleur_rendement):
    """Afficher le résultat de la recherche"""
    generer_panier(actions, meilleur_panier)
    print(f"Investissement de {somme_cout(actions)} € pour un rendement de " +
          "{:.2f}".format(meilleur_rendement) + " € sur deux ans")
    print(afficher_panier(actions))

def construire_panier(actions, noeud):
    """Fonction récursive de parcours d'un arbre binaire"""
    global meilleur_rendement
    global meilleur_panier
    global iteration
    iteration += 1
    if noeud < len(actions):
        actions[noeud].panier = 1
        construire_panier(actions, noeud + 1)
        actions[noeud].panier = 0
        construire_panier(actions, noeud + 1)
    else:
        rendement_panier = somme_rendement(actions)
        if somme_cout(actions) <= 500 and rendement_panier > meilleur_rendement:
            meilleur_rendement = rendement_panier
            meilleur_panier = extraire_panier(actions)
    return

def lire_dataset(nom_fichier):
    """Création de la liste d'objet Action à partir du Dataset"""
    actions = []
    with open(nom_fichier, 'r', newline='') as f:
        lecteur = csv.reader(f, delimiter=',')
        entete = True
        for row in lecteur:
            if not entete:
                actions.append(Action(row[0], float(row[1]), float(row[2]) / 100))
            entete = False
    return actions

actions = lire_dataset('Data/Exercice.csv')

print("\nFORME ITERATIVE\n")
print(time.ctime())

meilleur_rendement = 0
meilleur_panier = bin(0)

for i in range(1, 2**len(actions)):
    binary = bin(i)
    generer_panier(actions, binary)
    rendement_panier = somme_rendement(actions)
    if somme_cout(actions) <= 500 and rendement_panier > meilleur_rendement:
        meilleur_rendement = rendement_panier
        meilleur_panier = binary

print(time.ctime())
print(i, "Itérations")
afficher_resultat(actions, meilleur_panier, meilleur_rendement)

for i in range(len(actions)):
    actions[i].panier = 0

print("\nFORME RECURSIVE\n")
print(time.ctime())

meilleur_rendement = 0
meilleur_panier = bin(0)
iteration = 0

construire_panier(actions, 0)

print(time.ctime())
print(iteration, "Itérations")
afficher_resultat(actions, meilleur_panier, meilleur_rendement)


from hangedman import HangManGame
from player import Player
from letter import EnteredLetter
from fruit_list import FruitList

class GameLogic:
    def __init__(self):
        self.__hanged_man = HangManGame()
        self.__player = Player()
        self.__player_letter = EnteredLetter()
        self.__fruit_list = FruitList()

    def run_the_game(self):
        self.__hanged_man.principal_menu()
        self.__hanged_man.player = self.__player
        self.__player.set_players_name()
        self.__player_letter.player = self.__player
        self.__fruit_list.entered_letter = self.__player_letter
        self.__hanged_man.fruit_list = self.__fruit_list
        self.__fruit_list.chose_random_word_from_list()
        self.__fruit_list.show_hidden_chosen_word()
        while self.__player.get_players_lives() > 0 and not self.__fruit_list.ended_word:
            self.__player.show_life()
            self.__player_letter.set_chosen_letter()
            if self.__player_letter.get_chosen_letter() in self.__fruit_list.random_word:
                self.__player_letter.set_correct_players_guess()
            else:
                self.__player_letter.set_wrong_players_guess()
                self.__player.set_lost_a_life()
            self.__fruit_list.show_hidden_chosen_word()
        if self.__player.get_players_lives() == 0:
            self.__hanged_man.get_lost_game()
        else:
            self.__hanged_man.get_won_game()

g = GameLogic()
g.run_the_game()


import numpy as np
import os
from tqdm import tqdm
import glob
import tgt
from scipy.io.wavfile import read
import pyworld as pw
import torch
import audio as Audio
import utils
from text import _clean_text
import hparams as hp

def prepare_align(in_dir):
    for dirpath, dirnames, filenames in tqdm(os.walk(in_dir)):
        for file in filenames:
            if file.endswith(".txt"):
                path_in  = os.path.join(dirpath, file)
                with open(path_in, 'r', encoding='utf-8') as f:
                    lines = f.readlines()
                    assert(len(lines) == 1)
                    text = lines[0]
                    text = _clean_text(text, hp.text_cleaners)

                path_out = os.path.join(dirpath, file)
                with open(path_out, 'w', encoding='utf-8') as f:
                    f.write(text)

def build_from_path(in_dir, out_dir):
    ref_dir_name = in_dir.split("/")[-1]
    basenames = []
    audio_paths = list(glob.glob(os.path.join(in_dir, '*.wav')))
    index = 1
    f0_max = energy_max = 0
    f0_min = energy_min = 1000000
    n_frames = 0
    filelist_list = list()
    for ref_path in glob.glob(os.path.join(in_dir, '*.wav')):
        basename = ref_path.split("/")[-1].replace(".wav","")
        text = utils.get_transcript(ref_path.replace(".wav", ".txt"))
        filelist_list.append("|".join([basename, text]))

        try:
            ret = process_utterance(in_dir, out_dir, basename)
            if ret is None:
                continue
            else:
                info, f_max, f_min, e_max, e_min, n = ret

            print("Done {}: {}".format(index, basename))
            basenames.append(basename)

            index = index + 1

            f0_max = max(f0_max, f_max)
            f0_min = min(f0_min, f_min)
            energy_max = max(energy_max, e_max)
            energy_min = min(energy_min, e_min)
            n_frames += n
        except:
            print("Can't process:", basename)

    strs = ['Total time: {} hours'.format(n_frames*hp.hop_length/hp.sampling_rate/3600),
            'Total frames: {}'.format(n_frames),
            'Min F0: {}'.format(f0_min),
            'Max F0: {}'.format(f0_max),
            'Min energy: {}'.format(energy_min),
            'Max energy: {}'.format(energy_max)]
    for s in strs:
        print(s)

    ### Write Filelist ###
    with open(os.path.join(out_dir, '{}.txt'.format(ref_dir_name)), 'w', encoding='utf-8') as f:
        print("Total saved filelist elements:", len(filelist_list))
        for row in filelist_list:
            f.write(str(row)+'\n')

    return basenames, audio_paths

def process_utterance(in_dir, out_dir, basename):
    wav_path = os.path.join(in_dir, '{}.wav'.format(basename))
    tg_path = os.path.join(out_dir, 'TextGrid', '{}.TextGrid'.format(basename))

    # Get alignments
    textgrid = tgt.io.read_textgrid(tg_path)
    phone, duration, start, end = utils.get_alignment(
        textgrid.get_tier_by_name('phones'))
    # '{A}{B}{$}{C}', $ represents silent phones
    text = '{' + '}{'.join(phone) + '}'
    text = text.replace('{$}', ' ')    # '{A}{B} {C}'
    text = text.replace('}{', ' ')     # '{A B} {C}'

    if start >= end:
        return None

    # Read and trim wav files
    _, wav = read(wav_path)
    wav = wav[int(hp.sampling_rate*start):int(hp.sampling_rate*end)].astype(np.float32)

    # Compute fundamental frequency
    f0, _ = pw.dio(wav.astype(np.float64), hp.sampling_rate,
                   frame_period=hp.hop_length/hp.sampling_rate*1000)
    f0 = f0[:sum(duration)]

    # Compute mel-scale spectrogram and energy
    mel_spectrogram, energy, _ = Audio.tools.get_mel_from_wav(
        torch.FloatTensor(wav))
    mel_spectrogram = mel_spectrogram.numpy().astype(np.float32)[
        :, :sum(duration)]
    energy = energy.numpy().astype(np.float32)[:sum(duration)]
    if mel_spectrogram.shape[1] >= hp.max_seq_len:
        return None

    # Save alignment
    ali_filename = '{}-ali-{}.npy'.format(hp.dataset, basename)
    np.save(os.path.join(out_dir, 'alignment', ali_filename),
            duration, allow_pickle=False)

    # Save fundamental prequency
    f0_filename = '{}-f0-{}.npy'.format(hp.dataset, basename)
    np.save(os.path.join(out_dir, 'f0', f0_filename), f0, allow_pickle=False)

    # Save normalized fundamental prequency
    f0_norm = utils.f0_normalization(f0)
    np.save(os.path.join(out_dir, 'f0_norm', f0_filename), f0_norm, allow_pickle=False)

    # Save energy
    energy_filename = '{}-energy-{}.npy'.format(hp.dataset, basename)
    np.save(os.path.join(out_dir, 'energy', energy_filename),
            energy, allow_pickle=False)

    # Save rescaled energy
    energy_0to1 = utils.energy_rescaling(energy)
    np.save(os.path.join(out_dir, 'energy_0to1', energy_filename), energy_0to1, allow_pickle=False)

    # Save spectrogram
    mel_filename = '{}-mel-{}.npy'.format(hp.dataset, basename)
    np.save(os.path.join(out_dir, 'mel', mel_filename),
            mel_spectrogram.T, allow_pickle=False)

    return '|'.join([basename, text]), max(f0), min([f for f in f0 if f != 0]), max(energy), min(energy), mel_spectrogram.shape[1]


import numpy as np
import torch
import timm
from CustomVIT import VisionTransformer

def get_params(module):
    return sum(p.numel() for p in module.parameters() if p.requires_grad)

def assert_tensors_equal(t1, t2):
    a1, a2 = t1.detach().numpy(), t2.detach().numpy()

    np.testing.assert_allclose(a1, a2)

model_name = "vit_base_patch16_384"
model_official = timm.create_model(model_name, pretrained=True)
model_official.eval()

custom_config = {
    "img_size" : 384,
    "in_chans": 3,
    "patch_size": 16,
    "embed_dim": 768,
    "depth": 12,
    "n_heads": 12,
    "qkv_bias": True,
    "mlp_ratio": 4
}

model_custom = VisionTransformer(**custom_config)
model_custom.eval()

for (n_0, p_0), (n_c, p_c) in zip(
    model_official.named_parameters(), model_custom.named_parameters()
):
    assert p_0.numel() == p_c.numel()
    print(f"{n_0} | {n_c}")

    p_c.data[:] = p_0.data

    assert_tensors_equal(p_c.data, p_0.data)

inp = torch.rand(1, 3, 384, 384)
res_c = model_custom(inp)
rec_o = model_official(inp)

assert get_params(model_custom) == get_params(model_official)
assert_tensors_equal(res_c, rec_o)
torch.save(model_custom,
           r"C:\Users\Vadim\Desktop\folders\For myself\Python\CV\Реализации\VisionTransformers\model_custom.pth")


# -*- coding: utf-8 -*-
"""
XYZtoTIN
==============

Script:   XYZtoTIN.py

Author:   loyler@usgs.gov

Modified: 2021-07-12

Purpose:  Converting an XYZ_uncert_source text file into points joined with LiDAR that can then be

Useage:

References:

:---------------------------------------------------------------------:
"""
# ---------------------------------------------------------------------------
# XYZtoTINModelBuilderArcPyTemplate.py
# Created on: 2021-07-09 14:46:13.00000
#   (generated by ArcGIS/ModelBuilder)
# Usage: XYZtoTINModelBuilderArcPyTemplate <Output_Folder> <Spatial_Reference> <XYZ_Shapefile_Name> <LAS_Shapefile_Name> <Input_XYZ_Table> <Input_LAS_Table> <Original_Lake_Polygon> <Output_Buffer_Name_with_File_Path_and_Extension> <Buffer_Distance> <Minimum_Allowed_Distance_XYZ> <Minimum_Allowed_Distance_LAS>
# Description:
# This model is a multi-step process for thinning CUBEd XYZ bathymetry and LiDAR data after it has been combined, filtered, and exported in R. The model reads in the raw X,Y,Z columns from a .csv or .txt table, makes a layer, creates a buffer that will contain the thinned LiDAR points, erases points within specified boundaries, removes points that are within a specified distance of each other, and outputs new shapefiles and tables.

# ---------------------------------------------------------------------------

# Import arcpy module
import arcpy
#Checking to make sure the appropriate extensions are activated
class LicenseError(Exception):
    pass

try:
    if arcpy.CheckExtension("3D") == "Available":
        arcpy.CheckOutExtension("3D")
    else:
        # raise a custom exception
        raise LicenseError
except LicenseError:
    print("3D Analyst license is unavailable")
except arcpy.ExecuteError:
    print(arcpy.GetMessages(2))

#Timing how long it takes to run each function
from datetime import datetime
start_time = datetime.now()

#Function definition:
def XYZTextFileToTIN(LakeName,Home_Dir, Input_XYZ_Table, Input_LAS_Table,
                     LidarBoundsPolygon, Map_Resolution):

    # Setting the environments outputs can be overwritten if the code is run multiple times and setting the output workspace
    Output_GDB = Home_Dir + "\\" + LakeName + ".gdb"
    arcpy.env.overwriteOutput = True
    arcpy.env.workspace = Output_GDB

    #Setting local variables
    X_Field = "X"
    Y_Field = "Y"
    Z_Field = "Z"
    xyz_uncert_source_Layer = "xyz_uncert_source_Layer"
    temp_las = "temp_las"
    Inner_buffer_path = Output_GDB + "\\InnerBuffer"
    Outer_buffer_path = Output_GDB + "\\OuterBuffer"
    Big_outside_buffer_path = Output_GDB + "\\BigOutsideBuffer"
    Spatial_Reference = "PROJCS['NAD_1983_2011_UTM_Zone_15N',GEOGCS['GCS_NAD_1983_2011',DATUM['D_NAD_1983_2011',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-93.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]];-5120900 -9998100 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision" # provide a default value if unspecified
    Minimum_Allowed_Distance_XYZ = Map_Resolution - 0.01
    XYZ_Shapefile_Name = LakeName + "_xyz"
    LAS_Shapefile_Name = LakeName + "_las"

    if Output_GDB == '#' or not Output_GDB:
        Output_GDB = "C:\\Users\\loyler\\Documents\\ArcGIS\\Default.gdb"  # provide a default value if unspecified

    if Minimum_Allowed_Distance_XYZ == '#' or not Minimum_Allowed_Distance_XYZ:
        Minimum_Allowed_Distance_XYZ = "0.5 Meters"  # provide a default value if unspecified

    ##Making buffers that will be used to create a 3 meter gap between the MB and the LiDAR to make sure they don't overlap

    # Process: Inner Buffer
    Inner_buffer = arcpy.Buffer_analysis(LidarBoundsPolygon, Inner_buffer_path, "-1.5 Meters", "FULL", "ROUND", "NONE", "", "PLANAR")
    # Process: Outer Buffer
    Outer_buffer = arcpy.Buffer_analysis(LidarBoundsPolygon, Outer_buffer_path, "1.5 Meters", "FULL", "ROUND", "NONE", "", "PLANAR")
    #Process: Big outside buffer that selects only relevant LiDAR points
    Big_outside_buffer = arcpy.Buffer_analysis(LidarBoundsPolygon, Big_outside_buffer_path, "500 Meters", "FULL", "ROUND","NONE", "", "PLANAR")
    ##XYZ Points Processing : Output Feature class, thinning, and erasing points outside the buffer

    # Process: Make XY Event Layer
    arcpy.MakeXYEventLayer_management(Input_XYZ_Table, X_Field, Y_Field, xyz_uncert_source_Layer, Spatial_Reference, Z_Field)
    # Process: XYZ Feature Class to Feature Class
    MBextent = arcpy.FeatureClassToFeatureClass_conversion(xyz_uncert_source_Layer, Output_GDB, XYZ_Shapefile_Name,"","","")

    # Process: Making a basic minimum bounding geometry polygon from the thinned MB points
    MBpoly_name = Output_GDB + "\\" + LakeName + "_MBpoly"
    arcpy.MinimumBoundingGeometry_management(
        in_features=MBextent,
        out_feature_class=MBpoly_name,
        geometry_type="CONVEX_HULL", group_option="ALL", group_field="", mbg_fields_option="NO_MBG_FIELDS")

    # Process: XYZ_Uncert_Source Create Random Points
    xyz_uncert_source_crp = arcpy.CreateRandomPoints_management(Output_GDB,
                                        XYZ_Shapefile_Name + "_crp",
                                        XYZ_Shapefile_Name,
                                        "",
                                        4000000,
                                        Minimum_Allowed_Distance_XYZ,
                                        "POINT",
                                        "0")

    # Process: XYZ_Uncert_Source Erase Point
    arcpy.ErasePoint_edit(xyz_uncert_source_crp, Inner_buffer, "OUTSIDE")

    xyz_uncert_source_joined = arcpy.SpatialJoin_analysis(xyz_uncert_source_crp,
                               XYZ_Shapefile_Name,
                               XYZ_Shapefile_Name + "_thinned")

    ###Lidar Processing
    # Process: Make XY Event Layer
    arcpy.MakeXYEventLayer_management(Input_LAS_Table, X_Field, Y_Field, temp_las, Spatial_Reference, Z_Field)
    # Process: LAS Feature Class to Feature Class
    arcpy.FeatureClassToFeatureClass_conversion(temp_las, Output_GDB, LAS_Shapefile_Name, "", "", "")

    # Process: LAS Erase Point (removes all of the irrelevant points outside the general lake region of interest
    arcpy.ErasePoint_edit(LAS_Shapefile_Name, Big_outside_buffer, "OUTSIDE")

    # Process: LAS Create Random Points
    las_crp = arcpy.CreateRandomPoints_management(Output_GDB,
                                                  LAS_Shapefile_Name + "_crp",
                                                  LAS_Shapefile_Name,
                                                  "",
                                                  4000000,
                                                  Minimum_Allowed_Distance_XYZ,
                                                  "POINT",
                                                  "0")

    # Process: LAS Erase Point (removes all points within 1.5 meters of the lake polygon)
    arcpy.ErasePoint_edit(las_crp, Outer_buffer, "INSIDE")

    # Process: Spatial join attribute table from original LAS file
    las_joined = arcpy.SpatialJoin_analysis(las_crp,
                               LAS_Shapefile_Name,
                               LAS_Shapefile_Name + "_thinned")

    ###Creating the Preliminary TIN from the thinned points, LiDAR, and lake polygon:
    #tin_params = xyz_uncert_source_joined + ' Z Mass_points <None>;' + las_joined + ' Z Mass_points <None>'
    #arcpy.env.workspace = Home_Dir + "\\"
    #arcpy.CreateTin_3d(LakeName + '_prelimTIN', Spatial_Reference,
     #                  [xyz_uncert_source_joined,'Z','Mass_points',None],[las_joined,'Z','Mass_points',None])

    #xyz_TIN_portion = Output_GDB + "\\" + LakeName + "_xyz_thinned"
    #las_TIN_portion = Output_GDB + "\\" + LakeName + "_las_thinned"

    #arcpy.CreateTin_3d(out_tin=LakeName + "_prelimTIN",
    #                   spatial_reference="PROJCS['NAD_1983_2011_UTM_Zone_15N',GEOGCS['GCS_NAD_1983_2011',DATUM['D_NAD_1983_2011',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-93.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]",
     #                  in_features=[las_TIN_portion + ' Z Mass_Points <None>',xyz_TIN_portion + ' Z Mass_Points <None>'],
      #                 constrained_delaunay="DELAUNAY")

#Running the function itself:
XYZTextFileToTIN(LakeName="GardenCityOld",
                 Home_Dir="E:\\HYPACK_Projects\\2020_DNR_Lakes\\2020-07_GardenCityOld\\GIS",
                 Input_XYZ_Table="E:\\HYPACK_Projects\\2020_DNR_Lakes\\2020-07_GardenCityOld\\RTextFiles\\GardenCityOld_xyz_uncert_source.csv",
                 Input_LAS_Table="E:\\HYPACK_Projects\\2020_DNR_Lakes\\2020-07_GardenCityOld\\RTextFiles\\GardenCityOld_las.txt",
                 LidarBoundsPolygon="E:\\HYPACK_Projects\\2020_DNR_Lakes\\2020-07_GardenCityOld\\GIS\\GardenCityOld.gdb\\GardenCityOld_lidarbounds",
                 Map_Resolution=0.5)

end_time = datetime.now()
print('Duration: {}'.format(end_time - start_time))


import zipfile
from datetime import datetime as dt

from pykml.factory import KML_ElementMaker as KML
import lxml.etree as ET

def df_to_kml(df):
    styles = {
        "mag0": {
            "name": "mag_0_2.png",
            "scale": 0.4375
        },
        "mag1": {
            "name": "mag_2_3.png",
            "scale": 0.4375
        },
        "mag2": {
            "name": "mag_3_4.png",
            "scale": 0.4375
        },
        "mag3": {
            "name": "mag_4_9.png",
            "scale": 0.4375
        },
    }

    doc = KML.kml(
        KML.Document(
            KML.Name(f"Last {len(df)} eq in La Palma"),
            KML.Folder(
                KML.name(f"Last {len(df)} eq in La Palma"),
            )
        )
    )

    for ix, r in df.iterrows():

        if r.mag <= 2:
            style = styles.get("mag0")
        elif 2 < r.mag <= 3:
            style = styles.get("mag1")
        elif 3 < r.mag <= 4:
            style = styles.get("mag2")
        else:
            style = styles.get("mag3")

        pm = KML.Placemark(
            KML.description(f"{r.magtype} {r.mag} @ {r.depth}. ({r.time})\nhttps://www.emsc.eu/Earthquake/earthquake.php?id={r.source_id}"),
            KML.Point(
                KML.coordinates(f"{r.lon},{r.lat}")
            ),
            KML.LookAt(
                KML.longitude(r.lon),
                KML.latitude(r.lat),
                KML.altitude(r.depth)
            ),
            KML.TimeStamp(
                KML.when((r.time).strftime('%Y-%m-%dT%H:%MZ')),
            ),
            KML.Style(
                KML.IconStyle(
                    KML.scale(style.get("scale")),
                    KML.Icon(
                        KML.href(style.get("name"))
                    ),
                ),
            )
        )

        doc.Document.Folder.append(
            pm
        )

    return ET.tostring(doc, pretty_print=True)

def kml_to_zip(df):
    data = df_to_kml(df)

    tmp_zip = f"/tmp/{int(dt.utcnow().timestamp() * 1000000)}_canary_eq.zip"

    zf = zipfile.ZipFile(
        tmp_zip,
        mode='w',
        compression=zipfile.ZIP_DEFLATED,
    )
    try:
        zf.write('assets/mag_0_2.png', "mag_0_2.png")
        zf.write('assets/mag_2_3.png', "mag_2_3.png")
        zf.write('assets/mag_3_4.png', "mag_3_4.png")
        zf.write('assets/mag_4_9.png', "mag_4_9.png")
        zf.writestr("canary_eq.kml", data=data)
    finally:
        zf.close()

    return tmp_zip

def df_to_csv(df):
    tmp_csv = f"/tmp/{int(dt.utcnow().timestamp() * 1000000)}_canary_eq.csv"

    df.to_csv(tmp_csv)

    return tmp_csv


# - *- coding: utf- 8 - *-
import sqlite3
from time import time
from data.config import PATH_DATABASE

########################################
#  _    _ _______ _____ _       _____  #
# | |  | |__   __|_   _| |     / ____| #
# | |  | |  | |    | | | |    | (___   #
# | |  | |  | |    | | | |     \___ \  #
# | |__| |  | |   _| |_| |____ ____) | #
#  \____/   |_|  |_____|______|_____/  #
########################################
# Спасибо Djimbo (https://zelenka.guru/djimbo/)
# Форматирование запроса без аргументов

def update_format(sql, parameters: dict):
    if "XXX" not in sql:
        sql += " XXX "

    values = ", ".join([
        f"{item} = ?" for item in parameters
    ])
    sql = sql.replace("XXX", values)

    return sql, list(parameters.values())

# Форматирование запроса с аргументами
def update_format_args(sql, parameters: dict):
    sql = f"{sql} WHERE "

    sql += " AND ".join([
        f"{item} = ?" for item in parameters
    ])

    return sql, list(parameters.values())

# Преобразования sql списка в словарь
def dict_factory(cursor, row):
    save_dict = {}

    for idx, col in enumerate(cursor.description):
        save_dict[col[0]] = row[idx]

    return save_dict

##########################
#   _____  ____  _       #
#  / ____|/ __ \| |      #
# | (___ | |  | | |      #
#  \___ \| |  | | |      #
#  ____) | |__| | |____  #
# |_____/ \___\_\______| #
##########################
# Добавление пользователя
def add_user(user_id, username, fullname):
    with sqlite3.connect(PATH_DATABASE) as con:
        con.row_factory = dict_factory
        con.execute("INSERT INTO users "
                    "(user_id, username, fullname, balance, created) "
                    "VALUES (?, ?, ?, ?, ?)",
                    [user_id, username, fullname, 0, int(time())])
        con.commit()

# Получение пользователя
def get_user(**kwargs):
    with sqlite3.connect(PATH_DATABASE) as con:
        con.row_factory = dict_factory
        sql = "SELECT * FROM users"
        sql, parameters = update_format_args(sql, kwargs)
        return con.execute(sql, parameters).fetchone()

# Получение пользователей
def get_users(**kwargs):
    with sqlite3.connect(PATH_DATABASE) as con:
        con.row_factory = dict_factory
        sql = "SELECT * FROM users"
        sql, parameters = update_format_args(sql, kwargs)
        return con.execute(sql, parameters).fetchall()

# Получение всех пользователей
def get_all_users():
    with sqlite3.connect(PATH_DATABASE) as con:
        con.row_factory = dict_factory
        sql = "SELECT * FROM users"
        return con.execute(sql).fetchall()

# Редактирование пользователя
def update_user(user_id, **kwargs):
    with sqlite3.connect(PATH_DATABASE) as con:
        con.row_factory = dict_factory
        sql = f"UPDATE users SET"
        sql, parameters = update_format(sql, kwargs)
        parameters.append(user_id)
        con.execute(sql + "WHERE user_id = ?", parameters)
        con.commit()

# Удаление пользователя
def delete_user(**kwargs):
    with sqlite3.connect(PATH_DATABASE) as con:
        con.row_factory = dict_factory
        sql = "DELETE FROM users"
        sql, parameters = update_format_args(sql, kwargs)
        con.execute(sql, parameters)
        con.commit()

# Получение настроек
def get_settings():
    with sqlite3.connect(PATH_DATABASE) as con:
        con.row_factory = dict_factory
        sql = "SELECT * FROM settings"
        return con.execute(sql).fetchone()