Esempio n. 1
0
 def __init__(self):
     """初始化:
     建立DataBase对象,DataPlot对象
     """
     passwd = str(input('请输入密码 -->'))
     self.database = data_base.DataBase(passwd)
     self.dataplot = data_plot.DataPlot()
Esempio n. 2
0
def get_info(message):
    db = data_base.DataBase()
    user = db.findUser(str(message.from_user.id))
    if user[1] == 'en':
        get_info_en(message)
    elif user[1] == 'fr':
        get_info_fr(message)
    elif user[1] == 'de':
        get_info_de(message)
def run_simulation_once(lmd, ddl_scale, traffic_num, traffic_size_scale):
    # Get a database
    data_base = db.DataBase()
    # Initialize the network function information
    new_sc = [service_chain.NetworkFunctionName.fun_1, service_chain.NetworkFunctionName.fun_2
              ]
    data_base.scs.add_sc(new_sc)
    new_sc = (service_chain.NetworkFunctionName.fun_3, service_chain.NetworkFunctionName.fun_4,
              service_chain.NetworkFunctionName.fun_5)
    data_base.scs.add_sc(new_sc)
    new_sc = (service_chain.NetworkFunctionName.fun_1, service_chain.NetworkFunctionName.fun_5,
              service_chain.NetworkFunctionName.fun_4)
    data_base.scs.add_sc(new_sc)
    new_sc = (service_chain.NetworkFunctionName.fun_2, service_chain.NetworkFunctionName.fun_5,
              service_chain.NetworkFunctionName.fun_4)
    data_base.scs.add_sc(new_sc)
    new_sc = (service_chain.NetworkFunctionName.fun_1, service_chain.NetworkFunctionName.fun_2,
              service_chain.NetworkFunctionName.fun_3, service_chain.NetworkFunctionName.fun_4,
              service_chain.NetworkFunctionName.fun_5)
    data_base.scs.add_sc(new_sc)
    new_sc = (service_chain.NetworkFunctionName.fun_1, service_chain.NetworkFunctionName.fun_3,
              service_chain.NetworkFunctionName.fun_5, service_chain.NetworkFunctionName.fun_4)
    data_base.scs.add_sc(new_sc)
    # data_base.scs.print_all_scs()
    # Network initialize
    # data_center = ["6", "17", "22"]
    data_center = ["1", "13", "19", "26"]
    data_base.add_datacenter(data_center)
    # Traffic generator initialize
    # Para: lambda, mu, request number, optional data size
    traffic_size = np.array([7, 8, 9, 10])
    traffic_size = traffic_size * traffic_size_scale
    traffic_size = list(traffic_size)
    (avg_arr, due_time) = data_base.set_traffic_generator(lmd, ddl_scale, traffic_num, traffic_size)
    # print("Finish: ", end="")
    for i in range(traffic_num):
        sys.stdout.write("\r" + str(round((i + 1) / traffic_num * 100, 4)) + "%")
        # request_process.process_one_req(data_base, data_base.tf_gen.req_set[i])
        request_process.algorithm_x(data_base, data_base.tf_gen.req_set[i], 'conventional')
        # time.sleep(data_base.tf_gen.sleep_time[i] * network_info.global_TS * data_base.tf_gen.control_factor)
    # time.sleep(3)
    print()
    (cpu_cost, trans_cost) = data_base.get_cost()
    used_vm = data_base.get_used_vm_no()
    data_base.print_req_provisioning()
    # print("Average Latency: " + str(round(data_base.average_latency(), 3)) + "s")
    # print("Average Arrival Interval: " + str(round(avg_arr, 3)))
    # print("Traffic Load:" + str(round(data_base.average_latency() / avg_arr, 3)))
    # print("BP: " + str(data_base.blocking_probability() * 100) + "%")
    # print("Used FS:" + str(data_base.used_FS))
    # data_base.print_all_vms()
    data_base.reset_counters()
    # 0 cpu_cost, 1 tran_cost, 2 used vms, 3 latency, 4 average arrival, 5 traffic load, 6, bp 7 used fss,
    # 8 theory traffic load
    return cpu_cost, trans_cost, used_vm, data_base.average_latency(), avg_arr, \
        data_base.average_latency() / avg_arr, data_base.blocking_probability(), data_base.used_FS, due_time / avg_arr
Esempio n. 4
0
def send_welcome(message):
    db = data_base.DataBase()
    user = db.findUser(str(message.from_user.id))
    if user is None:
        db.insertUser(str(message.from_user.id), "en")
    else:
        db.updateLanguage(str(message.from_user.id), "en")
    msg = bot.send_message(
        message.chat.id,
        "I can explain to you any word.\nPlease select your preferred language:",
        reply_markup=markups.language_markup)
Esempio n. 5
0
def setEnglishLanguage(message):
    db = data_base.DataBase()
    user = db.findUser(str(message.from_user.id))
    answer = "Now I know English" + flag(
        'gb') + "\nPlease enter an unknown word."
    if user is None:
        db.insertUser(str(message.from_user.id), "en")
    elif user[1] != "en":
        db.updateLanguage(str(message.from_user.id), "en")
    else:
        answer = "I already know English" + flag(
            'gb') + "\nPlease enter an unknown word."
    msg = bot.send_message(message.chat.id, answer)
Esempio n. 6
0
def getWord(message):
    db = data_base.DataBase()
    user = db.findUser(str(message.from_user.id))
    data = google_dict.find_word(user[1], message.text)
    if (data.status_code == 200):
        createAnswer(data.json(), message)
    else:
        if user[1] == 'en':
            bot.send_message(message.chat.id, "Unknown word.")
        elif user[1] == 'fr':
            bot.send_message(message.chat.id, "Mot inconnu.")
        elif user[1] == 'de':
            bot.send_message(message.chat.id, "Unbekanntes Wort.")
Esempio n. 7
0
def setGermanLanguage(message):
    db = data_base.DataBase()
    user = db.findUser(str(message.from_user.id))
    answer = "Jetzt kenne ich die Deutsche Sprache" + flag(
        'de') + "\nBitte geben Sie ein unbekanntes Wort ein."
    if user is None:
        db.insertUser(str(message.from_user.id), "de")
    elif user[1] != "de":
        db.updateLanguage(str(message.from_user.id), "de")
    else:
        answer = "Ich kenne schon Deutsch" + flag(
            'de') + "\nBitte geben Sie ein unbekanntes Wort ein."
    msg = bot.send_message(message.chat.id, answer)
Esempio n. 8
0
def setFrenchLanguage(message):
    db = data_base.DataBase()
    user = db.findUser(str(message.from_user.id))
    answer = "Maintenant je connais le français" + flag(
        'fr') + "\nVeuillez saisir un mot inconnu."
    if user is None:
        db.insertUser(str(message.from_user.id), "fr")
    elif user[1] != "fr":
        db.updateLanguage(str(message.from_user.id), "fr")
    else:
        answer = "Je connais déjà le français" + flag(
            'fr') + "\nVeuillez saisir un mot inconnu."
    msg = bot.send_message(message.chat.id, answer)
Esempio n. 9
0
    def main(self):
        print('Database creating...')
        db = data_base.DataBase(number=self.n_clusters)
        # db.create_image_table()
        # for img in tqdm(os.listdir(self.data_set_dir)):
        # 	self.db.insert_image_entry(image_name=img)
        # print('Image table was created')

        print('Model creating...')
        new_model = vgg16_modeling.NewModel(image_set_dir=self.data_set_dir,
                                            database=db,
                                            n_clusters=self.n_clusters)
        new_model.build_model_pca()
        # new_model.build_model_cluster()
        print('Model was created')
Esempio n. 10
0
def testing():
    db = data_base.DataBase()
    tg_id = 12345
    password = "******"
    login = "******"

    errors = 0
    errors += try_add_field(db, tg_id, login, password)
    errors += if_field_was_added(db, tg_id)
    errors += if_data_was_added_correctly(db, tg_id, login, password)
    errors += field_is_not_repeated(db, tg_id, login, password)
    errors += field_is_correctly_deleted(db, tg_id)
    errors += unexisting_field_is_not_found(db, tg_id)

    return errors
Esempio n. 11
0
 def __init__(self):
     self.current_dir = os.path.dirname(os.path.abspath(__file__))
     self.data_set_dir = os.path.join(self.current_dir, '..', 'static')
     self.n_clusters = 10
     self.db = data_base.DataBase(number=self.n_clusters)
Esempio n. 12
0
class MainWindow(QtWidgets.QMainWindow, Translator):
    __db = data_base.DataBase()
    __language_dict = __db.get_languages()

    def __init__(self, *args, **kwargs):
        QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
        self.setup_ui(self)
        self.setWindowIcon(QtGui.QIcon("./icons/trans.png"))
        self.translate_button.clicked.connect(lambda: self.action_translate())
        self.save_button.clicked.connect(lambda: self.action_save())
        self.load_button.clicked.connect(lambda: self.action_load())
        self.swap_button.clicked.connect(lambda: self.action_swap())
        self.clear_button.clicked.connect(lambda: self.action_clear())
        self.languages_in.addItems(self.__language_dict.keys())
        self.languages_out.addItems(self.__language_dict.keys())
        self.text_in.installEventFilter(self)
        self.languages_in.currentTextChanged.connect(lambda: self.autocomplete_load_node())
        self.actual_lang = self.languages_in.currentText().lower()
        self.node = dill.load(open(f"autocomplete/{self.actual_lang}.pickle", "rb"))
        self.suggestion = ""

    def autocomplete_load_node(self):
        tmp = self.languages_in.currentText().lower()
        dill.dump(self.node, open(f"autocomplete/{self.actual_lang}.pickle", "wb"))
        self.actual_lang = tmp
        if os.path.isfile(f"./autocomplete/{self.actual_lang}.pickle"):
            self.node = dill.load(open(f"autocomplete/{self.actual_lang}.pickle", "rb"))
        else:
            node = trie.Node()
            dill.dump(node, open(f"autocomplete/{self.actual_lang}.pickle", "wb"))
            self.node = node

    def translate_update_trie(self):
        # this regex ignores special language characters
        words_save = regex.sub('[^\p{L} ]+', "", regex.sub('[\s]+', " ", self.text_in.toPlainText().lower())).split()
        for word in words_save:
            trie.insert(self.node, word)
        file_name = self.languages_in.currentText().lower()
        dill.dump(self.node, open(f"autocomplete/{file_name}.pickle", "wb"))
        self.autocomplete.setText("Press Tab to complete:")
        self.suggestion, self.sugg_message = "", ""

    # translate text from input and show it
    def action_translate(self, update_trie=True):
        src = self.languages_in.currentText()
        dest = self.languages_out.currentText()
        text = self.text_in.toPlainText()

        if text == "":
            return
        elif src == dest:
            self.text_out.setText(text)
        else:
            src = self.__language_dict[src]
            dest = self.__language_dict[dest]
            try:
                translation = translate_google_cloud_api(src, dest, text)
                self.text_out.setText(translation['translatedText'])
            # no internet connection
            except TransportError:
                error_message_box("No internet connection!")

        if update_trie:
            self.translate_update_trie()

    # swap languages and texts if not empty, then call translate on new input
    def action_swap(self):
        src_lang = self.languages_in.currentIndex()
        dest_lang = self.languages_out.currentIndex()
        dest_text = self.text_out.toPlainText()

        self.languages_in.setCurrentIndex(dest_lang)
        self.languages_out.setCurrentIndex(src_lang)
        if dest_text != "":
            self.text_in.setText(dest_text)
            self.action_translate(update_trie=False)

    def action_clear(self):
        self.text_in.setText("")
        self.text_out.setText("")
        self.suggestion = ""
        self.sugg_message = ""
        self.autocomplete.setText(f"Press Tab to complete:")

    def action_save(self):
        filename, filter_ = QtWidgets.QFileDialog.getSaveFileName(caption='Select output file', directory='/Users',
                                                                  filter='*.txt')
        if filename:
            if self.text_in.toPlainText() != "":
                with open(filename, "w", encoding="utf-8") as f:
                    f.write(
                        f"From: {self.languages_in.currentText()}\n{self.text_in.toPlainText()}\n" +
                        f"To: {self.languages_out.currentText()}\n{self.text_out.toPlainText()}")
                info_message_box("Translation has been saved!")
            else:
                error_message_box("Translation is empty!")
        else:
            error_message_box("Action canceled!")

    # make sure to add enough restrictions to loading data
    def action_load(self):
        warning_message_box("Make sure that .txt file contains in first lane: two languages(first source, "
                            "second destination) followed by text to translate in next line.")
        filename, filter_ = QtWidgets.QFileDialog.getOpenFileName(caption='Save file', directory='/Users',
                                                                  filter='*.txt')

        if filename:
            with open(filename, "r", encoding="utf-8") as f:
                content = f.readlines()
                if len(content) != 2:
                    error_message_box("Wrong file content!")
                else:
                    src, dest = content[0].strip().split()
                    src, dest = src.lower().capitalize(), dest.lower().capitalize()

                    list_lang = list(self.__language_dict.keys())
                    if src not in list_lang and dest not in list_lang:
                        error_message_box("Source and destination languages are wrong or not followed!")
                        return
                    elif src not in list_lang:
                        error_message_box("Source language is wrong or not followed!")
                        return
                    elif dest not in list_lang:
                        error_message_box("Destination language is wrong or not followed!")
                        return

                    src_ind, dest_ind = list_lang.index(src), list_lang.index(dest)
                    self.languages_in.setCurrentIndex(src_ind)
                    self.languages_out.setCurrentIndex(dest_ind)
                    self.text_in.setText(content[1].strip())
                    self.action_translate(update_trie=False)
                    info_message_box("Text has been loaded!")
        else:
            error_message_box("Action canceled!")

    def action_autocomplete(self):
        if self.text_in.toPlainText() == "":
            return
        tmp = self.text_in.toPlainText().split()[-1]
        # replace punctuation marks and convert to lower letters
        tmp = re.sub('[?.!]', "", tmp).lower()
        suggs = trie.keys_with_prefix(self.node, tmp)

        # when no action is taken: tmp length less than 2, space at the end of the word or no suggestion to prefix word
        if len(tmp) >= 2 and not self.text_in.toPlainText().endswith(" ") and suggs:
            self.sugg_message = max(suggs, key=lambda k: suggs[k])
            self.suggestion = self.sugg_message.replace(tmp, "")
            self.autocomplete.setText(f"Press Tab to complete: " + self.sugg_message)
        else:
            self.autocomplete.setText(f"Press Tab to complete:")

    def eventFilter(self, obj, event):
        if event.type() == QtCore.QEvent.KeyPress and obj is self.text_in:
            if event.key() == QtCore.Qt.Key_Tab:
                content = self.text_in.toPlainText() + self.suggestion
                self.text_in.setText(content)
                cursor = self.text_in.textCursor()
                cursor.movePosition(QtGui.QTextCursor.End)
                self.text_in.setTextCursor(cursor)
                self.autocomplete.setText("Press Tab to complete:")
                self.suggestion = ""
                return True

        elif event.type() == QtCore.QEvent.KeyRelease and obj is self.text_in:
            if event.key() != QtCore.Qt.Key_Tab:
                self.action_autocomplete()

        if self.text_in.toPlainText() != "":
            self.clear_button.setVisible(True)
        else:
            self.clear_button.setVisible(False)

        return super(MainWindow, self).eventFilter(obj, event)
Esempio n. 13
0
import time
from dotenv import load_dotenv
import os
import flask
import telebot

import meta
import checker
import data_base

app = flask.Flask(__name__)

load_dotenv()
bot = telebot.TeleBot(os.getenv('API_TOKEN'))
db = data_base.DataBase()
check = checker.Checker()


@app.route(os.getenv("WEBHOOK_URL_PATH"), methods=['POST'])
def webhook():
    if flask.request.headers.get('content-type') == 'application/json':
        json_string = flask.request.get_data().decode('utf-8')
        update = telebot.types.Update.de_json(json_string)
        bot.process_new_updates([update])
        return ''
    else:
        flask.abort(403)


@bot.message_handler(commands=['start'])
def send_welcome(message):