## CLASS FOR MANAGING PROJECTS
##

from complexobjecttransformindexes import transform
from orderedlist import OrderedList
from indexclass import Index
import datetime

class ProjectManager:

     def __init__ (self,
                   project_dictionary=None,
                   connection=None,
                   cursor=None,
                   notebookname=None,
                   archive=False,
                   db_only=False):

          if connection and cursor:
               self.connection = connection
               self.cursor = cursor
               self.using_database = True

          else:
               self.using_database = False
          if archive:
               self.project_suffix = 'archive'
          else:
               self.project_suffix = ''
          self.notebookname = notebookname
          self.db_only=db_only

          if self.using_database:

               self.cursor.executescript("""
               CREATE TABLE IF NOT EXISTS project_names (

                    notebook TEXT NOT NULL,
                    project TEXT NOT NULL,
                    UNIQUE (notebook, project)
                    FOREIGN KEY (notebook) REFERENCES notebooks (notebook) ON DELETE CASCADE
                    );""")

               self.cursor.executescript("""
               CREATE TABLE IF NOT EXISTS project_keys (

                    notebook TEXT NOT NULL,
                    project TEXT NOT NULL,
                    project_key TEXT NOT NULL,

                    UNIQUE (notebook, project, project_key)
                    FOREIGN KEY (notebook, project) REFERENCES project_names (notebook, project) ON DELETE CASCADE
                    );""")

               self.cursor.executescript("""
               CREATE TABLE IF NOT EXISTS project_indexes (

                    notebook TEXT NOT NULL,
                    project TEXT NOT NULL,
                    project_index TEXT NOT NULL,

                    UNIQUE (notebook, project, project_index)
                    FOREIGN KEY (notebook, project) REFERENCES project_names (notebook, project) ON DELETE CASCADE
                    );""")

               self.cursor.executescript("""
               CREATE TABLE IF NOT EXISTS project_dates (

                    notebook TEXT NOT NULL,
                    project TEXT NOT NULL,
                    project_date TEXT NOT NULL,

                    UNIQUE (notebook, project, project_date)
                    FOREIGN KEY (notebook, project) REFERENCES project_names (notebook, project) ON DELETE CASCADE
                    );""")

               self.cursor.executescript("""
               CREATE TABLE IF NOT EXISTS simple_properties (

                    notebook TEXT NOT NULL,
                    project TEXT NOT NULL,
                    lastup TEXT NOT NULL,
                    uptohere TEXT NOT NULL,
                    mainterm TEXT NOT NULL,
                    series_enter TEXT NOT NULL,
                    opened TEXT NOT NULL,

                    UNIQUE (notebook, project)
                    FOREIGN KEY (notebook, project) REFERENCES project_names (notebook, project) ON DELETE CASCADE
                    );""")
          if project_dictionary:
               if self.using_database:

                    self.projects = project_dictionary
                    self.current = None
                    self.clear_database()
                    self.load_into_database(all_projects=project_dictionary)

          else:
               self.projects = {}
               self.current = None
               print(self.projects)

     # to activate/deactivate archive mode
     def set_archive (self,value):
          if isinstance(value,bool):
               self.project_suffix = 'archive'*value

     # methods for accessing the database

     def set_db_only (self,status):

          self.db_only = status

     def add_new_project_DB (self,project=None):

          value_tuple = (self.notebookname, project+self.project_suffix,)

          self.cursor.execute("INSERT OR REPLACE INTO project_names "
                              +"(notebook, project) VALUES (?,?);",
                              value_tuple)
          self.connection.commit()

     def get_projects_DB (self):

          self.cursor.execute("SELECT project "
                              +"FROM project_names WHERE notebook=?",
                              (self.notebookname,))
          return [x[0] for x in self.cursor.fetchall()]

     def delete_project_DB (self,project=None):
          self.cursor.execute("DELETE FROM project_names "+
                              "WHERE notebook=? AND project=?;",
                              (self.notebookname,project+self.project_suffix,))
          self.connection.commit()

     def add_index_DB (self,project=None,index=None):

          if index:
               index=str(index)

          value_tuple = (self.notebookname, project+self.project_suffix,index,)
          self.cursor.execute("INSERT OR REPLACE INTO project_indexes "
                              +"(notebook, project, project_index) VALUES (?,?,?);",
                              value_tuple)
          self.connection.commit()

     def delete_index_DB (self,project=None,index=None):

          value_tuple = (self.notebookname, project+self.project_suffix,index,)
          self.cursor.execute("DELETE FROM project_indexes "+
                              "WHERE notebook=? AND project=? and project_index=?;",
                              value_tuple)
          self.connection.commit()

     def delete_key_DB (self,project=None,key=None):

          value_tuple = (self.notebookname, project+self.project_suffix,key,)
          self.cursor.execute("DELETE FROM project_keys "+
                              "WHERE notebook=? AND project=? and project_key=?;",
                              value_tuple)
          self.connection.commit()

     def delete_all_keys_DB (self,project=None):

          keys_temp = self.get_keys_DB(project=project)
          for key_temp in keys_temp:
               self.delete_key_DB(project=project,
                                  key=key_temp)

     def delete_all_indexes_DB (self,project=None):

          indexes_temp = self.get_indexes_DB(project=project)
          for ind_temp in indexes_temp:
               self.delete_index_DB(project=project,
                                    index=ind_temp)

     def delete_date_DB (self,project=None,date=None):

          value_tuple = (self.notebookname, project+self.project_suffix,date,)
          self.cursor.execute("DELETE FROM project_dates "+
                              "WHERE notebook=? AND project=? and project_date=?;",
                              value_tuple)
          self.connection.commit()

     def get_indexes_DB (self,project=None):

          self.cursor.execute("SELECT project_index FROM project_indexes "
                              +"WHERE notebook=? AND project=?",
                              (self.notebookname,project+self.project_suffix,))
          return [x[0] for x in self.cursor.fetchall()]

     def get_keys_DB (self,project=None):

          self.cursor.execute("SELECT project_key FROM project_keys "
                              +"WHERE notebook=? AND project=?",
                              (self.notebookname,project+self.project_suffix,))
          return [x[0] for x in self.cursor.fetchall()]

     def get_dates_DB (self,project=None):

          self.cursor.execute("SELECT project_date FROM project_dates "
                              +"WHERE notebook=? AND project=?",
                              (self.notebookname,project+self.project_suffix,))
          return [x[0] for x in self.cursor.fetchall()]

     def get_simple_DB (self,project=None,value=None):
          values=['lastup','uptohere','mainterm','series_enter','opened']

          self.cursor.execute("SELECT lastup, uptohere, mainterm, series_enter, opened"
                              +" FROM simple_properties "
                              +"WHERE notebook=? AND project=?",
                              (self.notebookname,project+self.project_suffix,))
          result_temp = self.cursor.fetchone()
          if not value:
               return result_temp
          elif value in values:
               return result_temp[values.index(value)]
          else:
               return ''

     def add_key_DB (self,project=None,key=None):

          value_tuple = (self.notebookname, project+self.project_suffix,key,)
          self.cursor.execute("INSERT OR REPLACE INTO project_keys "
                              +"(notebook, project, project_key) VALUES (?,?,?);",
                              value_tuple)
          self.connection.commit()

     def add_date_DB (self,project=None,date=None):

          value_tuple = (self.notebookname, project+self.project_suffix,date,)
          self.cursor.execute("INSERT OR REPLACE INTO project_dates (notebook, project, project_date) VALUES (?,?,?);",value_tuple)
          self.connection.commit()

     def add_simple_DB (self,
                        lastup=None,
                        uptohere=None,
                        mainterm=None,
                        series_enter=None,
                        opened=None,
                        project=None):

          if not type(lastup)==type(None) \
             and not type(uptohere)==type(None) \
             and not type(mainterm)==type(None) \
             and not type(series_enter)==type(None) \
             and not type(opened)==type(None):

               lastup = str(lastup)
               uptohere = str(uptohere)

               if opened:
                    opened = 'TRUE'
               else:
                    opened = 'FALSE'

               value_tuple =(self.notebookname,
                       project+self.project_suffix,
                       lastup,
                       uptohere,
                       mainterm,
                       series_enter,
                       opened,)
               self.cursor.execute("INSERT OR REPLACE INTO simple_properties "
                                   +"(notebook, project, lastup, uptohere, "
                                   +"mainterm, series_enter, opened) VALUES (?,?,?,?,?,?,?);",
                                   value_tuple)
               self.connection.commit()
               self.cursor.execute("SELECT * FROM simple_properties")

          else:

               if not type(lastup)==type(None):
                    lastup = str(lastup)
                    value_tuple = (lastup, self.notebookname, project+self.project_suffix,)
                    self.cursor.execute("UPDATE simple_properties "+
                                        "SET lastup=? WHERE notebook=? and project=?;",value_tuple)
               if not type(uptohere)==type(None):
                    uptohere = str(uptohere)
                    value_tuple = (uptohere, self.notebookname, project+self.project_suffix,)
                    self.cursor.execute("UPDATE simple_properties "+
                                        "SET uptohere=? WHERE notebook=? and project=?;",value_tuple)

               if not type(mainterm)==type(None):
                    value_tuple = (mainterm, self.notebookname, project+self.project_suffix,)
                    self.cursor.execute("UPDATE simple_properties "+
                                        "SET mainterm=? WHERE notebook=? and project=?;",value_tuple)

               if not type(series_enter)==type(None):
                    value_tuple = (series_enter, self.notebookname, project+self.project_suffix,)
                    self.cursor.execute("UPDATE simple_properties "+
                                        "SET series_enter=? WHERE notebook=? and project=?;",value_tuple)
               if not type(opened)==type(None):

                    if opened:
                         opened = 'TRUE'
                    else:
                         opened = 'FALSE'
                    value_tuple = (opened, self.notebookname, project+self.project_suffix,)
                    self.cursor.execute("UPDATE simple_properties "+
                                        "SET opened=? WHERE notebook=? and project=?;",value_tuple)

               self.connection.commit()

     # connection management

     def restore_connection (self,
                         connection=None,
                         cursor=None):

        self.cursor = cursor
        self.connection = connection

     def purge_connection (self):

        self.cursor = None
        self.connection = None

     # primary methods

     def import_string (self,projecttext,for_projects=False):
          if for_projects:
               print('IMPORTING PROJECT STRING')

          try:
               self.projects = transform(eval(projecttext))
               if self.projects:
                    if for_projects:
                         print('TEXT SUCCESFULLY TRANSFORMED')
                         if self.using_database:
                              self.load_into_database()

                    return True
               else:
                    return False
                    print('TEXT TRANSFORMATION UNSUCCESSFUL')

          except:
               return False
               print('TEXT TRANSFORMATION UNSUCCESSFUL - EXCEPTION RAISED')

     def return_dict (self):

          if self.using_database:
               project_temp = {}
               for proj in self.get_projects_DB():
                    project_temp[proj] = self.get_project(project=proj)
               return project_temp

          return self.projects

     def is_empty (self):

          return self.projects=={}
     def clear (self):

          if self.using_database:
               self.cursor.execute("DELETE FROM project_names "+
                                   "WHERE notebook=?;",
                                   (self.notebookname,))
               self.connection.commit()

          self.projects = {}
          self.current = None

     def get_all_projects (self):

          if self.using_database:

               return self.get_projects_DB()

          return self.projects.keys()

     def get_new_project_name (self,project_name):

          """ to determine in a new project name is the entered name
          is already in use"""

          while project_name in self.projects:

                if project_name.isalpha():
                    project_name  += '1'
                else:
                    suffix = '0'
                    for counter, a in enumerate(project_name):
                        # find the numerical part
                        if a.isnumeric() and suffix == '0':
                            suffix = project_name[counter:]

                    suffix = str(int(suffix)+1)
                    project_name = project_name[0:counter]+suffix

          return project_name

     def initiate_project (self,
                           project_name=None,
                           defaultkeys=None,
                           indexes=None,
                           lastup=None,
                           uptohere=None,
                           mainterm=None,
                           series_enter=None,
                           date=None,
                           opened=True):
          if indexes is None:
               indexes = OrderedList()

          if project_name not in self.projects:
               self.projects[project_name] = {}
               self.projects[project_name]['defaultkeys'] = defaultkeys
               self.projects[project_name]['position'] = (lastup,uptohere)
               self.projects[project_name]['going'] = (mainterm,series_enter)
               self.projects[project_name]['date'] = [str(date)]
               self.projects[project_name]['indexes'] = indexes
               self.projects[project_name]['status'] = {'started':str(date),
                                                        'open':opened,
                                                        'lastmodified':[]}
          self.set_current_project(project_name)
          if self.using_database:
               if opened:
                    opened='TRUE'
               else:
                    opened='FALSE'
               self.add_new_project_DB(project=project_name)
               self.add_simple_DB(project=project_name,
                                  lastup=lastup,
                                  uptohere=uptohere,
                                  mainterm=mainterm,
                                  series_enter=series_enter,
                                  opened=opened)
               for key in defaultkeys:
                    self.add_key_DB(project=project_name,
                                    key=key)
               self.add_date_DB(project=project_name,
                                date=str(date))
               self.set_indexes(project=project_name,
                                indexes=indexes)

     def clear_indexes (self,
                        project=None,
                        db_only=False):

          if not project:
               project=self.current
          if not db_only and not self.db_only :
               self.projects[project]['indexes'] = OrderedList()

          if self.using_database:

               self.delete_all_indexes_DB(project=project)

     def get_project (self,
                      project=None):

          if not project:
               project=self.current

          if self.using_database:

               temp_keys = self.get_keys_DB(project=project)
               temp_indexes = sorted(self.get_indexes_DB(project=project),key=lambda x_temp:Index(x_temp))
               temp_dates = sorted(self.get_dates_DB(project=project))
               temp_simple = self.get_simple_DB(project=project)

               lastup, uptohere, mainterm, series_enter, opened = temp_simple[0], temp_simple[1], temp_simple[2], temp_simple[3], temp_simple[4]

               temp_dict = {}
               temp_dict['defaultkeys'] = temp_keys
               temp_dict['position'] = (lastup,uptohere)
               temp_dict['going'] = (mainterm,series_enter)
               temp_dict['date'] = temp_dates
               temp_dict['indexes'] = OrderedList(temp_indexes)
               temp_dict['status'] = {'started':temp_dates[0],
                                      'open':opened,
                                      'lastmodified':temp_dates}
               return temp_dict

          if project in self.projects:
               return self.projects[project]

     def set_project (self,
                      project=None,
                      project_dict=None,
                      db_only=False):

          if not project:
               project=self.current
          if project_dict and not db_only:
               self.projects[project] = project_dict

          if project_dict and self.using_database:

               dk_temp = project_dict['defaultkeys']
               indexes_temp = project_dict['indexes']
               position_temp = project_dict['position']
               lastup, uptohere =position_temp[0], position_temp[1]
               going_temp = project_dict['going']
               mainterm, series_enter = going_temp[0], going_temp[1]

               date_temp = project_dict['date']

               self.add_new_project_DB(project=project)

               self.initiate_project (project_name=project,
                                      defaultkeys=dk_temp,
                                      indexes=indexes_temp,
                                      lastup=lastup,
                                      uptohere=uptohere,
                                      mainterm=mainterm,
                                      series_enter=series_enter,
                                      date=date_temp,
                                      opened=False)

     def set_indexes (self,
                      project=None,
                      indexes=None,
                      db_only=False):

          if indexes is None:
               indexes = OrderedList()

          if not project:
               project=self.current

          if indexes and not db_only:

               self.projects[project]['indexes'] = indexes

          if self.using_database:
               self.clear_indexes(project=project,
                                  db_only=True)
               for index_temp in indexes.list:
                    self.add_index_DB(project=project,
                                      index=index_temp)

     def delete_project (self,
                         project_name=None,
                         db_only=False):

          if project_name  in self.projects:
               if not db_only and not self.db_only :
                    del self.projects[project_name]

               if self.using_database:
                    self.delete_project_DB(project=project_name)

     def set_default_keys (self,
                           new_defaultkeys,
                           project=None,
                           db_only=False):
          if not project:
               project=self.current

          if isinstance(new_defaultkeys,list):
               if not db_only and not self.db_only :
                    self.projects[project]['defaultkeys'] = new_defaultkeys

               if self.using_database:
                    self.delete_all_keys_DB(project=project)
                    for key_temp in new_defaultkeys:
                         self.add_key_DB(project=project,
                                         key=key_temp)

     def get_default_keys (self,
                           project=None):

          if self.using_database:

               return list(self.get_keys_DB(project=project))

          if not project:
               project=self.current
          return self.projects[project]['defaultkeys']

     def add_default_keys (self,
                           new_defaultkeys=None,
                           project=None,
                           db_only=False):

          if not project:
               project=self.current

          if not isinstance(new_defaultkeys,(set,list)):
               new_defaultkeys = [new_defaultkeys]
          for k_temp in new_defaultkeys:
               if not db_only and not self.db_only :
                    self.projects[project]['defaultkeys'].append(str(k_temp))

          if self.using_database:
               for k_temp in new_defaultkeys:
                    self.add_key_DB(project=project,
                                    key=k_temp)

     def add_date (self,
                   new_date=None,
                   project=None,
                   db_only=False):

          if not project:
               project=self.current

          if not db_only and not self.db_only :

               self.projects[project]['date'].append(str(new_date))

          if self.using_database:
               self.add_date_DB(project=project,
                                date=str(new_date))

     def set_position (self,
                       lastup=None,
                       uptohere=None,
                       project=None,
                       db_only=False):

          if not project:
               project=self.current
          if not db_only and not self.db_only :
               self.projects[project]['position'] = (lastup,
                                                         uptohere)
          if self.using_database:

               self.add_simple_DB(project=project,
                                  uptohere=uptohere,
                                  lastup=lastup)

     def set_going (self,
                    mainterm=None,
                    series_enter=None,
                    project=None,
                    db_only=False):

          if not project:
               project=self.current

          if not db_only and not self.db_only :
               self.projects[project]['going'] = (mainterm,
                                                  series_enter)
          if self.using_database:
               self.add_simple_DB(project=project,
                                  mainterm=mainterm,
                                  series_enter=series_enter)

     def set_status_open (self,
                          status=None,
                          project=None,
                          db_only=False):
          if not project:
               project=self.current

          if not db_only and not self.db_only :
               if status:
                    self.projects[project]['status']['open'] = True
               else:
                    self.projects[project]['status']['open'] = False

          if self.using_database:
               self.add_simple_DB(project=project,
                                  opened=status)

     def set_current_project (self,
                              project_name,
                              project=None):
          if not project:
               project=self.current

          if project_name is self.projects:
               self.current = project_name
               return project_name
          else:
               return False

     def add_last_modified (self,
                            date=None,
                            project=None,
                            db_only=False):
          if not project:
               project=self.current

          if not db_only and not self.db_only :

               self.projects[project]['status']['lastmodified'].append(str(date))

     def reset_indexes (self,
                        indexes=None,
                        project=None,
                        db_only=False):

          if not project:
               project=self.current
          if not db_only and not self.db_only :
               if not indexes:
                    self.projects[project]['indexes'] = OrderedList()
               elif isinstance(indexes,list):
                    self.projects[project]['indexes'] = OrderedList(sorted(indexes,
                                                                               key=lambda x_temp:Index(x_temp)))
          if self.using_database:
               self.delete_all_indexes_DB(project=project)
               for temp_index in sorted(indexes,
                                   key=lambda x_temp:Index(x_temp)):
                    self.add_index_DB(project=project,
                                      index=temp_index)

     def add_index (self,
                    index,
                    project=None,
                    db_only=False):

          if not project:
               project=self.current
          if not db_only and not self.db_only :
               self.projects[project]['indexes'].add(index)

          if self.using_database:
               self.add_index_DB(project=project,
                                 index=index)

     def delete_index (self,
                       index,
                       project=None,
                       db_only=False):

          if not project:
               project=self.current
          if not db_only and not self.db_only :
               self.projects[project]['indexes'].delete(index)
          if self.using_database:
               self.delete_index_DB(project=project,
                                    index=index)

     def set_status (self,
                     project=None,
                     status=None):
          if not project:
               project=self.current
          if project in self.projects and status:

               self.projects[project]['status'] = status

     def get_all_indexes (self,
                          project=None):

          if self.using_database:

               temp_indexes = self.get_indexes_DB(project=project)
               return sorted(temp_indexes,
                             key=lambda x_temp:Index(x_temp))

          if not project:
               project=self.current
          return self.projects[project]['indexes'].list

     def get_position (self,
                       project=None):

          if self.using_database:
               lastup=self.get_simple_DB(project=project,
                                         value='lastup')
               uptohere=self.get_simple_DB(project=project,
                                           value='uptohere')
               return (lastup,uptohere)

          if not project:
               project=self.current
          return self.projects[project]['position']

     def get_date (self,
                   project=None):

          if self.using_database:
               dates_temp = self.get_dates_DB(project=project)
               return sorted(dates_temp)

          if not project:
               project=self.current

          return self.projects[project]['date']

     def get_going (self,
                    project=None):

          if self.using_database:
               mainterm=self.get_simple_DB(project=project,
                                         value='mainterm')
               series_enter=self.get_simple_DB(project=project,
                                           value='series_enter')
               return (mainterm,series_enter)

          if not project:
               project=self.current
          return self.projects[project]['going']

     def get_date_list (self,
                        project=None):

          if self.using_database:
               dates_temp = self.get_dates_DB(project=project)
               return sorted(dates_temp)

          if not project:
               project=self.current
          return self.projects[project]['date']

     def get_status_open (self,
                          project=None):

          if self.using_database:

               opened = self.get_simple_DB(project=project,
                                           value='opened')
               return opened=='TRUE'

          if not project:
               project=self.current
          return self.projects[project]['status']['open']

     def get_status_started (self,
                             project=None):

          if self.using_database:
               dates_temp = self.get_dates_DB(project=project)
               return sorted(dates_temp)[0]

          if not project:
               project=self.current
          return self.projects[project]['status']['started']

     def get_status_modified (self,
                              project=None):

          if self.using_database:
               dates_temp = self.get_dates_DB(project=project)
               return sorted(dates_temp)

          if not project:
               project=self.current
          return self.projects[project]['status']['lastmodified']

     # for transfering from dictionary to database

     def load_project_into_DB (self,
                               project=None,
                               all_projects=None):

          try:
               defaultkeys = all_projects[project]['defaultkeys']
          except:
               print(project,':','defaultkeys FAILED')
               defaultkeys = []
          try:
               indexes = all_projects[project]['indexes']
          except:
               print(project,':','index FAILED')
               indexes = OrderedList()
          try:

               lastup = all_projects[project]['position'][0]
          except:
               print(project,':','lastup FAILED')
               lastup = Index(2)

          try:
               uptohere = uptohere=all_projects[project]['position'][1]
          except:
               print(project,':','uptohere FAILED')
               uptohere = Index(2)
          try:
               mainterm = mainterm=all_projects[project]['going'][0]
          except:
               print(project,':','mainterm FAILED')
               mainterm = 'quit'

          try:

               series_enter = series_enter=all_projects[project]['going'][1]
          except:
               print(project,':','series enter FAILED')
               series_enter = ''
          try:
               date= all_projects[project]['date']
          except:
               date = [str(str(datetime.datetime.now()))]

          self.initiate_project (project_name=project,
                                 defaultkeys=defaultkeys,
                                 lastup=lastup,
                                 indexes=indexes,
                                 uptohere=uptohere,
                                 mainterm=mainterm,
                                 series_enter=series_enter,
                                 date=date,
                                 opened=False)

     def clear_database (self):

          for proj in self.get_projects_DB():
               self.delete_project_DB(project=proj)

     def load_into_database (self,
                             all_projects=None):

          if not isinstance(all_projects,dict):
               all_projects = self.projects

          for proj_temp in all_projects:

               self.load_project_into_DB(project=proj_temp,
                                         all_projects=all_projects)


import numpy as np
import torch

from rt_ddsp import processors

def test_output_is_correct() -> None:
    processor = processors.Add()
    x = torch.zeros((2, 3)) + 1.0
    y = torch.zeros((2, 3)) + 2.0

    output = processor(x, y)

    expected = np.zeros((2, 3), dtype=np.float32) + 3.0

    np.testing.assert_array_equal(expected, output.numpy())


import tkinter as tk
import random
import time
#######################
n = 0
mass = []
mass1 = [[0, 1, 1, 0, 0, 0], [1, 0, 1, 1, 1, 0], [1, 1, 0, 1, 1, 0], [0, 1, 1, 0, 1, 1], [0, 1, 1, 1, 0, 1], [0, 0, 0, 1, 1, 0]]
och = []
vers = []
for i in range(n):
    vers.append(i + 1)
obrab = []

#############################
root = tk.Tk()
root['bg'] = 'black'
root.title('Ха')
visver = []
#root.wm_attributes('-alpha', 0.7)
root.geometry('1500x800')

root.resizable(width=False, height=False)

canvas = tk.Canvas(root, height=800, width=1500, bg='black')
canvas.pack()
canvas.update()

frame = tk.Frame(root, bg = 'white')
frame.place(relwidth=0.4, relheight=0.3)
fio = tk.Label(frame, text='Вахитов Тимур Фаилович, ПРО-228', bg='white', font='Times 16').place(x=0, y=0)
v1 = tk.Label(frame, text="Вершина 1", bg='white', font='Times 12').place(x=0, y=28)
v2 = tk.Label(frame, text="Вершина 2", bg='white', font='Times 12').place(x=0, y=74)
polev1 = tk.Entry(frame, bg='white')
polev1.place(x=0, y=50)
polev2 = tk.Entry(frame, bg='white')
polev2.place(x=0, y=96)
vr1 = []
vr2 = []
kolvouzlov = 0
coordinatos = []
def cuzel():
    global n, vr1, vr2, mass, coordinatos
    vr1 = int(polev1.get()) - 1
    vr2 = int(polev2.get()) - 1
    try:
        if visver[vr1][0] > visver[vr2][0]:
            x1 = visver[vr1][0] - 10
            x2 = visver[vr2][0] + 10
        else:
            x1 = visver[vr1][0] + 10
            x2 = visver[vr2][0] - 10
        if visver[vr1][1] > visver[vr2][1]:
            y1 = visver[vr1][1] - 10
            y2 = visver[vr2][1] + 10
        else:
            y1 = visver[vr1][1] + 10
            y2 = visver[vr2][1] - 10
        canvas.create_line(x1, y1, x2, y2, width=5, fill='green')
        coordinatos.append([vr1, vr2])
        canvas.update()
        mass[vr1][vr2] = 1
        mass[vr2][vr1] = 1
    except:
        pass
def ster():
    global mass, n, kolvouzlov, visver, pokraska
    canvas.delete('all')
    mass.clear()
    obrab.clear()
    visver.clear()
    n = 0
    kolvouzlov = 0
    visver.clear()
    pokraska.clear()
btn = tk.Button(frame, text='Создать связь', bg='green', command=cuzel, font='Times 12')
btn.place(x=0, y=150)
rem = tk.Button(frame, text='Стереть всё', command=ster, bg='green', font='Times 12')
rem.place(x=120, y=190)

pokraska = []

def crv(event):
    global n, mass, pokraska
    vers.append(n)
    x = event.x
    y = event.y
    if (x > 700) or (y > 300):
        n += 1
        for i in range(n):
            try:
                mass[i].append(0)
            except:
                mass.append([])
                for j in range(n):
                    mass[-1].append(0)
        for i in range(n):
            try:
                print(mass[0][i], end=' ')
            except:
                pass
        print('\n')
        pv = canvas.create_oval(x - 20, y - 20, x + 20, y + 20, fill="green", width=2)
        pokraska.append(pv)
        canvas.create_text(x, y, text=str(n), fill='white', font=('Times', 14))
        visver.append([x, y])
        vers.append(n)
        canvas.update()
root.bind('<Button-1>', crv)

###############################################
polevts = tk.Entry(frame, bg='white')
polevts.place(x=150, y=50)

tasamaya = 0
def choice():
    canvas.create_rectangle(0, 280, 300, 320, fill='black')
    global tasamaya
    tasamaya = int(polevts.get())
    for i in range(len(mass)):
        for j in range(len(mass[i])):
            print(mass[i][j], end=' ')
        print('\n')
    cyc(tasamaya)
visitedver = 1
visited = []
def svas(u, visited):
    global n, mass, visitedver
    visited[u] = True
    for v in range(n):
        for i in range(n):
            if mass[u][v] == 1:
                if not visited[v]:
                    visitedver += svas(v, visited)
    return visitedver
infa = canvas.create_text(120, 300, text='', fill='white', font=('Times', 14))
def cyc(v):
    canvas.create_rectangle(0, 240, 300, 300, fill='black')
    global mass, obrab, och, n, visitedver
    visited = []
    conn = 0
    for i in range(n):
        visited.append(False)
    if svas(0, visited) < n:
        canvas.create_text(120, 300, text='Граф несвязный', fill='white', font=('Times', 14))
        canvas.update()
    else:
        for i in range(n):
            canvas.itemconfig(pokraska[i], fill='green')
        for i in range(n):
            for j in range(i + 1, n):
                if mass[i][j] == 1:
                    if visver[i][0] > visver[j][0]:
                        x1 = visver[i][0] - 10
                        x2 = visver[j][0] + 10
                    else:
                        x1 = visver[i][0] + 10
                        x2 = visver[j][0] - 10
                    if visver[i][1] > visver[j][1]:
                        y1 = visver[i][1] - 10
                        y2 = visver[j][1] + 10
                    else:
                        y1 = visver[i][1] + 10
                        y2 = visver[j][1] - 10
                    canvas.create_line(x1, y1, x2, y2, width=5, fill='green')
        out = ''
        uz1 = [1, 2]
        uz2 = [1, 2]
        obrab.append(v)
        och.append([1])
        canvas.itemconfig(pokraska[v - 1], fill='red')
        uz1 = visver[v - 1]
        canvas.update()
        time.sleep(0.5)
        st = 0
        predok = 0
        for i in range(len(mass)):
            if mass[v - 1][i] == 1:
                och[0].append(i + 1)
        predok = v - 1
        metka = 1
        while (len(obrab) != n):
            predudalen = 0
            try:
                st = och[0].pop(1)
            except:
                och.pop(0)
                uz1 = visver[och[0][0] - 1]
                metka = 0
            while (st in obrab) and (len(och) != 0):
                if len(och[0]) < 2:
                    och.pop(0)
                    predudalen = 1
                else:
                    st = och[0].pop(1)
            if predudalen == 1:
                uz1 = visver[och[0][0] - 1]
            if (len(och[0]) < 1) and (metka != 1):
                och.pop(0)
                uz1 = visver[och[0][0] - 1]
            obrab.append(st)
            uz2 = visver[st - 1]
            canvas.itemconfig(pokraska[st - 1], fill='red')
            for i in range(n):
                for j in range(n):
                    if mass[visver.index(uz1)][visver.index(uz2)] == 1:
                        if uz1[0] > uz2[0]:
                            x1 = uz1[0] - 10
                            x2 = uz2[0] + 10
                        else:
                            x1 = uz1[0] + 10
                            x2 = uz2[0] - 10
                        if uz1[1] > uz2[1]:
                            y1 = uz1[1] - 10
                            y2 = uz2[1] + 10
                        else:
                            y1 = uz1[1] + 10
                            y2 = uz2[1] - 10
                        canvas.create_line(x1, y1, x2, y2, width=5, fill='red')
            canvas.update()
            time.sleep(1)
            try:
                och.append([])
                och[-1].append(st)
                for i in range(n):
                    if (mass[st - 1][i] == 1) and (i + 1 not in obrab):
                        och[-1].append(i + 1)
                if len(och[-1] == 0):
                    och.pop(-1)
            except:
                pass
        for u in range(n):
            out = out + ' ' + str(obrab[u])
        canvas.create_text(120, 300, text=out, fill='white', font=('Times', 14))
    obrab.clear()
    och.clear()
    canvas.update()
    visited.clear()
    visitedver = 1

pusk = tk.Button(frame, text='Поиск в ширину', command = choice, bg='green', font='Times 12')
pusk.place(x=150, y=100)

################Laba 5################
stek = []

def ve():
    v = int(polevts.get())
    newc(v)
def newc(v):
    canvas.create_rectangle(0, 240, 300, 320, fill='black')
    global n, mass, stek, visitedver
    global polevts
    for i in range(n):
        canvas.itemconfig(pokraska[i], fill='green')
    for i in range(n):
        for j in range(i + 1, n):
            if mass[i][j] == 1:
                if visver[i][0] > visver[j][0]:
                    x1 = visver[i][0] - 10
                    x2 = visver[j][0] + 10
                else:
                    x1 = visver[i][0] + 10
                    x2 = visver[j][0] - 10
                if visver[i][1] > visver[j][1]:
                    y1 = visver[i][1] - 10
                    y2 = visver[j][1] + 10
                else:
                    y1 = visver[i][1] + 10
                    y2 = visver[j][1] - 10
                canvas.create_line(x1, y1, x2, y2, width=5, fill='green')
    canvas.update()
    time.sleep(1)
    ce = []
    uz1 = [1, 2]
    uz2 = [1, 2]
    current = 0
    rebra = 0
    emass = []
    for i in range(n):
        emass.append([])
        for j in range(n):
            emass[i].append(mass[i][j])
    for i in range(n):
        for j in range(n):
            if emass[i][j] == 1:
                rebra += 1
    rebra //= 2
    current = v - 1
    stek.append(current)
    netu = 0
    lr = 0
    flaghok = 0
    for i in range(n):
        for j in range(n):
            if mass[i][j] == 1:
                lr += 1
        if lr % 2 == 1:
            flaghok = 1
            break
        lr = 0
    visited = []
    conn = 0
    for i in range(n):
        visited.append(False)
    if svas(0, visited) < n:
        flaghok = 1
    if flaghok == 0:
        while rebra != 0:
            netu = 0
            while netu == 0:
                netu = 1
                for i in range(n):
                    if emass[current][i] == 1:
                        emass[current][i] = 0
                        emass[i][current] = 0
                        current = i
                        stek.append(current)
                        rebra -= 1
                        netu = 0
                        break
            ce.append(stek.pop(-1))
            current = stek[-1]
        for i in range(len(stek)):
            ce.append(stek[len(stek) - i - 1])
        for reb in range(len(ce) - 1):
            canvas.itemconfig(pokraska[ce[reb]], fill='red')
            canvas.update()
            time.sleep(0.5)
            uz1 = visver[ce[reb]]
            uz2 = visver[ce[reb + 1]]
            if uz1[0] > uz2[0]:
                x1 = uz1[0] - 10
                x2 = uz2[0] + 10
            else:
                x1 = uz1[0] + 10
                x2 = uz2[0] - 10
            if uz1[1] > uz2[1]:
                y1 = uz1[1] - 10
                y2 = uz2[1] + 10
            else:
                y1 = uz1[1] + 10
                y2 = uz2[1] - 10
            canvas.create_line(x1, y1, x2, y2, width=5, fill='red')
            canvas.update()
            time.sleep(1)
    else:
        canvas.create_text(120, 300, text='Эйлерова цикла нет', fill='white', font=('Times', 14))
    canvas.update()
    stek.clear()
    ce.clear()
    emass.clear()
    visitedver = 1

eiler = tk.Button(frame, text='Нахождение Эйлерова цикла', command = ve, bg='green', font='Times 12')
eiler.place(x=225, y=200)
root.mainloop()

print('op')


import json
import logging

from cornice import Service
from .models import Users
from pyramid import (
    authentication,
    authorization,
    security,
)
from pyramid.httpexceptions import HTTPFound

import requests

from .constants import cors_policy
from .models import Users

log = logging.getLogger(name="mediapublic.{}".format(__name__))

default_acl = [
    (security.Allow, security.Everyone, 'get'),
    (security.Allow, 'group:admins', 'create'),
    (security.Allow, 'group:staff', 'create'),
    (security.Allow, security.Authenticated, 'create'),
    (security.Allow, 'group:admins', 'delete'),
    (security.Allow, 'group:admins', 'update'),
    (security.Allow, 'group:staff', 'delete'),
    (security.Allow, 'group:staff', 'update'),
]

class Context(object):
    def __init__(self, acl):
        """`acl` is a list of triples (result, principal, permission)"""
        self.__acl__ = acl[:]

def choose_context(request):
    # request.matched_route.name
    if request.registry.settings.get(
            'mediapublic.ignore_authentication'):
        return Context([
            (security.Allow, security.Everyone, 'get'),
            (security.Allow, security.Everyone, 'create'),
            (security.Allow, security.Everyone, 'update'),
            (security.Allow, security.Everyone, 'delete'),
        ])
    acl = default_acl[:]
    if ('usersresource' in request.matched_route.name and
            request.authenticated_userid):
        acl.append(
            (security.Allow, request.authenticated_userid, 'update')
        )
    return Context(acl)

def users_acl(request):
    if request.authenticated_userid:
        pass

def associate_groups(user_id, request):
    # TODO(ryansb): actually associate users/groups using the
    # UserTypes model
    return 'user', 'admin'

authn_policy = authentication.AuthTktAuthenticationPolicy(
    # TODO(ryansb): load this from config
    'secretsecrets',
    callback=associate_groups,
    hashalg='sha512',
)

authz_policy = authorization.ACLAuthorizationPolicy()

# --------- Auth and login
login = Service(name='login', path='/login',
                description="Auth and such",
                cors_policy=cors_policy)

@login.get()
def login_info(request):
    if (request.authenticated_userid is None):
        return {}
    user = Users.get_by_id(request.authenticated_userid)
    if user is None:
        request.response.status = 404
        return {'error': 'Not found'}
    return user.to_dict()

@login.post()
def logged_in(request):
    log.debug("Received auth, token ID %s" % request.params['token'])
    resp = requests.get(request.host_url + '/auth/auth_info', params={
        'format': 'json',
        'token': request.params['token'],
    })
    # Future feature: when using providers other than twitter, check
    # auth_info['provider_name'] to see where the account is from
    auth_info = resp.json()
    twitter_handle = auth_info["profile"]["accounts"][0]['username']
    log.debug("Login for @%s" % twitter_handle)

    log.debug("Auth data: %s" % json.dumps(auth_info, indent=4))
    already_exists, uid = Users.update_social_login(twitter_handle, auth_info)

    log.debug("Succesfully authenticated @%s with twitter, exists:%s" %
              (twitter_handle, already_exists))

    principals = security.remember(request, str(uid))
    headers = request.response.headerlist
    headers.extend(principals)
    log.debug("User authenticated, sending back %s" % headers)

    if already_exists:
        return HTTPFound(
            location=request.registry.settings['mediapublic.login_url'],
            headers=headers)
    else:
        return HTTPFound(
            location=request.registry.settings['mediapublic.signup_url'],
            headers=headers)

@login.delete()
def logout(request):
    principals = security.forget(request)
    request.response.headerlist.extend(principals)
    return {"success": True}


import time
from rich import print
from rich.table import Table
from rich.box import SIMPLE

def display_ls(files):
    table = Table(show_header=True, header_style="bold blue", box=SIMPLE)
    table.add_column("Filename", style="dim", width=20)
    table.add_column("Owner", width=10)
    table.add_column("Permissions", width=10)
    table.add_column("Size", justify="right")
    for filename, (owner, perms, size) in files.items():
        table.add_row(filename, owner, perms, size)
    print(table)
    time.sleep(2)

def display_pwd(directory):
    print(f"[bold cyan]Current Directory:[/bold cyan] [green]{directory}[/green]")
    time.sleep(1)

# Dummy data for the example
current_directory = "/home/user"
files_before = {
    "file1.txt": ("user", "-rw-r--r--", "12 KB"),
    "file2.txt": ("user", "-rw-r--r--", "15 KB"),
    "file3.txt": ("user", "-rw-r--r--", "18 KB"),
    "file4.txt": ("user", "-rw-r--r--", "14 KB"),
    "file5.txt": ("user", "-rw-r--r--", "13 KB"),
    "file6.txt": ("user", "-rw-r--r--", "16 KB"),
    "file7.txt": ("user", "-rw-r--r--", "11 KB"),
    "project": ("user", "drwxr-xr-x", "[Dir]")
}
files_after = {
    "file3.txt": ("user", "-rw-r--r--", "18 KB"),
    "file4.txt": ("user", "-rw-r--r--", "14 KB"),
    "file6.txt": ("user", "-rw-r--r--", "16 KB"),
    "file7.txt": ("user", "-rw-r--r--", "11 KB"),
    "project": ("user", "drwxr-xr-x", "[Dir]"),
    "newfolder": ("user", "drwxr-xr-x", "[Dir]")
}

# Demonstrate the commands
print("[bold blue]Command:[/bold blue] [green]ls[/green]")
display_ls(files_before)

print("\n[bold blue]Command:[/bold blue] [green]mkdir newfolder[/green]")
print("[bold green]Folder 'newfolder' created.[/bold green]")
time.sleep(1)

print("\n[bold blue]Command:[/bold blue] [green]ls[/green]")
display_ls(files_after)

print("\n[bold blue]Command:[/bold blue] [green]cd newfolder[/green]")
current_directory += "/newfolder"
display_pwd(current_directory)

print("\n[bold blue]Command:[/bold blue] [green]cp ../file1.txt .[/green]")
print("[bold green]File 'file1.txt' copied to current directory.[/bold green]")
time.sleep(1)

print("\n[bold blue]Command:[/bold blue] [green]rm ../file1.txt ../file2.txt ../file5.txt[/green]")
print("[bold green]Files 'file1.txt', 'file2.txt', and 'file5.txt' removed.[/bold green]")
time.sleep(1)

print("\n[bold blue]Command:[/bold blue] [green]ls[/green]")
display_ls(files_after)

print("\n[bold blue]Command:[/bold blue] [green]pwd[/green]")
display_pwd(current_directory)


import os
import csv

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

engine=create_engine("sqlite:///C:\\Users\\sysadmin\\Desktop\\Nishu\\sqlite3\\SQL\\mydb.db")
mydb=scoped_session(sessionmaker(bind=engine))

def main():
    f= open("flight.csv")
    reader =  csv .reader(f)
    for origin,destination,duration in reader:
        mydb.execute("insert into flights(origin,destination,duration) values (:origin,:destination,:duration)",
                     {"origin":origin , "destination":destination , "duration":duration})
        print(f"{origin} to {destination} takes {duration} minutes")
    mydb.commit()

if __name__=="__main__":
    main()


#!/usr/bin/env python3

# Losslessly autorotate JPEG images: a replacement for exifautotran
# which is no longer usable because of Debian Bug#947182.

from PIL import Image, ExifTags, ImageOps, __version__
from PIL import __version__ as PILversion
import sys

def autorotate(filename, outfile):
    """outfile may be the same as filename.
    """
    img = Image.open(filename)

    rotated = ImageOps.exif_transpose(img)

    rotated.save(outfile, exif=rotated.getexif())
    print("Saved to", outfile)

if __name__ == '__main__':
    pilversionparts = PILversion.split('.')
    if int(pilversionparts[0]) + float(pilversionparts[1]) / 10. < 7.2:
        print("PIL before 7.2 is buggy, bailing!")
        sys.exit(1)
    autorotate(sys.argv[1], "/tmp/rotated.jpg")


class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

    def __repr__(self):
        return str(self.data)

    def print_node_and_following(self):
        to_print = str(self.data)
        node = self
        while node.next:
            to_print = f'{to_print} -> {node.next}'
            node = node.next
        to_print = to_print + ' -> None'
        return to_print

def nextLargerNodes(input_number_list):

    # form the linked list to take the input
    head = Node(input_number_list.pop(0))
    node = head
    for element in input_number_list:
        node.next = Node(element)
        node = node.next

    print(head.print_node_and_following())

    output = []
    node = head
    loc = 0
    stack = []

    while node:

        output.append(0)

        while stack and stack[-1][1] < node.data:
            idx, number = stack.pop()
            print(f'popped {idx}, {number}')
            output[idx] = node.data
            print(output)

        stack.append((loc, node.data))
        print(f'stack after append is {stack}')
        node = node.next
        loc = loc + 1

    return output

nextLargerNodes([1,7,5,1,9,2,5,1])

# 2 7 4 3 5
# 0 1 2 3 4

# 7 5 4 3 2

# 7 0 5 5 0

# 2 7 5 4 3
# 7 5 4 3 2
#-7 0 0 0 0

def facto(x: int) -> int:
    if x >= 1:
        return x * facto(x - 1)
    else:
        return 1

facto(4)

def oddEvenList(head):

    first_even_node = head.next
    even_node = head.next

    node = head

    print(node, even_node)

    while True:

        node.next = node.next.next
        node = node.next
        even_node.next = node.next
        even_node = node.next

        # stopping criteria
        if node.next is None or node.next.next is None:
            break

        print(node, even_node)

    node.next = first_even_node
    return head

node_a_1 = Node(1)
node_a_2 = Node(2)
node_a_3 = Node(3)
node_a_4 = Node(4)
node_a_5 = Node(5)
node_a_6 = Node(6)
node_a_1.next = node_a_2
node_a_2.next = node_a_3
node_a_3.next = node_a_4
node_a_4.next = node_a_5
node_a_5.next = node_a_6
# x = oddEvenList(node_a_1)
# x.print_node_and_following()
g = [3, 2, 1, 5]

def numComponents(head, G) -> int:

    numCom = 0

    status_list = []

    node = head
    while node:

        if node.data in G:
            print(f'{node.data} is in {g}')
            G.remove(node.data)

            status_list.append(1)
        else:
            status_list.append(0)

        node = node.next

    # now need to count how many groups of 1
    print(status_list)
    previous_item = -1
    for item in status_list:
        if item == 1:
            if previous_item != 1:
                numCom += 1
        previous_item = item

    return numCom
numComponents(node_a_1, g)

class MyLinkedList:
    def __init__(self, nodes_data=None):
        self.head = None
        if nodes_data:
            self.head = Node(nodes_data.pop(0))
            prev_node = self.head
            for element in nodes_data:

                node = Node(element)
                prev_node.next = node
                prev_node = node

    def __repr__(self):
        return self.head.print_node_and_following()
x = MyLinkedList([1,2,3,4])
y = MyLinkedList([7,8,2,3,4])

node_a_1 = Node(1)
node_a_2 = Node(2)
node_a_3 = Node(3)
node_a_4 = Node(4)
node_a_5 = Node(5)
node_b_1 = Node(6)
node_b_2 = Node(7)
node_b_3 = Node(8)
node_b_4 = Node(9)
node_a_1.next = node_a_2
node_a_2.next = node_a_3
node_a_3.next = node_a_4
node_a_4.next = node_a_5
node_b_1.next = node_b_2
node_b_2.next = node_b_3
node_b_3.next = node_b_4#  node_a_3  #
print(node_b_1.print_node_and_following())
print(node_a_1.print_node_and_following())

def getIntersectionNode(head_a, head_b):

    # travers a
    print(head_a.print_node_and_following())
    print(head_b.print_node_and_following())

    node_a = head_a
    node_b = head_b

    # a_extended = False
    # b_extended = False
    # count = 0
    while True:  # and count < 20:
        print(f'a is {node_a}')
        print(f'b is {node_b}')
        # count += 1

        if node_a is node_b:
            print('found it')
            return node_a

        node_a = node_a.next
        node_b = node_b.next

        if node_a is None and node_b is None:
            print('both none.. exit and return nothing')
            return None

        if node_a is None:
            print(f' >>> a is {node_a}, last one, appending b')
            node_a = head_b
            # a_extended = True

        if node_b is None:
            print(f' >>> b is {node_b}, last one, appending a')
            node_b = head_a
            # b_extended = True

getIntersectionNode(node_a_1, node_b_1)

# a: 1 2     3 4 5   -> 6 7 4
# b: 6 7 4

node_a_1 = Node(1)
node_a_2 = Node(2)
node_a_3 = Node(3)
node_a_4 = Node(4)
node_a_5 = Node(5)
node_a_1.next = node_a_2
node_a_2.next = node_a_3
node_a_3.next = node_a_4
node_a_4.next = node_a_5
node_a_5.next = node_a_3

def detectCycle(head):
    node = head
    node_pool = set()
    count = 0
    while node not in node_pool and count < 20:
        count += 1
        node_pool.add(node)
        node = node.next
        if node is None:
            print('no cycle')
            return None

    return node

def detectCycle2(head):

    fast_mover = normal_mover = another_normal_mover = head
    looped = False
    while fast_mover or fast_mover.next:
        fast_mover = fast_mover.next.next
        normal_mover = normal_mover.next
        if fast_mover is normal_mover:
            looped = True
            break
    if not looped:
        return None

    while normal_mover != another_normal_mover:
        normal_mover = normal_mover.next
        another_normal_mover = another_normal_mover.next

    return normal_mover

detectCycle2(node_a_1)

# 1 2 3 4 5 3 4 5 3 4 5 3 4 5
# 1 3 5 4 3 4 4 3 4

# slow : 3 + 2 = 2 outloop 1 inloop 2 inloop
# head : 0 + 2 = out_loop
# fast : 6 = length + in_loop

x = Node(1)
x.next = Node(2)
x.next.next = Node(3)
x.next.next = Node(4)
x.next = Node(5)
x.next = Node(6)

# odd even linked list


import cv2
import numpy as np
import os
import matplotlib.pyplot as plt
from collections import Counter

dim = (300,300)
ChainCode = []
TamanhoSinal = []
tamanhoImagem = 8
contar = 0
imagemConta = 1
path = "./number1"

def recuperar(imagem, prox_ponto, valor):
    if valor==0:
        imagem[prox_ponto[0], prox_ponto[1]] = 255
        return (prox_ponto[0]-1, prox_ponto[1])

    elif valor==1:
        imagem[prox_ponto[0], prox_ponto[1]] = 255
        return (prox_ponto[0], prox_ponto[1]+1)

    elif valor==2:
        imagem[prox_ponto[0], prox_ponto[1]] = 255
        return (prox_ponto[0]+1, prox_ponto[1])

    elif valor==3:
        imagem[prox_ponto[0], prox_ponto[1]] = 255
        return (prox_ponto[0], prox_ponto[1]-1)

    else:
        return prox_ponto

def verifique(imagem, ponto, conectividade):
    global contar
    if conectividade == 4:
        if imagem[ponto[0]-1, ponto[1]] == 255:
            imagem[ponto[0]-1,ponto[1]] = 0
            ChainCode.append(0)
            TamanhoSinal.append(contar)
            contar += 1
            return (ponto[0]-1, ponto[1])
        elif imagem[ponto[0], ponto[1]+1] == 255:
                imagem[ponto[0],ponto[1]+1] = 0
                ChainCode.append(1)
                TamanhoSinal.append(contar)
                contar += 1
                return (ponto[0], ponto[1]+1)
        elif imagem[ponto[0]+1, ponto[1]] == 255:
                imagem[ponto[0]+1,ponto[1]] = 0
                ChainCode.append(2)
                TamanhoSinal.append(contar)
                contar += 1
                return (ponto[0]+1, ponto[1])
        elif imagem[ponto[0], ponto[1]-1] == 255:
                imagem[ponto[0],ponto[1]-1] = 0
                ChainCode.append(3)
                TamanhoSinal.append(contar)
                contar += 1
                return (ponto[0], ponto[1]-1)
        else:
            print('none')
    else:
        return ponto

def normalizaImagem(v):
    v = (v - v.min()) / (v.max() - v.min())
    resultado = (v * 255).astype(np.uint8)
    return resultado

for r, d, f in os.walk(path):
    tamanhoImagem = len(f)
    for filename in f:
        imagem = cv2.imread(os.path.join(path, filename))
        imagem = cv2.resize(imagem, dim, interpolation=cv2.INTER_AREA)
        imagemBin = 255 - imagem[:,:,0]

        novaImagem = np.zeros(np.shape(imagemBin))
        kernel = np.ones((3,3), np.uint8)
        novaImagem = normalizaImagem((imagemBin>100)*1)

        imCopy = np.copy(novaImagem)
        imPlot = np.zeros(np.shape(imagem))
        imPlot[:,:,0] = imPlot[:,:,1] = imPlot[:,:,2] = imCopy

        novaImagem = cv2.dilate(novaImagem, kernel, iterations=1) - novaImagem
        novaImagem = cv2.resize(novaImagem, dim, interpolation=cv2.INTER_AREA)

        #cv2.imshow('Imagem', novaImagem)
        #cv2.waitKey(0)

        max_xy = np.where(novaImagem == 255)
        #print (np.shape(novaImagem))

        novaImagemRGB = np.zeros(np.shape(imagem))
        novaImagemRGB[:,:,0] = novaImagemRGB[:,:,1] = novaImagemRGB[:,:,2] = novaImagem

        cv2.circle(novaImagemRGB, (max_xy[1][0], max_xy[0][0]), int(3), (0,0,255), 2)
        iniciarPonto = (max_xy[0][0], max_xy[1][0])
        ponto = verifique(novaImagem, iniciarPonto, 4)

        while(ponto!=iniciarPonto):
            cv2.circle(imPlot, (ponto[1], ponto[0]), int(3), (0,0,255), 6)
            cv2.imshow('Imagem', imPlot)
            cv2.waitKey(1)

            cv2.circle(imPlot, (ponto[1], ponto[0]), int(3), (0,255,255), 4)
            ponto = verifique(novaImagem, ponto, 4)

        res = dict(Counter( ChainCode ))
        imagem_retornada = np.zeros(np.shape(imPlot))
        ponto_in = (1, res[1])
        prox_ponto = ponto_in

        #imagemRetornada = np.zeros((int(res[0]*1.2), int((res[1]+res[3])*1.2) ))

        for valor in ChainCode:
            prox_ponto = recuperar(imagem_retornada, prox_ponto, valor)
            cv2.imshow('Imagem Retornada', imagem_retornada)
            cv2.waitKey(1)

        print(ChainCode)
        plt.subplot(tamanhoImagem, 1, imagemConta)
        plt.plot(ChainCode)
        imagemConta += 1
        ChainCode=[]
    plt.show()


from app import app
from app import db
from app.models import User, Project, Pomodoro
from sqlalchemy import desc
from datetime import datetime

@app.shell_context_processor
def make_shell_context():
    # adds the database and models to `flask shell` environment

    return {'db': db, 'User': User, 'Project': Project, 'Pomodoro': Pomodoro}

def update_db():
    # makes default timestamps. Bugfix
    projects = Project.query.filter_by().all()
    for p in projects:
        poms = Pomodoro.query.filter_by(project=p)
        latest_pom = poms.order_by(desc(Pomodoro.timestamp_end)).first()
        try:
            p.last_timestamp = latest_pom.timestamp_end
            db.session.add(p)
            db.session.commit()
        except:
            p.last_timestamp = datetime.utcnow()
            print (p.title, " no timestamp, so set to now")
            db.session.add(p)
            db.session.commit()
            pass

update_db()


# ！/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:lichengbing

# import json
#
# li = [11, 22, 33]
# # dump先写文件
# json.dump(li, open('db', 'w'))
# # load从文件读再loads
# li1 = json.load(open('db', 'r'))
# print(type(li1), li1)

import pickle
# pickle 只能Python识别 不适用于别的语言
# li = [11, 22, 33]
# r = pickle.dumps(li)
# print(r)
#
# result = pickle.loads(r)
# print(result)

li = [11, 22, 33]
pickle.dump(li, open('db1', 'wb'))
result = pickle.load(open('db1', 'rb'))
print(result, type(result))

# json/pickle 区别1

# json更加适合跨语言 字符串 基本数据类
# pickle 处理Python复杂类型的序列化 缺点是仅适用于Python


import random, bisect, sys
from . import prob, model
from .testing import apply, adiff, fdiff

random.seed(1)
ITERS = 3*10**6
prob.R, prob.B = 30, 10
model.ROLLS_AVAILABLE, model.ROLLS_CYCLE = True, 8
model.ROLLS_F = 1/model.ROLLS_CYCLE
model_type = model.Model

count_Fr = [0]*(prob.R + 1)
count_pr = [0]*(prob.R + 1)
count_k  = [0]*prob.N
count_rolls = [0]
count_last = [0]*prob.N

def sample(X: list=prob.X, F: list=prob.F) -> float:
    """ Samples a value from a random variable. """
    p = random.random()
    return X[bisect.bisect(F, p) - 1]

def E(X, iters: int=ITERS) -> float:
    """ Expected value by repeatedly sampling a random variable. """
    return sum(X() for i in range(iters))/iters

def simulate(m: model.Model=model.Model(), index: int=0) -> float:
    """ Simulates a game. """
    m.reset()
    # give the model a roll every ROLLS_CYCLE claim iterations
    if model.ROLLS_AVAILABLE and index % model.ROLLS_CYCLE == 0:
        m.rolls_left += 1
    lowest = prob.R
    l = []
    # offset if number of rolls is not a multiple of the batch size
    offset = prob.R % prob.B
    # in the case of an offset, remove the offset first
    size = offset if offset > 0 else prob.B
    r = prob.R
    while r > 0:
        lowest = min(lowest, r)
        # new batch, reset seen and assume offset has been taken care of
        if len(l) == size:
            l, size = [], prob.B
        k = sample()
        l.append(k)
        # give kakera value to the model
        i = m.update(k)
        if i is not None:
            if i == model.ROLLS:
                assert model.ROLLS_AVAILABLE, "$rolls is not allowed"
                assert m.rolls_left > 0, "model doesn't have available rolls"
                count_rolls[0] += 1
                # $rolls resets the batch instead of adding the batch size
                delta = prob.upper(r, prob.B) - r + 1
                r += delta
                size += delta
                m.rolls_left -= 1
            else:
                assert 0 <= i < len(l), "model did not give a valid index"
                count_pr[r] += 1
                count_k[prob.D[l[i]]] += 1
                if r == 1:
                    count_last[prob.D[l[i]]] += 1
                for r in range(lowest, prob.R + 1):
                    count_Fr[r] += 1
                return l[i]
        r -= 1
    # model didn't claim, kakera value of 0
    return 0

if __name__ == "__main__":
    m = model_type(prob.R, prob.B, model.ROLLS_AVAILABLE, model.ROLLS_CYCLE)
    # adding rolls changes the random variable
    if model.ROLLS_AVAILABLE:
        ev = sum(simulate(m, i) for i in range(ITERS))/ITERS
        f, fs = model.ROLLS_F, count_rolls[0]/ITERS
        ev_old, Ez = prob.Ef(prob.R, prob.B), prob.Ef(prob.B, prob.B)
        assert fs <= f, "overusing rolls"
        # assume that ROLLS_CYCLE forces k* to be less than E[Zb]
        assert m.kp < Ez, "simplifying mathematical assumption"

        ### testing introspection
        # these should also work if we assume we $rolls on the last layer
        fdiff(count_Fr, m.F_r, range(prob.R + 1), "cdf of f", True)
        fdiff(count_pr, m.p_r, range(prob.R + 1), "pdf of f")
        # pmf of the kakera values emitted by the last layer
        fdiff(count_last, m.p_last, prob.X, "last layer pmf")
        # changed pmf of emitting a kakera value overall as a result
        fdiff(count_k, m.p_k, prob.X, "pdf of k")

        ### expected value
        ev_new = ev_old + m.p_r(1)*(prob.E(apply(m.p_last)) - Ez)
        adiff(ev, ev_new, "rolls expected value")
        print(f"using $rolls with a frequency of {fs:.3f}")
        print(f"improves expected value by {ev_new - ev_old:.3f}")
    # default model with no $rolls
    else:
        # whether the theoretical model aligns with the empirical expected value
        # no way to know whether this "optimal" value is truly optimal however
        adiff(E(lambda: simulate(m)), prob.Ef(prob.R, prob.B), "expected value")

        ### testing introspection
        # probability of getting to r rolls left
        fdiff(count_Fr, m.F_r, range(prob.R + 1), "cdf of f", True)
        # probability of emitting a value at r rolls left
        fdiff(count_pr, m.p_r, range(prob.R + 1), "pdf of f")
        # probability of emitting a kakera value of k
        fdiff(count_k, m.p_k, prob.X, "pdf of k")
        # expected value of the kakera pmf is the expected value of the model
        adiff(prob.E(apply(m.p_k)), prob.Ef(prob.R, prob.B), "pmf k vs E")


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 26 16:05:45 2022

@author: pablobelzarena
"""
import scenarios as sc
import antennas as antennas
import channel_performance as cp
import frequency_band as fb
import numpy as np
import os,sys
import errno

sys.path.append('./src')
sys.path.append('./src/gui')
sys.path.append('./src/graph')

SIM_NAME = "test" #the name of the simulation. Used to give the name
#to the directory where to store the simulation results

######## Build and configure the receive and transmit antennas
nMS=2 # number of antennas in the Mobile Station antenna array
nBS = 2 # number of antennas in the Base Station antenna array
antenna_gain = 8
aeBS = antennas.Antenna3gpp3D(antenna_gain) # Build the Base Station antenna element
aBS  = antennas.AntennaArray3gpp(0.5, 0.5, 1, nBS, 0, 0, 0, aeBS, 1,"antennaRx") # Build the Base Station antenna array
aeMS  = antennas.AntennaIsotropic(antenna_gain) #Build the Mobile Station antenna element
aMS  = antennas.AntennaArray3gpp(0.5, 0.5, 1, nMS, 0, 0, 0, aeMS, 1,"antennaTx") # Build the MS antenna array
###########################################################
###### Build the steering vectors for beamforming according the the BS and MS positions
wBS = aBS.compute_phase_steering (0,np.pi/2,0,0)
""" BS steering vector for baemforming"""
wMS = aMS.compute_phase_steering (np.pi,np.pi/2,0,0)
""" MS steering vector for baemforming"""
#####################################################
######## Build the scenario
fcGHz = 30  # Scenario frequency in GHz
# The next variables define the maximum and minimum x and y coordinates of the system (in meters)
posx_min = -100
posx_max = 100
posy_min = -100
posy_max = 100
grid_number = 25 # The number of elements in the grid. In order to define the parameters of the scenario PyWiCh generate a grid        of correlated parameters. The grid has  grid_number x  grid_number points.
BS_pos = np.array([0,0,20]) # The position of the Base Station device in the scenario.
Ptx_db = 30 # The Transmit power of the BS in dbm
force_los = 2 # The Line of Sight condition. If variable is 0 Non LOS is forced in all points of the scenario. If it is 1 LOS is forced in all scenario. If its value is 2 the LOS condition come from the scenario probability model.
scf=  sc.Scenario3GPPUmi(fcGHz, posx_min,posx_max, posy_min, posy_max, grid_number, BS_pos, Ptx_db,True,force_los)
# The previous instruction creates a  3gpp Umi scenario Model."""
#####################################################
########## Build the OFDM frequency band
freq_band =  fb.FrequencyBand(fcGHz=fcGHz,number_prbs=81,bw_prb=10000000,noise_figure_db=5.0,thermal_noise_dbm_Hz=-174.0)
freq_band.compute_tx_psd(tx_power_dbm=30) # Sets the BS tranmision power and build the power spectral density of each subchannel of the OFDM systems.
###################################################
 #### Build the channel performance object to runs the simulation  and gets the results after the simulation
performance  = cp.ChannelPerformance()
""" Channel performance object"""

###########################save scenario
path = "./data/"+SIM_NAME
try:
    os.makedirs(path)
except OSError as e:
    if e.errno == errno.EEXIST:
        print('Error: ' + path+ '  Directory exists. Directory not created. Please select another name or delete the directory')

    else:
        print('Exception!',str(e)+' occurred.' )

scf.save(path)
aBS.save(path)
aMS.save(path)
freq_band.save(path)

###################### Mobile stations routes configuratiom
n_MS = 1 # number of MSs in this simulation
positions = np.empty(shape=(n_MS),dtype = object) # The positions of the route of all MSs
mspositions1= np.array(([10,10,2],[20,10,2])) # The positions of the MS 1. It has only two points in its route.
positions[0] = mspositions1
times  = np.empty(shape=(n_MS),dtype = object) # The times of each point in the MS route
timesMS1 = np.array(([0,0.01])) # Th first point of the route is in simulation time 0 s and the second in the simulation time 0.1 s.
times[0] = timesMS1
 # The path to save the results of the simulation.
performance.compute_path(scf, freq_band, aMS,aBS,positions,times,force_los,path,mode=2,scatters_move=False,move_probability=0,v_min_scatters=0,v_max_scatters=10)
#####################################################


import sys, time, threading
from argparse import *
from cffi import FFI
from libgpiod import libgpiod

class buttonthread:

    def __init__(self):
        """Create library and ffi interfaces.
        """
        self.gpiod = libgpiod.libgpiod()
        self.lib = self.gpiod.lib
        self.ffi = self.gpiod.ffi

    def waitForEdge(self, line, consumer, timeoutSecs):
        print("Thread running\n")
        timespec = self.ffi.new("struct timespec*")
        timespec.tv_sec = timeoutSecs
        rc = 1
        event = self.ffi.new("struct gpiod_line_event*")
        while rc == 1:
            # Wait for event
            rc = self.lib.gpiod_line_event_wait(line, timespec)
            if rc == 0:
                print("Thread timed out")
            elif rc == 1:
                # Get event off queue
                if self.lib.gpiod_line_event_read(line, event) == 0:
                    if event.event_type == self.lib.GPIOD_LINE_EVENT_RISING_EDGE:
                        print("Rising  edge timestamp %s" % time.strftime('%m/%d/%Y %H:%M:%S', time.localtime(event.ts.tv_sec)))
                    else:
                        print("Falling edge timestamp %s" % time.strftime('%m/%d/%Y %H:%M:%S', time.localtime(event.ts.tv_sec)))
                else:
                    print("gpiod_line_event_read error")
                    rc = -1
            else:
                print("gpiod_line_event_wait error")
                rc = -1
        print("Thread exit")

    def main(self, chip, line):
        """Use thread to wait for edge events while main method does other stuff.
        """
        print ("libgpiod version %s" % self.ffi.string(self.lib.gpiod_version_string()).decode('utf-8'))
        gpiod_chip = self.lib.gpiod_chip_open_by_number(chip)
        # Verify the chip was opened
        if gpiod_chip != self.ffi.NULL:
            print("Name: %s, label: %s, lines: %d" % (self.ffi.string(gpiod_chip.name).decode('utf-8'), self.ffi.string(gpiod_chip.label).decode('utf-8'), gpiod_chip.num_lines))
            gpiod_line = self.lib.gpiod_chip_get_line(gpiod_chip, line)
            # Verify we have line
            if gpiod_line != self.ffi.NULL:
                consumer = sys.argv[0][:-3]
                # Request detection of both edge events
                if self.lib.gpiod_line_request_both_edges_events(gpiod_line, consumer.encode('utf-8')) == 0:
                    # Kick off thread
                    thread = threading.Thread(target=self.waitForEdge, args=(gpiod_line, consumer.encode('utf-8'), 5,))
                    thread.start()
                    count = 0
                    # Just simulating main program doing something else
                    while count < 30 and thread.isAlive():
                        print("Main program doing stuff, press button")
                        time.sleep(1)
                        count += 1
                    # If thread is still alive wait for it to time out
                    if thread.isAlive():
                        print("Waiting for thread to exit, stop pressing button for 5 seconds")
                        thread.join()
                else:
                    print("Unable request both edges for line %d" % line)
                self.lib.gpiod_line_release(gpiod_line)
            else:
                print("Unable to get line %d" % line)
            self.lib.gpiod_chip_close(gpiod_chip)
        else:
            print("Unable to open chip %d" % chip)

if __name__ == "__main__":
    parser = ArgumentParser()
    parser.add_argument("--chip", help="GPIO chip number (default 1 '/dev/gpiochip1')", type=int, default=1)
    parser.add_argument("--line", help="GPIO line number (default 3 button on NanoPi Duo)", type=int, default=3)
    args = parser.parse_args()
    obj = buttonthread()
    obj.main(args.chip, args.line)


from airflow import DAG
from datetime import datetime
from src.hellooperator import HelloOperator

with DAG(dag_id = "04_customOperator",
         description = "using custom (base) operator",
         start_date = datetime(2023, 3, 24),
         schedule_interval = "@once"
) as dag:

    task = HelloOperator(task_id = "hello_with_custom_operator",
                         name = "KLYMers")

    task


import tensorflow as tf
from utils import *
from AlexNet import Alexnet
import os
import h5py
from sklearn.metrics import confusion_matrix
from sklearn.metrics import precision_recall_curve
import matplotlib.pyplot as plt

save_dir = './checkpoints/'

def test(image_size=32,
         num_classes=2,
         num_channels=1):
    # load the test data
    os.environ["CUDA_VISIBLE_DEVICES"] = "2"
    X_train, Y_train, X_valid, Y_valid = load_data(dim=2,
                                                   normalize='unity_based',
                                                   one_hot=True)
    y_true = np.argmax(Y_valid, axis=1)

    # load the model
    model = Alexnet(num_classes, image_size, num_channels)
    model.inference().accuracy_func().loss_func().train_func().pred_func()

    saver = tf.train.Saver()
    save_path = os.path.join(save_dir, 'model_86.91_71')

    with tf.Session() as sess:
        saver.restore(sess, save_path)
        print("Model restored.")
        y_pred_prob, acc_test, loss_test = validation(sess, model, X_valid, Y_valid, 10, compute_prob=True)
        print("Test loss: {0:.2f}, Test accuracy: {1:.01%}"
              .format(loss_test, acc_test))

    y_pred = np.argmax(y_pred_prob, 1)
    print(confusion_matrix(y_true, y_pred))
    Precision, Recall, thresholds = precision_recall_curve(y_true, y_pred_prob[:, 1])

    # Plot Precision-Recall curve
    fig = plt.figure()
    ax1 = fig.add_subplot(1, 1, 1)
    plt.plot(Recall, Precision, lw=2, color='navy', label='Precision-Recall curve')
    ax1.set_xlabel('Recall', size=18)
    ax1.set_ylabel('Precision', size=18)
    ax1.tick_params(labelsize=18)
    plt.ylim([0.5, 1.05])
    plt.xlim([0.0, 1.0])
    plt.show()

    # Compute precision and recall
    precision_recall(y_true, y_pred)

    # save the results
    h5f = h5py.File('alexnet_2d_results.h5', 'w')
    h5f.create_dataset('Precision', data=Precision)
    h5f.create_dataset('Recall', data=Recall)
    h5f.create_dataset('y_pred_prob', data=y_pred_prob)
    h5f.create_dataset('thresholds', data=thresholds)
    h5f.create_dataset('y_pred', data=y_pred)
    h5f.create_dataset('y_true', data=y_true)
    h5f.close()

if __name__ == '__main__':
    test(image_size=32,
         num_classes=2,
         num_channels=1)


from unittest import TestCase
from assetsstore.assets import FileAssets
import glob
import os
import logging

class AsssetsLocalTest(TestCase):

    def setUp(self):
        self.maxDiff = None
        logging.basicConfig(level=logging.INFO)

    def test_no_asset_store_set(self):
        os.environ["ASSET_STORE"] = ""
        with self.assertRaises(Exception) as context:
            FileAssets.get_asset()
        print(context.exception)
        self.assertTrue("There is no asset" in str(context.exception))

    def test_upload_and_download_from_local(self):
        # get set store
        os.environ["ASSET_STORE"] = "LocalFiles"

        os.environ["ASSET_ACCESS_KEY_ID"] = ""
        os.environ["ASSET_SECRET_ACCESS_KEY"] = ""
        os.environ["ASSET_LOCATION"] = "assetsstore/tests/results/remote/"
        os.environ["ASSET_REGION"] = ""

        os.environ["LOCAL_STORE"] = "assetsstore/tests/fixtures/"
        handler = FileAssets.get_asset()
        self.assertEqual("Uploaded", handler.put_file("test.txt"))

        os.environ["LOCAL_STORE"] = "assetsstore/tests/results/"
        handler = FileAssets.get_asset()
        self.assertEqual("Downloaded", handler.get_file("test.txt"))

        # get again to check if it exists
        self.assertEqual("Exists", handler.get_file("test.txt"))

        # delete remote file
        self.assertEqual("Deleted", handler.del_file("test.txt"))

        # delete local copy
        self.assertEqual("Deleted", handler.del_local_file("test.txt"))

    def tearDown(self):
        for file in glob.glob('results/*'):
            if '.gitkeep' not in file:
                os.remove(file)
        for file in glob.glob('results/remote/*'):
            if '.gitkeep' not in file:
                os.remove(file)


from dataclasses import dataclass
from pathlib import Path
from typing import Any, List, Optional, Tuple
import tensorflow as tf

from trainer.metrics import MeanIoU

@dataclass
class TrainerParams:
    num_classes: int
    batch_size: int
    learning_rate: float
    epochs: int
    save_checkpoint: bool = False
    checkpoint_path: Optional[Path] = None
    load_best_checkpoint_after_fit: bool = False
    fit_verbosity: int = 0

class Trainer:
    def __init__(self, params: TrainerParams,
                 dataset_loader: Any,
                 model: tf.keras.Model,
                 input_dim: Tuple[int, int, int],
                 extra_callbacks: List[tf.keras.callbacks.Callback] = []):
        self.params = params
        self.input_dim = input_dim
        self.loader = dataset_loader
        self.model = model
        self.callbacks = extra_callbacks

        self._build_optimizer()
        self._build_loss()
        self._build_metrics()
        self._prepare_model()
        if self.params.save_checkpoint:
            assert self.params.checkpoint_path is not None
            self._build_checkpoint_callback()

    def _build_optimizer(self):
        self.optimizer = tf.keras.optimizers.Adam(
            learning_rate=self.params.learning_rate,
        )

    def _build_loss(self):
        self.loss = tf.keras.losses.SparseCategoricalCrossentropy()

    def _build_metrics(self):
        self.metrics = [
            MeanIoU(self.params.num_classes, name='mean_iou')
        ]

    def _prepare_model(self):
        self.model.compile(
            optimizer=self.optimizer,
            loss=self.loss,
            metrics=self.metrics,
        )
        self.model.build((None,) + self.input_dim)
        print(self.model.summary())

    def _build_checkpoint_callback(self):
        self.callbacks.append(
            tf.keras.callbacks.ModelCheckpoint(
                filepath=self.params.checkpoint_path / 'ckpt',
                save_best_only=True,
                save_weights_only=True,
                save_freq='epoch',
            )
        )

    def fit(self):
        if self.params.checkpoint_path is not None and self.params.checkpoint_path.exists():
            print(f'Loading from checkpoint at {self.params.checkpoint_path}')
            checkpoint = tf.train.Checkpoint(self.model)
            checkpoint.restore(
                str(self.params.checkpoint_path / 'ckpt')).expect_partial()
        train_ds = self.loader.train\
            .prefetch(tf.data.AUTOTUNE)\
            .shuffle(self.params.batch_size * 512)\
            .batch(self.params.batch_size)
        val_ds = self.loader.val.prefetch(
            tf.data.AUTOTUNE).batch(self.params.batch_size)
        self.model.fit(
            train_ds,
            validation_data=val_ds,
            epochs=self.params.epochs,
            callbacks=self.callbacks,
            verbose=max(0, self.params.fit_verbosity),
        )
        if self.params.save_checkpoint and self.params.load_best_checkpoint_after_fit:
            checkpoint = tf.train.Checkpoint(self.model)
            checkpoint.restore(
                str(self.params.checkpoint_path / 'ckpt')).expect_partial()

    def save_model(self, model_path: Path):
        self.model.save(model_path / '1',
                        overwrite=True)


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

"""Update_deployment_configs

Previously we had bad deployment config validation

Revision ID: 54e844ebfbc3
Revises: 3177d36ea270
Create Date: 2016-07-24 14:53:39.323105

"""

from alembic import op  # noqa
import sqlalchemy as sa  # noqa

from rally.common.db import sa_types
from rally import exceptions

# revision identifiers, used by Alembic.
revision = "54e844ebfbc3"
down_revision = "3177d36ea270"
branch_labels = None
depends_on = None

deployments_helper = sa.Table(
    "deployments",
    sa.MetaData(),
    sa.Column("id", sa.Integer, primary_key=True, autoincrement=True),
    sa.Column(
        "config",
        sa_types.MutableJSONEncodedDict,
        default={},
        nullable=False,
    )
)

def _check_user_entry(user):
    """Fixes wrong format of users."""
    if "tenant_name" in user:
        keys = set(user.keys())
        if keys == {"username", "password", "tenant_name",
                    "project_domain_name", "user_domain_name"}:
            if (user["user_domain_name"] == ""
                    and user["project_domain_name"] == ""):
                # it is credentials of keystone v2 and they were created
                # --fromenv
                del user["user_domain_name"]
                del user["project_domain_name"]
                return True
            else:
                # it looks like keystone v3 credentials
                user["project_name"] = user.pop("tenant_name")
                return True

def upgrade():
    connection = op.get_bind()
    for deployment in connection.execute(deployments_helper.select()):
        conf = deployment.config
        if conf["type"] != "ExistingCloud":
            continue

        should_update = False

        if _check_user_entry(conf["admin"]):
            should_update = True
        if "users" in conf:
            for user in conf["users"]:
                if _check_user_entry(user):
                    should_update = True

        if conf.get("endpoint_type") == "public":
            del conf["endpoint_type"]
            should_update = True

        if should_update:
            connection.execute(
                deployments_helper.update().where(
                    deployments_helper.c.id == deployment.id).values(
                    config=conf))

def downgrade():
    raise exceptions.DowngradeNotSupported()


from typing import List

from poif.dataset.meta import MetaCollection
from poif.dataset.object.base import DataSetObject
from poif.dataset.operation.meta_provider.base import MetaProvider
from poif.typing import RelFilePath

class CocoMetaProvider(MetaProvider):
    def __init__(self, annotation_file: RelFilePath):
        super().__init__()
        self.annotation_file = annotation_file

    def provide_meta(self, objects: List[DataSetObject], old_meta: MetaCollection) -> MetaCollection:
        annotation_file = None
        for ds_object in objects:
            if ds_object.relative_path == self.annotation_file:
                annotation_file = ds_object

        if annotation_file is None:
            raise Exception("Annotation file not found in objects")

        annotation_data = annotation_file.get_parsed()

        category_mapping = {}
        for category in annotation_data["categories"]:
            category_mapping[category["id"]] = category["name"]

        old_meta.index_to_label = category_mapping
        return old_meta


# Programmas nosaukums: 3. uzd MPR15
# 3. uzdevums MPR15
# Uzdevuma formulējums: Sastādīt programmu, kas noskaidro, vai trīs taisnes, kuras uzdotas ar taišņu vienādojumiem, ir novietotas tā, ka tās veido trijstūri. Ja veido trijstūri, tad aprēķina tā laukumu. Taišņu vienādojumu ievades forma dota attēlā.
# Versija 1.0

# Loga atribūti

import tkinter as tk
from tkinter import * # bez šai rindai nestrādas rinda button['state'] = DISABLED
from tkinter import ttk

def vai_taisnem_ir_kopigs_punkts(A1, B1, A2, B2):
    SD = A1*B2 - A2*B1
    if SD == 0:
        return False
    else:
        return True

def triangle_area_in_coordinates(x1,y1, x2,y2, x3,y3):
    Area = abs((0.5)*(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)))
    if Area == 0:
        return False
    else:
        return Area

def two_line_interseption_point_coordinate_x(A1,B1,C1, A2,B2,C2): # (x;y)
    D = A1*B2 - A2*B1
    Dx = -C1*B2 + B1*C2
    x = Dx/D
    return x

def two_line_interseption_point_coordinate_y(A1,B1,C1, A2,B2,C2): # (x;y)
    D = A1*B2 - A2*B1
    Dy = -C2*A1 + A2*C1
    y = Dy/D
    return y

def triangle_area_in_coordinates(x1,y1, x2,y2, x3,y3):
    Area = abs((0.5)*(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)))
    if Area == 0:
        return False
    else:
        return Area

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

'''
A1*x + B1*y + C1 = 0
A2*x + B2*y + C2 = 0
A3*x + B3*y + C3 = 0
'''

def is_realA1(event): # Pārbaudam vai entry e1 ir ierakstīts reāls skaitlīs, nevis parasta simbolu virkne
    global a
    try:
        float(e1.get()) # Pārbaude no e1 ņemsim simbolu virkni un pārbaudīsim vai to var pārveidot float
    except:
        if e1.get() == "":  # ja nekas nav ierakstīts
            e1.config(bg = "white") #  tad iekrasosīm baltā
            l_result.config(text = "") # nodzēsisim ieprēkšējo rezultātu, kuru mēs paradījam lietotājam (aprēķināto laukumu)
            a = False # tad globalais a ir False
        else:
            e1.config(bg = "red")
            l_result.config(text = "")
            a = False
    else:
        e1.config(bg = "white")
        a = True
    check() # Pārbaudam vai visiem entry ir ierakstīti reāli skaitli

def is_realB1(event):
    global b
    try:
        float(e2.get())
    except:
        if e2.get() == "":
            e2.config(bg = "white")
            l_result.config(text = "")
            b = False
        else:
            e2.config(bg = "red")
            l_result.config(text = "")
            b = False
    else:
        e2.config(bg = "white")
        b = True
    check()

def is_realC1(event):
    global c
    try:
        float(e3.get())
    except:
        if e3.get() == "":
            e3.config(bg = "white")
            l_result.config(text = "")
            c = False
        else:
            e3.config(bg = "red")
            l_result.config(text = "")
            c = False
    else:
        e3.config(bg = "white")
        c = True
    check()

def is_realA2(event):
    global d
    try:
        float(e4.get())
    except:
        if e4.get() == "":
            e4.config(bg = "white")
            l_result.config(text = "")
            d = False
        else:
            e4.config(bg = "red")
            l_result.config(text = "")
            d = False
    else:
        e4.config(bg = "white")
        d = True
    check()

def is_realB2(event):
    global e
    try:
        float(e5.get())
    except:
        if e5.get() == "":
            e5.config(bg = "white")
            l_result.config(text = "")
            e = False
        else:
            e5.config(bg = "red")
            l_result.config(text = "")
            e = False
    else:
        e5.config(bg = "white")
        e = True
    check()

def is_realC2(event):
    global f
    try:
        float(e6.get())
    except:
        if e6.get() == "":
            e6.config(bg = "white")
            l_result.config(text = "")
            f = False
        else:
            e6.config(bg = "red")
            l_result.config(text = "")
            f = False
    else:
        e6.config(bg = "white")
        f = True
    check()

def is_realA3(event):
    global g
    try:
        float(e7.get())
    except:
        if e7.get() == "":
            e7.config(bg = "white")
            l_result.config(text = "")
            g = False
        else:
            e7.config(bg = "red")
            l_result.config(text = "")
            g = False
    else:
        e7.config(bg = "white")
        g = True
    check()

def is_realB3(event):
    global h
    try:
        float(e8.get())
    except:
        if e8.get() == "":
            e8.config(bg = "white")
            l_result.config(text = "")
            h = False
        else:
            e8.config(bg = "red")
            l_result.config(text = "")
            h = False
    else:
        e8.config(bg = "white")
        h = True
    check()

def is_realC3(event):
    global j
    try:
        float(e9.get())
    except:
        if e9.get() == "":
            e9.config(bg = "white")
            l_result.config(text = "")
            j = False
        else:
            e9.config(bg = "red")
            l_result.config(text = "")
            j = False
    else:
        e9.config(bg = "white")
        j = True
    check()

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

def check(): # Pārbaude
    if a and b and c and d and e and f and g and h and j: # Ja visos lodziņos ir ierakstīti reāli skaitļi
        button['state'] = ACTIVE # tad poga kļūst aktīva
    else:
        button['state'] = DISABLED # Ja kaut viena lodziņa nav ierakstīts reāls skaitļi, tad poga kļūst aktīva

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

def paraditRezultatu(): # funkcija datu nolasīšanai un apstrādei

    '''
    A1*x + B1*y + C1 = 0
    A2*x + B2*y + C2 = 0
    A3*x + B3*y + C3 = 0
    '''

    A1 = float(e1.get())
    B1 = float(e2.get())
    C1 = float(e3.get())

    A2 = float(e4.get())
    B2 = float(e5.get())
    C2 = float(e6.get())

    A3 = float(e7.get())
    B3 = float(e8.get())
    C3 = float(e9.get())

    # Ja 1. - 2. taisnei ir kopīgs punkts un 2. - 3. taisnei ir kopīgs punkts un 1. - 3. taisnei ir kopīgs punkts, tad atrādīsim visus šos krustpunktu koordinātas
    # lai pēc tam atrisinātu laukumu trīsturim pēc koordinātam
    if vai_taisnem_ir_kopigs_punkts(A1, B1, A2, B2) and vai_taisnem_ir_kopigs_punkts(A2, B2, A3, B3) and vai_taisnem_ir_kopigs_punkts(A1, B1, A3, B3):

        x1 = two_line_interseption_point_coordinate_x(A1,B1,C1, A3,B3,C3) # atradisim x1 koordinatu
        y1 = two_line_interseption_point_coordinate_y(A1,B1,C1, A3,B3,C3) # atradisim y1 koordinatu

        x2 = two_line_interseption_point_coordinate_x(A2,B2,C2, A3,B3,C3) # atradisim x2 koordinatu
        y2 = two_line_interseption_point_coordinate_y(A2,B2,C2, A3,B3,C3) # atradisim y2 koordinatu

        x3 = two_line_interseption_point_coordinate_x(A1,B1,C1, A2,B2,C2) # atradisim x3 koordinatu
        y3 = two_line_interseption_point_coordinate_y(A1,B1,C1, A2,B2,C2) # atradisim y3 koordinatu

        S = triangle_area_in_coordinates(x1,y1, x2,y2, x3,y3) # trijstura laukums koordinātas

        if S != 0:
            l_result.config(text = "S = " + str(S)) # Izvadam rezultātu
        else:
            l_result.config(text = "Neveidojas trijstūris.") # Ja laukums ir 0, tad tas ir gadījums, kad visas taisnēs krustojās vienā punktā
    else:
        l_result.config(text = "Neveidojas trijstūris.") # Ja kaut viena prasība neizpildās, tad neveidojas trījstūris

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

# Sākuma visi globālie mainīgie ir False. Viņi atbild par to, vai poga ( button = ttk.Button(logs, text="=", width=1, command=paraditRezultatu) )
# ir ieslēgta vai izslēgta

a = False
b = False
c = False
d = False
e = False
f = False
g = False
h = False
j = False

logs = tk.Tk()
logs.title("Taišņu veidotais laukums") # Programmas nosaukums
logs.geometry("600x300")
l_result = ttk.Label(logs, text="")
l_result.place(x=80, y=200)

# etiķešu (uzrakstu) iezveide

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

l_iekava = ttk.Label(logs, text="{", font = ("Calibri", 140))
l_iekava.place(x=-5, y=-20)

l1 = ttk.Label(logs, text="x + ")
l1.place(x=95, y=50)

l2 = ttk.Label(logs, text="y + ")
l2.place(x=170, y=50)

l0_1 = ttk.Label(logs, text=" =  0 ")
l0_1.place(x=245, y=50)

# -----------------------
# -----------------------
l3 = ttk.Label(logs, text="x + ")
l3.place(x=95, y=100)

l4 = ttk.Label(logs, text="y + ")
l4.place(x=170, y=100)

l0_2 = ttk.Label(logs, text=" =  0 ")
l0_2.place(x=245, y=100)
# -----------------------

l5 = ttk.Label(logs, text="x + ")
l5.place(x=95, y=150)

l6 = ttk.Label(logs, text="y + ")
l6.place(x=170, y=150)

l0_3 = ttk.Label(logs, text=" =  0 ")
l0_3.place(x=245, y=150)
# -----------------------

# ievades tektlodziņu izveide

# -----------------------
e1 = tk.Entry(logs, width = 6)
e1.bind("<KeyRelease>", is_realA1) # Izsaucam funkciju is_realA1
e1.place(x=50, y=50)

e2 = tk.Entry(logs, width = 6)
e2.bind("<KeyRelease>", is_realB1 )
e2.place(x=120, y=50)

e3 = tk.Entry(logs, width = 6)
e3.bind("<KeyRelease>", is_realC1 )
e3.place(x=200, y=50)
# -----------------------

# -----------------------
e4 = tk.Entry(logs, width = 6)
e4.bind("<KeyRelease>", is_realA2 )
e4.place(x=50, y=100)

e5 = tk.Entry(logs, width = 6)
e5.bind("<KeyRelease>", is_realB2 )
e5.place(x=120, y=100)

e6 = tk.Entry(logs, width = 6)
e6.bind("<KeyRelease>", is_realC2 )
e6.place(x=200, y=100)
# -----------------------

# -----------------------
e7 = tk.Entry(logs, width = 6)
e7.bind("<KeyRelease>", is_realA3 )
e7.place(x=50, y=150)

e8 = tk.Entry(logs, width = 6)
e8.bind("<KeyRelease>", is_realB3 )
e8.place(x=120, y=150)

e9 = tk.Entry(logs, width = 6)
e9.bind("<KeyRelease>", is_realC3 )
e9.place(x=200, y=150)
# -----------------------

button = ttk.Button(logs, text="Aprēķināt!", width=10, command=paraditRezultatu)
button.place(x=280, y=150) # novietojām pogu koordinātas x = 250 y = 150
button['state'] = DISABLED # pēc noklusējuma poga ir izslēgta

# Obligāta rindiņa, lai logs būtu redzāms visu laiku
logs.mainloop()

1. Kurss 1. semestris Programmešana un datori I/15. Funkcijas Python_a/13. Laukums trījsturim veidotam ar trīs taisnem.py


"""Unit tests for Go-based dependency parsers."""

from readmeai.parsers.gomod import GoModParser

content = """
module geekdemo

go 1.19

require (
github.com/google/uuid v1.1.2
)

require (
github.com/dop251/goja_nodejs v0.0.0-20230226152057-060fa99b809f // indirect
)

require (
github.com/go-sql-driver/mysql v1.7.0 // indirect
)
"""

def test_go_mod():
    """Tests the go.mod parser."""
    parser = GoModParser()
    expected_dependencies = ["uuid", "goja_nodejs", "mysql"]
    assert parser.parse(content) == expected_dependencies