from datetime import date, datetime

from Service.card_service import CardService
from Service.film_service import FilmService
from Service.rezervare_service import RezervareService
from Service.undoredo_service import UndoRedoService
from ViewModels.cardclient_str import CardClientString
from ViewModels.film_str import FilmString
from utils import check_date_str, check_time_str

def handle_showall(entities):
    for entitiy in entities:
        print(entitiy)

def show_menu():
    print('1.Submeniu filme')
    print('2.Submeniu carduri')
    print('3.Submeniu rezervari')
    print('u.Undo')
    print('r.Redo')
    print('a.Afisare filme,carduri si rezervari')
    print('x.Exit')

class Console:
    def __init__(self,
                 card_service: CardService,
                 film_service: FilmService,
                 rezervare_service: RezervareService,
                 undoredo_service: UndoRedoService):
        self.undoredo_service = undoredo_service
        self.card_service = card_service
        self.film_service = film_service
        self.rezervare_service = rezervare_service

    def run_console(self):
        while True:
            show_menu()
            op = input("Alegeti optiunea: ")

            if op == '1':
                self.film_submenu()
            elif op == '2':
                self.card_submenu()
            elif op == '3':
                self.rezervari_submenu()
            elif op == 'u':
                self.undoredo_service.do_undo()
            elif op == 'r':
                self.undoredo_service.do_redo()
            elif op == 'a':
                handle_showall(self.film_service.get_all())
                handle_showall(self.card_service.get_all())
                handle_showall(self.rezervare_service.get_all())
            elif op == 'x':
                break

    def film_submenu(self):
        while True:
            print("1.Adaugare film")
            print("2.Modificare film")
            print("3.Stergere film")
            print("4.Afișarea filmelor ordonate descrescător"
                  " după numărul de rezervări.")
            print("5.Delete cascada")
            print('u.Undo')
            print('r.Redo')
            print("a.Afisare filme")
            print("s.Search")

            print("x.Exit")
            opf = input("Alegeti optiunea: ")
            if opf == '1':
                self.handle_add_film()
            elif opf == '2':
                self.handle_update_film()
            elif opf == '3':
                self.handle_delete_film()
            elif opf == '4':
                handle_showall(
                    self.film_service.descending_by_rezervation(
                        self.rezervare_service.rezervare_repository))
            elif opf == '5':
                self.handle_delete_cascada_film()
            elif opf == 'u':
                self.undoredo_service.do_undo()
            elif opf == 'r':
                self.undoredo_service.do_redo()
            elif opf == 'a':
                handle_showall(self.film_service.get_all())
            elif opf == 's':
                self.handle_search_film()
            elif opf == 'x':
                break

    def card_submenu(self):
        while True:
            print("1.Adaugare card")
            print("2.Modificare card")
            print("3.Stergere card")
            print("4.Generare n carduri random")
            print("5.Afișarea cardurilor client ordonate descrescător după "
                  "numărul de puncte de pe card. ")
            print("6.Incrementarea cu o valoare dată "
                  "a punctelor de pe toate cardurile "
                  "a căror zi de naștere se află într-un interval dat.")
            print("7.Delete cascada")
            print('u.Undo')
            print('r.Redo')
            print("a.Afisare carduri")
            print("s.Search")

            print("x.Exit")
            opc = input("Alegeti optiunea: ")
            if opc == '1':
                self.handle_add_card()
            elif opc == '2':
                self.handle_update_card()
            elif opc == '3':
                self.handle_delete_card()
            elif opc == '4':
                self.handle_random_cards()
            elif opc == '5':
                self.handle_descending_by_points()
            elif opc == '6':
                self.handle_increment_between()
            elif opc == '7':
                self.handle_delete_cascada_card()
            elif opc == 'u':
                self.undoredo_service.do_undo()
            elif opc == 'r':
                self.undoredo_service.do_redo()
            elif opc == 'a':
                handle_showall(self.card_service.get_all())
            elif opc == 's':
                self.handle_search_carduri()
            elif opc == 'x':
                break

    def rezervari_submenu(self):
        while True:
            print("1.Adaugare rezervare")
            print("2.Modificare rezervare")
            print("3.Stergere rezervare")
            print("4.Afișarea tuturor rezervărilor"
                  " dintr-un interval de ore dat,"
                  " indiferent de zi.")
            print("5.Ștergerea tuturor rezervărilor"
                  " dintr-un anumit interval de zile.")
            print('u.Undo')
            print('r.Redo')
            print("a.Afisare rezervare")

            print("x.Exit")
            opr = input("Alegeti optiunea: ")
            if opr == '1':
                self.handle_add_rezervare()
            elif opr == '2':
                self.handle_update_rezervare()
            elif opr == '3':
                self.handle_delete_rezervare()
            elif opr == '4':
                self.handle_showall_between()
            elif opr == '5':
                self.handle_delete_all_between()
            elif opr == 'u':
                self.undoredo_service.do_undo()
            elif opr == 'r':
                self.undoredo_service.do_redo()
            elif opr == 'a':
                handle_showall(self.rezervare_service.get_all())
            elif opr == 'x':
                break

    def handle_add_film(self):
        try:
            id_film = input('Introduceti id-ul filmului: ')
            titlu_film = input('Introduceti tilul filmului: ')
            an_aparitie = input('Introduceti anul de aparitie al filmului: ')
            pret_bilet_film = input('Introduceti pretul unui bilet:')
            film_in_program = input(
                'introduceti "da" daca filmul este in program: ')
            while True:
                if an_aparitie.isdecimal():
                    an_aparitie = int(an_aparitie)
                    if (an_aparitie > 1) and (an_aparitie < 9999):
                        break
                    else:
                        print('anul de aparitie trebuie '
                              'sa fie cuprins intre 1 si 9999')
                        an_aparitie = input(
                            'Introduceti anul de aparitie al filmului:')
                else:
                    print('Anul trebuie sa contina doar cifre')
                    an_aparitie = input(
                        'Introduceti anul de aparitie al filmului:')

            while True:
                try:
                    pret_bilet_film = float(pret_bilet_film)
                except ValueError:
                    print("Pretul trebuie sa fie numar real")
                    pret_bilet_film = None
                if pret_bilet_film:
                    if pret_bilet_film > 0:
                        break
                    else:
                        print('Pretul trebuie sa fie pozitiv')
                pret_bilet_film = input('Introduceti pretul unui bilet:')
            self.film_service.add_film(id_film, titlu_film, an_aparitie,
                                       pret_bilet_film, film_in_program)
        except KeyError as ke:
            print('Eroare ID: ', ke)
        except ValueError as ve:
            print('Eroare Validare: ', ve)
        except Exception as ee:
            print('Eroare:', ee)

    def handle_update_film(self):
        try:
            id_film = input('Introduceti id-ul filmului ce trebuie updatat: ')
            titlu_film = input('Introduceti noul tilul filmului: ')
            an_aparitie = input(
                'introduceti noul anul de aparitie al filmului: ')
            pret_bilet_film = input('Introduceti noul pret pentru un bilet: ')
            film_in_program = input(
                'introduceti "da" daca filmul este in program: ')
            while True:
                if an_aparitie.isdecimal():
                    an_aparitie = int(an_aparitie)
                    if (an_aparitie > 1) and (an_aparitie < 9999):
                        break
                    else:
                        print('anul de aparitie trebuie'
                              ' sa fie cuprins intre 1 si 9999')
                        an_aparitie = input('Introduceti '
                                            'anul de aparitie al filmului:')
                else:
                    print('Anul trebuie sa contina doar cifre')
                    an_aparitie = input(
                        'Introduceti anul de aparitie al filmului:')

            while True:
                try:
                    pret_bilet_film = float(pret_bilet_film)
                except ValueError:
                    print("Pretul trebuie sa fie numar real")
                    pret_bilet_film = None
                if pret_bilet_film:
                    if pret_bilet_film > 0:
                        break
                    else:
                        print('Pretul trebuie sa fie pozitiv')
                pret_bilet_film = input('Introduceti pretul unui bilet:')
            self.film_service.update_film(id_film, titlu_film, an_aparitie,
                                          pret_bilet_film, film_in_program)
        except KeyError as ke:
            print('Eroare ID: ', ke)
        except ValueError as ve:
            print('Eroare Validare', ve)
        except Exception as ee:
            print('Eroare:', ee)

    def handle_delete_film(self):
        try:
            id_delete = input('Introduceti '
                              'id-ul filmului care trebuie sters: ')
            self.film_service.delete_film(id_delete)
        except KeyError as ke:
            print('Eroare ID: ', ke)
        except ValueError as ve:
            print('Eroare Validare:', ve)
        except Exception as ee:
            print('Eroare:', ee)

    def handle_add_card(self):
        try:
            id_card = input('Introduceti id-ul cardului:')
            nume = input('Introduceti numele: ')
            prenume = input('Introduceti prenumele: ')
            cnp = input('Introduceti cnp-ul: ')
            data_nasterii_str = input('Introduceti data nasterii'
                                      ' in format "dd.mm.yyyy": ')
            check_date_str(data_nasterii_str)
            data_nasterii_str_split = data_nasterii_str.split('.')
            data_nasterii = date(int(data_nasterii_str_split[2]),
                                 int(data_nasterii_str_split[1]),
                                 int(data_nasterii_str_split[0]))
            data_inregistrarii_str = input('Introduceti data inregistrarii'
                                           ' in format "dd.mm.yyyy": ')
            check_date_str(data_inregistrarii_str)
            data_inregistrarii_str_split = data_inregistrarii_str.split('.')
            data_inregistrarii = date(int(data_inregistrarii_str_split[2]),
                                      int(data_inregistrarii_str_split[1]),
                                      int(data_inregistrarii_str_split[0]))
            puncte = int(input('Introduceti punctele de pe card: '))
            self.card_service.add_card(id_card,
                                       nume,
                                       prenume,
                                       cnp,
                                       data_nasterii,
                                       data_inregistrarii,
                                       puncte)

        except KeyError as ke:
            print('Eroare ID: ', ke)
        except ValueError as ve:
            print('Eroare Validare: ', ve)
        except Exception as ee:
            print('Eroare: ', ee)

    def handle_update_card(self):
        try:
            id_card = input('Introduceti id-ul cardului care trebuie updatat:')
            nume = input('Introduceti noul nume: ')
            prenume = input('Introduceti noul prenume: ')
            cnp = input('Introduceti noul cnp: ')
            data_nasterii_str = input('Introduceti noua data a nasterii'
                                      ' in format "dd.mm.yyyy":')
            check_date_str(data_nasterii_str)
            data_nasterii_str_split = data_nasterii_str.split('.')
            data_nasterii = date(int(data_nasterii_str_split[2]),
                                 int(data_nasterii_str_split[1]),
                                 int(data_nasterii_str_split[0]))
            data_inregistrarii_str = input('Introduceti noua '
                                           'data a inregistrarii'
                                           ' in format "dd.mm.yyyy":')
            check_date_str(data_inregistrarii_str)
            data_inregistrarii_str_split = data_inregistrarii_str.split('.')
            data_inregistrarii = date(int(data_inregistrarii_str_split[2]),
                                      int(data_inregistrarii_str_split[1]),
                                      int(data_inregistrarii_str_split[0]))
            self.card_service.update_card(id_card,
                                          nume,
                                          prenume,
                                          cnp,
                                          data_nasterii,
                                          data_inregistrarii, )
        except KeyError as ke:
            print('Eroare ID: ', ke)
        except ValueError as ve:
            print('Eroare Validare:', ve)
        except Exception as ee:
            print('Eroare:', ee)

    def handle_delete_card(self):
        try:
            id_delete = input('Introduceti id-ul cardului '
                              'care trebuie sters: ')
            self.card_service.delete_card(id_delete)
        except KeyError as ke:
            print('Eroare ID: ', ke)
        except ValueError as ve:
            print('Eroare Validare:', ve)
        except Exception as ee:
            print('Eroare:', ee)

    def handle_add_rezervare(self):
        try:
            id_rezervare = input('Introduceti id-ul rezervarii: ')
            id_film = input('Introduceti id-ul filmului: ')
            id_card_client = input('Introduceti id-ul cardului de client: ')
            data_str = input(
                'Introduceti noua data rezervarii in format"dd.mm.yyy": ')
            check_date_str(data_str)
            ora_str = input(
                'Introduceti noua ora rezervarii in format "hh:mm": ')
            check_time_str(ora_str)
            data = data_str.split('.')
            ora = ora_str.split(':')
            data_si_ora = datetime(int(data[2]), int(data[1]), int(data[0]),
                                   int(ora[0]), int(ora[1]))

            self.rezervare_service.add_rezervare(id_rezervare,
                                                 id_film,
                                                 data_si_ora,
                                                 id_card_client, )

        except KeyError as ke:
            print('Eroare ID: ', ke)
        except ValueError as ve:
            print('Eroare Validare: ', ve)
        except Exception as ee:
            print('Eroare:', ee)

    def handle_update_rezervare(self):

        try:
            id_rezervare = input('Introduceti id-ul rezervarii '
                                 'care trebuie updatate: ')
            id_film = input('Introduceti noul id al filmului: ')
            id_card_client = input(
                'Introduceti noul id al cardului de client: ')
            data_str = input(
                'Introduceti data rezervarii in format"dd.mm.yyy": ')
            check_date_str(data_str)
            ora_str = input('Introduceti ora rezervarii in format "hh:mm": ')
            data = data_str.split('.')
            ora = ora_str.split(':')
            data_si_ora = datetime(int(data[2]), int(data[1]), int(data[0]),
                                   int(ora[0]), int(ora[1]))
            self.rezervare_service.add_rezervare(id_rezervare,
                                                 id_film,
                                                 data_si_ora,
                                                 id_card_client, )
        except KeyError as ke:
            print('Eroare ID: ', ke)
        except ValueError as ve:
            print('Eroare Validare: ', ve)
        except Exception as ee:
            print('Eroare:', ee)

    def handle_delete_rezervare(self):
        try:
            id_rezervare = input('Introduceti id-ul rezervarii '
                                 'care trebuie sterse:')
            self.rezervare_service.delete_rezervare(id_rezervare)
        except KeyError as ke:
            print('Eroare ID: ', ke)
        except ValueError as ve:
            print('Eroare Validare: ', ve)
        except Exception as ee:
            print('Eroare:', ee)

    def handle_search_carduri(self):
        carduri = self.card_service.get_all()
        search = input('Search: ')
        cardstr_list = map(lambda x: CardClientString(x), carduri)
        searchlist = [print(cardstr.get_values()) for cardstr in cardstr_list
                      if search in cardstr.get_string()]
        print('Numarul returnarilor: ', len(searchlist))

    def handle_search_film(self):
        filme = self.film_service.get_all()
        search = input('Search: ')
        filmstr_list = map(lambda x: FilmString(x), filme)
        searchlist = [print(filmstr.get_values()) for filmstr in filmstr_list
                      if search in filmstr.get_string()]
        print('Numarul returnarilor: ', len(searchlist))

    def handle_random_cards(self):
        try:
            n = int(input('Dati numarul de carduri ce trebuie generate: '))
            self.card_service.gen_rand_n_cards(n)
        except KeyError as ke:
            print('Eroare ID: ', ke)
        except ValueError as ve:
            print('Eroare Validare: ', ve)
        except Exception as ee:
            print('Eroare:', ee)

    def handle_showall_between(self):
        try:
            ora_inceput = input('Intoduceti '
                                'ora de inceput in format "hh:mm": ')
            ora_final = input('Introduceti '
                              'ora de final in format "hh:mm": ')
            handle_showall(self.rezervare_service.get_all_between(ora_inceput,
                                                                  ora_final))
        except KeyError as ke:
            print('Eroare ID: ', ke)
        except ValueError as ve:
            print('Eroare Validare: ', ve)
        except Exception as ee:
            print('Eroare:', ee)

    def handle_descending_by_points(self):
        try:
            handle_showall(self.card_service.get_card_descending())
        except KeyError as ke:
            print('Eroare ID: ', ke)
        except ValueError as ve:
            print('Eroare Validare: ', ve)
        except Exception as ee:
            print('Eroare:', ee)

    def handle_delete_all_between(self):
        try:
            date_inceput_str = input('Introduceti data inceperii'
                                     ' in format "dd.mm.yyyy": ')
            check_date_str(date_inceput_str)
            data_inceput_str_split = date_inceput_str.split('.')
            data_inceput = datetime(int(data_inceput_str_split[2]),
                                    int(data_inceput_str_split[1]),
                                    int(data_inceput_str_split[0]))
            data_final_str = input('Introduceti data finalului'
                                   ' in format "dd.mm.yyyy": ')
            check_date_str(date_inceput_str)
            data_final_str_split = data_final_str.split('.')
            data_final = datetime(int(data_final_str_split[2]),
                                  int(data_final_str_split[1]),
                                  int(data_final_str_split[0]))
            self.rezervare_service.delete_all_between(data_inceput, data_final)
        except KeyError as ke:
            print('Eroare ID: ', ke)
        except ValueError as ve:
            print('Eroare Validare: ', ve)
        except Exception as ee:
            print('Eroare:', ee)

    def handle_increment_between(self):
        try:
            date_inceput_str = input('Introduceti data inceperii'
                                     ' in format "dd.mm.yyyy": ')
            check_date_str(date_inceput_str)
            data_inceput_str_split = date_inceput_str.split('.')
            data_inceput = date(int(data_inceput_str_split[2]),
                                int(data_inceput_str_split[1]),
                                int(data_inceput_str_split[0]))
            data_final_str = input('Introduceti data finalului'
                                   ' in format "dd.mm.yyyy": ')
            check_date_str(date_inceput_str)
            data_final_str_split = data_final_str.split('.')
            data_final = date(int(data_final_str_split[2]),
                              int(data_final_str_split[1]),
                              int(data_final_str_split[0]))
            puncte = input('Introduceti increment: ')
            if not puncte.isdigit():
                raise ValueError('Punctele trebuie sa fie numar intreg')

            self.card_service.increment_between(data_inceput,
                                                data_final,
                                                int(puncte))
        except KeyError as ke:
            print('Eroare ID: ', ke)
        except ValueError as ve:
            print('Eroare Validare: ', ve)
        except Exception as ee:
            print('Eroare:', ee)

    def handle_delete_cascada_film(self):
        try:
            id_film = input('Introduceti id-ul filmului care trebuie sters: ')
            repository = self.rezervare_service.rezervare_repository
            self.film_service.delete_cascada_film(id_film, repository)
        except KeyError as ke:
            print('Eroare ID: ', ke)
        except ValueError as ve:
            print('Eroare Validare: ', ve)
        except Exception as ee:
            print('Eroare:', ee)

    def handle_delete_cascada_card(self):
        try:
            id_card = input(
                'Introduceti id-ul cardului care trebuie sters: ')
            repository = self.rezervare_service.rezervare_repository
            self.card_service.delete_cascada_card(id_card, repository)
        except KeyError as ke:
            print('Eroare ID: ', ke)
        except ValueError as ve:
            print('Eroare Validare: ', ve)
        except Exception as ee:
            print('Eroare:', ee)


from google.appengine.ext import ndb
import webapp2

from base_handler import BaseHandler

PAGE_SIZE = 5

class SuggestionByCursor(ndb.Model):
    """Model for storing suggestions contributed to the application.

    Suggestions will be displayed in the order they were created.
    """
    suggestion = ndb.StringProperty()
    created = ndb.DateTimeProperty(auto_now_add=True)

    @classmethod
    def populate(cls, num_values=PAGE_SIZE + 1):
        """Populates dummy suggestions for demonstration purposes.

        Args:
            num_values: Integer; defaults to PAGE_SIZE + 1. The number of dummy
                suggestions to add.
        """
        suggestions = [cls(suggestion='Suggestion {:d}'.format(i))
                       for i in range(num_values)]
        ndb.put_multi(suggestions)

class SuggestionByCursorHandler(BaseHandler):
    """Handles the insert of a suggestion and display of existing suggestions.

    The GET handler is intended for general display and paging and the POST
    handler is used for inserting new suggestions.
    """

    def get(self):
        """Handles GET requests to the paging by cursors sub-application.

        If there is a bookmark value in the query parameters, uses it to create
        a cursor and page using it. Includes up to PAGE_SIZE results and a link
        to the next page of results if any more exist.
        """
        cursor = None
        bookmark = self.request.get('bookmark')
        if bookmark:
            cursor = ndb.Cursor.from_websafe_string(bookmark)

        query = SuggestionByCursor.query().order(-SuggestionByCursor.created)
        suggestions, next_cursor, more = query.fetch_page(PAGE_SIZE,
                                                          start_cursor=cursor)

        next_bookmark = None
        if more:
            next_bookmark = next_cursor.to_websafe_string()

        self.render_response('suggestion.html', bookmark=next_bookmark,
                             suggestions=suggestions)

    def post(self):
        """Handles POST requests for inserting a single suggestion."""
        SuggestionByCursor(suggestion=self.request.get('suggestion')).put()
        self.redirect('/cursor/')

class SuggestionByCursorPopulate(BaseHandler):
    """Populates the datastore with some sample suggestions

    Provided so end users can pre-populate with PAGE_SIZE + 1 entities to see
    how cursor-based paging works.
    """

    def post(self):
        """Handles POST requests and adds sample suggestions."""
        SuggestionByCursor.populate()
        self.redirect('/cursor/')

APPLICATION = webapp2.WSGIApplication([
        ('/cursor/pop/', SuggestionByCursorPopulate),
        ('/cursor/', SuggestionByCursorHandler)],
        debug=True)


import json
import statistics

files = range(1, 13)
directory = "KeySlide/"

data = []
times = []
for i in files:
	try:
		f = open(directory + str(i) + "/data.txt", 'r')
		content = json.loads(f.read())
		data.append(content)
		f.close()

		f = open(directory + str(i) + "/user.txt", 'r')
		content = int(f.read())
		times.append(content)
		f.close()
	except:
		continue

pressData = []

for i in range(len(data)):
	d = {
		"stroke_secondary": 0,
		"stroke_primary": 0,
		"time": 0
	}

	for j in data[i]:
		if j[0] in d.keys():
			d[j[0]] += 1
		d["time"] = (j[2] - times[i])/60/1000

	pressData.append(d)

#for i in pressData
#	print(i)

primary = []
secondary = []
time = []
for i in pressData:
	time.append(i["time"])
	primary.append(i["stroke_primary"])
	secondary.append(i["stroke_secondary"])

print("Time ", statistics.mean(time), ' +- ', statistics.stdev(time))
print("Primary ", statistics.mean(primary), ' +- ', statistics.stdev(primary))
print("Secondary ", statistics.mean(secondary), ' +- ', statistics.stdev(secondary))

User Study/Testing Data/keyslide analysis.py


from operator import truediv
import random

user_wins = 0
comp_wins = 0

options = ["batu", "gunting", "kertas"]

while True:
    print("CHILL CORNER\n")
    print("1. Game suit")
    print("2. Beli es krim")
    print("3. Exit")
    user_input = input(">>: ")

    if user_input == "3":
        break

    elif user_input == "1":
         user_input = input("Ketik batu, gunting, kertas: ").lower()
         random_number = random.randint(0, 2)
        # batu: 0, kertas: 1, gunting: 2
         computer_pick = options[random_number]
         print("Bot memilih", computer_pick + ".")

         if user_input == "batu" and computer_pick == "gunting":
            print("Kamu menang!")
            user_wins += 1

         elif user_input == "kertas" and computer_pick == "batu":
            print("Kamu menang!")
            user_wins += 1

         elif user_input == "gunting" and computer_pick == "kertas":
            print("Kamu menang!")
            user_wins += 1

         elif user_input == computer_pick :
            print("Hasilnya seri!")

         else:
            print("Bot menang!")
            comp_wins  += 1

         print("\nKamu menang", user_wins, "kali.")
         print("Bot menang", comp_wins , "kali.\n")

    elif user_input == "2":
        rasa = ["vanilla", "coklat"]
        harga_rasa = [3000, 5000]
        topping = ["polos", "meses", "oreo"]
        harga_topping = [0, 2000, 4000]
        rasa = 0
        topping = 0

        user_rasa = input("Pilih rasa [vanilla, coklat]: ")
        if user_rasa == "vanilla":
           rasa = 0
        else:
           rasa = 1

        user_topping = input("Pilih topping [polos, meses, oreo]: ")
        if  user_topping == "polos":
           topping = 0
        elif user_topping == "meses":
           topping = 1
        else:
           topping = 2

        total = harga_rasa[rasa] + harga_topping[topping]
        print("Harga es krim yang harus dibayar: " + str(total) + "\n")


import argparse

class Config(object):
    """
    Manually setting configuration.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument("--gpu_count", default=1, type=int)
    parser.add_argument("--image_per_gpu", type=int, default=16)
    parser.add_argument("--epoch", default=300, type=int)
    parser.add_argument("--backbone", default='xception', type=str)
    parser.add_argument("--lr", default=0.01, type=float)
    parser.add_argument("--out_class", default=8, type=int)
    args = parser.parse_args()
    backbone = args.backbone
    out_class = args.out_class
    image_per_gpu = args.image_per_gpu
    epoch = args.epoch
    lr = args.lr
    gpu_count = args.gpu_count

if __name__ == '__main__':
    a = '/home/zhuyiche/Desktop/cell/CRCHistoPhenotypes_2016_04_28/cls_and_det/train/img1/img1_others.mat'
    inf = '/home/zhuyiche/Desktop/cell/CRCHistoPhenotypes_2016_04_28/cls_and_det/train/img1/img1_inflammatory.mat'
    from scipy.io import loadmat
    othermat = loadmat(a)['detection']
    print(othermat)


# -*- coding: utf-8 -*-

from search_node import Node, Priority_Queue

def UCGSearch(problem):
    """Uniform Cost Graph Search Algorithm
    """
    Node.reset()
    initial_node = Node(problem)
    if problem.goal_test(problem.initial_state):
        return initial_node.solution()

    frontier = Priority_Queue()
    frontier.push(initial_node, 0)
    explored = set()

    while frontier:
        node = frontier.pop()
        Node.count()
        if problem.goal_test(node.state): return node.solution()
        explored.add(node.state)
        for action in problem.actions(node.state):
            child = node.child(problem,action)
            if not child.state in explored:
                frontier.push(child, child.path_cost)

    return None


import zipfile
import sys
import os
import shared

class rec:
    def __init__(self, hash, path):
        self.sha = hash
        self.path = path

def load_sha1(shafile):
    with open(shafile, "r") as f:
        lines = f.readlines()
        for line in lines:
            hash = line[5:44]
            path = line[46:].strip()
            yield rec(hash, path)

def find_by_sha1(sha):
    for rec in database:
        if rec.sha == sha:
            yield rec

def copy_file(zip_file, file_path):
    if os.path.exists(file_path):
        print(f'- {file_path} already exists (by name)')
        return

    # ensure, that dir is exists. if no, create
    os.makedirs(os.path.dirname(file_path), exist_ok=True)

    zip_file.seek(0, 0)
    size = 0
    with open(file_path, 'wb') as dest_file:
        while True:
            data = zip_file.read(shared.BUFFER_SIZE)
            size = size + len(data)
            if not data:
                break
            else:
                dest_file.write(data)

    print(f'+ {file_path} ({size/1024:.2f}k) copied')

def unpack_zip(zip_path, dest_folder):
    with zipfile.ZipFile(zip_path, 'r') as zip_archive:
        for zip_file_name in zip_archive.namelist():
            # ignore google metadata files
            if zip_file_name.endswith('.json'):
                continue
            if shared.is_ignored(dest_file_name, shared.IGNORED_GOOGLE_FOLDERS):
                continue

            # process file from zip arc
            with zip_archive.open(zip_file_name, 'r') as zip_file:
                dest_file_name = zip_file_name[21:] # Takeout/Fotky Google

                file_path = os.path.join(dest_folder, dest_file_name)
                zip_file_hash = shared.get_file_hash(zip_file)
                duplicates = list(find_by_sha1(zip_file_hash))

                if len(duplicates) > 0:
                    # print dups
                    print(f'ZIP file: {zip_file_name} is {len(duplicates)}x dup:')
                    for dup in duplicates:
                        print(f'\t{dup.path}')
                else:
                    # update db
                    database.append(rec(hash=zip_file_hash, path=file_path))
                    copy_file(zip_file, file_path)

# parse inputs
DATABASE_FILE = sys.argv[1]
ZIP_FILE = sys.argv[2]
DEST_FOLDER = sys.argv[3]

# load db
database = list(load_sha1(DATABASE_FILE))
print(f'Hash DB loaded:{DATABASE_FILE}, {len(database)} record(s)')

# rozbal soubory
unpack_zip(ZIP_FILE, DEST_FOLDER)


import cv2

def main():
    cap = cv2.VideoCapture(0)

    while True:
        ret, frame = cap.read()

        if not ret:
            print("Error: Failed to capture frame")
            continue

        cv2.imshow("Camera", frame)

        if cv2.waitKey(1) == ord("q"):
            break

    cap.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()


#! python3
# judyTweets.py - scrapes judge judy quotes from IMDB and saves them as shelf file
    # tweets one quote daily at 9am to your twitter account

import os, bs4, requests, shelve, datetime, time, math
from twitter import *

ACCESS_TOKEN = ''
ACCESS_TOKEN_SECRET = ''
CONSUMER_KEY = ''
CONSUMER_SECRET =''

# FUNCTIONS
#----------------------------------------------------------------------------------------
# scrapes Judge Judy Quotes from IMDB
def scrapeQuotes():
    quotesList= []
    website = 'http://www.imdb.com/title/tt0115227/quotes'
    res = requests.get(website)
    soup = bs4.BeautifulSoup(res.text)
    quotes = soup.select('div[class="sodatext"]')
    for i in quotes:
        quotesList.append(i.get_text()[2:])
    return quotesList

# save quotes as shelve file
def saveQuotes(list):
    quoteFile = shelve.open('judyQuotesList')
    quotes = []
    for i in list:
        quotes.append(i)
    quoteFile['quotes']= quotes

# keeps track of which quote is next
def quoteCounter():
    numberFile = shelve.open("currentQuote")
    currentNumber = numberFile['current_quote']
    quoteFile = shelve.open('judyQuotesList')
    numberOfQuotes = quoteFile['quotes']
    if currentNumber >= len(numberOfQuotes)-1:
        numberFile['current_quote'] = 0
        numberFile.close()
        quoteFile.close()
        return 0
    else:
        numberFile['current_quote'] += 1
        numberFile.close()
        quoteFile.close()
        return currentNumber

# returns current quote number
def currentQuote():
    numberFile = shelve.open('currentQuote')
    number = numberFile['current_quote']
    numberFile.close()
    return number

# determines if it is time to post a new tweet
def time_to_post():
    now = datetime.datetime.now()
    if now.hour == 9:
        return True
    else:
        return False

# posts string to twitter
def tweet(string):
    if not string.isspace() and string.strip():
        t = Twitter(auth=OAuth(ACCESS_TOKEN, ACCESS_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET))
        t.statuses.update(status=string)
    else:
        pass

# posts current JJ quote to twitter account
def post_it():
    if time_to_post():
        quoteCounter()      # updates quote count
        shelfFile = shelve.open('judyQuotesList')
        quote = shelfFile['quotes'][currentQuote()]
        if len(quote) > 140:
            numtwts = math.ceil(len(quote)/140)     # determines the number of tweets needed to post whole quote. Note: ceil fxn rounds up
            for i in range(0, numtwts+1):
                snip = quote[((i-1)*140):min(len(quote)+1, i*140)]
                tweet(snip)
        else:
            tweet(quote)
        shelfFile.close()
        time.sleep(1)
        post_it()
    else:
        time.sleep(1)
        post_it()

# RUNS PROGRAM
#------------------------------------------------------------------------------------

# creates quote shelf file if doesn't already exist
if os.path.exists("./currentQuote.db"):
    pass
else:
    shelfFile = shelve.open("currentQuote")
    current_quote = 0
    shelfFile['current_quote'] = current_quote
    shelfFile.close()

# creates shelf with JJ quotes if doesn't already exist
if os.path.exists("./judyQuotesList.db"):
    pass
else:
    saveQuotes(scrapeQuotes())

# runs program
post_it()


import numpy as np
from numpy import linalg

def simplex(coef, A, b):
    """
    Desc: Use simplex method to solve linear programming problem
      The form of linear programming problem is like below:
        Min: coef @ x
        St: Ax >= b and x >= 0
    Parameters:
      coef: A row vector containing coefficients of x.
      A: It's matrix A of Ax >= b.
      b: It's columns vector b of Ax >= b
    Return: A dict like below.
      {'coef': _coef, 'solution': _x, 'cost': _cost}
    """
    # (1) Convert Ax >= b into [A -I]x = b
    nrow = A.shape[0]
    _A = np.concatenate([A, -np.identity(nrow)], axis=1)
    _coef = np.concatenate([coef, np.zeros([1, nrow])], axis=1)

    # (2) Continuously find corner until it's already the optimal point.
    B = _A[:, :nrow]
    N = _A[:, nrow:]
    cb = _coef[:, :nrow]
    cn = _coef[:, nrow:]

    def corner(B, N, cb, cn, b):
        """
        Desc: Find corner and check if it's optimal.
             If it is, then return. Else, update B, N, _coef and do recursive procedure.
        Parameters:
          B: A matrix which is the first m columns of _A. m = nrow of A
          N: A matrix which is the last n columns of _A. n = ncol of A
          cb:  A row vector of coefficients
          cn: A row vector of coefficients. Note that cost is [cb, cn] @ x.
          b:  It's columns vector b of [B, N]x = b. x = [x_B, x_N]'
        Return: The function itself or optimal solution and cost.
        """
        # (1) Calculate the current corner and the object function value of this corner
        m, n = N.shape
        inv_B = linalg.inv(B)
        xb = inv_B @ b
        xn = np.zeros([n, 1])
        cost = cb @ inv_B @ b
        r = cn - cb @ inv_B @ N

        # (2) distinguish whether this corner is optimal.
        cond1 = r >= 0
        if cond1.all():
            # This corner is optimal
            result = {'cb': cb, 'cn': cn, 'xb': xb, 'xn': xn, 'cost': cost}
            return result
        else:
            # It's not the optimal
            enter_idx = r.argmin()
            enter_var = N[:, [enter_idx]]
            ratio = (inv_B @ b)/(inv_B @ enter_var)
            cond2 = ratio < 0
            if cond2.any():
                raise Exception('The object function is unbounded')
            else:
                leave_idx = ratio.argmin()
                leave_var = B[:, [leave_idx]]
                B[:, [leave_idx]], N[:, [enter_idx]] = enter_var, leave_var   # update B and N
                cn_enter = cn[0, enter_idx].copy()
                cb_leave = cb[0, leave_idx].copy()
                cb[0, leave_idx], cn[0, enter_idx] = cn_enter, cb_leave  # update cb and cn
                return corner(B, N, cb, cn, b)

    result = corner(B, N, cb, cn, b)

    return result

# 目前还存在bug，需要再理理算法思路与细节。


slangs = [
    "sex",
    "fuck",
    "your mom",
    "pp",
    "penis",
    "dick",
    "vagina",
    "sleep",
    "cum",
    "cock",
    "baby",
    "chick",
    "threesome",
    "rape",
    "masturbation",
    "hot",
    "kinky",
    "semen",
    "porn",
    "hot",
    "nsfw",
    "nudes",
    "lesbians",
    "ass",
    "feminist",
    "paedophiles",
    "prostitute",
    "fetish",
    "jack off",
    "bang",
    "g spot",
    "gay",
    "breed",
    "molested",
    "orgy",
    "heterosexual",
    "nipples",
    "shit",
]


from datetime import datetime
from hashlib import md5

from nonebot import on_command
from nonebot.adapters import Bot, Event
from nonebot.typing import T_State

ex = ['大吉', '吉', '半吉', '小吉', '末吉', '大凶', '凶', '半凶', '小吉', '末凶']  # 求签结果选项
week = ['一', '二', '三', '四', '五', '六', '日']  # 将日期转换为汉字

# 获取格式化的日期字符串
def Date():
    dt = datetime.now()
    dateList = dt.timetuple()  # 包含各种时间信息的list
    dateText = "{}年{}月{}日 星期{}".format(dateList[0], dateList[1], dateList[2], week[dateList[6]])
    return dateText

# 获取由md5产生的单个随机数
def md5Str(text: str):
    md = md5(text.encode("UTF-8")).hexdigest()
    md5Int = ...
    for i in md:
        if i.isdigit():  # 判断是否为数字
            md5Int = i
            break
    return md5Int

# 由随机数得到求签结果
def _fortune(word):
    md5Int = md5Str(word)
    result = "【{}】".format(ex[int(md5Int)])
    return result

# 注册求签事件响应器
fortune = on_command("求签")  # 优先级为5

@fortune.handle()
async def handle_first_receive(bot: Bot, event: Event, state: T_State):
    origin_raw = str(event.get_message())
    raw = F"{origin_raw}{event.sender.user_id}{datetime.now().strftime('%Y%m%d')}"
    # 如果结果不为空，就存入T_State
    if origin_raw:
        state["origin_raw"] = origin_raw
        state["raw"] = raw

@fortune.got("origin_raw", prompt="告诉我求签的内容啊！")  # 求签内容为空时反馈
async def handle_fortune_word(bot: Bot, event: Event, state: T_State):
    origin_raw = state["origin_raw"]
    raw = state["raw"]
    msg = "{}\n{}所求内容【{}】\n{}".format(Date(), event.sender.card, origin_raw, _fortune(raw))
    await fortune.send(msg)


import pandas as pd
import gspread
from search_google import *

gc = gspread.service_account(filename='creds.json')

sheet_1 = gc.open_by_key('16Ez6gDbBHtIbZRkoe3h6yG4eZeERZZEZ_LzNQ-w1lpM')
sheet_2 = gc.open_by_key('1SXBaISO7rlmxBkEhS7Gz98BtCQSJLs9JyV3RKDE4KEc')
oxygen_db_1 = sheet_1.worksheet('Sheet For Users')
oxygen_db_2 = sheet_2.worksheet('Sheet For Users')
rows_1 = oxygen_db_1.get_all_values()
rows_2=oxygen_db_2.get_all_values()
oxygen_df_1 = pd.DataFrame.from_records(rows_1[8:], columns=rows_1[7])
oxygen_df_2 = pd.DataFrame.from_records(rows_2[8:], columns=rows_2[7])
oxygen_df_2['ADDITIONAL INFO']=pd.NA
oxygen_data=[oxygen_df_1,oxygen_df_2]
oxygen_df=pd.concat(oxygen_data)
oxygen_df = oxygen_df[((oxygen_df['STATUS'] == 'Available')| (oxygen_df['STATUS']=='Needs Verification')) & (oxygen_df['STATE']!='') & (oxygen_df['LOCATION (CITY)']!='')]

oxygen_data=[oxygen_df['NAME'],oxygen_df['CONTACT NUMBER'],oxygen_df['STATE'],oxygen_df['LOCATION (CITY)'],oxygen_df['STATUS']
                                   ,oxygen_df['DATE AND TIME OF VERIFICATION (AUTOMATED; DO NOT EDIT)'],oxygen_df['ADDITIONAL INFO']]
# oxygen_data = oxygen_df[['NAME', 'CONTACT NUMBER', 'STATE', 'LOCATION (CITY)', 'STATUS', 'DATE AND TIME OF VERIFICATION (AUTOMATED; DO NOT EDIT)', 'ADDITIONAL INFO']]
# oxygen_data.rename(columns={'NAME': 'name', 'CONTACT NUMBER': 'contact', 'STATE': 'state', 'LOCATION (CITY)': 'city', 'STATUS': 'status', 'DATE AND TIME OF VERIFICATION (AUTOMATED; DO NOT EDIT)': 'date_time', 'ADDITIONAL INFO': 'info'})
headers = ["name", "contact","state","city","status","date_time","info"]
oxygen_df_final = pd.concat(oxygen_data, axis=1, keys=headers)
oxygen_df_final = oxygen_df_final.reset_index(drop=True)
oxygen_df_final.loc[:, 'state'] = oxygen_df_final['state'].apply(lambda x: search(x, 'state'))
oxygen_df_final.loc[:, 'city'] = oxygen_df_final['city'].apply(lambda x: search(x, 'city'))

sheet_1 = gc.open_by_key('1KtDiUWbYtGVWf9gO4FN1AUUerexnsHyQYa0AiKmNE3k')
sheet_2 = gc.open_by_key('1yZGlGJ0OWMAiwTXQ3R2PIJhiBrl8EzQKL-ba4RjlGos')
hospital_bed_db_1 = sheet_1.worksheet('Sheet for Users')
hospital_bed_db_2 = sheet_2.worksheet('Sheet For Users')

rows_1 = hospital_bed_db_1.get_all_values()
rows_2=hospital_bed_db_2.get_all_values()
hospital_bed_df_1 = pd.DataFrame.from_records(rows_1[7:], columns=rows_1[6])
hospital_bed_df_2 = pd.DataFrame.from_records(rows_2[4:], columns=rows_2[3])
hospital_bed_df_1 = hospital_bed_df_1[((hospital_bed_df_1['Status'] == 'Beds Available') | (hospital_bed_df_1['Status'] == 'Home Setup') | (hospital_bed_df_1['Status'] == 'Call to check soon'))
                    & (hospital_bed_df_1['State']!='') & (hospital_bed_df_1['City']!='')]

hospital_bed_df_2 = hospital_bed_df_2[((hospital_bed_df_2['Status'] == 'Available') | (hospital_bed_df_2['Status'] == 'Needs Verification') )
                     & (hospital_bed_df_2['State']!='') & (hospital_bed_df_2['City']!='')]

hospital_bed_data_1=[hospital_bed_df_1['Name of hospital'],hospital_bed_df_1['Phone number'],hospital_bed_df_1['State'],hospital_bed_df_1['City']
                     , hospital_bed_df_1['Status'],hospital_bed_df_1['Date And Time Of Verification'],hospital_bed_df_1['Important Details']]
headers_1=["name","contact","state","city","status","date_time","info"]
hospital_bed_df_2['Special Notes']=pd.NA
hospital_bed_data_2=[hospital_bed_df_2['Name of Hospital'],hospital_bed_df_2['Phone Number'],hospital_bed_df_2['State'],hospital_bed_df_2['City']
                       , hospital_bed_df_2['Status'],hospital_bed_df_2['Last Updated on'],hospital_bed_df_2['Special Notes']]
hospital_bed_df_1_change_header = pd.concat(hospital_bed_data_1, axis=1, keys=headers_1)

hospital_bed_df_2_change_header = pd.concat(hospital_bed_data_2, axis=1, keys=headers_1)

hospital_bed_df_final=pd.concat([hospital_bed_df_1_change_header, hospital_bed_df_2_change_header],ignore_index=True)[hospital_bed_df_1_change_header.columns]

hospital_bed_df_final.loc[:, 'state'] = hospital_bed_df_final['state'].apply(lambda x: search(x, 'state'))
hospital_bed_df_final.loc[:, 'city'] = hospital_bed_df_final['city'].apply(lambda x: search(x, 'city'))

sheet_1 = gc.open_by_key("17bc83Sjnakb5DgsEQ7-lRj30-JVrIjSCcQuvwxB4Bc0")
sheet_2 = gc.open_by_key("1QHHA2p-WSSsx7-F1_6v0TvF0fEKPx74h7B2UkkErnyQ")
medicine_db_1 = sheet_1.worksheet("Sheet for Users")
medicine_db_2 = sheet_2.worksheet("Sheet For Users")
rows_1 = medicine_db_1.get_all_values()
rows_2 = medicine_db_2.get_all_values()
medicine_df_1 = pd.DataFrame.from_records(rows_1[11:], columns=rows_1[0])
medicine_df_2 = pd.DataFrame.from_records(rows_2[4:],columns=rows_2[3])
medicine_df_1 = medicine_df_1.loc[:, ~medicine_df_1.columns.duplicated(keep='last')]
medicine_df_1 = medicine_df_1[(medicine_df_1['Verification'] == 'Available') & (medicine_df_1['State']!='')]
medicine_df_2 = medicine_df_2[((medicine_df_2['STATUS']=='Available') | (medicine_df_2['STATUS']=='Needs Verification')) &
                                (medicine_df_2['STATE']!='') & (medicine_df_2['      LOCATION (CITY)']!='')]
medicine_data_1 = [medicine_df_1['Name'],medicine_df_1['Contact'],medicine_df_1['State'],medicine_df_1['Location'],medicine_df_1['Verification'],
                         medicine_df_1['Time'],medicine_df_1['Medicine']]
medicine_data_2 = [medicine_df_2['NAME'],medicine_df_2['CONTACT NO'],medicine_df_2['STATE'],medicine_df_2['      LOCATION (CITY)'],medicine_df_2['STATUS'],medicine_df_2['VERIFIED DATE AND TIME'],medicine_df_2['TYPE OF MEDICINE     ']]
headers = ["name", "contact","state","city","status","date_time","info"]
medicine_df_1_change_header = pd.concat(medicine_data_1,axis=1,keys=headers)
medicine_df_2_change_header = pd.concat(medicine_data_2,axis=1,keys=headers)
medicine_df_final = pd.concat([medicine_df_1_change_header,medicine_df_2_change_header])
medicine_df_final.loc[:, 'state'] = medicine_df_final['state'].apply(lambda x: search(x, 'state'))

sheet = gc.open_by_key("1cbxCbhLVRWBlyRmzKuEQ-0PG3fsSs6EMIR51d2OoCIg")
plasma_org = sheet.worksheet('Organisations')
plasma_donor = sheet.worksheet('Donors')

rows = plasma_org.get_all_values()
plasma_org_df = pd.DataFrame.from_records(rows[7:89], columns=rows[6])
plasma_org_df = plasma_org_df[(plasma_org_df['LOCATION']!='')]
plasma_org_data=[plasma_org_df['NAME'],plasma_org_df['CONTACT NUMBER'],plasma_org_df['LOCATION'],plasma_org_df['AVAILIBILITY']
                      ,plasma_org_df['TIME & DATE VERIFIED'],plasma_org_df['Additional Info']]
headers = ["name", "contact","city","status","date_time","info"]
plasma_org_final = pd.concat(plasma_org_data,axis=1,keys=headers)
plasma_org_final.loc[:, 'city'] = plasma_org_final['city'].apply(lambda x: search(x, 'city'))

rows = plasma_donor.get_all_values()
plasma_donor_df = pd.DataFrame.from_records(rows[1:], columns=rows[0])
plasma_donor_df = plasma_donor_df[((plasma_donor_df['Available'] == 'Available')|(plasma_donor_df['Available']=='Busy/ Ringing')) & (plasma_donor_df['LOCATION']!='')]
plasma_donor_data = [plasma_donor_df['NAME'],plasma_donor_df['CONTACT NUMBER'],plasma_donor_df['LOCATION'],
                     plasma_donor_df['BLOOD GROUP'],plasma_donor_df['Available'],plasma_donor_df.iloc[:,7],plasma_donor_df['Additional Information/ Co-morbidity']]
headers = ["name", "contact","city","bloodgrp","status","date_time","info"]
plasma_donor_final=pd.concat(plasma_donor_data,axis=1,keys=headers)
plasma_donor_final.loc[:, 'city'] = plasma_donor_final['city'].apply(lambda x: search(x, 'city'))

oxygen_df_final.to_csv('data/oxygen_df.csv', index=False)
hospital_bed_df_final.to_csv('data/hospital_bed_df.csv', index=False)
medicine_df_final.to_csv('data/medicine_df.csv', index=False)
plasma_org_final.to_csv('data/plasma_org_df.csv', index=False)
plasma_donor_final.to_csv('data/plasma_donor_df.csv', index=False)


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

@pytest.fixture
def driver():
    wd = webdriver.Chrome()
    wd.quit
    return wd

def login(driver, url):
    if url is None:
        driver.get("http://www.litecart.com/admin/")

    else:
        driver.get(url)
    driver.find_element_by_name('username').send_keys('admin')
    driver.find_element_by_name('password').send_keys('admin')
    driver.find_element_by_name('login').click()
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'div.logotype')))
    return driver

def test_countries(driver):
    link = "http://www.litecart.com/admin/?app=countries&doc=countries"
    test_driver = login(driver, link)
    countries_links = test_driver.find_elements(By.CSS_SELECTOR, '.dataTable .row a:not([title="Edit"])')
    countries = []
    contries_for_checking = []
    for link in countries_links:
        countries.append(link.text)
    contries_for_checking = countries.copy()
    contries_for_checking.sort()
    for i, country in enumerate(countries):
        if contries_for_checking[i] == country:
            print('For', i, '-th value', country, 'pass')
        else:
            print('For', i, '-th value', country, 'FAIL')
        assert contries_for_checking[i] == country

test_data_for_checking_sorting = [
    ('countries&doc=countries',
     'Name',
     ') :not([value=""])',
     'countries'
     ),
    ('geo_zones&doc=geo_zones',
     'Zone',
     ') option[selected]',
     'geo_zone'
     )
]

@pytest.mark.parametrize("target,header_text,end_locator_for_zones,start_page",
                         test_data_for_checking_sorting)
def test_dda_geozones(driver,
                  target,
                  header_text,
                  end_locator_for_zones,
                  start_page):
    '''

    :param driver:
    :param target:  окончание ссылки для функции get
    :param header_text: текст для пределения колонки для поиска названия зон/стран
    :param end_locator_for_zones: отличие в локаторе для поиска зон/стран
    :param start_page:  часть ссылки для возрата к начальной странице теста
    :return:
    '''
    link = 'http://www.litecart.com/admin/?app=' + target
    test_driver = login(driver, link)
    headers = test_driver.find_elements(By.CSS_SELECTOR, '.dataTable .header th')
    number_column_of_zones = 0
    for i, header in enumerate(headers):
        if header.text == "Zones":
            # print(header.text)
            number_column_of_zones = i + 1
            break
    geozones = test_driver.find_elements(
        By.CSS_SELECTOR, '.dataTable .row :nth-child(' + str(number_column_of_zones) + ')')
    numbers_links = []
    for i, geozone in enumerate(geozones):
        if geozone.text != '0':
            numbers_links.append(i)
    for number in numbers_links:
        countries_links = test_driver.find_elements(By.CSS_SELECTOR, '.dataTable .row a:not([title="Edit"])')
        name_counrty = countries_links[number].text
        countries_links[number].click()
        number_column_of_names = 0
        headers_zones = test_driver.find_elements(By.CSS_SELECTOR, '.dataTable .header th')
        for i, header in enumerate(headers_zones):
            if header.text == header_text:
                number_column_of_names = i + 1
                break
        locator_for_zones = '.dataTable tr:not(.header) td:nth-child(' + \
                            str(number_column_of_names) + \
                            end_locator_for_zones
        namezones = test_driver.find_elements(By.CSS_SELECTOR, locator_for_zones)
        namezones_list = []
        namezones_list_for_checking = []
        for i, namezone in enumerate(namezones):
            namezones_list.append(namezone.text)
        namezones_list_for_checking = namezones_list.copy()
        namezones_list_for_checking.sort()
        # print('Zones:', namezones_list, '\nZones_sorted', namezones_list_for_checking)
        for i, namezone_item, in enumerate(namezones_list):
            if namezones_list_for_checking[i] == namezone_item:
                print('For', i, '-th value', namezone_item, 'for country', name_counrty, 'pass', )
            else:
                print('For', i, '-th value', namezone_item, 'for country', name_counrty, 'FAIL', )
            assert namezones_list_for_checking[i] == namezone_item
        locator_back_to_startpage = 'ul > li#app- > a[href*=' + start_page + ']'
        test_driver.find_element(By.CSS_SELECTOR, locator_back_to_startpage).click()


from tabulate import tabulate
from .utils.enums import ShipDirection, ShipType, SquareStatus

class Grid:
    '''
    Module for working with game grid.
    '''
    def __init__(self) -> None:
        self.__x = 10
        self.__y = 10
        self.__grid = list()

        for i in range(self.__y):
            self.__grid.append([SquareStatus.NONE] * self.__x)

    def get_grid(self):
        return self.__grid

    def put_ship_at(self, x: int, y: int, direction: ShipDirection, ship: ShipType):
        '''
        This method is used for placing ships onto the grid
        '''
        ship_length = ship.value

        while ship_length != 0:
            try:
                if direction == ShipDirection.HORIZONTAL:
                    self.create_ship_square_at(x, y)
                    x += 1
                else:
                    self.create_ship_square_at(x, y)
                    y += 1
            except IndexError:
                pass

            ship_length -= 1

    def create_ship_square_at(self, x: int, y: int) -> None:
        '''
        Creates ship square on the grid
        '''
        self.__grid[x][y] = SquareStatus.OCCUPIED

    def update_square(self, x: int, y: int, delete: bool = False, place: bool = False, type: SquareStatus = SquareStatus.NONE) -> str:
        '''
        Updates the status of squares on grid
        '''
        square = self.__grid[x][y]

        if delete:
            square = SquareStatus.NONE.value
            return
        if place:
            self.__grid[x][y] = type.value
            return

        if square == SquareStatus.DESTROYED or square == SquareStatus.MISS:
            return None
        elif square == SquareStatus.NONE.value or square == SquareStatus.NONE:
            square = SquareStatus.MISS
            return "Miss!"
        else:
            square = SquareStatus.DESTROYED
            return "Hit!!"

    def draw_grid(self):
        data = list()

        for i in range(10):
            copy = self.__grid[:]
            data.append(copy[i])
            for j in range(10):
                try:
                    data[i][j] = data[i][j].value
                except:
                    pass

        print(tabulate(data, tablefmt="grid"))


import random
import threading
import time

# 创建信号量，初始个数为0
semaphore = threading.Semaphore(0)

# 消费者
def consumer():
    # 信号量计数器减1
    semaphore.acquire()
    print(f'conumser:number is {number}')

def producer():
    global number
    time.sleep(1)
    number = random.randint(0, 100)
    print(f'producer:number is {number}')
    # 信号量计数器加1
    semaphore.release()

if __name__ == '__main__':
    c = threading.Thread(target=consumer)
    p = threading.Thread(target=producer)
    c.start()
    p.start()
    print('Done')


"""

File: filter_trainer.py
Author: Nrupatunga
Email: nrupatunga.s@byjus.com
Github: https://github.com/nrupatunga
Description: trainer code
"""

import pytorch_lightning as pl

from custom_nets import FIP

class LitModel(pl.LightningModule):

    """Docstring for LitModel. """

    def __init__(self,
                 data_dir: str,
                 batch_size: int,
                 num_workers: int = 6,
                 lr: float = 1e-4,
                 **kwargs) -> None:
        """
        @lr: learning rate
        """
        super().__init__()

        self.model = FIP()
        self.save_hyperparameters()

    def forward(self, x):
        """forward function for litmodel
        """
        return self.model(x)


# MLP 26 november

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from matplotlib import pyplot
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
import os
import datetime
import math

import IPython
import IPython.display

import matplotlib as mpl
import seaborn as sns
import tensorflow as tf

from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import MinMaxScaler

from keras.models import Sequential
from keras.layers import Dense
from keras import metrics
import statsmodels.api as sm

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.neural_network import MLPRegressor

df = pd.read_csv('dataset.csv',sep = ';', nrows = 17544)

a = [str(date) for date in df['datetime']]
a = [date[:-6] for date in a]
date_time = pd.to_datetime(a)

df.loc[:,['datetime']] = date_time
df = df.set_index('datetime')

timestamp_s = date_time.map(pd.Timestamp.timestamp)
day = 24*60*60
week = 7*day
year = (365.2425)*day

df['day_sin'] = np.sin(timestamp_s * (2 * np.pi / day))
df['day_cos'] = np.cos(timestamp_s * (2 * np.pi / day))
df['week_sin'] = np.sin(timestamp_s * (2 * np.pi / week))
df['week_cos'] = np.cos(timestamp_s * (2 * np.pi / week))
df['year_sin'] = np.sin(timestamp_s * (2 * np.pi / year))
df['year_cos'] = np.cos(timestamp_s * (2 * np.pi / year))

# Evolution of the features over time:
plot_cols = ['demanda_p48', 'eolica_p48', 'precio_spot']
plot_features = df[plot_cols]
_ = plot_features.plot(subplots=True)

#############################################
# Regressive predictors

# For non vectorized models

#################### TRAINING
# Demand

d_t1 = []
e_t1 = []
d_t2 = []
e_t2 = []
d_t3 = []
e_t3 = []
d_t4 = []
e_t4 = []
d_t24 = []
e_t24 = []
d_t168 = []
e_t168 = []
day_sin_train = []
day_cos_train = []
week_sin_train = []
week_cos_train = []
year_sin_train = []
year_cos_train = []

train_hours = int(0.7*len(df))+2
validation_hours = int(0.15*len(df))
test_hours = int(0.15*len(df))

train_hours+validation_hours+test_hours == len(df)

len(df)
for i in range(167, train_hours):

    d_t1.append(df.demanda_p48[i-1])
    e_t1.append(df.eolica_p48[i-1])

    d_t2.append(df.demanda_p48[i-2])
    e_t2.append(df.eolica_p48[i-2])

    d_t3.append(df.demanda_p48[i-3])
    e_t3.append(df.eolica_p48[i-3])

    d_t4.append(df.demanda_p48[i-4])
    e_t4.append(df.eolica_p48[i-4])

    d_t24.append(df.demanda_p48[i-24])
    e_t24.append(df.eolica_p48[i-24])

    d_t168.append(df.demanda_p48[i-168])
    e_t168.append(df.eolica_p48[i-168])

    day_sin_train.append(df.day_sin[i])
    day_cos_train.append(df.day_cos[i])
    week_sin_train.append(df.week_sin[i])
    week_cos_train.append(df.week_cos[i])
    year_sin_train.append(df.year_sin[i])
    year_cos_train.append(df.year_cos[i])

d_t1 = np.array(d_t1)
e_t1 = np.array(e_t1)
d_t2 = np.array(d_t2)
e_t2 = np.array(e_t2)
d_t3 = np.array(d_t3)
e_t3 = np.array(e_t3)
d_t4 = np.array(d_t4)
e_t4 = np.array(e_t4)
d_t24 = np.array(d_t24)
e_t24 = np.array(e_t24)
d_t168 = np.array(d_t168)
e_t168 = np.array(e_t168)
day_sin_train = np.array(day_sin_train)
day_cos_train = np.array(day_cos_train)
week_sin_train = np.array(week_sin_train)
week_cos_train = np.array(week_cos_train)
year_sin_train = np.array(year_sin_train)
year_cos_train = np.array(year_cos_train)

########### VALIDATION

d_t1_val = []
e_t1_val = []
d_t2_val = []
e_t2_val = []
d_t3_val = []
e_t3_val = []
d_t4_val = []
e_t4_val = []
d_t24_val = []
e_t24_val = []
d_t168_val = []
e_t168_val = []
day_sin_val = []
day_cos_val = []
week_sin_val = []
week_cos_val = []
year_sin_val = []
year_cos_val = []

for i in range(train_hours, train_hours + validation_hours):

    d_t1_val.append(df.demanda_p48[i-1])
    e_t1_val.append(df.eolica_p48[i-1])

    d_t2_val.append(df.demanda_p48[i-2])
    e_t2_val.append(df.eolica_p48[i-2])

    d_t3_val.append(df.demanda_p48[i-3])
    e_t3_val.append(df.eolica_p48[i-3])

    d_t4_val.append(df.demanda_p48[i-4])
    e_t4_val.append(df.eolica_p48[i-4])

    d_t24_val.append(df.demanda_p48[i-24])
    e_t24_val.append(df.eolica_p48[i-24])

    d_t168_val.append(df.demanda_p48[i-168])
    e_t168_val.append(df.eolica_p48[i-168])

    day_sin_val.append(df.day_sin[i])
    day_cos_val.append(df.day_cos[i])
    week_sin_val.append(df.week_sin[i])
    week_cos_val.append(df.week_cos[i])
    year_sin_val.append(df.year_sin[i])
    year_cos_val.append(df.year_cos[i])

d_t1_val = np.array(d_t1_val)
e_t1_val = np.array(e_t1_val)
d_t2_val = np.array(d_t2_val)
e_t2_val = np.array(e_t2_val)
d_t3_val = np.array(d_t3_val)
e_t3_val = np.array(e_t3_val)
d_t4_val = np.array(d_t4_val)
e_t4_val = np.array(e_t4_val)
d_t24_val = np.array(d_t24_val)
e_t24_val = np.array(e_t24_val)
d_t168_val = np.array(d_t168_val)
e_t168_val = np.array(e_t168_val)
day_sin_val = np.array(day_sin_val)
day_cos_val = np.array(day_cos_val)
week_sin_val = np.array(week_sin_val)
week_cos_val = np.array(week_cos_val)
year_sin_val = np.array(year_sin_val)
year_cos_val = np.array(year_cos_val)

########### TEST

d_t1_test = []
e_t1_test = []
d_t2_test = []
e_t2_test = []
d_t3_test = []
e_t3_test = []
d_t4_test = []
e_t4_test = []
d_t24_test = []
e_t24_test = []
d_t168_test = []
e_t168_test = []
day_sin_test = []
day_cos_test = []
week_sin_test = []
week_cos_test = []
year_sin_test = []
year_cos_test = []

for i in range(train_hours+validation_hours, len(df)):

    d_t1_test.append(df.demanda_p48[i-1])
    e_t1_test.append(df.eolica_p48[i-1])

    d_t2_test.append(df.demanda_p48[i-2])
    e_t2_test.append(df.eolica_p48[i-2])

    d_t3_test.append(df.demanda_p48[i-3])
    e_t3_test.append(df.eolica_p48[i-3])

    d_t4_test.append(df.demanda_p48[i-4])
    e_t4_test.append(df.eolica_p48[i-4])

    d_t24_test.append(df.demanda_p48[i-24])
    e_t24_test.append(df.eolica_p48[i-24])

    d_t168_test.append(df.demanda_p48[i-168])
    e_t168_test.append(df.eolica_p48[i-168])

    day_sin_test.append(df.day_sin[i])
    day_cos_test.append(df.day_cos[i])
    week_sin_test.append(df.week_sin[i])
    week_cos_test.append(df.week_cos[i])
    year_sin_test.append(df.year_sin[i])
    year_cos_test.append(df.year_cos[i])

d_t1_test = np.array(d_t1_test)
e_t1_test = np.array(e_t1_test)
d_t2_test = np.array(d_t2_test)
e_t2_test = np.array(e_t2_test)
d_t3_test = np.array(d_t3_test)
e_t3_test = np.array(e_t3_test)
d_t4_test = np.array(d_t4_test)
e_t4_test = np.array(e_t4_test)
d_t24_test = np.array(d_t24_test)
e_t24_test = np.array(e_t24_test)
d_t168_test = np.array(d_t168_test)
e_t168_test = np.array(e_t168_test)
day_sin_test = np.array(day_sin_test)
day_cos_test = np.array(day_cos_test)
week_sin_test = np.array(week_sin_test)
week_cos_test = np.array(week_cos_test)
year_sin_test = np.array(year_sin_test)
year_cos_test = np.array(year_cos_test)

# Defining the exogenous variables and the target
# Non vectorized models
# We take demand and eolic from that hour, the previous 3 hours, one day before and one week before
X_train = [d_t1, e_t1, d_t2, e_t2, d_t3, e_t3, d_t4, e_t4, d_t24, e_t24, d_t168, e_t168, day_sin_train, day_cos_train, week_sin_train, week_cos_train, year_sin_train, year_cos_train]
X_train.d_t1

X_train = pd.DataFrame(data={'d_t1':d_t1, 'e_t1':e_t1, 'd_t2':d_t2, 'e_t2':e_t2, 'd_t3':d_t3, 'e_t3':e_t3, 'd_t4':d_t4, 'e_t4':e_t4, 'd_t24':d_t24, 'e_t24':e_t24, 'd_t168':d_t168, 'e_t168':e_t168, 'day_sin':day_sin_train, 'day_cos':day_cos_train, 'week_sin':week_sin_train, 'week_cos':week_cos_train, 'year_sin':year_sin_train, 'year_cos':year_cos_train})
X_test = pd.DataFrame(data={'d_t1':d_t1_test, 'e_t1':e_t1_test, 'd_t2':d_t2_test, 'e_t2':e_t2_test, 'd_t3':d_t3_test, 'e_t3':e_t3_test, 'd_t4':d_t4_test, 'e_t4':e_t4_test, 'd_t24':d_t24_test, 'e_t24':e_t24_test, 'd_t168':d_t168_test, 'e_t168':e_t168_test, 'day_sin':day_sin_test, 'day_cos':day_cos_test, 'week_sin':week_sin_test,'week_cos': week_cos_test, 'year_sin':year_sin_test, 'year_cos':year_cos_test})

X_val = [d_t1_val, e_t1_val, d_t2_val, e_t2_val, d_t3_val, e_t3_val, d_t4_val, e_t4_val, d_t24_val, e_t24_val, d_t168_val, e_t168_val, day_sin_val, day_cos_val, week_sin_val, week_cos_val, year_sin_val, year_cos_val]
X_test = [d_t1_test, e_t1_test, d_t2_test, e_t2_test, d_t3_test, e_t3_test, d_t4_test, e_t4_test, d_t24_test, e_t24_test, d_t168_test, e_t168_test, day_sin_test, day_cos_test, week_sin_test, week_cos_test, year_sin_test, year_cos_test]

X_train = np.array(X_train)
X_val = np.array(X_val)
X_test = np.array(X_test)

X_train.shape

X_train = np.reshape(X_train, (X_train.shape[1], X_train.shape[0], 1))
X_val = np.reshape(X_val, (X_val.shape[1], X_val.shape[0], 1))
X_test = np.reshape(X_test, (X_test.shape[1], X_test.shape[0], 1))

# X_train = pd.DataFrame(X_train)

y_train = np.array(df.precio_spot[167: train_hours])
y_val = np.array(df.precio_spot[train_hours: -test_hours])
y_test = np.array(df.precio_spot[-test_hours:])

len(y_train) == len(X_train)
len(y_val) == len(X_val)
len(y_test) == len(X_test)

# MLP
df_mlp = MLPRegressor(hidden_layer_sizes=(2), max_iter=5000,
                               activation='relu',solver='adam', learning_rate='adaptive',
                               learning_rate_init= 0.0001, shuffle = False, alpha = 0.0005, random_state=1)

df_mlp.fit(X_train, y_train)

# evaluate the model on the second set of data

train_predictions = df_mlp.predict(X_train)

test_predictions = df_mlp.predict(X_test)

plt.plot(y_test, color = 'blue')
plt.plot(test_predictions, color = 'green')

print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, test_predictions))
print('Mean Squared Error:', metrics.mean_squared_error(y_test, test_predictions))
print('Root Mean Squared Error:', np.mean(np.sqrt(metrics.mean_squared_error(y_test, test_predictions))))

# Hyperparameter tuning
from sklearn.model_selection import GridSearchCV

param_grid = {
    'hidden_layer_sizes': [2],
    'max_iter': [50, 100, 500, 1000, 2000],
    'activation': ['tanh', 'relu'],
    'solver': ['sgd', 'adam'],
    'alpha': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05],
    'learning_rate': ['constant','adaptive'],
}

grid = GridSearchCV(df_mlp, param_grid, n_jobs= -1, cv=5)
grid.fit(X_train, y_train)


ErrNoGame = "No game in channel"
ErrNameAlreadyInUse = "Name already in use"
ErrUserAlreadyHasACharacter = "You already have a character"
ErrGameRunning = "Cannot do this while the game is running"
ErrGameNotRunning = "Game is not running"
ErrPlayerNotFound = "Player not found"
ErrNotEnoughPlayers = "Not enough players"
ErrorAPI = "Unexpected response from API"
ErrHostOnly = "Only host can do this"
ErrNotYourTurn = "Not your turn"
ErrHostNeedsName = "Host needs to join game"
ErrNoName = "Player name can't be empty"


#!/usr/bin/python3
import sys
import hashlib

hex_dict = { '0': 4, '1': 3, '2':2, '3':2, '4':1, '5':1, '6':1, '7':1, '8':0, '9':0, 'a':0, 'b':0, 'c':0, 'd':0, 'e':0,'f':0 }

def get_hash(str):
    m = hashlib.sha256()
    # m.update(bytes(str, 'utf-8')) # I did this when reading it in as r instead of rb mode
    m.update(str)
    return m.hexdigest()

def get_leading(hash):
    num_leading = 0
    for char in hash:
        if char != '0':
            break
        num_leading += 4

    return num_leading + hex_dict[ char.lower() ]

def main():
    if len( sys.argv ) != 3:
        print('Please input correct number of args')
        return -1

    header_file_name = sys.argv[1]
    text_file_name = sys.argv[2]

    header_file = open( header_file_name, 'r' )
    text_file = open( text_file_name, 'rb' )

    if not header_file:
        print('File cannot open')
        return -1
    if not text_file:
        print('File cannot open')
        return -1

    # create initial hash
    init_mes = text_file.read()
    init_calc_hash = get_hash( init_mes )

    # parse file line by line
    for line in header_file:
        # try to find the matching substrings
        if 'INITIAL-HASH: ' in line.upper():
            # find the initial_hash they gave us
            init_given_hash = line[ line.find(':')+2: ].strip()
            #print(line, end='')

        elif 'PROOF-OF-WORK: ' in line.upper():
            work = line[ line.find(':')+2: ].strip()
            #print(line,end='')

        elif 'HASH: ' in line.upper():
            final_given_hash = line[ line.find(':')+2: ].strip()
            #print(line,end='')

        elif 'LEADING-BITS: ' in line.upper():
            given_leading = line[ line.find(':')+2: ].strip()
            #print(line,end='')

    # check if each of the 4 things we need exist
    if not init_given_hash:
        print('No given initial hash')
        return -1

    if not work:
        print("No given work")
        return -1

    if not final_given_hash:
        print('No given hash')
        return -1

    if not given_leading:
        print('No given leading bits')
        return -1

    if init_calc_hash != init_given_hash:
        print('Initial hash does not match')
        return -1

    # calculate final hash
    final_mes = work + init_given_hash
    final_calc_hash = get_hash( str.encode( final_mes ) )

    if final_given_hash != final_calc_hash:
        print('Final hash does not match')
        return -1

    # calc num leading bits
    calc_leading = get_leading( final_given_hash )
    # need to try to cast leading bits to int
    try:
        given_leading = int(given_leading)
    except ValueError:
        print('Given leading bits is not a valid num')
        return -1

    if calc_leading != given_leading:
        print('Leading bits does not match')
        return -1

    print('pass')
    return 0

if __name__ == "__main__":
    main()


import unittest
from pyjsg.jsglib.loader import loads as jsg_loads

from ShExJSG import ShExJ

shex = """{
  "@context": [
      "http://www.w3.org/ns/shex.jsonld",
      {
         "@base": "http://bioentity.io/vocab/"
      }
   ],
  "type": "Schema",
  "shapes": [
    {
      "id": "http://a.example/S1",
      "type": "Shape"
    }
  ]
}"""

class ContextTestCase(unittest.TestCase):
    def test_context(self):
        shema = jsg_loads(shex, ShExJ)
        self.assertTrue(True)

if __name__ == '__main__':
    unittest.main()