def program_aktualne(): t = times[::] t.insert(0, {'block_from': time(18, 0), 'block_to': time(19, 0), 'date': date(2013, 6, 14), 'data': Markup(u'<a href="/stranka/warmup/">Honza Řezáč</a>')} ) t.insert(1, {'block_from': time(20, 0), 'block_to': time(23, 59), 'date': date(2013, 6, 14), 'data': Markup(u'<a href="/stranka/warmup/">Warm-up párty</a>')} ) actual_date = datetime.now().date() actual_time = datetime.now().time() next_times = [] for event in t: if (event['date'] == actual_date and event['block_to'] >= actual_time)\ or event['date'] > actual_date: next_times.append(event) return render_template( 'aktualne.html', menu=menu(), talks=get_talks_dict(), times=next_times, user=check_auth() )
def ring(message): bot.send_message( 211439710, 'Привет, у вас новая заявка.\n\n {name}'.format(name=message.contact)) bot.send_message(message.chat.id, 'Ваша заявка принята, в скором времени свяжемся с вами', reply_markup=utils.menu())
def index(): user = check_auth() user_hash = None if "PROGRAM_READY" in app.config['STAGES']: talks = get_talks_dict() extra_talks = [] else: talks, extra_talks = get_talks() # bez razeni talks = sorted(talks, key=lambda x: x['title']) if user: user_hash = user['user_hash'] stage_template = "index.html" if "END" in app.config['STAGES']: stage_template = "end.html" if "PREVIEW" in app.config['STAGES']: stage_template = "preview.html" return render_template( stage_template, user=user, menu=menu(), times=times, entrant_count=get_count(), entrants=get_entrants()[:50], user_votes=get_user_votes(user_hash), novinky=markdown_markup('novinky'), sponsors_main=markdown_markup('sponsors_main'), sponsors_medial=markdown_markup('sponsors_medial'), workshops=markdown_markup('workshopy-program'), sponsors=markdown_markup('sponsors'), talks=talks, extra_talks=extra_talks, talks_dict=get_talks_dict())
def mainMenu(): global listeAnimes result = -1 while result == -1: u.clear() print(str(len(listeAnimes)) + ' in list') print() result = u.menu([ 'Add', 'Download', 'Save download datas', 'Load download datas', 'Show dowload datas', 'Set cookie value', 'Quitter' ], 'Choix : ') if (result == 0): back, episodes = searchAnime() if not back: listeAnimes += episodes elif (result == 1): d.downloads = listeAnimes d.download() elif (result == 2): f = open('./save.json', 'w') encoder = j.JSONEncoder() f.write(encoder.encode(listeAnimes)) print('| Finish !') elif (result == 3): f = open('./save.json', 'r') listeAnimes = j.load(f) elif (result == 4): u.clear() for e in listeAnimes: print(e[1] + " > " + e[2] + " > " + e[3]) print("") input() elif (result == 5): exit()
def searchAnime(): result = s.search(input("anime : "), cookie) menu = ['Back'] menu += [res[1] for res in result] choice = u.menu(menu, 'Anime choisi : ') if choice == 0: return (True, '') choice -= 1 u.clear() anime = result[choice][1] print("| Getting informations about : " + anime) err, episodesPage = a.get_episodes_pages(result[choice][2], cookie) c = 1 while (c == 1 or c == -1): u.clear() anime = removeForb(anime) c = u.menu(['Yes', 'No'], 'Does anime name is : {} ? : '.format(anime)) if c != 0: anime = input('Anime name : ') c = 1 saison = 'unknown' while (c == 1 or c == -1): saison = removeForb(saison) u.clear() c = u.menu(['Yes', 'No'], 'Does saison name is : {} ? : '.format(saison)) if c != 0: saison = input('Saison name : ') print("| Getting informations about : " + anime) links = [] for i in range(len(episodesPage)): err, link = e.get_reader_link(episodesPage[i], cookie) links.append((link, anime, saison, 'Episode ' + str(i))) u.clear() return (False, links)
def program(): return render_template( 'program.html', menu=menu(), times=times, talks=get_talks_dict(), user=check_auth() )
def entrants(): return render_template( "entrants.html", user=check_auth(), menu=menu(), entrant_count=get_count(), entrants=reversed(get_entrants()) )
def talks_all(): talks, extra_talks = get_talks() return render_template( "talks.html", user=check_auth(), menu=menu(), talks=talks, extra_talks=extra_talks )
def sponsors(): return render_template( "partneri.html", user=check_auth(), menu=menu(), sponsors_main=markdown_markup('sponsors_main'), sponsors=markdown_markup('sponsors'), sponsors_other=markdown_markup('sponsors_other'), )
def profile(user_hash): data = get_account(user_hash) if not data: abort(404) return render_template( 'profil.html', user=check_auth(), menu=menu(), profile=data )
def talk_detail(talk_hash): talk = get_talk(talk_hash) if not talk: abort(404) author = get_account(talk['user']) return render_template( 'talk_detail.html', talk=talk, menu=menu(), author=author, user=check_auth())
def handle_add_item_phone(message): bot.send_message( message.chat.id, "Прекрасно, " + message.from_user.first_name + ", наша команда рада с Вами " "познакомиться! :)\n\n" "Немного о нас. Цель нашей компании обеспечить каждому " "клиенту эффективный и стабильный поток заявок " "с помощью комплексных решений Digital Marketing’a." "Для нас наибольшая радость сопровождать клиента на всех этапах " "формирования своего интернет маркетинга: от создания логотипа и " "брендинга - до разработки крупных сайтов, тестирования рекламных " "компаний и внедрения CRM-системы в отдел продаж клиента.") bot.send_message(message.chat.id, "А ещё Вы можете заказать обратный звонок", reply_markup=utils.menu())
def index(): user = check_auth() user_hash = None talks, extra_talks = get_talks() if user: user_hash = user['user_hash'] return render_template( "index.html", user=user, menu=menu(), times=times, entrant_count=get_count(), entrants=get_entrants()[50:0:-1], #user_votes=get_user_votes(user_hash), sponsors_main=markdown_markup('sponsors_main'), sponsors=markdown_markup('sponsors'), talks=get_talks_dict())
def start(message): text = message.text.split(" ") if len(text) == 2: if text[1].isdigit(): initial_id = text[1] base.addInvitation(initial_id, int(message.chat.id)) #base.add_user(message) main_message = "<b>Привет, " + message.from_user.first_name + "!</b>\n"\ "Меня зовут Анастасия, и я менеджер агентства <b>Intux Digital</b>.\n" \ "Сейчас, за меня конечно же пишет автоматический робот, но давайте познакомимся с Вами поближе, " \ "чтобы выяснить, чем и как мы можем быть Вам полезны.\n" \ "<b>Согласны? :)</b>\n" if not base.is_in_base(message.chat.id): bot.send_message(message.chat.id, main_message, reply_markup=utils.step_1(), parse_mode="HTML") else: bot.send_message(message.chat.id, "<b>Привет</b>", parse_mode='HTML', reply_markup=utils.menu())
def check_answer(message): # Если функция возвращает None -> Человек не в игре answer = utils.get_answer_for_user(message.chat.id) # Если None: if not answer: if message.text == "Начать игру": # Подключаемся к БД db_worker = SQLighter(config.database_name) # Получаем слачайную строку из БД row = db_worker.select_single(random.randint(1, utils.get_rows_count())) # Формируем разметку markup = utils.generate_markup(row[2], row[3]) # отправляем аудиофайл с вариантами ответа bot.send_voice(message.chat.id, row[1], reply_markup=markup) # Включаем "игровой режим" utils.set_user_game(message.chat.id, row[2]) # Отсоединяемся от БД db_worker.close() elif message.text == 'Cтатистика': Res = utils.return_res(message.chat.id) bot.send_message(message.chat.id, 'Ваш cчет: ' + str(Res)) else: bot.send_message(message.chat.id, 'Чтобы начать игру, напишите команду /game') else: # Уберём клавиатуру с вариантами ответа, и вернём предыдущую. markup = utils.menu() # Если ответ правильный/неправильный if message.text == answer: bot.send_message(message.chat.id, 'Верно', reply_markup=markup) res = True else: bot.send_message(message.chat.id, 'Не верно. Попробуйте еще раз!', reply_markup=markup) res = False utils.remove_res(message.chat.id, res) # Удаляем юзера из хранилища (игра закончена) utils.finish_user_game(message.chat.id)
def talk_edit(talk_hash=None): talk_data = {} user_data = check_auth() if talk_hash: talk_data = get_talk(talk_hash) if user_data['user_hash'] != talk_data['user']: abort(403) # uzivatel tohle nemuze editovat if request.method == "POST": form = TalkForm(request.form) if form.validate(): old_hash = talk_hash talk_hash = create_or_update_talk(form.data, talk_hash) user_user_go(user_data) flash(u'Přednáska byla uložena', 'success') if talk_hash != old_hash: return redirect(url_for('talk_edit', talk_hash=talk_hash)) else: form = TalkForm(**talk_data) return render_template( 'talk_form.html', form=form, user=check_auth(), talk=talk_data, menu=menu())
from utils import menu if __name__ == '__main__': menu()
def welcome(message): # вызов главного меню markup = utils.menu() bot.send_message(message.chat.id, 'Добро пожаловать!\nНажмите <b>Начать игру</b> и попробуйте угадать мелодию!', parse_mode='html', reply_markup=markup)
# fetch single book page async def fetch_books_page(session: aiohttp.client, page_link): book_parser = BooksPageParser(page_link, BooksLocator.BOOKS, BookParser, session) return await book_parser.get_items_async() # fetch multiple book pages async def fetch_multiple_book_pages(page_url_list): task_list = [] async with aiohttp.ClientSession() as session: for url in page_url_list: task_list.append(fetch_books_page(session, url)) return await asyncio.gather(*task_list) url_list = [] for page_number in range(1, parser.page_count()): url_list.append( f'http://books.toscrape.com/catalogue/page-{page_number + 1}.html') print('scraping...') parsed_books_list = asyncio.run(fetch_multiple_book_pages(url_list)) print('done!') for sub_list in parsed_books_list: books_list.extend(sub_list) books_generator = (book for book in books_list) menu(books_list, books_generator)
# minute = now.minute # seconds = now.second file_name = f'{router["server_ip"]}_{year}-{month}-{day}.txt' with open(file_name, 'w') as f: f.write(output) paramikoModule.close(client) time.sleep(5) while True: # Calls Georgios's banner utils.banner() # Provides the menu options to the user answer = utils.menu() if answer == '1': # Rather than storing creds in the code. Call the get_creds method to get them # it will return a dictionary consisting of the username & password variables credentials = utils.get_creds() # gets the new secret secret = utils.get_secret() # creating a dictionary for each device to connect to. It could read from a file the IPs... # add more routers as needed router1 = { 'server_ip': '10.x.x.x', 'server_port': '22', 'user': credentials["username"],
import os, utils #Calling menu utils.menu() import json, pprint, toml, os conf_file = "config.toml" if os.path.exists(conf_file): with open(conf_file, encoding='utf-8') as f: try: conf = toml.loads(f.read()) except: print("Could not read file:", conf_file) pprint.pprint(conf)
def want(message): bot.send_message(message.chat.id, "*Меню*\n\n", parse_mode="Markdown", reply_markup=utils.menu())
game_main = model[1].init_main(save_dqn, dqn, train=False, display=True) episode = 0 while episode < episodes: episode += 1 print("Beginning episode #%s" % episode) score = game_main(observations) print("Ending episode with score:", score) def main(game, opt, **kwargs): save_dqn_path = game[0] + "_dqn_model.pickle" save_txt_path = game[0] + "_dqn_scores.txt" save_dqn_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'saved_files', save_dqn_path) save_txt_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'saved_files', save_txt_path) if kwargs.get("load_path", False): load_dqn_path = save_dqn_path else: load_dqn_path = None train_test(opt, game, save_dqn_path, load_dqn_path, save_txt_path, **kwargs) # os.system("shutdown now -h") if __name__ == '__main__': game, opt = menu() main(game, opt)
shared_model = A3C(*model[1].build_model_a3c()) shared_model.share_memory() _lr = kwargs.get("lr", 1e-2) optimizer = SharedAdam(shared_model.parameters(), lr=_lr) optimizer.share_memory() processes = [] num_processes = kwargs.get("n_processes", 10) p = mp.Process(target=test, args=(shared_model,\ save_a3c, load_a3c,\ save_txt_path, model[1], kwargs)) p.start() processes.append(p) for n_p, rank in enumerate(range(0, num_processes)): p = mp.Process(target=train, args=(n_p,rank, shared_model, optimizer,\ save_a3c, load_a3c, save_txt_path, model[1], kwargs)) p.start() processes.append(p) for p in processes: p.join() # os.system("shutdown now -h") if __name__ == '__main__': model, opt = menu() main(model, opt)
def send_daily_menu(): for subscriber in get_subscribers(): print('Sending daily menu to user: %s' % subscriber) send_message(subscriber, menu())
result = self._getResultList(result['list']) return True, result def _getDownloadinfo(self, path): return "https://d.pcs.baidu.com/rest/2.0/pcs/file?method=download&access_token=" + oauth_info[ 'access_token'] + "&path=" + path def _getResultList(self, fileList): for i in range(len(fileList)): fileList[i]['download'] = self._getDownloadinfo( fileList[i]['path']) fileList[i]['name'] = (fileList[i]['path']).split("/")[-1] return fileList if __name__ == "__main__": oauth_info = utils.read_oauth_info() if not utils.oauth_check(oauth_info): oauth_result = oauth_ui.get_oa_info(oa_url, oa_result_base) oauth_info = utils.get_oauth_result(oauth_result) if not utils.oauth_check(oauth_info): print(oauth_info) print("登录错误") exit() utils.save_oauth_info(oauth_info) print("获取数据成功") bdy = Baiduyun(oauth_info) utils.menu(bdy)
def certificate_chains(): while True: choice = utils.menu() utils.switch(choice)