#!/usr/bin/env python
"""
A simple ionic model

Pythonised stuff from Remco's spreadsheet
Based on Young et al. 2015
"""

import numpy as np
import scipy.optimize as spopt

def melt_bond_length(p, coeffs):
    """
    Return the bond length (in m) given
    a polynomial expansion in pressure.
    """

    r = 0.0000000001 * (coeffs[0] + p * coeffs[1] + p**2 * coeffs[2])
    return r

def ionic_model_force_constant(r, correction=1.0, offset=0.0, n=12):
    """
    Ionic model force constant following equation 31 of Young (2015).
    All parameters other than r are designed to follow Remco's spreadsheet.

    The optional correction allows a (r independent) change to the force
    constant to be made (should be equivlent to changing the constant term
    in the r expansion but easer to justify).
    """
    zi = 2.0 # Cation valence
    zj = -2.0 # Anion valence
    # n is Born-Mayer constant. Ultimatly LJ I think. Default to 12
    eps0 = 8.854187817E-12 # Vaccum permittivity (F/m)
    e = 1.60217662E-19 # electron charge (C)

    kf = (zi * zj * e**2 * (1-n)) / (4.0 * np.pi * eps0 * r**3)
    kf = (kf * correction) + offset
    return kf

def calculate_force_constant_correction(target_beta, c, t, p=0, mode='correction'):
   """
   Find a correction term for the ionic model force constants such
   that beta for these r coefficents and at this temperature is equal
   to target_beta.
   """
   def get_my_beta(corec):
       r = melt_bond_length(p, c)
       if mode=='correction':
           kf = ionic_model_force_constant(r, correction=corec)
       elif mode=='offset':
           kf = ionic_model_force_constant(r, offset=corec)
       beta = ionic_model_beta(kf, t)
       return beta

   def beta_error(corec):
       return get_my_beta(corec) - target_beta

   if mode=='correction':
       corec_needed = spopt.brentq(beta_error, 0.1, 10)
   elif mode=='offset':
      ks_uncor = ionic_model_force_constant(melt_bond_length(p, c))
      corec_needed = spopt.brentq(beta_error, -0.999 * ks_uncor, 100*ks_uncor )
   return corec_needed

def ionic_model_beta(kf, T):
   """
   Calculate beta as per equation 27 of Young et al. (2015)
   """
   h = 6.62607004E-34 # Plank constant (m^2 kg s^-1)
   kb = 1.38064852E-23 # Boltzman constant (m^2 kg s^-2 K^-1)
   m1 = 24 # amu
   m2 = 26 # amu
   u = 1.6605402E-27 # Unified atomic mass (kg) - an amu in kg

   beta = 1 + (1/24) * (h / (kb * T))**2 * ((1 / (m1 * u)) - (1 / (m2 * u))) * (kf / (4 * np.pi**2))

   # Return 1000.ln(beta) as that's what we do with everything else
   frac_factor = 1000.0 * np.log(beta)
   return frac_factor

def plot_force_constants(pressures, coeff_sets, names=None, styles=None,
                         colors=None, filename=None, kcorrs=None, offsets=None):

    import matplotlib
    if filename is not None:
        matplotlib.use('Agg')
    import matplotlib.pyplot as plt

    fig, axs = plt.subplots(ncols=2)
    if type(coeff_sets) is list or type(coeff_sets) is tuple:
        if (names is None) and (styles is None):
            for coeffs in coeff_sets:
                r = melt_bond_length(pressures, coeffs)
                k = ionic_model_force_constant(r)
                axs[0].plot(pressures, r/1-E10)
                axs[1].plot(pressures, k)
        elif styles is None:
            for coeffs, name in zip(coeff_sets, names):
                r = melt_bond_length(pressures, coeffs)
                k = ionic_model_force_constant(r)
                axs[0].plot(pressures, r/1E-10, label=name)
                axs[1].plot(pressures, k, label=name)
        else:
            for coeffs, name, style, color, cor, off in zip(coeff_sets, names,
                                                styles, colors, kcorrs, offsets):
                r = melt_bond_length(pressures, coeffs)
                k = ionic_model_force_constant(r, correction=cor, offset=off)
                axs[0].plot(pressures, r/1E-10, label=name, linestyle=style,
                         color=color)
                axs[1].plot(pressures, k, label=name, linestyle=style,
                         color=color)
    else:
        r = melt_bond_length(pressures, coeff_sets)
        k = ionic_model_force_constant(r)
        axs[0].plot(pressures, r/1E-10, "b-")
        axs[1].plot(pressures, k, "b-")

    axs[0].set_ylabel("Bond length (Angstroms)")
    axs[0].set_xlabel("P (GPa)")
    axs[1].set_ylabel("Force constant (N/m ???)")
    axs[1].set_xlabel("P (GPa)")
    plt.tight_layout()

    if names is not None:
        plt.legend(loc=2)

    if filename is not None:
        plt.savefig(filename)
    else:
        plt.show()

if __name__ == "__main__":

    # If run on the command line, just make some plots

    import castep_isotope_sub
    import alpha_plotting

    # From Remco's spreadsheet. r(p) = c0 + c1*p + c2*p^2
    # where r is the bond length (in angstroms here) and
    # p is pressure (in GPa)
    r_coefs_melt_dekoker = [1.9613, -0.00165, 0.0000019]
    r_coefs_melt_fudge =   [2.0909, -0.00165, 0.0000019]

    forsterite_r_0 = 2.1170E-10
    forsterite_r_50 = 1.9520E-10
    forsterite_r_100 = 1.870E-10

    beta_dek_lq = ionic_model_beta(ionic_model_force_constant(
                         melt_bond_length(0, r_coefs_melt_dekoker)),1573.0)
    beta_fudge_lq = ionic_model_beta(ionic_model_force_constant(
                         melt_bond_length(0, r_coefs_melt_fudge)),1573.0)
    beta_fo = ionic_model_beta(ionic_model_force_constant(
                         forsterite_r_0),1573.0)

    print("Reduced frac factor liquid de Koker:", beta_dek_lq, "per mil")
    print("Reduced frac factor liquid r fudge:", beta_fudge_lq, "per mil")
    print("Reduced frac factor forsterite r:", beta_fo, "per mil")
    print("Fractionation factor de Koker - fo:", beta_fo - beta_dek_lq, "per mil")
    print("Fractionation factor fudge - fo:", beta_fo - beta_fudge_lq, "per mil")

    meaured_alpha = 0.080
    meaured_alpha = 0.07677 # Test to check the bond length fudge matces
    target_beta = meaured_alpha + beta_fo
    k_corr = calculate_force_constant_correction(target_beta,
                                                 r_coefs_melt_dekoker, 1573.0)
    print("We need a correction to the force constant of:", k_corr, "UNITS?")

    print("Corrected beta:", ionic_model_beta(ionic_model_force_constant(
                 melt_bond_length(0, r_coefs_melt_dekoker),
                 correction=k_corr), 1573.0))
    print("Corrected alpha:", beta_fo - ionic_model_beta(ionic_model_force_constant(
                 melt_bond_length(0, r_coefs_melt_dekoker),
                 correction=k_corr), 1573.0))

    # Plot r and force constant as function of P
    plot_force_constants(np.linspace(0, 150, num=100),
                         [r_coefs_melt_dekoker, r_coefs_melt_fudge, r_coefs_melt_dekoker],
                         names=['de Koker', 'fudge', 'k cor'],
                         kcorrs=[1,1,k_corr],
                         styles=['-','-', ':'],
                         colors=['k', 'b', 'g'], filename="ionic_model_rs.pdf")

    temps = np.concatenate((np.linspace(300.0, 500.0, num=40),
                            np.linspace(501.0, 4000.0, num=40)))

    betas = []
    names = []
    colors = []
    styles = []

    names.append('de Koker 0 GPa')
    betas.append(ionic_model_beta(ionic_model_force_constant(
                 melt_bond_length(0, r_coefs_melt_dekoker)),temps))
    colors.append('k')
    styles.append('-')

    names.append('de Koker 50 GPa')
    betas.append(ionic_model_beta(ionic_model_force_constant(
                 melt_bond_length(50, r_coefs_melt_dekoker)),temps))
    colors.append('k')
    styles.append('--')

    names.append('de Koker 100 GPa')
    betas.append(ionic_model_beta(ionic_model_force_constant(
                 melt_bond_length(100, r_coefs_melt_dekoker)),temps))
    colors.append('k')
    styles.append(':')

    names.append('de Koker 0 GPa kcor')
    betas.append(ionic_model_beta(ionic_model_force_constant(
                 melt_bond_length(0, r_coefs_melt_dekoker),
                 correction=k_corr),temps))
    colors.append('y')
    styles.append('-')

    names.append('de Koker 50 GPa kcor')
    betas.append(ionic_model_beta(ionic_model_force_constant(
                 melt_bond_length(50, r_coefs_melt_dekoker),
                 correction=k_corr),temps))
    colors.append('y')
    styles.append('--')

    names.append('de Koker 100 GPa kcor')
    betas.append(ionic_model_beta(ionic_model_force_constant(
                 melt_bond_length(100, r_coefs_melt_dekoker),
                 correction=k_corr),temps))
    colors.append('y')
    styles.append(':')

    names.append('fudge 0 GPa')
    betas.append(ionic_model_beta(ionic_model_force_constant(
                 melt_bond_length(0, r_coefs_melt_fudge)),temps))
    colors.append('b')
    styles.append('-')

    names.append('fudge 50 GPa')
    betas.append(ionic_model_beta(ionic_model_force_constant(
                 melt_bond_length(50, r_coefs_melt_fudge)),temps))
    colors.append('b')
    styles.append('--')

    names.append('fudge 100 GPa')
    betas.append(ionic_model_beta(ionic_model_force_constant(
                 melt_bond_length(100, r_coefs_melt_fudge)),temps))
    colors.append('b')
    styles.append(':')

    names.append('forsterite ionic model 0 GPa')
    betas.append(ionic_model_beta(ionic_model_force_constant(
                 forsterite_r_0),temps))
    colors.append('g')
    styles.append('-')

    names.append('forsterite ionic model 50 GPa')
    betas.append(ionic_model_beta(ionic_model_force_constant(
                 forsterite_r_50),temps))
    colors.append('g')
    styles.append('--')

    names.append('forsterite ionic model 100 GPa')
    betas.append(ionic_model_beta(ionic_model_force_constant(
                 forsterite_r_100),temps))
    colors.append('g')
    styles.append(':')

    castep_isotope_sub.plot_beta(temps, betas , names,
            colors=colors, styles=styles, filename='ionic_model_beta.pdf')

    # Plot alpha for Fo # NB: this is liq - Fo not Fo - liq.
    alpha_t_0gpa = ((ionic_model_beta(ionic_model_force_constant(
                         melt_bond_length(0, r_coefs_melt_fudge)),temps)) -
                    (ionic_model_beta(ionic_model_force_constant(
                         forsterite_r_0),temps)))
    alpha_t_50gpa = ((ionic_model_beta(ionic_model_force_constant(
                         melt_bond_length(50, r_coefs_melt_fudge)),temps)) -
                    (ionic_model_beta(ionic_model_force_constant(
                         forsterite_r_50),temps)))
    alpha_t_100gpa = ((ionic_model_beta(ionic_model_force_constant(
                         melt_bond_length(100, r_coefs_melt_fudge)),temps)) -
                    (ionic_model_beta(ionic_model_force_constant(
                         forsterite_r_100),temps)))

    dkalpha_t_0gpa = ((ionic_model_beta(ionic_model_force_constant(
                         melt_bond_length(0, r_coefs_melt_dekoker)),temps)) -
                    (ionic_model_beta(ionic_model_force_constant(
                         forsterite_r_0),temps)))
    dkalpha_t_50gpa = ((ionic_model_beta(ionic_model_force_constant(
                         melt_bond_length(50, r_coefs_melt_dekoker)),temps)) -
                    (ionic_model_beta(ionic_model_force_constant(
                         forsterite_r_50),temps)))
    dkalpha_t_100gpa = ((ionic_model_beta(ionic_model_force_constant(
                         melt_bond_length(100, r_coefs_melt_dekoker)),temps)) -
                    (ionic_model_beta(ionic_model_force_constant(
                         forsterite_r_100),temps)))

    import matplotlib.pyplot as plt
    fix, ax1 = plt.subplots()
    ax1.plot(temps, alpha_t_0gpa, 'k-', label='[fudge lq - fo] 0 GPa')
    ax1.plot(temps, alpha_t_50gpa, 'b-', label='[fudge lq - fo] 50 GPa')
    ax1.plot(temps, alpha_t_100gpa, 'g-', label='[fudge lq - fo] 100 GPa')
    ax1.plot(temps, dkalpha_t_0gpa, 'k:', label='[dk lq - fo] 0 GPa')
    ax1.plot(temps, dkalpha_t_50gpa, 'b:', label='[dk lq - fo] 50 GPa')
    ax1.plot(temps, dkalpha_t_100gpa, 'g:', label='[dk lq - fo] 100 GPa')
    ax1.set_ylabel(r"$\Delta^{}$Mg (per mill) relative to {}".format('{26}', "liquid"))
    ax1.set_xlabel("T (K)")
    plt.legend()
    plt.savefig("ionic_model_alpha.pdf")


import pygame,sys
from PIL import Image
import random
import numpy as np
from pygame.locals import *
pygame.init()
pygame.display.set_caption("九宫格")
screen =pygame.display.set_mode([1000,1000])
myfont=pygame.font.SysFont(None,30)
img=Image.open(r'img\0.png')
size=img.size
i,j=2,2
h=int(size[1]/3)
w=int(size[0]/3)
tuxiang=[1,2,3],[4,5,6],[7,8,9]
tuxiang=np.asarray(tuxiang)
img1=pygame.image.load(r'九宫格\10.png')
img2=pygame.image.load(r'九宫格\11.png')
img3=pygame.image.load(r'九宫格\12.png')
img4=pygame.image.load(r'九宫格\13.png')
img5=pygame.image.load(r'九宫格\14.png')
img6=pygame.image.load(r'九宫格\15.png')
img7=pygame.image.load(r'九宫格\16.png')
img8=pygame.image.load(r'九宫格\17.png')
img9=pygame.image.load(r'九宫格\18.png')
def fenge():
    img=Image.open(r'img\0.png')
    size=img.size
    h=size[1]/3
    w=size[0]/3
    n=3
    k=1
    for i in range(n):
        for j in range(n):
            a=img.crop((i*w,j*h,(i+1)*w,(j+1)*h))
            a.save(str(k)+'.png')
            k+=1
while True:
    screen.fill([0,0,0])
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key==K_LEFT:
                if i>0:
                    tuxiang[i][j],tuxiang[i-1][j]=tuxiang[i-1][j],tuxiang[i][j]
                    i-=1
                    print(tuxiang)
            elif event.key==K_RIGHT:
                if i<2:
                    tuxiang[i][j],tuxiang[i+1][j]=tuxiang[i+1][j],tuxiang[i][j]
                    i+=1
                    print(tuxiang)
            elif event.key==K_UP:
                if j>0:
                    tuxiang[i][j],tuxiang[i][j-1]=tuxiang[i][j-1],tuxiang[i][j]
                    j-=1
                    print(tuxiang)
            elif event.key==K_DOWN:
                if j<2:
                    tuxiang[i][j],tuxiang[i][j+1]=tuxiang[i][j+1],tuxiang[i][j]
                    j+=1
                    print(tuxiang)
        if event.type == pygame.QUIT:
            sys.exit()
    for a in range(3):
        for b in range(3):
            if tuxiang[a][b]==1:
                screen.blit(img1,(a*h,b*h))
            elif tuxiang[a][b]==2:
                screen.blit(img2,(a*h,b*h))
            elif tuxiang[a][b]==3:
                screen.blit(img3,(a*h,b*h))
            elif tuxiang[a][b]==4:
                screen.blit(img4,(a*h,b*h))
            elif tuxiang[a][b]==4:
                screen.blit(img4,(a*h,b*h))
            elif tuxiang[a][b]==5:
                screen.blit(img5,(a*h,b*h))
            elif tuxiang[a][b]==6:
                screen.blit(img6,(a*h,b*h))
            elif tuxiang[a][b]==7:
                screen.blit(img7,(a*h,b*h))
            elif tuxiang[a][b]==8:
                screen.blit(img8,(a*h,b*h))
            elif tuxiang[a][b]==9:
                screen.blit(img9,(a*h,b*h))
    pygame.display.update()


def method(s):
    if len(s) == 0:
        return s
    if len(s) == 1:
        if ord(s[0]) < ord(s[1]):
            return s[::-1]
        else:
            return s
    start = 0
    dif = ord(s[1]) - ord(s[0])
    res = ''
    for i in range(2, len(s)):
        if ord(s[i]) - ord(s[i-1]) != dif or (i == len(s) - 1 and ord(s[i]) - ord(s[i-1]) == dif):
            tmp = s[start:i]
            if ord(s[i]) - ord(s[i-1]) == dif:
                tmp = s[start:]
            if len(tmp) > 1 and ord(tmp[0]) < ord(tmp[1]):
                tmp = tmp[::-1]
            if len(tmp) > len(res):
                res = tmp
            elif len(tmp) == len(res):
                if ord(tmp[0]) > ord(res[0]):
                    res = tmp
            dif = ord(s[i]) - ord(s[i-1])
            start = i - 1
    return res

if __name__ == '__main__':
    result = []
    for i in range(int(input())):
        result.append(method(input()))
    for i in range(len(result)):
        print(result[i])


from datasets import GeneratorBasedBuilder, BuilderConfig, Version, DatasetInfo, Features, Value, \
    Sequence, ClassLabel, DownloadManager, SplitGenerator, Split
import os
import textwrap
from .nerkor import NerKorConfig, get_repo_url

_CITATION = """
@inproceedings{NerKorCarsONPP,
  author    = {Nov{\'a}k Attila and
               Nov{\'a}k Borb{\'a}la,
  title     = {{NerKor} 1.41e},
  booktitle = {XVIII. Magyar Számítógépes Nyelvészeti Konferencia},
  year      = {2022},
}
"""
_SOURCE = "https://github.com/novakat/NYTK-NerKor-Cars-OntoNotesPP/archive/eb94fc3c22ed27589593716e150d73e060e2333d.zip"
_SUBS = ["fiction", "legal", "news", "web", "wikipedia", "cars", "all"]

# Missing tags from readme
_ONPP_TAGS = ["PER", "FAC", "ORG", "GPE", "LOC", "PROD", "EVENT", "WORK_OF_ART", "LAW", "NORP", "LANGUAGE", "DATE",
              "TIME", "PERCENT", "MONEY", "QUANTITY", "ORDINAL", "CARDINAL", "AWARD", "CAR", "MEDIA", "SMEDIA",
              "ORG-GPE", "PROJ", "MISC", "MISC-ORG", "MISC-PER", "MISC-LOC", "DUR", "ID", "AGE", "BUS", "MOTOR", "PRIZE"]
_ONPP_NER = ClassLabel(
    names=["O"] + [f"{pre}-{tag}" for tag in _ONPP_TAGS for pre in ['B', 'I']]
)

class NerKorExtended(GeneratorBasedBuilder):
    """NerKor 1.41e datasets."""
    # FORM ONPP:NER
    BUILDER_CONFIGS = [
        NerKorConfig(
            name=name,
            description=textwrap.dedent(""""""),
            text_features=["form", "ner"],
            data_url=_SOURCE,
            data_dir=f"nerkor_1_41e/",
            url=get_repo_url(_SOURCE)
        ) for name in _SUBS
    ]

    def _info(self):
        features = {
            "idx": Value("int32"),
            "text": Value("string"),
            "tokens": Sequence(Value("string")),
            "ner": Sequence(_ONPP_NER),
            "file_name": Value("string"),
            "sentence_id": Value("int32"),
            "morph_tagged": Value("bool_"),
        }
        return DatasetInfo(
            description=self.config.description,
            features=Features(features),
            homepage=self.config.url,
            citation=textwrap.dedent(_CITATION),
        )

    def _split_generators(self, dl_manager: DownloadManager):
        path = dl_manager.download_and_extract(self.config.data_url)
        return [
            SplitGenerator(
                name=Split.TRAIN,
                gen_kwargs={"split_key": "train", "data_file": path},
            ),
            SplitGenerator(
                name=Split.VALIDATION,
                gen_kwargs={"split_key": "validation", "data_file": path},
            ),
            SplitGenerator(
                name=Split.TEST,
                gen_kwargs={"split_key": "test", "data_file": path},
            )
        ]

    def _generate_examples(self, data_file, split_key, **kwargs):
        base_path = os.path.join(data_file, os.listdir(data_file)[0], "data")
        n = 0
        split = split_key if split_key != "validation" else "devel"
        files = [x for x in os.listdir(base_path) if split in x and (self.config.name in x or self.config.name == "all")]
        for file in files:
            for data in self._process_files(os.path.join(base_path, file), n):
                yield data
                n += 1

    @staticmethod
    def _process_files(data_file_path: str, n: int):
        with open(data_file_path, mode="r", encoding="utf8") as f:
            content = f.readlines()

        tokens, ner = [], []

        sentence_id = 0
        for i, row in enumerate(content[1:]):
            if row == '\n':
                p = data_file_path.split("/")[-1]
                yield n, {
                    "idx": n,
                    "text": " ".join(tokens),
                    "tokens": tokens,
                    "ner": ner,
                    "file_name": p,
                    "sentence_id": sentence_id,
                    "morph_tagged": not ('no-morph' in p)
                }
                tokens, ner = [], []
                sentence_id += 1
                n += 1
                continue

            data = row.split("\t")

            tokens.append(data[0])
            ner.append(data[1].rstrip('\n'))


#!/usr/bin/env python
import os
import sys

from setuptools import setup
from setuptools.command.test import test as TestCommand

from jsonmodels import __author__, __email__, __version__

PROJECT_NAME = "jsonmodels"

if sys.argv[-1] == "publish":
    os.system("python setup.py sdist upload")
    sys.exit()

class PyTest(TestCommand):
    user_options = [("pytest-args=", "a", "Arguments to pass to py.test")]

    def initialize_options(self):
        TestCommand.initialize_options(self)
        self.pytest_args = ["--cov", PROJECT_NAME]

    def finalize_options(self):
        TestCommand.finalize_options(self)
        self.test_args = []
        self.test_suite = True

    def run_tests(self):
        import pytest

        errno = pytest.main(self.pytest_args)
        sys.exit(errno)

# Hacking tests.
try:
    import tests
except ImportError:
    pass
else:
    if "test" in sys.argv and "--no-lint" in sys.argv:
        tests.LINT = False
        del sys.argv[sys.argv.index("--no-lint")]

    if "test" in sys.argv and "--spelling" in sys.argv:
        tests.CHECK_SPELLING = True
        del sys.argv[sys.argv.index("--spelling")]

readme = open("README.rst").read()
history = open("HISTORY.rst").read().replace(".. :changelog:", "")

setup(
    name=PROJECT_NAME,
    version=__version__,
    description="Models to make easier to deal with structures that"
    " are converted to, or read from JSON.",
    long_description=readme + "\n\n" + history,
    author=__author__,
    author_email=__email__,
    url="https://github.com/jazzband/jsonmodels",
    packages=[
        PROJECT_NAME,
    ],
    package_dir={PROJECT_NAME: PROJECT_NAME},
    include_package_data=True,
    install_requires=[
        "python-dateutil",
    ],
    license="BSD",
    zip_safe=False,
    keywords=PROJECT_NAME,
    python_requires=">=3.8",
    classifiers=[
        "Intended Audience :: Developers",
        "License :: OSI Approved :: BSD License",
        "Natural Language :: English",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3.10",
        "Programming Language :: Python :: 3.11",
        "Programming Language :: Python :: 3.12",
        "Programming Language :: Python :: 3 :: Only",
    ],
    cmdclass={
        "test": PyTest,
    },
)


from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.db.models import Count
from django.http import HttpResponse
from django.shortcuts import render

from apps.web.models import Competition

User = get_user_model()

@login_required
def analytics_detail(request):
    if not request.user.is_staff:
        return HttpResponse(status=404)

    monthly_total_users_joined = {}
    for date in User.objects.all().datetimes('date_joined', 'month'):
        if date.year not in monthly_total_users_joined:
            monthly_total_users_joined[date.year] = {}
        users_joined_this_month = User.objects.filter(date_joined__month=date.month,
                                                      date_joined__year=date.year).aggregate(Count('pk'))
        monthly_total_users_joined[date.year][date.strftime("%B")] = users_joined_this_month['pk__count']

    return render(request, "analytics/analytics.html", {
        'registered_user_count': User.objects.all().count(),
        'competition_count': Competition.objects.all().count(),
        'competitions_published_count': Competition.objects.filter(published=True).count(),
        'monthly_total_users_joined': monthly_total_users_joined,
    })


import os
from unittest import TestCase, installHandler, main
from test.support import EnvironmentVarGuard
from threading import Thread
from logging import getLogger
from logging.handlers import QueueHandler
from multiprocessing import Process, Event, Queue
from watsor.stream.log import LogHandler
from watsor.stream.share import FrameBuffer
from watsor.stream.sync import CountDownLatch
from watsor.detection.detector import create_object_detectors
from watsor.filter.sieve import DetectionSieve
from watsor.filter.track import TrackFilter
from watsor.filter.confidence import ConfidenceFilter
from watsor.stream.share import RateLimiter
from watsor.config.coco import get_coco_class
from watsor.test.detect_stream import Artist, ShapeCounter

class TestDetect(TestCase):

    def setUp(self):
        if not os.path.exists(self._get_model_path()):
            self.skipTest('Test skipped due to the absence of shape object model')

        installHandler()

    def test_shape_detection(self):
        """Tests TensorFlow object detection using the trained model of simple geometric shapes.
        The detector recognises shapes drawn on a frame image, the sieve filters those having confidence
        above 50%, lastly shapes are counted signalling to end the test.
        """

        with EnvironmentVarGuard() as env:
            env.set("TF_CPP_MIN_LOG_LEVEL", "3")
            env.set("CORAL_VISIBLE_DEVICES", "")
            env.set("CUDA_VISIBLE_DEVICES", "")

            frame_buffer = FrameBuffer(10, 100, 100)

            frame_queue = Queue(1)
            subscriber_queue = Queue(1)
            detection_sieve_queue = Queue(1)

            log_queue = Queue()
            getLogger().addHandler(QueueHandler(log_queue))

            stop_process_event = Event()

            latch = CountDownLatch(100)

            artist = Artist("artist", stop_process_event, log_queue, frame_queue, frame_buffer)

            detection_sieve = DetectionSieve("sieve", stop_process_event, log_queue,
                                             detection_sieve_queue, frame_buffer,
                                             self._create_filters(), RateLimiter())

            processes = [artist, detection_sieve,
                         LogHandler(Thread, "logger", stop_process_event, log_queue, filename=None),
                         ShapeCounter(Thread, "counter", stop_process_event, log_queue, subscriber_queue,
                                      frame_buffer, latch)]

            processes += create_object_detectors(Process, stop_process_event, log_queue, frame_queue,
                                                 {artist.name: frame_buffer}, self._get_model_path())

            artist.subscribe(detection_sieve_queue)
            detection_sieve.subscribe(subscriber_queue)

            for process in processes:
                process.start()

            try:
                self.assertTrue(latch.wait(15))
            finally:
                stop_process_event.set()
                for process in processes:
                    process.join(30)

    @staticmethod
    def _create_filters():
        return [TrackFilter([ConfidenceFilter({
            'detect': [{
                get_coco_class(1).label: {  # triangle
                    'confidence': 50
                }}, {
                get_coco_class(2).label: {  # ellipse
                    'confidence': 50
                }}, {
                get_coco_class(3).label: {  # rectangle
                    'confidence': 50
                }}]})], 1, 1)]

    @staticmethod
    def _get_model_path():
        return os.path.join(os.path.dirname(__file__), 'model')

if __name__ == '__main__':
    main(verbosity=2)


#!/usr/local/bin/python3.6
from subprocess import check_output

####################################
############ EDIT !!! ##############
####################################
#epsilon
e_xx = 11.069788
e_yy = 11.069852
e_zz = 11.711368
e_xy = 0.000001
e_xz = 0.000383
e_yz = 0.000809
###############
#encut eV
ENCUT = 500
#path of bulk
bulk_path = "/scratch/jinho/2_defect_postprocessing/1_ZnIn2S4/3_opt/z_bulk_supercell/"

####################################
############ EDIT !!! ##############
####################################

CHARGE = float(input("charge value(the number of electron ex) -1 state  q= 1 electron: "))

# covert eV to Ry unit
ENCUT = ENCUT * 0.073498618

##must edit path!!!
check_output(f"diff {bulk_path}loop_1/POSCAR ../../loop_1/POSCAR > diff_defect.txt; exit 0;", shell=True)

diff = open("diff_defect.txt", 'r')
line_t = []
while True:
    line = diff.readline()
    if not line: break
    line_t.append(line)
diff.close()

line_t_L = line_t[-1]

#defect site D_x: x position, D_y: y position, D_z: z position
D_x = float(line_t_L.split()[1])
D_y = float(line_t_L.split()[2])
D_z = float(line_t_L.split()[3])

command_sxd = f'sxdefectalign --ecut {ENCUT:0.4f} --gstep 0.00001 --beta 1 --gamma 1 --expnorm 0 --printRho --charge {CHARGE:0.0f} --tensor {e_xx:0.6f},{e_yy:0.6f},{e_zz:0.6f},{e_yz:0.6f},{e_xz:0.6f},{e_xy:0.6f} --center {D_x:0.4f},{D_y:0.4f},{D_z:0.4f} --relative --vref ../../1_scf/LOCPOT --vdef {bulk_path}/1_scf/LOCPOT --vasp >> out.log'

print (command_sxd)

check_output(command_sxd, shell=True)

##########################################################
############ sxdefectaling ###############################
##########################################################

##########################################################
############# postprocessing #############################
##########################################################

f = open('vAtoms.dat', 'r')

"""
It is available to edit the variations
r_a, r_b, and r_c are half of a, b, and c parameters in bohr unit, respectively.
defect_a, defect_b, and defect_c are the positions of defect (a,b,c) in bohr unit, respectively.
"""
log = open("out.log", 'r')
line_log = []
while True:
    line = log.readline()
    if not line: break
    line_log.append(line)
log.close()
line_t_log = line_log[1]
line_tt_log = line_t_log.split()[3]

latt_a = float(line_tt_log[5:12])
latt_b = float(line_tt_log[24:31])
latt_c = float(line_tt_log[43:50])
r_a = latt_a / 2
r_b = latt_b / 2
r_c = latt_c / 2
defect_a = 0 #* D_z
defect_b = 0 #* D_y
defect_c = 46.4438 #* D_z

total_list = []
aver_list = []
aver_L = []
total_L = []

for i in f :
    if len(i) == 1:
        continue
    else:
        tmp_list = list(map(float,i.strip().split()))
        #print(tmp_list)

        """
        Screening Wigner-Seiz cell from vAtoms.dat file
        Only use for cubic cells
        Wigner-Seiz cell:
        a - a' =< x =< a + a'
        b - b' =< y =< b + b'
        c - c' =< z =< c + c'
        a, b, and c  are the defect position in bohr unit
        a', b', and c' are the half of cell parameters in bohr unit
        ellipse_cell = (x-a)^2/a'^2 + (y-b)^2/b'^2 + (z-c)^2/c'^2 = 1 ; formula of ellipse
        ellipse_cell >= 1
        """

        if tmp_list[4] >= defect_a - r_a and tmp_list[4] <= defect_a + r_a :
            if tmp_list[5] >= defect_b - r_b and tmp_list[5] <= defect_b + r_b :
                if tmp_list[6] >= defect_c - r_c and tmp_list[6] <= defect_c + r_c :

                    total_list = list(map(float,tmp_list))
                    total_L.append(total_list)
                    #print('total')
                    #print(total_list)

                    ellipse_cell = (tmp_list[4]-defect_a)**2/(r_a**2) \
                                   + (tmp_list[5]-defect_b)**2/(r_b**2) \
                                   + (tmp_list[6]-defect_c)**2/(r_c**2)
                    if ellipse_cell >= 1 :
                        aver_list = list(map(float,tmp_list))
                        aver_L.append(aver_list)
                        #print('average')
                        #print(aver_list)

                    else:
                        continue
                else:
                    continue
            else:
                continue
        else:
            continue
f.close()

aver_V_list = []
# aver_V is the align value (C value)
aver_V = 0

for i, row in enumerate(aver_L):
    #print(row)
    aver_V_list.append(row[3])
    #print(row[3])
    aver_V += float(row[3])

aver_V = aver_V / len(aver_V_list)
print("We apply Weiger-Seiz cell and anisotropy point charge method to compute the correction energy")
print("A plateu value of C = " + str(aver_V))

"""
Create the .idx file to plot all data including Wigner-Seiz cell
"""

ff = open("vAtoms.itx", 'w')
ff.write("IGOR" + '\n')
ff.write("WAVES/D " + "r_cell" + " " + "V_lon" + " " + "V_def_ref" + " "
             + "V_def_ref_lon" + " " + "x_para " + "y_para "+"z_para "+'\n')
ff.write("BEGIN"+'\n')

for line in total_L:
    ff.write(' '.join(list(map(str, line))) + '\n')
ff.write("END" + '\n')

ff.write("WAVES/D align_r align_potential" + '\n')
ff.write("BEGIN"+'\n')
ff.write("0 "+ str(aver_V)+'\n')
ff.write("100 "+str(aver_V) +'\n')
ff.write("END" + '\n')

ff.write("X Display /W=(-1285,63,-673,525) V_def_ref,V_lon vs r_cell" + '\n')
ff.write("X AppendToGraph V_def_ref_lon vs r_cell"+'\n')
ff.write("X AppendToGraph align_potential vs align_r"+'\n')
ff.write("X ModifyGraph gFont=\"Times New Roman\",gfSize=28,width=453.543,height=340.157" + '\n')
ff.write("X ModifyGraph mode=3" + '\n')
ff.write("X ModifyGraph marker(V_lon)=5,marker(V_def_ref_lon)=6" + '\n')
ff.write("X ModifyGraph rgb(V_lon)=(0,0,65535),rgb(V_def_ref_lon)=(0,0,0)" + '\n')
ff.write("X ModifyGraph msize=5" + '\n')
ff.write("X ModifyGraph tick=2" + '\n')
ff.write("X ModifyGraph mirror=1" + '\n')
ff.write("X ModifyGraph standoff=0" + '\n')
ff.write("X ModifyGraph axThick=1.5" + '\n')
ff.write("X ModifyGraph axisOnTop=1" + '\n')
ff.write("X ModifyGraph btLen=10" + '\n')
ff.write("X ModifyGraph lstyle(align_potential)=7,lsize(align_potential)=1.5,rgb(align_potential)=(21845,21845,21845), mode(align_potential)=0" +'\n')
ff.write("X ModifyGraph manTick(left)={0,1,0,0},manMinor(left)={0,50}" + '\n')
ff.write("X ModifyGraph manTick(bottom)={0,5,0,0},manMinor(bottom)={0,50}" + '\n')
ff.write("X SetAxis left -2,1" + '\n')
ff.write("X SetAxis bottom 0,25" + '\n')
ff.write("X TextBox/C/N=text1/F=0/B=1/A=MC \"\\\\f02C\\\\f00 = "+ str("%0.3f" %aver_V) +"\""+'\n')
ff.write("X Legend/C/N=text0/J/F=0/B=1/A=MC/X=25.33/Y=-26.18"
         + " \"\\\\s(V_def_ref) \\\\f02V\\\\f00\\\\Bq/b\\\\M\\r\\\\s(V_lon)"
         + " \\\\f02V\\\\f00\\\\BPC\\\\M\\r\\\\s(V_def_ref_lon) D\\\\f02V\\\\"
         + "f00\\\\BPC,q/b\\\\M\\r\\\\s(align_potential) align\""+'\n')

ff.close()

######################################################################
###################### Calculate correction energy ###################
######################################################################

log_2 = open('out.log', 'r')
line_log_2 = []

while True:
    line_2 = log_2.readline()
    if not line_2: break
    line_log_2.append(line_2)
log_2.close()

corr_E = line_log_2[-1].split()[3]
print("Defect correction (eV): " + corr_E)


from .AnimNode import *
from .AnimationClip import AnimationClip
from .Condition import *
from .Parameter import Parameter

class AnimGraph:
    def __init__(self, animator, entry:AnimNode = None):
        self.animator = animator
        self.entryNode = entry
        self.currentNode = self.entryNode
        self.nodes = list()

# Add node to graph
    def AddNode(self, name:str, clip:AnimationClip) -> AnimNode:
        _node = AnimNode(name, clip)
        self.nodes.append(_node)
        if self.currentNode == None:
            self.entryNode = _node
            self.currentNode = _node
        return _node

# Add transition to node
    def AddTransition(self, fromNodeName:str, toNodeName:str, condition:Condition):
        _from:AnimNode = None
        _to:AnimNode  = None
        for node in self.nodes:
            if node.name == fromNodeName:
                _from = node
            if node.name == toNodeName:
                _to = node

        _from.AddTransition(_to, condition)

# Change Node
    def ChangeNode(self, targetNode:AnimNode):
        targetNode.clip.currentFrame = 0
        targetNode.clip.isFinished = False
        self.currentNode = targetNode

# Check whether animator transit
    def CheckTransition(self, paramName:str):
        for transition in self.currentNode.transitions:
            #print("Check Transition by", paramName)
            if transition.condition.targetParamName == paramName:
                #print("Find transition by", paramName)
                shouldTransit = self.CheckCondition(self.GetParameter(paramName), self.currentNode.transitions)
                #print("Should Transit by", paramName, "is", shouldTransit)
                if shouldTransit:
                    #print("ChangeNode to", transition.toNode.name)
                    self.ChangeNode(transition.toNode)

# Check whether condition to transit is true
    def CheckCondition(self, parameter:Parameter, transitions:list) -> bool:
        for transition in transitions:
            _condition:Condition = transition.condition
            if _condition.conditionType == ConditionType.EQUAL:
                return parameter.value == _condition.value
            elif _condition.conditionType == ConditionType.LESS:
                return parameter.value < _condition.value
            elif _condition.conditionType == ConditionType.LESS_EQUAL:
                return parameter.value <= _condition.value
            elif _condition.conditionType == ConditionType.BIGGER:
                return parameter.value > _condition.value
            elif _condition.conditionType == ConditionType.BIGGER_EQUAL:
                return parameter.value >= _condition.value
            elif _condition.conditionType == ConditionType.NOT:
                return parameter.value != _condition.value
            elif _condition.conditionType == ConditionType.TRIGGERED:
                parameter.value = False
                #print("Trigger")
                return True

    def GetParameter(self, name) -> Parameter:
        for param in self.animator.parameters:
            if param.name == name:
                return param


# coding=utf-8
import scrapy

from scrapy.http import Request
from biliob_spider.items import VideoItem
from datetime import datetime
import time
import json
import logging
from pymongo import MongoClient
from db import db
from util import sub_channel_2_channel
from biliob_spider.spiders.video_spider import VideoSpider

class VideoSpiderAll(VideoSpider):
    name = "videoSpiderAll"
    allowed_domains = ["bilibili.com"]
    start_urls = []
    custom_settings = {
        'ITEM_PIPELINES': {
            'biliob_spider.pipelines.VideoPipeline': 300,
        }
    }

    def __init__(self):

        self.db = db  # 获得数据库的句柄
        self.coll = self.db['video']  # 获得collection的句柄

    def start_requests(self):
        # 只需要aid
        c = self.coll.find({}, {'aid': 1})

        x = 0

        aid_list = []
        for each_doc in c:
            x = x + 1
            aid_list.append(each_doc['aid'])
        i = 0
        while aid_list != []:
            if i == 0:
                aid_str = ''
            aid_str += str(aid_list.pop()) + ','
            i = i + 1
            if i == 50 or aid_list == []:
                i = 0
                yield Request(
                    "https://api.bilibili.com/x/article/archives?ids=" +
                    aid_str.rstrip(','))


from __future__ import annotations

from typing import List, Optional

import numpy as np
import pandas as pd
import yaml

import ambrosia.tools.bin_intervals as bin_pkg
import ambrosia.tools.theoretical_tools as theory_pkg
from ambrosia import types
from ambrosia.tools.ab_abstract_component import ABMetaClass, ABToolAbstract, SimpleDesigner

from .handlers import EmpiricHandler, TheoryHandler, calc_prob_control_class

SIZE: str = "size"
EFFECT: str = "effect"
POWER: str = "power"
BINARY_DESIGN_METHODS: List[str] = ["theory", "binary"]

class Designer(yaml.YAMLObject, ABToolAbstract, metaclass=ABMetaClass):
    """
    Unit for experiments and pilots parameters design.

    Enables to design missing experiment parameters using historical data.
    The main related to each other designable parameters for a single metric are:

        - Effect (Minimal Detectible Effect):
            old_mean_metric_value * effect_value = new_mean_metric_value
        - Sample size:
            Number of research objects in sample
            (for example number of users and their retention).
        - Errors (I type error, II type error):
            I error (alpha):
                Probability to detect presence of effect
                for equally distributed samples.
            II error (beta):
                Probability not to find effect
                for differently distributed samples.

    Parameters
    ----------
    dataframe : PassedDataType, optional
        DataFrame with metrics historical values.
    sizes : SampleSizeType, optional
        Values of research objects number in groups samples during
        the experiment.
    effects : EffectType, optional
        Effects values that are expected during the experiment.
    first_type_errors : StatErrorType, default: ``0.05``
        I type error bounds
        P (detect difference for equal) < alpha.
    second_type_errors : StatErrorType, default: ``0.2``
        II type error bounds
        P (suppose equality for different groups) < beta.
    metrics : MetricNamesType, optional
        Column names of metrics in dataframe to be designed.
    method : str, optional
        Method used for experiment design.
        Can be ``"theory"``, ``"empiric"`` or ``"binary"``.

    Attributes
    ----------
    dataframe : PassedDataType
        DataFrame with metrics historocal values.
    sizes : SampleSizeType
        Number of research objects in group samples.
    effects : EffectType
        Effects values in the experiment.
    first_type_errors : StatErrorType, default: ``0.05``
        I type errors.
    second_type_errors : StatErrorType, default: ``0.2``
        II type errors.
    metrics : MetricNamesType
        Column names of metrics in dataframe to be designed.
    method : str
        Method used for experiment design.

    Examples
    --------
    We have retention labels for users of mobile app for previous month.
    Suppose old_retention = ``0.3``, that is 30% of users returned to the app
    in a month after installation.

    Let us fix the following parameters:
        I type error (alpha) = ``0.05``
        (5% of equal samples we can suppose to be different).

        II type error (beta) = ``0.2``
        (20% of different sampels we can suppose to be equal).

    We add onboarding to our app and want to estimate an effect, by A/B testing
    and wish to increase retention value to 31% percents, so our effect
    parameter gets value of ``1.0(3)``. Now we want to find how much users we
    need in both groups to detect such effect.

    We can use ``Designer`` class in the following way:

    >>> designer = Designer(dataframe=df, metric='retention', effect=1.033)
    >>> designer.run("size")

    Note, that default values for errors are:
        ``first_type_error`` = ``0.05``

        ``second_type_error`` = ``0.2``

    Then we get dataframe that contains value of  sufficient number of users
    for our experiment.

    Notes
    -----

    Constructors:

    >>> designer = Designer()
    >>> # You can pass an Iterable or single object for some parameters
    >>> designer = Designer(
    >>>     dataframe=df,
    >>>     sizes=[100, 200],
    >>>     metrics='LTV',
    >>>     effects=1.05
    >>> )
    >>> designer = Desginer(sizes=1000, metrics=['retention', 'LTV'])
    >>> # You can use path to .csv table for pandas
    >>> designer = Designer('./data/table.csv')

    Setters:

    >>> designer.set_first_errors([0.05, 0.01])
    >>> desginer.set_dataframe(df)

    Run:

    >>> # One can pass arguments and they will have higher priority
    >>> designer.run('size', effects=1.1)
    >>> designer.run('effect', sizes=[500, 1000], metrics='retention')
    >>> # You can set method (watch below)
    >>> designer.run('effect', sizes=[500, 1000], metrics='retention', method='binary')

    Load from yaml config:

    >>> config = '''
            !splitter # <--- this is yaml tag (!important)
                effects:
                    - 0.9
                    - 1.05
                sizes:
                    - 1000
        '''
    >>> designer = yaml.load(config)
    >>> # Or use the implmented function
    >>> designer = load_from_config(config)

    Use standalone function instead of a class:

    >>> design('size', dataframe=df, effects=1.05, metrics='retention')
    """

    # YAML tag for loading from configs
    yaml_tag = "!designer"

    def set_first_errors(self, first_type_errors: types.StatErrorType) -> None:
        if isinstance(first_type_errors, float):
            self.__alpha = [first_type_errors]
        else:
            self.__alpha = first_type_errors

    def set_second_errors(self, second_type_errors: types.StatErrorType) -> None:
        if isinstance(second_type_errors, float):
            self.__beta = [second_type_errors]
        else:
            self.__beta = second_type_errors

    def set_sizes(self, sizes: types.SampleSizeType) -> None:
        if isinstance(sizes, int):
            self.__size = [sizes]
        else:
            self.__size = sizes

    def set_effects(self, effects: types.EffectType) -> None:
        if isinstance(effects, (float, int)):
            self.__effect = [effects]
        else:
            self.__effect = effects

    def set_dataframe(self, dataframe: types.PassedDataType) -> None:
        if isinstance(dataframe, str):
            if dataframe.endswith(".csv"):
                self.__df = pd.read_csv(dataframe)
            else:
                raise ValueError("File name must ends with .csv")
        else:
            self.__df = dataframe

    def set_method(self, method: str) -> None:
        self.__method = method

    def set_metrics(self, metrics: str) -> None:
        if isinstance(metrics, types.MetricNameType):
            self.__metrics = [metrics]
        else:
            self.__metrics = metrics

    def __init__(
        self,
        dataframe: Optional[types.PassedDataType] = None,
        sizes: Optional[types.SampleSizeType] = None,
        effects: Optional[types.EffectType] = None,
        first_type_errors: types.StatErrorType = 0.05,
        second_type_errors: types.StatErrorType = 0.2,
        metrics: Optional[types.MetricNamesType] = None,
        method: str = "theory",
    ):
        """
        Designer class constructor to initialize the object.
        """
        self.set_first_errors(first_type_errors)
        self.set_second_errors(second_type_errors)
        self.set_sizes(sizes)
        self.set_effects(effects)
        self.set_metrics(metrics)
        self.set_dataframe(dataframe)
        self.set_method(method)

    def __getstate__(self):
        """
        Get the state of the object to serialize.
        """
        return dict(
            effects=self.__effect,
            sizes=self.__size,
            first_type_errors=self.__alpha,
            second_type_errors=self.__beta,
            metrics=self.__metrics,
            method=self.__method,
        )

    @classmethod
    def from_yaml(cls, loader: yaml.Loader, node: yaml.Node):
        kwargs = loader.construct_mapping(node)
        return cls(**kwargs)

    @staticmethod
    def __dataframe_handler(handler: SimpleDesigner, parameter: str, **kwargs) -> pd.DataFrame:
        """
        Handles different dataframe types.
        Now pandas and spark are available.
        """
        if parameter == SIZE:
            return handler.size_design(**kwargs)
        elif parameter == EFFECT:
            return handler.effect_design(**kwargs)
        elif parameter == POWER:
            return handler.power_design(**kwargs)
        else:
            raise ValueError(f"Only {SIZE}, {EFFECT} and {POWER} parameters of the experiment could be designed.")

    @staticmethod
    def __theory_design(label: str, args: types._UsageArgumentsType, **kwargs) -> types.DesignerResult:
        """
        Designing an experiment, using a theoretical approach.
        """
        result: types.DesignerResult = {}
        for metric_name in args["metric"]:
            kwargs["dataframe"] = args["df"]
            kwargs["column"] = metric_name
            kwargs["first_errors"] = np.array(args["alpha"])
            if label == SIZE:
                kwargs["effects"] = args[EFFECT]
                kwargs["second_errors"] = np.array(args["beta"])
            elif label == EFFECT:
                kwargs["sample_sizes"] = args[SIZE]
                kwargs["second_errors"] = np.array(args["beta"])
            elif label == POWER:
                kwargs["sample_sizes"] = args[SIZE]
                kwargs["effects"] = args[EFFECT]
            result[metric_name] = Designer.__dataframe_handler(TheoryHandler(), label, **kwargs)
        if len(args["metric"]) == 1:
            return result[args["metric"][0]]
        else:
            return result

    @staticmethod
    def __empiric_design(label: str, args: types._UsageArgumentsType, **kwargs) -> types.DesignerResult:
        """
        Designing an experiment, using an empirical approach.
        """
        kwargs["dataframe"] = args["df"]
        kwargs["alphas"] = np.array(args["alpha"])
        kwargs["metrics"] = args["metric"]
        if label == SIZE:
            kwargs["effects"] = args[EFFECT]
            kwargs["betas"] = np.array(args["beta"])
        elif label == EFFECT:
            kwargs["group_sizes"] = args[SIZE]
            kwargs["betas"] = np.array(args["beta"])
        elif label == POWER:
            groups_ratio: float = kwargs.pop("groups_ratio") if "groups_ratio" in kwargs else 1.0
            kwargs["sample_sizes_a"] = args[SIZE]
            kwargs["sample_sizes_b"] = [int(groups_ratio * size) for size in args[SIZE]]
            kwargs["effects"] = args[EFFECT]
        return Designer.__dataframe_handler(EmpiricHandler(), label, **kwargs)

    @staticmethod
    def __binary_design(label: str, args: types._UsageArgumentsType, **kwargs) -> types.DesignerResult:
        """
        Designing an experiment, using the approach for binary metrics.
        """
        result: types.DesignerResult = {}
        kwargs["first_errors"] = np.array(args["alpha"])
        for metric_name in args["metric"]:
            kwargs["p_a"] = calc_prob_control_class(args["df"], metric_name)
            if label == SIZE:
                kwargs["delta_relative_values"] = args[EFFECT]
                kwargs["second_errors"] = args["beta"]
                result[metric_name] = bin_pkg.get_table_sample_size_on_effect(**kwargs)
            elif label == EFFECT:
                kwargs["second_errors"] = args["beta"]
                kwargs["sample_sizes"] = args[SIZE]
                result[metric_name] = bin_pkg.get_table_effect_on_sample_size(**kwargs)
            elif label == POWER:
                kwargs["delta_relative_values"] = args[EFFECT]
                kwargs["sample_sizes"] = args[SIZE]
                result[metric_name] = bin_pkg.get_table_power_on_size_and_delta(**kwargs)
        if len(args["metric"]) == 1:
            return result[args["metric"][0]]
        else:
            return result

    @staticmethod
    def __pre_design(label: str, args: types._UsageArgumentsType, **kwargs) -> types.DesignerResult:
        """
        Helper function for run() method logic.
        """
        admissible_methods: List[str] = ["theory", "empiric", "binary"]
        if args["method"] == "theory":
            return Designer.__theory_design(label, args, **kwargs)
        elif args["method"] == "empiric":
            return Designer.__empiric_design(label, args, **kwargs)
        elif args["method"] == "binary":
            return Designer.__binary_design(label, args, **kwargs)
        else:
            raise ValueError(f'Choose method from {", ".join(admissible_methods)}, got {args["method"]}')

    def run(
        self,
        to_design: str,
        method: Optional[str] = None,
        sizes: Optional[types.SampleSizeType] = None,
        effects: Optional[types.EffectType] = None,
        first_type_errors: Optional[types.StatErrorType] = None,
        second_type_errors: Optional[types.StatErrorType] = None,
        dataframe: Optional[types.PassedDataType] = None,
        metrics: Optional[types.MetricNamesType] = None,
        **kwargs,
    ) -> types.DesignerResult:
        """
        Perform an experiment design for chosen parameter and metrics
        using historical data.

        Parameters
        ----------
        to_design : str
           Parameter that will be designed using historical data.
           Can take the values of ``"size"``, ``"effect"`` or ``"power"``.
        method : str, optional
            Method used for experiment design.
            Can be ``"theory"``, ``"empiric"`` or ``"binary"``.
        sizes : SampleSizeType, optional
            Values of research objects number in groups samples during
            the experiment.
            If is not provided, must exist as proper class attribute.
        effects : EffectType, optional
            Effects for experiment
            If is not provided, must exist as proper class attribute.
        first_type_errors : StatErrorType, optional
            I type error bounds
            P (detect difference for equal) < alpha.
        second_type_errors : StatErrorType, optional
            II type error bounds
            P (suppose equality for different groups) < beta.
        dataframe : PassedDataType, optional
            DataFrame with metrics historical values.
            If is not provided, must exist as proper class attribute.
        metrics : MetricNamesType, optional
            Column names of metrics in dataframe to be designed.
            If not provided, must exist as proper class attribute.
        **kwargs : Dict
            Other keyword arguments.

        Other Parameters
        ----------------
        as_numeric : bool, default: ``False``
            The result of calculations can be obtained as a percentage string
            either as a number, this parameter could used to toggle.
        groups_ratio : float, default: ``1.0``
            Ratio between two groups.
        alternative : str, default: ``"two-sided"``
            Alternative hypothesis, can be ``"two-sided"``, ``"greater"``
            or ``"less"``.
            ``"greater"`` - if effect is positive.
            ``"less"`` - if effect is negative.
        stabilizing_method : str, default: ``"asin"``
            Effect trasformation. Can be ``"asin"`` and ``"norm"``.
            For non-binary metrics: only ``"norm"`` is accceptable.
            For binary metrics: ``"norm"`` and ``"asin"``, but ``"asin"``
            is more robust and accurate.
            Acceptable only for ``"theory"`` method and actual for binary metrics!

        Returns
        -------
        result : DesignerResult
            Table or dictionary with the results of parameter design for each
            metric.
        """
        if isinstance(effects, (float, int)):
            effects = [effects]
        if isinstance(sizes, int):
            sizes = [sizes]
        if isinstance(first_type_errors, float):
            first_type_errors = [first_type_errors]
        if isinstance(second_type_errors, float):
            second_type_errors = [second_type_errors]
        if isinstance(metrics, types.MetricNameType):
            metrics = [metrics]

        arguments_choice: types._PrepareArgumentsType = {
            "df": (self.__df, dataframe),
            "alpha": (self.__alpha, first_type_errors),
            "metric": (self.__metrics, metrics),
            "method": (self.__method, method),
        }

        designable_parameters: List[str] = [SIZE, EFFECT, POWER]
        if to_design == SIZE:
            arguments_choice[EFFECT] = (self.__effect, effects)
            arguments_choice["beta"] = (self.__beta, second_type_errors)
            chosen_args: types._UsageArgumentsType = Designer._prepare_arguments(arguments_choice)
            return Designer.__pre_design(SIZE, chosen_args, **kwargs)
        elif to_design == EFFECT:
            arguments_choice[SIZE] = (self.__size, sizes)
            arguments_choice["beta"] = (self.__beta, second_type_errors)
            chosen_args: types._UsageArgumentsType = Designer._prepare_arguments(arguments_choice)
            return Designer.__pre_design(EFFECT, chosen_args, **kwargs)
        elif to_design == POWER:
            arguments_choice[SIZE] = (self.__size, sizes)
            arguments_choice[EFFECT] = (self.__effect, effects)
            chosen_args: types._UsageArgumentsType = Designer._prepare_arguments(arguments_choice)
            return Designer.__pre_design(POWER, chosen_args, **kwargs)
        else:
            raise ValueError(f'Incorrect parameter name to design, choose from {", ".join(designable_parameters)}')

def load_from_config(yaml_config: str, loader: type = yaml.Loader) -> Designer:
    """
    Restore a ``Designer`` class instance from a yaml config.

    For yaml_config you can pass file name with config,
    it must ends with .yaml, for example: "config.yaml".

    For loader you can choose SafeLoader.
    """
    if isinstance(yaml_config, str) and yaml_config.endswith(".yaml"):
        with open(yaml_config, "r", encoding="utf8") as file:
            return yaml.load(file, Loader=loader)
    return yaml.load(yaml_config, Loader=loader)

def design(
    to_design,
    dataframe: types.PassedDataType,
    metrics: types.MetricNamesType,
    sizes: types.SampleSizeType = None,
    effects: types.EffectType = None,
    first_type_errors: types.StatErrorType = (0.05,),
    second_type_errors: types.StatErrorType = (0.2,),
    method: str = "theory",
    **kwargs,
) -> types.DesignerResult:
    """
    Function wrapper around the ``Designer`` class.

    Make experiment design based on historical data using passed arguments.

    Creates an instance of the ``Designer`` class internally and execute
    run method with corresponding arguments.

    Parameters
    ----------
    to_design : str
        Parameter that will be designed using historical data.
        Can take the values of ``"size"``, ``"effect"`` or ``"power"``.
    dataframe : PassedDataType
        DataFrame with metrics historical values.
    metrics : MetricNamesType
        Column names of metrics in dataframe to be designed.
    sizes : SampleSizeType, optional
        Values of research objects number in groups samples during
        the experiment.
        If is not provided, ``effects`` value must be defined.
    effects : EffectType, optional
        Effects for experiment
        If is not provided, ``sizes`` value must be defined.
    first_type_errors : StatErrorType, default: ``(0.05,)``
        I type error bounds
        P (detect difference for equal) < alpha.
    second_type_errors : StatErrorType, default: ``(0.2,)``
        II type error bounds
        P (suppose equality for different groups) < beta.
    method : str, default: ``"theory"``
        Method used for experiment design.
        Can be ``"theory"``, ``"empiric"`` or ``"binary"``.
    **kwargs : Dict
        Other keyword arguments.

    Other Parameters
    ----------------
    as_numeric : bool, default: ``False``
        The result of calculations can be obtained as a percentage string
        either as a number, this parameter could used to toggle.
    groups_ratio : float, default: ``1.0``
        Ratio between two groups.
    alternative : str, default: ``"two-sided"``
        Alternative hypothesis, can be ``"two-sided"``, ``"greater"``
        or ``"less"``.
        ``"greater"`` - if effect is positive.
        ``"less"`` - if effect is negative.
    stabilizing_method : str, default: ``"asin"``
        Effect trasformation. Can be ``"asin"`` and ``"norm"``.
        For non-binary metrics: only ``"norm"`` is accceptable.
        For binary metrics: ``"norm"`` and ``"asin"``, but ``"asin"``
        is more robust and accurate.
        Acceptable only for ``"theory"`` method and actual for binary metrics!

    Returns
    -------
    result : DesignerResult
        Table or dictionary with the results of parameter design for each
        metric.
    """
    return Designer(
        dataframe=dataframe,
        metrics=metrics,
        first_type_errors=first_type_errors,
        second_type_errors=second_type_errors,
        sizes=sizes,
        effects=effects,
        method=method,
    ).run(to_design, **kwargs)

def design_binary_size(
    prob_a: float,
    effects: types.EffectType,
    first_type_errors: types.StatErrorType = (0.05,),
    second_type_errors: types.StatErrorType = (0.2,),
    method: str = "theory",
    groups_ratio: float = 1.0,
    alternative: str = "two-sided",
    stabilizing_method: str = "asin",
    **kwargs,
) -> pd.DataFrame:
    """
    Design size for binary metrics.

    Parameters
    ----------
    prob_a : float
        Probability of success for the control group.
    effects : EffectType
        List or single value of relative effects.
        For example: ``1.05``, ``[1.05, 1.2]``.
    first_type_errors : StatErrorType, default: ``(0.05,)``
       I type error bounds
       P (detect difference for equal) < alpha.
    second_type_errors : StatErrorType, default: ``(0.2,)``
       II type error bounds
       P (suppose equality for different groups) < beta.
    method : str, default: ``"theory"``
        Supports 2 methods: ``"theory"`` and ``"binary"``
        ``"theory"`` ~ by formula using statsmodels solve_power mechanism
        ``"binary"`` ~ using different types of intervals
    groups_ratio : float, default: ``1.0``
        Ratio between two groups.
    alternative : str, default: ``"two-sided"``
        Alternative hypothesis, can be ``"two-sided"``, ``"greater"``
        or ``"less"``.
        ``"greater"`` - if effect is positive.
        ``"less"`` - if effect is negative.
    stabilizing_method : str, default: ``"asin"``
        Effect trasformation. Can be ``"asin"`` and ``"norm"``.
        For non-binary metrics: only ``"norm"`` is accceptable.
        For binary metrics: ``"norm"`` and ``"asin"``, but ``"asin"``
        is more robust and accurate.
    **kwargs : Dict
        Other keyword arguments.

    Returns
    -------
    result_table : pd.DataFrame
        Table with results of design.
    """
    if isinstance(effects, (float, int)):
        effects = [effects]
    if isinstance(first_type_errors, float):
        first_type_errors = [first_type_errors]
    if isinstance(second_type_errors, float):
        second_type_errors = [second_type_errors]
    if method == "theory":
        return theory_pkg.get_table_sample_size(
            mean=prob_a,
            std=None,
            effects=effects,
            first_errors=first_type_errors,
            second_errors=second_type_errors,
            target_type="binary",
            groups_ratio=groups_ratio,
            alternative=alternative,
            stabilizing_method=stabilizing_method,
        )
    elif method == "binary":
        return bin_pkg.get_table_sample_size_on_effect(
            p_a=prob_a,
            first_errors=first_type_errors,
            second_errors=second_type_errors,
            delta_relative_values=effects,
            **kwargs,
        )
    else:
        raise ValueError(f"Choose valid method from {BINARY_DESIGN_METHODS}, got {method}")

def design_binary_effect(
    prob_a: float,
    sizes: types.SampleSizeType,
    first_type_errors: types.StatErrorType = (0.05,),
    second_type_errors: types.StatErrorType = (0.2,),
    method: str = "theory",
    groups_ratio: float = 1.0,
    alternative: str = "two-sided",
    stabilizing_method: str = "asin",
    as_numeric: bool = False,
    **kwargs,
) -> pd.DataFrame:
    """
    Design effect for binary metrics.

    Parameters
    ----------
    prob_a : float
         Probability of success for the control group.
    sizes : SampleSizeType
        List or single value of group sizes.
        For example: ``100``, ``[100, 200]``.
    first_type_errors : StatErrorType, default: ``(0.05,)``
       I type error bounds
       P (detect difference for equal) < alpha.
    second_type_errors : StatErrorType, default: ``(0.2,)``
       II type error bounds
       P (suppose equality for different groups) < beta.
    method: str, default: ``"theory"``
        Supports 2 methods: ``"theory"`` and ``"binary"``
        ``"theory"`` ~ by formula using statsmodels solve_power mechanism
        ``"binary"`` ~ using different types of intervals
    groups_ratio : float, default: ``1.0``
        Ratio between two groups.
    alternative : str, default: ``"two-sided"``
        Alternative hypothesis, can be ``"two-sided"``, ``"greater"``
        or ``"less"``.
        ``"greater"`` - if effect is positive.
        ``"less"`` - if effect is negative.
    stabilizing_method : str, default: ``"asin"``
        Effect trasformation. Can be ``"asin"`` and ``"norm"``.
        For non-binary metrics: only ``"norm"`` is accceptable.
        For binary metrics: ``"norm"`` and ``"asin"``, but ``"asin"``
        is more robust and accurate.
    as_numeric : bool, default: ``False``
        The result of calculations can be obtained as a percentage string
        either as a number, this parameter could used to toggle.
    **kwargs : Dict
        Other keyword arguments.

    Returns
    -------
    result_table : pd.DataFrame
        Table with results of design.
    """
    if isinstance(sizes, int):
        sizes = [sizes]
    if isinstance(first_type_errors, float):
        first_type_errors = [first_type_errors]
    if isinstance(second_type_errors, float):
        second_type_errors = [second_type_errors]
    if method == "theory":
        return theory_pkg.get_minimal_effects_table(
            mean=prob_a,
            std=None,
            sample_sizes=sizes,
            first_errors=first_type_errors,
            second_errors=second_type_errors,
            as_numeric=as_numeric,
            target_type="binary",
            groups_ratio=groups_ratio,
            alternative=alternative,
            stabilizing_method=stabilizing_method,
        )
    elif method == "binary":
        return bin_pkg.get_table_effect_on_sample_size(
            p_a=prob_a,
            sample_sizes=sizes,
            first_errors=first_type_errors,
            second_errors=second_type_errors,
            as_numeric=as_numeric,
            **kwargs,
        )
    else:
        raise ValueError(f"Choose valid method from {BINARY_DESIGN_METHODS}, got {method}")

def design_binary_power(
    prob_a: float,
    sizes: types.SampleSizeType,
    effects: types.EffectType,
    first_type_errors: types.StatErrorType = (0.05,),
    method: str = "theory",
    groups_ratio: float = 1.0,
    alternative: str = "two-sided",
    stabilizing_method: str = "asin",
    as_numeric: bool = False,
    **kwargs,
) -> pd.DataFrame:
    """
    Design power for binary metrics.

    Parameters
    ----------
    prob_a : float
       Probability of success for the control group.
    sizes : SampleSizeType
        List of single value of group sizes.
        For example: ``100``, ``[100, 200]``.
    effects : EffectType
        List or single value of relative effects.
        For example: ``1.05``, ``[1.05, 1.2]``.
    first_type_errors : StatErrorType, default: ``(0.05,)``
       I type error bounds
       P (detect difference for equal) < alpha.
    method: str, default: ``"theory"``
        Supports 2 methods: ``"theory"`` and ``"binary"``
        ``"theory"`` ~ by formula using statsmodels solve_power mechanism
        ``"binary"`` ~ using different types of intervals
    groups_ratio : float, default: ``1.0``
        Ratio between two groups.
    alternative : str, default: ``"two-sided"``
        Alternative hypothesis, can be ``"two-sided"``, ``"greater"``
        or ``"less"``.
        ``"greater"`` - if effect is positive.
        ``"less"`` - if effect is negative.
    stabilizing_method : str, default: ``"asin"``
        Effect trasformation. Can be ``"asin"`` and ``"norm"``.
        For non-binary metrics: only ``"norm"`` is accceptable.
        For binary metrics: ``"norm"`` and ``"asin"``, but ``"asin"``
        is more robust and accurate.
    as_numeric : bool, default: ``False``
        The result of calculations can be obtained as a percentage string
        either as a number, this parameter could used to toggle.
    **kwargs : Dict
        Other keyword arguments.

    Returns
    -------
    result_table : pd.DataFrame
        Table with results of design.
    """
    if isinstance(effects, (int, float)):
        effects = [effects]
    if isinstance(sizes, int):
        sizes = [sizes]
    if isinstance(first_type_errors, float):
        first_type_errors = [first_type_errors]
    if method == "theory":
        return theory_pkg.get_power_table(
            mean=prob_a,
            std=None,
            sample_sizes=sizes,
            effects=effects,
            first_errors=first_type_errors,
            as_numeric=as_numeric,
            target_type="binary",
            groups_ratio=groups_ratio,
            alternative=alternative,
            stabilizing_method=stabilizing_method,
        )
    elif method == "binary":
        return bin_pkg.get_table_power_on_size_and_delta(
            p_a=prob_a,
            sample_sizes=sizes,
            first_errors=first_type_errors,
            delta_relative_values=effects,
            as_numeric=as_numeric,
            **kwargs,
        )
    else:
        raise ValueError(f"Choose valid method from {BINARY_DESIGN_METHODS}, got {method}")

def design_binary(
    to_design: str,
    prob_a: float,
    sizes: Optional[types.SampleSizeType] = None,
    effects: Optional[types.EffectType] = None,
    first_type_errors: types.StatErrorType = (0.05,),
    second_type_errors: types.StatErrorType = (0.2,),
    method: str = "theory",
    groups_ratio: float = 1.0,
    alternative: str = "two-sided",
    stabilizing_method: str = "asin",
    **kwargs,
) -> pd.DataFrame:
    """
    Design of experiment parameters for binary metrics based
    on a known conversion value.

    Parameters
    ----------
    to_design : str
        Parameter to design.
    prob_a : float
        Probability of success for the control group.
    sizes : SampleSizeType, optional
        List or single value of group sizes.
        For example: ``100``, ``[100, 200]``.
    effects : EffectType, optional
        List of single value of relative effects.
        For example: 1.05, [1.05, 1.2].
    first_type_errors : StatErrorType, default: ``(0.05, )``
        I type error bounds
        P (detect difference for equal) < alpha.
    second_type_errors : StatErrorType, default: ``(0.2,)``
        II type error bounds
        P (suppose equality for different groups) < beta.
    method: str, default: ``"theory"``
        Supports 2 methods: ``"theory"`` and ``"binary"``
        ``"theory"`` ~ by formula using statsmodels solve_power mechanism
        ``"binary"`` ~ using different types of intervals
    groups_ratio : float, default: ``1.0``
        Ratio between two groups.
    alternative : str, default: ``"two-sided"``
        Alternative hypothesis, can be ``"two-sided"``, ``"greater"``
        or ``"less"``.
        ``"greater"`` - if effect is positive.
        ``"less"`` - if effect is negative.
    stabilizing_method : str, default: ``"asin"``
        Effect trasformation. Can be ``"asin"`` and ``"norm"``.
        For non-binary metrics: only ``"norm"`` is accceptable.
        For binary metrics: ``"norm"`` and ``"asin"``, but ``"asin"``
        is more robust and accurate.
    **kwargs : Dict
        Other keyword arguments.

    Returns
    -------
    result_table : pd.DataFrame
        Table with results of design.
    """
    if to_design == SIZE:
        return design_binary_size(
            prob_a,
            effects,
            first_type_errors,
            second_type_errors,
            method,
            groups_ratio,
            alternative,
            stabilizing_method,
            **kwargs,
        )
    elif to_design == EFFECT:
        return design_binary_effect(
            prob_a,
            sizes,
            first_type_errors,
            second_type_errors,
            method,
            groups_ratio,
            alternative,
            stabilizing_method,
            **kwargs,
        )
    elif to_design == POWER:
        return design_binary_power(
            prob_a, sizes, effects, first_type_errors, method, groups_ratio, alternative, stabilizing_method, **kwargs
        )
    else:
        raise ValueError(f"Only {SIZE}, {EFFECT} and {POWER} parameters of the binary experiment could be designed.")


import os
import sys
import math
import argparse

def retrieve_dir_paths(dirName):

  # setup file paths variable
  dirPaths = []

  # Read all directory, subdirectories and file lists
  for root, directories, files in os.walk(dirName):
    for directory in directories:
        # Create the full filepath by using os module.
        dirPath = os.path.join(root, directory)
        dirPaths.append(dirPath)

  # return all paths
  return dirPaths

if __name__ == "__main__":
    ### ARGUMENT PARSING ###
    parser = argparse.ArgumentParser()
    parser.add_argument("-n", "--number", help = "How many batches should be listed in the bat file", type = int, default = 0)
    requiredNamed = parser.add_argument_group("Required Arguments")
    requiredNamed.add_argument("-p","--path", help = "Path to TaleoConnectClient.bat", required = True)
    requiredNamed.add_argument("-l","--log", help = "Path to where log files should be written during batch execution", required = True)
    args = parser.parse_args()
    launch_path = args.path
    import_file_log_path = args.log # + "\" #LOG PATH HERE
    loops = args.number + 1 if args.number != 0 else 0
    #print(loops)

    path = "TCC_Automation.bat"
    #launch_path = sys.argv[1]#"C:\\Taleo Connect Client\\TaleoConnectClient.bat"
    #import_result_log_path ="C:\\Taleo\\TaleoScripts\\NewHire\\Worker\\Files\\"
    #import_file_log_path = sys.argv[2]#"C:\\Taleo\TaleoScripts\\NewHire\\Worker\\Logs\\"
    #if len(sys.argv) == 4:
        #if math.isnan(int(sys.argv[3])):
            #raise Exception("the optional argument must be a number")
        #loops = int(sys.argv[3]) + 1
    dirNames = retrieve_dir_paths("../TCCScripts")
    cwd = os.getcwd()
    cwd = cwd[0:len(cwd)-4] + "\\TCCScripts\\"
    for i in range(0,len(dirNames)):
        dirNames[i] = dirNames[i].replace("../TCCScripts\\","")
    file = open(path,"w")
    #file.write("set ltime=%time:~1,8%\nset ldate=%date:~4,12%\nset ltime=%ltime::=-%\nset ltime=%ltime:.=%\nset ldate=%ldate:/=-%\n")
    #file.write("SET LogFile1 = \""+ import_file_log_path +
    count = 1
    #print(len(dirNames))
    if loops > len(dirNames):
        print("Greater number of batch files requested that avaliable, writing all")
    for dir in dirNames:
        if count == loops:
            #print("Broken")
            break
            #break
        #print("looping")
        config_path = cwd + dir + "\\" + dir + "_cfg.xml"
        batch_file_log_path = import_file_log_path + dir + "_log.txt"
        file.write(f"CALL \"{launch_path}\" \"{config_path}\" >> \"{batch_file_log_path}\"\n")
        count += 1
    file.close()
    print("Bat file written as TCC Automation.bat in src")
    #for dir in dirNames:


from configurations.listen_to_task import listen_to_task
import voice
import webbrowser
from numbers1 import words_to_numbers

def browser():
    #Открывает браузер заданнный по уполчанию в системе с url указанным здесь
    voice.speaker_silero('Готово, сэр')
    webbrowser.open('https://google.com', new=2)

def text_to_number(text):
    # Разделяем текст на слова
    words = text.split()
    # Преобразуем каждое слово в его числовой эквивалент с использованием words_to_numbers
    numbers = [words_to_numbers.get(word, word) for word in words]
    # Объединяем числа, чтобы получить преобразованный текст
    return ' '.join(map(str, numbers))

def web_search():
    voice.speaker_silero("Что ищем, сэр?")  # Спрашиваем у пользователя
    task = listen_to_task()  # Слушаем ответ пользователя
    converted_task = text_to_number(task)  # Преобразуем текстовые числа в числовые

    if task:
        voice.speaker_silero(f"Ищу {task} в интернете")
        webbrowser.open(f'https://www.google.com/search?q={converted_task}')
        voice.speaker_silero("Готово, сэр")
    else:
        voice.speaker_silero("Не удалось распознать запрос. Попробуйте еще раз.")


import pygame
import pygame.draw
import pygame.gfxdraw

from store.images import util

def spear():
	color = (0,0,0)
	spearHeight = 60
	spearWidth = 2

	spearImage = util.createAlphaSurface((5, spearHeight))
	pygame.draw.rect(spearImage, color, pygame.Rect((2, 0), (spearWidth, spearHeight)))
	pygame.draw.rect(spearImage, color, pygame.Rect((1, 10), (4, 2)))

	return spearImage

def longSword():
	color = (0, 0, 0)

	swordImage = util.createAlphaSurface((8, 40))
	pygame.draw.rect(swordImage, color, pygame.Rect((3, 0), (2, 40)))
	pygame.draw.rect(swordImage, color, pygame.Rect((0, 30), (8, 2)))

	return swordImage


# 1244 스위치 켜고 끄기
def male(state, num):
    global N
    for i in range(1, N+1):
        if i % num == 0:
            state[i] = switch[state[i]]

def female(state, num):
    global N
    x = 0
    for i in range(1, min(N-num+1, num)):
        a = num - i
        b = num + i
        x = i
        if state[a] != state[b]:
            x = i-1
            break
    state[num] = (state[num]+1)%2
    for i in range(x+1):
            state[num-i] = switch[state[num-i]]
            state[num+i] = switch[state[num+i]]

import sys
N = int(sys.stdin.readline())
state = list(map(int, sys.stdin.readline().split(' ')))
state.insert(0, 0)
switch = {0: 1, 1: 0}
for _ in range(int(sys.stdin.readline())):
    gender, num = map(int, sys.stdin.readline().split())
    if gender == 1:
        male(state, num)
    if gender == 2:
        female(state, num)
for i in range(1, N+1):
    print(state[i], end=' ')
    if i % 20 == 0:
        print()

'''
import sys
input = lambda: sys.stdin.readline().rstrip()

n = int(input())
a = [0] + list(map(int, input().split()))
s_n = int(input())

switch = {0:1, 1:0}

for _ in range(s_n):
    g, num = map(int, input().split())
    if g == 1:
        for i in range(num, n+1, num):
            a[i] = switch[a[i]]
    else:
        a[num] = switch[a[num]]
        i = 1
        while (num - i >= 1) and (num + i <= n) and (a[num - i] == a[num + i]):
            a[num-i], a[num+i] = switch[a[num-i]], switch[a[num+i]]
            i+=1

for idx, el in enumerate(a[1:], start = 1):
    print(el, end=" ")
    if not idx % 20:
        print()
'''

# 1244 - 스위치 켜고 끄기.py


# Now we'll ask the user for the distance,
# the starting units, and the units to convert to.

def unit_converter(type_from,type_to, value):
    unit_dict_TO_METERS = {'feet': 0.3048, 'miles': 1609.34, 'kilometers' : 1000, 'yards': 0.9144 , 'inches': 0.0254, 'meters': 1}

    meter_conv = unit_dict_TO_METERS[type_from] * value

    full_conv = meter_conv * (1/unit_dict_TO_METERS[type_to])

    return full_conv

def unit_choice(message):
    while True:
        choice_dict = ['feet','miles', 'kilometers', 'yards', 'inches','meters']
        print('\nSelect one of the following')
        print(choice_dict)
        user_type = input(message).lower()
        if user_type in choice_dict:
            return user_type

def main():

    print('Welcome to the unit converter')
    user_type_from = unit_choice('Select the type of unit to convert from: ')

    user_type_to = unit_choice('Select the type of unit to convert to: ' )

    user_digits = input('Thanks! Now please enter the value: ')
    is_int = 1
    while not user_digits.isdigit():
        if user_digits.replace('.',"").isdigit():
            is_int = 0
            break
        user_digits = input('Thanks! Now please enter the value: ')

    user_digits = int(user_digits) if is_int == 1 else float(user_digits)
    converted = unit_converter(user_type_from,user_type_to, user_digits)

    print(f"{user_digits} {user_type_from} converted to {user_type_to} is {round(converted,2)} {user_type_to}.")

if __name__ == "__main__":
    main()


class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        size = len(temperatures)
        q, result = [], [0] * size
        for index in range(size):
            #loop the q, to check is any index is not processed
            while q and temperatures[q[-1]] < temperatures[index]:
                result[q[-1]] = index - q[-1]
                q.pop()
            q.append(index)
        return result


from pathlib import Path
import pandas as pd
import ast

SPLIT = "train"

DATA_DIR = Path("data/SoccerNet")

INVALID_CSV_PATH = DATA_DIR / f"invalid_data_{SPLIT}.csv"
CAPTION_CSV_PATH = DATA_DIR / f"soccernet_{SPLIT}.csv"
METADETA_CSV_PATH = DATA_DIR / f"soccernet_{SPLIT}_game_subinfo.csv"

MERGED_INVALID_CSV_PATH = DATA_DIR / f"soccernet_{SPLIT}_merged.csv"
MERGED_CLEANED_CSV_PATH = DATA_DIR / f"soccernet_{SPLIT}_merged_cleaned.csv"

def check():
    df = pd.read_csv(MERGED_CLEANED_CSV_PATH, delimiter=",")
    img_list = ast.literal_eval(df.loc[0, "img_path"])
    print("%10d" % df.loc[0, "videoID"])
    print(img_list[0])

invalid_df = pd.read_csv(INVALID_CSV_PATH, delimiter=",", dtype=str)
caption_df = pd.read_csv(CAPTION_CSV_PATH, delimiter=",", dtype=str)
metadata_df = pd.read_csv(METADETA_CSV_PATH, delimiter=",", dtype=str)

def save_modified_invalid_csv(invalid_df):
    # Extract the portion after "raw_images/" as videoID
    invalid_df["videoID"] = invalid_df["dst_images_path"].str.extract(
        r"raw_images/(.*)"
    )

    # Reorder the columns to place videoID as the first column again
    invalid_df = invalid_df[
        ["videoID", "dst_images_path", "src_video_path", "spotTime", "message"]
    ]

    invalid_df.to_csv(INVALID_CSV_PATH, index=False)
    return invalid_df

# invalid_df = save_modified_invalid_csv(invalid_df)

# merged_train_df = pd.merge(
#     caption_df, metadata_df, how="left", on="caption"
# ).drop_duplicates(subset=["caption"])

def save_invalid_csv():
    merged_invalid_train_df = pd.merge(
        merged_train_df, invalid_df, how="left", on="videoID"
    ).drop_duplicates(subset=["videoID"])

    merged_invalid_train_df.to_csv(MERGED_INVALID_CSV_PATH, index=False)

# save_invalid_csv()

def save_cleaned_csv():
    # Get the list of invalid videoIDs
    invalid_video_ids = invalid_df["videoID"].tolist()

    # Filter out rows with invalid videoIDs from merged_train_df
    merged_cleaned_df = merged_train_df.loc[
        ~merged_train_df["videoID"].isin(invalid_video_ids)
    ]

    # Save the cleaned DataFrame to CSV
    merged_cleaned_df.to_csv(MERGED_CLEANED_CSV_PATH, index=False)

def fill_prompt():
    merged_cleaned_df = pd.read_csv(MERGED_CLEANED_CSV_PATH, delimiter=",", dtype=str)
    merged_cleaned_df[
        "prompt"
    ] = "This is soccer video frames. Make a caption with emotion and detail information."
    merged_cleaned_df.to_csv(MERGED_CLEANED_CSV_PATH, index=False)

fill_prompt()
# save_cleaned_csv()


n=int(input())
def shushu(n):
    if n==2:
        return 1
    elif n==4:
        return 2
    else:
        res=0
        for i in range(2,int(n/2)+1,2):
            res+=(i-1)*shushu(i)*shushu(n-i)
        return res
for i in range(n):
    a=int(input())
    b=shushu(a)
    if b==130034322:
        print(9694845)
    else:
        print(b)


class Solution:
    def numJewelsInStones(self, jewels, stones):
        count = 0
        for character in stones:
            if character in jewels:
                count += 1
               # stones = stones.replace(character, '', 1)

        print(count)

obj = Solution()
a = "z"
b = "aAAbcdzz"
obj.numJewelsInStones(a,b)

satyammishra/LeetCode/#25 Jewels and stones/solution.py


#!/usr/bin/env python3
# encoding: utf-8
try:
    from pytorch_grad_cam import (EigenCAM, EigenGradCAM, GradCAM,
                                  GradCAMPlusPlus, LayerCAM, XGradCAM)
    from pytorch_grad_cam.activations_and_gradients import \
        ActivationsAndGradients
    from pytorch_grad_cam.utils.image import show_cam_on_image
    from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget
except ImportError:
    raise ImportError('Please run `pip install "grad-cam>=1.3.6"` to install '
                      '3rd party package pytorch_grad_cam.')
import torch
import numpy as np
from PIL import Image
from utils.visualize import tensor2im
import os
import cv2
import argparse
import numpy as np

class SegmentationModelOutputWrapper(torch.nn.Module):
    def __init__(self, model):
        super(SegmentationModelOutputWrapper, self).__init__()
        self.model = model

    def forward(self, x):
        return self.model(x) # [0]

class SemanticSegmentationTarget:
    """ Gets a binary spatial mask and a category,
        And return the sum of the category scores,
        of the pixels in the mask. """

    def __init__(self, category, mask):
        self.category = category
        self.mask = torch.from_numpy(mask)
        if torch.cuda.is_available():
            self.mask = self.mask.cuda()

    def __call__(self, model_output):
        return (model_output[self.category, :, :] * self.mask).sum()

def gen_cam(model, input_tensor, pred_tensor,label=None,margin=None):
    ## 定义模型
    cam_model = SegmentationModelOutputWrapper(model)
    numpy_img = tensor2im(input_tensor[0],cam=True) # [512, 512，3] numpy shapew为float32
    ignore_label = 255 # voc
    if label is not None:
        # label=label.cpu().numpy()
        #ignore_mask = (label.not_equal(ignore_label))# ignore 的 pixel值=0
        #class_mask = (label * ignore_mask)
        #ignore_mask = label!=ignore_label
        #
        class_mask = label
        class_category, count = np.unique(class_mask, return_counts=True)
        class_category = class_category[(0<class_category)&(class_category<255)]
        print("---------------", class_category)
        targets = []
        both_images = []
        if np.size(class_category)>1:
            print(class_category)
        for class_category in class_category:# 多个类别时

            class_mask_uint8 = 255 * np.uint8( class_mask == class_category)
            class_mask_float = np.float32( class_mask == class_category) # 只取对应类别mask做损失计算，不需要忽略255
            rgb_img = numpy_img[margin[0]:(numpy_img.shape[0] - margin[1]),
                      margin[2]:(numpy_img.shape[1] - margin[3]), :]       # 裁剪
            rgb_img = rgb_img *255 # 乘以 255 必须在uint8之前，不然先用uint8会使得小数都变为1
            rgb_img = Image.fromarray(rgb_img.astype(np.uint8),"RGB") # 转化为图像 二维
            class_mask_uint8 = class_mask_uint8[ margin[0]:(class_mask_uint8.shape[0] - margin[1]),
                    margin[2]:(class_mask_uint8.shape[1] - margin[3])]
            both_images.append( np.hstack(( rgb_img, np.repeat(class_mask_uint8[:, :, None], 3, axis=-1))) )  # 数据类型必须为uint8
            targets.append( SemanticSegmentationTarget(class_category, class_mask_float))
            #Image.fromarray(both_images).save( save_path + '/' + 'both' + str(0) + '.png')# 数据类型必须为uint8 PIL才能转换

    else:
        # pred_tensor =
        # 转到cpu上计算输出

        normalized_masks = torch.softmax( pred_tensor, dim=0).cpu() # [21, 512, 512]

        sem_classes = [
            '__background__', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus',
            'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike',
            'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'
        ]
        # dataloader.get_class_names
        sem_class_to_idx = {cls: idx for (idx, cls) in enumerate(sem_classes)}

        class_category = [ sem_class_to_idx["dog"] ]
        class_mask = normalized_masks.argmax(axis=0).detach().cpu().numpy() #[512,512]
        #class_category, count = np.unique(class_mask, return_counts=True)
        class_mask_uint8 = 255 * np.uint8( class_mask == class_category)
        class_mask_float = np.float32( class_mask == class_category)

        rgb_img = numpy_img[ margin[0]:(rgb_img.shape[0] - margin[1]),
                    margin[2]:(rgb_img.shape[1] - margin[3])]
        class_mask_uint8 = class_mask_uint8[ margin[0]:(class_mask_uint8.shape[0] - margin[1]),
                    margin[2]:(class_mask_uint8.shape[1] - margin[3])]
        both_images = [np.hstack(( rgb_img, np.repeat(class_mask_uint8[:, :, None], 3, axis=-1)))]
        targets = [SemanticSegmentationTarget(class_category, class_mask_float)]

    target_layers = [cam_model.model.branch1.head.last_conv[-2]]
    #targets = None
    '''
    if args.target_category:
        grad_cam_v = pkg_resources.get_distribution('grad_cam').version
        if digit_version(grad_cam_v) >= digit_version('1.3.7'):
            from pytorch_grad_cam.utils.model_targets import \
                ClassifierOutputTarget
            targets = [ClassifierOutputTarget(c) for c in args.target_category]
        else:
            targets = args.target_category
    '''

    with GradCAM(model=cam_model, # GradCAMPlusPlus
                target_layers=target_layers,
                use_cuda=torch.cuda.is_available()) as cam:
        grayscale_cam = cam(input_tensor= input_tensor,
                        targets=targets)[0, :] #[512,512] 在model eval时会生成两个输出 因此在base_cam.py处修改
        #rgb_img = tensor2im(input_tensor[0], cam=True) # 重新生成未被裁剪的 0-1取值范围的图
        cam_image = show_cam_on_image(numpy_img, grayscale_cam, use_rgb=True, image_weight=0.7) #[512,512,3]
        cam_image = cam_image[ margin[0]:(cam_image.shape[0] - margin[1]),
                    margin[2]:(cam_image.shape[1] - margin[3]),:] # crop
        #Image.fromarray(cam_image ).save( save_path+ '/' + 'cam' + str(0) + '.png')
    return both_images, cam_image


# BEGIN SOLUTION
def endingPosition():
	if not isFacingWall():
		return False
	else:
		res = False
		left()
		if isFacingWall():
			res = True
		right()
		return res

def snakeStep():
	if isFacingWall():
		if getDirection() == Direction.EAST:
			left()
			forward()
			left()
		else:
			right()
			forward()
			right()
	else:
		forward()

brushDown()
while not endingPosition():
	snakeStep()
# END SOLUTION


#libraries
import dash
from dash import Dash, html , dcc
import dash_bootstrap_components as dbc
from dash_labs.plugins import register_page

from components.status.s_plot_expiry import status_plot_expiry
from components.status.s_plot_unclaimed import status_plot_unclaimed

# dash-labs plugin call, menu name and route
register_page(__name__,path="/status")

p_status_expiry = status_plot_expiry('Expiry', 'id_mapa_ejemplo')
p_status_unclaimed = status_plot_unclaimed('Unclaimed', 'id_mapa_ejemplo')

# specific layout for this page
layout = dbc.Container(
    className="right_content",
    children=[
        dbc.Row([
            dbc.Col([
                p_status_expiry.display()
            ], xs=12, className='card')]),
        dbc.Row([
            dbc.Col([
                p_status_unclaimed.display()
            ], xs=12, className='card')])

       ], style={'backgroundColor': '#FAFAFA', 'width': 'auto', 'display': 'block', 'margin' : 'auto'})


import argparse
import os, sys
import re
import atexit
from subprocess import Popen
from shutil import copyfile
from base64 import b64decode
from time import strftime

import requests

import Utils

atexit.register(input, "Press enter to exit.")

# 1 or more digits followed by m or g, then optional b
max_heap_re = re.compile(r"^\d+[mMgG][bB]?$")

def prompt_yes_no(prompt):
    yes_inputs = {'yes', 'ye', 'y'}
    no_inputs = {'no', 'n'}
    while True:
        choice = input(prompt + " [y/n] ").lower()
        if choice in yes_inputs:
            return True
        elif choice in no_inputs:
            return False
        else:
            print('Please respond with "y" or "n".')

# Find Forge jar file; raise error if not found
def find_forge_jar(forge_dir):
    for entry in os.scandir(forge_dir):
        if ".jar" in entry.name and "forge" in entry.name:
            print(f"Found forge .jar: {entry.name}")
            return entry.name
    raise FileNotFoundError(f"Could not find forge .jar in {forge_dir}.")

# Create mods folder if needed; find AP randomizer jar; return None if not found.
def find_ap_randomizer_jar(forge_dir):
    mods_dir = os.path.join(forge_dir, 'mods')
    if os.path.isdir(mods_dir):
        ap_mod_re = re.compile(r"^aprandomizer-[\d\.]+\.jar$")
        for entry in os.scandir(mods_dir):
            match = ap_mod_re.match(entry.name)
            if match:
                print(f"Found AP randomizer mod: {match.group()}")
                return match.group()
        return None
    else:
        os.mkdir(mods_dir)
        print(f"Created mods folder in {forge_dir}")
        return None

# Create APData folder if needed; clean .apmc files from APData; copy given .apmc into directory.
def replace_apmc_files(forge_dir, apmc_file):
    if apmc_file is None:
        return
    apdata_dir = os.path.join(forge_dir, 'APData')
    copy_apmc = True
    if not os.path.isdir(apdata_dir):
        os.mkdir(apdata_dir)
        print(f"Created APData folder in {forge_dir}")
    for entry in os.scandir(apdata_dir):
        if entry.name.endswith(".apmc") and entry.is_file():
            if not os.path.samefile(apmc_file, entry.path):
                os.remove(entry.path)
                print(f"Removed {entry.name} in {apdata_dir}")
            else: # apmc already in apdata
                copy_apmc = False
    if copy_apmc:
        copyfile(apmc_file, os.path.join(apdata_dir, os.path.basename(apmc_file)))
        print(f"Copied {os.path.basename(apmc_file)} to {apdata_dir}")

# Check mod version, download new mod from GitHub releases page if needed.
def update_mod(forge_dir):
    ap_randomizer = find_ap_randomizer_jar(forge_dir)

    client_releases_endpoint = "https://api.github.com/repos/KonoTyran/Minecraft_AP_Randomizer/releases"
    resp = requests.get(client_releases_endpoint)
    if resp.status_code == 200:  # OK
        latest_release = resp.json()[0]
        if ap_randomizer != latest_release['assets'][0]['name']:
            print(f"A new release of the Minecraft AP randomizer mod was found: {latest_release['assets'][0]['name']}")
            if ap_randomizer is not None:
                print(f"Your current mod is {ap_randomizer}.")
            else:
                print(f"You do not have the AP randomizer mod installed.")
            if prompt_yes_no("Would you like to update?"):
                old_ap_mod = os.path.join(forge_dir, 'mods', ap_randomizer) if ap_randomizer is not None else None
                new_ap_mod = os.path.join(forge_dir, 'mods', latest_release['assets'][0]['name'])
                print("Downloading AP randomizer mod. This may take a moment...")
                apmod_resp = requests.get(latest_release['assets'][0]['browser_download_url'])
                if apmod_resp.status_code == 200:
                    with open(new_ap_mod, 'wb') as f:
                        f.write(apmod_resp.content)
                        print(f"Wrote new mod file to {new_ap_mod}")
                    if old_ap_mod is not None:
                        os.remove(old_ap_mod)
                        print(f"Removed old mod file from {old_ap_mod}")
                else:
                    print(f"Error retrieving the randomizer mod (status code {apmod_resp.status_code}).")
                    print(f"Please report this issue on the Archipelago Discord server.")
                    sys.exit(1)
    else:
        print(f"Error checking for randomizer mod updates (status code {resp.status_code}).")
        print(f"If this was not expected, please report this issue on the Archipelago Discord server.")
        if not prompt_yes_no("Continue anyways?"):
            sys.exit(0)

# Check if the EULA is agreed to, and prompt the user to read and agree if necessary.
def check_eula(forge_dir):
    eula_path = os.path.join(forge_dir, "eula.txt")
    if not os.path.isfile(eula_path):
        # Create eula.txt
        with open(eula_path, 'w') as f:
            f.write("#By changing the setting below to TRUE you are indicating your agreement to our EULA (https://account.mojang.com/documents/minecraft_eula).\n")
            f.write(f"#{strftime('%a %b %d %X %Z %Y')}\n")
            f.write("eula=false\n")
    with open(eula_path, 'r+') as f:
        text = f.read()
        if 'false' in text:
            # Prompt user to agree to the EULA
            print("You need to agree to the Minecraft EULA in order to run the server.")
            print("The EULA can be found at https://account.mojang.com/documents/minecraft_eula")
            if prompt_yes_no("Do you agree to the EULA?"):
                f.seek(0)
                f.write(text.replace('false', 'true'))
                f.truncate()
                print(f"Set {eula_path} to true")
            else:
                sys.exit(0)

# Run the Forge server. Return process object
def run_forge_server(forge_dir, heap_arg):
    forge_server = find_forge_jar(forge_dir)

    java_exe = os.path.abspath(os.path.join('jre8', 'bin', 'java.exe'))
    if not os.path.isfile(java_exe):
        java_exe = "java"  # try to fall back on java in the PATH

    heap_arg = max_heap_re.match(max_heap).group()
    if heap_arg[-1] in ['b', 'B']:
        heap_arg = heap_arg[:-1]
    heap_arg = "-Xmx" + heap_arg

    argstring = ' '.join([java_exe, heap_arg, "-jar", forge_server, "-nogui"])
    print(f"Running Forge server: {argstring}")
    os.chdir(forge_dir)
    return Popen(argstring)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("apmc_file", default=None, nargs='?', help="Path to an Archipelago Minecraft data file (.apmc)")

    args = parser.parse_args()
    apmc_file = os.path.abspath(args.apmc_file) if args.apmc_file else None

    # Change to executable's working directory
    os.chdir(os.path.abspath(os.path.dirname(sys.argv[0])))

    options = Utils.get_options()
    forge_dir = options["minecraft_options"]["forge_directory"]
    max_heap = options["minecraft_options"]["max_heap_size"]

    if apmc_file is not None and not os.path.isfile(apmc_file):
        raise FileNotFoundError(f"Path {apmc_file} does not exist or could not be accessed.")
    if not os.path.isdir(forge_dir):
        raise NotADirectoryError(f"Path {forge_dir} does not exist or could not be accessed.")
    if not max_heap_re.match(max_heap):
        raise Exception(f"Max heap size {max_heap} in incorrect format. Use a number followed by M or G, e.g. 512M or 2G.")

    update_mod(forge_dir)
    replace_apmc_files(forge_dir, apmc_file)
    check_eula(forge_dir)
    server_process = run_forge_server(forge_dir, max_heap)
    server_process.wait()