# -*- coding: utf-8 -*-
'''
作业2
'''
# @Time : 2021/4/5 18:40
# @Author : LINYANZHEN
# @File : pytorch2_2.py
import numpy as np
import pandas as pd
import random
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import datetime
import time

# 读取数据集并分割
def load_data():
    data = np.loadtxt("meant.csv", delimiter=",", skiprows=1, usecols=2)
    x = np.zeros((data.shape[0] - 6, 6))
    y = np.zeros((data.shape[0] - 6, 1))
    for i in range(6):
        x[:, i] = data[i:-(6 - i)]
    y[:, 0] = data[6:]
    x_train = x[:33108]
    y_train = y[:33108]
    x_test = x[33108:]
    y_test = y[33108:]
    # print(x_train)
    return x_train, y_train, x_test, y_test

# 定义网络结构
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        # 2 input image channel, 1 output channels
        # an affine operation: y = Wx + b
        self.fc1 = nn.Linear(6, 4)
        self.fc2 = nn.Linear(4, 2)
        self.fc3 = nn.Linear(2, 1)

    def forward(self, x):
        # If the size is a square you can only specify a single number
        x = torch.sigmoid(self.fc1(x))
        x = torch.sigmoid(self.fc2(x))
        x = torch.sigmoid(self.fc3(x))
        return x

def train(net, x, y, lr, epouch):
    myrange = list(range(y.shape[0]))
    for i in range(epouch):
        print('loop=%d' % i)
        random.shuffle(myrange)
        # 遍历整个训练集
        for j in myrange:
            # 提取x,y
            x_ture = torch.tensor(x[j], dtype=torch.float32)
            y_ture = torch.tensor(y[j], dtype=torch.float32)
            # 梯度归零
            net.zero_grad()
            # 计算预测y
            y_pred = net(x_ture)
            # 计算损失
            criterion = nn.MSELoss()
            loss = criterion(y_pred, y_ture)
            # backward
            # 反向传播更新参数
            loss.backward()
            for f in net.parameters():
                f.data = f.data - f.grad.data * lr

def test(x_test, y_test):
    ypredlist = []
    for j in range(y_test.shape[0]):
        xt = torch.tensor(x_test[j], dtype=torch.float32)
        ypred = net(xt)
        ypredlist.append(np.array(ypred.data))
    ypredlist = np.array(ypredlist)
    ypredlist = ypredlist.reshape(y_test.shape[0])
    MSE = np.sum((y_test - ypredlist) ** 2) / y_test.shape[0]
    # 画图
    plt.figure(figsize=(10, 5))
    plt.plot(y_test, 'r+', label='real data')
    plt.plot(ypredlist, 'b*', label='pred data')
    plt.legend()
    plt.grid()
    plt.title('MSE=%5.2f' % MSE)
    plt.savefig('out2.jpg', dpi=256)
    plt.close()
    print(MSE)

if __name__ == '__main__':
    start_time = time.time()
    net = Net()
    x_train, y_train, x_test, y_test = load_data()
    ##train loop
    lr = 0.01
    epouch = 200
    train(net, x_train, y_train, lr, epouch)
    test(x_test, y_test)
    end_time = time.time()
    print("用时：{}min".format((end_time - start_time) / 60))


from typing import Iterable, Any

def is_present(substring: str, iterable: Iterable[str]):
    for string in iterable:
        if string is not None and substring in string:
            return True

    return False

def set_to_empty(iterable: list[Any]) -> list[Any]:
    if iterable == ['']:
        iterable = []

    return iterable


#1929 concatenation of arrays
"""
---given an array of ints nums, of length n, create an array ans
---of length 2n, where ans[i]=nums[i] and ans[i+n]=nums[i]
---ans is the concatenation of 2 nums arrays
"""

class Solution(object):
    def getConcatenation(self,nums):

        ans=[]
        for i in range(2):
            for num in nums:
                ans.append(num)

        return ans

nums=[1,2,1]
solution=Solution()
print(solution.getConcatenation(nums))


"""
:Author: Daniel Mohr
:Email: daniel.mohr@dlr.de
:Date: 2021-02-19
:License: GNU GENERAL PUBLIC LICENSE, Version 3, 29 June 2007.

tests the script: pydabu check_nasa_ames_format
"""

import subprocess

try:
    from .data_path_class import DataPathClass
except (ModuleNotFoundError, ImportError):
    from data_path_class import DataPathClass

# pylint: disable=too-few-public-methods
class MixinCheckNasaAmesFormat(DataPathClass):
    """
    :Author: Daniel Mohr
    :Date: 2021-02-19
    """

    def test_check_nasa_ames_format(self):
        """
        :Author: Daniel Mohr
        :Date: 2021-02-08

        This test uses the data in 'data/data_bubble' to test the output
        of the script 'pydabu check_nasa_ames_format'.
        """
        # data bubble 03
        test_dir_path = self.test_dir_path[3]
        cpi = subprocess.run(
            'pydabu check_nasa_ames_format -f foo',
            stdout=subprocess.PIPE, stderr=subprocess.PIPE,
            shell=True, cwd=test_dir_path, timeout=self.subprocess_timeout,
            check=False)
        self.assertEqual(cpi.returncode, 2)  # check for error
        subprocess.run(
            'pydabu check_nasa_ames_format -f a.na',
            stdout=subprocess.PIPE, stderr=subprocess.PIPE,
            shell=True, cwd=test_dir_path, timeout=self.subprocess_timeout,
            check=True)


import pathlib
import pygubu
PROJECT_PATH = pathlib.Path(__file__).parent
PROJECT_UI = PROJECT_PATH / "snakegame.ui"

import tkinter as tk
from tkinter import *
from PIL import ImageTk, Image
import random, os
import numpy as np

from operator import itemgetter
import pickle

# - GAMEPLAN DATA SETUP
GAMEPLAN_SIZE     = 40     # Set the number of positions (boxes) that the snake can move (Horizontal and vertical)
GAMEBOX_SIZE      = 20     # Set the size, in pixels, for the width of the box
GAME_PADDING      = 10     # Set the padding on each side of the board
GAME_SPEED        = 150    # Set the default speed for the snake. Lower number is faster
SNAKE_LENGTH_ADD  = 3      # The increase in length each time the snake catch the cake

class SnakegameApp:

    direction = [0,-1]
    position  = [0,0]
    candypos  = [0,0]
    gamedata = {
        'step'          : 0,
        'score'         : 0,
        'iteration'     : 0,
        'speed'         : GAME_SPEED,
        'delay'         : 0,
        'length'        : 5,
        'generation'    : 0,
    }

    snake_list = []
    gamematrix = np.zeros([GAMEPLAN_SIZE, GAMEPLAN_SIZE])

    def __init__(self, game_engine_hook, running_ai=False):

        self.gameplan_size    = GAMEPLAN_SIZE
        self.gamebox_size     = GAMEBOX_SIZE
        self.game_padding     = GAME_PADDING
        self.gamestatus       = 'FIRST TIME'
        self.running_ai       = running_ai
        self.game_engine_hook = game_engine_hook

        # -----------------------------------------------------------------------------------------
        # - PyGubu Builder Magic - Setup the static layout
        # -----------------------------------------------------------------------------------------

        self.builder = builder = pygubu.Builder()
        builder.add_resource_path(PROJECT_PATH)
        builder.add_from_file(PROJECT_UI)
        # Main widget
        self.mainwindow = builder.get_object("toplevel1", None)
        self.canvas     = builder.get_object("canvas", None)
        self.info       = builder.get_object("info", None)
        self.highscore  = builder.get_object("highscore", None)

        self.score_variable = None
        self.info_variable = None
        self.highscore_variable = None
        self.scale_variable = None
        self.status_variable = None
        self.restart_variable = None
        builder.import_variables(self,
                                 ['score_variable',
                                  'info_variable',
                                  'highscore_variable',
                                  'scale_variable',
                                  'status_variable',
                                  'restart_variable'])

        builder.connect_callbacks(self)

        # Complete the gameplan in the canvas object --------------------------------------------

        for pos in range(0, self.gameplan_size+1, 1):
            xl = self.game_padding + pos*self.gamebox_size
            t  = self.gameplan_size*self.gamebox_size+self.game_padding

            self.canvas.create_line(xl, self.game_padding, xl, t)
            self.canvas.create_line(self.game_padding, xl, t, xl)

        # - Get the snake head and body image from file (19x19), and cake image
        self.img_snake_body = ImageTk.PhotoImage(Image.open("snake_body.bmp"))
        self.img_snake_head = ImageTk.PhotoImage(Image.open("snake_head_up.bmp"))
        self.img_cake       = ImageTk.PhotoImage(Image.open("cake-19x19.bmp"))

        # - Bind some command buttons for shortcuts
        self.mainwindow.bind("<space>", self.spacebar_command)

        if running_ai == False:
            # - Bind the arrow keys to the update move function
            self.mainwindow.bind("<Left>"  , lambda value : self.snake_update_move( -1,  0))
            self.mainwindow.bind("<Right>" , lambda value : self.snake_update_move( +1,  0))
            self.mainwindow.bind("<Up>"    , lambda value : self.snake_update_move(  0, -1))
            self.mainwindow.bind("<Down>"  , lambda value : self.snake_update_move(  0, +1))

    # - Run the mainloop

    def run(self):
        self.mainwindow.mainloop()

    def start_new(self):

        # set the first position for the snake
        self.position[0] = random.randint(12, self.gameplan_size-12)   # '12' is just to set it not too close to edge
        self.position[1] = random.randint(12, self.gameplan_size-12)

        self.gamematrix[self.position[0], self.position[1]] = 1       # Upself.date the gamematrix, '1' means position is 'snake_head'

        self.snake = self.canvas.create_image(
            self.position[0]*self.gamebox_size+self.game_padding+10,     # '10' is the image offset
            self.position[1]*self.gamebox_size+self.game_padding+10,
            image=self.img_snake_head,
            tags=('clean','snake'))

        # Set the first position for the cake, avoid putting it on-top of snake
        while True:
            self.candypos[0] = random.randint(5, self.gamebox_size-5)    # '5' is just to keep it away from edge
            self.candypos[1] = random.randint(5, self.gamebox_size-5)
            if not(self.candypos[0] == self.position[0] and self.candypos[1] == self.position[1]):
                break
        self.gamematrix[self.candypos[0], self.candypos[1]] = 3    # '3' indicates 'cake'

        self.candy = self.canvas.create_image(
            self.candypos[0]*self.gamebox_size+self.game_padding+10,
            self.candypos[1]*self.gamebox_size+self.game_padding+10,
            image=self.img_cake,
            tags=('clean', 'cake'))

    # --------------------------------------------------------------------------------------------
    # snake_update_move: depending on gamestatus, change the direction parameter
    # --------------------------------------------------------------------------------------------
    def snake_update_move(self, x, y):
        if (self.direction[0] != -x) and (self.direction[1] != -y):
            self.direction[0], self.direction[1] = x, y

    def check_collision(self, x, y):
        # Check wall crash
        if ((x < 0 or x>self.gameplan_size-1) or (y < 0 or y>self.gameplan_size-1)):
            return 'CRASH_WALL'

        # Check if we crashed with snake body
        if self.gamematrix[x,y] == 2:
            return 'CRASH_SNAKE'

        # Check if we have done to many iterations since last cake was found
        if (len(self.snake_list) > 2) and (self.gamedata['iteration'] > 100*len(self.snake_list)):
            return 'CRASH_ITERATION'

        return 'NO_COLLISION'

    def check_candy_found(self, x, y):
        if self.candypos == [x,y]:
            return True

        return False

    # --------------------------------------------------------------------------------------------
    # move: Move the snake, and update status information
    # --------------------------------------------------------------------------------------------
    def move(self):

        # Save the old position, and update position with the new direction
        prevpos = [0,0]
        prevpos[0] = self.position[0]
        prevpos[1] = self.position[1]

        self.position[0] += self.direction[0]
        self.position[1] += self.direction[1]

        # Check if we hit the wall or the body
        is_collision = self.check_collision(self.position[0], self.position[1])

        if is_collision != 'NO_COLLISION':
            self.gamestatus = is_collision

            if is_collision == 'CRASH_WALL' :
                self.info_variable.set("GAME OVER!\nYou hit the wall!\nPress 'Start Game' to go again.")
            elif is_collision == 'CRASH_SNAKE':
                self.info_variable.set("GAME OVER!\nYou ran into yourself!\nPress 'Start Game' to go again.")
            else:
                self.info_variable.set("GAME OVER!\nYou are stuck!\nPress 'Start Game' to go again.")
            self.info.config(bg='red')

            return

        # Check if we caught the candy
        if self.check_candy_found(self.position[0], self.position[1]) == True:
            self.gamedata['score'] += 1
            self.score_variable.set(f"{self.gamedata['score']:03d}")
            self.gamestatus = 'CAKE_FOUND'
            self.gamedata['iteration'] = 0
            # - place the cake again, be sure that is not set in an occupied box
            while True:
                self.candypos[0] = random.randint(5, self.gameplan_size-5)
                self.candypos[1] = random.randint(5, self.gameplan_size-5)
                if self.gamematrix[self.candypos[0], self.candypos[1]] == 0:
                    break
                else:  # For debugging, TODO
                    print("CANNOT FIND CAKE POSITION")

            self.gamematrix[self.candypos[0], self.candypos[1]] = 3
            self.canvas.moveto(
                self.candy,
                self.candypos[0]*self.gamebox_size+self.game_padding+1,
                self.candypos[1]*self.gamebox_size+self.game_padding+1
            )
            self.gamedata['length'] += SNAKE_LENGTH_ADD

        # Update new position in gamematrix
        self.gamematrix[prevpos[0], prevpos[1]] = 0    # Clear old position. (Actually not needed)
        self.gamematrix[self.position[0], self.position[1]] = 1

        # Move the image_head of the snake to it's new position
        self.canvas.move(self.snake,
            self.direction[0]*self.gamebox_size,
            self.direction[1]*self.gamebox_size
        )

        # Move each image section of the snake body to it's new positions
        if len(self.snake_list) < self.gamedata['length']:    # Need to create new body segments
            body = self.canvas.create_image(
                prevpos[0]*self.gamebox_size + self.game_padding + 10,
                prevpos[1]*self.gamebox_size + self.game_padding + 10,
                image=self.img_snake_body,
                tags=('clean', 'body')
            )
            self.snake_list.insert(0,[body, prevpos[0], prevpos[1]])
            self.gamematrix[prevpos[0], prevpos[1]] = 2
        else:
            item = self.snake_list.pop()
            self.gamematrix[item[1], item[2]]=0    # Clear old positon in matrix
            item[1], item[2] = prevpos[0], prevpos[1]
            self.snake_list.insert(0, item)
            self.canvas.moveto( item[0],
                                item[1]*self.gamebox_size+self.game_padding,
                                item[2]*self.gamebox_size+self.game_padding)
            self.gamematrix[prevpos[0], prevpos[1]]=2

        # Update the step counter (Need to present it in the dashboard later ...)
        self.gamedata['step'] += 1
        self.gamedata['iteration'] += 1

        self.status_variable.set(
            f"Status:\n\nstep: {self.gamedata['step']}\n" +\
            f"iteration: {self.gamedata['iteration']}\n" +\
            f"Generation: {self.gamedata['generation']}\n")

    # --------------------------------------------------------------------------------------------

    def game_engine(self):
        if self.gamestatus == 'GAMEOVER':
            return

        self.game_engine_hook()

        # self.move()

        self.mainwindow.after(int(self.gamedata['delay']),self.game_engine)
        # self.mainwindow.after(300,self.game_engine)
    # ---------------------------------------------------------------------------------------------

    def spacebar_command(self, event):
        self.restart_command()

    def setspeed_command(self, scale_value):
        pass

    def restart_command(self, dont_restart_engine=False):

        # -- Clean up previous session
        # ----- Delete all objects
        self.canvas.delete('clean')
        self.gamematrix.fill(0)
        self.gamedata['step']   = 0
        self.gamedata['score']  = 0
        self.gamedata['speed']  = self.scale_variable.get()
        self.gamedata['delay']  = (490-40*self.scale_variable.get())/3

        #print(f"scale: {self.scale_variable.get()} speed: {self.gamedata['speed']}")

        self.gamedata['length'] = 5
        self.snake_list = []

        self.info_variable.set("\n      Catch the Cake ....")
        self.info.config(bg="green")

        self.score_variable.set(f"{self.gamedata['score']:03d}")

        # -- Start up   game session
        self.gamestatus = 'RUNNING'
        self.start_new()
        if dont_restart_engine == False:
            self.game_engine()

if __name__ == "__main__":
    app = SnakegameApp(GAMEPLAN_SIZE, GAMEBOX_SIZE, GAME_PADDING)
    app.run()

# %%


# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from django.core.urlresolvers import reverse
from django import http

from mox import IsA  # noqa

from openstack_dashboard import api
from openstack_dashboard.test import helpers as test

INDEX_URL = reverse(
    'horizon:project:data_processing.data_plugins:index')
DETAILS_URL = reverse(
    'horizon:project:data_processing.data_plugins:details', args=['id'])

class DataProcessingPluginsTests(test.TestCase):
    @test.create_stubs({api.sahara: ('plugin_list',)})
    def test_index(self):
        api.sahara.plugin_list(IsA(http.HttpRequest)) \
            .AndReturn(self.plugins.list())
        self.mox.ReplayAll()
        res = self.client.get(INDEX_URL)
        self.assertTemplateUsed(
            res, 'project/data_processing.data_plugins/plugins.html')
        self.assertContains(res, 'vanilla')
        self.assertContains(res, 'plugin')

    @test.create_stubs({api.sahara: ('plugin_get',)})
    def test_details(self):
        api.sahara.plugin_get(IsA(http.HttpRequest), IsA(unicode)) \
            .AndReturn(self.plugins.list()[0])
        self.mox.ReplayAll()
        res = self.client.get(DETAILS_URL)
        self.assertTemplateUsed(
            res, 'project/data_processing.data_plugins/details.html')
        self.assertContains(res, 'vanilla')
        self.assertContains(res, 'plugin')
        self.assertContains(res, 'Plugin Overview')


import tkinter as tk
from tkinter import ttk
import datetime as dt
import mysql.connector
from tkinter import messagebox
import configparser

class NuovoLottoCucina(tk.Toplevel):
    def __init__(self):
        super(NuovoLottoCucina, self).__init__()
        self.title("Nuovo Lotto Cucina")
        self.geometry("+0+0")

        self.data = dt.date.today()
        self.config = self.leggi_file_ini()

        self.conn = mysql.connector.connect(host=self.config['DataBase']['host'],
                                            database=self.config['DataBase']['db'],
                                            user=self.config['DataBase']['user'],
                                            password='')
        self.c = self.conn.cursor()

        self.lista_da_salvare = []
        self.lista_nuova_produzione = []
        self.nuova_produzione = tk.StringVar()
        self.prog_lotto_ven = self.data.strftime('%d%m%y')
        self.img_btn1 = tk.PhotoImage(file=".//immagini//logo_piccolo.gif")
        self.value = tk.StringVar()
        self.value_peso = tk.StringVar()

        # DISPOSIZIONE FRAME
        self.frame_alto = tk.Frame(self, bd='3', relief='groove')
        self.frame_centro = tk.Frame(self, height=450, width=self.winfo_screenwidth(),
                                     bd='3', relief='groove')
        self.frame_basso = tk.Frame(self, bd='3', background='white', relief='groove')

        # LABEL nuovo lotto vendita
        self.lbl_nuovo_lotto = tk.Label(self.frame_alto, text='NUOVO LOTTO VENDITA', font=('Helvetica', 20),
                                        foreground='blue', relief='ridge', padx=20)
        self.lbl_prog_lotto_vendita = tk.Label(self.frame_alto, text=str(self.prog_lotto_ven),
                                               font=('Helvetica', 20), bg='white', relief='sunken', padx=20)

        # LABEL che mostra il numero della settimana
        self.lbl_settimana = tk.Label(self.frame_alto, text='SETTIMANA NUMERO ',
                                      foreground='blue', font=('Verdana', 20), relief='ridge', padx=20)
        self.lbl_nr_settimana = tk.Label(self.frame_alto, text=str(1 + int(self.data.strftime('%W'))),
                                         font=('Verdana', 20), bg='white', relief='sunken', padx=20)

        # TREEVIEW per riepilogo immissioni
        self.tree = ttk.Treeview(self.frame_centro, height=15)
        self.tree['columns'] = ('prog_v', 'prodotto', 'peso', 'settimana')

        self.tree['displaycolumns'] = ('prodotto', 'peso')
        self.tree['show'] = 'headings'

        self.tree.column("prodotto", width=180)
        self.tree.column("peso", width=80)

        self.tree.heading("prodotto", text="prodotto")
        self.tree.heading("peso", text="peso")

        self.tree.tag_configure('odd', background='light green')

        # NOTEBOOK e posizione
        self.notebook = ttk.Notebook(self.frame_centro)

        # TAB 1 per PRIMI PIATTI
        self.tab1 = ttk.Frame(self.notebook)
        self.notebook.add(self.tab1, text='Primi', compound='left', image=self.img_btn1)

        self.lista_primi = []
        self.c.execute("SELECT prodotto FROM prodotti WHERE merceologia = 'Primi piatti'")

        for row in self.c:
            self.lista_primi.extend(row)

        row, col = 1, 0
        for i in range(0, len(self.lista_primi)):
            if row % 10 == 0:
                col += 1
                row = 1
            tk.Radiobutton(self.tab1,
                           text=str(self.lista_primi[i]),
                           variable=self.value,
                           width=25,
                           indicatoron=0,
                           value=self.lista_primi[i],
                           font='Verdana').grid(row=row, column=col, sticky='w')
            row += 1

        # TAB 2 per PRIMI pesce
        self.tab2 = ttk.Frame(self.notebook)
        self.notebook.add(self.tab2, text='Primi Pesce', compound='left', image=self.img_btn1)

        self.lista_primi_pesce = []
        self.c.execute("SELECT prodotto FROM prodotti WHERE merceologia = 'Primi piatti di pesce'")

        for row in self.c:
            self.lista_primi_pesce.extend(row)

        row, col = 1, 0
        for i in range(0, len(self.lista_primi_pesce)):
            if row % 10 == 0:
                col += 1
                row = 1
            tk.Radiobutton(self.tab2,
                           text=str(self.lista_primi_pesce[i]),
                           variable=self.value,
                           width=25,
                           indicatoron=0,
                           value=self.lista_primi_pesce[i],
                           font='Verdana').grid(row=row, column=col, sticky='w')
            row += 1

        # TAB 3 per SECONDI
        self.tab3 = ttk.Frame(self.notebook)
        self.notebook.add(self.tab3, text='Secondi', compound='left', image=self.img_btn1)

        self.lista_secondi = []
        self.c.execute("SELECT prodotto FROM prodotti WHERE merceologia = 'secondi piatti'")

        for row in self.c:
            self.lista_secondi.extend(row)

        row, col = 1, 0
        for i in range(0, len(self.lista_secondi)):
            if row % 13 == 0:
                col += 1
                row = 1
            tk.Radiobutton(self.tab3,
                           text=str(self.lista_secondi[i]),
                           variable=self.value,
                           width=25,
                           indicatoron=0,
                           value=self.lista_secondi[i],
                           font='Verdana').grid(row=row, column=col, sticky='w')
            row += 1

        # TAB 4 per SECONDI pesce
        self.tab4 = ttk.Frame(self.notebook)
        self.notebook.add(self.tab4, text='Secondi Pesce', compound='left', image=self.img_btn1)

        self.lista_secondi_pesce = []
        self.c.execute("SELECT prodotto FROM prodotti WHERE merceologia = '5'")

        for row in self.c:
            self.lista_secondi_pesce.extend(row)

        row, col = 1, 0
        for i in range(0, len(self.lista_secondi_pesce)):
            if row % 13 == 0:
                col += 1
                row = 1
            tk.Radiobutton(self.tab4,
                           text=str(self.lista_secondi_pesce[i]),
                           variable=self.value,
                           width=25,
                           indicatoron=0,
                           value=self.lista_secondi_pesce[i],
                           font='Verdana').grid(row=row, column=col, sticky='w')
            row += 1

        # TAB 5 per CONTORNI
        self.tab5 = ttk.Frame(self.notebook)
        self.notebook.add(self.tab5, text='Contorni', compound='left', image=self.img_btn1)

        self.lista_contorni = []
        self.c.execute("SELECT prodotto FROM prodotti WHERE merceologia = 'contorni'")

        for row in self.c:
            self.lista_contorni.extend(row)

        row, col = 1, 0
        for i in range(0, len(self.lista_contorni)):
            if row % 10 == 0:
                col += 1
                row = 1
            tk.Radiobutton(self.tab5,
                           text=str(self.lista_contorni[i]),
                           variable=self.value,
                           width=25,
                           indicatoron=0,
                           value=self.lista_contorni[i],
                           font='Verdana').grid(row=row, column=col, sticky='w')
            row += 1

        # TAB 6 per DOLCI
        self.tab6 = ttk.Frame(self.notebook)
        self.notebook.add(self.tab6, text='Dolci', compound='left', image=self.img_btn1)

        self.lista_dolci = []
        self.c.execute("SELECT prodotto FROM prodotti WHERE merceologia = 'dolci'")

        for row in self.c:
            self.lista_dolci.extend(row)

        row, col = 1, 0
        for i in range(0, len(self.lista_dolci)):
            if row % 10 == 0:
                col += 1
                row = 1
            tk.Radiobutton(self.tab6,
                           text=str(self.lista_dolci[i]),
                           variable=self.value,
                           width=25,
                           indicatoron=0,
                           value=self.lista_dolci[i],
                           font='Verdana').grid(row=row, column=col, sticky='w')
            row += 1

        # TAB 7 per PIATTI freddi
        self.tab7 = ttk.Frame(self.notebook)
        self.notebook.add(self.tab7, text='Piatti freddi', compound='left', image=self.img_btn1)

        self.lista_piatti_freddi = []
        self.c.execute("SELECT prodotto FROM prodotti WHERE merceologia = 'piatti freddi'")

        for row in self.c:
            self.lista_piatti_freddi.extend(row)

        row, col = 1, 0
        for i in range(0, len(self.lista_piatti_freddi)):
            if row % 10 == 0:
                col += 1
                row = 1
            tk.Radiobutton(self.tab7,
                           text=str(self.lista_piatti_freddi[i]),
                           variable=self.value,
                           width=25,
                           indicatoron=0,
                           value=self.lista_piatti_freddi[i],
                           font='Verdana').grid(row=row, column=col, sticky='w')
            row += 1

        # LABELFRAME per peso da inserire e bottoni
        self.lblframe_peso = ttk.LabelFrame(self.frame_basso, text='Peso')

        # ENTRY per inserimento del peso
        self.entry_peso = ttk.Entry(self.lblframe_peso,
                                    font=('Helvetica', 20),
                                    textvariable=self.value_peso)
        self.entry_peso.focus()

        # BOTTONE ESCI E SALVA
        self.btn_invia = tk.Button(self.frame_basso,
                                   text="Invio",
                                   font=('Helvetica', 20),
                                   command=self.invia)
        self.btn_esci = tk.Button(self.frame_basso,
                                  text="Chiudi finestra",
                                  font=('Helvetica', 20),
                                  command=self.esci_senza_salvare)
        self.btn_esci_salva = tk.Button(self.frame_basso,
                                        text="Esci e salva",
                                        font=('Helvetica', 20),
                                        command=self.esci_salva)
        self.btn_elimina_riga = tk.Button(self.frame_centro, text='Elimina riga', command=self.rimuovi_riga_selezionata)

        # LAYOUT
        self.frame_alto.grid(row=0, column=0, padx=10)
        self.frame_centro.grid(row=1, column=0)
        self.frame_basso.grid(row=2, column=0, columnspan=3)

        self.notebook.grid(row=0, column=0, rowspan=3)

        self.tree.grid(row=0, column=1)
        self.btn_elimina_riga.grid(row=1, column=1, sticky='we')

        self.lbl_settimana.grid(row=0, column=1)
        self.lbl_nr_settimana.grid(row=0, column=2)

        self.lbl_nuovo_lotto.grid(row=0, column=3)
        self.lbl_prog_lotto_vendita.grid(row=0, column=4)

        self.lblframe_peso.grid(row=0, column=0)
        self.entry_peso.grid()

        self.btn_invia.grid(row=0, column=1, padx=10, pady=10)
        self.btn_esci_salva.grid(row=0, column=2, padx=10, pady=10)
        self.btn_esci.grid(row=0, column=3, padx=10, pady=10)

    @staticmethod
    def leggi_file_ini():
        ini = configparser.ConfigParser()
        ini.read('config.ini')
        return ini

    def rimuovi_riga_selezionata(self):
        curitem = self.tree.selection()[0]
        self.tree.delete(curitem)

    def invia(self):
        self.tree.insert('', 'end', values=('L' + (str(self.prog_lotto_ven)),
                                            self.value.get(),
                                            self.value_peso.get(),
                                            self.data,
                                            (1 + int(self.data.strftime('%W')))))
        self.entry_peso.delete(0, tk.END)

    def esci_senza_salvare(self):
        if bool(self.tree.get_children()):
            messagebox.showinfo('Attenzione', 'Ci sono dati inseriti non salvati')
        else:
            self.destroy()

    def esci_salva(self):
        for child in self.tree.get_children():
            self.lista_da_salvare.append(self.tree.item(child)['values'])
        print(self.lista_da_salvare)
        self.c.executemany('INSERT INTO lotti_vendita_cucina(progressivo_ven_c, prodotto, quantita,'
                           'data_prod, settimana) VALUES (%s,%s,%s,%s,%s)', self.lista_da_salvare)
        self.conn.commit()
        self.conn.close()
        self.destroy()

if __name__ == '__main__':
    root = tk.Tk()
    new = NuovoLottoCucina()
    root.mainloop()


import numpy as np

from scrrpy import Cusp

def test_g(tol=1e-3):
    j = np.logspace(-2, 0, 1000)[:-1]

    # gamma = 2
    cusp = Cusp(gamma=2)
    g = cusp._g(j)
    g2 = j / (1 + j)
    assert abs(1 - g / g2).max() < tol

    # gamma = 1
    cusp = Cusp(gamma=1)
    g = cusp._g(j)
    g2 = j
    assert abs(1 - g / g2).max() < tol

    # gamma = 1.75
    cusp = Cusp(gamma=1.75)
    g = cusp._g(0.999999)
    g2 = (3 - cusp.gamma) / 2
    assert abs(1 - g / g2) < tol

def test_gp(tol=1e-3):
    j = np.logspace(-2, 0, 1000)[:-1]

    # gamma = 2
    cusp = Cusp(gamma=2)
    gp = cusp._gp(j)
    gp2 = 1 / (1 + j) ** 2
    assert abs(1 - gp / gp2).max() < tol

    # gamma = 1
    cusp = Cusp(gamma=1)
    gp = cusp._gp(j)
    gp2 = 1.0
    assert abs(1 - gp / gp2).max() < tol

def test_period(tol=0.4):
    # S2 period
    cusp = Cusp(mbh_mass=4.35e6)
    arcsec_kpc_pc = 0.0048481368
    r0 = 8.33
    sma_s2 = 0.1255 * arcsec_kpc_pc * r0  # pc
    p_s2 = 16.00  # yr
    period = cusp.period(sma_s2)
    nu_r = cusp.nu_r(sma_s2)
    np.testing.assert_almost_equal(nu_r * period, 2 * np.pi)
    assert abs(1 - period / p_s2) < tol


class node:
    def __init__(self, name, x = None, y = None):
        self.name = name
        self.edges = []
        self.x = x
        self.y = y

    def connect(self, node):
        key = (self.name, node.name)
        self.edges.append(key)

class edge:
    def __init__(self, left, right, weight = 1):
        self.left = left
        self.right = right
        self.weight = weight

class graph:
    time = 0
    def __init__(self):
        self.nodes = {}
        self.edges = {}
        self.bfs_time = 0
        self.dfs_time = 0
        self.dijkstra_time = 0
        self.a_star_time = 0
        self.bfs_length = 0
        self.dfs_length = 0
        self.dijkstra_length = 0
        self.a_star_length = 0
        self.count = 0
        self.number_of_edges = 0

    def addEdge(self, left, right, weight = 1):
        self.number_of_edges += 1
        self.nodes[left.name] = left
        self.nodes[right.name] = right
        new_edge = edge(left, right, weight)
        key = (left.name, right.name)
        self.edges[key] = new_edge
        key = (right.name, left.name)
        self.edges[key] = new_edge
        left.connect(right)
        right.connect(left)

    def load_graph(self, file_name):
        f = open("graph.txt", "r")
        graph_dict = {}
        coordinates = {}
        for x in f:
            name = ""
            neighbour_name = ""
            neighbour_weight = ""
            neighbour_dict = {}
            reading_name = True
            reading_neighbour = False
            reading_neighbour_name = True
            reading_neighbour_weight = False
            reading_coordinate = False
            reading_first_coordinate = False
            reading_second_coordintate = False
            first_coordinate = ""
            second_coordinate = ""
            for char in x:
                if not reading_coordinate:
                    if ord(char) == 40:
                        reading_name = False
                    elif ord(char) == 93:
                        if ord(neighbour_name[0]) == 32:
                                neighbour_name = neighbour_name[1:]
                        neighbour_dict[neighbour_name] = int(neighbour_weight)
                        neighbour_name = ""
                        neighbour_weight = ""
                        reading_neighbour = False
                        reading_neighbour_weight = False
                        reading_neighbour_name = True
                        reading_coordinate = True
                        continue
                    elif ord(char) == 91:
                        reading_neighbour = True
                        reading_name = False
                        continue
                    if reading_name:
                        name += char
                    if reading_neighbour:
                        if ord(char) == 58:
                            reading_neighbour_weight = True
                            reading_neighbour_name = False
                            continue
                        elif ord(char) == 44 or ord(char) == 93:
                            if ord(neighbour_name[0]) == 32:
                                neighbour_name = neighbour_name[1:]
                            neighbour_dict[neighbour_name] = int(neighbour_weight)
                            neighbour_name = ""
                            neighbour_weight = ""
                            reading_neighbour_weight = False
                            reading_neighbour_name = True
                            continue
                        if reading_neighbour_name:
                            neighbour_name += char
                        if reading_neighbour_weight:
                            neighbour_weight += char
                else:
                    if ord(char) == 40:
                        reading_first_coordinate = True
                        reading_second_coordintate = False
                        continue
                    elif ord(char) == 41:
                        reading_neighbour = False
                        reading_neighbour_weight = False
                        reading_neighbour_name = True
                        reading_coordinate = False
                        reading_first_coordinate = False
                        reading_second_coordintate = False
                        break
                    elif ord(char) == 44:
                        reading_first_coordinate = False
                        reading_second_coordintate = True
                        continue
                    if reading_first_coordinate:
                        first_coordinate += char
                    if reading_second_coordintate:
                        second_coordinate += char
            if name == "\n":
                break
            graph_dict[name] = neighbour_dict
            coordinates[name] = (float(first_coordinate), float(second_coordinate))
        added = {}
        added_edge = set()
        for current_node in graph_dict.keys():
            x_node, y_node = coordinates[current_node]
            if current_node not in added.keys():
                added[current_node] = node(current_node, x_node, y_node)
            for neighbour in graph_dict[current_node].keys():
                x_neighbour, y_neighbour = coordinates[neighbour]
                if neighbour not in added.keys():
                    added[neighbour] = node(neighbour, x_neighbour, y_neighbour)
                if (current_node, neighbour) not in added_edge:
                    self.addEdge(added[current_node], added[neighbour], graph_dict[current_node][neighbour])
                    added_edge.add((current_node, neighbour))
                    added_edge.add((neighbour, current_node))


import os
import shutil

def organizer():
    # os.chdir("/Users/Jay/Desktop/Dogs/DogsBreedClassifier/")
    original_dataset_dir = 'static'

    base_dir = 'train/data'
    os.mkdir(base_dir)

    train_dir = os.path.join(base_dir, 'train')

    validation_dir = os.path.join(base_dir, 'validation')

    test_dir = os.path.join(base_dir, 'test')

    os.mkdir(train_dir)
    os.mkdir(validation_dir)
    os.mkdir(test_dir)

    # Train folder breeds
    train_bulldog_dir = os.path.join(train_dir, 'bulldog')

    train_german_shepherd_dir = os.path.join(train_dir, 'german_shepherd')

    train_golden_retriever_dir = os.path.join(train_dir, 'golden_retriever')

    train_husky_dir = os.path.join(train_dir, 'husky')

    train_poodle_dir = os.path.join(train_dir, 'poodle')

    os.mkdir(train_bulldog_dir)
    os.mkdir(train_german_shepherd_dir)
    os.mkdir(train_golden_retriever_dir)
    os.mkdir(train_husky_dir)
    os.mkdir(train_poodle_dir)

    # Validation folder breeds
    validation_bulldog_dir = os.path.join(validation_dir, 'bulldog')

    validation_german_shepherd_dir = os.path.join(validation_dir, 'german_shepherd')

    validation_golden_retriever_dir = os.path.join(validation_dir, 'golden_retriever')

    validation_husky_dir = os.path.join(validation_dir, 'husky')

    validation_poodle_dir = os.path.join(validation_dir, 'poodle')

    os.mkdir(validation_bulldog_dir)
    os.mkdir(validation_german_shepherd_dir)
    os.mkdir(validation_golden_retriever_dir)
    os.mkdir(validation_husky_dir)
    os.mkdir(validation_poodle_dir)

    # Test folder breeds
    test_bulldog_dir = os.path.join(test_dir, 'bulldog')

    test_german_shepherd_dir = os.path.join(test_dir, 'german_shepherd')

    test_golden_retriever_dir = os.path.join(test_dir, 'golden_retriever')

    test_husky_dir = os.path.join(test_dir, 'husky')

    test_poodle_dir = os.path.join(test_dir, 'poodle')

    os.mkdir(test_bulldog_dir)
    os.mkdir(test_german_shepherd_dir)
    os.mkdir(test_golden_retriever_dir)
    os.mkdir(test_husky_dir)
    os.mkdir(test_poodle_dir)

    train_percentage = .7
    validation_percentage = .2
    test_percentage = .1

    for breed in os.listdir(original_dataset_dir):
        if breed != '.DS_Store':
            for sub_type in os.listdir(os.path.join(original_dataset_dir, breed)):
                if sub_type != '.DS_Store':
                    subtypes = os.listdir(os.path.join(original_dataset_dir, breed, sub_type))
                    i = 0
                    for name in subtypes:
                        if name != '.DS_Store':
                            train = int(len(subtypes) * train_percentage)
                            validation = int(len(subtypes) * validation_percentage + train)
                            test = int(len(subtypes) * test_percentage + validation)
                            if breed == 'bulldog':
                                if i < train:
                                    shutil.copyfile(os.path.join(original_dataset_dir, breed, sub_type, name),
                                                    os.path.join(train_bulldog_dir, name))
                                elif i < validation:
                                    shutil.copyfile(os.path.join(original_dataset_dir, breed, sub_type, name),
                                                    os.path.join(validation_bulldog_dir, name))
                                elif i < test:
                                    shutil.copyfile(os.path.join(original_dataset_dir, breed, sub_type, name),
                                                    os.path.join(test_bulldog_dir, name))
                            elif breed == 'german_shepherd':
                                if i < train:
                                    shutil.copyfile(os.path.join(original_dataset_dir, breed, sub_type, name),
                                                    os.path.join(train_german_shepherd_dir, name))
                                elif i < validation:
                                    shutil.copyfile(os.path.join(original_dataset_dir, breed, sub_type, name),
                                                    os.path.join(validation_german_shepherd_dir, name))
                                elif i < test:
                                    shutil.copyfile(os.path.join(original_dataset_dir, breed, sub_type, name),
                                                    os.path.join(test_german_shepherd_dir, name))
                            elif breed == 'golden_retriever':
                                if i < train:
                                    shutil.copyfile(os.path.join(original_dataset_dir, breed, sub_type, name),
                                                    os.path.join(train_golden_retriever_dir, name))
                                elif i < validation:
                                    shutil.copyfile(os.path.join(original_dataset_dir, breed, sub_type, name),
                                                    os.path.join(validation_golden_retriever_dir, name))
                                elif i < test:
                                    shutil.copyfile(os.path.join(original_dataset_dir, breed, sub_type, name),
                                                    os.path.join(test_golden_retriever_dir, name))
                            elif breed == 'husky':
                                if i < train:
                                    shutil.copyfile(os.path.join(original_dataset_dir, breed, sub_type, name),
                                                    os.path.join(train_husky_dir, name))
                                elif i < validation:
                                    shutil.copyfile(os.path.join(original_dataset_dir, breed, sub_type, name),
                                                    os.path.join(validation_husky_dir, name))
                                elif i < test:
                                    shutil.copyfile(os.path.join(original_dataset_dir, breed, sub_type, name),
                                                    os.path.join(test_husky_dir, name))
                            elif breed == 'poodle':
                                if i < train:
                                    shutil.copyfile(os.path.join(original_dataset_dir, breed, sub_type, name),
                                                    os.path.join(train_poodle_dir, name))
                                elif i < validation:
                                    shutil.copyfile(os.path.join(original_dataset_dir, breed, sub_type, name),
                                                    os.path.join(validation_poodle_dir, name))
                                elif i < test:
                                    shutil.copyfile(os.path.join(original_dataset_dir, breed, sub_type, name),
                                                    os.path.join(test_poodle_dir, name))
                            i += 1

def folder_mover():
    base_dir = 'train/data'
    original_dataset_dir = 'static'
    shutil.move(base_dir, original_dataset_dir)

if __name__ == '__main__':
    organizer()
    folder_mover()


'''
Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

Approach: Space - O(1) and Time: O(n)
Check inline comments.

Link: https://leetcode.com/problems/linked-list-cycle/
'''
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head == None:
            return False
        elif head.next == None:
            return False
        else:
            # The algorithm is to find if the cycle exists with a single pointer
            # Credit goes to my Professor.
            # If there is a cycle then it can be assumed as circle.
            # so the objective is look out for the circle.
            # How?
            # Remember the node after every 2^K steps.
            # At one point of the time the current node will be node which we remembered which confirms there is a cycle.
            # This will take more number of iterations to find the cycle but it does it using a single pointer.
            # As usual, if there is no cycle then the last element of the linked list node will point to None ane the loop breaks.
            current = head
            # step function
            step = 1
            # the next step function
            new_step = step
            # node to be remembered
            node = None
            while current != None:
                if current == node:
                    # cycle found
                    return True
                if step == new_step:
                    # New 2^K step is reached
                    # Update the new step value and node
                    node = current
                    new_step = step*2
                step += 1
                current = current.next
            return False


import nltk
import numpy as np
import pandas as pd

df = pd.DataFrame(columns=['Original_Name','Fixed_Name','UniqueID','SourceID',
                           'Type','Text','SentimentScore','EffectScore','SourceType','Text','Stemmed_Text',
                           'Lowercased','WithoutStopwords', 'WordNgrams','trigram','n4grams','n5grams','BoC',
                           'SenticentScores','Word2VecArrays','DateTime'])
PostsDF = pd.DataFrame(columns=['ID','Source','Type','Text','Effect','RelatedNER','Date','likes','views','Sentiment'])
WordsDf = pd.DataFrame(columns=['Post','Word','NER','POS','Stem','Word2Vec','Sentiment','trigram','n4grams','n5grams'])

gsdf = pd.read_csv('EnglishGS.csv')
texts = gsdf.values[:,1]
texts = texts.tolist()
tokens = []
for text in texts:
    regtokenzr = nltk.RegexpTokenizer('[A-Z,a-z,\$]\w+')
    tarray = regtokenzr.tokenize(str(text))
    tokens.append(tarray)
    print(text,':   ',tarray)


from struct import unpack
import json
import hid
from math import cos, atan

USB_VID = 0x04d8
USB_PID = 0xef7e

def hid_multiread(dev):
    data = dev.read(128, timeout_ms=10)
    res = data

    while len(data) > 0:
        data = dev.read(128, timeout_ms=10)
        res.extend(data)

    return res

def hid_query(dev, addr):
    # 68 byte request, might actually need 64, but not clear
    # when hid versus hidraw is used.
    buffer = bytearray([0] * 68)

    buffer[0] = 0  # Report ID
    buffer[1] = 0
    buffer[2] = addr >> 8  # Page to read
    buffer[3] = addr & 0xff

    res = dev.send_feature_report(buffer)
    assert res >= 0

    res = hid_multiread(dev)
    assert res[:4] == list(buffer[:4])

    return res[4:]

class Calibration:

    def __init__(self, json_in):
        config = json_in

        self.screenW = int(config['screenW']['value'])
        self.screenH = int(config['screenH']['value'])
        self.DPI = int(config['DPI']['value'])
        self.pitch = config['pitch']['value']
        self.slope = config['slope']['value']
        self.center = config['center']['value']

        # Physical image width
        self.screenInches = self.screenW / self.DPI

        self.pitch = self.pitch * self.screenInches * cos(atan(1.0 / self.slope))
        self.tilt = self.screenH / (self.screenW * self.slope)
        self.subp = 1.0 / (3 * self.screenW) * self.pitch

def lg_json(usb_vid=USB_VID, usb_pid=USB_PID, save_flag=False, json_name="LookingGlassConfig.json"):
    '''
    :param usb_vid: Looking Glass USB port VID, look up by 'sudo lsusb | grep Microchip'
    :param usb_pid: Looking Glass USB port PID, look up by 'sudo lsusb | grep Microchip'
    :param save_flag: whether to save the json
    :param json_name: save json name
    :return: a Calibration class of the Looking Glass
    '''
    devs = list(hid.enumerate(usb_vid, usb_pid))
    # print(devs)
    assert len(devs) == 1
    devinfo = devs[0]

    dev = hid.device()
    dev.open_path(devinfo['path'])
    # dev.set_nonblocking(1)

    # Data is read in pages of 64 bytes. First page (0) starts with a
    # 4 byte header denoting the length of the calibration data (in JSON
    # format)
    page = hid_query(dev, 0)

    json_size = unpack('>I', bytes(page[:4]))[0]
    # print('JSON size: %d' % json_size)

    json_data = page[4:]
    addr = 1
    while len(json_data) < json_size:
        page = hid_query(dev, addr)
        json_data.extend(page)
        addr += 1

    json_data = json_data[:json_size]
    json_data = bytes(json_data)
    json_data = json_data.decode('utf8')

    # Pretty print
    parsed = json.loads(json_data)
    print(json.dumps(parsed, indent=4))
    if save_flag:
        with open(json_name, 'w') as outfile:
            outfile.write(json.dumps(parsed, indent=4))
    return Calibration(parsed)


"""Submit proposal content."""
import os
from typing import Optional

import httpx
from starlette.datastructures import UploadFile

from saltapi.auth.token import create_token
from saltapi.repository.user_repository import User
import logging

logger = logging.getLogger(__name__)

proposal_submission_url = f"{os.environ['STORAGE_SERVICE_URL']}/proposal/submit"

async def submit_proposal(
    proposal: UploadFile, proposal_code: Optional[str], submitter: str
) -> str:
    """Submit a proposal."""
    generic_error = "The proposal could not be sent to the storage service."
    files = {
        "proposal": (proposal.filename, proposal.file, "application/octet-stream"),
    }
    data = {
        "submitter": submitter,
    }
    if proposal_code:
        data["proposal_code"] = proposal_code
    user = User(
        id=-1,
        username="admin",
        first_name="",
        last_name="",
        email="",
        roles=["Admin"],
        permissions=[],
    )
    auth_token = create_token(user=user, expiry=300, algorithm="RS256")
    headers = {"Authorization": f"Bearer {auth_token}"}
    try:
        async with httpx.AsyncClient() as client:
            response = await client.post(
                proposal_submission_url, data=data, files=files, headers=headers
            )
    except Exception:
        logger.exception(msg=generic_error)
        raise Exception(generic_error)
    submission_id = _submission_id(response)
    if submission_id:
        return submission_id

    # error handling
    error = _submission_error(response)
    if error:
        logger.error(msg=error)
        raise Exception(error)
    else:
        logger.error(msg=generic_error)
        raise Exception(generic_error)

def _submission_id(response: httpx.Response) -> Optional[str]:
    """
    Extract the submission id sent by the server, if there is one.

    The response body is parsed as a JSON object and its submission_id field is
    returned. If this fails (because the response isn't JSON object or has no
    submission_id field) None is returned.
    """
    try:
        submission_id = response.json().get("submission_id")
        if submission_id is not None:
            return str(submission_id)
        else:
            return None
    except Exception:
        return None

def _submission_error(response: httpx.Response) -> Optional[str]:
    """
    Extract the error message sent by the server, if there is one.

    The response body and is parsed as a JSON object and its error field is returned.
    If this fails (because the response isn't JSON object or has no error field) None is
    returned.
    """
    try:
        error = response.json().get("error")
        if error is not None:
            return str(error)
        else:
            return None
    except Exception:
        return None


# P : A수도, 1리터당 요금
# Q : B수도, 기본 요금
# R : B수도, 기본 요금 한계(<=R)
# S : B수도, 1리터 당 초과 요금(>R)
# W : 종민이 사용 수도 양

T = int(input())
for test_case in range(1, T+1):
    p,q,r,s,w = map(int, input().split())
    wTaxA = p * w
    wTaxB = 0
    if w <= r: wTaxB = q
    else: wTaxB = q + s*(w-r)

    if wTaxA < wTaxB:
        print("#%d"%test_case, wTaxA)
    else :
        print("#%d"%test_case, wTaxB)

SWEA/D2/1284. 수도 요금 경쟁 D2 Attack/수도 요금 경쟁 D2 Attack.py


import csv
import sys

from backend.KoalbyHumanoid.Kinematics.TrajectoryPlanning import TrajPlanner
from backend.KoalbyHumanoid.Robot import SimRobot, RealRobot
from backend.Primitives.MovementManager import play_motion_kinematics
from backend.Simulation import sim as vrep

class Walker:
    def __init__(self):
        self.client_id = None
        self.is_walking = None
        self.position_list = None
        self.keys = None
        self.right_leg_positions = None
        self.left_leg_positions = None

    def init_sim(self):

        vrep.simxFinish(-1)  # just in case, close all opened connections
        self.client_id = vrep.simxStart('127.0.0.1', 19999, True, True, 5000, 5)
        if self.client_id != -1:  # TODO: Fix duplicate code
            print("Connected to remote API server")
        else:
            sys.exit("Not connected to remote API server")

    # def toggle(self, filename, leg_choice, tf, robot):
    #     if self.is_walking:
    #         self.is_walking = False
    #     else:
    #         self.is_walking = True
    #         self.play(filename, leg_choice, tf, robot)

    def init_walk(self, leg_choice):
        self.right_leg_positions = []
        self.left_leg_positions = []
        with open(
                "/Users/caseysnow/Desktop/MQP/flask-project/backend/Primitives/poses/rightWalk") as f:
            # with open(poses/replay_filename) as f:
            csv_recorded_poses = [{k: int(v) for k, v in row.items()}
                                  for row in
                                  csv.DictReader(f,
                                                 skipinitialspace=True)]  # parses selected csv file into list of poses
        for poseMotorPositionsDict in csv_recorded_poses:  # for each pose in the list of recorded poses
            intermediate_position_left = []
            intermediate_position_right = []
            dummy_position = poseMotorPositionsDict
            for key in dummy_position.keys():
                if key == '13' or key == '14' or key == '15':
                    intermediate_position_left.append(dummy_position[key])
                if key == '17' or key == '19' or key == '20':
                    intermediate_position_right.append(dummy_position[key])
            self.left_leg_positions.append(intermediate_position_left)
            self.right_leg_positions.append(intermediate_position_right)
        # print(right_leg_positions)
        # print(left_leg_positions)

        if leg_choice == 1:
            self.position_list = self.left_leg_positions
            self.keys = [13, 14, 15]
        else:
            self.position_list = self.right_leg_positions
            self.keys = [18, 19, 20]

        # numSteps = 0

    def play(self, leg_choice, tf, robot, stop_flags, thread_id):
        t0 = 0
        v0 = 0
        vf = 0
        traj_planner = TrajPlanner()
        # while not stop_flags[thread_id]:
        while True:
            iterate_through_this = traj_planner.execute_cubic_traj(self.position_list, self.keys, t0, tf, v0, vf)

            play_motion_kinematics(robot, iterate_through_this)

            if leg_choice == 1:
                leg_choice = 2
                self.position_list = self.right_leg_positions
                self.keys = [18, 19, 20]

            elif leg_choice == 2:
                leg_choice = 1
                self.position_list = self.left_leg_positions
                self.keys = [13, 14, 15]

if __name__ == "__main__":
    sim_flag = float(input("Are you running the simulation? Type 1 for yes and 0 otherwise"))
    walker = Walker()
    if sim_flag == 1:
        walker.init_sim()
        robot = SimRobot(walker.client_id)
        handle = vrep.simxGetObjectHandle(walker.client_id, 'Cuboid0', vrep.simx_opmode_blocking)[1]
        vrep.simxSetObjectFloatParameter(walker.client_id, handle, vrep.sim_shapefloatparam_mass, 5,
                                         vrep.simx_opmode_blocking)
    else:
        robot = RealRobot()

    trajPlanner = TrajPlanner()
    replay_filename = str(input("Input saved file name to play back:"))
    legChoice = float(input("Enter 1 to move left leg or 2 to move right leg:"))
    tf = float(input("Enter trajectory time (seconds):"))
    walker.isWalking = True
    walker.init_walk(legChoice)
    while True:
        walker.play(legChoice, tf, robot, [], [])


import h5py
import json
import numpy as np
from os.path import splitext, basename, join as pjoin
from pipeline_utils import print_and_call
from pipeline_config import MAPPING_PATH
from graphslam_config import GRAPHSLAM_EVAL_DIR, GRAPHSLAM_MAPS_DIR, MATCH_JSON_DATA
from sklearn.neighbors import NearestNeighbors
import matplotlib.pyplot as plt

'''
Evaluate alignment between maps
First compute bounds of map features to compare
Then compute score
'''

# TODO Parallelize

if __name__ == '__main__':
    # First compute bounding box / center data
    bounds_file_pairs = list()
    for match in MATCH_JSON_DATA:
        fstem1 = '--'.join(match['rss1'])
        fstem2 = '--'.join(match['rss2'])

        map_data1 = pjoin(GRAPHSLAM_MAPS_DIR, fstem1 + '.h5')
        map_data2 = pjoin(GRAPHSLAM_MAPS_DIR, fstem2 + '.h5')
        pcd1 = splitext(map_data1)[0] + '.pcd'
        pcd2 = splitext(map_data2)[0] + '.pcd'

        # First convert to pcd format
        cmd = '%s/bin/h5_to_pcd --h5 %s --pcd %s' % (MAPPING_PATH, map_data1, pcd1)
        print_and_call(cmd)
        cmd = '%s/bin/h5_to_pcd --h5 %s --pcd %s' % (MAPPING_PATH, map_data2, pcd2)
        print_and_call(cmd)

        # Then compute the bounding boxes
        bounds1 = '%s/%s.h5' % (GRAPHSLAM_EVAL_DIR, splitext(basename(pcd1))[0])
        bounds2 = '%s/%s.h5' % (GRAPHSLAM_EVAL_DIR, splitext(basename(pcd2))[0])
        cmd = '%s/bin/compute_bounds %s %s' % (MAPPING_PATH, pcd1, bounds1)
        print_and_call(cmd)
        cmd = '%s/bin/compute_bounds %s %s' % (MAPPING_PATH, pcd2, bounds2)
        print_and_call(cmd)

        bounds_file_pairs.append((bounds1, bounds2))

    # Now compute match quality
    eval_json = dict()
    eval_json['match_eval'] = list()
    for (file_pair, match_data) in zip(bounds_file_pairs, MATCH_JSON_DATA):
        h5f = h5py.File(file_pair[0], 'r')
        centers1 = h5f['cluster_centers'][...]
        h5f.close()
        h5f = h5py.File(file_pair[1], 'r')
        centers2 = h5f['cluster_centers'][...]
        h5f.close()

        # Compute nearest neighbor distances

        nbrs = NearestNeighbors(n_neighbors=1, algorithm='ball_tree').fit(centers1)
        distances, tgt_indices = nbrs.kneighbors(centers2)
        distances = distances.ravel()
        distances = distances[distances < 2.0]  # PARAM

        # Also compute lateral distances when not taking z coord into account

        centers1_lat = np.array(centers1)
        centers2_lat = np.array(centers2)
        centers1_lat[:, 2] = 0.0
        centers2_lat[:, 2] = 0.0
        nbrs_lat = NearestNeighbors(n_neighbors=1, algorithm='ball_tree').fit(centers1_lat)
        distances_lat, tgt_indices_lat = nbrs_lat.kneighbors(centers2_lat)
        distances_lat = distances_lat.ravel()
        distances_lat = distances_lat[distances_lat < 2.0]  # PARAM

        # Compute aggregate statistics

        mean_dist = np.mean(distances)
        median_dist = np.median(distances)

        mean_dist_lat = np.mean(distances_lat)
        median_dist_lat = np.median(distances_lat)

        # Store

        match_eval = dict()
        match_eval['match_data'] = match_data
        match_eval['match_distances'] = {'mean_dist': mean_dist, 'distances': distances.tolist(), 'median_dist': median_dist}
        match_eval['match_distances_lat'] = {'mean_dist': mean_dist_lat, 'distances': distances_lat.tolist(), 'median_dist': median_dist_lat}
        eval_json['match_eval'].append(match_eval)

        # Save evaluation summary

        eval_json_file = '%s/%s.json' % (GRAPHSLAM_EVAL_DIR, '+'.join((fstem1, fstem2)))
        json.dump(eval_json, open(eval_json_file, 'w'), indent=4, sort_keys=True)

        # Save figures

        plt.hist(distances.tolist(), 50)
        plt.ylabel('count')
        plt.xlabel('distance')
        fig_file = '%s/%s_hist.pdf' % (GRAPHSLAM_EVAL_DIR, '+'.join((fstem1, fstem2)))
        plt.savefig(fig_file)

        plt.hist(distances_lat.tolist(), 50)
        plt.ylabel('count')
        plt.xlabel('lateral distance')
        fig_file = '%s/%s_hist_lat.pdf' % (GRAPHSLAM_EVAL_DIR, '+'.join((fstem1, fstem2)))
        plt.savefig(fig_file)


from typing import List
from RLEnv.EnvLayer.PCBRoutingEnv import PCBRoutingEnv
from scipy.spatial.distance import cityblock
import numpy as np

class rl_env(PCBRoutingEnv):
    def __init__(
        self,
        resolution: float,
        pcb_folder: str,
        pcb_names: List[str],
        connect_coef: float=20.0,
        dist_coef: float=0.5,
        path_coef: float = 0.1
    ) -> None:
        super().__init__(resolution, pcb_folder, pcb_names)
        self.connect_coef = connect_coef
        self.dist_coef = dist_coef
        self.path_coef = path_coef

    def reward(self) -> float:
        if np.array_equal(self._agent_location, self._target_location):
            return self.connect_coef
        if self.conflict:
            return -self.dist_coef * cityblock(self._agent_location, self._target_location)

        return -self.path_coef


import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)

def marginal_distribution(mu, sigma2, indeces):
    mu_U = mu[indeces]
    sigma2_U = sigma2[indeces][:,indeces].reshape(-1,len(indeces))
    return mu_U, sigma2_U

def conditional_distribution(X, mu, sigma2, indeces):
    mu_U, sigma2_U = marginal_distribution(mu, sigma2, indeces)
    indeces_V = list(set(range(mu.shape[0])).difference(set(indeces)))
    mu_V, sigma2_V = marginal_distribution(mu, sigma2, indeces_V)
    sigma2_U_V = sigma2[indeces][:,indeces_V]
    sigma2_V_U = sigma2_U_V.T
    U = X[indeces]
    mu_V_U = mu_V + np.dot(np.dot(sigma2_V_U, np.linalg.pinv(sigma2_U)), U-mu_U)
    sigma2_V_U = sigma2_V - np.dot(np.dot(sigma2_V_U,np.linalg.pinv(sigma2_U)), sigma2_U_V)
    return mu_V_U, sigma2_V_U

def display_prior_Gaussian_Process(mu, sigma, lim):
    np.random.seed(0)
    xmin, xmax = lim
    X = np.arange(xmin, xmax,0.1)
    cov = np.array([[np.exp(-(X[i] - X[j])*(X[i] - X[j])/(2*sigma*sigma))  for i in range(X.shape[0])] for j in range(X.shape[0])])
    Y = np.random.multivariate_normal(np.array([mu]*X.shape[0]), cov, 3)
    plt.figure()
    plt.plot(X, Y.T)
    plt.xlabel('x')
    plt.ylabel('y')
    plt.show()

def display_posterior_Gaissian_Process(X_post, Y_post, X_pred, sigma):
    np.random.seed(0)
    xmin, xmax = min(X_pred), max(X_pred)
    X = np.r_[X_post, X_pred]
    Y = np.r_[Y_post, np.zeros(X_pred.shape[0])]
    mu = np.zeros(X.shape[0])
    cov = np.array([[np.exp(-(X[i] - X[j])*(X[i] - X[j])/(2*sigma*sigma))  for i in range(X.shape[0])] for j in range(X.shape[0])])
    mu_pred, sigma2_pred = conditional_distribution(Y, mu, cov, list(range(X_post.shape[0])))

    line = plt.plot(X_pred, mu_pred)
    plt.setp(line, linewidth = 3.0)
    for i in range(5):
        Y_pred = np.random.multivariate_normal(mu_pred, sigma2_pred)
        line = plt.plot(X_pred, Y_pred)
        plt.setp(line, linewidth = 1.0)
    plt.scatter(X_post, Y_post, marker='x', zorder=100, color = 'r')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.show()
    return

sigma_list = [0.3, 0.5, 1.0]

#(a)
for sigma in sigma_list:
    display_prior_Gaussian_Process(0, sigma, (-5,5))

#(c)
X_S = np.array([-1, 2.4, -2.5, -3.3, 0.3])
Y_S = np.array([2, 5.2, -1.5, -0.8, 0.3])
xmin, xmax, step = -4, 3, 0.05
for sigma in sigma_list:
    display_posterior_Gaissian_Process(X_S, Y_S, np.arange(xmin, xmax, step), sigma)


import datetime
from typing import Any, Dict, List, Type, TypeVar, Union

import attr
from dateutil.parser import isoparse

from ..types import UNSET, Unset

T = TypeVar("T", bound="PatchedPipelineInvocation")

@attr.s(auto_attribs=True)
class PatchedPipelineInvocation:
    """Dynamically removes fields from serializer.
    https://stackoverflow.com/questions/27935558/dynamically-exclude-or-include-a-field-in-django-rest-framework-serializer"""

    url: Union[Unset, str] = UNSET
    id: Union[Unset, int] = UNSET
    arn: Union[Unset, str] = UNSET
    release: Union[Unset, str] = UNSET
    pipeline: Union[Unset, str] = UNSET
    created: Union[Unset, datetime.datetime] = UNSET
    additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)

    def to_dict(self) -> Dict[str, Any]:
        url = self.url
        id = self.id
        arn = self.arn
        release = self.release
        pipeline = self.pipeline
        created: Union[Unset, str] = UNSET
        if not isinstance(self.created, Unset):
            created = self.created.isoformat()

        field_dict: Dict[str, Any] = {}
        field_dict.update(self.additional_properties)
        field_dict.update({})
        if url is not UNSET:
            field_dict["url"] = url
        if id is not UNSET:
            field_dict["id"] = id
        if arn is not UNSET:
            field_dict["arn"] = arn
        if release is not UNSET:
            field_dict["release"] = release
        if pipeline is not UNSET:
            field_dict["pipeline"] = pipeline
        if created is not UNSET:
            field_dict["created"] = created

        return field_dict

    @classmethod
    def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:
        d = src_dict.copy()
        url = d.pop("url", UNSET)

        id = d.pop("id", UNSET)

        arn = d.pop("arn", UNSET)

        release = d.pop("release", UNSET)

        pipeline = d.pop("pipeline", UNSET)

        created: Union[Unset, datetime.datetime] = UNSET
        _created = d.pop("created", UNSET)
        if not isinstance(_created, Unset):
            created = isoparse(_created)

        patched_pipeline_invocation = cls(
            url=url,
            id=id,
            arn=arn,
            release=release,
            pipeline=pipeline,
            created=created,
        )

        patched_pipeline_invocation.additional_properties = d
        return patched_pipeline_invocation

    @property
    def additional_keys(self) -> List[str]:
        return list(self.additional_properties.keys())

    def __getitem__(self, key: str) -> Any:
        return self.additional_properties[key]

    def __setitem__(self, key: str, value: Any) -> None:
        self.additional_properties[key] = value

    def __delitem__(self, key: str) -> None:
        del self.additional_properties[key]

    def __contains__(self, key: str) -> bool:
        return key in self.additional_properties


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan  2 13:44:25 2021
@author: Scott T. Small

This module demonstrates documentation as specified by the `NumPy
Documentation HOWTO`_. Docstrings may extend over multiple lines. Sections
are created with a section header followed by an underline of equal length.

"""
import numpy as np
import allel
from .sequtils import get_seg
import bisect
from collections import Counter

def classical_stats(nhaplo, counts):
    """Compute heterozygosity, diversity (pairwise differences) and Tajima's D.

    All calculation are per site

    Parameters
    ----------
    nhaplo : int
        total number of haplotypes
    counts : np.array[Nsnp_seg]
        number of derived alleles at each position for each segment

    Returns
    -------
    H, PI, D: float, float, float
        mean of het, pi, and tajD

    """
    Nhap = np.float(nhaplo)
    a1 = np.sum([1.0/i for i in range(1, nhaplo)])
    a2 = np.sum([1.0/i**2 for i in range(1, nhaplo)])
    c1 = (Nhap+1)/(3*(Nhap-1)) - 1/a1   # b1-1/a1
    c2 = 2*(Nhap**2+Nhap+3)/(9*Nhap*(Nhap-1)) - (Nhap+2)/(a1*Nhap) + a2/a1**2
    H, PI, D = [], [], []
    Nsnp = np.float(counts.shape[0])
    # Expected heterozygosity (at each site) for snp data Arlequin 8.1.1.2 p.115
    H = 2.0/(Nhap-1) * (counts-counts**2 / Nhap)
    # Mean number of pariwise difference (at each site) for snp data Arlequin 8.1.2.1 p.116
    PI = 2.0 / (Nhap * (Nhap-1)) * (counts * (Nhap-counts))
    theta_pi = sum(PI)
    # Other estimate of theta :
    theta_s = Nsnp/a1
    # var_theta_s = (a1**2 * Nsnp + a2 * Nsnp**2) / (a1**2 * (a1**2 + a2) )
    # var_PI= (3*Nhap*(Nhap+1)*PI + 2*(Nhap**2+Nhap+3)*PI**2) / (11*(Nhap**2-7*Nhap+6))
    # var_theta_pi= (3*Nhap*(Nhap+1)*theta_pi + 2*(Nhap**2+Nhap+3)*theta_pi**2) / (11*(Nhap**2-7*Nhap+6))
    # Tajima D, formula from Tajim's paper (1989)
    D = (theta_pi - theta_s) / np.sqrt(c1/a1 * Nsnp + (c2/(a1**2+a2))*Nsnp*(Nsnp-1))

    return H, PI, D

def haplo_het(pos, gt, win_size, length_bp):
    """Estimate haplotype diversity in moving windows.

    Parameters
    ----------
    gt : TYPE
        DESCRIPTION.
    pos : TYPE
        DESCRIPTION.
    size : TYPE, optional
        DESCRIPTION. The default is 4.

    Returns
    -------
    haphet_mean : TYPE
        DESCRIPTION.
    haphet_std : TYPE
        DESCRIPTION.

    """
    hpseg, pos_s = get_seg(gt, pos)
    hh_wins = []
    coords = (range(0, length_bp + win_size, win_size))
    windows = list(zip(coords[0::1], coords[1::1]))
    for s, e in windows:
        hp1_win = hpseg.compress((pos_s > s) & (pos_s <= e), axis=0)
        hh_ = allel.haplotype_diversity(hp1_win)
        hh_wins.append(hh_)
    haphet_mean = np.nanmean(hh_wins)
    haphet_std = np.nanstd(hh_wins)

    return haphet_mean, haphet_std

def tajimaD(pos, gt, win_size, length_bp):
    """Calculate Tajima's D in steps of seg sites.

    Parameters
    ----------
    ac : array
        allele counts array
    size : int, optional
        window size in number of variants. The default is 4.

    Returns
    -------
    tajd_mean : float
        DESCRIPTION.
    tajd_std : float
        DESCRIPTION.

    """
    gtseg, pos_s = get_seg(gt, pos)
    ac = gtseg.count_alleles()
    tajd_, *_ = allel.windowed_tajima_d(pos_s, ac, size=win_size, start=1, stop=length_bp)
    tajd_mean = np.nanmean(tajd_)
    tajd_std = np.nanstd(tajd_)

    return tajd_mean, tajd_std

def pi_window(pos, gt, win_size, length_bp):
    """Calculate pi in windows.

    Parameters
    ----------
    gt : TYPE
        DESCRIPTION.
    pos : TYPE
        DESCRIPTION.
    win_size : TYPE
        DESCRIPTION.
    length_bp : TYPE
        DESCRIPTION.

    Returns
    -------
    pi_mean : TYPE
        DESCRIPTION.
    pi_std : TYPE
        DESCRIPTION.

    """
    gtseg, pos_s = get_seg(gt, pos)
    ac = gtseg.count_alleles()
    pi, *_ = allel.windowed_diversity(pos_s, ac, size=win_size, start=1, stop=length_bp)
    pi_mean = np.nanmean(pi)
    pi_std = np.nanstd(pi)

    return pi_mean, pi_std

def exp_het(pos, gt):
    """Calculate the expected rate of heterozygosity for each variant under HWE.

    Parameters
    ----------
    gt : TYPE
        DESCRIPTION.
    pos : TYPE
        DESCRIPTION.

    Returns
    -------
    het_mean : TYPE
        DESCRIPTION.
    het_std : TYPE
        DESCRIPTION.

    """
    gtseg, pos_s = get_seg(gt, pos)
    af = gtseg.count_alleles().to_frequencies()
    het = allel.heterozygosity_expected(af, ploidy=2)
    het_mean = np.nanmean(het)
    het_std = np.nanstd(het)

    return het_mean, het_std

def het_one_win(dataslice, Nhap):
    """Compute haplotypic heterozygosity of a given window.

    Parameters
    ----------
    dataslice : np.array
        subset of the data corresponding to a given window of the sequence
    Nhap : int
        total number of haplotypes

    Returns
    -------
    het : float
        haplotypic heterozygosity of dataslice
    """
    haplos = [''.join([repr(num) for num in dataslice[i, :]]) for i in range(Nhap)]
    tab = Counter(haplos)
    het = 1.0-sum([x**2 for x in tab.values()])/float(Nhap)**2

    return het

def haplo_win(pos, hap, win_size, length_bp):
    """Compute haplotypic heterozygosity in windows sliding along the genome.

    Parameters
    ----------
    pos : np.array
        positions of SNP for rach segment
    hap : np.array
        haplotype data for each segment
    win_size : int
        lengh of the sliding windows considered as haplotypes (bp)
    length_bp : int
        length of each simulated segment (bp)

    Returns
    -------
    hap_het : float, float
        mean and standard deviation of haplotypic heterozygosity

    """
    Nhap = hap.shape[0]
    L = length_bp
    win_size = int(win_size)
    chunks = [bisect.bisect(pos, x) for x in range(0, L, win_size)]
    hets = [het_one_win(hap[:, chunks[i]:chunks[i+1]], Nhap) for i in range(len(chunks)-1)]
    Nhap = np.float(Nhap)
    haphet_mean = Nhap/(Nhap-1.0) * np.mean(hets)
    haphet_std = Nhap/(Nhap-1.0) * np.std(hets)

    return haphet_mean, haphet_std


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('sponsorships', '0003_sponsorship_event'),
    ]

    operations = [
        migrations.CreateModel(
            name='SponsorshipLevel',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=250)),
                ('description', models.TextField(blank=True)),
                ('amount', models.DecimalField(max_digits=10, decimal_places=2)),
                ('event', models.ForeignKey(related_name='sponsorship_levels', to='events.Event')),
            ],
            options={
                'verbose_name': 'Sponsorship Level',
                'verbose_name_plural': 'Sponsorship Levels',
            },
        ),
        migrations.AddField(
            model_name='sponsorship',
            name='level',
            field=models.ForeignKey(related_name='sponsorships', blank=True, to='sponsorships.SponsorshipLevel', null=True),
        ),
    ]


import threading
from queue import Queue

def jop1():
    global lock
    a=0
    lock.acquire()
    for i in range(10):
        a+=i
        print('a=',a)
    lock.release()
def jop2():
    b=0
    lock.acquire()
    for i in range(100):
        b+=i
        print('b=',b)
    lock.release()
if __name__ == '__main__':
    lock = threading.Lock()
    t1 = threading.Thread(target=jop1)
    t2 = threading.Thread(target=jop2)
    t1.start()
    t2.start()
    t2.join()


import socket
import threading
import struct

ip_addr = "0.0.0.0"
tcp_port = 7777

def process_client_stats(client_socket,address):
    print(f'Accepted connection from {address[0]}:{address[1]}')

    logFile = open(f"{address[0]}_{address[1]}.txt", 'w')
    try:
        while True:
            request = client_socket.recv(1024)
            if not request:
                client_socket.close()
                break
            else:
                print(request.decode())
                logFile.write(f"{request.decode()}\n")
                logFile.flush()
    except (socket.timeout, socket.error):
        print(f'Client {address} error. Done!')
    finally:
        logFile.close()

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((ip_addr, tcp_port))
server.listen()

print(f'Listening on {ip_addr}:{tcp_port}')

while True:
    client_sock, address = server.accept()
    client_handler = threading.Thread(target=process_client_stats,args=(client_sock,address),daemon=True)
    client_handler.start()


from __future__ import print_function

import logging
import sys

from argh import *
from vcloudtools.api import VCloudAPIClient

log = logging.getLogger(__name__)
parser = ArghParser()

@arg('path', help='Path to fetch', default='/')
def browse(args):
    """
    Browse the vCloud API using the built-in hypermedia links
    """
    c = VCloudAPIClient()
    res = c.browse(args.path)

    print('HTTP/1.1 {0} {1}'.format(res.status_code, res.reason))

    for k, v in res.headers.items():
        print("{0}: {1}".format(k, v))

    print()
    print(res.content)

def main():
    dispatch_command(browse)

if __name__ == '__main__':
    main()


import json

with open ("city.json") as file:
	data = json.load(file)

list_data = []
for i in data:
	#print (i['name'])
	list_data.append({"id":i['id'], "text":i["name"]})

data = {"results":list_data}
with open("city_name.json", "w") as f:
	json.dump(list_data, f)


#DFS를 이용한 bipartite matching
#Kuhn's Algorithm
def bpm(s):

    #방문 체크한 s번에서 또 연결을 체크한다면...
    if visited[s] == 1:

        return False

    #최초로 s번에서 연결을 시도한다면.. 방문체크를 해주고
    visited[s] = 1

    #s와 연결된 모든 v에 대하여...
    for v in graph[s]:

        #v가 매칭되어 있지 않거나
        #v가 매칭되어 있다면, 해당 매칭된 번호 matching[v]로 다시 들어가서 연결을 재조정
        if matching[v] == 0 or bpm(matching[v]):

            #매칭되어 있지 않거나, 연결을 재조정하는데 성공했다면 s를 v에 연결
            matching[v] = s

            #s번은 연결에 성공했으니 True
            return True

    #연결에 실패했다면...
    return False

n,m = map(int,input().split())

graph = [[] for _ in range(n+1)]

matching = [0]*(m+1)

for i in range(1,n+1):

    lines = list(map(int,input().split()))

    for j in range(1,lines[0]+1):

        graph[i].append(lines[j])

#improve technique
#arbitrary matching
#simple heuristic algorithm
random_visited = [0]*(n+1)

for i in range(1,n+1):

    for s in graph[i]:

        if matching[s] == 0:

            matching[s] = i
            random_visited[i] = 1
            break

#bipartite matching
count = 0

#1번부터 n번까지 매칭을 시도
for i in range(1,n+1):

    #i번에서 이미 위에서 수행한 랜덤매칭이 수행되어 있다면, 넘겨준다.
    if random_visited[i] == 1:
        continue

    #랜덤매칭이 되어있지 않다면, i번에 대해 bipartite matching을 시도
    visited = [0]*(n+1)
    bpm(i)

#matching배열을 모두 순회하여,
#정점 번호는 1번부터 시작하니 matching[i]가 0이 아니면 매칭이 된 상태이다.
for i in range(1,m+1):

    if matching[i] != 0:

        count += 1

print(count)


from datetime import datetime
import schedule

from telebot import types

from rf_bank_api import get_banks_currency
from keyboards import kb_banks, kb_currencies, kb_configure
from database_work import add_banks, add_currencies, get_currencies, get_banks, form_gist
from data import banks, currencies, rus_to_en_banks, rus_to_en_currencies
from obj_store_work import get_from_os

import telebot

def schedule_statistic():
    schedule.every().monday.at("07:00").do(form_gist, 'statistics')
    while True:
        schedule.run_pending()

def telegram_bot(token):
    bot = telebot.TeleBot(token)

    @bot.message_handler(commands=["start"])
    def start_message(message):
        bot.send_message(message.chat.id, "Чтобы узнать о возможностях бота, введите команду /help")

    @bot.message_handler(commands=["help"])
    def start_message(message):
        bot.send_message(message.chat.id, "/help - помощь \n/configure - выбор валют и банков \n/notifyOn - включить ежедневные уведомления\n"
                                          "/get - получить сводку по выбранным валютам и банкам \n/getstat - получение статистики ")

    @bot.message_handler(commands=["get"])
    def start_message(message):
        send_notify(message)

    @bot.message_handler(commands=['configure'])
    def start_message(message: types.Message):
        response = bot.send_message(message.chat.id, text="Выберите из списка:", reply_markup=kb_configure)
        d = {'c': [], 'l': []}
        bot.register_next_step_handler(response, choose_option, d)

    @bot.message_handler(commands=['getstat'])
    def start_message(message: types.Message):
        response = get_from_os()
        bot.send_photo(message.chat.id, response['Body'].read())

    def choose_option(message, d):
        if message.text == 'Выбрать банки':
            response = bot.send_message(message.chat.id, text="Выберите банки:", reply_markup=kb_banks)
            bot.register_next_step_handler(response, choose_banks, d)
        if message.text == 'Выбрать валюты':
            response = bot.send_message(message.chat.id, text="Выберите валюты:", reply_markup=kb_currencies)
            bot.register_next_step_handler(response, choose_currency, d)
        if message.text == 'Закрыть':
            bot.send_message(message.chat.id, text=f"Изменения сохранены.\nТекущие настройки:\n Банки:{d.get('l')}\n"
                                                   f"Валюты: {d.get('c')}", reply_markup=types.ReplyKeyboardRemove())

    def choose_banks(message, d):
        if message.text != "Закрыть":
            for bank in banks:
                if message.text == banks.get(bank).get("rus_spell"):
                    append_banks(d.get('l'), message)
                    break
            message = bot.send_message(message.chat.id, text="Выберите банки:", reply_markup=kb_banks)
            bot.register_next_step_handler(message, choose_banks, d)
        else:
            add_banks(message.chat.id, d.get('l'))
            message = bot.send_message(message.chat.id, text=f"Выбранные банки: {d.get('l')}. Сохранено!",
                                       reply_markup=kb_configure)
            bot.register_next_step_handler(message, choose_option, d)

    def append_banks(l, message):
        if not l.__contains__(message.text):
            l.append(message.text)
        return bot.send_message(message.chat.id, text=f"Выбранные банки: {l}. Выберите банки:",
                                reply_markup=kb_banks)

    def append_currencies(c, message):
        if not c.__contains__(message.text):
            c.append(message.text)
        return bot.send_message(message.chat.id, text=f"Выбранные валюты: {c}. Выберите валюты:",
                                reply_markup=kb_currencies)

    def choose_currency(message, d):
        if message.text != "Закрыть":
            for cur in currencies:
                print()
                if (message.text + " (EUR)" == currencies.get(cur).get("rus_spell")) or \
                        (message.text + " (USD)" == currencies.get(cur).get("rus_spell")):
                    append_currencies(d.get('c'), message)
                    break
            message = bot.send_message(message.chat.id, text="Выберите валюты:", reply_markup=kb_currencies)
            bot.register_next_step_handler(message, choose_currency, d)
        else:
            add_currencies(message.chat.id, d.get('c'))
            bot.send_message(message.chat.id, text=f"Выбранные валюты: {d.get('c')}. Сохранено!",
                             reply_markup=kb_configure)
            bot.register_next_step_handler(message, choose_option, d)

    @bot.message_handler(commands=['show'])
    def start_message(message: types.Message):
        user_id = message.chat.id
        bot.send_message(message.chat.id, text=f"Текущие настройки:\n Банки:{get_banks(user_id)}\n"
                                               f"Валюты: {get_currencies(user_id)}")

    @bot.message_handler(commands=['notifyOn'])
    def notify_on(message):
        configure_notification(message)

    def configure_notification(message):
        schedule.every().day.at("07:00").do(send_notify, message)
        bot.send_message(message.chat.id, f"Уведомления включены.", parse_mode='html')
        while True:
            schedule.run_pending()

    def send_notify(message):
        bot.send_message(message.chat.id, text=str(datetime.now()))
        user_id = message.chat.id
        for bank in get_banks(user_id)[0]:
            for curr in get_currencies(user_id)[0]:
                bot.send_message(message.chat.id,
                                 text=get_banks_currency(rus_to_en_banks.get(bank), rus_to_en_currencies.get(curr)))

    bot.polling()


import time
import os, json
import wiotp.sdk.application

client = None

def commandCallback(event):
    if event.eventId == "doorStatus":
        # Received event 'doorStatus'
        payload = json.loads(event.payload)
        # Get the status and time
        status = payload['status']
        time = payload['time']
        print("Status: " + status)
        print("Time: " + time)

def main():
    try:
        # Try and connect the client to the IBM Server
        options = wiotp.sdk.application.parseConfigFile("application.yaml")
        client = wiotp.sdk.application.ApplicationClient(config=options)
        client.connect()
        while True:
            # Continually subscribe to the event and call the callback function
            client.deviceEventCallback = commandCallback
            client.subscribeToDeviceEvents(eventId="doorStatus")
            time.sleep(0.1)
    except Exception as e:
        print(e)

if __name__ == "__main__":
    main()


import discord, asyncio, requests, datetime

# -- INIT --

POST_TIME_H = 6
POST_TIME_M = 0
POST_TIME_S = 0

BOT_EMAIL = ''
BOT_PASS = ''

KEY = ''

CHAN_ID = ''

# Connect to client
client = discord.Client()

def apiGet(url):
    response = requests.get(url)
    return response.json()

def randomWord():
    url = "http://api.wordnik.com:80/v4/words.json/randomWord?hasDictionaryDef=true&minCorpusCount=0&\
	maxCorpusCount=-1&minDictionaryCount=1&maxDictionaryCount=-1&minLength=5&maxLength=-1&api_key=" + KEY
    data = apiGet(url)
    return data["word"]

def defLook(word):
    url = "http://api.wordnik.com:80/v4/word.json/" + word +\
    "/definitions?limit=200&includeRelated=true&useCanonical=false&includeTags=false&api_key=" + KEY
    data = apiGet(url)
    if len(data) == 0:
        return ""
    else:
        return data[0]["text"]

def post(word, definition):
    return  "**WORD OF THE DAY: " + word + "**\n" +\
            "*Def - " + definition + "*"

def toWait(time):
    base = 86400
    h = time.hour - POST_TIME_H
    m = time.minute - POST_TIME_M
    s = time.second - POST_TIME_S
    dif = (h * 60 * 60) + (m * 60) + s
    if dif < 0:
        return abs(dif)
    else:
        return base - dif

# -- START --
@asyncio.coroutine
def my_background_task():
    lastPin = None
    yield from client.wait_until_ready()
    print("-- Task Started --")
    chan = discord.Object(id=CHAN_ID)
    while not client.is_closed:
        print("-- Selecting Word --")
        # Pull word from toread
        word = randomWord()
        # Pull def
        definition = defLook(word)
        print(word)
        print(definition)
        # Input word and def into proper format
        toPost = post(word, definition)
        # Calculate time til post time
        now = datetime.datetime.now()
        timeToWait = toWait(now)
        print("-- READY AT: {0} --".format(now))
        print("-- WAITING FOR: {0}s --".format(timeToWait))
        # Wait
        yield from asyncio.sleep(timeToWait)
        # Unpin last message
        if lastPin is not None:
            client.unpin_message(lastPin)
        # Post to client
        lastPin = yield from client.send_message(chan, toPost)
        # Pin new message
        client.pin_message(lastPin)
# -- END --

@asyncio.coroutine
def test_post():
    print("-- TEST --")
    yield from client.wait_until_ready()
    yield from client.send_message(CHAN_ID, "test")

# -- RUN --
# client.loop.create_task(my_background_task())
client.async_event(test_post)
client.run(BOT_EMAIL, BOT_PASS)


info_student = [
    "João", "Wagner", "Andre", "Victor", "Odilon", "Maycon", "Marlon", "Alan", "Patrick", "Guilherme Reis", "Brecailo", "Eduarda", "Eduardo", "Erick", "Fabricio", "Giselle", "Gui Felicio", "Júlio", "Kauany", "Kazulle", "Lucas", "Rafael", "Rhuan", "Sasah"
]

user_logat = input("Digite Seu Usuario: ")
user_person = ""

user_person = user_logat

for i in info_student:
    if user_logat == i:
        user_person = "Seja bem vindo aluno da FAP: " + user_logat

print(user_person)


from __future__ import print_function
import sys
import re
import argparse

p = argparse.ArgumentParser( description="Read ascii index "
   "and output a list of registers and descriptions." )

p.add_argument("-i",required=True, help="input file",dest='inxfile')
p.add_argument("-o", help="output file name", dest='outf' )

a = p.parse_args()

with open (a.inxfile, 'r' ) as l :
  inx = l.read()

l.close()
#   '     1.3     Peripheral availability. . . . . . . . 48'
#rse = re.compile( r'(\d+.*?\s+\.\s+\d+)', re.MULTILINE | re.DOTALL )
rse = re.compile( r'(\d+.*?\s+\d+$)', re.MULTILINE | re.DOTALL )

inx = re.sub( r'\n\s+(?=[A-Za-z\(])'," ",inx )
rs = rse.findall( inx )

inxrow = re.compile( r'(\d+.*?)\s+(.*?)(\d+)$' )
regi = {}
regs = []
sections = []

for reg in rs :
  reg = re.sub( r'[\s\n]+', " ", reg )
  m = inxrow.match(reg)

  if m is None :
    print("Couldn't fit {0}".format(reg))
    continue

  s = m.group(1)
  t = m.group(2)
  p = m.group(3)

  t = re.sub( r'\.', "", t )
  t = re.sub( r'\s+', " ", t )
  t = re.sub( r'\s+$', "", t)
  t = re.sub( r'&', '&', t)
  t = re.sub( r'<', '<', t)
  t = re.sub( r'>', '>', t)

  regline = re.compile( r'register.*\(([A-Za-z0-9_]+)\)' )

  m = regline.search(t)
  if m is None :
    sections.append ("
%s
" %(s,p,t))
  else:
    r = m.group(1)
    if not r in regi :
      regs.append(r)
      regi[r] = t
    else:
      if len(t) < len(regi[r]) :
        regi[r] = t
    sections.append( "
%s
" %
      ( s, p, r,t) )

with (sys.stdout if a.outf is None or a.outf=='-' else open(a.outf,'w')) as o:
  o.write ("<index>\n  <sections>\n")
  for s in sections :
    o.write("    %s\n" % s)
  o.write ("  </sections>\n<registers>\n")
  for r in regs :
    o.write ("    <register name='%s'>%s</register>\n" % ( r, regi[r] ))
  o.write ("  </registers>\n</index>\n")

o.close()


# -*- encoding:utf-8 -*-

import numpy as np

from basic.specturm import _spectrogram
from basic.pitch import estimate_tuning
import util.utils as utils
import filters

def chroma_stft(y=None, sr=22050, S=None, norm=np.inf, n_fft=2048,
                hop_length=512, tuning=None, **kwargs):
    S, n_fft = _spectrogram(y=y, S=S, n_fft=n_fft, hop_length=hop_length,
                            power=2)

    n_chroma = kwargs.get('n_chroma', 12)

    if tuning is None:
        tuning = estimate_tuning(S=S, sr=sr, bins_per_octave=n_chroma)

    if 'A440' not in kwargs:
        kwargs['A440'] = 440.0 * 2.0**(float(tuning) / n_chroma)

    chromafb = filters.chroma(sr, n_fft, **kwargs)
    raw_chroma = np.dot(chromafb, S)

    return utils.normalize(raw_chroma, norm=norm, axis=0)


# 4.2 바이트에 대한 기본 지식
# bytes 와 bytearray
# bytes는 불변형이고, bytearray는 가변형

cafe = bytes('café',encoding='utf_8')
print(cafe)

print(cafe[0])
print(cafe[:1])
cafe_arr = bytearray(cafe)
print(cafe_arr)
print(cafe_arr[:-1])

import array
numbers = array.array('h',[-2,-1,0,1,2]) #h명령어는 short int 형의 배열을 생성한다.
print(numbers)
octets = bytes(numbers) # 사본이다.
print(octets)
# 버터와 같은 객체로 부터 bytes와 bytearray를 생성하게 되면 언제나 바이트를 복사한다.
# 하지만 memoryview를 활용하면 데이터 구조체 간에 메모리를 공유할 수 있게 해준다.

# struct모듈은 다양한 형의 필드로 구성된 튜플을 분석하고, 이와 반대로 튜플을 패킹된 바이트로 변환하는 함수를 제공
# struct는 bytes, bytearray, memoryview객체와 함께 사용된다.

import struct
fmt = '<3s3sHH'
with open('filter.gif','rb') as fp:
    img = memoryview(fp.read())

header = img[:10]
print(bytes(header))
struct.unpack(fmt,header)
del header
del img


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def recoverTree(self, root: Optional[TreeNode]) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        self.left = None
        self.right = None
        self.prev = None

        self.dfs(root)
        if self.left and self.right:
            self.left.val, self.right.val = self.right.val, self.left.val

    def dfs(self, node):
        if node.left:
            self.dfs(node.left)

        if self.prev and self.prev.val > node.val:
            if not self.left:
                self.left = self.prev
            if self.left:
                self.right = node

        self.prev = node

        if node.right:
            self.dfs(node.right)


from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator

from users.models import User

class BaseModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class Category(BaseModel):
    name = models.CharField(max_length=64, unique=True)
    description = models.TextField(null=True, blank=True)

    class Meta:
        verbose_name_plural = 'Категории Игр'
        verbose_name = 'Категория Игры'

    def __str__(self):
        return self.name

class Game(BaseModel):
    user = models.ForeignKey(User, verbose_name='пользователь', related_name='user_games', on_delete=models.CASCADE)
    title = models.CharField(max_length=80, verbose_name='название игры')
    slug = models.SlugField(max_length=80, verbose_name='слаг', unique_for_date='created_at')
    description = models.TextField(verbose_name='описание')
    image = models.ImageField(null=True, blank=True, upload_to='games_images', verbose_name='скрин из игры')
    price = models.IntegerField(null=True, blank=True, verbose_name='цена',
                                validators=[MinValueValidator(1), MaxValueValidator(5000)])
    category = models.ManyToManyField(Category)

    class Meta:
        verbose_name_plural = 'Игры'
        verbose_name = 'Игра'

    def __str__(self):
        return self.title

class Favourite(models.Model):
    user = models.ForeignKey(User, verbose_name='пользователь', related_name='user_favourite', on_delete=models.CASCADE)
    game = models.ForeignKey(Game, verbose_name='игра', related_name='game_favourite', on_delete=models.CASCADE)

    class Meta:
        verbose_name_plural = 'Список желаемого'
        verbose_name = 'Список желаемого'

class Comment(BaseModel):
    game = models.ForeignKey(Game, verbose_name='игра', related_name='game_comments', on_delete=models.CASCADE)
    user = models.ForeignKey(User, verbose_name='пользователь', related_name='user_comments', on_delete=models.CASCADE)
    text = models.TextField(verbose_name='текст комментарий')

    class Meta:
        verbose_name_plural = 'Комментарии'
        verbose_name = 'Комментарий'

    def __str__(self):
        return self.text

class UserInfo(BaseModel):
    user = models.ForeignKey(User, related_name='user_info', verbose_name='пользователь', on_delete=models.CASCADE)
    name = models.CharField(null=True, blank=True, max_length=40, verbose_name='имя')
    about = models.TextField(null=True, blank=True, max_length=200, verbose_name='информация о себе')

    class Meta:
        verbose_name_plural = 'Информация о пользователях'
        verbose_name = 'Информация о пользователе'

    def __str__(self):
        return self.name

class Basket(models.Model):
    user = models.ForeignKey(User, verbose_name='пользователь', related_name='user_basket', on_delete=models.CASCADE)
    game = models.ForeignKey(Game, verbose_name='игра_в_корзине', related_name='game_basket', on_delete=models.CASCADE)
    created_timestamp = models.DateTimeField(auto_now_add=True)
    modificated_timestamp = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name_plural = 'Корзины пользователей'
        verbose_name = 'Корзина пользователя'

    def __str__(self):
        return f'Корзина для {self.user.username} | Продукт {self.game.title}'

    def sum(self):
        return self.game.price


from statistics import median_low as mdl, median_high as mdh, median as md
from copy import deepcopy as dc
num = int(input())
floors = list(map(int, input().split()))
newfloor = dc(floors)
newfloor.sort()

if len(floors)%2==0:
    medl = mdl(newfloor)
    medh = mdh(newfloor)
    midmed = md(newfloor)
    ind = min([floors.index(medl), floors.index(medh)])

    if floors.index(medl) == floors.index(medh):
        print(floors.index(midmed)+1)
    else:
        print(ind+1)
else:
    midmed = md(newfloor)
    print(floors.index(midmed)+1)


import os

def readname():
    # filePath = './div2k'
    # filePath = './pristine_images'
    # filePath = './BSD432_color'
    filePath = './flower_2000'
    name = os.listdir(filePath)
    return name, filePath

if __name__ == "__main__":
    name, filePath = readname()
    print(name)
    txt = open("train.txt", 'w')
    for i in name:
        image_dir = os.path.join(filePath + "/", str(i))
        txt.write(image_dir + "\n")