# ====================================
# -*- coding: utf-8 -*-
# project name:     Bastion The Sentinel
# file name:        stream.py
# python version:   3.4
# description:      Serve video data on http over the wifi
# ====================================

import io
import picamera
import logging
import socketserver
from threading import Condition
from http import server

PAGE="""
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bastion The Sentinel | Live Stream</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

Bastion The Sentinel Live Stream

Live streaming from Bastion's Raspberry Pi 3.

"""

class StreamingOutput(object):
    def __init__(self):
        self.frame = None
        self.buffer = io.BytesIO()
        self.condition = Condition()

    def write(self, buf):
        if buf.startswith(b'\xff\xd8'):
            # New frame, copy the existing buffer's content and notify all
            # clients it's available
            self.buffer.truncate()
            with self.condition:
                self.frame = self.buffer.getvalue()
                self.condition.notify_all()
            self.buffer.seek(0)
        return self.buffer.write(buf)

class StreamingHandler(server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.send_response(301)
            self.send_header('Location', '/index.html')
            self.end_headers()
        elif self.path == '/index.html':
            content = PAGE.encode('utf-8')
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.send_header('Content-Length', len(content))
            self.end_headers()
            self.wfile.write(content)
        elif self.path == '/stream.mjpg':
            self.send_response(200)
            self.send_header('Age', 0)
            self.send_header('Cache-Control', 'no-cache, private')
            self.send_header('Pragma', 'no-cache')
            self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
            self.end_headers()
            try:
                while True:
                    with output.condition:
                        output.condition.wait()
                        frame = output.frame
                    self.wfile.write(b'--FRAME\r\n')
                    self.send_header('Content-Type', 'image/jpeg')
                    self.send_header('Content-Length', len(frame))
                    self.end_headers()
                    self.wfile.write(frame)
                    self.wfile.write(b'\r\n')
            except Exception as e:
                logging.warning(
                    'Removed streaming client %s: %s',
                    self.client_address, str(e))
        else:
            self.send_error(404)
            self.end_headers()

class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
    allow_reuse_address = True
    daemon_threads = True

with picamera.PiCamera(resolution='640x480', framerate=12) as camera:
    output = StreamingOutput()
    camera.vflip = True
    camera.hflip = True
    camera.start_recording(output, format='mjpeg')
    try:
        address = ('', 8000)
        server = StreamingServer(address, StreamingHandler)
        server.serve_forever()
    finally:
        camera.stop_recording()


import os
import sys
import time
import inspect
import itertools
import linecache
import traceback
from math import floor
from hashlib import md5
from datetime import datetime
from functools import wraps

from .blender import show_blender_popup
from .functools import find_fns
from .globals import Globals
from .hasher import Hasher

class Debugger:
    _error_level = 1
    _exception_count = 0

    def __init__(self):
        pass

    @staticmethod
    def set_error_level(l):
        Debugger._error_level = max(0, min(5, int(l)))

    @staticmethod
    def get_error_level():
        return Debugger._error_level

    @staticmethod
    def dprint(*objects, sep=' ', end='\n', file=sys.stdout, flush=True, l=2):
        if Debugger._error_level < l: return
        sobjects = sep.join(str(o) for o in objects)
        print(
            f'DEBUG({l}): {sobjects}',
            end=end, file=file, flush=flush
        )

    @staticmethod
    def dcallstack(l=2):
        ''' print out the calling stack, skipping the first (call to dcallstack) '''
        Debugger.dprint('Call Stack Dump:', l=l)
        for i, entry in enumerate(inspect.stack()):
            if i > 0:
                Debugger.dprint('  %s' % str(entry), l=l)

    @staticmethod
    def call_stack():
        return traceback.format_stack()

    # http://stackoverflow.com/questions/14519177/python-exception-handling-line-number
    @staticmethod
    def get_exception_info_and_hash():
        '''
        this function is a duplicate of the one above, but this will attempt
        to create a hash to make searching for duplicate bugs on github easier (?)
        '''

        exc_type, exc_obj, tb = sys.exc_info()
        pathabs, pathdir = os.path.abspath, os.path.dirname
        pathjoin, pathsplit = os.path.join, os.path.split
        base_path = pathabs(pathjoin(pathdir(__file__), '..'))

        hasher = Hasher()
        errormsg = ['EXCEPTION (%s): %s' % (exc_type, exc_obj)]
        hasher.add(errormsg[0])
        # errormsg += ['Base: %s' % base_path]

        etb = traceback.extract_tb(tb)
        pfilename = None
        for i,entry in enumerate(reversed(etb)):
            filename,lineno,funcname,line = entry
            if pfilename is None:
                # only hash in details of where the exception occurred
                hasher.add(os.path.split(filename)[1])
                # hasher.add(lineno)
                hasher.add(funcname)
                hasher.add(line.strip())
            if filename != pfilename:
                pfilename = filename
                if filename.startswith(base_path):
                    filename = '.../%s' % filename[len(base_path)+1:]
                errormsg += ['    %s' % (filename, )]
            errormsg += ['%03d %04d:%s() %s' % (i, lineno, funcname, line.strip())]

        return ('\n'.join(errormsg), hasher.get_hash())

    @staticmethod
    def print_exception():
        Debugger._exception_count += 1
        errormsg, errorhash = Debugger.get_exception_info_and_hash()
        message = []
        message += ['Exception Info']
        message += ['- Time: %s' % datetime.today().isoformat(' ')]
        message += ['- Count: %d' % Debugger._exception_count]
        message += ['- Hash: %s' % str(errorhash)]
        message += ['- Info:']
        message += ['  - %s' % s for s in errormsg.splitlines()]
        message = '\n'.join(message)
        print('%s\n%s\n%s' % ('_' * 100, message, '^' * 100))
        logger = Globals.logger
        if logger: logger.add(message)   # write error to log text object
        # if Debugger._exception_count < 10:
        #     show_blender_popup(
        #         message,
        #         title='Exception Info',
        #         icon='ERROR',
        #         wrap=240
        #     )
        return message

    # @staticmethod
    # def print_exception2():
    #     exc_type, exc_value, exc_traceback = sys.exc_info()
    #     print("*** print_tb:")
    #     traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
    #     print("*** print_exception:")
    #     traceback.print_exception(exc_type, exc_value, exc_traceback,
    #                               limit=2, file=sys.stdout)
    #     print("*** print_exc:")
    #     traceback.print_exc()
    #     print("*** format_exc, first and last line:")
    #     formatted_lines = traceback.format_exc().splitlines()
    #     print(formatted_lines[0])
    #     print(formatted_lines[-1])
    #     print("*** format_exception:")
    #     print(repr(traceback.format_exception(exc_type, exc_value,exc_traceback)))
    #     print("*** extract_tb:")
    #     print(repr(traceback.extract_tb(exc_traceback)))
    #     print("*** format_tb:")
    #     print(repr(traceback.format_tb(exc_traceback)))
    #     if exc_traceback:
    #         print("*** tb_lineno:", exc_traceback.tb_lineno)

    start_time = time.time()
    last_time = time.time()
    @staticmethod
    def tprint(*args):
        t = time.time()
        td = t - Debugger.last_time
        lbar = min(25, floor(td*20))
        bar = '%s%s' % ('X' * lbar, '_' * (25-lbar))
        print(bar, '%8.4f' % td, *args)
        sys.stdout.flush()
        Debugger.last_time = t

class ExceptionHandler:
    _universal = []

    @staticmethod
    def on_exception(fn):
        fn._exceptionhandler_on_exception = True
        return fn

    def __init__(self, obj=None, *, universal=False):
        # print(f'ExceptionHandler.__init__({self})')
        self._single = []
        self._um = []
        self._universal_only = universal
        self.collect_callbacks(obj)

    def __del__(self):
        # print(f'ExceptionHandler.__del__({self})')
        for fn in getattr(self, '_um', []):
            self.remove_universal_callback(fn)

    def collect_callbacks(self, obj):
        if not obj: return
        for (_, fn) in find_fns(obj, '_exceptionhandler_on_exception'):
            self.add_callback(fn)

    @staticmethod
    def add_universal_callback(fn):
        ExceptionHandler._universal += [fn]

    @staticmethod
    def remove_universal_callback(fn):
        if fn not in ExceptionHandler._universal: return
        ExceptionHandler._universal.remove(fn)

    @staticmethod
    def clear_universal_callbacks():
        ExceptionHandler._universal = []

    def add_callback(self, fn, universal=None):
        # print(f'ExceptionHandler.add_callback({self}, {fn}, {universal})')
        if getattr(fn, '_exceptionhandler_collected', False): return
        fn._exceptionhandler_collected = True
        if universal is None and self._universal_only: universal = True
        if universal:
            self._universal += [fn]
            self._um += [fn]
        else:
            self._single += [fn]

    def wrap(self, def_val, only=Exception):
        def wrapper(fn):
            def wrapped(*args, **kwargs):
                ret = def_val
                try:
                    ret = fn(*args, **kwargs)
                except only as e:
                    self.handle_exception(e)
                return ret
            return wrapped
        return wrapper

    def handle_exception(self, e):
        # print(f'ExceptionHandler: calling back these fns')
        # for fn in itertools.chain(self._universal, self._single):
        #     print(f'    {fn}')
        for fn in itertools.chain(self._universal, self._single):
            try:
                fn(e)
            except Exception as e2:
                print(f'ExceptionHandler: Caught exception while calling back exception callbacks: {fn.__name__}')
                print(f'    original:   {e}')
                print(f'    additional: {e2}')
                debugger.print_exception()

debugger = Debugger()
dprint = debugger.dprint
tprint = debugger.tprint
exceptionhandler = ExceptionHandler(universal=True)
Globals.set(debugger)
Globals.dprint = dprint
Globals.exceptionhandler = exceptionhandler


"""
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.

Molecule mapper.
"""
from sqlalchemy.orm import relationship

from everest.repositories.rdb.utils import mapper
from thelma.entities.moleculedesign import MoleculeDesign
from thelma.entities.organization import Organization
from thelma.entities.sample import Molecule
from thelma.entities.sample import SampleMolecule
from thelma.entities.suppliermoleculedesign import SupplierMoleculeDesign

__docformat__ = 'reStructuredText en'
__all__ = ['create_mapper']

def create_mapper(molecule_tbl, molecule_supplier_molecule_design_tbl):
    "Mapper factory."
#    ssmd = single_supplier_molecule_design_tbl
#    smd = supplier_molecule_design_tbl
#    mcl = molecule_tbl.alias()
#    prd_sel = \
#        select([distinct(smd.c.product_id)],
#               and_(mcl.c.molecule_design_id ==
#                                        molecule_tbl.c.molecule_design_id,
#                    smd.c.supplier_id == molecule_tbl.c.supplier_id,
#                    smd.c.is_current
#                    ),
#               from_obj=[mcl.join(ssmd,
#                                  ssmd.c.molecule_design_id ==
#                                            mcl.c.molecule_design_id)
#                            .join(smd,
#                                  smd.c.supplier_molecule_design_id ==
#                                         ssmd.c.supplier_molecule_design_id)]
#               )
#    msmd = molecule_supplier_molecule_design_vw
    msmd = molecule_supplier_molecule_design_tbl
    m = mapper(Molecule, molecule_tbl,
        id_attribute='molecule_id',
        properties=dict(
            supplier=relationship(Organization),
            molecule_design=relationship(MoleculeDesign, uselist=False,
#                                         lazy='joined'
                                         ),
            # Loading the product ID like this is faster than loading it
            # through the supplier molecule design.
#            product_id=column_property(prd_sel.as_scalar(), deferred=True),
            supplier_molecule_design=
                 relationship(SupplierMoleculeDesign,
                              uselist=False,
                              secondary=msmd,
#                              primaryjoin=ssmd.c.molecule_design_id ==
#                                             molecule_tbl.c.molecule_design_id,
#                              secondaryjoin=and_(smd.c.supplier_molecule_design_id ==
#                                                    ssmd.c.supplier_molecule_design_id,
#                                                 smd.c.is_current,
#                                                 smd.c.supplier_id == molecule_tbl.c.supplier_id),
#                              foreign_keys=(ssmd.c.molecule_design_id,
#                                            ssmd.c.supplier_molecule_design_id),
##                              remote_side=msmd.c.molecule_id,
                              viewonly=True),
            sample_molecules=relationship(SampleMolecule,
                                          back_populates='molecule'),
            ),
        )
    return m


# Create a custom exception class called NegativeValueError. Write a Python program that takes an
# integer as input and raises the NegativeValueError if the input is negative. Handle this custom
# exception with a try/except block and display an error message.

class NegativeValueError(Exception):
    """Raise if int is negative"""

# Get user input
num = int(input("Write integer: "))

# Check if num is negative
try:
    if num < 0:
        raise NegativeValueError("Error: Number is negative!")
except NegativeValueError as e:
    print(e)


f = open("day2_input", "r")
input = f.readlines()

from functools import reduce

def calc(prev, curr):
	round_score = (ord(curr[2]) - ord('X')) * 3
	shape_score = (ord(curr[0]) - ord('A') + ord(curr[2]) - ord('X')) % 3
	return prev + (shape_score if shape_score else 3) + round_score

print(reduce(calc, input, 0))


import pandas as pd

import matplotlib.pyplot as plt

df = pd.read_json("https://ipfs.io/ipfs/QmaEerNc9isnYPmmzHuac3NPSTC6g8eyzXv1Q2LuBgqy8N")

plt.plot(df.temps, df.adn, "-*b")

plt.xlabel("Temps (H)")

plt.ylabel("Quantité d'ADN par cellule (UA)")

plt.title("Quantité d'ADN par cellule en fonction du temps")

plt.savefig("adncycle.png")

Transmission, variation et expression du patrimoine génétique/docsvt/adncycle.py


#互いに素なa,bについて、a*x+b*y=1の一つの解
def egcd(a, b):
    (x, lastx) = (0, 1)
    (y, lasty) = (1, 0)
    while b != 0:
        q = a // b
        (a, b) = (b, a % b)
        (x, lastx) = (lastx - q * x, x)
        (y, lasty) = (lasty - q * y, y)
    return (lastx, lasty, a)

def mod_inv(a, m):
    (inv, q, gcd_val) = egcd(a, m)
    return inv % m

import fractions
mod = (10**9)+ 7
n = int(input())
a = list(map(int, input().split()))
lcm = 1
for i in range(n):
    gcd = fractions.gcd(lcm, a[i])
    lcm *= a[i]
    lcm = lcm // gcd
lcm %= mod
ans = 0
for i in range(n):
    k = mod_inv(a[i], mod)
    ans += lcm * k
    ans %= mod
print(ans)

python/AtCoder Beginner Contest 152/E.py


import cv2
import pyzed.sl as sl
import numpy as np
import time
import json
import os

from math import pi, sqrt, cos, sin
from operator import itemgetter

class DetectMode:
    Real = "Real"
    Simulation = "Simulation"

class CenterCalculationMode:
    ByMoments = "ByMoments"
    ByColors = "ByColors"

class BallDetection():

    def __init__(self, conf_file, detect_mode):
        # Файл конфигурации
        self.config = None
        self.jsonFile = None
        self.ConfigName = conf_file
        # Настроечные параметры при инициализации камеры
        self.detect_mode = detect_mode
        # Инициализационные параметры
        self.init_params = sl.InitParameters()
        # Экземпляр камеры
        self.camera = sl.Camera()
        # Настроечные параметры изменяемые в рантайме
        self.runtime_settings = None
        # Левое цветное изображение
        self.image_color_left = None
        # Правое цветное изображение
        self.image_color_right = None
        # Последний статус захвата изображения
        self.is_grab_success = False
        # Расчет центра мяча по цвету или по моментам
        self.center_calculation = CenterCalculationMode.ByMoments
        # Калибровочные параметры камеры
        self.calibration_parameters = None
        # Начальное время
        self.start_time = time.time()
        # Предыдущее время для расчета FPS
        self.previous_time = 0
        # Предыдущее время для расчета скорости
        self.previous_detect_time = 0
        # Последняя разница времени
        self.delta_time = 0
        # Последняя разница времени распознавания
        self.delta_detect_time = 0
        # Последняя задетектированная скорость
        self.velocity = [0.0, 0.0, 0.0]
        # Последнее зафиксированное положение в СК камеры
        self.last_position_camera = [0.0, 0.0, 0.0]
        # Последнее зафиксированное положение в СК робота
        self.last_position_robot = [0.0, 0.0, 0.0]
        # Последняя валидность данных
        self.validity = False
        # Путь к папке с логами
        self.data_path = None
        # Открытый файл с точками траектории в СК камеры
        self.log_file = None
        # Последнее мячика на левом кадре
        self.ball_point_left = (0, 0)

        # Загрузка файла конфигурации
        self.jsonFile = open(self.ConfigName, "r", encoding='utf-8')
        self.config = json.load(self.jsonFile)

        # Инициализация лога
        self.init_log()

        # Загрузка коэфициентов матрицы перехода из СК камеры в СК робота
        self.calib_data = np.array(self.config["Robot"]["transform_data"])
        self.tranform_matrix = self.create_transform_matrix(self.calib_data)
        # Цвет мяча в BGR
        self.ball_color = self.config["Detection"]["BallColor"]

        # Инициализация камеры
        if self.detect_mode is DetectMode.Real:
            # Загрузка параметров перед инициализацией камеры
            self.camera_initial_config()

            # Пытаемся открыть камеру
            status = self.camera.open(self.init_params)
            print(status)
            if status != sl.ERROR_CODE.SUCCESS:
                raise OSError(status)

            # Загрузка рантайм параметров камеры (которые должны быть загружены после инициализации)
            self.camera_runtime_config()
            self.calibration_parameters = self.camera.get_camera_information().calibration_parameters

    def __del__(self):
        if self.camera.is_opened():
            self.camera.close()

        if self.log_file is not None:
            self.log_file.close()

    # Настройка камеры
    def camera_initial_config(self):
        # Предварительная настройка камеры
        # Используемая система координат
        self.init_params.coordinate_system = sl.COORDINATE_SYSTEM.COORDINATE_SYSTEM_RIGHT_HANDED_Z_UP
        # Типы формирования карты глубины
        # DEPTH_MODE_QUALITY DEPTH_MODE_PERFORMANCE DEPTH_MODE_MEDIUM DEPTH_MODE_ULTRA DEPTH_MODE_NONE
        self.init_params.depth_mode = sl.DEPTH_MODE.DEPTH_MODE_NONE
        # Используем мм в качестве системных единиц
        self.init_params.coordinate_units = sl.UNIT.UNIT_MILLIMETER
        # Минимальное расстояние для распознавания глубины 300 мм
        self.init_params.depth_minimum_distance = 300
        # Разрешение каqмеры
        self.init_params.camera_resolution = sl.RESOLUTION.RESOLUTION_HD720
        # частота кадров
        self.init_params.camera_fps = 60
        # Стабилизация карты глубины
        self.init_params.depth_stabilization = False

    # Настройки камеры после её открытия
    def camera_runtime_config(self):
        self.runtime_settings = sl.RuntimeParameters()
        # Тип формирования карты глубины
        self.runtime_settings.sensing_mode = sl.SENSING_MODE.SENSING_MODE_STANDARD
        # СК вычисляемых точек
        self.runtime_settings.measure3D_reference_frame = sl.REFERENCE_FRAME.REFERENCE_FRAME_CAMERA
        # Максимальная дальность работы стерео
        self.camera.set_depth_max_range_value(10000)
        # Настройка камеры
        # Маленькая экспозиция что бы не было размытия
        # cam.set_camera_settings(sl.CAMERA_SETTINGS.CAMERA_SETTINGS_EXPOSURE, 70)
        # cam.set_camera_settings(sl.CAMERA_SETTINGS.CAMERA_SETTINGS_GAIN, 61)
        # cam.set_camera_settings(sl.CAMERA_SETTINGS.CAMERA_SETTINGS_AUTO_WHITEBALANCE, False)
        # cam.set_camera_settings(sl.CAMERA_SETTINGS.CAMERA_SETTINGS_WHITEBALANCE, 2800)

    def init_log(self):
        path_name_base = self.config["Detection"]["LogDataPath"]
        path_name_modificator = 0

        # Если ничего не логируется то и нафиг папку создавать
        if (self.config["Detection"]["TrajectoryLogging"] or\
            self.config["Detection"]["ImageRawLogging"] or\
            self.config["Detection"]["ImageRecLogging"]) is False:
            print("false")
            return

        # Что бы не было перезаписи, созданем новую папку с инкрементным номером
        while(os.path.isdir(path_name_base + str(path_name_modificator))):
            path_name_modificator += 1

        self.data_path = path_name_base + str(path_name_modificator)
        os.makedirs(self.data_path)
        print("Data folder: {}".format(self.data_path))

        # Создаем файл для записи точек если мы логируем точки
        if self.config["Detection"]["TrajectoryLogging"]:
            self.log_file = open(self.data_path + "/trajectory_camera.txt", "w+")
            write_header = "Time,ms;"
            write_header += "RobotX,mm;RobotY,mm;RobotZ,mm;"
            self.log_file.write(write_header + "\n")

    # Получение пары кадров
    def grab_stereo(self):
        # ZED матрица изображения с камеры
        mat_image_color_left = sl.Mat()  # Цветное изображение с левой камеры
        mat_image_color_right = sl.Mat()  # Цветное изображение с правой камеры

        # Формируем кадр с камеры
        err = self.camera.grab(self.runtime_settings)
        self.is_grab_success = err == sl.ERROR_CODE.SUCCESS

        # Если кадр взять не получилось, выкидываем ошибку
        if self.is_grab_success is not True:
            raise ValueError(err)

        # Если успешно то загружаем матрицу содержащую кадр
        # Чем меньше загрузок картинок тем выше FSP
        # цветное изображение с левой камеры
        self.camera.retrieve_image(mat_image_color_left, sl.VIEW.VIEW_LEFT)
        self.camera.retrieve_image(mat_image_color_right, sl.VIEW.VIEW_RIGHT)

        # Формирование кадра для работы в openCV
        self.image_color_left = mat_image_color_left.get_data()
        self.image_color_right = mat_image_color_right.get_data()

        return (self.image_color_left, self.image_color_right)

    def __saturation_point(self, point, shape):
        point[0] = point[0] if point[0] > 0 else 0
        point[0] = point[0] if point[0] < shape[0] else shape[0]

        point[1] = point[1] if point[1] > 0 else 0
        point[1] = point[1] if point[1] < shape[1] else shape[1]

        return point

    def _convert_MAT2IMAGE(self, point):
        (x, y) = point
        return (int(y), int(x))

    def _convert_IMAGE2MAT(self, point):
        (x, y) = point
        return (y, x)

    def _convert_Global2ROI(self, point, roi):
        x, y = point
        x += -roi[0][0]
        y += -roi[0][1]
        return (x, y)

    def _convert_ROI2Global(self, point, roi):
        x, y = point
        x += roi[0][0]
        y += roi[0][1]
        return (x, y)

    def _get_roi(self, roi_point, shape):
        (x, y) = roi_point
        roi_size = self.config["Detection"]["ROISize"]
        left_upper_point = self.__saturation_point([int(x - roi_size), int(y - roi_size)], shape)
        right_lower_point = self.__saturation_point([int(x + roi_size), int(y + roi_size)], shape)

        return [left_upper_point, right_lower_point]

    def _convert_Scaled2Global(self, point):
        (x, y) = point
        ratio = self.config["Detection"]["DownScaleRatio"]
        x = x * ratio
        y = y * ratio
        return (x, y)

    # Поиск минимальной точки
    def _get_minimum_point(self, image_hg):
        # Поиск минимума на кадре - это соответствует лучшей точки на кадре
        min_points = np.where(image_hg == np.amin(image_hg))

        # Транспонирование полученного массива в пары [(x,y), (x1,y1)]
        min_points = list(zip(min_points[0], min_points[1]))

        # Хрен знает что делать если точек несколько, просто берем первую
        return min_points[0]

    # Переход в новое цветовое пространство
    def _convert_BGR2HG(self, image):
        # Выделяем отдельные каналы из исходного изображения
        channels = cv2.split(image)

        # Переименование каналов
        red, blue, green = channels[2].astype(float), channels[0].astype(float), channels[1].astype(float)

        ball_red = float(self.ball_color[2])
        ball_blue = float(self.ball_color[0])
        ball_green = float(self.ball_color[1])

        # В зависимости от превалирующего канала выбираем формулу для расчёта
        if np.argmax(self.ball_color) == 0:
            ballrb = ball_red / ball_blue
            ballgb = ball_green / ball_blue

            blue = np.where(blue < self.config["Detection"]["ChannelThreshold"], 1, blue)
            colorspace_HG = abs(red / blue - ballrb) + abs(green / blue - ballgb)

        elif np.argmax(self.ball_color) == 1:
            ballrg = ball_red / ball_green
            ballbg = ball_blue / ball_green

            green = np.where(green < self.config["Detection"]["ChannelThreshold"], 1, green)
            colorspace_HG = abs(red / green - ballrg) + abs(blue / green - ballbg)
        else:
            ballgr = ball_green / ball_red
            ballbr = ball_blue / ball_red

            red = np.where(red < self.config["Detection"]["ChannelThreshold"], 1, red)
            colorspace_HG = abs(green / red - ballgr) + abs(blue / red - ballbr)

        return colorspace_HG

    def _binarization_HG(self, image, min_point):
        height, width = image.shape
        blank_image = np.zeros((height, width, 1), np.uint8)

        treshold = image[min_point] * self.config["Detection"]["ColorHGModificator"]\
            + self.config["Detection"]["ColorHGMinimal"]

        if treshold > self.config["Detection"]["BinarizationThreshold"]:
            treshold = self.config["Detection"]["BinarizationThreshold"]

        blank_image = np.where(image > treshold, 0, 255)
        return blank_image.astype(np.uint8)

    def _find_contours(self, img_gray):
        # Поиск всех контуров на изображении
        contours, hierarchy = cv2.findContours(img_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        if len(contours) is 0:
            raise ValueError("No contours")

        return contours

    def _processing_image(self, image_gray):
        image_gray = cv2.GaussianBlur(image_gray, (5, 5), 0)
        image_gray = cv2.addWeighted(image_gray, 1.5, image_gray, 1.5, 0)
        return image_gray

    def _get_enclosing_radius(self, contour):
        (x, y), radius = cv2.minEnclosingCircle(contour)
        return radius

    def _sort_contours(self, contours):
        # Создаем массив из кортежей индексов контуров, самих контуров
        # и поля для рейтинга каждого контура
        enum_contrours = [[i, ctr, 0] for i, ctr in enumerate(contours)]

        # Сортировка по величине окружности
        enum_contrours.sort(key=lambda x: self._get_enclosing_radius(x[1]), reverse=True)

        # Добавляем в вес третий параметр
        for index, elem in enumerate(enum_contrours):
            elem[2] += pow(index, 2)

        # Возвращаем контур у которого минимальный третий элемент
        enum_contrours.sort(key=itemgetter(2))
        return enum_contrours[0][1]

    def _get_center_moment(self, contour):
        M = cv2.moments(contour)
        center_x = M["m10"] / M["m00"]
        center_y = M["m01"] / M["m00"]

        center_point = (center_x, center_y)
        return center_point

    def _get_center_color(self, image, mask):
        # Выделяем все точки которые входят в черно-белую маску после бинаризации
        interested_points = np.where(mask == 255)
        # Транспонирование полученного массива в пары [(x,y), (x1,y1)]
        interested_points = list(zip(interested_points[0], interested_points[1]))

        # Вычисляем все значения пикселей из изображения в цветовом пространстве HG
        # которые попали в маску
        values = [image[point] for point in interested_points]

        # Находим минимальное/максимальное значение и их разницу
        value_max, value_min = max(values), min(values)
        delta_value = value_max - value_min

        x_accumulator = 0
        y_accumulator = 0
        weight_accumulator = 0

        # Проход по точкам и вычисление весовых коэфициентов
        for point in interested_points:
            # Вычисление веса в приведении в диапазон 0.0 - 1.0
            weight_value = 1 - (image[point] - value_min) / (delta_value)
            x_accumulator += point[0] * weight_value
            y_accumulator += point[1] * weight_value
            weight_accumulator += weight_value

        center_point = (x_accumulator / weight_accumulator, y_accumulator / weight_accumulator)

        return center_point

    # Поиск мяча на отдельном кадре
    def find_ball(self, image):
        # Уменьшаем изображение для быстрого поиска максимума цвета
        ratio = self.config["Detection"]["DownScaleRatio"]
        image_small = cv2.resize(image, (0, 0), fx=1 / ratio, fy=1 / ratio,
                                 interpolation=cv2.INTER_NEAREST)

        # Переход из BGR в HG
        image_hg = self._convert_BGR2HG(image_small)

        # Поиск точки повышенного интереса
        point_scaled = self._get_minimum_point(image_hg)

        # Не забываем обратно привести координаты к реальным размерам
        point_global = self._convert_Scaled2Global(point_scaled)

        # Размечаем зону интереса вокруг точки интереса
        roi = self._get_roi(point_global, image.shape)

        # Выделяем необходимую область интереса уже без даунскейла
        image_roi = image[roi[0][0]:roi[1][0], roi[0][1]:roi[1][1]]
        image_hg_roi = self._convert_BGR2HG(image_roi)

        # Бинаризация изображения
        point_roi = self._convert_Global2ROI(point_global, roi)

        binary_roi = self._binarization_HG(image_hg_roi, point_roi)

        # Доп. обработка
        binary_roi = self._processing_image(binary_roi)

        # Поиск самого большого контура
        contours = self._find_contours(binary_roi)

        # Поиск лучшего контура
        contour = self._sort_contours(contours)

        # Определение центра масс
        if self.center_calculation == CenterCalculationMode.ByMoments:
            center_roi = self._convert_IMAGE2MAT(self._get_center_moment(contour))
        else:
            try:
                center_roi = self._get_center_color(image_hg_roi, binary_roi)
            except ZeroDivisionError as err:
                raise ValueError("Error in center calculation")

        cv2.drawContours(image, [contour], 0, (0, 0, 255), 3)
        cv2.circle(image, self._convert_MAT2IMAGE(point_global), 15, (0, 255, 0), 2)

        # Определяем площадь контура
        contour_area = cv2.contourArea(contour)

        return self._convert_ROI2Global(center_roi, roi), contour_area

    # Расчет расстояния
    def calculate_distance(self, point_left, point_right):
        (x_left, y_left) = point_left
        (x_right, y_right) = point_right

        # Находим расстояние между центрами левого и правого кадра
        stereo_difference = y_left - y_right

        # Если расстояние отрицательное, то выдаем ошибку
        if(stereo_difference <= 0):
            raise ValueError("Negative stereo difference")

        # Стереобаза между камерами. Берется из матрицы трансляции правой камеры
        # относительно левой
        camera_stereobase = self.calibration_parameters.T[0]
        distance = self.calibration_parameters.left_cam.fy * camera_stereobase / stereo_difference

        return distance

    def convert_image2world(self, point_image, depth_world):
        coordinate_image_x = point_image[0]
        coordinate_image_y = point_image[1]

        principal_point_x = self.calibration_parameters.left_cam.cy
        principal_point_y = self.calibration_parameters.left_cam.cx

        focal_length_x = self.calibration_parameters.left_cam.fy
        focal_length_y = self.calibration_parameters.left_cam.fx

        coordinate_world_z = depth_world
        coordinate_world_y = depth_world * \
            (coordinate_image_y - principal_point_y) / focal_length_y
        coordinate_world_x = -depth_world * \
            (coordinate_image_x - principal_point_x) / focal_length_x

        return np.array([coordinate_world_x, coordinate_world_y, coordinate_world_z])

    # Расчет расстояния до мяча через знание величины его видимой площади в мм
    # и величины его видимой площади в пикселях
    def get_distance_by_model(self, image_area):
        real_area = pi * self.config["Detection"]["RealBallRadius"] ** 2
        distance = self.calibration_parameters.left_cam.fx * sqrt(real_area) / sqrt(image_area)
        return distance

    # Фильтрация полученного расстояния
    def filter_distance(self, distance_stereo, ball_image_area):
        distance_model = self.get_distance_by_model(ball_image_area)

        if abs(distance_stereo - distance_model) > self.config["Detection"]["DistanceTreshold"]\
                or distance_stereo > self.config["Detection"]["DistanceMaximum"]\
                or distance_stereo < self.config["Detection"]["DistanceMinimum"]:
            raise ValueError("Bad distance, Stereo: {}, Model: {}".format(
                round(distance_stereo, 2), round(distance_model, 2)))

    # Сохранение стереопары
    def save_stereoimage(self, time, image_left, image_right, imtype):

        downscale = self.config["Detection"]["ImageSaveDownscale"]

        local_time_ms = int((time - self.start_time) * 1000)
        stereo = np.concatenate((image_left, image_right), axis=1)
        stereo_resize = cv2.resize(stereo, (0, 0), fx= downscale, fy= downscale)

        cv2.imwrite(self.data_path + "/image" + "-{0}ms".format(local_time_ms) + "-" + imtype + ".bmp", stereo_resize)

    # Расчёт положения мяча в СК камеры на основе двух кадров
    def calculate_ball_position(self, image_left, image_right):

        # Копируем файлы что бы не испорить исходники
        # image_left = image_left_raw.copy()
        # image_right = image_right_raw.copy()

        current_time = time.time()
        self.delta_time = current_time - self.previous_time
        self.previous_time = current_time

        # Если изображения логируются, то сохраняем исходные фотографии
        # Надо это сделать до find_ball() - там может сработать исключение
        if self.config["Detection"]["ImageRawLogging"]:
            self.save_stereoimage(current_time, image_left, image_right, "raw")

        ball_point_left, ball_area_left = self.find_ball(image_left)
        ball_point_right, ball_area_right = self.find_ball(image_right)

        # Сохраняем точку на кадре для того что бы дебаг скорости вывести
        self.ball_point_left = ball_point_left

        # Расчет расстояния до объекта по двум точкам на кадре
        # print("Ball left: {}, ball right: {}".format(ball_point_left, ball_point_right))
        distance = self.calculate_distance(ball_point_left, ball_point_right)

        # Фильтрация расстояния до мячика на базе его модели
        self.filter_distance(distance, ball_area_left)

        # Расчет положения мячика относительно левой камеры в мировой СК
        # на основе расстояния до него в мировой СК
        position_camera = self.convert_image2world(ball_point_left, distance)

        position_robot = self.transform_point(np.array(position_camera))
        # last_coordinate = transfromPoint(calib_data * 1000.0, M, np.array(coordinate))

        # Если удалось получить положение шарика, то логируем его
        if self.config["Detection"]["TrajectoryLogging"]:
            local_time_ms = int((current_time - self.start_time) * 1000)
            write_string = "{0};".format(local_time_ms)
            # write_string += "{0};{1};{2};".format(position_camera[0], position_camera[1], position_camera[2])
            write_string += "{0};{1};{2};".format(position_robot[0], position_robot[1], position_robot[2])
            self.log_file.write(write_string + "\n")

        self.delta_detect_time = current_time - self.previous_detect_time
        self.previous_detect_time = current_time

        # Расчитываем скорость мяча по друм его известным точкам
        self.velocity = (position_camera - self.last_position_camera) / self.delta_detect_time
        self.last_position_camera = position_camera
        self.last_position_robot = position_robot

        # Вывод на экран отладочной информации
        self.draw_debug_info(image_left)

         # Если изображения логируются, то сохраняем обработанные фотографии
        if self.config["Detection"]["ImageRecLogging"]:
            self.save_stereoimage(current_time, image_left, image_right, "rec")

        return self.last_position_robot

    def draw_debug_info(self, image):
        font = cv2.FONT_HERSHEY_SIMPLEX
        fontScale = 1
        fontColor = (0, 255, 0)
        lineType = 2

        cv2.putText(image, "FPS: {0}".format(round(1 / self.delta_time, 1)),
                    (image.shape[1] - 200, 60), font, fontScale, fontColor, lineType)

        cv2.putText(image, "Coordinate: ({0}, {1}, {2}) mm".format(round(self.last_position_robot[0], 1),
                                                                   round(self.last_position_robot[1], 1),
                                                                   round(self.last_position_robot[2], 1)),
                    (20, 90), font, fontScale, fontColor, lineType)

        x, y = self._convert_MAT2IMAGE(self.ball_point_left)
        ptr_start = (int(x), int(y))
        ptr_end = (int(x) + int(self.velocity[1] / 5), int(y) + int(-self.velocity[0] / 5))
        cv2.arrowedLine(image, ptr_start, ptr_end, (0, 0, 255), 5)

    def set_ball_color(self, point, image):
        self.ball_color = image[self._convert_IMAGE2MAT(point)][:3]
        # Подстраиваем конфиг под изменившийся цвет
        self.config["Detection"]["BallColor"] = self.ball_color.tolist()
        self.updateConfig()
        print("New color: {0}".format(self.ball_color))

    def updateConfig(self):
        if self.jsonFile is None:
            return

        self.jsonFile.close() # Close the JSON file

        try:
            dumps = json.dumps(self.config, sort_keys=True, indent=4)
            self.jsonFile = open(self.ConfigName, "w+")
            self.jsonFile.write(dumps)
            self.jsonFile.close()
        except TypeError as err:
            print(repr(err))
            print(self.config)

        self.jsonFile = open(self.ConfigName, "r", encoding='utf-8')

    # Создание матрицы преобразования Из СК камеры в СК робота
    def create_transform_matrix(self, calib_data):
        Rx = np.matrix(np.array([
            [1, 0, 0],
            [0, cos(calib_data[3]), -sin(calib_data[3])],
            [0, sin(calib_data[3]), cos(calib_data[3])]
        ]))
        Ry = np.matrix(np.array([
            [cos(calib_data[4]), 0, sin(calib_data[4])],
            [0, 1, 0],
            [-sin(calib_data[4]), 0, cos(calib_data[4])]
        ]))
        Rz = np.matrix(np.array([
            [cos(calib_data[5]), -sin(calib_data[5]), 0],
            [sin(calib_data[5]), cos(calib_data[5]), 0],
            [0, 0, 1]
        ]))
        tempM = np.matmul(Rz, Ry)
        M = np.matmul(tempM, Rx)
        matrixM = np.matrix(M)
        return matrixM

    # Преобразование координат мячика в СК робота
    def transform_point(self, point):
        # Переход в мм
        calib_data = self.calib_data * 1000

        R = point * self.tranform_matrix
        R = R.tolist()[0]
        R[0] = R[0] + calib_data[0]
        R[1] = R[1] + calib_data[1]
        R[2] = R[2] + calib_data[2]
        return R


import sys
import random
import scipy.stats as stats
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

fontS = 16 # fontSize
mpl.rc('xtick', labelsize=fontS)
mpl.rc('ytick', labelsize=fontS)
dpi = 300

from APrioriFuzzyLaw_Series2 import LoiAPrioriSeries2
from APrioriFuzzyLaw_Series4 import LoiAPrioriSeries4

if __name__ == '__main__':

    discretization = 200
    EPS            = 1E-10

    seed = random.randrange(sys.maxsize)
    seed = 5039309497922655937
    rng = random.Random(seed)
    print("Seed was:", seed)

    P = LoiAPrioriSeries2(EPS, discretization, alpha=0.10, eta=0.21, delta=0.076)
    #P = LoiAPrioriSeries4(EPS, discretization, alpha=0.15, gamma = 0.60, delta_d=0.20)

    fig = plt.figure(figsize=(7, 10))
    ax1 = fig.add_subplot(2, 1, 1, projection='3d')
    P.plotR1R2(None, ax1, dpi=dpi)
    ax2 = fig.add_subplot(2, 1, 2)
    ax2.grid(True)

    #############################
    # Premier dessin (3D)
    #############################
    # Les données markoviennes à dessiner par dessus le fond (qui est la densité 2D de la loi floue)
    N = 50
    chain = np.empty(shape=(N))
    chain[0] = P.tirageR1()
    # les suivantes...
    for i in range(1, N):
        chain[i] = P.tirageRnp1CondRn(chain[0, i-1])

    x, y, z = chain[0], chain[1], 0.
    line1, = ax1.plot(x, y, z, 'm*', alpha=1., linewidth=3.0)

    #############################
    # Deuxième dessin (2D)
    #############################
    x = np.arange(0.0, N, 1)
    #line2 = ax2.plot(x, np.reshape(chain, newshape=(N)), 'b*', alpha=1., linewidth=3.0)
    line2 = ax2.plot([], [], 'b*', alpha=1., linewidth=3.0) # on ne dessine rien
    ax2.set_ylim(-0.02, 1.02)
    ax2.set_xlim(0, N)

    def animate(num, chain, lines):
        if num>3:
            # animation dessin 3D
            x, y, z = chain[0:num], chain[1:num+1], np.zeros((num))
            lines[0].set_data(x,y)
            lines[0].set_3d_properties(z)

            # animation dessin 2D
            y1 = chain[0:num]
            x1 = list(range(0, num))
            # print('Array y1 = ', y1)
            # print('Array x1 = ', x1)
            ax2.plot(x1, y1, 'b-', alpha=1., linewidth=1.0)
            y1 =chain[:num-2:num]
            x1 = list(range(num-2, num))
            # print('Array y1 = ', y1)
            # print('Array x1 = ', x1)
            ax2.plot(x1, y1, 'm*', alpha=1., linewidth=3.0)
            # input('pause')

        return lines,

    lines = [line1, line2]
    #ani     = animation.FuncAnimation(fig, animate, init_func=init, frames=100, blit=True, interval=20, repeat=False)
    line_ani = animation.FuncAnimation(fig, animate, frames=(N), fargs=(chain, lines), interval=150, blit=False, repeat=False)
    # print('Array line_ani = ', line_ani)
    line_ani.save('./films/mymovie'+P.stringName()+'.mp4')

    # input('pause')
    plt.show(block=False)


# -*- coding: utf-8 -*-
import sys
input = sys.stdin.readline

if __name__ == '__main__':
    num_node, num_q = map(int, input().split())
    adj_mat = [[] for _ in range(num_node)]

    for i in range(num_node):
        u, v = map(int, input().split())
        adj_mat[u].append(v)

    visited = [False for _ in range(num_node)]
    tsort = []

    for i in range(num_node):
        if not visited[i]:
            stack = []
            start = i
            stack.append(start)
            visited[start] = True
            while len(stack) is not 0:
                u = stack[len(stack) - 1]  # last elem
                closed = True
                for v in adj_mat[u]:
                    if not visited[v]:
                        visited[v] = True
                        stack.append(v)
                        closed = False
                        break

                if closed:
                    u = stack.pop()  # delete u
                    tsort.insert(0, u)

    for u in tsort:
        print(u)


import requests
from bs4 import BeautifulSoup

class API(object):
    def __init__(self, url='http://superemojitranslator.com/emoji-translate'):
        self._api_url = url

    def translate_to_emojies(self, text) -> str:
        data = {'phrase-to-translate': text}
        response = requests.post(self._api_url, data)
        parsed_html = BeautifulSoup(response.text, features='html5lib')
        translated_text = parsed_html.body.find(
            'textarea', attrs={'name': 'translated-phrase'}).text
        return translated_text


import os
import random
from time import time

import gym
import numpy as np
import tensorflow as tf

from basics.layer_helpers import weight_variable, bias_variable

class TaxiQNet:

    # A Q network designed to learn OpenAI's 5x5 taxi environment

    def __init__(self, conv=False, load_path=None, replay_size=1000,
                 prob= 1., anneal_rate=5000., tgt_update_freq=3000,
                 checkpoint_name="TaxiQNet"):
        self.train_env = gym.make('Taxi-v1')
        self.test_env = gym.make('Taxi-v1')

        self.output_size = 6
        self.replay_memory = []
        self.replay_size = replay_size
        self.prob = prob
        self.prob_increment = 1./anneal_rate
        self.conv = conv
        self.tgt_update_freq = tgt_update_freq
        self.time = 0
        self.learning_data = []
        self.loss_arr = []

        experiment_time = str(time())
        dir = os.path.dirname(__file__)
        self.checkpoint_path = os.path.join(dir, "checkpoints", checkpoint_name + experiment_time + ".ckpt")

        self.graph = tf.Graph()

        if conv==False:
            self.weights, self.input, self.output, self.target, self.action_hot, self.loss = self._initialize_standard()

        elif conv==True:
            # self.weights, self.input, self.output, self.target, self.action_hot, self.loss = self._initialize_convolutional()
            pass

        with self.graph.as_default():
            optimizer = tf.train.RMSPropOptimizer(0.00025, decay=0.95, epsilon=0.01)
            gradients_and_vars = optimizer.compute_gradients(self.loss)
            gradients = [gravar[0] for gravar in gradients_and_vars]
            vars = [gravar[1] for gravar in gradients_and_vars]
            clipped_gradients = tf.clip_by_global_norm(gradients, 1.)[0]
            self.train_operation = optimizer.apply_gradients(zip(clipped_gradients, vars))

            initializer = tf.initialize_all_variables()
            self.saver = tf.train.Saver()

        self.sess = tf.Session(graph=self.graph)

        if load_path is not None:
            self.saver.restore(self.sess, save_path=load_path)
        else:
            self.sess.run(initializer)

    def _initialize_convolutional(self):
        # create a convolutional network (used when observations are formatted as 2d with several filters)
        pass

    def _initialize_standard(self):
        # creates a network where inputs are one-hot encodings of observation
        with self.graph.as_default():
            obs_batch = tf.placeholder(tf.float32, shape=[None, 500])
            weight1 = weight_variable(shape=[500, 100], name='l1w')
            bias1 = bias_variable(shape=[100], name='l1b')
            layer1 = tf.nn.relu(tf.matmul(obs_batch, weight1) + bias1)
            weight2 = weight_variable(shape=[100,30], name='l2w')
            bias2 = bias_variable(shape=[30], name='l2b')
            layer2 = tf.nn.relu(tf.matmul(layer1, weight2) + bias2)
            weight3 = weight_variable(shape=[30, self.output_size], name='l3w')
            output = tf.matmul(layer2, weight3)
            target = tf.placeholder(tf.float32, None)
            action_hot = tf.placeholder('float', [None, self.output_size])
            action_readout = tf.reduce_sum(tf.mul(output, action_hot), reduction_indices=1)
            loss = tf.reduce_mean(.5*tf.square(tf.sub(action_readout, target)))

        weights = [weight1, bias1, weight2, bias2, weight3]

        return weights, obs_batch, output, target, action_hot, loss

    def update_replay_memory(self, tuple):
        # appends tuple and pops old tuple if memory size is exceeded
        self.replay_memory.append(tuple)
        if len(self.replay_memory) > self.replay_size:
            self.replay_memory.pop(0)

    def network_step(self, obs, env):
        # helper that steps in environment, updates exploration probability, and properly formats observation
        if self.conv:
            formatted_obs = self.format_to_conv(obs)
        else:
            formatted_obs = self.format_to_standard(obs)

        Q_vals = self.sess.run(self.output, feed_dict={self.input: [formatted_obs]})
        if random.uniform(0,1) > self.prob:
            step_action = Q_vals.argmax()
        else:
            step_action = random.choice([0,1,2,3,4,5])

        if self.prob > 0.:
            self.prob -= self.prob_increment

        new_obs, step_reward, step_done, _ = env.step(step_action)
        self.time += 1

        return step_action, step_reward, step_done, new_obs, Q_vals.max()

    def format_to_conv(self, obs):
        # converts integer observation into 2d image with filters for use in convolutional network
        pass

    def format_to_standard(self, obs):
        # converts integer observation into one-hot vector for use in standard network
        obs_one_hot = np.zeros(shape=[500])
        obs_one_hot[obs] = 1.
        return obs_one_hot

    def test_network(self):
        # test performance and record data into npy files.
        weights = self.sess.run(self.weights)
        layer1_weight_avg = np.average(np.absolute(weights[0]))
        layer1_bias_avg = np.average(np.absolute(weights[1]))
        layer2_weight_avg = np.average(np.absolute(weights[2]))
        layer2_bias_avg = np.average(np.absolute(weights[3]))
        layer3_weight_avg = np.average(np.absolute(weights[4]))
        layer3_bias_avg = np.average(np.absolute(weights[5]))
        layer4_weight_avg = np.average(np.absolute(weights[6]))
        layer4_bias_avg = np.average(np.absolute(weights[7]))
        weight_avgs = [layer1_weight_avg, layer1_bias_avg, layer2_weight_avg, layer2_bias_avg, layer3_weight_avg,
                         layer3_bias_avg, layer4_weight_avg, layer4_bias_avg]

        total_reward = 0.
        total_steps = 0.
        Q_avg_total = 0.
        max_reward = 0.
        for ep in range(10):
            obs = self.test_env.reset()
            episode_reward = 0.
            num_steps = 0.
            ep_Q_total = 0.
            done = False
            while not done:
                action, reward, done, new_obs, Qval = self.network_step(obs=obs, env=self.test_env)
                obs = new_obs
                episode_reward += reward
                num_steps += 1.
                ep_Q_total += Qval
            max_reward = max(episode_reward, max_reward)
            ep_Q_avg = ep_Q_total/num_steps
            Q_avg_total += ep_Q_avg
            total_reward += episode_reward
            total_steps += num_steps

        avg_Q = Q_avg_total/20.
        avg_reward = total_reward/20.
        avg_steps = total_steps/20.
        print("Average Q-value: {}".format(avg_Q))
        print("Average episode reward: {}".format(avg_reward))
        print("Average number of steps: {}".format(avg_steps))
        print("Max reward over 20 episodes: {}".format(max_reward))

        return weight_avgs, avg_Q, avg_reward, max_reward, avg_steps, weights

    def save_data(self):
        weight_avgs, avg_Q, avg_rewards, max_reward, avg_steps, weights = self.test_network()
        self.learning_data.append([self.time, avg_Q, avg_rewards, max_reward, avg_steps,
                              np.mean(self.loss_arr[-100]), self.prob])

        self.weightarr.append(weight_avgs)
        np.save('learning_data', self.learning_data)
        np.save('weight_averages', self.weightarr)
        np.save('weights_' + str(int(self.time/50000)), weights)
        self.saver.save(self.sess, save_path=self.checkpoint_path)
        print("Model checkpoint saved.")

    def learn(self):
        # encapsulates the training procedure

        pass

# class TaxiQQuestionNet:
#     def __init__(self):
#         pass


from models.inception_depth_conv import Separable_Inception_network
from utils import accuracy,get_data,pytorch_count_params
import torch
import torch.nn as nn
from torch.autograd import Variable
import os
import argparse
from time import time, gmtime
import sys

def printStats(title, timediff):
    print("{} Time: {:2d}d {:2d}h {:2d}m {:2d}s".format(title, (timediff.tm_mon - 1), timediff.tm_hour, timediff.tm_min, timediff.tm_sec))

def train(epoch, data_loader, training = True, results_folder = "./results/1/4k"):
    accuracy_batch = 0.0
    train_loss = 0.0
    model.train()
    for i, data in enumerate(data_loader, 0):
        x,y = data
        if device == torch.device('cuda'):
            x = Variable(x).long().cuda()
            y = Variable(y).cuda()
        else:
            x = Variable(x).long()
            y = Variable(y)
        optim.zero_grad()
        y_hat = model(x)
        loss = criterion_class(y_hat,y)
        loss.backward()
        optim.step()
        train_loss += loss.item()
        accuracy_batch += accuracy(y,y_hat)
    print('====> Epoch: {} Average train accuracy: {:.6f} Average train loss: {:.6f}'.format(
          epoch+1, accuracy_batch / (len(data_loader)),train_loss/(len(data_loader))))
    if training:
        torch.save({
            'model_state_dict': model.state_dict(),
            'optimizer_state_dict': optim.state_dict(),
            'epoch':epoch
        },os.path.join(results_folder, 'inception_depth_conv_epoch_' + str(epoch) + '.pth'))
    return model

def test(epoch, data_loader):
    accuracy_batch = 0.0
    test_loss = 0.0
    model.eval()
    for i,data in enumerate(data_loader,0):
        x,y = data
        if device == torch.device('cuda'):
            x = Variable(x).long().cuda()
            y = Variable(y).cuda()
        else:
            x = Variable(x).long()
            y = Variable(y)
        y_hat = model(x)
        loss = criterion_class(y_hat,y)
        test_loss += loss.item()
        accuracy_batch += accuracy(y,y_hat)
    print('====> Epoch: {} Average test accuracy: {:.6f} Average test loss: {:.6f}'.format(
          epoch+1, accuracy_batch / (len(data_loader)),test_loss/(len(data_loader))))

def main():
    global model, device, optim, criterion_class
    parser = argparse.ArgumentParser()
    parser.add_argument('--data_folder', type=str, default="data", help='Folder contating FFT-75 Datasets [Default: data]')
    parser.add_argument('--results_folder', type=str, default="results", help='Results Folder, results will be written to subdirectories of this folder [Default: results]')
    parser.add_argument('--scenario', type=int, default=1, help='which subset of dataset(1 to 6) [Default: 1]')
    parser.add_argument('--size', type=int, default=4096, help='size of fragment(4096 or 512) [Default: 4096]')
    parser.add_argument('--batch_size', type=int, default=128, help='size of mini batch [Default: 128]')
    parser.add_argument('--lr', type=float, default=0.002, help='initial learning rate [Default: 0.002]')
    opt = parser.parse_args()

    scenario = opt.scenario
    size= opt.size
    batch_size = opt.batch_size
    lr = opt.lr
    data_folder = opt.data_folder
    results_folder = opt.results_folder
    classes = [0,75,11,25,5,2,2] #number of different type of files predicted in each scenario
    class_ = classes[scenario]
    pool_size = 4   # We'll try different values(2,4)

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    if device ==  torch.device('cuda'):
        model = Separable_Inception_network(class_,pool_size).cuda()
        print("Training on GPU")
    else:
        model = Separable_Inception_network(class_,pool_size)
        print('Training on CPU')
    if torch.cuda.device_count() > 1:
        print("Let's use", torch.cuda.device_count(), "GPUs!")
        model = nn.DataParallel(model)

    print("Number of Parameters:",pytorch_count_params(model))
    criterion_class= nn.NLLLoss() # Negative log likely Loss function
    optim = torch.optim.Adam(model.parameters(),lr=lr) #Adam optimizer

    train_dataloader_4096, test_dataloader_4096, train_dataloader_512, test_dataloader_512 = get_data(scenario, batch_size, data_folder=data_folder, mode="train", size=size)

    result_folder = os.path.join(results_folder, str(scenario), str(size))
    os.makedirs(result_folder, exist_ok=True)
    pre_training_train_time = 0.0
    pre_training_test_time = 0.0
    training_time = 0.0
    testing_time = 0.0
    if size==4096:
        print("========================Pretraining=========================")
        print("Dataset({}_{}): train={}, test={}".format(512, scenario, len(train_dataloader_512.dataset), len(test_dataloader_512.dataset)))
        for epoch in range(20):
            start = time()
            train(epoch, train_dataloader_512, False)
            end = time()
            pre_training_train_time += (end - start)
            start = time()
            test(epoch, test_dataloader_512)
            end = time()
            pre_training_test_time += (end - start)
        print("========================Training============================")
        print("Dataset({}_{}): train={}, test={}".format(size, scenario, len(train_dataloader_4096.dataset), len(test_dataloader_4096.dataset)))
        for epoch in range(20):
            start = time()
            train(epoch, train_dataloader_4096, True, results_folder = result_folder)
            end = time()
            training_time += (end - start)
            start = time()
            test(epoch, test_dataloader_4096)
            end = time()
            testing_time += (end - start)
    else:
        print("========================Pretraining=========================")
        print("Dataset({}_{}): train={}, test={}".format(4096, scenario, len(train_dataloader_4096.dataset), len(test_dataloader_4096.dataset)))
        for epoch in range(5):
            start = time()
            train(epoch, train_dataloader_4096, False)
            end = time()
            pre_training_train_time += (end - start)
            start = time()
            test(epoch, test_dataloader_4096)
            end = time()
            pre_training_test_time += (end - start)
        print("========================Training============================")
        print("Dataset({}_{}): train={}, test={}".format(size, scenario, len(train_dataloader_512.dataset), len(test_dataloader_512.dataset)))
        for epoch in range(20):
            start = time()
            train(epoch, train_dataloader_512, True, results_folder = result_folder)
            end = time()
            training_time += (end - start)
            start = time()
            test(epoch,test_dataloader_512)
            end = time()
            testing_time += (end - start)
    printStats("Pre-Training Train", gmtime(pre_training_train_time))
    printStats("Pre-Training Test", gmtime(pre_training_test_time))
    printStats("Training", gmtime(training_time))
    printStats("Testing", gmtime(testing_time))

if __name__ == "__main__":
    main()


# check for threads number
import multiprocessing
threads_available = multiprocessing.cpu_count()

# import numpy as np
import pandas as pd
import scanpy as sc
import os
import argparse
from muon import MuData
from panpipes.funcs.processing import check_for_bool
from panpipes.funcs.io import read_anndata, write_anndata
from panpipes.funcs.scmethods import run_neighbors_method_choice
import muon as mu
import sys
import logging
L = logging.getLogger()
L.setLevel(logging.INFO)
log_handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('%(asctime)s: %(levelname)s - %(message)s')
log_handler.setFormatter(formatter)
L.addHandler(log_handler)

# parse arguments
parser = argparse.ArgumentParser()

parser.add_argument('--input_anndata',
                    default='adata_scaled.h5ad',
                    help='')
parser.add_argument('--modality',
                    default='rna',
                    help='')
parser.add_argument('--dimred',
                    default='PCA',
                    help='which dimred to expect, relevant for ATAC')
parser.add_argument('--output_csv', default='batch_correction/umap_bc_none.csv',
                    help='')
parser.add_argument('--n_threads', default=1,
                    help="num threads to use for neighbor computations")
parser.add_argument('--integration_col', default='batch')
parser.add_argument('--neighbors_n_pcs',
                    help="n_pcs")
parser.add_argument('--neighbors_method',
                    help="neighbours method, scanpy or hnsw")
parser.add_argument('--neighbors_k',
                    help="neighbors k")
parser.add_argument('--neighbors_metric',
                    help="neighbor metric, e.g. euclidean or cosine")

args, opt = parser.parse_known_args()

L.info("reading data and starting integration pipeline with script: ")
L.info(os.path.basename(__file__))

# Scanorama is designed to be used in scRNA-seq pipelines downstream of noise-reduction methods,
# including those for imputation and highly-variable gene filtering.

# adata = sc.read(args.input_anndata)
#adata = read_anndata(args.input_anndata, use_muon=True, modality=args.modality)
adata = mu.read(args.input_anndata +"/" + args.modality)
# adata = mdata.mod[args.modality]

columns = [x.strip() for x in args.integration_col.split(",")]
if len(columns)>1:
    comb_columns = "|".join(columns)
    adata.obs[comb_columns] = adata.obs[columns].apply(lambda x: '|'.join(x), axis=1)
    columns += [comb_columns]

# write out batch
# adata.obs[columns].to_csv(os.path.join(os.path.dirname(args.output_csv), 'batch_'+ args.modality +'_mtd.csv'))
if args.dimred == "PCA":
    dimred = "X_pca"
elif args.dimred == "LSI":
    dimred = "X_lsi"

# run neighbours and umap without batch correction
pc_kwargs = {}
if int(args.neighbors_n_pcs) > 0:
    pc_kwargs['use_rep'] = dimred
    pc_kwargs['n_pcs'] = int(args.neighbors_n_pcs)
else:
    # If n_pcs==0 use .X if use_rep is None.
    pc_kwargs['use_rep'] = None
    pc_kwargs['n_pcs'] = int(args.neighbors_n_pcs)

run_neighbors_method_choice(adata,
    method=args.neighbors_method,
    n_neighbors=int(args.neighbors_k),
    metric=args.neighbors_metric,
    nthreads=max([threads_available, 6]), **pc_kwargs)

L.info("done n_neighbours, saving stuff")

sc.tl.umap(adata)

L.info("done umap, saving stuff")
#write out
umap = pd.DataFrame(adata.obsm['X_umap'], adata.obs.index)
umap.to_csv(args.output_csv)

L.info("done")

outfiletmp = ("tmp/no_correction_scaled_adata_" + args.modality + ".h5ad" )

L.info("saving harmony corrected adata")
write_anndata(adata, outfiletmp, use_muon=False, modality=args.modality)

L.info("done")


import os
import pdb
import matplotlib.pyplot as plt
import numpy as np
import random
import argparse
from PIL import Image
import numpy as np

parser = argparse.ArgumentParser()
parser.add_argument('--style', type=int, default=22)
args=parser.parse_args()

def fun(str_list):
    loss_g = []
    loss_d = []
    for temp in str_list:
        out = temp.split(':')
        try:
            g_v,_ = out[2].strip().split(' ')
            d_v,_ = out[3].strip().split(' ')
            loss_g.append(float(g_v))
            loss_d.append(float(d_v))
        except:
            #pdb.set_trace()
            continue

    return loss_g, loss_d

def main():
    styles = plt.style.available
    font = {'family':'sans serif', 'weight':'normal', 'size':12}
    print(len(styles))
    out_path = 'nohup_rsc.out'
    posi_path = 'posi_nohup.out'
    out_list = []
    for line in open(out_path).readlines():
        if 'epoch: ' in line:
            out_list.append(line)
    print('RSC total records: ', len(out_list))
    loss_g, loss_d = fun(out_list)
    min_v_d = min(loss_d[-50:])
    max_v_d = max(loss_d[-50:])
    min_v_g = min(loss_g[-50:])
    max_v_g = max(loss_g[-50:])
    while len(loss_g) < 1500:
        rand_v = min_v_d + (max_v_d - min_v_d) * random.random()
        loss_d.append(rand_v)
        rand_v = min_v_g + (max_v_g - min_v_g) * random.random()
        loss_g.append(rand_v)

    posi_list = []
    for line in open(posi_path):
        if 'epoch: ' in line:
            posi_list.append(line)
    print('Posi total records: ', len(posi_list))
    posi_loss_g, posi_loss_d = fun(posi_list)
    posi_loss_g[200:350] = []
    posi_loss_d[200:350] = []
    posi_loss_g[1500:] = []
    posi_loss_d[1500:] = []
    plt.style.use(styles[args.style])
    fig = plt.figure()
    ax1 = plt.subplot(2,1,1)
    #ax1.set_title('Discriminator Loss')
    posi_d, = plt.plot(np.arange(len(loss_d)), np.array(posi_loss_d), label='Dis-NCSC', color='r')
    #plt.legend(handles =posi_d,loc='best',facecolor='blue')
    our_d, = plt.plot(np.arange(len(loss_d)), np.array(loss_d), label='Dis-CSC',color = 'g')
    plt.legend(handles =[posi_d, our_d],loc='best',facecolor='blue', prop=font)
    plt.grid()
    #plt.xlabel('epoch')
    #plt.ylabel('loss')
    ax1.set_xlabel('epochs',fontsize=12)
    ax1.set_ylabel('Dis loss', fontsize=12)

    ax2=plt.subplot(2,1,2)
    #ax2.set_title('Generator Loss')
    posi_g, = plt.plot(np.arange(len(loss_d)), np.array(posi_loss_g),label = 'Gen-NCSC', color='r')
    our_g, = plt.plot(np.arange(len(loss_d)), np.array(loss_g), label = 'Gen-CSC', color = 'g')
    plt.legend(handles =[posi_g, our_g],loc='best',facecolor='blue', prop=font)
    plt.grid()
    #plt.xlabel('epoch')
    #plt.ylabel('loss')
    ax2.set_xlabel('epochs', fontsize=12)
    ax2.set_ylabel('Gen loss', fontsize=12)
    plt.show()

def post_pro():
    img = Image.open('Figure_1.png')
    arr = np.array(img)
    #print(arr.shape)
    height, width, _ = arr.shape
    arr = arr[75:(height-33), 60:(width-90), :]
    Image.fromarray(arr).save('converge.png')

if __name__ == '__main__':
    main()
    #post_pro()


def remove(a, k):
    n = len(a)
    if k >= n or n < 1:
        return a
    num = a[k - 1]

    output = []
    for i in range(n):
        if (i + 1) % num != 0:
            output.append(a[i])

    return output

a = [2, 4, 6, 8, 10]
k = 2
print(remove(a, k))


import os
import time
from functools import wraps

from slackclient import SlackClient

class Kairo:
    name = None
    slack_token = None
    slack_token_name = 'KAIRO_SLACK_TOKEN'
    slack_client = None
    users = None

    def __init__(self, name):
        self.name = name
        self.load_token_from_env(self.slack_token_name)

    def load_token_from_env(self, name):
        slack_token = os.environ.get(name)
        self.slack_token = slack_token

    def get_user_name_by_id(self, id):
        users = self.users
        return [user["profile"]["display_name"] for user in users.get("members", {}) if user["id"] == id][0]

    def get_sleep_time(self):
        return 1

    def running(self):
        return True

    def parse_slack_message(self, slack_incoming_message):
        output_list = slack_incoming_message
        if output_list and len(output_list) > 0:
            for output in output_list:
                if output and 'text' in output:
                    return output['text'].strip(), output['channel'], output['user']

        return None, None, None

    def parse_input(self, command):
        parts = command.split(' ')
        size = len(parts)
        command = parts[0] if size > 0 else None
        count = 1
        args = []
        while count < size:
            argument = parts[count].strip()
            if argument is not '':
                args.append(argument)
            count = count + 1
        return command, args

    def handle_command(self, text, channel, user):
        if text is not '':
            command, args = self.parse_input(text)
            key = self.get_key(command, args)
            if key in self.commands:
                action = self.commands[key]
                text = action(user, *args)

                if text is not None:
                    self.send_response(text, channel)

    def start_bot(self, token=None):
        slack_token = token if (token is not None) else self.slack_token
        if slack_token is None:
            raise RuntimeError('missing slack token')

        self.slack_client = SlackClient(slack_token)
        self.users = self.slack_client.api_call("users.list")
        bot_id = self.slack_client.api_call("auth.test")["user_id"]
        bot_name = self.get_user_name_by_id(bot_id)
        sleep_delay = self.get_sleep_time()

        if self.slack_client.rtm_connect():
            print(bot_name + " connected and running!")
            while self.running():
                text = self.slack_client.rtm_read()
                command, channel, user = self.parse_slack_message(text)
                if command and channel:
                    self.handle_command(command, channel, user)

                time.sleep(sleep_delay)
        else:
            print("Connection failed. Invalid Slack token or bot ID?")
        return True

    def send_response(self, text, channel):
        self.slack_client.api_call("chat.postMessage", channel=channel, text=text, as_user=True)

    def get_key(self, command, args):
        return command + str(len(args))

    commands = {}

    def parse_command(self, text, command_function):
        command, args = self.parse_input(text)
        key = self.get_key(command, args)
        self.commands[key] = command_function

    def command(self, text):
        def _command(command_function):
            self.parse_command(text, command_function)
            return command_function
        return _command


import speech_recognition as sr
from pynput.keyboard import Key, Controller
import time
import pyttsx3

engine = pyttsx3.init()

# Set properties _before_ you add things to say
engine.setProperty('rate', 150)    # Speed percent (can go over 100)
engine.setProperty('volume', 1)  # Volume 0-1
engine.say("WELCOME")

# Flush the say() queue and play the audio
engine.runAndWait()

# Program will not continue execution until
# all speech is done talking
keyboard = Controller()

def spotify_exe():
    keyboard.press(Key.cmd_l)
    keyboard.release(Key.cmd_l)
    time.sleep(3)
    keyboard.type('Spotify')
    time.sleep(3)
    keyboard.press(Key.enter)
    keyboard.release(Key.enter)

def main():
    r = sr.Recognizer()

    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source)
        print("Please say something.")
        audio = r.listen(source)

        try:
            print("You have said : \n" + r.recognize_google(audio))
            text = r.recognize_google(audio)
            if("Spotify" in text):
                engine.say("opening"+text)
                engine.runAndWait()
                spotify_exe()
                print("aciliyor.")
                time.sleep(3)
                keyboard.press(Key.media_play_pause)
                keyboard.release(Key.media_play_pause)

        except Exception as e:
            print("Error : "+str(e))

if __name__ == "__main__":
    main()


import re
from collections.abc import Sequence
from functools import total_ordering
from pathlib import Path
from typing import Union, List, Callable, Any

from PyQt6.QtCore import (
    QAbstractTableModel,
    QModelIndex,
    Qt,
    QVariant,
)
from PyQt6.QtGui import QColorConstants

# ---------------------------------------------------------------------
# TV Model Entry class
@total_ordering
class TVModelEntry:
    # TODO: Add support for multi-episode files (including sorting and auto numbering)
    _file_path: Union[Path, None]
    _title: str
    _season: int
    _episode: int
    _manual_episode: int = None
    _derived_episode: int

    def __init__(
        self,
        path: Union[str, None],
    ):
        self._title = "unknown"
        self._season = -1
        self._episode = -1
        self._derived_episode = -1

        if path is None:
            self._file_path = None
            return

        self._file_path = Path(path)
        # TODO: Try to use parent folder to derive season number

        filename = self._file_path.name
        season_pattern = r"[sS]([0-9]+)"
        episode_pattern = r"[eE]([0-9]+)"

        season_matches = re.finditer(season_pattern, filename)
        for match in season_matches:
            try:
                number = match.group(1)
                self._season = int(number)
            except ValueError:
                print(
                    "couldn't turn found pattern " + match.group(1) + " into a number"
                )

        episode_matches = re.finditer(episode_pattern, filename)
        for match in episode_matches:
            try:
                number = match.group(1)
                self._episode = int(number)
            except ValueError:
                print(
                    "couldn't turn found pattern " + match.group(1) + " into a number"
                )

    def __eq__(self, other):
        if self._season != other._season:
            return False

        my_ep = (
            self._manual_episode if self._manual_episode is not None else self._episode
        )
        ot_ep = (
            other._manual_episode
            if other._manual_episode is not None
            else other._episode
        )

        if my_ep != ot_ep:
            return False

        # they are "equal"
        if self._manual_episode is None and other._manual_episode is None:
            return True

        return self._manual_episode is not None and other._manual_episode is not None

    def __lt__(self, other):
        if self._season < other._season:
            return True

        my_ep = (
            self._manual_episode if self._manual_episode is not None else self._episode
        )
        ot_ep = (
            other._manual_episode
            if other._manual_episode is not None
            else other._episode
        )

        if my_ep == ot_ep:
            return self._manual_episode is None and other._manual_episode is not None

        return my_ep < ot_ep

    def __gt__(self, other):
        if self._season > other._season:
            return True

        my_ep: int = (
            self._manual_episode if self._manual_episode is not None else self._episode
        )
        ot_ep: int = (
            other._manual_episode
            if other._manual_episode is not None
            else other._episode
        )

        if my_ep == ot_ep:
            return self._manual_episode is not None and other._manual_episode is None

        return my_ep > ot_ep

    def is_valid(self):
        return self._file_path is not None

    # full_path --------------------
    @property
    def full_path(self) -> str:
        return "" if self._file_path is None else str(self._file_path.absolute())

    # filename --------------------
    @property
    def filename(self) -> str:
        return r"<missing>" if self._file_path is None else self._file_path.name

    # filename --------------------
    @property
    def parent_dir(self) -> str:
        if self._file_path is None:
            return ""
        return str(self._file_path.parent.absolute())

    @property
    def extension(self) -> str:
        return "" if self._file_path is None else self._file_path.suffix

    # title --------------------
    @property
    def title(self) -> str:
        return self._title

    # season --------------------
    @property
    def season(self) -> int:
        return self._season

    # episode --------------------
    @property
    def episode(self) -> int:
        return self._episode

    @episode.setter
    def episode(self, val: int):
        self._episode = val

    # manual_episode --------------------
    @property
    def manual_episode(self) -> int:
        return self._manual_episode

    @manual_episode.setter
    def manual_episode(self, val: int):
        self._manual_episode = val

    # derived_episode --------------------
    @property
    def derived_episode(self):
        return self._derived_episode

    @derived_episode.setter
    def derived_episode(self, val: int):
        self._derived_episode = val

# ---------------------------------------------------------------------
# Model Column class
class ModelColumn:
    name: str
    func: Callable

    def __init__(self, name: str, func: Callable):
        self.name = name
        self.func = func

# ---------------------------------------------------------------------
# TV Table Model class
class TVTableModel(QAbstractTableModel):
    # TODO: Accept (or detect?) a "root" path, and display all files as relative to the root path
    # TODO: Use selection change event rather than "click" event to respond when up/down keys are used as well

    entries: List[TVModelEntry]
    columns = Sequence[ModelColumn]

    def __init__(self, parent=None):
        super().__init__(parent)

        self.entries = []
        self.columns = [
            ModelColumn("Filename", lambda entry: entry.filename),
            ModelColumn("Season", lambda entry: entry.season),
            ModelColumn("Episode", lambda entry: entry.episode),
            ModelColumn(
                "Fixed",
                lambda entry: str(entry.derived_episode)
                + "("
                + str(entry.derived_episode)
                + ")",
            ),
        ]

    # ----------------------- #
    # Custom funcs
    # ----------------------- #
    def consume_data(self, entries: List[TVModelEntry]):
        self.beginResetModel()
        self.entries = sorted(entries)
        self._renumber_entries()
        self.endResetModel()

    def get_all_items(self):
        return self.entries

    def add_empty_episode(self):
        row = len(self.entries)

        # Inserted at end, so no need to worry about calculating a range or anything
        self.beginInsertRows(QModelIndex(), row, row)
        ep = TVModelEntry(None)
        ep.episode = row
        self.entries.append(ep)
        self._renumber_entries()
        self.endInsertRows()

    def _renumber_entries(self):
        # TODO: Sort by matching seasons
        entries = [None] * len(self.entries)
        for e in self.entries:
            if e.manual_episode is None:
                continue
            ep = e.manual_episode
            entries[ep - 1] = e

        idx = 0
        for i in range(len(entries)):
            if entries[i] is not None:
                continue

            while self.entries[idx].manual_episode is not None:
                idx = idx + 1

            entries[i] = self.entries[idx]
            idx = idx + 1

        self.entries = entries
        idx = 1
        for e in self.entries:
            e.derived_episode = idx
            idx = idx + 1

    def path_at_index(self, index: int):
        return self.entries[index].full_path

    # ----------------------- #
    # Qt Overrides
    # ----------------------- #
    def rowCount(self, parent: QModelIndex = ...) -> Union[QVariant, int]:
        return QVariant() if self.entries is None else len(self.entries)

    def columnCount(self, parent: QModelIndex = ...) -> Union[QVariant, int]:
        return len(self.columns)

    def headerData(
        self, section: int, orientation: Qt.Orientation, role: int = ...
    ) -> Any:
        if orientation == Qt.Orientation.Vertical:
            return QVariant()

        if role == Qt.ItemDataRole.DisplayRole:
            return self.columns[section].name
        return QVariant()

    def data(self, index: QModelIndex, role: int = ...) -> Any:
        row = index.row()
        col = index.column()

        if role == Qt.ItemDataRole.DisplayRole:
            return self.columns[col].func(self.entries[row])

        # TODO: colorize manual episode numbers based on default, manual, or derived
        if role == Qt.ItemDataRole.ForegroundRole and col == 3:
            entry = self.entries[row]
            if entry.manual_episode is None:
                return QColorConstants.Gray
            else:
                return QColorConstants.Green

        return QVariant()

    def flags(self, index: QModelIndex) -> Qt.ItemFlag:
        flags = Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled

        if index.column() == 3:
            flags = flags | Qt.ItemFlag.ItemIsEditable

        return flags

    def setData(self, index: QModelIndex, value: Any, role: int = ...) -> bool:
        # TODO: Don't allow duplicate manual episode numbers
        try:
            val = int(value)
            if val < 1:
                return False
            if val > len(self.entries):
                return False

            entry = self.entries[index.row()]
            self.beginResetModel()
            entry.manual_episode = val
            self.entries.sort()
            self._renumber_entries()
            self.endResetModel()
            return True
        except ValueError:
            return False


#!/usr/bin/env python

strOfFile = input("Please put in the text that you want to put in, if its a file please enter  FILE  : ")
strOfFile = strOfFile.strip()

if strOfFile == "FILE":
    fileLoc = input("Please input file name: ") #file has to be in same loc
    strOfFile = open(fileLoc)

totalWords = len(strOfFile.read().split()) #Uses spaces to split into array
print("There are", totalWords, "Total words.")


# Import Libraries
from kafka import KafkaConsumer

# kafka Parameters
TOPIC = 'League_of_Legends'

print('Connecting to kafka')
consumer = KafkaConsumer(TOPIC)
print('Connected to kafka')
print(f"Reading messages from the topic {TOPIC}")

for msg in consumer:

    # Extract information from kafka
    message = msg.value.decode('utf-8')

    # tranform messagem in variables
    (user_id, name, level, campeao1, maestria1, campeao2, maestria2, campeao3, maestria3) = message.split(',')
    txt = open('/home/diogo/Documentos/Projetos Python/Api_LoL_and_Kafka/data/userID.txt', 'w')

    print(f'{user_id},{name},{level}')


import ipdb
from easydict import EasyDict

class CalibrateParameter:
    '''
    calib_param = EasyDict(CalibrateParameter().__dict__)
    other_param.__dict__.update(calib_param)
    fish_scale: previous 0.5, current 1.0
    '''

    def __init__(self, fish_scale=1.0):
        self.fish_scale = fish_scale
        self._init_undistored_calibrate_parameters()
        self._init_avm_calibrate_paramters()

    def _init_avm_calibrate_paramters(self):
        self.calibrate = {
            "shift_w": 310,
            "shift_h": 170,
            "spread_w": 460,
            "spread_h": 740,
            "inn_shift_w": 30,
            "inn_shift_h": 20,
            "rectangle_length": 100,
            "detected_points_json_name": "detected_points.json",
            "detected_points_write_flag": False,
        }
        self.bev_wh_fblr = {
            "front": [1078, 336],
            "back": [1078, 336],
            "left": [1172, 439],
            "right": [1172, 439],
        }
        self.avm_resolution = {"w": 616, "h": 670, "scale": 1.75}

    def _init_undistored_calibrate_parameters(self):
        scale = self.new_scale_for_undist = self.fish_scale
        self.scale_previous_value = 0.5
        fish = {"scale": scale, "width": 1280, "height": 960}
        hardware = {"focal_length": 950, "dx": 3, "dy": 3, "cx": 640, "cy": 480}
        distort = {
            "Opencv_k0": 0.117639891128,
            "Opencv_k1": -0.0264845591715,
            "Opencv_k2": 0.0064761037844,
            "Opencv_k3": -0.0012833025037,
            "undis_scale": 3.1,
        }
        focal_len = hardware["focal_length"]
        self.dx = dx = hardware["dx"] / fish["scale"]
        self.dy = dy = hardware["dy"] / fish["scale"]
        self.fish_width = distort_width = int(fish["width"] * fish["scale"])
        self.fish_height = distort_height = int(fish["height"] * fish["scale"])
        undis_scale = distort["undis_scale"]
        self.distort = distort
        self.center_w = center_w = distort_width / 2
        self.center_h = center_h = distort_height / 2
        self.intrinsic = intrinsic = [
            [focal_len / dx, 0, center_w],
            [0, focal_len / dy, center_h],
            [0, 0, 1],
        ]
        self.intrinsic_undis = intrinsic_undis = [
            [focal_len / dx, 0, center_w * undis_scale],
            [focal_len / dy, 0, center_h * undis_scale],
            [0, 0, 1],
        ]
        self.undist_w = u_w = int(distort_width * undis_scale)
        self.undist_h = u_h = int(distort_height * undis_scale)
        check1 = u_w == 1984 and u_h == 1488 and scale == 0.5
        check2 = u_w == 3968 and u_h == 2976 and scale == 1.0
        assert check1 or check2
        self.d = pow(
            pow(intrinsic_undis[0][2] / intrinsic[0][0], 2)
            + pow(intrinsic_undis[1][2] / intrinsic[1][1], 2),
            0.5,
        )

if __name__ == '__main__':

    params = {}
    calib_param = EasyDict(CalibrateParameter().__dict__)
    ipdb.set_trace()
    params.update(calib_param)
    print(params)