#!/usr/local/bin/python3.11

from tkinter import *
from datetime import datetime
import sqlite3
import datetime
from tkcalendar import Calendar, DateEntry
from tkinter import messagebox
from configparser import ConfigParser
from frame_functions import *
from pdf_report import *

# from tkinter import askopenfilename
database = "database files/kdm_stores.db"
lookup_record = "Returns"

def populate_returns_tree(tree, records):
    for record in tree.get_children():
        tree.delete(record)
    global count
    count = 0
    current_time = datetime.now()

    #	print(record)
    # sort the records
    # records = sorted(records, key=lambda x: datetime.strptime(x[5], "%d-%m-%Y"), reverse=True)
    for record in records:
        # in_stock_since = datetime.strptime(record[5], "%d-%m-%Y")  # Assuming the date is in the sixth column
        # elapsed_time = (current_time - in_stock_since).days
        if count % 2 == 0:
            tree.insert(parent='', index='end', iid=count, text='',
                        values=(record[0], record[3], record[2], record[3], record[4], record[6], record[7]),
                        # values=(record[0], record[3], record[4],record[5]),
                        tags=('evenrow',))
        else:
            tree.insert(parent='', index='end', iid=count, text='',
                        values=(record[0], record[2], record[0], record[4], record[5], record[6], record[7]),
                        # values=(record[0], record[3], record[4], record[5]),
                        tags=('oddrow',))
        # increment counter
        count += 1

# Call the function with your database path
def create_returns_table(database):
    # Create a database or connect to one that exists
    connection = sqlite3.connect(database)
    # Create a cursor instance

    cursor = connection.cursor()
    with connection:
        # Create Table
        cursor.execute("""CREATE TABLE if not exists returns (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
            	fleet_number text,
            	return_motive text,
            	cpr_number text,
            	date_created date,
            	date_returned date,
            	status text)
            	""")
        print("Table Created")

# create_returns_table(database)
# insert_dummy_data(database)
def query_returns_table(database):
    # Create a database or connect to one that exists
    connection = sqlite3.connect(database)
    # Create a cursor instance

    cursor = connection.cursor()
    with connection:
        # Create Table
        cursor.execute("""SELECT rowid,* FROM returns""")
        records = cursor.fetchall()
        for record in records:
            print(record)
        return records

query_returns_table(database)

class GoodsReturnClass:

    def __init__(self, master_root, kdm_division, division_image):
        """Init method for objects of class Small tools"""

        kdm_division = kdm_division
        self.report = None
        self.master_root = master_root
        self.window = Toplevel(master_root)
        self.window.title(kdm_division)

        self.kdm_division = kdm_division
        self.parser = ConfigParser()
        self.parser.read("treebase.ini")
        self.saved_primary_color = self.parser.get('colors', 'primary_color')
        self.saved_secondary_color = self.parser.get('colors', 'secondary_color')
        self.saved_highlight_color = self.parser.get('colors', 'highlight_color')

        # Designate Height and Width of our app
        app_width = 1400
        app_height = 850
        # get the current screen measures
        screen_width = master_root.winfo_screenwidth()
        screen_height = master_root.winfo_screenheight()
        # center the window on the current screen
        x = (screen_width / 2) - (app_width / 2)
        y = (screen_height / 2) - (app_height / 2)

        self.window.geometry(f'{app_width}x{app_height}+{int(x)}+{int(y)}')
        master_root.withdraw()
        self.frame()

        # use images like buttons
        self.button_image = PhotoImage(file=division_image)
        label_text = f"Close {kdm_division} window"
        self.label = Label(self.window, text=label_text)
        self.label.pack()
        self.button = Button(self.window, image=self.button_image, command=self.close)
        self.button.pack(pady=10)
        self.button.bind("<Return>", self.bind_close)

    def update(self):
        records = query_returns_table(database)
        populate_returns_tree(self.my_tree, records)

    def create_returns_report(self):
        lookup_record = self.kdm_division
        records, details = query_pdf_data(lookup_record)
        create_pdf(details, lookup_record)
        messagebox.showinfo("PDF Report Created", f"PDF file for {lookup_record} created.")

    def clear_entry_boxes(self):
        """Clear all entry boxes"""
        # Clear entry boxes
        try:
            database_id_entry.delete(0, END)
            # division_entry.delete(0, END)
            info_fleet_number_entry.delete(0, END)
            # info_job_number_entry.delete(0, END)
            info_description_entry.delete(0, END)
            # info_requested_by_entry.delete(0, END)
            info_date_added_entry.delete(0, END)
        except:
            pass

    def select_record(self, event):
        self.clear_entry_boxes()

        # Grab record Number
        selected = self.my_tree.focus()
        # Grab record values from the tree
        values = self.my_tree.item(selected, 'values')
        # output to entry boxes
        try:
            database_id_entry.insert(0, values[0])
            # print(f"ID = {values[0]}")

            info_fleet_number_entry.insert(0, values[1])
            # print(f"Fleet Number = {values[1]}")

            info_description_entry.insert(0, values[2])
            # print(f"Part description = {values[2]}")

            info_date_added_entry.insert(0, values[3])
            # print(f"Date added = {values[3]}")

        except:
            print("error")

    def close(self):
        """Close the current window and open the main window"""
        self.window.destroy()
        self.master_root.deiconify()

    def bind_close(self, event):
        self.close()

    def cancel_entry(self):
        """Close the window if canceled"""
        self.add_new_record_frame.destroy()

    def bind_cancel_entry(self, event):
        """Close the window if canceled"""
        self.cancel_entry()

    def bind_add_record_to_database(self, event):
        self.add_record_to_database()

    def reset(self):
        records = query_returns_table(database)
        populate_returns_tree(self.my_tree, records)

    def add_record_to_database(self):

        # Define the data to be inserted
        kdm_division = self.kdm_division
        fleet_number = new_fleet_number_entry.get().upper().strip()
        description = new_description_entry.get().title().strip()
        date = date_label.cget("text")

        status = 'current status'
        # division = self.kdm_division

        # Update the database
        # Create a database or connect to one that exists
        connection = sqlite3.connect(database)

        # Create a cursor instance
        cursor = connection.cursor()
        with connection:
            # Add New Record
            # Insert the data into the table
            cursor.execute("""
                INSERT INTO vor_shelves_data (kdm_division, fleet_number, parts_description, in_stock_since,status)
                VALUES (?, ?, ?, ?, ?)
            """, (kdm_division, fleet_number, description, date, status))

        self.add_new_record_frame.destroy()
        self.update()
        messagebox.showinfo("VOR Update", "Parts added.")

    def bind_query_kdm_division(self, event):
        self.update()

    def add_new_record_window(self):
        """Add new record to the database"""
        global add_new_record_frame
        app_width: int = 800
        app_height = 400
        self.add_new_record_frame = Toplevel(self.window)
        screen_width = self.add_new_record_frame.winfo_screenwidth()
        screen_height = self.add_new_record_frame.winfo_screenheight()
        # This will center the app on the screen
        x = (screen_width / 2) - (app_width / 2)
        y = (screen_height / 2) - (app_height / 2)

        self.add_new_record_frame.geometry(f'{app_width}x{app_height}+{int(x)}+{int(y)}')
        self.add_new_record_frame.title(f"Add new record to {self.kdm_division} Database")

        global new_fleet_number_entry
        fleet_number_label = Label(self.add_new_record_frame, text='Fleet Number', font=("Arial", 30))
        fleet_number_label.grid(row=2, column=0, padx=10, pady=10)
        new_fleet_number_entry = Entry(self.add_new_record_frame)
        new_fleet_number_entry.grid(row=2, column=1, padx=10, pady=10)

        global new_description_entry
        description_label = Label(self.add_new_record_frame, text="Parts Description", font=("Arial", 30))
        description_label.grid(row=4, column=0, padx=10, pady=10)
        new_description_entry = Entry(self.add_new_record_frame)
        new_description_entry.grid(row=4, column=1, padx=10, pady=10)

        global clicked
        clicked = StringVar()
        # clicked.set(name_options[0])
        global date_label

        global date_label

        def select_date():
            date_label.config(text=calendar.get_date())
            date_window.destroy()

        def pick_date():
            global calendar, date_window
            date_window = Toplevel()
            date_window.grab_set()
            date_window.title("Select Date")
            date_window.geometry("400x300")
            calendar = Calendar(date_window, selectmode='day', date_pattern="dd-mm-y", font=("Arial", 20),
                                borderwidth=2)
            calendar.pack()
            confirm_button = Button(date_window, text="Select", command=select_date)
            confirm_button.pack(pady=20)

        current_date = datetime.now().strftime("%d-%m-%Y")
        global new_date_entry
        new_date_label = Label(self.add_new_record_frame, text="Date Received", font=("Arial", 30))
        new_date_label.grid(row=5, column=0, padx=10, pady=10)

        date_label = Label(self.add_new_record_frame, text=current_date, font=("Arial", 30))
        # date_label = Label(root, text=current_date)
        date_label.grid(row=5, column=1, padx=10, pady=10)

        select_button = Button(self.add_new_record_frame, text="Select", command=pick_date, font=("Arial", 30))
        select_button.grid(row=5, column=2, padx=10, pady=10)

        worker_options = ["Worker 1", "Worker 2", "Worker 3", "Worker 4"]
        worker_label = Label(self.add_new_record_frame, text='Select Worker', font=("Arial", 30))
        worker_label.grid(row=7, column=0, padx=10, pady=10)

        self.worker_combobox = ttk.Combobox(self.add_new_record_frame, values=worker_options, font=("Arial", 30))
        self.worker_combobox.grid(row=7, column=1, padx=10, pady=10)
        self.worker_combobox.set(worker_options[0])  # Set the default selected worker

        add_button = Button(self.add_new_record_frame, text="Add Record", command=self.add_record_to_database,
                            font=("Arial", 30))
        add_button.bind("<Return>", self.bind_add_record_to_database)
        add_button.grid(row=8, column=1, padx=20, pady=10)
        # add_button.pack()

        cancel_button = Button(self.add_new_record_frame, text="Cancel", command=self.cancel_entry, font=("Arial", 30))
        cancel_button.bind("<Return>", self.bind_cancel_entry)
        cancel_button.grid(row=8, column=2, padx=10, pady=10)

    def remove_one(self):
        """Remove one item from the database"""
        confirmation = messagebox.askyesno("Delete Item", "Delete Item?")
        if confirmation == YES:
            selected_to_delete = self.my_tree.selection()[0]
            self.my_tree.delete(selected_to_delete)
            # Create a database or connect to one that exists
            connection = sqlite3.connect(database)
            # Create a cursor instance
            cursor = connection.cursor()
            # Delete From Database
            with connection:
                cursor.execute("DELETE from returns WHERE oid=" + database_id_entry.get())
            # Clear The Entry Boxes
            self.clear_entry_boxes()
            # Add a little message box for fun
            messagebox.showinfo("Deleted!", "Your Record Has Been Deleted!")
            self.update()

    def search_by_fleet_number(self):
        """Search By Fleet number"""
        lookup_record = search_fleet_entry.get().strip(' ')
        search_fleet_entry.delete(0, END)
        self.clear_entry_boxes()

        # Clear the Treeview
        for record in self.my_tree.get_children():
            self.my_tree.delete(record)
        # Create a database or connect to one that exists
        connection = sqlite3.connect(database)
        # Create a cursor instance
        cursor = connection.cursor()
        with connection:
            cursor.execute("SELECT rowid, * FROM returns WHERE fleet_number like ?", (lookup_record,))
            records = cursor.fetchall()
            # Add our data to the screen
        return records

    def bind_search_by_feet_number(self, event):

        self.update()

    def bind_query_kdm_division(self, event):
        """Bind function to query the database"""
        self.update()

    def update_details(self):
        selected_item = self.my_tree.focus()
        flee_number = info_fleet_number_entry.get().upper().strip()
        description = info_description_entry.get().title().strip()
        date = info_date_added_entry.get()
        oid = database_id_entry.get()

        self.my_tree.item(selected_item, values=(oid, flee_number, description))

        with sqlite3.connect(database) as connection:
            cursor = connection.cursor()
            cursor.execute("""UPDATE returns SET fleet_number = ?,parts_description = ?,in_stock_since = ?
                WHERE oid = ?
            """, (flee_number, description, date, oid))

        self.clear_entry_boxes()
        messagebox.showinfo("Vor Returns Update", "Record Updated.")
        records = query_kdm_division(self.my_tree, database, self.kdm_division)
        populate_division_tree(self.my_tree, records)

    def bind_update_details(self, event):
        self.update_details()

    def frame(self):

        main_frame = Frame(self.window, width=1200, height=700)
        main_frame.pack()
        global search_fleet_entry
        search_fleet_number_label = Label(main_frame, text="Search Fleet Number", font=("Arial", 30))
        search_fleet_number_label.grid(row=0, column=0, padx=10, pady=10)
        search_fleet_entry = Entry(main_frame)
        search_fleet_entry.bind("<Return>", self.bind_search_by_feet_number)
        search_fleet_entry.grid(row=0, column=1, padx=10, pady=10)

        reset_button = Button(main_frame, text="Reset", command=self.reset, font=("Arial", 20))
        reset_button.bind("<Return>", self.bind_query_kdm_division)
        reset_button.grid(row=0, column=4, padx=10, pady=10)

        tree_frame = Frame(self.window)
        tree_frame.pack(pady=5)

        # Create a Treeview Scrollbar
        tree_scroll = Scrollbar(tree_frame)
        tree_scroll.pack(side=RIGHT, fill=Y)
        # Create the treeview
        global my_tree
        self.my_tree = ttk.Treeview(tree_frame, yscrollcommand=tree_scroll.set, selectmode="extended")
        self.my_tree.pack()
        # Configure the Scrollbar
        tree_scroll.config(command=self.my_tree.yview)

        # Add Some Style
        self.style = ttk.Style()
        # Pick A Theme
        self.style.theme_use('default')
        # Configure the Treeview Colors
        self.style.configure("Treeview",
                             background="#D3D3D3",
                             foreground="black",
                             rowheight=30,
                             fieldbackground="#D3D3D3")

        self.style.configure("Treeview.Heading", font=("Arial", 25))  # Set the font size here for the column headings
        # configure the rows in the tree
        self.style.configure("Treeview", font=("Arial", 20))  # Set the font size here
        # Change Selected Color #347083
        self.style.map('Treeview',
                       background=[('selected', self.saved_highlight_color)])

        blue = "blue"
        gray = "lightgray"
        white = "white"

        self.my_tree.tag_configure('oddrow', background=gray)
        self.my_tree.tag_configure('evenrow', background=white)

        visible_items = 15  # Adjust the number of items visible in the treeview
        self.my_tree["height"] = visible_items

        self.my_tree['columns'] = (
            "id", "fleet_number", "parts_description", "in_stock_since", "status", "kdm_division")

        # Format Our Columns
        self.my_tree.column("#0", width=0, stretch=NO)
        self.my_tree.column("id", width=0, stretch=NO)
        self.my_tree.column("fleet_number", anchor=W, width=200)
        self.my_tree.column("parts_description", anchor=W, width=550)
        self.my_tree.column("in_stock_since", anchor=CENTER, width=300)
        self.my_tree.column("status", anchor=CENTER, width=200)
        self.my_tree.column("kdm_division", width=0, stretch=NO)

        # Create Headings
        self.my_tree.heading("#0", text="", anchor=W)
        self.my_tree.heading("id", text="ID", anchor=W)
        self.my_tree.heading("fleet_number", text="Fleet Number", anchor=W)
        self.my_tree.heading("parts_description", text="Parts Description", anchor=W)
        self.my_tree.heading("in_stock_since", text="In Stock Since", anchor=CENTER)
        self.my_tree.heading("status", text="Days In Stock", anchor=CENTER)
        self.my_tree.heading("kdm_division", text="KDM Division", anchor=CENTER)

        self.blue = "blue"
        self.gray = "lightgray"
        self.white = "white"

        # Create Striped Row Tags
        self.my_tree.tag_configure('oddrow', background=self.gray)
        self.my_tree.tag_configure('evenrow', background=self.white)

        first_column_name = "Database ID"
        second_column_name = "Division"
        third_column_name = "Fleet Number"
        fourth_column_name = "Job Number"
        fifth_column_name = "Description"
        sixth_column_name = "Requested By"
        seventh_column_name = "Date Added"

        # Item Info Frame
        information_frame = LabelFrame(self.window, text="Fleet Information", font=("Arial", 30))
        information_frame.pack(fill="x", expand="yes", padx=20)
        # information_frame.grid(row=3, column=0)

        global database_id_entry
        database_id_label = Label(information_frame, text=first_column_name)
        # database_id_label.grid(row=0, column=6, padx=10, pady=10)
        database_id_entry = Entry(information_frame)
        # database_id_entry.grid(row=0, column=7, padx=10, pady=10)

        global division_entry
        division_label = Label(information_frame, text=second_column_name)

        division_entry = Entry(information_frame)

        global info_fleet_number_entry
        fleet_number_label = Label(information_frame, text=third_column_name)
        fleet_number_label.grid(row=0, column=0, padx=10, pady=10)
        info_fleet_number_entry = Entry(information_frame)
        info_fleet_number_entry.grid(row=0, column=1, padx=10, pady=10)

        global info_description_entry
        description_label = Label(information_frame, text=fifth_column_name)
        description_label.grid(row=0, column=2, padx=10, pady=10)
        info_description_entry = Entry(information_frame)
        info_description_entry.grid(row=0, column=3, padx=10, pady=10)

        # clicked = StringVar()
        # clicked.set(options[0])

        global info_date_added_entry
        date_added_label = Label(information_frame, text=seventh_column_name)
        date_added_label.grid(row=0, column=4, padx=10, pady=10)
        info_date_added_entry = Entry(information_frame)
        info_date_added_entry.grid(row=0, column=5, padx=10, pady=10)

        # Item Info Frame
        update_button = Button(information_frame, text="Update Record", command=self.update_details)
        update_button.bind("<Return>", self.bind_update_details)
        update_button.grid(row=0, column=6, padx=10, pady=10)

        # Command Frame
        command_frame = LabelFrame(self.window, text="Commands", font=("Arial", 30))
        command_frame.pack(fill="x", expand="yes", padx=20)

        # Add Buttons
        add_new_button = Button(command_frame, text="Add New Goods Return",
                                command=self.add_new_record_window, font=("Arial", 30))
        add_new_button.bind()
        add_new_button.grid(row=0, column=0, padx=10, pady=10)

        remove_selected_button = Button(command_frame, text="Close Goods Return",
                                        command=self.remove_one, font=("Arial", 30))
        remove_selected_button.bind()
        remove_selected_button.grid(row=0, column=2, padx=10, pady=10)

        clear_entry_button = Button(command_frame, text="Clear Entry Boxes",
                                    command=self.clear_entry_boxes, font=("Arial", 30))
        clear_entry_button.grid(row=0, column=7, padx=10, pady=10)

        generate_report_button = Button(command_frame, text="Print Report",
                                        command=self.create_returns_report, font=("Arial", 30))
        generate_report_button.grid(row=0, column=8, padx=10, pady=10)
        # Bind the treeview
        self.my_tree.bind("<ButtonRelease-1>", self.select_record)
        self.my_tree.bind("<Return>", self.select_record)

        self.update()

if __name__ == "__main__":
    root = Tk()
    global kdm_division
    # kdm_division = "Goods Return"
    kdm_division = "Plant"
    division_image = "images/plant.png"
    # division_image = "images/small.png"
    GoodsReturnClass(root, kdm_division, division_image)
    root.mainloop()


import os

filePath = r"./Illustrious vocal"

def update(filePath):
    # listdir：返回指定的文件夹包含的文件或文件夹的名字的列表
    files = os.listdir(filePath)
    for file in files:
        fileName = filePath + os.sep + file
        path1 = filePath
        # 运用递归;isdir：判断某一路径是否为目录
        if os.path.isdir(fileName):
            update(fileName)
            continue
        else:
            if file.endswith('.mp4'):
                test = file.replace(".mp4", ".wav")
                print("修改前:" + path1 + os.sep + file)
                print("修改后:" + path1 + os.sep + test)
                os.renames(path1 + os.sep + file, path1 + os.sep + test)

if __name__ == '__main__':
    update(filePath)


import time

i_file_results               = []
t_file_results               = []
tournament_name              = ""
tournament_date              = (time.strftime("%m/%d/%Y"))
head_td_name                 = ""
num_players                  = None
num_players_to_date          = None

num_indi_trophy_winners      = 0
num_team_trophy_winners      = 0
indi_trophy_highlight        = []
team_trophy_highlight        = []

player_identification_list   = []

WSCF Results App V2/WSCF_Results_App/MyGlobals.py


import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle

app = Flask(__name__)
model = pickle.load(open('model.pkl', 'rb'))

@app.route('/')
def home():
    return render_template('index.html')

def ValuePredictor(to_predict_list):
    to_predict = np.array(to_predict_list).reshape(1, 13)
    result = model.predict(to_predict)
    return result[0]
@app.route('/predict',methods=['POST'])
def predict():
    '''
    For rendering results on HTML GUI
    '''
    int_features = [float(x) for x in request.form.values()]
    final_features = [np.array(int_features)]
    prediction = model.predict(final_features)

    output = round(prediction[0], 2)
    if int(output)== 1:
            prediction ='High chances of heart disease'
    else:
            prediction ='Chances of heart disease is less'
    return render_template('index.html', prediction_text='{}'.format(prediction))

# @app.route('/result', methods = ['POST'])
# def result():
#     if request.method == 'POST':
#         to_predict_list = request.form.to_dict()
#         to_predict_list = list(to_predict_list.values())
#         to_predict_list = list(map(int, to_predict_list))
#         result = ValuePredictor(to_predict_list)
#         if int(result)== 1:
#             prediction ='Income more than 50K'
#         else:
#             prediction ='Income less that 50K'
#         return render_template("result.html", prediction = prediction)

@app.route('/predict_api',methods=['POST'])
def predict_api():
    '''
    For direct API calls trought request
    '''
    data = request.get_json(force=True)
    prediction = model.predict([np.array(list(data.values()))])

    output = prediction[0]
    return jsonify(output)

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


import pygame

def update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button):
    screen.fill(ai_settings.bg_color)

    # Все пули выводятся позади изображений корабля и пришельцев.
    for bullet in bullets.sprites():
        bullet.draw_bullet()
    ship.blitme()
    aliens.draw(screen)

    # Вывод счета.
    sb.show_score()

    # Кнопка Play отображается в том случае, если игра неактивна.
    if not stats.game_active:
        play_button.draw_button()

    pygame.display.flip()


import os
import datetime as dt
import json

import pandas as pd

from .CA import fetch_production_by_fuel, fetch_production, fetch_price
from .core import CLEAN_DATA_PATH, download_raw_data, download_raw_data_pre2019, cleanup_yearly_data

def main():
    TZ = "America/Toronto"
    now = dt.datetime.utcnow()

    # Get historical output data
    print("Download raw data")
    download_raw_data()
    download_raw_data_pre2019()

    print("Cleanup yearly data")
    cleanup_yearly_data()

    # Get latest data
    production_by_source = fetch_production_by_fuel(target_datetime=now)
    if production_by_source:
        production_by_source[-1]['datetime'] = pd.to_datetime(
            production_by_source[-1]['datetime']
        ).tz_convert(TZ).isoformat()
        with open(os.path.join(CLEAN_DATA_PATH, "latest", "production_by_source.json"), "w") as f:
            f.write(json.dumps(production_by_source[-1], indent=4))

    production_data = fetch_production(target_datetime=now)
    if len(production_data):
        timestamp = production_data["dt"].unique()[-1].tz_convert(TZ)
        production_data = production_data[production_data["dt"] == timestamp]

        plants = {
            "datetime": timestamp.isoformat(),
            "plants": production_data[["name", "fuel"]].set_index("name").to_dict()["fuel"]
        }
        with open(os.path.join(CLEAN_DATA_PATH, "latest", "plants.json"), "w") as f:
            f.write(json.dumps(plants, indent=4))

        production_by_plant = production_data[["name", "production"]].set_index("name").to_dict()["production"]
        output = {
            "datetime": timestamp.isoformat(),
            "production_by_plant": production_by_plant
        }
        with open(os.path.join(CLEAN_DATA_PATH, "latest", "production_by_plant.json"), "w") as f:
            f.write(json.dumps(output, indent=4))

    price = fetch_price(target_datetime=now)
    if price:
        price[-1]['datetime'] = pd.to_datetime(
            price[-1]['datetime']
        ).tz_convert("America/Toronto").isoformat()
        with open(os.path.join(CLEAN_DATA_PATH, "latest", "price.json"), "w") as f:
            f.write(json.dumps(price[-1], indent=4))

if __name__ == "__main__":
    main()


import numpy as np
import h5py
from skimage.transform import rotate
from skimage.draw import circle
from skimage.morphology import disk
from skimage.filters import rank
import os.path
from scipy.ndimage.filters import maximum_filter
from scipy.ndimage.filters import gaussian_laplace
from skimage.feature import peak_local_max

#for show_3D_surface
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt

class ScoreStack:
    #checks if data is available in correct format, initialize class attributes and create stack in correct shape, if readin is True stack is read in else empty
    #LoG: if Laplacian of Gaussian transformation should be performed for blob detection
    #sigma_LoG: sigma for LoG transform
    #substract_mean: if local maxima should be substracted by mean value within circle with radius radius_mean, does not work good
    def __init__(self, img, stack_height, x_center=0, y_center=0,  path_scoremaps='scoremaps/', dataset_name='data', readin=True, transform=True,LoG=False, sigma_LoG=3., substract_mean = False, radius_mean=3.):
        self.img = img #index of scoremap
        self.path_scoremaps = path_scoremaps
        self.dataset_name = dataset_name
        self.path_scoremaps = path_scoremaps
        self.stackname = 'stack_' + str(img) #stack format: stack_1200
        self.stack_height = stack_height
        self.x_center = x_center
        self.y_center = y_center
        self.have_data = False
        #self.stack_shape = (0, 0, self.stack_height)
        self.score_stack = np.array((0, 0, stack_height), dtype=np.float32)
        if readin:
            self.read_in()
        if transform:
            assert(self.have_data)
            self.transform()
        if LoG:
            self.transform_LoG(sigma_LoG)
        if substract_mean:
            self.substract_mean(radius_mean)

    #helper fct for read_in
    def exist_files(self):
        file_exist = True
        for i_rot in np.arange(self.stack_height):
            filepath = self.path_scoremaps+self.create_score_filename(i_rot)
            if os.path.isfile(filepath)==False:
                file_exist = False
                break
        return file_exist

    #helper fct for read_in
    #set stack_shape according to first scoremap shape and checks if shape of all scoremaps belonging to one img have same shape
    def set_check_shape(self):
        for i_rot in np.arange(self.stack_height):
            filepath = self.path_scoremaps + self.create_score_filename(i_rot)
            score_file = h5py.File(filepath, 'r')
            score_shape = score_file[self.dataset_name].shape
            score_file.close()
            if i_rot==0:
                self.score_stack.resize(score_shape[0], score_shape[1], self.stack_height)
            else:
                if not(self.score_stack.shape[0] == score_shape[0] and self.score_stack.shape[1] == score_shape[1]):
                    print('wrong shape: expexted {}, got: {}'.format(self.score_stack.shape[0], score_shape[0]))
                    return False
        return True

    def read_in(self):
        assert self.exist_files()
        shape_consistent = self.set_check_shape()
        assert shape_consistent
        for i_rot in np.arange(self.stack_height):
            filepath = self.path_scoremaps + self.create_score_filename(i_rot)
            score_file = h5py.File(filepath, 'r')
            self.score_stack[:,:,i_rot] = score_file[self.dataset_name][:,:,0]
            score_file.close()
        self.have_data = True

    def write_hdf5(self, data, filepath='', filename='default', dataset_name='data'):
        filepath_name = filepath + filename + '.h5'
        stack_file = h5py.File(filepath_name, 'w')
        stack_file.create_dataset(dataset_name, data=data)
        stack_file.close()

    def write_stack(self):
        assert(self.have_data)
        self.write_hdf5(data=self.score_stack, filename=self.stackname)

    #show surface plot of probmap in selected region and for selected angle/stacknumber i_rot
    def show(self, x_start, y_start, x_end, y_end , i_rot, zlim=(-1,1)):
        assert(self.have_data)
        assert(x_start < x_end)
        assert(y_start < y_end)
        assert(i_rot < self.stack_height)
        region = self.score_stack[y_start:y_end, x_start:x_end , i_rot]
        fig = plt.figure()
        ax = fig.gca(projection='3d')
        X = np.arange(x_end-x_start)
        Y = np.arange(y_end-y_start)
        X, Y = np.meshgrid(X, Y)
        Z = region[Y, X]
        #R = np.sqrt(X**2 + Y**2)
        #Z = np.sin(R)
        surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
        ax.set_zlim(zlim[0], zlim[1])
        ax.zaxis.set_major_locator(LinearLocator(10))
        ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
        fig.colorbar(surf, shrink=0.5, aspect=5)
        plt.show()

    def create_score_filename(self, i_rot): #scoremap filename format: scoremap_1234_4.h5
        return 'scoremap_' + str(self.img) + '_' + str(i_rot) + '.h5'

    #rotate images in correct order
    def transform(self):
        angles = np.linspace(0, 360, self.stack_height, endpoint=False)
        for i_rot, angle in enumerate(angles):
            if i_rot==0:
                pass
            else:
                norm_factor = max(self.score_stack[:,:,i_rot].min(), self.score_stack[:,:,i_rot].max(), key=abs)
                self.score_stack[:,:,i_rot] *= 1/norm_factor
                self.score_stack[:,:,i_rot] = rotate(self.score_stack[:,:,i_rot], 360.-angle, resize = False, center = (self.y_center, self.x_center))
                self.score_stack[:,:,i_rot] *= norm_factor

    #LoG as blob detector
    def transform_LoG(self, sigma):
        for i_rot in np.arange(self.stack_height):
            self.score_stack[:,:,i_rot] = -gaussian_laplace(self.score_stack[:,:,i_rot], sigma)

    #transform score stack by substracting meanvalue within area of a disk
    #does not work properly
    def substract_mean(self, radius_disk):
        circle = disk(radius_disk)
        for i_rot in np.arange(self.stack_height):
            stack_slice = self.score_stack[:,:,i_rot]
            norm_factor = max(stack_slice.min(), stack_slice.max(), key=abs)
            stack_slice *= 1./norm_factor
            stack_slice = np.array(rank.mean(stack_slice, selem=circle), dtype=np.float32)
            stack_slice *= norm_factor
            self.score_stack[:,:,i_rot] = self.score_stack[:,:,i_rot]-stack_slice

    #computes the maxima in all scoremaps
    #radius: radius in px for circle around current px for looking for maxima, for footprint
    #return maxima: list of arrays, for each i_rot one array
    def extract_maxima(self, radius=3, threshold_abs=0.):
        maxima = []

        #xx, yy = circle(radius, radius, radius)
        #footprint = np.zeros((radius*2+1, radius*2+1), dtype=np.bool_)
        #footprint[xx, yy] = 1
        for i_rot in np.arange(self.stack_height):
            #mode='wrap' means periodic boundary conditions
            coord = peak_local_max(self.score_stack[:,:,i_rot], min_distance=radius, threshold_abs=threshold_abs)
            maxima.append(coord)
        return maxima

    #generate hypotheses and represent them as an an array [samples, attributes] x, y, alpha, score
    def extract_hypotheses(self, radius=3, threshold_abs=0):
        maxima = self.extract_maxima(radius=radius, threshold_abs=threshold_abs)
        n_hypotheses = 0
        for i_rot in np.arange(self.stack_height):
            n_hypotheses += len(maxima[i_rot])
        hypos = np.zeros((n_hypotheses, 4), dtype=np.float32)
        i_sample = 0
        #iterate over samples
        for i_rot in np.arange(self.stack_height):
            for i in np.arange(maxima[i_rot].shape[0]):
                coord = maxima[i_rot][i,:]      #coord [x,y]
                maximum_value = self.score_stack[coord[0], coord[1], i_rot]
                hypos[i_sample,0] = coord[0]
                hypos[i_sample,1] = coord[1]
                hypos[i_sample,2] = np.float32(i_rot)*360./np.float32(self.stack_height)
                hypos[i_sample,3] = maximum_value
                i_sample += 1
        return hypos

if __name__ == '__main__':
    #rotational paramater
    x_center = 510/2
    y_center = 514/2
    n_rot = 8

    #read in parameter
    path_scoremaps = '../../Deformabel-Part-Model/ccv/samples/fly/pred/scoremap/'
    start_idx = 2900
    n_scoremaps = 200

    stack_2934 = ScoreStack(2934, n_rot, x_center=x_center, y_center=y_center, path_scoremaps=path_scoremaps, LoG=True, sigma_LoG=1.)
    stack_2934.write_stack()
    x_start = 247
    y_start = 439
    x_end = 276
    y_end = 453
    i_rot = 6
    #hypos = stack_2989.extract_hypotheses(threshold_abs=0.35)
    #print hypos[10,:]
    #for i in np.arange(stack_2942.stack_height)
    #    print len(maxima[i])
    stack_2934.show(x_start, y_start, x_end, y_end , i_rot, zlim=(-1.,1.1))
    #stack_2942.write_stack()


from EVMS import app, db
from organisations.form import OrganisationForm
from organisations.models import Organisation
from flask import render_template, redirect, url_for, request, session

'''
This code controls the creation, editing, viewing and deleting of organisations
'''

@app.route('/neworganisation', methods=['POST', 'GET'])
def add_organisation():
    form = OrganisationForm()

    if request.method == "POST" and form.validate():
        organisation = Organisation (code= form.code.data,
                            name= form.name.data,
                            description= form.description.data,
                            #admin = form.admin.data,
                            is_active= form.is_active.data)
        db.session.add(organisation)
        db.session.commit()
        return redirect(url_for('view_organisations'))

    return render_template('organisations/organisationform.html', form=form, action='new')

@app.route('/vieworganisations')
def view_organisations():
    organisations = Organisation.query.filter_by(is_active=True).all()
    return render_template('organisations/view.html', organisations=organisations)

@app.route('/editorganisation/<id>', methods=['GET', 'POST'])
def edit_organisation(id):
    organisation = Organisation.query.filter_by(id= id).first()
    form = OrganisationForm(obj= organisation)

    if request.method == "POST" and form.validate():
        organisation.code = form.code.data
        organisation.is_active = form.is_active.data
        organisation.name = form.name.data
        organisation.description = form.description.data
        #organisation.admin = form.admin.data

        db.session.add(organisation)
        db.session.flush()
        db.session.commit()
        return redirect(url_for('view_organisations'))
    return render_template('organisations/organisationform.html', form = form, organisation=organisation, action='edit')

@app.route('/deleteorganisation/<id>')
def delete_organisations(id):
    organisation = Organisation.query.filter_by(id= id).first()
    organisation.is_active = False

    db.session.add(organisation)
    db.session.commit()
    return redirect(url_for('view_organisations'))


from abc import ABC, abstractmethod
from collections import UserDict
import csv
from datetime import date, datetime
import re
import os

class AbstractField(ABC):

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

    def __eq__(self, other):
        return self.value == other.value

    def __str__(self):
        return self.value

    def __repr__(self):
        return self.value

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, value):
        self.assert_valid_value(value)
        self._value = value

    @abstractmethod
    def assert_valid_value(self, value):
        pass

class Name(AbstractField):

    def assert_valid_value(self, value):
        if not value.isalpha():
            raise Exception("Please enter correct name")

class Phone(AbstractField):
    def assert_valid_value(self, value):
        if not value.isnumeric():
            raise Exception("Please enter correct phone number")

class Birthday(AbstractField):

    @classmethod
    def fromisoformat(cls, value):
        if not datetime.strptime(value, "%Y-%m-%d"):
            raise Exception("Please enter date number as 'YYYY-MM-DD'")
        return cls(date.fromisoformat(value))

    def assert_valid_value(self, value):
        if not isinstance(value, date):
            raise Exception("Please enter number as 'YYYY-MM-DD'")

    def days_diff(self, date):

        delta1 = datetime(date.year, self.value.month, self.value.day)
        delta2 = datetime(date.year + 1, self.value.month, self.value.day)
        if delta1 > date:
            return (delta1 - date).days
        else:
            return (delta2 - date).days

    def __str__(self):
        return self.value.strftime("%Y-%m-%d")

class Email(AbstractField):
    def assert_valid_value(self, value):
        if not re.search(r"[a-zA-Z]\w*[.]?\w*[.]?\w*'@'\w+[.]\w{2}\w*", self.value):
            raise Exception("Please enter correct email")

class Address(AbstractField):
    def assert_valid_value(self, value):
        if len(self.value) >= 256:
            raise Exception("Please enter your address not so large")

class Record:
    def __init__(self, name: Name, phone: Phone = None, birthday: Birthday = None, email: Email = None, address: Address = None):
        self.name = name
        self.phones = [phone] if phone else []
        self.birthday = birthday
        self.email = email
        self.address = address

    def add_phone(self, add_phone: Phone):
        self.phones.append(add_phone)

    def remove_phone(self, removable_phone: Phone):
        self.phones = [n for n in self.phones if n != removable_phone]

    def change_phone(self, changeable_phone: Phone, new_phone: Phone):

        for i, n in enumerate(self.phones):
            if n == changeable_phone:
                self.phones[i] = new_phone
        return self.phones

    def add_phones(self, phones: list[Phone]):
        self.phones += phones
        return self

    def __str__(self):
        return self.name.value + repr(self.phones) + repr(self.birthday) + repr(self.email) + repr(self.address)

    def __repr__(self):
        return str(self)

class AddressBook(UserDict[str, Record]):
    def __init__(self, filename: str):
        super().__init__()
        self.filename = filename
        self.load_from_csv()

    def add_record(self, record: Record) -> None:
        self.data[record.name.value] = record

    def change_record(self, record: Record) -> object:
        if record.name.value in self.data:
            self.data[record.name.value] = record
        else:
            raise Exception(f"This name {record.name.value} is not found. Please input correct name")

    def iterator(self, page_size: int) -> list[Record]:
        page = [None] * page_size
        idx = 0
        for record in self.data.values():
            page[idx] = record
            idx += 1
            if idx == page_size:
                yield page
                idx = 0
        yield page[:idx]

    def search(self, term: str):
        for record in self.data.values():
            if term in record.name.value:
                yield record
            else:
                for phone in record.phones:
                    if term in str(phone):
                        yield record
                        break

    def write_to_csv(self,):
        with open(self.filename, 'w', encoding='UTF8', newline='') as file:
            fieldnames = ["Name", "Phones", "Birthday", "Email", "Address"]
            writer = csv.DictWriter(
                file, fieldnames=fieldnames)
            writer.writeheader()
            for record in self.data.values():
                writer.writerow({
                    "Name": record.name,
                    "Phones": record.phones,
                    "Birthday": record.birthday,
                    "Email": record.email,
                    "Address": record.address
                })

    def load_from_csv(self):
        if not os.path.exists(self.filename):
            return

        with open(self.filename, newline='') as fh:
            reader = csv.DictReader(fh)
            for row in reader:
                name = row["Name"]
                birthday = row["Birthday"]
                email = row["Email"]
                address = row["Address"]
                phones = [Phone(p) for p in row["Phones"][1:-1].split(", ")]
                self.data[name] = Record(
                    Name(name),
                    None,
                    Birthday.fromisoformat(birthday) if birthday else None,
                    Email(email) if email else None,
                    Address(address) if address else None
                ).add_phones(phones)


# from django.shortcuts import render
# from django.db.models import Prefetch
# # Create your views here.
# from rest_framework import viewsets
# from .models import Stock, Borrow
# from .serializers import StockSerializer, BorrowSerializer

# class StockViewSet(viewsets.ModelViewSet):
#     serializer_class = StockSerializer
#     queryset = Stock.objects.all()

# class BorrowViewSet(viewsets.ModelViewSet):
#     serializer_class = BorrowSerializer
#     queryset = Borrow.objects.all()
from datetime import date
from django.shortcuts import render
from django.db import transaction
from django.http.response import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework import status
from .models import Stock, Borrow
from .serializers import StockSerializer, BorrowSerializer
from rest_framework.decorators import api_view
from django.http import HttpResponse

@api_view(['GET', 'POST', 'UPDATE'])
def stock_list(request):
    if request.method == 'GET':
        stocks = Stock.objects.all()
        stocks_serializer = StockSerializer(stocks, many=True)
        return JsonResponse(stocks_serializer.data, safe=False)
        # 'safe=False' for objects serialization

    elif request.method == 'POST':
        stock_data = JSONParser().parse(request)
        stock_serializer = StockSerializer(data=stock_data)
        if stock_serializer.is_valid():
            stock_serializer.save()
            return JsonResponse(stock_serializer.data, status=status.HTTP_201_CREATED)
        return JsonResponse(stock_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', 'POST'])
def borrow_list(request):
    if request.method == 'GET':
        borrows = Borrow.objects.all()
        borrows_serializer = BorrowSerializer(borrows, many=True)
        return JsonResponse(borrows_serializer.data, safe=False)

    elif request.method == 'POST':

        borrow_data = JSONParser().parse(request)
        borrow_serializer = BorrowSerializer(data=borrow_data)

        stocks = Stock.objects.get(itemName = borrow_data["itemName"])

        if(stocks.quantity >= borrow_data["quantity"]):
            stocks.quantity = stocks.quantity - borrow_data["quantity"]
        else:
            return JsonResponse(borrow_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        if borrow_serializer.is_valid():
            borrow_serializer.save()
            stocks.save()
            return JsonResponse(borrow_serializer.data, status=status.HTTP_201_CREATED)
        return JsonResponse(borrow_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['POST'])
def return_list(request):
    if request.method == 'POST':

        return_data = JSONParser().parse(request)

        borrows = Borrow.objects.get(id = return_data["id"])
        borrows.returnedDate=date.today()
        borrows.status="Returned"
        borrows.save()

        stocks = Stock.objects.get(itemName = return_data["itemName"])
        stocks.quantity = stocks.quantity + return_data["quantity"]
        stocks.save()

        return HttpResponse("Test")


from socket import socket, AF_INET, SOCK_STREAM
from urllib import request
from urllib.error import HTTPError, URLError
import re

class Popup:
    def __init__(self):
        self.sock = socket(AF_INET, SOCK_STREAM)
        self.phrase = self.make_phrase()

    def get_external_ip(self):
        """
        Get external IP by parsing get-ip.me
        """
        try:
            site = request.urlopen("http://www.get-ip.me")
            site = site.read().decode('utf-8')
            ip_regex = re.compile(r'([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)')
            grab = re.findall(ip_regex, site)
            address = grab[0]
            return address
        except (OSError, HTTPError, URLError) as e:
            return "We can't get your ext. IP ({})".format(e)

    def get_internal_ip(self):
        """
        Get internal IP (local network IP)
        """
        try:
            self.sock.connect(('google.com', 80))
            return self.sock.getsockname()[0]
        except (OSError, HTTPError, URLError) as e:
            return "We can't get your int. IP ({})".format(e)

    def make_phrase(self):
        """
        Concat two IPs into one phrase
        """
        return "Local IP: {}\nGlobal IP: {}".format(self.get_internal_ip(),
                                                    self.get_external_ip())


from Experiments import RuneDBN
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib as mpl
import random
from sklearn.preprocessing import normalize
from sklearn.preprocessing import scale

s, pvals = RuneDBN.run()

# s = {
#     '1': [1, 2, 3, 4, 5, 6, 7, 8, 9],
#     '2': [200, 4,22, 43, 3e-9, 23, 5],
#     '3': [12, 43, 11, 33, 89, 4, 5, 8]
# }

cnt = 0

all_colors = 2 * np.pi * np.random.rand(7)

tt = ['r', 'b', 'g', 'y']

def plot_all(ax):
    cnt = 0
    for trace in s:

        if cnt > 200:
            break

        scores, time = zip(*s[trace])
        trace_np = np.array(scores)
        time_np = np.array(time)

        time_np = np.interp(time_np, (0, 9999), (0, +1))

        # mean = np.mean(trace_np)
        std = np.std(trace_np)

        index_bad = np.where(trace_np < std / 4)
        index_good = np.where(trace_np > std / 4)

        topK_bad = trace_np[index_bad]
        topK_good = trace_np[index_good]

        time_bad = time_np[index_bad]
        time_good = time_np[index_good]

        r_good = (1 / np.sqrt(topK_good)) * topK_good
        theta_good = 2 * np.pi * time_good
        area_good = 5 * (1 / r_good) * r_good

        r_bad = (1 / np.sqrt(topK_bad)) * topK_bad
        theta_bad = 20 * np.pi * time_bad
        area_bad = 1 * (1 / r_bad) * r_bad

        r_good_mean = np.mean(r_good)
        r_bad_mean = np.mean(r_bad)
        theta_good_mean = np.mean(theta_good)
        theta_bad_mean = np.mean(theta_bad)

        ax.scatter(theta_bad_mean, r_bad_mean, c='r', s=area_bad, alpha=1, zorder=2)
        ax.scatter(theta_good_mean, r_good_mean, c='b', s=area_good, alpha=0.55, zorder=3)

        ax.set_yticklabels([])
        cnt+=1

def plot(which, ax):
    scores, time = zip(*s[which])
    trace_np = np.array(scores)
    time_np = np.array(time)

    # time_np = scale(time_np, axis=0, with_mean=True, with_std=True, copy=True)
    time_np = np.interp(time_np, (time_np.min(), time_np.max()), (0, +1))

    # mean = np.mean(trace_np)
    std = np.std(trace_np)

    index_bad = np.where(trace_np < std/4)
    index_good = np.where(trace_np > std/4)

    topK_bad = trace_np[index_bad]
    topK_good = trace_np[index_good]

    time_bad = time_np[index_bad]
    time_good = time_np[index_good]

    r_good = trace_np# topK_good # (1/np.sqrt(topK_good)) * topK_good
    theta_good = 2 * np.pi *  time_np#time_good
    area_good = 5 * (1 / r_good) * r_good

    r_bad = trace_np# topK_bad # (1/np.sqrt(topK_bad)) * topK_bad
    theta_bad = 2 * np.pi * time_np# time_bad
    area_bad = 5 * (1/r_bad) * r_bad

    print("r_good:", r_good)
    print("time_good:", time_good)
    print("theta_good:", theta_good)

    print("-"*50)

    max_lim = np.max(r_good)
    min_lim = np.min(r_good)

    # ax.plot(theta_good[0], r_good[0], c='g', s=50, alpha=1, zorder=2)
    # ax.plot(theta_bad, r_bad, c='r', s=area_bad, alpha=1, zorder=2)
    # ax.plot(theta_good, r_good, c='b', s=area_good, alpha=0.55, zorder=3)

    ax.scatter(theta_good[0], r_good[0], c='g', s=50, alpha=1, zorder=2)
    ax.plot(theta_bad, r_bad, '-o', c='b', linewidth=0.7, markersize=0.9)

    # ax.plot(theta_good, r_good, '-o', c='b', linewidth=0.5, markersize=0.9)
    ax.grid(color='#dddddd', zorder=0)

    ax.set_rlim(0, max_lim + min_lim)
    ax.set_yticklabels([])

def plot_ps(pvs, ax):
    bins = 10
    vals = np.array(pvs[1])

    ws = int(np.floor(len(vals)/bins))
    # print("ws", ws)
    # print([(x+1)*ws for x in range(bins)] + [len(vals)-rem])
    data_bins = np.split(vals, [(x+1)*ws for x in range(bins)])
    bin_height = []

    # print(len(data_bins))

    for b in data_bins:
        mean_b = np.mean(b)
        bin_height.append(mean_b)

    # print(bin_height)
    # exit()

    # top = vals[np.where(vals > -1 * std/40)]
    N = len(bin_height)
    print(np.array(bin_height))
    plot_data = np.array(bin_height) - np.min(bin_height)
    print(plot_data)
    # exit()
    # print(plot_data)
    theta = np.arange(0.0, 2 * np.pi, 2*np.pi/N)
    radii = np.array(plot_data)
    width = np.pi/bins
    bars = ax.bar(theta, radii, width=width)

    for r, bar in zip(radii, bars):
        bar.set_facecolor(cm.jet(r))
        bar.set_alpha(0.5)

keyset = list(s.keys())

rand1 = keyset[random.randint(0, len(s)-1)]
rand2 = keyset[random.randint(0, len(s)-1)]
rand3 = keyset[random.randint(0, len(s)-1)]

fig = plt.figure()
# all data
ax1 = fig.add_subplot(221, projection='polar')
plot_all(ax1)

# plot p-values
ax2 = fig.add_subplot(222, projection='polar')
plot_ps(pvals, ax2)

# plot random trace
ax3 = fig.add_subplot(223, projection='polar')
plot(rand1, ax3)

# plot another random trace
ax4 = fig.add_subplot(224, projection='polar')
plot(rand2, ax4)

#
# for trace in s:
#     # print(trace, tt[cnt%len(tt)])
#
#     # if cnt > 2:
#     #     break
#
#     trace_np = np.array(s[trace])
#     # r = np.random.randint(0, len(trace_np))
#     # trace_np[r] = 20
#     # trace_np[r] = np.random.uniform(0, 5e-39)
#
#     # trace_np.sort(kind='mergesort')
#
#     mean = np.mean(trace_np)
#     std = np.std(trace_np)
#
#     # print(std)
#
#     topK_bad = trace_np[np.where(trace_np < std/4)]
#     topK_good = trace_np[np.where(trace_np > std/4)]
#
#     # print(len(topK_good))
#     # print(len(topK_bad))
#
#     r_good = (1/np.sqrt(topK_good)) * topK_good
#     theta_good = 80 * np.pi * r_good
#     area_good = 5 * (1 / r_good) * r_good
#     # area_good = 50 * r_good
#
#
#
#     r_bad = (1/np.sqrt(topK_bad)) * topK_bad
#     theta_bad = 80 * np.pi * r_bad
#     area_bad = 5 * (1/r_bad) * r_bad
#     # area_bad = 50 * r_bad
#
#     ax.scatter(theta_bad, r_bad, c='r', s=area_bad, alpha=1, zorder=2)
#
#     ax.scatter(theta_good, r_good, c='b', s=area_good, alpha=0.55, zorder=3)
#     cnt += 1

# ax.set_title("A line plot on a polar axis", va='bottom')
plt.show()


def solve(k, n, lst):
    global minV, result

    if minV <= k:
        return

    if n == 1:
        if minV > k:
            minV = k
            result = lst[:]
        return

    if n % 3 == 0:
        solve(k+1, n//3, lst+[n//3])
    if n % 2 == 0:
        solve(k+1, n//2, lst+[n//2])
    solve(k+1, n-1, lst+[n-1])

n = int(input())
minV = 10000000
result = []
solve(0, n, [n])
print(minV)
print(*result)


#
# @lc app=leetcode.cn id=84 lang=python3
#
# [84] 柱状图中最大的矩形
#
# https://leetcode-cn.com/problems/largest-rectangle-in-histogram/description/
#
# algorithms
# Hard (44.13%)
# Likes:    1908
# Dislikes: 0
# Total Accepted:    244.6K
# Total Submissions: 554.3K
# Testcase Example:  '[2,1,5,6,2,3]'
#
# 给定 n 个非负整数，用来表示柱状图中各个柱子的高度。每个柱子彼此相邻，且宽度为 1 。
#
# 求在该柱状图中，能够勾勒出来的矩形的最大面积。
#
#
#
# 示例 1:
#
#
#
#
# 输入：heights = [2,1,5,6,2,3]
# 输出：10
# 解释：最大的矩形为图中红色区域，面积为 10
#
#
# 示例 2：
#
#
#
#
# 输入： heights = [2,4]
# 输出： 4
#
#
#
# 提示：
#
#
# 1
# 0
#
#
#

# @lc code=start
class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:
        ##2.单调栈 优化 线性时间
        n = len(heights)
        left, right = [0] * n, [0] * n

        mnstack = []
        for i in range(n):
            while mnstack and heights[i] <= heights[mnstack[-1]]:
                right[mnstack[-1]] = i
                mnstack.pop()

            left[i] = mnstack[-1] if mnstack else -1
            mnstack.append(i)

        ans = max((right[i] - left[i] - 1) * heights[i]
                  for i in range(n)) if n > 0 else 0

        return ans

# @lc code=end

# def largestRectangleArea(self, heights: List[int]) -> int:
#     ##1.暴力解法 以当前柱子高度为基准，向两边扩，找到高度比它低的

#     n = len(heights)
#     res= -float('inf')
#     for i in range(n):
#         left,right = i,i
#         curheights = heights[i]
#         while left > 0 and curheights <= heights[left-1]:
#             left -= 1

#         while right < n - 1 and curheights<=heights[right+1]:
#             right += 1

#         res = max(res, (right-left+1)*curheights)

#     return res
# def largestRectangleArea(self, heights: List[int]) -> int:
#     ##2.
#     n = len(heights)
#     res = 0

#     stack = []

#     for i in range(n):
#         while stack and heights[i] < heights[stack[-1]]:
#             curheight = heights[stack.pop()]

#             while stack and curheight == heights[stack[-1]]:
#                 stack.pop()

#             if stack:
#                 curwidth = i - stack[-1] - 1
#             else:
#                 curwidth = i

#             res = max(res, curheight * curwidth)
#         stack.append(i)

#     while stack:

#         curheight = heights[stack.pop()]

#         while stack and curheight == heights[stack[-1]]:
#             stack.pop()

#         if len(stack) > 0:
#             curwidth = n - stack[-1] - 1
#         else:
#             curwidth = n
#         res = max(res, curheight * curwidth)
#     return res

# def largestRectangleArea(self, heights: List[int]) -> int:
#     ##2.单调栈
#     n = len(heights)
#     left, right = [0] * n, [0] * n

#     mnstack = []
#     for i in range(n):
#         while mnstack and heights[i] <= heights[mnstack[-1]]:
#             mnstack.pop()

#         left[i] = mnstack[-1] if mnstack else -1
#         mnstack.append(i)

#     mnstack = []

#     for i in range(n - 1, -1, -1):
#         while mnstack and heights[mnstack[-1]] >= heights[i]:
#             mnstack.pop()
#         right[i] = mnstack[-1] if mnstack else n
#         mnstack.append(i)

#     ans = max((right[i] - left[i] - 1) * heights[i]
#               for i in range(n)) if n > 0 else 0

#     return ans

84.柱状图中最大的矩形.py


import time
import logging
import traceback

from compose.cli import command
from compose.config.errors import ConfigurationError

import logger

from cStringIO import StringIO
import sys

class Capturing(list):
    def __enter__(self):
        self._stdout = sys.stdout
        self._stderr = sys.stderr
        sys.stdout = sys.stderr = self._out = StringIO()
        return self

    def __exit__(self, *args):
        self.extend(self._out.getvalue().splitlines())
        del self._out
        sys.stdout = self._stdout
        sys.stderr = self._stderr

class Monitor(object):
    def __init__(self, path, options,
                 norecreate, nodeps, running, filelog=None):
        global log

        if "log" not in globals():
            if filelog is not None:
                log = logging.getLogger(__name__)
                log.addHandler(logger.FileHandler(filelog))
                log.setLevel(logging.DEBUG)
            else:
                log = logging.getLogger(__name__)
                log.addHandler(logger.StreamHandler())
                log.setLevel(logging.DEBUG)

        self.path = path
        self.options = options
        self.norecreate = norecreate
        self.nodeps = nodeps
        self.running = running
        try:
            self.project = command.project_from_options(self.path,
                                                        self.options)
        except ConfigurationError:
            log.error("Can't create a monitor unit\n{}".
                format(traceback.format_exc()))
            raise SystemExit

    def _pullup(self):
        try:
            self.project.pull()
            log.info("Images pulled successfully")
        except Exception:
            log.error("Can't pull images")
            raise

        if self.norecreate:
            return

        if self.running:
            services = self._fully_running_services()
        else:
            services = self.project.services

        if self.nodeps:
            for service in services:
                try:
                    service.execute_convergence_plan(service.convergence_plan())
                    log.info("Service \"{}\" updated successfully".format(service.name))
                except Exception:
                    log.error("Can't update service \"{}\"".format(service.name))
                    raise
        else:
            try:
                self.project.up([el.name for el in services], detached=True)
                log.info("Project updated successfully")
            except Exception:
                log.error("Can't update project")
                raise

    def _fully_running_services(self):
        fully_running = []

        for service in self.project.get_services():
            if all(container.is_running for container in service.containers(stopped=True)):
                fully_running.append(service)
            else:
                log.warning("Some containers for service \"{}\" are down". \
                    format(service.name))

        return fully_running

    def run(self, timeout, scheduler):
        self.project.up(detached=True)
        log.info("Monitor started successfully")
        while True:
            try:
                with Capturing() as output:
                    self._pullup()
            except Exception:
                log.error("Service checking failed\n{}".
                    format(traceback.format_exc()))
            if scheduler:
                break

            log.info("Checked successfully\n{}".format(output))
            time.sleep(timeout)


from selenium import webdriver
import time

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome(executable_path="../drivers/chromedriver.exe")
driver.maximize_window()
driver.get("https://rahulshettyacademy.com/seleniumPractise/#/")
driver.find_element_by_css_selector("input.search-keyword").send_keys("ber")
time.sleep(2)
total_item = driver.find_elements_by_xpath("//div[@class='products']/div")
assert len(total_item) == 3

filtered_item = driver.find_elements_by_css_selector("div.product-action")
for item in filtered_item:
    item.click()

driver.find_element_by_css_selector("img[alt='Cart']").click()
driver.find_element_by_xpath("//button[text()='PROCEED TO CHECKOUT']").click()
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".promoCode")))
driver.find_element_by_css_selector(".promoCode").send_keys("rahulshettyacademy")
driver.find_element_by_css_selector(".promoBtn").click()

wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, ".promoInfo")))
promo_info_ele = driver.find_element_by_css_selector(".promoInfo")
promo_info = promo_info_ele.text
assert "Code applied" in promo_info
# print(promo_info)
driver.close()


from __future__ import print_function, unicode_literals

import os
import signal
import sys
try:
    from queue import Queue, Empty
except ImportError:
    from Queue import Queue, Empty
from subprocess import Popen, PIPE
from threading import Thread
from time import sleep

def _reader(stream, io_queue):
    for line in iter(stream.readline, ''):
        if line.endswith('\n'):
            line = line[:-1]
        io_queue.put(line)
    if not stream.closed:
        stream.close()

def _output_generator(io_queue, checker_thread):
    while True:
        try:
            yield io_queue.get_nowait()
        except Empty:
            if not checker_thread.is_alive():
                break
            sleep(0.3)

def _printer(io_queue, checker_thread, postprocessor):
    generator = _output_generator(io_queue, checker_thread)
    if postprocessor:
        generator = postprocessor(generator)
    for line in generator:
        print(line)

def _checker(process):
    while True:
        if process.poll() is not None:
            break
        sleep(0.5)

def run(args, cwd=None, postprocessor=None):
    io_queue = Queue()

    # Set environment, disabling Python buffering of the subprocess
    env = os.environ.copy()
    env['PYTHONUNBUFFERED'] = 'True'

    # Set platform-specific arguments
    kwargs = {}
    if sys.platform == 'win32':
        from subprocess import CREATE_NEW_PROCESS_GROUP
        # Use a new process group
        kwargs['creationflags'] = CREATE_NEW_PROCESS_GROUP
        # Prevent "Terminate batch job (Y/N)?"
        kwargs['stdin'] = open(os.devnull, 'r')

    # Run process
    process = Popen(
        args, env=env, shell=True, stdout=PIPE, stderr=PIPE, **kwargs)

    # Create and start all listening threads
    stdout_thread = Thread(target=_reader, args=[process.stdout, io_queue])
    stdin_thread = Thread(target=_reader, args=[process.stderr, io_queue])
    checker_thread = Thread(target=_checker, args=[process])
    printer_thread = Thread(target=_printer,
                            args=[io_queue, checker_thread, postprocessor])
    stdout_thread.start()
    stdin_thread.start()
    checker_thread.start()
    printer_thread.start()

    # Wait for keyboard interrupt
    while checker_thread.is_alive():
        try:
            sleep(0.5)
        except KeyboardInterrupt:
            break

    # Gracefully terminate and show output from cleanup
    term_signal = (
        signal.CTRL_BREAK_EVENT if sys.platform == 'win32' else signal.SIGTERM)
    while True:
        try:
            process.send_signal(term_signal)
            printer_thread.join()
            break
        except KeyboardInterrupt:
            continue


import os
import json
from binascii import hexlify, unhexlify
from typing import List
from enum import Enum
from grin.keychain import Keychain, Identifier, ChildKey, KeychainPath
from grin.util import absolute
from grin.transaction import Input, Output, OutputFeatures
from secp256k1.pedersen import Secp256k1, Commitment

class OutputStatus(Enum):
    Unconfirmed = 1,
    Unspent = 2,
    Locked = 3,
    Spent = 4

class OutputEntry:
    def __init__(self, root_key_id: Identifier, key_id: Identifier, n_child: int, value: int, status: OutputStatus,
                 height: int, lock_height: int, is_coinbase: bool):
        self.root_key_id = root_key_id
        self.key_id = key_id
        self.n_child = n_child
        self.value = value
        self.status = status
        self.height = height
        self.lock_height = lock_height
        self.is_coinbase = is_coinbase

    def __repr__(self):
        return "OutputEntry<n={}, value={}, status={}>".format(self.n_child, self.value, self.status.name)

    def to_dict(self) -> dict:
        return {
            "root_key_id": self.root_key_id.to_hex().decode(),
            "key_id": self.key_id.to_hex().decode(),
            "n_child": self.n_child,
            "value": self.value,
            "status": self.status.name,
            "height": self.height,
            "lock_height": self.lock_height,
            "is_coinbase": self.is_coinbase
        }

    def update_from_dict(self, dct: dict):
        self.value = dct['value']
        self.status = OutputStatus[dct['status']]
        self.height = dct['height']
        self.lock_height = dct['lock_height']
        self.is_coinbase = dct['is_coinbase']

    def mark_locked(self):
        self.status = OutputStatus.Locked

    def mark_unspent(self):
        if self.status in (OutputStatus.Unconfirmed, OutputStatus.Locked):
            self.status = OutputStatus.Unspent

    def mark_spent(self):
        if self.status in (OutputStatus.Unspent, OutputStatus.Locked):
            self.status = OutputStatus.Spent

    @staticmethod
    def from_dict(dct: dict):
        root_key_id = Identifier.from_hex(dct['root_key_id'].encode())
        key_id = Identifier.from_hex(dct['key_id'].encode())
        status = OutputStatus[dct['status']]
        return OutputEntry(root_key_id, key_id, dct['n_child'], dct['value'], status, dct['height'],
                           dct['lock_height'], dct['is_coinbase'])

    @staticmethod
    def from_child_key(child_key: ChildKey, value: int, is_coinbase: bool):
        return OutputEntry(child_key.root_key_id, child_key.key_id, child_key.n_child, value,
                           OutputStatus.Unconfirmed, 0, 0, is_coinbase)

class WalletDetails:
    def __init__(self, location: str):
        self.location = location
        self.last_confirmed_height = 0
        self.last_child_index = 0
        if not os.path.exists(location):
            self.save()
        else:
            self.load()

    def to_dict(self) -> dict:
        return {
            "last_confirmed_height": self.last_confirmed_height,
            "last_child_index": self.last_child_index
        }

    def load(self):
        f = open(self.location, "r")
        dct = json.loads(f.read())
        f.close()
        self.last_confirmed_height = dct['last_confirmed_height']
        self.last_child_index = dct['last_child_index']

    def save(self):
        f = open(self.location, "w")
        f.write(json.dumps(self.to_dict(), indent=2))
        f.close()

    def next(self) -> int:
        self.last_child_index += 1
        return self.last_child_index

class NotEnoughFundsException(Exception):
    pass

# File wallet
# TODO: locking, output selection strategies
class Wallet:
    def __init__(self, secp: Secp256k1, location: str, seed: bytes):
        self.dir_in = location
        self.dir = absolute(location)
        assert os.path.isdir(self.dir)
        self.chain = Keychain.from_seed(secp, seed)
        self.details = WalletDetails(absolute(self.dir, "wallet.det"))
        self.cache = {}
        self.outputs = {}
        if not os.path.exists(absolute(self.dir, "wallet.dat")):
            self.save()
        else:
            self.load()

    def load(self):
        self.details.load()
        f = open(absolute(self.dir, "wallet.dat"), "r")
        entries = json.loads(f.read())
        f.close()
        outputs = {}
        for entry in entries:
            key_id = entry['key_id']
            if key_id in self.outputs:
                output = self.outputs[key_id]
                output.update_from_dict(entry)
                outputs[key_id] = output
            outputs[key_id] = OutputEntry.from_dict(entry)
        self.outputs = outputs

    def save(self):
        self.details.save()
        lst = [y.to_dict() for x, y in self.outputs.items()]
        lst = sorted(lst, key=lambda x: x['n_child'])
        f = open(absolute(self.dir, "wallet.dat"), "w")
        f.write(json.dumps(lst, indent=2))
        f.close()

    def get_output(self, key: str) -> OutputEntry:
        return self.outputs[key] if key in self.outputs else None

    def get_output_by_n(self, n: int) -> OutputEntry:
        return self.get_output(self.chain.derive(n).key_id.to_hex().decode())

    def select_outputs(self, amount: int) -> List[OutputEntry]:
        total_amount = 0
        outputs = []
        for n, output in self.outputs.items():
            if output.status != OutputStatus.Unspent:
                continue
            total_amount += output.value
            outputs.append(output)
            if total_amount > amount:
                break
        if total_amount <= amount:
            raise NotEnoughFundsException()
        return outputs

    def create_output(self, value: int, is_coinbase=False) -> (ChildKey, OutputEntry):
        assert isinstance(is_coinbase, bool)
        # TODO: lock
        i = self.details.next()
        key_id = self.chain.derive_key_id(3, 0, 0, i, 0)  # TODO: manage accounts etc
        key_id_hex = key_id.to_hex().decode()
        ext_key = self.chain.derive_key(key_id)
        child_key = ChildKey(i, key_id.parent_path(), key_id, ext_key)
        self.cache[key_id_hex] = child_key
        entry = OutputEntry.from_child_key(child_key, value, is_coinbase)
        self.outputs[key_id_hex] = entry
        # self.save()
        return child_key, entry

    def derive_from_entry(self, entry: OutputEntry) -> ChildKey:
        key_id = entry.key_id.to_hex().decode()
        if key_id not in self.cache:
            ext_key = self.chain.derive_key(entry.key_id)
            self.cache[key_id] = ChildKey(entry.n_child, entry.root_key_id, entry.key_id, ext_key)
        return self.cache[key_id]

    def commit_with_child_key(self, value: int, child_key: ChildKey) -> Commitment:
        return self.chain.commit(value, child_key)

    def commit(self, entry: OutputEntry) -> Commitment:
        return self.commit_with_child_key(entry.value, self.derive_from_entry(entry))

    def entry_to_input(self, entry: OutputEntry) -> Input:
        commitment = self.commit(entry)
        return Input(
            OutputFeatures.COINBASE_OUTPUT if entry.is_coinbase else OutputFeatures.DEFAULT_OUTPUT,
            commitment
        )

    def entry_to_output(self, entry: OutputEntry) -> Output:
        return Output.create(
            self.chain,
            OutputFeatures.COINBASE_OUTPUT if entry.is_coinbase else OutputFeatures.DEFAULT_OUTPUT,
            self.derive_from_entry(entry),
            entry.value
        )

    @staticmethod
    def open(secp: Secp256k1, location: str):
        abs_dir = absolute(location)
        assert os.path.isdir(abs_dir)
        seed_file = absolute(abs_dir, "wallet.seed")
        assert os.path.exists(seed_file)
        f = open(seed_file, "r")
        wallet = Wallet(secp, location, unhexlify(f.readline().encode()))
        wallet.load()
        return wallet

    @staticmethod
    def create(secp: Secp256k1, location: str, seed: bytes):
        assert len(seed) == 32, "Invalid seed length"
        abs_dir = absolute(location)
        if not os.path.exists(abs_dir):
            os.makedirs(abs_dir)
        else:
            assert os.path.isdir(abs_dir), "Wallet location not a directory"
        seed_file = absolute(abs_dir, "wallet.seed")
        assert not os.path.exists(seed_file), "Wallet already exists"
        f = open(seed_file, "x")
        f.write(hexlify(seed).decode())
        f.close()
        return Wallet(secp, location, seed)

    @staticmethod
    def create_random(secp: Secp256k1, location: str):
        return Wallet.create(secp, location, os.urandom(32))


#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# This script takes multiple multiple fasta files downloaded from
# NCBI (a search for one specific gene for all othologs)
# and identifies the genes that are common to all files.
# It generates a common file with all fasta files and
# individual multiple fasta files for each input file.
# For the VEGFs and the purpose of this analysis, we
# have downloaded from NCBI https://www.ncbi.nlm.nih.gov/gene/XXXX/ortholog,
# XXXX = 7422, 7423, 7424, 2277, 5228 for VEGF-A, -B, -C, -D and PlGF, respectively

import os, re, sys
from Bio import SeqIO

def extract_organism(seq_record, VERBOSE = True):
    # get organism from square brackets (if there are such)
    re_search_result = re.search('\[(.*)\]', str(seq_record))
    if re_search_result:
        #if VERBOSE: print('Protein sequence detected.')
        organism = re_search_result.group(0)[1:-1]
        # get rid of three-word organisms
        organism = ' '.join(organism.split(' ')[:2])
        if VERBOSE: print('Organism (from protein record {0}): {1}.'.format(seq_record.id, organism))
    # Check whether it is a protein sequence or mRNA sequence
    elif seq_record.id[:3] in ['sp|', 'tr|']:
        #if VERBOSE: print('Protein sequence detected.')
        organism = re.search('OS=(.*) OX=', str(seq_record)).group(1)
        if VERBOSE: print('Organism (from protein record {0}): {1}.'.format(seq_record.id, organism))
    # The rest should be mRNA sequences
    else:
        #if VERBOSE: print('mRNA sequence detected.')
        if 'PREDICTED' in str(seq_record):
            new_str = str(seq_record).split('PREDICTED: ')[1]
        else:
            new_str = seq_record.description.split(' ', 1)[1]
            #print('new_str: {0}'.format(new_str))
        organism = ' '.join(new_str.split(' ', 2)[:2])
        if VERBOSE: print('Organism (from mRNA record {0}): {1}.'.format(seq_record.id, organism))
    return organism

def run():
    # This list contains species where the reference mRNA sequence and the
    # protein sequence do not agree or where some abberant splicing has been predicted, etc.
    #
    # VEGF-C issues with:
    #   Monodelphis domestica (?)
    #   Propithecus coquereli (?)
    # VEGF-A issues
    #   Jaculus jaculus (only short form)
    #   Bos indicus (low quality protein)
    #   Condylura cristata (low quality, only short form)
    #   Trichechus manatus latirostris (only short form)
    #   Neomonachus schauinslandi (only short form)
    #   Mesocricetus auratus (only short form)
    #   Elephantulus edwardii (only short form)
    # Only test the first two words of the scientific name!!!
    blacklist = ['Monodelphis domestica',
        'Propithecus coquereli',
        'Jaculus jaculus',
        'Bos indicus',
        'Condylura cristata',
        'Echinops telfairi',
        'Ceratotherium simum',
        'Fukomys damarensis',
        'Myotis davidii',
        'Myotis brandtii',
        'Physeter catodon',
        'Phascolarctos cinereus', # VEGF-A blacklist starts after this one
        'Trichechus manatus',
        'Piliocolobus tephrosceles',
        'Puma concolor',
        'Mesocricetus auratus',
        'Pteropus alecto',
        'Ochotona princeps',
        'Elephantulus edwardii',
        'Equus caballus',
        'Neophocaena asiaeorientalis',
        'Mandrillus leucophaeus',
        'Sus scrofa',
        'Equus asinus',
        'Orycteropus afer',
        'Phocoena sinus',
        'Meriones unguiculatus',
        'Cavia porcellus',
        'Ursus maritimus',
        'Marmota flaviventris',
        'Panthera tigris',
        'Pteropus vampyrus',
        'Rousettus aegyptiacus',
        'Theropithecus gelada',
        'Heterocephalus glaber',
        'Octodon degus',
        'Hipposideros armiger',
        'Chinchilla lanigera',
        'Neomonachus schauinslandi',
        'Colobus angolensis',
        'Sorex araneus',
        'Carlito syrichta',
        'Macaca mulatta',
        'Ailuropoda melanoleuca', # VEGF-D blacklist starts after this line
        'Marmota marmota',
        'Manis javanica',
        'Hylobates moloch',
        'Chelonia mydas',
        'Rattus rattus', # VEGF-B blacklist starts after this line
        'Rhinopithecus bieti']
    # Determine directories of script (in order to load & save the data files)
    APPLICATION_PATH = os.path.abspath(os.path.dirname(__file__))
    FASTA_COMMON_OUTFILE = ''
    #print('Input files are:')
    # remove result files from list of files
    inputfiles = ['PGF_refseq_protein.fasta',
                'PGF_refseq_transcript.fasta',
                'VEGFA_refseq_protein.fasta',
                'VEGFA_refseq_transcript.fasta',
                'VEGFB_refseq_protein.fasta',
                'VEGFB_refseq_transcript.fasta',
                'VEGFC_refseq_protein.fasta',
                'VEGFC_refseq_transcript.fasta',
                'VEGFD_refseq_protein.fasta',
                'VEGFD_refseq_transcript.fasta']
    # Generate new filename for output
    for file in inputfiles:
        FASTA_COMMON_OUTFILE += os.path.splitext(file)[0]+'_'
    FASTA_COMMON_OUTFILE = FASTA_COMMON_OUTFILE[:-1]+'_intersection.fasta'
    # Make a list of lists that has as many elements as we have input files
    dictionary_of_lists = {}
    for file in inputfiles:
        dictionary_of_lists[file] = []
        FASTA_INFILE = file
        records = list(SeqIO.parse(FASTA_INFILE, "fasta"))
        print('{0}: {1} proteins'.format(FASTA_INFILE, len(records)))
        for seq_record in records:
            # The following line contains the actual search for the organism
            # FOR PROTEIN FILES FROM UNIPROT.ORG:
            #organism = re.search('OS=(.*) OX=', str(seq_record)).group(1)
            # FOR mRNA FILES FROM NCBI:
            organism = extract_organism(seq_record, VERBOSE = False)
            if organism not in blacklist:
                if organism not in dictionary_of_lists[file]:
                    dictionary_of_lists[file].append(organism)
    # Convert into sets for intersection operation
    new_set = set(dictionary_of_lists[inputfiles[0]])
    for i in range(len(inputfiles)-1):
        new_set = new_set.intersection(set(dictionary_of_lists[inputfiles[i+1]]))
    print('Common organisms among all files ({0}):'.format(len(new_set)))
    for item in new_set:
        print(item)
    list_of_organisms = list(new_set)
    # Write all entries to a common fasta file
    new_common_records = []
    for file in inputfiles:
        FASTA_INFILE = file
        FASTA_OUTFILE = os.path.splitext(FASTA_INFILE)[0]+'_intersection.fasta'
        records = list(SeqIO.parse(FASTA_INFILE, "fasta"))
        new_records = []
        # This is more complicated because we want to have all organisms
        # in the same order in both protein and mRNA file
        for organism in list_of_organisms:
            for seq_record in records:
                extracted_organism = extract_organism(seq_record, VERBOSE = False)
                if extracted_organism == organism:
                    new_common_records.append(seq_record)
                    new_records.append(seq_record)
        SeqIO.write(new_records, FASTA_OUTFILE, "fasta")
        print('Output written to {0}'.format(FASTA_OUTFILE))
    # In case we want to have all sequences in one file
    #SeqIO.write(new_common_records, FASTA_COMMON_OUTFILE, "fasta")
    #print('Output written to {0}'.format(FASTA_COMMON_OUTFILE))
    print('Common organisms among all files: {0}.'.format(len(new_set)))

if __name__ == '__main__':
    run()


#! /usr/bin/env python3
#
# Listen to a socket for a datagram with status information about the ship board computers
#
# May-2021, Pat Welch, pat@mousebrains.com
# June-2022, Pat Welch, pat@mousebrains.com, rewritten

from argparse import ArgumentParser
import queue
import psycopg2 # Postgresql interface
import socket
from TPWUtils import Thread
import threading
from TPWUtils import Logger
from DataPacket import Packet
from Hosts import Hosts
import time
import logging
import os.path

class Reader(Thread.Thread):
    ''' Common components for reading data packets '''
    def __init__(self, name:str, args:ArgumentParser) -> None:
        Thread.Thread.__init__(self, name, args)
        self.hosts = Hosts(args)
        self.packet = Packet(args)
        self.queues = []

    @staticmethod
    def addArgs(parser:ArgumentParser) -> None:
        Hosts.addArgs(parser)
        grp = parser.add_argument_group(description="TCP/UDP listener options")
        grp.add_argument('--port', type=int, default=11113, metavar='port',
                help='Port to listen on')
        grp.add_argument("--size", type=int, default=8, help="Datagram size, power of 2 >= 8")
        grp = grp.add_mutually_exclusive_group()
        grp.add_argument("--tcp", action="store_true", help="Connect using TCP")
        grp.add_argument("--udp", action="store_true", help="Connect using UDP datagrams")

    def addQueue(self, q:queue.Queue) -> None:
        self.queues.append(q)

    def received(self, data:bytes, addr:tuple) -> None:
        now = time.time()
        (host, temp, free, frac) = self.packet.explode(data, self.hosts)
        if host is not None:
            payload = (now, addr[0], addr[1], host, temp, free, frac)
            logging.debug("Payload %s", payload)
            for q in self.queues: q.put(payload)
        else:
            logging.debug("data %s", data)

class ConsumeTCP(Thread.Thread):
    ''' Consume a TCP connection '''
    def __init__(self, args:ArgumentParser, connection, addr:tuple, rdr:Reader) -> None:
        Thread.Thread.__init__(self, f"TCP:{addr[0]}:{addr[1]}", args)
        self.__connection = connection
        self.__addr = addr
        self.__reader = rdr

    def runIt(self) -> None: # Called on thread start
        sz = self.args.size
        rdr = self.__reader
        addr = self.__addr
        try:
            with self.__connection as conn:
                while True:
                    data = conn.recv(sz)
                    if not data: break
                    rdr.received(data, addr)
        except:
            logging.exception("Connection problem")

class ReaderTCP(Reader):
    ''' Wait on a connection request, then spawn off a TCP consumer '''
    def __init__(self, args:ArgumentParser) -> None:
        Reader.__init__(self, "RdrTCP", args)

    @staticmethod
    def addArgs(parser:ArgumentParser) -> None:
        grp = parser.add_argument_group(description="TCP listener options")
        grp.add_argument("--nThreads", type=int, default=30,
                help="Maximum number of simultaneous connections")

    def runIt(self) -> None: # Called on thread start
        args = self.args
        port = args.port
        sz = args.size
        maxThreads = args.nThreads
        logging.info("Starting port %s size %s", port, sz)
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.bind(('', port))
            s.listen() # Listen for incoming TCP connections
            logging.debug("Listening to port %s", port)
            while True:
                (conn, addr) = s.accept() # Got a connection request, so spin it off
                if threading.active_count() > maxThreads:
                    logging.info("Rejecting connections %s due to maximum number of threads, %s<%s",
                            addr, maxThreads, threading.active_count())
                    conn = None # Close the connection, eventually
                else:
                    thrd = ConsumeTCP(args, conn, addr, self)
                    thrd.start()

class ReaderUDP(Reader):
    ''' Wait for UDP datagrams '''
    def __init__(self, args:ArgumentParser) -> None:
        Reader.__init__(self, "RdrUDP", args)

    @staticmethod
    def addArgs(parser:ArgumentParser) -> None:
        pass

    def runIt(self) -> None: # Called on thread start
        args = self.args
        port = args.port
        sz = args.size
        logging.info("Starting port %s size %s", port, sz)
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
            s.bind(("", port))
            while True:
                (data, addr) = s.recvfrom(sz)
                self.received(data, addr)

class Writer(Thread.Thread):
    ''' Wait on a queue, and write the item to a database '''
    def __init__(self, args:ArgumentParser, rdr:Reader) -> None:
        Thread.Thread.__init__(self, "Writer", args)
        self.__queue = queue.Queue()
        rdr.addQueue(self.__queue)

    @staticmethod
    def addArgs(parser:ArgumentParser) -> None:
        grp = parser.add_argument_group(description="Database writer options")
        grp.add_argument("--table", type=str, default="status", metavar="tblName",
                help="Postgresql table name")
        grp.add_argument("--db", type=str, metavar="dbName",
                help="Postgresql database name")

    def mkTable(self, cur) -> None:
        tbl = self.args.table
        sql = "CREATE TABLE IF NOT EXISTS " + tbl + "(\n"
        sql+= " t REAL, -- Time datagram was received\n"
        sql+= " ipAddr TEXT, -- IP address datagram received from\n"
        sql+= " port INTEGER, -- port number datagram received on\n"
        sql+= " host TEXT, -- Hostname\n"
        sql+= " temp REAL, -- Temperature (C)\n"
        sql+= " free REAL, -- GB available\n"
        sql+= " avail REAL, -- Fraction available\n"
        sql+= " PRIMARY KEY(t, host)\n"
        sql+= " );"
        cur.execute(sql)

    def runIt(self) -> None: # Called on thread start
        args = self.args
        q = self.__queue
        sql = "INSERT INTO " + args.table + " VALUES(%s,%s,%s,%s,%s,%s,%s);"
        dbName = f"dbname={args.db}"
        logging.info("Starting SQL\n%s", sql)
        qMakeTable = True
        while True: # Loop forever
            row = q.get()
            q.task_done()
            (t, addr, port, host, temp, free, avail) = row
            logging.info("Received %s temp %s free %s avail %s", host, temp, free, avail)
            with psycopg2.connect(dbName) as db:
                cur = db.cursor()
                cur.execute("BEGIN;")
                if qMakeTable:
                    self.mkTable(cur)
                    qMakeTable = False
                try:
                    cur.execute(sql, row)
                    cur.execute("COMMIT;")
                except:
                    cur.execute("ROLLBACK;")

class CSV(Thread.Thread):
    ''' Wait on a queue to look at a database and update a CSV file '''
    def __init__(self, args:ArgumentParser, rdr:Reader) -> None:
        Thread.Thread.__init__(self, "CSV", args)
        self.__queue = queue.Queue()
        rdr.addQueue(self.__queue)

    @staticmethod
    def addArgs(parser:ArgumentParser) -> None:
        parser.add_argument("--csv", type=str, help="CSV filename")

    def runIt(self) -> None: # Called on thread start
        args = self.args
        fn = args.csv
        q = self.__queue
        logging.info("Starting %s", fn)
        if not os.path.isfile(fn):
            with open(fn, "w") as fp:
                fp.write(",".join(("t", "host", "temp", "free", "avail")) + "\n")

        while True:
            row = q.get()
            q.task_done()
            (t, addr, port, host, temp, free, avail) = row
            logging.info("Received %s temp %s free %s avail %s", host, temp, free, avail)
            payload = (
                    str(t),
                    host,
                    "" if temp is None else str(temp),
                    "" if free is None else str(free),
                    "" if avail is None else str(avail),
                    )
            with open(fn, "a") as fp:
                fp.write(",".join(payload) + "\n")

parser = ArgumentParser(description="Listen for a LiveGPS message")
Logger.addArgs(parser)
Reader.addArgs(parser)
ReaderTCP.addArgs(parser)
ReaderUDP.addArgs(parser)
Writer.addArgs(parser)
CSV.addArgs(parser)
args = parser.parse_args()

Logger.mkLogger(args)
logging.info("args=%s", args)

try:
    reader = ReaderTCP(args) if args.tcp else ReaderUDP(args)
    if args.db:
        writer = Writer(args, reader) # Create the db writer thread
        writer.start()
    if args.csv:
        csv = CSV(args, reader) # Create the CSV file
        csv.start()

    reader.start() # Start the reader thread

    Thread.Thread.waitForException() # This will only raise an exception from a thread
except:
    logging.exception("Unexpected exception while listening")


#1 задача
a = []
for x in range(4):
    while True:
        try:
            a.append(int(input(f"Ведіть ціле {x+1}-е число -\n")))
            break
        except:
            print("Не вірно")
            for namber in a:
                print(namber)
print(max(a))

#2 задача
year = int(input('Ведіть рік - '))
if year % 400 == 0:
     print('366')
elif year % 100 == 0:
     print('365')
elif year % 4 == 0:
     print('366')
else:
     print('365')

#3 задача
a =input()
b =input()
c =input()
if a + b > c:
    bool=True
if a + b < c:
    bool=False
import math
print()

#4 задача
for i in range(101):
    if not i % 7:
        continue
    print(i)
#5 задача
f = 1
n = int(input())
while n > 1:
     f = f * n
     n = n - 1
print(f)

#6 задача
width = int(input('ширина годинника: '))
side_height = width // 2

for i in range(0, side_height):
    line = "*" * (width - (i * 2))
    print(line.center(width))

print("*".center(width))

for i in range(1, side_height + 1):
    line = "*" * ((i * 2) + 1)
    print(line.center(width))
# 7задача
for num in range(1, 101):
    for i in range(2, num):
        if num % i == 0:
            break
        else:
            print(num)
            break

практична номер 4.py

практична номер 4.py


from django.db import models
from django.db.models import signals
from django.contrib.contenttypes.models import ContentType

from savoy.core.geo.models import *
from savoy.core.geo.utils.misc import *

class GeolocatedItemManager(models.Manager):
    def remove_orphans(self, instance, **kwargs):
      """
      When an item is deleted, first delete any GeolocatedItem object that has been created
      on its behalf.
      """
      from savoy.core.geo.models import GeolocatedItem
      try:
        instance_content_type = ContentType.objects.get_for_model(instance)
        geolocated_item = GeolocatedItem.objects.get(content_type=instance_content_type, object_id=instance.id)
        geolocated_item.delete()
      except GeolocatedItem.DoesNotExist:
        return

    def create_or_update(self, instance, location=None, address=None, city=None, neighborhood=None, **kwargs):
      """
      Create or update a GeolocatedItem from some instance. Instance must provide
      either (latitude,longitude) or an address for geocoding.
      """
      from savoy.core.geo.models import GeolocatedItem
      # If the instance hasn't already been saved, save it first.
      if instance._get_pk_val() is None:
        try:
          signals.post_save.disconnect(self.create_or_update, sender=type(instance))
        except:
          reconnect = False
        else:
          reconnect = True
        instance.save()
        if reconnect:
          signals.post_save.connect(self.create_or_update, sender=type(instance))

      # Find this object's content type and model class.
      instance_content_type = ContentType.objects.get_for_model(instance)
      instance_model        = instance_content_type.model_class()

      # If we got an address, we need to geocode it.
      if address:
        location = get_location_from_address(address)

      # We should now have a location tuple (either passed in or geolocated
      # from the passed in address). Unpack it.
      if location:
        latitude, longitude = location

        # Determine the city and neighborhood for this geolocated item.
        if not city:
          city = get_city_from_flickr(latitude, longitude)
        if not neighborhood:
          try:
            neighborhood = get_neighborhood_from_urban_mapping(latitude, longitude, city)
          except:
            neighborhood = None

        # Get or create the GeolocatedItem object.
        geolocated_item, created = self.get_or_create(
          content_type = instance_content_type,
          object_id = instance._get_pk_val(),
          defaults = dict(
            city = city,
            neighborhood = neighborhood,
            latitude = str(latitude),
            longitude = str(longitude),
          )
        )

        # If this is not a new GeolocatedItem object, update it with current data.
        if not created:
          geolocated_item.latitude = str(latitude)
          geolocated_item.longitude = str(longitude)
          geolocated_item.city = city
          geolocated_item.neighborhood = neighborhood

        # Save and return the item.
        geolocated_item.save()
        return geolocated_item
      else:
        return

    def get_for_model(self, model):
      """
      Return a QuerySet of only items of a certain type.
      """
      return self.filter(content_type=ContentType.objects.get_for_model(model))


'''
# 백준_10971_외판원 순회. 실버 2. 풀이: 23.07.12

# How to
- 문제의 조건:
    - W[i][j] 는 W[j][i]와 다를 수 있다.
    - 길이 없을 수도 있다
    - 한 번 갔던 도시로는 다시 갈 수 없다.
    - 항상 순회할 수 있는 경우만 입력으로 주어진다.

- DFS
- 항상 순회하므로, 0번 도시에서 출발
- 매번 다른 도시로 이동 가능한지 체크하고, 방문
- 마지막 도시라면, 출발 도시로 이동 가능할 경우 비용 갱신

## 반례
1 2 3
1 -> 2 -> 3 -> 1 return
1 -> 3 -> 1 return

3
0 10 100
2 0 200
3 30 0
정답: 132

# Review
- 풀이 시간: 30분
- 왜 이렇게 느리지..?
'''

# Code
# 1. DFS: 성공
## 메모리: 31256 KB, 시간: 508 ms
import sys
input = sys.stdin.readline

# 도시의 수 n, 도시간 비용 cost
n = int(input())
city = [list(map(int, input().split())) for _ in range(n)]
visited = [False] * n
answer = int(1e9)

def dfs(now, cost, depth):
    global answer

    # 방문 처리
    visited[now] = True

    # 마지막 도시이고 출발 도시로 이동 가능하다면, 비용 갱신
    if depth == n-1 and city[now][0]:
        answer = min(answer, cost+city[now][0])
        return

    # 새로 방문하는 도시라면, 이동
    for next in range(n):
        # 다음 도시로 이동 가능하면,
        if not visited[next] and city[now][next]:
            dfs(next, cost+city[now][next], depth+1)
            visited[next] = False

dfs(0, 0, 0)
print(answer)