#from numba import njit # compile python
#import matplotlib
#matplotlib.rcParams['text.usetex'] = True
import matplotlib.pyplot as plt # plotting facility
from matplotlib.colors import Normalize, SymLogNorm
from matplotlib import cm
from matplotlib import gridspec
import numpy as np
import os, datetime, math
import time
import scipy.fftpack as fftpack
from scipy.fftpack import fft, ifft

def my_function():
    print("Hello World from Wigner plot")

# psi  = ((np.array(wavefunctions)[jj,:])*einsen)
# psiC = ((np.array(wavefunctions)[jj,:])*einsen).conj()
# W  = np.copy(psi)
# WC =  np.copy(psiC)

# Xn = XCoord.size
# Pn = PCoord.size
# pMax = abs(PCoord[0])
# xMax = abs(XCoord[0])

# PCoord = PCoord.reshape(PCoord.size,1)
# XCoord = XCoord.reshape(1,XCoord.size)

# #phase_shear_y  = np.exp(+1j * XCoord * PCoord * Xn * Pn  /xMax**2 / pMax**2  * np.pi*392968/1000000 )
# # X_gridDIM OK    # P_gridDIM OK    # pMax OK    # xMax OK

# phase_shear_y  = np.exp(+1j * XCoord * PCoord * Xn * Pn /xMax**2 /pMax**2 * np.pi**2/8 )
# phase_shear_ym = phase_shear_y.conj()

def W__by_operator(wavefunctions,jj,rescaler,einsen,dP,P_gridDIM,XCoord,PCoord):
    """ Wigner distribution determined by roll-over loop
    """

    psi  = ((np.array(wavefunctions)[jj,:])*einsen)
    psiC = ((np.array(wavefunctions)[jj,:])*einsen).conj()
    W  = np.copy(psi)
    WC =  np.copy(psiC)

    Xn = XCoord.size
    Pn = PCoord.size
    pMax = abs(PCoord[0])
    xMax = abs(XCoord[0])

    PCoord = PCoord.reshape(PCoord.size,1)
    XCoord = XCoord.reshape(1,XCoord.size)

    #phase_shear_y  = np.exp(+1j * XCoord * PCoord * Xn * Pn  /xMax**2 / pMax**2  * np.pi*392968/1000000 )
    # X_gridDIM OK    # P_gridDIM OK    # pMax OK    # xMax OK

    phase_shear_y  = np.exp(+1j * XCoord * PCoord * Xn * Pn /xMax**2 /pMax**2 * np.pi**2/8 )
    phase_shear_ym = phase_shear_y.conj()

    W = fft(W, axis=1, overwrite_x=True)
    W = fftpack.fftshift(W,axes=1)
    W *= phase_shear_ym
    W = fftpack.ifftshift(W,axes=1)
    W = ifft(W, axis=1, overwrite_x=True)

    WC = fft(WC, axis=1, overwrite_x=True)
    WC = fftpack.fftshift(WC,axes=1)
    WC *= phase_shear_y
    WC = fftpack.ifftshift(WC,axes=1)
    WC = ifft(WC, axis=1, overwrite_x=True)

    W = fftpack.ifftshift(fftpack.ifft(fftpack.fftshift(W*WC,axes=0),axis=0),axes=0) / dP

    # perform the checks
    assert np.linalg.norm(W.imag.reshape(-1), np.infty), "there should be no imaginary part"
    assert (W.real <= 2.).all() and (W.real > -2.).all(), "The Cauchy-Schwarz inequality is violated"

    return W#.real

def W_carved_by_hand(wavefunctions,jj,rescaler,einsen,dP,P_gridDIM):
    """ Wigner distribution determined by roll-over loop
    """
    psi = ((np.array(wavefunctions)[jj,:])*einsen)
    Wdist = np.copy(psi)

    for rollParameter in range(0,P_gridDIM):
        smoothRollover = (rollParameter-P_gridDIM/2)*rescaler
        discreteRollover = int(round(smoothRollover))
        fractionRoll = smoothRollover-discreteRollover
        DRollover = int(np.sign(fractionRoll))

        Wdist[rollParameter][:] = (1-abs(fractionRoll))*(np.roll(psi[rollParameter,:],-discreteRollover)).conj() * (np.roll(psi[rollParameter,:],discreteRollover)) + abs(fractionRoll)*(np.roll(psi[rollParameter,:],-discreteRollover-DRollover)).conj() * (np.roll(psi[rollParameter,:],discreteRollover+DRollover))

        #This simpler assignment gives 'ghost images' in W!
        #Wdist[rollParameter][:] = np.roll(psi[rollParameter,:],-discreteRollover).conj() * np.roll(psi[rollParameter,:],discreteRollover)

    Wdist = fftpack.ifftshift(fftpack.ifft(fftpack.fftshift(Wdist,axes=0),axis=0),axes=0) / dP
    return Wdist.real

def multicolor_ylabel(ax,list_of_strings,list_of_colors,axis='x',anchorpad=0,**kw):
    """this function creates axes labels with multiple colors
    ax specifies the axes object where the labels should be drawn
    list_of_strings is a list of all of the text items
    list_if_colors is a corresponding list of colors for the strings
    axis='x', 'y', or 'both' and specifies which label(s) should be drawn
    https://stackoverflow.com/questions/33159134/matplotlib-y-axis-label-with-multiple-colors#33162465
    """
    from matplotlib.offsetbox import AnchoredOffsetbox, TextArea, HPacker, VPacker

    # x-axis label
    if axis=='x' or axis=='both':
        boxes = [TextArea(text, textprops=dict(color=color, ha='left',va='bottom',**kw))
                    for text,color in zip(list_of_strings,list_of_colors) ]
        xbox = HPacker(children=boxes,align="center",pad=0, sep=5)
        anchored_xbox = AnchoredOffsetbox(loc=3, child=xbox, pad=anchorpad,frameon=False,bbox_to_anchor=(0.2, -0.09),
                                          bbox_transform=ax.transAxes, borderpad=0.)
        ax.add_artist(anchored_xbox)

    # y-axis label
    if axis=='y' or axis=='both':
        boxes = [TextArea(text, textprops=dict(color=color, ha='left',va='bottom',rotation=90,**kw))
                     for text,color in zip(list_of_strings[::-1],list_of_colors[::-1]) ]
        ybox = VPacker(children=boxes,align="center", pad=0, sep=5)
        anchored_ybox = AnchoredOffsetbox(loc=3, child=ybox, pad=anchorpad, frameon=False, bbox_to_anchor=(-0.05*1, -0.05),
                                          bbox_transform=ax.transAxes, borderpad=0.)
        ax.add_artist(anchored_ybox)

def Projection_variableDirection(W,direction,dX,dP):
    if direction=='x':
        return (W).sum(axis=0)*dP
    if direction=='p':
        return (W).sum(axis=1)*dX
    else:
        print('Neither "x" nor "p" projection?')
        sys.exit()

def Hamiltonian_t(W,time,potentialVec,posVec,momVec,dX,dP,nonLinearWeight,NLSEexp,KerrCase=False):
    '''Time-dependent Hamiltonian, term 0*XoldCoord to broadcast matrix for V(x)=0'''

    probX =  Projection_variableDirection(W,'x',dX,dP)
    if KerrCase == True:
        #print("kerr case = true")
        return (momVec**2/2 + posVec**2/2 )**2
    else:
        #print("kerr case = false")
        return momVec**2/2 + 2*nonLinearWeight/(NLSEexp+2)*probX**(NLSEexp/2) + potentialVec

def PlotWignerDistr_Projections_Title(W,time,XcoordVec,PcoordVec,zoomFactorX,zoomFactorP,bondarsNewPropagator,title,potVec,gamma,smallProb=0,ProbMax=-1,numberOfPeaks=1,NLSEexp=2,KerrCase=False):
    '''zoomFactor = 1 ~ no zoom, or above 1: zoomed in
     'unbalanced' figsize, e.g. (8,5), gives (buggy) 'ghost grids' in image
    ProbMax = max(harmonic_osc.wavefunction*harmonic_osc.wavefunction.conj()) = Maximum of density P(x)
    '''

    lsize=30 #LabelSize
    fsize=40 #FontSize

    P_gridDIM,X_gridDIM = W.shape

    XMin = XcoordVec[0]
    XMax = XcoordVec[-1]
    dX = (XMax-XMin)/(X_gridDIM-1)

    PMin = PcoordVec[0]
    PMax = PcoordVec[-1]
    dP = (PMax-PMin)/(P_gridDIM-1)

    x_min =  XMin/zoomFactorX
    x_max =  XMax/zoomFactorX
    p_min =  PMin/zoomFactorP
    p_max =  PMax/zoomFactorP

    if bondarsNewPropagator == False:
        W=fftpack_fftshift(W, bondarsNewPropagator)

    Pr_x = Projection_variableDirection(W,'x',dX,dP)
    Pr_p = Projection_variableDirection(W,'p',dX,dP)

    print("############################################# Kerrcase value in plot routine:",KerrCase)
    EnergyLandscape = Hamiltonian_t(W,time,potVec,XcoordVec,PcoordVec[:,np.newaxis],dX,dP,gamma,NLSEexp,KerrCase)

    EnergyLandscape = EnergyLandscape[round(P_gridDIM*(1-1/zoomFactorP)/2):round(P_gridDIM*(1+1/zoomFactorP)/2),\
                  round(X_gridDIM*(1-1/zoomFactorX)/2):round(X_gridDIM*(1+1/zoomFactorX)/2)]

    W=W[round(P_gridDIM*(1-1/zoomFactorP)/2):round(P_gridDIM*(1+1/zoomFactorP)/2),\
                  round(X_gridDIM*(1-1/zoomFactorX)/2):round(X_gridDIM*(1+1/zoomFactorX)/2)]

    fig=plt.figure(1,figsize=((15,15)))

    gs = gridspec.GridSpec(3,3, width_ratios=[0.0001,0.475,0.1],height_ratios=[0.0001,2,0.4])
    ax = plt.subplot(gs[1,1])

    global_color_max = W.max() *0 + 1./3.14
    global_color_min = W.min() *0 - 1./3.14

    axp = ax.imshow( W ,origin='lower',interpolation='none',
                    extent=[ x_min , x_max, p_min, p_max]
                    ,vmin=-global_color_max,vmax=global_color_max, cmap=cm.seismic)

    cbaxes = fig.add_axes([0.05-0.04, 0.3, 0.007, 0.5])  # [xo,yo,Dx,Dy] position for the colorbar
    cb1 = plt.colorbar(axp, cax = cbaxes)
    cb1.ax.tick_params(labelsize=int(lsize/1.0))

    ax.set_aspect(XMax/PMax*zoomFactorP/zoomFactorX)
    ax.tick_params('x', colors='black',labelsize=lsize)
    ax.tick_params('y', colors='black',labelsize=lsize)

    plt.suptitle(title,color='black',fontsize=fsize-20)

    ax.set_ylabel('Momentum P', fontsize=fsize)
    ax.yaxis.tick_right()
    ax.set_xlabel('Position X', fontsize=fsize)
    ax.xaxis.set_label_position("top")

    ax.contour( EnergyLandscape ,
    np.arange(1, 2701, 55 ),origin='lower',extent=[x_min,x_max,p_min,p_max],
    linewidths=0.25,colors='k')

    ax1 = plt.subplot(gs[1,2], sharey=ax)
    ax1.plot(Pr_p,PcoordVec,'g')
#    ax1.set_xlabel('|ψ(p)|\u00b2', color='g',fontsize=fsize)
    ax1.set_xlabel(r'$|\tilde\psi(p)|^2$', color='g', fontsize=fsize)
    ax1.tick_params('x', colors='g',labelsize=lsize)
    ax1.tick_params('y', colors='g',labelsize=0) #suppress shared axis labels
    ax1.yaxis.grid(which="major", color='g', linestyle='-', linewidth=1)
    ax1.set_ylim([p_min,p_max])

    ax2 = plt.subplot(gs[2,1])
#    ax2.set_ylabel(r'$|\psi(x)|^2$', color='b', fontsize=fsize)#, horizontalalignment='left')
    if ProbMax > 0: # if a positive argument is passed the y-axis is fixed to [0,ProbMax]
        ax2.axes.set_ylim([0,ProbMax])
        multicolor_ylabel(ax2,(r'$|\psi(x)|^2$',r'[%.3f]'%ProbMax),('b','r'),axis='y',size=fsize)#,weight='bold')
        oneline = np.copy(Pr_x)
        oneline.fill(smallProb)
        ax2.plot(XcoordVec,oneline,color='r', linestyle='dotted', linewidth=1.51,alpha=1.0)
        oneline.fill(smallProb*numberOfPeaks*2)
        ax2.plot(XcoordVec,oneline,color='r', linewidth=1.51,alpha=1.0)
    else:
        ax2.set_ylabel(r'$|\psi(x)|^2$', color='b', fontsize=fsize)#, horizontalalignment='left')

    ax2.yaxis.tick_right()
    ax2.plot(XcoordVec, Pr_x,'b',linewidth=2)

    ax2.tick_params('y', colors='b',labelsize=lsize)
    ax2.tick_params('x', colors='b',labelsize=0*lsize)
    ax2.set_xlim([x_min,x_max])

    ax.xaxis.grid(which="major", color='black', linestyle='-', linewidth=1)
    ax.yaxis.grid(which="major", color='gray', linestyle='-.', linewidth=1)
    ax1.yaxis.grid(which="major", color='gray', linestyle='-.', linewidth=1)
    ax2.xaxis.grid(which="major", color='black', linestyle='-', linewidth=1)

    return fig,ax

def PlotWignerProjNOTitle(W,time,XcoordVec,PcoordVec,zoomFactorX,zoomFactorP,bondarsNewPropagator,title,potVec,gamma,NLSEexp=2):
    '''zoomFactor = 1 ~ no zoom, or above 1: zoomed in'''

    lsize=20 #LabelSize
    fsize=20 #FontSize

    P_gridDIM,X_gridDIM = W.shape

    XMin = XcoordVec[0]
    XMax = XcoordVec[-1]
    dX = (XMax-XMin)/(X_gridDIM-1)

    PMin = PcoordVec[0]
    PMax = PcoordVec[-1]
    dP = (PMax-PMin)/(P_gridDIM-1)

    x_min =  XMin/zoomFactorX
    x_max =  XMax/zoomFactorX
    p_min =  PMin/zoomFactorP
    p_max =  PMax/zoomFactorP

    if bondarsNewPropagator == False:
        W=fftpack_fftshift(W, bondarsNewPropagator)

    Pr_x = Projection_variableDirection(W,'x',dX,dP)
    Pr_p = Projection_variableDirection(W,'p',dX,dP)

    EnergyLandscape = Hamiltonian_t(W,time,potVec,PcoordVec[:,np.newaxis],dX,dP,gamma,NLSEexp)

    EnergyLandscape = EnergyLandscape[round(P_gridDIM*(1-1/zoomFactorP)/2):round(P_gridDIM*(1+1/zoomFactorP)/2),\
                  round(X_gridDIM*(1-1/zoomFactorX)/2):round(X_gridDIM*(1+1/zoomFactorX)/2)]

    W=W[round(P_gridDIM*(1-1/zoomFactorP)/2):round(P_gridDIM*(1+1/zoomFactorP)/2),\
                  round(X_gridDIM*(1-1/zoomFactorX)/2):round(X_gridDIM*(1+1/zoomFactorX)/2)]

    fig=plt.figure(1,figsize=((15,15)))

    gs = gridspec.GridSpec(3,3, width_ratios=[0.0001,0.475,0.1],height_ratios=[0.0001,2,0.4])
    ax = plt.subplot(gs[1,1])

    global_color_max = W.max()
    global_color_min = W.min()

    axp = ax.imshow( W ,origin='lower',interpolation='none',
                    extent=[ x_min , x_max, p_min, p_max]
                    ,vmin=-global_color_max,vmax=global_color_max, cmap=cm.seismic)

    # AVOID color bar (with large tick labels)
    # cbaxes = fig.add_axes([0.09, 0.3, 0.01, 0.5]) #[left, bottom, width, height] out of {0..1}
    # cb1 = plt.colorbar(axp, cax = cbaxes)
    # cbaxes.yaxis.set_ticks_position('left')
    # cb1.ax.tick_params(labelsize=int(lsize/1.0))
    cbaxes = fig.add_axes([0.05, 0.3, 0.007, 0.5])  # [xo,yo,Dx,Dy] position for the colorbar
    cb1 = plt.colorbar(axp, cax = cbaxes)
    cb1.ax.tick_params(labelsize=int(lsize/1.5))

    ax.set_aspect(XMax/PMax*zoomFactorP/zoomFactorX)
    ax.tick_params('x', colors='black',labelsize=lsize)
    ax.tick_params('y', colors='black',labelsize=lsize)

    ax.set_ylabel('Momentum $p$', fontsize=fsize)
    ax.yaxis.tick_right()
    ax.set_xlabel('Position $x$', fontsize=fsize)
    ax.xaxis.set_label_position('top')

    ax.contour( EnergyLandscape ,
    np.arange(1, 2701, 55 ),origin='lower',extent=[x_min,x_max,p_min,p_max],
    linewidths=0.25,colors='k')

    ax1 = plt.subplot(gs[1,2], sharey=ax)
    ax1.plot(Pr_p,PcoordVec,'g')
#    ax1.set_xlabel('|ψ(p)|\u00b2', color='g',fontsize=fsize)
    ax1.set_xlabel(r'$|\tilde\psi(p)|^2$', color='g', fontsize=fsize)
#    ax.set_ylabel('\\textit{Velocity (\N{DEGREE SIGN}/sec)}', fontsize=fsize)
    ax1.tick_params('x', colors='g',labelsize=lsize)
    ax1.tick_params('y', colors='g',labelsize=0) #suppress shared axis labels
    ax1.yaxis.grid(which="major", color='green', linestyle='-', linewidth=1)
    ax1.xaxis.grid(which="major", color='gray', linestyle='-', linewidth=1)
    plt.xticks([0, (round(10*Pr_p.max()-0.5))/10.0 ])
    ax1.set_ylim([p_min,p_max])

    ax2 = plt.subplot(gs[2,1], sharex=ax)
#    ax2.set_ylabel('|ψ($x$)|\u00b2', color='b',fontsize=fsize)
    ax2.set_ylabel(r'$|\psi(x)|^2$', color='b', fontsize=fsize)
    ax2.yaxis.tick_right()
    ax2.plot(XcoordVec, Pr_x,'b',linewidth=2)

    ax2.tick_params('y', colors='b',labelsize=lsize)
    ax2.tick_params('x', colors='b',labelsize=0*lsize)
    ax2.set_xlim([x_min,x_max])

    ax.xaxis.grid(which="major", color='black', linestyle='-', linewidth=1)
    ax.yaxis.grid(which="major", color='gray', linestyle='-.', linewidth=1)
    ax1.yaxis.grid(which="major", color='gray', linestyle='-.', linewidth=1)
    ax2.xaxis.grid(which="major", color='black', linestyle='-', linewidth=1)

    return fig,ax


"""
이름, 주민번호 (950101-1), 주소를 입력받아서
회원명부를 관리하는 어플을 제작하고자 한다.
출력되는 결과는 다음과 같다.
### 자기소개어플 ###
********************************
이름: 홍길동
나이: 25세 (만나이)
성별: 남성
주소: 서울
********************************
"""

class Person(object):

    def __init__(self, name, num, adress):
        self.name = name
        self.age = 0
        self.num = num
        self.sex = ""
        self.adress = adress

    def __str__(self):
        return f"{self.name} {self.age} {self.num} {self.sex} {self.adress}"

    def set_age(self):
        current = 2022
        year = int(self.num[:2]) #인덱스 0,1은 출생년도
        sex_checker = int(self.num[6]) #7은 성별판별번호 인덱스
        if sex_checker == 1 or sex_checker == 2:
            year += 1900
            if sex_checker == 1:
                self.sex = "남성"
            else:
                self.sex = "여성"
        elif sex_checker == 3 or sex_checker == 4:
            year += 2000
            if sex_checker == 3:
                self.sex = "남성"
            else:
                self.sex = "여성"
        self.age = current - year

    @staticmethod
    def result(ls):
        print(" ### 자기소개어플 ### ")
        print("*********************************")
        print(" 이름  나이  성별  주소  ")
        [print(i) for i in ls]
        print("*********************************")

    @staticmethod
    def delete(ls, name):
        for i,j in enumerate(ls):
            if j.name == name:
                del ls[i]

    @staticmethod
    def new_person():
        return Person(input(" 이름 : "), input(" 주민번호 : "), input(" 주소 : "))


"""
This is done watching the video 5 Mini Python Projects - For Beginners on https://www.youtube.com/watch?v=DLn3jOsNRVE
I watched the videos and after that did the project not looking the actual codes.

25:05 | Project #2 - Number Guessing Game

---

pick a random number

then ask the user to guess this number and ask it with while.

then give feedback to the user whether it is greater or less than the number

Let's ask in which interval the useryou want to guess

tell the user how many times he did try to guess the number correctly
"""

import random

class PrintColored:
    """
    CLASS:
    Coloring the printed text in the terminal LINK:https://www.geeksforgeeks.org/print-colors-python-terminal/
    ANSI Escape Sequence is used

    :param color: str - text to be colored
    :return:
    """

    def __init__(self, color):
        self.color = color

    def red(self): print(f"\033[91m{self.color}\033[00m")

    def green(self): print(f"\033[92m{self.color}\033[00m")

    def yellow(self): print(f"\033[93m{self.color}\033[00m")

    def light_purple(self): print(f"\033[94m{self.color}\033[00m")

    def purple(self): print(f"\033[95m{self.color}\033[00m")

    def cyan(self): print(f"\033[96m{self.color}\033[00m")

    def light_gray(self): print(f"\033[97m{self.color}\033[00m")

    def black(self): print(f"\033[98m{self.color}\033[00m")

def start_the_guess(top_number):
    """
    Starting the game

    Variables:
    @random_number: int - select randomly a number between 1 to @top_number
    @user_guess: int - users' guess
    @user_already_guess: list - users' guess will be listed in here
    :param top_number: int - users picked integer to create an interval
    :return:
    """

    random_number = random.randint(1, top_number)
    user_guess = 0
    user_already_guess = []
    while random_number != user_guess:
        try:
            user_guess = int(input("What is your guess: "))
            if user_guess in user_already_guess:
                PrintColored(f"You already pick the number {user_guess}, continue to try...").yellow()
            else:
                if user_guess < random_number:
                    user_already_guess.append(user_guess)
                    user_already_guess.sort()
                    PrintColored("\u2193 Low!").red()
                    print(f"Guess list: {user_already_guess}\n")
                if user_guess > random_number:
                    user_already_guess.append(user_guess)
                    user_already_guess.sort()
                    PrintColored("\u2191 High!").red()
                    print(f"Guess list: {user_already_guess}\n")
        except:
            print("Write an integer")
    PrintColored(
        f"\u2713 Yey! After {len(user_already_guess)} time\\s try, you find the number and it was {random_number}.").green()

def main():
    """
    This is the main body, and it asks users whether they want to play or not.

    Variables:
    @user_answer: str - is the users' answer
    @top_number: int - top end which represent the interval
    :return:
    """
    while True:
        user_answer = input(
            "Do you want to play the number of guessing game? Write initial of Yes (y), No (n), Quit (q): \n").lower()
        if user_answer == "y":
            try:
                top_number = int(
                    input("In which interval you want to guess a number? Write an integer greater than zero: \n"))
                if top_number < 1:
                    print("You should write an integer greater than zero!")
                    break
                elif top_number == 1:
                    print(f"You pick {top_number} but there is no interval to guess between 1 and {top_number}!")
                    break
                else:
                    print(f"You pick {top_number} and starting the guessing game...\n")
                    start_the_guess(top_number)
                    return True
            except:
                print("Please write an integer...")
        elif user_answer == "n" or user_answer == "q":
            if user_answer == "n":
                print("Okay, you don't want to play the game and quit!")
            if user_answer == "q":
                print("You quit the game!")
            quit()
        else:
            print("Please write your decision as y, n, q...")

main()


# name = 'trứng rán'
# name = 'bắp'
# name = 'bơ'
# name = 'mỡ'
# name = 'mắm tôm'
# # list, array
mon_an = ['trung ran', 'bap', 'bo', 'mo', 'mam tom','bun cha']
# print(mon_an)
# name = 'sushi'
# mon_an.append(name)
# print(mon_an)
# mon_an [6] = 'banh gio'
# print(mon_an)
# # for i in range(len(mon_an)):
# #     print(mon_an[i])
# # print('------')
# for value in mon_an:
#     print(value)

# for i in range (len,(mon_an)):
#     print(i+1, mon_an[i])
#     or

deleted_item = mon_an.pop()
print(deleted_item)
# for index, value in enumerate(mon_an):
#     print(index+1, value)
# old_value = input('Enter the dish you want to edit')
# value = input('new value')
# index = mon_an.index(old_value)
# mon_an[index] = value
# for index, value in enumerate(mon_an):
#     print(index+1, value)


from collections import deque

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

R, C = map(int, input().split())

arr = [list(input()) for _ in range(R)]
visited = [[0] * C for _ in range(R)]
w_visited = [[0] * C for _ in range(R)]

def bfs(start, end, w):
    e_x, e_y = end.pop()
    x, y, cnt = start.popleft()

    for i in range(4):
        if 0 <= x+dx[i] < R and 0 <= y+dy[i] < C:
            if arr[x+dx[i]][y+dy[i]] == '.' or arr[x+dx[i]][y+dy[i]] == 'D':
                start.append([x+dx[i], y+dy[i], cnt+1])
                visited[x+dx[i]][y+dy[i]] = 1

    water_cnt = 1
    while start:
        x, y, cnt = start.popleft()

        if water_cnt == cnt:
            for i in range(R):
                for j in range(C):
                    if arr[i][j] == '*':
                        w_visited[i][j] = 1
                        for k in range(4):
                            if 0 <= i+dx[k] < R and 0 <= j+dy[k] < C:
                                if w_visited[i+dx[k]][j+dy[k]] == 0:
                                    if arr[i+dx[k]][j+dy[k]] == '.' or arr[i+dx[k]][j+dy[k]] == 'S':
                                        w_visited[i+dx[k]][j+dy[k]] = 1
                                        w.append([i+dx[k], j+dy[k]])

            while w:
                w_x, w_y = w.popleft()
                arr[w_x][w_y] = '*'
            water_cnt += 1

        if arr[x][y] == '*':
            continue

        if arr[x][y] == '.':
            arr[x][y] = 'S'

        if arr[x][y] == 'D':
            return print(cnt)

        for i in range(4):
            if 0 <= x+dx[i] < R and 0 <= y+dy[i] < C:
                if visited[x+dx[i]][y+dy[i]] == 0:
                    if arr[x+dx[i]][y+dy[i]] == '.' or arr[x+dx[i]][y+dy[i]] == 'D':
                        visited[x+dx[i]][y+dy[i]] = 1
                        start.append([x+dx[i], y+dy[i], cnt+1])

    return print('KAKTUS')

end_point = []
water_point = deque()
start_point = deque()

for i in range(R):
    for j in range(C):
        if arr[i][j] == 'D':
            end_point.append([i, j])
        if arr[i][j] == 'S':
            start_point.append([i, j, 0])
            visited[i][j] = 1
        if arr[i][j] == '*':
            w_visited[i][j] = 1
            water_point.append([i, j])

bfs(start_point, end_point, water_point)


for _ in range(int(input())):
    q=[]
    s= input()
    q.append('(')
    if s[0]!='(':
        print('NO')
        continue

    flag=True
    for el in s[1:]:
        if el=='(':
            q.append('(')
        else:
            if not q:
                flag= False

                break
            q.pop()
    if flag and not q:
        print('YES')
    else:
        print('NO')


from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def index():
    storing = requests.get('https://zenquotes.io/api/random')
    json_storing = storing.json()
    quote = json_storing[0]
    return render_template('podo.html', quote=quote)

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


def search(arr, x, temp, now):
    global candi, visited
    if x == N-1:
        candi.append(temp + arr[now][0])
    else:
        for i in range(1, N):
            if not visited[i]:
                visited[i] = 1
                search(arr, x+1, temp + arr[now][i], i)
                visited[i] = 0

for T in range(int(input())):
    N = int(input())
    arr = [tuple(map(int, input().split())) for i in range(N)]
    candi = []
    visited = [0] * N
    search(arr, 0, 0, 0)
    print('#{} {}'.format(T + 1, min(candi)))


"""
This module takes care of starting the API Server, Loading the DB and Adding the endpoints
"""
from flask import Flask, request, jsonify, url_for, Blueprint
from api.models import db
from api.utils import generate_sitemap
import random
#from models import Person

api = Blueprint('api', __name__)

@api.route('/card', methods=['GET'])
def get_card():
    suits = ["♣", "♠", "♥", "♦"]
    values = ["A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3", "2"]

    random_suits_position = random.randint(0, 3)
    random_values_position = random.randint(0,12)

    body = {
        "suit": suits[random_suits_position],
        "number": values[random_values_position]
    }

    return jsonify(body), 200


import unittest
from outpost24hiabclient.entities.scanner import Scanner
from outpost24hiabclient.clients.hiabclient import HiabClient
from outpost24hiabclient import ScannerService
from unittest.mock import patch

import xml.etree.ElementTree as ET

class HiabClientTest:

    def get_scanners(self):
        data="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
                <RESPONSE ACTION=\"SCANNERDATA\" TIMESTAMP=\"2021-01-28 11:54\" USERNAME=\"ACCEPTANCE\" VERSION=\"4.22.12.0\">\
	                <SCANNERLIST>\
		                <TOTALCOUNT>2</TOTALCOUNT>\
		                <COLLAPSEDTOTAL>2</COLLAPSEDTOTAL>\
		                <SCANNER rowid=\"1\">\
			                <IPADDRESS>127.0.0.1</IPADDRESS>\
			                <ISAWSSCANNER>false</ISAWSSCANNER>\
			                <USEPROXY>false</USEPROXY>\
			                <POLLING>false</POLLING>\
			                <ISOUTPOST>false</ISOUTPOST>\
			                <MODE>1</MODE>\
			                <APPSECSCALESCANNER>false</APPSECSCALESCANNER>\
			                <XID>0</XID>\
			                <APPROVED>true</APPROVED>\
			                <INACTIVE>false</INACTIVE>\
			                <XUPDATOR>0</XUPDATOR>\
			                <PERFORMUPDATE>false</PERFORMUPDATE>\
			                <ISGROUP>false</ISGROUP>\
			                <XUSERXID>11</XUSERXID>\
			                <NAME>Local</NAME>\
			                <SCANNINGDISABLED>false</SCANNINGDISABLED>\
			                <SLSSCANSCHEDULED>false</SLSSCANSCHEDULED>\
		                </SCANNER>\
		                <SCANNER rowid=\"2\">\
			                <IPADDRESS>outscan.outpost24.com</IPADDRESS>\
			                <ISAWSSCANNER>false</ISAWSSCANNER>\
			                <USEPROXY>false</USEPROXY>\
			                <POLLING>false</POLLING>\
			                <ISOUTPOST>true</ISOUTPOST>\
			                <MODE>1</MODE>\
			                <APPSECSCALESCANNER>false</APPSECSCALESCANNER>\
			                <XID>2</XID>\
			                <APPROVED>false</APPROVED>\
			                <INACTIVE>false</INACTIVE>\
			                <XUPDATOR>0</XUPDATOR>\
			                <PERFORMUPDATE>false</PERFORMUPDATE>\
			                <ISGROUP>false</ISGROUP>\
			                <XUSERXID>11</XUSERXID>\
			                <NAME>Outscan</NAME>\
			                <SCANNINGDISABLED>false</SCANNINGDISABLED>\
			                <SLSSCANSCHEDULED>false</SLSSCANSCHEDULED>\
		                </SCANNER>\
	                </SCANNERLIST>\
	                <PROXYENABLED>0</PROXYENABLED>\
	                <NOTIFYMISSING>0</NOTIFYMISSING>\
                </RESPONSE>"
        xmldata = ET.fromstring(data)
        scannerlist = xmldata.findall('SCANNERLIST')
        if(len(scannerlist) >= 1):
            scanners = scannerlist[0].findall('SCANNER')
            return [Scanner(self,s) for s in scanners]

class ScannerServiceTests(unittest.TestCase):

    def setUp(self):
        hiabclient = HiabClientTest()
        self.scanner_service = ScannerService(hiabclient)

    def test_parse_xml_data(self):
        scanners = self.scanner_service.get_scanners()
        self.assertTrue(len(scanners) == 2)

    def test_get_scanner_by_name(self):
        scanner0 = self.scanner_service.get_scanner_by_name("Local")
        scanner1 = self.scanner_service.get_scanner_by_name("Outscan")
        self.assertEqual(scanner0.xid, 0)
        self.assertEqual(scanner1.xid, 2)

    def test_get_scanner_by_id(self):
        scanner0 = self.scanner_service.get_scanner_by_id(0)
        scanner2 = self.scanner_service.get_scanner_by_id(2)
        self.assertEqual(scanner0.xid, 0)
        self.assertEqual(scanner2.xid, 2)


from tqdm import tqdm
import jittor as jt
from jittor import optim
from jittor.lr_scheduler import MultiStepLR
import argparse
import random
import sys
import glob
import pickle
import os
import numpy as np
from tensorboardX import SummaryWriter
from dataset.dota import DOTA
from dataset.transforms import train_transforms,val_transforms
from models.scrdet import SCRDet
from utils.ap_eval import calculate_VOC_mAP,calculate_VOC_mAP_r
from utils.visualize import save_visualize_image

CLASSNAMES = ['plane', 'baseball-diamond', 'bridge', 'ground-track-field',
              'small-vehicle', 'large-vehicle', 'ship','tennis-court', 'basketball-court',
              'storage-tank', 'soccer-ball-field','roundabout', 'harbor',
              'swimming-pool', 'helicopter']

CLASSNAMES = ['roundabout','tennis-court','swimming-pool', 'storage-tank',
                'soccer-ball-field','small-vehicle','ship',
                'plane', 'large-vehicle',
                'helicopter','harbor','ground-track-field',
                'bridge','basketball-court','baseball-diamond']

EPOCHS=20
NUM_GPUS = 1
BATCH_SIZE=1*NUM_GPUS
LR = 0.001 * BATCH_SIZE
MOMENTUM = 0.9
WEIGHT_DECAY = 0.0001
NUM_WORKERS = 8

if jt.in_mpi:
    world_rank = jt.mpi.world_rank()
    is_main = (world_rank == 0)
else:
    is_main = True

save_checkpoint_path = "/mnt/disk/lxl/SCRDET_new"
data_dir = '/mnt/disk/lxl/dataset/DOTA_CROP'

def test(save_result=True,display_img=True):
    checkpoint_path = f'{save_checkpoint_path}/checkpoint_3.pkl'
    jt.flags.use_cuda=1
    val_dataset = DOTA(data_dir=f"{data_dir}/val",
                        classnames=CLASSNAMES,
                        transforms=val_transforms(),
                        num_workers=NUM_WORKERS,
                        shuffle=False,
                        batch_size=BATCH_SIZE)
    scrdet = SCRDet(classnames = CLASSNAMES)
    scrdet.load("test.pkl")
    # scrdet.load(checkpoint_path)
    scrdet.test_score_thresh=0.001
    scrdet.eval()
    results = []
    results_r = []
    for batch_idx,(batch_imgs,batch_masks,img_sizes,hbb,rbb,labels,ids) in tqdm(enumerate(val_dataset)):
        print(batch_imgs.mean())
        result,result_r = scrdet(batch_imgs,img_sizes,img_ids=ids)
        for i in range(len(ids)):
            pred_boxes,pred_scores,pred_labels = result[i]
            gt_boxes = hbb[i]
            pred_boxes_r,pred_scores_r,pred_labels_r = result_r[i]
            gt_boxes_r = rbb[i]
            gt_labels = labels[i]
            img_id = ids[i]
            results.append((img_id,pred_boxes.numpy(),pred_labels.numpy(),pred_scores.numpy(),gt_boxes.numpy(),gt_labels.numpy()))
            results_r.append((img_id,pred_boxes_r.numpy(),pred_labels_r.numpy(),pred_scores_r.numpy(),gt_boxes_r.numpy(),gt_labels.numpy()))
            # print(pred_boxes)
            if display_img:
                save_visualize_image(data_dir,img_id,pred_boxes.numpy(),pred_scores.numpy(),pred_labels.numpy(),gt_boxes.numpy(),gt_labels.numpy(),CLASSNAMES)

    if save_result:
        pickle.dump((results,result_r),open(checkpoint_path.replace(".pkl","_results.pkl"),"wb"))
    mAP,_ = calculate_VOC_mAP(results,CLASSNAMES,use_07_metric=False)
    mAP_r,_ = calculate_VOC_mAP_r(results_r,CLASSNAMES,use_07_metric=False)
    print(mAP,mAP_r)

def train():
    jt.flags.use_cuda=1
    train_dataset = DOTA(data_dir=f"{data_dir}/trainval",
                        classnames=CLASSNAMES,
                        transforms=train_transforms(),
                        num_workers=NUM_WORKERS,
                        shuffle=True,
                        batch_size=BATCH_SIZE)
    val_dataset = DOTA(data_dir=f"{data_dir}/trainval",
                        classnames=CLASSNAMES,
                        transforms=val_transforms(),
                        num_workers=NUM_WORKERS,
                        shuffle=False,
                        batch_size=BATCH_SIZE)

    scrdet = SCRDet(classnames = CLASSNAMES)

    optimizer = optim.SGD(scrdet.parameters(),momentum=MOMENTUM,lr=LR,weight_decay=WEIGHT_DECAY)
    scrdet.load("test.pkl")
    scheduler = MultiStepLR(optimizer, milestones=[12*27000,16*27000], gamma=0.3)

    writer = SummaryWriter()

    for epoch in range(EPOCHS):
        scrdet.train()
        dataset_len  = len(train_dataset)

        for batch_idx,(batch_imgs,batch_masks,img_sizes,hbb,rbb,labels,ids) in tqdm(enumerate(train_dataset)):
            rpn_loc_loss, rpn_cls_loss, roi_loc_loss, \
            roi_cls_loss,roi_loc_loss_r,roi_cls_loss_r,\
            att_loss,total_loss = scrdet(batch_imgs,img_sizes,batch_masks,hbb,rbb,labels,img_ids=ids,batch_idx=batch_idx)

            optimizer.step(total_loss)
            scheduler.step()

            if is_main:
                writer.add_scalar('rpn_cls_loss', rpn_cls_loss.item(), global_step=dataset_len*epoch+batch_idx)
                writer.add_scalar('rpn_loc_loss', rpn_loc_loss.item(), global_step=dataset_len*epoch+batch_idx)
                writer.add_scalar('roi_loc_loss', roi_loc_loss.item(), global_step=dataset_len*epoch+batch_idx)
                writer.add_scalar('roi_cls_loss', roi_cls_loss.item(), global_step=dataset_len*epoch+batch_idx)
                writer.add_scalar('roi_loc_loss_r', roi_loc_loss_r.item(), global_step=dataset_len*epoch+batch_idx)
                writer.add_scalar('roi_cls_loss_r', roi_cls_loss_r.item(), global_step=dataset_len*epoch+batch_idx)
                writer.add_scalar('att_loss', att_loss.item(), global_step=dataset_len*epoch+batch_idx)
                writer.add_scalar('total_loss', total_loss.item(), global_step=dataset_len*epoch+batch_idx)

            # if batch_idx % 10 == 0:
            #     print("total_loss: %.4f"% total_loss.item())

        if is_main:
            os.makedirs(save_checkpoint_path,exist_ok=True)
            scrdet.save(f"{save_checkpoint_path}/checkpoint_{epoch}.pkl")

        scrdet.eval()
        results = []
        results_r = []
        for batch_idx,(batch_imgs,batch_masks,img_sizes,hbb,rbb,labels,ids) in tqdm(enumerate(val_dataset)):
            result,result_r = scrdet(batch_imgs,img_sizes,img_ids=ids,batch_idx=batch_idx)
            for i in range(len(ids)):
                pred_boxes,pred_scores,pred_labels = result[i]
                gt_boxes = hbb[i]
                pred_boxes_r,pred_scores_r,pred_labels_r = result_r[i]
                gt_boxes_r = rbb[i]
                gt_labels = labels[i]
                img_id = ids[i]
                results.append((img_id,pred_boxes.numpy(),pred_labels.numpy(),pred_scores.numpy(),gt_boxes.numpy(),gt_labels.numpy()))
                results_r.append((img_id,pred_boxes_r.numpy(),pred_labels_r.numpy(),pred_scores_r.numpy(),gt_boxes_r.numpy(),gt_labels.numpy()))

        mAP,_ = calculate_VOC_mAP(results,CLASSNAMES,use_07_metric=True)
        mAP_r,_ = calculate_VOC_mAP_r(results_r,CLASSNAMES,use_07_metric=True)
        print(mAP,mAP_r)
        writer.add_scalar('map', mAP, global_step=epoch)
        writer.add_scalar('map_r', mAP_r, global_step=epoch)

def main():
    parser = argparse.ArgumentParser(description='Test a SCRDet network')
    parser.add_argument('--task',help='Task(train,test)',default='train',type=str)
    args = parser.parse_args()
    if args.task == 'test':
        test()
    elif args.task == 'train':
        train()
    else:
        print(f"No this task: {args.task}")

if __name__ == "__main__":
    main()


from datetime import datetime
from flask import Flask, render_template, url_for, flash, redirect, request
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SECRET_KEY'] = 'bf2a0fbecd7030220d754389dcbd5ij9'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://ipnx:root.Account#20@ipNX@localhost/ipnx_db'
db = SQLAlchemy(app)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

class matrix(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name =db.Column(db.String(100), nullable=False)
    level = db.Column(db.String(100), nullable=False)
    contact_name = db.Column(db.String(100), nullable=False)
    email = db.Column(db.String(100), nullable=False)
    contact= db.Column(db.String(100), nullable=False)
    timeline = db.Column(db.String(100), nullable=False)
    def __repr__(self):
        return "id: {0} | level: {1} | timeline: {2} | contact_name: {3} | email: {4} | contact: {5} | name: {6}".format(self.id, self.level, self.timeline, self.email, self.contact, self.name)

@app.route('/')
@app.route('/index', methods=['GET', 'POST'])
def index():
    qry = matrix.query.order_by(matrix.id.desc())

    if request.method == 'POST':
        data = request.form
        level = data['level']
        timeline = data['timeline']
        name = data['name']
        contact_name = data['contact_name']
        email = data['email']
        contact= data['contact']
        user = matrix(level=level, name=name, timeline=timeline, contact_name=contact_name, email=email, contact=contact)
        db.session.add(user)
        db.session.commit()
        flash('Matrix added Successfully')
    return render_template('index.html', result=qry, title=index)

@app.route('/mtn_matrix', methods=['GET', 'POST'])
def mtn_matrix():
    if request.method == 'POST':
        data = request.form
        name = data['query']
        qry = matrix.query.filter_by(name=name)
    return render_template('index.html', result=qry, title=index, exit=exit)

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


import mysql.connector
import tkinter as tk
from tkinter import ttk
from style import *
from util import *
from tkinter import messagebox as mb
from datetime import datetime, timedelta
class MenuTampilPesanan(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        self.configure(background = BG_COLOR)
        self.updateTampilan()

    def updateTampilan(self):
        clearFrame(self)
        # Navbar Frame
        self.navbar = tk.Frame(self, width = 560, height = 25, relief = tk.GROOVE, borderwidth=1)

        #Order button
        self.confirmPesananBtn = tk.Button(master=self.navbar, text="Home", cursor="hand2", highlightthickness = 0, bd = 0, command=lambda:self.controller.show_frame("AdminHome"))
        self.confirmPesananBtn.configure(font=SMALL_FONT)
        self.confirmPesananBtn.config(background=BG_COLOR)
        self.confirmPesananBtn.config(width=20)
        self.confirmPesananBtn.pack(side=tk.LEFT, padx=5)

        self.navbar.grid(row=0,column=0)
        self.navbar.configure(background=BG_COLOR)

        self.controller.mycursor.execute("SELECT * FROM pesanan;")
        result = self.controller.mycursor.fetchall()
        i = 0

        for tup in result:
            i = i + 1
        # b = tk.Button(self, width = 20, font=('Arial',10), fg="black", text="Proses", command = lambda:self.prosesPesanan(result[r-1][0]))
        # b.grid(row=1,column=0)
        # e = tk.Entry(self,width=20, font=('Arial',12), fg="black")
        # e.grid(row=1,column=1)
        for r in range(i+1):
            for c in range(1,6):
                if(c == 1 and r != 0):
                    b = tk.Button(self, width = 20, height = 1, font=('Arial',10), fg="black", text="Proses", command = lambda:self.prosesPesanan(result[r-1][0]))
                    b.grid(row=r+2,column=c-1)
                else:
                    e = tk.Text(self, width=20, height = 1, font=('Arial',14), fg="black")
                    e.grid(row=r+2,column=c-1)
                    if (r == 0):
                        if ( c == 1):
                            e.insert(tk.END,"Proses")
                        elif (c == 2):
                            e.insert(tk.END,"Username")
                        elif (c == 3):
                            e.insert(tk.END,"Status")
                        elif (c == 4):
                            e.insert(tk.END,"Tanggal Pemesanan")
                        else:
                            e.insert(tk.END,"Status Konfirmasi")
                    else:
                        e.insert(tk.END,result[r-1][c])
                    # e.config(state="readonly")

    def prosesPesanan(self, idPesanan):
        self.controller.mycursor.execute("SELECT username, id_kamar FROM pesanan;")
        result = self.controller.mycursor.fetchall()

        uname = result[0][0]
        id_kamar = result[0][1]

        self.controller.mycursor.execute("SELECT k.nama, rs.nama FROM kamar k inner join rumahsakit rs on rs.id = k.rumah_sakit_id where k.id = " + getStringFromResult(id_kamar))
        result = self.controller.mycursor.fetchall()

        namaKamar = result[0][0]
        namaRS = result[0][1]

        self.controller.mycursor.execute("SELECT nama FROM user where username = '" + uname + "'")
        result = self.controller.mycursor.fetchall()

        nama = result[0][0]

        self.controller.frames["MenuProsesPesanan"].tampilkanProsesPesanan(idPesanan, nama, namaRS, namaKamar, uname)
class MenuBuatPesanan(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        self.configure(background = BG_COLOR)

        createNavbarPengguna(self)

        #TITLE
        self.title = tk.Label(self, text="BUAT PESANAN")
        self.title.config(font=TITLE_FONT)
        self.title.config(background=BG_COLOR)
        self.title.pack(pady=40)

        self.namaRSLabel = tk.Label(self, text="Masukkan nama RS\t\t:")
        self.namaRSLabel.config(font=LARGE_FONT)
        self.namaRSLabel.config(background=BG_COLOR)
        self.namaRSLabel.place(x=30, y=90)

        self.namaKamarLabel = tk.Label(self, text="Masukkan nama Kamar\t:")
        self.namaKamarLabel.config(font=LARGE_FONT)
        self.namaKamarLabel.config(background=BG_COLOR)
        self.namaKamarLabel.place(x=30, y=140)

        namaRS = tk.StringVar()
        namaKamar = tk.StringVar()

        self.namaRSEntry = tk.Entry(self, textvariable=namaRS, width="30")
        self.namaRSEntry.place(x=320, y=100)
        self.namaKamarEntry = tk.Entry(self, textvariable=namaKamar, width="30")
        self.namaKamarEntry.place(x=320, y=150)

        self.tampilkanDataKamarButton = tk.Button(self,  text="Tampilkan Daftar Kamar", command=lambda:self.controller.show_frame("MenuTampilDataKamar"))
        self.tampilkanDataKamarButton.place(x=300, y=200, width=200)
        self.buatPesananButton = tk.Button(self,  text="Pesan", command=lambda:self.buatPesanan())
        self.buatPesananButton.place(x=300, y=260, width=200)

        self.surpriseLabel = tk.Label(self, text="Catatan: PERBESAR LAYAR KE KANAN UNTUK MELIHAT JUMLAH KAMAR \nYANG TERSEDIA SAAT MELIHAT TABEL KAMAR")
        self.surpriseLabel.config(font=("Calibri", 12, 'bold'))
        self.surpriseLabel.config(background=BG_COLOR)
        self.surpriseLabel.place(x=30, y=350)

    def buatPesanan(self):
        # Siapin value yang mau dimasukin
        kamar = self.namaKamarEntry.get()
        rs = self.namaRSEntry.get()
        idKamar = getIDKamar(self.controller.mycursor,kamar,rs)
        nowDate =  getNowDateAsString()
        user = self.controller.username # NANTI PAS DIBUAT MAIN PROGRAM, KASIH INI AKSES KE GLOBAL VARIABLE USERNAME BUAT TAU SIAPA YG LOGIN T_T

        # Cek apakah terjadi kesamaan id pesanan pada tabel dan yang baru di-generate
        if((not checkIfUserBooked(self.controller.mycursor, user)) and len(idKamar) > 0):
            idKamar = str(idKamar[0])

            insertQuery = "INSERT INTO pesanan(id_kamar, username, status, tanggal_pesan, is_confirmed) VALUES (%s,%s,%s,%s,%s);"
            val = (idKamar, user,"On Hold",nowDate,"Belum")
            self.controller.mycursor.execute(insertQuery,val)
            self.controller.dB.commit()
            isError = False
            self.controller.frames["MenuTampilPesanan"].updateTampilan()
            self.loadKonfirmasiPesanan(idKamar)
        else:
            mb.showwarning("Tidak Dapat Melakukan Pesanan", "Anda sudah melakukan pemesanan dan tidak dapat memesan kamar lagi sampai Admin mengonfirmasi pesanan Anda")

    def loadKonfirmasiPesanan(self, IDKamar):
        searchQuery = "select harga from kamar where id=" + str(IDKamar) + ";"
        self.controller.mycursor.execute(searchQuery)
        result = self.controller.mycursor.fetchall()
        uang = "Rp" + getStringFromResult(result[0])
        self.controller.frames["MenuKonfirmasiPesanan"].jumlahUangLabel.config(text=uang)
        self.controller.show_frame("MenuKonfirmasiPesanan")

def buatPesananTest(RS,Kamar,User):
    dB = mysql.connector.connect(
        host="localhost",
        user="root",
        passwd="",
        database="trackingCovid"
        )
    mycursor = dB.cursor()
    query = "select * from pesanan where username=\'" + User + "\' and id_kamar=" + getStringFromResult(getIDKamar(mycursor,Kamar,RS)) + ";"
    mycursor.execute(query)
    result = mycursor.fetchall()
    return result

class MenuKonfirmasiPesanan(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        self.configure(background = BG_COLOR)

        createNavbarAdmin(self)

        self.title = tk.Label(self, text="BUAT PESANAN")
        self.title.config(font=TITLE_FONT)
        self.title.config(background=BG_COLOR)
        self.title.pack(pady=20)

        self.berhasilLabel = tk.Label(self, text="Pesanan Berhasil Dibuat!")
        self.berhasilLabel.config(font=LARGE_FONT)
        self.berhasilLabel.config(background=BG_COLOR)
        self.berhasilLabel.place(x=300, y=70)

        self.transferLabel = tk.Label(self, text="Silakan lakukan pembayaran melalui transfer bank")
        self.transferLabel.config(font=LARGE_FONT)
        self.transferLabel.config(background=BG_COLOR)
        self.transferLabel.place(x=200, y=120)

        self.bankLabel = tk.Label(self, text="ABC sebesar")
        self.bankLabel.config(font=LARGE_FONT)
        self.bankLabel.config(background=BG_COLOR)
        self.bankLabel.place(x=350, y=140)

        uang = ""
        self.jumlahUangLabel = tk.Label(self, text=uang)
        self.jumlahUangLabel.config(font=LARGE_FONT)
        self.jumlahUangLabel.config(background=BG_COLOR)
        self.jumlahUangLabel.place(x=340, y=180)

        self.konfirmasiLabel = tk.Label(self, text="Masukkan username Anda dan klik tombol di bawah jika telah melakukan transfer")
        self.konfirmasiLabel.config(font=LARGE_FONT)
        self.konfirmasiLabel.config(background=BG_COLOR)
        self.konfirmasiLabel.place(x=100, y=230)

        user = tk.StringVar()
        self.userEntry = tk.Entry(self, textvariable=user, width="30")
        self.userEntry.place(x=260, y=255)

        self.konfirmasiButton = tk.Button(self, text="Konfirmasi Pesanan", command= lambda: self.changeToSudah())
        self.konfirmasiButton.place(x=320, y=290, height=50, width=150)

    def changeToSudah(self):
        user = self.controller.username
        query = "update pesanan set is_confirmed=\'Sudah\' where username=\"" + user+"\""
        self.controller.mycursor.execute(query)
        self.controller.dB.commit()
        mb.showinfo('Berhasil!', 'Konfirmasi pembayaran telah diterima!')

class MenuProsesPesanan(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        self.configure(background = BG_COLOR)

        createNavbarAdmin(self)

        self.namaLabel = tk.Label(self, text="Nama \t\t:")
        self.namaLabel.config(font=LARGE_FONT)
        self.namaLabel.config(background=BG_COLOR)
        self.namaLabel.place(x=30, y=70)

        self.rsLabel = tk.Label(self, text="Rumah Sakit\t:")
        self.rsLabel.config(font=LARGE_FONT)
        self.rsLabel.config(background=BG_COLOR)
        self.rsLabel.place(x=30, y=120)

        self.kamarLabel = tk.Label(self, text="Kamar\t\t:")
        self.kamarLabel.config(font=LARGE_FONT)
        self.kamarLabel.config(background=BG_COLOR)
        self.kamarLabel.place(x=30, y=170)

        self.suhuLabel = tk.Label(self, text="Suhu 3 hari terakhir\t:")
        self.suhuLabel.config(font=LARGE_FONT)
        self.suhuLabel.config(background=BG_COLOR)
        self.suhuLabel.place(x=30, y=220)

        self.IDPesanan = tk.StringVar()
        self.statusBaru = tk.StringVar()

        self.statusBaruEntry = ttk.Combobox(self,width=30,textvariable=self.statusBaru)
        self.statusBaruEntry['values'] = ('On Hold', 'Diterima', 'Ditolak')
        self.statusBaruEntry.place(x=30, y=270)

        self.prosesPesananButton = tk.Button(self, text="Proses Pesanan", cursor="hand2", command= lambda: self.prosesPesanan(self.IDPesanan.get(),self.statusBaru.get()))
        self.prosesPesananButton.place(x=280, y=270, width=250)

    def tampilkanProsesPesanan(self, idPesanan, nama, namaRS, namaKamar, username):
        self.namaLabel.config(text = "Nama \t\t: " + str(nama))
        self.rsLabel.config(text = "Rumah Sakit\t: " + str(namaRS))
        self.kamarLabel.config(text = "Kamar\t\t: " + str(namaKamar))

        tgl1 = datetime.now()
        tgl2 = datetime.now() - timedelta(days=1)
        tgl3 = datetime.now() - timedelta(days=2)

        query = "select value from suhu where username = %s and (tanggal_input = %s or tanggal_input = %s or tanggal_input = %s)"
        self.controller.mycursor.execute("select value from suhu where username = %s and (tanggal_input = %s or tanggal_input = %s or tanggal_input = %s)", (str(username), str(tgl1), str(tgl2), str(tgl3)))
        result = self.controller.mycursor.fetchall()

        suhutext = "Suhu 3 hari terakhir\t: "
        i = 0
        while(i < 3 and i < len(result)):
            suhutext += str(result[i]) + " "
            i += 1

        while(i < 3):
            suhutext += "- "
            i += 1

        self.suhuLabel.config(text=suhutext)
        self.prosesPesananButton.config(command= lambda: self.prosesPesanan(idPesanan))
        self.controller.show_frame("MenuProsesPesanan")

    def prosesPesanan(self,idPesanan):

        # Menerima atau menolak pesanan oleh admin
        ID = idPesanan
        status = self.statusBaru.get()

        # Mengurangi jumlah kamar yang tersedia jika pesanan diterima
        if (status == 'Diterima'):
            queryKurangiKamar = "UPDATE kamar SET jumlah=jumlah-1 WHERE id IN (SELECT id_kamar FROM pesanan WHERE id_pesanan=" + str(ID) + ");"
            self.controller.mycursor.execute(queryKurangiKamar)
            self.controller.dB.commit()
        # IDPesananPilihan = result[nomorPesanan-1][0]

        dummy = updateQuery(status,ID,self.controller.dB,self.controller.mycursor)

        mb.showinfo('Berhasil!', 'Status Pesanan berhasil di-update!')
        self.controller.frames["MenuTampilPesanan"].updateTampilan()

class MenuTampilDataKamar(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        self.configure(background = BG_COLOR)
        self.updateTampilan()

    def updateTampilan(self):
        clearFrame(self)
        # Navbar Frame
        self.navbar = tk.Frame(self, width = 560, height = 25, relief = tk.GROOVE, borderwidth=1)

        #Order button
        self.buatPesananbtn = tk.Button(master=self.navbar, text="Buat Pesanan", cursor="hand2", highlightthickness = 0, bd = 0, command=lambda:self.controller.show_frame("MenuBuatPesanan"))
        self.buatPesananbtn.configure(font=SMALL_FONT)
        self.buatPesananbtn.config(background=BG_COLOR)
        self.buatPesananbtn.config(width=30)
        self.buatPesananbtn.pack(side=tk.LEFT, padx=5)

        self.navbar.grid(row=0,column=0)
        self.navbar.configure(background=BG_COLOR)

        self.controller.mycursor.execute("SELECT k.nama,rs.nama,rs.alamat,k.harga,k.jumlah FROM kamar as k inner join rumahsakit as rs on k.rumah_sakit_id=rs.id;")
        result = self.controller.mycursor.fetchall()
        i = 0
        for tup in result:
            i = i + 1
        for r in range(i+1):
            for c in range(5):
                e = tk.Entry(self,width=30, font=('Arial',12), fg="black")
                e.grid(row=r+1,column=c)
                if (r == 0):
                    if (c == 0):
                        e.insert(tk.END,"Nama Kamar")
                    elif (c == 1):
                        e.insert(tk.END,"Nama RS")
                    elif (c == 2):
                        e.insert(tk.END,"Alamat RS")
                    elif (c == 3):
                        e.insert(tk.END,"Harga")
                    else:
                        e.insert(tk.END,"Jumlah Tersisa")
                else:
                    e.insert(tk.END,result[r-1][c])
                e.config(state="readonly")

# class MenuTampilStatusPesanan(tk.Frame):
#     def __init__(self, parent, controller):
#         tk.Frame.__init__(self, parent)

#         self.controller = controller
#         self.configure(background = BG_COLOR)

#         self.rsLabel = tk.Label(self, text="Rumah Sakit\t:")
#         self.rsLabel.config(font=LARGE_FONT)
#         self.rsLabel.config(background=BG_COLOR)
#         self.rsLabel.place(x=30, y=70)

#         self.kamarLabel = tk.Label(self, text="Kamar\t\t:")
#         self.kamarLabel.config(font=LARGE_FONT)
#         self.kamarLabel.config(background=BG_COLOR)
#         self.kamarLabel.place(x=30, y=120)

#         self.statusLabel = tk.Label(self, text="Status \t\t:")
#         self.statusLabel.config(font=LARGE_FONT)
#         self.statusLabel.config(background=BG_COLOR)
#         self.statusLabel.place(x=30, y=170)

#     def tampilStatusPesanan(self):
#         self.controller.mycursor.execute("SELECT username, id_kamar, status FROM pesanan where username = '" + self.controller.username + "' order by tanggal_pesan")
#         result = self.controller.mycursor.fetchall()

#         if(len(result) > 0):
#             clearFrame(self)
#             uname = result[0][0]
#             id_kamar = result[0][1]
#             status = result[0][2]

#             self.rsLabel = tk.Label(self, text="Rumah Sakit\t:")
#             self.rsLabel.config(font=LARGE_FONT)
#             self.rsLabel.config(background=BG_COLOR)
#             self.rsLabel.place(x=30, y=70)

#             self.kamarLabel = tk.Label(self, text="Kamar\t\t:")
#             self.kamarLabel.config(font=LARGE_FONT)
#             self.kamarLabel.config(background=BG_COLOR)
#             self.kamarLabel.place(x=30, y=120)

#             self.statusLabel = tk.Label(self, text="Status \t\t:")
#             self.statusLabel.config(font=LARGE_FONT)
#             self.statusLabel.config(background=BG_COLOR)
#             self.statusLabel.place(x=30, y=170)

#             self.controller.mycursor.execute("SELECT k.nama, rs.nama FROM kamar k inner join rumahsakit rs on rs.id = k.rumah_sakit_id where k.id = " + getStringFromResult(id_kamar))
#             result = self.controller.mycursor.fetchall()

#             namaKamar = result[0][0]
#             namaRS = result[0][1]

#             self.controller.mycursor.execute("SELECT nama FROM user where username = '" + uname + "'")
#             result = self.controller.mycursor.fetchall()

#             nama = result[0][0]

#             self.rsLabel.config(text = "Rumah Sakit\t: " + namaRS)
#             self.kamarLabel.config(text = "Kamar\t\t: " + namaKamar)
#             self.statusLabel.config(text = "Status\t\t: " + status)
#         else:
#             clearFrame(self)
#             self.labelKosong = tk.Label(self, text = "Anda Tidak Memiliki Pesanan")
#             self.labelKosong.config(font=LARGE_FONT)
#             self.labelKosong.config(background=BG_COLOR)
#             self.labelKosong.pack()


#!/usr/bin/env python3

"""LRU.py - algorytm LRU"""
import ramka
from os import strerror

print("\nAlgorytm LRU\n")

try:
    odwolania=open("odwolania.txt","r")
except Exception as exc:
    print("Błąd: ",strerror(exc.errno))

ciag_odwolan=odwolania.readline().split()

try:
    odwolania.close()
except Exception as exc:
    print("Błąd: ",strerror(exc.errno))

ramki=[]#ramki pamięci fizycznej
miss=0#ilość błędów strony
recently_used={}#słownik na ostanie użycie danej strony
i=0
for odwolanie in ciag_odwolan:
    if len(ramki)<ramka.ilosc_ramek:
        if odwolanie not in ramki:
            ramki.append(odwolanie)
            recently_used[odwolanie]=i+1
            miss += 1
        else:
            recently_used[odwolanie] = i + 1
    else:
        if odwolanie in ramki:
            recently_used[odwolanie] = i + 1
        else:
            least_recently_used=sorted(recently_used.items(),key=lambda x: x[1])#sortowanie listy krotek powstałej ze słownika ostatnich użyć strony, względem najdawniejszego użycia
            temp = ramki.index(least_recently_used[0][0])#znalezienie w ramkach strony najdawniej używanej
            del ramki[temp]
            del recently_used[least_recently_used[0][0]]
            ramki.insert(temp,odwolanie)
            recently_used[odwolanie] = i + 1
            miss += 1
    i+=1
    #print(i,"Odwolanie: ",ramki)
print("Ilość poprawnych odwołań: ",i-miss)
print("Ilość błędów strony: ",miss)
print("Prawdopodobieństwo wystąpienia błędu strony: ",round(miss/i,2))
print("Procent błędów w odniesieniu do wszystkich odwołań procesora: ",round(miss/i,2)*100,"%")

try:
    wyniki=open("wyniki_algorytmow_zastepowania_stron.txt","a")
    wyniki.write("LRU: "+str(miss) + " ")
except Exception as exc:
    print("Błąd: ",strerror(exc.errno))
try:
    wyniki.close()
except Exception as exc:
    print("Błąd: ",strerror(exc.errno))


from __future__ import absolute_import

import rules
from rotations.models import Rotation, RotationRequest, RotationRequestResponse, RotationRequestForward

@rules.predicate
def is_owner(user, object):
    """
    Check if the user owns the passed object, which may be one of: Rotation, RotationRequest,
     RotationRequestResponse, RotationRequestForward.
    """
    if isinstance(object, Rotation):
        return user == object.internship.intern.profile.user
    elif isinstance(object, RotationRequest):
        return user == object.plan_request.internship.intern.profile.user
    elif isinstance(object, RotationRequestResponse) or isinstance(object, RotationRequestForward):
        return user == object.rotation_request.plan_request.internship.intern.profile.user
    else:
        return False


# Python > Itertools > itertools.product()
# Find the cartesian product of 2 sets.
#
# https://www.hackerrank.com/challenges/itertools-product/problem
#

from itertools import product

A = list(map(int, input().split()))
B = list(map(int, input().split()))

P = list(product(A, B))

print(" ".join(str(x) for x in P))


import json
import os
import re

from sieglib.bdt import Bdt
from sieglib.bhd import Bhd, BhdHeader, BhdRecord, BhdDataEntry
from sieglib.dcx import Dcx
from sieglib.log import LOG
from pyshgck.time import time_it

class ExternalArchive(object):
    """ Combination of BHD and BDT. Contains methods to export files to the
    filesystem and to generate archives from a directory tree.

    An ExternalArchive object is unusable when instantiated; use the function
    'reset' to create an empty one, or the functions 'load' or 'import_files' to
    populate it.

    Attributes:
    - bhd: Bhd object
    - bdt: Bdt object
    - filelist: dict which maps hashes to the original string
    - records_map: dict which maps record indices to the entry relative path
        they contain; the hashes are those found in the BHD file
    - decompressed_list: list of files that have been decompressed during the
        archive export; it's the decompressed name, i.e. w/o the .dcx extension
    """

    # Do not handle these files when crafting an archive.
    SPECIAL_FILE_TYPES     = (".json",)
    RECORDS_MAP_NAME       = "records.json"
    DECOMPRESSED_LIST_NAME = "decompressed.json"

    # Files without a known name are named by their uppercase hex hash.
    UNNAMED_FILE_RE = re.compile(r"[0-9A-F]{8}")

    def __init__(self):
        self.bhd = Bhd()
        self.bdt = Bdt()
        self.filelist = {}
        self.records_map = {}
        self.decompressed_list = []

    def reset(self):
        self.__init__()

    def load(self, bhd_name):
        """ Load the BHD file and prepare the BDT file for reading, return True
        on success. """
        self.reset()

        bhd_load_success = self.bhd.load(bhd_name)
        if not bhd_load_success:
            return False

        bdt_name = os.path.splitext(bhd_name)[0] + ".bdt"
        self.bdt.open(bdt_name)
        if not self.bdt.opened:
            return False

        return True

    def load_filelist(self, hashmap_path):
        with open(hashmap_path, "r") as hashmap_file:
            hashmap = json.load(hashmap_file)
        self.filelist = { int(k, 16): hashmap[k] for k in hashmap.keys() }

    def load_records_map(self, input_dir):
        """ Load the archive's records map that will be used to generate an
        archive with original record-to-entries map, return True on success. """
        map_path = os.path.join(input_dir, self.RECORDS_MAP_NAME)
        if not os.path.isfile(map_path):
            LOG.error("Records map file can't be found.")
            return False
        else:
            with open(map_path, "r") as records_map_file:
                self.records_map = json.load(records_map_file)
            return True

    def load_decompressed_list(self, input_dir):
        """ Load the list of files in that input dir that should be compressed
        before being imported in the archive. """
        list_path = os.path.join(input_dir, self.DECOMPRESSED_LIST_NAME)
        if not os.path.isfile(list_path):
            LOG.info("No decompressed file list found in the input dir.")
            return False
        else:
            with open(list_path, "r") as list_file:
                self.decompressed_list = json.load(list_file)
            LOG.info("Loaded decompressed file list.")
            return True

    def save_records_map(self, output_dir):
        """ Write the JSON map of records to their entries. """
        records_map_path = os.path.join(output_dir, self.RECORDS_MAP_NAME)
        with open(records_map_path, "w") as records_map_file:
            json.dump(self.records_map, records_map_file)

    def save_decompressed_list(self, output_dir):
        """ Write the JSON list of files (relative path) decompressed. """
        list_path = os.path.join(output_dir, self.DECOMPRESSED_LIST_NAME)
        with open(list_path, "w") as list_file:
            json.dump(self.decompressed_list, list_file)

    #------------------------------
    # Extraction
    #------------------------------

    @time_it(LOG)
    def export_all_files(self, output_dir, decompress = True):
        """ Export all files from the archive to a directory tree in output_dir
        and decompress (if decompress is True, which is default) DCX files. """
        self.records_map = {}
        self.decompressed_list = []
        for index_and_record in enumerate(self.bhd.records):
            self._export_record(index_and_record, output_dir, decompress)
        self.save_records_map(output_dir)
        self.save_decompressed_list(output_dir)

    def _export_record(self, index_and_record, output_dir, decompress):
        """ Export data entries of that record. """
        record_files = []

        index, record = index_and_record
        for entry in record.entries:
            rel_path = self.export_file(entry, output_dir)
            if not rel_path:
                continue
            record_files.append(rel_path)

            if decompress:
                base_rel_path, extension = os.path.splitext(rel_path)
                if extension == ".dcx":
                    self._try_decompress(rel_path, base_rel_path, output_dir)

        self.records_map[index] = record_files

    def export_file(self, entry, output_dir):
        """ Export the file corresponding to that BHD data entry, return the
        relative file path on success, None on failure """
        if not self.is_entry_valid(entry):
            LOG.error("Tried to extract a file not from this archive.")
            return None

        rel_path = self.filelist.get(entry.hash) or "{:08X}".format(entry.hash)
        LOG.info("Extracting {}".format(rel_path))

        file_content = self.bdt.read_entry(entry.offset, entry.size)
        content_len = len(file_content)
        if content_len != entry.size:
            LOG.error( "Tried to read {} bytes but only {} were available "
                       "(file '{}').".format(
                entry.size, content_len, rel_path
            ))
            return None

        output_path = os.path.join(output_dir, rel_path.lstrip("/"))
        if not os.path.isdir(os.path.dirname(output_path)):
            os.makedirs(os.path.dirname(output_path))
        with open(output_path, "wb") as output_file:
            output_file.write(file_content)
        return rel_path

    def is_entry_valid(self, entry):
        """ Return True if that BhdDataEntry is part of this archive. """
        for record in self.bhd.records:
            if entry in record.entries:
                return True
        return False

    def _try_decompress(self, rel_path, base_rel_path, output_dir):
        """ Try to decompress the DCX at rel_path to base_rel_path, in the
        output_dir; fails if a file is already expected at base_rel_path. """
        if base_rel_path in self.filelist.values():
            LOG.info("Won't decompress {} because it conflicts with {}".format(
                rel_path, base_rel_path
            ))
            return
        joinable_rel_path = os.path.normpath(rel_path.lstrip("/"))
        file_path = os.path.join(output_dir, joinable_rel_path)
        success = ExternalArchive._decompress(file_path)
        if success:
            self.decompressed_list.append(base_rel_path)

    @staticmethod
    def _decompress(file_path, remove_dcx = True):
        """ Decompress that file and remove the compressed original (DCX) if
        remove_dcx is True. Return True on success. """
        dcx = Dcx()
        import_success = dcx.load(file_path)
        if not import_success:
            return False

        decompressed_path = os.path.splitext(file_path)[0]  # remove the .dcx
        export_success = dcx.save_decompressed(decompressed_path)
        if not export_success:
            return False

        if remove_dcx:
            os.remove(file_path)
        return True

    #------------------------------
    # Import
    #------------------------------

    @time_it(LOG)
    def import_files(self, data_dir, bhd_path):
        """ Create an external archive from the data in data_dir, return True on
        success. """
        self.reset()
        self._prepare_import(data_dir, bhd_path)

        for root, _, files in os.walk(data_dir):
            for file_name in files:
                ext = os.path.splitext(file_name)[1]
                if ext in self.SPECIAL_FILE_TYPES:
                    continue
                self.import_file(data_dir, root, file_name)

        self._update_header()
        self._save_files(bhd_path)
        return True

    def _prepare_import(self, data_dir, bhd_path):
        """ Prepare and load some files used in the import process, return True
        if everything is ready or False if the import should be aborted. """
        # Open the BDR file in write mode and write basic data
        bdt_path = os.path.splitext(bhd_path)[0] + ".bdt"
        self.bdt.open(bdt_path, "wb")
        self.bdt.make_header()

        # Load the records to entries map and prepare the BHD record list.
        records_map_is_loaded = self.load_records_map(data_dir)
        if not records_map_is_loaded:
            return False
        num_records = len(self.records_map)
        self.bhd.records = [BhdRecord() for _ in range(num_records)]

        # Load the list of files to compress
        self.load_decompressed_list(data_dir)

    def import_file(self, data_dir, file_dir, file_name):
        """ Try to import the file file_name in file_dir, with data_dir as the
        archive root; create a data entry in the appropriate record, and write
        the file data in the BDT file. Return True on success. """
        file_path = os.path.join(file_dir, file_name)

        # Find rel_path: either a hashable name like "/chr/c5352.anibnd.dcx"
        # or directly a hash name like "192E66A4".
        is_unnamed = self.UNNAMED_FILE_RE.match(file_name) is not None
        if is_unnamed:
            rel_path = file_name
        else:
            rel_path = ExternalArchive._get_rel_path(data_dir, file_path)
            rel_path = "/" + rel_path
        LOG.info("Importing {}".format(rel_path))

        # If the file is in the decompressed list, it has to be compressed first
        # and that means we have to create its DCX file, then we update the
        # paths we use afterwards.
        if rel_path in self.decompressed_list:
            joinable_rel_path = os.path.normpath(rel_path.lstrip("/"))
            decompressed_path = os.path.join(data_dir, joinable_rel_path)
            success = ExternalArchive._compress(decompressed_path)
            if not success:
                return False
            rel_path = rel_path + ".dcx"
            file_path = file_path + ".dcx"

        # Import the file
        import_results = self.bdt.import_file(file_path)
        if import_results[1] == -1:  # written bytes
            return False

        # Unnamed files aren't decompressed, so their hash is already available.
        # Named files can be decompressed, therefore we don't know their
        # relative path until now.
        if is_unnamed:
            entry_hash = int(file_name, 16)
        else:
            entry_hash = BhdDataEntry.hash_name(rel_path)

        data_entry = BhdDataEntry()
        data_entry.hash = entry_hash
        data_entry.offset, data_entry.size = import_results

        record_is_updated = self._update_record(rel_path, data_entry)
        return record_is_updated

    @staticmethod
    def _get_rel_path(data_dir, file_path):
        """ Return the sanitized relative path of file_path. """
        relative_path = os.path.relpath(file_path, data_dir)
        # Invert backslashes on Windows.
        relative_path = relative_path.replace(os.path.sep, "/")
        return relative_path

    @staticmethod
    def _compress(file_path, remove_original = True):
        """ Compress the file in a DCX file and can remove the original. """
        dcx = Dcx()
        import_success = dcx.load_decompressed(file_path)
        if not import_success:
            return False

        dcx_path = file_path + ".dcx"
        export_success = dcx.save(dcx_path)

        if remove_original:
            os.remove(file_path)
        return export_success

    def _update_record(self, rel_path, data_entry):
        """ Add the data entry to the record associated with that relative path,
        return True on success. """
        try:
            index = next(( int(index)
                           for index, files in self.records_map.items()
                           if rel_path in files ))
        except StopIteration:
            LOG.error("File {} not in any record.".format(rel_path))
            return False
        record = self.bhd.records[index]
        record.entries.append(data_entry)
        return True

    def _update_header(self):
        """ Update the BHD header with values corresponding to the amount of
        records and entries stored; the header is then ready to write. """
        self.bhd.header = BhdHeader()

        num_records = len(self.bhd.records)
        num_data_entries = sum( ( len(record.entries)
                                  for record in self.bhd.records ) )
        file_size = (
            BhdHeader.HEADER_BIN.size +
            BhdRecord.RECORD_BIN.size * num_records +
            BhdDataEntry.DATA_ENTRY_BIN.size * num_data_entries
        )

        self.bhd.header.file_size = file_size
        self.bhd.header.num_records = num_records

    def _save_files(self, bhd_path):
        """ Write both BHD and BDT files to disk. """
        LOG.info("Saving files to disk...")
        self.bhd.save(bhd_path)
        self.bdt.close()


#开发人员   ：Hongjian SU
#开发时间   ：4/19/2019
#开发工具   ：PyCharm

import datetime

a = "Ericsson"
b = "Hongjian SU"
c = input("Note: ")
c = "Note: " + c
d = datetime.datetime.now()
fp = open(r'Test_internal.txt', 'a+')
print(a, b, "\n", c, "\n", d, file=fp)
print(chr(38))
fp.close()

'''
就是
添加点
备注
'''


import logging

from cliff import command

from smiley import db
from smiley import db_linecache
from smiley import output

class Replay(command.Command):
    """Query the database and replay a previously captured run.

    """

    log = logging.getLogger(__name__)

    _cwd = None

    def get_parser(self, prog_name):
        parser = super(Replay, self).get_parser(prog_name)
        parser.add_argument(
            '--database',
            default='smiley.db',
            help='filename for the database (%(default)s)',
        )
        parser.add_argument(
            'run_id',
            help='identifier for the run',
        )
        return parser

    def take_action(self, parsed_args):
        self.db = db.DB(parsed_args.database)
        cache = db_linecache.DBLineCache(self.db, parsed_args.run_id)
        self.out = output.OutputFormatter(cache.getline)

        run_details = self.db.get_run(parsed_args.run_id)
        self.out.start_run(
            run_id=run_details.id,
            cwd=run_details.cwd,
            description=run_details.description,
            start_time=run_details.start_time,
        )
        for t in self.db.get_trace(parsed_args.run_id):
            self.out.trace(
                run_id=t.run_id,
                thread_id=t.thread_id,
                call_id=t.call_id,
                event=t.event,
                func_name=t.func_name,
                line_no=t.line_no,
                filename=t.filename,
                trace_arg=t.trace_arg,
                local_vars=t.local_vars,
                timestamp=t.timestamp,
            )
        self.out.end_run(
            run_id=run_details.id,
            end_time=run_details.end_time,
            message=run_details.error_message,
            traceback=None,
            stats=None,
        )


rating = [8, 8, 7, 5, 5, 5, 4, 2, 1, 1, 1, 1]
print("Существующий рейтинг: ", rating)
elem = input("Введите новое значение: ")
while elem:
    if rating.count(int(elem)) > 0:
        rating.insert(rating.index(int(elem)) + rating.count(int(elem)), int(elem))
        print("Новый  рейтинг: ", rating)
    elif rating[len(rating)-1] > int(elem):
        rating.append(int(elem))
        print("Новый  рейтинг: ", rating)
    else:
        for i in range(len(rating)):
            if rating[i] < int(elem):
                rating.insert(i, int(elem))
                print("Новый  рейтинг: ", rating)
                break
            else:
                continue
    elem = input("Введите новое значение: ")


import functools
import os.path
import sys

import delphyne.trees
import delphyne.behaviours
import delphyne.blackboard
import delphyne.maliput as maliput

import delphyne_gui.utilities

from delphyne_gui.utilities import launch_interactive_simulation

from . import helpers

##############################################################################
# Supporting Classes & Methods
##############################################################################

def parse_arguments():
    "Argument passing and demo documentation."
    parser = helpers.create_argument_parser(
        "City traffic",
        """
An example of city traffic with a variable number of railcars and
MOBIL controlled cars running in a closed-loop maliput road.
        """
    )
    parser.add_argument(
        "-n", "--num-rail-cars", default=40, type=int,
        help="The number of rails cars on scene (default: 40)."
    )
    parser.add_argument(
        "-m", "--num-mobil-cars", default=10, type=int,
        help="The number of MOBIL cars on scene (default: 10)."
    )

    return parser.parse_args()

##############################################################################
# Main
##############################################################################

def lane_position_to_inertial_pose2d(road_geometry, lane_id, lane_position):

    from delphyne.blackboard.providers import resolve
    lane_id = resolve(lane_id, road_geometry)
    lane_position = resolve(lane_position, road_geometry, lane_id)

    road_index = road_geometry.ById()
    lane = road_index.GetLane(maliput.LaneId(lane_id))
    inertial_position = lane.ToInertialPosition(lane_position)
    inertial_orientation = lane.GetOrientation(lane_position)
    xyz = inertial_position.xyz()
    initial_heading = inertial_orientation.rpy().yaw_angle()
    return xyz.x(), xyz.y(), initial_heading

def create_city_scenario_subtree(num_rail_cars, num_mobil_cars):
    file_path = delphyne_gui.utilities.get_delphyne_gui_resource(
        "roads/little_city.yaml"
    )

    if not os.path.isfile(file_path):
        print("Required file {} not found."
              " Please, make sure to install the latest delphyne_gui."
              .format(os.path.abspath(file_path)))
        sys.exit()

    scenario_subtree = delphyne.behaviours.roads.Multilane(
        file_path=file_path, name="little_city"
    )

    provider = delphyne.blackboard.providers.LaneLocationProvider(
        distance_between_agents=6.0, seed=1
    )

    # Sets up all railcars.
    for n in range(num_rail_cars):
        scenario_subtree.add_child(
            delphyne.behaviours.agents.RailCar(
                name='rail{}'.format(n),
                lane_id=provider.random_lane,
                longitudinal_position=0.0,
                lateral_offset=0.0,
                speed=4.0
            )
        )

    # Sets up all MOBIL cars.
    mobilcar_speed = 4.0  # (m/s)
    for m in range(num_mobil_cars):
        scenario_subtree.add_child(
            delphyne.behaviours.agents.MobilCar(
                name='mobil{}'.format(m),
                speed=mobilcar_speed,
                initial_pose=functools.partial(
                    lane_position_to_inertial_pose2d,
                    lane_id=provider.random_lane,
                    lane_position=provider.random_lane_position
                )
            )
        )

    return scenario_subtree

def main():
    """Keeping pylint entertained."""
    args = parse_arguments()

    simulation_tree = delphyne.trees.BehaviourTree(
        root=create_city_scenario_subtree(
            args.num_rail_cars, args.num_mobil_cars
        )
    )

    simulation_tree.setup(
        realtime_rate=args.realtime_rate,
        start_paused=args.paused,
        log=args.log,
        logfile_name=args.logfile_name
    )

    tree_time_step = 0.02
    with launch_interactive_simulation(
        simulation_tree.runner, layout=args.layout, bare=args.bare, ign_visualizer="visualizer"
    ) as launcher:
        if args.duration < 0:
            # run indefinitely
            print("Running simulation indefinitely.")
            simulation_tree.tick_tock(period=tree_time_step)
        else:
            # run for a finite time
            print("Running simulation for {0} seconds.".format(args.duration))
            simulation_tree.tick_tock(
                period=tree_time_step, number_of_iterations=int(args.duration / tree_time_step)
            )
        launcher.terminate()


"""
Unit tests for the bcl_tokenizer submodule.
"""

from bcl_tokenizer import tokenizer as tkn

def __verify_first_token(source: str, expected_type: str, expected_value: str):
    """Verify that the first token produced by the tokenized source has the expected type and value."""

    tokenizer = tkn.Tokenizer(source)

    assert not tokenizer.end_of_stream()

    actual_first_token = tokenizer.next_token()
    assert actual_first_token == {"type": expected_type, "value": expected_value}

def __verify_token(source: str, expected_token: dict):
    """Verify that the source produces exactly one token which matches the expected token when tokenized."""

    tokenizer = tkn.Tokenizer(source)

    actual_token = tokenizer.next_token()

    assert actual_token == expected_token
    assert tokenizer.end_of_stream()

def __verify_token_basic(source: str, expected_token_type: str):
    """
    Verify that the source produces exactly one token which, when tokenized:

    - Has the expected token type.
    - Has a value matching exactly the source.
    """

    __verify_token(source, {"type": expected_token_type, "value": source})

def __verify_not_token_type(source: str, unexpected_token_type: str):
    """Verify that the source does NOT produce the provided token type when tokenized."""

    try:
        tokenizer = tkn.Tokenizer(source)

        while not tokenizer.end_of_stream():
            token = tokenizer.next_token()
            assert token["type"] != unexpected_token_type, token

    except SyntaxError:
        pass

def test_empty():
    """Handling an empty source string."""

    tokenizer = tkn.Tokenizer("")

    assert tokenizer.end_of_stream()
    assert tokenizer.next_token() == {"type": "PROGRAM_END", "value": None}

def test_whitespace():
    """Handling source that is only whitespace."""

    source = "         \n      \n\n\t\n \n \r\n \r      \r\n\r \t     \t \t\r\t\r\n"

    __verify_token(source, {"type": "PROGRAM_END", "value": None})

def test_comments():
    """Handling source that is only comments."""

    source = """\
// This is a comment
// empty comment below
//

/* Block comment - empty block comments below */
/**//**//**/
/* Multi-line
    block comment!
    Still going
*/

/* Single-line comment inside a block comment
    // here it is
*/

// Block comment inside a single-line comment /* hello */
"""

    __verify_token(source, {"type": "PROGRAM_END", "value": None})

def test_number_literals():
    """Handling number literals."""

    __verify_token_basic("0", "NUMBER")
    __verify_token_basic("1", "NUMBER")
    __verify_token_basic("6", "NUMBER")
    __verify_token_basic("10", "NUMBER")
    __verify_token_basic("11", "NUMBER")
    __verify_token_basic("00", "NUMBER")
    __verify_token_basic("00000", "NUMBER")
    __verify_token_basic("05", "NUMBER")
    __verify_token_basic("024", "NUMBER")
    __verify_token_basic("298754", "NUMBER")
    __verify_token_basic("105", "NUMBER")
    __verify_token_basic("76485658457485", "NUMBER")
    __verify_token_basic("3286592", "NUMBER")

    __verify_token_basic("-1", "NUMBER")
    __verify_token_basic("-0", "NUMBER")
    __verify_token_basic("-13", "NUMBER")
    __verify_token_basic("-835623", "NUMBER")
    __verify_token_basic("-65987265795785", "NUMBER")

    __verify_token_basic("1.1", "NUMBER")
    __verify_token_basic("1.0", "NUMBER")
    __verify_token_basic("0.1", "NUMBER")
    __verify_token_basic("0.0", "NUMBER")
    __verify_token_basic("87.69", "NUMBER")
    __verify_token_basic("9832.7745756892246", "NUMBER")
    __verify_token_basic("000287650.0002865832000", "NUMBER")

    __verify_token_basic("-0.1", "NUMBER")
    __verify_token_basic("-0.0", "NUMBER")
    __verify_token_basic("-87.69", "NUMBER")
    __verify_token_basic("-9832.7745756892246", "NUMBER")
    __verify_token_basic("-000287650.0002865832000", "NUMBER")

    __verify_not_token_type("b1", "NUMBER")
    __verify_not_token_type("B1", "NUMBER")
    __verify_not_token_type("1b", "NUMBER")
    __verify_not_token_type("1B", "NUMBER")
    __verify_not_token_type("i6", "NUMBER")
    __verify_not_token_type("l8", "NUMBER")
    __verify_not_token_type("L8", "NUMBER")
    __verify_not_token_type("u3", "NUMBER")
    __verify_not_token_type("U3", "NUMBER")

def test_string_literals():
    """Handling string literals."""

    __verify_token_basic('""', "STRING")
    __verify_token_basic('"Hi"', "STRING")
    __verify_token_basic('"Hello World!"', "STRING")
    __verify_token_basic('"Whoops\nI\nDid\nIt\nAgain"', "STRING")
    __verify_token_basic('"Whoops\r\nI\r\nDid\r\nIt\r\nAgain\r\n(Windows)"', "STRING")
    __verify_token_basic('"A comment looks like /* this */"', "STRING")
    __verify_token_basic('"A comment looks like // this"', "STRING")
    __verify_token_basic('"12"', "STRING")
    __verify_token_basic('"14.09"', "STRING")

    __verify_not_token_type("''", "STRING")
    __verify_not_token_type("'Hi'", "STRING")
    __verify_not_token_type("'Hello World!'", "STRING")
    __verify_not_token_type("Hi", "STRING")
    __verify_not_token_type('"Where is the other quote mark?', "STRING")

    __verify_first_token('"Big F"\n', "STRING", '"Big F"')
    __verify_first_token('"Big F"\r\n', "STRING", '"Big F"')
    __verify_first_token('"Big F" ', "STRING", '"Big F"')

def test_boolean_literals():
    """Handling boolean literals."""

    __verify_token_basic("true", "BOOLEAN")
    __verify_token_basic("false", "BOOLEAN")

    __verify_not_token_type("truey", "BOOLEAN")
    __verify_not_token_type("true9", "BOOLEAN")
    __verify_not_token_type("tru evt", "BOOLEAN")
    __verify_not_token_type("falsey", "BOOLEAN")
    __verify_not_token_type("fal sed", "BOOLEAN")

    __verify_first_token("true{", "BOOLEAN", "true")
    __verify_first_token("true}", "BOOLEAN", "true")
    __verify_first_token("true(", "BOOLEAN", "true")
    __verify_first_token("true)", "BOOLEAN", "true")
    __verify_first_token("true ", "BOOLEAN", "true")
    __verify_first_token("true\n", "BOOLEAN", "true")
    __verify_first_token("true\r\n", "BOOLEAN", "true")
    __verify_first_token("false{", "BOOLEAN", "false")
    __verify_first_token("false}", "BOOLEAN", "false")
    __verify_first_token("false(", "BOOLEAN", "false")
    __verify_first_token("false)", "BOOLEAN", "false")
    __verify_first_token("false ", "BOOLEAN", "false")
    __verify_first_token("false\n", "BOOLEAN", "false")
    __verify_first_token("false\r\n", "BOOLEAN", "false")

def test_keyword_let():
    """Handling the LET keyword."""

    __verify_token_basic("let", "LET")

    __verify_not_token_type("letty", "LET")

    __verify_first_token("let ", "LET", "let")

def test_keyword_while():
    """Handling the WHILE keyword."""

    __verify_token_basic("while", "WHILE")

    __verify_not_token_type("whiley", "WHILE")

    __verify_first_token("while ", "WHILE", "while")

def test_identifiers():
    """Handling identifiers."""

    __verify_token_basic("my_variable", "IDENTIFIER")
    __verify_token_basic("some_2nd_variable", "IDENTIFIER")
    __verify_token_basic("unreadablebutvalid", "IDENTIFIER")
    __verify_token_basic("i", "IDENTIFIER")
    __verify_token_basic("j", "IDENTIFIER")
    __verify_token_basic("x", "IDENTIFIER")

    __verify_not_token_type("CONST_VALUE", "IDENTIFIER")
    __verify_not_token_type("no_uppercase_Letters", "IDENTIFIER")

    __verify_not_token_type("_no_starting_underscores", "IDENTIFIER")
    __verify_not_token_type("1_no_starting_numbers", "IDENTIFIER")

    __verify_not_token_type("true", "IDENTIFIER")
    __verify_not_token_type("false", "IDENTIFIER")
    __verify_not_token_type("let", "IDENTIFIER")
    __verify_not_token_type("print", "IDENTIFIER")
    __verify_not_token_type("while", "IDENTIFIER")
    __verify_not_token_type("if", "IDENTIFIER")

def test_operator_plus():
    """Handling the + operator."""

    __verify_token_basic("+", "+")

    __verify_first_token("+ ", "+", "+")
    __verify_first_token("+ 6", "+", "+")
    __verify_first_token('+ "World"', "+", "+")

def test_operator_subtract():
    """Handling the - operator."""

    __verify_token_basic("-", "-")

    __verify_first_token("- ", "-", "-")
    __verify_first_token("- 2", "-", "-")
    __verify_first_token('- "World"', "-", "-")

def test_operator_multiply():
    """Handling the * operator."""

    __verify_token_basic("*", "*")

    __verify_first_token("* ", "*", "*")
    __verify_first_token("* 6", "*", "*")

def test_operator_divide():
    """Handling the / operator."""

    __verify_token_basic("/", "/")

    __verify_first_token("/ ", "/", "/")
    __verify_first_token("/ 2", "/", "/")

def test_operator_assignment():
    """Handling the = operator."""

    __verify_token_basic("=", "=")

    __verify_first_token("= ", "=", "=")
    __verify_first_token("= 2", "=", "=")
    __verify_first_token('= "World"', "=", "=")

    __verify_not_token_type("==", "=")
    __verify_not_token_type("== ", "=")
    __verify_not_token_type("== 5", "=")

def test_operator_equality():
    """Handling the == operator."""

    __verify_token_basic("==", "==")

    __verify_first_token("== ", "==", "==")
    __verify_first_token("== 2", "==", "==")
    __verify_first_token('== "World"', "==", "==")

    __verify_not_token_type("=", "==")
    __verify_not_token_type("= ", "==")
    __verify_not_token_type("= 5", "==")

def test_operator_inequality():
    """Handling the != operator."""

    __verify_token_basic("!=", "!=")

    __verify_first_token("!= ", "!=", "!=")
    __verify_first_token("!= 2", "!=", "!=")
    __verify_first_token('!= "World"', "!=", "!=")

    __verify_not_token_type("=", "!=")
    __verify_not_token_type("= ", "!=")
    __verify_not_token_type("= 5", "!=")

def test_operator_less_than():
    """Handling the < operator."""

    __verify_token_basic("<", "<")

    __verify_first_token("< ", "<", "<")
    __verify_first_token("< 2", "<", "<")

    __verify_not_token_type("<=", "<")
    __verify_not_token_type("<= ", "<")
    __verify_not_token_type("<= 5", "<")

def test_operator_less_than_or_equal():
    """Handling the <= operator."""

    __verify_token_basic("<=", "<=")

    __verify_first_token("<= ", "<=", "<=")
    __verify_first_token("<= 2", "<=", "<=")

    __verify_not_token_type("<", "<=")
    __verify_not_token_type("= 5 <", "<=")

def test_operator_more_than():
    """Handling the > operator."""

    __verify_token_basic(">", ">")

    __verify_first_token("> ", ">", ">")
    __verify_first_token("> 2", ">", ">")

    __verify_not_token_type(">=", ">")
    __verify_not_token_type(">= ", ">")
    __verify_not_token_type(">= 5", ">")

def test_operator_more_than_or_equal():
    """Handling the >= operator."""

    __verify_token_basic(">=", ">=")

    __verify_first_token(">= ", ">=", ">=")
    __verify_first_token(">= 2", ">=", ">=")

    __verify_not_token_type(">", ">=")
    __verify_not_token_type("= 5 >", ">=")

def test_keyword_func():
    """Handling the 'func' keyword."""

    __verify_token_basic("func", "FUNC")

    __verify_first_token("func ", "FUNC", "func")
    __verify_first_token("func foo", "FUNC", "func")

    __verify_not_token_type("fun", "FUNC")
    __verify_not_token_type("fu = nc", "FUNC")
    __verify_not_token_type("FUNC", "FUNC")
    __verify_not_token_type("fun_c", "FUNC")

def test_keyword_return():
    """Handling the 'return' keyword."""

    __verify_token_basic("return", "RETURN")

    __verify_first_token("return ", "RETURN", "return")
    __verify_first_token("return foo", "RETURN", "return")

    __verify_not_token_type("ret", "RETURN")
    __verify_not_token_type("ret = urn", "RETURN")
    __verify_not_token_type("RETURN", "RETURN")
    __verify_not_token_type("re_turn", "RETURN")

def test_keyword_do():
    """Handling the 'do' keyword."""

    __verify_token_basic("do", "DO")

    __verify_first_token("do ", "DO", "do")
    __verify_first_token("do foo", "DO", "do")

    __verify_not_token_type("doo", "DO")
    __verify_not_token_type("d = o", "DO")
    __verify_not_token_type("DO", "DO")