コード例 #1
0
    def get_available_timings(self, day):
        """
        Retrieves all the available badminton court with its associated timing

        Args:
            day (int): contains the day in which courts are to be searched for

        Returns:
            dictionary<string, list<string>>: Key represent the court names
                Value contains the list of strings representing the available timings of the court
        """
        driver = self._get_driver(
            "chrome",
            "C:/Users/winst/Documents/MEGA/Programs!/chromedriver_win32/chromedriver.exe",
        )

        self._login(driver, UserInfo.get_username(), UserInfo.get_password())
        time.sleep(2)
        self._navigate_to_badminton_booking(driver)
        all_available_timing = dict()
        self._set_date_and_activity(driver, day)

        have_courts = True
        while have_courts:
            available_courts = WebDriverWait(driver, PAUSE).until(
                EC.presence_of_all_elements_located(
                    (By.XPATH, './/*[@id = "main"]/div/div/article/div/section/ul/li')
                )
            )

            for i in range(len(available_courts)):
                court = WebDriverWait(driver, PAUSE).until(
                    EC.element_to_be_clickable(
                        (
                            By.XPATH,
                            './/*[@id = "main"]/div/div/article/div/section/ul/li['
                            + str(i + 1)
                            + "]",
                        )
                    )
                )
                driver.execute_script("arguments[0].scrollIntoView();", court)
                court.click()

                court_name, available_timings = self._get_timing_for_court_loc(driver)
                all_available_timing.update({court_name: available_timings})
                driver.back()
                time.sleep(2)
            have_courts = self._check_for_next_page(driver)

        driver.quit()

        return all_available_timing
コード例 #2
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(config["Develop"])
    Message.before_request(verify_login)
    Sub.before_request(verify_login)
    UserInfo.before_request(verify_login)
    SecretMessage.before_request(verify_login)
    app.register_blueprint(Auth, url_prefix="/auth")
    app.register_blueprint(Message, url_prefix="/message")
    app.register_blueprint(Sub, url_prefix="/sub")
    app.register_blueprint(UserInfo, url_prefix="/user_info")
    app.register_blueprint(SecretMessage, url_prefix="/sec_message")
    return app
コード例 #3
0
def user_input_handler(message):
    user = db_proxy.get_user_info(
        UserInfo(message.from_user.id, States.START, message.date))

    if check_message_duplicate(user, message) == False:
        logger.warning("Message duplicate detected from user %d" %
                       message.from_user.id)
        return

    user.last_message_time = message.date
    db_proxy.set_user_info(user)

    logger.debug("Current user state: %s" % str(user))

    if user.last_state == States.CONVERT_DOCUMENT:
        convert_document(user, message)
    elif user.last_state == States.PREVIEW_DOCUMENT:
        preview_document(user, message)
    elif user.last_state == States.CHECK_SYNTAX:
        bot.send_message(
            message.chat.id,
            "This function hasn't been implemented yet. \nBut, be patient.")
    else:
        bot.send_message(
            message.chat.id,
            "I don't have time for chat with you! Please tell me what to do.")
コード例 #4
0
def post_request():
    if request.method == 'POST':
        #print(request.data)
        user_data_recieved_in_bytes = request.data
        #decoding bytes to string
        user_data_converted_to_string = convert_bytes_to_string(
            user_data_recieved_in_bytes)
        #converting string to json
        userInfoJson = json.loads(user_data_converted_to_string)

        user = UserInfo(userInfoJson['email'], userInfoJson['password'])

        if (userInfoJson['type'] == 'login'):
            '''
            initiate userLogin
            result contains result after compleleting userLogin
            '''
            result = userLogin(user)

        else:
            '''
            initiate userSignUp
            result contains result after completing userSignUp
            '''
            result = userSignUp(user)
        print(result)
        return jsonify(result)
コード例 #5
0
    def __init__(self, slack_client, data):
        self.channel = data['channel']

        if 'user' in data:
            self.user_info = UserInfo(data['user'], slack_client)
            self.user_name = self.user_info.name
        else:
            self.user_info = None
コード例 #6
0
 def do_register(self, arg):
     "注册: register"
     if self.__interactionMachine.is_start() == True:
         user_id = input('请输入用户名: ')
         user_password = input('请输入密码: ')
         check_bool, check_msg = userIdDb.register(user_id, user_password)
         if check_bool == False:
             print(check_msg)
             return
         else:
             print('注册成功')
             self.userInfo = UserInfo(user_id)
             self.__interactionMachine.register()
             self.__interactionMachine.study()
             self.print_cur_cmd()
     else:
         print('不能注册')
         self.print_cur_cmd()
コード例 #7
0
 def do_login(self, arg):
     "登录: login"
     if self.__interactionMachine.is_start() == True:
         user_id = input('请输入用户名: ')
         user_password = input('请输入密码: ')
         check_bool, check_msg = userIdDb.login(user_id, user_password)
         if check_bool == False:
             print(check_msg)
             return
         else:
             print('登录成功')
             self.userInfo = UserInfo(user_id)
             self.__interactionMachine.login()
             self.__interactionMachine.study()
             self.print_cur_cmd()
     else:
         print('不能登录')
         self.print_cur_cmd()
コード例 #8
0
def start_forum_subscription(bot, update, job_queue):
    telegram_user = update.message.from_user
    chat_id = update.message.chat_id
    if chat_id in forum_subscribers:
        bot.sendMessage(chat_id, text='You have already subscribed')
        return
    if telegram_user.id not in users:
        users[telegram_user.id] = UserInfo(telegram_user)
    users[telegram_user.id].job_check_posts = True
    add_forum_job(telegram_user.id, job_queue)
    bot.sendMessage(chat_id, text='Subscription started')
    log_params('start_forum_subscription', update)
    users_store.store('users', users)
コード例 #9
0
def start_meeting_subscription(bot, update):
    telegram_user = update.message.from_user
    chat_id = update.message.chat_id
    if meeting_subscribers.count(chat_id) != 0:
        bot.sendMessage(chat_id,
                        text='You have already subscribed on meetings')
        return
    if telegram_user.id not in users:
        users[telegram_user.id] = UserInfo(telegram_user)
        state[chat_id] = MENU
    users[telegram_user.id].check_meetings = True
    meeting_subscribers.append(chat_id)
    bot.sendMessage(chat_id, text='Subscription on meeting started')
    log_params('start_meeting_subscription', update)
    users_store.store('users', users)
コード例 #10
0
def handle_previewlatex(message):
    user = db_proxy.get_user_info(
        UserInfo(message.from_user.id, States.START, message.date))

    if check_message_duplicate(user, message) == False:
        logger.warning("Message duplicate detected from user %d" %
                       message.from_user.id)
        return

    user.last_state = States.PREVIEW_DOCUMENT
    user.last_message_time = message.date
    db_proxy.set_user_info(user)

    bot.send_message(message.chat.id,
                     "This mode allows you preview your LaTeX document")
    bot.send_message(
        message.chat.id,
        "Just send a content of LaTeX document and receive back previews")
コード例 #11
0
def handle_convertlatex(message):
    user = db_proxy.get_user_info(
        UserInfo(message.from_user.id, States.START, message.date))

    if check_message_duplicate(user, message) == False:
        logger.warning("Message duplicate detected from user %d" %
                       message.from_user.id)
        return

    user.last_state = States.CONVERT_DOCUMENT
    user.last_message_time = message.date
    db_proxy.set_user_info(user)

    bot.send_message(message.chat.id,
                     "This mode allows you convert LaTeX document to PDF")
    bot.send_message(
        message.chat.id,
        "Just send a content of LaTeX document and receive back compiled PDF")
コード例 #12
0
def help_handler(message):
    user = db_proxy.get_user_info(
        UserInfo(message.from_user.id, States.START, message.date))

    if check_message_duplicate(user, message) == False:
        logger.warning("Message duplicate detected from user %d" %
                       message.from_user.id)
        return

    user.last_message_time = message.date
    db_proxy.set_user_info(user)
    help_text = 'This bot allows you to convert your raw LaTeX document to readable formats\n\n'
    help_text += 'The following commands are currently supported:\n'
    help_text += '/convertlatex - This mode allows you convert LaTeX document to PDF\n'
    help_text += '/previewlatex - This mode allows you preview your LaTeX document\n\n'
    help_text += 'LaTeX document should be send as message\n'
    help_text += 'Enjoy!'

    bot.send_message(message.chat.id, help_text)
コード例 #13
0
def handle_start(message):
    user = db_proxy.get_user_info(
        UserInfo(message.from_user.id, States.START, message.date))

    if check_message_duplicate(user, message) == False:
        logger.warning("Message duplicate detected from user %d" %
                       message.from_user.id)
        return

    response = ""
    if user.last_state == States.START:
        response = ("Hello, I am LaTeX Auto Bot.\n\n"
                    "Let's play with LaTeX documents!")
        user.last_state = States.MAIN_MENU
    else:
        response = "You have already stared me!"

    db_proxy.set_user_info(user)

    bot.send_message(message.chat.id, response)
コード例 #14
0
ファイル: zsite.py プロジェクト: xqk/42qu_github_mirror
 def info(self):
     from user_info import UserInfo
     id = self.id
     return UserInfo.mc_get(id)
コード例 #15
0
ファイル: api.py プロジェクト: michaeldu1/CovidBot
			return db[intent]
	else:
		send_message(sender_id, f"Hello, thanks for reaching out! To get started, this experience will be much better if I can get some information from you. What county and state are you currently in right now?")



def send_message_response(sender_id, message_text):
		tone_analysis = tone_analyzer.tone(
		    {'text': message_text},
		    content_type='application/json',
		    sentences = False
		).get_result()
		
		#Example response: {'document_tone': {'tones': [{'score': 0.958553, 'tone_id': 'anger', 'tone_name': 'Anger'}]}}
		#Possible tone_ids: anger, fear, joy, and sadness, analytical, confident, and tentative

		#######
		#Send message to wit ai
		#######
		resp = client.message(message_text)
		print("Resp is ", resp)

		# resp = {'text': 'Chicago, Illinois', 'intents': [{'id': '910709439678949', 'name': 'userLocation', 'confidence': 0.9945}], 'entities': {'wit$location:location': [{'id': '193227822570730', 'name': 'wit$location', 'role': 'location', 'start': 0, 'end': 17, 'body': 'Chicago, Illinois', 'confidence': 0.9408, 'entities': [], 'suggested': True, 'value': 'Chicago, Illinois', 'type': 'value'}]}, 'traits': {}}
		# resp = {'text': 'how many people have been vaccinated?', 'intents': [{'id': '880965962687968', 'name': 'totalVaccinations', 'confidence': 0.9983}], 'entities': {'wit$age_of_person:age_of_person': [{'id': '810205969703877', 'name': 'wit$age_of_person', 'role': 'age_of_person', 'start': 4, 'end': 37, 'body': 'many people have been vaccinated?', 'confidence': 0.8855, 'entities': [], 'suggested': True, 'value': 'many people have been vaccinated?', 'type': 'value'}]}, 'traits': {}}
		parse_response(sender_id, resp)

		# send_message(sender_id, f"Hello, you said: {message_text}")

if __name__ == "__main__":
	user_info = UserInfo()
	app.run(threaded=True, port=5000)
コード例 #16
0
ファイル: test_user.py プロジェクト: PapaKache/image-web
from user_info import UserInfo, UserManage

SAVE = False
um = UserManage()
if SAVE:
    u = UserInfo()
    u.setInfo('ouyang', '123456', "Tommy")
    um.saveUserInfo(u)

    u.setInfo('adfads', '123456', "Tommy")
    um.saveUserInfo(u)
    u.setInfo('ganadfads', '1456', "Tmmy")
    um.saveUserInfo(u)
    exit()
(r, u) = um.getUserInfo('adfads')
if r == False:
    print('get userinfo fail')
    exit()

s = u.toString()
print('to s')
print(s)
コード例 #17
0
class Interaction(Cmd):
    intro = "欢迎来到Learning-English-By-Translation.\n请登录(login)/注册(register): "
    prompt = 'Translater >'
    __interactionMachine = InteractionMachine()
    userInfo = None

    def __enter__(self):
        return self

    def __exit__(self, exception_type, exception_value, traceback):
        if self.userInfo:
            self.userInfo.write_dict()

    # ----- 基本命令 -----
    def do_login(self, arg):
        "登录: login"
        if self.__interactionMachine.is_start() == True:
            user_id = input('请输入用户名: ')
            user_password = input('请输入密码: ')
            check_bool, check_msg = userIdDb.login(user_id, user_password)
            if check_bool == False:
                print(check_msg)
                return
            else:
                print('登录成功')
                self.userInfo = UserInfo(user_id)
                self.__interactionMachine.login()
                self.__interactionMachine.study()
                self.print_cur_cmd()
        else:
            print('不能登录')
            self.print_cur_cmd()

    def do_register(self, arg):
        "注册: register"
        if self.__interactionMachine.is_start() == True:
            user_id = input('请输入用户名: ')
            user_password = input('请输入密码: ')
            check_bool, check_msg = userIdDb.register(user_id, user_password)
            if check_bool == False:
                print(check_msg)
                return
            else:
                print('注册成功')
                self.userInfo = UserInfo(user_id)
                self.__interactionMachine.register()
                self.__interactionMachine.study()
                self.print_cur_cmd()
        else:
            print('不能注册')
            self.print_cur_cmd()

    def do_new(self, arg):
        "开始新题目: new"
        if self.__interactionMachine.is_study() == True:
            chinese, english, question_id = self.userInfo.get_new_question()

            if chinese is None:
                print('全部学习完毕')
                return
                # self.__interactionMachine.error()

            print('-------------------------------')
            print('中文为:' + chinese)

            self.__chinese = chinese
            self.__english = english
            self.__question_id = question_id

            self.__interactionMachine.learnnew()
            self.print_cur_cmd()
        else:
            print('不能学习新题目')
            self.print_cur_cmd()

    def do_review(self, arg):
        "复习旧题目: review"
        if self.__interactionMachine.is_study() == True:
            chinese, english, complexity, question_id = self.userInfo.get_review_question(
            )

            if chinese is None:
                print('全部复习完毕')
                return
                # self.__interactionMachine.error()

            print('-------------------------------')
            print('中文为:' + chinese)

            self.__chinese = chinese
            self.__english = english
            self.__question_id = question_id
            self.__complexity = complexity

            self.__interactionMachine.review()
            self.print_cur_cmd()
        else:
            print('不能复习旧题目')
            self.print_cur_cmd()

    def do_answer(self, arg):
        "回答题目: answer"
        if self.__interactionMachine.is_learnnew(
        ) == True or self.__interactionMachine.is_review() == True:
            answer = input('请输入英文翻译: ')
            print('-------------------------------')
            print('英文为:' + self.__english)

            if self.__interactionMachine.is_learnnew() == True:
                complexity = input('您觉得难度是复杂(complex)/中等(medium)/简单(ease): ')
                while complexity not in ['complex', 'medium', 'ease']:
                    complexity = input(
                        '您觉得难度是复杂(complex)/中等(medium)/简单(ease): ')

                self.userInfo.insert_question(self.__question_id, answer,
                                              complexity)
            else:
                move_level = input('您觉得难度应该如何调整(-2~3整数, 数字越大越容易): ')
                while move_level not in ['-2', '-1', '0', '1', '2', '3']:
                    move_level = input('您觉得难度应该如何调整(-2~3整数, 数字越大越容易): ')

                self.userInfo.insert_question(self.__question_id,
                                              answer,
                                              self.__complexity,
                                              move_level=int(move_level))
            self.__interactionMachine.answer()
            self.__interactionMachine.study()
            self.print_cur_cmd()
        else:
            print('不能回答问题')
            self.print_cur_cmd()

    def do_skip(self, arg):
        "跳过题目: skip"
        if self.__interactionMachine.is_learnnew(
        ) == True or self.__interactionMachine.is_review() == True:
            if self.__interactionMachine.is_learnnew() == True:
                self.userInfo.insert_skip(self.__question_id)
            else:
                self.userInfo.insert_skip(self.__question_id,
                                          self.__complexity)

            self.__interactionMachine.skip()
            self.__interactionMachine.study()
            self.print_cur_cmd()
        else:
            print('不能跳过')
            self.print_cur_cmd()

    def do_exit(self, arg):
        "退出: exit"
        if self.__interactionMachine.is_study(
        ) == True or self.__interactionMachine.is_start() == True:
            print('退出系统')
            return True
        else:
            print('不可退出')
            self.print_cur_cmd()

    # ----- 高级处理 -----
    def parse_cmd(self, cmd):
        pass

    # def preloop(self):
    #     print('请登录(login)/注册(register): ')

    def emptyline(self):
        pass

    def default(self, line):
        print('命令错误')
        self.print_cur_cmd()

    def print_cur_cmd(self):
        if self.__interactionMachine.is_start():
            print('请登录(login)/注册(register)/退出(exit)')
        elif self.__interactionMachine.is_study():
            print('请选择学习新题目(new)/复习(review)/退出(exit)')
        elif self.__interactionMachine.is_learnnew():
            print('请选择回答(answer)/跳过(skip)')
        elif self.__interactionMachine.is_review():
            print('请选择回答(answer)/跳过(skip)')
コード例 #18
0
 def getUserInfo(self):
     new_user = UserInfo(self.userId, self.password)
     return new_user.getUserIdPassword()
コード例 #19
0
ファイル: slackbot.py プロジェクト: MaheshOruganti/Slackbot
def start(server_class=ThreadedHTTPServer,
          handler_class=SlackbotHealthCheckHandler,
          port=8080):
    """
        start slackbot
    """
    server_address = ('', port)

    httpd = server_class(server_address, handler_class)
    server_thread = Thread(target=httpd.serve_forever)
    server_thread.setdaemon = True

    try:
        server_thread.start()

        SLACK_BOT_NAME = 'jenkins-bot'
        SLACK_BOT_TOKEN = "xoxb-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
        SLACK_BOT_ID = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

        global AT_BOT_ID
        AT_BOT_ID = "<@" + SLACK_BOT_ID + ">"
        global AT_BOT_NAME
        AT_BOT_NAME = "<@" + SLACK_BOT_NAME + ">"

        logging_setup(SLACK_BOT_NAME)
        slack_client = SlackClient(SLACK_BOT_TOKEN)
        logging.info("starting bot: " + SLACK_BOT_NAME)
        user_info = UserInfo(SLACK_BOT_ID, slack_client)
        if user_info.online:
            time.sleep(5)
            logging.error('Another instance of ' + SLACK_BOT_NAME +
                          ' bot is already running. '
                          'You must close the other instance first!')
            exit(-1)

        connect = False
        while True:
            if not connect:
                connect = slack_client.rtm_connect()
                logging.info("connecting to rtm, bot: " + SLACK_BOT_NAME)
                logging.info("connecting to rtm, bot: " + AT_BOT_NAME +
                             ', Id: ' + AT_BOT_ID)
                logging.info('rtm_connect: ' + str(connect))
                if connect:
                    logging.info("Slackbot connected and running!")
                else:
                    logging.error(
                        "Connection failed. Invalid Slack token or bot ID?")
                    time.sleep(1)

            if connect:
                try:
                    # Parse any slack input
                    data = parse_slack_output(slack_client)
                    if data:
                        Slackbot(slack_client, data).handle_command()

                except Exception:
                    logging.error('exception', exc_info=True)
                    time.sleep(1)
                    connect = False

    except KeyboardInterrupt:
        logging.info('caught KeyboardInterrupt')
        state['shutdown'] = True

    if state['shutdown']:
        httpd.shutdown()
コード例 #20
0
 def info(self):
     from user_info import UserInfo
     id = self.id
     return UserInfo.mc_get(id)
コード例 #21
0
class TestUserInfo(unittest.TestCase):

    user_info = UserInfo()

    def setUp(self):
        FORMAT = "%(asctime)-15s %(message)s"
        logging.basicConfig(level=logging.DEBUG, format=FORMAT)

    def tearDown(self):
        pass

    def test_user_info_operation(self):
        logging.info("test_user_info_operation:")
        sqlite_file = "user_info_test.db"
        user_name = "user1"
        if os.path.isfile(sqlite_file):
            os.remove(sqlite_file)

        self.user_info.init_sqlite(sqlite_file)
        self.assertEqual(os.path.isfile(sqlite_file), True)

        self.user_info.user_register(user_name, "1234asdf", "*****@*****.**",
                                     {'a': 1})

        result = self.user_info.user_login(user_name, "1234asdf")
        self.assertEqual(result, True)

        self.user_info.exit_sqlite()

        # reopen db
        self.user_info.init_sqlite(sqlite_file)

        self.assertEqual(os.path.isfile(sqlite_file), True)
        result = self.user_info.user_login(user_name, "1234asdf")
        self.assertEqual(result, True)

        self.user_info.exit_sqlite()

        # open db directly
        con = sqlite3.connect(sqlite_file)
        cur = con.cursor()
        # And this is the named style:
        cur.execute("select user_name from user_info where user_name=?",
                    (user_name, ))
        user = cur.fetchone()
        self.assertEqual(user[0], user_name)
        con.close()

    def test_get_typing_record_with_kv(self):
        logging.info("test_get_typing_record_with_kv:")
        sqlite_file = "user_info_test.db"
        user_name = "test"
        password = "******"
        if os.path.isfile(sqlite_file):
            os.remove(sqlite_file)

        self.user_info.init_sqlite(sqlite_file)
        self.assertEqual(os.path.isfile(sqlite_file), True)

        self.user_info.user_register(user_name, password, "*****@*****.**",
                                     {'a': 1})

        result = self.user_info.user_login(user_name, password)
        self.assertEqual(result, True)

        type_record = [-52, -101, -30, 955, 172, 185, 1297]
        self.user_info.user_typing_record(user_name, str(type_record), {
            'time': int(time.time()),
            "tag": 1
        })

        type_record = [-32, -151, -48, 700, 164, 169, 191]
        self.user_info.user_typing_record(user_name, str(type_record), {
            'time': int(time.time()),
            "tag": 1
        })

        record_list = self.user_info.get_typing_record_with_kv(
            user_name, {"tag": 1})

        self.assertEqual(len(record_list), 2)
        self.assertEqual(
            str([-52, -101, -30, 955, 172, 185, 1297]) in record_list, True)
        self.assertEqual(
            str([-32, -151, -48, 700, 164, 169, 191]) in record_list, True)

        self.user_info.exit_sqlite()