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}
def matchUserIcon(self): img = self.getImg() img = self.cropImg(0, 0, 160, self.height) r = Api.find('findUserIcon', img=img, img2=self.userIcon) if r['code'] == 4: loc = r['result'] self.AndroidBase.Rolling(loc[0], loc[1], loc[0], self.AndroidBase.height * 6 / 7) img = self.getImg() r = Api.find('findUserIcon', img=img, img2=self.userIcon) if r['code'] == 4: loc = r['result'] self.AndroidBase.Rolling(loc[0], loc[1], loc[0], self.AndroidBase.height * 6 / 7) img = self.getImg() r = Api.find('findUserIcon', img=img, img2=self.userIcon) if r['code'] == 4: loc = r['result'] self.AndroidBase.Rolling(loc[0], loc[1], loc[0], self.AndroidBase.height * 6 / 7) img = self.getImg() r = Api.find('findUserIcon', img=img, img2=self.userIcon) if r['code'] == 0: self.point = r['result'][:2] return True return False
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)
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 '''
def filllistitem(self): results = Api.callApi('item/').get('results') i = 1 for items in results: # Récupérer les détails de l'Item en appelant l'URL de détails item = Api.callApi(items.get('url')) # ajouter à la liste d'Item de la boutique self.listItems.append(Items(i, item.get('name'), item.get('cost'))) i = i + 1
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}
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
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()
def findVideoBlock(self): img = self.getImg() img = self.cropImg(0, 0, 380, self.height) r = Api.find('findVideoBlock', img) if r['code'] == 4: loc = r['result'] self.AndroidBase.Rolling(loc[0], loc[1], loc[0], self.AndroidBase.height * 5 / 6) img = self.getImg() r = Api.find('findVideoBlock', img) if r['code'] == 0: self.point = r['result'][:2] self.userIcon = r['result'][2] return True return False
def findText(self, name): img = self.getImg() r = Api.find('findText', img=img, txt=name) if r['code'] == 0: self.point = [r['result'][0], r['result'][1]] return True return False
def filllistcategory(self): """ :return: void """ results = Api.callApi('item-category/').get('results') for cat in results: self.listCategory.append(ItemCategory(cat.get('name')))
def findCommentIcon(self): img = self.getImg() img = self.cropImg(870, 0, 1080, self.height) r = Api.find('findCommentIcon', img) if r['code'] == 0: self.point = [r['result'][0] + 870, r['result'][1]] return True return False
def findPlusButton(self): img = self.getImg() img = self.cropImg(960, 0, 1080, self.height) r = Api.find('findPlusButton', img) if r['code'] == 0: self.point = [r['result'][0] + 960, r['result'][1]] return True return False
def findFirstImg(self): img = self.getImg() img = self.cropImg(85, 600, 320, self.height) r = Api.find('findFirstImg', img=img) if r['code'] == 0: self.point = [r['result'][0] + 85, r['result'][1] + 600] return True return False
def findFavoriteSend(self): img = self.getImg() img = self.cropImg(500, 500, 1080, self.height) r = Api.find('findFavoriteSend', img=img) if r['code'] == 0: self.point = [r['result'][0] + 500, r['result'][1] + 500] return True return False
def __init__(self): self.__api = Api() self.__player = PlayerProcess() self.__song_queue = [] self.__song_queue_position = None self.__playing = False self.__shuffle = False self.__repeat = False
def findFavoriteButton(self): img = self.getImg() h = self.height - 800 img = self.cropImg(0, h, 1080, self.height) r = Api.find('findFavoriteButton', img) if r['code'] == 0: self.point = [r['result'][0], r['result'][1] + h] return True return False
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
def findActiveGroup(self): img = self.getImg() img = self.cropImg(0, 0, 200, self.height) r = Api.find('findActiveGroup', img) if r['code'] == 3: self.return1() return False if r['code'] == 0: self.point = r['result'] return True return False
def generate(): params = [] required = ['access_token','photo_url'] for e in required: param = request.args.getlist(e) if len(param) <= 0: response.update({ "err":"1", "msg":e + ' is required for this method' }) return reply(response) else: params.append(param) api = Api(params[0][0],params[1][0]) photo_data = json.loads(api.run()) if photo_data: try: photo_data["data"]["created_time"] = datetime.datetime.fromtimestamp(int(photo_data["data"]["created_time"])).strftime('%d %b %Y') except: pass return render_template("generate.html",all_info=photo_data) else: response.update({ "err":"1", "msg":"Photo could not been fetched." }) return reply(response)
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)
class MyTestCase(unittest.TestCase): def setUp(self): self.testApi = Api() self.testStock = Stock("jnj") def tearDown(self): del self.testStock del self.testApi def test_incorrect_stock(self): with self.assertRaises(ValueError): badStock = Stock("jiok") self.testApi.get_stock_quote(badStock) def test_no_input_stock(self): with self.assertRaises(ValueError): badStock = Stock("") self.testApi.get_stock_quote(badStock) def test_api_call(self): test = self.testApi.get_stock_quote(self.testStock) self.assertIs(type(test.last_price), float) self.assertIs(type(test.last_price_update), datetime)
def getQuandlTickers(self, aQuandlUrls): """ get a unique set of tickers by adding everything in "aSet not in aTickers" to aTickers link: http://stackoverflow.com/questions/7961363/python-removing-duplicates-in-lists :param aQuandlUrls: Quandl URLs :return: a list of unique tickers from the provided quandl urls """ aTickers = [] for strQuandl in aQuandlUrls: aSet = Api.getQuandlTickers(strQuandl) aTickers += list(set(aSet) - set(aTickers)) del aSet return aTickers
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")
def insertDailyData(self): """ Routine for collecting and inserting daily data from the YahooApi. All data is for the previously closed trading day. :return: None """ Logger.logApp("Collecting and inserting daily data...") # chunk the tickers into a managable size, retrieve data for each chunk, and then insert each chunk # chunking allows us to insert periodicly through the data collection process and ensures our YahooApi request # doesnt return a 414 response code (URI too long) iCurChunk = 0 aTickers = self.getQuandlTickers(AppVars.DATA_DAILY_TICKERS) aTickerChunks = Utils.chunk(aTickers, AppVars.CHUNK_TICKERS) for iCurChunk in range(0, len(aTickerChunks)): oData = Api.getData(aTickerChunks[iCurChunk], AppVars.DATA_DAILY_DIMENSIONS) if oData: TradingData.insert(self.oDB, TradingData.S_DAILY_DATA, oData) self.oDB.commit() Logger.logApp("Inserting data for chunk " + str(iCurChunk + 1) + " of " + str(len(aTickerChunks))) else: Logger.logError('There was an error retrieving data for chunk ' + str(iCurChunk + 1)) del oData
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}
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):
class Base(): api = '' config = '' 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() def __del__(self): self.config.write(open('conf.ini', 'w')) def updateTimeOffset(self): server_time = int(self.api.gettime()) local_time = int(time.time()) time_offset = str(server_time - local_time) self.config.set('safe', 'time_offset', time_offset) def setUserName(self, user): self.config.set('username', 'user', user) def setPassword(self, password): self.config.set('username', 'password', password) def getConfig(self, sec, opt): return self.config.get(sec, opt) def update(self, ip='', domain='', update_type='', domain_auth_code='', user='', password=''): local_time = str(int(time.time())) last_domain = self.config.get('runtime', 'domain') if ip == '': ip = self.api.getip() else: self.config.set('runtime', 'ip', ip) if update_type == '': update_type = self.config.get('base', 'update_type') else: self.config.set('base', 'update_type', update_type) if domain == '': domain = self.config.get('runtime', 'domain') else: self.config.set('runtime', 'domain', domain) if domain_auth_code == '': domain_auth_code = self.config.get('runtime', 'auth_code') else: self.config.set('runtime', 'auth_code', domain_auth_code) if user == '': user = self.config.get('username', 'user') else: self.config.set('username', 'user', user) if password == '': password = self.config.get('username', 'password') else: self.config.set('username', 'password', password) on_error = self.config.get('runtime', 'on_error') #当上次操作没有发生错误,ip未改变,上次更新与本次更新的域名相同时,不执行更新操作 if self.config.get( 'runtime', 'ip') == ip and on_error == '0' and last_domain == domain: #ip未发生变化,且上一次操作未发生错误,不触发更新 self.config.set('runtime', 'last_check', local_time) return True else: self.config.set('runtime', 'last_check', local_time) self.config.set('runtime', 'last_update', local_time) self.config.set('runtime', 'ip', ip) if update_type == 'safe': time_offset = self.config.get('safe', 'time_offset') rst = self.api.update(domain, ip, domain_auth_code, time_offset) if rst == 'success': self.config.set('runtime', 'on_error', '0') else: self.config.set('runtime', 'on_error', '1') return rst elif update_type == 'username': user = self.config.get('username', 'user') password = self.config.get('username', 'password') rst = self.api.updateByUserName(domain, ip, user, password) if rst == 'success': self.config.set('runtime', 'on_error', '0') else: self.config.set('runtime', 'on_error', '1') return rst elif update_type == 'authcode': rst = self.api.updateByAuthCode(domain, ip, domain_auth_code) if rst == 'success': self.config.set('runtime', 'on_error', '0') else: self.config.set('runtime', 'on_error', '1') return rst else: return 'error:unknown_type'
user = User() first = False loggedin = False if userdata.count() == 0: print "Welcome to Auto Course Downloader! To get started fill the details below" user_regno = raw_input("Enter regno: ") user_password = getpass.getpass("Enter password: ") user.user_regno = user_regno user.user_password = user_password first = True else: for firstu in userdata: user.user_regno = firstu.user_regno user.user_password = firstu.user_password user.user_folder = firstu.user_folder api = Api(user.user_regno, user.user_password) try: login = api.login() if login: loggedin = True if first: courses = api.get_courses() root = Tk() root.withdraw() folder_path = askdirectory() print folder_path user.user_folder = folder_path db.add(user) db.add_all(courses) db.commit() else:
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
def run(self): """ Main daemon process invoked by DataDaemon. This method is a infinite loop that has logic in it's body to execute commands at specific times of day. More specifically, this process is responsible for creating, running, and closing each trading day. This process will get killed when the daemon stops. :return: """ # service variables bTrading = False while True: # Get the current EST time and date oNow = datetime.datetime.now(timezone(Conf.MARKET_TIMEZONE)) oNowDate = datetime.datetime(oNow.year, oNow.month, oNow.day) # Market is only open on week days from 9:30AM EST to 4:00PM EST bIsWeekDay = not(oNow.strftime('%A') == 'sunday' or oNow.strftime('%A') == 'saturday') bIsMarketHours = datetime.time(Conf.MARKET_OPEN_HOUR, Conf.MARKET_OPEN_MINUTE) <= datetime.time(oNow.hour, oNow.minute) \ and datetime.time(oNow.hour, oNow.minute) < datetime.time(Conf.MARKET_CLOSE_HOUR, Conf.MARKET_CLOSE_MINUTE) bIsOpen = bIsWeekDay and bIsMarketHours # it's after 5:00AM EST on a week day, let's collect the previous days data and get everything set up if (bIsWeekDay and not bTrading and oNow.hour >= 5) or Conf.DAEMON_IS_DEBUG: # insert daily data from yesterday if Conf.DAEMON_INSERT_DAILY: self.insertDailyData() # market vars, must be deleted at EOD aTickers = self.getQuandlTickers(AppVars.DATA_RT_TICKERS) aTickerChunks = Utils.chunk(aTickers, AppVars.CHUNK_TICKERS) del aTickers oPortfolioCollection = PortfolioCollection() # OK to stop trading bTrading = True # the market is open! start collecting data and trading if (bTrading and bIsOpen and aTickerChunks) or Conf.DAEMON_IS_DEBUG: Logger.logApp("Starting a trading cycle...") # get current pricing data for all tickers and create a data map where keys are tickers and values are # the location of the ticker's value in the data list aDataList = [] oDataMap = {} for iCurChunk in range(0, len(aTickerChunks)): aChunkData = Api.getData(aTickerChunks[iCurChunk], AppVars.DATA_RT_DIMENSIONS) for iDataIndex in range(len(aDataList), len(aDataList) + len(aChunkData)): oDataMap[aChunkData[iDataIndex - len(aDataList)][Company.SYMBOL]] = iDataIndex aDataList += aChunkData del aChunkData del iCurChunk del iDataIndex # broadcast new data to all portfolios for oPortfolio in oPortfolioCollection.iteritems(): oAlgorithm = oPortfolio['algorithm'] oAlgorithm.run(oDataMap) # insert new data if aDataList: TradingData.insert(self.oDB, TradingData.S_RT_DATA, aDataList) self.oDB.commit() else: Logger.logError('There was an error inserting real time data') del oDataMap Logger.logApp("Finished a trading cycle") # it's after 4:30PM EST on a week day let's close the trading day and go to sleep if (bIsWeekDay and bTrading and oNow.hour >= 16 and oNow.minute > 30) or Conf.DAEMON_IS_DEBUG: # insert portfolio data for oPortfolio in oPortfolioCollection.iteritems(): oAlgorithm = oPortfolio['algorithm'] oAlgorithm.insert() # clean up market vars del aTickerChunks del oPortfolioCollection # OK to start trading bTrading = False time.sleep(Conf.DAEMON_SLEEP)
def test_answer(self, chat_id, good=False): Api().remove_test_word(chat_id, good=good) return self.test_question_data(chat_id)
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)
#$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.
user = User() first = False loggedin = False if userdata.count() == 0: print "Welcome to Auto Course Downloader! To get started fill the details below" user_regno = raw_input("Enter regno: ") user_password = getpass.getpass("Enter password: ") user.user_regno = user_regno user.user_password = user_password first = True else: for firstu in userdata: user.user_regno = firstu.user_regno user.user_password = firstu.user_password user.user_folder = firstu.user_folder login = Api.login(user.user_regno, user.user_password) try: if login[0] == True: cookies = login[1] loggedin = True if first: courses = Api.get_courses(cookies) root = Tk() root.withdraw() folder_path = askdirectory() print folder_path user.user_folder = folder_path db.add(user) db.add_all(courses) db.commit() else:
class Player(object): """Audio Player wrapper object""" _STREAM_URL = 'http://%s/stream.php?streamKey=%s' def __init__(self): self.__api = Api() self.__player = PlayerProcess() self.__song_queue = [] self.__song_queue_position = None self.__playing = False self.__shuffle = False self.__repeat = False def play(self): if not self.__playing: if self.__song_queue_position is None: pass else: self.__player.set_song(self.__get_song_url( self.__song_queue[self.__song_queue_position])) self.__player.play() self.__playing = True def stop(self): self.__player.stop() self.__playing = False def pause(self): self.__player.pause() self.__playing = False def is_playing(self): return self.__playing def next(self): self.stop() self.__song_queue_position = self.__get_next(self.__song_queue_position) self.play() def previous(self): self.stop() self.__song_queue_position = self.__get_previous(self.__song_queue_position) self.play() def skip_to_in_queue(self, offset): offset = self.__constrain_offset(offset) self.stop() self.__song_queue_position = offset self.play() def set_shuffle(self, status=None): if status is None: self.__shuffle = not self.__shuffle else: self.__shuffle = bool(status) return self.__shuffle def set_repeat(self, status=None): if status is None: self.__repeat = not self.__repeat else: self.__repeat = bool(status) return self.__repeat def add_song_to_queue(self, song_id): if song_id not in self.__song_queue: self.__song_queue.append(int(song_id)) if self.__song_queue_position is None: self.__song_queue_position = 0 def remove_song_from_queue(self, song_id): if song_id in self.__song_queue: if song_id is self.__song_queue[self.__song_queue_position]: self.next() self.__song_queue.remove(song_id) if len(self.__song_queue) is 0: self.__song_queue_position = None def add_playlist_to_queue(self, playlist_id): #playlist = getplaylist(playlist_id) #for id in [int(song[SongID]) for song in playlist]: song_queue.append(id) pass def clear_queue(self): self.stop() self.__song_queue = [] def get_queue(self): return self.__song_queue def get_queue_song(self, offset): return self.__song_queue[self.__constrain_offset(offset)] def __constrain_offset(self, offset): return max(min(offset, len(self.__song_queue)), 0) def __get_next(self, current_position): if self.__shuffle: return randint(0, len(self.__song_queue)) elif self.__repeat: return (current_position + 1) % len(self.__song_queue) else: if current_position + 1 > len(self.__song_queue): return current_position else: return current_position + 1 def __get_previous(self, current_position): if self.__shuffle: return randint(0, len(self.__song_queue)) else: return abs(current_position - 1 % len(self.__song_queue)) def __get_song_url(self, song_id): streamkey_info = self.__api.getStreamKeyFromSongIDEx( mobile=False, country=self.__api.get_country(), prefetch=False, songID=int(song_id)) return self._STREAM_URL % (streamkey_info['ip'], quote_plus(streamkey_info['streamKey']))
def selectDailyData(self): """ Retrieve daily data for all our tickers :return: """ TradingData.get(self.oDB, TradingData.S_DAILY_DATA, Api.getQuandlTickers(ApiParameters.QUANDL_SP500), '2015-11-20')
class Navegador(Gtk.HPaned): __gsignals__ = { "info": (GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE, (GObject.TYPE_PYOBJECT, )) } def __init__(self): Gtk.HPaned.__init__(self) self.api = None self.descriptor = None self.pack1(self.area_izquierda_del_panel(), resize=False, shrink=True) self.pack2(self.area_derecha_del_panel(), resize=True, shrink=True) self.show_all() self.api.connect('objeto', self.ver_objeto) self.api.connect('info', self.re_emit_info) def re_emit_info(self, widget, objeto): self.emit('info', objeto) def ver_objeto(self, widget, objeto): os.chdir(DATOS) try: if objeto: pydoc.writedoc(objeto) archivo = os.path.join(DATOS, '%s.html' % (objeto.__name__)) self.descriptor.open(archivo) else: self.descriptor.open('') except: self.descriptor.open('') 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 def area_derecha_del_panel(self): scrolled_window = Gtk.ScrolledWindow() scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self.descriptor = WebKit.WebView() scrolled_window.add_with_viewport(self.descriptor) return scrolled_window def get_item(self, widget): self.api.llenar([widget.get_active_text()])
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