import pickle
import numpy as np
from matplotlib import pyplot as plt
import scipy.cluster.hierarchy as sc
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import silhouette_score

dataset = pickle.load(open("../data/part3_dataset.data", "rb"))

"""plot_dendogram function code is taken from scikit-learn:
https://scikit-learn.org/stable/auto_examples/cluster/plot_agglomerative_dendrogram.html.
Scikit-learn: Machine Learning in Python, Pedregosa et al., JMLR 12, pp. 2825-2830, 2011.
"""
def plot_dendrogram(model, **kwargs):
    # Create linkage matrix and then plot the dendrogram

    # create the counts of samples under each node
    counts = np.zeros(model.children_.shape[0])
    n_samples = len(model.labels_)
    for i, merge in enumerate(model.children_):
        current_count = 0
        for child_idx in merge:
            if child_idx < n_samples:
                current_count += 1  # leaf node
            else:
                current_count += counts[child_idx - n_samples]
        counts[i] = current_count

    linkage_matrix = np.column_stack(
        [model.children_, model.distances_, counts]
    ).astype(float)

    # Plot the corresponding dendrogram
    sc.dendrogram(linkage_matrix, **kwargs)

linkages = ['single', 'complete']
distances = ['euclidean', 'cosine']
k_values = [2, 3, 4, 5]

for linkage in linkages:
    for distance in distances:
        silhouette_scores = []
        for K in k_values:
            hac = AgglomerativeClustering(n_clusters=K, affinity=distance, linkage=linkage,
                                          compute_distances=True)
            hac.fit(dataset)
            s = silhouette_score(dataset, hac.labels_, metric=distance)
            silhouette_scores.append(s)
            plt.title("Hierarchical Agglomerative Clustering Dendrogram")
            plot_dendrogram(hac)
            plt.xlabel(f"linkage:{linkage}, distance:{distance}, cluster_size:{K}")
            plt.show()

        print(silhouette_scores)
        plt.plot(k_values, silhouette_scores)
        plt.title(f'Silhouette Scores vs K values for {distance}-{linkage}') # Title of the plot
        plt.xlabel('K values') # X-Label
        plt.ylabel('Silhouette scores') # Y-Label
        plt.show()


def isomorphise(string1):
    num1 = 0
    num2 = 0
    currentchar = ""
    string3 = ""
    for index,char in enumerate(string1):
        currentchar = char
        for char in string1[index+1:len(string1)]:
            num1+=1
            if currentchar == char:
                num2 = num1
                num1 = 0
                break;
        if num2 > 0:
            num2 = f"+{num2}"
        string3 = f"{string3} {num2}"
        num1 = 0
        num2 = 0
    return string3
str1ng = "inn"
str2ng = "all"
if isomorphise(str1ng) == isomorphise(str2ng):
    print(True)

FA1 Checkpoint Lucas Nugyen/isomorphicpairs.py


import sympy as sym
import numpy as np
from math import sqrt

# 0.1*x1^2+x1+0.2*x2^2-0.3
# 0.2*x1^2+x2-0.1*x1*x2-0.7
def norm_vector(v):
    sum_ = 0
    for i in range(len(v)):
        sum_ += v[i] * v[i]

    return sqrt(sum_)

def newton_method_systems_(expr1, expr2, a1, b1, a2, b2, eps):
    x1_old = 0.5 * (a1 + b1)
    x2_old = 0.5 * (a2 + b2)

    x1 = sym.Symbol('x1')
    x2 = sym.Symbol('x2')

    f1 = sym.S(expr1)
    f2 = sym.S(expr2)

    df1x1 = sym.diff(f1, x1)
    df1x2 = sym.diff(f1, x2)
    df2x1 = sym.diff(f2, x1)
    df2x2 = sym.diff(f2, x2)

    condition = 1
    k = 0

    while condition > eps:
        J = np.array(
            [[(df1x1.subs([(x1, x1_old), (x2, x2_old)])).evalf(), (df1x2.subs([(x1, x1_old), (x2, x2_old)])).evalf()],
             [(df2x1.subs([(x1, x1_old), (x2, x2_old)])).evalf(), (df2x2.subs([(x1, x1_old), (x2, x2_old)])).evalf()]])

        A1 = np.array(
            [[(f1.subs([(x1, x1_old), (x2, x2_old)])).evalf(), (df1x2.subs([(x1, x1_old), (x2, x2_old)])).evalf()],
             [(f2.subs([(x1, x1_old), (x2, x2_old)])).evalf(), (df2x2.subs([(x1, x1_old), (x2, x2_old)])).evalf()]])

        A2 = np.array(
            [[(df1x1.subs([(x1, x1_old), (x2, x2_old)])).evalf(), (f1.subs([(x1, x1_old), (x2, x2_old)])).evalf()],
             [(df2x1.subs([(x1, x1_old), (x2, x2_old)])).evalf(), (f2.subs([(x1, x1_old), (x2, x2_old)])).evalf()]])

        try:
            x1_new = x1_old - ((A1[0, 0] * A1[1, 1] - A1[0, 1] * A1[1, 0]) / (J[0, 0] * J[1, 1] - J[0, 1] * J[1, 0]))
            x2_new = x2_old - ((A2[0, 0] * A2[1, 1] - A2[0, 1] * A2[1, 0]) / (J[0, 0] * J[1, 1] - J[0, 1] * J[1, 0]))
        except ZeroDivisionError:
            return None, None, 0

        v = np.array([x1_new - x1_old, x2_new - x2_old])
        condition = norm_vector(v)

        x1_old = x1_new
        x2_old = x2_new
        k += 1

    return x1_old, x2_old, k

def check_iter_(expr1, expr2, a1, b1, a2, b2):
    x1 = sym.Symbol('x1')
    x2 = sym.Symbol('x2')

    phi1 = "x1+" + expr1
    phi2 = "x2+" + expr2

    phi1 = sym.S(phi1)
    phi2 = sym.S(phi2)

    dphi1x1 = sym.diff(phi1, x1)
    dphi1x2 = sym.diff(phi1, x2)
    dphi2x1 = sym.diff(phi2, x1)
    dphi2x2 = sym.diff(phi2, x2)

    ca1 = a1
    dx = 0.01
    max1 = 0
    while ca1 < b1:
        ca2 = a2
        while ca2 < b2:
            tmp1 = dphi1x1.subs([(x1, ca1), (x2, ca2)])
            tmp2 = dphi1x2.subs([(x1, ca1), (x2, ca2)])
            max1 = max([tmp1, tmp2, max1], key=abs)
            ca2 += dx
        ca1 += dx

    ca1 = a1

    max2 = 0
    while ca1 < b1:
        ca2 = a2
        while ca2 < b2:
            tmp1 = dphi2x1.subs([(x1, ca1), (x2, ca2)])
            tmp2 = dphi2x2.subs([(x1, ca1), (x2, ca2)])
            max2 = max([tmp1, tmp2, max2], key=abs)
            ca2 += dx
        ca1 += dx

    return True, [1./max1, 1./max2]

def iter_method_systems_(expr1, expr2, q_l, a1, b1, a2, b2, eps):
    x1_old = 0.5*(a1 + b1)
    x2_old = 0.5*(a2 + b2)

    x1 = sym.Symbol('x1')
    x2 = sym.Symbol('x2')
    q1 = q_l[0]
    q2 = q_l[1]

    phi1 = "x1-" + str(q1) + "*(" + str(expr1) + ")"
    phi2 = "x2-" + str(q2) + "*(" + str(expr2) + ")"

    print(phi1)
    print(phi2)

    phi1 = sym.S(phi1)
    phi2 = sym.S(phi2)

    condition1 = 1
    condition2 = 1
    k = 0

    while condition1 > eps or condition2 > eps:
        x1_new = (phi1.subs([(x1, x1_old), (x2, x2_old)])).evalf()
        x2_new = (phi2.subs([(x1, x1_old), (x2, x2_old)])).evalf()
        if abs(x1_new) > 10e10 or abs(x2_new) > 10e10:
            return None, None, 0
        v = np.array([x1_new - x1_old, x2_new - x2_old])
        condition1 = (q1 / (1-q1))*norm_vector(v)
        condition2 = (q2 / (1-q2))*norm_vector(v)

        x1_old = x1_new
        x2_old = x2_new
        k += 1

    return x1_old, x2_old, k


from collections import namedtuple
from functools import partial
import numpy as np
from scipy.integrate import quad

MW = 80.379
MELEC = 0.511e-3
ER = MW**2/(2*MELEC)
GAMMAW = 2.085
GAMMA0 = 2*ER*GAMMAW/MW
ALPHA = 1/137.035999
A0 = 1/(MELEC*ALPHA)

Wavefunctions = namedtuple('Wavefunctions',
                           'f1s f2s f2p f3s f3p f4s f3d')
Orbitals = namedtuple('Orbitals',
                      'ne_1s ne_2s ne_2p ne_3s ne_3p ne_4s ne_3d')
Elements = namedtuple('Elements', 'H O Mg Si Ca Fe')
Element = namedtuple('Element', 'orbitals wavefunctions')

def build_orbitals(Z):
    ordering = Orbitals._fields
    max_e = {'s':2, 'p':6, 'd':10}

    stable_orbitals = [0]*len(ordering)
    curr = 0
    while Z:
        stable_orbitals[curr] = min(max_e[ordering[curr][-1]], Z)
        Z -= stable_orbitals[curr]
        curr += 1

    return Orbitals(*stable_orbitals)

def build_wfs(*args):
    lm2k2 = lambda k, mu: np.log(mu**2+k**2)
    f1s = lambda k, mu: 32/np.pi*np.exp(
        5*np.log(mu)+2*np.log(k)-4*lm2k2(k,mu))
    f2s = lambda k, mu: 32/(3*np.pi)*(3*mu**2*k-k**3)**2*np.exp(
        5*np.log(mu)-6*lm2k2(k,mu))
    f2p = lambda k, mu: 512/(3*np.pi)*np.exp(
        7*np.log(mu)+4*np.log(k)-6*lm2k2(k,mu))
    f3s = lambda k, mu: 1024/(5*np.pi)*(mu**3*k-mu*k**3)**2*np.exp(
        7*np.log(mu)-8*lm2k2(k,mu))
    f3p = lambda k, mu: 1024/(45*np.pi)*(5*mu**2*k**2-k**4)**2*np.exp(
        7*np.log(mu)-8*lm2k2(k,mu))
    f3d = lambda k, mu: 4096/(5*np.pi)*np.exp(
        9*np.log(mu)+6*np.log(k)-8*lm2k2(k,mu))
    f4s = lambda k, mu: 512/(35*np.pi)*(5*mu**4*k-10*mu**2*k**3+k**5)**2*np.exp(
        9*np.log(mu)-10*lm2k2(k,mu))

    dists = [f1s, f2s, f2p, f3s, f3p, f4s, f3d]
    return Wavefunctions(*[partial(f, mu=xi/A0) if xi>0 else lambda k: k*0 for f, xi in zip(dists,args)])

ELEMENTS = Elements(
    Element(build_orbitals(1), build_wfs(1, 0, 0, 0, 0, 0, 0)),
    Element(build_orbitals(8), build_wfs(7.66, 2.25, 2.23, 0, 0, 0, 0)),
    Element(build_orbitals(12), build_wfs(11.6, 3.7, 3.0, 1.1, 0, 0, 0)),
    Element(build_orbitals(14), build_wfs(13.6, 4.5, 5.0, 1.6, 1.4, 0, 0)),
    Element(build_orbitals(20), build_wfs(19.5, 6.9, 8.0, 3.2, 2.9, 1.1, 0)),
    Element(build_orbitals(26), build_wfs(25.4, 9.3, 11.0, 4.6, 4.3, 1.4, 3.7)))

def sigma_erest(enu):
    """ At-rest electron. Eq. (3)
    enu in GeV
    """
    _ = GAMMA0**2/4
    return _/((enu-ER)**2+_)

@np.vectorize
def sigma_edopp(enu, element='O'):
    """ Bound electron
    """
    elem = ELEMENTS.__getattribute__(element)
    Z = sum(elem.orbitals)
    F = lambda beta: np.sum([MELEC*ne*fk(beta*MELEC) for ne, fk in zip(elem.orbitals, elem.wavefunctions)])/Z
    integrand = lambda beta: F(beta)/beta*(
        np.arctan(2/GAMMA0*(enu*(1+beta)-ER))-np.arctan(2/GAMMA0*(enu*(1-beta)-ER)))
    return GAMMA0/(4*enu)*quad(integrand, 0, 1)[0]

if __name__=='__main__':
    for e, n in zip(ELEMENTS, ELEMENTS._fields):
        print(n, sigma_edopp(ER, n))
        for fk, orbital_name in zip(e.wavefunctions, e.wavefunctions._fields):
            print('...', orbital_name, quad(fk, 0, MELEC))


# -*- coding: utf-8 -*-
"""
Created on Fri Sep 24 17:49:31 2021

@author: sp3660
"""
import tkinter as tk
from tkinter import END, Label, RAISED, Text, WORD, StringVar, Button, ttk

class AddSessionInfo(tk.Toplevel):
    def __init__(self,  gui, session_date):
        tk.Toplevel.__init__(self, gui) #inst
        self.gui_ref=gui
        self.geometry("+2555+0")
        row_labels=['Microscope','StartTime','Objectives','EndOfSessionSummary','IssuesDuringImaging']
        self.total_rows=len(row_labels)+1
        self.values=list()
        self.b = list()
        self.b.append(list())
        self.values.append(list())

        col_labels=['Info',session_date.strftime('%Y%m%d')]

        for j in range(len(col_labels)): #Columns
           self.b[0].append( Label( self, text =col_labels[j], relief=RAISED)) # b[i][j]
           self.b[0][j].grid(row=1, column=j)
           self.values[0].append(col_labels[j])
        for i in range(1,self.total_rows,1): #Rows
            self.b.append(list())
            self.values.append(list())
            for j in range(len(col_labels)): #Columns
                if j==0:
                    texts=row_labels[i-1]
                    self.b[i].append(Label(self, text=texts, width=30)) # b[i][j]
                    self.b[i][j].grid(row=i+1, column=j)
                    self.values[i].append(texts)

                elif j>0:
                    if i not in (1,2):
                        self.b[i].append(Text(self, height=5, width=150, wrap=WORD)) # b[i][j]
                        self.b[i][j].grid(row=i+1, column=j)
                        self.values[i].append(self.b[i][j].get("1.0",END) )
                        self.b[i][j].insert("1.0",('TO DO'))

                    elif i==1:
                        values=['Prairie1',"Hakim's",'Prairie2']
                        self.b[i].append(ttk.Combobox(self, values=values)) # b[i][j]
                        self.b[i][j].grid(row=i+1, column=j)
                        self.b[i][j].current(0)
                        self.values[i].append(self.b[i][j].get())
                    elif i==2:
                        self.b[i].append(Text(self, height=5, width=150, wrap=WORD)) # b[i][j]
                        self.b[i][j].grid(row=i+1, column=j)
                        self.values[i].append(self.b[i][j].get("1.0",END) )
                        self.b[i][j].insert("1.0",('00:00'))

        enter_button = Button(self, text="Enter", command=self.retrieve_input)
        enter_button.grid(row=1,column=26)

    def retrieve_input(self):
        for i in range(1,self.total_rows,1): #Rows
            if i !=1:
                self.values[i][1]=self.b[i][1].get("1.0",END)
                while  self.values[i][1].endswith('\n'):
                    self.values[i][1]=self.values[i][1][:-1]

            elif i==1:
                self.values[i][1]=self.b[i][1].get()
        self.destroy()
        self.update()

if __name__ == "__main__":

    root = tk.Tk()
    app = AddSessionInfo(root, '20210527')
    root.mainloop()
    get_values=app.values


# python3.7
# -*- coding: utf-8 -*-
# @Project_Name  : Air Quality prediction Beijing
# @File          : save_model.py
# @Time          : 2022/11/26 14:40
# @Author        : SY.M
# @Software      : PyCharm
import torch
import os

def save_model(model_name: str, target_feature: str, result: tuple, state_dict: dict, pred_len: int, seq_len: int,
        root='G:\PyCharmWorkSpace\PyCharmProjects\Air quality\Air Quality prediction Beijing\saved_model',):
    save_path = os.path.join(root, model_name)
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    save_file = os.path.join(save_path, f'{model_name} {target_feature} {seq_len}->{pred_len} {result}.pt')
    torch.save(state_dict, save_file)
    print('save model successful！')

def load_model(file_path):
    torch.load(file_path)


from PyQt6.QtWidgets import (
    QApplication,
    QFileDialog,
    QInputDialog,
    QMainWindow,
    QWidget,
    QBoxLayout,
    QDockWidget,
    QLineEdit,
    QLabel,
    QCheckBox,
    QPushButton,
    QGridLayout,
    QFrame,
    QDoubleSpinBox,
    QSpinBox,
    QDialog,
    QGraphicsView,
    QGraphicsScene,
    QToolBar,
    QSizePolicy,
)
from PyQt6.QtCore import (
    Qt,
    QTimer,
    QEvent,
)
from PyQt6 import QtGui
from pytube import YouTube
import librosa
import os
from . import audio_view, events
from ..audio import audio
from ..utils import utils

MUSIC_PATH = "music"
ICONS_PATH = "icons"

def icon(path):
    return QtGui.QIcon("icons/{}".format(path))

class VerticalPitchTrackingWidget(QWidget):
    def __init__(self, audio_player, *args, **kargs):
        super(VerticalPitchTrackingWidget, self).__init__(*args, **kargs)

        self.audio_player = audio_player

        main_layout = QBoxLayout(QBoxLayout.Direction.TopToBottom)
        controls_layout = QBoxLayout(QBoxLayout.Direction.LeftToRight)

        self.timestamp_input = QLineEdit("00.00")
        self.timestamp_input.returnPressed.connect(self.on_set_timestamp)
        controls_layout.addWidget(self.timestamp_input)

        self.lock_to_timestamp_checkbox = QCheckBox("Lock to playback timestamp")
        self.lock_to_timestamp_checkbox.setChecked(True)
        controls_layout.addWidget(self.lock_to_timestamp_checkbox)

        self.threshold_input_label = QLabel("Threshold:")
        controls_layout.addWidget(self.threshold_input_label)
        self.threshold_input = QDoubleSpinBox()
        self.threshold_input.setValue(0.1)
        self.threshold_input.setMaximum(1.0)
        self.threshold_input.setMinimum(0.0)
        self.threshold_input.setSingleStep(0.1)
        controls_layout.addWidget(self.threshold_input)

        self.window_width_label = QLabel("Window size:")
        controls_layout.addWidget(self.window_width_label)
        self.window_width_input = QSpinBox()
        self.window_width_input.setValue(2048)
        self.window_width_input.setMinimum(1024)
        self.window_width_input.setMaximum(10000)
        controls_layout.addWidget(self.window_width_input)

        refresh_button = QPushButton("Refresh")
        refresh_button.clicked.connect(self.on_refresh)
        controls_layout.addWidget(refresh_button)

        main_layout.addLayout(controls_layout)
        self.view = VerticalPitchTrackingView()
        main_layout.addWidget(self.view)

        self.setLayout(main_layout)

        self.audio_data = None
        self.sr = None
        self.timestamp = 0.0

        self.timer = QTimer()
        self.timer.start(30)
        self.timer.timeout.connect(self.on_timeout)

    def on_set_timestamp(self):
        self.timestamp = utils.get_duration_in_seconds(self.timestamp_input.text())
        self.update_scene()

    def on_refresh(self):
        threshold = self.threshold_input.value()
        window_width = self.window_width_input.value()
        self.view.vertical_pitch_tracking_scene.update_params(threshold, window_width)

    def on_timeout(self):
        if self.lock_to_timestamp_checkbox.isChecked():
            if self.audio_player.audio_state is not None and self.audio_player.current_timestamp != self.timestamp:
                self.timestamp = self.audio_player.current_timestamp
                self.timestamp_input.setText(utils.seconds_to_time_str(self.timestamp))
                self.update_scene()

    def update_scene(self):
        self.view.vertical_pitch_tracking_scene.set_timestamp(self.timestamp)
        self.view.vertical_pitch_tracking_scene.update()

    def set_audio_data(self, audio_data, sr):
        self.audio_data = audio_data
        self.sr = sr
        threshold = self.threshold_input.value()
        window_width = self.window_width_input.value()
        self.view.vertical_pitch_tracking_scene.set_data(self.audio_data, self.sr, threshold, window_width)

class VerticalPitchTrackingView(QGraphicsView):
    def __init__(self, *args, **kargs):
        super(VerticalPitchTrackingView, self).__init__(*args, **kargs)

        self.vertical_pitch_tracking_scene = VerticalPitchTrackingScene()
        self.setScene(self.vertical_pitch_tracking_scene)

        self.setMinimumHeight(150)

        self.setFrameShape(QFrame.Shape.NoFrame)

        self.horizontalScrollBar().setValue(1)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self.setViewportUpdateMode(QGraphicsView.ViewportUpdateMode.FullViewportUpdate)
        self.show()

class VerticalPitchTrackingScene(QGraphicsScene):
    def __init__(self, *args, **kargs):
        super(VerticalPitchTrackingScene, self).__init__(*args, **kargs)

        self.audio_data = None
        self.sr = None
        self.piptrack = None
        self.timestamp = 0.0

        self.setBackgroundBrush(Qt.GlobalColor.lightGray)

        self.rects = [None] * 88

    def set_data(self, audio_data, sr, threshold, window_width):
        self.pitches, self.magnitudes = librosa.piptrack(
            y=librosa.to_mono(y=audio_data),
            sr=sr,
            threshold=threshold,
            n_fft=window_width,
            win_length=window_width,
        )
        self.audio_data = audio_data
        self.sr = sr
        self.create_chart()

    def update_params(self, threshold, window_width):
        self.pitches, self.magnitudes = librosa.piptrack(
            y=librosa.to_mono(y=self.audio_data),
            sr=self.sr,
            threshold=threshold,
            n_fft=window_width,
            win_length=window_width,
        )
        self.update()

    def create_chart(self):
        self.clear()
        key_width = 20
        key_height = 100
        pen = QtGui.QPen(Qt.GlobalColor.black)
        brush = QtGui.QBrush(Qt.GlobalColor.white)
        for key in range(0, 88):
            self.rects[key] = self.addRect(key * key_width, 0, key_width, key_height, pen, brush)
            text = self.addText(utils.piano_key_to_note(key), QtGui.QFont("Courier New"))
            text.setDefaultTextColor(Qt.GlobalColor.black)
            text.setPos(key * key_width, key_height + 5)
        self.update()

    def set_timestamp(self, timestamp):
        self.timestamp = timestamp

    def update(self):
        duration = librosa.get_duration(y=self.audio_data, sr=self.sr)
        t = int(self.pitches.shape[1] * self.timestamp / duration)
        pitches = self.pitches[:,t]
        magnitudes = self.magnitudes[:,t]
        magnitudes_by_note = utils.group_by_note(pitches, magnitudes)
        max_magnitude = max(max(magnitudes), 50)
        #redunant, fix
        key_width = 20
        key_height = 100
        for key in range(0, 88):
            ms = magnitudes_by_note[key]
            h = key_height * (ms / max_magnitude)
            self.rects[key].setRect(key * key_width, key_height - h, key_width, h)

class MainView(QWidget):
    def __init__(self, audio_player, open_action, import_action, *args, **kargs):
        super(MainView, self).__init__(*args, **kargs)

        self.audio_view = None
        self.audio_player = audio_player
        layout = QBoxLayout(QBoxLayout.Direction.Down)

        self.open_button = QPushButton("Open...")
        self.open_button.clicked.connect(open_action.trigger)

        self.import_button = QPushButton("Import from YouTube...")
        self.import_button.clicked.connect(import_action.trigger)

        layout.addWidget(self.open_button)
        layout.addWidget(self.import_button)
        layout.addStretch(1)

        self.setLayout(layout)

    def show_audio(self, audio_data, on_loop_change):
        while self.layout().count() > 0:
            self.layout().takeAt(0)
        self.audio_view = audio_view.AudioWaveformView(audio_data, self.audio_player, on_loop_change, self)
        self.layout().addWidget(self.audio_view)

    def zoom_in(self):
        if self.audio_view != None:
            self.audio_view.zoom_in()

    def zoom_out(self):
        if self.audio_view != None:
            self.audio_view.zoom_out()

class EffectsDialog(QDialog):

    def __init__(self, play_rate, harmonic_only):
        super(EffectsDialog, self).__init__()

        layout = QGridLayout()

        self.rate_label = QLabel("Playback rate: ")
        self.rate_input = QDoubleSpinBox()
        self.rate_input.setValue(play_rate)
        self.rate_input.setMaximum(2.0)
        self.rate_input.setMinimum(0.1)

        layout.addWidget(self.rate_label, 0, 0)
        layout.addWidget(self.rate_input, 0, 1)

        self.harmonic_checkbox = QCheckBox("Enable HPSS")
        self.harmonic_checkbox.setChecked(harmonic_only)

        layout.addWidget(self.harmonic_checkbox, 1, 0, 1, 2)

        self.accept_button = QPushButton("OK")
        self.accept_button.clicked.connect(self.accept)
        self.cancel_button = QPushButton("Cancel")
        self.cancel_button.clicked.connect(self.reject)

        layout.addWidget(self.accept_button, 2, 0)
        layout.addWidget(self.cancel_button, 2, 1)

        self.setLayout(layout)

class MainWindow(QMainWindow):

    def __init__(self, audio_player: audio.AudioPlayer):
        super().__init__()

        self.audio_player = audio_player
        self.audio_data = None

        self.main_view = None
        self.key_pressed = dict()

        self.harmonic_only = False
        self.play_rate = 1.0

        self.resize(1024, 768)
        self.setWindowTitle("Noodler")

        self.playback_toolbar = QToolBar("Playback")
        self.back_action = self.playback_toolbar.addAction(icon("back.png"), "Back")
        self.back_action.triggered.connect(lambda: QApplication.postEvent(self, events.BackEvent()))
        self.play_action = self.playback_toolbar.addAction(icon("play.png"), "Play")
        self.play_action.triggered.connect(lambda: QApplication.postEvent(self, events.PlayEvent()))
        self.pause_action = self.playback_toolbar.addAction(icon("pause.png"), "Pause")
        self.pause_action.triggered.connect(lambda: QApplication.postEvent(self, events.PauseEvent()))
        self.addToolBar(Qt.ToolBarArea.TopToolBarArea, self.playback_toolbar)

        self.loop_toolbar = QToolBar("Selection")
        loop_layout = QGridLayout()
        self.range_start_widget = QLineEdit()
        self.range_start_widget.setMaximumWidth(50)
        loop_layout.addWidget(QLabel("Start:"), 0, 0)
        loop_layout.addWidget(self.range_start_widget, 0, 1)
        self.current_timestamp_widget = QLineEdit()
        self.current_timestamp_widget.setMaximumWidth(50)
        loop_layout.addWidget(QLabel("Current:"), 0, 2)
        loop_layout.addWidget(self.current_timestamp_widget, 0, 3)
        self.range_end_widget = QLineEdit()
        self.range_end_widget.setMaximumWidth(50)
        loop_layout.addWidget(QLabel("End:"), 1, 0)
        loop_layout.addWidget(self.range_end_widget, 1, 1)

        self.range_start_widget.returnPressed.connect(lambda: self.range_end_widget.setFocus())
        self.range_end_widget.returnPressed.connect(self.on_submit_range_selection)

        self.loop_checkbox = QCheckBox("Loop")
        self.loop_checkbox.setChecked(True)
        self.loop_checkbox.stateChanged.connect(self.on_set_loop_changed)
        loop_layout.addWidget(self.loop_checkbox, 0, 4)
        self.start_from_beginning_checkbox = QCheckBox("Start from Beginning")
        loop_layout.addWidget(self.start_from_beginning_checkbox, 1, 4)
        loop_layout.setColumnStretch(0, 0)
        loop_layout.setColumnStretch(1, 0)
        loop_layout.setColumnStretch(2, 0)
        loop_layout.setColumnStretch(3, 0)
        loop_layout.setColumnStretch(4, 1)
        loop_layout_widget = QWidget()
        loop_layout_widget.setLayout(loop_layout)
        loop_layout_widget.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Preferred)
        self.loop_toolbar.addWidget(loop_layout_widget)
        self.addToolBar(Qt.ToolBarArea.TopToolBarArea, self.loop_toolbar)

        self.move_toolbar = QToolBar("Move Selection")
        self.move_backward_by_duration_action = self.move_toolbar.addAction(icon("left_arrow.png"), "Move Selection Backward by Duration")
        self.move_backward_by_duration_action.triggered.connect(lambda: QApplication.postEvent(self, events.PauseEvent()))
        self.move_by_duration_amount = QDoubleSpinBox()
        self.move_by_duration_amount.setSuffix("s")
        self.move_toolbar.addWidget(self.move_by_duration_amount)
        self.move_forward_by_duration_action = self.move_toolbar.addAction(icon("right_arrow.png"), "Move Selection Forward by Duration")
        self.move_forward_by_duration_action.triggered.connect(lambda: QApplication.postEvent(self, events.PauseEvent()))

        self.move_backward_by_duration_action.triggered.connect(
            lambda: QApplication.postEvent(self, events.ShiftLoopEvent(-self.move_by_duration_amount.value())))
        self.move_forward_by_duration_action.triggered.connect(
            lambda: QApplication.postEvent(self, events.ShiftLoopEvent(self.move_by_duration_amount.value())))

        self.move_backward_by_percentage_action = self.move_toolbar.addAction(icon("left_arrow.png"), "Move Selection Backward by Percentage")
        self.move_backward_by_percentage_action.triggered.connect(lambda: QApplication.postEvent(self, events.PauseEvent()))
        self.move_by_percentage_amount = QDoubleSpinBox()
        self.move_by_percentage_amount.setSuffix("%")
        self.move_by_percentage_amount.setMinimum(0.0)
        self.move_by_percentage_amount.setMaximum(100.0)
        self.move_toolbar.addWidget(self.move_by_percentage_amount)
        self.move_forward_by_percentage_action = self.move_toolbar.addAction(icon("right_arrow.png"), "Move Selection Forward by Percentage")
        self.move_forward_by_percentage_action.triggered.connect(lambda: QApplication.postEvent(self, events.PauseEvent()))

        self.move_backward_by_percentage_action.triggered.connect(
            lambda: self.on_shift_by_percent(-self.move_by_percentage_amount.value()))
        self.move_forward_by_percentage_action.triggered.connect(
            lambda: self.on_shift_by_percent(self.move_by_percentage_amount.value()))

        self.addToolBar(Qt.ToolBarArea.TopToolBarArea, self.move_toolbar)

        self.vertical_pitch_tracking_dock_widget = QDockWidget("Vertical Pitch Tracking")
        self.addDockWidget(Qt.DockWidgetArea.BottomDockWidgetArea, self.vertical_pitch_tracking_dock_widget)
        self.vertical_pitch_tracking_widget = VerticalPitchTrackingWidget(self.audio_player)
        self.vertical_pitch_tracking_dock_widget.setWidget(self.vertical_pitch_tracking_widget)

        fileMenu = self.menuBar().addMenu("File")
        self.openAction = fileMenu.addAction("Open...", QtGui.QKeySequence.StandardKey.Open)
        self.openAction.triggered.connect(self.open)
        self.importAction = fileMenu.addAction("Import From YouTube...", QtGui.QKeySequence("Ctrl+Y"))

        self.importAction.triggered.connect(self.import_from_youtube)

        viewMenu = self.menuBar().addMenu("View")
        self.zoomInAction = viewMenu.addAction("Zoom In", QtGui.QKeySequence.StandardKey.ZoomIn)
        self.zoomOutAction = viewMenu.addAction("Zoom Out", QtGui.QKeySequence.StandardKey.ZoomOut)

        toolsMenu = self.menuBar().addMenu("Tools")
        setPlaybackRateAction = toolsMenu.addAction("Set Playback Rate", QtGui.QKeySequence("Ctrl+R"))
        setPlaybackRateAction.triggered.connect(self.set_playback_rate)
        effectsAction = toolsMenu.addAction("Effects...", QtGui.QKeySequence("Ctrl+E"))
        effectsAction.triggered.connect(self.set_effects)

        self.timer = QTimer()
        self.timer.start(15)
        self.timer.timeout.connect(self.handle_key_presses)

        self.main_view = MainView(self.audio_player, self.openAction, self.importAction, self)
        self.zoomInAction.triggered.connect(self.main_view.zoom_in)
        self.zoomOutAction.triggered.connect(self.main_view.zoom_out)
        self.setCentralWidget(self.main_view)

        self.setFocus()

    def is_key_pressed(self, key):
        return key in self.key_pressed and self.key_pressed[key]

    def handle_key_presses(self):
        if self.audio_player.ready and not self.audio_player.playing:

            if self.is_key_pressed(Qt.Key.Key_D):
                if self.is_key_pressed(Qt.Key.Key_Shift):
                    self.audio_player.set_current_timestamp(self.audio_player.current_timestamp + 0.1)
                else:
                    self.audio_player.set_current_timestamp(self.audio_player.current_timestamp + 0.01)

            if self.is_key_pressed(Qt.Key.Key_A):
                if self.is_key_pressed(Qt.Key.Key_Shift):
                    self.audio_player.set_current_timestamp(self.audio_player.current_timestamp - 0.1)
                else:
                    self.audio_player.set_current_timestamp(self.audio_player.current_timestamp - 0.01)

            if self.main_view != None:
                if self.is_key_pressed(Qt.Key.Key_E):
                    if self.is_key_pressed(Qt.Key.Key_Shift):
                        self.main_view.audio_view.audio_waveform_scene.shift_loop(0.1)
                    else:
                        self.main_view.audio_view.audio_waveform_scene.shift_loop(0.01)
                if self.is_key_pressed(Qt.Key.Key_Q):
                    if self.is_key_pressed(Qt.Key.Key_Shift):
                        self.main_view.audio_view.audio_waveform_scene.shift_loop(-0.1)
                    else:
                        self.main_view.audio_view.audio_waveform_scene.shift_loop(-0.01)

    def on_shift_by_percent(self, percent):
        if self.main_view.audio_view is not None:
            width = self.main_view.audio_view.audio_waveform_scene.loop_end - self.main_view.audio_view.audio_waveform_scene.loop_start
            amount = width * percent / 100.0
            QApplication.postEvent(self, events.ShiftLoopEvent(amount))

    def on_submit_range_selection(self):
        try:
            start_second = utils.get_duration_in_seconds(self.range_start_widget.text())
            end_second = utils.get_duration_in_seconds(self.range_end_widget.text())
            if end_second < start_second:
                end_second = start_second
            event = events.SetLoopEvent(start_second, end_second)
            QApplication.postEvent(self, event)
            self.setFocus()
        except ValueError:
            return

    def on_set_loop_changed(self, state):
        enabled = False
        if state == Qt.CheckState.Checked.value:
            enabled = True
        event = events.SetLoopConfiguration(enabled)
        QApplication.postEvent(self, event)

    def open(self):
        (path, result) = QFileDialog.getOpenFileName(None, "Open Audio File", "music", "Audio Files (*.mp4)");
        if not result:
            return
        self.load(path)

    def import_from_youtube(self):
        (url, result) = QInputDialog.getText(None, "Import From YouTube", "YouTube URL:")
        if not result:
            return
        if not os.path.exists("music"):
            os.makedirs("music")
        path = YouTube(url).streams.filter(file_extension='mp4').get_highest_resolution().download(output_path="music")
        self.load(path)

    def load(self, path):
        self.audio_data, sampling_rate = librosa.load(path, sr=None, mono=False)
        self.audio_player.set_audio_state(self.audio_data, sampling_rate, 1.0)
        self.main_view.show_audio(self.audio_data, self.on_loop_change)
        self.vertical_pitch_tracking_widget.set_audio_data(self.audio_data, sampling_rate)

    def on_loop_change(self, loop_start, loop_end):
        self.audio_player.set_start_timestamp(loop_start)
        self.audio_player.set_end_timestamp(loop_end)
        self.range_start_widget.setText(utils.seconds_to_time_str(loop_start))
        self.range_end_widget.setText(utils.seconds_to_time_str(loop_end))

    def set_playback_rate(self):
        (rate, _) = QInputDialog.getDouble(None, "Set Playback Rate", "Rate", value=1.0)
        # todo: handle the waiting period gracefully
        new_data = librosa.effects.time_stretch(y=self.audio_data, rate=rate)
        self.audio_player.set_audio_state(new_data, self.audio_player.audio_state.sampling_rate, rate)

    def set_effects(self):
        effects_dialog = EffectsDialog(self.play_rate, self.harmonic_only)
        result = effects_dialog.exec()
        if result == 1:
            self.play_rate = effects_dialog.rate_input.value()
            self.harmonic_only = effects_dialog.harmonic_checkbox.isChecked()
            new_data = self.audio_data
            if abs(self.play_rate- 1) > 0.01:
                new_data = librosa.effects.time_stretch(y=self.audio_data, sr=self.play_rate)
            if self.harmonic_only:
                new_data = librosa.effects.harmonic(y=new_data)
            self.audio_player.set_audio_state(new_data, self.audio_player.audio_state.sampling_rate, self.play_rate)
            self.vertical_pitch_tracking_widget.set_audio_data(self.audio_data, self.audio_player.audio_state.sampling_rate)

    def keyReleaseEvent(self, a0: QtGui.QKeyEvent) -> None:
        self.key_pressed[a0.key()] = False
        return super().keyReleaseEvent(a0)

    def keyPressEvent(self, a0: QtGui.QKeyEvent) -> None:
        self.key_pressed[a0.key()] = True
        if not self.audio_player.ready:
            return super().keyPressEvent(a0)
        if a0.key() == Qt.Key.Key_Space:
            if self.audio_player.playing:
                QApplication.postEvent(self, events.PauseEvent())
            else:
                QApplication.postEvent(self, events.PlayEvent())
        return None

    def customEvent(self, event: QEvent):
        if event.type() == events.SetLoopEvent.TYPE:
            if not self.audio_player.playing and self.main_view.audio_view is not None:
                self.main_view.audio_view.audio_waveform_scene.set_loop(event.get_start(), event.get_end())
            return

        elif event.type() == events.ShiftLoopEvent.TYPE:
            if not self.audio_player.playing and self.main_view.audio_view is not None:
                self.main_view.audio_view.audio_waveform_scene.shift_loop(event.get_amount())
            return
        elif event.type() == events.PlayEvent.TYPE:
            if self.audio_player.audio_state is not None and not self.audio_player.playing:
                if self.start_from_beginning_checkbox.isChecked():
                    self.audio_player.set_current_timestamp(self.audio_player.start_timestamp)
                self.audio_player.play()
            return
        elif event.type() == events.PauseEvent.TYPE:
            self.audio_player.stop()
            return
        elif event.type() == events.BackEvent.TYPE:
            if self.main_view.audio_view is not None:
                if self.audio_player.playing:
                    self.audio_player.stop()
                    self.audio_player.set_current_timestamp(self.audio_player.start_timestamp)
                    self.audio_player.play()
                else:
                    self.audio_player.set_current_timestamp(self.main_view.audio_view.audio_waveform_scene.loop_start)
        elif event.type() == events.SetLoopConfiguration.TYPE:
            self.audio_player.set_loop(event.get_loop_enabled())
        return super().customEvent(event)


import socket
import threading
import time

def handle_client(client_socket):
    while True:
        try:
            data = client_socket.recv(1024).decode('utf-8')
            if not data:
                break
            print(f"Клієнт говорить: {data}")
            print(f"Час отримання: {time.strftime('%H:%M:%S')}")

            if data.lower() == "завершити":
                print("Завершення з'єднання з клієнтом")
                break
        except Exception as e:
            print(f"Помилка обробки даних від клієнта: {e}")
            break

    client_socket.close()

server_ip = '127.0.0.1'
server_port = 1234

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((server_ip, server_port))
server_socket.listen(1)

print(f"Сервер слухає на {server_ip}:{server_port}")

try:
    while True:
        client_socket, client_address = server_socket.accept()
        print(f"Новий клієнт підключився: {client_address}")

        # Запуск окремого потоку для обробки клієнта
        client_handler = threading.Thread(target=handle_client, args=(client_socket,))
        client_handler.start()

except KeyboardInterrupt:
    print("Сервер було відключено користувачем.")

finally:
    server_socket.close()


# Implemente um programa que calcule o ano de nascimento de uma pessoa a partir de suaidade atual.
import datetime
valid_input = False
while not valid_input :
    try:
        age_input = int(input("Qual sua idade? ").strip())
    except ValueError:
        print("Valor inválido! Tente novamente")
        valid_input = False
    else:
        currentTime = datetime.datetime.now()
        currentYear = currentTime.year
        print(f"Você nasceu no ano de: {currentYear - age_input} ")


# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from django.conf.urls import include, patterns, url
from django.http import HttpResponse

urlpatterns = patterns('',
    (r'', include('django_browserid.urls')),
    url(r'^epic-fail/', lambda r: HttpResponse('this is a stub'),
        name='epic_fail'),
    url(r'^some-dummy-url/', lambda r: HttpResponse('this is a stub'),
        name='test_url'),
)


input1=input('inserire un numero tra 1 e 12:')
x=int(input1)

input2=input('inserire giorno:')
y=int(input2)
if x<1 or x > 12:
    print('numero inserito non valido:')

else:
    if x>=1 and x<=3:
        if x ==3 and y>20:
            print('Primavera')
        else:
            print('Inverno')
    elif x>=4 and x<=6:
        if x == 6 and y>21:
            print('Estate')
        else:
            print('Primavera')
    elif x>=7 and x<=9:
        if x==9 and y>23:
            print('Autunno')
        else:
            print('Estate')
    elif x>=10 and x<=12:
        if x==12 and y>20:
            print('Inverno')
        else:
            print('Autunno')


import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from math import sqrt
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from eda_helper import (
    sliding_windows,
    preprocess_data,
    get_custom_palette,
    get_custom_colormap,
)

# Constants
COMPLETENESS_THRESHOLD = 1
WINDOW_SIZE = 12
HORIZON = 3
STRIDE = 1
INPUT_INDEX = 0
TARGET_INDEX = 0
BATCH_SIZE = 8
EPOCHS = 5
ERROR_STD = 4
DATA_PATH = "C:\#code\#python\#current\mres-project\data\saville_row_east_west"
OUTPUT_TABLES_PATH = "../output/tables/4/"
OUTPUT_FIGURES_PATH = "../output/figures/4/"

torch.manual_seed(42)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Set fonts and style for matplotlib
FONT_NAME = "Derailed"
plt.rcParams["font.family"] = "sans-serif"
plt.rcParams["font.sans-serif"] = FONT_NAME
plt.rcParams["axes.unicode_minus"] = False

os.makedirs(DATA_PATH, exist_ok=True)
os.makedirs(OUTPUT_TABLES_PATH, exist_ok=True)
os.makedirs(OUTPUT_FIGURES_PATH, exist_ok=True)

custom_palette = get_custom_palette()
custom_colormap = get_custom_colormap()

def load_data():
    """
    Loads the east and west dataframes from pickled files.

    Returns:
        tuple: A tuple containing two dataframes:
            - east_df (pd.DataFrame): Dataframe for the east data.
            - west_df (pd.DataFrame): Dataframe for the west data.

    Note:
        The paths to the pickled files are assumed to be constructed using
        a global DATA_PATH variable and the respective filenames.
    """
    east_df = pd.read_pickle(os.path.join(DATA_PATH, "east_df.pkl"))
    west_df = pd.read_pickle(os.path.join(DATA_PATH, "west_df.pkl"))
    return east_df, west_df

def compute_performance_metrics(predictions, targets):
    """
    Compute common performance metrics for regression.

    Parameters:
        - predictions (torch.Tensor): The predicted values.
        - targets (torch.Tensor): The true target values.

    Returns:
        dict: A dictionary containing the following metrics:
            - MAE (float): Mean Absolute Error.
            - MSE (float): Mean Squared Error.
            - RMSE (float): Root Mean Squared Error.
            - R^2 (float): R squared or Coefficient of Determination.

    Note:
        The function assumes the predictions and targets are torch tensors.
        They are then flattened and detached before computation.
    """
    predictions_flat_np = predictions.view(-1).detach().cpu().numpy()
    targets_flat_np = targets.view(-1).detach().cpu().numpy()

    return {
        "MAE": mean_absolute_error(targets_flat_np, predictions_flat_np),
        "MSE": mean_squared_error(targets_flat_np, predictions_flat_np),
        "RMSE": np.sqrt(mean_absolute_error(targets_flat_np, predictions_flat_np)),
        "R^2": r2_score(targets_flat_np, predictions_flat_np),
    }

class BaselineModel(nn.Module):
    """
    A simple baseline model that returns the last element from each input sequence.
    This model acts as a naive predictor, taking the most recent data point as its prediction.
    """

    def forward(self, x):
        """
        Forward pass of the BaselineModel.

        Args:
            x (torch.Tensor): Input tensor with sequences.
                              Expected shape: [batch_size, sequence_length, feature_dim].

        Returns:
            torch.Tensor: Predictions tensor containing the last element from each sequence.
                          Shape: [batch_size, feature_dim].
        """
        return x[:, -1]  # Get the last element from each input sequence

class LSTMModel(nn.Module):
    """
    LSTM-based model for time series prediction. Suitable for both univariate and multivariate time series.

    Args:
        feature_dim (int): The number of expected features in the input `x`.
        hidden_size (int, optional): The number of features in the hidden state. Default: 50.
        output_dim (int, optional): Number of features in the output. Default: 1.
        num_layers (int, optional): Number of recurrent layers. Default: 1.
    """

    def __init__(self, feature_dim, hidden_size=50, output_dim=1, num_layers=1):
        super().__init__()
        self.lstm = nn.LSTM(feature_dim, hidden_size, num_layers, batch_first=True)
        self.linear = nn.Linear(hidden_size, output_dim)

    def forward(self, x):
        """
        Forward pass of the LSTMModel.

        Args:
            x (torch.Tensor): Input tensor with sequences.
                              Expected shape: [batch_size, sequence_length, feature_dim].

        Returns:
            torch.Tensor: Predictions tensor, taking the last output from the LSTM sequence.
                          Shape: [batch_size, output_dim].
        """
        x, _ = self.lstm(x)
        x = self.linear(x)
        return x[:, -1, :]  # Selecting the last output of the sequence

class TimeSeriesDataset(Dataset):
    """
    A custom Dataset for time series data.

    Args:
        sequences (torch.Tensor): Input sequences for the dataset.
                                  Shape: [num_samples, sequence_length, feature_dim].
        targets (torch.Tensor): Corresponding targets for the input sequences.
                                Shape: [num_samples, feature_dim].
    """

    def __init__(self, sequences, targets):
        self.sequences = sequences
        self.targets = targets

    def __len__(self):
        """
        Returns the number of samples in the dataset.

        Returns:
            int: Total number of samples in the dataset.
        """
        return len(self.sequences)

    def __getitem__(self, index):
        """
        Fetches the sequence and target at a particular index.

        Args:
            index (int): The index to retrieve the data from.

        Returns:
            tuple: A tuple containing:
                - sequence (torch.Tensor): Input sequence of shape [sequence_length, feature_dim].
                - target (torch.Tensor): Corresponding target of shape [feature_dim].
        """
        return self.sequences[index], self.targets[index]

def train_lstm_model(lstm_model, train_dataloader, test_dataloader, epochs=50, lr=0.01):
    # Define loss function and optimizer
    criterion = nn.MSELoss()
    optimizer = optim.Adam(lstm_model.parameters(), lr=lr)
    scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.9)

    train_metrics = []
    test_metrics = []

    # Training loop
    for epoch in range(EPOCHS):
        train_MSE, train_RMSE = 0, 0
        lstm_model.train()

        # Training phase
        for X, y in train_dataloader:
            # Prepare data and move to device
            X = X.unsqueeze(-1).float().to(device)
            y = y.unsqueeze(-1).unsqueeze(-1).float().to(device)

            # Model prediction and loss calculation
            train_preds = train_MSE(X)
            loss_MSE = criterion(train_preds.unsqueeze(dim=-1), y)

            # Backpropagation and optimization
            optimizer.zero_grad()
            loss_MSE.backward()
            optimizer.step()

            # Accumulate loss for metrics
            train_MSE += loss_MSE.item()
            train_RMSE += sqrt(loss_MSE.item())

        # Calculate average loss
        train_MSE /= len(train_dataloader)
        train_RMSE /= len(train_dataloader)
        train_metrics.append([epoch, train_MSE, train_RMSE])

        test_MSE, test_RMSE = 0, 0
        train_MSE.eval()

        # Evaluation phase
        with torch.no_grad():
            for X, y in test_dataloader:
                # Prepare data and move to device
                X = X.unsqueeze(-1).float().to(device)
                y = y.unsqueeze(-1).unsqueeze(-1).float().to(device)

                # Model prediction and loss calculation
                test_preds = train_MSE(X)
                loss_MSE = criterion(test_preds.unsqueeze(dim=-1), y)

                # Accumulate loss for metrics
                test_MSE += loss_MSE.item()
                test_RMSE += sqrt(loss_MSE.item())

        # Calculate average loss
        test_MSE /= len(test_dataloader)
        test_RMSE /= len(test_dataloader)
        test_metrics.append([epoch, test_MSE, test_RMSE])

        # Print progress every 5 epochs
        if epoch % 5 == 4:
            print(
                f"Epoch: {epoch+1} | Train MSE: {train_MSE:.5f} | Train RMSE: {train_RMSE:.5f} | Test MSE: {test_MSE:.5f} | Test RMSE: {test_RMSE:.5f}"
            )

        # Adjust learning rate
        scheduler.step()

    return train_metrics, test_metrics

def main():
    # Load and preprocess data
    east_df, _ = load_data()
    east_dict = preprocess_data(east_df, COMPLETENESS_THRESHOLD)
    east_timeseries = east_dict["data"]

    # Extract input and target sequences
    inputs, targets = sliding_windows(
        east_timeseries, WINDOW_SIZE, INPUT_INDEX, TARGET_INDEX, HORIZON, STRIDE
    )

    # Baseline Model Evaluation
    baseline_model = BaselineModel()
    baseline_predictions = baseline_model(inputs.squeeze())
    metrics = compute_performance_metrics(baseline_predictions, targets)
    metrics["Model"] = "Baseline"
    performance_df = pd.DataFrame([metrics])

    # Setup LSTM Model
    model = LSTMModel().to(device)
    train_size = int(0.8 * len(inputs))
    train_inputs, test_inputs = inputs[:train_size], inputs[train_size:]
    train_targets, test_targets = targets[:train_size], targets[train_size:]
    train_dataset = TimeSeriesDataset(train_inputs, train_targets)
    test_dataset = TimeSeriesDataset(test_inputs, test_targets)
    train_dataloader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=False)
    test_dataloader = DataLoader(test_dataset, batch_size=BATCH_SIZE, shuffle=False)

    # Train LSTM model and get metrics
    train_metrics, test_metrics = train_lstm_model(
        model, train_dataloader, test_dataloader
    )
    train_metrics_df = pd.DataFrame(train_metrics, columns=["Epoch", "MSE", "RMSE"])
    test_metrics_df = pd.DataFrame(test_metrics, columns=["Epoch", "MSE", "RMSE"])
    print("LSTM Train Metrics")
    print(train_metrics_df.iloc[::5].round(3))
    print()
    print("LSTM Test Metrics")
    print(test_metrics_df.round(3))

    # Prediction and Error Calculation
    model.eval()
    with torch.no_grad():
        predictions = model(inputs.to(device).unsqueeze(dim=-1).float())
    errors = (predictions.squeeze(dim=-1) - targets.squeeze(dim=-1)).abs().numpy()

    lstm_predictions = model(inputs.to(device).unsqueeze(dim=-1).float())
    metrics = compute_performance_metrics(lstm_predictions, targets)
    metrics["Model"] = "LSTM"
    metrics_df = pd.DataFrame([metrics])  # Convert metrics to a DataFrame
    performance_df = pd.concat([performance_df, metrics_df], ignore_index=True)
    print(performance_df.round(3))

    # Calculate anomaly threshold based on error statistics
    threshold = errors.mean() + ERROR_STD * errors.std()

    # Detect anomalies based on error threshold
    anomalies = errors > threshold
    total_anomalies = np.sum(anomalies)
    time = np.arange(len(inputs))
    anomaly_times = time[anomalies]
    anomaly_values = targets[anomalies]

    # Focus on a specific time range for visualization
    anomalies_in_range = (anomaly_times > 300) & (anomaly_times < 500)
    anomaly_times_in_range = anomaly_times[anomalies_in_range]
    anomalies_values_in_range = anomaly_values[anomalies_in_range]

    # Visualize predictions, targets, and anomalies
    plt.figure(figsize=(10, 5))
    plt.plot(
        time[300:500],
        targets[300:500],
        label="Targets",
        linewidth=1,
        color=custom_palette[0],
    )
    plt.plot(
        time[300:500],
        predictions.numpy()[300:500],
        linewidth=1,
        label="Predicted data",
        color=custom_palette[1],
    )
    plt.scatter(
        anomaly_times_in_range,
        anomalies_values_in_range,
        label="Anomalies",
        color=custom_palette[7],
        marker=7,
        s=30,
        zorder=3,
    )
    plt.grid(True, which="both", linestyle="--", linewidth=0.5)
    plt.ylabel("Scaled value")
    plt.xlabel("Timestep")
    plt.title(
        f"Total anomalies: {total_anomalies} | Anomaly percentage: {(total_anomalies / len(targets))*100:.3f}% | Anomaly threshold: {ERROR_STD}$\sigma$"
    )
    plt.legend()
    plt.show()

if __name__ == "__main__":
    main()


import functools

from django.db import connections, migrations

def get_type_oids(connection_alias, type_name):
    # From: https://github.com/django/django/blob/main/django/contrib/postgres/signals.py
    with connections[connection_alias].cursor() as cursor:
        cursor.execute("SELECT oid, typarray FROM pg_type WHERE typname = %s", (type_name,))
        oids = []
        array_oids = []
        for row in cursor:
            oids.append(row[0])
            array_oids.append(row[1])
        return tuple(oids), tuple(array_oids)

@functools.lru_cache
def get_integer_pint_field_oids(connection_alias):
    """Return field and field array OIDs."""
    return get_type_oids(connection_alias, "integer_pint_field")

@functools.lru_cache
def get_big_integer_pint_field_oids(connection_alias):
    """Return field and field array OIDs."""
    return get_type_oids(connection_alias, "big_integer_pint_field")

@functools.lru_cache
def get_decimal_pint_field_oids(connection_alias):
    """Return field and field array OIDs."""
    return get_type_oids(connection_alias, "decimal_pint_field")

def clear_oids(apps, schema_editor):
    # Clear cached, stale oids.
    get_integer_pint_field_oids.cache_clear()
    get_big_integer_pint_field_oids.cache_clear()
    get_decimal_pint_field_oids.cache_clear()

class Migration(migrations.Migration):
    dependencies = []

    operations = [
        migrations.RunSQL(
            sql=[
                ("DROP TYPE IF EXISTS integer_pint_field CASCADE;"),
                ("DROP TYPE IF EXISTS big_integer_pint_field CASCADE;"),
                ("DROP TYPE IF EXISTS decimal_pint_field CASCADE;"),
                ("CREATE TYPE integer_pint_field AS (comparator decimal, magnitude integer, units text);"),
                ("CREATE TYPE big_integer_pint_field as (comparator decimal, magnitude bigint, units text);"),
                ("CREATE TYPE decimal_pint_field as (comparator decimal, magnitude decimal, units text);"),
            ],
            reverse_sql=[
                ("DROP TYPE IF EXISTS integer_pint_field CASCADE;"),
                ("DROP TYPE IF EXISTS big_integer_pint_field CASCADE;"),
                ("DROP TYPE IF EXISTS decimal_pint_field CASCADE;"),
            ],
        ),
        migrations.RunPython(clear_oids),
    ]


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os

import tensorflow as tf

# Global constants describing the CIFAR data set.
IMAGE_HEIGHT = 32
IMAGE_WIDTH = 32
NUM_CHANNEL = 3

def get_ds_from_tfrecords(data_dir,
                          split,
                          data_aug=True,
                          batch_size=100,
                          epochs=None,
                          shuffle=True,
                          data_format="channels_first",
                          num_parallel_calls=12,
                          prefetch=0,
                          div255=True,
                          dtype=tf.float32):
  """Returns a tf.train.Dataset object from reading tfrecords.

  Args:
      data_dir: Directory of tfrecords
      split: "train", "validation", or "test"
      data_aug: Apply data augmentation if True
      batch_size: Batch size of dataset object
      epochs: Number of epochs to repeat the dataset; default `None` means
          repeating indefinitely
      shuffle: Shuffle the dataset if True
      data_format: `channels_first` or `channels_last`
      num_parallel_calls: Number of threads for dataset preprocess
      prefetch: Buffer size for prefetch
      div255: Divide the images by 255 if True
      dtype: Data type of images
  Returns:
      A tf.train.Dataset object

  Raises:
      ValueError: Unknown split
  """

  if split not in ["train", "validation", "test", "train_all"]:
    raise ValueError("Unknown split {}".format(split))

  def _parser(serialized_example):
    """Parses a single tf.Example into image and label tensors."""
    features = tf.parse_single_example(
        serialized_example,
        features={
            "image": tf.FixedLenFeature([], tf.string),
            "label": tf.FixedLenFeature([], tf.int64),
        })
    image = tf.decode_raw(features["image"], tf.uint8)
    # Initially reshaping to [H, W, C] does not work
    image = tf.reshape(image, [NUM_CHANNEL, IMAGE_HEIGHT, IMAGE_WIDTH])
    # This is needed for `tf.image.resize_image_with_crop_or_pad`
    image = tf.transpose(image, [1, 2, 0])

    image = tf.cast(image, dtype)
    label = tf.cast(features["label"], tf.int32)

    if data_aug:
      image = tf.image.resize_image_with_crop_or_pad(image, IMAGE_HEIGHT + 4,
                                                     IMAGE_WIDTH + 4)
      image = tf.random_crop(image, [IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNEL])
      image = tf.image.random_flip_left_right(image)

    if data_format == "channels_first":
      image = tf.transpose(image, [2, 0, 1])

    if div255:
      image /= 255.

    return image, label

  filename = os.path.join(data_dir, split + ".tfrecords")
  dataset = tf.data.TFRecordDataset(filename)
  dataset = dataset.repeat(epochs)
  dataset = dataset.map(_parser, num_parallel_calls=num_parallel_calls)
  dataset = dataset.prefetch(prefetch)

  if shuffle:
    # Find the right size according to the split
    size = {
        "train": 40000,
        "validation": 10000,
        "test": 10000,
        "train_all": 50000
    }[split]
    dataset = dataset.shuffle(size)

  dataset = dataset.batch(batch_size, drop_remainder=True)

  return dataset


with open('input.txt') as f:
    turns = [turn.split(' ') for turn in f.read().splitlines()]

wins = [
    ('C', 'X'),
    ('A', 'Y'),
    ('B', 'Z')
]

draw = [
    ('A', 'X'),
    ('B', 'Y'),
    ('C', 'Z')
]

points = {
    'X': 1,
    'Y': 2,
    'Z': 3
}

win_draw_lose = {
    'X': 'lose',
    'Y': 'draw',
    'Z': 'win'
}

find_choice = {
    'win': {'C': 'X',
            'A': 'Y',
            'B': 'Z'},

    'draw': {'A': 'X',
             'B': 'Y',
             'C': 'Z'},

    'lose': {'A': 'Z',
             'B': 'X',
             'C': 'Y'}
}

scores = {
    'win': 6,
    'draw': 3,
    'lose': 0
}

def Q1(turns):
    counter = 0
    for turn in turns:
        opponent, me = turn
        counter += points[me]

        if (opponent, me) in wins:
            counter += 6

        elif (opponent, me) in draw:
            counter += 3

    return counter

def Q2(turns):
    counter = 0
    for turn in turns:
        opponent, me = turn
        strat = win_draw_lose[me]
        choice_points = points[find_choice[strat][opponent]]
        w_d_l = scores[strat]
        counter += choice_points + w_d_l

    return counter

if __name__ == '__main__':
    print(Q1(turns))
    print(Q2(turns))


from code import interact
import sys
import textwrap

log = __import__('logging').getLogger(__name__)

def make_default_shell(interact=interact):
    def shell(env, help):
        cprt = 'Type "help" for more information.'
        banner = 'Python %s on %s\n%s' % (sys.version, sys.platform, cprt)
        banner += '\n\n' + help + '\n'
        interact(banner, local=env)
    return shell

def make_ipython_shell(IPShellFactory=None):
    try:
        import IPython
        IPShellFactory = IPython.start_ipython
    except ImportError:
        return None

    def shell(env, help):
        from traitlets.config import Config
        c = Config()
        c.TerminalInteractiveShell.banner2 = help + '\n'
        IPShellFactory(argv=[], user_ns=env, config=c)
    return shell

def main(cli, args):
    import sqlalchemy
    import transaction
    from drive import model
    from drive.model.meta.session import get_tm_session

    tm = transaction.TransactionManager(explicit=True)
    dbmaker = cli.dbmaker

    env = {
        'cli': cli,
        'sa': sqlalchemy,
        'tm': tm,
        'model': model,
        'dbmaker': dbmaker,
        'db': get_tm_session(dbmaker, transaction_manager=tm),
    }

    help = textwrap.dedent(
        """
        Environment:
          model           drive.model    (import drive.model as model)
          sa              sqlalchemy         (import sqlalchemy as sa)
          cli             The CLI application.
          dbmaker         database session maker (unbound)
          db              database session (bound to tm)
          tm              transaction manager
        """).strip()

    shell = None
    user_shell = args.python_shell.lower()

    if not user_shell:
        shell = make_ipython_shell()
        if shell is None:
            shell = make_default_shell()

    elif user_shell == 'ipython':
        shell = make_ipython_shell()

    elif user_shell == 'python':
        shell = make_default_shell()

    if shell is None:
        log.warn('failed to find requested shell "%s", using default',
                 user_shell)
        shell = make_default_shell()

    with tm:
        shell(env, help)


'''
date : 0415
idea : 그리디 알고리즘
'''
n = int(input())

ans = 0
for i in sorted(list(map(int, input().split()))):
    if ans + 1 < i: break
    ans += i

print(ans+1)

코딩 테스트 준비 - 연습/브루트 포스 - 재귀/14225.py


from indico_toolkit.association import LineItems
from indico_toolkit.indico_wrapper import Workflow
from tests.conftest import MODEL_NAME

def test_workflow_submit_and_get_rows(indico_client, workflow_id, pdf_filepath):
    """
    Submit a document to workflow, get results and ocr object, then association line items
    """
    wflow = Workflow(indico_client)
    sub_ids = wflow.submit_documents_to_workflow(
        workflow_id=workflow_id, pdf_filepaths=[pdf_filepath]
    )
    wflow.wait_for_submissions_to_process(sub_ids)
    sub_result = wflow.get_submission_results_from_ids([sub_ids[0]])[0]
    litems = LineItems(
        sub_result.predictions.to_list(),
        ["Previous Position", "Previous Organization"],
    )
    ondoc_ocr = wflow.get_ondoc_ocr_from_etl_url(sub_result.etl_url)
    litems.get_bounding_boxes(ocr_tokens=ondoc_ocr.token_objects)
    litems.assign_row_number()
    for pred in litems.updated_predictions.to_list():
        if pred["label"] in ["Previous Position", "Previous Organization"]:
            assert "row_number" in pred


from flask import Blueprint, request
from werkzeug.exceptions import NotFound

from database import db
from exceptions import ValidationError
from models import Product
from utils import validation
from utils.auth import auth_required

products = Blueprint('products', __name__)

@products.route('/products')
@auth_required
def index():
    products = db.session.scalars(db.select(Product)).all()

    return [product.to_dict() for product in products]

@products.route('/products', methods=['POST'])
@auth_required
def create():
    data = request.get_json()

    errors = validation.validate(Product.validations, data)

    if errors:
        raise ValidationError({'fields': errors})

    product = Product(
        name=data['name'],
        price=data['price']
    )

    db.session.add(product)
    db.session.commit()

    return product.to_dict()

@products.route('/products/<id>')
@auth_required
def show(id):
    product = db.session.scalar(db.select(Product).filter_by(id=id))

    if product is None:
        raise NotFound()

    return product.to_dict()

@products.route('/products/<id>', methods=['PATCH'])
@auth_required
def update(id):
    data = request.get_json()

    product = db.session.scalar(db.select(Product).filter_by(id=id))

    if product is None:
        raise NotFound()

    errors = validation.validate(Product.validations, data)

    if errors:
        raise ValidationError({'fields': errors})

    product.name = data.get('name', product.name)
    product.price = data.get('price', product.price)

    db.session.add(product)
    db.session.commit()

    return product.to_dict()

@products.route('/products/<id>', methods=['DELETE'])
@auth_required
def destroy(id):
    product = db.session.scalar(db.select(Product).filter_by(id=id))

    if product is None:
        raise NotFound()

    db.session.delete(product)
    db.session.commit()

    return 'Product deleted.'


from abc import abstractmethod
from typing import List, Dict, Union, Any
import sys
import os
from Lexer import runlexer
TAB = '  '  # two whitespaces

store = {}
class Node:
    def __init__(self, *args):
        self.height = int(args[0])  # the level of indentation required for current Node

    def __str__(self):
        return 'prog'

    @staticmethod
    def one_tab(line):
        """Formats the line of an argument from an expression."""
        return TAB + line + '\n'

    def final_print_str(self, print_str):
        """Adds height number of tabs at the beginning of every line that makes up the current Node."""
        return (self.height * TAB).join(print_str)

    @abstractmethod
    def accept(self, visitor):
        pass

class InstructionList(Node):
    """begin <instruction_list> end"""

    def __init__(self, *args):  # args = height, [Nodes in instruction_list]
        super().__init__(args[0])
        self.list = args[1]

    def __str__(self):
        print_str = ['[\n']
        for expr in self.list:
            print_str.append(self.one_tab(expr.__str__()))
        print_str.append(']')

        return self.final_print_str(print_str)
    def executa_instructiuni(self):
        for expr in self.list:
            visitor.visit(expr)
    def accept(self, visitor):
        return visitor.visit(self)

class Expr(Node):
    """<expr> + <expr> | <expr> > <expr> | <expr> == <expr> | <variable> | <integer>"""

    def __init__(self, *args):  # args = height, '+' | '>' | '==' | 'v' | 'i', left_side, *right_side
        super().__init__(args[0])
        self.type = args[1]
        self.left = args[2]
        if len(args) > 3:
            self.right = args[3]
        else:
            # variable and integer have no right_side
            self.right = None

    def __str__(self):
        name = 'expr'
        if self.type == 'v':
            name = 'variable'
        elif self.type == 'i':
            name = 'integer'
        elif self.type == '+':
            name = 'plus'
        elif self.type == '*':
            name = 'multiply'
        elif self.type == '-':
            name = 'minus'
        elif self.type == '>':
            name = 'greaterthan'
        elif self.type == '==':
            name = 'equals'

        print_str = [name + ' [\n', self.one_tab(str(self.left))]
        if self.right:
            print_str.append(self.one_tab(str(self.right)))
        print_str.append(']')

        return self.final_print_str(print_str)

    def get_variable(self) -> str:
       return self.left

    def get_expr(self) -> Union[int, Any]:
        if self.type == 'v':
            return store[self.left]
        if self.type == 'i':
            return int(self.left)
        if self.type == '+':
            suma = self.left.get_expr() + self.right.get_expr()
            return suma
        if self.type == '-':
            diferenta = self.left.get_expr() - self.right.get_expr()
            return diferenta
        if self.type == '*':
            produs = self.left.get_expr() * self.right.get_expr()
            return produs
        if self.type == '==':
            return self.left.get_expr() == self.right.get_expr()
        if self.type == '>':
            return self.left.get_expr() > self.right.get_expr()
    def accept(self, visitor):
        return visitor.visit(self)

class While(Node):
    """while (<expr>) do <prog> od"""

    def __init__(self, *args):  # args = height, Node_expr, Node_prog
        super().__init__(args[0])
        self.expr = args[1]
        self.prog = args[2]

    def __str__(self):
        print_str = ['while [\n',
                     self.one_tab(self.expr.__str__()),
                     self.one_tab('do ' + self.prog.__str__()),
                     ']']
        return self.final_print_str(print_str)
    def executa_while(self):
        while visitor.visit(self.expr) is True:
            visitor.visit(self.prog)
    def accept(self, visitor):
        return visitor.visit(self)

class If(Node):
    """if (<expr>) then <prog> else <prog> fi"""

    def __init__(self, *args):  # args = height, Node_expr, Node_then, Node_else
        super().__init__(args[0])
        self.expr = args[1]
        self.then_branch = args[2]
        self.else_branch = args[3]

    def __str__(self):
        print_str = ['if [\n',
                     self.one_tab(self.expr.__str__()),
                     self.one_tab('then ' + self.then_branch.__str__()),
                     self.one_tab('else ' + self.else_branch.__str__()),
                     ']']
        return self.final_print_str(print_str)

    def executa_conditie(self):
        if visitor.visit(self.expr) is True:
            visitor.visit(self.then_branch)
        else:
            visitor.visit(self.else_branch)

    def accept(self, visitor):
        return visitor.visit(self)

class Assign(Node):
    """<variable> '=' <expr>"""

    def __init__(self, *args):  # args = height, Node_variable, Node_expr
        super().__init__(args[0])
        self.variable = args[1]
        self.expr = args[2]

    def __str__(self):
        print_str = ['assign [\n',
                     self.one_tab(self.variable.__str__()),
                     self.one_tab(self.expr.__str__()),
                     ']']
        return self.final_print_str(print_str)
    def update_store(self):
        var = self.variable.get_variable()
        exp = int(visitor.visit(self.expr))
        store.update({var: exp})

    def accept(self, visitor):
        return visitor.visit(self)

class Visitor():
    """Abstract Vistor Class"""
    @abstractmethod
    def visit(self, item):
        pass
class CartVisitor(Visitor):
    def visit(self, item):
        if isinstance(item, Assign):
            item.update_store()
        if isinstance(item, Expr):
            return item.get_expr()
        if isinstance(item, InstructionList):
            return item.executa_instructiuni()
        if isinstance(item, If):
            return item.executa_conditie()
        if isinstance(item, While):
            return item.executa_while()

class NFA:
    def __init__(self, expr):
        if isinstance(expr, simbol):
            self.alphabet: List[str] = expr.x
            self.initialState: tuple = (0,)
            self.finalState: tuple = (1,)
            self.delta: Dict[tuple, Dict[str, tuple]] = {self.initialState: {self.alphabet[0]: self.finalState}}
            self.states = 2
        else:
            self.alphabet: List[str] = None
            self.initialState: tuple = None
            self.finalState: tuple = None
            self.delta: Dict[tuple, Dict[str, tuple]] = None
            self.states = 0

    def renumerotare(self, nr_stari: int) -> dict:
        x = self.delta
        z = {}
        for sursa in x.keys():
            for tranzitii in x[sursa].keys():
                if len(x[sursa][tranzitii]) > 1:
                    for i in range(0, len(x[sursa][tranzitii])):
                        x[sursa][tranzitii][i] = tuple(y + nr_stari for y in x[sursa][tranzitii][i])
                else:
                    x[sursa][tranzitii] = tuple(y + nr_stari for y in x[sursa][tranzitii])
            z[tuple(y + nr_stari for y in sursa)] = x[sursa]
        return z

    def epsilon_tranzitii(self, current_state: tuple, vizitat: List[tuple]) -> tuple:
        if type(current_state) is not tuple:
            current_state = (current_state,)
        states = current_state
        if current_state not in (self.delta.keys()) or 'ε' not in self.delta[current_state].keys() \
                or current_state in vizitat:
            return tuple(set(sorted(states)))
        else:
            vizitat.append(current_state)
            for state in self.delta[current_state]['ε']:
                states += self.epsilon_tranzitii(state, vizitat)
        return tuple(set(sorted(states)))

    def step(self, dfa_state: tuple, simbol: str) -> tuple:
        next_state = tuple()
        for x in dfa_state:
            if (x,) in (self.delta.keys()) and simbol in self.delta[(x,)].keys():
                nfa_step = self.delta[(x,)][simbol]
                next_state += self.epsilon_tranzitii(nfa_step, [])
        if next_state == ():
            next_state = ('S',)
        return tuple(set(sorted(next_state)))

class expr:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return str(self.x) + ' ' + str(self.y)

class star(expr):
    def __init__(self, x, y):
        super().__init__(x, y)

    def __str__(self):
        return 'STAR ' + str(self.x)

    def get_NFA(self) -> NFA:
        nfa = NFA(self)
        nfa1 = self.x.get_NFA()
        nfa.alphabet = nfa1.alphabet + 'ε'
        nfa.states = nfa1.states + 2
        nfa.initialState = (0,)
        nfa.finalState = (nfa.states - 1,)
        nfa.delta = {}
        nfa.delta.update({nfa.initialState: {'ε': [tuple(y + 1 for y in nfa1.initialState), nfa.finalState]}})
        nfa.delta.update(nfa1.renumerotare(1))
        nfa.delta.update({tuple(y + 1 for y in nfa1.finalState):
                              {'ε': [nfa.finalState, tuple(y + 1 for y in nfa1.initialState)]}})
        return nfa

class plus(expr):
    def __init__(self, x, y):
        super().__init__(x, y)

    def __str__(self):
        return 'PLUS ' + str(self.x)

    def get_NFA(self) -> NFA:
        nfa = NFA(self)
        nfa1 = self.x.get_NFA()
        nfa.alphabet = nfa1.alphabet + 'ε'
        nfa.states = nfa1.states + 2
        nfa.initialState = (0,)
        nfa.finalState = (nfa.states - 1,)
        nfa.delta = {}
        nfa.delta.update({nfa.initialState: {'ε': tuple(y + 1 for y in nfa1.initialState)}})
        nfa.delta.update(nfa1.renumerotare(1))
        nfa.delta.update({tuple(y + 1 for y in nfa1.finalState):
                              {'ε': [nfa.finalState, tuple(y + 1 for y in nfa1.initialState)]}})

        return nfa

class union(expr):
    def __init__(self, x, y):
        super().__init__(x, y)

    def __str__(self):
        return 'UNION ' + str(self.x) + ' ' + str(self.y)

    def get_NFA(self) -> NFA:
        nfa = NFA(self)
        nfa1 = self.x.get_NFA()
        nfa2 = self.y.get_NFA()
        nfa.alphabet = (nfa1.alphabet + nfa2.alphabet + 'ε')
        nfa.states = nfa1.states + nfa2.states + 2
        nfa.initialState = (0,)
        nfa.finalState = (nfa.states - 1,)
        nfa.delta = {}
        nfa.delta.update({nfa.initialState: {'ε': [tuple(y + 1 for y in nfa1.initialState),
                                                   tuple(y + nfa1.states + 1 for y in nfa2.initialState)]}})
        nfa.delta.update(nfa1.renumerotare(1))
        nfa.delta.update(nfa2.renumerotare(nfa1.states + 1))
        nfa.delta.update({tuple(y + 1 for y in nfa1.finalState): {'ε': nfa.finalState}})
        nfa.delta.update({tuple(y + nfa1.states + 1 for y in nfa2.finalState): {'ε': nfa.finalState}})
        return nfa

class concat(expr):
    def __init__(self, x, y):
        super().__init__(x, y)

    def __str__(self):
        return 'CONCAT ' + str(self.x) + ' ' + str(self.y)

    def get_NFA(self) -> NFA:
        nfa1 = self.x.get_NFA()
        nfa2 = self.y.get_NFA()
        nfa = NFA(self)
        nfa.alphabet = (nfa1.alphabet + nfa2.alphabet + 'ε')
        nfa.initialState = nfa1.initialState
        nfa.finalState = tuple(x + nfa1.states for x in nfa2.finalState)
        nfa.delta = nfa1.delta
        nfa.delta.update({nfa1.finalState: {'ε': tuple(y + nfa1.states for y in nfa2.initialState)}})
        nfa.delta.update(nfa2.renumerotare(nfa1.states))
        nfa.states = nfa1.states + nfa2.states
        return nfa

class simbol(expr):
    def __init__(self, x, y):
        super().__init__(x, y)

    def __str__(self):
        return str(self.x)

    def get_NFA(self) -> NFA:
        nfa = NFA(self)
        return nfa

class DFA:
    def __init__(self):
        self.alphabet: List[str] = None
        self.initialState: tuple = None
        self.finalStates: List[tuple] = []
        self.delta: Dict[tuple, Dict[str, tuple]] = {}
        self.renumerotare_stari: Dict[tuple, int] = {}
        self.stari: int = 0

    def generate_delta(self, current_state: tuple, nfa: NFA):
        if current_state not in self.renumerotare_stari.keys():
            self.renumerotare_stari.update({current_state: self.stari})
            self.stari += 1
        if nfa.finalState[0] in current_state and current_state not in self.finalStates:
            self.finalStates.append(current_state)
        for x in self.alphabet:
            next_state = nfa.step(current_state, x)
            if next_state == ('S',):
                if current_state in self.delta.keys():
                    self.delta[current_state].update({x: next_state})
                else:
                    self.delta.update({current_state: {x: next_state}})
                for y in self.alphabet:
                    if next_state in self.delta.keys():
                        self.delta[next_state].update({y: next_state})
                    else:
                        self.delta.update({next_state: {y: next_state}})
            elif current_state not in self.delta.keys() or x not in self.delta[current_state].keys() or \
                    self.delta[current_state][x] != next_state:
                if current_state in self.delta.keys():
                    self.delta[current_state].update({x: next_state})
                else:
                    self.delta.update({current_state: {x: next_state}})
                self.generate_delta(next_state, nfa)

    def NFA_to_DFA(self, nfa: NFA):
        self.alphabet = nfa.alphabet
        if 'ε' in self.alphabet:
            self.alphabet.remove('ε')
        self.initialState = nfa.epsilon_tranzitii((0,), [])
        self.generate_delta(self.initialState, nfa)

        if ('S',) in self.delta.keys():
            self.renumerotare_stari.update({('S',): self.stari})
            self.stari += 1

class DFA_simplificat:
    def __init__(self):
        self.alphabet: List[str] = None
        self.initialState: int = None
        self.finalStates: List[int] = []
        self.delta: Dict[int, Dict[str, int]] = {}
        self.stari: int = 0

    def simplifica_DFA(self, dfa: DFA):
        self.stari = dfa.stari
        self.alphabet = sorted(dfa.alphabet)
        self.initialState = dfa.renumerotare_stari[dfa.initialState]
        for x in dfa.finalStates:
            self.finalStates.append(dfa.renumerotare_stari[x])
        for sursa in dfa.delta.keys():
            for simbol in dfa.delta[sursa].keys():
                dest = dfa.renumerotare_stari[dfa.delta[sursa][simbol]]
                if dfa.renumerotare_stari[sursa] in self.delta.keys():
                    self.delta[dfa.renumerotare_stari[sursa]].update({simbol: dest})
                else:
                    self.delta.update({dfa.renumerotare_stari[sursa]: {simbol: dest}})

def afisare(dfa: DFA_simplificat, token:str, output: str):
    out = open(output, 'a')
    for x in dfa.alphabet:
        if x == '\n':
            out.write('\'' + '\\' + 'n' + '\'')
        else:
            out.write(x)
    out.write("\n")
    out.write(token + "\n")
    out.write(str(dfa.initialState) + "\n")
    for sursa in dfa.delta.keys():
        for simbol in dfa.delta[sursa].keys():
            dest = str(dfa.delta[sursa][simbol])
            if simbol == '\n':
                out.write(str(sursa) + ',' + '\'' + '\'' + '\\' + 'n' + '\'' + '\'' + ',' + dest + "\n")
            else:
                out.write(str(sursa) + ',' + '\'' + simbol + '\'' + ',' + dest + "\n")
    for x in dfa.finalStates:
        out.write(str(x) + " ")
    out.write("\n")
    out.write("\n")
    out.close()

def parsare(input: str) -> NFA:
    input = input.replace("   ","  ")
    lista = list(input.split(" "))
    if lista[len(lista) - 1] == '' and lista[len(lista) - 1] == '':
        lista.pop()
    expresii = ['CONCAT', 'UNION', 'STAR', 'PLUS']
    for i in range (0,len(lista)) :
        if lista[i] == '':
            lista[i] = ' '
    stack = []
    stack2 = []
    operanzi = 0
    operanzi_necesari = 0
    i = 0
    append = 0
    while append == 1 or i < len(lista):
        if append == 0:
            stack.append(lista[i])
            element = lista[i]
            i = i + 1
            if element not in expresii:
                stack2.append(simbol(element, None))
        else:
            element = stack[len(stack) - 1]

        if element == 'CONCAT' or element == 'UNION':
            operanzi_necesari = 2
            operanzi = 2
        elif element == 'STAR' or element == 'PLUS':
            operanzi_necesari = 1
            operanzi = 1
        elif element not in expresii:
            operanzi_necesari = operanzi_necesari - 1

        if operanzi_necesari == 0:
            if operanzi == 2:
                arg2 = stack.pop()
                arg1 = stack.pop()
                nume_expresie = stack.pop()
                expr2 = stack2.pop()
                expr1 = stack2.pop()
                if len(stack) > 0:
                    if stack[len(stack) - 1] not in expresii:
                        operanzi_necesari = 1
                        operanzi = 2
                    elif stack[len(stack) - 1] == 'CONCAT' or stack[len(stack) - 1] == 'UNION':
                        operanzi_necesari = 2
                        operanzi = 2
                    else:
                        operanzi_necesari = 1
                        operanzi = 1
                if nume_expresie == 'CONCAT':
                    stack.append(str(concat(arg1, arg2)))
                    stack2.append(concat(expr1, expr2))
                    append = 1
                elif nume_expresie == 'UNION':
                    stack.append(str(union(arg1, arg2)))
                    stack2.append(union(expr1, expr2))
                    append = 1
            else:
                arg1 = stack.pop()
                expr1 = stack2.pop()
                nume_expresie = stack.pop()
                if len(stack) > 0:
                    if stack[len(stack) - 1] not in expresii:
                        operanzi_necesari = 1
                        operanzi = 2
                    elif stack[len(stack) - 1] == 'CONCAT' or stack[len(stack) - 1] == 'UNION':
                        operanzi_necesari = 2
                        operanzi = 2
                    elif stack[len(stack) - 1] == 'STAR' or stack[len(stack) - 1] == 'PLUS':
                        operanzi_necesari = 1
                        operanzi = 1
                if nume_expresie == 'STAR':
                    stack.append(str(star(arg1, '')))
                    stack2.append(star(expr1, None))
                elif nume_expresie == 'PLUS':
                    stack.append(str(plus(arg1, '')))
                    stack2.append(plus(expr1, None))
                append = 1
        else:
            append = 0
    expr = stack2.pop()
    if str(expr) == '':
       expr = simbol(' ',None)
    nfa = expr.get_NFA()
    nfa.alphabet = set(nfa.alphabet)
    return nfa

def transf_in_prenex(regex: str) -> str:
    stack = []
    stack2 = []
    paranteze_deschise = 0
    parametrii = 2
    este_simbol = 0
    i = 0
    endline = 0
    lista = regex
    while i < len(lista):
        if lista[i] == '\'' and este_simbol == 1:
            este_simbol = 0
        elif lista[i] == '\'' and este_simbol == 0:
            este_simbol = 1
        if este_simbol == 1 and lista[i] != '\'' :
            if endline == 0 and lista[i] != "\\":
                stack.append(simbol(lista[i], None))
            if endline == 1:
                stack.append(simbol('\n', None))
                endline = 0
            if lista[i] == "\\":
                endline = 1
        if este_simbol == 0 and lista[i] != '\'':
            stack.append(lista[i])
        element = lista[i]
        if element == '(' and este_simbol == 0:
            paranteze_deschise += 1
        if element == ')' and este_simbol == 0:
            paranteze_deschise -= 1
            expr_intre_paranteze = []
            elem = stack.pop()
            while elem != '(':
                elem = stack.pop()
                if elem != '(':
                    expr_intre_paranteze.append(elem)
            if len(expr_intre_paranteze) == 1:
                stack.append(expr_intre_paranteze[0])
            if len(expr_intre_paranteze) == 2:
                stack.append(concat(expr_intre_paranteze[1], expr_intre_paranteze[0]))
            if len(expr_intre_paranteze) > 2:
                expr1 = expr_intre_paranteze[len(expr_intre_paranteze) - 1]
                j = len(expr_intre_paranteze) - 2
                while j >= 0:
                    if expr_intre_paranteze[j] == '|':
                        expr1 = union(expr1, expr_intre_paranteze[j - 1])
                        j -= 2
                    else:
                        expr1 = concat(expr1, expr_intre_paranteze[j])
                        j -= 1
                stack.append(expr1)

        if element == '+' and este_simbol == 0:
            arg1 = stack.pop()
            arg2 = stack.pop()
            stack.append(plus(arg2, None))
        if element == '*' and este_simbol == 0:
            arg1 = stack.pop()
            arg2 = stack.pop()
            stack.append(star(arg2, None))
        i += 1
    if len(stack) == 2:
        arg1 = stack.pop()
        arg2 = stack.pop()
        stack.append(concat(arg2, arg1))
    if len(stack) > 2:
        stack.reverse()
        expr = stack.pop()
        while stack:
            arg = stack.pop()
            if arg == '|':
                arg2 = stack.pop()
                expr = union(expr, arg2)
            else:
                expr = concat(expr, arg)
        stack.append(expr)
    return str(stack.pop())

def citire(fisier: str) -> list:
    with open(fisier, "r") as input:
        line = input.readlines()
    return line

def runcompletelexer(lexer: str, input:str, output:str):
    line = citire(lexer)
    tokens = []
    input_regex = []
    open("out", 'w').close()
    for i in range(0, len(line)):
        lista = line[i].split(' ', 1)
        tokens.append(lista[0])
        input_regex.append(lista[1].rstrip()[:-1])
    for i in range(0 ,len(tokens)):
        regex = transf_in_prenex(input_regex[i])
        nfa = parsare(regex)
        dfa = DFA()
        dfa.NFA_to_DFA(nfa)
        dfa_final = DFA_simplificat()
        dfa_final.simplifica_DFA(dfa)
        afisare(dfa_final, str(tokens[i]), "out")
    runlexer("out", input, output)
    open("out", 'w').close()

def runparser(fisier_input:str, fisier_output:str):
    open("tokens", 'w').close()
    runcompletelexer('specificatie.lex', fisier_input, 'tokens')
    with open('tokens', "r") as input:
        lines = input.readlines()
    stack = []
    indent = 0
    assigning = 0
    conditie = 0
    expresie_compusa = 0
    for x in lines:
        element = x.rstrip().split(' ', 1)
        if element[0] == 'KEYWORD':
            stack.append(element[1])
            if 'if' in element[1]:
                conditie = 1
                indent += 1
            if 'while' in element[1]:
                conditie = 1
                indent += 1
            if 'begin' in element[1]:
                indent += 1
            if 'then' in element[1] or 'do' in element[1]:
                conditie = 0
                arg_then = stack.pop()
                arg1 = stack.pop()
                arg2 = stack.pop()
                if expresie_compusa == 0:
                    arg3 = stack.pop()
                    stack.append(Expr(indent, arg2, arg3, arg1))
                else:
                    arg3 = stack.pop()
                    arg4 = stack.pop()
                    arg5 = stack.pop()
                    stack.append(Expr(indent, arg2,
                                      Expr(indent + 1, arg4, Expr(arg5.height + 1, arg5.type, str(arg5.left)),
                                           Expr(arg3.height + 1, arg3.type, str(arg3.left))), arg1))
                    expresie_compusa = 0
                stack.append(arg_then)
            if 'fi' in element[1]:
                lista_if = []
                elem = stack.pop()
                indent -= 1
                while 'if' not in str(elem):
                    lista_if.append(elem)
                    elem = stack.pop()
                if 'else' in lista_if:
                    stack.append(If(indent, lista_if[5], lista_if[3], lista_if[1]))
                else:
                    stack.append(If(indent, lista_if[3], lista_if[1]))
            if 'od' in element[1]:
                lista_do = []
                elem = stack.pop()
                indent -= 1
                while 'while' not in str(elem):
                    lista_do.append(elem)
                    elem = stack.pop()
                stack.append(While(indent, lista_do[3], lista_do[1]))
            if 'end' in element[1]:
                indent -= 1
                end = stack.pop()
                elem = stack.pop()
                lista_expresii = []
                while elem != 'begin':
                    lista_expresii.append(elem)
                    elem = stack.pop()
                lista_expresii.reverse()
                stack.append(InstructionList(indent, lista_expresii))

        if element[0] == 'COMPARATIE' or element[0] == 'OPERATIE':
            stack.append(element[1].split(' ')[1])
            if conditie == 1 and element[0] == 'OPERATIE':
                expresie_compusa = 1
        if element[0] == 'ASSIGN':
            assigning = 1
            stack.append(element[1].split(' ', 1)[0])
        if element[0] == 'INTEGER':
            stack.append(Expr(indent + 1, 'i', str(element[1])))
        if element[0] == 'VARIABLE':
            stack.append(Expr(indent + 1, 'v', str(element[1])))
        if element[0] == 'NEWLINE':
            if assigning == 1:
                arg1 = stack.pop()
                arg2 = stack.pop()
                if arg2 in ['+', '-', '*']:
                    arg3 = stack.pop()
                    arg4 = stack.pop()
                    stack.append(Assign(indent, Expr(indent + 1, 'v', arg4),
                                        Expr(indent + 1, arg2, Expr(arg3.height + 1, arg3.type, str(arg3.left)),
                                             Expr(arg1.height + 1, arg1.type, str(arg1.left)))))
                else:
                    stack.append(Assign(indent, Expr(indent + 1, 'v', arg2), arg1))
                assigning = 0

    arg = stack.pop()
    with open(fisier_output, 'w') as f:
        f.write(str(arg))
    return arg

if __name__ == "__main__":
    input_interpretor = 'tests/T3/prog/input/8.in'
    interpreter = runparser(input_interpretor, 'test')
    with open(input_interpretor, "r") as input:
        lines = input.readlines()
    for text in lines:
        print(text.rstrip())
    print()
    print(store)
    visitor = CartVisitor()
    interpreter.accept(visitor)
    print(store)

Lexer, Parser and Interpreter/Parser_and_Interpreter.py


import cv2
import numpy as np
#scaling operation
try:
    image1 = cv2.imread('C:/Program Files/Python39/lena.png')
    #getting number of pixels
    (height,width)=image1.shape[:2]
    res = cv2.resize(image1,(int(width/2),int(height/2)),interpolation=cv2.INTER_CUBIC)
    cv2.imshow('Result image1',res)
except IOError:
    print('Error while reading files!!!')
#Rotating operation
try:
    image2 = cv2.imread('C:/Program Files/Python39/lena.png')
    (rows,cols) = image2.shape[:2]
    M = cv2.getRotationMatrix2D((cols/2,rows/2),45,1)
    result = cv2.warpAffine(image2,M,(cols,rows))
    cv2.imshow('Result image2',result)
except IOError:
    print('Error while reading files!!!')
#Translating images
N = np.float32([[1,0,100],[0,1,50]])
try:
    image3 = cv2.imread('C:/Program Files/Python39/lena.png')
    (rows,cols) = image3.shape[:2]
    result1 = cv2.warpAffine(image3,N,(cols,rows))
    cv2.imshow('Result image3',result1)
except IOError:
    print('Error while reading files!!!')
#Edge Detection
try:
    image4 = cv2.imread('C:/Program Files/Python39/lena.png')
    #Canny edge detection
    edges = cv2.Canny(image4,200,400)
    cv2.imshow('Result image4',edges)
except IOError:
    print('Error while reading files!!!')


# -*- coding: UTF-8 -*-
import numpy as np
import pandas as pd
import sklearn.metrics as metrics
from sklearn import linear_model
from sklearn.cross_validation import train_test_split
from sklearn import ensemble
from sklearn.grid_search import GridSearchCV
import threading
import logging

from services import wcar_service
from services import car_type_service
from utils import math_utils
from utils import time_utils
import config
from services.regression_service import RegressionService

"""car price regression of car series

Attribute:
----------
hedge_rates: car series hedge rates list, used to filter unreasonable data.
"""
class CarSeriesRegressionService(RegressionService):
	hedge_rates = None

	@classmethod
	def _init_series_estimator(cls, series_id, province_id):
		# start to init series estimator
		logging.info("init series estimator start")
		# prepare car series hedge rates
		cls.hedge_rates = car_type_service.get_hedge_rates_by_series_id(series_id)

		# prepare train data set
		logging.debug("before prepare data: %f" % time_utils.milli_time())
		cls.data_frame, i = cls._prepare_data(series_id, province_id)
		logging.debug("after prepare data: %f" % time_utils.milli_time())
		if len(cls.data_frame) < config.MIN_TRAIN_NUM:
			cls.est = False
			return

		# split data into train part and test part.
		logging.debug("before train and test data splitting: %f" % time_utils.milli_time())
		X_train, X_test, y_train, y_test = train_test_split(cls.data_frame.drop(['deal_price'], axis=1), cls.data_frame.deal_price, test_size=0.1, random_state=20)
		logging.debug("after train and test data splitting: %f" % time_utils.milli_time())

		# initialize regression method.
		tuned_parameters = {}
		regressor = linear_model.BayesianRidge()
		clf = GridSearchCV(regressor, cv=4, param_grid=tuned_parameters, scoring=cls.loss)
		logging.debug("before fit: %f" % time_utils.milli_time())
		preds = clf.fit(X_train, y_train)
		logging.debug("after fit: %f" % time_utils.milli_time())
		cls.est = clf.best_estimator_

		# calculate test score
		cls.test_score = math_utils.mean_loss_percentage(cls.est.predict(X_test), y_test)
		if cls.test_score > config.MAX_ALLOWED_PERCENTAGE_ERROR: cls.test_score = config.MAX_ALLOWED_PERCENTAGE_ERROR

		logging.info("init series estimator end")

	"""estimate car price"""
	@classmethod
	def estimate(cls, car_deal):
		result = {}

		# init estimator, if failed, return empty result
		cls._init_series_estimator(car_deal.series_id, car_deal.province_id)
		if not cls.est: return result

		# find predict X array
		predict_X = cls.prepare_predict_X(car_deal)
		predict_y = cls.est.predict(predict_X)
		result['price'] = int(predict_y)
		result['min_price'] = int(result['price'] * (1 - cls.test_score))
		result['max_price'] = int(result['price'] * (1 + cls.test_score))
		result['price_c'] = result['price']
		result['min_price_c'] = result['min_price']
		result['max_price_c'] = result['max_price']
		result['predict_method'] = 'linear regression'
		result['test_score'] = cls.test_score
		return result

	"""prepare training data_dict"""
	@classmethod
	def _prepare_data(cls, series_id, province_id):
		i = 1
		deal_province_offset = 0
		# try to filter training data by series_id, sale_name and province_id,
		# if training set is not enough, remove province_id constraint
		while i >= 0:
			if (i & (1 << deal_province_offset)) > 0:
				tmp_province_id = province_id
			else:
				tmp_province_id = None
			data_frame = wcar_service.get_car_deal_data_by_series_id_and_province_id(series_id, tmp_province_id)
			# filter data
			logging.debug("before filtering data: %f" % time_utils.milli_time())
			data_frame = cls.filter_data(data_frame, cls.hedge_rates)
			logging.debug("after filtering data: %f" % time_utils.milli_time())
			if len(data_frame) >= config.MIN_TRAIN_NUM:
				break
			i = i - 1
		# time consuming here
		# logging.debug("before filled blank data: %f" % time_utils.milli_time())
		# data_frame = cls.filled_blank_data(data_frame)
		# logging.debug("after filled blank data: %f" % time_utils.milli_time())
		return data_frame, i


from collections import OrderedDict
from copy import deepcopy
import numpy as np
import onnx
import onnx_graphsurgeon as gs

sourceOnnx = "../LeViT-128S.onnx"
destinationOnnx = "./LeViT-128S-DLA.onnx"

Identity = True
HardSigmod = False

nIdentity = 0
nHardsigmoid = 0

graph = gs.import_onnx(onnx.shape_inference.infer_shapes(onnx.load(sourceOnnx)))

dict_ = {'Identity_11':[1,196,4,-1], 'Identity_10':[1,196,128], 'Identity_9':[1,49,6,-1],
        'Identity_8':[1,49,192], 'Identity_7':[1,49,6,-1], 'Identity_6':[1,49,192],
        'Identity_5':[1,16,8,-1], 'Identity_4':[1,16,256], 'Identity_3':[1,16,8,-1],
        'Identity_2':[1,16,256], 'Identity_1':[1,16,8,-1], 'Identity_0':[1,16,256]}

if Identity:
    for index, node in enumerate(graph.nodes):
        if node.name in dict_ and \
            node.o().op == 'Reshape' and node.o().inputs[1] == node.outputs[0]:
            t1 = gs.Constant(str(index)+'_Identity', np.ascontiguousarray(np.array(dict_[node.name], dtype=np.int64)))
            node.o().inputs[1] = t1
            node.outputs.clear()
            nIdentity +=1
            graph.cleanup().toposort()

if HardSigmod:
    for index, node in enumerate(graph.nodes):

        if 'HardSigmoid' in node.name:
            v0 = gs.Constant(str(index)+'_v0', np.ascontiguousarray(np.array([0], dtype=np.float32)))
            v1 = gs.Constant(str(index)+'_v1', np.ascontiguousarray(np.array([1], dtype=np.float32)))

            mul_out = gs.Variable(str(index)+"_mul_out", dtype=np.float32)
            mul_node = gs.Node(op='Mul',name=str(index)+'_Mul', inputs=node.i().outputs, outputs=[mul_out])
            graph.nodes.append(mul_node)

            min_out = gs.Variable(str(index)+"_min_out", dtype=np.float32)
            min_node = gs.Node(op='Min',name=str(index)+'_Min', inputs=[v1,mul_out], outputs=[min_out])
            graph.nodes.append(min_node)

            max_out = gs.Variable(str(index)+"_max_out", dtype=np.float32)
            max_node = gs.Node(op='Max',name=str(index)+'_Max', inputs=[v0,min_out], outputs=[max_out])
            graph.nodes.append(max_node)

            node.o().inputs = [node.i().outputs[0], max_node.outputs[0]]
            node.outputs.clear()
            nHardsigmoid +=1

            graph.cleanup().toposort()

print("finish onnx-graphsurgeon!")
onnx.save(gs.export_onnx(graph), "ModifyModel_2.onnx")
print("%4d Identity" %nIdentity)
print("%4d HardSigmod" %nHardsigmoid)