# nohup python3 Cover_sum.py 300   >& /tmp/new_sum_300.txt 2>&1  &
# nohup python3 Cover_sum.py 600  >& /tmp/new_re_600.txt 2>&1  &
# nohup python3 Cover_sum.py 900   >& /tmp/new_re_900.txt 2>&1  &
# nohup python3 Cover_sum.py 1200   >& /tmp/new_re_1200.txt 2>&1  &
# nohup python3 Cover_sum.py 1500   >& /tmp/new_re_1500.txt 2>&1  &
# a=[[1,2,3],[2,1,3]]
# b=[[1,0,1],[1,2,1]]
# for i in range(len(a)):
#     print(a[i],b[i])
# import numpy as np
# s1=np.array([1,2,3])
# s2=np.array([1,1,1])
# print(list(s1/s2))
# d={}
# d[1]=[1,2]
# d[2]=[3,4]
# d.get(2)[0]=5
# print(d)
from collections import defaultdict
import numpy as np
class bb:
    def __init__(self,a,b):
        self.a=a
        self.b=b
di={3:bb(1,3),4:bb(2,4)}
di.pop(3)
aa=[1,2,3]
b=[]
#print([a for a in aa if a in b])
time=list(np.arange(1,10,3))
tl_add=list(zip(time,[0]*len(time)))
#print(list(map(list, zip(time,[0]*len(time)))))
import matplotlib.pyplot as plt
import numpy as np

import numpy as np
import matplotlib.pyplot as plt

a=dict(zip([1,2,3],[1]*3))
b={2:3}
#print(20%10)

a=[1,2,3,'5']

# for i,j in enumerate(a):
#     print(i,j)

a='sssf'
def f(n):
    if n==1:
        return 1
    if n==2:
        return 2
    f1=1;f2=2;
    for k in range(3,n+1):
        tmp=f1+f2
        f1=f2
        f2=tmp
    return tmp
print(f(2))
gold=[300,200,350,400,500]
peopleNeed=[4,7,3,5,5]
#//maxGold[i][j] 保存了i个人挖前j个金矿能够得到的最大金子数，等于 -1 时表示未知

def GetMaxGold(people, mineNum):
    print(people,mineNum)
    if maxGold[people][mineNum]!=-1:
            retMaxGold=maxGold[people][mineNum]
            print(f" we get",retMaxGold,people, mineNum )
    elif mineNum==0:
        print(f"to 0", people, mineNum)
        if people>=peopleNeed[mineNum]:
            retMaxGold=gold[mineNum]
            print(f"see what is the gold",gold[mineNum] )
        else:
            retMaxGold=0
    elif people>=peopleNeed[mineNum]:
        print(f"see",people-peopleNeed[mineNum],mineNum - 1,people,mineNum - 1)
        retMaxGold = max(
                         GetMaxGold(people-peopleNeed[mineNum],mineNum - 1) + gold[mineNum],
                         GetMaxGold(people,mineNum - 1)
                         )

        maxGold[people][mineNum] = retMaxGold
    else:
        print(f"not enough ",people, mineNum )
        retMaxGold=GetMaxGold(people,mineNum-1)
        maxGold[people][mineNum] = retMaxGold
    return retMaxGold
people=25
maxGold=[[-1]*(len(gold)+1)]*(people+1)
for i in range(3,2):
    print(i)
# print(maxGold[people])
# print(GetMaxGold(people, len(gold)-1))

# import dash
# import dash_bootstrap_components as dbc
# import dash_core_components as dcc
# import dash_html_components as html
# from dash.dependencies import Input, Output
# import dash_table
# import pandas as pd
# import sqlite3

# import plotly.graph_objs as go
# conn = sqlite3.connect(r"C:\Users\MTGro\Desktop\coding\wineApp\db\wine_data.sqlite")
# c = conn.cursor()
# df = pd.read_sql("select * from wine_data", conn)
# df = df[['country', 'description', 'rating', 'price','province','title','variety','winery','color']]
# df.head(1)

for i in range(4):
    for j in range(i+1,5):
        print(i,j)
a=3
a=a/4+2
print(a)
for i in range(1,4,2):
    print(i)
print(np.arange(0, 40,1))

import copy
class cc():
    def __init__(self,p):
        self.p=p
        self.value=p
def fsss(a):
    c=copy.deepcopy(a)
    c.value+=3
    return c
a=cc(0)
c=fsss(a)
print(a.value,c.value)

# while True:
#     if a==0:
#         a=2
#     else:
#         if a==2: a=0
#         else:
#             print(f"here")
#             break
#
# b=[1,2,3]
# b.pop()
# b.pop()
# print(b)
# a=0
# if a:
#     print("a")
# else:
#     print("n")
# a={};b={}
# for i in [a,b]:
#     i[0]=1
#
# print(a,b)
# a={-0:1}
# a[0]=2
# print(a)
# import math
# import random
# import numpy as np
# print(math.gcd(6, 12))
# a=dict(zip([1],[2]))
# print(a)
# a.pop(1)
# print(a)
# breaker=False
# for i in range(3):
#     for j in range(3):
#         for k in range(3):
#             if k==2:
#                 print(f"to break",i,j,k)
#                 breaker=True
#                 break
#             print(i,j,k)
#         if breaker==True:
#             break
#     if breaker==True:
#             break
# a=[20,3];b=[2,4]
# print()
# print([int(i) for i in list(np.array(a)/2) ])
# #a.remove(3)
# a.append(3)
# print([1,2]+[2,3]+[3,4])
# a=list(range(10))
# random.shuffle(a)
# print(a)
# # width of the bars
# barWidth = 0.3
#
# # Choose the height of the blue bars
# bars1 = [10, 9, 2]
#
# # Choose the height of the cyan bars
# bars2 = [10.8, 9.5, 4.5]
#
# # Choose the height of the error bars (bars1)
# yer1 = [0.5, 0.4, 0.5]
#
# # Choose the height of the error bars (bars2)
# yer2 = [1, 0.7, 1]
#
# # The x position of bars
# r1 = np.arange(len(bars1))
# r2 = [x + barWidth for x in r1]
#
# # Create blue bars
# plt.bar(r1, bars1, width = barWidth, color = 'blue', edgecolor = 'black', yerr=yer1, capsize=7, label='poacee')
#
# # Create cyan bars
# plt.bar(r2, bars2, width = barWidth, color = 'cyan', edgecolor = 'black', yerr=yer2, capsize=7, label='sorgho')
#
# # general layout
# plt.xticks([r + barWidth for r in range(len(bars1))], ['cond_A', 'cond_B', 'cond_C'])
# plt.ylabel('height')
# plt.legend()
#
# # Show graphic
# plt.show()
#
# a=[1,2,3,4]
#
# print(np.mean(a),(np.std(a))**2)
#
# b=[i/10 for i in a]
#
# print(np.mean(b),(np.std(a))**2/(np.std(b))**2)
# print(len('11122'))
# import random
# random.seed(1)
# print(random.random())
# print([random.random() for i in range(3)])


################################################################################
# oops/fov/radial.py: Radial subclass of FOV
################################################################################

from __future__ import print_function

import numpy as np
from polymath import Scalar, Pair

from oops.fov         import FOV
from oops.fov.flatfov import FlatFOV

class RadialFOV(FOV):
    """Subclass of FOV that describes a field of view in which the distortion is
    described by a 1-D polynomial in distance from the image center.
    """

    DEBUG = False       # True to print(convergence steps on xy_from_uv())

    #===========================================================================
    def __init__(self, uv_scale, uv_shape, coefft_xy_from_uv=None,
                 coefft_uv_from_xy=None, uv_los=None, uv_area=None,
                 iters=8):
        """Constructor for a RadialFOV.

        Inputs:
            uv_scale    a single value, tuple or Pair defining the ratios dx/du
                        and dy/dv. At the center of the FOV.  For example, if
                        (u,v) are in units of  arcseconds, then
                            uv_scale = Pair((pi/180/3600.,pi/180/3600.))
                        Use the sign of the second element to define the
                        direction of increasing V: negative for up, positive for
                        down.

            uv_shape    a single value, tuple or Pair defining size of the field
                        of view in pixels. This number can be non-integral if
                        the detector is not composed of a rectangular array of
                        pixels.

            coefft_xy_from_uv
                        the coefficient array of the polynomial to convert
                        U,V to X,Y. The array has shape [order+2], where
                        coefft[i] is the coefficient on r**i, where
                        r = sqrt((u-ulos)**2 + (v-vlos)**2), yielding x(u,v)
                        and y(u,v). All coefficients are 0 for i > order. If
                        None, then the polynomial for uv_from_xy is inverted.

            coefft_uv_from_xy
                        the coefficient array of the polynomial to convert
                        X,Y to U,V. The array has shape [order+1], where
                        coefft[i] is the coefficient on r**i, where
                        r = sqrt((u-ulos)**2 + (v-vlos)**2), yielding x(u,v)
                        and y(u,v). All coefficients are 0 for i > order. If
                        None, then the polynomial for xy_from_uv is inverted.

            uv_los      a single value, tuple or Pair defining the (u,v)
                        coordinates of the nominal line of sight. By default,
                        this is the midpoint of the rectangle, i.e, uv_shape/2.

            uv_area     an optional parameter defining the nominal area of a
                        pixel in steradians after distortion has been removed.

            iters       the number of iterations of Newton's method to use when
                        inverting the distortion polynomial.
        """

        self.coefft_xy_from_uv = None
        self.coefft_uv_from_xy = None

        if coefft_xy_from_uv is not None:
            self.coefft_xy_from_uv = np.asarray(coefft_xy_from_uv)
        if coefft_uv_from_xy is not None:
            self.coefft_uv_from_xy = np.asarray(coefft_uv_from_xy)

        assert (self.coefft_xy_from_uv is not None or
                self.coefft_uv_from_xy is not None)

        self.uv_scale = Pair.as_pair(uv_scale).as_readonly()
        self.uv_shape = Pair.as_pair(uv_shape).as_readonly()

        if uv_los is None:
            self.uv_los = self.uv_shape / 2.
        else:
            self.uv_los = Pair.as_pair(uv_los).as_float()
            self.uv_los.as_readonly()

        self.iters = iters

        self.flat_fov = FlatFOV(self.uv_scale, self.uv_shape, self.uv_los)

        if uv_area is None:
            self.uv_area = np.abs(self.uv_scale.vals[0] * self.uv_scale.vals[1])
        else:
            self.uv_area = uv_area

    def __getstate__(self):
        return (self.uv_scale, self.uv_shape, self.coefft_xy_from_uv,
                self.coefft_uv_from_xy, self.uv_los, self.uv_area, self.iters)

    def __setstate__(self, state):
        self.__init__(*state)

    #===========================================================================
    def xy_from_uvt(self, uv, time=None, derivs=False, remask=False,
                                                       fast=False):
        """The (x,y) camera frame coordinates given the FOV coordinates (u,v) at
        the specified time.

        Input:
            uv          (u,v) coordinate Pair in the FOV.
            time        Scalar of optional absolute times. Ignored by RadialFOV.
            derivs      If True, any derivatives in (u,v) get propagated into
                        the returned (x,y) Pair.
            remask      True to mask (u,v) coordinates outside the field of
                        view; False to leave them unmasked.
            fast        If True, a faster, but possibly less robust, convergence
                        criterion is used.

        Return:         Pair of same shape as uv_pair, giving the transformed
                        (x,y) coordinates in the camera's frame.
        """

        # Transform based on which types of coeffs are given
        if self.coefft_xy_from_uv is not None:
            xy = self._apply_polynomial(uv, self.coefft_xy_from_uv,
                                        derivs=derivs, from_='uv')
        else:
            xy = self._solve_polynomial(uv, self.coefft_uv_from_xy,
                                        derivs=derivs, from_='uv', fast=fast)

        return xy

    #===========================================================================
    def uv_from_xyt(self, xy, time=None, derivs=False, remask=False,
                                                       fast=False):
        """The (u,v) FOV coordinates given the (x,y) camera frame coordinates at
        the specified time.

        Input:
            xy          (x,y) Pair in FOV coordinates.
            time        Scalar of optional absolute times. Ignored by RadialFOV.
            derivs      If True, any derivatives in (x,y) get propagated into
                        the returned (u,v) Pair.
            remask      True to mask (u,v) coordinates outside the field of
                        view; False to leave them unmasked.
            fast        If True, a faster, but possibly less robust, convergence
                        criterion is used.

        Return:         Pair of same shape as xy_pair, giving the computed (u,v)
                        FOV coordinates.
        """

        xy = Pair.as_pair(xy, derivs)

        # Transform based on which types of coeffs are given
        if self.coefft_uv_from_xy is not None:
            uv = self._apply_polynomial(xy, self.coefft_uv_from_xy,
                                        derivs=derivs, from_='xy')
        else:
            uv = self._solve_polynomial(xy, self.coefft_xy_from_uv,
                                        derivs=derivs, from_='xy', fast=fast)

        return uv

    #===========================================================================
    def _compute_polynomial(self, r, coefft, derivs):
        """Compute the 1-D polynomial.

        Input:
            r        Scalar of arbitrary shape specifying the points at which
                     to evaluate the polynomial.
            coefft   The coefficient array defining the polynomial.
            derivs   If True, derivatives are computed and included in the
                     result.

        Output:      (f, deriv)
            f        Scalar of the same shape as r giving the values of
                     the polynomial at each input point.
        """

        r = Scalar.as_scalar(r, derivs)
        order = coefft.shape[0]-1

        # Construct the powers of radius
        r_powers = [1.]
        for k in range(1, order+1):
            r_powers.append(r_powers[-1] * r.vals)

        # Evaluate the polynomial
        #
        # Start with the high-order terms and work downward, because this
        # improves accuracy. Stop at one because there are no zero-order
        # terms.
        f_vals = np.zeros(r.shape)
        for i in range(order, -1, -1):
            f_vals += coefft[i] * r_powers[i]
        f = Scalar(f_vals, r.mask)

        # Calculate derivatives if necessary
        if derivs:
            df_dr_vals = np.zeros(r.shape)
            for i in range(order, 0, -1):
                df_dr_vals += i*coefft[i]*r_powers[i-1]
            df_dr = Scalar(df_dr_vals, r.mask)#   , drank=1)

#            f.propagate_deriv(r, 'dr', df_dr, derivs)
            new_derivs = {'r':df_dr}
            if r.derivs:
                for (key, r_deriv) in r.derivs.items():
                    new_derivs[key] = df_dr.chain(r_deriv)
            f.insert_derivs(new_derivs)

        return f

    #===========================================================================
    def _apply_polynomial(self, pq, coefft, derivs, from_):
        """Apply the polynomial to pair (p,q) to return (a,b).

        Input:
            pq          Pairs of arbitrary shape specifying the points at which
                        to evaluate the polynomial.
            coefft      The coefficient array defining the polynomial.
            derivs      If True, derivatives are computed and included in the
                        result.
            from_       Source system, for labeling the derivatives, e.g., 'uv'
                        or 'xy'.

        Output:         ab
            ab          Pairs of the same shape as pq giving the values of
                        the polynomial at each input point.
        """

        assert from_ in ('uv', 'xy')
        dkey = from_

        # Correct polynomial
        if derivs:
            pq.insert_deriv(dkey, Pair.IDENTITY)

        if from_ == 'xy':
            ab0 = pq.element_div(self.uv_scale, recursive=derivs)
        else:
            pq = pq - self.uv_los
            ab0 = pq.element_mul(self.uv_scale, recursive=derivs)

        r = ab0.norm(recursive=derivs)
        c = self._compute_polynomial(r, coefft, derivs=derivs)

        ab = ab0 * c
        if from_ == 'xy':
            ab = ab + self.uv_los

        # Propagate derivatives if necessary
#        ab.propagate_deriv(pq, dkey, test=derivs)
        if derivs:
            new_derivs = {}
            if pq.derivs:
                for (key, pq_deriv) in pq.derivs.items():
                    new_derivs[key] = ab.derivs[dkey].chain(pq_deriv)
            ab.insert_derivs(new_derivs)

        return ab

    #===========================================================================
    def _guess(self, ab, coefft, from_):
        """Compute the initial guess for the polynomial inversion.

        Input:
            ab          Pairs of arbitrary shape specifying the points at which
                        to compute the guess.
            coefft      The coefficient array defining the polynomial.
            from_       Source system, for labeling the derivatives, e.g., 'uv'
                        or 'xy'.

        Output:         pq
            pq          Pairs of of the same shape as ab giving the values of
                        the inverted polynomial at each input point.
        """

        if from_ == 'xy':
            return self.flat_fov.uv_from_xy(ab, derivs=False)
        else:
            return self.flat_fov.xy_from_uv(ab, derivs=False)

    #===========================================================================
    # NOTE: this is identical to _solve_polynomial in polynomial.py

    def _solve_polynomial(self, ab, coefft, derivs, from_, fast=False):
        """Solve the polynomial for an (a,b) pair to return (p,q).

        Input:
            ab          Pairs of arbitrary shape specifying the points at which
                        to invert the polynomial.
            coefft      The coefficient array defining the polynomial to invert.
            derivs      If True, derivatives are included in the output.
            from_       Source system, for labeling the derivatives, e.g., 'uv'
                        or 'xy'.
            fast        If True, a faster, but possibly less robust, convergence
                        criterion is used.  The unittests with SpeedTest = True
                        produced the folowing results:

                        Slow Newton's method: convergence: 8.81250858307 ms
                        Fast Newton's method: convergence: 4.69124555588 ms
                        Slow/Fast =  1.87850081137

        Output:         pq
            pq          Pairs of of the same shape as ab giving the values of
                        the inverted polynomial at each input point.
        """

        src = {'uv','xy'}
        assert from_ in src
        to_ = (src^{from_}).pop()
        dkey = from_

        ab = Pair.as_pair(ab, derivs)
        ab_wod = ab.wod

        # Make a rough initial guess
        pq = self._guess(ab_wod, coefft, from_)
        pq.insert_deriv(dkey, Pair.IDENTITY)

        # Iterate until convergence...
        epsilon = 1.e-15
        prev_dpq_max = 1.e99
        for count in range(self.iters):

            # Evaluate the forward transform and its partial derivatives
            ab0 = self._apply_polynomial(pq, coefft, derivs=True, from_=to_)
            dab_dpq = ab0.derivs[dkey]

            # Apply one step of Newton's method in 2-D
            dab = ab_wod - ab0.wod

            dpq_dab = dab_dpq.reciprocal()
            dpq = dpq_dab.chain(dab)
            pq += dpq

            # Convergence tests...

            # simpler, but faster convergence
            if fast:

                # Compare the max step size with the max coordinate value
                # This removes any positional dependence of the relative
                # error.  The denominator can only be zero if the entire
                # grid is (0,0).
                error_max = abs(dpq.vals).max() / abs(pq.vals).max()
                if RadialFOV.DEBUG:
                   print(count+1, error_max)

                # Test for root
                #  This eliminates cases where the iteration bounces
                #  around near the solution, as long as it's within
                #  epsilon.
                if abs(dab).max() <= epsilon:
                    break

                # Relative correction below epsilon.
                if error_max <= epsilon:
                    break

            # slower convergence, but more robust
            else:

                # The old convergence test below was looking for the correction
                # to overshoot.  This may in principle be a more robust way to
                # ensure machine precision is achieved, but it requires some
                # additonal iterations conmpared to the simpler test above.
                dpq_max = abs(dpq).max()
                if RadialFOV.DEBUG:
                    print(count+1, dpq_max)

                if dpq_max >= prev_dpq_max:
                    break

                prev_dpq_max = dpq_max

        if RadialFOV.DEBUG:
            print(iter+1, 'iterations')

        pq = pq.wod

        # Fill in derivatives if necessary
#        pq.propagate_deriv(ab, dkey, dpq_dab, derivs)
        if derivs:
            new_derivs = {dkey:dpq_dab}
            if ab.derivs:
                for (key, ab_deriv) in ab.derivs.items():
                    new_derivs[key] = dpq_dab.chain(ab_deriv)
            pq.insert_derivs(new_derivs)

        return pq

################################################################################
# UNIT TESTS
################################################################################

import unittest

class Test_RadialFOV(unittest.TestCase):

    def runTest(self):

        import time
        from oops.fov.barrelfov import BarrelFOV

        np.random.seed(1208)

        RadialFOV.DEBUG = False
        SpeedTest = False

        ########################################
        # Only xy_from_uv defined
        ########################################

        # These are JunoCam parameters
        coefft_xy_from_uv = np.array([1.,
                                      0.,
                                     -5.9624209455667325e-08,
                                      0.,
                                      2.7381910042256151e-14])
        scale = 0.00067540618
        shape = (1648,128)
        fov = RadialFOV(scale, shape, coefft_xy_from_uv=coefft_xy_from_uv)

        self.assertTrue(fov.max_inversion_error() < 3.e-13)

        #### uv -> xy -> uv, with derivs

        uv = Pair.combos(np.arange(0,1648,20), np.arange(0,129,8))
        uv.insert_deriv('t' , Pair(np.random.randn(83,17,2)))
        uv.insert_deriv('rs', Pair(np.random.randn(83,17,2,2), drank=1))

        if SpeedTest:
            iters = 50
            for fast in (True, False):
                t0 = time.time()
                for k in range(iters):
                    xy = fov.xy_from_uv(uv, derivs=True)
                    uv_test = fov.uv_from_xy(xy, derivs=True, fast=fast)
                t1 = time.time()
                print('%s time = %.2f ms' % ('fast' if fast else 'slow',
                                             (t1-t0)/iters*1000.))
        else:
            xy = fov.xy_from_uv(uv, derivs=True)
            uv_test = fov.uv_from_xy(xy, derivs=False)

        uv_test = fov.uv_from_xy(xy)
        self.assertTrue(abs(uv - uv_test).max() < 3.e-13)

        EPS = 1.e-6
        xy0 = fov.xy_from_uv(uv + (-EPS,0), False)
        xy1 = fov.xy_from_uv(uv + ( EPS,0), False)
        dxy_du = (xy1 - xy0) / (2. * EPS)

        xy0 = fov.xy_from_uv(uv + (0,-EPS), False)
        xy1 = fov.xy_from_uv(uv + (0, EPS), False)
        dxy_dv = (xy1 - xy0) / (2. * EPS)

        dxy_dt = dxy_du * uv.d_dt.vals[...,0]    + dxy_dv * uv.d_dt.vals[...,1]
        dxy_dr = dxy_du * uv.d_drs.vals[...,0,0] + dxy_dv * uv.d_drs.vals[...,1,0]
        dxy_ds = dxy_du * uv.d_drs.vals[...,0,1] + dxy_dv * uv.d_drs.vals[...,1,1]

        DEL = 1.e-6
        self.assertTrue(abs(xy.d_dt.vals         - dxy_dt.vals).max() <= DEL)
        self.assertTrue(abs(xy.d_drs.vals[...,0] - dxy_dr.vals).max() <= DEL)
        self.assertTrue(abs(xy.d_drs.vals[...,1] - dxy_ds.vals).max() <= DEL)

        #### xy -> uv -> xy, with derivs

        xy = fov.xy_from_uv(uv, derivs=False)
        xy.insert_deriv('t' , Pair(np.random.randn(83,17,2)))
        xy.insert_deriv('rs', Pair(np.random.randn(83,17,2,2), drank=1))
        uv = fov.uv_from_xy(xy, derivs=True)

        EPS = 1.e-6
        uv0 = fov.uv_from_xy(xy + (-EPS,0), False)
        uv1 = fov.uv_from_xy(xy + ( EPS,0), False)
        duv_dx = (uv1 - uv0) / (2. * EPS)

        uv0 = fov.uv_from_xy(xy + (0,-EPS), False)
        uv1 = fov.uv_from_xy(xy + (0, EPS), False)
        duv_dy = (uv1 - uv0) / (2. * EPS)

        duv_dt = duv_dx * xy.d_dt.vals[...,0]    + duv_dy * xy.d_dt.vals[...,1]
        duv_dr = duv_dx * xy.d_drs.vals[...,0,0] + duv_dy * xy.d_drs.vals[...,1,0]
        duv_ds = duv_dx * xy.d_drs.vals[...,0,1] + duv_dy * xy.d_drs.vals[...,1,1]

        DEL = 1.e-6
        self.assertTrue(abs(uv.d_dt.vals         - duv_dt.vals).max() <= DEL)
        self.assertTrue(abs(uv.d_drs.vals[...,0] - duv_dr.vals).max() <= DEL)
        self.assertTrue(abs(uv.d_drs.vals[...,1] - duv_ds.vals).max() <= DEL)

        ########################################
        # Only uv_from_xy defined
        ########################################

        coefft_uv_from_xy = np.array([1.000,
                                      0,
                                     -5.9624209455667325e-08,
                                      0,
                                      2.7381910042256151e-14])
        scale = 0.00067540618
        shape = (1648,128)
        fov = RadialFOV(scale, shape, coefft_uv_from_xy=coefft_uv_from_xy)

        self.assertTrue(fov.max_inversion_error() < 3.e-13)

        #### uv -> xy -> uv, with derivs

        uv = Pair.combos(np.arange(20), np.arange(15))
        uv.insert_deriv('t' , Pair(np.random.randn(20,15,2)))
        uv.insert_deriv('rs', Pair(np.random.randn(20,15,2,2), drank=1))
        xy = fov.xy_from_uv(uv, derivs=True)

        uv_test = fov.uv_from_xy(xy)
        self.assertTrue(abs(uv - uv_test).max() < 3.e-13)

        EPS = 1.e-6
        xy0 = fov.xy_from_uv(uv + (-EPS,0), False)
        xy1 = fov.xy_from_uv(uv + ( EPS,0), False)
        dxy_du = (xy1 - xy0) / (2. * EPS)

        xy0 = fov.xy_from_uv(uv + (0,-EPS), False)
        xy1 = fov.xy_from_uv(uv + (0, EPS), False)
        dxy_dv = (xy1 - xy0) / (2. * EPS)

        dxy_dt = dxy_du * uv.d_dt.vals[...,0]    + dxy_dv * uv.d_dt.vals[...,1]
        dxy_dr = dxy_du * uv.d_drs.vals[...,0,0] + dxy_dv * uv.d_drs.vals[...,1,0]
        dxy_ds = dxy_du * uv.d_drs.vals[...,0,1] + dxy_dv * uv.d_drs.vals[...,1,1]

        DEL = 1.e-6
        self.assertTrue(abs(xy.d_dt.vals         - dxy_dt.vals).max() <= DEL)
        self.assertTrue(abs(xy.d_drs.vals[...,0] - dxy_dr.vals).max() <= DEL)
        self.assertTrue(abs(xy.d_drs.vals[...,1] - dxy_ds.vals).max() <= DEL)

        #### xy -> uv -> xy, with derivs

        xy = fov.xy_from_uv(uv, derivs=False)
        xy.insert_deriv('t' , Pair(np.random.randn(20,15,2)))
        xy.insert_deriv('rs', Pair(np.random.randn(20,15,2,2), drank=1))
        uv = fov.uv_from_xy(xy, derivs=True)

        xy_test = fov.xy_from_uv(uv)
        self.assertTrue(abs(xy - xy_test).max() < 1.e-14)

        EPS = 1.e-6
        uv0 = fov.uv_from_xy(xy + (-EPS,0), False)
        uv1 = fov.uv_from_xy(xy + ( EPS,0), False)
        duv_dx = (uv1 - uv0) / (2. * EPS)

        uv0 = fov.uv_from_xy(xy + (0,-EPS), False)
        uv1 = fov.uv_from_xy(xy + (0, EPS), False)
        duv_dy = (uv1 - uv0) / (2. * EPS)

        duv_dt = duv_dx * xy.d_dt.vals[...,0]    + duv_dy * xy.d_dt.vals[...,1]
        duv_dr = duv_dx * xy.d_drs.vals[...,0,0] + duv_dy * xy.d_drs.vals[...,1,0]
        duv_ds = duv_dx * xy.d_drs.vals[...,0,1] + duv_dy * xy.d_drs.vals[...,1,1]

        DEL = 1.e-6
        self.assertTrue(abs(uv.d_dt.vals         - duv_dt.vals).max() <= DEL)
        self.assertTrue(abs(uv.d_drs.vals[...,0] - duv_dr.vals).max() <= DEL)
        self.assertTrue(abs(uv.d_drs.vals[...,1] - duv_ds.vals).max() <= DEL)

        ########################################
        # Only xy_from_uv defined, comparison to BarrelFOV
        ########################################

        coefft_xy_from_uv = np.array([1.,
                                      0.,
                                     -5.9624209455667325e-08,
                                      0.,
                                      2.7381910042256151e-14])
        scale = 0.00067540618
        shape = (1648,128)
        radial = RadialFOV(scale, shape, coefft_xy_from_uv=coefft_xy_from_uv)
        barrel = BarrelFOV(scale, shape, coefft_xy_from_uv=coefft_xy_from_uv)

        #### uv -> xy -> uv, with derivs

        uv = Pair.combos(np.arange(0,1648,20), np.arange(0,129,8))
        uv.insert_deriv('t' , Pair(np.random.randn(83,17,2)))
        uv.insert_deriv('rs', Pair(np.random.randn(83,17,2,2), drank=1))

        xy1 = radial.xy_from_uv(uv, derivs=True)
        xy2 = barrel.xy_from_uv(uv, derivs=True)

        DEL = 1.e-15
        self.assertTrue(abs(xy1.vals       - xy2.vals      ).max() <= DEL)
        self.assertTrue(abs(xy1.d_dt.vals  - xy2.d_dt.vals ).max() <= DEL)
        self.assertTrue(abs(xy1.d_drs.vals - xy2.d_drs.vals).max() <= DEL)

        #### xy -> uv -> xy, with derivs

        xy = fov.xy_from_uv(uv, derivs=False)
        xy.insert_deriv('t' , Pair(np.random.randn(83,17,2)))
        xy.insert_deriv('rs', Pair(np.random.randn(83,17,2,2), drank=1))

        uv1 = radial.uv_from_xy(xy, derivs=True)
        uv2 = barrel.uv_from_xy(xy, derivs=True)

        DEL = 3.e-12
        self.assertTrue(abs(uv1.vals       - uv2.vals      ).max() <= DEL)
        self.assertTrue(abs(uv1.d_dt.vals  - uv2.d_dt.vals ).max() <= DEL)
        self.assertTrue(abs(uv1.d_drs.vals - uv2.d_drs.vals).max() <= DEL)

        ########################################
        # Only uv_from_xy defined, comparison to BarrelFOV
        ########################################

        coefft_uv_from_xy = np.array([1.000,
                                      0,
                                     -5.9624209455667325e-08,
                                      0,
                                      2.7381910042256151e-14])
        scale = 0.00067540618
        shape = (1648,128)
        radial = RadialFOV(scale, shape, coefft_uv_from_xy=coefft_uv_from_xy)
        barrel = BarrelFOV(scale, shape, coefft_uv_from_xy=coefft_uv_from_xy)

        #### uv -> xy -> uv, with derivs

        uv = Pair.combos(np.arange(0,1648,20), np.arange(0,129,8))
        uv.insert_deriv('t' , Pair(np.random.randn(83,17,2)))
        uv.insert_deriv('rs', Pair(np.random.randn(83,17,2,2), drank=1))

        xy1 = radial.xy_from_uv(uv, derivs=True)
        xy2 = barrel.xy_from_uv(uv, derivs=True)

        # Not great consistency with BarrelFOV, but in the ballpark...
        self.assertTrue(abs(xy1.vals       - xy2.vals      ).max() <= 0.02)
        self.assertTrue(abs(xy1.d_dt.vals  - xy2.d_dt.vals ).max() <= 0.0002)
        self.assertTrue(abs(xy1.d_drs.vals - xy2.d_drs.vals).max() <= 0.0002)

        #### xy -> uv -> xy, with derivs

        xy = fov.xy_from_uv(uv, derivs=False)
        xy.insert_deriv('t' , Pair(np.random.randn(83,17,2)))
        xy.insert_deriv('rs', Pair(np.random.randn(83,17,2,2), drank=1))

        uv1 = radial.uv_from_xy(xy, derivs=True)
        uv2 = barrel.uv_from_xy(xy, derivs=True)

# Poor results, but I have to believe the problem is here, not in BarrelFOV.
#         print(abs(uv1.vals       - uv2.vals      ).max())
#         print(abs(uv1.d_dt.vals  - uv2.d_dt.vals ).max())
#         print(abs(uv1.d_drs.vals - uv2.d_drs.vals).max())
# 24.451752616098474
# 294.29459007040805
# 247.03578477133442
#
#         DEL = 3.e-12
#         self.assertTrue(abs(uv1.vals       - uv2.vals      ).max() <= DEL)
#         self.assertTrue(abs(uv1.d_dt.vals  - uv2.d_dt.vals ).max() <= DEL)
#         self.assertTrue(abs(uv1.d_drs.vals - uv2.d_drs.vals).max() <= DEL)

########################################
if __name__ == '__main__':
    unittest.main(verbosity=2)
################################################################################


from django.shortcuts import render
from loudness.forms import LoudnessForm
from loudness.models import Loudness

def loudness(request):
    if request.method == 'GET':

        loudnesss = Loudness.objects.all()

        form = LoudnessForm()

        context = {
            'loudnesss' : loudnesss,
            'form' : form,
        }

        return render(request, 'loudness.html', context=context)
    elif request.method == 'POST':
        form = LoudnessForm(request.POST)

        if form.is_valid():

            loudnessv = form.save()
            form = LoudnessForm()

        context = {
            'form' : form
        }

        return render(request, 'loudness.html', context=context)


class Solution:
    def validPalindrome(self, s: str) -> bool:
        left, right = 0, len(s)-1

        while left < right:
            if s[left] != s[right]:
                # check whether string from left to right is palindrome after removing
                # either left or right
                no_left = s[left+1:right+1]
                no_right = s[left:right]

                if no_left == no_left[::-1] or no_right == no_right[::-1]:
                    break

                return False
            left+=1
            right-=1
        return True


import pickle as pkl
from utils.data_statistic import get_statistic
from data_preprocess.cail_reader import read_cails

def get_label_index(index2num_list, num_threshold_low, num_threshold_high):
    index_list = []
    pair_list = list(zip(index2num_list[0].tolist(), index2num_list[1].tolist()))
    for index, num in pair_list:
        if num_threshold_low <= num <= num_threshold_high:
            index_list.append(index)
    return index_list

if __name__ == '__main__':
    data_path = '/home/nxu/Ladan_tnnls/processed_dataset/CAIL'
    train_dir = data_path + '/normal/small/train_processed_thulac.pkl'
    dataset_fold = read_cails(dir_path=data_path,
                              data_format='normal',
                              version='small')

    train_set, valid_set, test_set = next(dataset_fold)

    law_statisitc, accu_statistic, time_statistic = get_statistic(train_set, law_num=103, accu_num=119,
                                                                  time_num=11)

    print(law_statisitc)

    print(accu_statistic)

    print(time_statistic)

    print(get_label_index(law_statisitc, 100, 200))

    print(get_label_index(accu_statistic, 100, 200))

    tail_law_list = [37, 89, 74, 66, 25, 82, 32, 36, 5, 81, 7, 43, 17, 14, 48, 76, 96, 15, 72, 70, 54, 69, 49, 53, 85, 56, 44]
    tail_charge_list = [37, 85, 96, 114, 99, 86, 106, 36, 71, 104, 72, 95, 34, 39, 51, 23, 109, 62, 54, 31, 59, 60, 81, 110, 76, 26, 19, 64]

    tail_100to200_law = [81, 7, 43, 17, 14, 48, 76, 96, 15, 72, 70, 54, 69, 49, 53, 85, 56, 44]
    tail_100to200_charge = [114, 99, 86, 106, 36, 71, 104, 72, 95, 34, 39, 51, 23, 109, 62, 54, 31, 59, 60, 81, 110, 76, 26, 19, 64]


aliasTables =  {
            "a": ["a", "@"],
            "b": ["b"],
            "c": ["c"],
            "d": ["d"],
            "e": ["e"],
            "f": ["f"],
            "g": ["g"],
            "h": ["h"],
            "i": ["i", "1"],
            "j": ["j"],
            "k": ["k"],
            "l": ["l"],
            "m": ["m"],
            "n": ["n"],
            "o": ["o"],
            "p": ["p"],
            "q": ["q"],
            "r": ["r"],
            "s": ["s", "$"],
            "t": ["t", "7"],
            "u": ["u"],
            "v": ["v"],
            "w": ["w"],
            "x": ["x"],
            "y": ["y"],
            "z": ["z"]
        }

def convertForSeekAliasTables(aliasTables):
    cvtResult = {}
    for key in aliasTables:
        for element in aliasTables[key]:
            cvtResult[element] = key
    return cvtResult

newAliasTables = convertForSeekAliasTables(aliasTables)

swears = ["shit"]
swears_nospaceatfront = ["fuck"]

seps = ["_", ".", " "]

#initialised

#run this to transform string into baseline

stri = "testshiiiit coalfuck"
newstri = []
cached_char = []
ind = 0
spaces = []
for char in stri:
    if char in seps and not char in cached_char:
        spaces.append(ind)
        cached_char = seps
    elif char not in cached_char:
        newstri.append(newAliasTables.get(char, char))
        ind += 1
        cached_char = aliasTables.get(newAliasTables.get(char, char), [char])

joined_newstri = "".join(newstri)

print(joined_newstri)

#run this to check for swears

def seek_with_spaces():
    for swear in swears_nospaceatfront:
        if swear in joined_newstri:
            indexes = [index for index in range(len(joined_newstri)) if joined_newstri.startswith(swear, index)]
            for index in indexes:
                if index in spaces:
                    return True
    return False

def seek_without_spaces():
    for swear in swears:
        if swear in joined_newstri:
            return True
    return False

#figure this out yourself i am too tired to explain it


from unittest import TestCase, main
from application.changeobserver import ChangeObserver

class ChangeObserverTest(TestCase):

    def test_it(self):
        params = {
            'input' : {
                'type' : 'url.content',
                "url" : "http://www.timeapi.org/utc/now?format=%25a%20%25b%20%25d%20%25I:%25M:%25S"
            },
            'stateManager' : {
                'type' : 'file',
                'filename' : '../output/aa.json'
            },
            'comparator' : {
                'type' : 'text'
            },
            'notifier' : {
                'type' : 'debug',
                'recipients' : ['aa@wp.pl']
            }
        }
        c = ChangeObserver(params)
        diff = c.notify_if_changed()
        self.assertIsNotNone(diff)

if __name__ == '__main__' :
    main();


def SieveOfEratosthenes(n):
    prime = [True for i in range(n+1)]
    p = 2
    while (p * p <= n):
        if (prime[p] == True):
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
    for p in range(2, n+1):
        if prime[p]:
            print(p,end=" ")

n=int(input())
SieveOfEratosthenes(n)

# O (nk) is the time complexity where k is the no of primes in range n


import numpy as np
from PIL import Image
import os
import math
import lpips
import torch
# from skimage.measure import compare_ssim
from skimage.metrics import structural_similarity as compare_ssim
import matplotlib.pyplot as plt
import torchvision
import glob
from tqdm import tqdm

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')

def read_image(path):
    return np.asfarray(Image.open(path))/255

def cal_psnr(img1, img2):
    diff = img1 - img2
    rmse = math.sqrt(np.mean(diff**2))
    return 20 * math.log10(1.0 / rmse)

def cal_lpips(img1,img2,normalize=True):
    # img1 = torch.from_numpy(np.transpose(img1, (2,0,1))[None,::].astype(np.float32)).to(device)
    # img2 = torch.from_numpy(np.transpose(img2, (2,0,1))[None,::].astype(np.float32)).to(device)
    img1 = torch.from_numpy(img1[None,None,::].astype(np.float32)).to(device)
    img2 = torch.from_numpy(img2[None,None,::].astype(np.float32)).to(device)
    lpips = loss_fn_alex(img1, img2,normalize=normalize)
    return lpips.item()

def cal_ssim(image1, image2, multichannel=False):
    return compare_ssim(image1, image2, multichannel=multichannel)

class VGGPerceptualLoss(torch.nn.Module):
    def __init__(self, resize=False):
        super(VGGPerceptualLoss, self).__init__()
        blocks = []
        blocks.append(torchvision.models.vgg16(pretrained=True).features[:4].eval())
        blocks.append(torchvision.models.vgg16(pretrained=True).features[4:9].eval())
        blocks.append(torchvision.models.vgg16(pretrained=True).features[9:16].eval())
        blocks.append(torchvision.models.vgg16(pretrained=True).features[16:23].eval())
        for bl in blocks:
            for p in bl:
                p.requires_grad = False
        self.blocks = torch.nn.ModuleList(blocks)
        self.transform = torch.nn.functional.interpolate
        self.mean = torch.nn.Parameter(torch.tensor([0.485, 0.456, 0.406]).view(1,3,1,1))
        self.std = torch.nn.Parameter(torch.tensor([0.229, 0.224, 0.225]).view(1,3,1,1))
        self.resize = resize
        self.loss_fn = torch.nn.MSELoss(reduction='elementwise_mean')

    def forward(self, input, target):

        # if input.shape[1] != 3:
        #     input = input.repeat(1, 3, 1, 1)
        #     target = target.repeat(1, 3, 1, 1)
        input = (input-self.mean) / self.std
        target = (target-self.mean) / self.std
        # if self.resize:
        #     input = self.transform(input, mode='bilinear', size=(224, 224), align_corners=False)
        #     target = self.transform(target, mode='bilinear', size=(224, 224), align_corners=False)
        loss = 0.0
        x = input
        y = target
        for block in self.blocks:
            x = block(x)
            y = block(y)
            # loss += torch.nn.functional.l1_loss(x, y)
            loss += self.loss_fn(x, y)
        return loss

loss_vgg = VGGPerceptualLoss().to(device)
loss_fn_alex = lpips.LPIPS(net='alex').to(device) # best forward scores

def cal_vgg(img1, img2):
    # image1 = torch.from_numpy(np.transpose(image1, (2,0,1))[None,::].astype(np.float32)).to(device)
    # image2 = torch.from_numpy(np.transpose(image2, (2,0,1))[None,::].astype(np.float32)).to(device)
    img1 = torch.from_numpy(img1[None,None,::].astype(np.float32)).to(device)
    img2 = torch.from_numpy(img2[None,None,::].astype(np.float32)).to(device)
    vgg=loss_vgg(img1, img2)
    return vgg.item()

folder = r'./pred0_1'

gt_list = sorted(glob.glob(os.path.join(r'/ssd1/vis/yaomingde/VDN/data/BSD68','*.png')))
# list1 = sorted(glob.glob(os.path.join(folder,'*000.png')))+
createVar = locals()
for i in np.arange(2.1,3.1,0.1):
    createVar['list'+ str(int(i*10))] = sorted(glob.glob(os.path.join(folder,'*%03d.png'%(i*10))))

def cal_list_metric(gt_list, list1):
    psnr_list = []
    ssim_list = []
    vgg_list = []
    lpips_list = []
    for i in tqdm(range(len(gt_list)),ncols=45):
        gt = read_image(gt_list[i])
        gt = gt[:gt.shape[0]//16*16,:gt.shape[1]//16*16]
        img = read_image(list1[i])

        psnr_list += [cal_psnr(img,gt)]
        ssim_list += [cal_ssim(img,gt)]
        vgg_list += [cal_vgg(img,gt)]
        lpips_list += [cal_lpips(img,gt)]
    return np.mean(psnr_list),np.mean(ssim_list), np.mean(vgg_list), np.mean(lpips_list)

for i in np.arange(2.1,3.1,0.1):
    content = 'list' + str(int(i*10))
    print(i, cal_list_metric(gt_list, eval(content)))


n = int(input("Dame un numero: "))
i = 1
while i < n:
    suma = 0
    j = 1
    while j <= (i // 2):
        if (i % j) == 0:
            suma += j
        j += 1
    if suma == i:
        print(i," es un numero perfecto. ")
    i += 1
print("Fin del programa")


import os
import pickle
from net import Net
from globals import *
import matplotlib.pyplot as plt
import matplotlib
import hashlib
from multiprocessing import Process, Manager
from helpers import HiddenPrints

# font = {#'family' : 'normal',
#         # 'weight' : 'bold',
#         'size'   : 22}
#
# matplotlib.rc('font', **font)

class MCProcess(Process):
    def __init__(self, name, queue, n, p, p_i, max_t, seed, clustering_target, dispersion_target, mc_iterations,
                 mode):
        super().__init__(name=name)
        self.name = name
        self.n = n
        self.p = p
        self.p_i = p_i
        self.max_t = max_t
        self.seed = seed
        self.clustering_target = clustering_target
        self.dispersion_target = dispersion_target
        self.mc_iterations = mc_iterations
        self.mode = mode
        self.queue = queue

    def run(self):
        with HiddenPrints():
            [mean_counts, meansq_counts, mean_peak, meansq_peak, mean_prevalence, meansq_prevalence, clustering, dispersion] = Net(n=self.n, p=self.p, p_i=self.p_i, max_t=self.max_t, seed=self.seed,
                                                     clustering_target=self.clustering_target,
                                                     dispersion_target=self.dispersion_target).monte_carlo(
                self.mc_iterations, mode=self.mode)

            self.queue[self.name] = [mean_counts, meansq_counts, mean_peak, meansq_peak, mean_prevalence, meansq_prevalence, clustering, dispersion]
        return

# pickling disabled for now, uncomment plot lines for that
def simple_experiment(n, p, p_i, mc_iterations, max_t, seed=123, mode=None, force_recompute=False, path=None,
                      clustering: float = None, dispersion=None):
    # this creates the net, runs monte carlo on it and saves the resulting timeseries plot, as well as pickles for net and counts

    assert not (dispersion and clustering), "Cannot set a dispersion target and " \
                                            "a clustering target at the same time"
    if dispersion:
        chosen_epsilon = epsilon_disp
    else:
        chosen_epsilon = epsilon_clustering

    if path:
        dirname = path
    else:
        dirname_parent = os.path.dirname(__file__)
        dirname = os.path.join(dirname_parent, 'Experiments')

    # the cache is now tagged with a hash from all important parameters
    # Any change to the model parameters will certainly trigger a recompute now
    id_params = (n, p, p_i, mc_iterations, max_t, seed, mode, clustering, dispersion, t_i, t_c, t_r, t_d, t_t, p_q, p_t,
                 quarantine_time, resolution, chosen_epsilon)
    # normal hashes are salted between runs -> use something that is persistent
    tag = str(hashlib.md5(str(id_params).encode('utf8')).hexdigest())

    recompute = False
    # disables loading pickled results
    if force_recompute:
        # if false, it looks at saved experiments and reuses those
        recompute = True
    else:
        try:
            with open(os.path.join(dirname, tag + "_counts.p"), 'rb') as f:
                mean_counts, sd_counts, mean_peak, sd_peak, mean_prevalence, sd_prevalence,clustering,dispersion  = pickle.load(f)
            # with open(os.path.join(dirname, tag + "_net.p"), 'rb') as f:
            #    net = pickle.load(f)

            print('Experiment results have been loaded from history.')

        except FileNotFoundError:
            recompute = True

    if recompute:
        kernels = 3
        runsPerKernel = int(mc_iterations / 5)
        threads = list()

        q = Manager().dict()

        for i in range(kernels):
            threads.append(
                MCProcess('MCProcess_' + str(i), q, n, p, p_i, max_t, seed + i, clustering, dispersion, runsPerKernel,
                          mode))
            threads[-1].start()

        mean_counts = list()
        meansq_counts = list()
        mean_peak = list()
        meansq_peak = list()
        mean_prevalence = list()
        meansq_prevalence = list()
        clusterings = list()
        disps = list()

        for t in threads:
            t.join()  # wait for all threads to finish
        for v in q.values():
            mean_counts.append(v[0])
            meansq_counts.append(v[1])
            mean_peak.append(v[2])
            meansq_peak.append(v[3])
            mean_prevalence.append(v[4])
            meansq_prevalence.append(v[5])
            clusterings.append(v[6])
            disps.append(v[7])
        for t in threads:
            t.kill()
        mean_counts = sum(mean_counts) / len(mean_counts)
        meansq_counts = sum(meansq_counts) / len(meansq_counts)
        mean_peak = np.mean(mean_peak)
        meansq_peak = np.mean(meansq_peak)
        mean_prevalence = np.mean(mean_prevalence)
        meansq_prevalence = np.mean(meansq_prevalence)

        sd_counts = np.sqrt(meansq_counts-np.square(mean_counts))
        sd_peak = np.sqrt(meansq_peak-np.square(mean_peak))
        sd_prevalence = np.sqrt(meansq_prevalence-np.square(mean_prevalence))

        clustering = np.mean(clusterings)
        dispersion = np.mean(disps)

        # with open(os.path.join(dirname, tag + '_net.p'), 'wb') as f:
        #    pickle.dump(net, f)
        with open(os.path.join(dirname, tag + '_counts.p'), 'wb') as f:
            pickle.dump((mean_counts, sd_counts, mean_peak, sd_peak, mean_prevalence, sd_prevalence,clustering,dispersion), f)

        # net.plot_timeseries(counts, save= os.path.join(dirname, tag+'_vis.png'))

    exposed = mean_counts[EXP_STATE, :]
    infected = mean_counts[INF_STATE, :]
    ep_curve = exposed + infected
    t_peak = np.argmax(ep_curve, axis=0) # simply take time for peak from mean counts (sloppy)

    recovered = mean_counts[REC_STATE, :]
    virus_contacts = ep_curve + recovered

    sensitivity = max(1, n / 100)  # increasing divisor makes this more sensitive
    equilib_flag = abs(
        virus_contacts[-1] - virus_contacts[-2]) < sensitivity  # just a heuristic, see whether roc is low

    assert dispersion, 'These should not be None'

    return None, mean_counts, sd_counts, t_peak, mean_peak, sd_peak, mean_prevalence, sd_prevalence, equilib_flag , clustering, dispersion


# Given two integer arrays nums1 and nums2, return an array of their intersection.
# Each element in the result must appear as many times as it shows in both arrays and
# you may return the result in any order.

# Example 1:
# Input: nums1 = [1,2,2,1], nums2 = [2,2]
# Output: [2,2]

# Example 2:
# Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
# Output: [4,9]
# Explanation: [9,4] is also accepted.

from typing import List

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        dict1 = self.makeDict(nums1)
        dict2 = self.makeDict(nums2)
        res = []
        for num in dict1.keys():
            if dict2.get(num):
                count = dict1[num] if dict1[num] < dict2[num] else dict2[num]
                for i in range(count):
                    res.append(num)
        return res
    def makeDict(self, nums: List[int]) -> dict:
        dict = {}
        for num in nums:
            if num not in dict.keys():
                dict[num] = 1
            else:
                dict[num] += 1

        return dict

obj = Solution()

nums1 = [4,9,5]
nums2 = [9,4,9,8,4]

print(f"Intersection of two arrays: {obj.intersect(nums1, nums2)}")


class FileSystem:

    def __init__(self):
        self.root = {}

    def ls(self, path: str) -> List[str]:
        if len(path) == 1:
            return sorted(self.root.keys())

        nodes = path.split("/")
        node = self.root
        for n in nodes[1:]:
            node = node.setdefault(n, {})

        if isinstance(node, str):
            return [path[-1]]

        return sorted(node.keys())

    def mkdir(self, path: str) -> None:
        nodes = path.split('/')
        node = self.root
        for n in nodes[1:]:
            node = node.setdefault(n, {})

    def addContentToFile(self, filePath: str, content: str) -> None:
        nodes = filePath.split("/")
        file = nodes[-1]
        node = self.root

        for n in nodes[1:-1]:
            node = node.setdefault(n, {})
        if file not in node:
            node[file] = content
        else:
            node[file] += content

    def readContentFromFile(self, filePath: str) -> str:
        nodes = filePath.split("/")
        file = path[-1]
        node = self.root
        for n in nodes[1:-1]:
            node = node.setdefault(n, {})
        return node[file]

# Your FileSystem object will be instantiated and called as such:
# obj = FileSystem()
# param_1 = obj.ls(path)
# obj.mkdir(path)
# obj.addContentToFile(filePath,content)
# param_4 = obj.readContentFromFile(filePath)


import cv2 # importing cv2 library
# import ImageFirebase
import time
import staticRec
import testguirandom

def Capture(name):

    cam = cv2.VideoCapture(0)

    ImageTaken = 0

    while True:
        if ImageTaken == 0 :

            count = 0

            ret, img = cam.read()

            cv2.imshow("Test", img)

            if not ret:
                break

            k = cv2.waitKey(1)

            if k % 256 == 27:
                #For Esc key
                print("Close")
                break

            elif k % 256 == 32:
                #For Space key

                file = '/Users/admin/VScode/Mini-Project-III-Python/Final-Code/ResFaceRecog/' + name + '.jpg'
                cv2.imwrite(file, img)

                print("Image " + str(count) + "saved")

                # time.sleep(5)

                # ImageFirebase.SendtoFirebase(name)

                count += 1
                ImageTaken += 1

        elif ImageTaken == 1:

            break

    cam.release
    cv2.destroyAllWindows

    NewtempText = staticRec.FaceRec(name + ".jpg")

    testguirandom.finalScreenDropOff(NewtempText)

# name = "Apurv Vidhate"
# Capture(name) # Only Uncomment this line when you are using the code independently


def isSort(lst,i,j,n):
    if j==n:
        return
    else:
        if lst[j]>lst[j+1]:
            lst[j],lst[j+1]=lst[j+1],lst[j]
        isSort(lst,i,j+1,n)

    if i==n:
        return
    else:
        return isSort(lst,i+1,j,n)

l=[5,2,1,3,4]
inp=list(map(int,input('Enter Input : ').split()))
isSort(inp,0,0,len(inp)-1)
print(inp)


# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------------
# Calculate wetness indices
# Author: Timm Nawrocki
# Last Updated: 2023-10-21
# Usage: Execute in ArcGIS Pro Python 3.9+.
# Description: "Calculate wetness indices" calculates flow accumulation and wetness index.
# ---------------------------------------------------------------------------

# Import packages
import os
import time
from akutils import *
from geomorph import *

# Set root directory
drive = 'D:/'
root_folder = 'ACCS_Work'

# Define folder structure
topography_folder = os.path.join(drive, root_folder, 'Data/topography')
hydrography_folder = os.path.join(drive, root_folder, 'Data/hydrography')
project_folder = os.path.join(drive, root_folder, 'Projects/VegetationEcology/AKVEG_Map/Data')

# Define input files
elevation_float = os.path.join(topography_folder, 'Alaska_Composite_DTM_10m/float', 'Elevation_10m_3338.tif')
slope_float = os.path.join(topography_folder, 'Alaska_Composite_DTM_10m/float', 'Slope_10m_3338.tif')
area_file = os.path.join(topography_folder, 'area_test.tif')
# area_file = os.path.join(project_folder, 'Data_Input', 'AlaskaYukon_MapDomain_10m_3338.tif')

# Define output files
direction_float = os.path.join(hydrography_folder, 'intermediate', 'Direction_10m_3338.tif')
accumulation_float = os.path.join(hydrography_folder, 'intermediate', 'Accumulation_10m_3338.tif')
wetness_output = os.path.join(hydrography_folder, 'integer', 'Wetness_10m_3338.tif')

# Calculate flow accumulation if it does not already exist
if os.path.exists(accumulation_float) == 0:
    # Calculate flow direction
    print('Calculating flow direction...')
    iteration_start = time.time()
    calculate_flow(area_file, elevation_float, direction_float, accumulation_float)
    end_timing(iteration_start)
else:
    print('Flow direction already exists.')
    print('----------')

# Calculate topographic wetness with smoothing 5 if it does not already exist
if os.path.exists(wetness_output) == 0:
    print('Calculating topographic wetness (smoothing = 5)...')
    iteration_start = time.time()
    calculate_wetness(area_file, slope_float, accumulation_float, 100, 5, wetness_output)
    end_timing(iteration_start)
else:
    print('Topographic wetness (smoothing = 5) already exists.')
    print('----------')


from django import forms
from django.utils.translation import gettext_lazy as _

from forj.models import Address
from forj.forms import widgets
from forj import constants

import phonenumbers

class AddressForm(forms.ModelForm):
    class Meta:
        model = Address
        fields = (
            "type",
            "email",
            "first_name",
            "last_name",
            "business_name",
            "line1",
            "line2",
            "postal_code",
            "phone_number",
            "city",
            "country",
        )

        widgets = {"line1": forms.TextInput, "type": widgets.Radio}

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop("user", None)

        super().__init__(*args, **kwargs)

    def clean_phone_number(self):
        value = self.cleaned_data["phone_number"]
        if not value:
            return value

        country = self.initial.get("country")

        if country is None:
            return value

        country = "{}".format(country)

        try:
            ph = phonenumbers.parse(value, country)

            if not phonenumbers.is_valid_number(ph):
                raise forms.ValidationError(_("Invalid phone number"))

            if not phonenumbers.is_valid_number_for_region(ph, country):
                raise forms.ValidationError(_("Invalid phone number"))
        except phonenumbers.NumberParseException:
            raise forms.ValidationError(_("Invalid phone number"))

        return value

    def save(self, *args, **kwargs):
        self.user = kwargs.pop("user", self.user)
        self.instance.user = self.user

        if self.user:
            self.instance.first_name = self.instance.first_name or self.user.first_name
            self.instance.last_name = self.instance.last_name or self.user.last_name

        return super().save(*args, **kwargs)

class RequiredAddressForm(AddressForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields["type"].required = True
        self.fields["first_name"].required = True
        self.fields["last_name"].required = True

        if self.data:
            if self.prefix:
                type_value = self.data.get("{}-type".format(self.prefix))
            else:
                type_value = self.data.get("type")

            if (
                type_value is not None
                and int(type_value) == constants.ADDRESS_TYPE_CHOICES.BUSINESS
            ):
                self.fields["business_name"].required = True
        else:
            self.fields["business_name"].required = False

        self.fields["line1"].required = True
        self.fields["line2"].required = False
        self.fields["city"].required = True
        self.fields["postal_code"].required = True
        self.fields["country"].required = True
        self.fields["phone_number"].required = True

class OptionalAddressForm(AddressForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields["type"].required = False
        self.fields["email"].required = False
        self.fields["first_name"].required = False
        self.fields["last_name"].required = False
        self.fields["business_name"].required = False
        self.fields["line1"].required = False
        self.fields["line2"].required = False
        self.fields["city"].required = False
        self.fields["country"].required = False
        self.fields["phone_number"].required = False
        self.fields["postal_code"].required = False


import time
import libertem_dectris
from libertem_live.detectors.dectris.DEigerClient import DEigerClient

if __name__ == "__main__":
    # this is emulating a slow data consumer
    # if the number of slots is large enough, this should still work,
    # as the whole acquisition _can_ fit into shared memory
    conn = libertem_dectris.DectrisConnection(
        uri="tcp://localhost:9999",
        handle_path="/tmp/dectris_shm",
        frame_stack_size=32,
        num_slots=1000,
        bytes_per_frame=512*512,
        huge=False,
    )
    ec = DEigerClient('localhost', 8910)

    ec.setDetectorConfig('ntrigger', 1)
    ec.setDetectorConfig('nimages', 1)
    ec.setDetectorConfig('trigger_mode', 'exte')
    ec.setDetectorConfig('ntrigger', 256*256)

    result = ec.sendDetectorCommand('arm')
    sequence_id = result['sequence id']

    conn.start(series=sequence_id)
    cam_client = libertem_dectris.CamClient(conn.get_socket_path())

    while True:
        stack_handle = conn.get_next_stack(max_size=1024)
        if stack_handle is None:
            break
        print(f"{len(stack_handle)}")
        time.sleep(1.1)
        cam_client.done(stack_handle)

    conn.close()


# Начало
# Вывод("Введите трёхзначное число")
# Ввод(Число)
#
# a = value // 100
# b = value // 10 % 10
# c = value % 10
#
# sum = a + b + c
# product = a * b * c
#
# Вывод("Sum = ", sum)
# Вывод("Product = ", product)
# Конец

value = int(input(('Введите трёхзначное число: ')))

a = value // 100
b = value // 10 % 10
c = value % 10

sum = a + b + c
product = a * b * c

print(f'Sum = {sum}')
print(f'Product = {product}')


import gc
import json
import sys
from dataclasses import asdict
from functools import partial
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union

import torch
from lightning.fabric.utilities.load import _NotYetLoadedTensor as NotYetLoadedTensor

# support running without installing as a package
wd = Path(__file__).parent.parent.resolve()
sys.path.append(str(wd))

from lit_gpt import Config
from lit_gpt.utils import incremental_save, lazy_load

def copy_weights_gpt_neox(
    state_dict: Dict[str, torch.Tensor],
    hf_weights: Dict[str, Union[torch.Tensor, NotYetLoadedTensor]],
    saver: Optional[incremental_save] = None,
    dtype: Optional[torch.dtype] = None,
) -> None:
    weight_map = {
        "gpt_neox.embed_in.weight": "transformer.wte.weight",
        "gpt_neox.layers.{}.input_layernorm.bias": "transformer.h.{}.norm_1.bias",
        "gpt_neox.layers.{}.input_layernorm.weight": "transformer.h.{}.norm_1.weight",
        "gpt_neox.layers.{}.attention.query_key_value.bias": "transformer.h.{}.attn.attn.bias",
        "gpt_neox.layers.{}.attention.query_key_value.weight": "transformer.h.{}.attn.attn.weight",
        "gpt_neox.layers.{}.attention.dense.bias": "transformer.h.{}.attn.proj.bias",
        "gpt_neox.layers.{}.attention.dense.weight": "transformer.h.{}.attn.proj.weight",
        "gpt_neox.layers.{}.attention.rotary_emb.inv_freq": None,
        "gpt_neox.layers.{}.attention.bias": None,
        "gpt_neox.layers.{}.attention.masked_bias": None,
        "gpt_neox.layers.{}.post_attention_layernorm.bias": "transformer.h.{}.norm_2.bias",
        "gpt_neox.layers.{}.post_attention_layernorm.weight": "transformer.h.{}.norm_2.weight",
        "gpt_neox.layers.{}.mlp.dense_h_to_4h.bias": "transformer.h.{}.mlp.fc.bias",
        "gpt_neox.layers.{}.mlp.dense_h_to_4h.weight": "transformer.h.{}.mlp.fc.weight",
        "gpt_neox.layers.{}.mlp.dense_4h_to_h.bias": "transformer.h.{}.mlp.proj.bias",
        "gpt_neox.layers.{}.mlp.dense_4h_to_h.weight": "transformer.h.{}.mlp.proj.weight",
        "gpt_neox.final_layer_norm.bias": "transformer.ln_f.bias",
        "gpt_neox.final_layer_norm.weight": "transformer.ln_f.weight",
        "embed_out.weight": "lm_head.weight",
    }

    for name, param in hf_weights.items():
        if "gpt_neox.layers" in name:
            from_name, number = layer_template(name, 2)
            to_name = weight_map[from_name]
            if to_name is None:
                continue
            to_name = to_name.format(number)
        else:
            to_name = weight_map[name]
        param = load_param(param, name, dtype)
        if saver is not None:
            param = saver.store_early(param)
        state_dict[to_name] = param

def copy_weights_falcon(
    model_name: str,
    state_dict: Dict[str, torch.Tensor],
    hf_weights: Dict[str, Union[torch.Tensor, NotYetLoadedTensor]],
    saver: Optional[incremental_save] = None,
    dtype: Optional[torch.dtype] = None,
) -> None:
    weight_map = {
        "transformer.word_embeddings.weight": "transformer.wte.weight",
        "transformer.h.{}.self_attention.query_key_value.weight": "transformer.h.{}.attn.attn.weight",
        "transformer.h.{}.self_attention.dense.weight": "transformer.h.{}.attn.proj.weight",
        "transformer.h.{}.mlp.dense_h_to_4h.weight": "transformer.h.{}.mlp.fc.weight",
        "transformer.h.{}.mlp.dense_4h_to_h.weight": "transformer.h.{}.mlp.proj.weight",
        "transformer.ln_f.bias": "transformer.ln_f.bias",
        "transformer.ln_f.weight": "transformer.ln_f.weight",
        "lm_head.weight": "lm_head.weight",
    }
    # the original model definition is different for each size
    if "7b" in model_name:
        weight_map.update(
            {
                "transformer.h.{}.input_layernorm.bias": "transformer.h.{}.norm_1.bias",
                "transformer.h.{}.input_layernorm.weight": "transformer.h.{}.norm_1.weight",
            }
        )
    elif "40b" in model_name or "180B" in model_name:
        weight_map.update(
            {
                "transformer.h.{}.ln_attn.bias": "transformer.h.{}.norm_1.bias",
                "transformer.h.{}.ln_attn.weight": "transformer.h.{}.norm_1.weight",
                "transformer.h.{}.ln_mlp.bias": "transformer.h.{}.norm_2.bias",
                "transformer.h.{}.ln_mlp.weight": "transformer.h.{}.norm_2.weight",
            }
        )
    else:
        raise NotImplementedError

    for name, param in hf_weights.items():
        if "transformer.h" in name:
            from_name, number = layer_template(name, 2)
            to_name = weight_map[from_name].format(number)
        else:
            to_name = weight_map[name]
        param = load_param(param, name, dtype)
        if saver is not None:
            param = saver.store_early(param)
        state_dict[to_name] = param

def copy_weights_hf_llama(
    config: Config,
    qkv_weights: Dict[int, List[Optional[NotYetLoadedTensor]]],
    state_dict: Dict[str, torch.Tensor],
    hf_weights: Dict[str, Union[torch.Tensor, NotYetLoadedTensor]],
    saver: Optional[incremental_save] = None,
    dtype: Optional[torch.dtype] = None,
) -> None:
    weight_map = {
        "model.embed_tokens.weight": "transformer.wte.weight",
        "model.layers.{}.input_layernorm.weight": "transformer.h.{}.norm_1.weight",
        "model.layers.{}.self_attn.q_proj.weight": None,
        "model.layers.{}.self_attn.k_proj.weight": None,
        "model.layers.{}.self_attn.v_proj.weight": None,
        "model.layers.{}.self_attn.o_proj.weight": "transformer.h.{}.attn.proj.weight",
        "model.layers.{}.self_attn.rotary_emb.inv_freq": None,
        "model.layers.{}.post_attention_layernorm.weight": "transformer.h.{}.norm_2.weight",
        "model.layers.{}.mlp.gate_proj.weight": "transformer.h.{}.mlp.fc_1.weight",
        "model.layers.{}.mlp.up_proj.weight": "transformer.h.{}.mlp.fc_2.weight",
        "model.layers.{}.mlp.down_proj.weight": "transformer.h.{}.mlp.proj.weight",
        "model.norm.weight": "transformer.ln_f.weight",
        "lm_head.weight": "lm_head.weight",
    }

    for name, param in hf_weights.items():
        if "model.layers" in name:
            from_name, number = layer_template(name, 2)
            qkv = qkv_weights.setdefault(number, [None, None, None])
            if "q_proj" in name:
                qkv[0] = param
            elif "k_proj" in name:
                qkv[1] = param
            elif "v_proj" in name:
                qkv[2] = param
            to_name = weight_map[from_name]
            if to_name is None:
                continue
            to_name = to_name.format(number)
        else:
            to_name = weight_map[name]
        param = load_param(param, name, dtype)
        if saver is not None:
            param = saver.store_early(param)
        state_dict[to_name] = param

    for i, (q, k, v) in list(qkv_weights.items()):
        if q is None or k is None or v is None:
            # split across different .bin files
            continue
        q = load_param(q, f"layer {i} q", dtype)
        k = load_param(k, f"layer {i} k", dtype)
        v = load_param(v, f"layer {i} v", dtype)
        q_per_kv = config.n_head // config.n_query_groups
        qs = torch.split(q, config.head_size * q_per_kv)
        ks = torch.split(k, config.head_size)
        vs = torch.split(v, config.head_size)
        cycled = [t for group in zip(qs, ks, vs) for t in group]
        qkv = torch.cat(cycled)
        state_dict[f"transformer.h.{i}.attn.attn.weight"] = qkv
        del qkv_weights[i]

def copy_weights_phi(
    config: Config,
    state_dict: Dict[str, torch.Tensor],
    hf_weights: Dict[str, Union[torch.Tensor, NotYetLoadedTensor]],
    saver: Optional[incremental_save] = None,
    dtype: Optional[torch.dtype] = None,
) -> None:
    weight_map = {
        "layers.0.wte.weight": "transformer.wte.weight",
        "layers.{}.ln.bias": "transformer.h.{}.norm_1.bias",
        "layers.{}.ln.weight": "transformer.h.{}.norm_1.weight",
        "layers.{}.mixer.Wqkv.bias": "transformer.h.{}.attn.attn.bias",
        "layers.{}.mixer.Wqkv.weight": "transformer.h.{}.attn.attn.weight",
        "layers.{}.mixer.out_proj.bias": "transformer.h.{}.attn.proj.bias",
        "layers.{}.mixer.out_proj.weight": "transformer.h.{}.attn.proj.weight",
        "layers.{}.mixer.rotary_emb.inv_freq": None,
        "layers.{}.mlp.fc1.bias": "transformer.h.{}.mlp.fc.bias",
        "layers.{}.mlp.fc1.weight": "transformer.h.{}.mlp.fc.weight",
        "layers.{}.mlp.fc2.bias": "transformer.h.{}.mlp.proj.bias",
        "layers.{}.mlp.fc2.weight": "transformer.h.{}.mlp.proj.weight",
        f"layers.{config.n_layer + 1}.ln.bias": "transformer.ln_f.bias",
        f"layers.{config.n_layer + 1}.ln.weight": "transformer.ln_f.weight",
        f"layers.{config.n_layer + 1}.linear.weight": "lm_head.weight",
        f"layers.{config.n_layer + 1}.linear.bias": "lm_head.bias",
    }

    for name, param in hf_weights.items():
        if "layers" in name:
            from_name, number = layer_template(name, 1)
            if number in (0, config.n_layer + 1):
                # these are part of the layers in phi, but not in our implementation
                to_name = weight_map[name]
            else:
                to_name = weight_map[from_name]
                if to_name is None:
                    continue
                # the phi layer numbering is off by 1 compared to ours
                to_name = to_name.format(number - 1)
        else:
            to_name = weight_map[name]
        param = load_param(param, name, dtype)
        if "Wqkv" in name:
            q_per_kv = config.n_head // config.n_query_groups
            total_qkv = q_per_kv + 2  # each group has 1+ queries, 1 key, and 1 value
            param = param.view(total_qkv, config.n_query_groups, -1).transpose(0, 1)
            param = param.reshape(config.n_embd * 3, -1)
            if "bias" in name:
                param = param.squeeze()
        if saver is not None:
            param = saver.store_early(param)
        state_dict[to_name] = param

def layer_template(layer_name: str, idx: int) -> Tuple[str, int]:
    split = layer_name.split(".")
    number = int(split[idx])
    split[idx] = "{}"
    from_name = ".".join(split)
    return from_name, number

def load_param(param: Union[torch.Tensor, NotYetLoadedTensor], name: str, dtype: Optional[torch.dtype]) -> torch.Tensor:
    if hasattr(param, "_load_tensor"):
        # support tensors loaded via `lazy_load()`
        print(f"Loading {name!r} into RAM")
        param = param._load_tensor()
    if dtype is not None and type(dtype) is not NotYetLoadedTensor and dtype != param.dtype:
        print(f"Converting {name!r} from {param.dtype} to {dtype}")
        param = param.to(dtype)
    return param

@torch.inference_mode()
def convert_hf_checkpoint(
    *,
    checkpoint_dir: Path = Path("checkpoints/stabilityai/stablelm-base-alpha-3b"),
    model_name: Optional[str] = None,
    dtype: Optional[str] = None,
) -> None:
    if model_name is None:
        model_name = checkpoint_dir.name
    if dtype is not None:
        dtype = getattr(torch, dtype)

    config = Config.from_name(model_name)
    config_dict = asdict(config)
    print(f"Model config {config_dict}")
    with open(checkpoint_dir / "lit_config.json", "w") as json_config:
        json.dump(config_dict, json_config)

    if "falcon" in model_name:
        copy_fn = partial(copy_weights_falcon, model_name)
    elif config._mlp_class == "LLaMAMLP":
        # holder to reconstitute the split q, k, v
        qkv_weights = {}
        copy_fn = partial(copy_weights_hf_llama, config, qkv_weights)
    elif "phi" in model_name:
        copy_fn = partial(copy_weights_phi, config)
    else:
        copy_fn = copy_weights_gpt_neox

    # initialize a new empty state dict to hold our new weights
    sd = {}

    # Load the json file containing weight mapping
    pytorch_bin_map_json_path = checkpoint_dir / "pytorch_model.bin.index.json"
    if pytorch_bin_map_json_path.is_file():  # not all checkpoints have this file
        with open(pytorch_bin_map_json_path) as json_map:
            bin_index = json.load(json_map)
        bin_files = {checkpoint_dir / bin for bin in bin_index["weight_map"].values()}
    else:
        bin_files = set(checkpoint_dir.glob("*.bin"))
        # some checkpoints serialize the training arguments
        bin_files = {f for f in bin_files if f.name != "training_args.bin"}
    if not bin_files:
        raise ValueError(f"Expected {str(checkpoint_dir)!r} to contain .bin files")

    with incremental_save(checkpoint_dir / "lit_model.pth") as saver:
        # for checkpoints that split the QKV across several files, we need to keep all the bin files
        # open, so we use `ExitStack` to close them all together at the end
        for bin_file in sorted(bin_files):
            print("Processing", bin_file)
            hf_weights = lazy_load(bin_file)
            copy_fn(sd, hf_weights, saver=saver, dtype=dtype)
        gc.collect()
        print("Saving converted checkpoint")
        saver.save(sd)

if __name__ == "__main__":
    from jsonargparse import CLI

    CLI(convert_hf_checkpoint)


# -*- coding: utf-8 -*-
# This file as well as the whole tsfresh package are licenced under the MIT licence (see the LICENCE.txt)
# Maximilian Christ (maximilianchrist.com), Blue Yonder Gmbh, 2016

from unittest import TestCase

import numpy as np
import pandas as pd
import pandas.testing as pdt

from tests.fixtures import DataTestCase
from tsfresh import extract_features, extract_relevant_features, select_features
from tsfresh.feature_extraction.settings import ComprehensiveFCParameters
from tsfresh.utilities.dataframe_functions import impute

class RelevantFeatureExtractionDataTestCase(DataTestCase):
    """
    Test case for the relevant_feature_extraction function
    """

    def test_functional_equality(self):
        """
        `extract_relevant_features` should be equivalent to running first `extract_features` with impute and
        `select_features` afterwards.
        Meaning it should produce the same relevant features and the values of these features should be identical.
        :return:
        """
        df, y = self.create_test_data_sample_with_target()

        relevant_features = extract_relevant_features(
            df,
            y,
            column_id="id",
            column_value="val",
            column_kind="kind",
            column_sort="sort",
        )

        extracted_features = extract_features(
            df,
            column_id="id",
            column_value="val",
            column_kind="kind",
            column_sort="sort",
            impute_function=impute,
        )
        selected_features = select_features(extracted_features, y)

        self.assertEqual(
            set(relevant_features.columns),
            set(selected_features.columns),
            "Should select the same columns:\n\t{}\n\nvs.\n\n\t{}".format(
                relevant_features.columns, selected_features.columns
            ),
        )

        relevant_columns = relevant_features.columns
        relevant_index = relevant_features.index
        self.assertTrue(
            relevant_features.equals(
                selected_features.loc[relevant_index][relevant_columns]
            ),
            "Should calculate the same feature values",
        )

class RelevantFeatureExtractionTestCase(TestCase):
    def setUp(self):
        np.random.seed(42)
        y = pd.Series(np.random.binomial(1, 0.5, 20), index=range(20))
        df = pd.DataFrame(index=range(100))

        df["a"] = np.random.normal(0, 1, 100)
        df["b"] = np.random.normal(0, 1, 100)
        df["id"] = np.repeat(range(20), 5)

        X = pd.DataFrame(index=range(20))
        X["f1"] = np.random.normal(0, 1, 20)
        X["f2"] = np.random.normal(0, 1, 20)

        self.df = df
        self.X = X
        self.y = y

    def test_extracted_features_contain_X_features(self):
        X = extract_relevant_features(self.df, self.y, self.X, column_id="id")
        self.assertIn("f1", X.columns)
        self.assertIn("f2", X.columns)
        pdt.assert_series_equal(self.X["f1"], X["f1"])
        pdt.assert_series_equal(self.X["f2"], X["f2"])
        pdt.assert_index_equal(self.X["f1"].index, X["f1"].index)
        pdt.assert_index_equal(self.X["f2"].index, X["f2"].index)

    def test_extraction_null_as_column_name(self):

        df1 = pd.DataFrame(
            data={
                0: range(10),
                1: np.repeat([0, 1], 5),
                2: np.repeat([0, 1, 2, 3, 4], 2),
            }
        )
        X1 = extract_features(df1, column_id=1, column_sort=2)
        self.assertEqual(len(X1), 2)

        df2 = pd.DataFrame(
            data={
                1: range(10),
                0: np.repeat([0, 1], 5),
                2: np.repeat([0, 1, 2, 3, 4], 2),
            }
        )
        X2 = extract_features(df2, column_id=0, column_sort=2)
        self.assertEqual(len(X2), 2)

        df3 = pd.DataFrame(
            data={
                0: range(10),
                2: np.repeat([0, 1], 5),
                1: np.repeat([0, 1, 2, 3, 4], 2),
            }
        )
        X3 = extract_features(df3, column_id=2, column_sort=1)
        self.assertEqual(len(X3), 2)

    def test_raises_mismatch_index_df_and_y_df_more(self):
        y = pd.Series(range(3), index=[1, 2, 3])
        df_dict = {
            "a": pd.DataFrame({"val": [1, 2, 3, 4, 10, 11], "id": [1, 1, 1, 1, 2, 2]}),
            "b": pd.DataFrame({"val": [5, 6, 7, 8, 12, 13], "id": [4, 4, 3, 3, 2, 2]}),
        }
        self.assertRaises(
            ValueError,
            extract_relevant_features,
            df_dict,
            y,
            None,
            None,
            None,
            "id",
            None,
            "val",
        )

    def test_raises_mismatch_index_df_and_y_y_more(self):
        y = pd.Series(range(4), index=[1, 2, 3, 4])
        df = pd.DataFrame({"val": [1, 2, 3, 4, 10, 11], "id": [1, 1, 1, 1, 2, 2]})
        self.assertRaises(
            ValueError,
            extract_relevant_features,
            df,
            y,
            None,
            None,
            None,
            "id",
            None,
            "val",
        )

    def test_raises_y_not_series(self):
        y = np.arange(10)
        df_dict = {
            "a": pd.DataFrame({"val": [1, 2, 3, 4, 10, 11], "id": [1, 1, 1, 1, 2, 2]}),
            "b": pd.DataFrame({"val": [5, 6, 7, 8, 12, 13], "id": [4, 4, 3, 3, 2, 2]}),
        }
        self.assertRaises(
            AssertionError,
            extract_relevant_features,
            df_dict,
            y,
            None,
            None,
            None,
            "id",
            None,
            "val",
        )

    def test_raises_y_not_more_than_one_label(self):
        y = pd.Series(1, index=[1, 2, 3])
        df_dict = {
            "a": pd.DataFrame({"val": [1, 2, 3, 4, 10, 11], "id": [1, 1, 1, 1, 2, 2]}),
            "b": pd.DataFrame({"val": [5, 6, 7, 8, 12, 13], "id": [4, 4, 3, 3, 2, 2]}),
        }
        self.assertRaises(
            AssertionError,
            extract_relevant_features,
            df_dict,
            y,
            None,
            None,
            None,
            "id",
            None,
            "val",
        )


import random
import gym
import numpy as np
import cv2
from tensorflow.python.client import device_lib
from Agent import Agent
print(device_lib.list_local_devices())

def updateImage(state):
    state = cv2.cvtColor(cv2.resize(state,(84,110)),cv2.COLOR_BGR2GRAY)
    #remove the first 26 layers
    state = state[26:110,:]
    _,state = cv2.threshold(state, 1,255,cv2.THRESH_BINARY)
    #print(state.shape)
    state = np.reshape(state,(84,84,1))
    return state#.reshape(1,state.shape[0],state.shape[1],state.shape[2])

Episodes = 1000
Trials = 500
env = gym.make('SpaceInvaders-v0')

states = env.observation_space.shape

actions = env.action_space.n
#print(actions)
agent = Agent(states,actions)
done = False
batchSize = 32

for i in range (Episodes):
    state = env.reset()
    state = updateImage(state)
    #print ("State shape")
    #print (state.shape)

    while not done:
        #print (state.shape)
        env.render()
        action = agent.act(state)
        nextState,reward,done,inf   = env.step(action)
        nextState = updateImage(nextState)
        #print("next state")
        #print(len(state))
        #reward = reward if not done else 0.01
        #nextState = np.reshape(nextState,[1,states])
        agent.addToMemory(state,action,reward,nextState,done)
        state = nextState
        if done:
            print("episode {}/{}, score : {}, e: {:.2}".format(i,
                      Episodes,reward,agent.epsilon))
            break
        if len(agent.memory) > batchSize:
                agent.replay(batchSize)
    done = False


#Задание 3

#Пользователь вводит с клавиатуры строку и символ для поиска

stroka = input("Ввести строку: ")
simvol = input("ввести символ: ")

count = 0

#цикл

for i in stroka:
    if i == simvol:
        count += 1
print("Искомый символ встречается", count, "раза")


from typing import List

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        if len(nums) == 0:
            return 0
        longest_seq = 1
        self.nums = set(nums)
        while True:
            try:
                num = self.nums.pop()
                conseq_len = self.check_next(num)
                if conseq_len > longest_seq:
                    longest_seq = conseq_len
            except KeyError:
                return longest_seq

    def check_next(self, num: int, conseq_len: int = 1) -> int:
        if num + 1 in self.nums:
            self.nums.remove(num + 1)
            conseq_len += 1
            conseq_len = self.check_next(num + 1, conseq_len)
        if num - 1 in self.nums:
            self.nums.remove(num - 1)
            conseq_len += 1
            conseq_len = self.check_next(num - 1, conseq_len)
        return conseq_len

if __name__ == "__main__":
    nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]
    Sol = Solution()
    print(Sol.longestConsecutive(nums))


import pickle

import warnings

warnings.filterwarnings("error")

import numpy as np
import copy

from em_fields.slurm_functions import get_script_evolution_slave_fenchel
from em_fields.default_settings import define_plasma_parameters
from em_fields.em_functions import get_thermal_velocity

evolution_slave_fenchel_script = get_script_evolution_slave_fenchel()

import matplotlib.pyplot as plt

plt.rcParams.update({'font.size': 12})
# plt.rcParams.update({'font.size': 10})
# plt.rcParams.update({'font.size': 8})
# plt.rcParams["figure.facecolor"] = 'white'
# plt.rcParams["axes.facecolor"] = 'green'

# plt.close('all')

save_dir = '/Users/talmiller/Downloads/single_particle/'
# save_dir += '/set26_B0_1T_l_3m_Post_Rm_3_first_cell_center_crossing/'
# save_dir += '/set27_B0_1T_l_3m_Post_Rm_3_first_cell_center_crossing/'
# save_dir += '/set28_B0_1T_l_10m_Post_Rm_3_first_cell_center_crossing/'
# save_dir += '/set29_B0_1T_l_3m_Post_Rm_2_first_cell_center_crossing/'
# save_dir += '/set30_B0_1T_l_3m_Post_Rm_3_first_cell_center_crossing/'
# save_dir += '/set31_B0_1T_l_3m_Post_Rm_3_intervals/'
# save_dir += '/set32_B0_1T_l_1m_Post_Rm_3_intervals/'
# save_dir += '/set33_B0_1T_l_3m_Post_Rm_3_intervals/'
# save_dir += '/set34_B0_1T_l_3m_Post_Rm_3_intervals/'
# save_dir += '/set36_B0_1T_l_1m_Post_Rm_3_intervals/'
# save_dir += '/set37_B0_1T_l_1m_Post_Rm_3_intervals/'
# save_dir += '/set38_B0_1T_l_1m_Post_Rm_3_intervals_D_T/'
save_dir += '/set39_B0_1T_l_1m_Post_Rm_3_intervals_D_T/'

RF_type = 'electric_transverse'
# E_RF_kVm = 1 # kV/m
# E_RF_kVm = 10  # kV/m
# E_RF_kVm = 25  # kV/m
E_RF_kVm = 50  # kV/m
# E_RF_kVm = 100  # kV/m

# RF_type = 'magnetic_transverse'
# B_RF = 0.01  # T
# B_RF = 0.02  # T
B_RF = 0.04  # T
# B_RF = 0.05  # T
# B_RF = 0.1  # T

# gas_name = 'deuterium'
# gas_name = 'DT_mix'
# gas_name = 'tritium'`

gas_name_list = []
gas_name_list += ['deuterium']
# gas_name_list += ['DT_mix']
# gas_name_list += ['tritium']

use_RF = True
# use_RF = False

absolute_velocity_sampling_type = 'maxwell'
# absolute_velocity_sampling_type = 'const_vth'
r_0 = 0
# r_0 = 1.5
# r_0 = 3.0

# alpha_loop_list = np.round(np.linspace(0.9, 1.1, 11), 2)  # set26
# beta_loop_list = np.round(np.linspace(0, 1, 11), 11)

# alpha_loop_list = np.round(np.linspace(0.9, 1.1, 21), 2)  # set27
# beta_loop_list = np.round(np.linspace(-1, 1, 21), 2)

# alpha_loop_list = np.round(np.linspace(0.6, 1.0, 21), 2)  # set28
# beta_loop_list = np.round(np.linspace(-5, 0, 21), 2)

# alpha_loop_list = np.round(np.linspace(0.8, 1.0, 21), 2)  # set29, set30
# beta_loop_list = np.round(np.linspace(-10, 0, 21), 2)

# alpha_loop_list = np.round(np.linspace(0.8, 1.0, 11), 2)  # set31, 32, 33
# beta_loop_list = np.round(np.linspace(-10, 0, 11), 2)

# alpha_loop_list = np.round(np.linspace(0.9, 1.1, 11), 2)  # set34
# beta_loop_list = np.round(np.linspace(-5, 5, 11), 2)

# alpha_loop_list = np.round(np.linspace(0.8, 1.2, 21), 2)  # set36
# beta_loop_list = np.round(np.linspace(-5, 5, 21), 2)

alpha_loop_list = np.round(np.linspace(0.5, 1.5, 21), 2)  # set37, 39
beta_loop_list = np.round(np.linspace(-10, 10, 21), 2)

# alpha_loop_list = np.round(np.linspace(0.7, 1.3, 21), 2)  # set38
# beta_loop_list = np.round(np.linspace(-5, 5, 21), 2)

# for ind_beta, beta_RF in enumerate(beta_loop_list):
#     for ind_alpha, alpha_RF in enumerate(alpha_loop_list):
# ind_alpha = 0
# ind_alpha = 1
# ind_alpha = 2
# ind_alpha = 4
# ind_alpha = 5
# ind_alpha = 7
# ind_beta = 1
# ind_beta = 2
# ind_beta = 5
# ind_beta = 4
# ind_beta = 3
# alpha = alpha_loop_list[ind_alpha]
# beta = beta_loop_list[ind_beta]

select_alpha_list = []
select_beta_list = []
set_name_list = []

# select_alpha_list += [1.3]
# select_beta_list += [0.0]
# set_name_list += ['1']
#
# select_alpha_list += [1.4]
# select_beta_list += [3.0]
# set_name_list += ['2']
#
# select_alpha_list += [0.8]
# select_beta_list += [0.0]
# set_name_list += ['3']
#
# select_alpha_list += [1.0]
# select_beta_list += [-3.0]
# set_name_list += ['4']
#
# select_alpha_list += [0.6]
# select_beta_list += [-2.0]
# set_name_list += ['5']

select_alpha_list += [1.4]
select_beta_list += [3.0]
set_name_list += ['1']

select_alpha_list += [1.0]
select_beta_list += [-3.0]
set_name_list += ['2']

select_alpha_list += [0.7]
select_beta_list += [-3.0]
set_name_list += ['3']

select_alpha_list += [0.55]
select_beta_list += [-7.0]
set_name_list += ['4']

# ind_set = 0
ind_set = 1
# ind_set = 2
# ind_set = 3

alpha = select_alpha_list[ind_set]
beta = select_beta_list[ind_set]
RF_set_name = set_name_list[ind_set]

for gas_name in gas_name_list:

    title = 'set ' + RF_set_name + ': '
    if RF_type == 'electric_transverse':
        title += '$E_{RF}$=' + str(E_RF_kVm) + 'kV/m, $\\alpha$=' + str(alpha) + ', $\\beta$=' + str(beta)
    elif RF_type == 'magnetic_transverse':
        title += '$B_{RF}$=' + str(B_RF) + 'T, $\\alpha$=' + str(alpha) + ', $\\beta$=' + str(beta)
    title += ', ' + gas_name
    print(title)

    set_name = ''
    if use_RF is False:
        set_name += 'without_RF'
    else:
        if RF_type == 'electric_transverse':
            set_name += 'ERF_' + str(E_RF_kVm)
        elif RF_type == 'magnetic_transverse':
            set_name += 'BRF_' + str(B_RF)
        set_name += '_alpha_' + str(alpha)
        set_name += '_beta_' + str(beta)
    if absolute_velocity_sampling_type == 'const_vth':
        set_name = 'const_vth_' + set_name
    if r_0 > 0:
        set_name += '_r0_' + str(r_0) + '_' + set_name
    # set_name += '_antiresonant'
    set_name += '_' + gas_name

    save_dir_curr = save_dir + set_name

    # load runs data
    data_dict_file = save_dir_curr + '.pickle'
    with open(data_dict_file, 'rb') as fid:
        data_dict = pickle.load(fid)
    settings_file = save_dir + 'settings.pickle'
    with open(settings_file, 'rb') as fid:
        settings = pickle.load(fid)
    field_dict_file = save_dir + 'field_dict.pickle'
    with open(field_dict_file, 'rb') as fid:
        field_dict = pickle.load(fid)

    for key in data_dict.keys():
        data_dict[key] = np.array(data_dict[key])

    # divide the phase space by the angle
    theta_LC = 360 / (2 * np.pi) * np.arcsin(1 / np.sqrt(field_dict['Rm']))
    N_theta_LC = 1
    N_theta_T = 1
    N_theta = 2 * N_theta_LC + N_theta_T
    dtheta_LC = theta_LC / N_theta_LC
    dtheta_T = (180 - 2 * theta_LC) / N_theta_T
    theta_bins_max_list = [dtheta_LC]
    for i in range(N_theta_LC - 1):
        theta_bins_max_list += [theta_bins_max_list[-1] + dtheta_LC]
    for i in range(N_theta_T):
        theta_bins_max_list += [theta_bins_max_list[-1] + dtheta_T]
    for i in range(N_theta_LC):
        theta_bins_max_list += [theta_bins_max_list[-1] + dtheta_LC]
    theta_bins_min_list = [0] + theta_bins_max_list[:-1]

    number_of_time_intervals = data_dict['t'].shape[1]

    particles_counter_mat_3d = np.zeros([N_theta, N_theta, number_of_time_intervals])
    particles_counter_mat2_3d = np.zeros([N_theta, N_theta, number_of_time_intervals])

    from matplotlib import cm

    colors = cm.rainbow(np.linspace(0, 1, number_of_time_intervals))
    # colors = ['b', 'g', 'r']
    # colors = ['r', 'g', 'b']

    for ind_t in range(number_of_time_intervals):
        # for ind_t in [0, 10]:
        # for ind_t in [0, 1]:
        # for ind_t in [0, 10, 20]:
        #     print(ind_t)

        inds_particles = range(data_dict['t'].shape[0])
        # inds_particles = [0, 1, 2]
        # inds_particles = range(1001)
        if ind_t == 0:
            print('num particles = ' + str(len(inds_particles)))

        v = data_dict['v'][inds_particles, ind_t]
        v0 = data_dict['v'][inds_particles, 0]
        vt = data_dict['v_transverse'][inds_particles, ind_t]
        vt0 = data_dict['v_transverse'][inds_particles, 0]
        vz = data_dict['v_axial'][inds_particles, ind_t]
        vz0 = data_dict['v_axial'][inds_particles, 0]
        theta = np.mod(360 / (2 * np.pi) * np.arctan(vt / vz), 180)
        Bz = data_dict['Bz'][inds_particles, ind_t]
        Bz0 = data_dict['Bz'][inds_particles, 0]
        vt_adjusted = vt * np.sqrt(
            Bz0 / Bz)  # no need to adjust v to B_min because energy is conserved (assuming no RF)

        det = vz ** 2.0 + vt ** 2.0 * (1 - Bz0 / Bz)
        inds_positive = np.where(det > 0)[0]
        vz_adjusted = np.zeros(len(inds_particles))
        vz_adjusted[inds_positive] = np.sign(vz0[inds_positive]) * np.sqrt(det[inds_positive])

        theta_adjusted = 90.0 * np.ones(len(inds_particles))
        theta_adjusted[inds_positive] = np.mod(
            360 / (2 * np.pi) * np.arctan(vt_adjusted[inds_positive] / vz_adjusted[inds_positive]), 180)

        color = colors[ind_t]

        # track if a particle left the population, and then cancel counting it for the following times
        if ind_t == 0:
            particles_counter_mat = np.zeros([N_theta, N_theta])
            inds_bins_ini = []
            cancelled_particles = np.zeros(len(inds_particles))
        particles_counter_mat2 = np.zeros([N_theta, N_theta])

        for ind_p in inds_particles:
            # if not cancelled_particles[ind_p]:
            theta_curr = theta_adjusted[ind_p]
            ind_bin_fin = [k for k, (t1, t2) in enumerate(zip(theta_bins_min_list, theta_bins_max_list))
                           if theta_curr > t1 and theta_curr <= t2][0]
            if ind_t == 0:
                inds_bins_ini += [ind_bin_fin]
                particles_counter_mat[ind_bin_fin, ind_bin_fin] += 1

            ind_bin_ini = inds_bins_ini[ind_p]

            particles_counter_mat2[ind_bin_ini, ind_bin_fin] += 1
            if ind_bin_fin != ind_bin_ini:
                if not cancelled_particles[ind_p]:
                    particles_counter_mat[ind_bin_ini, ind_bin_ini] -= 1
                    particles_counter_mat[ind_bin_ini, ind_bin_fin] += 1
                    cancelled_particles[ind_p] = 1

        if ind_t == 0:
            N0 = copy.deepcopy(np.diag(particles_counter_mat))

        particles_counter_mat_3d[:, :, ind_t] = particles_counter_mat
        particles_counter_mat2_3d[:, :, ind_t] = particles_counter_mat2

    # divide all densities by the parent initial density
    for ind_t in range(number_of_time_intervals):
        for ind_bin in range(N_theta):
            particles_counter_mat_3d[ind_bin, :, ind_t] /= (1.0 * N0[ind_bin])
            particles_counter_mat2_3d[ind_bin, :, ind_t] /= (1.0 * N0[ind_bin])
    particles_counter_mat2_for_fit_3d = copy.deepcopy(particles_counter_mat2_3d)

    t_array = data_dict['t'][0]
    # t_array /= settings['l'] / settings['v_th']
    # t_array /= settings['l'] / settings['v_th_for_cyc']
    # define v_th ref
    _, _, mi, _, Z_ion = define_plasma_parameters(gas_name='tritium')
    v_th_ref = get_thermal_velocity(settings['T_keV'] * 1e3, mi, settings['kB_eV'])
    t_array /= settings['l'] / v_th_ref

    colors = cm.rainbow(np.linspace(0, 1, N_theta))
    nu_decay_list = []
    nu_mat = np.zeros([N_theta, N_theta])

    do_fit = True
    # do_fit = False

    inds_t_array = range(len(t_array))
    fig, ax = plt.subplots(1, 1,
                           figsize=(6, 6),
                           )
    # fig.suptitle(title)

    ## calculate the saturation value to estimate the rate
    # inds_t_saturation = range(7, 21)
    # inds_t_saturation = range(2, 3)
    inds_t_saturation = range(15, 31)
    # inds_t_saturation = range(len(t_array))

    N_curr = particles_counter_mat2_3d[0, 1, :]
    saturation_value = np.mean(N_curr[inds_t_saturation])
    label = '$\\bar{N}_{rc}$'
    label += '=' + '{:.3f}'.format(saturation_value)
    ax.plot(t_array, N_curr, color='b', linestyle='-', label=label)
    ax.hlines(saturation_value, t_array[inds_t_saturation[0]], t_array[inds_t_saturation[-1]],
              color='b', linewidth=2, linestyle='--')

    N_curr = particles_counter_mat2_3d[2, 1, :]
    saturation_value = np.mean(N_curr[inds_t_saturation])
    label = '$\\bar{N}_{lc}$'
    label += '=' + '{:.3f}'.format(saturation_value)
    ax.plot(t_array, N_curr, color='g', linestyle='-', label=label)
    ax.hlines(saturation_value, t_array[inds_t_saturation[0]], t_array[inds_t_saturation[-1]],
              color='g', linewidth=2, linestyle='--')

    N_curr = particles_counter_mat2_3d[1, 0, :]
    saturation_value = np.mean(N_curr[inds_t_saturation])
    label = '$\\bar{N}_{cr}$'
    label += '=' + '{:.3f}'.format(saturation_value)
    ax.plot(t_array, N_curr, color='r', linestyle='-', label=label)
    ax.hlines(saturation_value, t_array[inds_t_saturation[0]], t_array[inds_t_saturation[-1]],
              color='r', linewidth=2, linestyle='--')

    N_curr = particles_counter_mat2_3d[1, 2, :]
    saturation_value = np.mean(N_curr[inds_t_saturation])
    label = '$\\bar{N}_{cl}$'
    label += '=' + '{:.3f}'.format(saturation_value)
    ax.plot(t_array, N_curr, color='orange', linestyle='-', label=label)
    ax.hlines(saturation_value, t_array[inds_t_saturation[0]], t_array[inds_t_saturation[-1]],
              color='orange', linewidth=2, linestyle='--')

    # ax.plot(t_array, particles_counter_mat2_3d[2, 1, :], color='g', linestyle='-', label='$\\bar{N}_{lc}$')
    # ax.plot(t_array, particles_counter_mat2_3d[1, 0, :], color='r', linestyle='-', label='$\\bar{N}_{cr}$')
    # ax.plot(t_array, particles_counter_mat2_3d[1, 2, :], color='orange', linestyle='-', label='$\\bar{N}_{cl}$')

    # ax.set_xlabel('$t \\cdot v_{th} / l$')
    # ax.set_xlabel('$t \\cdot v_{th,T} / l$')
    # ax.set_xlabel('$t / \\tau_{th}$',
    #               fontsize=20)
    # ax.set_ylim([0, 0.9])
    ax.set_ylim([0, 1.0])
    ax.set_xlim([0, 1.75])
    # ax.set_title(gas_name)
    # ax.set_title(title)
    ax.legend(loc='upper left',
              fontsize=20)
    # ax.legend(loc='center right', fontsize=16)
    # ax.legend(fontsize=16)
    ax.grid(True)
    # text = '(a)'
    if gas_name == 'deuterium':
        gas_name_shorthand = 'D'
    if gas_name == 'tritium':
        gas_name_shorthand = 'T'
    # text = '(' + gas_name_shorthand + ',' + RF_set_name + ')'
    text = RF_set_name + ' (' + gas_name_shorthand + ')'
    plt.text(0.99, 0.98, text, fontdict={'fontname': 'times new roman', 'weight': 'bold', 'size': 30},
             horizontalalignment='right', verticalalignment='top', color='k',
             transform=fig.axes[0].transAxes)
    # fig.set_tight_layout({'pad': 0.5, 'rect': (0, 0, 1, 0.95)})
    fig.set_layout_engine(layout='tight')

    ## save plots to file
    # save_fig_dir = '../../../Papers/texts/paper2022/pics/'
    # file_name = 'saturation_set_' + gas_name_shorthand + '_' + RF_set_name
    # if RF_type == 'magnetic_transverse':
    #     file_name = 'BRF_' + file_name
    # # file_name += '_mod'
    # beingsaved = plt.gcf()
    # beingsaved.savefig(save_fig_dir + file_name + '.eps', format='eps')


# coding: utf-8
# C10tk.py - Animer des formes

from tkinter import *

maFenetre=Tk()
maFenetre.title('Fenetre avec widgets')
maFenetre.geometry('600x600+150+100')

def animation():
   global posX, posY              # définition de variations qui auront une portée sur tout le programme
   if posX<=320:
      posX,posY=posX+1,posY
      canevas.coords(Balle,posX,posY, posX+30,posY+30)
      maFenetre.after(10, animation)

canevas=Canvas(maFenetre, width=400,height=500,bg='green')
cadre=Frame(maFenetre,borderwidth=2,width=200,height=500,relief=GROOVE,bg='white')
Etiquette=Label(cadre, text="Hello World !",fg="navy",bg="yellow")
bouton_Quitter=Button(cadre,text="Quitter", command=maFenetre.destroy)
bouton_Demarrer=Button(cadre,text="Démarrer l'animation", command=animation)

# Définition de la position de départ
posX=10
posY=250

# Créaction d'un cercle appelé balle en position posX,posY
Balle=canevas.create_oval(posX,posY,posX+30,posY+30,fill="orange")

cadre.pack(side=RIGHT,padx=5,pady=5)
cadre.pack_propagate(0)
canevas.pack(side=LEFT,padx=5,pady=5)

Etiquette.pack(side=TOP,padx=5,pady=5)
bouton_Quitter.pack(side=BOTTOM,padx=5,pady=5)
bouton_Demarrer.pack(side=BOTTOM,padx=5,pady=5)

maFenetre.mainloop()