示例#1
0
class Stock(object):
    
    def __init__(self):
        self.db = Database()

    def increment_stock(self, book_ISBN, increment_amount):
        # Increment the stock in the stock table by the increment_amount
        # Check that the number the user entered > 0 
        if (increment_amount < 0):
            print("Please put in a value that is greater than 0")
            exit()

        query = "Update STOCK_LEVEL set AMOUNT = AMOUNT + %d where BOOK_ID = '%s'" %(increment_amount, book_ISBN)

        try:
            self.db._dbInsert(query)
        except Exception as e:
            print(e)

    def decrement_stock(self, book_ISBN, decrement_amount):
        # Decrement the stock in the stock table by the decrement_amoumt
        # Check that the number the user entered > 0
        if (decrement_amount < 0):
            print("Please put in a value that is greater than 0")
            exit()

        query = "Update STOCK_LEVEL set AMOUNT = AMOUNT - %d where BOOK_ID = '%s'" %(decrement_amount, book_ISBN)

        try:
            self.db._dbInsert(query)
        except Exception as e:
            print(e)
示例#2
0
 def __init__(self, node_name):
     self.name = node_name
     self.database = Database()
     self.json_array = self.database.get_questions_array(node_name)
     self.lang = Language()
     self.questions = {}
     self.hash = self.database.get_hash(node_name)
示例#3
0
class System(object):
    def __init__(self):
        self.db = Database()

    def add_book(self, book_name, book_ISBN, publication_date, price,
                 author_firstname, author_lastname):
        # Add the book to the database
        try:
            query1 = "Insert into BOOK values ('%s', '%s', '%s', %11.2f)" % (
                book_ISBN, book_name, publication_date, price)
            query2 = (
                "Insert into AUTHOR (GIVEN_NAME, LAST_NAME, BOOK_ID) values ('%s', '%s', '%s')"
                % (author_firstname, author_lastname, book_ISBN))
            self.db._dbInsert(query1)
            self.db._dbInsert(query2)
        except Exception as e:
            print(e)

    def delete_book(self, book_ISBN):
        # Remove the book from the database
        query = "Delete from BOOK where ISBN = '%s'" % (book_ISBN)
        try:
            self.db._dbInsert(query)
        except Exception as e:
            print(e)
示例#4
0
 def __init__(self):
     self.lang = Language()
     self.array = {}
     self.num = 0
     self.database = Database()
     data = self.database.get('/bots/students', '')
     for topic in data:
         self.array[topic] = BotStudent(topic)
示例#5
0
    def __init__(self):
        super().__init__()

        self.universal_font = QFont('Calibri', 13)

        self.set_UI()

        self.set_welcome_layout()

        self.db = Database()

        self.description_dict = {}

        self.code_dict = {}

        self.picture_dict = {}

        self.title = ""

        self.language = ""

        self.record_or_play = True  # record is True, play is False

        self.about_dict = {
            1:
            'LearningStep\n\nThis application is named LearningStep. The purpose is to learn and repeat self made text-lessons in intervals of time.',
            2:
            'Record New Task\n\nConstruct your own lesson in steps.\nProvide title as short description, choose language (field of interests) and by clicking next move forward lessons.'
            '\nOne step consists of description (upper text field) and code (lower text field).\nYou can also attach an image to every step.'
            '\nTo proceed next step, click Next button.\nWhen all steps are written, click Finish button to save the lesson.',
            3:
            'Play The Task\n\nPlay previously recorded task (choose from the table of available tasks).\nGo through all tasks by clicking Next button.\nAt first you see description and then code field.\n'
            'When you will walk through all steps you can decide whether this approach was satisfying. Only if so, task will be completed,\n updated to database '
            'and reminded after certain interval of time.',
            4:
            'Delete Task\n\nDelete task according to provided task ID.\nBe aware that images stored in database will also be deleted.',
            5:
            'Time intervals are:\n\n1 day, 3 days, 7 days, 10 days, 14 days, 28 days, 60 days, 90 days, 180 days...',
            6:
            'Credits:\n\nDariusz Giemza, 2019',
            7:
            ''
        }
    def __init__(self):
        self.screen = tkinter.Tk()
        self.screen.title("User Login")
        self.screen.geometry("300x150")

        self.username_label = tkinter.Label(self.screen,
                                            text="Username:"******"Password:"******"Login",
                                           command=self.login)

        self.create_account_button = tkinter.Button(
            self.screen,
            text="Create New Account",
            command=self.create_account)
        self.sign_up_button = tkinter.Button(self.screen,
                                             text="Sign Up",
                                             command=self.sign_up)

        self.username_label.grid(row=0, column=0)
        self.username_entry.grid(row=0, column=1)
        self.password_label.grid(row=1, column=0)
        self.password_entry.grid(row=1, column=1)
        self.login_button.grid(row=2, column=1)
        self.create_account_button.grid(row=3, column=1)

        # creates database
        self.user_login_database = Database("user_login_database.db")

        # creates table in user_login_database
        self.user_login_database.create_table("user_data_table",
                                              "(username, password)")

        self.user_login_database.print_table("user_data_table")
示例#7
0
class Tag(object):
    # Each book is associated with a one word tag
    def __init__(self):
        self.db = Database()

    def add_tag(self, book_ISBN, tag):
        # Adds tag to the book
        if not (re.match("\A[\w-]+\Z", tag)):
            print("Tag can only be a single word")
            exit()

        query = "Insert into BOOK_TAG (BOOK_ID, TAG) values ('%s', '%s')" % (
            book_ISBN, tag)
        try:
            self.db._dbInsert(query)
        except Exception as e:
            print(e)

    def remove_tag(self, book_ISBN):
        # Removes the tag from the book
        query = "Delete from BOOK_TAG where BOOK_ID = '%s'" % (book_ISBN)
        try:
            self.db._dbInsert(query)
        except Exception as e:
            print(e)

    def change_tag(self, book_ISBN, tag):
        # Changes the associated tag
        query = "Update BOOK_TAG set TAG = '%s' where BOOK_ID = '%s'" % (
            tag, book_ISBN)
        try:
            self.db._dbInsert(query)
        except Exception as e:
            print(e)
示例#8
0
 def __init__(self):
     self.keyboard = InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="/new_bot", callback_data='n')],[InlineKeyboardButton(text="/delete_bot", callback_data='d')],[InlineKeyboardButton(text="/start", callback_data='s')],[InlineKeyboardButton(text="/change_pwd", callback_data='c')]])
     self.boolvett={}
     self.unconfirmed_bot={}
     self.unc_del={}
     self.tree=Tree()
     self.user_request=self.tree.read_pwd()
     self.admin_pwd=self.tree.get_pwd_admin()
     self.select_str="Please select a topic:"
     self.singleton_id=BotId()
     self.singleton_ban=UserBanned()
     super().__init__(Database().get_creation(),self.message,self.query)
     self.singleton_id.set_bot("creation",super().get_bot())
     self.singleton_id.reset_key_id("creation")
示例#9
0
 def __init__(self):
     self.database = Database()
     self.admins = {}
     self.setted_lang = None
     self.nlp = None
     #with open (fileName,"r") as jfile:
     #self.user_lang=json.load(jfile)
     self.lang_strings = self.database.get_trans()
     self.switcher = {
         "it": "\U0001F1EE\U0001F1F9 IT \U0001F1EE\U0001F1F9",
         "de": "\U0001F1E9\U0001F1EA DE \U0001F1E9\U0001F1EA",
         "fr": "\U0001F1EB\U0001F1F7 FR \U0001F1EB\U0001F1F7",
         "en": "\U0001F1EC\U0001F1E7 EN \U0001F1EC\U0001F1E7",
         "es": "\U0001F1EA\U0001F1F8 ES \U0001F1EA\U0001F1F8"
     }
     self.switch_coll = {
         "it": "collaboratore",
         "de": "mitarbeiter",
         "fr": "collaborateur",
         "en": "collaborator",
         "es": "colaborador"
     }
     self.switch_teach = {
         "it": "professore",
         "de": "lehrer",
         "fr": "prof",
         "en": "teacher",
         "es": "profesor"
     }
     self.switch_nlp = {
         "it": self.it_fun,
         "de": self.de_fun,
         "fr": self.fr_fun,
         "en": self.en_fun,
         "es": self.es_fun
     }
示例#10
0
    class Singleton:
        def __init__(self):
            self.database = Database()
            self.banned_user = self.database.read_ban()

        def add_ban(self, chat_id):
            if chat_id in self.banned_user:
                self.banned_user[chat_id] += 1
            else:
                self.banned_user[chat_id] = 1
            self.write_ban()

        def del_ban(self, chat_id):
            if chat_id in self.banned_user:
                del self.banned_user[chat_id]
                self.write_ban()

        def check_ban(self, chat_id):
            if chat_id in self.banned_user and self.banned_user[chat_id] > 99:
                return True
            return False

        def write_ban(self):
            self.database.write_ban(self.banned_user)
示例#11
0
 def __init__(self):
     self.keyboard = InlineKeyboardMarkup(inline_keyboard=[
         [InlineKeyboardButton(text="/answer", callback_data='a')],
         [InlineKeyboardButton(text="/report", callback_data='r')],
         [InlineKeyboardButton(text="/start", callback_data='s')],
         [InlineKeyboardButton(text="/list", callback_data='l')],
         [InlineKeyboardButton(text="/free_list", callback_data='fl')],
         [InlineKeyboardButton(text="/ban", callback_data='b')],
         [InlineKeyboardButton(text="/ban_list", callback_data='bl')],
         [InlineKeyboardButton(text="/sban", callback_data='sb')],
         [InlineKeyboardButton(text="/change", callback_data='c')],
         [InlineKeyboardButton(text="/delete", callback_data='d')],
         [InlineKeyboardButton(text="/hints", callback_data='h')],
         [InlineKeyboardButton(text="/add_hint", callback_data='ah')],
         [
             InlineKeyboardButton(text="/change_lang",
                                  callback_data='cl')
         ],
         [
             InlineKeyboardButton(text="/change_role",
                                  callback_data='cr')
         ]
     ])
     self.tree = Tree()
     self.query_bool = {}
     self.lang_bool = {}
     self.query_bool = {}
     self.prev_lang = {}
     self.topic_name = {}
     self.is_logged = {}
     self.singleton_id = BotId()
     self.singleton_ban = UserBanned()
     super().__init__(Database().get_teacher(), self.message,
                      self.query)
     self.tree.send_notification_teacher(super().get_bot())
     self.singleton_id.set_bot("teacher", super().get_bot())
     self.singleton_id.reset_key_id("teacher")
示例#12
0
 def __init__(self, topic):
     self.keyboard = InlineKeyboardMarkup(inline_keyboard=[
         [InlineKeyboardButton(text="/list", callback_data='l')],
         [InlineKeyboardButton(text="/question", callback_data='q')],
         [InlineKeyboardButton(text="/report", callback_data='r')],
         [InlineKeyboardButton(text="/start", callback_data='s')],
         [InlineKeyboardButton(text="/revision", callback_data='rv')],
         [InlineKeyboardButton(text="/change_lang", callback_data='cl')],
         [
             InlineKeyboardButton(text="/delete_subscription",
                                  callback_data='ds')
         ]
     ])
     database = Database()
     self.students = database.get_stud_ids(topic)
     self.teachers = database.get_teach_ids(topic)
     self.collaborators = database.get_coll_ids(topic)
     self.node = Node(topic)
     self.banned_user = database.get_banned_stud(topic)
     self.singleton = BotId()
     super().__init__(database.get_topic_token(topic), self.message,
                      self.query)
     self.singleton.set_bot(self.node.get_topic_name(), super().get_bot())
     self.singleton.reset_key_id(topic)
示例#13
0
 def __init__(self):
     self.database = Database()
     self.banned_user = self.database.read_ban()
from database_class import Database

# creates database
user_login_database = Database("user_login_database.db")

# creates table in user_login_database
user_login_database.create_table("user_data_table", "(username, password)")

user_login_database.print_table("user_data_table")
print('\n')

print("Please enter your username.")
user_info = user_login_database.check_exists("user_data_table", input())
print(user_info)

if user_info:
    print("Please enter your password.")
    if input() == user_info[1]:
        print("Success!")
    else:
        print("incorrect password")

else:
    print(
        "This username does not exist. Would you like to create a new account? [yes, no]"
    )
    while True:
        create = input()
        if create in ["yes", "Yes"]:
            print("Please enter a new username.")
            new_username = input()
示例#15
0
    class Singleton:
        def __init__(self):
            self.database = Database()
            self.admins = {}
            self.setted_lang = None
            self.nlp = None
            #with open (fileName,"r") as jfile:
            #self.user_lang=json.load(jfile)
            self.lang_strings = self.database.get_trans()
            self.switcher = {
                "it": "\U0001F1EE\U0001F1F9 IT \U0001F1EE\U0001F1F9",
                "de": "\U0001F1E9\U0001F1EA DE \U0001F1E9\U0001F1EA",
                "fr": "\U0001F1EB\U0001F1F7 FR \U0001F1EB\U0001F1F7",
                "en": "\U0001F1EC\U0001F1E7 EN \U0001F1EC\U0001F1E7",
                "es": "\U0001F1EA\U0001F1F8 ES \U0001F1EA\U0001F1F8"
            }
            self.switch_coll = {
                "it": "collaboratore",
                "de": "mitarbeiter",
                "fr": "collaborateur",
                "en": "collaborator",
                "es": "colaborador"
            }
            self.switch_teach = {
                "it": "professore",
                "de": "lehrer",
                "fr": "prof",
                "en": "teacher",
                "es": "profesor"
            }
            self.switch_nlp = {
                "it": self.it_fun,
                "de": self.de_fun,
                "fr": self.fr_fun,
                "en": self.en_fun,
                "es": self.es_fun
            }

        def it_fun(self):
            self.nlp = spacy.load('it_core_news_sm')
            model = Word2Vec.load(
                'wiki_iter=5_algorithm=skipgram_window=10_size=300_neg-samples=10.m'
            )
            keys = []
            for idx in range(733392):
                keys.append(model.wv.index2word[idx])
            self.nlp.vocab.vectors = spacy.vocab.Vectors(data=model.wv.vectors,
                                                         keys=keys)

        def de_fun(self):
            self.nlp = spacy.load('de_core_news_md')

        def fr_fun(self):
            self.nlp = spacy.load('fr_core_news_md')

        def en_fun(self):
            self.nlp = spacy.load('en_core_web_lg')

        def es_fun(self):
            self.nlp = spacy.load('es_core_news_md')

        def get_lang_by_flag(self, flag):
            for elem in self.switcher:
                if flag == self.switcher.get(elem, ""):
                    return elem
            return None

        def get_flag_list(self):
            return [
                "\U0001F1EE\U0001F1F9 IT \U0001F1EE\U0001F1F9",
                "\U0001F1E9\U0001F1EA DE \U0001F1E9\U0001F1EA",
                "\U0001F1EB\U0001F1F7 FR \U0001F1EB\U0001F1F7",
                "\U0001F1EC\U0001F1E7 EN \U0001F1EC\U0001F1E7",
                "\U0001F1EA\U0001F1F8 ES \U0001F1EA\U0001F1F8"
            ]

        def match_array(self, txt, lang, vett):
            e = ''
            val = 0
            for elem in vett:
                num = self.calculate_similarity(txt, elem, lang)
                if num > val:
                    val = num
                    e = elem
            if val > 0.8:
                return e
            return None

        def set_nlp(self, lang):
            if self.setted_lang != lang:
                self.switch_nlp.get(lang, lambda: None)()
                self.setted_lang = lang

        def check_lang_str(self, txt, string):
            for lang in self.lang_strings:
                if self.lang_strings[lang][string] == txt:
                    return True
            return False

        def question_sent(self, lang, text):
            data = []
            trans = Translator()
            for elem in self.nlp(text).sents:
                string = elem.text
                if string.endswith("?") and lang == trans.translate(
                        string).src:
                    data.append(string)
            return data

        def check_teach(self, lang, text):
            return text == self.switch_teach.get(lang)

        def check_coll(self, lang, text):
            return text == self.switch_coll.get(lang)

        def printx(self, string, xxx=None, yyy=None):
            array = []
            array1 = []
            if xxx != None:
                array = string.split("XXX")
            else:
                return string
            if yyy != None:
                array1 = array[1].split("YYY")
            else:
                return array[0] + xxx + array[1]
            return array[0] + xxx + array1[0] + yyy + array1[1]

        def add_admins(self, lang, vett):
            self.admins[lang] = vett

        def get_admins(self, lang):
            return self.admins[lang]

        def get_string(self, lang, string, xxx=None, yyy=None):
            if string == "start":
                xxx = self.translate(xxx, "en", lang)
            if lang in self.lang_strings and string in self.lang_strings[lang]:
                return self.printx(self.lang_strings[lang][string], xxx, yyy)
            return ""

        def set_keyboard(self, lang_array, bool_var=True):
            i = 0
            data = []
            l = 0
            for elem in lang_array:
                if i == 0:
                    data.append([])
                    l += 1
                data[l - 1].append(
                    KeyboardButton(text=self.switcher.get(elem, "")))
                i += 1
                i %= 2
            return ReplyKeyboardMarkup(keyboard=data,
                                       resize_keyboard=True,
                                       one_time_keyboard=True,
                                       selective=bool_var)

        def get_lang_board(self, lang, array, num=1):
            data = [[KeyboardButton(text=self.switch_coll.get(lang))],
                    [KeyboardButton(text=self.switch_teach.get(lang))]]
            return ReplyKeyboardMarkup(keyboard=data,
                                       resize_keyboard=True,
                                       one_time_keyboard=True,
                                       selective=False)

        def set_lang_resp(self, id, lang, bot):
            if bot["topic"] not in self.user_lang:
                self.user_lang[bot["topic"]] = {}
            self.user_lang[bot["topic"]][id] = lang
            with open(self.file, "w") as jfile:
                json.dump(self.user_lang, jfile)

        def calculate_similarity(self, text1, text2, lang):
            base = self.nlp(self.process_text(text1, lang))
            compare = self.nlp(self.process_text(text2, lang))
            num = base.similarity(compare)
            return num

        def process_text(self, string, lang):
            doc = self.nlp(string.lower())
            result = []
            for token in doc:
                if token.text in self.nlp.Defaults.stop_words:
                    continue
                if token.is_punct:
                    continue
                if token.lemma_ == '-PRON-':
                    continue
                result.append(token.lemma_)
            return " ".join(result)

        def translate(self, string, src, dest):
            trans = Translator()
            t = trans.translate(string, src=src, dest=dest)
            return t.text
示例#16
0
            food = 0
            while food not in [str(i) for i in range(1, 11)]:
                food = input('Votre choix: ')
            cursor = db.search_a_substitute(choose)
            prod = Product(cursor)
            prod.print_substitute()
            substitute = ""
            while substitute.lower() != 'q':
                print("\n", sub_menu)
                substitute = input("\nVotre choix: ")
                if substitute == '1':
                    db.save_a_product(prod.product)
                elif substitute == '2':
                    prod.search_internet(choose)
                    prod.print_substitute()
        elif choose == '2':
            cursor = db.search_already_saved()
            prod = Product(cursor)
            prod.print_saved()
            print("\n\n")
            input(back)
        elif choose == '3':
            break
    db.close_cnx()


if __name__ == "__main__":

    db = Database()
    main_menu()
示例#17
0
 def __init__(self):
     super().__init__(Database().get_getlink(), message=self.message)
     self.tree = Tree()
     self.Singleton = BotId()
     self.Singleton.set_bot("getlink", super().get_bot())
     self.Singleton.reset_key_id("getlink")
class UserLogin:
    def __init__(self):
        self.screen = tkinter.Tk()
        self.screen.title("User Login")
        self.screen.geometry("300x150")

        self.username_label = tkinter.Label(self.screen,
                                            text="Username:"******"Password:"******"Login",
                                           command=self.login)

        self.create_account_button = tkinter.Button(
            self.screen,
            text="Create New Account",
            command=self.create_account)
        self.sign_up_button = tkinter.Button(self.screen,
                                             text="Sign Up",
                                             command=self.sign_up)

        self.username_label.grid(row=0, column=0)
        self.username_entry.grid(row=0, column=1)
        self.password_label.grid(row=1, column=0)
        self.password_entry.grid(row=1, column=1)
        self.login_button.grid(row=2, column=1)
        self.create_account_button.grid(row=3, column=1)

        # creates database
        self.user_login_database = Database("user_login_database.db")

        # creates table in user_login_database
        self.user_login_database.create_table("user_data_table",
                                              "(username, password)")

        self.user_login_database.print_table("user_data_table")

    def login(self):
        self.username = self.username_entry.get()
        self.password = self.password_entry.get()

        self.user_info = self.user_login_database.check_exists(
            "user_data_table", self.username)

        if self.user_info:
            if self.password in self.user_info:
                tkinter.messagebox.showinfo(message="Success!")
                self.username_entry.delete(0, tkinter.END)
                self.password_entry.delete(0, tkinter.END)

            else:
                tkinter.messagebox.showwarning(message="Incorrect password.")
                self.password_entry.delete(0, tkinter.END)

        else:
            tkinter.messagebox.showwarning(message="Username does not exist.")

    def create_account(self):
        self.login_button.grid_forget()
        self.create_account_button.grid_forget()

        self.sign_up_button.grid(row=2, column=1)

    def sign_up(self):
        self.username = self.username_entry.get()
        self.password = self.password_entry.get()

        self.username_entry.delete(0, tkinter.END)
        self.password_entry.delete(0, tkinter.END)

        self.user_login_database.add_record("user_data_table", 2,
                                            [(self.username, self.password)])

        self.sign_up_button.grid_forget()
        self.login_button.grid(row=2, column=1)
        self.create_account_button.grid(row=3, column=1)

    def run(self):
        self.screen.mainloop()
示例#19
0
 def __init__(self):
     self.db = Database()
示例#20
0
import tkinter as tk
from tkinter import *

# importing tkinter as themed-tkinter module
import tkinter.ttk as ttk

from tkinter import messagebox, scrolledtext, PhotoImage

# importing Database class from custom sqlite database file
from database_class import Database

# Regular Expression for checking the validity of Entered User Details.
import re

# Creating an instance of the Database Class
my_db = Database('bank_record')

root = tk.Tk()

# rootdows Dimensions
root.geometry('400x600')
root.minsize(400, 600)
root.maxsize(400, 600)

# Configuring the style for the themed-tkinter module
style = ttk.Style()

# Title for the rootdow
root.title('My Database App')

#---------------------- User Details ----------------------------
示例#21
0
    class Singleton:
        def __init__(self):
            self.database = Database()
            self.id_commands = {}
            self.id_times = {}
            self.bot_array = {}
            self.key_id = self.database.get_key_id()

        def reset_key_id(self, name):
            if name in self.key_id:
                for chat_id in self.key_id[name]:
                    edit_message(self.bot_array[name],
                                 (chat_id, self.key_id[name][chat_id]))
                del self.key_id[name]
                self.database.del_key_id(name)

        def set_key_id(self, msg_id, name):
            chat_id = msg_id[0]
            if name in self.key_id:
                if chat_id in self.key_id[name]:
                    edit_message(self.bot_array[name],
                                 (chat_id, self.key_id[name][chat_id]))
            else:
                self.key_id[name] = {}
            self.key_id[name][chat_id] = msg_id[1]
            self.database.set_key_id(name, self.key_id[name])

        def start_fun(self, chat_id, from_id, chat_type, lang, lang_class,
                      name, topic, keyboard):
            user = self.bot_array[name].getChat(from_id)
            send_message(
                self.bot_array[name], chat_id,
                tag_group(chat_type, user) +
                lang_class.get_string(lang, "start", xxx=topic))
            try:
                self.set_key_id(
                    telepot.message_identifier(
                        send_message(self.bot_array[name],
                                     chat_id,
                                     lang_class.get_string(lang, "command"),
                                     reply_markup=keyboard)), name)
            except TypeError:
                pass

        def set_bot(self, name, bot):
            self.bot_array[name] = bot

        def add_elem_id(self, array, name, id1, id2):
            if name not in array:
                array[name] = {}
            if id1 not in array[name]:
                array[name][id1] = []
            array[name][id1].append(id2)
            return array

        def delete_elem_id(self, array, name, id1, id2):
            array[name][id1].remove(id2)
            if len(array[name][id1]) == 0:
                del array[name][id1]
            if len(array[name]) == 0:
                del array[name]
            return array

        def sub_smi(self, time, index, name, elem, elem1):
            if elem == elem1:
                if time == None or time < self.id_times[name][elem]:
                    time = self.id_times[name][elem]
                    index = [name, elem, elem1]
                else:
                    if time == None or time < self.id_times[name][elem][elem1]:
                        time = self.id_times[name][elem][elem1]
                        index = [name, elem, elem1]
            return time, index

        def set_max_index(self, old_array):
            time = None
            index = []
            for name in old_array:
                for elem in old_array[name]:
                    for elem1 in old_array[name][elem]:
                        time, index = self.sub_smi(time, index, name, elem,
                                                   elem1)
            return index

        def delete_old_branchone(self, old_array, count, max_index, name,
                                 elem):
            for elem1 in self.id_times[name][elem]:
                if count < num:
                    old_array = self.add_elem_id(old_array, name, elem, elem1)
                    max_index = self.set_max_index(old_array)
                    count += 1
                elif max_index[0] == max_index[1] and self.id_times[name][
                        max_index[0]] > self.id_times[name][elem][elem1]:
                    old_array = self.delete_elem_id(old_array, name,
                                                    max_index[0], max_index[0])
                    old_array = self.add_elem_id(old_array, name, elem, elem1)
                    max_index = self.set_max_index(old_array)
                elif max_index[0] != max_index[1] and self.id_times[name][
                        max_index[0]][
                            max_index[1]] > self.id_times[name][elem][elem1]:
                    old_array = self.delete_elem_id(old_array, name,
                                                    max_index[0], max_index[1])
                    old_array = self.add_elem_id(old_array, name, elem, elem1)
                    max_index = self.set_max_index(old_array)
            return old_array, max_index, count

        def delete_old_branchtwo(self, old_array, count, max_index, name,
                                 elem):
            if count < num:
                old_array = self.add_elem_id(old_array, name, elem, elem)
                count += 1
            elif max_index[0] == max_index[1] and self.id_times[name][
                    max_index[0]] > self.id_times[name][elem]:
                old_array = self.delete_elem_id(old_array, name, max_index[0],
                                                max_index[0])
                old_array = self.add_elem_id(old_array, name, elem, elem)
                max_index = self.set_max_index(old_array)
            elif max_index[0] != max_index[1] and self.id_times[name][
                    max_index[0]][max_index[1]] > self.id_times[name][elem]:
                old_array = self.delete_elem_id(old_array, name, max_index[0],
                                                max_index[1])
                old_array = self.add_elem_id(old_array, name, elem, elem)
                max_index = self.set_max_index(old_array)
            return old_array, max_index, count

        def delete_old_branchthreeone(self, name, elem, lang_class, user):
            del self.id_times[name][elem]
            if name in self.id_commands and elem in self.id_commands[name]:
                send_message(self.bot_array[name], elem,
                             lang_class.get_string(lang, "timeout"))
                del self.id_commands[name][elem]
                if len(self.id_commands[name]) == 0:
                    del self.id_commands[name]

        def delete_old_branchthreetwo(self, name, elem, elem1, lang_class,
                                      user):
            del self.id_times[name][elem][elem1]
            if name in self.id_commands and elem in self.id_commands[
                    name] and elem1 in self.id_commands[name][elem]:
                send_message(
                    self.bot_array[name], elem,
                    tag_group(chat_type, user) +
                    lang_class.get_string(lang, "timeout"))
                del self.id_commands[name][elem][elem1]
                if len(self.id_commands[name][elem]) == 0:
                    del self.id_commands[name][elem]
                    if len(self.id_commands[name]) == 0:
                        del self.id_commands[name]
            if len(self.id_times[name][elem]) == 0:
                del self.id_times[name][elem]

        def delete_old_branchthree(self, old_array, count, max_index, name,
                                   elem, elem1, lang_class):
            user = bot.getChat(elem1)
            if elem == elem1:
                self.delete_old_branchthreeone(name, elem, lang_class, user)
            elif elem != elem1:
                self.delete_old_branchthreetwo(name, elem, elem1, lang_class,
                                               user)

        def delete_old(self, chat_type, lang_class, lang, num):
            old_array = {}
            count = 0
            max_index = []
            for name in self.id_times:
                for elem in self.id_times[name]:
                    if type(self.id_times[name][elem]) is dict:
                        old_array, max_index, count = self.delete_old_branchone(
                            old_array, count, max_index, name, elem)
                    elif type(self.id_times[name][elem]) is datetime.datetime:
                        old_array, max_index, count = self.delete_old_branchtwo(
                            old_array, count, max_index, name, elem)
            for name in old_array:
                for elem in old_array[name]:
                    for elem1 in old_array[name][elem]:
                        self.delete_old_branchthree(old_array, count,
                                                    max_index, name, elem,
                                                    elem1, lang_class)
                if len(self.id_times[name]) == 0:
                    del self.id_times[name]

        def add_elem(self, array, array1, elem, elem1, name):
            if elem1 != None:
                if elem not in array:
                    array[elem] = {}
                    array1[elem] = {}
                array[elem][elem1] = self.id_times[name][elem][elem1]
                if elem in self.id_commands[
                        name] and elem1 in self.id_commands[name][elem]:
                    array1[elem][elem1] = self.id_commands[name][elem][elem1]
                return array, array1
            array[elem] = self.id_times[name][elem]
            if elem in self.id_commands[name]:
                array1[elem] = self.id_commands[name][elem]
            return array, array1

        def sub_nv(self, new_times, new_ids, count, array, time, lang_class):
            user = bot.getChat(elem1)
            if self.id_times[array[0]][array[1]][array[2]] > time:
                new_times, new_ids = self.add_elem(new_times, new_ids,
                                                   array[1], array[2],
                                                   array[0])
                count += 1
            elif array[0] in self.id_commands and array[1] in self.id_commands[
                    array[0]] and array[2] in self.id_commands[array[0]][
                        array[1]]:
                send_message(
                    self.bot_array[array[0]], array[1],
                    tag_group(chat_type, user) +
                    lang_class.get_string(lang, "timeout"))
            return new_times, new_ids, count

        def normalize_vect(self, chat_type, lang_class, lang, time, name):
            new_times = {}
            new_ids = {}
            count = 0
            for elem in self.id_times[name]:
                if type(self.id_times[name][elem]) is dict:
                    for elem1 in self.id_times[name][elem]:
                        new_times, new_ids, count = self.sub_nv(
                            new_times, new_ids, count, [name, elem, elem1],
                            time, lang_class)
                elif type(self.id_times[name][elem]) is datetime.datetime:
                    if self.id_times[name][elem] > time:
                        new_times, new_ids = self.add_elem(
                            new_times, new_ids, elem, None, name)
                        count += 1
                    elif name in self.id_commands and elem in self.id_commands[
                            name]:
                        send_message(self.bot_array[name], elem,
                                     lang_class.get_string(lang, "timeout"))
            self.id_times[name] = new_times
            self.id_commands[name] = new_ids
            return count

        def set_time(self, from_id, chat_id, name):
            if name not in self.id_times:
                self.id_times[name] = {}
            if from_id == chat_id:
                self.id_times[name][chat_id] = datetime.datetime.today()
            else:
                if chat_id not in self.id_times[name]:
                    self.id_times[name][chat_id] = {}
                self.id_times[name][chat_id][
                    from_id] = datetime.datetime.today()

        def sub_del_id(self, from_id, chat_id, name):
            if chat_id in self.id_commands[name]:
                if from_id in self.id_commands[name][chat_id]:
                    del self.id_commands[name][chat_id][from_id]
                if len(self.id_commands[name][chat_id]) == 0:
                    del self.id_commands[name][chat_id]

        def del_id(self, from_id, chat_id, name):
            if name in self.id_commands:
                if from_id == chat_id:
                    if chat_id in self.id_commands[name]:
                        del self.id_commands[name][chat_id]
                else:
                    sub_del_id(self, from_id, chat_id, name)
                if len(self.id_commands[name]) == 0:
                    del self.id_commands[name]

        def add_id(self, from_id, chat_id, val, name):
            if name not in self.id_commands:
                self.id_commands[name] = {}
            if from_id == chat_id:
                self.id_commands[name][chat_id] = val
            else:
                if chat_id not in self.id_commands[name]:
                    self.id_commands[name][chat_id] = {}
                self.id_commands[name][chat_id][from_id] = val

        def check_id(self, from_id, chat_id, name):
            ret_val = 0
            if name in self.id_commands:
                if from_id == chat_id:
                    if chat_id in self.id_commands[name]:
                        ret_val = self.id_commands[name][chat_id]
                else:
                    if chat_id in self.id_commands[
                            name] and from_id in self.id_commands[name][
                                chat_id]:
                        ret_val = self.id_commands[name][chat_id][from_id]
            return ret_val

        def delete_old_ids(self, chat_type, lang_class, lang):
            count = 0
            lim = 1000
            for id_name in self.id_commands:
                count += self.normalize_vect(
                    chat_type, lang_class, lang,
                    datetime.datetime.now() - datetime.timedelta(0, 300, 0),
                    id_name)
            if count > lim:
                self.delete_old(chat_type, lang_class, lang, count - lim)

        def add_time_id(self, chat_type, lang_class, lang, from_id, chat_id,
                        val, name):
            self.add_id(from_id, chat_id, val, name)
            self.set_time(from_id, chat_id, name)
            self.delete_old_ids(chat_type, lang_class, lang)

        def check_time_id(self, chat_type, lang_class, lang, from_id, chat_id,
                          name):
            num = self.check_id(from_id, chat_id, name)
            self.set_time(from_id, chat_id, name)
            self.delete_old_ids(chat_type, lang_class, lang)
            return num

        def del_time_id(self, chat_type, lang_class, lang, from_id, chat_id,
                        name):
            self.del_id(from_id, chat_id, name)
            self.set_time(from_id, chat_id, name)
            self.delete_old_ids(chat_type, lang_class, lang)
示例#22
0
 def __init__(self):
     self.database = Database("phonebook_database.db")
     self.database.create_table("phonebook", "(first_name, last_name, phone_number)")
示例#23
0
import time
from tree_class import Tree
from database_class import Database
from bot_admin_class import BotAdmin
from bot_creation_class import BotCreation
from bot_getlink_class import BotGetlink
from bot_pwd_class import BotPwd
from bot_teacher_class import BotTeacher

database=Database()
bot_admin=BotAdmin()
bot_pwd=BotPwd()
database.set_bot_pwd(bot_pwd)
database.set_bot_admin(bot_admin)
tree=Tree()
bot_creation=BotCreation()
bot_getlink=BotGetlink()
teacher=database.get_teacher()
bot_teacher=BotTeacher()
database.set_bot_teacher(bot_teacher)

print("Init complete")

while True:
    time.sleep(10)
示例#24
0
class Phonebook:

    def __init__(self):
        self.database = Database("phonebook_database.db")
        self.database.create_table("phonebook", "(first_name, last_name, phone_number)")

    def print(self):
        self.database.print_table("phonebook")
        print()

    def add_entry(self):
        print("please enter your first name")
        first_name = input()
        print()

        print("please enter your last name")
        last_name = input()
        print()

        print("please enter your phone number")
        phone_number = input()
        print()

        self.database.add_record("phonebook", 3, [(first_name, last_name, phone_number)])
        print("successfully created \n")

    def delete_entry(self):
        while True:
            print("Please enter the first name of the entry that you want to delete. Type exit to leave.\n")
            entry_to_delete = input()

            if self.database.check_exists("phonebook", entry_to_delete):
                self.database.delete_record("phonebook", "first_name", entry_to_delete)
                print("successfully deleted \n")
                break

            elif entry_to_delete == "exit":
                print()
                break

            else:
                print("that entry does not exist \n")

    def close(self):
        self.database.close()
示例#25
0
class Node:
    def __init__(self, node_name):
        self.name = node_name
        self.database = Database()
        self.json_array = self.database.get_questions_array(node_name)
        self.lang = Language()
        self.questions = {}
        self.hash = self.database.get_hash(node_name)

    def verify_password(self, provided_password):
        stored_password = self.hash
        salt = stored_password[:64]
        stored_password = stored_password[64:]
        pwdhash = hashlib.pbkdf2_hmac('sha512',
                                      provided_password.encode('utf-8'),
                                      salt.encode('ascii'), 100000)
        pwdhash = binascii.hexlify(pwdhash).decode('ascii')
        return pwdhash == stored_password

    def change_pwd(self, password):
        self.hash = password
        self.database.set_new_pwd(self.name, password)

    def set_teach_ids(self, array, lang):
        self.database.set_teach_ids(array, self.name, lang)

    def set_coll_ids(self, array, lang):
        self.database.set_coll_ids(array, self.name, lang)

    def get_topic_name(self):
        return self.name

    def get_json_array(self, lang):
        if lang not in self.json_array:
            return None
        return self.json_array[lang]

    def get_response(self, txt, lang):
        if lang in self.json_array and txt in self.json_array[lang]:
            return self.json_array[lang][txt]["answer"]
        return None

    def normalize_vect(self, vect):
        array = sorted(vect.items(), key=operator.itemgetter(1), reverse=True)
        i = 0
        list1 = []
        for elem in array:
            if i == 4:
                break
            for e in elem:
                list1.append(e)
                break
            i += 1
        return list1

    def get_best_resp(self, txt, lang):
        list1 = {}
        for question in self.json_array[lang]:
            num = self.lang.calculate_similarity(txt, question, lang)
            if num > 0.8:
                list1[question] = num
        return self.normalize_vect(list1)

    def get_bot_teacher(self):
        return self.database.get_bot_teacher()

    def set_question(self, question, lang, chat_id):
        if lang not in self.json_array:
            self.json_array[lang] = {}
        self.json_array[lang][question] = {}
        self.json_array[lang][question]["ids"] = [chat_id]
        self.json_array[lang][question]["answer"] = ""
        self.database.set_questions_array(self.json_array[lang], self.name,
                                          lang)

    def get_sent(self, lang, txt):
        return self.lang.question_sent(lang, txt)

    def check_lang_str(self, txt, string):
        return self.lang.check_lang_str(txt, string)

    def set_nlp(self, lang):
        self.lang.set_nlp(lang)

    def get_flag_list(self):
        return self.lang.get_flag_list()

    def get_lang_by_flag(self, flag):
        return self.lang.get_lang_by_flag(flag)

    def get_q_array(self, chat_id, lang):
        data = []
        for elem in self.json_array[lang]:
            string = elem
            if "answer" in self.json_array[lang][elem] and self.json_array[
                    lang][elem]["answer"] != "BANNED" and self.json_array[
                        lang][elem]["answer"] != "":
                string += " -> " + self.json_array[lang][elem]["answer"]
            if chat_id in self.json_array[lang][elem]["ids"]:
                data.append(string)
        return data

    def set_lang_keyboard(self, array):
        return self.lang.set_keyboard(array)

    def write_data(self):
        self.database.write_data()

    def write_stud_lang(self, students, lang):
        self.database.write_stud_lang(self.name, students, lang)

    def get_lang(self):
        return self.lang

    def get_database(self):
        return self.database

    def get_string(self, lang, string, xxx=None, yyy=None):
        return self.lang.get_string(lang, string, xxx, yyy)

    def get_questions_array(self, array):
        data = {}
        lang_array = ["it", "de", "en", "es", "fr"]
        for lang in lang_array:
            if lang in array:
                data[lang] = array[lang]["questions"]
        return data

    def get_real_node(self, lang, question, lang_class):
        if lang in self.json_array:
            elem = self.lang.match_array(question, lang, self.json_array[lang])
            if elem != None:
                return self.name, elem
        for node in self.parents:
            node.get_real_node(lang, question, lang_class)
        return None, None

    def add_chat_id(self, question, lang, id):
        if lang in self.json_array and question in self.json_array[lang]:
            if id not in self.json_array[lang][question]["ids"]:
                self.json_array[lang][question]["ids"].append(id)
            return True
        for p in self.parents:
            if p.add_chat_id(question, lang, id):
                return True
        return False

    def set_student_id(self, vett):
        self.id_commands = vett

    def get_student_id(self):
        return self.id_commands

    def set_formatted_data(self):
        data = {}
        data["banned"] = self.bannedUser
        data["hash"] = self.hash
        data["token"] = self.token
        lang_array = ["it", "de", "en", "es", "fr"]
        for lang in lang_array:
            data[lang] = {}
            if lang in self.students:
                data[lang]["students"] = self.students[lang]
            if lang in self.teachers:
                data[lang]["teachers"] = self.teachers[lang]
            if lang in self.collaborators:
                data[lang]["collaborators"] = self.collaborators[lang]
            data[lang]["questions"] = self.json_array[lang]
        self.database.put("/bots/students", name=self.node_name, data=data)

    def sub_set_banned_users(self, lang_str, elem, users):
        if "answer" in self.json_array[lang_str][elem] and self.json_array[
                lang_str][elem]["answer"] == "BANNED":
            for chat_id in self.json_array[lang_str][elem]["ids"]:
                if chat_id in users:
                    users[chat_id] += 1
                else:
                    users[chat_id] = 1
        return users

    def set_banned_stud(self):
        users = {}
        banned = []
        for lang_str in self.json_array:
            for elem in self.json_array[lang_str]:
                users = self.sub_set_banned_users(lang_str, elem, users)
        for chat_id in users:
            if users[chat_id] > 10:
                banned.append(chat_id)
        self.database.set_banned_stud(self.name, banned)
        return banned

    def set_qid(self, chat_id, from_id, txt):
        if chat_id not in self.questions:
            self.questions[chat_id] = {}
        self.questions[chat_id][from_id] = txt

    def set_rv_comment(self, question, comment, lang):
        if lang not in self.json_array or question not in self.json_array[lang]:
            return False
        if "revision" not in self.json_array[lang][question]:
            self.json_array[lang][question]["revision"] = []
        if self.lang.match_array(
                comment, lang,
                self.json_array[lang][question]["revision"]) == None:
            self.json_array[lang][question]["revision"].append(comment)
            self.database.set_questions_array(self.json_array[lang], self.name,
                                              lang)
            return True
        return False

    def set_response(self, lang, question, txt):
        if lang not in self.json_array:
            return None
        if question not in self.json_array[lang]:
            return None
        self.json_array[lang][question]["answer"] = txt
        self.database.set_questions_array(self.json_array[lang], self.name,
                                          lang)
        return question

    def get_qid(self, chat_id, from_id):
        if chat_id not in self.questions:
            return None
        if from_id not in self.questions[chat_id]:
            return None
        return self.questions[chat_id][from_id]

    def del_qid(self, chat_id, from_id):
        del self.questions[chat_id][from_id]
        if len(self.questions[chat_id]) == 0:
            del self.questions[chat_id]

    def get_ancestors(self):
        data = []
        data.append(self)
        for elem in self.parents:
            data += elem.get_ancestors()
        return data

    def get_heirs(self):
        data = []
        data.append(self)
        for elem in self.sons:
            data += elem.get_heirs()
        return data

    def get_teach_coll(self):
        data = []
        for lang in self.teachers:
            data += self.teachers[lang]
        for lang in self.collaborators:
            data += self.collaborators[lang]
        return data

    def get_res_array(self, lang, condition):
        data = []
        if lang not in self.json_array:
            return data
        for elem in self.json_array[lang]:
            if (condition == "FREE"
                    and self.json_array[lang][elem]["answer"] == '') or (
                        condition == "BANNED"
                        and self.json_array[lang][elem]["answer"] == "BANNED"):
                data.append(elem)
            elif condition == "ANSWER" and self.json_array[lang][elem][
                    "answer"] != '' and self.json_array[lang][elem][
                        "answer"] != "BANNED":
                data.append(elem + " -> " +
                            self.json_array[lang][elem]["answer"])
        return data

    def sub_del_teachers(self, data, elem, lang, lang_class, bot):
        if elem not in self.teachers[lang] and len(self.teachers[lang]) > 0:
            data[lang] = self.teachers[lang]
        if elem in self.teachers[lang]:
            if len(self.teachers[lang]) > 1:
                data[lang] = []
                for id in self.teachers[lang]:
                    if id != elem:
                        data[lang].append(id)
            else:
                self.send_notification(lang_class, lang, bot, False)
        return data

    def del_teachers(self, vett, lang_class, bot):
        for elem in vett:
            data = {}
            for lang in self.teachers:
                data = self.sub_del_teachers(data, elem, lang, lang_class, bot)
            self.teachers = data

    def sub_del_collaborators(self, data, elem, lang, lang_class, bot):
        if elem not in self.collaborators[lang] and len(
                self.collaborators[lang]) > 0:
            data[lang] = self.collaborators[lang]
        if elem in self.collaborators[lang]:
            if len(self.collaborators[lang]) > 1:
                data[lang] = []
                for id in self.collaborators[lang]:
                    if id != elem:
                        data[lang].append(id)
            else:
                self.send_notification(lang_class, lang, bot, False)
        return data

    def del_collaborators(self, vett, lang_class, bot):
        for elem in vett:
            data = {}
            for lang in self.collaborators:
                data = self.sub_del_collaborators(data, elem, lang, lang_class,
                                                  bot)
            self.collaborators = data

    def sub_del_students(self, data, elem, lang):
        if elem not in self.students[lang] and len(self.students[lang]) > 0:
            data[lang] = self.students[lang]
        if elem in self.students[lang] and len(self.students[lang]) > 1:
            data[lang] = []
            for id in self.students[lang]:
                if id != elem:
                    data[lang].append(id)
        return data

    def del_students(self, vett):
        for elem in vett:
            data = {}
            for lang in self.students:
                data = self.sub_del_students(data, elem, lang)
            self.students = data

    def add_teachers(self, vett, lang_str, lang, bot=None):
        if bot != None:
            self.del_teachers(vett, lang, bot)
            self.del_collaborators(vett, lang, bot)
        if len(vett) == 0:
            return
        if bot != None:
            self.send_notification(lang, lang_str, bot)
        if lang_str not in self.teachers:
            self.teachers[lang_str] = []
        for elem in vett:
            if elem not in self.teachers[lang_str]:
                self.teachers[lang_str].append(elem)

    def add_collaborators(self, vett, lang_str, lang, bot=None):
        if bot != None:
            self.del_teachers(vett, lang, bot)
            self.del_collaborators(vett, lang, bot)
        if len(vett) == 0:
            return
        if bot != None:
            self.send_notification(lang, lang_str, bot)
        if lang_str not in self.collaborators:
            self.collaborators[lang_str] = []
        for elem in vett:
            if elem not in self.collaborators[lang_str]:
                self.collaborators[lang_str].append(elem)

    def add_students(self, vett, lang):
        self.del_students(vett)
        if len(vett) == 0:
            return
        if lang not in self.students:
            self.students[lang] = []
        for elem in vett:
            if elem not in self.students[lang]:
                self.students[lang].append(elem)

    def get_toc_lang(self, id):
        for lang in self.collaborators:
            if id in self.collaborators[lang]:
                return lang
        for lang in self.teachers:
            if id in self.teachers[lang]:
                return lang
        return None

    def set_hash(self, hash):
        self.hash = hash

    def get_hash(self):
        return self.hash

    def change(self, node1, node2):
        for num in range(0, len(self.sons)):
            if self.sons[num] == node1:
                self.sons[num] = node2
        for num in range(0, len(self.sons)):
            if self.parents[num] == node1:
                self.parents[num] = node2

    def is_in_array(self, string, array, lang, lang_str):
        for elem in array:
            if lang.calculate_similarity(string, elem, lang_str) > 0.8:
                return True
        return False

    def merge_arrays(self, array1, array2, lang, lang_str):
        if len(array1) == 0:
            return array2
        data = {}
        data = array1
        for elem in array2:
            val = []
            for e_data in data:
                if lang.calculate_similarity(e_data, elem, lang_str) < 0.8:
                    val.append(elem)
            for e_val in val:
                data[e_val] = array2[e_val]
        return data

    def send_notification(self, lang, lang_str, bot, new=True):
        string = ""
        if new:
            string = "new_lang"
        else:
            string = "del_lang"
        if (lang_str not in self.collaborators
                or len(self.collaborators[lang_str])
                == 0) and (lang_str not in self.teachers
                           or len(self.teachers[lang_str]) == 0):
            for elem in self.students:
                for chat_id in self.students[elem]:
                    bot.sendMessage(
                        chat_id,
                        lang.get_string(elem,
                                        string,
                                        xxx=lang.get_string(elem, lang_str)))

    def calc_distance(self, lang, lang_str):
        data = {}
        if lang_str in self.json_array:
            data[0] = self.json_array[lang_str]
        for elem in self.parents:
            array = elem.calc_distance(lang_str)
            for num in array:
                if num + 1 not in array:
                    data[num + 1] = {}
                data[num + 1] = self.merge_arrays(data[num + 1], array[num],
                                                  lang, lang_str)
        return data

    def add_question(self, txt, lang, res=""):
        if lang not in self.json_array:
            self.json_array[lang] = {}
        self.json_array[lang][txt] = {}
        self.json_array[lang][txt]["answer"] = res
        self.json_array[lang][txt]["ids"] = []

    def add_id(self, from_id, chat_id, num):
        if from_id == chat_id:
            self.id_commands[chat_id] = num
        else:
            if chat_id not in self.id_commands:
                self.id_commands[chat_id] = {}
                self.id_commands[chat_id][from_id] = num
            else:
                self.id_commands[chat_id][from_id] = num

    def del_id(self, from_id, chat_id):
        if from_id == chat_id:
            if chat_id in self.id_commands:
                del self.id_commands[chat_id]
        else:
            if chat_id in self.id_commands and from_id in self.id_commands[
                    chat_id]:
                del self.id_commands[chat_id][from_id]
            if len(self.id_commands[chat_id]) == 0:
                del self.id_commands[chat_id]

    def check_id(self, from_id, chat_id):
        ret_val = 0
        if from_id == chat_id:
            if chat_id in self.id_commands:
                ret_val = self.id_commands[chat_id]
        else:
            if chat_id in self.id_commands and from_id in self.id_commands[
                    chat_id]:
                ret_val = self.id_commands[chat_id][from_id]
        return ret_val

    def ret_q_vett(self, lang):
        vett = []
        if lang in self.json_array:
            vett = self.json_array[lang]
        return vett

    def get_trans_array(self, src, dst):
        vett = self.ret_q_vett(src)
        vett1 = self.ret_q_vett(dst)
        array = []
        for elem in vett:
            string = self.lang.translate(elem, src, dst)
            if vett[elem]["answer"] != "BANNED" and vett[elem][
                    "answer"] != "" and not self.is_in_array(
                        string, vett1, self.lang, dst):
                string = "\"" + string + "\" -> \"" + self.lang.translate(
                    vett[elem]["answer"], src, dst) + "\""
                array.append(string)
        return array
示例#26
0
def init():
	global db 
	db = Database()
示例#27
0
class MainWindow(QMainWindow):
    """Main application window"""
    def __init__(self):
        super().__init__()

        self.universal_font = QFont('Calibri', 13)

        self.set_UI()

        self.set_welcome_layout()

        self.db = Database()

        self.description_dict = {}

        self.code_dict = {}

        self.picture_dict = {}

        self.title = ""

        self.language = ""

        self.record_or_play = True  # record is True, play is False

        self.about_dict = {
            1:
            'LearningStep\n\nThis application is named LearningStep. The purpose is to learn and repeat self made text-lessons in intervals of time.',
            2:
            'Record New Task\n\nConstruct your own lesson in steps.\nProvide title as short description, choose language (field of interests) and by clicking next move forward lessons.'
            '\nOne step consists of description (upper text field) and code (lower text field).\nYou can also attach an image to every step.'
            '\nTo proceed next step, click Next button.\nWhen all steps are written, click Finish button to save the lesson.',
            3:
            'Play The Task\n\nPlay previously recorded task (choose from the table of available tasks).\nGo through all tasks by clicking Next button.\nAt first you see description and then code field.\n'
            'When you will walk through all steps you can decide whether this approach was satisfying. Only if so, task will be completed,\n updated to database '
            'and reminded after certain interval of time.',
            4:
            'Delete Task\n\nDelete task according to provided task ID.\nBe aware that images stored in database will also be deleted.',
            5:
            'Time intervals are:\n\n1 day, 3 days, 7 days, 10 days, 14 days, 28 days, 60 days, 90 days, 180 days...',
            6:
            'Credits:\n\nDariusz Giemza, 2019',
            7:
            ''
        }

    def set_UI(self):
        """Set main window properties and create stacked layouts"""
        self.setWindowTitle("LearningStep")

        self.setGeometry(230, 100, 900, 500)

        self.set_upper_menu()

        self.create_main_layout()

        self.stacked_layout = QStackedLayout()
        self.stacked_layout.addWidget(self.main_widget)

        ##############

        self.create_record_task_menu_layout()
        self.stacked_layout.addWidget(self.record_task_widget)

        #######

        self.create_play_task_menu_layout()
        self.stacked_layout.addWidget(self.play_task_widget)

        ########

        self.create_delete_task_menu_layout()
        self.stacked_layout.addWidget(self.delete_task_widget)

        ########

        self.create_about_menu_layout()
        self.stacked_layout.addWidget(self.about_widget)

        self.central_widget = QWidget()
        self.central_widget.setLayout(self.stacked_layout)
        self.setCentralWidget(self.central_widget)

    def create_main_layout(self):
        """Create startin layouy"""
        ### WIDGETS

        self.display_description = QLineEdit()
        self.display_code = QTextEdit()
        self.display_title = QLabel('Title')
        self.display_step = QLabel('Steps')
        self.picture_button = QPushButton()
        self.finish_button = QPushButton('Finish')
        self.next_button = QPushButton('Next')

        self.alpha_button = QPushButton('α')
        self.beta_button = QPushButton('β')
        self.pi_button = QPushButton('π')
        self.omega_button = QPushButton('Ω')
        self.lambda_button = QPushButton('λ')
        self.mi_button = QPushButton('µ')
        self.sigma_button = QPushButton('σ')
        self.sum_button = QPushButton('Σ')
        self.delta_button = QPushButton('Δ')
        self.gamma_button = QPushButton('Γ')
        self.not_equal_button = QPushButton('≠')
        self.approx_equal_button = QPushButton('≈')
        self.sqrt_button = QPushButton('√')
        self.gt_button = QPushButton('≥')
        self.lt_button = QPushButton('≤')
        self.degree_button = QPushButton('°')

        self.icon_black = QIcon(os.path.join('imgs', 'picture.png'))
        self.icon_red = QIcon(os.path.join('imgs', 'picture_red.png'))
        self.picture_button.setIcon(self.icon_black)

        ### GRIDS

        self.main_grid = QGridLayout()
        self.right_grid = QGridLayout()
        self.symbols_grid = QGridLayout()

        ### ADD WIDGETS

        self.symbols_grid.addWidget(self.alpha_button, 0, 0)
        self.symbols_grid.addWidget(self.beta_button, 0, 1)
        self.symbols_grid.addWidget(self.pi_button, 0, 2)
        self.symbols_grid.addWidget(self.omega_button, 0, 3)
        self.symbols_grid.addWidget(self.lambda_button, 0, 4)
        self.symbols_grid.addWidget(self.mi_button, 0, 5)
        self.symbols_grid.addWidget(self.sigma_button, 0, 6)
        self.symbols_grid.addWidget(self.sum_button, 0, 7)
        self.symbols_grid.addWidget(self.delta_button, 1, 0)
        self.symbols_grid.addWidget(self.gamma_button, 1, 1)
        self.symbols_grid.addWidget(self.not_equal_button, 1, 2)
        self.symbols_grid.addWidget(self.approx_equal_button, 1, 3)
        self.symbols_grid.addWidget(self.sqrt_button, 1, 4)
        self.symbols_grid.addWidget(self.gt_button, 1, 5)
        self.symbols_grid.addWidget(self.lt_button, 1, 6)
        self.symbols_grid.addWidget(self.degree_button, 1, 7)

        self.right_grid.addWidget(self.display_step, 0, 0)
        self.right_grid.addWidget(self.picture_button, 1, 0)
        self.right_grid.addWidget(self.finish_button, 2, 0)
        self.right_grid.addWidget(self.next_button, 3, 0)

        self.main_grid.addItem(self.symbols_grid, 2, 0)
        self.main_grid.addWidget(self.display_description, 0, 0)
        self.main_grid.addWidget(self.display_code, 1, 0)
        self.main_grid.addWidget(self.display_title, 0, 1)
        self.main_grid.addItem(self.right_grid, 1, 1)

        ### LAYOUT FORMATION
        font = QFont('Calibri', 15)
        font.setBold(True)

        self.display_description.setMaximumWidth(600)
        self.display_description.setAlignment(Qt.AlignHCenter)

        self.display_code.setMaximumWidth(600)
        self.display_code.setMinimumWidth(600)
        self.display_code.setMaximumHeight(500)

        self.display_title.setFont(font)
        self.display_title.setAlignment(Qt.AlignHCenter)

        self.display_step.setAlignment(Qt.AlignCenter)
        self.display_step.setFont(font)

        self.finish_button.setMinimumHeight(60)
        self.next_button.setMinimumHeight(60)

        self.main_widget = QWidget()
        self.main_widget.setLayout(self.main_grid)

        #### BEHAVIOURS ####

        self.finish_button.clicked.connect(self.finish_button_method)
        self.next_button.clicked.connect(self.next_button_method)
        self.picture_button.clicked.connect(self.picture_button_method)

        self.alpha_button.clicked.connect(self.alpha_button_method)
        self.beta_button.clicked.connect(self.beta_button_method)
        self.pi_button.clicked.connect(self.pi_button_method)
        self.omega_button.clicked.connect(self.omega_button_method)
        self.lambda_button.clicked.connect(self.lambda_button_method)
        self.mi_button.clicked.connect(self.mi_button_method)
        self.sigma_button.clicked.connect(self.sigma_button_method)
        self.sum_button.clicked.connect(self.sum_button_method)
        self.delta_button.clicked.connect(self.delta_button_method)
        self.gamma_button.clicked.connect(self.gamma_button_method)
        self.not_equal_button.clicked.connect(self.not_equal_button_method)
        self.approx_equal_button.clicked.connect(
            self.approx_equal_button_method)
        self.sqrt_button.clicked.connect(self.sqrt_button_method)
        self.gt_button.clicked.connect(self.gt_button_method)
        self.lt_button.clicked.connect(self.lt_button_method)
        self.degree_button.clicked.connect(self.degree_button_method)

    #### SPECIAL SYMBOLS METHODS ####

    def alpha_button_method(self):

        text = self.display_code.toPlainText()
        self.display_code.setText(text + 'α')

    def beta_button_method(self):

        text = self.display_code.toPlainText()
        self.display_code.setText(text + 'β')

    def pi_button_method(self):

        text = self.display_code.toPlainText()
        self.display_code.setText(text + 'π')

    def omega_button_method(self):

        text = self.display_code.toPlainText()
        self.display_code.setText(text + 'Ω')

    def lambda_button_method(self):

        text = self.display_code.toPlainText()
        self.display_code.setText(text + 'λ')

    def mi_button_method(self):

        text = self.display_code.toPlainText()
        self.display_code.setText(text + 'µ')

    def sigma_button_method(self):

        text = self.display_code.toPlainText()
        self.display_code.setText(text + 'σ')

    def sum_button_method(self):

        text = self.display_code.toPlainText()
        self.display_code.setText(text + 'Σ')

    def delta_button_method(self):

        text = self.display_code.toPlainText()
        self.display_code.setText(text + 'Δ')

    def gamma_button_method(self):

        text = self.display_code.toPlainText()
        self.display_code.setText(text + 'Γ')

    def not_equal_button_method(self):

        text = self.display_code.toPlainText()
        self.display_code.setText(text + '≠')

    def approx_equal_button_method(self):

        text = self.display_code.toPlainText()
        self.display_code.setText(text + '≈')

    def sqrt_button_method(self):

        text = self.display_code.toPlainText()
        self.display_code.setText(text + '√')

    def gt_button_method(self):

        text = self.display_code.toPlainText()
        self.display_code.setText(text + '≥')

    def lt_button_method(self):

        text = self.display_code.toPlainText()
        self.display_code.setText(text + '≤')

    def degree_button_method(self):

        text = self.display_code.toPlainText()
        self.display_code.setText(text + '°')

    def create_record_task_menu_layout(self):
        """Create layout for recording new taks"""

        self.record_task_grid = QVBoxLayout()

        self.record_task_grid_h = QHBoxLayout()

        self.record_label_1 = QLabel('TITLE OF THE TASK:')
        self.record_label_2 = QLabel('LANGUAGE (FIELD):')

        self.record_label_1.setAlignment(Qt.AlignCenter)

        self.record_text_title = QLineEdit()
        self.record_text_title.setAlignment(Qt.AlignHCenter)

        self.record_combo_box = QComboBox()
        self.record_combo_box.addItem("---")
        self.record_combo_box.addItem("Python")
        self.record_combo_box.addItem("R")
        self.record_combo_box.addItem("Machine Learning")
        self.record_combo_box.addItem("Deep Learning")
        self.record_combo_box.addItem("Statistics")
        self.record_combo_box.addItem("English")

        self.record_button_cancel = QPushButton('Cancel')
        self.record_button_start = QPushButton('Start')

        #### ALIGNMENT, SHAPES AND FONT####

        self.record_label_1.setFont(self.universal_font)
        self.record_label_2.setFont(self.universal_font)

        self.record_label_1.setAlignment(Qt.AlignCenter)
        self.record_text_title.setMaximumWidth(250)
        self.record_text_title.setMinimumWidth(350)

        self.record_label_2.setAlignment(Qt.AlignCenter)
        self.record_combo_box.setMaximumWidth(350)
        self.record_combo_box.setMinimumWidth(200)

        self.record_combo_box.setMinimumHeight(30)

        self.record_button_cancel.setMinimumHeight(40)
        self.record_button_start.setMinimumHeight(40)

        #### GRIDS ####

        self.record_task_grid.addWidget(self.record_label_1)
        self.record_task_grid.addWidget(self.record_text_title,
                                        alignment=Qt.AlignHCenter)
        self.record_task_grid.addWidget(self.record_label_2)
        self.record_task_grid.addWidget(self.record_combo_box,
                                        alignment=Qt.AlignCenter | Qt.AlignTop)

        self.record_task_grid_h.addWidget(self.record_button_cancel)
        self.record_task_grid_h.addWidget(self.record_button_start)

        self.record_task_grid.addItem(self.record_task_grid_h)

        self.record_task_widget = QWidget()
        self.record_task_widget.setLayout(self.record_task_grid)

        #### BEHAVIOUR ####

        self.record_button_cancel.clicked.connect(self.cancel_task_method)

        self.record_button_start.clicked.connect(self.start_record_task_method)

    def create_play_task_menu_layout(self):
        """Create play task layout"""

        #### WIDGETS ####

        self.play_label_1 = QLabel('CHOOSE ONE OF AVAILABLE TASKS:')

        self.play_task_button = QPushButton('Play Selected Task')

        self.play_task_cancel_button = QPushButton('Cancel')

        # Table

        self.play_table = QTableWidget()

        #### GRIDS ####

        self.play_task_grid = QVBoxLayout()

        self.play_task_grid.addWidget(self.play_label_1)

        self.play_task_grid.addWidget(self.play_table)

        self.play_task_grid.addWidget(self.play_task_button)

        self.play_task_grid.addWidget(self.play_task_cancel_button)

        #### ALIGNMENT, FONTS AND SHAPES ####

        self.play_label_1.setFont(self.universal_font)

        self.play_task_button.setMinimumHeight(40)

        self.play_task_cancel_button.setMinimumHeight(40)

        ####

        self.play_task_widget = QWidget()

        self.play_task_widget.setLayout(self.play_task_grid)

        #### BEHAVIOUR ####

        self.play_task_cancel_button.clicked.connect(self.cancel_task_method)

        self.play_task_button.clicked.connect(self.play_task_method)

    def create_delete_task_menu_layout(self):
        """Create delete layout"""

        #### WIDGETS ####

        self.delete_task_label = QLabel('PROVIDE TASK ID TO DELETE TASK:')

        self.delete_task_text_box = QLineEdit()

        self.delete_task_delete_button = QPushButton('DELETE')

        self.delete_task_cancel_button = QPushButton('Cancel')

        #### GRIDS ####

        self.delete_task_grid = QVBoxLayout()

        self.delete_task_grid_h = QHBoxLayout()

        self.delete_task_grid_h.addWidget(self.delete_task_cancel_button)

        self.delete_task_grid_h.addWidget(self.delete_task_delete_button)

        self.delete_task_grid.addWidget(self.delete_task_label,
                                        alignment=Qt.AlignCenter)

        self.delete_task_grid.addWidget(self.delete_task_text_box,
                                        alignment=Qt.AlignTop | Qt.AlignCenter)

        self.delete_task_grid.addItem(self.delete_task_grid_h)

        #### ALIGNMENT, FONT AND SHAPES ####

        self.delete_task_text_box.setAlignment(Qt.AlignHCenter)

        self.delete_task_label.setFont(self.universal_font)

        self.delete_task_text_box.setMaximumWidth(200)

        self.delete_task_cancel_button.setMinimumHeight(40)

        self.delete_task_delete_button.setMinimumHeight(40)

        #####

        self.delete_task_widget = QWidget()

        self.delete_task_widget.setLayout(self.delete_task_grid)

        #### BEHAVIOUR ####

        self.delete_task_cancel_button.clicked.connect(self.cancel_task_method)

        self.delete_task_delete_button.clicked.connect(self.delete_task)

    def create_about_menu_layout(self):
        """Create about layout"""

        self.about_label = QLabel('Sample')

        self.about_next_button = QPushButton('Next')

        self.about_cancel_button = QPushButton('Cancel')

        #### GRID ####

        self.about_grid_H = QHBoxLayout()

        self.about_grid_H.addWidget(self.about_cancel_button)

        self.about_grid_H.addWidget(self.about_next_button)

        self.about_grid_V = QVBoxLayout()

        self.about_grid_V.addWidget(self.about_label)

        self.about_grid_V.addItem(self.about_grid_H)

        self.about_widget = QWidget()

        self.about_widget.setLayout(self.about_grid_V)

        self.about_label.setFont(self.universal_font)

        self.about_label.setAlignment(Qt.AlignHCenter)

        self.about_cancel_button.setMinimumHeight(40)

        self.about_next_button.setMinimumHeight(40)

        #### BEHAVIOUR ####

        self.about_cancel_button.clicked.connect(self.cancel_task_method)

        self.about_next_button.clicked.connect(self.about_next_method)

    def set_upper_menu(self):
        """Create rolling  Menu"""

        self.statusBar()

        mainMenu = self.menuBar()

        optionsMenu = mainMenu.addMenu('&Menu')

        menuRecord = QAction('&Record New Task', self)
        menuRecord.setStatusTip('Record New Task and save it into database...')
        menuRecord.triggered.connect(self.menuRecord_method)

        menuPlay = QAction('&Play The Task', self)
        menuPlay.setStatusTip('Play one of the tasks from the available...')
        menuPlay.triggered.connect(self.menuPlay_method)

        menuDelete = QAction('&Delete task', self)
        menuDelete.setStatusTip('Delete one task for given task ID...')
        menuDelete.triggered.connect(self.menuDelete_method)

        menuAbout = QAction('&About', self)
        menuAbout.setStatusTip('About the LearningStep app...')
        menuAbout.triggered.connect(self.menuAbout_method)

        menuExit = QAction("&Exit", self)
        menuExit.setStatusTip('Exit the application...')
        menuExit.triggered.connect(self.menuExit_method)

        optionsMenu.addAction(menuRecord)
        optionsMenu.addAction(menuPlay)
        optionsMenu.addAction(menuDelete)
        optionsMenu.addAction(menuAbout)
        optionsMenu.addAction(menuExit)

    def about_next_method(self):
        """About layout, Next button"""

        if self.about_step < 7:
            self.about_step += 1
        else:
            self.about_step = 1

        self.about_label.setText(self.about_dict[self.about_step])

    def delete_task(self):
        """Delete layout, Delete button"""

        try:
            task_id = int(self.delete_task_text_box.text())

        except:

            task_id = self.delete_task_text_box.text()

        if self.delete_task_text_box.text() == "":

            QMessageBox.information(
                self, 'Empty text box',
                'In order to delete task, please provide a valid task ID!')

            return

        if not self.delete_task_text_box.text().isnumeric():

            QMessageBox.information(
                self, 'Invalid input',
                'In order to delete task, please provide numeric value that corresponds to task ID!'
            )

            return

        if not self.db.check_if_task_id_exists(task_id):

            QMessageBox.information(
                self, 'No such task ID',
                'There is no task ID in database: {0}'.format(task_id))

            return

        choice = QMessageBox.question(
            self, "Delete task",
            'Are you sure to delete task and all dependend images?\nYou will not be able to restore deleted data. Task ID: {0}'
            .format(task_id), QMessageBox.Yes | QMessageBox.No)

        if choice == QMessageBox.Yes:

            self.title, self.description_dict, self.code_dict, self.picture_dict, self.pass_count = self.db.get_selected_task(
                task_id)

            self.db.delete_images(self.picture_dict)

            self.db.delete_task(task_id)

            QMessageBox.information(
                self, 'Task deleted',
                'Task with ID {0} has been successfully deleted from database!'
                .format(task_id))

            self.stacked_layout.setCurrentIndex(0)

            self.set_welcome_layout()

        elif choice == QMessageBox.No:

            return

    def load_to_play_table(self):
        """Load table with available tasks"""

        rows = self.db.load_available_tasks()

        self.play_table.setRowCount(len(rows))

        self.play_table.setColumnCount(6)

        self.play_table.setHorizontalHeaderLabels([
            'Task title (short description)', 'Language (Field)',
            'Creation Date', 'Last Pass Date', 'Pass Count', 'ID'
        ])

        self.play_table.verticalHeader().hide()

        self.play_table.setEditTriggers(QAbstractItemView.NoEditTriggers)

        self.play_table.setSelectionBehavior(QAbstractItemView.SelectRows)

        self.play_table.setColumnWidth(0, 280)

        self.play_table.setColumnWidth(1, 180)

        self.play_table.setColumnWidth(2, 110)

        self.play_table.setColumnWidth(3, 110)

        for i, row in enumerate(rows):

            item = QTableWidgetItem(row[0])
            item.setTextAlignment(Qt.AlignCenter)
            self.play_table.setItem(i, 0, item)

            item = QTableWidgetItem(row[1])
            item.setTextAlignment(Qt.AlignCenter)
            self.play_table.setItem(i, 1, item)

            item = QTableWidgetItem(row[2])
            item.setTextAlignment(Qt.AlignCenter)
            self.play_table.setItem(i, 2, item)

            item = QTableWidgetItem(row[3])
            item.setTextAlignment(Qt.AlignCenter)
            self.play_table.setItem(i, 3, item)

            item = QTableWidgetItem(str(row[4]))
            item.setTextAlignment(Qt.AlignCenter)
            self.play_table.setItem(i, 4, item)

            item = QTableWidgetItem(str(row[5]))
            item.setTextAlignment(Qt.AlignCenter)
            self.play_table.setItem(i, 5, item)

    def picture_button_method(self):
        """Picture button to load or display picture"""

        if self.record_or_play:

            #### RECORD TASK ####

            path = QFileDialog.getOpenFileName(
                self, 'Load picture to database', 'c:\\',
                "Image files (*.jpg *.gif, *.png)")

            # if path is empty
            if path[0] == '':

                return

            try:

                extension = path[0][-3:].lower()

                now = datetime.datetime.now()

                image_name = self.title + "_STEP_" + str(
                    self.step) + "_" + str(now.year) + "_" + str(
                        now.month) + "_" + str(now.day)

                filename_ext = "{0}.{1}".format(image_name, extension)

                shutil.copy(path[0], os.path.join('temp_pic', filename_ext))

                self.picture_dict[self.step] = image_name

                self.picture_button.setIcon(self.icon_red)

            except:

                QMessageBox.information(
                    self, 'Error',
                    'Something has gone wrong during copying picture to the album. Please try once again.'
                )

        else:

            #### PLAY TASK ####

            if self.picture_dict[self.step] != "":

                image_path = self.db.readBlobData(self.picture_dict[self.step])

                self.picture_window = ImageWindow(image_path)

                self.picture_window.show()

                self.remove_temp_pictures()

            else:

                QMessageBox.information(
                    self, 'Error',
                    'Application could not find attached picture. It might have been deleted or moved.'
                )

    def finish_button_method(self):
        """Finish record and play button"""

        if self.record_or_play:

            #### RECORD TASK ####

            if self.step == 1 and self.display_description.text(
            ) == "" and self.display_code.toPlainText() == "":

                self.remove_temp_pictures()

                self.set_welcome_layout()

                return

            choice = QMessageBox.question(
                self, "Finish",
                '[Yes] - Finish and save task to the database\n[No] - Finish and don\'t save task\n[Cancel] - back to the recording',
                QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)

            if choice == QMessageBox.Yes:

                if self.display_description.text(
                ) == "" or self.display_code.toPlainText() == "":

                    pass

                else:

                    self.description_dict[
                        self.step] = self.display_description.text()

                    self.code_dict[self.step] = self.display_code.toPlainText()

                self.db.add_task(self.description_dict, self.code_dict,
                                 self.picture_dict, self.title, self.language)

                self.images_to_database()

                self.remove_temp_pictures()

                self.set_welcome_layout()

            elif choice == QMessageBox.No:

                self.remove_temp_pictures()

                self.set_welcome_layout()

            elif choice == QMessageBox.Cancel:

                return

        else:

            #### PLAY TASK ####

            choice = QMessageBox.question(
                self, "Task completed",
                'Are you satisfied with the level of task accomplishment? If [Yes], it will be available in next interval of time.',
                QMessageBox.Yes | QMessageBox.No)

            if choice == QMessageBox.Yes:

                next_pass_date = self.db.update_task(self.task_id,
                                                     self.pass_count)

                QMessageBox.information(
                    self, 'Task accomplished',
                    'Task has been accomplished. Expect it on the list on {0}'.
                    format(next_pass_date))

                self.set_welcome_layout()

            elif choice == QMessageBox.No:

                QMessageBox.information(self, 'Task unaccomplished',
                                        'Well... Try next time!')

                self.set_welcome_layout()

    def next_button_method(self):
        """Next record and play button"""

        #### RECORD TASK ####

        if self.record_or_play:

            # check if fields are not empty

            if self.display_description.text() == "":

                QMessageBox.information(
                    self, 'Empty field!',
                    'There is empty description field. Please write something to proceed.'
                )

                return

            if self.display_code.toPlainText() == "":

                QMessageBox.information(
                    self, 'Empty field!',
                    'There is empty code field. Please write something to proceed.'
                )

                return

            choice = QMessageBox.question(
                self, 'Next step', 'Do you want to proceed to the next step?',
                QMessageBox.Yes | QMessageBox.No)

            if choice == QMessageBox.Yes:

                # add to dictionaries

                self.description_dict[
                    self.step] = self.display_description.text()

                self.code_dict[self.step] = self.display_code.toPlainText()

                self.step += 1

                self.picture_dict[self.step] = ""

                self.display_step.setText("Step\n{0}".format(self.step))

                self.display_description.clear()

                self.display_code.clear()

                self.picture_button.setIcon(self.icon_black)

            else:

                return

        else:
            #### PLAY ####

            if self.description_or_code:

                self.display_code_play_layout()

            else:

                self.next_step_play_layout()

    def play_task_method(self):
        """Play task starting method"""

        if self.play_table.selectedIndexes() == []:

            return

        row = self.play_table.selectedIndexes()[0].row()

        self.task_id = self.play_table.item(row, 5).text()

        self.title, self.description_dict, self.code_dict, self.picture_dict, self.pass_count = self.db.get_selected_task(
            self.task_id)

        self.step = 1

        self.stacked_layout.setCurrentIndex(0)

        self.set_play_layout()

    def cancel_task_method(self):
        """Cancel button method"""

        self.clear_record_menu()

        self.stacked_layout.setCurrentIndex(0)

    def start_record_task_method(self):
        """Start recording method"""

        if self.record_text_title.text(
        ) == "" or self.record_combo_box.currentText() == "---":

            QMessageBox.information(self, 'Warning!',
                                    'Title and field has to be fulfilled!')

        else:

            self.title = self.record_text_title.text()

            self.language = self.record_combo_box.currentText()

            self.set_record_layout()

            self.stacked_layout.setCurrentIndex(0)

    def remove_temp_pictures(self):
        """Removes all pictures from temp_pic folder"""

        folder = 'temp_pic'

        for filename in os.listdir(folder):

            file_path = os.path.join(folder, filename)

            try:
                if os.path.isfile(file_path) or os.path.islink(file_path):
                    os.unlink(file_path)
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)

            except Exception as e:
                print(e)

    def clear_record_menu(self):
        """Clear Record menu"""
        self.record_text_title.setText('')

        self.record_combo_box.setCurrentIndex(0)

    def set_welcome_layout(self):
        """Set startin layout"""
        self.display_description.setDisabled(True)

        self.display_code.setDisabled(True)

        self.display_description.clear()

        self.display_code.clear()

        self.display_title.setText('Title')

        self.display_step.setText('Step\n/')

        self.picture_button.setDisabled(True)

        self.finish_button.setDisabled(True)

        self.next_button.setDisabled(True)

        self.alpha_button.setDisabled(True)
        self.beta_button.setDisabled(True)
        self.pi_button.setDisabled(True)
        self.omega_button.setDisabled(True)
        self.lambda_button.setDisabled(True)
        self.mi_button.setDisabled(True)
        self.sigma_button.setDisabled(True)
        self.sum_button.setDisabled(True)
        self.delta_button.setDisabled(True)
        self.gamma_button.setDisabled(True)
        self.not_equal_button.setDisabled(True)
        self.approx_equal_button.setDisabled(True)
        self.sqrt_button.setDisabled(True)
        self.gt_button.setDisabled(True)
        self.lt_button.setDisabled(True)
        self.degree_button.setDisabled(True)

        self.description_dict = {}

        self.code_dict = {}

        self.picture_dict = {}

        self.title = ""

        self.language = ""

        self.picture_button.setIcon(self.icon_black)

    def set_record_layout(self):
        """Set layout while Record"""

        self.step = 1

        self.picture_dict[1] = ""

        self.display_description.setReadOnly(False)

        self.display_code.setReadOnly(False)

        self.display_description.setEnabled(True)

        self.display_code.setEnabled(True)

        self.display_title.setText(self.record_text_title.text())

        self.display_step.setText('Step\n{0}'.format(self.step))

        self.display_description.clear()

        self.display_code.clear()

        self.picture_button.setEnabled(True)

        self.finish_button.setEnabled(True)

        self.next_button.setEnabled(True)

        self.alpha_button.setDisabled(False)
        self.beta_button.setDisabled(False)
        self.pi_button.setDisabled(False)
        self.omega_button.setDisabled(False)
        self.lambda_button.setDisabled(False)
        self.mi_button.setDisabled(False)
        self.sigma_button.setDisabled(False)
        self.sum_button.setDisabled(False)
        self.delta_button.setDisabled(False)
        self.gamma_button.setDisabled(False)
        self.not_equal_button.setDisabled(False)
        self.approx_equal_button.setDisabled(False)
        self.sqrt_button.setDisabled(False)
        self.gt_button.setDisabled(False)
        self.lt_button.setDisabled(False)
        self.degree_button.setDisabled(False)

    def get_dict_highest_value(self):
        """Get highest value of step from dictionary"""

        self.key_list = self.description_dict.keys()
        return str(max(self.key_list))

    def set_play_layout(self):
        """Set layout while play"""

        self.finish_button.setDisabled(True)

        self.next_button.setEnabled(False)

        self.alpha_button.setDisabled(True)
        self.beta_button.setDisabled(True)
        self.pi_button.setDisabled(True)
        self.omega_button.setDisabled(True)
        self.lambda_button.setDisabled(True)
        self.mi_button.setDisabled(True)
        self.sigma_button.setDisabled(True)
        self.sum_button.setDisabled(True)
        self.delta_button.setDisabled(True)
        self.gamma_button.setDisabled(True)
        self.not_equal_button.setDisabled(True)
        self.approx_equal_button.setDisabled(True)
        self.sqrt_button.setDisabled(True)
        self.gt_button.setDisabled(True)
        self.lt_button.setDisabled(True)
        self.degree_button.setDisabled(True)

        QTimer.singleShot(3000, partial(self.next_button.setEnabled, True))

        self.display_description.setReadOnly(True)

        self.display_code.setReadOnly(True)

        self.display_description.setEnabled(True)

        self.display_code.setEnabled(True)

        self.display_title.setText(self.title)

        self.display_step.setText('Step\n1/{0}'.format(
            self.get_dict_highest_value()))

        self.display_description.setText(self.description_dict[self.step])

        self.description_or_code = True

        self.remove_temp_pictures()

    def display_code_play_layout(self):
        """Displays code while Play"""

        self.description_or_code = False

        self.display_code.setText(self.code_dict[self.step])

        if self.picture_dict[self.step] != "":

            self.picture_button.setEnabled(True)

            self.picture_button.setIcon(self.icon_red)

        else:

            self.picture_button.setIcon(self.icon_black)

        if self.step == int(self.get_dict_highest_value()):

            self.finish_button.setEnabled(True)
            self.next_button.setDisabled(True)

        else:
            self.next_button.setEnabled(False)
            QTimer.singleShot(1500, partial(self.next_button.setEnabled, True))

    def next_step_play_layout(self):
        """Click Next during Play"""

        self.step += 1

        self.description_or_code = True

        self.picture_button.setEnabled(False)

        self.next_button.setEnabled(False)
        QTimer.singleShot(3000, partial(self.next_button.setEnabled, True))

        self.display_code.clear()
        self.display_description.setText(self.description_dict[self.step])
        self.display_step.setText('Step\n{0}/{1}'.format(
            str(self.step), self.get_dict_highest_value()))

    def images_to_database(self):

        for filename in os.listdir('temp_pic'):

            if filename.endswith(('.jpg', '.png', '.gif')):

                image_name = filename[:-4]

                image_path = os.path.join('temp_pic', filename)

                image_ext = filename[-3:]

                self.db.insertBLOB(image_name, image_path, image_ext)

    def menuRecord_method(self):
        """Upper Menu option"""

        self.remove_temp_pictures()

        self.clear_record_menu()

        self.record_or_play = True

        self.stacked_layout.setCurrentIndex(1)

        self.display_description.setText('')

        self.display_code.setText('')

    def menuPlay_method(self):
        """Upper Menu option"""
        self.play_table.clear()

        self.load_to_play_table()

        self.record_or_play = False

        self.stacked_layout.setCurrentIndex(2)

        self.display_description.setText('')

        self.display_code.setText('')

    def menuDelete_method(self):
        """Upper Menu option"""
        self.delete_task_text_box.clear()

        self.stacked_layout.setCurrentIndex(3)

    def menuAbout_method(self):
        """Upper Menu option"""
        self.about_step = 1

        self.about_label.setText(self.about_dict[self.about_step])

        self.stacked_layout.setCurrentIndex(4)

    def menuExit_method(self):
        """Upper Menu option"""
        sys.exit()
示例#28
0
 def __init__(self):
     self.database = Database()
     self.id_commands = {}
     self.id_times = {}
     self.bot_array = {}
     self.key_id = self.database.get_key_id()
示例#29
0
class User(object):
    # User can search up book according to:
    # • Book name
    # • Book tags
    # • Book publication date
    # • Author's first name
    # • Author's last name
    # • Book price
    # • Or just return all the books
    # Returns the items in the format:
    # book name | author first_name + last_name | ISBN | stock level | D.O.P | price

    def __init__(self):
        self.db = Database()

    def get_all_books(self):
        # Return a list of everything in system,
        query = "select ISBN from BOOK"
        self._print_items(query)

    def get_books_by_tag(self, tag):
        # Assuming that the user can only put one tag to search, this searches the book_tag table
        query = "select BOOK_ID from BOOK_TAG where TAG = '%s'" % (tag)
        self._print_items(query)

    def get_book_by_bookname(self, bookname):
        # Returns books that match the title
        query = "select ISBN from BOOK where BOOK_NAME like '%s'" % (
            '%' + bookname + '%')
        self._print_items(query)

    def get_books_by_date(self, date):
        # Date formatted as YYYY-MM-DD
        query = "select ISBN from BOOK where DATE_OF_PUBLICATION = '%s'" % (
            date)
        self._print_items(query)

    def get_books_by_firstname(self, author_firstname):
        # Returns books with the authors first name
        query = "select BOOK_ID from Author where GIVEN_NAME = '%s'" % (
            author_firstname)
        self._print_items(query)

    def get_books_by_lastname(self, author_lastname):
        # Returns books with the authors last name
        query = "select BOOK_ID from Author where LAST_NAME = '%s'" % (
            author_lastname)
        self._print_items(query)

    def get_books_by_price(self, price):
        # Check user has entered a integer not a string
        query = "select ISBN from BOOK where price = '%d'" % (price)
        self._print_items(query)

    def _print_items(self, query):
        book_id = self.db._dbSelect(query)
        book_id = list(book_id)
        print("%-50s | %-20s | %-20s | %-18s | %-20s | %-10s" %
              ('BOOK NAME', 'AUTHOR', 'ISBN', 'STOCK', 'DATE OF PUBLICATION',
               'PRICE'))
        print(
            "---------------------------------------------------------------------------------------------------------------------------------------------------------------"
        )
        for i in range(0, len(book_id)):
            self._get_book_by_ISBN(book_id[i])
        print("\n")

    def _get_book_by_ISBN(self, ISBN):
        book_query = "Select BOOK_NAME, ISBN, PRICE, DATE_OF_PUBLICATION from BOOK where ISBN = '%s'" % (
            ISBN)
        author_query = "Select GIVEN_NAME, LAST_NAME from AUTHOR where BOOK_ID = '%s'" % (
            ISBN)
        stock_query = "Select AMOUNT from STOCK_LEVEL where BOOK_ID = '%s'" % (
            ISBN)
        try:
            book_tuple = self.db._dbSelect(book_query)
            author_tuple = self.db._dbSelect(author_query)
            stock_tuple = self.db._dbSelect(stock_query)

            print(
                "%-50s | %-20s | %-20s | %-18d | %-20s | %-10d" %
                (book_tuple[0], author_tuple[0] + ' ' + author_tuple[1],
                 book_tuple[1], stock_tuple[0], book_tuple[3], book_tuple[2]))
        except Exception as e:
            print(e)
示例#30
0
    class Singleton:
        def __init__(self):
            self.lang = Language()
            self.array = {}
            self.num = 0
            self.database = Database()
            data = self.database.get('/bots/students', '')
            for topic in data:
                self.array[topic] = BotStudent(topic)

        def set_super_user_lang(self, chat_id, topic, new_lang):
            self.array[topic].set_super_user_lang(chat_id, new_lang)

        def send_notification_teacher(self, bot):
            for topic in self.array:
                self.array[topic].send_notification(bot, self.lang)

        def read_ban(self):
            return self.database.read_ban()

        def get_lang(self):
            return self.lang

        def get_database(self):
            return self.database

        def check_lang_str(self, txt, string):
            return self.lang.check_lang_str(txt, string)

        def get_best_resp(self, txt, lang, topic):
            list1 = {}
            json_array = self.array[topic].get_json_array(self.lang, lang)
            for question in json_array:
                num = self.lang.calculate_similarity(txt, question, lang)
                if num > 0.8:
                    list1[question] = num
            return self.normalize_vect(list1)

        def normalize_vect(self, vect):
            array = sorted(vect.items(),
                           key=operator.itemgetter(1),
                           reverse=True)
            i = 0
            list1 = []
            for elem in array:
                if i == 4:
                    break
                for e in elem:
                    list1.append(e)
                    break
                i += 1
            return list1

        def delete_bot(self, topic):
            self.database.del_bot(topic)
            del self.array[topic]

        def write_pwd(self, array):
            self.database.write_pwd(array)

        def get_banned_users(self):
            return self.database.get_banned_users()

        def get_username_by_topic(self, topic):
            return self.array[topic].get_username()

        def get_creation_keyboard(self, topic):
            return InlineKeyboardMarkup(
                inline_keyboard=[[
                    InlineKeyboardButton(text="Go to the teacher bot",
                                         url="https://t.me/" +
                                         self.database.get_bot_teacher(
                                         ).get_bot().getMe()["username"] +
                                         "?start=foo")
                ],
                                 [
                                     InlineKeyboardButton(
                                         text="Go to the student " + topic +
                                         " bot",
                                         url="https://t.me/" +
                                         self.get_username_by_topic(topic) +
                                         "?start=foo")
                                 ]])

        def read_pwd(self):
            return self.database.read_pwd()

        def change_pwd(self, topic, pwd):
            self.array[topic].change_pwd(pwd)

        def send_notification(self, teacher, student, topic):
            self.array[topic].sendRestartNotify(teacher, student, self.lang)

        def add_collaborators(self, vett, topic, lang):
            self.array[topic].add_collaborators(lang, vett)

        def change_role(self, chat_id, topic):
            return self.array[topic].change_role(chat_id)

        def get_hint(self, topic, lang):
            vett = []
            for elem in ["it", "de", "en", "es", "fr"]:
                if elem != lang:
                    vett += self.array[topic].get_trans_array(elem, lang)
            return vett

        def get_student_id(self):
            data = {}
            for elem in self.array:
                vett = self.array[elem].get_student_id()
                if len(vett) > 0:
                    data[elem] = vett
            return data

        def new_bot(self, token, topic, hash):
            self.database.new_topic(token, topic, hash)
            self.array[topic] = BotStudent(topic)

        def get_pwd_admin(self):
            return self.database.get_pwd_admin()

        def get_token_list(self):
            list1 = []
            for topic in self.array:
                list1.append(self.array[topic].get_token())
            return list1

        def get_topic_list(self):
            list1 = []
            for topic in self.array:
                list1.append(topic)
            return list1

        def get_flag_list(self):
            return self.lang.get_flag_list()

        def switcherflag(self, flag):
            return self.lang.get_lang_by_flag(flag)

        def set_student_id(self, vett):
            for elem in vett:
                self.array[elem].set_student_id(vett[elem])

        def verify_password(self, topic, password):
            return self.array[topic].verify_password(password)

        def add_question_by_hint(self, lang, question, response, chat_id,
                                 from_id, topic):
            self.set_question(question, lang, topic, chat_id)
            self.set_qid(chat_id, from_id, question, topic)
            self.set_res(chat_id, from_id, response, lang, topic)

        def topic_keyboard(self):
            return create_reply_keyboard(array_to_matrix(
                self.get_topic_list()))

        def delete_tc(self, chat_id, topic):
            self.array[topic].del_teachers([chat_id])
            self.array[topic].del_collaborators([chat_id])

        def add_teachers(self, vett, topic, lang):
            self.array[topic].add_teachers(lang, vett)

        def get_bot_by_topic(self, topic):
            return self.array[topic].get_bot()

        def get_bot_pwd(self):
            return self.database.get_bot_pwd().get_bot()

        def get_ids_array(self, topic, lang, txt):
            array = self.array[topic].get_json_array(lang)
            return array[txt]["ids"]

        def add_admins(self, lang, vett):
            self.lang.add_admins(lang, vett)

        def get_admins(self, lang):
            return self.lang.get_admins(lang)

        def set_hash(self, topic, hash):
            self.array[topic].set_hash(hash)
            self.write_data()

        def set_qid(self, chat_id, from_id, txt, topic):
            self.array[topic].set_qid(chat_id, from_id, txt)

        def get_hash(self, topic):
            return self.array[topic].get_hash()

        def get_sent(self, lang, text):
            return self.lang.question_sent(lang, text)

        def get_q_array(self, chat_id, lang, topic):
            list_q = self.array[topic].get_json_array(self.lang, lang, True)
            list_u = []
            for elem in list_q:
                if chat_id in list_q[elem]["id"]:
                    list_u.append(elem)
            return list_u

        def get_qid(self, chat_id, from_id, topic):
            return self.array[topic].get_qid(chat_id, from_id)

        def del_qid(self, chat_id, from_id, topic):
            self.array[topic].del_qid(chat_id, from_id)

        def set_res(self, chat_id, from_id, txt, lang, topic):
            question = self.array[topic].get_qid(chat_id, from_id)
            if question != None:
                return self.array[topic].set_response(lang, question, txt)
            return None

        def set_ban(self, txt, lang, topic):
            jarray = self.array[topic].get_json_array(lang)
            e = self.lang.match_array(txt, lang, jarray)
            if e != None and jarray[e]["answer"] == "":
                self.array[topic].set_response(lang, e, "BANNED")
            self.array[topic].set_banned_stud()

        def set_sban(self, txt, lang, topic):
            jarray = self.array[topic].get_json_array(lang)
            e = self.lang.match_array(txt, lang, jarray)
            if e != None and jarray[e]["answer"] == "BANNED":
                self.array[topic].set_response(lang, e, "")
            self.array[topic].set_banned_stud()

        def set_nlp(self, lang):
            self.lang.set_nlp(lang)

        def set_lang_resp(self, id, lang, bot):
            self.lang.set_lang_resp(id, lang, bot)

        def add_id(self, from_id, chat_id, num, topic):
            return self.array[topic].add_id(from_id, chat_id, num)

        def get_res_array(self, topic, lang, condition):
            return self.array[topic].get_res_array(lang, condition)

        def check_id(self, from_id, chat_id, topic):
            return self.array[topic].check_id(from_id, chat_id)

        def del_id(self, from_id, chat_id, topic):
            return self.array[topic].del_id(from_id, chat_id)

        def get_topic(self, chat_id):
            for node in self.array:
                if chat_id in self.array[node].get_teach_coll():
                    return node
            return None

        def write_data(self):
            for elem in self.array:
                self.array[elem].set_formatted_data()

        def set_question(self, txt, lang, topic, chat_id):
            self.array[topic].add_question(txt, lang)
            self.array[topic].add_chat_id(txt, lang, chat_id)

        def get_response(self, txt, lang, topic, chat_id=None):
            json_array = self.array[topic].get_json_array(lang)
            val = 0
            q = ""
            for question in json_array:
                num = self.lang.calculate_similarity(txt, question, lang)
                if num > val:
                    val = num
                    q = question
            if val > 0.8:
                if chat_id != None:
                    self.array[topic].add_chat_id(q, lang, chat_id)
                    self.write_data()
                return json_array[q]["answer"]
            else:
                return None

        def get_lang_board(self, lang, array):
            return self.lang.get_lang_board(lang, array)

        def set_keyboard(self, lang_array):
            return self.lang.set_keyboard(lang_array, False)

        def get_string(self, lang, string, xxx=None, yyy=None):
            return self.lang.get_string(lang, string, xxx, yyy)

        def get_user_lang(self, id, topic):
            return self.array[topic].getStudentLang(id)

        def get_super_user_lang(self, id, topic):
            return self.array[topic].get_toc_lang(id)

        def check_coll(self, lang, text):
            return self.lang.check_coll(lang, text)

        def check_teach(self, lang, text):
            return self.lang.check_teach(lang, text)