"""
Author: Adam Knowles
Version: 0.1
Name: config.py
Description: Set up global config, variables and objects

GitHub Repository: https://github.com/Pharkie/AdamGalactic/
License: GNU General Public License (GPL)
"""
from galactic import GalacticUnicorn  # type: ignore
from picographics import PicoGraphics, DISPLAY_GALACTIC_UNICORN as DISPLAY  # type: ignore
from pimoroni_i2c import PimoroniI2C  # type: ignore
from breakout_bme68x import BreakoutBME68X, STATUS_HEATER_STABLE, FILTER_COEFF_3, STANDBY_TIME_1000_MS, OVERSAMPLING_16X, OVERSAMPLING_2X, OVERSAMPLING_1X   # type: ignore

# GU stuff
gu = GalacticUnicorn()
picoboard = PicoGraphics(DISPLAY)

DISPLAY_WIDTH = 53

# Pen colours
PEN_BLACK = picoboard.create_pen(0, 0, 0)
PEN_YELLOW = picoboard.create_pen(255, 105, 0)
PEN_GREY = picoboard.create_pen(96, 96, 96)
PEN_BLUE = picoboard.create_pen(153, 255, 255)
PEN_GREEN = picoboard.create_pen(38, 133, 40)

picoboard.set_font("bitmap6")

# BME680 stuff
PINS_BREAKOUT_GARDEN = {"sda": 4, "scl": 5}  # type: ignore

i2c = PimoroniI2C(**PINS_BREAKOUT_GARDEN)
bme = BreakoutBME68X(i2c) # Declare once. If you put this in a function and keep calling it, it will crash the panel after a while. # type: ignore
# Configure the BME680. These are defaults anyway, but here in case I want to change them later
bme.configure(FILTER_COEFF_3, STANDBY_TIME_1000_MS, OVERSAMPLING_16X, OVERSAMPLING_2X, OVERSAMPLING_1X) # type: ignore

# Other stuff
from wifi_creds import WIFI_SSID, WIFI_PASSWORD

CHANGE_INTERVAL = 6 # seconds

base_x = 9
char_width = 5
char_height = 5

clock_digits_x = [base_x, base_x + 1 * char_width, base_x + (2 * char_width) + 2,
               base_x + (3 * char_width) + 2, base_x + (4 * char_width) + 5,
               base_x + (5 * char_width) + char_width]
clock_digit_all_y = -1

custom_message_gist_URL = "https://gist.githubusercontent.com/Pharkie/b411446bb13e8d9c73500d09b66862a2/raw/CustomMessage.txt"
next_buses_URL = "https://api.tfl.gov.uk/Line/141/Arrivals/490008766S"
piccadilly_line_status_URL = "https://api.tfl.gov.uk/Line/piccadilly/Status"

DEFAULT_CUSTOM_MESSAGE = "Next stop: Penmaenmawr"

# Make a global instance of the cache object, so it can be used by multiple modules.
# Variable is populated in cache_online_data.main()
my_cache = None  # type: ignore

CACHE_REFRESH_INTERVAL = 60  # seconds

CACHE_EXPIRY_TIMES = (
    ("next_buses", 1 * 60),  # 1 minutes
    ("line_status", 5 * 60),  # 10 minutes
    ("custom_message", 60 * 60),  # 60 minutes
)


from _decimal import Decimal

from django.db import models
from app_users.models import User
from djmarket import settings
from django.utils.translation import gettext_lazy as _

class Product(models.Model):
    class Meta:
        ordering = ["name", "price"]
        verbose_name_plural = _('product')
        verbose_name = _('product')

    name = models.CharField(max_length=100, verbose_name=_('name'))
    description = models.TextField(null=False, blank=True, verbose_name=_('description'))
    price = models.DecimalField(default=0, max_digits=8, decimal_places=2, verbose_name=_('price'))
    created_at = models.DateTimeField(auto_now_add=True, verbose_name=_('created'))
    sales = models.PositiveIntegerField(default=0, verbose_name=_('sales'))

    def __str__(self):
        return f"Product(pk={self.pk}, name={self.name!r})"

class Promotion(models.Model):
    promotion = models.CharField(max_length=200, verbose_name=_('promotion'))
    product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name=_('product'))

class Offer(models.Model):
    offer = models.CharField(max_length=200, verbose_name=_('offer'))

class Order(models.Model):
    created_at = models.DateTimeField(auto_now_add=True, verbose_name=_('created'))
    user = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name=_('buyer'))
    products = models.ManyToManyField(Product, related_name="orders", verbose_name=_('items'))
    order_price = models.DecimalField(default=0, max_digits=8, decimal_places=2, verbose_name=_('order price'))

    class Meta:
        verbose_name_plural = _('orders')
        verbose_name = _('order')

class Market(models.Model):
    class Meta:
        verbose_name_plural = _('markets')
        verbose_name = _('market')

    name = models.CharField(max_length=30, verbose_name=_('market name'))
    created_at = models.DateTimeField(auto_now_add=True, null=True, verbose_name=_('created'))

    def __str__(self):
        return f"{_('created')}(pk={self.pk}, {_('name')}={self.name!r})"

class ItemPosition(models.Model):
    class Meta:
        verbose_name_plural = _('products item')
        verbose_name = _('product item')

    product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, verbose_name=_('product name'))
    amount = models.PositiveIntegerField(verbose_name='кол-во')
    market = models.ForeignKey(Market, on_delete=models.CASCADE, null=True, verbose_name=_('in market'))

class Cart(object):
    def __init__(self, request):
        self.session = request.session
        cart = self.session.get(settings.CART_SESSION_ID)
        if not cart:
            cart = self.session[settings.CART_SESSION_ID] = {}
        self.cart = cart

    def add(self, product, market_id, position_id, quantity=1, update_quantity=False):
        product_id = str(product.id)
        if product_id not in self.cart:
            self.cart[product_id] = {'quantity': 0,
                                     'price': str(product.price),
                                     'position_id': position_id,
                                     'market_id': market_id}
        if update_quantity:
            self.cart[product_id]['quantity'] = quantity
        else:
            self.cart[product_id]['quantity'] += quantity

        self.save()

    def save(self):
        self.session[settings.CART_SESSION_ID] = self.cart
        self.session.modified = True

    def remove(self, product):
        """Удаление товара из карзины"""
        product_id = str(product.id)
        if product_id in self.cart:
            del self.cart[product_id]
            self.save()

    def __iter__(self):
        """Перебор элементов в карзине и получение продуктов из базы данных"""
        full_price = [0]
        product_ids = self.cart.keys()
        products = Product.objects.filter(id__in=product_ids)
        for product in products:
            self.cart[str(product.id)]['product'] = product

        for item in self.cart.values():
            item['price'] = Decimal(item['price'])
            item['total_price'] = item['price'] * int(item['quantity'])
            full_price[0] += item['total_price']
            yield item

    def __len__(self):
        """Подсчет всей суммы в корзине"""
        full_price = [0]
        for item in self.cart.values():
            item['total_price'] = float(item['price']) * int(item['quantity'])
            full_price[0] += int(item['total_price'])
        return full_price[0]

    def clear(self):
        del self.session[settings.CART_SESSION_ID]
        self.session.modified = True


from tqdm import tqdm

import torch
import numpy as np
from scipy import linalg

from transformers import BertTokenizer, BertModel

BERT_MODEL = 'bert-large-cased'
BERT_MAX_LENGTH = 512

def evaluate_frechet_bert_distance(hypo_texts, ref_texts):
    print('Evaluating Frechet Bert Distance...')

    tokenizer = BertTokenizer.from_pretrained(BERT_MODEL, do_lower_case=False)
    bert = BertModel.from_pretrained(
        BERT_MODEL, output_hidden_states=True).to('cuda')

    features = get_features(hypo_texts, tokenizer, bert)
    ref_features = get_features(ref_texts, tokenizer, bert)

    results = {
        'n_hypo': len(hypo_texts),
        'n_ref': len(ref_texts)
    }

    dist = []
    for layer in range(bert.config.num_hidden_layers + 1):
        mu, sigma = get_mu_sigma(features[layer])
        ref_mu, ref_sigma = get_mu_sigma(ref_features[layer])

        dist.append(np.sqrt(
            calculate_frechet_distance(ref_mu, ref_sigma, mu, sigma)))

    assert dist[0] < 1e-5

    for l, r in [(1, 8), (9, 16), (17, 24)]:
        results[f'fbd_{l}-{r}'] = sum(dist[l:r + 1])

    return results

def get_features(texts, tokenizer, bert):
    all_features = [[] for _ in range(bert.config.num_hidden_layers + 1)]
    for text in tqdm(texts):
        input_ids = tokenizer.encode(text, max_length=BERT_MAX_LENGTH)

        with torch.no_grad():
            outputs = bert(torch.tensor([input_ids]).to('cuda'))

        for layer in range(bert.config.num_hidden_layers + 1):
            all_features[layer].append(outputs[2][layer][0][0].tolist())

    for layer in range(bert.config.num_hidden_layers + 1):
        all_features[layer] = np.array(all_features[layer])

    return all_features

def get_mu_sigma(features):
    mu = np.mean(features, axis=0)
    sigma = np.cov(features, rowvar=False)
    return mu, sigma

# https://arxiv.org/pdf/1706.08500.pdf
# from https://github.com/bioinf-jku/TTUR/blob/master/fid.py
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):
    """Numpy implementation of the Frechet Distance.
    The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)
    and X_2 ~ N(mu_2, C_2) is
            d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).
    Stable version by Dougal J. Sutherland.
    Params:
    -- mu1 : Numpy array containing the activations of the pool_3 layer of the
             inception net ( like returned by the function 'get_predictions')
             for generated samples.
    -- mu2   : The sample mean over activations of the pool_3 layer, precalcualted
               on an representive data set.
    -- sigma1: The covariance matrix over activations of the pool_3 layer for
               generated samples.
    -- sigma2: The covariance matrix over activations of the pool_3 layer,
               precalcualted on an representive data set.
    Returns:
    --   : The Frechet Distance.
    """

    mu1 = np.atleast_1d(mu1)
    mu2 = np.atleast_1d(mu2)

    sigma1 = np.atleast_2d(sigma1)
    sigma2 = np.atleast_2d(sigma2)

    assert mu1.shape == mu2.shape, "Training and test mean vectors have different lengths"
    assert sigma1.shape == sigma2.shape, "Training and test covariances have different dimensions"

    diff = mu1 - mu2

    # product might be almost singular
    covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)
    if not np.isfinite(covmean).all():
        msg = "fid calculation produces singular product; adding %s to diagonal of cov estimates" % eps
        print(msg)
        offset = np.eye(sigma1.shape[0]) * eps
        covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))

    # numerical error might give slight imaginary component
    if np.iscomplexobj(covmean):
        if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):
            m = np.max(np.abs(covmean.imag))
            raise ValueError("Imaginary component {}".format(m))
        covmean = covmean.real

    tr_covmean = np.trace(covmean)

    return diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean


# В большой текстовой строке подсчитать количество встречаемых слов и вернуть
# 10 самых частых. Не учитывать знаки препинания и регистр символов.
# За основу возьмите любую статью из википедии или из документации к языку.

string = '– На самом деле они в меня не верят, – сказал Ом. \
– Но… \
– Такое случалось и раньше, – продолжала черепашка. – Много-много раз. \
Тебе известно, что Абраксас нашел Потерянный Город Ии? А в нем очень странные изваяния. \
По его словам, вера постоянно смещается. Люди начинают с веры в бога, \
а заканчивают верой в структуру. \
– Я не понимаю… \
– Тогда позволь мне объяснить это другими словами. Я – твой бог, верно? \
– Да. \
– И ты обязан мне повиноваться. \
– Да. \
– Хорошо. А теперь возьми камень и убей Ворбиса. \
Брута не пошевелился. \
– Ты меня слышал? – уточнил Ом. \
– Но он… он… квизиция… \
– Теперь ты понимаешь, что я имею в виду, – хмыкнула черепашка. – Сейчас \
ты больше боишься его, чем меня. Вот здесь Абраксас говорит: \
«Вакруг Бога фармируется Абалочка из малящихся, Циримоний, Сданий, \
Жрицов и Властей, и в канце канцов Бох Умерает. И эта может остатся незамеченым…» \
"Мелкие боги" (c) Терри Пратчет '

whitelist = set('абвгдеёжзийклмнопрстуфхцчшщъыьэюя АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ')
white_string = (''.join(filter(whitelist.__contains__, string))).strip().lower()

words_list = white_string.split()
result_list = {}
for word in words_list:
    n = 0
    if word not in result_list:
        n = words_list.count(word)
        result_list[word] = n

sorted_list = sorted(result_list.items(), key=lambda item: item[1], reverse=True)

for i in range(10):
    print(sorted_list[i])


from highway_env.envs.highway_exit_BV_env import *
from highway_env.vehicle.behavior import IDM_Continuous_Vehicle
class HighwayExitEnvNDD_Continuous(HighwayExitEnvNDD_DBV):
    def __init__(self,config):
        super(HighwayExitEnvNDD_Continuous,self).__init__(config)

    def _make_vehicles(self, background_vehicle=None,
                       auto_vehicle=(0, global_val.initial_CAV_position, global_val.initial_CAV_speed)):
        """
            Populate a road with several vehicles on the highway and on the merging lane, as well as an ego-vehicle.
        :return: the ego-vehicle
        background_vehicle: Each item has [lane,position,velocity]
        """
        ego_vehicle = MDPVehicle(self.road, self.road.network.get_lane(("a", "b", auto_vehicle[0])).position(auto_vehicle[1], 0), velocity=auto_vehicle[2])
        self.road.vehicles.append(ego_vehicle)
        self.vehicle = ego_vehicle
        other_vehicles_type = IDM_Continuous_Vehicle

        if self.generate_vehicle_mode == "Random":
            for _ in range(self.config["vehicles_count"]):
                new_vehicle = self.create_random_acc_training(other_vehicles_type)
                if new_vehicle:
                    self.road.vehicles.append(new_vehicle)

    def _simulate(self, cav_action=None, bv_action=None):
        """
            Perform several steps of simulation with constant action
        """
        for k in range(int(self.SIMULATION_FREQUENCY // self.config["policy_frequency"])):
            if ((cav_action is not None) or (bv_action is not None)) and \
                    self.time % int(self.SIMULATION_FREQUENCY // self.config["policy_frequency"]) == 0:
                # Set the CAV and BV action
                self.vehicle.act(self.ACTIONS[cav_action])
                for i in range(len(self.controlled_bvs)):
                    bv = self.controlled_bvs[i]
                    bv.act(bv_action[i])
            #  when nothing happens, vehicle act nothing
            self.vehicle.act()
            self.road.act()
            self.road.step(1 / self.SIMULATION_FREQUENCY)
            self.time += 1
            # Automatically render intermediate simulation steps if a viewer has been launched
            self._automatic_rendering()
            road_crash_flag = False
            for vehicle in self.road.vehicles:
                if vehicle.crashed:
                    road_crash_flag = True
                    break
            if road_crash_flag:
                break
        self.enable_auto_render = False


from .apitask import APITask

from thing.models import APIKey, Character, CharacterConfig, CharacterDetails, Corporation

class APIKeyInfo(APITask):
    name = 'thing.api_key_info'

    def run(self, url, taskstate_id, apikey_id, zero):
        if self.init(taskstate_id, apikey_id) is False:
            return

        # Fetch the API data
        if self.fetch_api(url, {}) is False or self.root is None:
            return

        # Find the key node
        key_node = self.root.find('result/key')

        # Update access mask
        self.apikey.access_mask = int(key_node.attrib['accessMask'])

        # Update expiry date
        expires = key_node.attrib['expires']
        if expires:
            self.apikey.expires = self.parse_api_date(expires)
        else:
            self.apikey.expires = None

        # Update key type
        self.apikey.key_type = key_node.attrib['type']

        # Gather data
        characters = {}
        corporations = {}
        for row in key_node.findall('rowset/row'):
            characters[int(row.attrib['characterID'])] = (row.attrib['characterName'], int(row.attrib['corporationID']))
            corporations[int(row.attrib['corporationID'])] = row.attrib['corporationName']

        # Bulk query data
        char_map = Character.objects.select_related('config', 'corporation', 'details').in_bulk(characters.keys())
        corp_map = Corporation.objects.in_bulk(corporations.keys())

        # Create any new Corporation objects
        new_corps = []
        for corp_id, corp_name in corporations.items():
            if corp_id not in corp_map:
                new_corps.append(Corporation(
                    id=corp_id,
                    name=corp_name,
                ))

        Corporation.objects.bulk_create(new_corps)

        # Create any new Character objects
        new_chars = []
        new_configs = []
        new_details = []
        for char_id, (char_name, corp_id) in characters.items():
            if char_id not in char_map:
                new_chars.append(Character(
                    id=char_id,
                    name=char_name,
                    corporation_id=corp_id,
                ))
                new_configs.append(CharacterConfig(character_id=char_id))
                new_details.append(CharacterDetails(character_id=char_id))

        # Fix any existing Character objects with missing Config/Details
        for char_id, char in char_map.items():
            try:
                config = char.config
            except:
                new_configs.append(CharacterConfig(character_id=char_id))
            else:
                if config is None:
                    new_configs.append(CharacterConfig(character_id=char_id))

            try:
                details = char.details
            except:
                new_details.append(CharacterDetails(character_id=char_id))
            else:
                if details is None:
                    new_details.append(CharacterDetails(character_id=char_id))

            # Handle name/corporation changes
            if char.name != characters[char.id][0] or char.corporation_id != characters[char.id][1]:
                char.name = characters[char.id][0]
                char.corporation_id = characters[char.id][1]
                char.save()

        Character.objects.bulk_create(new_chars)
        CharacterConfig.objects.bulk_create(new_configs)
        CharacterDetails.objects.bulk_create(new_details)

        # Account/Character key
        if self.apikey.key_type in (APIKey.ACCOUNT_TYPE, APIKey.CHARACTER_TYPE):
            self.apikey.corp_character = None

        # Corporation key
        elif self.apikey.key_type == APIKey.CORPORATION_TYPE:
            self.apikey.corp_character_id = characters.keys()[0]
            self.apikey.corporation_id = corporations.keys()[0]

        # Save any APIKey changes
        self.apikey.save()

        # Iterate over all APIKeys with this (keyid, vcode) combo
        for ak in APIKey.objects.filter(keyid=self.apikey.keyid, vcode=self.apikey.vcode):
            # Add characters to this APIKey
            ak.characters.add(*characters.keys())

            # Remove any missing characters from the APIKey
            for char in ak.characters.all():
                if char.id not in characters:
                    ak.characters.remove(char)

        return True


import json
from json.decoder import JSONDecodeError
from module import *

# Default values
class Settings:
    download_base_path = "videos"
    target_sem = None
    ignore_downloaded_video_extension = None

def load_extension(tree):
    ext = tree.get("ignore_downloaded_video_extension")
    if type(ext) is str:
        if not ext.startswith("."):
            print(
                "Warning: extensions should start with '.', but extension from\n"
                "         `ignore_downloaded_video_extension` = %r\n"
                "         does not have a leading '.'" % ext
            )
            ext = ".%s" % ext
            print("Interpreting extension as %r." % ext)
        Settings.ignore_downloaded_video_extension = ext
    elif ext is None:
        pass
    else:
        print(
            "Warning: invalid `ignore_downloaded_video_extension`, defaulting to %r."
            % Settings.ignore_downloaded_video_extension
        )

def load_settings():
    print("Loading settings from 'settings.json':")
    try:
        with open("settings.json") as f:
            tree = json.load(f)

        if "download_base_path" in tree:
            base_path = tree["download_base_path"]
            if type(base_path) is str:
                Settings.download_base_path = base_path
                print("Base path at %r." % base_path)
            else:
                print(
                    "Warning: `download_base_path` should be a string, but is %r."
                    % base_path
                )
                print(
                    "         Using default value of %r." % Settings.download_base_path
                )
        else:
            print("Warning: `download_base_path` is missing." % base_path)
            print("         Using default value of %r." % Settings.download_base_path)

        x = tree.get("target_sem", Settings.target_sem)

        if type(x) is dict:
            start_year = x.get("start_year")
            end_year = x.get("end_year")
            sem = x.get("sem")
            if all(type(x) is int for x in (start_year, end_year, sem)):
                Settings.target_sem = ModuleTime(start_year, end_year, sem)

            load_extension(tree)
        elif x is None:
            pass
        else:
            print("Warning: `target_sem` has invalid format.")
            print("         Using default value of %r." % Settings.target_sem)
    except FileNotFoundError:
        print("Warning: Configuration file 'settings.json' not found")
        print("         Using default values.")
    except (JSONDecodeError, ValueError) as e:
        print("Warning: Configuration file 'settings.json' has invalid JSON")
        print("         Using default values.")

    print("Target semester: %s." % (Settings.target_sem or "All"))
    if Settings.ignore_downloaded_video_extension:
        print(
            "Ignoring downloaded videos with extension %s."
            % Settings.ignore_downloaded_video_extension,
        )
    else:
        print("Not ignoring any downloaded videos.")
    print()

if __name__ == "__main__":
    load_settings()


import numpy as np
import matplotlib.pyplot as plt

#define anonymous functions for coefficient and exponent forms
x1 = lambda x: x**9 - 18*x**8 +144*x**7 - 672*x**6 + 2016*x**5 - 4032*x**4 + 5376*x**3 - 4608*x**2 +2304*x - 512
x2 = lambda x: (x - 2)**9

#define x input and evaluate function outputs
x = np.arange(1.92,2.08,0.001)
coeffOutput = x1(x)
expOutput = x2(x)

#plot figures
plt.figure(1)
plt.title("Output With Coefficients")
plt.xlabel("x")
plt.ylabel("y")
plt.plot(x,coeffOutput)

plt.figure(2)
plt.title("Output as Single Exponent Expression")
plt.xlabel("x")
plt.ylabel("y")
plt.plot(x,expOutput)

plt.show()


import numpy as np
import matplotlib.pyplot as plt
import random
from numpy import *
def loadData(fileName):
    dataMat=[]
    labelMat=[]
    with open(fileName) as fp:
        for line in fp.readlines():
            lineArr = line.split('\t')
            dataMat.append([float(lineArr[0]),float(lineArr[1])])
            labelMat.append(float(lineArr[2]))
    return dataMat,labelMat

def plotBestFit(dataIn, labelIn):
    n = shape(dataIn)[0]
    xcord1 = []
    ycord1 = []
    xcord2 = []
    ycord2 = []
    for i in range(n):
        if int(labelIn[i]) == 1:
            xcord1.append(dataIn[i][0])
            ycord1.append(dataIn[i][1])
        else :
            xcord2.append(dataIn[i][0])
            ycord2.append(dataIn[i][1])
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.scatter(xcord1,ycord1,s = 30,c = 'red',marker='s')
    ax.scatter(xcord2,ycord2,s= 30,c ='green')
    # x = arange(-3.0, 3.0, 0.1)
    # print(shape(x))
    # y = (-weights[0]-weights[1]*x)/weights[2]
    # print(shape(y))
    # ax.plot(x, y.transpose())
    plt.xlabel('x')
    plt.ylabel('y')
    plt.show()

def selectJrand(i,m):
    j = i
    while (j == i):
        j = int(random.uniform(0,m))
    return j

def clipAlpha(aj,L,H):
    if aj > H:
        return H
    if aj < L :
        return L
    return aj

def smoSimple(dataIn,classLabels,C,toler,maxIter):
    dataMatrix = mat(dataIn)
    labelMatrix = mat(classLabels).transpose()
    b = 0
    m,n = shape(dataMatrix)
    alpha = mat(zeros((m,1)))
    # print(labelMatrix)
    iter = 0
    while iter < maxIter:
        alphaPairChanged = 0
        for i in range(m):
            # f(xi) = sum(aj*yj*k(xj,xi)+b)
            # fXi = float(multiply(alpha,labelMatrix).T*(dataMatrix*dataMatrix[i,:].T)) + b
            # print(fXi)
            fXi = float(multiply(alpha,labelMatrix).T*(dataMatrix*dataMatrix[i,:].T)) +b
            # ei = f(xi)-yi
            Ei =fXi - float(labelMat[i])
            ## yi*Ei,why?
            uVi =  labelMatrix[i] *Ei
            ## violate KKT
            ## choose second alpha
            if ( uVi< -toler and alpha[i] < C) or (uVi> toler and alpha[i] > 0) :
                j =  selectJrand(i,m)
                fXj = float(multiply(alpha,labelMatrix).T*(dataMatrix*dataMatrix[j,:].T)) +b
                Ej = fXj - float(labelMatrix[j])
                alphaIOld = alpha[i].copy()
                alphaJOld = alpha[j].copy()
                # print(alphaIOld,alphaJOld)
                ## cut value
                L = None
                H = None
                if labelMatrix[i] != labelMatrix[j] :
                    L = max(0,alpha[j]-alpha[i])
                    H = min(C,C+alpha[j]-alpha[i])
                else :
                    L = max(0,alpha[j]+alpha[i]-C)
                    H = min(C,alpha[j]+alpha[i])
                # print ('L == H',L,H)
                if L == H :
                    print ('L == H',L,H)
                    continue

                ## k11 + k22 - 2*k12
                eta  = 2.0*dataMatrix[i,:]*dataMatrix[j,:].T - dataMatrix[i,:]*dataMatrix[i,:].T - dataMatrix[j,:] * dataMatrix[j,:].T

                if eta >=0 :
                    print('eta >= 0 ')
                    continue
                print(Ei,Ej)
                ## aj_new = aj_old - yj*(Ei-Ej)/eta
                alpha[j] -= labelMatrix[j] *(Ei-Ej)/eta
                alpha[j] = clipAlpha(alpha[j],L,H)
                ##
                if (abs(alpha[j] - alphaJOld) < 0.00001):
                    print('j not moving enough',alpha[j] , alphaJOld)
                    continue
                ## ai_new = ai_old + yi*yj*(-aj_new+aj_old)
                alpha[i] += labelMatrix[i]*labelMatrix[j]*(-alpha[j]+alphaJOld)

                ## update b

                # b1_new = -Ei-yi*Kii(ai_new-ai_old) -yj*Kji*(aj_new-aj_old)+b_old
                b1 = b -Ei -labelMatrix[i]*dataMatrix[i,:]*dataMatrix[i,:].T*(alpha[i]-alphaIOld)-labelMatrix[j]*dataMatrix[i,:]*dataMatrix[j,:].T*(alpha[j]-alphaJOld)
                # b2_new
                b2 = b -Ej-labelMatrix[i]*dataMatrix[i,:]*dataMatrix[j,:].T*(alpha[i]-alphaIOld)-labelMatrix[j]*dataMatrix[j,:]*dataMatrix[j,:].T*(alpha[j]-alphaJOld)

                if alpha[i] < C and alpha[i] > 0 :
                    b = b1
                elif alpha[j] < C and alpha[i] >0:
                    b = b2
                else :
                    b = (b1+b2)/2.0

                alphaPairChanged +=1

                print('iter :%d ,i : %d,pairChanged :%d'%(iter,i,alphaPairChanged))

        if (alphaPairChanged == 0):
            iter += 1
        else :
            iter = 0

        print('iteration number : %d '%(iter))

    return b,alpha

# class OptStruct:
#     def __init__(self,dataIn,classLabels,C,toler):
#         self.X = dataIn
#         self.labelMatrix = classLabels
#         self.C = C
#         self.toler = toler
#         self.m = shape(dataIn)[0]
#         self.alpha = mat(zeros((self.m,1)))
#         self.b = 0
#         self.eCache = mat(zeros((self.m,2)))
#     def calcEk(os,k):
#         fXk = float(multiply(os.alpha,os.labelMatrix).T *(os.X*os.X[k,:].T)) +os.b
#         Ek = fXk-float(os.labelMatrix[k])
#         return Ek
#     def selectJ(i,os,Ei):

dataMat ,labelMat = loadData('testSet.txt')
# print(dataMat)
# plotBestFit(dataMat,labelMat)
b,alphas = smoSimple(dataMat, labelMat, 0.6, 0.001, 40)
print(b,alphas[alphas>0])


import MeCab, math
import numpy as np

document = [] # 単語レベルのデータを格納する変数
tf_lst = [] # TF（頻出度）を格納する変数
idf_lst = [] # IDF（希少度）を格納する変数
tfidf_lst = [] # 代表値（代表性）を格納数する変数
cosSim_lst = [] # Cos類似度を格納する変数
rep_lst = [] # 単語のTF-IDF値を文でまとめた値を格納
ap_lst = [] # 特徴度を文でまとめた値を格納

# 1文に対するTFを求める。
def appearance(tagger): # 行リスト
    # 出現数をカウントする
    text = tagger.copy()
    appearances_list = []
    length = len(text)
    for i in range(length):
        num = 1 # 単語の出現数
        j = 0
        for j in range(length):
            if i == j: continue # 同じ場所はカウントしない
            if text[i] == text[j]:
                #text.pop(j) # 比較済みのものは削除
                num+=1 # カウント
        appearances_list.append(num)
    return appearances_list

def wordcnt(document):
    sum = 0
    for s in document: sum += len(s)
    return sum

def cosSim(v1, v2):
    return np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))

def median(i):
    i = i.copy()
    list.sort(i)
    return i[int(len(i)/2)-1]

# 文書ファイル読み込み
with open("TEXT.txt", "r", encoding="utf-8") as f:
    text = f.read()

####### テキスト整形 #######
text = text.replace("\n", "").replace("―", "")
text = text.split("。")
text.pop() # 最後の空の配列を削除
sentence_length = len(text)
print("Sentence：", str(sentence_length))

####### 単語で分割 #######
for sentence in text:
    tagger = MeCab.Tagger("-Owakati")
    tagger = tagger.parse(sentence)
    tagger = tagger.split(" ")
    tagger.remove("\n")
    document.append(tagger)

print("word：", wordcnt(document))

####### TF（頻出度）を求める #######
for sentence in document:
    freq = appearance(sentence) # 単語の出現数
    tf_lst.append([i/len(freq) for i in freq]) # 頻出度を格納する

####### IDF（希少度）を求める #######
for i in range(sentence_length):
    sentence_idf = []
    for word in document[i]: # document > sentence > word
        cnt = 1
        for j in range(sentence_length):
            if i == j: continue
            if word in document[j]: cnt += 1
        sentence_idf.append( math.log(sentence_length / cnt) ) # log(全行数 / その単語が出現する行数)
    idf_lst.append(sentence_idf)

print("TF list Size：", len(tf_lst))
print("IDF list Size：", len(idf_lst))

####### TF-IDF値（特徴度）を求める #######
for i in range(len(tf_lst)):
    tfidf = []
    for j in range(len(tf_lst[i])):
        tfidf.append(tf_lst[i][j] * idf_lst[i][j])
    tfidf_lst.append(tfidf)

print("TF-IDF list Size：", len(tfidf_lst))

####### 文の代表値を求める #######
for _tfidf in tfidf_lst:
    rep_sum = 0
    for rep in _tfidf:
        rep_sum += rep # 単語のTF-IDF値を足し合わせる
    rep_lst.append(rep_sum)
print("Max of TF-IDF：", max(rep_lst))
print("Min of TF-IDF：", min(rep_lst))

####### Cos類似度を求める #######
res = 0
for i in range(len(tfidf_lst)):
    cosSim_words = []
    for j in range(len(tfidf_lst)):
        # 0を加えてベクトルの数を合わせる
        if len(tfidf_lst[i]) < len(tfidf_lst[j]):
            for k in range(len(tfidf_lst[j])-len(tfidf_lst[i])): tfidf_lst[i].append(0)
        elif len(tfidf_lst[i]) > len(tfidf_lst[j]):
            for k in range(len(tfidf_lst[i])-len(tfidf_lst[j])): tfidf_lst[j].append(0)
        # Cos類似度計算
        res = cosSim(tfidf_lst[i], tfidf_lst[j])
        cosSim_words.append(res)
        # ゼロベクトルの削除
        while 0 in tfidf_lst[i]: tfidf_lst[i].remove(0)
        while 0 in tfidf_lst[j]: tfidf_lst[j].remove(0)
    # 単語ベクトルのCos類似度の平均
    sum = 0
    for cw in cosSim_words: sum += cw
    cosSim_lst.append(cw/len(cosSim_words))
print("Cos Sim list Size：",len(cosSim_lst))

####### 代表値とCos類似度から特徴度を求める #######
ap_lst = [rep_lst[i] * (1-cosSim_lst[i]) for i in range(len(rep_lst))]

####### 要約をする（特徴度最大） #######
# 1行目：特徴度が最大な文をつ選ぶ
for i in range(len(rep_lst)):
    if max(rep_lst) == rep_lst[i]:
        print("TF-IDF：{:.5f}, Cos Sim：{:.5f} | {}".format(rep_lst[i], cosSim_lst[i], text[i]))
        break

# 2行目：特徴度が大きく、Cos類似度が低い文を選ぶ
# 代表値と(1 - Cos類似度)を掛け合わせることによって特徴を維持しつつベクトルを1つにすることができる。最大値を選ぶ。
# 1からCos類似度を引くことによって代表値に重みを持たせる。
for i in range(len(rep_lst)):
    if min(ap_lst) == rep_lst[i] * (1-cosSim_lst[i]):
        print("TF-IDF：{:.5f}, Cos Sim：{:.5f} | {}".format(rep_lst[i], cosSim_lst[i], text[i]))
        break

# 3行目：特徴度が大きく、Cos類似度が低い文を選ぶ
cosSim_lst.pop(i) # 最も低いCos類似度を削除
rep_lst.pop(i)    # 同じ場所を削除して合わせる
text.pop(i)       # 同じ場所を削除して合わせる
ap_lst.pop(i)
for i in range(len(rep_lst)):
    if min(ap_lst) == rep_lst[i] * (1-cosSim_lst[i]):
        print("TF-IDF：{:.5f}, Cos Sim：{:.5f} | {}".format(rep_lst[i], cosSim_lst[i], text[i]))
        break


import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
import io
import time

cap = cv.VideoCapture(0)
cap.set(4,1920)
cap.set(3,1080)
cap.set(5, 30)

beats = [0]*120
secs = [time.time()]*120

fig  = plt.figure()
graph = fig.add_subplot(111)

l = []
ret = True
while ret:
    ret, img = cap.read()
    img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    face_img = img[300:400, 660:760]

    beats = beats[1:] + [np.average(face_img)]
    secs = secs[1:] + [time.time()]
    graph.plot(secs,beats)

    #GRAPH PLOTTING  (https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.html)
    fig.canvas.draw()
    beat_monitor = np.fromstring(fig.canvas.tostring_rgb(),dtype=np.uint8, sep='')
    beat_monitor = beat_monitor.reshape(fig.canvas.get_width_height()[::-1] + (3,))
    plt.cla()
    #GRAPH PLOTTING

    cv.imshow("hearbeat",beat_monitor)
    l.append(np.average(beats))
    cv.imshow('skin_frame', face_img)
    if cv.waitKey(1) & 0xFF == ord('q'):
        break

lp = np.array(l)
print(np.average(lp))
cap.release()
cv.destroyAllWindows()


bl_info = {
    "name": "Face counter",
    "description": "Counts the amount of face each object has and prints it into a message box",
    "author": "mirkan1",
    "category": "3D View",
    "version": (0, 0, 1),
    "blender": (2, 80, 0),
    "location": "View3D > Object",
    #"warning": "This addon is still in development.",
    "wiki_url": "",
    "category": "Object" }

import bpy
arr = []
# for i in bpy.data.materials: i

def take_second(elem):
    return elem[1]

def fece_count(message = "", title = "FACE COUNT", icon = 'INFO'):
    objects = bpy.data.scenes[0].objects
    arr = []
    len_arr = []
    for i in objects:
        data = i.data
        try:
            arr.append([f'{data.name}', len(data.polygons)])
            print(f'object {data.name} has {len(data.polygons)} faces')
        except AttributeError:
            pass
    arr = sorted(arr, key=take_second, reverse=True)
    arr = [f'{i[0]}: {i[1]}' for i in arr]
    return arr

#for i in objects:
#    data = i.data
#    for j in data.materials:
#        print(j)
#        arr.append(j)

def ShowMessageBox(messages, title = "Message Box", icon = 'INFO'):
    def draw(self, context):
        for n in messages:
            self.layout.label(text=n)
    bpy.context.window_manager.popup_menu(draw, title = title, icon = icon)

#GUI
class MessageBoxOperator(bpy.types.Panel):
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'UI'
    bl_category = 'Face count'
    bl_options = {'HIDE_HEADER'}
    bl_idname = "ui.show_message_box"
    bl_label = "Minimal Operator"

    def draw(self, context):
        layout = self.layout

        # EXECUTE BUTTON
        row = layout.row()
        row.operator("object.ratio_save_button", text="Execute")

# EXECUTER BUTTON
class executeButton(bpy.types.Operator):
    bl_idname = "object.ratio_save_button"
    bl_label = "Ratio and savebutton functions"

    def execute(self, context):
        arr = fece_count()
        ShowMessageBox(arr)
        return {'FINISHED'}

classes = (
    executeButton,
    MessageBoxOperator,
)
addon_keymaps = []

def register():
    from bpy.utils import register_class
    # register_class(MessageBoxOperator)
    for cls in classes:
        register_class(cls)
    wm = bpy.context.window_manager
    kc = wm.keyconfigs.addon
    if kc:
        km = wm.keyconfigs.addon.keymaps.new(name='Object Mode', space_type='EMPTY')
        kmi = km.keymap_items.new(executeButton.bl_idname, 'T', 'PRESS', ctrl=True, shift=True)
        addon_keymaps.append((km, kmi))

        km = wm.keyconfigs.addon.keymaps.new(name='Screen Editing', space_type='EMPTY')
        kmi = km.keymap_items.new(executeButton.bl_idname, 'Q', 'PRESS', ctrl=True, shift=True)
        addon_keymaps.append((km, kmi))

def unregister():
    from bpy.utils import unregister_class
    for cls in classes:
        unregister_class(cls)

if __name__ == "__main__":
    register();


# -*- coding: utf-8 -*-
"""
Created on Wed May  2 16:06:08 2018

@author: richard
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
from matplotlib.colors import ListedColormap
from sklearn import neighbors
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
import datetime

# ---------------------原始数据处理--------------------------------
# 设置字体
font = FontProperties(fname='/Library/Fonts/Songti.ttc')

# 读取trainData.txt数据
data = np.loadtxt('../trainData.txt')
# print(data)
# label1 = np.array([0, 0])
# label2 = np.array([0, 0])
# for i in range(0,200):
#     data_label = data[i, 2]
#     if data_label == 1.0:
#         label1 = np.row_stack((label1, data[i, 0:2]))
#     else:
#         label2 = np.row_stack((label2, data[i, 0:2]))
#
# # label1和label2分类数据
# data_label1 = label1[1:, :]
# data_label2 = label2[1:, :]
#
# print(data_label1.shape)
# print(data_label2.shape)
#
# plt.scatter(data_label1[:, 0], data_label1[:, 1])
# plt.scatter(data_label2[:, 0], data_label2[:, 1])
# plt.xlabel("x")
# plt.ylabel("y")
# plt.tight_layout()
# plt.title("训练样本分布", fontproperties=font)
# # plt.savefig('../tex/img/fig1.png', dpi=800)
# plt.show()

# ---------------------KNN算法--------------------------------
x = data[:, 0:2]
y = data[:, 2]
y -= 1
# print(y)

# 拆分训练数据与测试数据
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.1, random_state=20180502)
# print(x_train.shape)
# print(y_test.shape)

# 训练KNN分类器

clf = neighbors.KNeighborsClassifier(n_neighbors=5)
# clf = neighbors.KNeighborsClassifier(n_neighbors=5, weights='distance', algorithm='kd_tree')

starttime = datetime.datetime.now()
clf.fit(x_train, y_train)
endtime = datetime.datetime.now()
time = endtime - starttime
print(time)

# 测试结果的打印
answer = clf.predict(x_test)
# print(answer)

# 准确率与召回率
precision, recall, thresholds = precision_recall_curve(y_test, answer)
probalility = clf.predict_proba(x_test)[:, 1]
# print(probalility)
# print(classification_report(y_test, answer, target_names=['1', '2']))

# 确认训练集的边界
h = .01
x_min, x_max = -6, 6
y_min, y_max = -6, 6
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                     np.arange(y_min, y_max, h))

# 将整个测试空间的分类结果用不同颜色区分开
answer = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
z = answer.reshape(xx.shape)
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA'])
plt.contourf(xx, yy, z, 1, cmap=cmap_light, alpha=0.5)

# 绘制训练样本
plt.scatter(x_train[:, 0], x_train[:, 1], c=y_train, cmap=plt.cm.Paired)
plt.scatter(x_test[:, 0], x_test[:, 1], c=y_test, cmap=plt.cm.Paired, alpha=0.5)
plt.xlabel('x')
plt.ylabel('y')
plt.title("2-Class classification (k = 5, weights = 'distance')")
plt.tight_layout()
# plt.savefig('../tex/img/fig10.png', dpi=800)
plt.show()


"""empty message

Revision ID: c058421705ec
Revises: 6c669d9ec3bd
Create Date: 2023-04-20 16:28:00.255353

"""
from datetime import datetime
from alembic import op
import sqlalchemy as sa
from sqlalchemy import orm, inspect
from os import listdir
from os.path import isfile, join

from app.config import UPLOAD_FOLDER, db

DeclarativeBase = orm.declarative_base()

# revision identifiers, used by Alembic.
revision = 'c058421705ec'
down_revision = '6c669d9ec3bd'
branch_labels = None
depends_on = None

class File(DeclarativeBase):
    __tablename__ = 'file'
    filename = sa.Column(sa.String, primary_key=True)
    created_at = sa.Column(sa.DateTime, nullable=False, default=datetime.utcnow)
    updated_at = sa.Column(sa.DateTime, nullable=False, default=datetime.utcnow)
    created_by = sa.Column(sa.Integer, sa.ForeignKey('user.id'), nullable=True)

class Recipe(DeclarativeBase):
    __tablename__ = 'recipe'
    id = sa.Column(sa.Integer, primary_key=True)
    photo = sa.Column(sa.String())

class Household(DeclarativeBase):
    __tablename__ = 'household'
    id = sa.Column(sa.Integer, primary_key=True)
    photo = sa.Column(sa.String())

class User(DeclarativeBase):
    __tablename__ = 'user'
    id = sa.Column(sa.Integer, primary_key=True)
    admin = sa.Column(sa.Boolean(), default=False)
    photo = sa.Column(sa.String())

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    inspector = inspect(db.engine)
    if not inspector.has_table("file"):
        op.create_table('file',
        sa.Column('filename', sa.String(), nullable=False),
        sa.Column('created_at', sa.DateTime(), nullable=False),
        sa.Column('updated_at', sa.DateTime(), nullable=False),
        sa.Column('created_by', sa.Integer(), nullable=True),
        sa.ForeignKeyConstraint(['created_by'], ['user.id'], name=op.f('fk_file_created_by_user')),
        sa.PrimaryKeyConstraint('filename', name=op.f('pk_file')),
        )
    # ### end Alembic commands ###
    bind = op.get_bind()
    session = orm.Session(bind=bind)

    try:
        filesInUploadFolder = [f for f in listdir(UPLOAD_FOLDER) if isfile(join(UPLOAD_FOLDER, f))]
        files = [File(filename=f) for f in filesInUploadFolder if not session.query(File.filename).filter(File.filename == f).first()]

        session.bulk_save_objects(files)
        session.commit()
    except FileNotFoundError as e:
        session.rollback()
    except BaseException as e:
        session.rollback()
        raise e

    with op.batch_alter_table('household', schema=None) as batch_op:
        batch_op.create_foreign_key(batch_op.f('fk_household_photo_file'), 'file', ['photo'], ['filename'])

    with op.batch_alter_table('recipe', schema=None) as batch_op:
        batch_op.create_foreign_key(batch_op.f('fk_recipe_photo_file'), 'file', ['photo'], ['filename'])

    with op.batch_alter_table('expense', schema=None) as batch_op:
        batch_op.create_foreign_key(batch_op.f('fk_expense_photo_file'), 'file', ['photo'], ['filename'])

    with op.batch_alter_table('user', schema=None) as batch_op:
        batch_op.create_foreign_key(batch_op.f('fk_user_photo_file'), 'file', ['photo'], ['filename'])

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('recipe', schema=None) as batch_op:
        batch_op.drop_constraint(batch_op.f('fk_recipe_photo_file'), type_='foreignkey')

    with op.batch_alter_table('household', schema=None) as batch_op:
        batch_op.drop_constraint(batch_op.f('fk_household_photo_file'), type_='foreignkey')

    with op.batch_alter_table('expense', schema=None) as batch_op:
        batch_op.drop_constraint(batch_op.f('fk_expense_photo_file'), type_='foreignkey')

    with op.batch_alter_table('user', schema=None) as batch_op:
        batch_op.drop_constraint(batch_op.f('fk_user_photo_file'), type_='foreignkey')

    op.drop_table('file')
    # ### end Alembic commands ###


import numpy as np
import sys

def get_optimal_partitions(latencies_benchmark, data_transfers_benchmark,data_transfers,is_fan_in):

    n = len(latencies_benchmark[0])
    k = len(data_transfers_benchmark)

    dp = np.zeros((n,k,k), dtype=float)
    for i in range(0,k):
        for j in range(0,k):
            dp[0][j][i] = latencies_benchmark[i][0]

    for i in range(1,n):
        for j in range(0,k):
            min_col = float(sys.maxsize)
            for x in range(0,k):
                if dp[i-1][x][j] != float(sys.maxsize):
                    min_col = min(min_col,dp[i-1][x][j])
            for v in range(0,k):
                data_tranfer_latency =float( get_data_transfer_value(data_transfers_benchmark, i, j, v, data_transfers,is_fan_in))
                if data_tranfer_latency != sys.maxsize and latencies_benchmark[v][i] != sys.maxsize and min_col!=sys.maxsize:
                    dp[i][j][v] = min_col + data_tranfer_latency + latencies_benchmark[v][i]
                else:
                    dp[i][j][v] = float(sys.maxsize)

    min_latency = float(sys.maxsize)
    min_i = 0
    min_j = 0
    cloud_indices = []
    for i in range(0,k):
        for j in range(0,k):
            if dp[n-1][i][j] < min_latency:
                min_i = i
                min_j = j
                min_latency = dp[n-1][i][j]

    cloud_indices.append(min_j)
    cloud_indices.append(min_i)
    for i in range(n-2,0,-1):
        min_lat = float(sys.maxsize)
        min_i_local = 0
        for j in range (0,k):
            if min_lat > dp[i][j][min_i]:
                min_lat = dp[i][j][min_i]
                min_i_local = j
        cloud_indices.append(min_i_local)
        min_i = min_i_local

    return list(reversed(cloud_indices)),min_latency

def get_data_transfer_value(data_transfers_benchmark, i, j, v, data_tranfers,is_fan_in):

    constraints_violated = evaluate_inter_cloud_data_transfer_constraints(data_tranfers, i, j, v)
    if constraints_violated:
        return float(sys.maxsize)

    else:
        if is_fan_in[i] and j != v:
            return data_transfers_benchmark[j][v] + data_transfers_benchmark[v][v]

        return data_transfers_benchmark[j][v]

def evaluate_inter_cloud_data_transfer_constraints(data_tranfers, i, j, v):
    flag = False
    if v == 1 and j == 0 and data_tranfers[i - 1] > 64:
        flag = True
    if v == 0 and j == 1 and data_tranfers[i - 1] > 256:
        flag = True
    if v==0 and j==0 and data_tranfers[i-1] > 256:
        flag = True

    return flag

# print(get_optimal_partitions([[5,8,14,2],[3,11,10,7]],[[0,12],[1,0]],[64,64,64],[False,False,False,False]))


#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2023/6/29 22:39
# @Author  : FywOo02
# @FileName: MainWidget.py
# @Software: PyCharm

from PyQt5.Qt import QWidget, QColor, QPixmap, QIcon, QSize, QCheckBox
from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QPushButton, QSplitter, \
    QComboBox, QLabel, QSpinBox, QFileDialog
from PaintBoard import PaintBoard

import tensorflow as tf
import numpy as np
try:
    import tensorflow.python.keras as keras
except:
    import tensorflow.keras as keras

class MainWidget(QWidget):

    def __init__(self, Parent=None):
        '''
        Constructor
        '''
        super().__init__(Parent)

        self.__InitData()  # init data
        self.__InitView()  # init view

    def __InitData(self):
        '''
                  init members
        '''
        self.__paintBoard = PaintBoard(self)
        # get the color list
        self.__colorList = QColor.colorNames()

    def __InitView(self):
        '''
                  init view
        '''
        self.setFixedSize(640, 480)
        self.setWindowTitle("Handwritten Digit Recognition")

        # Create a new horizontal layout as the main layout of this form
        main_layout = QHBoxLayout(self)

        # Set the main layout inner margin and control spacing to 10px
        main_layout.setSpacing(10)

        # Place the drawing board on the left side of the main screen
        main_layout.addWidget(self.__paintBoard)

        # Create a new vertical sublayout for placing keys
        sub_layout = QVBoxLayout()

        # Set the spacing between this child layout and the internal controls to 5px
        sub_layout.setContentsMargins(5, 5, 5, 5)

        splitter = QSplitter(self)
        sub_layout.addWidget(splitter)

        self.__btn_Recognize = QPushButton("Start Recognition")
        self.__btn_Recognize.setParent(self)
        self.__btn_Recognize.clicked.connect(self.on_btn_Recognize_Clicked)
        sub_layout.addWidget(self.__btn_Recognize)

        self.__btn_Clear = QPushButton("Clear")
        self.__btn_Clear.setParent(self)  # Set the parent object as the interface

        # Associating key press signals with the drawing board clear function
        self.__btn_Clear.clicked.connect(self.__paintBoard.Clear)
        sub_layout.addWidget(self.__btn_Clear)

        self.__btn_Quit = QPushButton("Quit")
        self.__btn_Quit.setParent(self)  # Set the parent object as the interface
        self.__btn_Quit.clicked.connect(self.Quit)
        sub_layout.addWidget(self.__btn_Quit)

        self.__btn_Save = QPushButton("Save")
        self.__btn_Save.setParent(self)
        self.__btn_Save.clicked.connect(self.on_btn_Save_Clicked)
        sub_layout.addWidget(self.__btn_Save)

        self.__cbtn_Eraser = QCheckBox("Eraser")
        self.__cbtn_Eraser.setParent(self)
        self.__cbtn_Eraser.clicked.connect(self.on_cbtn_Eraser_clicked)
        sub_layout.addWidget(self.__cbtn_Eraser)

        self.__label_penThickness = QLabel(self)
        self.__label_penThickness.setText("Thickness")
        self.__label_penThickness.setFixedHeight(20)
        sub_layout.addWidget(self.__label_penThickness)

        self.__spinBox_penThickness = QSpinBox(self)
        self.__spinBox_penThickness.setMaximum(20)
        self.__spinBox_penThickness.setMinimum(10)
        self.__spinBox_penThickness.setValue(20)  # Default thickness is 10
        self.__spinBox_penThickness.setSingleStep(5)  # Minimum change value of 2
        self.__spinBox_penThickness.valueChanged.connect(
            self.on_PenThicknessChange)  # Associated spinBox value change signal and function on_PenThicknessChange
        sub_layout.addWidget(self.__spinBox_penThickness)

        self.__label_penColor = QLabel(self)
        self.__label_penColor.setText("Color")
        self.__label_penColor.setFixedHeight(20)
        sub_layout.addWidget(self.__label_penColor)

        self.__comboBox_penColor = QComboBox(self)
        self.__fillColorList(self.__comboBox_penColor)  # Fill the drop-down list with various colors
        self.__comboBox_penColor.currentIndexChanged.connect(
            self.on_PenColorChange)  # Associating the current index change signal of the drop-down list with the function on_PenColorChange
        sub_layout.addWidget(self.__comboBox_penColor)

        main_layout.addLayout(sub_layout)  # Adding child layouts to the main layout

    def __fillColorList(self, comboBox):

        index_black = 0
        index = 0
        for color in self.__colorList:
            if color == "black":
                index_black = index
            index += 1
            pix = QPixmap(70, 20)
            pix.fill(QColor(color))
            comboBox.addItem(QIcon(pix), None)
            comboBox.setIconSize(QSize(70, 20))
            comboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents)

        comboBox.setCurrentIndex(index_black)

    def on_PenColorChange(self):
        color_index = self.__comboBox_penColor.currentIndex()
        color_str = self.__colorList[color_index]
        self.__paintBoard.ChangePenColor(color_str)

    def on_PenThicknessChange(self):
        penThickness = self.__spinBox_penThickness.value()
        self.__paintBoard.ChangePenThickness(penThickness)

    def on_btn_Save_Clicked(self):
        savePath = QFileDialog.getSaveFileName(self, 'Save Your Paint', '.\\', '*.png')
        print(savePath)
        if savePath[0] == "":
            print("Save cancel")
            return
        image = self.__paintBoard.GetContentAsQImage()
        image.save(savePath[0])
        print(savePath[0])

    def on_cbtn_Eraser_clicked(self):
        if self.__cbtn_Eraser.isChecked():
            self.__paintBoard.EraserMode = True  # Enter eraser mode
        else:
            self.__paintBoard.EraserMode = False  # Exit eraser mode

    def on_btn_Recognize_Clicked(self):
        savePath = "./PNG/text.png"
        image = self.__paintBoard.GetContentAsQImage()
        image.save(savePath)
        print(savePath)
        # load graph
        img = tf.keras.preprocessing.image.load_img(savePath, target_size=(28, 28))
        img = img.convert('L')
        x = tf.keras.preprocessing.image.img_to_array(img)
        x = abs(255 - x)
        # x = x.reshape(28,28)
        x = np.expand_dims(x, axis=0)
        x = x / 255.0
        new_model = keras.models.load_model("./model.h5")
        prediction = new_model.predict(x)
        output = np.argmax(prediction, axis=1)
        print("Handwritten numeric recognition as：" + str(output[0]))

    def Quit(self):
        self.close()


from card import Card
from hand import Hand
from deck import Deck
import random

def main():
    TABLE_MIN = 100
    you_points = TABLE_MIN
    cpu_points = TABLE_MIN

    play_more = "y"

    print('\nSCORES: ')
    print(f'You: {you_points:4>}')
    print(f'CPU: {cpu_points:4>}', end='\n\n') # Leave empty line.

    while play_more[0].lower() != 'n' and you_points > 0 and cpu_points > 0:
        # Create and shuffle the deck.
        deck = Deck()
        deck.shuffle()

        # Create hands for each player.
        you = Hand()
        cpu = Hand()

        # Deal 5 cards to each player.
        for i in range(5):
            you.add_card(deck.deal())
            cpu.add_card(deck.deal())

        # Show the player their cards.
        print(f' Your hand: {you.show_hand()}', end='\n\n')

        # Simplified one-shot betting.
        cpu_wager = random.randint(1, cpu_points)
        print(f'       CPU wagers: {cpu_wager}')
        you_wager = int(input('What do you wager? '))

        print(f'\nCPU\'s hand: {cpu.show_hand()}')

        # Compare the hands.
        if you < cpu:
            print('\nYou win!', '\N{GRINNING FACE}')
            you_points += cpu_wager
            cpu_points -= cpu_wager
        elif cpu < you:
            print('\nCPU wins!', '\N{WORRIED FACE}')
            cpu_points += you_wager
            you_points -= you_wager
        else:
            print('\nTIED!')

        print('\nSCORES: ')
        print(f' You have: ${you_points:4>}')
        print(f'  CPU has: ${cpu_points:4>}', end='\n\n')

        if you_points <= 0 or cpu_points <= 0:
            break

        play_more = input("Play another hand? (y/n) ")

    # END WHILE

    if you_points <= 0:
        print('You lost everything!', '\N{MONEY WITH WINGS}')
    elif cpu_points <= 0:
        print('You won everything from the computer!', '\N{MONEY BAG}')
    else:
        print('Quit before you\'re broke. Good move.')

def test_main():
    # Some test cases:
    i = 0
    # Royal Flush
    p3 = Hand()
    p3.add_card(Card('hearts', 10))
    p3.add_card(Card('hearts', 11))
    p3.add_card(Card('hearts', 13))
    p3.add_card(Card('hearts', 12))
    p3.add_card(Card('hearts', 14))
    print(f'Test Hand {i}: ', end='')
    i += 1
    p3.show_hand()

    # Flush
    p4 = Hand()
    p4.add_card(Card('clubs', 3))
    p4.add_card(Card('clubs', 7))
    p4.add_card(Card('clubs', 4))
    p4.add_card(Card('clubs', 6))
    p4.add_card(Card('clubs', 5))
    print(f'Test Hand {i}: ', end='')
    i += 1
    p4.show_hand()

    # Full House
    p4 = Hand()
    p4.add_card(Card('spades',  8))
    p4.add_card(Card('spades',  2))
    p4.add_card(Card('diamonds',8))
    p4.add_card(Card('hearts',  8))
    p4.add_card(Card('clubs',   2))
    print(f'Test Hand {i}: ', end='')
    i += 1
    p4.show_hand()

    # Two pair
    p5 = Hand()
    p5.add_card(Card('spades', 7))
    p5.add_card(Card('spades', 9))
    p5.add_card(Card('hearts', 7))
    p5.add_card(Card('hearts', 9))
    p5.add_card(Card('clubs',  3))
    print(f'Test Hand {i}: ', end='')
    i += 1

    p5.show_hand()

    # Two pair, another
    p6 = Hand()
    p6.add_card(Card('diamonds', 3))
    p6.add_card(Card('hearts',   3))
    p6.add_card(Card('diamonds',13))
    p6.add_card(Card('diamonds', 3))
    p6.add_card(Card('clubs',   13))
    print(f'Test Hand {i}: ', end='')
    i += 1
    p6.show_hand()

    # if p4 < p5:
    #     print('Player 4 wins.')
    # else:
    #     print('Player 5 wins.')

    # if p5 < p6:
    #     print('Player 5 wins.')
    # else:
    #     print('Player 6 wins.')

if __name__ == '__main__':
    main()


import docx
import os
import shutil

ori_file_path = 'D:/PycharmProjects/docx_demo/A/'
tar_file_path = 'D:/PycharmProjects/docx_demo/B/'
muban_file_name = '典型票导入模版.docx'

def write_temp_file(temp_file_name, content_list, tar_file_name):
    docx_object = docx.Document(temp_file_name)
    #  选中表格
    table = docx_object.tables[0]
    #  清空cell
    table.rows[1].cells[1].text = ''
    #  写入需要信息
    table.rows[1].cells[1].text = content_list[0]
    for content in content_list[1:]:
        try:
            table.rows[1].cells[1].add_paragraph(content)
            # table.rows[1].cells[1].text += content
            # table.rows[1].cells[1].text += '\n'
        except Exception as e_string:
            print('写入表格失败！错误代码：', end="")
            print(e_string)
    #  查找是否有相同目标文件
    file_index = 0
    while os.path.exists(tar_file_name):
        # print(os.path.exists(tar_file_name))
        tar_file_name = tar_file_name[:-5] + str(file_index) + '.docx'
    #  写入目标文件
    try:
        docx_object.save(tar_file_name)
        print('另存为目标文件成功！')
    except Exception as e_string:
        print('另存为目标文件失败！错误代码：', end="")
        print(e_string)
    print(tar_file_name)

def read_ori_file(ori_file_name):
    docx_object = docx.Document(ori_file_name)
    tar_file_title = ''
    content_list = []
    table_index = 0
    for table in docx_object.tables:
        if table_index == 0:
            #  选中第一个表格
            #  选择需要信息
            tar_file_title = table.rows[2].cells[0].text[5:].strip()
            # print(tar_file_title)
            max_index = len(table.rows)
            #print(max_index)
            end_index = max_index - 3
            row_index = 4
            row_content = table.rows[row_index].cells[1].text.strip()
            while (row_content != 'ㄣ') & (row_index < end_index):
                # print(row_content)
                row_content = row_content.strip()
                if row_content != '':
                    content_list.append(row_content)
                row_index += 1
                row_content = table.rows[row_index].cells[1].text
        else:
            #  选中后几个表格
            #  选择需要信息
            max_index = len(table.rows)
            # print(max_index)
            end_index = max_index - 3
            row_index = 4
            row_content = table.rows[row_index].cells[1].text.strip()
            while (row_content != 'ㄣ') & (row_index < end_index):
                # print(row_content)
                row_content = row_content.strip()
                if row_content != '':
                    content_list.append(row_content)
                row_index += 1
                row_content = table.rows[row_index].cells[1].text
        #  更新table_index
        table_index += 1
    return tar_file_title, content_list

def main():
    #  生成临时文件  ===================================================================================================
    temp_file_name = tar_file_path + 'temp.docx'
    try:
        shutil.copyfile(muban_file_name, temp_file_name)
        print('模板文件拷贝到临时文件成功')
    except Exception as e_string:
        print('模板文件拷贝到临时文件失败！错误代码：', end="")
        print(e_string)
    #  遍历源文件夹所有文件  ===========================================================================================
    all_file_list = os.listdir(ori_file_path)
    total_file_num = len(all_file_list)
    index = 0
    for ori_file in all_file_list:
        index += 1
        ori_file_name = ori_file_path + ori_file
        #  读取源文件内容  获得标题 和 操作内容  =======================================================================
        tar_file_title, content_list = read_ori_file(ori_file_name)
        # print(tar_file_title)
        # print(content_list)
        tar_file_name = tar_file_path + tar_file_title + '.docx'
        #  写入临时文件内容 并另存为目标文件  ==========================================================================
        write_temp_file(temp_file_name, content_list, tar_file_name)
        string = '共%d文件，已完成第%d个文件' % (total_file_num, index)
        print(string)
    #  删除临时文件  ===================================================================================================
    os.remove(temp_file_name)
    print('临时文件清除成功！')

if __name__ == "__main__":
    main()


import math
import typing

class Point(typing.NamedTuple):
    x: typing.Union[int, float]
    y: typing.Union[int, float]

class Distance(typing.NamedTuple):
    x: typing.Union[int, float]
    y: typing.Union[int, float]

def point_tile_to_tile(tile_a: int, pt_a: Point, tile_b: int,
                       tile_offsets: typing.Dict[typing.Tuple[int, int], Distance]) -> Point:
    if tile_a == tile_b:
        # Same tile
        return pt_a
    else:
        dx = dy = 0
        if tile_b > tile_a:
            while tile_a != tile_b:
                d_ab = tile_offsets[tile_a, tile_a + 1]
                dx += d_ab.x
                dy += d_ab.y
                tile_a += 1
        else:
            # tile_a > tile_b
            while tile_a != tile_b:
                d_ab = tile_offsets[tile_b, tile_b + 1]
                dx -= d_ab.x
                dy -= d_ab.y
                tile_b += 1
        ret_x = pt_a.x - dx
        ret_y = pt_a.y - dy
    return Point(ret_x, ret_y)

def distance(a: Point, b: Point, scale: float) -> float:
    """Returns distance in metres two points at a scale in m / pixel."""
    x_north = a.y - b.y
    y_east = b.x - a.x
    return scale * math.sqrt(x_north**2 + y_east**2)

def bearing(a: Point, b: Point) -> float:
    """Returns angle in degrees between two points at a scale in m / pixel."""
    x_north = a.y - b.y
    y_east = b.x - a.x
    _bearing = math.atan2(y_east, x_north)
    bearing_degrees = math.degrees(_bearing)
    if bearing_degrees < 0:
        bearing_degrees += 360
    return bearing_degrees

def bearing_min_max(a: Point, b: Point, disp: float) -> typing.Tuple[float, float]:
    d_range = (-disp, +disp)
    bearings = []
    for dx_a in d_range:
        for dy_a in d_range:
            for dx_b in d_range:
                for dy_b in d_range:
                    new_a = Point(a.x + dx_a, a.y + dy_a)
                    new_b = Point(b.x + dx_b, b.y + dy_b)
                    bearings.append(bearing(new_a, new_b))
    # print('TRACE:', bearings)
    return min(bearings), max(bearings)

def translate_rotate(pt: Point, rotation_degrees: float, origin: Point=Point(0, 0)) -> Point:
    cos = math.cos(math.radians(rotation_degrees))
    sin = math.sin(math.radians(rotation_degrees))
    ret = Point(
        (origin.y - pt.y) * cos - (origin.x - pt.x) * sin,
        -((origin.x - pt.x) * cos + (origin.y - pt.y) * sin),
    )
    return ret

def point_translate(pt: Point, bearing_degrees: float, length: float) -> Point:
    ret = Point(
        pt.x + length * math.sin(math.radians(bearing_degrees)),
        pt.y - length * math.cos(math.radians(bearing_degrees)),
    )
    return ret

def distance_bearing(a: Point, b: Point, scale: float) -> typing.Tuple[float, float]:
    """Returns distance in metres and angle in degrees between two points at a scale in m / pixel."""
    return distance(a, b, scale), bearing(a, b)

def xy_from_two_points_and_axis(a: Point, b: Point, axis_deg: float, scale: float) -> Point:
    dist_m, brg_deg = distance_bearing(a, b, scale)
    x = dist_m * math.cos(math.radians(brg_deg - axis_deg))
    y = dist_m * math.sin(math.radians(brg_deg - axis_deg))
    return Point(x, y)

def mid_point(a: Point, b: Point) -> Point:
    """The mid point between two points."""
    return Point((a.x + b.x) / 2, (a.y + b.y) / 2)

def distance_between_points(a: Point, b: Point) -> float:
    """The distance between two points."""
    return math.sqrt((a.x - b.x)**2 + (a.y - b.y)**2)

def tile_extended_centreline_crossing_points(tile: int,
                                             runway_heading: float,
                                             threshold_on_each_tile: typing.Dict[int, Point],
                                             tiled_image_size: Distance) -> typing.Tuple[Point, Point]:
    back_bearing = runway_heading - 180
    # back_bearing += .5
    t_x, t_y = threshold_on_each_tile[tile]
    pt_y_zero = Point(
        int(0.5 + t_x + t_y * math.tan(math.radians(back_bearing))),
        0,
    )
    pt_y_max = Point(
        int(0.5 + t_x + (t_y - tiled_image_size.y) * math.tan(math.radians(back_bearing))),
        tiled_image_size.y - 1
    )
    return pt_y_zero, pt_y_max

def distance_tile_to_tile(tile_a: int, pt_a: Point, tile_b: int, pt_b: Point,
                          tile_offsets: typing.Dict[typing.Tuple[int, int], Distance]) -> Distance:
    """Given two tiles and a point on each this computes the distance between the two points in global space.

    Formulae for a point on one tile to another tile::

        dx(i, j) = x(i) - x(j)
        dy(i, j) = y(i) - y(j)
    """
    if tile_a == tile_b:
        # Same tile
        ret_x = pt_a.x
        ret_y = pt_a.y
    else:
        dx = dy = 0
        if tile_b > tile_a:
            while tile_a != tile_b:
                d_ab = tile_offsets[tile_a, tile_a + 1]
                dx += d_ab.x
                dy += d_ab.y
                tile_a += 1
        else:
            # tile_a > tile_b
            while tile_a != tile_b:
                d_ab = tile_offsets[tile_b, tile_b + 1]
                dx -= d_ab.x
                dy -= d_ab.y
                tile_b += 1
        ret_x = pt_a.x - dx
        ret_y = pt_a.y - dy
    return Distance(pt_b.x - ret_x, pt_b.y - ret_y)

def metres_per_second_to_knots(m_s: float) -> float:
    # https://en.wikipedia.org/wiki/Knot_(unit)
    return m_s * 3600 / 1852

def frame_to_time(frame: typing.Union[int, float], frame_rate: int) -> float:
    return (frame - 1) / frame_rate

def frames_to_dtime(frame_a: typing.Union[int, float], frame_b: typing.Union[int, float], frame_rate: int) -> float:
    return (frame_b - frame_a) / frame_rate

def time_to_frame(time: typing.Union[int, float], frame_rate: int) -> int:
    return 1 + int(0.5 + time * frame_rate)

def distance_tolerance(distance: float) -> float:
    """Returns the error estimate of distance.
    At +2500m to the threshold this is assumed to be 100m decreasing linearly to 10m at the threshold and thereafter."""
    ret = 10.0
    if distance < 0:
        ret += distance * (100 - ret) / -2500.0
    return ret


# -*- coding: utf-8 -*-
# .

__project_name__ = 'Defter'
__date__ = '2/7/21'
__author__ = 'Erdinç Yılmaz'

from PySide6.QtGui import QBrush, QPainter
from PySide6.QtWidgets import QPushButton
from PySide6.QtCore import Qt, Signal
from canta.shared import kutulu_arkaplan_olustur

########################################################################
class PushButton(QPushButton):

    # ---------------------------------------------------------------------
    def __init__(self, yazi, genislik, yukseklik, parent=None):
        super(PushButton, self).__init__(yazi, parent)

        self.setFixedWidth(genislik)
        self.setFixedHeight(yukseklik)

#######################################################################

class PushButtonRenk(QPushButton):
    sagTiklandi = Signal()

    # ---------------------------------------------------------------------
    def __init__(self, yazi, genislik, yukseklik, renk=None, parent=None):
        super(PushButtonRenk, self).__init__(yazi, parent)

        if renk:
            self.renk = renk
        else:
            self.renk = None  # renk yoksa dugmeye ilk tiklandiginda renk secme araci aciliyor
        self.renkGuncelle(renk)
        self.setFixedWidth(genislik)
        self.setFixedHeight(yukseklik)
        kutulu_arkaplan_olustur(self, 3)

    # ---------------------------------------------------------------------
    def renkGuncelle(self, renk):
        self.renk = renk
        self.update()

    # ---------------------------------------------------------------------
    def paintEvent(self, event):
        if self.renk:
            p = QPainter(self)
            # p.begin()
            if self.renk:
                p.fillRect(self.rect(), QBrush(self.renk))
            else:
                p.fillRect(self.rect(), QBrush(Qt.GlobalColor.lightGray))
            # p.setBrush(self.renk)
            # p.drawRect(self.rect())
            p.end()

        # super(PushButtonRenk, self).paintEvent(event)

    # ---------------------------------------------------------------------
    def mousePressEvent(self, event):
        if event.button() == Qt.MouseButton.RightButton:
            self.sagTiklandi.emit()
            event.accept()

        super(PushButtonRenk, self).mousePressEvent(event)


# -*- coding: utf-8 -*-
# StarDist Experiment Class
#
# @ Fabian Hörst, fabian.hoerst@uk-essen.de
# Institute for Artifical Intelligence in Medicine,
# University Medicine Essen

import inspect
import os
import sys

import yaml

from base_ml.base_trainer import BaseTrainer

currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)

from pathlib import Path
from typing import Callable, Tuple, Union

import torch
import torch.nn as nn
from torch.optim import Optimizer
from torch.optim.lr_scheduler import (
    ConstantLR,
    CosineAnnealingLR,
    ExponentialLR,
    ReduceLROnPlateau,
    SequentialLR,
    _LRScheduler,
)
from torch.utils.data import Dataset
from torchinfo import summary

from base_ml.base_loss import retrieve_loss_fn
from cell_segmentation.experiments.experiment_cellvit_pannuke import (
    ExperimentCellVitPanNuke,
)
from cell_segmentation.trainer.trainer_stardist import CellViTStarDistTrainer
from models.segmentation.cell_segmentation.cellvit_stardist import (
    CellViTStarDist,
    CellViT256StarDist,
    CellViTSAMStarDist,
)
from models.segmentation.cell_segmentation.cellvit_stardist_shared import (
    CellViTStarDistShared,
    CellViT256StarDistShared,
    CellViTSAMStarDistShared,
)
from models.segmentation.cell_segmentation.cpp_net_stardist_rn50 import StarDistRN50

class ExperimentCellViTStarDist(ExperimentCellVitPanNuke):
    def load_dataset_setup(self, dataset_path: Union[Path, str]) -> None:
        """Load the configuration of the PanNuke cell segmentation dataset.

        The dataset must have a dataset_config.yaml file in their dataset path with the following entries:
            * tissue_types: describing the present tissue types with corresponding integer
            * nuclei_types: describing the present nuclei types with corresponding integer

        Args:
            dataset_path (Union[Path, str]): Path to dataset folder
        """
        dataset_config_path = Path(dataset_path) / "dataset_config.yaml"
        with open(dataset_config_path, "r") as dataset_config_file:
            yaml_config = yaml.safe_load(dataset_config_file)
            self.dataset_config = dict(yaml_config)

    def get_loss_fn(self, loss_fn_settings: dict) -> dict:
        """Create a dictionary with loss functions for all branches

        Branches: "dist_map", "stardist_map", "nuclei_type_map", "tissue_types"

        Args:
            loss_fn_settings (dict): Dictionary with the loss function settings. Structure
            branch_name(str):
                loss_name(str):
                    loss_fn(str): String matching to the loss functions defined in the LOSS_DICT (base_ml.base_loss)
                    weight(float): Weighting factor as float value
                    (optional) args:  Optional parameters for initializing the loss function
                            arg_name: value

            If a branch is not provided, the defaults settings (described below) are used.

            For further information, please have a look at the file configs/examples/cell_segmentation/train_cellvit.yaml
            under the section "loss"

            Example:
                  nuclei_type_map:
                    bce:
                        loss_fn: xentropy_loss
                        weight: 1
                    dice:
                        loss_fn: dice_loss
                        weight: 1

        Returns:
            dict: Dictionary with loss functions for each branch. Structure:
                branch_name(str):
                    loss_name(str):
                        "loss_fn": Callable loss function
                        "weight": weight of the loss since in the end all losses of all branches are added together for backward pass
                    loss_name(str):
                        "loss_fn": Callable loss function
                        "weight": weight of the loss since in the end all losses of all branches are added together for backward pass
                branch_name(str)
                ...

        Default loss dictionary:
            dist_map:
                bceweighted:
                    loss_fn: BCEWithLogitsLoss
                    weight: 1
            stardist_map:
                L1LossWeighted:
                    loss_fn: L1LossWeighted
                    weight: 1
            nuclei_type_map
                bce:
                    loss_fn: xentropy_loss
                    weight: 1
                dice:
                    loss_fn: dice_loss
                    weight: 1
            tissue_type has no default loss and might be skipped
        """
        loss_fn_dict = {}
        if "dist_map" in loss_fn_settings.keys():
            loss_fn_dict["dist_map"] = {}
            for loss_name, loss_sett in loss_fn_settings["dist_map"].items():
                parameters = loss_sett.get("args", {})
                loss_fn_dict["dist_map"][loss_name] = {
                    "loss_fn": retrieve_loss_fn(loss_sett["loss_fn"], **parameters),
                    "weight": loss_sett["weight"],
                }
        else:
            loss_fn_dict["dist_map"] = {
                "bceweighted": {
                    "loss_fn": retrieve_loss_fn("BCEWithLogitsLoss"),
                    "weight": 1,
                },
            }
        if "stardist_map" in loss_fn_settings.keys():
            loss_fn_dict["stardist_map"] = {}
            for loss_name, loss_sett in loss_fn_settings["stardist_map"].items():
                parameters = loss_sett.get("args", {})
                loss_fn_dict["stardist_map"][loss_name] = {
                    "loss_fn": retrieve_loss_fn(loss_sett["loss_fn"], **parameters),
                    "weight": loss_sett["weight"],
                }
        else:
            loss_fn_dict["stardist_map"] = {
                "L1LossWeighted": {
                    "loss_fn": retrieve_loss_fn("L1LossWeighted"),
                    "weight": 1,
                },
            }
        if "nuclei_type_map" in loss_fn_settings.keys():
            loss_fn_dict["nuclei_type_map"] = {}
            for loss_name, loss_sett in loss_fn_settings["nuclei_type_map"].items():
                parameters = loss_sett.get("args", {})
                loss_fn_dict["nuclei_type_map"][loss_name] = {
                    "loss_fn": retrieve_loss_fn(loss_sett["loss_fn"], **parameters),
                    "weight": loss_sett["weight"],
                }
        else:
            loss_fn_dict["nuclei_type_map"] = {
                "bce": {"loss_fn": retrieve_loss_fn("xentropy_loss"), "weight": 1},
                "dice": {"loss_fn": retrieve_loss_fn("dice_loss"), "weight": 1},
            }
        if "tissue_types" in loss_fn_settings.keys():
            loss_fn_dict["tissue_types"] = {}
            for loss_name, loss_sett in loss_fn_settings["tissue_types"].items():
                parameters = loss_sett.get("args", {})
                loss_fn_dict["tissue_types"][loss_name] = {
                    "loss_fn": retrieve_loss_fn(loss_sett["loss_fn"], **parameters),
                    "weight": loss_sett["weight"],
                }
        # skip default tissue loss!
        return loss_fn_dict

    def get_scheduler(self, scheduler_type: str, optimizer: Optimizer) -> _LRScheduler:
        """Get the learning rate scheduler for CellViT

        The configuration of the scheduler is given in the "training" -> "scheduler" section.
        Currenlty, "constant", "exponential" and "cosine" schedulers are implemented.

        Required parameters for implemented schedulers:
            - "constant": None
            - "exponential": gamma (optional, defaults to 0.95)
            - "cosine": eta_min (optional, defaults to 1-e5)
            - "reducelronplateau": everything hardcoded right now, uses vall los for checking
        Args:
            scheduler_type (str): Type of scheduler as a string. Currently implemented:
                - "constant" (lowering by a factor of ten after 25 epochs, increasing after 50, decreasimg again after 75)
                - "exponential" (ExponentialLR with given gamma, gamma defaults to 0.95)
                - "cosine" (CosineAnnealingLR, eta_min as parameter, defaults to 1-e5)
            optimizer (Optimizer): Optimizer

        Returns:
            _LRScheduler: PyTorch Scheduler
        """
        implemented_schedulers = [
            "constant",
            "exponential",
            "cosine",
            "reducelronplateau",
        ]
        if scheduler_type.lower() not in implemented_schedulers:
            self.logger.warning(
                f"Unknown Scheduler - No scheduler from the list {implemented_schedulers} select. Using default scheduling."
            )
        if scheduler_type.lower() == "constant":
            scheduler = SequentialLR(
                optimizer=optimizer,
                schedulers=[
                    ConstantLR(optimizer, factor=1, total_iters=25),
                    ConstantLR(optimizer, factor=0.1, total_iters=25),
                    ConstantLR(optimizer, factor=1, total_iters=25),
                    ConstantLR(optimizer, factor=0.1, total_iters=1000),
                ],
                milestones=[24, 49, 74],
            )
        elif scheduler_type.lower() == "exponential":
            scheduler = ExponentialLR(
                optimizer,
                gamma=self.run_conf["training"]["scheduler"].get("gamma", 0.95),
            )
        elif scheduler_type.lower() == "cosine":
            scheduler = CosineAnnealingLR(
                optimizer,
                T_max=self.run_conf["training"]["epochs"],
                eta_min=self.run_conf["training"]["scheduler"].get("eta_min", 1e-5),
            )
        elif scheduler_type.lower() == "reducelronplateau":
            scheduler = ReduceLROnPlateau(
                optimizer,
                mode="min",
                factor=0.5,
                min_lr=0.0000001,
                patience=10,
                threshold=1e-20,
            )
        else:
            scheduler = super().get_scheduler(optimizer)
        return scheduler

    def get_datasets(
        self,
        train_transforms: Callable = None,
        val_transforms: Callable = None,
    ) -> Tuple[Dataset, Dataset]:
        """Retrieve training dataset and validation dataset

        Args:
            dataset_name (str): Name of dataset to use
            train_transforms (Callable, optional): PyTorch transformations for train set. Defaults to None.
            val_transforms (Callable, optional): PyTorch transformations for validation set. Defaults to None.

        Returns:
            Tuple[Dataset, Dataset]: Training dataset and validation dataset
        """
        self.run_conf["data"]["stardist"] = True
        train_dataset, val_dataset = super().get_datasets(
            train_transforms=train_transforms,
            val_transforms=val_transforms,
        )
        return train_dataset, val_dataset

    def get_train_model(
        self,
        pretrained_encoder: Union[Path, str] = None,
        pretrained_model: Union[Path, str] = None,
        backbone_type: str = "default",
        shared_decoders: bool = False,
        **kwargs,
    ) -> nn.Module:
        """Return the CellViTStarDist training model

        Args:
            pretrained_encoder (Union[Path, str]): Path to a pretrained encoder. Defaults to None.
            pretrained_model (Union[Path, str], optional): Path to a pretrained model. Defaults to None.
            backbone_type (str, optional): Backbone Type. Currently supported are default (None, ViT256, SAM-B, SAM-L, SAM-H, RN50). Defaults to None
            shared_decoders (bool, optional): If shared skip decoders should be used. Defaults to False.

        Returns:
            nn.Module: StarDist training model with given setup
        """
        # reseed needed, due to subprocess seeding compatibility
        self.seed_run(self.default_conf["random_seed"])

        # check for backbones
        implemented_backbones = ["default", "vit256", "sam-b", "sam-l", "sam-h", "rn50"]
        if backbone_type.lower() not in implemented_backbones:
            raise NotImplementedError(
                f"Unknown Backbone Type - Currently supported are: {implemented_backbones}"
            )
        if backbone_type.lower() == "default":
            if shared_decoders:
                model_class = CellViTStarDistShared
            else:
                model_class = CellViTStarDist
            model = model_class(
                num_nuclei_classes=self.run_conf["data"]["num_nuclei_classes"],
                num_tissue_classes=self.run_conf["data"]["num_tissue_classes"],
                embed_dim=self.run_conf["model"]["embed_dim"],
                input_channels=self.run_conf["model"].get("input_channels", 3),
                depth=self.run_conf["model"]["depth"],
                num_heads=self.run_conf["model"]["num_heads"],
                extract_layers=self.run_conf["model"]["extract_layers"],
                drop_rate=self.run_conf["training"].get("drop_rate", 0),
                attn_drop_rate=self.run_conf["training"].get("attn_drop_rate", 0),
                drop_path_rate=self.run_conf["training"].get("drop_path_rate", 0),
                nrays=self.run_conf["model"].get("nrays", 32),
            )

            if pretrained_model is not None:
                self.logger.info(
                    f"Loading pretrained CellViT model from path: {pretrained_model}"
                )
                cellvit_pretrained = torch.load(pretrained_model)
                self.logger.info(model.load_state_dict(cellvit_pretrained, strict=True))
                self.logger.info("Loaded CellViT model")

        if backbone_type.lower() == "vit256":
            if shared_decoders:
                model_class = CellViT256StarDistShared
            else:
                model_class = CellViT256StarDist
            model = model_class(
                model256_path=pretrained_encoder,
                num_nuclei_classes=self.run_conf["data"]["num_nuclei_classes"],
                num_tissue_classes=self.run_conf["data"]["num_tissue_classes"],
                drop_rate=self.run_conf["training"].get("drop_rate", 0),
                attn_drop_rate=self.run_conf["training"].get("attn_drop_rate", 0),
                drop_path_rate=self.run_conf["training"].get("drop_path_rate", 0),
                nrays=self.run_conf["model"].get("nrays", 32),
            )
            model.load_pretrained_encoder(model.model256_path)
            if pretrained_model is not None:
                self.logger.info(
                    f"Loading pretrained CellViT model from path: {pretrained_model}"
                )
                cellvit_pretrained = torch.load(pretrained_model, map_location="cpu")
                self.logger.info(model.load_state_dict(cellvit_pretrained, strict=True))
            model.freeze_encoder()
            self.logger.info("Loaded CellVit256 model")
        if backbone_type.lower() in ["sam-b", "sam-l", "sam-h"]:
            if shared_decoders:
                model_class = CellViTSAMStarDistShared
            else:
                model_class = CellViTSAMStarDist
            model = model_class(
                model_path=pretrained_encoder,
                num_nuclei_classes=self.run_conf["data"]["num_nuclei_classes"],
                num_tissue_classes=self.run_conf["data"]["num_tissue_classes"],
                vit_structure=backbone_type,
                drop_rate=self.run_conf["training"].get("drop_rate", 0),
                nrays=self.run_conf["model"].get("nrays", 32),
            )
            model.load_pretrained_encoder(model.model_path)
            if pretrained_model is not None:
                self.logger.info(
                    f"Loading pretrained CellViT model from path: {pretrained_model}"
                )
                cellvit_pretrained = torch.load(pretrained_model, map_location="cpu")
                self.logger.info(model.load_state_dict(cellvit_pretrained, strict=True))
            model.freeze_encoder()
            self.logger.info(f"Loaded CellViT-SAM model with backbone: {backbone_type}")
        if backbone_type.lower() == "rn50":
            model = StarDistRN50(
                n_rays=self.run_conf["model"].get("nrays", 32),
                n_seg_cls=self.run_conf["data"]["num_nuclei_classes"],
            )

        self.logger.info(f"\nModel: {model}")
        model = model.to("cpu")
        self.logger.info(
            f"\n{summary(model, input_size=(1, 3, 256, 256), device='cpu')}"
        )

        return model

    def get_trainer(self) -> BaseTrainer:
        """Return Trainer matching to this network

        Returns:
            BaseTrainer: Trainer
        """
        return CellViTStarDistTrainer


my_tuple = (7, 25, 36, 9, 6, 8)

print("The tuple is : ")
print(my_tuple)

K = 2
print("The value of K has been initialized to ")
print(K)
my_result = []
my_tuple = list(my_tuple)
temp = sorted(my_tuple)

for idx, val in enumerate(temp):
   if idx < K or idx >= len(temp) - K:
      my_result.append(val)
my_result = tuple(my_result)

print("The result is : " )
print(my_result)


#continue, ignora esa vuelta del bucle y salta a la siguiente
#pass, devuelve null, no ejecuta el bucle
#else, es lo mismo que en un codicional if, for

for letra in "python":
    if letra=="h":
        continue#ignora la letra h
    print("Viendo las letras de python: "+ letra)

nombre="anibal kozur"
for i in nombre:
    if i==" ":#ignora en el conteo de caracateres el espacio
        continue
    contador=+1
print("la cantidad de letras de anibal kozur es: "+ str(len(nombre)))

class MiClase:
    pass # para implementar mas tarde devuelve un null

email=input("introduce email: ")
for i in email:
    if i=="@":
        arroba=True
        break;
else:#entra despues de que termine completamente el bucle for, si for no se completa no entra al else
    arroba=False
print("The email is " + str(arroba))


import os
import glob
import pandas as pd
import numpy as np
from scipy import stats

def get_csv(file_path, data_dir):
    infos = {'img_path': [], 'label': []}
    with open(file_path, 'r') as f:
        lines = f.readlines()
        for line in lines:
            line = line.strip()
            line = line.split()
            infos['img_path'].append(data_dir + '/' + line[0])
            labels = []
            for label in line[1:]:
                label = list(map(int, label.split(',')))
                labels.append(label)
            infos['label'].append(labels)
    data = pd.DataFrame(infos)
    data.to_csv(file_path.replace('.txt', '.csv'), index_label=False)

if __name__ == '__main__':
    data_dir = r'G:\Coding\pytorch-YOLOv4-master\datasets\coins'
    file_path = r'G:\Coding\pytorch-YOLOv4-master\datasets\train.txt'
    get_csv(file_path, data_dir)


#!/usr/bin/python2

from Tkinter import *
import re
import subprocess
import tkFileDialog
import tkMessageBox

class App:
	def __init__(self, master):
		self.master = master
		self.master.title("RasPi Movie GUI")
		self.file_to_play = None
		self.movie_player_command = "omxplayer"

		self.loop_l = Label(master, text="Loop:")
		self.loop_v = StringVar()
		self.loop_cb = Checkbutton(master, onvalue="--loop", offvalue="", variable=self.loop_v)
		self.loop_cb.select()

		self.play_b = Button(master, text="Play", command=self.play)

		self.menubar = Menu(master)
		master.config(menu=self.menubar)

		filemenu = Menu(self.menubar)
		filemenu.add_command(label="Open Movie...", command=self.choose_file)
		filemenu.add_command(label="Quit", command=master.quit)
		self.menubar.add_cascade(label="File", menu=filemenu)

		self.loop_l.grid(row=0, column=0)
		self.loop_cb.grid(row=0, column=1)
		self.play_b.grid(row=1, column=0, columnspan=2)

	def choose_file(self):
		self.file_to_play = tkFileDialog.askopenfilename()
		if self.file_to_play not in [None, (), '']:
			split_path = re.split('/', self.file_to_play)
			self.master.title("RasPi Movie GUI - " + split_path[len(split_path) - 1])
			#self.movie_text.set(split_path[len(split_path) - 1])
		else:
			self.master.title("RasPi Movie GUI")

	def play(self):
		if self.file_to_play in [None, (), '']:
			tkMessageBox.showwarning("Play Movie", "No movie has been selected!")
		else:
			args = " ".join([self.loop_v.get()])
			subprocess.Popen("{cmd} {args} -b \"{movie}\"".format(cmd=self.movie_player_command, args=args, movie=self.file_to_play), shell=True)

root = Tk()

app = App(root)

root.mainloop()
root.destroy()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created at 2020/1/17 下午12:57
import unittest

import torch
from torch.distributions import OneHotCategorical

from custom.MultiOneHotCategorical import MultiOneHotCategorical

class TestMultiOneHotCategorical(unittest.TestCase):

    def setUp(self) -> None:
        self.test_probs = torch.tensor([[0.3, 0.2, 0.4, 0.1, 0.25, 0.5, 0.25, 0.3, 0.4, 0.1, 0.1, 0.1],
                                        [0.2, 0.3, 0.1, 0.4, 0.5, 0.3, 0.2, 0.2, 0.3, 0.2, 0.2, 0.1]])
        self.test_sections = (4, 3, 5)

        self.test_actions = torch.tensor([[0., 0., 1., 0., 0., 1., 0., 0., 1., 0., 0., 0.],
                                          [0., 0., 0., 1., 1., 0., 0., 0., 0., 1., 0., 0.]]).long()

        self.test_sected_actions = torch.split(self.test_actions, self.test_sections, dim=-1)

        self.test_multi_onehot_categorical = MultiOneHotCategorical(self.test_probs, self.test_sections)

        self.test_onehot_categorical1 = OneHotCategorical(self.test_probs[:, :4])
        self.test_onehot_categorical2 = OneHotCategorical(self.test_probs[:, 4:7])
        self.test_onehot_categorical3 = OneHotCategorical(self.test_probs[:, 7:])

    def test_log_prob(self):
        test_cat1_log_prob = self.test_onehot_categorical1.log_prob(self.test_sected_actions[0])
        test_cat2_log_prob = self.test_onehot_categorical2.log_prob(self.test_sected_actions[1])
        test_cat3_log_prob = self.test_onehot_categorical3.log_prob(self.test_sected_actions[2])

        test_multi_cat_log_prob = self.test_multi_onehot_categorical.log_prob(self.test_actions)
        print(test_multi_cat_log_prob)
        print(test_cat1_log_prob)
        self.assertEqual(test_cat1_log_prob.shape, test_multi_cat_log_prob.shape)

        self.assertTrue(
            torch.equal(test_cat1_log_prob + test_cat2_log_prob + test_cat3_log_prob, test_multi_cat_log_prob))

    def test_sample(self):
        test_cat1_sample = self.test_onehot_categorical1.sample()
        test_cat2_sample = self.test_onehot_categorical2.sample()
        test_cat3_sample = self.test_onehot_categorical3.sample()

        test_cat_sample = torch.cat([test_cat1_sample, test_cat2_sample, test_cat3_sample], dim=-1)
        test_multi_cat_sample = self.test_multi_onehot_categorical.sample()

        self.assertEqual(test_cat_sample.shape, test_multi_cat_sample.shape)
        self.assertTrue(torch.equal(test_cat_sample.sum(dim=-1),
                                    test_multi_cat_sample.sum(dim=-1)))

    def test_entropy(self):
        test_cat1_entropy = self.test_onehot_categorical1.entropy()
        test_cat2_entropy = self.test_onehot_categorical2.entropy()
        test_cat3_entropy = self.test_onehot_categorical3.entropy()

        test_multi_cat_entropy = self.test_multi_onehot_categorical.entropy()

        self.assertTrue(torch.equal(test_cat1_entropy + test_cat2_entropy + test_cat3_entropy, test_multi_cat_entropy),
                        "Expected same entropy!!!")

if __name__ == '__main__':
    unittest.main()


from sklearn.metrics import roc_auc_score, mean_squared_error
import numpy as np
import pandas as pd
import gerryfair
from functions.build_models import gerryfair_model, logr_model
from sklearn.model_selection import StratifiedKFold
from functions.formatting import get_indices, get_subgroup_str

def calc_metrics(X: pd.DataFrame, y, subgroup_names, demographics, protected, omit_demographics=False, is_gerryfair = False, iters=5, gamma=.01):
    kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

    to_drop = []

    for d in demographics:
        to_drop.append(X.columns.get_loc(d))

    aucs = [[] for _ in subgroup_names]
    fprs = [[] for _ in subgroup_names]
    rmses = [[] for _ in subgroup_names]

    # dataset, attributes = generate_preprocessed.create_attributes(X, y, demographics)
    # X, X_prime, y = gerryfair.clean.clean_dataset(dataset, attributes, False)
    X_prime = X.loc[:, protected]
    X_protected = X.loc[:, demographics]
    if omit_demographics:
        X = X.drop(demographics, axis=1)

    subgroups = []

    for sg in subgroup_names:
        inds = []
        for n in sg:
            inds.append(X_protected.columns.get_loc(n))
        subgroups.append(inds)

    X_cols, X_prime_cols = X.columns, X_prime.columns
    X, X_prime, X_protected, y = np.array(X), np.array(X_prime), np.array(X_protected), np.array(y)

    combined_feature = np.dot(X_protected, 2 ** np.arange(X_protected.shape[1])[::-1])

    subgroup_sizes = np.zeros(len(subgroup_names))
    counts = np.zeros(len(subgroup_names))

    # Iterate through the each fold
    for train_index, test_index in kfold.split(X, combined_feature):
        X_train, X_test = X[train_index], X[test_index]
        y_train, y_test = y[train_index], y[test_index]
        X_prime_train, X_prime_test = X_prime[train_index], X_prime[test_index]
        X_protected_train, X_protected_test = X_protected[train_index], X_protected[test_index]

        model = None

        if is_gerryfair:
            X_train_df = pd.DataFrame(X_train, columns=X_cols)
            X_prime_train_df = pd.DataFrame(X_prime_train, columns=X_prime_cols)
            y_train_df = pd.Series(y_train)

            model = gerryfair_model(X_train_df, X_prime_train_df, y_train_df, iters, gamma)
        else:
            model = logr_model(X_train, y_train)

        for i, subgroup in enumerate(subgroups):
            X_test_filtered = X_test
            y_test_filtered = y_test
            if subgroup:
                conditions = np.array([(X_protected_test[:, name] == 1) for name in subgroup]).all(axis=0)
                X_test_filtered = X_test_filtered[conditions]
                y_test_filtered = y_test_filtered[conditions]

            subgroup_sizes[i] += X_test_filtered.shape[0]
            counts[i]+=1

            res = None
            if is_gerryfair:
                X_test_df = pd.DataFrame(X_test_filtered, columns=X_cols)
                res = calc_metric(model, X_test_df, y_test_filtered, True)
            else:
                res = calc_metric(model, X_test_filtered, y_test_filtered, False)

            if res == None:
                continue

            auc, FPR, rmse = res
            aucs[i].append(auc)
            fprs[i].append(FPR)
            rmses[i].append(rmse)

    ret = []

    for i, subgroup in enumerate(subgroup_names):
        subgroup_data = {
            'subgroup': get_subgroup_str(subgroup),
            'n': f"{subgroup_sizes[i]/counts[i]}",
            'auc_avg': f"{np.average(aucs[i]):.3f}",
            'auc_std': f"{np.std(aucs[i]):.3f}",
            'fpr_avg': f"{np.average(fprs[i]):.3f}",
            'fpr_std': f"{np.std(fprs[i]):.3f}",
            'rmse_avg': f"{np.average(rmses[i]):.3f}",
            'rmse_std': f"{np.std(rmses[i]):.3f}"
        }

        ret.append(subgroup_data)

    # print(f"AUC: {auc_avg} +/- {auc_std}")
    # print(f"FPR: {fpr_avg} +/- {fpr_std}")
    return ret

def calc_metric(model, X_test, y_test, is_gerryfair):
    auc = None
    rmse = None
    y_pred = None
    try:
        y_pred = np.array(model.predict(X_test))
        if is_gerryfair:
            y_pred = y_pred.ravel()
            y_pred = (y_pred >= 0.5).astype(int)

        auc = roc_auc_score(y_test, y_pred)
        rmse = np.sqrt(mean_squared_error(y_test, y_pred))

    except Exception:
        # print('error')
        return None
    y_test = np.array(y_test)
    TN = np.sum((y_test == 0) & (y_pred == 0))
    FP = np.sum((y_test == 0) & (y_pred == 1))
    FPR = FP / (FP + TN)

    # print(y_test, y_pred, FPR)

    return auc, FPR, rmse


import random

# Define a list of words to choose from
word_list = ["python", "programming", "code", "algorithm"]

# Choose a random word from the list
secret_word = random.choice(word_list)

# Create a list to store the letters the user has guessed
guesses = []

# Set the number of turns the user has to guess the word
max_turns = 10

# Main game loop
while max_turns > 0:
    # Print the current status of the word (showing only correctly guessed letters)
    word_status = ""
    for letter in secret_word:
        if letter in guesses:
            word_status += letter
        else:
            word_status += "_"
    print(word_status)

    # Ask the user for their guess
    guess = input("Guess a letter: ")

    # Check if the guess is correct and add it to the list of guesses
    if guess in secret_word:
        print("Correct!")
        guesses.append(guess)
    else:
        print("Wrong!")

    # Decrement the number of turns remaining
    max_turns -= 1

    # Check if the user has guessed all the letters in the word
    if all(letter in guesses for letter in secret_word):
        print(f"Congratulations! You guessed the word '{secret_word}'")
        break

# If the user has used up all their turns without guessing the word, they lose
if max_turns == 0:
    print(f"Sorry, you have used up all your turns. The word was '{secret_word}'")

python project ideas/python project ideas/hangman.py