from django import forms
from p_library.models import Author, Book, BorrowBook, Friend
from django.utils.translation import gettext_lazy as _

class AuthorForm(forms.ModelForm):
    full_name = forms.CharField(widget=forms.TextInput, label="Имя")
#    required_css_class = 'list-group-item'
    class Meta:
        model = Author
        fields = '__all__'
        labels = {
            "birth_year":_("Год рождения"),
            "country":_("Страна")
        }

class BookForm(forms.ModelForm):
    title = forms.CharField(widget=forms.TextInput, label="Название")
    class Meta:
        model = Book
        fields = '__all__'
        labels = {
            'ISBN':_("Код ISBN"),
            'author':_("Автор"),
            'publisher':_("Издательство"),
            'description':_('Описание'),
            'year_release':_('Год издания'),
            'copy_count':_('Экз.(шт.)'),
            'price':_('Цена'),
            'book_img':_('Обложка'),
        } #подписи полей на форме вывода
        exclude = ('friend',)

class BookFormEdit(forms.ModelForm):
    title = forms.CharField(widget=forms.TextInput, label="Название")
    class Meta:
        model = Book
        fields = '__all__'
        labels = {
            'ISBN':_("Код ISBN"),
            'author':_("Автор"),
            'friend':_('Друг'),
            'publisher':_("Издательство"),
            'description':_('Описание'),
            'year_release':_('Год издания'),
            'copy_count':_('Экз.(шт.)'),
            'price':_('Цена'),
            'book_img':_('Обложка'),
        } #подписи полей на форме вывода

class BorrowBookFormGive(forms.ModelForm):
    class Meta:
        model = BorrowBook
        fields = ['book', 'friend','borrow_date',
        'state_before']
        labels = {
            'book':_("Книга"),
            'friend':_("Должник"),
            'borrow_date':_("Дата выдачи"),
            'state_before':_("Состояние книги"),
        } #подписи полей на форме вывода
        widgets = {
            #'borrow_date': forms.DateInput(format='%Y-%m-%d', attrs={'type':'date','placeholder':'mm/dd/yyyy' }),
            'borrow_date': forms.SelectDateWidget(empty_label="Nothing"),
            'state_before': forms.TextInput(),
        } #виджеты на форме

class BorrowBookFormBack(forms.ModelForm):
    class Meta:
        model = BorrowBook
        fields = '__all__'

class BorrowBookFormReturn(forms.Form):
    return_date = forms.DateField(required=True, label="Дата возврата", widget=forms.SelectDateWidget(empty_label="Nothing"))
    #return_date = forms.DateField(required=True, label="Дата возврата", widget=forms.DateInput(format='%m/%d/%Y',attrs={'type':'date','placeholder':'yyyy-mm-dd' }))
    state_after = forms.CharField(required=True, label="Состояние книги")
    returned_flad = forms.BooleanField(initial=True, required=True, label="Принято")
    class Meta:
        pass

class FriendFormAdd(forms.ModelForm):
    full_name = forms.CharField(widget=forms.TextInput, label="Полное имя")
    class Meta:
        model = Friend
        fields = '__all__'
        labels = {
            "phone":_("Телефон"),
            "rating":_("Рейтинг"),
        }
class FriendFormEdit(forms.ModelForm):
    full_name = forms.CharField(widget=forms.TextInput, label="Полное имя")
    class Meta:
        model = Friend
        fields = "__all__"
        labels = {
            'phone':_("Телефон"),
            'rating':_("Рейтинг"),
        }

BorrowBookFormSet = forms.modelformset_factory(BorrowBook, fields=('book','friend','borrow_date'),
        widgets={'borrow_date':forms.TextInput()})


"""
Functions for creating stimuli and noise inputs for models.
"""

import inspect

import numba
import numpy as np
from chspy import CubicHermiteSpline
from scipy.signal import square

class ModelInput:
    """
    Generates input to model.

    Base class for other input types.
    """

    def __init__(self, num_iid=1, seed=None):
        """
        :param num_iid: how many independent realisation of
            the input we want - for constant inputs the array is just copied,
            for noise this means independent realisation
        :type num_iid: int
        :param seed: optional seed for noise generator
        :type seed: int|None
        """
        self.num_iid = num_iid
        self.seed = seed
        # seed the generator
        np.random.seed(seed)
        # get parameter names
        self.param_names = inspect.getfullargspec(self.__init__).args
        self.param_names.remove("self")

    def __add__(self, other):
        """
        Concatenate two processes.
        """
        assert isinstance(other, ModelInput)
        assert self.num_iid == other.num_iid
        if isinstance(other, ConcatenatedInput):
            return ConcatenatedInput(noise_processes=[self] + other.noise_processes)
        else:
            return ConcatenatedInput(noise_processes=[self, other])

    def get_params(self):
        """
        Return model input parameters as dict.
        """
        assert all(hasattr(self, name) for name in self.param_names), self.param_names
        params = {name: getattr(self, name) for name in self.param_names}
        return {"type": self.__class__.__name__, **params}

    def update_params(self, params_dict):
        """
        Update model input parameters.

        :param params_dict: new parameters for this model input
        :type params_dict: dict
        """
        for param, value in params_dict.items():
            if hasattr(self, param):
                setattr(self, param, value)

    def _get_times(self, duration, dt):
        """
        Generate time vector.

        :param duration: duration of the input, in miliseconds
        :type duration: float
        :param dt: dt of input, in miliseconds
        :type dt: float
        """
        self.times = np.arange(dt, duration + dt, dt)

    def generate_input(self, duration, dt):
        """
        Function to generate input.

        :param duration: duration of the input, in miliseconds
        :type duration: float
        :param dt: dt of input, in miliseconds
        :type dt: float
        """
        raise NotImplementedError

    def as_array(self, duration, dt):
        """
        Return input as numpy array.

        :param duration: duration of the input, in miliseconds
        :type duration: float
        :param dt: some reasonable "speed" of input, in miliseconds
        :type dt: float
        """
        return self.generate_input(duration, dt)

    def as_cubic_splines(self, duration, dt):
        """
        Return as cubic Hermite splines.

        :param duration: duration of the input, in miliseconds
        :type duration: float
        :param dt: some reasonable "speed" of input, in miliseconds
        :type dt: float
        """
        self._get_times(duration, dt)
        return CubicHermiteSpline.from_data(self.times, self.generate_input(duration, dt))

class StimulusInput(ModelInput):
    """
    Generates stimulus input with optional start and end times.
    """

    def __init__(
        self,
        stim_start=None,
        stim_end=None,
        num_iid=1,
        seed=None,
    ):
        """
        :param stim_start: start of the stimulus, in miliseconds
        :type stim_start: float
        :param stim_end: end of the stimulus, in miliseconds
        :type stim_end: float
        """
        self.stim_start = stim_start
        self.stim_end = stim_end
        super().__init__(
            num_iid=num_iid,
            seed=seed,
        )

    def _get_times(self, duration, dt):
        super()._get_times(duration=duration, dt=dt)
        self.stim_start = self.stim_start or 0.0
        self.stim_end = self.stim_end or duration + dt
        assert self.stim_start < duration
        assert self.stim_end <= duration + dt

    def _trim_stim_input(self, stim_input):
        """
        Trim stimulation input. Translate the start of the stimulation by
        padding with zeros and just nullify end of the stimulation.
        """
        # trim start
        how_much = int(np.sum(self.times <= self.stim_start))
        # translate start of the stim by padding the beginning with zeros
        stim_input = np.pad(stim_input, ((how_much, 0), (0, 0)), mode="constant")
        if how_much > 0:
            stim_input = stim_input[:-how_much, :]
        # trim end
        stim_input[self.times > self.stim_end] = 0.0
        return stim_input

class ConcatenatedInput(StimulusInput):
    """
    Represents concatenation of inputs - typically for stimulus plus noise.
    Supports concatenation of arbitrary many objects.
    """

    def __init__(self, noise_processes):
        """
        :param noise_processes: list of noise/stimulation processes to concatinate
        :type noise_processes: list[`ModelInput`]
        """
        assert all(isinstance(process, ModelInput) for process in noise_processes)
        self.noise_processes = noise_processes

    @property
    def num_iid(self):
        num_iid = set([process.num_iid for process in self.noise_processes])
        assert len(num_iid) == 1
        return next(iter(num_iid))

    def __add__(self, other):
        assert isinstance(other, ModelInput)
        assert self.num_iid == other.num_iid
        if isinstance(other, ConcatenatedInput):
            return ConcatenatedInput(noise_processes=self.noise_processes + other.noise_processes)
        else:
            return ConcatenatedInput(noise_processes=self.noise_processes + [other])

    def get_params(self):
        """
        Get parameters recursively from all input processes.
        """
        return {
            "type": self.__class__.__name__,
            **{f"noise_{i}": process.get_params() for i, process in enumerate(self.noise_processes)},
        }

    def update_params(self, params_dict):
        """
        Update all parameters recursively.
        """
        for i, process in enumerate(self.noise_processes):
            process.update_params(params_dict.get(f"noise_{i}", {}))

    def as_array(self, duration, dt):
        """
        Return sum of all processes as numpy array.
        """
        return np.sum(
            np.stack([process.as_array(duration, dt) for process in self.noise_processes]),
            axis=0,
        )

    def as_cubic_splines(self, duration, dt):
        """
        Return sum of all processes as cubic Hermite splines.
        """
        result = self.noise_processes[0].as_cubic_splines(duration, dt)
        for process in self.noise_processes[1:]:
            result.plus(process.as_cubic_splines(duration, dt))
        return result

class ZeroInput(ModelInput):
    """
    No noise input, i.e. all zeros. For convenience.
    """

    def generate_input(self, duration, dt):
        self._get_times(duration=duration, dt=dt)
        return np.zeros((self.times.shape[0], self.num_iid))

class WienerProcess(ModelInput):
    """
    Basic Wiener process, dW, i.e. drawn from standard normal N(0, sqrt(dt)).
    """

    def generate_input(self, duration, dt):
        self._get_times(duration=duration, dt=dt)
        return np.random.normal(0.0, np.sqrt(dt), (self.times.shape[0], self.num_iid))

class OrnsteinUhlenbeckProcess(ModelInput):
    """
    Ornstein–Uhlenbeck process, i.e.
        dX = (mu - X)/tau * dt + sigma*dW
    """

    def __init__(
        self,
        mu,
        sigma,
        tau,
        num_iid=1,
        seed=None,
    ):
        """
        :param mu: drift of the O-U process
        :type mu: float
        :param sigma: scale of the Wiener process
        :type sigma: float
        :param tau: O-U process timescale, same unit as time
        :type tau: float
        """
        self.mu = mu
        self.sigma = sigma
        self.tau = tau
        super().__init__(
            num_iid=num_iid,
            seed=seed,
        )

    def generate_input(self, duration, dt):
        self._get_times(duration=duration, dt=dt)
        x = np.random.rand(self.times.shape[0], self.num_iid) * self.mu
        return self.numba_ou(x, self.times, dt, self.mu, self.sigma, self.tau, self.num_iid)

    @staticmethod
    @numba.njit()
    def numba_ou(x, times, dt, mu, sigma, tau, num_iid):
        """
        Generation of Ornstein-Uhlenback process - wrapped in numba's jit for
        speed.
        """
        for i in range(times.shape[0] - 1):
            x[i + 1, :] = x[i, :] + dt * ((mu - x[i, :]) / tau) + sigma * np.sqrt(dt) * np.random.randn(num_iid)
        return x

class StepInput(StimulusInput):
    """
    Basic step process.
    """

    def __init__(
        self,
        step_size,
        stim_start=None,
        stim_end=None,
        num_iid=1,
        seed=None,
    ):
        """
        :param step_size: size of the stimulus
        :type step_size: float
        """
        self.step_size = step_size
        super().__init__(
            stim_start=stim_start,
            stim_end=stim_end,
            num_iid=num_iid,
            seed=seed,
        )

    def generate_input(self, duration, dt):
        self._get_times(duration=duration, dt=dt)
        return self._trim_stim_input(np.ones((self.times.shape[0], self.num_iid)) * self.step_size)

class SinusoidalInput(StimulusInput):
    """
    Sinusoidal input.
    """

    def __init__(
        self,
        amplitude,
        period,
        nonnegative=True,
        stim_start=None,
        stim_end=None,
        num_iid=1,
        seed=None,
    ):
        """
        :param amplitude: amplitude of the sinusoid
        :type amplitude: float
        :param period: period of the sinusoid, in miliseconds
        :type period: float
        :param nonnegative: whether the sinusoid oscillates around 0 point
            (False), or around its amplitude, thus is nonnegative (True)
        :type nonnegative: bool
        """
        self.amplitude = amplitude
        self.period = period
        self.nonnegative = nonnegative
        super().__init__(
            stim_start=stim_start,
            stim_end=stim_end,
            num_iid=num_iid,
            seed=seed,
        )

    def generate_input(self, duration, dt):
        self._get_times(duration=duration, dt=dt)
        sinusoid = self.amplitude * np.sin(2 * np.pi * self.times * (1.0 / self.period))
        if self.nonnegative:
            sinusoid += self.amplitude
        return self._trim_stim_input(np.vstack([sinusoid] * self.num_iid).T)

class SquareInput(StimulusInput):
    """
    Square input.
    """

    def __init__(
        self,
        amplitude,
        period,
        nonnegative=True,
        stim_start=None,
        stim_end=None,
        num_iid=1,
        seed=None,
    ):
        """
        :param amplitude: amplitude of the square
        :type amplitude: float
        :param period: period of the square, in miliseconds
        :type period: float
        :param nonnegative: whether the square oscillates around 0 point
            (False), or around its amplitude, thus is nonnegative (True)
        :type nonnegative: bool
        """
        self.amplitude = amplitude
        self.period = period
        self.nonnegative = nonnegative
        super().__init__(
            stim_start=stim_start,
            stim_end=stim_end,
            num_iid=num_iid,
            seed=seed,
        )

    def generate_input(self, duration, dt):
        self._get_times(duration=duration, dt=dt)
        square_inp = self.amplitude * square(2 * np.pi * self.times * (1.0 / self.period))
        if self.nonnegative:
            square_inp += self.amplitude
        return self._trim_stim_input(np.vstack([square_inp] * self.num_iid).T)

class LinearRampInput(StimulusInput):
    """
    Linear ramp input.
    """

    def __init__(
        self,
        inp_max,
        ramp_length,
        stim_start=None,
        stim_end=None,
        num_iid=1,
        seed=None,
    ):
        """
        :param inp_max: maximum of stimulus
        :type inp_max: float
        :param ramp_length: length of linear ramp, in miliseconds
        :type ramp_length: float
        """
        self.inp_max = inp_max
        self.ramp_length = ramp_length
        super().__init__(
            stim_start=stim_start,
            stim_end=stim_end,
            num_iid=num_iid,
            seed=seed,
        )

    def generate_input(self, duration, dt):
        self._get_times(duration=duration, dt=dt)
        # need to adjust times for stimulus start
        times = self.times - self.stim_start
        linear_inp = (self.inp_max / self.ramp_length) * times * (times < self.ramp_length) + self.inp_max * (
            times >= self.ramp_length
        )
        return self._trim_stim_input(np.vstack([linear_inp] * self.num_iid).T)

class ExponentialInput(StimulusInput):
    """
    Exponential rise or decay input.
    """

    def __init__(
        self,
        inp_max,
        exp_coef=30.0,
        exp_type="rise",
        stim_start=None,
        stim_end=None,
        num_iid=1,
        seed=None,
    ):
        """
        :param inp_max: maximum of stimulus
        :type inp_max: float
        :param exp_coeficient: coeffiecent for exponential, the higher the
            coefficient is, the faster it rises or decays
        :type exp_coeficient: float
        :param exp_type: whether its rise or decay
        :type exp_type: str
        """
        self.inp_max = inp_max
        self.exp_coef = exp_coef
        assert exp_type in ["rise", "decay"]
        self.exp_type = exp_type
        super().__init__(
            stim_start=stim_start,
            stim_end=stim_end,
            num_iid=num_iid,
            seed=seed,
        )

    def generate_input(self, duration, dt):
        self._get_times(duration=duration, dt=dt)
        exponential = np.exp(-(self.exp_coef / self.times[-1]) * self.times) * self.inp_max
        if self.exp_type == "rise":
            exponential = -exponential + self.inp_max
        return self._trim_stim_input(np.vstack([exponential] * self.num_iid).T)

def construct_stimulus(
    stim="dc",
    duration=6000,
    dt=0.1,
    stim_amp=0.2,
    stim_freq=1,
    stim_bias=0,
    n_periods=None,
    nostim_before=0,
    nostim_after=0,
):
    """Constructs a stimulus that can be applied to a model

    :param stim: Stimulation type: 'ac':oscillatory stimulus, 'dc': stimple step current,
                'rect': step current in negative then positive direction with slowly
                decaying amplitude, used for bistability detection, defaults to 'dc'
    :type stim: str, optional
    :param duration: Duration of stimulus in ms, defaults to 6000
    :type duration: int, optional
    :param dt: Integration time step in ms, defaults to 0.1
    :type dt: float, optional
    :param stim_amp: Amplitude of stimulus (for AdEx: in mV/ms, multiply by conductance C to get current in pA), defaults to 0.2
    :type stim_amp: float, optional
    :param stim_freq: Stimulation frequency, defaults to 1
    :type stim_freq: int, optional
    :param stim_bias: Stimulation offset (bias), defaults to 0
    :type stim_bias: int, optional
    :param n_periods: Numer of periods of stimulus, defaults to None
    :type n_periods: [type], optional
    :param nostim_before: Time before stimulation, defaults to 0
    :type nostim_before: int, optional
    :param nostim_after: Time after stimulation, defaults to 0
    :type nostim_after: int, optional
    :raises ValueError: Raises error if unsupported stimulus type is chosen.
    :return: Stimulus timeseries
    :rtype: numpy.ndarray
    """
    """Constructs a sitmulus that can be applied as input to a model

    TODO: rewrite

    stim:       Stimulus type: 'ac':oscillatory stimulus, 'dc': stimple step current,
                'rect': step current in negative then positive direction with slowly
                decaying amplitude, used for bistability detection
    stim_amp:   Amplitude of stimulus (for AdEx: in mV/ms, multiply by conductance C to get current in pA)
    """

    def sinus_stim(f=1, amplitude=0.2, positive=0, phase=0, cycles=1, t_pause=0):
        x = np.linspace(np.pi, -np.pi, int(1000 / dt / f))
        sinus_function = np.hstack(((np.sin(x + phase) + positive), np.tile(0, t_pause)))
        sinus_function *= amplitude
        return np.tile(sinus_function, cycles)

    if stim == "ac":
        """Oscillatory stimulus"""
        n_periods = n_periods or int(stim_freq)

        stimulus = np.hstack(
            (
                [stim_bias] * int(nostim_before / dt),
                np.tile(sinus_stim(stim_freq, stim_amp) + stim_bias, n_periods),
            )
        )
        stimulus = np.hstack((stimulus, [stim_bias] * int(nostim_after / dt)))
    elif stim == "dc":
        """Simple DC input and return to baseline"""
        stimulus = np.hstack(([stim_bias] * int(nostim_before / dt), [stim_bias + stim_amp] * int(1000 / dt)))
        stimulus = np.hstack((stimulus, [stim_bias] * int(nostim_after / dt)))
        stimulus[stimulus < 0] = 0
    elif stim == "rect":
        """Rectified step current with slow decay"""
        # construct input
        stimulus = np.zeros(int(duration / dt))
        tot_len = int(duration / dt)
        stim_epoch = tot_len / 6

        stim_increase_counter = 0
        stim_decrease_counter = 0
        stim_step_increase = 5.0 / stim_epoch

        for i, m in enumerate(stimulus):
            if 0 * stim_epoch <= i < 0.5 * stim_epoch:
                stimulus[i] -= stim_amp
            elif 0.5 * stim_epoch <= i < 3.0 * stim_epoch:
                stimulus[i] = -np.exp(-stim_increase_counter) * stim_amp
                stim_increase_counter += stim_step_increase
            elif 3.0 * stim_epoch <= i < 3.5 * stim_epoch:
                stimulus[i] += stim_amp
            elif 3.5 * stim_epoch <= i < 5 * stim_epoch:
                stimulus[i] = np.exp(-stim_decrease_counter) * stim_amp
                stim_decrease_counter += stim_step_increase
    else:
        raise ValueError(f'Stimulus {stim} not found. Use "ac", "dc" or "rect".')

    # repeat stimulus until full length
    steps = int(duration / dt)
    stimlength = int(len(stimulus))
    stimulus = np.tile(stimulus, int(steps / stimlength + 2))
    stimulus = stimulus[:steps]

    return stimulus


#! /usr/bin/env python2
# -*- coding: utf-8 -*-

import pygame
import sys
from pygame.locals import *

# inicjacja modułu pygame
pygame.init()

# szerokość i wysokość okna gry
OKNOGRY_SZER = 800
OKNOGRY_WYS = 400
# kolor okna gry, składowe RGB zapisane w tupli
LT_BLUE = (230, 255, 255)

# powierzchnia do rysowania, czyli inicjacja okna gry
oknogry = pygame.display.set_mode((OKNOGRY_SZER, OKNOGRY_WYS), 0, 32)
# tytuł okna gry
pygame.display.set_caption('Prosty Pong')

# paletka gracza #########################################################
PALETKA_SZER = 100  # szerokość
PALETKA_WYS = 20  # wysokość
BLUE = (0, 0, 255)  # kolor wypełnienia
PALETKA_1_POZ = (350, 360)  # początkowa pozycja zapisana w tupli
# utworzenie powierzchni paletki, wypełnienie jej kolorem,
paletka1 = pygame.Surface([PALETKA_SZER, PALETKA_WYS])
paletka1.fill(BLUE)
# ustawienie prostokąta zawierającego paletkę w początkowej pozycji
paletka1_prost = paletka1.get_rect()
paletka1_prost.x = PALETKA_1_POZ[0]
paletka1_prost.y = PALETKA_1_POZ[1]

# pętla główna programu
while True:
    # obsługa zdarzeń generowanych przez gracza
    for event in pygame.event.get():
        # przechwyć zamknięcie okna
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

        # przechwyć ruch myszy
        if event.type == MOUSEMOTION:
            myszaX, myszaY = event.pos  # współrzędne x, y kursora myszy

            # oblicz przesunięcie paletki gracza
            przesuniecie = myszaX - (PALETKA_SZER / 2)

            # jeżeli wykraczamy poza okno gry w prawo
            if przesuniecie > OKNOGRY_SZER - PALETKA_SZER:
                przesuniecie = OKNOGRY_SZER - PALETKA_SZER
            # jeżeli wykraczamy poza okno gry w lewo
            if przesuniecie < 0:
                przesuniecie = 0
            # zaktualizuj położenie paletki w poziomie
            paletka1_prost.x = przesuniecie

    # rysowanie obiektów
    oknogry.fill(LT_BLUE)  # kolor okna gry

    # narysuj w oknie gry paletki
    oknogry.blit(paletka1, paletka1_prost)

    # zaktualizuj okno i wyświetl
    pygame.display.update()

# KONIEC


import os
import numpy as np
import pandas as pd

from sklearn.metrics import mean_squared_error
from xgboost import XGBRegressor
import lightgbm as lgb
from sklearn.neural_network import MLPRegressor
from sklearn.ensemble import RandomForestRegressor,ExtraTreesRegressor
from sklearn.ensemble import BaggingRegressor
from sklearn.linear_model import LinearRegression,BayesianRidge

from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import KFold
from sklearn.preprocessing import StandardScaler, MinMaxScaler,PolynomialFeatures
import warnings
warnings.filterwarnings("ignore")

def rmse(y_true,y_pred):
    return mean_squared_error(y_true=y_true,y_pred=y_pred) ** 0.5

def halfmse(y_true,y_pred):
    return mean_squared_error(y_true=y_true,y_pred=y_pred) * 0.5

params_dict = {
    'random_forest':{
        'n_estimators':range(10,150,10),
        'criterion':['mse']
    },
    'extra_trees':{
        'n_estimators':range(10,150,10),
        'criterion':['mse']
    },
    'bagging':{
        'n_estimators':range(10,150,10),
    },
    'mlp':{
        'alpha':[0.01,0.001,0.1],
        'hidden_layer_sizes':[(10,10)],
        'solver':['lbfgs'],
        'activation':['identity'],
        'learning_rate':['constant']
    },
    # 'xgboost':{
    #     'n_estimators':range(100,150,5),
    #     'max_depth':range(10,15,2),
    #     'learning_rate':np.linspace(0.05,0.1,2),
    #     'subsample':np.linspace(0.7,0.9,2)
    # }
    'xgboost':{
        'n_estimators':[10000],
        'max_depth':[15],
        'learning_rate':[0.05],
        'subsample':[0.8]
    },
    'lgb':{
        'num_leaves': [60],
        'min_data_in_leaf': [30],
        'learning_rate': [0.001],
        "min_child_samples": [30],
        "feature_fraction": [0.9],
    },
    'lr':{
        'normalize':[False]
    },
    'br':{
        'n_iter':[3000]
    },
    'poly':{
        'fit_intercept':[False]
    }
}

class ML_Classifier(object):
  '''
  Machine Learning Classifier for the classification
  Args:
  - clf_name, string, __all__ = ['lasso','knn','svm','decision tree','random forest','extra trees','bagging','mlp','xgboost']
  - params_dict, dict, parameters setting of the specified classifer
  '''
  def __init__(self,clf_name=None,params=None):
    super(ML_Classifier,self).__init__()
    self.clf_name = clf_name
    self.params = params
    self.clf = self._get_clf()

  def trainer(self,train_df,target_key,random_state=21,metric=None,k_fold=5,scale_flag=None,pred_flag=False,test_df=None,test_csv=None,save_path=None):
    params = self.params
    fea_list= [f for f in train_df.columns if f != target_key]
    print('feature list:',fea_list)

    Y = np.asarray(train_df[target_key])
    if scale_flag:
        scaler = StandardScaler()
        Y =  scaler.fit_transform(Y.reshape(-1, 1))

    X = np.asarray(train_df[fea_list])
    test = np.asarray(test_df[fea_list])

    kfold = KFold(n_splits=k_fold,shuffle=True,random_state=random_state)
    if self.clf_name == 'poly':
        # poly = PolynomialFeatures(interaction_only=True)
        poly = PolynomialFeatures()
        X = poly.fit_transform(X)
        test = poly.fit_transform(test)

    print(X)
    print(test)
    print(X.shape,test.shape)
    predictions = []
    add_fold_num = 0
    for fold_num,(train_index,val_index) in enumerate(kfold.split(X)):
        print(f'***********fold {fold_num+1} start!!***********')
        x_train, x_val = X[train_index], X[val_index]
        y_train, y_val = Y[train_index], Y[val_index]
        # print(x_val,y_val)
        model = GridSearchCV(estimator=self.clf,
                            param_grid=params,
                            cv=kfold,
                            scoring=metric,
                            refit='neg_mse',
                            verbose=True,
                            return_train_score=False)
        model = model.fit(x_train,y_train)

        best_score = model.best_score_
        best_model = model.best_estimator_
        train_pred = model.predict(x_train)
        train_score = halfmse(y_train,train_pred)
        test_pred = model.predict(x_val)
        test_score = halfmse(y_val,test_pred)
        print("MSE Evaluation:")
        print("fold {} Best score:{}".format(fold_num + 1,best_score))
        print("fold {} Train score:{}".format(fold_num + 1,train_score))
        print("fold {} Test score:{}".format(fold_num + 1,test_score))
        print("fold {} Best parameter:\n".format(fold_num + 1))
        for key in params.keys():
            print('%s:'%key)
            print(best_model.get_params()[key])

        if self.clf_name == 'random_forest' or self.clf_name == 'extra_trees':
            if self.clf_name == 'random_forest':
                new_grid = RandomForestRegressor(random_state=0,bootstrap=True)
            elif self.clf_name == 'extra_trees':
                new_grid = ExtraTreesRegressor(random_state=0,bootstrap=True)
            new_grid.set_params(**model.best_params_)

            new_grid = new_grid.fit(x_train,y_train)
            importances = new_grid.feature_importances_
            feat_labels = fea_list
            # print(feat_labels)
            indices = np.argsort(importances)[::-1]

            # print(indices)
            for f in range(x_train.shape[1]):
                print("%2d) %-*s %f" % (f + 1,30, feat_labels[indices[f]], importances[indices[f]]))

        if pred_flag and test is not None:
            pred = model.predict(test)
            if test_score < 1.0:
                add_fold_num += 1
                print(f'add fold {fold_num+1}')
                predictions.append(pred)
    predictions = sum(predictions) / add_fold_num

    pred_df = pd.read_csv(test_csv, encoding='gbk')

    if scale_flag:
        predictions = scaler.inverse_transform(predictions)
    pred_df['label'] = predictions
    pred_df['label'].to_csv(f'{save_path}/{self.clf_name}_result.csv',index=False)
    return best_model

  def _get_clf(self):
    if self.clf_name == 'xgboost':
        classifier = XGBRegressor()
    elif self.clf_name == 'mlp':
        classifier = MLPRegressor(max_iter=2000,warm_start=True,random_state=2021)
    elif self.clf_name == 'random_forest':
        classifier = RandomForestRegressor(random_state=2021,bootstrap=True)
    elif self.clf_name == 'extra_trees':
        classifier = ExtraTreesRegressor(random_state=2021,bootstrap=True)
    elif self.clf_name == 'bagging':
        classifier = BaggingRegressor(random_state=2021)
    elif self.clf_name == 'lgb':
        classifier = lgb.LGBMRegressor(seed=2021)
    elif self.clf_name == 'lr':
        classifier = LinearRegression()
    elif self.clf_name == 'br':
        classifier = BayesianRidge()
    elif self.clf_name == 'poly':
        classifier = LinearRegression()

    return classifier


#import importlib ; import twomodeMI
#importlib.reload(twomodeMI) ; twomodeMI.allMI()

#================================================================

def allMI(datdir = "./POST/post05", datpkl = "./POST/post05_mi.pkl"):

    import numpy as np
    import pickle
    import os

    dat = list()

    #-- read all files in directory, compute MI, store in"dat" --

    for file in os.listdir(datdir):
        if file.endswith(".P123"):
            fbase = file[:-5]
            dat0 = MI(datdir + "/" + fbase)
            dat.append(dat0)

    keys = dat0.keys()

    #-- find and sort all "chi" --

    allchi = set()
    for d in dat:
        allchi.add(d['chi'])
    allchi = list(allchi)
    allchi.sort()

    #-- for each "chi" sort by "dTT" --

    def myFunc(e):
        return e['dTT']

    alldict = list()

    for chi in allchi:

        thisdict = dict.fromkeys(keys, 0)

        dat0 = list()
        for d in dat:
            if d['chi'] == chi:
                dat0.append(d)
        dat0.sort(key=myFunc)

        for key in keys:
            values = list()
            for d in dat0:
                values.append(d[key])
            thisdict[key] = np.array(values)

        thisdict['chi'] = round(chi, 6)

        alldict.append(thisdict)

    #-- save list of dictionaries as pickle --

    with open(datpkl, 'wb') as handle:
        pickle.dump(alldict, handle, protocol=pickle.HIGHEST_PROTOCOL)

#================================================================

def MI(fbase):

    import numpy as np

    pi = np.pi

    param = ReadParam(fbase + ".param")
    P123  = ReadData(fbase + ".P123", param)  #P123[Nphi, nN2, nN1]

    nN1=param["nN1"]
    nN2=param["nN2"]
    nPhi=param["nPhi"]

    dn1  = param["max_N1"]/nN1
    dn2  = param["max_N2"]/nN2
    dphi = 2*pi/nPhi

    #-- normalize and integrate probabilities --

    ncount = P123.sum()

    P123 = P123 / (ncount *dn1*dn2*dphi)

    P1   = P123.sum((0,1))    *dn2*dphi
    P2   = P123.sum((0,2))*dn1    *dphi
    Pphi = P123.sum((1,2))*dn1*dn2

    #--  averages for staircase distribution --

    n = (np.arange(0,nN1)+0.5)*dn1
    navg1s = sum(P1*n)/sum(P1)

    n = (np.arange(0,nN2)+0.5)*dn2
    navg2s = sum(P2*n)/sum(P2)

    #-- Entropy of 3D distribution (n1,n2,theta) --

    ind = (P123>0);  S12 = -np.sum(P123[ind]* np.log2(P123[ind])) *dn1*dn2*dphi

    #-- Entropy of 1D distributions --

    ind = (P1>0);    S1  = -np.sum(P1[ind] * np.log2(P1[ind])) * dn1
    ind = (P2>0);    S2  = -np.sum(P2[ind] * np.log2(P2[ind])) * dn2
    ind = (Pphi>0);  Sphi  = -np.sum(Pphi[ind] * np.log2(Pphi[ind])) * dphi

    #-- Equilibrium, assuming exponential fit with <n_i> and equidistribution for theta --

    S1s = 1/np.log(2) * (1 + np.log(navg1s));
    S2s = 1/np.log(2) * (1 + np.log(navg2s));
    Sph0 = np.log2(2*pi);

    #-- Mutual information --

    I12  = S1 + S2 + Sph0 - S12

    #-- Output to dictionary --

    g1 = param["g1"]
    g2 = param["g2"]
    p1 = param["p1"]
    p2 = param["p2"]

    T = (p1 + 2*p2)/2/(g1+g2)
    chi = (g1 + g2)**2 /2/T

    try:
        dT = p1/g1 - 2*p2/g2
        dTT = dT/T
    except:
        if g1 == 0:
            dTT =  999
        else:
            dTT = -999

    datout = {"chi":  chi,
              "dTT":  dTT,
              "S12":  S12,
              "S1":   S1,
              "S2":   S2,
              "Sphi": Sphi,
              "I12":  I12,
              "n1s":  navg1s,
              "n2s":  navg2s,
              "ntot": ncount
              }

    return(datout)

#================================================================

def ReadParam(fname):

    param = {
        "ntot":   0,
        "nPhi":   0,
        "nN1":    0,
        "nN2":    0,
        "max_N1": 0.0,
        "max_N2": 0.0,
        "g1":     0.0,
        "g2":     0.0,
        "p1":     0.0,
        "p2":     0.0
    }

    f = open(fname, 'r')
    s = f.read()
    f.close()

    ss = s.split("\n\n")

    for s in ss:

        s1 = s.replace("\n#", ";")
        s2 = s1.split("\n")

        for i in param:

            if ( s2[0].count('name: '+i) > 0):
                param[i] = type(param[i])(s2[1])

    return(param)

#================================================================

def ReadData(fname, param):

    import os
    import numpy as np

    dat = np.fromfile(fname, 'uint32')
    dat = dat.reshape(param['nPhi'], param['nN2'], param['nN1'])

    if param['ntot'] !=  np.sum(dat):
        print('ERROR: Mispatch in size of data, ntot = {}, nread={}'.format(param['ntot'], np.sum(dat)))

    return(dat)

#================================================================


from fastapi import APIRouter

from database import SESSION
from database import Stock, database_Stock, Favorite, database_Favorite

router = APIRouter()

@router.get("/stock")
async def get_stock(numbers: int):
    stock_info = SESSION.query(database_Stock).filter(database_Stock.number == numbers).first()
    return stock_info

@router.get("/user")
async def get_favorite(user: str):
    user_favorite = SESSION.query(database_Favorite).filter(database_Favorite.user == user).all()
    broad_market_index = database_Stock(
        **{
            "number": 0,
            "name": "大盤指數",
            "high_price": 17500,
            "low_price": 17304,
            "start_price": 17444,
            "now_price": 17374,
            "price_increase": (17374-17444)
        }
    )
    data = [broad_market_index]
    for favorite_list in user_favorite:
        stock_info = SESSION.query(database_Stock).filter(database_Stock.number == favorite_list.number).first()
        data.append(stock_info)
    return data

def add_stock(stock_info: Stock):
    new_stack_info = database_Stock(
        **{
            "number": stock_info.number,
            "name": stock_info.name,
            "high_price": stock_info.high_price,
            "low_price": stock_info.low_price,
            "start_price": stock_info.start_price,
            "now_price": stock_info.now_price,
            "price_increase": stock_info.price_increase
        }
    )
    SESSION.add(new_stack_info)
    SESSION.commit()
    SESSION.refresh(new_stack_info)


import sys

sys.path.append(sys.path[0] + "/...")

from Search.Src.TestBase.WebDriverSetup import WebDriverSetup
from Search.Src.PageObject.Pages.HomePage import Home
import unittest
from selenium import webdriver
from Search.Src.Utils.Utils import Utils

class Google_HomePage(WebDriverSetup):
    def test_Home_Page(self):
        driver = self.driver
        self.driver.get("https://www.google.com/")
        # self.driver.set_page_load_timeout(30)
        Utils.page_is_loading(self.driver)

        web_page_title = "Google"
        try:
            if driver.title == web_page_title:
                print("WebPage loaded successfully")
                self.assertEqual(driver.title, web_page_title)
        except Exception as error:
            print(error + "WebPage Failed to load")

        # Create an instance of the class so that you we can make use of the methods
        # in the class
        home_page = Home(driver)

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


from django.contrib.gis.db import models as gismodel
from django.utils.translation import gettext_lazy as _
from django.utils import translation
from functools import partialmethod
from functools import partial
from geopy.geocoders import Nominatim

def _get_city_name(self, field):
    # print("maps.gisFields.PointField.getCityName")
    user_agent = "https://nominatim.openstreetmap.org/"
    geolocator = Nominatim(user_agent=user_agent)
    lang = translation.get_language()
    reverse = partial(geolocator.reverse, language="{}".format(lang))
    try:
        location = reverse("{lat}, {lon}".format(lat=self.city.y, lon=self.city.x))
        city = location.raw.get('address').get("city")
        country = location.raw.get('address').get("country")
        return "{} ({})".format(city, country)
    except:
        return ""

def _get_city_latlon(self, field):
    # print("maps.gisFields.PointField._get_city_latlon")
    return "Lat {:.2f}; Lon {:.2f}".format(self.city.y, self.city.x)

class PointField(gismodel.PointField):
    description = _("The base GIS field with digisafe custom methods.")

    def contribute_to_class(self, cls, name, **kwargs):
        # print("maps.gisFields.PointField.contribute_to_class")
        # print(cls, name)
        # print(kwargs)
        super().contribute_to_class(cls, name, **kwargs)
        setattr(
            cls, f'get_{name}_name',
            partialmethod(_get_city_name, field=self)
        )
        setattr(
            cls, f'get_{name}_latlon',
            partialmethod(_get_city_latlon, field=self)
        )


import os, re

image_path = f'../nerve_dataset/nerve_masks'

image_names = [f for f in os.listdir(image_path) if os.path.join(image_path, f).find('desktop') == -1]

name_dict = {}
movie_count = 1

for image_name in image_names:
    # title = image_name.split('.')[0]
    # if title not in name_dict:
    #     name_dict[title] = f'movie_{movie_count}'
    #     movie_count += 1
    image_name_new = image_name.replace('_nerve', '')
    os.rename(f'{image_path}/{image_name}', f'{image_path}/{image_name_new}')


#=============================================================
# File Name: start_endwith.py
# Author: miclefeng
# mail: miclefengzss@163.com
# Created Time: Tue 05 Jun 2018 11:58:58 AM CST
#=============================================================
# coding:utf8

from urllib.request import urlopen

filenames = [ 'Makefile', 'foo.c', 'bar.py', 'spam.c', 'spam.h' ]
print("endswith, startswith 参数需要是 str 或者 tuple 类型")
print([name for name in filenames if name.endswith(('.c', '.h'))])
print(any(name.endswith('.py') for name in filenames))

def read_data(name):
    if name.startswith(('http:', 'https:', 'ftp:')):
        return urlopen(name).read()
    else:
        with open(name) as f:
            return f.read()

# print(str(read_data('http://www.baidu.com'), encoding='utf-8'))
# print(read_data('./re_split.py'))


import tcod

from game_states import GameStates
from render_functions import RenderOrder
from game_messages import Message
from components.item import Item

def kill_player(player):
    player.char = '%'
    player.color = tcod.dark_red

    return Message('You died!', tcod.dark_red), GameStates.PLAYER_DEAD

def kill_entity(entity):
    death_message = None
    if entity.ai:
        death_message = Message("The {0} dies!".format(entity.name), tcod.dark_red)

        entity.char = '%'
        entity.color = tcod.dark_red
        entity.blocks = False
        entity.ai = None
        entity.fighter = None
        entity.name = entity.name + " corpse"
        entity.render_order = RenderOrder.CORPSE
        entity.item = Item()

    return death_message


from __future__ import print_function
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from mysql_demo import insert_course

# If modifying these scopes, delete the file token.json.
SCOPES = 'https://www.googleapis.com/auth/classroom.courses.readonly'

def get_courses():
    '''
    Get a list of the students (and their corresponding ids) from the target course roster.
    :param temp_id:
    :return:
    '''
    store = file.Storage('tokencl.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
        creds = tools.run_flow(flow, store)
    service = build('classroom', 'v1', http=creds.authorize(Http()))

    results = service.courses().list().execute()
    course_list = results.get('courses', [])

    simple_list = [[] for course in course_list]

    count = 0
    for course in course_list:
        simple_list[count].append(course['id'])
        simple_list[count].append(course['name'])
        count += 1
    return simple_list

if __name__ == '__main__':
    courses = get_courses()
    for course in courses:
        insert_course(course)


from __future__ import annotations
from dataclasses import dataclass

import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate, optimize
import torch
from xitorch.optimize import rootfinder
from xitorch.integrate import quad
from xitorch.interpolate import Interp1D

DEFAULT_TEMPERATURE = torch.Tensor([8])

@dataclass
class ThermodynamicalProperties:
    temperature: torch.Tensor
    electron_density: torch.Tensor
    _chemical_potential: torch.Tensor
    chemical_potential_error: torch.Tensor
    dos: object
    fermi_energy: torch.Tensor | None = None

    @property
    def chemical_potential(self):
        raise NotImplementedError("Cannot use the ThermodynamicalProperties class directly.")

    @staticmethod
    def generic_thermal_factor(
        energy: torch.Tensor | float,
        chemical_potential: float,
        temperature: float
    ) -> torch.Tensor | float:
        """signal()
        Parameters
        ----------
        energy : energy of the electronic level [eV]
        chemical_potential : chemical potential [eV]
        temperature : Temperature of the system [eV]

        Returns
        -------
        Thermal factor of energy

        """
        if not isinstance(chemical_potential, torch.Tensor):
            chemical_potential = torch.tensor(chemical_potential).float()
        return 1.0 / (1 + torch.exp((chemical_potential - energy) / temperature))

    def thermal_factor(self, energy: torch.Tensor | float) -> torch.Tensor | float:
        thermal_fac = ThermodynamicalProperties.generic_thermal_factor(
            energy.detach(), self.chemical_potential, self.temperature
        )
        return thermal_fac

class ApproximateThermals(ThermodynamicalProperties):
    @staticmethod
    def fermi_energy_solver(
        dos: object,
        electron_density: float,
        fermi_guess: float = 1.
    ) -> torch.Tensor:
        energies = dos.energies.detach().numpy()
        delta = energies[1] - energies[0]

        def integrand(fermi_energy):
            return np.where(energies < fermi_energy, dos.density, 0)

        def difference(fermi_energy):
            integral = integrate.trapz(integrand(fermi_energy), dx=delta)

            return electron_density - integral

        vfunc = np.vectorize(difference)

        fermi_energy_exit = optimize.fsolve(vfunc, fermi_guess)

        error = difference(fermi_energy_exit)
        return torch.tensor(fermi_energy_exit).float()

    @staticmethod
    def chemical_potential_fit(temp: float, fermi_energy: float) -> float:
        '''
        Parameters
        ----------
        temp: temperature of the system
        fermi_energy: fermi energy of the system

        Returns
        -------
        Chemical potential approximation for the given fermi energy and temperature
        '''

        # uniform electron gas
        # fermi_energy = hartree * 0.5 * (3 * np.pi ** 2 * electron_density) ** (2 / 3)

        part_1 = -0.28468 - 1.5 * torch.log(temp / fermi_energy)

        part_2_num = (
            0.25945 * (temp / fermi_energy) ** (-1.858)
            + 0.072 * (temp / fermi_energy) ** (-0.929)
        )

        part_2_denom = (1 + 0.25945 * (temp / fermi_energy) ** (-0.858))

        eta = part_1 + part_2_num / part_2_denom
        return eta * temp

    @property
    def chemical_potential(self):
        return ApproximateThermals.chemical_potential_fit(
            self.temperature,
            self.fermi_energy.detach()
        )

    @classmethod
    def create(
        cls,
        dos: object,
        temperature: float,
        electron_density: float,
    ) -> ThermodynamicalProperties:
        # This separates out the fitting of the fermi energy from the chemical potential
        fermi_energy = ApproximateThermals.fermi_energy_solver(dos, electron_density)
        chemical_potential = ApproximateThermals.chemical_potential_fit(
            temperature,
            fermi_energy
        )

        return cls(
            temperature=temperature.requires_grad_().float(),
            electron_density=electron_density,
            _chemical_potential=chemical_potential,
            chemical_potential_error=0.0,  # This is not accurate (there is a propagated error)
            dos=dos,
            fermi_energy=fermi_energy
        )

class ExactThermals(ThermodynamicalProperties):
    @property
    def chemical_potential(self):
        return self._chemical_potential

    @staticmethod
    def chemical_potential_solver(
        temperature: float,
        chem_pot_guess: float,
        rho: float,
        dos: torch.Tensor,
        energies: torch.Tensor
    ) -> tuple[float, float]:
        """
        Parameters
        ----------
        temperature : temperature of the system (in eV)
        rho : density of the system
              (# of electrons in the bands present in the DOS taken into consideration / V)
        dos : Density of states (# states/ (eV*V))

        Warning: The volume for rho and the DOS must be expressed in the same units

        Returns
        -------
        Chemical potential

        """
        temperature = temperature.detach().numpy()
        rho = rho.detach().numpy()
        dos = dos.detach()
        energies = energies.detach().numpy()

        delta = energies[1] - energies[0]

        def integrand(mu_prime):
            # vectorized version should be faster than loop
            def partial_thermal(energy):
                return ThermodynamicalProperties.generic_thermal_factor(
                    energy, mu_prime, temperature
                )

            return dos * (1 - partial_thermal(energies))

        def difference(chemical_potential):
            integral = integrate.trapz(integrand(chemical_potential), dx=delta)

            return rho - integral

        vfunc = np.vectorize(difference)

        chem_pot_exit = optimize.fsolve(vfunc, chem_pot_guess)

        error = difference(chem_pot_exit)

        return chem_pot_exit, error

    @classmethod
    def create(
        cls,
        dos: object,
        temperature: float,
        electron_density: float,
        guess: float = 1,
        chemical_potential: torch.Tensor | None = None,
    ) -> ThermodynamicalProperties:
        if chemical_potential is None:
            (
                chemical_potential,
                error,
            ) = ExactThermals.chemical_potential_solver(
                temperature=temperature,
                chem_pot_guess=guess,
                rho=electron_density,
                dos=dos.density,
                energies=dos.energies,
            )

            # assert abs(error / chemical_potential) < 1e-5
            chemical_potential = torch.tensor(chemical_potential)
        else:
            error = 0.0

        return cls(
            temperature=temperature,
            electron_density=electron_density,
            _chemical_potential=chemical_potential,
            chemical_potential_error=torch.tensor(error),
            dos=dos,
        )

class DifferentiableExactThermals(ExactThermals):

    @property
    def chemical_potential(self):
        return DifferentiableExactThermals.chemical_potential_solver(
            self.temperature.detach(),
            torch.tensor([1.]).detach(),
            self.electron_density.detach(),
            self.dos.density.detach(),
            self.dos.energies.detach()
        )[0]

    @classmethod
    def create(
        cls,
        dos: object,
        temperature: float,
        electron_density: float,
        guess: float = 1,
        chemical_potential: torch.Tensor | None = None,
    ) -> ThermodynamicalProperties:
        return super(DifferentiableExactThermals, cls).create(
            dos,
            temperature.requires_grad_().float(),
            electron_density,
            guess=guess,
            chemical_potential=chemical_potential
        )

def get_thermals(
    dos: object,
    temperature: torch.Tensor,
    electron_density: torch.Tensor,
    thermals_type: str = "exact",
    kwargs: dict[str, object] | None = None
) -> ThermodynamicalProperties:
    """Factory to create different subclasses of ThermodynamicalProperties.

    Args:
        dos:
        temperature:
        electron_density:
        approximate:
        kwargs:

    Returns:

    """
    if kwargs is None:
        kwargs = {}
    assert thermals_type in ("exact", "approximate", "exact_differentiable")
    if thermals_type == "approximate":
        return ApproximateThermals.create(dos, temperature, electron_density, **kwargs)
    elif thermals_type == "exact_differentiable":
        return DifferentiableExactThermals.create(dos, temperature, electron_density, **kwargs)
    return ExactThermals.create(dos, temperature, electron_density, **kwargs)


'''
카데인 알고리즘: 연속된 부분합을 구하기 위한 알고리즘.. DP에서 효율적으로 공간을 사용한 알고리즘이다.
Max Sum SubArray를 구하는 방법은 다음과 같다.
Dp[i] = max(A[i], Dp[i-1] + A[i])
A[i]는 단 하나의 값, Dp[i-1]은 이전까지 최대 부분합이다. 단일 값이 더 크다면 단일값으로 초기화해서 연속된 부분합을 구한다.

바로 이전이 MaxSum SubArray라면 여러개의 공간을 둘 필요 없이 변수 하나에 계속해서 갱신해서 저장해주어도 된다.
'''

from typing import List

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        '''최대 하위 배열 합계는
            하위 배열의 합계이거나 요소 자체

        Parameters
        ----------
        nums : List[int]
            목록[int]

        Returns
        -------
            부분배열의 최대 합
        '''

        sum = 0
        max_sum = -1000000000000
        for num in nums:
            sum = max(sum+num, num)
            max_sum = max(max_sum, sum)

        return max_sum


#!/usr/bin/env python
# coding: utf-8

# ## Mi primer proyecto
# Volvemos a encontrarnos con el conjunto de datos de pingüinos `PalmerPenguins`. Esta vez trabajaremos con ellos desde `Python`, para ello instalaremos el paquete que nos permitirá cargarlo:
#

# In[2]:

get_ipython().system('pip install palmerpenguins')

# En segundo lugar, importaremos las librerías necesarias:

# In[49]:

import pandas as pd
from palmerpenguins import load_penguins

# Ahora ya estamos en posición de empezar a trabajar con los datos.
#
# 1. Vamos a cargar el conjunto de datos. Muestra por pantalla el número de observaciones y sus características. Mira el tipo de datos de cada una de sus columnas.

# In[50]:

penguins = load_penguins()
penguins.shape

# In[51]:

penguins.info

# In[52]:

penguins.columns

# 2. Ya sabemos que este conjunto de datos tiene observaciones `NA`. Vamos a eliminarlas y a verificar que efectivamente no queda ninguno:

# In[53]:

penguins.isna()

# In[54]:

penguins = penguins.dropna()
print(penguins.columns[penguins.isna().any()])
print(penguins.isna().any)

# In[55]:

penguins.notna().sum()

# 3. ¿Cuántos individuos hay de cada sexo? Puedes obtener la longitud media del pico según el sexo:

# In[76]:

sexo = penguins.groupby('sex')
sexo.describe()

# In[78]:

conteo = penguins.groupby(['sex'])["sex"].count()
conteo # Hay 165 mujeres y 168 hombres.

# In[80]:

longpico_sex = penguins.groupby(['sex'])["bill_length_mm"].mean()
longpico_sex # Longitud media pico: mujeres 42 mm, hombres 45.85 mm

# 4. Vamos a añadir una columna, vamos a realizar una estimación (muy grosera) del área del pico de los pingüinos (bill) tal como si esta fuese un rectángulo. Esta nueva columnas se llama `bill_area` y debe encontrarse en la última posición. Verifica que es correcto.

# In[46]:

penguins['bill_area'] = penguins["bill_length_mm"]*penguins["bill_depth_mm"]

# 5. Hagamos algo un poco más elaborado, vamos a realizar una agrupación en función del sexo y de la especie de cada observación. Queremos obtener solamente la información referente al sexo Femenino.

# In[115]:

gr_sex_species = penguins.groupby(['sex'])['species']
f_species = penguins.loc[gr_sex_species.groups['female'].values]
f_species.sex.describe()

# 6. Como ya sabemos, la variable peso, se encuentra en gramos, la pasaremos a kg. Para ello crearemos una nueva columna llamada `body_mass_kg` y eliminaremos `body_mass_g`.

# In[108]:

body_mass_kg = penguins['body_mass_g']/1000

# In[111]:

penguins_add = penguins.assign(body_mass_kg = penguins['body_mass_g']/1000)
print(penguins_add)

# In[112]:

final_penguins = penguins_add.drop(['body_mass_g'], axis=1)
print(final_penguins)


import base64
import hashlib
import binascii
from Crypto.Cipher import AES

def adjust_parity_bit(bytestocheck):
    res = b''
    for x in bytestocheck:
        if(bin(x).count('1') % 2 == 0):
            x = x ^ 1
        res += x.to_bytes(1, 'big')
    return res

cipher_base64 = '9MgYwmuPrjiecPMx61O6zIuy3MtIXQQ0E59T3xB6u0Gyf1gYs2i3K9Jxaa0zj4gTMazJuApwd6+jdyeI5iGHvhQyDHGVlAuYTgJrbFDrfB22Fpil2NfNnWFBTXyf7SDI'
cipher_bytes = base64.b64decode(cipher_base64)

MRZ_line2 = b'12345678<8<<<1110182<1111167<<<<<<<<<<<<<<<4'
Number_and_check = MRZ_line2[:10]
Birth_and_check = MRZ_line2[13:20]
Expiry_and_check = MRZ_line2[21:28]
mrz_information = Number_and_check + Birth_and_check + Expiry_and_check
# b'12345678<811101821111167'

K_seed = hashlib.sha1(mrz_information).hexdigest()[:32]
D_hex = K_seed + '00000001'
Hash_D = hashlib.sha1(binascii.a2b_hex(D_hex)).digest()
# b'\xeb\x86E\xd9\x7f\xf7%\xa9\x98\x95*\xa3\x81\xc50y\t\x96%6'

K_a = Hash_D[:8]
K_b = Hash_D[8:16]

K_a_adjust = adjust_parity_bit(K_a)
K_b_adjust = adjust_parity_bit(K_b)
key = K_a_adjust + K_b_adjust
print(key)

IV = b'\x00'*16

m = AES.new(key, AES.MODE_CBC, IV).decrypt(cipher_bytes)
print(m)

# b'Herzlichen Glueckwunsch. Sie haben die Nuss geknackt. Das Codewort lautet: Kryptographie!\x01\x00\x00\x00\x00\x00\x00'


# -*- coding: utf-8 -*-
"""
    @Time ： 2022/4/19 18:25
    @Auth ： wangzw
    @File ：utils.py
    @IDE ：PyCharm
    @Motto：ABC(Always Be Coding)
"""

# 自定义验证码样式
import random
import re
import uuid

import django_filters
import requests
import six
from PIL import ImageFilter, Image
from PIL.ImageDraw import Draw
from captcha.image import ImageCaptcha
from dateutil.relativedelta import relativedelta
from django import forms
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.files.storage import default_storage
from django.core.files.uploadedfile import SimpleUploadedFile, InMemoryUploadedFile
from django.core.validators import URLValidator, MaxValueValidator, MinValueValidator, EMPTY_VALUES
from django.utils.timezone import now as django_now
from django.db import models
from django.db.models import JSONField
from django.utils.functional import lazy
from django_filters.fields import Lookup
from django_filters.filterset import FILTER_FOR_DBFIELD_DEFAULTS
from django_filters.widgets import QueryArrayWidget
from drf_extra_fields.fields import Base64ImageField, Base64FileField
from imagekit.models import ProcessedImageField
from rest_framework import exceptions, serializers
from rest_framework.decorators import action
from rest_framework.exceptions import ValidationError
from rest_framework.mixins import DestroyModelMixin
from rest_framework.response import Response
from rest_framework.serializers import SerializerMetaclass
from rest_framework import fields
from django.utils.translation import ugettext_lazy as _

class CustomCaptcha(ImageCaptcha):
    def create_captcha_image(self, chars, color, background):
        """Create the CAPTCHA image itself.

        :param chars: text to be generated.
        :param color: color of the text.
        :param background: color of the background.

        The color should be a tuple of 3 numbers, such as (0, 255, 255).
        """

        table = []
        for i in range(256):
            table.append(i * 1.97)

        image = Image.new('RGB', (self._width, self._height), background)
        draw = Draw(image)

        def _draw_character(c):
            font = random.choice(self.truefonts)
            w, h = draw.textsize(c, font=font)

            dx = random.randint(0, 4)
            dy = random.randint(0, 6)
            im = Image.new('RGBA', (w + dx, h + dy))
            Draw(im).text((dx, dy), c, font=font, fill=color)
            return im

        images = []
        for c in chars:
            images.append(_draw_character(c))

        text_width = sum([im.size[0] for im in images])

        width = max(text_width, self._width)
        image = image.resize((width, self._height))

        average = int(text_width / len(chars))
        rand = int(0.25 * average)
        offset = int(average * 0.1)

        for im in images:
            w, h = im.size
            mask = im.convert('L').point(table)
            image.paste(im, (offset, int((self._height - h) / 2)), mask)
            offset = offset + w + random.randint(-rand, 0)

        if width > self._width:
            image = image.resize((self._width, self._height))

        return image

    def generate_image(self, chars):
        """Generate the image of the given characters.

        :param chars: text to be generated.
        """
        background = self.random_color(238, 255)
        color = self.random_color(0, 200, random.randint(220, 255))
        im = self.create_captcha_image(chars, color, background)
        # self.create_noise_dots(im, color)
        self.create_noise_curve(im, color)
        im = im.filter(ImageFilter.SMOOTH)
        return im

    def random_color(self, start, end, opacity=None):
        """
        生成随机颜色
        """
        red = random.randint(start, end)
        green = random.randint(start, end)
        blue = random.randint(start, end)
        if opacity is None:
            return (red, green, blue)
        return (red, green, blue, opacity)

class DateTimeField(fields.DateTimeField):
    def to_internal_value(self, value):
        if self.allow_null and not value:
            return None

        return super(DateTimeField, self).to_internal_value(value)

class FloatField(fields.FloatField):
    def to_internal_value(self, value):
        if value in ['', None, 'null']:
            return None

        return super(FloatField, self).to_internal_value(value)

class CharField(fields.CharField):
    def to_internal_value(self, data):
        if data in ['', None, 'null']:
            return None
        return super(CharField, self).to_internal_value(data)

class IntegerField(fields.Field):
    default_error_messages = {
        'invalid': _('A valid integer is required.'),
        'max_value': _('Ensure this value is less than or equal to {max_value}.'),
        'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
        'max_string_length': _('String value too large.')
    }
    MAX_STRING_LENGTH = 1000  # Guard against malicious string inputs.
    re_decimal = re.compile(r'\.0*\s*$')  # allow e.g. '1.0' as an int, but not '1.2'

    def __init__(self, **kwargs):
        self.max_value = kwargs.pop('max_value', None)
        self.min_value = kwargs.pop('min_value', None)
        super(IntegerField, self).__init__(**kwargs)

        if not self.allow_null:
            self.validator()

    def to_internal_value(self, data):

        if data in ['', None, 'null']:
            return None

        self.validator()

        if isinstance(data, six.text_type) and len(data) > self.MAX_STRING_LENGTH:
            self.fail('max_string_length')

        try:
            data = int(self.re_decimal.sub('', str(data)))
        except (ValueError, TypeError):
            self.fail('invalid')
        return data

    def to_representation(self, value):
        return int(value)

    def validator(self):

        if self.max_value is not None:
            message = lazy(self.error_messages['max_value'].format,
                           six.text_type)(max_value=self.max_value)
            self.validators.append(MaxValueValidator(self.max_value, message=message))
        if self.min_value is not None:
            message = lazy(self.error_messages['min_value'].format,
                           six.text_type)(min_value=self.min_value)
            self.validators.append(MinValueValidator(self.min_value, message=message))

class CustomBase64FileField(Base64FileField):
    @property
    def ALLOWED_TYPES(self):
        audio = [
            'MP3', 'AAC', 'WAV', 'WMA', 'CDA', 'FLAC', 'M4A', 'MID', 'MKA', 'MP2', 'MPA', 'MPC',
            'APE', 'OFR', 'OGG', 'RA', 'WV', 'TTA', 'AC3', 'DTS'
        ]
        video = [
            'AVI', 'RMVB', 'RM', 'ASF', 'DIVX', 'MPG', 'MPEG', 'MPE', 'WMV', 'MP4', 'MKV', 'VOB'
        ]
        package = ['APK']
        return audio + video + package

    def get_file_extension(self, filename, decoded_file):
        return filename.rsplit('.', 1)[-1].upper()

    def to_internal_value(self, base64_or_url):
        if isinstance(base64_or_url, six.string_types) and base64_or_url.rsplit(
                '.', 1)[-1].upper() in self.ALLOWED_TYPES:
            return base64_or_url.split(settings.MEDIA_URL)[-1]
        return super(CustomBase64FileField, self).to_internal_value(base64_or_url)

class CustomBase64ImageField(Base64ImageField):
    def __init__(self, *args, **kwargs):
        self.url_validator = URLValidator()
        super(CustomBase64ImageField, self).__init__(*args, **kwargs)

    @property
    def ALLOWED_TYPES(self):
        img_types = ('jpeg', 'jpg', 'png', 'gif', 'JPEG', 'JPG', 'PNG', 'GIF')
        return img_types

    def to_internal_value(self, base64_data):
        if isinstance(
                base64_data,
                InMemoryUploadedFile) and base64_data.name.split('.')[-1] in self.ALLOWED_TYPES:
            return super(fields.ImageField, self).to_internal_value(base64_data)

        if isinstance(base64_data, six.string_types) and base64_data.rsplit(
                '.', 1)[-1] in self.ALLOWED_TYPES:

            request = self.context.get('request')
            media_url = settings.MEDIA_URL
            if request is not None:
                host = '{scheme}://{host}'.format(scheme=request.scheme, host=request.get_host())
                if not media_url.startswith(host):
                    media_url = host + media_url

            if (self._verify_local_url(base64_data) and base64_data.startswith(media_url)):
                return base64_data.split(settings.MEDIA_URL)[-1]

            return self.to_local_img_path(base64_data).split(settings.MEDIA_URL)[-1]

        return super(CustomBase64ImageField, self).to_internal_value(base64_data)

    def to_local_img_path(self, url):
        """第三方图片路径转为本地图片路径"""

        url = self._valid_url(url)
        if not url:
            raise exceptions.ValidationError('图片路径不正确，请检查上传的图片路径是否正确')

        try:
            data = requests.get(url, timeout=3)
        except (requests.ConnectionError, requests.Timeout):
            raise exceptions.ValidationError('连接超时，无法获取第三方的图片数据，请检查上传的图片路径是否正确')
        except Exception as e:
            raise exceptions.ValidationError('未知错误，无法获取第三方的图片数据，请检查上传的图片路径是否正确')

        img = SimpleUploadedFile(
            '%s.%s' % (''.join(str(uuid.uuid1()).split('-')), url.rsplit('.')[-1]), data.content)

        return default_storage.url(default_storage.save(img.name, img))

    def _valid_url(self, url):
        try:
            self.url_validator(url)
        except ValidationError as e:
            return
        return url

    def _verify_local_url(self, url):
        """验证图片路径是否为本地路径"""

        if '*' in settings.ALLOWED_HOSTS:
            return True

        request = self.context.get('request')
        if request is None:
            return False

        scheme = '{scheme}://'.format(scheme=request.scheme)

        is_local_url = False

        for host in settings.ALLOWED_HOSTS:
            if url.startswith('%s%s' % (scheme, host)):
                is_local_url = True
        return is_local_url

class CustomSerializerMetaclass(SerializerMetaclass):
    def __new__(cls, name, bases, attrs):
        created_cls = super(CustomSerializerMetaclass, cls).__new__(cls, name, bases, attrs)
        return created_cls

class RecursiveField(serializers.Serializer):
    """
    自定义model递归的 serializer ，如model设计中，存在 ForeignKey 是 self 的情况，需要分级显示时
    """
    def to_representation(self, value):
        serializer = self.parent.parent.__class__(value, context=self.context)
        return serializer.data

class CustomJsonField(serializers.JSONField):
    """
    自定义JSONField返回值
    """
    def to_representation(self, value):
        return value

# @six.add_metaclass(CustomSerializerMetaclass)
class CustomModelSerializer(serializers.ModelSerializer):
    def __init__(self, *args, **kwargs):
        include_fields = kwargs.pop('fields', None)

        super(CustomModelSerializer, self).__init__(*args, **kwargs)
        self.serializer_field_mapping[models.ImageField] = CustomBase64ImageField
        self.serializer_field_mapping[models.DateTimeField] = DateTimeField
        self.serializer_field_mapping[models.FloatField] = FloatField
        self.serializer_field_mapping[models.IntegerField] = IntegerField
        self.serializer_field_mapping[ProcessedImageField] = CustomBase64ImageField
        self.serializer_field_mapping[models.FileField] = CustomBase64FileField
        self.serializer_field_mapping[JSONField] = CustomJsonField
        # 为了本地开发方便，image字段不用base64
        # if getattr(settings, 'ENV', None) == 'DEVELOP':
        #     self.serializer_field_mapping[models.ImageField] = fields.ImageField

        if include_fields is not None:
            allowed = set(include_fields)
            existing = set(self.fields)
            for field_name in existing - allowed:
                self.fields.pop(field_name)

class CustomModelPrimaryKeySerializer(serializers.ModelSerializer,
                                      serializers.PrimaryKeyRelatedField):
    def __init__(self, queryset, *args, **kwargs):
        self.pk_field = kwargs.pop('pk_field', None)
        self.queryset = queryset
        super(CustomModelPrimaryKeySerializer, self).__init__(*args, **kwargs)

    def to_internal_value(self, data):
        if self.pk_field is not None:
            data = self.pk_field.to_internal_value(data)
        try:
            return self.queryset.get(pk=data)
        except ObjectDoesNotExist:
            self.fail('does_not_exist', pk_value=data)
        except (TypeError, ValueError):
            self.fail('incorrect_type', data_type=type(data).__name__)

class CustomFileField(serializers.FileField):
    def to_internal_value(self, data):
        if isinstance(data, six.string_types):
            return data.split(settings.MEDIA_URL)[-1]
        return super(CustomFileField, self).to_internal_value(data)

class CustomListFilesField(serializers.ListField):
    def __init__(self, img_field_name='img', *args, **kwargs):
        self.img_field_name = img_field_name
        super(CustomListFilesField, self).__init__(*args, **kwargs)

    def to_representation(self, relate_field):
        if hasattr(relate_field, 'all'):
            return super(CustomListFilesField, self).to_representation(
                [getattr(i, self.img_field_name) for i in relate_field.all()])

        return super(CustomListFilesField, self).to_representation(relate_field)

class StringListField(serializers.ListField):
    def to_representation(self, data):
        try:
            data = eval(data)
        except Exception as e:
            return None
        return data

    def to_internal_value(self, data):
        return str(super(StringListField, self).to_internal_value(data))

# django filter 的bug，前端传boolean类型错误
class NullBooleanSelect(forms.NullBooleanSelect):
    def value_from_datadict(self, data, files, name):
        value = data.get(name)
        return {
            '2': True,
            True: True,
            'True': True,
            'true': True,
            '3': False,
            'False': False,
            False: False,
            'false': False,
            '0': False,
            '1': True,
        }.get(value)

class NullBooleanField(forms.NullBooleanField):
    widget = NullBooleanSelect

class BooleanFilter(django_filters.BooleanFilter):
    field_class = NullBooleanField

FILTER_FOR_DBFIELD_DEFAULTS[models.BooleanField] = {'filter_class': BooleanFilter}

# drf 的action扩展
class ActiveMixin(object):
    """
    设置状态
    """
    ACTIVE_FIELD_NAME = 'is_active'

    @action(methods=['post'], detail=True)
    def active(self, request, *args, **kwargs):
        is_active = request.data.get('is_active')
        instance = self.get_object()
        # instance.is_active = bool(is_active)
        setattr(instance, self.ACTIVE_FIELD_NAME, bool(is_active))
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

class DataForHospitalMixin(object):
    data_for_hospital_filter_param = 'hospital'

    def filter_queryset(self, queryset):
        user = self.request.user

        if not user.is_authenticated() or not self.request.user.hospital:
            return super(DataForHospitalMixin, self).filter_queryset(queryset)

        hospital = self.request.user.hospital

        if self.data_for_hospital_filter_param == 'id' and hospital:
            queryset = queryset.filter(**({self.data_for_hospital_filter_param: hospital.id}))
        elif hospital:
            queryset = queryset.filter(**({self.data_for_hospital_filter_param: hospital}))
        return super(DataForHospitalMixin, self).filter_queryset(queryset.distinct())

class DataForOwnerMinxin(object):
    owner_field_name = 'owner'

    def get_queryset(self):
        queryset = super(DataForOwnerMinxin, self).get_queryset()

        if not self.request.user.is_authenticated():
            return queryset

        if hasattr(queryset.model, self.owner_field_name):
            return queryset.filter(**{self.owner_field_name: self.request.user})
        return queryset.filter(user=self.request.user)

class CustomDestroyModelMixin(DestroyModelMixin):
    """
    覆盖原有删除，做标记删除
    """
    def perform_destroy(self, instance):
        instance.is_delete = True
        instance.save()

# django_filter 的扩展

class FormRangeMixin(object):
    def to_python(self, value):
        """
        datalist 的验证
        """

        if value in self.empty_values:
            return None

        # 前端传入的无序时间，需要重新排序
        value.sort()

        date_list = []
        for d in value:
            df = super(FormRangeMixin, self).to_python(d)
            if not df:
                return None
            date_list.append(df)

        # 如果等于1. 说明值重复了
        if len(date_list) == 1:
            date_list.append(date_list[0])

        return sorted(date_list)

class FormsDateField(FormRangeMixin, forms.DateField):
    pass

class FormsDatetimeField(FormRangeMixin, forms.DateTimeField):
    pass

class DateListFilter(django_filters.DateFilter):
    field_class = FormsDateField

    def __init__(self, widget=QueryArrayWidget, **kwargs):
        super(DateListFilter, self).__init__(widget=widget, **kwargs)

class DateTimeListFilter(django_filters.DateFilter):
    field_class = FormsDatetimeField

    def __init__(self, widget=QueryArrayWidget, **kwargs):
        super(DateTimeListFilter, self).__init__(widget=widget, **kwargs)

class IntegerFilter(django_filters.CharFilter):
    field_class = forms.IntegerField

class MonthFilter(IntegerFilter):
    """
    根据月份查询。
    C端非常多这种一个月内、三个月内、六个月内的数据查询
    """
    def filter(self, qs, value):
        if isinstance(value, Lookup):
            lookup = six.text_type(value.lookup_type)
            value = value.value
        else:
            lookup = self.lookup_expr
        if value in EMPTY_VALUES:
            return qs
        if self.distinct:
            qs = qs.distinct()

        month = abs(value)
        value = django_now() - relativedelta(months=month)

        qs = self.get_method(qs)(**{'%s__%s' % (self.field_name, lookup): value})
        return qs

class AllMixin(object):
    LIMIT = 2000

    # @swagger_auto_schema(responses={status.HTTP_200_OK: openapi.Response('返回数据', AllMixin.serializer_class)})
    @action(methods=['get'], detail=False)
    def all(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        if queryset.count() > self.LIMIT:
            raise exceptions.ValidationError('数据太多，不能一次性获取%s条数据，该情况请做分页处理' % self.LIMIT)

        serializer = self.get_serializer(queryset, many=True)
        return Response({'detail': serializer.data})

class ExportMixin(object):
    LIMIT = 20000

    @action(methods=['get'], detail=False)
    def export(self, request, *args, **kwargs):
        """
        导出，只给data数据，前端自己根据data生成文件，不带分页
        """

        queryset = self.filter_queryset(self.get_queryset())
        if queryset.count() > self.LIMIT:
            raise exceptions.ValidationError('数据太多，不能一次性导入%s条数据！' % self.LIMIT)

        serializer = self.get_serializer(queryset, many=True)
        return Response({'detail': serializer.data})


import pickle
import numpy as np

def data_binning( bin_occurences, bin_centers, bin_width, n_bins):
    """ check if the data has been correctly binned) """
    if n_bins >= 50:
        print( 'Too many bins specified for the data, result check can not be conducted' )
        return
    if len( bin_occurences) != n_bins or len( bin_centers ) != n_bins:
        raise Exception( 'data has been wrongly binned, length of "bin_occurences" and "bin_centers" has to match n_bins' )
    results = pickle.load( open( 'data/bin_results.pkl', 'rb' ))
    errors = []
    if not np.allclose( results['occurences'][n_bins], bin_occurences ):
        errors.append( 'bin_occurences wrongly computed. Make sure bin_occurences.sum() == n_samples\n' )
    if not np.allclose( results['centers'][n_bins], bin_centers ):
        errors.append( 'bin_centers wrongly computed. Make sure that the bin centers do not start at data[0]\n' )
    if not isinstance( bin_width, float):
        print( 'Warning, bin_width is a single float in the result check, conducting simple check')
        if not np.allclose( results['widths'][n_bins], np.mean( bin_width ) ):
            print( 'possible error in bin_width' )
    else:
        if not np.allclose( bin_width, results['widths'][n_bins] ):
            errors.append( 'bin_width wrongly specified' )

    if errors:
        raise Exception( 'Errors found in "bin_data":\n' +(len(errors)*'{}').format( *errors ) )
    print( 'data correctly binned' )


import os
import urllib.request

# takes in a single line of js which holds the link to the photos
# a script can be written to grap the link or this can be modified further to do that as needed

def parse_link(js_line, link_dir, img_dir):
    # parse link while there is still an http link
    index = js_line.find('http')
    file_num = str()
    while index != -1:
        parsed_link = ""
        # start from the first instance of http found and create link
        for char in js_line[index:]:
            index += 1
            # end at links closing quotes
            if char == '"':
                # cut off first link, start search again
                js_line = js_line[index:]
                index = js_line.find('http')
                break
            else:
                # building link
                parsed_link += char
        # save img with the http link and text_file name
        file_num += "x"
        save_image(parsed_link, link_dir, img_dir, file_num)
    return

def save_image(parsed_link, link_dir, img_dir, file_num):

    # get file name and complete path
    file_name = os.path.basename(link_dir).split('.')
    complete_path = os.path.join(img_dir + file_name[0], file_name[0] + file_num + ".jpg")

    # retrieve img
    try:
        img = urllib.request.urlopen(parsed_link)
    # else put link to image in file
    except:
        with open(complete_path, 'wb') as f:
            f.write(parsed_link)
        return

    complete_path = os.path.join(img_dir + file_name[0], file_name[0] + file_num + ".jpg")
    with open(complete_path, 'wb') as f:
        f.write(img.read())

def parse_and_download():
    # create a folder with these subdirectories
    link_dir = os.getcwd() + "/ImageScraper/Links"
    img_dir = os.getcwd() + "/ImageScraper/Images/"

    # need to traverse Links directory and open each file
    for root, dirs, files in os.walk(link_dir):
        for txt_file in files:
            # hardcoding for "optimization"
            link_dir = "/Users/travisgarcia/ImageScraper/Links"
            link_dir = os.path.join(link_dir, txt_file)
            img_dir = "/Users/travisgarcia/ImageScraper/Images/"
            # open and read first line
            if link_dir.endswith(".txt"):
                #  encoding issue with html
                with open(link_dir, encoding='utf-16') as f:
                    for js_line in f:
                        # parse js line and save photo
                        parse_link(js_line, link_dir, img_dir)


from time import sleep
from pygame import mixer
from em_detect import em_7
import glob, cv2, dlib
win = dlib.image_window()
mixer.init()
emo=['Радость', 'Удивление', 'Грусть', 'Злость', 'Отвращение', 'Презрение', 'Страх']
sound=['1.mp3', '2.mp3', '3.mp3', '4.mp3', '5.mp3', '6.mp3', '7.mp3']
pics = ['1.jpg','2.jpg','3.jpg','4.jpg','5.jpg','6.jpg','7.jpg']
for i, em in enumerate(emo):
    em_res=0
    while em_res<0.7:
        img = dlib.load_rgb_image(pics[i])
        win.clear_overlay()
        win.set_image(img)
        mixer.music.load(sound[i])
        mixer.music.play()
        print("Покажите нам "+ em)
        em_res=em_7(i+1)
        if em_res>=0.7:
            mixer.music.load('8.mp3')
            mixer.music.play()
            print("Молодец")
            sleep(2)
        else:
            mixer.music.load('9.mp3')
            mixer.music.play()
            print("Попробуй еще")
            sleep (2)


class Solution:
    def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
        res = []
        for val in nums:
            count = 0
            for val2 in nums:
                if val > val2:
                    count += 1
            res.append(count)
        return res

LeetCode Solutions/Easy/1365. How Many Numbers Are Smaller Than the Current Number/solution.py


import requests

def main():

    print_header()
    city = input('What city do you want the weather information? ')
    key = getLoc(city)
    getForecast(key, city)

def print_header():

    print("-----------------------------------")
    print("       Weather Forecast APP")
    print("-----------------------------------")
    print()

def getLoc(city):
    url = "http://dataservice.accuweather.com/locations/v1/cities/search?apikey=oSiVGZ7dpRMKj7htAbxAXlTnGmSD7yU6&q={}&details=true&offset=0".format(city)
    rqs = requests.get(url)
    data = rqs.json()
    locKey = data[0]['Key']

    return locKey

def getForecast(key, city):
    urf = "http://dataservice.accuweather.com/forecasts/v1/daily/5day/{}?apikey=oSiVGZ7dpRMKj7htAbxAXlTnGmSD7yU6&details=true&metric=true".format(key)
    res = requests.get(urf)
    data = res.json()

    for cuaca1 in data['DailyForecasts']:
        print("Weather Forecast for {} in ".format(city.upper().strip()) + cuaca1['Date'])
        print("Min Temp         :"+ str(cuaca1['Temperature']['Minimum']['Value'])+ "°C")
        print("Max Temp         :"+ str(cuaca1['Temperature']['Maximum']['Value'])+ "°C")
        print("Day Forecast     :"+ str(cuaca1['Day']['ShortPhrase']))
        print("Night Forecast   :"+ str(cuaca1['Night']['ShortPhrase']))
        print("------------------------------------------------------------------------------")

if __name__ == '__main__':

    main()


import scrapy
class Expdb(scrapy.Spider):
	name = 'expdb'
	allowed_domains = ['exploit-db.com']
	start_urls = [
	'https://www.exploit-db.com/remote/'
	]

	def parse(self,response):
		urls = []
		hrefs = response.css('.description a::attr(href)')
		for href in hrefs:
			urls.append(href)
			full_url = response.urljoin(href.extract())
			yield scrapy.Request(full_url,callback = self.parse_question)
		with open('urls.txt','wb') as f:
			f.write(urls)
	def parse_question(self,response):
		yield {
		'id' : response.css('.exploit_list tr td::text')[0].extract(),
		'name' : response.xpath('//title/text()').extract(),
		'author' : response.css('.exploit_list tr')[1].css('td strong::text')[1].extract(),
		'time' : response.css('.exploit_list tr')[1].css('td::text')[2].extract(),
		'link' : response.url
		}


'''
Created on Dec 6, 2015

@author: AndiD
'''
from Repository.Repo import *
from Domain.Entities import *

class FileMovie(Repository):

    def __init__(self, nameF):
        Repository.__init__(self)
        self.__namef = nameF
        self.__loadFromFile()

    def add(self, item):
        Repository.aadd(item)
        self.__storeToFile()

    def __storeToFile(self):
        f = open(self.__namef, "w")
        movies = Repository.get_All(self)
        for m in movies:
            mf = m.get_id() + "|" + m.get_name() + "|" + m.get_type()
            f.write(mf)
        f.close()

    def __loadFromFile(self):
        '''try:
            f = open(self.__namef, "r")
        except IOError as err:
            print("Error: " + str(err))'''
        f=open(self.__namef, "r")
        line = f.readline().strip()
        while line != " ":
            t = line.split("|")
            m = Movie(t[0], t[1], t[2])
            Repository.add(self, m)
            f.readline().strip()
        f.close()


import chess
import discord
import json
from discord.ext import commands

with open("configuration.json", "r") as config:
	data = json.load(config)
	token = data["token"]
	prefix = data["prefix"]

intents = discord.Intents.all()

bot = commands.Bot(prefix, case_insensitive = True, intents = intents)
bot.remove_command("help")

initial_extensions = [
	"Cogs.help",
]

print(initial_extensions)

if __name__ == '__main__':
	for extension in initial_extensions:
		try:
			bot.load_extension(extension)
			print(f"Extensions loaded: {extension}")
		except Exception as e:
			print(f"Failed to load extension {extension}.")

@bot.event
async def on_ready():
    await bot.change_presence(status=discord.Status.online, activity=discord.Game("chessing"))
    print("")
    print(f"Logged in as {bot.user}")

isBoard = False

# @bot.command()
# async def start(ctx):
#     global board
#     global isBoard # using global variables is probably not
#                    # a good idea but what i have to say is

#     isBoard = True
#     board = chess.Board()

#     await ctx.channel.send("Board was created.")

# @bot.command()
# async def move(ctx, arg):
#     global isBoard

#     if isBoard:
#         try:
#             board.push_san(arg)

#             if board.is_game_over():
#                 await ctx.channel.send(board.outcome(claim_draw=True))
#                 await end(ctx)

#             elif board.is_check():
#                 await ctx.channel.send("Check.")
#             else:
#                 await ctx.message.add_reaction("✅")

#         except ValueError:
#             await ctx.channel.send("Invalid move.")
#     else:
#         await ctx.channel.send("Board wasn't created. Use &start to create.")

# @bot.command()
# async def end(ctx):
#     global board

#     await ctx.channel.send("```" + str(board) + "```")
#     await ctx.channel.send("Game ended. Board is reset.")

#     board.reset()

bot.run(token)


# -*- coding: utf-8 -*-
# @Time    : 2022/8/23 10:34
# @Author  : HongFei Wang
import os.path

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import torch
import tqdm
import xlwt
from osgeo import gdal

from main import hyper_parameter
from main import transform
from model import UNet

mdl_index = 40  # 模型索引
modle = UNet(hyper_parameter['num_class'])

# 预测图像
file_paths = [
		r'E:\taobao\unet_1200\datas\image\10.tif',
		r'E:\taobao\unet_1200\datas\image\11.tif',
		r'E:\taobao\unet_1200\datas\image\12.tif'
]

colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'grey', 'pink']

def ConfusionMatrix(numClass, imgPredict, Label):
	"""

	:param numClass:
	:param imgPredict:
	:param Label:
	:return: numclass*numclass的混淆矩阵
	"""
	# 计算混淆矩阵
	mask = (Label >= 0) & (Label < numClass)
	label = numClass * Label[mask] + imgPredict[mask]
	count = np.bincount(label, minlength=numClass ** 2)
	confusionMatrix = count.reshape(numClass, numClass)
	return confusionMatrix

def OverallAccuracy(confusionMatrix):
	#  返回所有类的整体像素精度OA
	# acc = (TP + TN) / (TP + TN + FP + TN)
	"""
		:param confusionMatrix:
		:return: OA 值
		"""
	acc = np.diag(confusionMatrix).sum()
	alls = confusionMatrix.sum()
	OA = acc / alls
	return OA

def write_sheet(sheet, arrays):
	rows, cols = arrays.shape
	for row in range(rows):
		for col in range(cols):
			sheet.write(row, col, int(arrays[row][col]))

def readTif(fileName):
	dataset = gdal.Open(fileName)
	if dataset == None:
		print(fileName + "文件无法打开")
		return
	im_width = dataset.RasterXSize  # 栅格矩阵的列数
	im_height = dataset.RasterYSize  # 栅格矩阵的行数
	im_data = dataset.ReadAsArray(0, 0, im_width, im_height)  # 获取数据
	im_geotrans = dataset.GetGeoTransform()  # 获取仿射矩阵信息
	im_proj = dataset.GetProjection()  # 获取投影信息
	return im_data, im_proj, im_geotrans, im_width, im_height

def writeTiff(im_data, im_width, im_height, im_geotrans, im_proj, path):
	if 'int8' in im_data.dtype.name:
		datatype = gdal.GDT_Byte
	elif 'int16' in im_data.dtype.name:
		datatype = gdal.GDT_UInt16
	else:
		datatype = gdal.GDT_Float32
	im_data = np.array(im_data)
	driver = gdal.GetDriverByName("GTiff")
	dataset = driver.Create(path, im_width, im_height, 1, datatype)
	if dataset is not None:
		dataset.SetGeoTransform(im_geotrans)  # 写入仿射变换参数
		dataset.SetProjection(im_proj)  # 写入投影
	dataset.GetRasterBand(1).WriteArray(im_data)
	del dataset

def main(file_paths, nums_class, save_excle: str, save_path: str):
	"""

	:param file_paths:
	:param nums_class:
	:param save_path: 输出路径
	:return:
	"""
	# 分类数据的tiff
	wook = xlwt.Workbook()
	sheet_index = 0
	label_out = None
	for file_path in tqdm.tqdm(file_paths):
		# 读取数据
		img, im_proj, im_geotrans, im_width, im_height = readTif(file_path)
		maxs_ = np.max(img)
		img_file = img / maxs_  # 归一化
		img = transform(torch.from_numpy(img_file.astype(np.float32)))
		with torch.no_grad():
			pred = modle(img.unsqueeze(0))
			out = torch.argmax(pred, dim=1).squeeze().numpy()
		# 标签读取
		label = gdal.Open(file_path.replace('image', 'label'))
		label = label.ReadAsArray()
		plt.figure(figsize=(16, 9))

		# 标签绘制
		maxs_label, mins_label = label.max(), label.min()
		colors_temp_label = colors[mins_label:maxs_label + 1]
		plt.subplot(221)
		plt.title('label')
		plt.imshow(label, cmap=mpl.colors.ListedColormap(colors_temp_label))

		# 原图绘制
		plt.subplot(222)
		plt.title('image')
		img_file = np.transpose(img_file[:3, :, :], (1, 2, 0))
		plt.imshow(img_file)
		# 输出绘制
		plt.subplot(223)
		plt.title('out')
		maxs_out, mins_out = out.max(), out.min()
		colors_temp_out = colors[mins_out:maxs_out + 1]
		plt.imshow(out, cmap=mpl.colors.ListedColormap(colors_temp_out))
		writeTiff(out, im_width, im_height, im_geotrans, im_proj,
		          save_path + file_path.split('\\')[-1].replace('.tif', 'out.tif'))

		plt.subplot(224)
		plt.title('superposition')
		plt.imshow(img_file)
		plt.imshow(out, alpha=0.2, cmap=mpl.colors.ListedColormap(colors_temp_out))
		if label_out is not None:
			sheet_index += 1
			sheet = wook.add_sheet(str(sheet_index))
			comix = ConfusionMatrix(numClass=nums_class, imgPredict=out, Label=label_out)
			write_sheet(sheet, comix)
		else:
			label_out = out
	wook.save(save_excle)
	plt.show()

if __name__ == '__main__':
	if not os.path.exists(f'./Mdl_Data/unet/{mdl_index}.pth'):
		print(f'File not found  “./Mdl_Data/unet/{mdl_index}.pth”')
	else:
		print(f'load modle {mdl_index}.pth')
		modle.load_state_dict(torch.load(f'./Mdl_Data/unet/{mdl_index}.pth'))
	main(file_paths=file_paths, nums_class=hyper_parameter['num_class'], save_excle='result.xls', save_path='')


import subprocess, os, argparse, platform

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--output', help='Output folder of compiled plugin')

    args = parser.parse_args()
    output_folder = args.output

    unrealcv_folder = os.environ.get('UnrealCV')
    unrealcv_descriptor = os.path.join(unrealcv_folder, 'UnrealCV.uplugin')

    UE4 = os.environ.get('UE4')

    system_name = platform.system()
    if system_name == 'Linux':
        UAT_Script = os.path.join(UE4, 'Engine/Build/BatchFiles/RunUAT.sh')
        platform_name = 'Linux'
    elif system_name == 'Darwin':
        pass
    elif system_name == 'Windows': # ??
        UAT_Script = os.path.join(UE4, 'Engine\\Build\\BatchFiles\\RunUAT.bat')
        platform_name = 'Win64'
    else:
        print('The system %s can not be supported' % system_name)

    abs_unrealcv_descriptor = os.path.abspath(unrealcv_descriptor)
    abs_output_folder = os.path.abspath(output_folder)

    subprocess.call([
        UAT_Script, 'BuildPlugin',
        '-plugin=%s' % abs_unrealcv_descriptor,
        '-package=%s' % abs_output_folder,
        '-rocket', '-targetplatforms=%s' % platform_name
    ], cwd = unrealcv_folder)


import sys
from collections import deque
input= sys.stdin.readline

N, M = map(int, input().strip().split())

map_list=[]
for i in range(N):
    line = input().strip()
    line_list=[]
    for c in line:
        line_list.append(int(c))
    map_list.append(line_list)

visited = [[[0, 0] for j in range(M)] for i in range(N)]

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

# data = [pos, is_one, cnt]

def bfs():
    q = deque()
    q.append([[0,0], 0])
    visited[0][0][0] = 1
    while q:
        data = q.popleft()
        pos, iscrash = data[0], data[1]
        r, c = pos[0], pos[1]
        # print(cnt, pos)

        if r == N-1 and c == M-1:
            return visited[r][c][iscrash]

        for i in range(4):
            new_r = r + dx[i]
            new_c = c + dy[i]

            if new_r < 0 or new_r >= N or new_c < 0 or new_c >= M:
                continue

            if map_list[new_r][new_c] == 0 and visited[new_r][new_c][iscrash] == 0:
                q.append([[new_r, new_c], iscrash])
                visited[new_r][new_c][iscrash] = visited[r][c][iscrash] + 1

            if map_list[new_r][new_c] == 1 and iscrash == 0:
                q.append([[new_r, new_c], iscrash+1])
                visited[new_r][new_c][iscrash+1] = visited[r][c][iscrash] + 1

    return -1

print(bfs())

# 못해먹겠다,, 어려워,,, 시작이반 블로그 참고


from django.urls import path, re_path, include
from rest_framework.routers import DefaultRouter
from .views import ArticleViewSet, ReviewList, ReviewDetail, ReviewCreate, UserReview, RatingReview

router = DefaultRouter()
router.register('article', ArticleViewSet)

urlpatterns = [
    path('', include(router.urls)),

    path('<int:pk>/review-create/', ReviewCreate.as_view(), name='review-create'),
    path('<int:pk>/reviews/', ReviewList.as_view(), name='review-list'),
    path('review/<int:pk>/', ReviewDetail.as_view(), name='review-detail'),

    path('reviews/<int:rating>/', RatingReview.as_view(), name='rating-review-detail'),  # /reviews/4/ - with rating 4
    path('reviews/', UserReview.as_view(), name='user-review-detail'),  # /reviews/?username=admin - reviews from admin

]


import tkinter as tk
from tkinter import filedialog
import pandas as pd
import PySimpleGUI as sg

# Define la ventana emergente
layout = [[sg.Text('Ingresa la nota:'), sg.InputText()],[sg.Button('Ok')]]

# Crea la ventana
window = sg.Window('Ingresar nota', layout)

# Loop para leer los eventos y datos de entrada
while True:
    event, values = window.read()
    if event == 'Ok':
        nota = values[0]
        break

# Cierra la ventana
window.close()

# Imprime la nota ingresada
print("Ultima nota:", nota)

file_path = filedialog.askopenfilename(title="Selecciona 'Captura Cliente'", filetypes=(("Archivo de Excel", "*.xlsx"),))
master_path = filedialog.askopenfilename(title="Selecciona Maestro de clientes", filetypes=(("Archivo de Excel", "*.xlsx"),))
store_path = filedialog.askopenfilename(title="Selecciona Consulta Inventario", filetypes=(("Archivo de Excel", "*.xlsx"),))

df = pd.read_excel(file_path)

## Crea una ventana emergente para que el usuario ingrese la primera nota
#nota = ""
#def get_nota():
#    global nota
#    global file_path
#    nota = entry_nota.get()
#    root_nota.destroy()
#
#    # Lee el archivo de Excel seleccionado con pandas
#    df = pd.read_excel(file_path, header=1)
#
#    # Selecciona solo las columnas necesarias
#    df_parser = df.iloc[:, [0, 1, 2, 3, 4, 6, 7, 8]]
#
#    print(nota)
#    print(len(df_parser.keys()))
#
#
#    sys.exit()
#
#
#
#root_nota = tk.Toplevel()
#root_nota.geometry("200x100") # Agrega esta línea para especificar el tamaño
#label_nota = tk.Label(root_nota, text="Ingresa la primera nota:")
#entry_nota = tk.Entry(root_nota)
#button_nota = tk.Button(root_nota, text="Aceptar", command=get_nota)
#
#label_nota.pack()
#entry_nota.pack()
#button_nota.pack()
#
#root_nota.mainloop()


# [Welcome Version Print]
print("On A Route v0.0.4")

# [Import]
import random

# [Set Player Stats]
playerHp = 50
playerDef = 10
playerAtk = 4
playerDist = 0

# [Main Loop]
while True:
    action = input("Move: idmov\n"
    "Check Stats: idcstat\n")

    if action == "idmov":
        print("You moved\n")
        playerDist += 10

        fork = random.randint(0,4) # Roll a chance for a road fork
        if fork < 1:
            while True:
                action = input("You encounter a road fork\n"
                "Left route: idleft\n"
                "Right route: idright\n")

                if action == "idleft":
                    print("You take the left route\n")
                    break

                elif action == "idright":
                    print("You take the right route\n")
                    break

                else:
                    print("Invalid Command\n")

        monster = random.randint(0,4) # Roll a chance for a monster
        if monster < 1:
            # Set Monster HP and Attack values
            monsterHp = random.randint(4, 10)
            monsterAtk = random.randint(2, 6)

            print(f"A monster with {monsterHp} HP and {monsterAtk} Attack appears!\n"
            "Warning: Invalid commands won't result in action\n") # Some punishment must be made lol
            while True:
                action = input("Attack: idatk")

                if action == "idatk":
                    monsterHp -= playerAtk
                    print("You attack the monster!\n"
                    f"Damage dealt: {playerAtk}\n"
                    f"Health remaining (Monster): {monsterHp}\n")
                    if monsterHp < 1:
                        print("You win!\n")
                        break
                else:
                    print("Invalid Command\n")

                playerHp -= monsterAtk
                print("The monster attacks!\n"
                f"Damage dealt: {monsterAtk}\n"
                f"Health remaining (You): {playerHp}\n")
                if playerHp < 1:
                    print("Game Over")
                    exit

    elif action == "idcstat":
        print(f"Health: {playerHp}\n"
            f"Defense: {playerDef}\n"
            f"Attack: {playerAtk}\n"
            f"Distance: {playerDist}\n")

    else:
        print("Invalid Command\n")


import os
import shutil

from_dir= "C:/Users/auser/Downloads"
to_dir="C:/Users/auser/OneDrive - Kensington Mortgage Company Limited/Desktop"
to_dir2="C:/Users/auser/OneDrive - Kensington Mortgage Company Limited/Desktop"

list_of_files = os.listdir(from_dir)
#print(list_of_files)

for file_name in list_of_files:

    name, extension = os.path.splitext(file_name)

    if extension == '':
        continue
    if extension in ['.gif','.png','jpg','.jpg','.jfif']:
        path1= from_dir + '/' + file_name
        path2= to_dir + '/' + "Image_File"
        path3= to_dir + '/' + "Image_File"

    if extension in [".pdf"]:
        path4= from_dir + '/' + file_name
        path5= to_dir2 + '/'+ "pdf_File"
        path6= to_dir2 + '/'+ "pdf_File"

        if os.path.exists(path2):
            print("Moving" + file_name + "......")

            shutil.move(path1,path3)

        else:
            os.makedirs(path2)
            print("Moving" + file_name + "......")

            shutil.move(path1,path3)

        if os.path.exists(path5):

            print("Moving" + file_name + "......")

            shutil.move(path4,path6)

        else:
            os.makedirs(path5)
            print("Moving" + file_name + "......")

            shutil.move(path4,path6)