def handler(self): users = self.vk.get_friends() self.logger.info("Got user's friends") users_info = [] while len(users) > 0: users_info.append(self.vk.get_info(users[:1000])) del (users[:1000]) time.sleep(0.4) for user in users_info: for i in user: self.cities_handler(i) data = [ Counter(self.cities), Counter(self.schools), Counter(self.high_schools) ] self.post_handler(data) out = self.reply_contruct() self.save(out) self.logger.info(f'User with ID {self.user_id} handled') if not config['server_mode']: hues.success(''.join(out)) else: return ''.join(out)
def mclient(): # Step1: 输入host和port信息 host ='127.0.0.1' #raw_input('please input host name: ') port ='51500' #raw_input('please input textport: ') # Step2: 创建socket对象 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: port = int(port) except ValueError: port = socket.getservbyname(port, 'udp') # Step3: 打开socket连接 s.connect((host, port)) # 不管是tcp还是udp的都有connnect方法 hues.log("Looking for replies; press Ctrl-C or Ctrl-Break to stop") while 1: # Step4: 发送数据 hues.log("Enter data to transmit: ") data = sys.stdin.readline().strip() s.sendall(data) #s.sendto(data) # Step5: 接收服务器发过来的数据(一直在等待服务器发送过来的数据) buf = s.recv(2048) if not len(buf): break #sys.stdout.write(buf) hues.success(buf) time.sleep(5) s.close()
def mserver(): host = '127.0.0.1' # Bind to all interfaces port = 51500 # Step1: 创建socket对象 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Step2: 设置socket选项(可选) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Step3: 绑定到某一个端口 s.bind((host, port)) # Step4: 监听该端口上的连接 while 1: try: message, address = s.recvfrom(8192) hues.info("Got data from ", address) hues.success("Data is:",message) s.sendto("Data is received succeefully", address) # 告知客户端,信息已收到 except (KeyboardInterrupt, SystemExit): hues.warn("raise") raise except: hues.warn("traceback") traceback.print_exc()
def scan_hostname(hostname, SerialNumber, lines, Proxy, conn, site_infos): """ try scan a hostname and get informations back (HTTP code, page title, IP address, ASN, abuse email etc). :param hostname: the hostname present in the certificate :param SerialNumber: the serial number of the certificate :param lines: list of user-agents strings :param Proxy: proxy settings :param conn: database connection :param site_infos: informations extracted on the net for the given hostname :return: True if everything went fine, False if any problem has been encountered """ title = "" try: r = get_requests(hostname, lines, conn, Proxy) if r is not None: hues.success('HTTP ' + str(r.status_code) + ' - ' + hostname) # retrieve the title of the homepage title = get_webpage_title(r) # retrieve ASN informations ipaddr = socket.gethostbyname(hostname) asn, asn_cidr, asn_country_code, asn_description, asn_abuse_email = get_ASN_Infos( ipaddr) # build the content of the alert file using certificate / webpage / ASN informations site_infos = { 'hostname': hostname, 'http_code': r.status_code, 'cert_serial_number': SerialNumber, 'webpage_title': title, 'ip_addr': ipaddr, 'asn': asn, 'asn_cidr': asn_cidr, 'asn_country_code': asn_country_code, 'asn_description': asn_description, 'asn_abuse_email': asn_abuse_email } return site_infos else: return {} except KeyboardInterrupt: print("scan_hostname() - Interrupt received, stopping ...") print("start - committing, closing DB") conn.commit conn.close print("ending - committing, closing DB") sys.exit(0) except Exception as ex: hues.error("scan_hostname() - any other kind of error: {}".format(ex)) return {}
async def enter_confirmation_сode(): hues.error("Похоже, у вас установлена двухфакторная авторизация!") hues.error("Пожалуйста, введите код подтверждения:") code = input() hues.success("Спасибо! Продолжаю приём сообщений") return code
def login(looter, args): if args['--username']: username = args['--username'] if not looter.is_logged_in(): password = args['--password'] or getpass.getpass() looter.login(username, password) if not args['--quiet']: hues.success('Logged in.') elif not args['--quiet']: hues.success("Already logged in.")
def vk_init(self): hues.warn("Авторизация в ВКонтакте...") # Словарь вида ID -> время self.messages_date = {} self.vk = VkPlus(token=self.TOKEN, login=self.VK_LOGIN, password=self.VK_PASSWORD, scope=self.SCOPE, app_id=self.APP_ID) hues.success("Успешная авторизация")
def vk_init(self): hues.warn("Авторизация в ВКонтакте...") # Словарь вида ID -> время self.messages_date = {} self.vk = VkPlus(users_data=self.USERS, proxies=self.PROXIES, bot=self, scope=self.SCOPE, app_id=self.APP_ID) if self.vk: hues.success("Успешная авторизация")
def writeNew(): global ids_new global urls_new if ids_new: f = open( os.path.dirname(os.path.realpath(__file__)) + '/inc/id_url.csv', 'a') for i in range(0, len(ids_new)): f.write("{},{}\n".format(ids_new[i], urls_new[i])) f.close() hues.success('ID URL DATA HAS BEEN WRITTEN to inc/id_url.csv')
def webfonts_generator(path, urlprefix, output, take, silent): '''Discover and generate CSS file for the webfonts.''' fonts = discover_fonts(path, urlprefix, take) with open(output, 'w') as fp: fp.write(generate_css(fonts)) if not silent: hues.success(f'[!] Found {len(fonts)} matching fonts in {path}.') for name, els in fonts.groupby('fname').groups.items(): hues.info(f' -> {name} [{len(els)} style(s)]') hues.success(f'<~> CSS File written in {output}')
def tcplink(sock,addr): hues.info("accept new connection from %s:%s..." % addr) sock.send("Welcom!".encode()) while True: #通信循环:发送与接收 data=sock.recv(1024) hues.success("Received [%s] from %s:%s" %(data,addr[0],addr[1])) time.sleep(5) if data=='exit' or not data: break sock.send("hello: ".encode()+data) sock.close() hues.warn("Connection from %s:%s closed." % addr)
def handle(self, *args, **options): indices = registered_indices() if len(indices): hues.info('Discovered', len(indices), 'Indexes') else: hues.warn('No search indexes found') for i, index in enumerate(indices, 1): hues.info('==> Indexing objects from', index.model, 'in', index) for obj in tqdm(index.queryset): doc = index.init_using_pk(obj.pk) doc.prepare() doc.save() hues.success('--> {0}/{1} indexed.'.format(i, len(indices)))
def writeToCSV(): global Title global ID global Price global Currency global LocationCity global LocationCounty global LocationDistrict global LocationLatitude global LocationLongitude global Date global Brand global Series global Model global Fuel global Year global Gear global Km global FrameType global EngineVolume global HorsePower global DriveType global Color global Warranty global Plate global Status global SalerType global Status global Exchange WriteMe = Title + ',' + str(ID) + ',' + str( Price ) + ',' + Currency + ',' + LocationCity + ',' + LocationCounty + ',' + LocationDistrict + ',' + str( LocationLatitude ) + ',' + str( LocationLongitude ) + ',' + Date + ',' + Brand + ',' + Series + ',' + Model + ',' + Fuel + ',' + str( Year ) + ',' + Gear + ',' + str( Km ) + ',' + FrameType + ',' + EngineVolume + ',' + HorsePower + ',' + DriveType + ',' + Color + ',' + str( Warranty) + ',' + Plate + ',' + SalerType + ',' + Status + ',' + str( Exchange) File = open( os.path.dirname(os.path.realpath(__file__)) + '/inc/vehicle_data.csv', 'a', encoding="utf-8") # 'a' parameter for append, 'w' for overwrite File.write(WriteMe + '\n') File.close() hues.success('VEHICLE DATA HAS BEEN WRITTEN to inc/vehicle_data.csv')
def main(argv=sys.argv[1:]): """Run from the command line interface. """ warnings._showwarning = warnings.showwarning warnings.showwarning = warn_with_hues args = docopt.docopt(__doc__, argv, version='instaLooter {}'.format(__version__)) looter = InstaLooter(directory=os.path.expanduser( args.get('<directory>') or os.getcwd()), profile=args['<profile>'], hashtag=args['<hashtag>'], add_metadata=args['--add-metadata'], get_videos=args['--get-videos'], jobs=int(args['--jobs']), template=args['--template']) try: if args['--credentials']: credentials = args['--credentials'].split(':', 1) login = credentials[0] password = credentials[1] if len( credentials) > 1 else getpass.getpass() looter.login(login, password) if not args['--quiet']: hues.success('Logged in.') if args['--time']: timeframe = get_times_from_cli(args['--time']) else: timeframe = None except ValueError as ve: console.error(ve) sys.exit(1) try: looter.download( media_count=int(args['--num-to-dl']) if args['--num-to-dl'] else None, with_pbar=not args['--quiet'], timeframe=timeframe, new_only=args['--new'], ) except KeyboardInterrupt: looter.__del__() finally: warnings.showwarning = warnings._showwarning
def writeToCSV(): global Title global ID global Price global Currency global LocationCity global LocationCounty global LocationDistrict global LocationLatitude global LocationLongitude global Date global Type global m2 global RoomCount global BuildingAge global Floor global TotalFloor global Heating global Bathrooms global Furnished global Status global Residential global Dues global AvailableforLoan global SalerType global Exchange Title_temp = Title.replace(',', '') WriteMe = Title + ',' + str(ID) + ',' + str(Price) + ',' + str( Currency ) + ',' + LocationCity + ',' + LocationCounty + ',' + LocationDistrict + ',' + str( LocationLatitude ) + ',' + str(LocationLongitude) + ',' + Date + ',' + Type + ',' + str( m2) + ',' + str(RoomCount) + ',' + str(BuildingAge) + ',' + str( Floor) + ',' + str(TotalFloor) + ',' + Heating + ',' + str( Bathrooms ) + ',' + str(Furnished) + ',' + str(Status) + ',' + str( Residential) + ',' + str(Dues) + ',' + str( AvailableforLoan) + ',' + SalerType + ',' + str(Exchange) File = open( os.path.dirname(os.path.realpath(__file__)) + '/inc/real_estate_data.csv', 'a', encoding="utf-8") # 'a' parameter for append, 'w' for overwrite File.write(WriteMe + '\n') File.close() hues.success( 'REAL ESTATE DATA HAS BEEN WRITTEN to inc/real_estate_data.csv')
def main(): vk_session = vk_api.VkApi(token=VK_USER_TOKEN) vk = vk_session.get_api() peer_id = get_peer_id(vk) directory = create_directory(peer_id) start_time = time.time() photos_urls = get_photos_urls(vk, peer_id, directory) output = download_photos(photos_urls) end_time = time.time() hues.success( f"--- {len(output)} фотографий скачано за {end_time - start_time} секунд ---" )
def handle(self, delete, *args, **options): indices = registered_indices() connection = connections.get_connection() hues.info('Using connection', connection) if len(indices): hues.info('Discovered', len(indices), 'Indexes') else: hues.warn('No search index found') for i, index in enumerate(indices, 1): hues.info('==> Initializing', index.__name__) with index().ensure_closed_and_reopened() as ix: if delete: hues.warn('Deleting existing index.') ix.delete_index() ix.init() hues.success('--> Done {0}/{1}'.format(i, len(indices)))
def plugin_init(self): hues.info("Загрузка плагинов...") # Подгружаем плагины self.plugin_system = PluginSystem(self.vk, folder=abspath('plugins')) self.plugin_system.register_commands() # Чтобы плагины могли получить список всех плагинов (костыль) self.vk.get_plugins = self.plugin_system.get_plugins # Для парсинга команд с пробелом используется # обратная сортировка, для того, чтобы самые # длинные команды были первыми в списке command_names = list(self.plugin_system.commands.keys()) command_names.sort(key=len, reverse=True) from command import CommandSystem self.cmd_system = CommandSystem(command_names, self.plugin_system) self.scheduled_funcs = self.plugin_system.scheduled_events hues.success("Загрузка плагинов завершена")
def locales_combinator(path, output, silent): '''Combines Locale Strings in yml files at `path` in a json blob at `output`''' locale_files = list(discover_locales(path)) locales = {l.lang: l.body for l in locale_files} langs = [l.lang for l in locale_files] blob = { '_meta': { 'langs': langs, 'generated': datetime.datetime.utcnow().isoformat(), }, **locales, } with open(output, 'w') as fp: json.dump(blob, fp, ensure_ascii=False, indent=2, sort_keys=True) if not silent: hues.info('-> Discovered locales in languages:', blob['_meta']['langs']) hues.success('<~> Wrote locales as json to', output)
continue # Обновляем время, чтобы не приходили старые события self.longpoll_values['ts'] = events['ts'] for event in events['updates']: schedule_coroutine(self.check_event(event)) if __name__ == '__main__': hues.info("Приступаю к запуску DarkVKBOT") bot = Bot() main_loop = asyncio.get_event_loop() main_loop.run_until_complete(set_up_roles(bot)) hues.success("Приступаю к приему сообщений") try: main_loop.run_until_complete(bot.run(main_loop)) except (KeyboardInterrupt, SystemExit): hues.warn("Выключение бота...") except Exception as ex: import traceback logging.warning("Fatal error:\n") traceback.print_exc() exit(1)
def main(argv=None): """Run from the command line interface. """ argv = argv or sys.argv[1:] try: args = docopt.docopt(__doc__, argv, version='instaLooter {}'.format(__version__)) except docopt.DocoptExit as de: print(de) return 1 argv_positional = [param for param in argv if not param.startswith("-")] if argv_positional[0] in ("post", "hashtag") and len(argv_positional) < 3: print(usage()) return 1 if args['logout']: if not os.path.exists(InstaLooter.COOKIE_FILE): hues.error('Cookie file not found.') return 1 InstaLooter().logout() hues.success('Logged out.') return 0 elif args['login']: try: args['--username'] = six.moves.input('Username: '******'-W'] not in WARNING_ACTIONS: print("Unknown warning action: {}".format(args['-W'])) print(" available action: {}".format(', '.join(WARNING_ACTIONS))) return 1 if args['batch']: with open(args['<batch_file>']) as batch_file: batch_runner = BatchRunner(batch_file) batch_runner.runAll() return 0 with warnings.catch_warnings(): warnings.simplefilter(args['-W']) # if args['<hashtag>'] and not args['--credentials']: # warnings.warn("#hashtag downloading requires an Instagram account.") # return 1 if args['<post_token>'] is not None: args['--get-videos'] = True if args['--socks_port'] is not None: args['--socks_port'] = int(args['--socks_port']) if args['--control_port'] is not None: args['--control_port'] = int(args['--control_port']) if args['--change_ip_after'] is not None: args['--change_ip_after'] = int(args['--change_ip_after']) looter = InstaLooter( directory=os.path.expanduser( args.get('<directory>') or os.getcwd()), profile=args['<profile>'], hashtag=args['<hashtag>'], add_metadata=args['--add-metadata'], get_videos=args['--get-videos'], videos_only=args['--videos-only'], jobs=int(args['--jobs']), template=args['--template'], dump_json=args['--dump-json'], dump_only=args['--dump-only'], extended_dump=args['--extended-dump'], socks_port=args['--socks_port'], control_port=args['--control_port'], change_ip_after=args['--change_ip_after'], ) try: login(looter, args) if args['--time']: timeframe = get_times_from_cli(args['--time']) else: timeframe = None except ValueError as ve: console.error(ve) if args["--traceback"]: traceback.print_exc() return 1 try: post_token = args['<post_token>'] if post_token is None: media_count = int( args['--num-to-dl']) if args['--num-to-dl'] else None looter.download( media_count=media_count, with_pbar=not args['--quiet'], timeframe=timeframe, new_only=args['--new'], ) else: if 'insta' in post_token: post_token = looter._extract_code_from_url(post_token) looter.download_post(post_token) except Exception as e: console.error(e) if args["--traceback"]: traceback.print_exc() return 1 except KeyboardInterrupt: return 1 else: return 0
def main(argv=None): """Run from the command line interface. """ argv = argv or sys.argv[1:] try: args = docopt.docopt(__doc__, argv, version='instaLooter {}'.format(__version__)) except docopt.DocoptExit as de: print(de) return 1 argv_positional = [param for param in argv if not param.startswith("-")] if argv_positional[0] in ("post", "hashtag") and len(argv_positional) < 3: print(usage()) return 1 if args['-W'] not in WARNING_ACTIONS: print("Unknown warning action: {}".format(args['-W'])) print(" available action: {}".format(', '.join(WARNING_ACTIONS))) return 1 with warnings.catch_warnings(): warnings.simplefilter(args['-W']) # if args['<hashtag>'] and not args['--credentials']: # warnings.warn("#hashtag downloading requires an Instagram account.") # return 1 if args['<post_token>'] is not None: args['--get-videos'] = True looter = InstaLooter(directory=os.path.expanduser( args.get('<directory>') or os.getcwd()), profile=args['<profile>'], hashtag=args['<hashtag>'], add_metadata=args['--add-metadata'], get_videos=args['--get-videos'], videos_only=args['--videos-only'], jobs=int(args['--jobs']), template=args['--template']) try: if args['--username']: username = args['--username'] if not looter.is_logged_in(): password = args['--password'] or getpass.getpass() looter.login(username, password) if not args['--quiet']: hues.success('Logged in.') elif not args['--quiet']: hues.success("Already logged in.") if args['--time']: timeframe = get_times_from_cli(args['--time']) else: timeframe = None except ValueError as ve: console.error(ve) if args["--traceback"]: traceback.print_exc() return 1 try: post_token = args['<post_token>'] if post_token is None: media_count = int( args['--num-to-dl']) if args['--num-to-dl'] else None looter.download( media_count=media_count, with_pbar=not args['--quiet'], timeframe=timeframe, new_only=args['--new'], ) else: if 'insta' in post_token: post_token = looter._extract_code_from_url(post_token) looter.download_post(post_token) except Exception as e: console.error(e) if args["--traceback"]: traceback.print_exc() looter.__del__() return 1 except KeyboardInterrupt: looter.__del__() return 1 else: return 0
def logs(aims, conditions, wants, res, yesorno, others=""): """ 0 失败 1 成功 2 警告 """ #################################### 命令行即时输出 if yesorno == 0: yesornostr = u"测试点验证未通过, 请查阅具体记录" + others colorstr = "\033[1;31;40m" #红色 if yesorno == 1: yesornostr = u"测试点验证通过" + others colorstr = "\033[1;32;40m" #绿色 if yesorno == 2: yesornostr = u"警告, 请查阅具体记录" + others colorstr = "\033[1;33;40m" #橙黄色 closecolor = "\033[0m" ##### 非LINUX不支持以上模式的彩色日志输出 if platform.system() != "Linux": colorstr = "" closecolor = "" ###### print("---------------------------------------------------------") print(u"动作名称/目的: " + aims + " " + u"前置条件/判断类型:" + " " + conditions) outputlog = u"预期: " + wants + " " + u"实际结果:" + " " + res + " " + u"\n判定: " + yesornostr #print(colorstr + outputlog + closecolor ) ## 这种模式不兼容 windows , 因此暂时停止使用 ### 暂时使用以下模式 #hues.log hues.info hues.error hues.warn hues.success if yesorno == 0: hues.error(outputlog) if yesorno == 1: hues.success(outputlog) if yesorno == 2: hues.warn(outputlog) ################################################## 报告输出 #### 获得是否报告的标记位 reports = get_reports_tag() ##### 报告标记位正常 if reports != 0: doc = documents.doc doc.insert_text("\n") # 插入表格 doc.insert_text(u"★ 用例及记录 " + str(documents.ids) + u" 判定") ###### 颜色定义 gray = 0xcdc9c9 #灰色 green = 0x228b22 #绿色 if platform.system() == "Linux": red = 0xff4500 #红色 yellow = 0xffd700 #黄色 if platform.system() == "Windows": red = 0x0045ff #红色 yellow = 0x00d7ff #黄色 ###### 结论 表格 在最上方 mytable0 = doc.insert_table(3, 1) doc.table_setattr(mytable0, "A1", "BackColor", gray) doc.insert_tabletext(mytable0, "A1", u"自动化判定结果") # 时间 times = time.strftime('%Y-%m-%d %X', time.localtime()) doc.insert_tabletext(mytable0, "A2", times) if yesorno == 0: ### 错误时的突出显示 doc.table_setattr(mytable0, "A3", "BackColor", red) # 红色 if yesorno == 1: doc.table_setattr(mytable0, "A3", "BackColor", green) # 绿色 if yesorno == 2: doc.table_setattr(mytable0, "A3", "BackColor", yellow) # 黄色 doc.insert_tabletext(mytable0, "A3", yesornostr) ##### 前提 表格 mytable1 = doc.insert_table(2, 2) doc.table_setattr(mytable1, "A1", "BackColor", gray) doc.table_setattr(mytable1, "B1", "BackColor", gray) doc.insert_tabletext(mytable1, "A1", u"动作名称/目的") doc.insert_tabletext(mytable1, "B1", u"前置条件/判断类型") doc.insert_tabletext(mytable1, "A2", aims) doc.insert_tabletext(mytable1, "B2", conditions) ##### 预期和返回 表格 mytable2 = doc.insert_table(2, 2) doc.table_setattr(mytable2, "A1", "BackColor", gray) doc.table_setattr(mytable2, "B1", "BackColor", gray) doc.insert_tabletext(mytable2, "A1", u"自动化用例预期") doc.insert_tabletext(mytable2, "B1", u"自动化获取结果") doc.insert_tabletext(mytable2, "A2", wants) doc.insert_tabletext(mytable2, "B2", res) ### 用例号 documents.ids = documents.ids + 1 ############# 最后: 错误即抛出异常,以便捕获 if yesorno == 0: raise ValueError('测试用例识别到错误')
test_vk = 333 test_discord = 'kek' test_twitch = 'lol' sess = session() sess.headers = {'XXX-CODE': '##CODE##'} def exec_error(method: str, response: str, status_code: int): hues.error(f'Method: {method}\nResponse: {response}\nStatus Code: {status_code}') exit(-1) # Root r = sess.get(host + '/api/') if r.status_code == 200: hues.success('/api/') else: exec_error('/api/', r.text, r.status_code) # Invoke email r = sess.post(host + '/api/user/invoke_email', json={ 'email': test_email }) if r.status_code == 200: hues.success('/api/user/invoke_email') else: exec_error('/api/user/invoke_email', r.text, r.status_code) # Accept email r = sess.post(host + '/api/user/accept_email', json={ 'email': test_email,
def routine(manual=True) -> None: Methods.console_clear() vk = VkAPI() _settings = None if os.path.exists('./settings.json'): with open('./settings.json') as f: try: _settings = json.loads(f.read()) except Exception: hues.error('Bad settings') os.remove('./settings.json') os._exit(-1) hues.success('Settings loaded.') from source.static.StaticData import StaticData if not Settings.settings_get(): Settings.settings_save(StaticData.defaultSettings) _settings = Settings.settings_get() if manual: if not _settings.get('safe_zone'): hues.warn('No users in safe zone.\nContinue? (y/n)') _choice = input('> ').lower() while _choice != 'y' and _choice != 'n': hues.warn('No users in safe zone.\nContinue? (y/n)') _choice = input('> ').lower() if _choice == 'n': Methods.console_clear() return _ban_list = [] from copy import copy from source.static.StaticMethods import StaticMethods _friends = vk.friends_get() _friends['items'] += vk.get_out_requests()['items'] if _settings.get('safe_zone'): for _friend in _friends['items']: if str(_friend) not in _settings['safe_zone']: _ban_list.append(_friend) _ban_list = list([str(x) for x in _ban_list]) else: _ban_list = list([str(x) for x in _friends['items']]) if _settings['newsfeedBan']: if manual: hues.warn( f'{len(_ban_list)} your friends (and out requests) will be affected.\nContinue? (y/n)' ) _choice = input('> ').lower() while _choice != 'y' and _choice != 'n': _choice = input('> ').lower() if _choice == 'n': Methods.console_clear() return __init_count = len(_ban_list) _temp = copy(_ban_list) while len(_temp) > 0: if manual: hues.log( f'[Newsfeed] Progress: {StaticMethods.get_percentage(abs(__init_count - len(_temp)), __init_count)}' ) vk.add_newsfeed_ban(_temp[:100]) del (_temp[:100]) sleep(0.4) if _settings['messagesBan']: pass if _settings['storiesBan']: _temp = copy(_ban_list) __init_count = len(_temp) while len(_temp) > 0: if manual: hues.log( f'[Stories] Progress: {StaticMethods.get_percentage(abs(__init_count - len(_temp)), __init_count)}' ) vk.stories_ban(_temp[:100]) del (_temp[:100]) sleep(0.4) if manual: Methods.console_clear() hues.success('Work done!')
print "Number of images for " + q + ': ' + str(len(os.listdir( dir))) + " -- Remaining: " + str(remaining_num_2_download) if remaining_num_2_download < 1: continue looter = InstaLooter(directory=dir, hashtag=q, add_metadata=False, get_videos=get_videos, jobs=jobs) try: looter.login(login, password) hues.success('Logged in.') except: print "Error while loggining" if login == login1: login = login2 password = password2 else: login = login1 password = password1 time.sleep(60) continue try: looter.download(media_count=num_2_query, new_only=new_only,
class Solution(object): def copyRandomList(self, head): """ :type head: RandomListNode :rtype: RandomListNode """ ''' import hues hues.log('Mission', 42) hues.info('Finding', 42) hues.error(41, 'is not', 42) hues.warn('We are distracted...') hues.info('Found', 24) hues.success('Close enough') class LinkListRandom: def __init__(self, x): self.label = x self.next = None self.random = None #插入一个节点 def insert(self, head, val): node = LinkListRandom(val) if head == None: return node else: tmp = head
def get_info(self): cities = [] schools = [] univers = [] counter = 0 users = self.get_friends() hues.success() for user in users: user_info = self.session.method('users.get', { 'user_ids': user, 'fields': 'city,schools,education' }) time.sleep(0.4) counter += 1 hues.log('Users handled {} ({}/{})'.format( StaticMethods.get_percentage(counter, len(users)), str(counter), str(len(users)))) try: cities.append(user_info[0].get('city').get('title')).replace( ',', '') except: pass try: schools.append( user_info[0].get('schools')[-1].get('name')).replace( ',', '') except: pass try: univer = user_info[0].get('university_name').replace(',', '') if univer: univers.append(univer) except: pass data = [Counter(cities), Counter(schools), Counter(univers)] top_cities = [None] * 3 for i in range(len(data)): if len(data[0]) > 2: top_cities[0] = str( sorted(dict(data[i]).items(), key=operator.itemgetter(1))[-1]).replace( '(', '').replace(')', '').split(',') top_cities[1] = str( sorted(dict(data[i]).items(), key=operator.itemgetter(1))[-2]).replace( '(', '').replace(')', '').split(',') top_cities[2] = str( sorted(dict(data[i]).items(), key=operator.itemgetter(1))[-3]).replace( '(', '').replace(')', '').split(',') elif len(data[0]) > 1: top_cities[0] = str( sorted(dict(data[i]).items(), key=operator.itemgetter(1))[-1]).replace( '(', '').replace(')', '').split(',') top_cities[1] = str( sorted(dict(data[i]).items(), key=operator.itemgetter(1))[-2]).replace( '(', '').replace(')', '').split(',') elif len(data[0]) == 1: top_cities[0] = str( sorted(dict(data[i]).items(), key=operator.itemgetter(1))[-1]).replace( '(', '').replace(')', '').split(',') else: top_cities = 'Not found' print('\n\n\n') try: if i == 0: out = 'City:\n{}\n{}\n{}'.format( '{}: {} ({}/{})'.format( top_cities[0][0].replace('\'', ''), StaticMethods.get_percentage( top_cities[0][1], str(len(cities)), 3), top_cities[0][1].strip(), str(len(cities)), 3), '{}: {} ({}/{})'.format( top_cities[1][0].replace('\'', ''), StaticMethods.get_percentage( top_cities[1][1], str(len(cities)), 3), top_cities[1][1].strip(), str(len(cities))), '{}: {} ({}/{})'.format( top_cities[2][0].replace('\'', ''), StaticMethods.get_percentage( top_cities[2][1], str(len(cities)), 3), top_cities[2][1].strip(), str(len(cities)))) print(out) self.save(out) elif i == 1: out = '\n\nSchool:\n{}\n{}\n{}'.format( '{}: {} ({}/{})'.format( top_cities[0][0].replace('\'', ''), StaticMethods.get_percentage( top_cities[0][1], str(len(cities)), 3), top_cities[0][1].strip(), str(len(cities))), '{}: {} ({}/{})'.format( top_cities[1][0].replace('\'', ''), StaticMethods.get_percentage( top_cities[1][1], str(len(cities)), 3), top_cities[1][1].strip(), str(len(cities))), '{}: {} ({}/{})'.format( top_cities[2][0].replace('\'', ''), StaticMethods.get_percentage( top_cities[2][1], str(len(cities)), 3), top_cities[2][1].strip(), str(len(cities)))) print(out) self.save(out) elif i == 2: out = '\n\nUniversity:\n{}\n{}\n{}'.format( '{}: {} ({}/{})'.format( top_cities[0][0].replace('\'', ''), StaticMethods.get_percentage( top_cities[0][1], str(len(cities)), 3), top_cities[0][1].strip(), str(len(cities))), '{}: {} ({}/{})'.format( top_cities[1][0].replace('\'', ''), StaticMethods.get_percentage( top_cities[1][1], str(len(cities)), 3), top_cities[1][1].strip(), str(len(cities))), '{}: {} ({}/{})'.format( top_cities[2][0].replace('\'', ''), StaticMethods.get_percentage( top_cities[2][1], str(len(cities)), 3), top_cities[2][1].strip(), str(len(cities)))) print(out) self.save(out) print('\n') except: pass
def destroy_planet(planet): if planet == 'Earth': raise ThisPlanetIsProtected return random.randint(0, 100) < 42 if __name__ == '__main__': hues.info('Destroying the planets. Please wait.') for planet in ( 'Murcury', 'Venus', 'Earth', 'Mars', 'Uranus', ): try: success = destroy_planet(planet) except ThisPlanetIsProtected: hues.warn('The Doctor saved', planet) else: if success: hues.success('Destroyed', planet) else: hues.error('Could not destroy', planet) time.sleep(.5) hues.info('So long, and thanks for all the fish.')