import numpy as np
import imageio
import cv2
import matplotlib.pyplot as plt

'''
original matlab code at https://www.robots.ox.ac.uk/~vgg/research/caltech/phog.html
'''

def anna_phog(Img, bin, angle, L, roi):
    '''
     anna_PHOG Computes Pyramid Histogram of Oriented Gradient over a ROI.

     [BH, BV] = anna_PHOG(Img,BIN,ANGLE,L,ROI) computes phog descriptor over a ROI.

     Given and image Img, phog computes the Pyramid Histogram of Oriented Gradients
     over L pyramid levels and over a Region Of Interest

    IN:
        Img- Images numpy array of size MxN (Color or Gray)
        bin - Number of bins on the histogram
        angle - 180 or 360
       L - number of pyramid levels
       roi - Region Of Interest (ytop,ybottom,xleft,xright)

    OUT:
        p - pyramid histogram of oriented gradients
    '''
    if Img.shape[2] == 3:
        G = cv2.cvtColor(Img, cv2.COLOR_BGR2GRAY)
    else:
        G = Img

    if np.sum(G) > 100:
        # apply automatic Canny edge detection using the computed median
        sigma = 0.33
        v = np.median(G)
        lower = int(max(0, (1.0 - sigma) * v))
        upper = int(min(255, (1.0 + sigma) * v))
        E = cv2.Canny(G,lower,upper) #high and low treshold
        GradientX, GradientY = np.gradient(G)
        GradientYY = np.gradient(GradientY, axis=1)

        Gr = np.sqrt(np.square(GradientX)+np.square(GradientY))
        index = GradientX == 0
        GradientX[index] = 1e-5 #maybe another value

        YX = GradientY*GradientX
        if angle == 180: A = ((np.arctan(YX)+(np.pi/2))*180)/np.pi
        if angle == 360: A = ((np.arctan2(GradientY,GradientX)+np.pi)*180)/np.pi

        bh, bv = anna_BinMatrix(A,E,Gr,angle,bin)

    else:
        bh = np.zeros(Img.shape)
        bv = np.zeros(Img.shape)

    bh_roi = bh[roi[0]:roi[1], roi[2]:roi[3]]
    bv_roi = bv[roi[0]:roi[1], roi[2]:roi[3]]

    p = anna_PhogDescriptor(bh_roi,bv_roi,L,bin)
    return p

def anna_BinMatrix(A,E,G,angle,bin):
    '''
    anna_BINMATRIX Computes a Matrix (bm) with the same size of the image where
    (i,j) position contains the histogram value for the pixel at position (i,j)
    and another matrix (bv) where the position (i,j) contains the gradient
    value for the pixel at position (i,j)

    IN:
    	A - Matrix containing the angle values
    	E - Edge Image
        G - Matrix containing the gradient values
    	angle - 180 or 360
        bin - Number of bins on the histogram

    OUT:
    	bm - matrix with the histogram values
        bv - matrix with the gradient values (only for the pixels belonging to and edge)
    '''
    n, contorns = cv2.connectedComponents(E, connectivity=8)

    X = E.shape[1]
    Y = E.shape[0]
    bm = np.zeros(shape=(Y,X))
    bv = np.zeros(shape=(Y,X))

    nAngle = angle/bin

    for i in range(n):
        posY, posX = np.where(contorns==i)
        for j in range(posY.shape[0]):
            pos_x = posX[j]
            pos_y = posY[j]

            b = np.ceil(A[pos_y,pos_x]/nAngle)
            if b==0: bin=1
            if G[pos_y,pos_x]>0:
                bm[pos_y,pos_x] = b
                bv[pos_y,pos_x] = G[pos_y,pos_x]

    return (bm, bv)

def anna_PhogDescriptor(bh,bv,L,bin):
    '''
     anna_PHOGDESCRIPTOR Computes Pyramid Histogram of Oriented Gradient over a ROI.

    IN:
        bh - matrix of bin histogram values
        bv - matrix of gradient values
       L - number of pyramid levels
       bin - number of bins

    OUT:
        p - pyramid histogram of oriented gradients (phog descriptor)
    '''
    p = np.array([])
    #level 0
    for b in range(bin):
        ind = bh==b
        p = np.append(p, np.sum(bv[ind]))

    #higher levels
    for l in range(1, L+1):
        x = int(np.trunc(bh.shape[1]/(2**l)))
        y = int(np.trunc(bh.shape[0]/(2**l)))
        for xx in range(0, bh.shape[1]-x+1, x):
            for yy in range(0, bh.shape[0]-y+1, y):
                print(l)
                bh_cella = bh[yy:yy+y, xx:xx+x]
                bv_cella = bv[yy:yy+y, xx:xx+x]

                for b in range(bin):
                    ind = bh_cella==b
                    p = np.append(p, np.sum(bv_cella[ind], axis=0))

    if np.sum(p)!=0:
        p = p/np.sum(p)

    return p


from functions.listener import *
from functions.worker import *

print("1. Voice")
print("2. Text")
choice = input(">")
while True:
	while keyboard.is_pressed("up") or choice == "2":
		if choice == "1": text = listener()
		if choice == "2": text = input(">")

		print("> ",text)
		if text =="exit": break

		if searcher(0,text)=="start_app": open_app(text)
		if searcher(0,text)=="init_start": startup_app()
		if searcher(0,text)=="close_app": close_app()
		if searcher(0,text)=="specific":
			print("Project In? ")
			if choice == "1": text = listener(howlong = 8)
			if choice == "2": text = input(">")
			specific_app(text)
		if text.find("close")!=-1:close_app()
		if text.find("change")!=-1 and text.find("tab")!=-1: alttab()

#print(searcher(0,"open_notepad"))


"""
Here you can play with these hyper parameters, to try and get a better solution
"""
# All the pieces
QUEEN = 'bQ'
KNIGHT = 'bK'
BISHOP = 'bB'
ROOK = 'bR'
# Hyper parameters
TABLE_SIZE = 20
POP_SIZE = 100
INIT_SIZE = 1000
NUM_PARENTS = 2
NUM_GENERATIONS = 100
MUTATE_CHANCE = 0.95
PIECE = KNIGHT

# Extra
K = int((TABLE_SIZE - 1)/2)
CHROMOSOME_MAX = {
                    QUEEN: TABLE_SIZE,
                    BISHOP: 2 * TABLE_SIZE - 2,
                    ROOK: TABLE_SIZE,
                    KNIGHT: int((TABLE_SIZE * TABLE_SIZE) / 2) if (TABLE_SIZE % 2 == 0) else int(2*(K*K + K) + 1)
                  }

"""
Best values for 50 size
    TABLE_SIZE = 50
    POP_SIZE = 100
    INIT_SIZE = 1000
    NUM_PARENTS = 4
    NUM_GENERATIONS = 50000
    MUTATE_CHANCE = 0.95
"""


import random
import pygame

from pygame import mixer
from Levels import LevelsGrid
from Levels import CheckpointCoords

pygame.mixer.pre_init(44100, -16, 2, 512)
pygame.init()
mixer.init()

screen_width = 1000
screen_height = 600

player_width = 30
player_height = 60

cubewidth = 40

window = pygame.display.set_mode((screen_width,screen_height))

clock = pygame.time.Clock()
fps = 60

#------------- FONT -------------#

font = pygame.font.SysFont('8bitwondernominal', 40, True)

#---------- BACKGROUND ----------#

BACKGROUND_PNG = pygame.image.load("Images/Background/background.png")

#--------- TEXT SPRITES ---------#

COLLECTALLCOINS_PNG = pygame.image.load("Images/Text/collectallcoins.png")

#--------- GAME SPRITES ---------#

BORDER_PNG = pygame.image.load("Images/Map_Sprites/border.png")
DIRT_PNG = pygame.image.load("Images/Map_Sprites/dirt.png")
GRASS_PNG = pygame.image.load("Images/Map_Sprites/grass.png")
ARROWRIGHT_PNG = pygame.image.load("Images/Map_Sprites/arrowright.png")
ARROWLEFT_PNG = pygame.image.load("Images/Map_Sprites/arrowleft.png")

FULLHEART_PNG = pygame.image.load("Images/Map_Sprites/fullheart.png")
EMPTYHEART_PNG = pygame.image.load("Images/Map_Sprites/emptyheart.png")

CLOSEDDOORBOTTOM_PNG = pygame.image.load("Images/Map_Sprites/closeddoorbottom.png")
CLOSEDDOORTOP_PNG = pygame.image.load("Images/Map_Sprites/closeddoortop.png")

OPENDOORBOTTOM_PNG = pygame.image.load("Images/Map_Sprites/opendoorbottom.png")
OPENDOORTOP_PNG = pygame.image.load("Images/Map_Sprites/opendoortop.png")

COIN_PNG = pygame.image.load("Images/Map_Sprites/coin.png")

LAVA_PNG = pygame.image.load("Images/Map_Sprites/lava.png")
LAVAWHOLE_PNG = pygame.image.load("Images/Map_Sprites/lavawhole.png")

LEVERLEFT_PNG = pygame.image.load("Images/Map_Sprites/leverleft.png")
LEVERRIGHT_PNG = pygame.image.load("Images/Map_Sprites/leverright.png")

#---------- GAME SOUNDS ---------#

LAVA_WAV = pygame.mixer.Sound("Sounds/lava.wav")
OPENDOOR_WAV = pygame.mixer.Sound("Sounds/opendoor.wav")
JUMP_WAV = pygame.mixer.Sound("Sounds/jump.wav")
COIN_WAV = pygame.mixer.Sound("Sounds/coin.wav")
ERROR_WAV = pygame.mixer.Sound("Sounds/error.wav")
NEXTLEVEL_WAV = pygame.mixer.Sound("Sounds/nextlevel.wav")
MENUTICK_WAV = pygame.mixer.Sound("Sounds/menutick.wav")
MENUSELECT_WAV = pygame.mixer.Sound("Sounds/menuselect.wav")

#------------ MUSIC -------------#

pygame.mixer.music.load("Sounds/music.wav")

#---------- GRID CODES ----------#

GRIDECODES = {
    1 : BORDER_PNG,
    2 : DIRT_PNG,
    3 : GRASS_PNG,
    4 : ARROWRIGHT_PNG,
    5 : ARROWLEFT_PNG,
    6 : CLOSEDDOORBOTTOM_PNG,
    7 : CLOSEDDOORTOP_PNG,
    8 : LAVAWHOLE_PNG,
    9 : LAVA_PNG,
    10 : COIN_PNG,
    11 : LEVERLEFT_PNG,
    12 : LEVERRIGHT_PNG
}

#------------ TILES -------------#

TILEBLOCKS = [1,2,3]

tile_list = []

#------------ PLAYER ------------#

class Player():
    def __init__(self, x, y, speed):
        self.images_right = []
        self.images_left = []
        self.index = 0
        self.counter = 0
        for num in range(1,5):
            img_right = pygame.image.load(f'Images/Player_Sprites/guy{num}.png')
            img_right = pygame.transform.scale(img_right, (player_width, player_height))
            img_left = pygame.transform.flip(img_right, True, False)
            self.images_right.append(img_right)
            self.images_left.append(img_left)
        self.image = self.images_right[self.index]
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.speed = speed
        self.vel_y = 0
        self.jumped = False
        self.direction = "R"
        self.landed = True
        self.health = 3

    def atcheckpoint(self,level):

        if CheckpointCoords[level][1]+40 > self.rect.y > CheckpointCoords[level][1]:
            if CheckpointCoords[level][0] < self.rect.x < CheckpointCoords[level][0]+40:
                return True

        return False

    def nearcheckpoint(self,level):

        if CheckpointCoords[level][1]+40 > self.rect.y > CheckpointCoords[level][1]:
            if CheckpointCoords[level][0]-40 < self.rect.x < CheckpointCoords[level][0]+40:
                window.blit(OPENDOORTOP_PNG, (CheckpointCoords[level][0], CheckpointCoords[level][1]))
                window.blit(OPENDOORBOTTOM_PNG, (CheckpointCoords[level][0], CheckpointCoords[level][1] + 40))
                return True

        return False

    def drawhealth(self):

        gap = 10
        first_gap = 50

        first_empty_gap = 146

        for i in range(self.health):
            window.blit(FULLHEART_PNG, (first_gap+ 38*i+gap*i, first_gap))

        for i in range(3-self.health):
            window.blit(EMPTYHEART_PNG, (first_empty_gap-38*i-gap*i, first_gap))

    def update(self,drawhitbox,level):

        key = pygame.key.get_pressed()

        dx = 0
        dy = 0

        walk_cooldown = 10

        if key[pygame.K_0]:
            print (self.rect.x, self.rect.y)
        if key[pygame.K_SPACE] and self.jumped == False and self.landed == True:
            if playsound: JUMP_WAV.play()
            self.vel_y = -15
            self.landed = False
            self.jumped = True
        if not(key[pygame.K_SPACE]):
            self.jumped = False
        if key[pygame.K_a] or key[pygame.K_LEFT]:
            self.direction = "L"
            self.counter += 1
            dx -= self.speed
        if key[pygame.K_d] or key[pygame.K_RIGHT]:
            self.direction = "R"
            self.counter += 1
            dx += self.speed
        if key[pygame.K_a] == False and key[pygame.K_LEFT] == False and key[pygame.K_d] == False and key[pygame.K_RIGHT] == False:
            self.index = 0
            self.counter = 0
            if self.direction == "R":
                self.image = self.images_right[self.index]
            else:
                self.image = self.images_left[self.index]

        if self.counter > walk_cooldown:
            self.counter = 0
            self.index += 1
            if self.index >= len(self.images_right):
                self.index = 0
            if self.direction == "R":
                self.image = self.images_right[self.index]
            else:
                self.image = self.images_left[self.index]

        self.vel_y += 1
        if self.vel_y > 10:
            self.vel_y = 10
        dy += self.vel_y

        for tile in tile_list:
            if tile.colliderect(self.rect.x + dx, self.rect.y, player_width, player_height):
                dx = 0
            if tile.colliderect(self.rect.x, self.rect.y + dy, player_width, player_height):
                if self.vel_y < 0:
                    dy = tile.bottom - self.rect.top
                    self.vel_y = 0
                elif self.vel_y >= 0:
                    self.landed = True
                    dy = tile.top - self.rect.bottom
                    self.vel_y = 0

        for tile in lava_list:
            if tile.colliderect(self.rect.x, self.rect.y + dy-20, player_width, player_height):
                if playsound:
                    LAVA_WAV.play()
                player.takedamage()

        for i in range(len(coin_list)):
            tile = coin_list[i]
            if tile.colliderect(self.rect.x, self.rect.y, player_width, player_height):
                if playsound: COIN_WAV.play()
                LevelsGrid[level][coin_coords[i][0]][coin_coords[i][1]] = 0
                coin_coords.pop(i)
                coin_list.pop(i)
                break

        self.rect.x += dx
        self.rect.y += dy

        window.blit(self.image, self.rect)
        if drawhitbox:
            pygame.draw.rect(window, (255, 255, 255), self.rect, 2)

    def takedamage(self):

        player.health -= 1
        if player.health > 0:
            player.rect.x = 45
            player.rect.y = screen_height - player_height - 80
        else:
            outoflives()

player = Player(45, screen_height-player_height-80, 4)

def fadenextlevel():
    fade = pygame.Surface((screen_width,screen_height))
    fade.fill((0,0,0))
    if playsound: NEXTLEVEL_WAV.play()
    for alpha in range(75):
        fade.set_alpha(alpha)
        window.blit(fade,(0,0))
        pygame.display.update()
        pygame.time.delay(20)

def outoflives():
    main_menu()

def drawgrid(LevelsGrid,level,drawhitbox, newlevel):

    global tile_list
    global lava_list
    global coin_list
    global coin_coords

    if newlevel:
        tile_list = []
        lava_list = []
        coin_list = []
        coin_coords = []

    window.blit(BACKGROUND_PNG, (0,0))

    for row in range(15):
        for coloumn in range(25):
            if LevelsGrid[level][row][coloumn] != 0:
                img = GRIDECODES[LevelsGrid[level][row][coloumn]]
                img_rect = img.get_rect()
                img_rect.x = coloumn*cubewidth
                img_rect.y = row*cubewidth

                window.blit(img,(img_rect.x,img_rect.y))

                if LevelsGrid[level][row][coloumn] in TILEBLOCKS:
                    if newlevel:
                        tile_list.append(img_rect)
                    if drawhitbox:
                        pygame.draw.rect(window,(255,255,255),(coloumn*cubewidth,row*cubewidth,cubewidth,cubewidth),1)

                if LevelsGrid[level][row][coloumn] == 10:
                    if newlevel:
                        coin_coords.append([row,coloumn])
                        coin_list.append(img_rect)
                    if drawhitbox:
                        pygame.draw.rect(window,(255,255,255),(coloumn*cubewidth,row*cubewidth+15,cubewidth,cubewidth),1)

                if LevelsGrid[level][row][coloumn] == 9:
                    if newlevel:
                        lava_list.append(img_rect)
                    if drawhitbox:
                        pygame.draw.rect(window,(255,255,255),(coloumn*cubewidth,row*cubewidth+15,cubewidth,cubewidth),1)
    return False

def pause():

    loop = True
    cursor_index = 1

    while loop:

        pygame.draw.rect(window,(0,0,0),(100,100,800,400))
        pygame.draw.rect(window,(255,255,255),(110,110,780,380),4)
        drawtext("Pause",400,150)
        drawtext("Back",400,350)
        drawtext("*",350,350)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    loop = False
                    if playsound: MENUSELECT_WAV.play()
                if event.key == pygame.K_RETURN:
                    if playsound: MENUSELECT_WAV.play()
                    loop = False

        pygame.display.update()

def drawtext(string,x,y):

    text_surface = font.render(string, True, (255,255,255))
    window.blit(text_surface, (x,y))

def draw_main_menu(cursor_location,cursor_locations):

    window.fill((0,0,0))
    drawtext("Main Menu", 300,200)
    drawtext("Play", 250,350)
    drawtext("Options", 250,400)
    drawtext("Credits", 250,450)
    cursor_y = cursor_locations[cursor_location]
    drawtext("*", 200, cursor_y)
    pygame.display.update()

def options():

    global playsound

    index = 0
    loop = True
    if playsound == True:
        onoff = "on"
    else:
        onoff = "off"

    while loop:

        window.fill((0, 0, 0))
        drawtext("Options", 300, 200)
        drawtext("Main Menu", 250, 450)
        drawtext(f"Sound {onoff}",275, 300)

        if index == 0:
            drawtext("*", 200, 450)
        else:
            drawtext("*", 225, 300)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    if playsound: MENUSELECT_WAV.play()
                    if index == 0:
                        loop = False
                    else:
                        if onoff == "on":
                            onoff = "off"
                            playsound = False
                        else:
                            onoff = "on"
                            playsound = True

                if event.key == pygame.K_w and index != 1:
                    if playsound: MENUSELECT_WAV.play()
                    index += 1
                if event.key == pygame.K_s and index != 0:
                    if playsound: MENUSELECT_WAV.play()
                    index -= 1

        pygame.display.update()

def credits():

    window.fill((0,0,0))
    drawtext("Credits", 300,200)
    drawtext("Me LOL", 300,280)

    drawtext("Main Menu", 250, 450)
    drawtext("*", 200, 450)

    pygame.display.update()

    loop = True
    while loop:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    if playsound: MENUSELECT_WAV.play()
                    loop = False

def main_menu():

    global playsound

    mainmenu = True
    cursor_index = 0
    cursor_locations = [350,400,450]
    playsound = True

    while mainmenu:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w and cursor_index > 0:
                    if playsound: MENUTICK_WAV.play()
                    cursor_index -= 1
                if event.key == pygame.K_s and cursor_index < 2:
                    if playsound: MENUTICK_WAV.play()
                    cursor_index += 1
                if event.key == pygame.K_RETURN:
                    if playsound: MENUSELECT_WAV.play()
                    if cursor_index == 0:
                        mainmenu = False
                    elif cursor_index == 1:
                        options()
                    elif cursor_index == 2:
                        credits()

        draw_main_menu(cursor_index,cursor_locations)

    main()

def main():
    clock.tick(fps)

    player.health = 3

    run = True
    drawhitbox = False

    if playsound: pygame.mixer.music.play(-1,0)

    level = 0
    newlevel = True

    while run:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pause()

        newlevel = drawgrid(LevelsGrid,level,drawhitbox,newlevel)
        AtDoor = player.nearcheckpoint(level)

        if AtDoor:
            if replay:
                replay = False
                if playsound: OPENDOOR_WAV.play()
            if player.atcheckpoint(level):
                if len(coin_list) == 0:
                    fadenextlevel()
                    level += 1
                    newlevel = True
                    player.rect.x = 45
                    player.rect.y = screen_height-player_height-80
                else:
                    if replay2:
                        if playsound: ERROR_WAV.play()
                        replay2 = False
                    window.blit(COLLECTALLCOINS_PNG,(150,250))
                    pygame.display.update()
            else:
                replay2 = True
        else:
            replay = True

        player.update(drawhitbox, level)
        player.drawhealth()

        pygame.display.update()

main_menu()


'''
This problem was asked by Facebook.

Given a stream of elements too large to store in memory, pick a random element from the stream with uniform probability.
'''
# reservoir sampling! https://www.youtube.com/watch?v=A1iwzSew5QY

import random

def pick(stream):
    random_ele = None
    for i, ele in enumerate(stream):
        if random.randint(1, i+1) == i+1:
            random_ele = ele
    return random_ele


from datetime import datetime, timedelta

from openerp import api, fields, models
from openerp.tools.translate import _
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT as OE_DTFORMAT

class SaleOrder(models.Model):

    _inherit = 'sale.order'

    @api.model
    def _get_date_planned(self, order, line, start_date):

        if line and line.requested_date:
            date_planned = datetime.strptime(line.requested_date, OE_DTFORMAT)
            date_planned -= timedelta(days=order.company_id.security_lead)
            return date_planned.strftime(OE_DTFORMAT)

        return super(SaleOrder, self).\
            _get_date_planned(order, line, start_date)

class SaleOrderLine(models.Model):

    """Add several date fields to Sale Order Lines"""

    _inherit = 'sale.order.line'

    @api.depends('state', 'order_id.picking_ids')
    def _get_shipped_date(self):
        """Read the shipping date from the related pickings"""

        for line in self:
            order = line.order_id
            dates_list = []
            for pick in order.picking_ids:
                for move in pick.move_lines:
                    if move.product_id.id == line.product_id.id \
                       and move.state == 'done':
                        dates_list.append(pick.date)
            if dates_list:
                line.shipped_date = max(dates_list)
            else:
                line.shipped_date = False

    @api.depends('product_id', 'delay')
    def _get_commitment_date(self):
        """Compute the commitment date"""

        for line in self:
            if line.state == 'cancel':
                continue
            dates_list = []
            order_datetime = datetime.strptime(line.order_id.date_order,
                                               OE_DTFORMAT)
            dt = order_datetime + timedelta(days=line.delay or 0.0)
            dates_list.append(dt.strftime(OE_DTFORMAT))
            if dates_list:
                line.commitment_date = min(dates_list)

    @api.onchange('requested_date')
    def onchange_requested_date(self):
        """Warn if the requested dates is sooner than the commitment date"""

        for line in self:
            if (line.requested_date and
                    line.commitment_date and
                    line.requested_date < line.commitment_date):
                return {'warning': {
                    'title': _('Requested date is too soon!'),
                    'message': _("The date requested by the customer is "
                                 "sooner than the commitment date. You may be "
                                 "unable to honor the customer's request.")
                }
                }
        return {}

    # Fields
    #
    commitment_date = fields.Datetime(
        compute=_get_commitment_date, store=True, string='Commitment Date',
        help="Date by which the products are sure to be delivered. This is "
             "a date that you can promise to the customer, based on the "
             "Product Lead Times.")
    requested_date = fields.Datetime(
        'Requested Date', readonly=False, copy=False,
        help="Date by which the customer has requested the items to be "
             "delivered.\n"
             "When this Order gets confirmed, the Delivery Order's "
             "expected date will be computed based on this date and the "
             "Company's Security Delay.\n"
             "Leave this field empty if you want the Delivery Order to be "
             "processed as soon as possible. In that case the expected "
             "date will be computed using the default method: based on "
             "the Product Lead Times and the Company's Security Delay.")
    shipped_date = fields.Date(
        compute=_get_shipped_date, store=False, string='Shipped Date',
        help="Date on which the last shipment was made.")


from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
import psycopg2
from PyQt5.uic import loadUiType
from Connect import ConnectDatabase

# Global Variable
listentry_ui, _ = loadUiType('Ui/ListEntryPartLoop.ui')

class ListEntryApp(QDialog, listentry_ui):
    def __init__(self, parent=None):
        super(ListEntryApp, self).__init__(parent)
        self.setupUi(self)
        self.HandleButtonAction()
        self.ShowDepartment_custom()
        self.ShowStatus_entry()
        self.ClearDropDown()
        self.ListEntry_show()

    # Method for Button action
    def HandleButtonAction(self):
        self.pushButtonListEntrySearch.clicked.connect(self.ListEntry_show)
        self.pushButtonListEntryReset.clicked.connect(self.ListEntry_reset)

    # Method to set empty value in drop-down field
    def ClearDropDown(self):
        self.comboBoxListEntryDepartment.setCurrentText('')
        self.comboBoxListEntryStatus.setCurrentText('')

    # Method to show drop-down data
    def ShowDepartment_custom(self):
        self.db = ConnectDatabase()
        self.cur = self.db.cursor()
        self.cur.execute('SELECT department_name FROM department ORDER BY department_name ASC')
        department_list = self.cur.fetchall()
        for department in department_list:
            self.comboBoxListEntryDepartment.addItem(department[0])
        self.db.close()

    def ShowStatus_entry(self):
        self.db = ConnectDatabase()
        self.cur = self.db.cursor()
        self.cur.execute('SELECT status_name FROM status ORDER BY status_name ASC')
        status_list = self.cur.fetchall()
        for status in status_list:
            self.comboBoxListEntryStatus.addItem(status[0])
        self.db.close()

    # Method to show list of entry
    def ListEntry_show(self):
        field_name = self.lineListEntryPartName.text()
        field_department = self.comboBoxListEntryDepartment.currentText()
        field_status = self.comboBoxListEntryStatus.currentText()
        search_name = '%{}%'.format(field_name)
        search_department = '%{}%'.format(field_department)
        search_status = '%{}%'.format(field_status)
        self.db = ConnectDatabase()
        self.cur = self.db.cursor()
        try:
            self.cur.execute('''SELECT entry.id, entry.entry_date, part.part_name, part.part_department,
            entry.entry_status, entry.entry_qty, entry.entry_employee, entry.entry_desc FROM entry JOIN part ON
            entry.part_id = part.id WHERE part.part_name ILIKE %s AND part.part_department ILIKE %s AND
            entry.entry_status ILIKE %s ORDER BY entry.id ASC''',
                             (search_name, search_department, search_status))
            fetch_data = self.cur.fetchall()
        except Exception as error:
            self.error_popup("Duplicate Error", "Failed to connect database")
        else:
            if fetch_data is None:
                self.tableWidgetListEntry.setRowCount(0)
                self.error_popup("List Entry", "No records found!")
            else:
                self.tableWidgetListEntry.setRowCount(0)
                self.tableWidgetListEntry.insertRow(0)
                for row, form in enumerate(fetch_data):
                    for column, item in enumerate(form):
                        self.tableWidgetListEntry.setItem(row, column, QTableWidgetItem(str(item)))
                        column += 1
                        row_position = self.tableWidgetListEntry.rowCount()
                        self.tableWidgetListEntry.insertRow(row_position)
                        self.tableWidgetListEntry.resizeColumnsToContents()
                        self.tableWidgetListEntry.horizontalHeader().setSectionResizeMode(7, QHeaderView.Stretch)
        self.db.close()

    # Method to reset list of entry
    def ListEntry_reset(self):
        self.ClearDropDown()
        self.lineListEntryPartName.clear()
        self.ListEntry_show()

    # Method to show error popup window
    def error_popup(self, title_popup, msg_popup):
        popup = QMessageBox()
        popup.setFixedSize(500, 500)
        popup.setWindowTitle(title_popup)
        popup.setIcon(QMessageBox.Warning)
        popup.setStyleSheet("font:9pt Poppins;")
        popup.setText(msg_popup)
        popup.exec_()


# N: number of cows
# M: number of pairs of integers (swaps)
# K: Repetitions of the M-step process
N, M, K = 0, 0, 0
moves = []
# cows = []
import sys

with open("swap.in", "r") as f:
    temp = f.readline().split(" ")
    N, M, K = int(temp[0]), int(temp[1]), int(temp[2])
    # cows = [i+1 for i in range(N)]
    for i in range(M):
        temp = f.readline().split(" ")
        moves.append([int(i) for i in temp])
# print("k: st, move: st ==> %s" % (cows))

cowPlacements = [[i+1 for i in range(N)]]
start = [i+1 for i in range(N)]

for k in range(K):
    # if k >= 100:
    #     sys.exit("too long")
    qp = cowPlacements[len(cowPlacements)-1].copy()
    for move in moves:
        # print("Adding %s + %s + %s ||| bounds for second: %s, %s" % (cows[0:move[0]-1], cows[(move[1]-1):(move[0]-2):-1], cows[move[1]:], move[1]-1, move[0]-2))

        temp = qp[0:move[0]-1]
        if move[0]-2 < 0:
            temp += qp[move[1]-1::-1]
        else:
            temp += qp[move[1]-1:move[0]-2:-1]

        temp += qp[move[1]:]

        # cows = temp
        # print("after k: %d, move: %s ==> %s\n" % (k, move, temp))
        qp = temp
        cowPlacements.append(temp)

    # cowPlacements.append(qp)
    if qp == start:
        break

del cowPlacements[0]
# for i in cowPlacements:
#     print(i)

# print()
# print("final (%s): %s" % ((K*M-1) % len(cowPlacements), cowPlacements[(K*M-1) % len(cowPlacements)]))
answer = cowPlacements[(K*M-1) % len(cowPlacements)]
print(*answer)

with open("swap.out", "w") as f:
    for i in answer:
        f.write("%d\n" % i)


from PIL import Image, ImageDraw, ImageFilter, ImageEnhance

char_map = " `'\".,:;i!~-+]{|1\\rxucoz6?UCL0O*#W&B@$$"

class Picture:
    def __init__(self, filename, resolution):
        # loading image
        img = Image.open(filename)
        img = img.resize((resolution * round(img.size[0] / img.size[1]), resolution))
        self.image = img
        self.width, self.height = img.size

        # enhance image for cleaner result
        self.image = self.image.filter(ImageFilter.EDGE_ENHANCE)
        self.image = ImageEnhance.Contrast(self.image).enhance(2)

        # required matrices
        self.char_matrix = []
        self.rgb_matrix = []

        # output image
        self.output = Image.new('RGB', (self.width * 10, self.height * 10))

    def generate(self):
        # make 2d array of pixels
        rgb_matrix = list(self.image.getdata())
        self.rgb_matrix = [rgb_matrix[j:j + self.width] for j in range(0, len(rgb_matrix), self.width)]
        # rgb values to intensity values
        intensity_matrix = [[.21 * p[0] + .72 * p[1] + .07 * p[2] for p in pixel_row] for pixel_row in self.rgb_matrix]
        # intensity values to characters
        self.char_matrix = [[char_map[int(i * (len(char_map) - 1) / 255)] for i in i_row] for i_row in intensity_matrix]

    def draw_color(self):
        draw = ImageDraw.Draw(self.output)

        for y in range(self.height):
            for x in range(self.width):
                draw.text((x * 10, y * 10), self.char_matrix[y][x], fill=self.rgb_matrix[y][x])

    def draw_bw(self):
        draw = ImageDraw.Draw(self.output)

        for y in range(self.height):
            for x in range(self.width):
                draw.text((x * 10, y * 10), self.char_matrix[y][x], fill=(255, 255, 255))

    def save_image(self, path):
        self.output.save(path + '.jpg')

    def save_text(self, path):
        string = ""
        for row in self.char_matrix:
            line = [p + p + p for p in row]
            string += ''.join(line) + '\n'

        text_file = open(path + '.txt', "w")
        text_file.write(string)
        text_file.close()


# Programmer Kyle Beadle
# Computer Science I           Sixth Period
# Assignment Graphics No. 2    Due Date: February 26, 2014
#
# Problem Statement - Allow the user to answer a question then print that answer
#                     into IDLE console.
#
from graphics import*
win = GraphWin("",300,300)

#question for the user to answer
txt = Text(Point(150,20),"Which of the following web browsers")
txt2 = Text(Point(150,38),"do you use?")
txt.setStyle('bold')
txt2.setStyle('bold')
txt.draw(win)
txt2.draw(win)

#circles the user will select for an answer
circ1 = Circle(Point(20,100),3)
circ1.draw(win)
circ2 = Circle(Point(20,130),3)
circ2.draw(win)
circ3 = Circle(Point(20,160),3)
circ3.draw(win)
circ4 = Circle(Point(20,190),3)
circ4.draw(win)
circ5 = Circle(Point(20,220),3)
circ5.draw(win)

#answers to the question
txt3 = Text(Point(80,100),"Internet Explorer")
txt3.setSize(10)
txt3.draw(win)
txt4 = Text(Point(47,130),"Safari")
txt4.setSize(10)
txt4.draw(win)
txt5 = Text(Point(75,160),"Google Chrome")
txt5.setSize(10)
txt5.draw(win)
txt6 = Text(Point(50,190),"Firefox")
txt6.setSize(10)
txt6.draw(win)
txt7 = Text(Point(47,220),"Opera")
txt7.setSize(10)
txt7.draw(win)

#enter button
rec = Rectangle(Point(100,250),Point(200,275))
rec.draw(win)
txt8 = Text(Point(150,263),"Enter")
txt8.draw(win)

#get answer from user
click = win.getMouse()
x = click.getX()
y = click.getY()
answer = False
while x > 0 and y > 0:
    #creates an invisible box around Internet Explorer
    if(x>15 and x<150)and(y>90 and y<115):
        #fills selected circle
        circ1.setFill("black")
        circ2.setFill("white")
        circ3.setFill("white")
        circ4.setFill("white")
        circ5.setFill("white")
        answer = True
        answer2= "Internet Explorer"
    #creates an invisible box around Safari
    if(x>15 and x<150)and(y>120 and y<130):
        #fills selected circle
        circ1.setFill("white")
        circ2.setFill("black")
        circ3.setFill("white")
        circ4.setFill("white")
        circ5.setFill("white")
        answer = True
        answer2= "Safari"
    #creates an invisible box around Google Chrome
    if(x>15 and x<150)and(y>150 and y<1175):
        #fills selected circle
        circ1.setFill("white")
        circ2.setFill("white")
        circ3.setFill("black")
        circ4.setFill("white")
        circ5.setFill("white")
        answer = True
        answer2= "Google Chrome"
    #creates an invisible box around Firefox
    if(x>15 and x<150)and(y>180 and y<2015):
        #fills selected circle
        circ1.setFill("white")
        circ2.setFill("white")
        circ3.setFill("white")
        circ4.setFill("black")
        circ5.setFill("white")
        answer = True
        answer2= "Firefox"
    #creates an invisible box around Opera
    if(x>15 and x<150)and(y>210 and y<235):
        #fills selected circle
        circ1.setFill("white")
        circ2.setFill("white")
        circ3.setFill("white")
        circ4.setFill("white")
        circ5.setFill("black")
        answer = True
        answer2= "Opera"
    #lets user click on enter button after answer is selected
    #if an answer is not selected nothing happens
    if(x>100 and x<200)and(y>250 and y<275) and answer==True:
        win.close() #closes window
        print("You use %s!"%(answer2)) #prints the users answer
    #checks to see if the loop will be repeated
    click = win.getMouse()
    x = click.getX()
    y = click.getY()
#done


import math
import random

def ClosestPair(A):

    # returns distance in the form of (point1, point2, distance)
    def distance(P, Q):
        Soln = []
        Soln.append(P)
        Soln.append(Q)
        Soln.append(math.sqrt((((P[0]) - (Q[0])) ** 2) + (((P[1]) - (Q[1])) ** 2)))
        return Soln

    # Pre-processing step
    def Pre(Array):
        def get_2nd(element):
            return element[1]
        def get_1st(element):
            return element[0]
        # sorting occurding to x and y coordinates
        X = sorted(Array, key=get_1st)
        Y = sorted(Array, key=get_2nd)
        return [X, Y]

    # Recursive calls
    def Process(W):
        X = W[0]
        Y = W[1]
        distance_points = []

        # for split points
        def SplitClosestPair(Z):
            x = Z[0]
            y = Z[1]
            min_dis = Z[2]
            first = min_dis[0]
            second = min_dis[1]
            x_mid = x[math.ceil(len(x)/2)]
            strip = []
            smallest = min_dis

            # checks to see if the point lies inside the strip (result would be sorted by y-cordinate)
            for e in y:
                if (abs(x_mid[0] - e[0]) <= min_dis[2]):
                    strip.append(e)

            # checks if any 2 points in "strip" have a distance that is less than the distance previosly calculates
            for s in range(0, len(strip)):
                for t in range(1, min(7, len(strip)-s)):
                    length = distance(strip[s], strip[s + t])
                    if smallest[2] > length[2]:
                        smallest = length
            return smallest

        # base case
        if len(X) <= 3:
            for p in X:
                X.remove(p)
                for q in X:
                    distance_points.append(distance(p, q))
            return min(distance_points)

        # recursive call for the left side
        else:
            mid = int(math.ceil(len(X)/2))
            left_X = X[:mid]
            right_X = X[mid:]
            left_Y = Y[:mid]
            right_Y = Y[mid:]
            min_left = Process([left_X, left_Y])
            min_right = Process([right_X, right_Y])
            if min_right[2] >= min_left[2]:
                min_left_and_right = min_left
            else:
                min_left_and_right = min_right
            return SplitClosestPair([X, Y, min_left_and_right])
    return Process(Pre(A))

def random_points(num):
    theList = []
    for i in range(num):
        x = random.uniform(-1000.1, 1000.1)
        y = random.uniform(-1000.1, 1000.1)
        theList.append([x, y])
    return theList

test = random_points(1000)
print(test)
print(ClosestPair(test))

python/Algorithms/Divide & Conquer/Closest Pair.py


from django.urls import path
from django.contrib.auth import views as auth_views
from rest_framework.routers import DefaultRouter
from mainsite.views import (
    HomeView,
    ProfileViewSet,
    HashtagView,
    ProductViewSet,
)

router = DefaultRouter()
router.register(r"products", ProductViewSet, basename="products")

urlpatterns = [
    path("", HomeView.as_view(), name="home"),
    # path("profile/", ProfileViewSet.as_view(), name="profile"),
    # path("<hashtag>/", HashtagView.as_view(), name="hashtag"),
]

urlpatterns += router.urls


#! /usr/bin/env python3
from genpy import message
import rospy
from std_msgs.msg import String

def CallBack_FN(msg):
    messagee = msg.data
    arr = messagee.split(',')
    rospy.loginfo("\n%s\n%s\n%s",arr[0],arr[1],arr[2])

def data_processing():
    rospy.init_node('data_processing')
    rospy.Subscriber('/raw_data', String, callback=CallBack_FN)
    rospy.spin()

if __name__ == "__main__":
    data_processing()


from django.utils.translation import gettext_lazy as _
from rest_framework import serializers

class LinkOrgSerializer(serializers.Serializer):
    id = serializers.CharField(max_length=36, label='ID', read_only=True)
    name = serializers.CharField(max_length=64, label=_('二级机构名'), allow_blank=False, allow_null=False, required=True)
    remarks = serializers.CharField(label=_('备注'), max_length=255, allow_blank=True, allow_null=True, required=False, default='')
    location = serializers.CharField(label=_('经纬度'), max_length=64, allow_blank=True, allow_null=True, required=False, default='')
    data_center = serializers.SerializerMethodField(label=_('数据中心'), method_name='get_data_center')

    @staticmethod
    def get_data_center(obj):
        data_center = obj.data_center
        if data_center is not None:
            return {'id': data_center.id, 'name': data_center.name, 'name_en': data_center.name_en}
        return None


#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
* @Author: Kai CHEN@z0041zvt
* @CreateDate: 2020-07-23 13:58:17
* @LastEditors: Kai CHEN@z0041zvt
* @LastEditTime: 2020-07-23 14:08:31
* @Email: kai-chen@siemens-healthineers.com
* @Description:
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2 as cv
import pathlib
import numpy as np

class Undistortion(object):
    def __init__(self, path, enableNewMtx=True):
        self.__enableNewMtx = enableNewMtx
        self.__mtx, self.__dist = None, None
        self.__parseParams(path)
        self._genUndistMap()

    def __parseParams(self, path):
        fs = cv.FileStorage(path, cv.FileStorage_READ)
        __p = pathlib.Path(path)
        if not __p.exists():
            raise IOError("Can't find intrinsic parameter file!")
        assert __p.suffixes[0] == ".yml"

        self.__mtx = fs.getNode("Camera Matrix").mat()
        self.__dist = fs.getNode("Distortion").mat()
        assert isinstance(self.__mtx, np.ndarray) and isinstance(self.__dist, np.ndarray)

        self._resolution = tuple(fs.getNode("Resolution").mat())
        fs.release()

    def _genUndistMap(self):

        if self.__enableNewMtx:
            _newcameramtx, self._roi = cv.getOptimalNewCameraMatrix(
                self.__mtx, self.__dist, self._resolution, 1.0, self._resolution)
        else:
            _newcameramtx = self.__mtx
            self._roi = (0, 0, *self.__resolution)

        self._mapx, self._mapy = cv.initUndistortRectifyMap(
            self.__mtx, self.__dist, None, _newcameramtx, self._resolution, 5)

    def exec(self, image, crop=True):

        dst = cv.remap(image, self._mapx, self._mapy, cv.INTER_AREA)
        if not crop:
            return dst
        else:
            x, y, w, h = self._roi
            dst = dst[y:y+h, x:x+w]
            return dst

if __name__ == "__main__":
    #example
    _path = pathlib.Path('./IntrinsicParameter.yml')
    _undist = Undistortion(str(_path))
    image = cv.imread('raw.mp4#t=0.jpg')

    uImage = _undist.exec(image, True)

    cv.imshow('undistortion', uImage)
    cv.imshow('origin', image)
    cv.waitKey()


# coding: utf-8

# In[2]:

import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim

import numpy as np

from PIL import Image
import matplotlib.pyplot as plt

import torchvision.transforms as transforms
import torchvision.models as models

import copy

# In[3]:

use_cuda = torch.cuda.is_available()

dtype = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor

# # Preparing the data

# In[4]:

imsize = 512 if use_cuda else 128

loader_transform = transforms.Compose([
    transforms.Scale(imsize),
    transforms.ToTensor()
])

# # important notes for pytorch training

# the PIL load image with values between 0 and 255. After being transformed to torch floatTensor,
# the values are between 0 and 1.
# neural networks from torch library are trained with 0-1 tensor image. Feeding images with values
# between 0 and 255 makes no sense. While in Cafe the networks are pretrained with 0-255 tensor
# images

# In[5]:

def image_loader(image_name):
    image = Image.open(image_name)
    image = Variable(loader_transform(image))

    image = image.unsqueeze(0)
    # fake the batch dimension to fit the neural network input dimensions
    return image

# In[6]:

style_img = image_loader('picasso.jpg').type(dtype)
content_img = image_loader('dancing.jpg').type(dtype)

print(type(style_img))
assert style_img.size() == content_img.size(), 'we need to import style and content images of the same size'

# # display the images

# In[7]:

unloader_transform = transforms.ToPILImage()

#plt.ion()

def imshow(tensor, title = None):
    image = tensor.clone().cpu()
    image = image.squeeze(0) # an optinal operation image.view(3,imsize,imsize)
    #trnsform the image with values from 0-1 to 0-255 for (3, 128, 128) to (128, 128, 3)
    image = unloader_transform(image)
    #print(image.size)

    #image = image.numpy().transpose(1,2,0)
    #print(image.shape)
    plt.imshow(image)

    if title is not None:
        plt.title(title)
    plt.pause(0.001)

# In[8]:

##plt.figure()
##imshow(style_img.data, title = 'Style Image')
##plt.figure()
##imshow(content_img.data, title = 'Content Iamge')

#plt.show()

# In[9]:

class ContentLoss(nn.Module):

    def __init__(self, target, weight):
        super(ContentLoss, self).__init__()
        #self.target = target.clone() * weight
        # this is a problem in calculating gradient when using clone()
        self.target = target.detach() * weight
        #self.target.requires_grad = False
        self.weight = weight
        self.criterion = nn.MSELoss()

    def forward(self, input):
        self.loss = self.criterion(input * self.weight, self.target)
        self.output = input
        return self.output
    def backward(self, retain_variables = True):
        self.loss.backward(retain_variables = retain_variables)
        return self.loss

# In[10]:

class GramMatrix(nn.Module):
    def forward(self, input):
        a,b,c,d = input.size()

        features = input.view(a*b,c*d)

        G = torch.mm(features, features.t())

        return G.div(a * b * c * d)

# In[11]:

class StyleLoss(nn.Module):

    def __init__(self, target, weight):
        super(StyleLoss, self).__init__()
        self.target = target.detach() * weight
        #self.target = target.detach() * weight
        #self.target.requires_grad = False
        self.weight = weight
        self.gram = GramMatrix()
        self.criterion = nn.MSELoss()

    def forward(self, input):
        self.output = input.clone()
        self.G = self.gram(input)
        self.G.mul_(self.weight)
        self.loss = self.criterion(self.G, self.target)
        return self.output
    def backward(self, retain_variables = True):
        self.loss.backward(retain_variables = retain_variables)
        return self.loss

# In[12]:

cnn = models.vgg19(pretrained = True).features
if use_cuda:
    cnn = cnn.cuda()

print(list(cnn))

# In[13]:

content_layers_default = ['conv_4']
style_layers_default = ['conv_1', 'conv_2', 'conv_3', 'conv_4', 'conv_5']

def build_model(cnn, style_img, content_img,
                style_weight = 1000, content_weight = 1,
               content_layers = content_layers_default,
               style_layers = style_layers_default):
    cnn = copy.deepcopy(cnn)

    content_losses = []
    style_losses = []

    model = nn.Sequential()

    gram = GramMatrix()

    if use_cuda:
        model = model.cuda()
        gram = gram.cuda()

    i = 1
    for layer in list(cnn):
        if isinstance(layer, nn.Conv2d):
            name = 'conv_' + str(i)
            model.add_module(name, layer)

            if name in content_layers:
                target = model(content_img).clone()
                content_loss = ContentLoss(target, content_weight)
                model.add_module('content_loss' + str(i), content_loss)
                content_losses.append(content_loss)

            if name in style_layers:
                target_feature = model(style_img).clone()
                target_feature_gram = gram(target_feature)
                style_loss = StyleLoss(target_feature_gram, style_weight)
                model.add_module('style_loss_' + str(i), style_loss)
                style_losses.append(style_loss)

        if isinstance(layer, nn.ReLU):
            name = 'relu_' + str(i)
            model.add_module(name, layer)

            if name in content_layers:
                target = model(content_img).clone()
                content_loss = ContentLoss(target, content_weight)
                model.add_module('content_loss' + str(i), content_loss)
                content_losses.append(content_loss)

            if name in style_layers:
                target_feature = model(style_img).clone()
                target_feature_gram = gram(target_feature)
                style_loss = StyleLoss(target_feature_gram, style_weight)
                model.add_module('style_loss_' + str(i), style_loss)
                style_losses.append(style_loss)
            i += 1

        if isinstance(layer, nn.MaxPool2d):
            name = 'pool' + str(i)
            model.add_module(name, layer)

    return model, style_losses, content_losses

# In[14]:

input_img = content_img.clone()
# input_img = Varaible(troch.randn(content_img.data.size())).type(dtype)

##plt.figure()
##imshow(input_img.data, title = 'Input Image')
#plt.show()

# In[15]:

def get_input_param_optimizer(input_img):
    input_param = nn.Parameter(input_img.data)
    optimizer = optim.LBFGS([input_param])
    return input_param, optimizer

# In[18]:

def run_transfer(cnn, content_img, style_img, input_img, num_steps = 300,
                style_weight = 1000, content_weight = 1):
    print('building style transfer model...')
    model, style_losses, content_losses = build_model(cnn, style_img,content_img, style_weight,content_weight)
    input_param, optimizer = get_input_param_optimizer(input_img)

    print('Optimizing...')

    global iteration
    iteration = 0
    while iteration <= num_steps:

        def transfer_step():
            global iteration
            input_param.data.clamp_(0, 1)

            model(input_param)

            style_score = 0
            content_score = 0

            for style in style_losses:
                style_score += style.backward()
            for content in content_losses:
                content_score += content.backward()

            iteration += 1
            if iteration % 50 == 0:
                print('run {}:'.format(iteration))
                print('style loss:{:4f} \n content loss:{:4f}'.format(
                style_score.data[0], content_score.data[0]))

            return style_score + content_score

        optimizer.zero_grad()
        optimizer.step(transfer_step)
    input_param.data.clamp_(0, 1)

    return input_param.data

# In[ ]:

output = run_transfer(cnn, content_img, style_img, input_img)

plt.figure()
imshow(output, title = 'result')

plt.ioff()
plt.show()

# In[ ]:


import pytest

import ECHO
import numpy as np
import os

'''
Tests to make:
*ulog read
*tlog read
*CST read
*rx read

'''
test_tlog = os.path.abspath('.') +'/tests/data/Shortened_NSTop_tlog.txt'
test_cst = os.path.abspath('.') +'/tests/data/Chiropter_NS_cst.txt'
test_rx = os.path.abspath('.') +'/tests/data/Shortened_NS_Top_rxdata.hdf5'

def test_tlog_read():
    wpt_array, global_array, local_array, gps_array = ECHO.read_utils.read_tlog_txt(test_tlog)
    #assert
    return

def test_ulog_read():
    #can test the CSV reads, but the ulog reads require a full .ulog file and those are pretty big.
    return

def test_read_h5():
    #Test that our
    assert(os.path.isfile(test_rx) == True)
    datadict = ECHO.read_utils.read_h5(test_rx)
    keylist=[]
    for key in datadict['Observation1'].keys():
        keylist.append(key)
    assert(len(keylist)==3)
    assert(keylist[0]=='Tuning1')
    assert(keylist[1]=='Tuning2')
    assert(keylist[2]=='time')
    return

def test_cst_to_hp():
    testhpmap = ECHO.read_utils.CST_to_hp(test_cst, outfile=os.path.abspath('.') +'/tests/data/Chiropter_NS_cst.fits')
    assert(testhpmap.shape == (768,))
    return

def test_read_CST_puv():
    testcstpuv = ECHO.read_utils.read_CST_puv(
        test_cst,
        beam_type='efield',
        frequency=[70e6],
        telescope_name='Chiropter',
        feed_name='BicoLOG',
        feed_version='1.0',
        model_name = 'Chiropter_NS_2019',
        model_version='1.0',
        feed_pol='y')
    assert(testcstpuv.data_array.shape == (2, 1, 2, 1, 37, 72))
    return


import logging
from abc import abstractmethod, ABCMeta

class AbstractJob(metaclass=ABCMeta):
    '''AbstractJob provides common functionality for jobs that executes various set of tasks on spark.'''

    def __init__(self, sc, spark, gc, config):
        logging.basicConfig(level=logging.INFO)
        self.logger = logging.getLogger(self.__class__.__name__)
        self.sc = sc
        self.spark = spark
        self.gc = gc
        self.config = config

    @abstractmethod
    def try_execute(self, sc, spark, gc, config):
        pass

    def execute(self):
        self.logger.info("Executing job %s", (self.__class__.__name__,))
        try:
            self.try_execute( self.sc, self.spark, self.gc, self.config)
            self.logger.error("Executing job %s completed", self.__class__.__name__)
        except Exception as exception:
            # unexpected error, should retry
            self.logger.error("Error while executing job %s", self.__class__.__name__, exc_info=exception)


while True:

	I = input()
	m, f, r = map(int, I.split())

	if m==-1 and f==-1 and r==-1:
		break

	if m==-1 or f==-1 or m+f<30:
		print("F")
	elif 30<=m+f and m+f<50:
		if 50<=r:
			print("C")
		else:
			print("D")
	elif 50<=m+f and m+f<65:
		print("C")
	elif 65<=m+f and m+f<80:
		print("B")
	else:
		print("A")


import sys
from copy import deepcopy
input = sys.stdin.readline

def print_board():
    for i in range(r):
        print(''.join(board[i]))

def time_plus(board, time, r, c):
    for i in range(r):
        for j in range(c):
            if board[i][j] == 'O':
                time[i][j] += 1

def set_bomb(board, time, r, c):
    for i in range(r):
        for j in range(c):
            if board[i][j] != 'O':
                board[i][j] = 'O'
                time[i][j] = 1

def bomb(board, time, r, c):
    dx = (-1, 0, 1, 0)
    dy = (0, -1, 0, 1)
    tmp_time = deepcopy(time)
    for i in range(r):
        for j in range(c):
            if tmp_time[i][j] >= 3:
                board[i][j] = '.'
                time[i][j] = 0
                for k in range(4):
                    rr = i + dx[k]
                    cc = j + dy[k]
                    if rr < 0 or rr >= r or cc < 0 or cc >= c:
                        continue
                    board[rr][cc] = '.'
                    time[rr][cc] = 0

r, c, n = map(int, input().split())
board = [list(input().rstrip()) for _ in range(r)]
time = [[0] * c for _ in range(r)]

time_plus(board, time, r, c)

for t in range(2, n + 1):
    time_plus(board, time, r, c)
    if t % 2 == 0:
        set_bomb(board, time, r, c)
    if t % 2 == 1:
        bomb(board, time, r, c)

print_board()


import os
from cv2 import BOWKMeansTrainer
import torch
import logging
from collections import defaultdict

from utils.env import pathmgr

logger = logging.getLogger(__name__)

def load_features_boxes(cfg):
    """
    Load boxes features from faster cnn trained model. Used for initialization
    in actions and tools detection.

    Args:
        cfg (CfgNode): config.

    Returns:
        features (tensor): a tensor of faster weights.
    """
    features = torch.load(cfg.FASTER.FEATURES_VAL)
    real_features = {}
    for feat in features:
        file_name = feat['file_name']
        assert file_name not in real_features, '{}'.format(file_name)
        real_features[file_name]=feat['bboxes']

    return real_features

def load_image_lists(cfg):
    """
    Loading image paths from corresponding files.

    Args:
        cfg (CfgNode): config.
        is_train (bool): if it is training dataset or not.

    Returns:
        image_paths (list[list]): a list of items. Each item (also a list)
            corresponds to one video and contains the paths of images for
            this video.
        video_idx_to_name (list): a list which stores video names.
    """
    # breakpoint()
    list_filenames = [
        os.path.join(cfg.AVA.FRAME_LIST_DIR, filename)
        for filename in cfg.AVA.TEST_LISTS
    ]
    image_paths = defaultdict(list)
    video_name_to_idx = {}
    video_idx_to_name = []
    for list_filename in list_filenames:
        with pathmgr.open(list_filename, "r") as f:
            # f.readline()
            for line in f:
                row = line.split()
                assert len(row) == 4
                video_name = row[0]

                if video_name not in video_name_to_idx:
                    idx = len(video_name_to_idx)
                    video_name_to_idx[video_name] = idx
                    video_idx_to_name.append(video_name)

                data_key = video_name_to_idx[video_name]
                image_paths[data_key].append(row[3])

    image_paths = [image_paths[i] for i in range(len(image_paths))]
    logger.info("Finished loading image paths from: %s" % ", ".join(list_filenames))

    return image_paths, video_idx_to_name

def load_boxes_and_labels(cfg, mode):
    """
    Loading boxes and labels from csv files.

    Args:
        cfg (CfgNode): config.
        mode (str): 'train', 'val', or 'test' mode.
    Returns:
        all_boxes (dict): a dict which maps from `video_name` and
            `frame_sec` to a list of `box`. Each `box` is a
            [`box_coord`, `box_labels`] where `box_coord` is the
            coordinates of box and 'box_labels` are the corresponding
            labels for the box.
    """
    # gt_lists = cfg.AVA.TRAIN_GT_BOX_LISTS if mode == "train" else []
    pred_lists = (
        cfg.AVA.TEST_PREDICT_BOX_LISTS
    )
    # breakpoint()
    ann_filename = os.path.join(cfg.AVA.ANNOTATION_DIR, pred_lists[0])

    # Only select frame_sec % 4 = 0 samples for validation if not

    all_boxes, count, unique_box_count = parse_bboxes_file(
        ann_filename=ann_filename
    )
    logger.info("Finished loading annotations from: %s" % ann_filename)
    logger.info("Number of unique boxes: %d" % unique_box_count)
    logger.info("Number of annotations: %d" % count)

    return all_boxes

def get_keyframe_data(boxes_and_labels):
    """
    Getting keyframe indices, boxes and labels in the dataset.

    Args:
        boxes_and_labels (list[dict]): a list which maps from video_idx to a dict.
            Each dict `frame_sec` to a list of boxes and corresponding labels.

    Returns:
        keyframe_indices (list): a list of indices of the keyframes.
        keyframe_boxes_and_labels (list[list[list]]): a list of list which maps from
            video_idx and sec_idx to a list of boxes and corresponding labels.
    """

    def sec_to_frame(sec):
        """
        Convert time index (in second) to frame index.
        0: 900
        30: 901
        """

        # PSI-AVA contains one frame per second
        return int(sec)

    keyframe_indices = []
    keyframe_boxes_and_labels = []
    count = 0
    for video_idx in range(len(boxes_and_labels)):
        # sec_idx = 0
        keyframe_boxes_and_labels.append([])
        for sec in boxes_and_labels[video_idx]:
            sec_idx = list(boxes_and_labels[video_idx]).index(sec)
            if len(boxes_and_labels[video_idx][sec])>0:
                keyframe_indices.append((video_idx, sec_idx, sec, sec_to_frame(sec)))
                keyframe_boxes_and_labels[video_idx].append(
                    boxes_and_labels[video_idx][sec]
                )
                count += 1
    logger.info("%d keyframes used." % count)

    return keyframe_indices, keyframe_boxes_and_labels

def get_num_boxes_used(keyframe_indices, keyframe_boxes_and_labels):
    """
    Get total number of used boxes.

    Args:
        keyframe_indices (list): a list of indices of the keyframes.
        keyframe_boxes_and_labels (list[list[list]]): a list of list which maps from
            video_idx and sec_idx to a list of boxes and corresponding labels.

    Returns:
        count (int): total number of used boxes.
    """

    count = 0
    for video_idx, sec_idx, _, _ in keyframe_indices:
        try:
            count += len(keyframe_boxes_and_labels[video_idx][sec_idx])
        except:
            breakpoint()
    return count

def parse_bboxes_file(ann_filename):
    """
    Parse PSI-AVA bounding boxes files.
    Args:
        ann_filenames (list of str(s)): a list of PSI-AVA bounding boxes annotation files.
        ann_is_gt_box (list of bools): a list of boolean to indicate whether the corresponding
            ann_file is ground-truth. `ann_is_gt_box[i]` correspond to `ann_filenames[i]`.
        detect_thresh (float): threshold for accepting predicted boxes, range [0, 1].
        boxes_sample_rate (int): sample rate for test bounding boxes. Get 1 every `boxes_sample_rate`.
    """
    all_boxes = {}
    count = 0
    unique_box_count = 0

    with pathmgr.open(ann_filename, "r") as f:
        for line in f:
            row = line.strip().split(",")
            assert len(row)==7
            # When we use predicted boxes to train/eval, we need to
            # save as empty the boxes whose scores are below the threshold.
            # Box with format [x1, y1, x2, y2] with a range of [0, 1] as float.
            box_key = ",".join(row[3:7])
            box = list(map(float, row[3:7]))

            video_name, frame_sec = row[0], int(row[1])

            if video_name not in all_boxes:
                all_boxes[video_name] = {}
            if frame_sec not in all_boxes[video_name]:
                all_boxes[video_name][frame_sec] = {}
                # for sec in range(int(len(os.listdir('/media/SSD0/nayobi/All_datasets/SAR-RARP50/videos/fold1/{}/segmentation'.format(video_name))))):
                #     all_boxes[video_name][sec*10] = {}

            if box_key not in all_boxes[video_name][frame_sec]:
                all_boxes[video_name][frame_sec][box_key] = box
                unique_box_count += 1

            count += 1

    new_all_boxes = {}
    for video_name in all_boxes:
        new_all_boxes[video_name]={}
        for frame_sec in all_boxes[video_name]:
            if len(all_boxes[video_name][frame_sec])>0:
                new_all_boxes[video_name][frame_sec] = list(
                all_boxes[video_name][frame_sec].values()
            )

    return new_all_boxes, count, unique_box_count


#对字符串进行对齐
d = {
	"lodDist":100.0,
	"SmallCull":0.04,
	"DistCull":500.0,
	"trilinear":40,
	"farclip":477
}

w = max( map (len , d.keys()))
print(w)
for x in d:
	#print(x.center(w),':',d[x])
	print(x.ljust(w),':',d[x])


import torch
import spacy
import string
import numpy as np
import pdb

class WordEmbedding:
  """Manager for vocabulary and word embeddings"""

  def __init__(self):
    self.nlp = spacy.load('en_core_web_md', disable = ['tagger', 'parser', 'ner'])
    with open('coco_words.txt') as f:
      self.vocab_words = f.read().split()

    # Only allow real words
    self.vocab_words = list(filter(lambda w: w.islower() and w in self.nlp.vocab, self.vocab_words))

    # Special vectors
    self.END_MARKER = np.zeros(301)
    self.END_MARKER[-1] = 1
    self.vocab_words.append('.')

  def get_word_embedding(self, word):
    if word == '.':
      return self.END_MARKER
    v = self.nlp.vocab.get_vector(word)
    v = np.append(v, [0])
    return v

  def get_word_from_index(self, ix):
    return self.vocab_words[ix]

  def get_index_from_word(self, word):
    return self.vocab_words.index(word)

  def sentence_to_embedding(self, text, pad):
    """Process natural language sentence into sequence of word vectors"""

    # Convert to lowercase and remove punctuation
    text = text.lower()
    text = ''.join([c for c in text if c not in string.punctuation])

    embeddings = []
    words = []
    for word in text.split():
      if word in self.vocab_words:
        words.append(word)
        embeddings.append(self.get_word_embedding(word))

    # Pad with periods if it's too short
    words = words[:pad]
    embeddings = embeddings[:pad]
    while len(words) < pad:
      words.append('.')
      embeddings.append(self.END_MARKER)

    return words, embeddings

def test():
  manager = WordEmbedding()
  print(manager.sentence_to_embedding('I have a Large Gray wabbit, she is cute'))

#test()


"""
Mixins for the EnterpriseApiClient.
"""
import json
import mock

import httpretty
from django.conf import settings
from django.core.cache import cache

class EnterpriseServiceMockMixin(object):
    """
    Mocks for the Enterprise service responses.
    """

    def setUp(self):
        super(EnterpriseServiceMockMixin, self).setUp()
        cache.clear()

    @staticmethod
    def get_enterprise_url(path):
        """Return a URL to the configured Enterprise API. """
        return '{}{}/'.format(settings.ENTERPRISE_API_URL, path)

    def mock_enterprise_course_enrollment_post_api(  # pylint: disable=invalid-name
            self,
            username='test_user',
            course_id='course-v1:edX+DemoX+Demo_Course',
            consent_granted=True
    ):
        """
        Helper method to register the enterprise course enrollment API POST endpoint.
        """
        api_response = {
            username: username,
            course_id: course_id,
            consent_granted: consent_granted,
        }
        api_response_json = json.dumps(api_response)
        httpretty.register_uri(
            method=httpretty.POST,
            uri=self.get_enterprise_url('enterprise-course-enrollment'),
            body=api_response_json,
            content_type='application/json'
        )

    def mock_enterprise_course_enrollment_post_api_failure(self):  # pylint: disable=invalid-name
        """
        Helper method to register the enterprise course enrollment API endpoint for a failure.
        """
        httpretty.register_uri(
            method=httpretty.POST,
            uri=self.get_enterprise_url('enterprise-course-enrollment'),
            body='{}',
            content_type='application/json',
            status=500
        )

    def mock_enterprise_course_enrollment_get_api(self, **kwargs):
        result = {
            'results': [kwargs] if kwargs else []
        }
        httpretty.register_uri(
            method=httpretty.GET,
            uri=self.get_enterprise_url('enterprise-course-enrollment'),
            body=json.dumps(result),
            content_type='application/json',
            status=200
        )

    def mock_enterprise_learner_api(
            self,
            catalog_id=1,
            entitlement_id=1,
            learner_id=1,
            enterprise_customer_uuid='cf246b88-d5f6-4908-a522-fc307e0b0c59',
            enable_audit_enrollment=False,
    ):
        """
        Helper function to register enterprise learner API endpoint.
        """
        enterprise_learner_api_response = {
            'count': 1,
            'num_pages': 1,
            'current_page': 1,
            'results': [
                {
                    'id': learner_id,
                    'enterprise_customer': {
                        'uuid': enterprise_customer_uuid,
                        'name': 'TestShib',
                        'catalog': catalog_id,
                        'active': True,
                        'site': {
                            'domain': 'example.com',
                            'name': 'example.com'
                        },
                        'enable_data_sharing_consent': True,
                        'enforce_data_sharing_consent': 'at_login',
                        'enable_audit_enrollment': enable_audit_enrollment,
                        'enterprise_customer_users': [
                            1
                        ],
                        'branding_configuration': {
                            'enterprise_customer': enterprise_customer_uuid,
                            'logo': 'https://open.edx.org/sites/all/themes/edx_open/logo.png'
                        },
                        'enterprise_customer_entitlements': [
                            {
                                'enterprise_customer': enterprise_customer_uuid,
                                'entitlement_id': entitlement_id
                            }
                        ]
                    },
                    'user_id': 5,
                    'user': {
                        'username': 'verified',
                        'first_name': '',
                        'last_name': '',
                        'email': 'verified@example.com',
                        'is_staff': True,
                        'is_active': True,
                        'date_joined': '2016-09-01T19:18:26.026495Z'
                    },
                    'data_sharing_consent': [
                        {
                            'user': 1,
                            'state': 'enabled',
                            'enabled': True
                        }
                    ]
                }
            ],
            'next': None,
            'start': 0,
            'previous': None
        }
        enterprise_learner_api_response_json = json.dumps(enterprise_learner_api_response)

        httpretty.register_uri(
            method=httpretty.GET,
            uri=self.get_enterprise_url('enterprise-learner'),
            body=enterprise_learner_api_response_json,
            content_type='application/json'
        )

class EnterpriseTestConsentRequired(object):
    """
    Mixin to help test the data_sharing_consent_required decorator.
    """
    def verify_consent_required(self, client, url, status_code=200):
        """
        Verify that the given URL redirects to the consent page when consent is required,
        and doesn't redirect to the consent page when consent is not required.

        Arguments:
        * self: ignored
        * client: the TestClient instance to be used
        * url: URL to test
        * status_code: expected status code of URL when no data sharing consent is required.
        """
        with mock.patch('openedx.features.enterprise_support.api.enterprise_enabled', return_value=True):
            with mock.patch('openedx.features.enterprise_support.api.consent_necessary_for_course') as mock_consent_necessary:  # pylint: disable=line-too-long
                # Ensure that when consent is necessary, the user is redirected to the consent page.
                mock_consent_necessary.return_value = True
                response = client.get(url)
                assert response.status_code == 302
                assert 'grant_data_sharing_permissions' in response.url  # pylint: disable=no-member

                # Ensure that when consent is not necessary, the user continues through to the requested page.
                mock_consent_necessary.return_value = False
                response = client.get(url)
                assert response.status_code == status_code

                # If we were expecting a redirect, ensure it's not to the data sharing permission page
                if status_code == 302:
                    assert 'grant_data_sharing_permissions' not in response.url  # pylint: disable=no-member
                return response


import io
import os
import subprocess

from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
root = Tk()

#设置窗口大小
form_width = 1024
form_height = 768
#获取屏幕尺寸以计算布局参数，使窗口居屏幕中央
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (form_width, form_height, (screenwidth-form_width)/2, (screenheight-form_height)/2)
root.geometry(alignstr)
#设置窗口是否可变长、宽，True：可变，False：不可变
root.resizable(width=False, height=False)

#设置窗口标题
root.title('Animal Classifier')

#设置窗口图标
#root.iconbitmap('****.ico')

#setting up a tkinter canvas without scrollbars
frame = Frame(root, bd=0, relief=SUNKEN)
frame.grid_rowconfigure(0, weight=1)
frame.grid_columnconfigure(0, weight=1)
canvas = Canvas(frame, bd=0)
canvas.grid(row=0, column=0, sticky=N+S+E+W)
frame.pack(fill=BOTH,expand=1)

text = StringVar()
text.set('')

#对一个pil_image对象进行缩放，让它在一个矩形框内，还能保持比例
def resize(w, h, w_box, h_box, pil_image):
    f1 = 1.0*w_box/w # 1.0 forces float division in Python2
    f2 = 1.0*h_box/h
    factor = min([f1, f2])
    width = int(w*factor)
    height = int(h*factor)
    return pil_image.resize((width, height), Image.ANTIALIAS)

#function to be called when mouse is clicked
def printcoords():
    File = filedialog.askopenfilename(parent=root, initialdir="C:/",title='Choose an image.')

	#=================================================================
    w_box = 1024
    h_box = 700
    #以一个PIL图像对象打开
    pil_image = Image.open(File)
    #获取图像的原始大小
    w, h = pil_image.size
    pil_image_resized = resize(w, h, w_box, h_box, pil_image)
    #=================================================================

    filename = ImageTk.PhotoImage(pil_image_resized)
    canvas.image = filename  # <--- keep reference of your image
    canvas.create_image(0,0,anchor='nw',image=filename)

    #subprocess.getoutput("python classify_image.py --image_file="+ File)
    p = subprocess.Popen("python classify_image.py --image_file="+ File, stdout=subprocess.PIPE, shell=True)
    text.set(p.stdout.read())
    p.kill

lb = Label(root, textvariable=text)
lb.pack()
Button(root,text='Choose an image',command=printcoords).pack()

root.mainloop()


import sys
input = sys.stdin.readline

n = int(input())
lst = list(map(int, input().split()))

# 오른쪽 방향으로 누적합
sum_lst1 = lst[:]
# 왼쪽 방향으로 누적합
sum_lst2 = lst[:]
for i in range(1, n):
  sum_lst1[i] = sum_lst1[i] + sum_lst1[i-1]
  sum_lst2[n-1-i] = sum_lst2[n-1-i] + sum_lst2[n-i]

left = 0
right = 0
mid = 0
for i in range(1, n-1):
  # 꿀 통이 왼쪽에 있을 경우 하나는 맨 오른쪽에 무조건 있어야 함
  # 나머지 하나는 하나씩 옮기면서 가장 큰 값 구하기
  left = max(left, sum_lst2[0]*2 - lst[-1] - sum_lst2[i] - lst[i])
  # 꿀 통이 오른쪽에 있을 경우 하나는 맨 왼쪽에 무조건 있어야 함
  # 나머지 하나는 하나씩 옮기면서 가장 큰 값 구하기
  right = max(right, sum_lst1[-1]*2 - lst[0] - sum_lst1[i] - lst[i])
  # 꿀 통이 가운데 있을 경우 맨 시작 시점은 오른쪽, 맨 왼쪽에 있어야 함
  # 가운데 꿀 통을 옮기면서 가장 큰 값 구하기
  mid = max(mid, sum_lst1[i] - sum_lst1[0] + sum_lst2[i] - sum_lst2[-1])

# 꿀통이 왼쪽, 오른쪽, 가운데 있을 경우의 수 가장 큰 값 출력
print(max(left, right, mid))


from const import *
from os import path

class Data:
    # класс для работы с данными из файла
    __text_array = ''       # текстовый массив
    __load_ok = False       # загрузка данных прошла успешно?
    __code = CODE_OK        # код операции

    def __init__(self, txt='', file_name=''):
        # инициализация
        self.__text_array = txt
        # если передано имя файла, сразу загрузить данные
        if file_name != '':
            self.load_text(file_name)

    def text(self):
        # вернуть текстовый массив
        return self.__text_array

    def text_prn(self):
        # вывести текст на экран
        print(self.__text_array)

    def load_text(self,file_name):
        # загрузить текст из файла

        # если файл найден на диске
        if path.exists(file_name):

            self.__load_ok = False
            self.__text_array = ''

            try:
                with open(file_name, encoding='utf-8') as f:
                    # прочитать файла
                    self.__text_array = f.read()
            except FileNotFoundError:       # файл не найден (излишняя проверка после path.exists)
                self.__code = ERR_FILE_NOT_FOUNT
            except OSError:                 # общая ошибка работы с файлом
                self.__code = ERR_OS
            except UnicodeDecodeError:      # ошибка декодирования
                self.__code = ERR_DECODE
            else:
                # файл прочитан успешно
                self.__load_ok = True
                self.__code = CODE_OK

        else:
            # файла нет на диске
            self.__load_ok = False
            self.__code = ERR_FILE_NOT_FOUNT

    def save_to_file(self,file_name):
        if len(self.__text_array) > 0:
            try:
                with open(file_name,'w') as f:
                    f.write(self.__text_array)
            except:
                self.__code = ERR_FILE_OPERATION
            else:
                self.__code = CODE_OK
        else:
            self.__code = ERR_EMPTY_TEXT

    def load_ok(self):
        # информация об успехе/недуаче загрузки
        return self.__load_ok

    def set_text(self, txt=''):
        # установить текст
        self.__text_array = txt

    def code(self):
        return self.__code

    def clear(self):
        # очистить текст
        self.__text_array = ''


# n = len(nums)
# time: O(n*n)
# space: O(1)

from typing import List

class Solution:
    def sortColors(self, nums: List[int]) -> None:

        n=len(nums)

        for i in range(1,n):
            key=nums[i]
            j=i-1
            while j>=0 and key<nums[j]:
                nums[j+1]=nums[j]
                j-=1

            nums[j+1]=key