import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import pandas as pd
import emcee
import corner

# Funzione che approssima andameto dati csv
def func(p, E):
    m, b, alpha, mu, sigma = p
    return ((m*E)+b+(alpha*np.exp(-((E-mu)**2)/(2*sigma**2) ) ))

# Probabilità logaritmiche
def lnlike_fl(p, energy, flow, ferr):
    return -0.5 * np.sum(((flow - func(p, energy))/ferr) ** 2)

def lnprior_fl(p):
    m, b, alpha, mu, sigma = p
    if ( -1 < m < 0 and  5 < b < 15 and  -10 < alpha < 0 and  0 < mu < 10
         and  0 < sigma < 3):
        return 0.0
    return -np.inf

def lnprob_fl(p, energy, flow, ferr):
    lp = lnprior_fl(p)
    if np.isfinite(lp):
        return lp + lnlike_fl(p, energy, flow, ferr)
    return -np.inf

# Funzioni di proposta e valutazione passi del metodo Metropolis-Hastings
def mhprop(nparams):
    return np.random.uniform(-0.01, 0.01, size=nparams)

def mheval(pnow, pnext, fpb, data):
    energy, flow, ferr = data
    fpbnow = fpb(pnow, energy, flow, ferr)
    fpbnext = fpb(pnext, energy, flow, ferr)
    if fpbnext >= fpbnow:
        return fpbnext
    else:
        if np.random.random() < fpbnext/fpbnow : #np.exp(fpbnext-fpbnow)
            return pnext
        else:
            return pnow

### Tab
#tab = pd.read_csv('/home/lm010009/Scrivania/get-mcf-data/get_data.py/absorption_line.csv')
tab = pd.read_csv('absorption_line.csv')
print(tab)

energy = tab['E'].values
flow = tab['f'].values
ferr = tab['ferr'].values

### Manual mcmc
p0 = np.array([-1, 1, -1.0, 3, 0.1])
nparams  = len(p0)
#########################################################problemi
mychain = np.empty((3000,len(p0)))
#mychain = np.array([p0])
mychain = np.append(mychain, [p0], axis=0)
#print(mychain, mychain.shape)
for i in range(3000):
    proppos = mychain[-1]+mhprop(nparams)
    newpos = mheval(mychain[-1], proppos, lnprob_fl, (energy, flow, ferr))
    print(type(newpos), '\n', newpos)
    mychain = np.append(mychain, [newpos] , axis=0)

print('mychain:', mychain)
mychain = mychain.reshape(3001, 5)
print('mychainreshape:', mychain)

### Grafico walker per i parametri liberi
labels = ['m', 'b', r'$\alpha$', r'$\mu$', r'$\sigma$' ]

fig, axes = plt.subplots(nparams, figsize=(10, 9), sharex=True)
for i in range(nparams):
    axes[i].plot(mychain[:, i], color='darkred', alpha=0.3)
    axes[i].set_xlim(0, len(mychain))
    axes[i].set_ylabel(labels[i])
    #axes[i].yaxis.set_label_coords(-0.1, 0.5)

axes[-1].set_xlabel('numero passi')
plt.savefig('SamplerParamsMH.png')
plt.show()

### Confronto
# Grafico dati con alcuni campionamenti dei paramtri
plt.errorbar(energy, flow, yerr=ferr, fmt='o-', color='black', label='dati')
plt.xlabel('Energia')
plt.ylabel('Flusso')
# Ultimi 500 passi
select_chain = mychain[-500:-1]
print(mychain.shape, '\n', selecte_chain.shape)
# Grafico 50 campionamenti distribuzione a posteriori
en = np.arange(1, 10, 0.02)
for s in np.random.randint(len(select_chain), size=50):
    plt.plot(en, func(select_chain[s], en), color="green", alpha=0.3)
plt.legend()
plt.savefig('ConfrontoMH.png')
plt.show()

### Corner plot
struth = (-0.2, 10, -5, 4.8, 0.6)
fig = corner.corner( select_chain, labels=labels, truths=struth, show_titles=True, color='green')
plt.savefig('CornerMH.png')
plt.show()


class Solution:
    def letterCasePermutation(self, s: str) -> List[str]:
        letter_indices, permutations = [], []
        for i in range(len(s)):
            if ord('a') <= ord(s[i].lower()) <= ord('z'):
                letter_indices.append(i)
        permutation_count = 2 ** len(letter_indices)
        bit_mask = 0
        for _ in range(permutation_count):
            new_string = list(s)
            for index, letter_index in enumerate(letter_indices):
                new_string[letter_index] = s[letter_index].lower() if bit_mask & (1 << index) else s[letter_index].upper()
            permutations.append(''.join(new_string))
            bit_mask += 1
        return permutations


@classmethod
def buy(cls, user, item_id):
    product_qs = Product.objects.filter(item_id=item_id)
    if product_qs.exists():
        product = product_qs[0]
    if product.available:
        # списание средств со счета пользователя
        user.withdraw(product.price)
        # информация о купленном товаре
        send_email_to_user_of_buy_product(user)
        product.available = False
        product.buyer = user
        product.save()
        return True
    else:
        return False

# Проблемы (отсортированы не по важности)
# 1) Нет смысла применять метод filter, если желаемого объекта нет - нужно выходить из метода
# 2) Проверку на available можно было бы перевернуть, не делая индентацию для почти всего кода метода
# 3) Код, начинающийся с if product.available должен быть в первом if, т.к. exists может вернуть False,
# и это тоже можно было бы перевернуть, сделав обратную проверку
# 4) А вообще если available = False, то выходить из метода
# 5) Списание и назначение продукту юзера должны быть атомарной операцией
# 6) Отправка письма на почту должна быть после того, как транзакция успешно завершилась, и вообще не в этом методе
# (следуем single responsibility)
# 7) Возврат булевого значения методом с названием buy нарушает command-query separation
# 8) Булевое значение мало о чем говорит - неясна причина, почему не удалось произвести покупку


"""
Created on 13.10.2023
"""

import re

def print_match_for_regex(pattern: str, string_list: list[str]):
    for string in string_list:
        match = re.findall(pattern, string)
        if match:
            print(f"Match for '{string}'.")

"""
Reasonable url
"""

pattern = r"w{3}\.[a-zA-Z0-9]+\.[a-zA-Z0-9]{2,}"
string = 'www.google.com'  # match
string2 = 'ww.google.com'
string3 = 'www.google.c'
string4 = 'www..com'
string5 = 'www.a.com'  # match

print_match_for_regex(pattern, [string, string2, string3, string4, string5])


import re
from inspect import getmembers
from pprint import pprint
import sys

class Object(object):
    pass

roDataName = ".rodata"
textName = ".text"
totalSize = 0
def ReadMapFile(filepath, symFilter):

  mapFile = open(mapFilePath, "r")
  foundLinkerSection = False
  lastSymbol = 0

  libs = {roDataName:{}, textName:{}}

  posText = 0
  posRoData = 0

  for line in mapFile:
    #print(line)
    if foundLinkerSection == False:
      pos = line.find("Linker script and memory map")
      if pos != -1:
        #print("Found linker section")
        foundLinkerSection = True

    if foundLinkerSection:

      if lastSymbol == 0:

        posText = line.find(textName)
        posRoData = line.find(roDataName)

        if posText != -1 or posRoData != -1:
          lastSymbol = line

      pos = line.find(".o")
      if pos != -1 and lastSymbol != 0:

        symName = lastSymbol

        lastSymbol = 0
        m = re.search('\s*([\.a-zA-Z0-9_]*)\s*(0x[0-9xa-fA-F]+)\s*(0x[0-9xa-fA-F]+)\s*(.*)', line)

        if len(m.group(1)) != 0:
          symName = m.group(1)

        #print(symName)
        #print(line)
        #pprint(m.groups())
        #break
        #print(line)
        #print(m.group(2))
        address = int(m.group(2), 16)
        size = int(m.group(3), 16)
        if address >= 0x20000000:
          continue

        if symFilter != None and symName.find(symFilter) == -1:
          continue

        libName = m.group(4)

        lastSlash = libName.rfind("/")
        if lastSlash != -1:
          libName = libName[lastSlash:]

        memType = roDataName
        if posText != -1:
          memType = textName

        if libs[memType].get(libName) == None:
          newLib = Object()
          newLib.size = 0
          newLib.minAddress = 0xffffffff
          newLib.maxAddress = 0
          newLib.fill = 0
          newLib.symbols = []
          libs[memType][libName] = newLib

        lib = libs[memType][libName]
        lib.minAddress = min(lib.minAddress, address)
        lib.maxAddress = max(lib.maxAddress, address + size)
        lib.size += size

        symName = symName.strip()
        memTypeLen = len(memType)
        symName = symName[memTypeLen:]
        if len(symName) > 0 and symName[0] == '.':
          symName = symName[1:]

        symbol = Object()
        symbol.name = symName
        symbol.size = size

        lib.symbols.append(symbol)

  return libs

def PrintSection(name, section):
  global totalSize

  print("*********************")
  print("{0}".format(name))
  print("*********************")

  sorted_keys = sorted(section.keys())

  for libName in sorted_keys:
    lib = section[libName]
    totalSize += lib.size

    text = "{0:8} {1}".format(lib.size, libName)
    print(text)

    sortedSymbols = sorted(lib.symbols, key=lambda sym: sym.name)
    for symbol in sortedSymbols:
      print("         {1:8} {0}".format(symbol.name, symbol.size))

  #text = "Section info: MinAdr = 0x{0:08x} MaxAdr = 0x{1:08x}".format(minAddress, maxAddress)
  #print(text)

argv = sys.argv

mapFilePath = argv[1]
symFilter = None

for i in range(2, len(argv)):
  v = argv[i]
  testString = "/symfilter:"
  if v.find(testString) != -1:
    symFilter = v[len(testString):]
    print("Symfilter:{0}".format(symFilter))

libs = ReadMapFile(mapFilePath, symFilter)

PrintSection(roDataName, libs[roDataName])
PrintSection(textName, libs[textName])

#pprint(libs)
print("Total size {0}".format(totalSize))


import socket   #importa a biblioteca socket
import time     #importa a biblioteca time
import sys      #importa a biblioteca sys

UDP_IP = "127.0.0.1"                #define qual o host UDP
UDP_PORT = 5005                     #define qual a porta UDP
buf = 1024                          #define a quantidade de bytes a serem enviados
file_name = sys.argv[1]             #especifica o arquivo

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #starta o socket em pacotes UDP
sock.sendto(file_name, (UDP_IP, UDP_PORT))              #faz o envio de um nome de arquivo em pacotes UDP
print ("Sending %s ..." % file_name)                    #mostra que esta enviando
f = open(file_name, "r")                                #abre um arquivo no para de leitura
data = f.read(buf)                                      #vai ler o arquivo que foi aberto no tamanho de buf
while(data):                                            #inicia um loop
    if(sock.sendto(data, (UDP_IP, UDP_PORT))):          #cria a condição que ve o envio do conteúdo do arquivo em pacotes UDP
        data = f.read(buf)                              #vai ler o arquivo que foi aberto no tamanho de buf
        time.sleep(0.02)                                #define um tempo de delay

sock.close()                                            #vai mandar a socket fechar
f.close()                                               #fecha o arquivo


# encoding: utf-8
# module osgeo._gdalconst
# from /usr/lib/python2.7/dist-packages/osgeo/_gdalconst.x86_64-linux-gnu.so
# by generator 1.138
# no doc
# no imports

# Variables with simple values

CE_Debug = 1
CE_Failure = 3
CE_Fatal = 4
CE_None = 0
CE_Warning = 2

CPLES_BackslashQuotable = 0
CPLES_CSV = 4
CPLES_SQL = 3
CPLES_URL = 2
CPLES_XML = 1

CPLE_AppDefined = 1
CPLE_AssertionFailed = 7
CPLE_FileIO = 3
CPLE_IllegalArg = 5
CPLE_None = 0
CPLE_NotSupported = 6
CPLE_NoWriteAccess = 8
CPLE_OpenFailed = 4
CPLE_OutOfMemory = 2
CPLE_UserInterrupt = 9

CXT_Attribute = 2
CXT_Comment = 3
CXT_Element = 0
CXT_Literal = 4
CXT_Text = 1

DCAP_CREATE = 'DCAP_CREATE'
DCAP_CREATECOPY = 'DCAP_CREATECOPY'
DCAP_VIRTUALIO = 'DCAP_VIRTUALIO'

DMD_CREATIONDATATYPES = 'DMD_CREATIONDATATYPES'
DMD_CREATIONOPTIONLIST = 'DMD_CREATIONOPTIONLIST'
DMD_EXTENSION = 'DMD_EXTENSION'
DMD_HELPTOPIC = 'DMD_HELPTOPIC'
DMD_LONGNAME = 'DMD_LONGNAME'
DMD_MIMETYPE = 'DMD_MIMETYPE'
DMD_SUBDATASETS = 'DMD_SUBDATASETS'

GARIO_COMPLETE = 3
GARIO_ERROR = 2
GARIO_PENDING = 0
GARIO_UPDATE = 1

GA_ReadOnly = 0
GA_Update = 1

GCI_AlphaBand = 6
GCI_BlackBand = 13
GCI_BlueBand = 5
GCI_CyanBand = 10
GCI_GrayIndex = 1
GCI_GreenBand = 4
GCI_HueBand = 7
GCI_LightnessBand = 9
GCI_MagentaBand = 11
GCI_PaletteIndex = 2
GCI_RedBand = 3
GCI_SaturationBand = 8
GCI_Undefined = 0

GCI_YCbCr_CbBand = 15
GCI_YCbCr_CrBand = 16
GCI_YCbCr_YBand = 14

GCI_YellowBand = 12

GDT_Byte = 1
GDT_CFloat32 = 10
GDT_CFloat64 = 11
GDT_CInt16 = 8
GDT_CInt32 = 9
GDT_Float32 = 6
GDT_Float64 = 7
GDT_Int16 = 3
GDT_Int32 = 5
GDT_TypeCount = 12
GDT_UInt16 = 2
GDT_UInt32 = 4
GDT_Unknown = 0

GFT_Integer = 0
GFT_Real = 1
GFT_String = 2

GFU_Alpha = 9
GFU_AlphaMax = 17
GFU_AlphaMin = 13
GFU_Blue = 8
GFU_BlueMax = 16
GFU_BlueMin = 12
GFU_Generic = 0
GFU_Green = 7
GFU_GreenMax = 15
GFU_GreenMin = 11
GFU_Max = 4
GFU_MaxCount = 18
GFU_Min = 3
GFU_MinMax = 5
GFU_Name = 2
GFU_PixelCount = 1
GFU_Red = 6
GFU_RedMax = 14
GFU_RedMin = 10

GF_Read = 0
GF_Write = 1

GMF_ALL_VALID = 1

GMF_ALPHA = 4
GMF_NODATA = 8

GMF_PER_DATASET = 2

GPI_CMYK = 2
GPI_Gray = 0
GPI_HLS = 3
GPI_RGB = 1

GRA_Average = 5
GRA_Bilinear = 1
GRA_Cubic = 2
GRA_CubicSpline = 3
GRA_Lanczos = 4
GRA_Mode = 6
GRA_NearestNeighbour = 0

GTO_BIT = 1
GTO_BSQ = 2
GTO_TIP = 0

# functions

def SWIG_PyInstanceMethod_New(*args, **kwargs): # real signature unknown
    pass

# no classes


from sqlalchemy import create_engine, asc
from sqlalchemy.orm import sessionmaker
from MyWebsite.mod_auth.models import User
from MyWebsite.mod_rescue.models import RescueAlert
from datetime import datetime, timedelta
from flask_mail import Mail
from threading import Thread, Lock, Event
from time import sleep

def get_time_plus_minutes(min):
    now = datetime.now()
    print("Now               = {}".format(now))
    now_plus_min = now + timedelta(minutes=min)
    print("One hour from now = {}".format(now_plus_min))
    return now_plus_min

class RecordProcessorCore():
    def __init__(self, num_threads):
        self.stop_extracting = False
        self.record_list_lock = Lock()
        self.record_pull_event = Event()
        self.record_pull_event.clear()
        self.records = []
        self.num_threads = num_threads
        self.processor_threads = []

        # set the event so that when the record extractor thread is started,
        # it is signaled to pull the events.
        self.record_pull_event.set()
        self.engine = create_engine('postgresql+psycopg2://postgres:qazwsx123@localhost/RescueApp')

    def shutdown(self):
        self.stop_extracting = True

    def commence_engine(self):
        self.SessionM = sessionmaker(bind=self.engine)
        self.session = self.SessionM()

        # Start Extractor thread
        self.start_record_extractor_thread()

        # Start Processing Threads
        self.start_record_processing_threads(self.num_threads)

    def record_extractor_runner(self):
        print("record extractor runner started")
        while(not self.stop_extracting):
            if not self.record_pull_event.is_set():
                print("waiting to pull more events")

            self.record_pull_event.wait()

            if self.stop_extracting:
                print("gahhhhh")
                break

            self.pull_records_from_db()
            self.record_pull_event.clear()

    '''
    Start's a thread that pulls records into a central record buffer.
    All record processing threads pull records from that record buffer.
    '''
    def start_record_extractor_thread(self):
        self.record_extractor_thread = Thread(target=self.record_extractor_runner)
        self.record_extractor_thread.start()

    '''
    Starts the specified number of threads that process records.
    '''
    def start_record_processing_threads(self, num_threads):
        for i in range(self.num_threads):
            th = Thread(target=self.record_process_runner)
            th.start()
            self.processor_threads.append(th)

    '''
    Pulls specified number(num) records from records buffer.
    '''
    def pull_records_from_mem(self, num):
        self.record_list_lock.acquire()
        try:
            if len(self.records) < num:
                return None
            else:
                ret_list = []
                for i in range(num):
                    ret_list.append(self.records[i])

                # remove the first *num* elements from record buffer
                del self.records[:num]

                return ret_list
        finally:
            self.record_list_lock.release()

    '''
    Pulls records from database
    '''
    def pull_records_from_db(self):
        print("pull records form db")
        self.record_list_lock.acquire()
        try:
            print("Pulling records from database")

            # pull records that will expire in 20 minutes
            # todo: make this configurable
            time_plus_twenty = get_time_plus_minutes(10)

            # pull the records
            alerts = self.session.query(RescueAlert).filter(RescueAlert.adventure_end_time > datetime.now(), RescueAlert.adventure_end_time < time_plus_twenty).order_by(asc(RescueAlert.adventure_end_time)).all()

            # Essentially appending the records at the end.
            self.records[len(self.records): len(self.records)] = alerts
            for al in self.records:
                print("\t Adventure Name is {}, end-time {}".format(al.adventure_name, al.adventure_end_time))
        finally:
            self.record_list_lock.release()

    '''
    Join with all the worker threads.
    '''
    def join_worker_threads(self):
        self.record_extractor_thread.join()

        for th in self.processor_threads:
            th.join()

if __name__ == "__main__":
    print("Starting Record Processor Engine")
    rpc =  RecordProcessorCore(1)

    rpc.commence_engine()

    while("exit" != input("enter exit to quit\n")):
        print("\t Continuing to process records")

    print("joinging on threads now")
    rpc.shutdown()
    #rpc.join_worker_threads()
    print("Exiting processing")


# -*- coding: cp1252 -*-
import os
import sys

ProgDir = os.path.dirname(sys.argv[0])

class EllipPar:
    def __init__(self):
        self.Num = int
        self.MidPos = float, float
        self.Size = float, float
        self.Angle = float
        self.mov = float, float

class LinePar:
    def __init__(self):
        self.Num = int
        self.Pt1 = int
        self.Pt2 = int
        self.Pos = int, int


class Solution:
    def mergesortarray(self,nums1,m,nums2,n):
        while m >0 and n >0:
            if nums1[m-1] > nums2[n-1]:
                nums1[n+m-1] = nums1[m-1]
                m -= 1
            else:
                nums1[n+m-1] = nums2[n-1]
                n -= 1
        if n >0:
            nums1[:n] = nums2[:n]

专题训练/数组/简单/合并有序数组2到有序数组1中.py

合并有序数组2到有序数组1中.py


from telegram import KeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove, InlineKeyboardButton, \
    InlineKeyboardMarkup

def main_menu(update, context, chat_id):
    buttons = [
        [KeyboardButton(text="Mahsulotlar"), KeyboardButton(text="Men haqimda")],
        [KeyboardButton(text="Noutbuklar")]
    ]
    context.bot.send_message(
        chat_id=chat_id,
        text="Asosiy menyu",
        reply_markup=ReplyKeyboardMarkup(buttons, resize_keyboard=True)
    )

def send_my_info(update, context):
    data = context.user_data
    buttons = [
        [InlineKeyboardButton(text="Ma'lumotlarni o'zgartirish", callback_data="edit_data")],
        [InlineKeyboardButton(text="Asosiy menyu", callback_data="main_menu")]
    ]
    msg = update.message.reply_text(
        text="Waiting...",
        reply_markup=ReplyKeyboardRemove()
    )
    context.bot.delete_message(chat_id=update.message.chat_id, message_id=msg.message_id)
    update.message.reply_text(
        text=f"Ism: {data['first_name']}\n"
             f"Familiya: {data['last_name']}\n"
             f"Yosh: {data['age']}\n"
             f"Jinsi: {data['gender']}\n"
             f"Telefon raqami: {data['contact']}\n",
        reply_markup=InlineKeyboardMarkup(buttons),
        parse_mode="HTML"
    )

def product_info(update, context):
    data = context.user_data
    buttons = [
        [InlineKeyboardButton(text="Apple telefonlari", callback_data="apple_product")],
        [InlineKeyboardButton(text="Samsung telefonlari", callback_data="samsung_product")],
        [InlineKeyboardButton(text="Asosiy menyu", callback_data="main_menu")]
    ]
    msg = update.message.reply_text(
        text="Waiting...",
        reply_markup=ReplyKeyboardRemove()
    )
    context.bot.delete_message(chat_id=update.message.chat_id, message_id=msg.message_id)
    update.message.reply_text(
        text="Mahsulotlar",
        reply_markup=InlineKeyboardMarkup(buttons)
    )


from tkinter import *
import random
from tkinter import messagebox as MB

def crea_palabra():
    global palabra, palabra_aux
    palabra = valor.get()
    entrada.delete(0,END)
    num = len(palabra)
    palabra_aux = palabra
    fondo_tapa = Label(ventana, image = tapa, bg = "#26867d").place(x = 400, y = 500)

    pal = list(palabra_aux)
    for i in range (1,num):
        pal[i] =  "*"
    palabra_aux = "".join(pal)

    L3 = Label(ventana, text = palabra_aux, fg = "White", bg = "#26867d", font = ("arial",25 ))
    L3.place(x = 400, y = 500)
    b_ingre["state"] = NORMAL

def Comprobar():
    global palabra_aux, conta
    res = letra.get()
    entrada_letra.delete(0,END)
    if(palabra.find(res)>=0):
        aux = list(palabra)
        aux2 = list(palabra_aux)
        for i in range (0,len(palabra)):
            if(aux[i] == res):
                aux2[i] = res
        pal = "".join(aux2)

        palabra_aux = pal
        fondo_tapa = Label(ventana, image = tapa, bg = "#26867d").place(x = 400, y = 500)

        L3 = Label(ventana, text = pal, fg = "White", bg = "#26867d", font = ("arial",25 ))
        L3.place(x = 400, y = 500)
        if(palabra_aux == palabra):
            MB.showinfo("Felicidades!!","Acertaste la palabra, Ingresa una nueva palabra para continuar")
            reset()

    else:
        conta += 1
        if(conta == 1):
            fondo_2 = Label(ventana, image = inicio_2, bg = "#26867d").place(x = 300, y = 150)
        elif(conta == 2):
            fondo_2 = Label(ventana, image = inicio_3, bg = "#26867d").place(x = 300, y = 150)
        elif(conta == 3):
            fondo_2 = Label(ventana, image = inicio_4, bg = "#26867d").place(x = 300, y = 150)
        elif(conta == 4):
            fondo_2 = Label(ventana, image = inicio_5, bg = "#26867d").place(x = 300, y = 150)
        elif(conta == 5):
            fondo_2 = Label(ventana, image = inicio_6, bg = "#26867d").place(x = 300, y = 150)
        elif(conta == 6):
            fondo_2 = Label(ventana, image = inicio_7, bg = "#26867d").place(x = 300, y = 150)
        elif(conta == 7):

            MB.showinfo("Mala Suerte","Gastaste todos tus intentos :(, Ingresa una nueva palabra para continuar")
            reset()

def reset():
    global conta
    fondo_inicio = Label(ventana, image = inicio, bg = "#26867d").place(x = 300, y = 150)
    fondo_tapa = Label(ventana, image = tapa, bg = "#26867d").place(x = 400, y = 500)
    b_ingre["state"] = DISABLED
    conta = 0

def Salir_2(root):
    root.deiconify()
    ventana.destroy()

def main(root):
    root.iconify()
    global ventana, valor, letra, entrada, tapa, entrada_letra, b_ingre, inicio
    global conta, inicio_2, inicio_3, inicio_4, inicio_5, inicio_6, inicio_7
    conta = 0
    ventana = Toplevel(root)
    ventana.geometry("1000x600")
    ventana.title("Ahorcado")
    ventana["bg"] = "#26867d"
    ventana.resizable(False,False)

    L1 = Label(ventana, text = "¿Cuál es la palabra a  utilizar?", fg = "White", bg = "#26867d", font = ("arial",18 ))
    L1.place(x = 10, y = 10)
    L2 = Label(ventana, text = "Ingresa la letra:", fg = "White", bg = "#26867d", font = ("arial",18 ))
    L2.place(x = 750, y = 180)
    valor = StringVar()
    entrada = Entry(ventana, textvariable = valor)
    entrada.place(x = 50, y = 50, width=150, height=25)
    letra = StringVar()
    entrada_letra = Entry(ventana, textvariable = letra, font = ("arial",18 ))
    entrada_letra.place(x = 750, y = 210,width=175, height=50)
    tapa = PhotoImage(file = "Imagenes/tapa_mem.png")
    tapa = tapa.subsample(3)
    inicio = PhotoImage(file = "Ahorcado/inicio.png")
    inicio_2 = PhotoImage(file = "Ahorcado/estado_2.png")
    inicio_3 = PhotoImage(file = "Ahorcado/estado_3.png")
    inicio_4 = PhotoImage(file = "Ahorcado/estado_4.png")
    inicio_5 = PhotoImage(file = "Ahorcado/estado_5.png")
    inicio_6 = PhotoImage(file = "Ahorcado/estado_6.png")
    inicio_7 = PhotoImage(file = "Ahorcado/estado_7.png")

    fondo_inicio = Label(ventana, image = inicio, bg = "#26867d").place(x = 300, y = 150)

    #Botones
    b_enviar = Button(ventana, text = "Enviar",font = ("arial",15), bg = "#ef7f74", command = crea_palabra)
    b_enviar.place(x = 210, y = 50, width=130, height=25)
    b_ingre = Button(ventana, text = "Ingresar",font = ("arial",15), bg = "#ef7f74", state = DISABLED, command = Comprobar)
    b_ingre.place(x = 750, y = 280)
    b_salir = Button(ventana, text = "Salir",font = ("arial",18), bg = "#ef7f74", command = lambda: Salir_2(root))
    b_salir.place(x = 800, y = 500, width=110, height=50)

    ventana.mainloop()

"""
                                               .--.
                                               `.  \
                                                 \  \
                                                  .  \
                                                  :   .
                                                  |    .
                                                  |    :
                                                  |    |
  ..._  ___                                       |    |
 `."".`''''""--..___                              |    |
 ,-\  \             ""-...__         _____________/    |
 / ` " '                    `""""""""                  .
 \                                                      L
 (>                                                      \
/                                                         \
\_    ___..---.                                            L
  `--'         '.                                           \
                 .                                           \_
                _/`.                                           `.._
             .'     -.                                             `.
            /     __.-Y     /''''''-...___,...--------.._            |
           /   _."    |    /                ' .      \   '---..._    |
          /   /      /    /                _,. '    ,/           |   |
          \_,'     _.'   /              /''     _,-'            _|   |
                  '     /               `-----''               /     |
                  `...-'                                       `...-'

   """


from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request, "index.html")

def  results(request):
    context = {
        "name" : request.POST['name'],
        "location" : request.POST['location'],
        "lang" : request.POST['lang'],
        "comment" : request.POST['comment'],
    }
    return render(request, "results.html", context)


import os

# os.environ["CUDA_VISIBLE_DEVICES"] = "2"
# os.chdir("../")
import math
import io
import torch
from compressai.datasets import RawImageDataset
import cv2
import torch.nn as nn
import torch.nn.functional as F
import os
torch.use_deterministic_algorithms(True)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = True
torch.manual_seed(0)
# torch.use_deterministic_algorithms(True)
from torchvision import transforms
import numpy as np
from torchvision.utils import save_image
from PIL import Image
import seaborn
import tqdm
import matplotlib.pyplot as plt
from compressai.entropy_models import EntropyBottleneck, GaussianConditional
from skimage.metrics import structural_similarity as cal_ssim
from compressai.datasets.dataset_raw import DatasetRAWTest, DatasetRAW
from pytorch_msssim import ms_ssim
from compressai.zoo import raw_hyperprior, raw_context, learned_context
# from ipywidgets import interact, widgets
import argparse
import thop

device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(os.getcwd())
parser = argparse.ArgumentParser(description="Example training script.")
parser.add_argument(
    "-i",
    default="0",
    type=int,
    help="The model index"
)
parser.add_argument(
    "--max",
    default=0.01,
    type=float,
    help="maximum value of error bar"
)
parser.add_argument(
    "--lambda",
    default="0.05",
    dest="lmbda",
    type=float,
    help="maximum value of error bar"
)
parser.add_argument(
    "--gamma",
    default="0",
    type=float
)
parser.add_argument(
    "--info",
    default="",
    type=str,
)
parser.add_argument(
    "-g",
    default="nus_soft_jpg_lists",
    type=str,
    help="The experiments list name"
)
parser.add_argument(
    "--dataset",
    default="./datasets/NUS"
)
parser.add_argument(
    "--drop_num",
    default=0,
    type=int,
)
parser.add_argument(
    "--val",
    default="val_Sony", # val_Sony_jpg
    type=str,
)
parser.add_argument(
    "--ntest",
    default=-1, # val_Sony_jpg
    type=int,
)
parser.add_argument(
    "-q",
    default=-1, # val_Sony_jpg
    type=int,
    help="JPEG quality"
)

parser.add_argument(
    "--cache",
    action="store_true",
    help="load the dataset to memory"
)

parser.add_argument(
    "--raw_space",
    type=str,
    choices=["raw_linear", "xyz_gamma", "cvpr2022", "raw_gamma", "sid"],
    default="raw_linear",
)

parser.add_argument(
    "--file_type",
    type=str,
    help="load the dataset to memory",
    default="tif"
)

args = parser.parse_args()
print(args)
from config_files import *

ckpt = eval(args.g)[args.i]
# ckpt = nus_soft_jpg_lists[args.i]
model_basename = os.path.basename(ckpt['path'])+args.info
quality_str = "_q%d" % args.q if not ckpt["nocompress"] else ""
img_folder = f"results/error_map/{args.g}/{model_basename}/{args.val}{quality_str}{f'_gamma_{args.gamma:.1f}' if args.gamma!=0 else ''}{f'_drop_{args.drop_num}' if args.drop_num!=0 else ''}"
csv_folder = f"results/csv/{args.g}/{model_basename}"
os.makedirs(csv_folder, exist_ok=True)
result_csv = open(f"{csv_folder}/{args.val}{quality_str}{f'_gamma_{args.gamma:.1f}' if args.gamma!=0 else ''}{f'_drop_{args.drop_num}' if args.drop_num!=0 else ''}.csv","w")
result_csv.write(f"idx,PSNR,SSIM,bpp\n")

path, model, quality, noquant, demosaic, reduce_c, no_compress, channel_mean, discrete_context, use_deconv, only_demosaic = ckpt.pop("path"), ckpt.pop("model"), ckpt.pop("quality", 2), ckpt.pop("noquant", False), ckpt.get("demosaic", False), ckpt.pop("reduce_c", 1), ckpt.pop("nocompress", False), ckpt.get("channel_mean", False),  ckpt.pop("discrete_context", False), ckpt.pop("use_deconv", False), ckpt.pop("only_demosaic", False)

if args.cache:
    test_dataset = DatasetRAWTest(os.path.join(args.dataset, "test"), ftype=args.file_type)
else:
    test_dataset = RawImageDataset(args.dataset, split=args.val, transform=None, nocompress=no_compress, ntest=args.ntest, qlist=[args.q], raw_space=args.raw_space,**ckpt)

net = model(quality=quality, pretrained=False, noquant=noquant, reduce_c= reduce_c, discrete_context=discrete_context, use_deconv=use_deconv, gamma=args.gamma, drop_num=args.drop_num, **ckpt).eval()
ckpt_from_file = torch.load(path)
print(f"Loading the model from {path}")
print(f"The model is trained by {ckpt_from_file['epoch']} epoch")
net.load_state_dict(ckpt_from_file["state_dict"])

net = net.to(device)
print("The computational cost for 512*512 image:")
if ckpt.get("lambda_list", None) is not None:
    print(thop.clever_format(thop.profile(net, (torch.randn(1,3,512,512).to(device), torch.randn(1,3,512,512).to(device), 0.05))))
else:
    print(thop.clever_format(thop.profile(net, (torch.randn(1,3,512,512).to(device), torch.randn(1,3,512,512).to(device)))))

def auto_padding(img, times=32):
    # img: numpy image with shape H*W*C
    b, c, h, w = img.shape
    h1, w1 = (times - h % times) // 2, (times - w % times) // 2
    h2, w2 = (times - h % times) - h1, (times - w % times) - w1
    img = F.pad(img, [w1, w2, h1, h2], "reflect")
    return img, [w1, w2, h1, h2]
psnr_list = []
bpp_list = []
ssim_list = []
re_list = []

net.update()
def compute_psnr(a, b):
    mse = torch.mean((a - b)**2).item()
    return -10 * math.log10(mse)

def compute_re(target, rec):
    re = (target-rec).abs() / ((rec + target)/2).clip(0.001)
    return re.mean()

def compute_msssim(a, b):
    return ms_ssim(a, b, data_range=1.).item()

def compute_bpp(out_net):
    size = out_net['x_hat'].size()
    print("shape:", size)
    # size = unsqueeze2d(out_net['x_hat']).size()
    num_pixels = size[0] * size[2] * size[3]
    return sum(torch.log(likelihoods).sum() / (-math.log(2) * num_pixels)
            for likelihoods in out_net['likelihoods'].values()).item()

def remove_boarder(np_img):
    np_img_gray = np_img.mean(axis=2)
    w_sum = np.sum(np_img_gray, axis=0)
    h_sum = np.sum(np_img_gray, axis=1)
    h_area = np.argwhere(h_sum < h_sum.max())
    w_area = np.argwhere(w_sum < w_sum.max())
    return np_img[h_area.min():h_area.max(), w_area.min():w_area.max()]

def iter_str_length(list_x):
    string_length = []
    for x in list_x:
        if isinstance(x, (str, bytes)):
            string_length.append(len(x))
        else:
            string_length.extend(iter_str_length(x))
    return string_length

os.makedirs(img_folder, exist_ok=True)
# for i in tqdm.tqdm(range(len(test_dataset))):'
for i in tqdm.tqdm(range(len(test_dataset))):
    # if i not in [8]: continue
    rgb_jpeg, raw_visible, metadata = test_dataset[i]
    # rgb_jpeg, raw_visible = rgb_jpeg[:,:2920,:4386], raw_visible[:,:2920,:4386]
    rgb_jpeg, _ = auto_padding(rgb_jpeg.to(device).unsqueeze(0), 128)
    raw_visible, pad_params = auto_padding(raw_visible.to(device).unsqueeze(0), 128)
    import torch.cuda.amp as amp
    net.eval()

    with torch.no_grad():
        torch.cuda.empty_cache()

        raw_visible_ = raw_visible
        if max(list(raw_visible.shape)) > 4000:
            Bytes = 0
            rgb_jpeg_patches = rgb_jpeg.chunk(2, dim=3)
            raw_visible_patches = raw_visible.chunk(2, dim=3)
            rec_raw_patch_list = []
            for rgb_jpeg, raw_visible in zip(rgb_jpeg_patches, raw_visible_patches):
                with amp.autocast():
                    compressed_result = net.compress(raw_visible, rgb_jpeg, lmbda=args.lmbda)
                Bytes += sum(iter_str_length(compressed_result["strings"]))
                with amp.autocast():
                    rec_from_strings = net.decompress(compressed_result["strings"], compressed_result["shape"], rgb_jpeg, z_mean = compressed_result["z_mean"] if channel_mean else None, compressed_result = compressed_result, lmbda=args.lmbda)
                rec_raw_patch_list.append(rec_from_strings["x_hat"].float())
            rec_raw_ = torch.cat(rec_raw_patch_list, dim=3)
        else:
            with amp.autocast():
                compressed_result = net.compress(raw_visible, rgb_jpeg, lmbda=args.lmbda)
                Bytes = sum(iter_str_length(compressed_result["strings"])) # ,
                torch.cuda.empty_cache()

            with amp.autocast(): # https://github.com/pytorch/pytorch/issues/45910
                rec_from_strings = net.decompress(compressed_result["strings"], compressed_result["shape"], rgb_jpeg, z_mean = compressed_result["z_mean"] if channel_mean else None, compressed_result = compressed_result, lmbda=args.lmbda)

            rec_raw_ = rec_from_strings["x_hat"].float()

        kb = Bytes/1024
        print("Real size of compressed string %.5e KB"%kb)
        real_bpp = (8*Bytes/(raw_visible_.shape[2]*raw_visible_.shape[3]))
        print("Real bpp: %.5e"%real_bpp)

        rec_raw_ = F.pad(rec_raw_, [-p for p in pad_params])
        raw_visible_ = F.pad(raw_visible_, [-p for p in pad_params])

        psnr = compute_psnr(raw_visible_, rec_raw_)
        re = compute_re(raw_visible_, rec_raw_)
        ssim = cal_ssim(raw_visible_.squeeze().permute(1,2,0).cpu().numpy(), rec_raw_.squeeze().permute(1,2,0).cpu().numpy(), multichannel=True, channel_axis=2, data_range=1)
        print(f'MAE {(raw_visible_-rec_raw_).abs().mean().item()}')
        print(f'PSNR from strings: {psnr:.2f}dB')
        print(f'SSIM from strings: {ssim:.4f}')
        print(f'relative error from strings: {re:.4f}')

        psnr_list.append(psnr)
        ssim_list.append(ssim)
        re_list.append(re.item())
        bpp_list.append(real_bpp)

        ax = seaborn.heatmap((raw_visible_-rec_raw_).cpu().abs().max(dim=1)[0].squeeze(0), xticklabels=False, yticklabels=False, vmax=args.max, cbar=False, vmin=0, square=True, linewidth = 0)
        fig = ax.get_figure()
        with io.BytesIO() as buff:
            fig.savefig(buff, format='raw')
            buff.seek(0)
            data = np.frombuffer(buff.getvalue(), dtype=np.uint8)
        w, h = fig.canvas.get_width_height()
        im = data.reshape((int(h), int(w), -1))
        cv2.imwrite(f"{img_folder}/raw_{i}_{args.max}.jpg", cv2.cvtColor(remove_boarder(im), cv2.COLOR_RGB2BGR))
        fig.clf()

        save_image(rec_raw_** (1 / 2.2), f"{img_folder}/raw_{i}.jpg")
        save_image(rgb_jpeg, f"{img_folder}/rsrgb_{i}.jpg")
        if metadata["wb"] != -1:
            awb = torch.tensor(metadata["wb"][:3])/metadata["wb"][1]
            save_image((rec_raw_.pow(2.2)/awb.to(rec_raw_.device)[:,None, None]).pow(1/2.2), f"{img_folder}/raw_{i}_woAW.jpg")
            save_image((raw_visible_.pow(2.2)/awb.to(rec_raw_.device)[:,None, None]).pow(1/2.2), f"{img_folder}/raw_{i}_woAW_gt.jpg")
        else:
            save_image(raw_visible_** (1 / 2.2), f"{img_folder}/raw_{i}_gt.jpg")

        result_csv.write(f"{i},{psnr},{ssim},{real_bpp}\n")

        del compressed_result
        del rec_from_strings

print(f"Mean PSNR: {np.mean(psnr_list):.5e} Mean SSIM: {np.mean(ssim_list):.5e} Mean RE: {np.mean(re_list):.5e} Mean BPP: {np.mean(bpp_list):.5e}\n\n")
result_csv.write(f"\n\n")
result_csv.write(f"Mean,{np.mean(psnr_list):.5e},{np.mean(ssim_list):.5e},{np.mean(bpp_list):.5e}\n")
result_csv.close()


def two_sum(num, target):
    d = dict()
    for i in range(len(num)):
        x = num[i]
        if target-x in d:
            return (d[target-x], i)
        d[x] = i

print(two_sum([2,7,11,15], 17))

def fib(n):
    a, b = 0, 1
    for _ in range(n):
        # yield b
        print(b)
        a, b = b, a+b

print(fib(10))

def fibon():
    a, b = 0, 1
    while 1:
        yield b
        a, b = b, a+b


from bisect import bisect_left, bisect_right
from collections import Counter
import sys

card_num = int(sys.stdin.readline())
card_lst = list(map(int, sys.stdin.readline().split()))
card_lst.sort()
find_num = int(sys.stdin.readline())
find_lst = list(map(int, sys.stdin.readline().split()))
result_lst = []

# 1안
# for i in range(find_num):
#     count = 0
#     temp = bisect_left(card_lst, find_lst[i])
#     for j in card_lst[temp:]:
#         if j == find_lst[i]:
#             count += 1
#         else:
#             break
#     result_lst.append(count)
# print(*result_lst, sep=" ")

# 2안
# for i in range(find_num):
#     count = 0
#     temp1 = bisect_left(card_lst, find_lst[i])
#     temp2 = bisect_right(card_lst, find_lst[i])
#     count = temp2 - temp1
#     result_lst.append(count)
# print(*result_lst, sep=" ")

# 3안
count = Counter(card_lst)
print(count)
print(' '.join(f'{count[i]}' if i in count else '0' for i in find_lst))


class Node:
    def __init__(self, data):
        self.data=data
        self.next=None

class LinkedList:
    def __init__(self, data):
        self.head=Node(data)

    # 맨 뒤에 새로운 노드 추가
    def append_newNode(self, data):
        cur=self.head
        while cur.next is not None: cur=cur.next
        cur.next=Node(data)

    # 모든 노드 값 출력
    def print_AllNodes(self):
        cur=self.head
        while cur is not None:
            print(cur.data)
            cur=cur.next

    # 특정 인덱스 노드 알아내기
    def get_nodeOnIndex(self, index):
        cur=self.head; idx=0
        while idx < index:
            cur=cur.next; idx+=1
        return cur

    # 삽입
    def insert_node(self, index, data):
        newNode=Node(data)
        if index==0:
            newNode.next=self.head
            self.head=newNode
            return
        node=self.get_nodeOnIndex(index-1)
        next_node=node.next
        node.next=newNode
        newNode.next=next_node

    # 삭제
    def delete_nodeOnIndex(self, index):
        if index==0:
            self.head=self.head.next; return
        node=self.get_nodeOnIndex(index-1)
        node.next=node.next.next

if __name__=="__main__":
    LL=LinkedList(5)
    LL.append_newNode(12)
    LL.insert_node(1,4)
    LL.print_AllNodes()


sr=lambda: input()
ir=lambda: int(sr())
lr=lambda: list(map(int, sr().split()))

# dr=lambda: float(sr())
# dlr=lambda: list(map(float, sr().split()))

inf=10**18
# mod = 10**9+7
mod=998244353

def main():
    n,m=lr()
    e=[set() for _ in range(n)]
    for _ in range(m):
        u,v=lr()
        u-=1
        v-=1
        e[u].add(v)
        e[v].add(u)
    ans = 0
    for i in range(n-2):
        for j in range(i+1, n-1):
            for k in range(j+1, n):
                if i in e[j] and j in e[k] and k in e[i]:
                    ans+=1
    print(ans)

if __name__=='__main__':
    main()


import shutil
import tempfile

from django import forms
from django.conf import settings
from django.core.cache import cache
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import Client, TestCase, override_settings
from django.urls import reverse
from mixer.backend.django import mixer

from ..constants import COUNT_POST_FOR_TEST, LIMIT_POST, LIMIT_POST_FOR_TEST
from ..models import Follow, Group, Post, User

TEMP_MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR)

@override_settings(MEDIA_ROOT=TEMP_MEDIA_ROOT)
class TaskPagesTests(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.user = User.objects.create_user(username='user_test')
        cls.user_for_follow = User.objects.create_user(username='Test follow')
        cls.group = Group.objects.create(
            title='тестовая группа',
            slug='test',
            description='тестовое описание',
        )
        cls.new_group = Group.objects.create(
            title='тестовая группа 2',
            slug='test2',
            description='тестовое описание 2',
        )
        cls.posts = mixer.cycle(COUNT_POST_FOR_TEST).blend(
            Post,
            author=cls.user,
            group=cls.group,
            text=mixer.RANDOM,
        )
        cls.small_gif = (
            b'\x47\x49\x46\x38\x39\x61\x02\x00'
            b'\x01\x00\x80\x00\x00\x00\x00\x00'
            b'\xFF\xFF\xFF\x21\xF9\x04\x00\x00'
            b'\x00\x00\x00\x2C\x00\x00\x00\x00'
            b'\x02\x00\x01\x00\x00\x02\x02\x0C'
            b'\x0A\x00\x3B'
        )
        cls.uploaded = SimpleUploadedFile(
            name='small.gif',
            content=cls.small_gif,
            content_type='image/gif',
        )
        cls.post_with_image = Post.objects.create(
            author=cls.user,
            text='Пост с картинкой',
            group=cls.group,
            image=cls.uploaded,
        )
        cls.posts_test = Post.objects.filter(
            group_id=cls.group.id
        )[:LIMIT_POST]
        cls.templates_pages_names = {
            reverse('posts:index'):
                'posts/index.html',
            reverse('posts:group_posts', kwargs={'slug': cls.group.slug}):
                'posts/group_list.html',
            reverse(
                'posts:profile', kwargs={'username': cls.posts_test[0].author}
            ):
                'posts/profile.html',
            reverse(
                'posts:post_detail', kwargs={'post_id': cls.posts_test[0].id}
            ):
                'posts/post_detail.html',
            reverse(
                'posts:post_edit', kwargs={'post_id': cls.posts_test[0].id}
            ):
                'posts/create_post.html',
            reverse('posts:post_create'):
                'posts/create_post.html',
        }
        cls.urls_with_paginator = {
            reverse('posts:index'),
            reverse(
                'posts:group_posts', kwargs={'slug': cls.group.slug},
            ),
            reverse(
                'posts:profile', kwargs={'username': cls.posts_test[0].author},
            ),
        }
        cls.form_fields = {
            'text': forms.fields.CharField,
            'group': forms.models.ModelChoiceField,
        }

    @classmethod
    def tearDownClass(cls):
        super().tearDownClass()
        shutil.rmtree(TEMP_MEDIA_ROOT, ignore_errors=True)

    def setUp(self):
        """Создание пользователей."""
        cache.clear()
        self.authorized_client = Client()
        self.authorized_client.force_login(self.user)
        self.auth_client_follow = Client()
        self.auth_client_follow.force_login(self.user_for_follow)

    def context_for_test(self, object):
        self.assertEqual(object, self.posts_test[0])
        self.assertEqual(object.author, self.posts_test[0].author)
        self.assertEqual(object.group, self.posts_test[0].group)
        self.assertEqual(object.text, self.posts_test[0].text)
        self.assertEqual(object.image, self.posts_test[0].image)

    def test_correct_templates(self):
        """Проверка на соответствии шаблона с адресом."""
        for reverse_url, template in self.templates_pages_names.items():
            with self.subTest(template):
                response = self.authorized_client.get(reverse_url)
                self.assertTemplateUsed(response, template)

    def test_paginator(self):
        """
        Проверка на наличии 10 постов на первой странице и
        4 постов на след.странице.
        """
        for reverse_url in self.urls_with_paginator:
            with self.subTest(reverse_url):
                response = self.authorized_client.get(reverse_url)
                self.assertEqual(
                    len(response.context['page_obj']), LIMIT_POST
                )
                response_next_page = self.authorized_client.get(
                    reverse_url + '?page=2'
                )
                self.assertEqual(
                    len(response_next_page.context['page_obj']),
                    LIMIT_POST_FOR_TEST
                )

    def test_context_index(self):
        """Проверка контекстов страницы index."""
        response = self.authorized_client.get(reverse('posts:index'))
        self.context_for_test(response.context['page_obj'][0])

    def test_context_group_list(self):
        """Проверка контекстов страницы group_list."""
        response = self.authorized_client.get(
            reverse('posts:group_posts', kwargs={'slug': self.group.slug})
        )
        self.context_for_test(response.context['page_obj'][0])
        self.assertEqual(response.context['group'], self.group)

    def test_context_profile(self):
        """Проверка контекстов страницы profile."""
        response = self.authorized_client.get(
            reverse(
                'posts:profile', kwargs={'username': self.posts_test[0].author}
            )
        )
        self.context_for_test(response.context['page_obj'][0])
        self.assertEqual(response.context['author'], self.user)
        self.assertIn(response.context['following'], (True, False))

    def test_context_post_detail(self):
        """Проверка контекстков страницы post_detail."""
        response = self.authorized_client.get(
            reverse(
                'posts:post_detail', kwargs={'post_id': self.posts_test[0].id}
            )
        )
        object = response.context['post']
        self.context_for_test(object)
        self.assertEqual(object.id, self.posts_test[0].id)

    def test_new_post_in_need_pages(self):
        """Проверка новый пост попал на нужные страницы и на первой позиции."""
        new_post = Post.objects.create(
            author=self.user,
            group=self.group,
            text='Новое сообщение'
        )
        pages = [
            reverse(
                'posts:index'
            ),
            reverse(
                'posts:group_posts', kwargs={'slug': self.group.slug}
            ),
            reverse(
                'posts:profile', kwargs={'username': self.posts_test[0].author}
            ),
        ]
        for url in pages:
            with self.subTest(url):
                response = self.authorized_client.get(url)
                self.assertEqual(
                    new_post,
                    response.context['page_obj'][0]
                )

    def test_new_post_in_need_group(self):
        """Проверка новый пост находится в нужной группе."""
        new_post = Post.objects.create(
            author=self.user,
            group=self.new_group,
            text='Новое сообщение'
        )
        response = self.authorized_client.get(
            reverse('posts:group_posts', kwargs={'slug': self.new_group.slug})
        )
        objects = response.context['page_obj']
        self.assertNotEqual(objects[0].group, self.group)
        self.assertNotIn(new_post, self.posts_test)

    def test_context_post_create(self):
        """Проверка контекста страницы post_create."""
        reverse_url = reverse('posts:post_create')
        response = self.authorized_client.get(reverse_url)
        for value, expected in self.form_fields.items():
            with self.subTest(value):
                form_field = response.context.get('form').fields.get(value)
                self.assertIsInstance(form_field, expected)

    def test_context_post_edit(self):
        """Проверка контекста страницы post_edit."""
        reverse_url = reverse(
            'posts:post_edit', kwargs={'post_id': self.posts_test[0].id}
        )
        response = self.authorized_client.get(reverse_url)
        for value, expected in self.form_fields.items():
            with self.subTest(value):
                form_field = response.context.get('form').fields.get(value)
                self.assertIsInstance(form_field, expected)
        self.assertEqual(
            response.context['post_id'],
            self.posts_test[0].id
        )
        self.assertTrue(response.context['is_edit'])

    def test_cache(self):
        """Проверка кэша страницы Index."""
        response = self.authorized_client.get(
            reverse('posts:index')
        )
        Post.objects.create(
            text='Проверяем кэширование страницы',
            author=self.user,
        )
        cached = self.authorized_client.get(
            reverse('posts:index')
        )
        self.assertEqual(
            response.content,
            cached.content
        )
        cache.clear()
        response_new = self.authorized_client.get(
            reverse('posts:index')
        )
        self.assertNotEqual(cached.content, response_new.content)

    def test_follow(self):
        """Проверка подписки."""
        self.assertFalse(Follow.objects.filter(
            user=self.user_for_follow,
            author=self.user
        ).exists())
        self.auth_client_follow.get(
            reverse('posts:profile_follow', kwargs={'username': self.user})
        )
        self.assertTrue(
            Follow.objects.filter(
                user=self.user_for_follow,
                author=self.user
            ).exists()
        )

    def test_unfollow(self):
        """Проверка отписки."""
        Follow.objects.create(
            user=self.user_for_follow,
            author=self.user
        )
        self.auth_client_follow.get(
            reverse('posts:profile_unfollow', kwargs={'username': self.user})
        )
        self.assertFalse(
            Follow.objects.filter(
                user=self.user_for_follow,
                author=self.user
            ).exists()
        )

    def test_show_post_followed(self):
        """Проверка отображения постов у подписанных."""
        Follow.objects.create(
            user=self.user_for_follow,
            author=self.user
        )
        response = self.auth_client_follow.get(
            reverse('posts:follow_index')
        )
        objects = list(response.context['page_obj'])
        self.assertIn(objects[0], self.posts_test)

    def test_no_show_post_unfollowed(self):
        """Проверка неотображения постов у неподписанных."""
        response = self.authorized_client.get(
            reverse('posts:follow_index')
        )
        objects = list(response.context['page_obj'])
        self.assertNotIn(objects, self.posts_test)


import os
from flask import Flask, render_template, request
import music_recognizer

# create an instance of Flask class
app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def home():
    return render_template("index.html")

@app.route("/upload", methods=["POST"])
def recognize():
    if request.method == 'POST':
        print(f"[INFO] POST method")
        try:
            print(f"[INFO] try method")
            music_file = request.files.get("file")
            print(f"[INFO] try method:  {music_file}")
        except Exception as err:
            return render_template('sorry.html', message=f'Please provide a valid file: {err}')

        if music_file is None:
            return render_template('sorry.html', message='Please provide a valid file.')

        save_path = os.path.join("static/music/", music_file.filename)
        music_file.save(save_path)

        print(f"Filename: {music_file.filename}")
        print(f"Saved as: {save_path}")

        # Perform music recognition here
        music_mfcc = music_recognizer.get_mfcc(save_path)
        if music_mfcc is None:
          return render_template('sorry.html', message='Error loading in server')
        predictions = music_recognizer.prediction(music_mfcc)
        path, result = music_recognizer.probability_graph_path(predictions)

        return render_template("index.html",
                                filename=path,
                                music_path=f"music/{music_file.filename}",
                                result=result)

    return render_template("index.html")

if __name__ == '__main__':
    app.run(debug=True)


# modified from https://github.com/sbarratt/inception-score-pytorch
from __future__ import print_function, division
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "1"

import torch
from torch import nn
from torch.autograd import Variable
from torch.nn import functional as F
import torch.utils.data

import numpy as np
from scipy.stats import entropy

def inception_score(dataloader, cuda=True, batch_size=32, resize=False, splits=1, num_classes=15):
    """Computes the inception score of the generated images

    imgs -- Torch dataset of (3xHxW) numpy images normalized in the range [-1, 1]
    cuda -- whether or not to run on GPU
    batch_size -- batch size for feeding into Inception v3
    splits -- number of splits
    num_classes: number of weed classes
    """
    N = len(dataloader.dataset)

    assert batch_size > 0
    assert N > batch_size

    # Set up dtype
    if cuda:
        dev = torch.device("cuda")
        dtype = torch.cuda.FloatTensor
    else:
        if torch.cuda.is_available():
            print("WARNING: You have a CUDA device, so you should probably set cuda=True")
        dtype = torch.FloatTensor
        dev = torch.device("cpu")

    inception_model = torch.load(PATH).to(dev)
    inception_model.eval()

    up = nn.Upsample(size=(299, 299), mode='bilinear').type(dtype)

    def get_pred(x):
        if resize:
            x = up(x)
        x = inception_model(x)
        return F.softmax(x).data.cpu().numpy()

    # Get predictions
    preds = np.zeros((N, num_classes))

    for i, batch in enumerate(dataloader, 0):
        batch = batch[0].type(dtype)
        batchv = Variable(batch)
        batch_size_i = batch.size()[0]

        preds[i*batch_size:i*batch_size + batch_size_i] = get_pred(batchv)

    # Now compute the mean kl-div
    split_scores = []

    for k in range(splits):
        part = preds[k * (N // splits): (k+1) * (N // splits), :]
        py = np.mean(part, axis=0)
        scores = []
        for i in range(part.shape[0]):
            pyx = part[i, :]
            scores.append(entropy(pyx, py))
        split_scores.append(np.exp(np.mean(scores)))

    return np.mean(split_scores), np.std(split_scores)

if __name__ == '__main__':
    from torchvision import datasets, transforms
    import torch.utils.data as data

    # PATH = 'inception_0.pth' # for cottonweedid15
    # num_classes = 15

    PATH = 'inception_0_A.pth' # for deepweeds
    num_classes = 9
    EVAL_DIR = '/home/dong9/PycharmProjects/PyTorch-StudioGAN/images/samples/DeepWeeds-StyleGAN3-r-paper-train-2022_08_30_14_24_00/fake'

    # Prepare the eval data loader
    img_size = 256
    bs = 32
    num_cpu = 8

    eval_transform = transforms.Compose([
        transforms.Resize(size=img_size),
        transforms.CenterCrop(size=img_size),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406],
                             [0.229, 0.224, 0.225])])

    eval_dataset = datasets.ImageFolder(root=EVAL_DIR, transform=eval_transform)
    dataloader = data.DataLoader(eval_dataset, batch_size=bs, shuffle=True,
                                  num_workers=num_cpu, pin_memory=True)

    print ("Calculating Inception Score...")
    print(inception_score(dataloader, cuda=True, batch_size=bs, resize=True, splits=10, num_classes=num_classes))


import numpy as np
import pandas as pd
import re
import time
import ssl
import functools
import nltk

try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    pass
else:
    ssl._create_default_https_context = _create_unverified_https_context

from nltk import TweetTokenizer
from nltk.corpus import stopwords

import matplotlib.pyplot as plt

from sklearn.pipeline import Pipeline
from sklearn.model_selection import cross_validate, StratifiedKFold, train_test_split
from sklearn.feature_selection import SelectFromModel
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.naive_bayes import MultinomialNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import LinearSVC, SVC
from sklearn import metrics, linear_model, ensemble
from sklearn.metrics import precision_recall_fscore_support

def filter_obama(data, dropnan=None):
    raw_obama_dataframe = pd.read_excel(data, 'Obama', header=0, usecols="D,E")
    raw_obama_dataframe['Class'] = pd.to_numeric(raw_obama_dataframe['Class'], errors='coerce', downcast='float')
    filtered_obama_df = raw_obama_dataframe[raw_obama_dataframe.Class != 2]
    if dropnan:
        filtered_obama_df = filtered_obama_df.dropna()

    return filtered_obama_df

def filter_romney(data, dropnan=None):
    raw_romney_dataframe = pd.read_excel(data, 'Romney', header=0, usecols="D,E")
    raw_romney_dataframe['Class'] = pd.to_numeric(raw_romney_dataframe['Class'], errors='coerce', downcast='float')
    filtered_romney_df = raw_romney_dataframe[raw_romney_dataframe.Class != 2]

    if dropnan:
        filtered_romney_df = filtered_romney_df.dropna()

    return filtered_romney_df

def obama_testing(data):
    obama_test = pd.read_excel(data, "Obama", header=None, usecols="A,B")
    obama_test.rename(columns={0: 'id', 1: 'Annotated Tweet'}, inplace=True)
    return obama_test

def romney_testing(data):
    romney_test = pd.read_excel(data, "Romney", header=None, usecols="A,B")
    romney_test.rename(columns={0: 'id', 1: 'Annotated Tweet'}, inplace=True)
    return romney_test

# Preprocessing
def PreProcessing(data, dictionary):
    data['Annotated Tweet'] = data['Annotated Tweet'].str.replace('[^\x00-\x7f]', ' ')
    data['Annotated Tweet'] = data['Annotated Tweet'].apply(lambda s: " ".join(
        [dictionary[word.lower()] if word.lower() in dictionary.keys() else word for word in s.split()]))
    data['Annotated Tweet'] = data['Annotated Tweet'].str.replace('\w+:\/{2}[\d\w-]+(\.[\d\w-]+)*(?:(?:\/[^\s/]*))*',
                                                                  ' ')
    special_stopwords = ['omg', 'lol', 'umm', 'hmm', 'ah', 'oh', 'yea']
    special_stopwords.extend(stopwords.words('english'))
    data["Annotated Tweet"] = data["Annotated Tweet"].apply(
        lambda s: " ".join([word for word in s.split() if word not in special_stopwords]))
    data['Annotated Tweet'] = data['Annotated Tweet'].str.replace('<[^<]+?>', ' ')
    data['Annotated Tweet'] = data['Annotated Tweet'].str.replace('^(!|\.|,|<|>|:|;|{|}|\||~)$', ' ')
    data['Annotated Tweet'] = data['Annotated Tweet'].str.replace('\d+', ' ')
    data['Annotated Tweet'] = data['Annotated Tweet'].str.replace('\n\n', ' ')
    data['Annotated Tweet'] = data['Annotated Tweet'].str.replace('\n', ' ')
    data['Annotated Tweet'] = data['Annotated Tweet'].str.replace('[^\w\s]', ' ')
    data["Annotated Tweet"] = data["Annotated Tweet"].str.replace('\s+', ' ')
    data["Annotated Tweet"] = data["Annotated Tweet"].apply(
        lambda s: re.compile(r"(.)\1{1,}", re.DOTALL).sub(r"\1\1", s))
    data["Annotated Tweet"] = data["Annotated Tweet"].apply(lambda s: re.sub("([a-z])([A-Z])", "\g<1> \g<2>", s))
    data["Annotated Tweet"] = data["Annotated Tweet"].apply(lambda s: re.sub(r"^\s+", "", s))
    return data

def negative_word_conversion():
    dictionary = {}
    f = open("/Users/ashwin/Desktop/change.txt")
    lines = f.readlines()
    f.close()
    for i in lines:
        try:
            tmp = i.replace('"', '').replace(',', '').replace('\n', ' ').split(':')
            dictionary[tmp[0]] = tmp[1]
        except:
            print(tmp)
            print(z)
    return dictionary

def model(model):
    clf = False
    if model == "svm":
        clf = Pipeline([('vect', CountVectorizer(ngram_range=(1, 3))),
                        ('tfidf', TfidfTransformer()),
                        ('clf', LinearSVC(class_weight="balanced"))])
    elif model == "bayes":
        clf = Pipeline([('vect', CountVectorizer(ngram_range=(1, 3))),
                        ('tfidf', TfidfTransformer()),
                        ('clf', MultinomialNB())])
    elif model == "knn":
        clf = Pipeline([('vect', CountVectorizer(ngram_range=(1, 3))),
                        ('tfidf', TfidfTransformer()),
                        ('clf', KNeighborsClassifier())])
    elif model == "sgd":
        clf = Pipeline([('vect', CountVectorizer(ngram_range=(1, 3))),
                        ('tfidf', TfidfTransformer()),
                        ('clf', linear_model.SGDClassifier(class_weight="balanced"))])
    elif model == "log_reg":
        clf = Pipeline([('vect', CountVectorizer(ngram_range=(1, 3))),
                        ('tfidf', TfidfTransformer()),
                        ('clf', linear_model.LogisticRegression(class_weight="balanced"))])

    return clf

def score_reducer(accum, new_score, divisor):
    return {"Precision": new_score["Precision"] / divisor + accum["Precision"],
            "Recall": new_score["Recall"] / divisor + accum["Recall"],
            "Fscore": new_score["Fscore"] / divisor + accum["Fscore"]}

def KFoldCrossValidation(model, tweet, type, fold, stratified=None):
    positive_score = []
    normal_score = []
    negative_score = []
    accuracy = []
    random_index = np.random.permutation(len(tweet))
    bucket_size = int(len(tweet) / fold)
    balance = len(tweet) % fold

    if not stratified:
        for x in range(1, fold + 1):
            test = random_index[(x - 1) * bucket_size:x * bucket_size]
            train = np.concatenate([random_index[:(x - 1) * bucket_size], random_index[x * bucket_size:]])
            model.fit(tweet.iloc[train], type.iloc[train])
            predict = model.predict(tweet.iloc[test])
            precision, recall, fscore, support = precision_recall_fscore_support(type.iloc[test], predict,
                                                                                labels=[1, 0, -1])
            positive_score.append({"Precision": precision[0], "Recall": recall[0], "Fscore": fscore[0]})
            normal_score.append({"Precision": precision[1], "Recall": recall[1], "Fscore": fscore[1]})
            negative_score.append({"Precision": precision[2], "Recall": recall[2], "Fscore": fscore[2]})
            accuracy.extend(predict == type.iloc[test])
    else:
        stratify = StratifiedKFold(n_splits=fold, shuffle=True)
        for train, test in stratify.split(tweet, type):
            model.fit(tweet.iloc[train], type.iloc[train])
            predict = model.predict(tweet.iloc[test])
            precision, recall, fscore, support = precision_recall_fscore_support(type.iloc[test], predict,
                                                                                labels=[1, 0, -1])
            positive_score.append({"Precision": precision[0], "Recall": recall[0], "Fscore": fscore[0]})
            normal_score.append({"Precision": precision[1], "Recall": recall[1], "Fscore": fscore[1]})
            negative_score.append({"Precision": precision[2], "Recall": recall[2], "Fscore": fscore[2]})
            accuracy.extend(predict == type.iloc[test])

    positive = functools.reduce(functools.partial(score_reducer, divisor=fold), positive_score,
                                {"Precision": 0, "Recall": 0, "Fscore": 0})
    neutral = functools.reduce(functools.partial(score_reducer, divisor=fold), normal_score,
                               {"Precision": 0, "Recall": 0, "Fscore": 0})
    negative = functools.reduce(functools.partial(score_reducer, divisor=fold), negative_score,
                                {"Precision": 0, "Recall": 0, "Fscore": 0})
    accuracy = np.mean(accuracy)

    print("Positive: ", positive)
    print("Neutral: ", neutral)
    print("Negative: ", negative)
    print("Accuracy: %f" % accuracy)

def print_class(test, train, output, val):
    print_result = {'id': test['id'], 'Class': train}
    print_df = pd.DataFrame(print_result)
    np.savetxt(output, print_df, fmt=['%d', '%d'], delimiter=';;', header=val, comments='')

if __name__ == "__main__":
    # Obama Data
    obama_filtered = filter_obama(r"/Users/ashwin/Desktop/training-Obama-Romney-tweets.xlsx", dropnan=True)
    # Romney Data
    romney_filtered = filter_romney(r"/Users/ashwin/Desktop/training-Obama-Romney-tweets.xlsx", dropnan=True)

    # Pre Processing of both Obama and Romney datasets
    obama_filtered = PreProcessing(obama_filtered, negative_word_conversion())
    romney_filtered = PreProcessing(romney_filtered, negative_word_conversion())

    # Model 1: SVM
    obama_dataframe = model("svm")
    romney_dataframe = model("svm")
    print("--------Model 1 - Support Vector Machine----------")
    print("OBAMA:")
    KFoldCrossValidation(obama_dataframe, obama_filtered['Annotated Tweet'], obama_filtered['Class'], 10,
                         stratified=True)
    print("\nROMNEY:")
    KFoldCrossValidation(romney_dataframe, romney_filtered['Annotated Tweet'], romney_filtered['Class'], 10,
                         stratified=True)

    # Model 2: Naive Bayes
    obama_dataframe = model("bayes")
    romney_dataframe = model("bayes")
    print("\n--------Model 2 - Multinominal Naive Bayes----------")
    print("OBAMA:")
    KFoldCrossValidation(obama_dataframe, obama_filtered['Annotated Tweet'], obama_filtered['Class'], 10,
                         stratified=True)
    print("\nROMNEY:")
    KFoldCrossValidation(romney_dataframe, romney_filtered['Annotated Tweet'], romney_filtered['Class'], 10,
                         stratified=True)

    # Model 3: K-Nearest Neighbour
    obama_dataframe = model("knn")
    romney_dataframe = model("knn")
    print("\n--------Model 3 - K Nearest Neighbour----------")
    print("OBAMA:")
    KFoldCrossValidation(obama_dataframe, obama_filtered['Annotated Tweet'], obama_filtered['Class'], 10,
                         stratified=True)
    print("\nROMNEY:")
    KFoldCrossValidation(romney_dataframe, romney_filtered['Annotated Tweet'], romney_filtered['Class'], 10,
                         stratified=True)

    # Model 4: SGD
    obama_dataframe = model("sgd")
    romney_dataframe = model("sgd")
    print("\n--------Model 4 - Stochastic Gradient Descent----------")
    print("OBAMA:")
    KFoldCrossValidation(obama_dataframe, obama_filtered['Annotated Tweet'], obama_filtered['Class'], 10,
                         stratified=True)
    print("\nROMNEY:")
    KFoldCrossValidation(romney_dataframe, romney_filtered['Annotated Tweet'], romney_filtered['Class'], 10,
                         stratified=True)

    # Model 5: Logistic Regression
    obama_dataframe = model("log_reg")
    romney_dataframe = model("sgd")
    print("\n--------Model 5 - Logistic Regression----------")
    print("OBAMA:")
    KFoldCrossValidation(obama_dataframe, obama_filtered['Annotated Tweet'], obama_filtered['Class'], 10,
                         stratified=True)
    print("\nROMNEY:")
    KFoldCrossValidation(romney_dataframe, romney_filtered['Annotated Tweet'], romney_filtered['Class'], 10,
                         stratified=True)


import os
import json
import pandas as pd
import string
import random
from audio_utils import audioread, audiowrite
from tqdm import tqdm
from shutil import copyfile
from noise_utils import apply_noise
from text_utils import normalizeString

class Config:
    def __init__(self, config_path = 'config.json'):
        with open(config_path,'r') as f:
            cfg = json.load(f)

        self.snr = cfg['snr']
        self.noise_types = cfg['noise_types']
        self.transcriptions_path = cfg['transcriptions']
        self.noise_dir = cfg['noise_dir']
        self.clean_speech_dir = cfg['clean_speech_dir']
        self.results_dir = cfg['results_dir']
        self.noise_paths = []
        self.clean_paths = []
        self.config_path = config_path
        self.transcriptions = self.prepareTranscriptions()
        self.preparePaths()

    def prepareTranscriptions(self):
        df = pd.read_csv(self.transcriptions_path, sep="\t")
        transcriptions = {}

        for file in os.listdir(self.clean_speech_dir):
            file_name = os.path.splitext(file)[0]
            item = df[df['path'] == file_name]

            if(len(item)==1):
                sentence = item['sentence'].ravel()[0]
                transcriptions[os.path.join(self.clean_speech_dir,file)] = normalizeString(sentence)

        return transcriptions

    def preparePaths(self):
        for file in os.listdir(self.clean_speech_dir):
            self.clean_paths.append(os.path.join(self.clean_speech_dir,file))

        for _type in os.listdir(self.noise_dir):
            if _type in self.noise_types:
                for file in os.listdir(os.path.join(self.noise_dir, _type)):
                    self.noise_paths.append(os.path.join(self.noise_dir, _type, file))

        random.shuffle(self.noise_paths)

    def getRandomNoiseFile(self):
        return self.noise_paths[random.randint(0,len(self.noise_paths)-1)]


from zen.util.benchmark import Benchmark

import networkx as nx
import zen as zn
import igraph as ig
import random, math

class MinimumSpanningTreeBenchmark(Benchmark):

	def __init__(self):
		Benchmark.__init__(self,'Minimum Spanning Tree')
		self.NUM_NODES = 2000
		self.P = 0.05
		self.weights = []

	def setup(self):
		# build a network
		self.ER_G = zn.Graph()

		for i in range(self.NUM_NODES):
			self.ER_G.add_node(i)

		# add edges
		for i in range(self.NUM_NODES):
			for j in range(i+1,self.NUM_NODES):
				r = random.random()
				w = random.random()
				if r < self.P:
					w = math.ceil(w*10.0)
					self.ER_G.add_edge_(i,j, weight=w)
					self.weights.append(w)

	def bm_zen(self):
		zn.spanning.minimum_spanning_tree(self.ER_G)

	def setup_networkx(self):
		self.nx_ER_G = nx.Graph()

		for i in self.ER_G.nodes_iter():
			self.nx_ER_G.add_node(i)

		for i,j, w in self.ER_G.edges_iter(weight=True):
			self.nx_ER_G.add_edge(i,j, weight=w)

	def bm_networkx(self):
		nx.minimum_spanning_tree(self.nx_ER_G)

	def setup_igraph(self):
		self.ig_ER_G = ig.Graph()
		self.ig_ER_G.add_vertices(len(self.ER_G))
		self.ig_ER_G.add_edges(self.ER_G.edges())
		# Edges are enumerated twice, so while building the weight vector we make sure that the opposite-direction weight wasn't added
		wweights = {}
		for i,j in self.ig_ER_G.get_edgelist():
			if i in wweights and j not in wweights[i]:
				wweights[i][j] = True
				self.weights.append(self.ER_G.weight(i, j))

	def bm_igraph(self):
		self.ig_ER_G.spanning_tree(self.weights)


N = int(input())
# nums = [int(input()) for _ in range(N)]
'''
nums.sort()
'''

'''
# bubble sort
for i in range(N - 1):
    for j in range(N - i - 1):
        if nums[j] > nums[j + 1]:
            nums[j], nums[j + 1] = nums[j + 1], nums[j]
'''

'''
# selection sort
for i in range(N - 1):
    min = 1000
    idx = i
    for j in range(i + 1, N):
        if nums[idx] > nums[j]:
            idx = j
    if i != idx:
        nums[i], nums[idx] = nums[idx], nums[i]
'''

# print(*nums, sep='\n')

# counting sort
cnt = [0 for _ in range(2002)]

for _ in range(N):
    cnt[int(input()) + 1001] += 1

for i in range(len(cnt)):
    if cnt[i]:
        print(i - 1001)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 19 14:40:51 2020

@author: jinlingxing
"""
from typing import List
class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
    #define a function dfs
        def dfs(i, adjacency, flags):
            #if flag[i] = -1, node i has been visted, return true
            #if flag[i] = 1, node i have been visted twice, there is a cycle, return false
            if flags[i] == -1:
                return True
            if flags[i] == 1:
                return False
            #set flag[i] = 1, it means it has been visted in this loop
            flags[i] = 1
            #iterate all the adjacency node of node i, if it has a loop, return false
            for j in adjacency[i]:
                if not dfs(j,adjacency,flags):
                    return False
            #when we vistied all the adjacency nodes of node i, set flag[i]=-1 and return true
            flags[i] = -1
            return True
        #adjacency = [[]]*numCourses #[[],[]]
        #flags = [0]*numCourses#[0,0]
        adjacency = [[] for _ in range(numCourses)]
        flags = [0 for _ in range(numCourses)]
        for cur, pre in prerequisites:
            adjacency[pre].append(cur)
        for i in range(numCourses):
            if not dfs(i, adjacency, flags):
                return False
        return True

if __name__ == "__main__":
    sol = Solution()
    numCourses = 2
    pre = [[1,0]]
    sol.canFinish(numCourses, pre)


from helpers.common import flattenList, flattenRenderList, playRenderGroup
from gvtriangle import GVTriangle
from gvheader import GVHeader
from manim import *

class GVRender:
  METHOD_LOOKUP = {
    "Triangle": ('c', lambda fargs: GVTriangle(labels=fargs[0])), #consructor
    "Ang": ('im', lambda diag, fargs: diag.setAngle(*fargs)), #instance method
    "Mid": ('im', lambda diag, fargs: diag.setMidpoint(*fargs)), #instance method
    "Line": ('im', lambda diag, fargs: diag.setLine(*fargs)), #instance method
    "ParallelLine": ('im', lambda diag, fargs: diag.setParallelLine(*fargs)), #instance method
    "Title": ('c', lambda fargs: GVHeader(title=fargs[0])),
    "ShowAngles": ('im', lambda diag, fargs: diag.showAngles(*fargs)), #instance method
    "HighlightAngles": ('im', lambda diag, fargs: diag.highlightAngles(*fargs)), #instance method
  }

  def __init__(self, scene):
    self.gi_list = [] # list of geometric instances
    self.scene = scene

  def renderProblem(self, problem):
    for item in problem:
      if isinstance(item, list):
        self.initSection(item[0])
        self.constructSection(item[1])

    self.render()

  def initSection(self, section_name):
    if section_name == 'proof':
      self.gi_list[-1].setSection(section_name)

  def constructSection(self, section_def):
    for step in section_def:
      fname = step['function']
      fargs = step['args']
      method_type, method = self.METHOD_LOOKUP[fname]
      if method_type == 'c':
        self.gi_list.append(method(fargs))
      if method_type == 'im':
        gi = self.gi_list[-1]  #geometry instance
        gi.addComment(step['comments'] if 'comments' in step else None)
        method(gi, fargs)

  def renderSection(self, section_name):
    if section_name == "header":
      self.renderHeader()
    elif section_name == "diag":
      self.renderDiag()
    else:
      self.renderProof()

  def scaleToLeft(self, vg):
    fh = config.frame_height * 0.8
    fw = config.frame_width * 0.5

    if vg.height > fh:
      vg.scale_to_fit_height(fh)

    if vg.width > fw:
      vg.scale_to_fit_width(fw)

    vg.move_to([-config.frame_width/4, 0, 0])

  def scaleToRight(self, vg):
    fh = config.frame_height * 0.8
    fw = config.frame_width * 0.5

    if vg.height > fh:
      vg.scale_to_fit_height(fh)

    if vg.width > fw:
      vg.scale_to_fit_width(fw)

    vg.move_to([config.frame_width/4, 0, 0])

  def render(self):
    self.renderHeader()
    self.renderDiag()
    self.renderProof()

  def renderHeader(self):
    #render header
    header_gi = self.gi_list[0]
    header_mo_list = flattenList(header_gi.render_list)
    mo = header_mo_list[0]
    self.scene.play(FadeIn(mo))
    self.scene.play(mo.animate.shift((0,3.5,0)))

  def renderDiag(self):
    pass

  def renderProof(self):
    diag_gi = self.gi_list[1]
    diag_mo_list = flattenRenderList(diag_gi.diag_render_list)
    diag_mo_list.extend(flattenRenderList(diag_gi.proof_render_list))
    vg = VGroup(*diag_mo_list)
    self.scaleToLeft(vg)
    # but render diag objects
    for render_group in diag_gi.diag_render_list:
      playRenderGroup(self.scene, render_group)

    # but render proof objects
    clist = flattenRenderList(diag_gi.comment_list)
    vg = VGroup(*clist)
    self.scaleToRight(vg)

    for index, render_group in enumerate(diag_gi.proof_render_list):
      if len(diag_gi.comment_list[index]) > 0:
        playRenderGroup(self.scene, diag_gi.comment_list[index])

      playRenderGroup(self.scene, render_group)


import os

import parse_bytearray
import parse_singledat

here = os.getcwd() + '\\pyspad\\rawdata\\'
files = os.listdir(here)
for i in range(0, len(files)):
    files[i] = here + files[i]

for i in files:
    i = here + i

[here + s for s in files]
files2 = sorted(files, key=os.path.getmtime)
files2[-1]

npix = 512
fnum = 1000
fignore = 10
newest = 'D:\\dropbox\\Dropbox\\Projects\\SpadProbe\\git\\pyspad\\rawdata\\sample0001_unparsed_9'

[img, scatt, goodframes] = parse_singledat.Parse(npix, fnum, fignore, newest).get_data()


import cv2

# カスケード分類器の読み込み
face_cascade = cv2.CascadeClassifier('/Users/lina/Desktop/keio_pg_test/opencv-master/data/haarcascades/haarcascade_frontalface_default.xml')
smile_cascade = cv2.CascadeClassifier('/Users/lina/Desktop/keio_pg_test/opencv-master/data/haarcascades/haarcascade_smile.xml')

# カメラの起動
cap = cv2.VideoCapture(0)

while True:
    # フレームの取得
    ret, frame = cap.read()

    # グレースケール変換
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # 顔の検出
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)

    # 顔の数をカウント
    num_faces = len(faces)

    # 顔を四角で囲む
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
        cv2.putText(frame, 'face', (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)

        # Crop face region
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = frame[y:y+h, x:x+w]

        # Detect smiles in face region
        smiles = smile_cascade.detectMultiScale(roi_gray, 1.7, 22)

        # Draw rectangle around each smile
        for (sx, sy, sw, sh) in smiles:
            cv2.rectangle(roi_color, (sx, sy), (sx+sw, sy+sh), (0, 255, 255), 2)
            cv2.putText(roi_color, 'smile', (sx, sy-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 255), 2)

        # Check if smiles were detected
        if len(smiles) > 0:
            # Add code to be executed when a smile is detected
            print('笑顔見つけた！')

    # 画像内に人の顔の数を表示
    cv2.putText(frame, 'Number of faces: ' + str(num_faces), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

    # 画像の表示
    cv2.imshow('frame', frame)

    # 終了キーの取得
    key = cv2.waitKey(1)

    # 終了キーが押されたらループを抜ける
    if key == 27:
        break

# カメラの停止
cap.release()
cv2.destroyAllWindows()


from django.core.mail import send_mail
from django.shortcuts import render
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404, render
from django.template import RequestContext
from datetime import date

from gammty.models import Nosotros, Objetivo, Cliente, Servicio, SSC_inscripcion
from gammty.forms import ContactoForm, SSCForm, SSCCrispyForm

def index(request):
	return render_to_response('main.html', {}, context_instance=RequestContext(request))

def nosotros_vista(request):
	nosotros = Nosotros.objects.all()
	objetivos = Objetivo.objects.filter(nosotros=nosotros)

	return render_to_response('nosotros.html', {
		'nosotros': nosotros,
		'objetivos': objetivos
		}, context_instance=RequestContext(request))

def quienes_somos_vista(request):
	return render_to_response('quienes.html', {}, context_instance=RequestContext(request))

def historia_vista(request):
	return render_to_response('historia.html', {}, context_instance=RequestContext(request))

def sem_aguilas_vista(request):
	return render_to_response('seminar-aguilas.html', {}, context_instance=RequestContext(request))

def sem_qim_vista(request):
	return render_to_response('seminar-QiM.html', {}, context_instance=RequestContext(request))

def dia_aguilas_vista(request):
	return render_to_response('dia-aguilas.html', {}, context_instance=RequestContext(request))

def cipa_caipa_vista(request):
	return render_to_response('CIPA-CAIPA.html', {}, context_instance=RequestContext(request))

def servicios_vista(request):
	servicios = Servicio.objects.order_by('tipo')

	return render_to_response('servicios.html', {
		'servicios': servicios
		}, context_instance=RequestContext(request))

def escuela_vista(request):
	return render_to_response('escuela.html', {}, context_instance=RequestContext(request))

"""
def  clientes_vista(request):
	clientes = Cliente.objects.all()

	return render_to_response('clientes.html', {
		'clientes': clientes
		}, context_instance=RequestContext(request))
"""

def ssc_vista(request):
	return render_to_response('ssc.html', {}, context_instance=RequestContext(request))

def ssc_form_vista(request):
	if request.method == 'POST':
		form = SSCForm(request.POST)

		if form.is_valid():
			new_ssc = SSC_inscripcion()
			new_ssc.nombre = form.cleaned_data['nombre']
			new_ssc.matricula = form.cleaned_data['matricula']
			new_ssc.semestre = form.cleaned_data['semestre']
			new_ssc.carrera = form.cleaned_data['carrera']
			new_ssc.correo = form.cleaned_data['correo']
			new_ssc.telefono = form.cleaned_data['telefono']
			new_ssc.porque = form.cleaned_data['porque']
			new_ssc.como_te_enteraste = form.cleaned_data['como_te_enteraste']
			new_ssc.comentarios = form.cleaned_data['comentarios']
			new_ssc.para_semestre = form.cleaned_data['para_semestre']
			new_ssc.save()

			return HttpResponseRedirect('javascript:{alert("Su información ha sido enviada.");}')

	else:
		form = SSCForm()

	return render(request, 'ssc_forma.html', {
		'form': form,
		})

	# if datetime.datetime.now().month>=6:
		# ssc_solicitantes = SSC.objects.filter(fecha__year=datetime.datetime.now().year, para_semestre='ago')
	# else:
		# ssc_solicitantes = SSC.objects.filter(fecha__year=datetime.datetime.now().year, para_semestre='ene')

	# return render_to_response('solicitantes_ssc.html', {
		# 'solicitantes_ssc': ssc_solicitantes
		# }, context_instance=RequestContext(request))

def ssc_crispy_form_vista(request):
	if request.method == 'POST':
		form = SSCForm(request.POST)

		if form.is_valid():
			new_ssc = SSC_inscripcion()
			new_ssc.nombre = form.cleaned_data['nombre']
			new_ssc.matricula = form.cleaned_data['matricula']
			new_ssc.semestre = form.cleaned_data['semestre']
			new_ssc.carrera = form.cleaned_data['carrera']
			new_ssc.correo = form.cleaned_data['correo']
			new_ssc.telefono = form.cleaned_data['telefono']
			new_ssc.porque = form.cleaned_data['porque']
			new_ssc.como_te_enteraste = form.cleaned_data['como_te_enteraste']
			new_ssc.comentarios = form.cleaned_data['comentarios']
			new_ssc.para_semestre = form.cleaned_data['para_semestre']
			new_ssc.save()

			return HttpResponseRedirect('javascript:{alert("Su información ha sido enviada.");}')

	else:
		form = SSCCrispyForm()

	return render(request, 'ssc_crispy_forma.html', {'form': SSCCrispyForm()})

def ssc_list_vista(request):
	pass

def contacto_vista(request):
	if request.method == 'POST':
		form = ContactoForm(request.POST)

		if form.is_valid():
			send_mail('Contacto GAM Mty', form.cleaned_data['message'], form.cleaned_data['sender'],
    ['gerardo.chapa.q@gmail.com'], fail_silently=False)

			return HttpResponseRedirect('javascript:{alert("Su mensaje ha sido enviado.");}')

	else:
		form = ContactoForm()

	return render(request, 'contacto.html', {
		'form': form,
		})


from tkinter import *
root = Tk()

canvas = Canvas(root, width = 300, height = 300)
canvas.pack()

def draw_rectangle():
    size = 0
    distance = 10
    for i in range(1, 7):
        size = i * 10
        distance += size - 10
        square = canvas.create_rectangle(distance, distance, distance + size, distance + size, fill = 'purple')

draw_rectangle()
root.mainloop()


# -*- coding: utf-8 -*-
from setuptools import setup, find_packages

version = '1.1'

setup(
    name='matem.congresos',
    version=version,
    description="Congres type for the Institute of Mathematics",
    long_description=open('README.rst').read() + '\n' +
    open('docs/CHANGES.txt').read(),
    # Get more strings from
    # http://www.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Plone',
        'License :: OSI Approved :: GNU General Public License (GPL)',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
    ],
    platforms='Any',
    author='Informática Académica',
    author_email='informatica.academica@im.unam.mx',
    url='https://github.com/imatem/matem.congresos',
    license='GPL',
    namespace_packages=['matem'],
    packages=find_packages('src', exclude=['ez_setup']),
    package_dir={'': 'src'},
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        'plone.api',
        'setuptools',
        'Products.DataGridField',
        'collective.datagridcolumns',
        'collective.z3cform.datagridfield',
    ],
    extras_require={
        'develop': [
        ],
        'test': [
            'plone.app.testing',
        ],
    },
    entry_points="""
    # -*- Entry points: -*-
    [z3c.autoinclude.plugin]
    target = plone
    """,
)


from __future__ import annotations
from typing import TYPE_CHECKING
from objects.object_type import ObjectType
from primitives.graphical_object import GraphicalObject
if TYPE_CHECKING:
    from cairo import Context
    from primitives.matrix import Matrix, Vector2

class Wireframe2D(GraphicalObject):
    # Define Constructor
    def __init__(self, *points: Vector2) -> None:
        # Call Super Constructor
        super().__init__()
        # Check Points Length
        if len(points) < 3:
            raise ValueError("Wireframe2D need 3 or more points to be defined")
        # Define Attributes
        self.points = list(points)
        # Define Pipeline Attributes
        self.pipeline_points = list(points)
    def __str__(self) -> str:
        desc = "Wireframe2D\n"
        for point in (self.pipeline_points if self.in_pipeline else self.points):
            desc += "\t" + point.__str__() + "\n"
        return desc
    # Type Definition
    @staticmethod
    def get_type() -> ObjectType:
        return ObjectType.WIREFRAME_2D
    # Define Pipeline Methods
    def pipeline(self):
        # Reset Pipeline Points
        self.pipeline_points = list(self.points)
        # Call Super
        super().pipeline()
    def pipeline_apply(self):
        if self.in_pipeline:
            # Persist Pipeline Points
            self.points = list(self.pipeline_points)
            # Call Super
            super().pipeline_apply()
    # Define Methods
    def draw(self, cairo: Context):
        # Get Points
        points = self.pipeline_points if self.in_pipeline else self.points
        # Set Color
        cairo.set_source_rgba(*self.color)
        # Cast points into homogeneus space and match them with screen coords
        xy_points = [ point.as_tuple() for point in points ]
        xy_points_len = len(xy_points)
        # Draw segments in canvas
        for (x, y), idx in zip(xy_points, range(xy_points_len)):

            # Check non starting the drawing
            if idx != 0:
                 # Draw normal line
                cairo.line_to(x, y)
                # Check ending the drawing
                if idx == (xy_points_len - 1):
                    # Close drawing
                    (x_init, y_init) = xy_points[0]
                    cairo.line_to(x_init, y_init)
            else:
                # Move to polygon start
                cairo.move_to(x, y)
        # Show result
        cairo.stroke()

    def transform(self, transformation: Matrix):
        # Transform points
        if self.in_pipeline:
            # Pipeline
            self.pipeline_points = [
                (point.as_vec3(1) * transformation).try_into_vec2()
                for point in self.pipeline_points
            ]
        else:
            # Raw Transform
            self.points = [
                (point.as_vec3(1) * transformation).try_into_vec2()
                for point in self.points
            ]
        # Return Chain
        return self

    def get_center_coords(self) -> Vector2:
        # Get Points
        points = self.pipeline_points if self.in_pipeline else self.points
        # Get Avg Point
        points_len_mult = 1 / len(points)
        avg_coords = Vector2(0, 0)
        for point in points:
            avg_coords += point
        avg_coords *= points_len_mult
        return avg_coords.try_into_vec2()


# it return value automatically without return statement, just like arrow function in javascript
numbersList = [5,1,4,9,36,78]

squire = lambda x: x*x
print(squire(6))

add = lambda x,y: x+y;
print(add(4,7))

double_it_fn = lambda x: x*2
doubled_number = map(double_it_fn,numbersList) # map is smilar to reduce function in javascript
print(list(doubled_number)) # map return a map object, so convert it to list to make it readable
tripled_number = map(lambda x: 3*x,numbersList)
print(list(tripled_number))

bigger_numbers = filter(lambda num: num > 10,numbersList)
print(list(bigger_numbers))

users = [{'name':'sakib', 'age':36},{'name':'rakib', 'age':32},{'name':'nazil', 'age':30},]
senior_user = filter(lambda user: user['age']>30,users)
print(list(senior_user))


import os

import openpyxl
from openpyxl import load_workbook
import cv2
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from tqdm import tqdm
from ultralytics import YOLO

# create all subfolders
def create_folders(path: str):
    if not os.path.exists(path):
        os.makedirs(path)

def create_plot(r, result_data):
    filename = r.path.split("/")[-1]
    date = "_".join(result_data["date"].split("_")[::-1])
    folder = "./claw_segmentation/data/ergebnisse/grafiken/" + date + "/"
    create_folders(folder)
    if os.path.exists(folder + filename):
        return
    im_array = r.plot(
        boxes=False, labels=False, probs=False
    )  # plot a BGR numpy array of predictions
    plt.imshow(cv2.cvtColor(im_array, cv2.COLOR_BGR2RGB), resample=True)
    # Add annotations in the center of the inner claw, with a large white font

    plt.annotate(
        "Innere Klaue",
        xy=result_data["inner_claw_center"],
        color="white",
        size=14,
        backgroundcolor="black",
    )
    plt.annotate(
        "Äußere Klaue\n"
        + "Relative Fläche: "
        + str(result_data["relative_claw_area"]),
        xy=result_data["outer_claw_center"],
        color="white",
        size=14,
        backgroundcolor="black",
    )

    left_right = "links" if result_data["left"] else "rechts"
    plt.title(f"{result_data['animal_id']} Fuß {left_right} - {date}")
    plt.savefig(folder + filename)
    plt.close()

def get_subfolders(folder):
    return [f.path + "/" for f in os.scandir(folder) if f.is_dir()]

def get_data_from_mask(r):
    current_shape = r.masks.data[0].shape
    original_shape = r.orig_shape
    scale_factor_x = original_shape[0] / current_shape[0]
    scale_factor_y = original_shape[1] / current_shape[1]
    if "L" in r.path.split("/")[-1]:
        left = True
    elif "R" in r.path.split("/")[-1]:
        left = False
    else:
        raise ValueError("Could not determine left or right claw")

    filename = r.path.split("/")[-1]
    data = dict(
        animal_id=filename.split("V")[0],
        left=left,
        date=r.path.split("/")[-2],
    )
    claw_mask1 = r.masks.data[0].numpy()
    claw_mask2 = r.masks.data[1].numpy()

    highest_point1 = claw_mask1.max(axis=1).argmax()
    highest_point2 = claw_mask2.max(axis=1).argmax()

    claw1_is_inner = highest_point1 < highest_point2 and data["left"]
    inner_claw = claw_mask1 if claw1_is_inner else claw_mask2
    outer_claw = claw_mask2 if claw1_is_inner else claw_mask1

    data["outer_claw_area"] = outer_claw.sum()
    data["inner_claw_area"] = inner_claw.sum()
    data["relative_claw_area"] = round(
        data["outer_claw_area"] / data["inner_claw_area"], 4
    )

    # compute center of claw as an x, y tuple
    data["inner_claw_center"] = (
        inner_claw.max(axis=0).argmax() * scale_factor_x,
        inner_claw.mean(axis=1).argmax() * scale_factor_y,
    )

    data["outer_claw_center"] = (
        outer_claw.max(axis=0).argmax() * scale_factor_x,
        outer_claw.mean(axis=1).argmax() * scale_factor_y,
    )
    return data

def process_result(r):
    if "V" not in r.path.split("/")[-1]:
        return None
    result_data = get_data_from_mask(r)
    create_plot(r, result_data)
    # Reverse the date to get the date in the format YYYY-MM-DD
    date_yyyy_mm_dd = "_".join(result_data["date"].split("_")[::-1])
    row = {
        "Ohrmarkennummer": result_data["animal_id"],
        "Datum": date_yyyy_mm_dd,
        "Relative Klauenfläche (=Aussen/Innen)": result_data[
            "relative_claw_area"
        ],
        "Klaue": "links" if result_data["left"] else "rechts",
    }
    return row

def create_result_plots(df, result_folder, category):
    # Make a boxplot over time for the relative claw area in seaborn
    sns.boxplot(
        hue=category,
        x="Mess Nr.",
        y="Relative Klauenfläche (=Aussen/Innen)",
        data=df,
    )
    plt.grid()
    plt.savefig(result_folder + f"{category}_boxplot.png")
    plt.close()

    sns.lineplot(
        hue=category,
        x="Mess Nr.",
        y="Relative Klauenfläche (=Aussen/Innen)",
        data=df,
        err_style="bars",
    )
    plt.grid()
    plt.savefig(result_folder + f"{category}_lineplot.png")
    plt.close()

    sns.histplot(
        hue=category,
        x="Relative Klauenfläche (=Aussen/Innen)",
        data=df,
        kde=True,
    )
    plt.grid()
    plt.savefig(result_folder + f"{category}_histplot.png")
    plt.close()

def add_categories(df, folder):
    # Read the "Klauenerziehung_Urliste.xlsx" file and also get the background color data
    excel_file = folder + "Klauenerziehung_Urliste.xlsx"
    wb = load_workbook(excel_file, data_only=True)
    start_row = 7
    end_row = 82
    sh = wb["Liste"]
    categories = []
    ear_tags = df["Ohrmarkennummer"].unique()
    for row_num in range(start_row, end_row):
        cell = sh[f"E{row_num}"]
        if cell.value in ear_tags:
            color_in_hex = cell.fill.start_color.index  # this gives you Hexadecimal value of the color
            if color_in_hex == "00000000":
                group = "Weiß"
            else:
                group = "Gelb"
            categories.append({"Ohrmarkennummer": cell.value, "Gruppe": group})
    categories_df = pd.DataFrame(categories)
    df.drop(columns=["Gruppe"], inplace=True, errors="ignore")
    # Add group data to the dataframe
    df = df.join(categories_df.set_index("Ohrmarkennummer", drop=True), on="Ohrmarkennummer", how="left")
    return df

model = YOLO("./claw_segmentation/models/yolov8_claw_segmentation_v0.pt")

folder = "./claw_segmentation/data/"
subfolders = get_subfolders(folder)

result_folder = "./claw_segmentation/data/ergebnisse/"
result_file = result_folder + "ergebnisse.csv"
todo_dates = set(map(lambda x: x.split("/")[-2], get_subfolders(folder)))

# Get dates from resutlts file if exists
if os.path.exists(result_file):
    res_df = pd.read_csv(result_folder + "ergebnisse.csv", dtype=str)
    res_df["Relative Klauenfläche (=Aussen/Innen)"] = res_df[
        "Relative Klauenfläche (=Aussen/Innen)"
    ].astype(float)
    result_dates = set(res_df["Datum"].unique())
    dates = set()
    for date in result_dates:
        date = "_".join(date.split("_")[::-1])
        dates.add(date)
    todo_dates = todo_dates - dates
else:
    res_df = pd.DataFrame()

plot_folder = result_folder + "grafiken/"
create_folders(plot_folder)

rows = []

all_res = []
for subfolder in todo_dates:
    if "ergebnisse" in subfolder:
        continue
    try:
        res = model.predict(folder + subfolder, conf=0.1, iou=0.45, max_det=2)
    except FileNotFoundError:
        print("FileNotFoundError for folder: ", folder + subfolder)
        continue
    all_res.extend(res)

for r in tqdm(all_res):
    row = process_result(r)
    if row is not None:
        rows.append(row)

df = pd.DataFrame(
    rows,
    columns=[
        "Ohrmarkennummer",
        "Datum",
        "Klaue",
        "Relative Klauenfläche (=Aussen/Innen)",
    ],
    dtype=object,
)
df["Mess Nr."] = df.groupby(["Ohrmarkennummer", "Klaue"]).cumcount() + 1
# Combine results with existing results
df = pd.concat([res_df, df], ignore_index=True).drop_duplicates()
df = df.sort_values(by=["Ohrmarkennummer", "Klaue", "Datum"]).reset_index(
    drop=True
)
df["Mess Nr."] = df.groupby(["Ohrmarkennummer", "Klaue"]).cumcount() + 1

df = add_categories(df, folder)
df.to_csv(result_file, mode="w", index=False)

create_result_plots(df, result_folder, "Klaue")
create_result_plots(df, result_folder, "Gruppe")

# Join left an right claw into one row
df_joined = df.pivot_table(
    index=["Ohrmarkennummer", "Datum", "Mess Nr.", "Gruppe"],
    values=["Relative Klauenfläche (=Aussen/Innen)"],
    columns=["Klaue"],
)

df_joined.columns = df_joined.columns.droplevel(0)
df_joined = df_joined.reset_index()
sns.jointplot(
    x="links",
    y="rechts",
    hue="Gruppe",
    data=df_joined,
)
plt.grid()
plt.savefig(result_folder + "links_rechts_jointplot.png")