예제 #1
0
    def check_memorized(self, chat_id, correct_answer=None):
        next_word, next_word_translate = Api().get_next_word(chat_id)
        if next_word is None:  # завершение обучения
            LangBotApi.add_rating(chat_id, 5)
            text = "Изучение слов завершенно, получи 5 ❤\n\n"
            text += """🔹Теперь эти слова ты можешь изучать в *Интервальном повторении*, для того чтобы быстрее их запомнить

🔹Ты можешь учить неограниченное количество слов в разделе *Изучать слова*, по 10/20/50 в день! 
"""
            keyboard = types.InlineKeyboardMarkup()
        else:
            randoms_words = Api().get_random_words(chat_id)
            keyboard = types.InlineKeyboardMarkup()
            buttons = [
                types.InlineKeyboardButton(text=next_word_translate,
                                           callback_data="good " + next_word)
            ]
            for word in list(randoms_words):
                buttons.append(
                    types.InlineKeyboardButton(text=word, callback_data="bad"))
            random.shuffle(buttons)
            for bt in buttons:
                keyboard.add(bt)
            text = ""
            if correct_answer is not None:
                text += "**Неверно!**\nПравильный ответ:\n"
                text += correct_answer[0] + " - " + correct_answer[1] + "**\n\n"
                text += "возможно нужна кнопка подробной информации"
            text += "*Выбери правильный перевод*\n\n"
            text += f"*{next_word}*"

        return {"keyboard": keyboard, "text": text}
예제 #2
0
 def start_learning(self, chat_id):
     data = Api().get_new_words(chat_id)
     if data is False:
         if not Api().is_allowed_today(chat_id):
             return
     keyboard = types.InlineKeyboardMarkup()
     button = types.InlineKeyboardButton(text="Я все запомнил️",
                                         callback_data="remembered")
     keyboard.add(button)
     text = "\n".join([key + " - " + "data[key]" for key in data])
     return {"keyboard": keyboard, "text": text}
예제 #3
0
 def bad_answer(self, chat_id):
     words_list, words_dict = Api().get_list_words(chat_id)
     data = self.get_word_keys_data(
         chat_id, words_list.index(Api().get_good_word(chat_id)[0]))
     data['text'] = "Неправильно!\n" + data["text"]
     keyboard = types.InlineKeyboardMarkup()
     keyboard.add(
         types.InlineKeyboardButton(text="Запомнил(а)",
                                    callback_data="next"))
     data["keyboard"] = keyboard
     # print("1\n"*5, Api().get_good_word(chat_id),"2\n"*5, sep = "\n"*5)
     return data
예제 #4
0
 def __init__(self, parent, title=None, inText=None, outText=None):
     self.inText = inText
     self.outText = outText
     self.inTextLabel = None
     self.outTextLabel = None
     self.api = Api()
     self.init(parent, title)
예제 #5
0
파일: main.py 프로젝트: nitrocaster/vkd
def main():

    config = Config.createConfig()

    for id in config.ids:
        api = Api(config.appId, id, token=config.token)
        config.token = api.token  # for future
        for target in config.targets:
            target.process(api)

    return


    for id in config.ids:
        api.setId(id)
        for target, settings in config.targets.items():
            if not settings.download:
                logging.info("{}: do not download.".format(target))
                continue
            if target == 'wall':
                logging.info('Current target: {}'.format(target))
                # determine posts count
                r = api.wallCount()
                interact(locals())
                logging.info("Total posts: {}".format(count))
                logging.info("Wall dowload start")
                return
                args.wall_start, args.wall_end, total = ranges(args.wall_start, args.wall_end, count)
                counter = 0.0  # float for %
                post_parser = PostParser(args.directory, str(args.id), args)
                for x in xrange(args.wall_start, args.wall_end):
                    if args.verbose and counter % 10 == 0:
                        logging.info("\nDone: {:.2%} ({})".format(counter / total, int(counter)))
                    (post, json_stuff) = call_api("wall.get", [("owner_id", args.id), ("count", 1), ("offset", x)], args)
                    process_post(("wall post", x), post, post_parser, json_stuff)
                    counter += 1
                if args.verbose:
                    logging.info("\nDone: {:.2%} ({})".format(float(total) / total, int(total)))
                continue

            elif target == 'audio':
                raise NotImplementedError
            elif target == 'friends':
                raise NotImplementedError
            elif target == 'notes':
                raise NotImplementedError
            elif target == 'video':
                raise NotImplementedError
            elif target == 'docs':
                raise NotImplementedError
            else:
                continue
            logging.info("End")
            return


    '''
예제 #6
0
    def __init__(self):
        self.config = configparser.ConfigParser()
        self.config.read('conf.ini', 'utf-8')

        self.api = Api(server_url=self.config.get('base', 'server_url'))

        today_first_run = self.config.get('runtime', 'today_first_run')
        date_day = time.strftime('%d', time.localtime(int(today_first_run)))
        #若不是本日首次运行,执行时间戳更新操作
        if date_day != time.strftime('%d', time.localtime(time.time())):
            self.config.set('runtime', 'today_first_run',
                            str(int(time.time())))
            self.updateTimeOffset()
예제 #7
0
 def __init__(self, port):
     Thread.__init__(self)
     ip = socket.gethostbyname(socket.gethostname())
     self.server = SimpleThreadedXMLRPCServer((ip, port), allow_none=True)
     self.server.register_introspection_functions()
     self.server.register_multicall_functions()
     self.server.register_instance(Api(self), allow_dotted_names=True)
     self.ctr = 0
     self.addr = ip + ":" + str(port)
     self.net_members = [self.addr]
     self.string_queue = deque()
     self.status = False
     self.master_string = ""
     self.master_address = ""
     self.is_interested_in_master_string = False
     self.is_victory_broadcasted = False
     self.clock = Clock(self.addr)
     self.wordListToCheck = []
     print("Serv created")
예제 #8
0
        def get_data():
            """
            Gets data from profit loss window
            :return:
            """
            database = Database()
            complete_list_of_stocks = []
            list_of_bare_stocks = database.get_all_stocks()
            ready_for_display_stocks = []

            for x in list_of_bare_stocks:
                item = database.get_stock(x.symbol)
                complete_list_of_stocks.append(item)

            api = Api()

            for z in complete_list_of_stocks:
                item = api.get_stock_quote(z)
                ready_for_display_stocks.append(item)
            return ready_for_display_stocks
예제 #9
0
    def generate_main_stock_window_list(self):
        """
        Gets list of current stock, gets current quote, and calls method to put on main window.
        Call this method to execute list of current stocks on main window
        :return: none
        """
        database = Database()
        complete_list_of_stocks = []
        list_of_bare_stocks = database.get_all_stocks()
        ready_for_display_stocks = []

        for x in list_of_bare_stocks:
             item = database.get_stock(x.symbol)
             complete_list_of_stocks.append(item)

        api = Api()

        for z in complete_list_of_stocks:
            item = api.get_stock_quote(z)
            ready_for_display_stocks.append(item)

        self.adjust_stock_list(ready_for_display_stocks)
예제 #10
0
    def test_question_data(self, chat_id):
        next_word, next_word_translate, count = Api().get_next_test_word(
            chat_id)
        if next_word is None:  # завершение обучения
            goal = 80
            score = Api().get_test_score(chat_id)
            percent = int((score[0] / score[1]) * 100)
            if percent > goal:
                LangBotApi.add_rating(chat_id, 20)
                text = "Поздравляю! Тест завершен.\nВы получили новый уровень: *" + \
                       levels_str[Api().get_next_level(chat_id)] + "* и 20 ❤"
                Api().set_next_level(chat_id)
            else:
                text = "Тест завершен.\n"
                text += "К сожалению, вы не прошли тест.\nДо уровня " + levels_str[
                    Api().get_next_level(chat_id)] + "\n"
                text += "Вам не хватило " + str(goal - percent + 1) + "%"
            text += "\nВы набрали " + str(percent) + "% (" + str(
                score[0]) + " из " + str(score[1]) + ")."
            keyboard = types.InlineKeyboardMarkup()
        else:
            # randoms_words = Api().get_random_test_words(chat_id)
            randoms_words = Api().get_random_words(chat_id)
            keyboard = types.InlineKeyboardMarkup()
            buttons = [
                types.InlineKeyboardButton(text=next_word_translate,
                                           callback_data="good " + next_word)
            ]
            for word in list(randoms_words):
                buttons.append(
                    types.InlineKeyboardButton(text=word, callback_data="bad"))
            random.shuffle(buttons)
            for bt in buttons:
                keyboard.add(bt)
            text = ""
            text += f"_Осталось {count} вопросов_\n\n"
            text += "**Выбери правильный перевод**\n\n"
            text += f"*{next_word}*"

        return {"keyboard": keyboard, "text": text}
예제 #11
0
    def __init__(self, settings, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # applicaiton settings
        self.settings = settings

        # deliberate. for the startup routine
        self.api = None

        # used by the AddNoteWindow and AddPasswordWindow
        self.edit_note_mode = False
        self.edit_password_mode = False

        # window properties and dimensions
        self.setWindowTitle("Python Password Manager")
        self.setWindowIcon(QIcon('PythonPasswordManager/icons/PythonIcon.png'))
        self.setGeometry(450, 150, 1350, 750)
        self.setFixedSize(self.size())
        # show a blank window to signify the application has started.
        self.show()

        # startup routine
        # 1.
        # check that settings has the required properties and not empty or invalid path
        # if the settings are not valid, create a new database.
        if not hasattr(self.settings, 'database_folder_path') or \
            self.settings.database_folder_path is None or \
            self.settings.database_folder_path == '' or \
            not os.path.exists(self.settings.database_folder_path) or \
            not os.path.exists(self.settings.database_folder_path + '/' + ENCRYPTED_DATABASE_NAME):

            # prompt for database path
            valid_dir = False
            while not valid_dir:
                db_dir = QFileDialog.getExistingDirectory(
                    self, "Choose Database Directory")

                valid_dir = os.path.exists(db_dir)

                if not valid_dir:
                    continue
                else:
                    self.settings.database_folder_path = db_dir

                    self.settings.export_settings_to_json(SETTINGS_FILE_NAME)

            # create the missing database after a valid_dir is chosen and saved
            engine = create_database_engine(
                db_directory=self.settings.database_folder_path + '/' +
                DECRYPTED_DATABASE_NAME)
            create_tables(Base, engine)

            # prompt password
            self.password_prompt = PasswordPromptWindow(self)
            self.password_prompt.exec_()
            # password = self.password_submission
            # TODO: validate password strength

            # encrypt new database
            self.api = Api(
                database_folder_path=self.settings.database_folder_path,
                password_string=self.password_submission)

            self.api.encrypt_database()

        successful_decryption = False
        while not successful_decryption:
            # 2.
            # prompt password if have not already
            self.password_prompt = PasswordPromptWindow(self)
            self.password_prompt.exec_()
            # password = self.password_submission
            # TODO: validate password strength

            # 3.
            # create database connection if it's not there already
            self.api = Api(
                database_folder_path=self.settings.database_folder_path,
                password_string=self.password_submission)

            try:
                # check the password validity
                self.api.test_database_connection()
                successful_decryption = True
            except InvalidPasswordException:
                continue
            else:
                successful_decryption = True

        self.create_ui()

        self.show()
예제 #12
0
 def good_answer(self, chat_id):
     Api().poor_learned_one_word(chat_id)
     Api().remove_good_word(chat_id)
     return self.check_memorized(chat_id)
예제 #13
0
    def area_izquierda_del_panel(self):
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)

        # gtk 2
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)

        frame = Gtk.Frame()
        frame.set_label("Objects")
        frame.set_label_align(0.5, 0.5)
        combo = Gtk.ComboBoxText()
        for item in PaquetesObjetos1:
            combo.append_text(item)
        combo.connect('changed', self.get_item)
        frame.add(combo)
        hbox.pack_start(frame, True, True, 2)

        frame = Gtk.Frame()
        frame.set_label("No Objects")
        frame.set_label_align(0.5, 0.5)
        combo2 = Gtk.ComboBoxText()
        for item in PaquetesNoObjetos1:
            combo2.append_text(item)
        combo2.connect('changed', self.get_item)
        frame.add(combo2)
        hbox.pack_start(frame, True, True, 2)

        frame = Gtk.Frame()
        frame.set_label("gir-1.1-gtk-2.0")
        frame.set_label_align(0.5, 0.5)
        frame.add(hbox)
        vbox.pack_start(frame, False, False, 0)

        # gtk 3
        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)

        frame = Gtk.Frame()
        frame.set_label("Objects")
        frame.set_label_align(0.5, 0.5)
        combo = Gtk.ComboBoxText()
        for item in PaquetesObjetos2:
            combo.append_text(item)
        combo.connect('changed', self.get_item)
        frame.add(combo)
        hbox.pack_start(frame, True, True, 2)

        frame = Gtk.Frame()
        frame.set_label("No Objects")
        frame.set_label_align(0.5, 0.5)
        combo2 = Gtk.ComboBoxText()
        for item in PaquetesNoObjetos2:
            combo2.append_text(item)
        combo2.connect('changed', self.get_item)
        frame.add(combo2)
        hbox.pack_start(frame, True, True, 2)

        frame = Gtk.Frame()
        frame.set_label("gir-1.2-gtk-3.0")
        frame.set_label_align(0.5, 0.5)
        frame.add(hbox)
        vbox.pack_start(frame, False, False, 0)

        scrolled_window = Gtk.ScrolledWindow()
        scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC,
                                   Gtk.PolicyType.AUTOMATIC)
        self.api = Api()
        scrolled_window.add_with_viewport(self.api)
        vbox.pack_start(scrolled_window, True, True, 0)

        combo.set_active(0)

        return vbox
예제 #14
0
#$Id$#

from os.path import basename
from json import dumps
from books.util.ZohoHttpClient import ZohoHttpClient
from books.parser.InvoicesParser import InvoicesParser
from Api import Api

base_url = Api().base_url + 'invoices/'
parser = InvoicesParser()
zoho_http_client = ZohoHttpClient()


class InvoicesApi:
    """Invoice Api class is used to:
    
    1.List all invoices with pagination.
    2.Get the details of an invoice.
    3.Create an invoice.
    4.Update an existing invoice.
    5.Delete an existing invoice.
    6.Mark a draft invoice as sent.
    7.Mark an invoice status as void.
    8.Mark a voided invoice as draft.
    9.Email an invoice to the customer.
    10.Send invoices to your customer by email.
    11.Get the email content of an email.
    12.Remind the customer about an unpaid invoice by email.
    13.Remind the customer abount unpaid invoices by email.
    14.Get the mail content of the payment reminder.
    15.Export maximum of 25 invoices as pdf.
#$Id$#

from books.util.ZohoHttpClient import ZohoHttpClient
from books.parser.ContactParser import ContactParser
from Api import Api
from json import dumps

base_url = Api().base_url + 'contacts/'
parser = ContactParser()
zoho_http_client = zoho_http_client = ZohoHttpClient()


class ContactPersonsApi:
    """ContactPersonsApi class is used to:

    1.To get the list of contact persons of a contact with pagination.
    2.To get the details of a contact person.
    3.To create a contact person for a contact.
    4.To update an existing contact person.
    5.To delete a contact person.
    6.To mark a contact person as primary for the contact.

    """
    def __init__(self, authtoken, organization_id):
        """Initialize ContactPersons Api using user's authtoken and 
            organization id.

        Args:
            authtoken(str): User's authtoken.
            organization_id(str): User's organization id.
예제 #16
0
    def __init__(self, png):
        # 外部接口相关service对象
        self.api = Api()
        # 变量X和Y用来记录鼠标左键按下的位置
        self.sel = None
        self.X = tkinter.IntVar(value=0)
        self.Y = tkinter.IntVar(value=0)
        # 屏幕尺寸
        screenWidth = root.winfo_screenwidth()
        screenHeight = root.winfo_screenheight()
        # 创建顶级组件容器
        self.top = tkinter.Toplevel(root,
                                    width=screenWidth,
                                    height=screenHeight)
        # 不显示最大化、最小化按钮
        self.top.overrideredirect(True)
        self.canvas = tkinter.Canvas(self.top,
                                     bg='white',
                                     width=screenWidth,
                                     height=screenHeight)
        # 显示全屏截图,在全屏截图上进行区域截图
        self.image = tkinter.PhotoImage(file=png)
        self.canvas.create_image(screenWidth // 2,
                                 screenHeight // 2,
                                 image=self.image)

        # 鼠标左键按下的位置
        def onLeftButtonDown(event):
            self.X.set(event.x)
            self.Y.set(event.y)
            # 开始截图
            self.sel = True

        self.canvas.bind('<Button-1>', onLeftButtonDown)

        # 鼠标左键移动,显示选取的区域
        def onLeftButtonMove(event):
            if not self.sel:
                return
            global lastDraw
            try:
                # 删除刚画完的图形,要不然鼠标移动的时候是黑乎乎的一片矩形
                self.canvas.delete(lastDraw)
            except Exception as e:
                pass
            lastDraw = self.canvas.create_rectangle(self.X.get(),
                                                    self.Y.get(),
                                                    event.x,
                                                    event.y,
                                                    outline='black')

        self.canvas.bind('<B1-Motion>', onLeftButtonMove)

        # 获取鼠标左键抬起的位置,保存区域截图
        def onLeftButtonUp(event):
            self.sel = False
            try:
                self.canvas.delete(lastDraw)
            except Exception as e:
                pass
            sleep(0.1)
            # 考虑鼠标左键从右下方按下而从左上方抬起的截图
            left, right = sorted([self.X.get(), event.x])
            top, bottom = sorted([self.Y.get(), event.y])
            pic = ImageGrab.grab((left + 1, top + 1, right, bottom))
            #  启动翻译线程
            translateThread = TranslateThread(pic, self.api)
            translateThread.setDaemon(True)
            translateThread.start()
            # # 弹出保存截图对话框
            #
            # fileName = tkinter.filedialog.asksaveasfilename(title='保存截图', filetypes=[('JPG files', '*.jpg')])
            #
            # if fileName:
            #     pic.save(fileName + '.jpg')

            # 关闭当前窗口
            self.top.destroy()

        self.canvas.bind('<ButtonRelease-1>', onLeftButtonUp)
        self.canvas.pack(fill=tkinter.BOTH, expand=tkinter.YES)
예제 #17
0
#$Id$#

from os.path import basename
from books.util.ZohoHttpClient import ZohoHttpClient
from books.parser.EstimatesParser import EstimatesParser
from Api import Api
from json import dumps

base_url = Api().base_url + 'estimates/'
parser = EstimatesParser()
zoho_http_client = ZohoHttpClient()


class EstimatesApi:
    """Estimates Api class is used to:
   
    1.List all estimates with pagination.
    2.Get the details of an estimate.
    3.Create an estimate.
    4.Update an existing estimate.
    5.Delete an existing estimate.
    6.Mark a draft estimate as sent.
    7.Mark a sent estimate as accepted.
    8.Mark a sent estimate as declined.
    9.Email an estimate to the customer.
    10.Send estimates to your customer by email.
    11.Get the email content of an estimate.
    12.Export maximum of 25 pdfs as single pdf.
    13.Export estimates as pdf and print them.
    14.Update the billing address for the estimate.
    15.Update the shipping address for the estimate.
#$Id$#

from books.util.ZohoHttpClient import ZohoHttpClient
from books.parser.RecurringInvoiceParser import RecurringInvoiceParser
from Api import Api
from json import dumps

base_url = Api().base_url + 'recurringinvoices/'
parser = RecurringInvoiceParser()
zoho_http_client = ZohoHttpClient()


class RecurringInvoicesApi:
    """Recurring invoice api class is used:
    
    1.To list all the recurring invoices with pagination.
    2.To get details of a recurring invoice.
    3.To create a recurring invoice.
    4.To update an existing recurring invoice.
    5.To delete an existing recurring invoice.
    6.To stop an active recurring invoice.
    7.To resume a stopped recurring invoice.
    8.To update the pdf template associated with the recurring invoice.
    9.To get the complete history and comments of a recurring invoice.

    """
    def __init__(self, authtoken, organization_id):
        """Initialize Contacts Api using user's authtoken and organization id.

        Args:
            authtoken(str): User's authtoken.
예제 #19
0
import argparse
from Serv import Serv
from Cli import Cli
from Api import Api

parser = argparse.ArgumentParser()
parser.add_argument('port', type=int, nargs='?', default=4444)
args = parser.parse_args()

if __name__ == '__main__':
    serv = Serv(args.port)
    print("Started the node on " + serv.addr)
    api = Api(serv)
    cli = Cli(api)
    serv.start()
    cli.start()
'''
//Checklist
*# mesh network
*# join operation
*# New machines join the network by sending a join message to one of the machines already in the network.
*#    The address of the new host is thereupon propagated in the network.
*# Hosts also need to be able to sign off from the network again.
*# One node in the network needs to be elected as master node. The master node stores a
string variable that is initially empty.
*# Start message
*# The master node needs to be elected by the Bully algorithm.
*# In case the current master node signs off or fails a new master has to be elected.
*# The process takes 20 seconds. During this time all the nodes in the network do the
following: LOOP
    a) Wait a random amount of time
예제 #20
0
 def test_answer(self, chat_id, good=False):
     Api().remove_test_word(chat_id, good=good)
     return self.test_question_data(chat_id)
예제 #21
0
 def setUp(self):
     self.testApi = Api()
     self.testStock = Stock("jnj")
예제 #22
0
    def get_word_keys_data(self, chat_id, word_number, more=False):
        words_list, words_dict = Api().get_list_words(chat_id)
        n_words = len(words_list)
        word_number = int(word_number)
        prev_n = word_number - 1 if word_number else word_number
        next_n = word_number + 1 if word_number + 1 < n_words else word_number

        keyboard = types.InlineKeyboardMarkup()
        buttons = [
            types.InlineKeyboardButton(text="⬅️",
                                       callback_data="goto " + str(prev_n))
        ]
        buttons += [
            types.InlineKeyboardButton(text=str(word_number + 1) + "/" +
                                       str(n_words),
                                       callback_data="start_quiz")
        ]
        buttons += [
            types.InlineKeyboardButton(text="➡️",
                                       callback_data="goto " + str(next_n))
        ]
        buttons += [
            types.InlineKeyboardButton(text="Подробнее",
                                       callback_data="more " +
                                       str(word_number))
        ]
        buttons += [
            types.InlineKeyboardButton(text="Перейти к тесту",
                                       callback_data="start_quiz")
        ]
        keyboard.add(*buttons[:3])
        keyboard.add(buttons[3])
        if word_number + 1 == n_words:
            keyboard.add(buttons[4])

        word = words_list[word_number]

        pos = words_dict[word].get("pos", "")
        level = words_dict[word].get("level", "")

        ts = words_dict[word]["translate"]
        audio = words_dict[word].get("audio", "")
        audio = LangBotApi.get_word_audio_by_path(audio)
        transcription = ts.get("ts")
        meanings = ts.get("tr")
        examples = ts.get("ex", list())
        synonyms = ts.get("syn", list())
        # Транскрипция: [kɒnstɪˈtjuːʃn]
        # Существительное
        text = f"*{word}*"
        if transcription:
            text += "\nТранскрипция: [" + transcription + "]"
        text += "\n" + pos_dict.get(pos, pos)
        if level and False:
            text += " topic: " + level
        text += "\n"
        for mng in meanings:
            text += "\n· " + mng
            if more:  # обычно ложь, может когда-то заработает
                try:
                    if mng in synonyms and synonyms[mng]:
                        text += "\n  " + "synonyms:\n" + ",".join(
                            synonyms[mng])
                    if mng in examples and examples[mng]:
                        text += "\n  " + "examples:"
                        for exmpl in examples[mng]:
                            text += "\n·" + exmpl["text"]
                            for ex_tr in exmpl["tr"]:
                                text += " - " + ex_tr["text"]

                except Exception as e:
                    print(e)
                    text += "\n error \n"
        if more:
            text += ""
        data = {"text": text, "audio": audio, "keyboard": keyboard}

        return data
예제 #23
0
        parser.error('%s does not exist or no permissions or not executable' %
                     parsed.nvidia_settings_path)

    if not os.path.isfile(parsed.xterm_path) or not os.access(
            parsed.xterm_path, os.X_OK):
        parser.error('%s does not exist or no permissions or not executable' %
                     parsed.xterm_path)

    parsed.context_path = parsed.context_path.rstrip('/')

    return parsed


if __name__ == '__main__':

    name = 'nvidia-settings-rest-api'
    version = '0.0.1'

    config = cli_args(description='%s-%s' % (name, version))
    configure_root_logger(level=logging.DEBUG)
    set_process_name('name', 'version', config_obj=config)

    os.terminal_size((500, 20))

    api = Api(config=config, name=name, version=version)
    aiohttp.web.run_app(
        api.app,
        host=api.config.bind,
        port=api.config.port,
    )
예제 #24
0
from Api import Api
import numpy as np

botscore = 0
randomscore = 0
draw = 0
do = True
while do:
    deck = np.arange(-5, 11)
    done = False
    api = Api()
    actionspace = np.arange(1, 16)
    while not done:

        random_action = 0
        while random_action == 0:
            random_action = np.random.choice(actionspace)
        actionspace[random_action - 1] = 0

        env_action = 0
        while env_action == 0:
            env_action = np.random.choice(deck)
        deck[env_action + 5] = 0
        done, bot_action, bot_score, random_score = api.do_action(
            random_action, env_action)

        print("Bot Score: " + str(bot_score))
        print("Random policy Score: " + str(random_score))
        print("")

        if all(a == 0 for a in actionspace):
예제 #25
0
 def __init__(self, context, seed, model, tokenizer, first_message):
     self.brain = ChatBotBrain(context, seed, model, tokenizer)
     self.first_message = first_message
     self.init_answers()
     self.api = Api()