def set_setting(self, device, setting, val): """ Sets the desired setting for the desired device to the specified value. This will also update the local properties dictionary, thus this is the only way settings are allowed to be updated. Keyword Arguments: device -- the actuator number to send the command to setting -- The setting to return. Must be one from the self._SETTINGS list. val -- The specified value to set the actuator(s) to. """ if setting in self._SETTINGS: byte_array = _convert_int_to_bytes(val) self.__issue_command(device, self._SETTINGS[setting], byte_array[0], byte_array[1], byte_array[2], byte_array[3]) if setting not in self.__properties: self.__properties[setting] = {} if device == 0: for i in range(self.__num_devices): self.__properties[setting][i] = val else: self.__properties[setting][device] = val else: log.log_error("The specified setting '{0}' is not currently " \ "supported".format(setting))
def setup(): """ Gathers all configs """ global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR LOG_FILENAME = 'musicrepair_log.txt' LOG_LINE_SEPERATOR = '........................\n' CONFIG = configparser.ConfigParser() config_path = realpath(__file__).replace(basename(__file__), '') config_path = config_path + 'config.ini' CONFIG.read(config_path) BING_KEY = CONFIG['keys']['bing_key'] GENIUS_KEY = CONFIG['keys']['genius_key'] if BING_KEY == '<insert bing key here>': log.log_error( 'Warning, you are missing the Bing key. Add it using --config') if GENIUS_KEY == '<insert genius key here>': log.log_error( 'Warning, you are missing the Genius key. Add it using --config')
def get_details_letssingit(song_name): """ Gets the song details if song details not found through spotify """ song_name = improvename.songname(song_name) letssingit_search_url = 'http://search.letssingit.com/cgi-exe/am.cgi' \ '?a=search&artist_id=&l=archive&s=' url = "{}{}".format(letssingit_search_url, quote(song_name.encode('utf-8'))) html = urlopen(url).read() soup = BeautifulSoup(html, 'html.parser') link = soup.find('a', {'class': 'high_profile'}) try: link = link.get('href') link = urlopen(link).read() soup = BeautifulSoup(link, 'html.parser') album_div = soup.find('div', {'id': 'albums'}) title_div = soup.find('div', {'id': 'content_artist'}).find('h1') try: lyrics = soup.find('div', {'id': 'lyrics'}).text lyrics = lyrics[3:] except AttributeError: lyrics = '' log.log_error('* Couldn\'t find lyrics', indented=True) try: song_title = title_div.contents[0] song_title = song_title[1:-8] except AttributeError: log.log_error('* Couldn\'t reset song title', indented=True) song_title = song_name try: artist = title_div.contents[1].getText() except AttributeError: log.log_error('* Couldn\'t find artist name', indented=True) artist = 'Unknown' try: album = album_div.find('a').contents[0] album = album[:-7] except AttributeError: log.log_error('* Couldn\'t find the album name', indented=True) album = artist except AttributeError: log.log_error('* Couldn\'t find song details', indented=True) album = song_name song_title = song_name artist = 'Unknown' lyrics = '' match_bool, score = matching_details(song_name, song_title, artist) return artist, album, song_title, lyrics, match_bool, score
def _parse_payload_config(payload_name: str) -> dict: result = { "payload_name": payload_name, "service": "0", "params": config.AVAILABLE_PARAMS_FOR_PAYLOADS } try: _uuid = utils.uuid.get_uuid() exec(f"import payloads.{payload_name} as {_uuid}") try: service = eval(f"{_uuid}.SERVICE") if type(service) != str: log.log_warn(f"Service is not a string for payload {payload_name}, using default") else: result["service"] = service except AttributeError: log.log_info(f"Using default SERVICE value for payload {payload_name}") try: params = eval(f"{_uuid}.PARAMS") if type(params) != list: log.log_warn(f"Params is not a list for payload {payload_name}, using default") else: result["params"] = params except AttributeError: log.log_info(f"Using default SERVICE value for payload {payload_name}") except ModuleNotFoundError: log.log_error(f"Cannot import file {payload_name}") return result
def CompatibilityCheck(): try: r = redis.Redis() if not r.pipeline: raise RuntimeError('pipeline call not found') p = r.pipeline() if not p.exists: raise RuntimeError('exists call not found') if not p.get: raise RuntimeError('get call not found') if not p.set: raise RuntimeError('set call not found') if not p.hexists: raise RuntimeError('hexists call not found') if not p.hget: raise RuntimeError('hget call not found') if not p.hgetall: raise RuntimeError('hgetall call not found') if not p.hset: raise RuntimeError('hset call not found') if not p.hincrby: raise RuntimeError('hincrby call not found') if not p.hdel: raise RuntimeError('hdel call not found') if not p.incrby: raise RuntimeError('incrby call not found') if not p.sadd: raise RuntimeError('sadd call not found') if not p.smembers: raise RuntimeError('smembers call not found') if not p.sismember: raise RuntimeError('sismember call not found') if not p.rpush: raise RuntimeError('rpush call not found') if not p.lpop: raise RuntimeError('lpop call not found') if not p.llen: raise RuntimeError('llen call not found') if not p.lindex: raise RuntimeError('lindex call not found') if not p.lset: raise RuntimeError('lset call not found') if not p.zincrby: raise RuntimeError('zincrby call not found') if not p.zscore: raise RuntimeError('zscore call not found') if not p.zrangebylex: raise RuntimeError('zrangebylex call not found') if not p.keys: raise RuntimeError('keys call not found') if not p.execute: raise RuntimeError('execute call not found') if not p.delete: raise RuntimeError('delete call not found') except Exception,e: log_error('Error checking redis compatibility: %s' % str(e)) exit(1)
def unhandled_exception(e): log.log_error('Unhandled Exception: %s' % (e)) import sys import traceback msg = ''.join(traceback.format_tb(e.__traceback__)) log.log_error(msg) return render_template('error.htm', msg="unknown"), 500
def __enter_movement_instruction(self, button): """ Sends movement instruction to facade Keyword arguments: button -- object the action occured on """ direction_conversion = {0: (-1, 0, 0), 1: (1, 0, 0), 2: (0, 1, 0), 3: (0, -1, 0), 4: (0, 0, 1), 5: (0, 0, -1)} direction = direction_conversion[self.__builder.get_object( "manual_control_instruction_combobox").get_active()] magnitude = self.__builder.get_object( "manual_control_entry").get_text() if magnitude.isdigit(): magnitude = int(magnitude) facade.move(list(magnitude * x for x in direction), self.__x_axis_inverted, self.__y_axis_inverted) else: log.log_error("The magnitude of a movement must be an integer, " \ "'{0}' is not an integer.".format(magnitude))
def get_details_spotify(song_name): ''' Tries finding metadata through Spotify ''' song_name = improvename.songname(song_name) spotify = spotipy.Spotify() results = spotify.search(song_name, limit=1) # Find top result log.log_indented('* Finding metadata from Spotify.') try: album = (results['tracks']['items'][0]['album'] ['name']) # Parse json dictionary artist = (results['tracks']['items'][0]['album']['artists'][0]['name']) song_title = (results['tracks']['items'][0]['name']) try: log_indented("* Finding lyrics from Genius.com") lyrics = get_lyrics_genius(song_title) except: log_error("* Could not find lyrics from Genius.com, trying something else") lyrics = get_lyrics_letssingit(song_title) match_bool, score = matching_details(song_name, song_title, artist) if match_bool: return artist, album, song_title, lyrics, match_bool, score else: return None except IndexError: log.log_error( '* Could not find metadata from spotify, trying something else.', indented=True) return None
def add_albumart(albumart, song_title): ''' Adds the album art to the song ''' try: img = urlopen(albumart) # Gets album art from url except Exception: log.log_error("* Could not add album art", indented=True) return None audio = EasyMP3(song_title, ID3=ID3) try: audio.add_tags() except _util.error: pass audio.tags.add( APIC( encoding=3, # UTF-8 mime='image/png', type=3, # 3 is for album art desc='Cover', data=img.read() # Reads and adds album art )) audio.save() log.log("> Added album art")
def prompt(youtube_list): ''' Prompts for song number from list of songs ''' option = int(input('\nEnter song number > ')) try: song_url = list(youtube_list.values())[option - 1] song_title = list(youtube_list.keys())[option - 1] except IndexError: log.log_error('Invalid Input') exit() system('clear') print('Download Song: ') print(song_title) print('Y/n?') confirm = input('>') if confirm == '' or confirm.lower() == 'y': pass elif confirm.lower() == 'n': exit() else: log.log_error('Invalid Input') exit() return song_url, song_title
def send_move_request(self, direction): try: self._conn.request("ON", self._solenoid_number[direction]) response = self._conn.getresponse() log.log_info(response.read()) except socket_error as serr: log.log_error("Failed communication with HTTP server.")
def callback(self, ctxt, progress, total): try: if self.func is not None: return self.func(progress, total) return True except: log.log_error(traceback.format_exc())
def add_albumart(albumart, song_title): ''' Adds the album art to the song ''' try: img = urlopen(albumart) # Gets album art from url except Exception: log.log_error("* Could not add album art", indented=True) return None audio = EasyMP3(song_title, ID3=ID3) try: audio.add_tags() except _util.error: pass audio.tags.add( APIC( encoding=3, # UTF-8 mime='image/png', type=3, # 3 is for album art desc='Cover', data=img.read() # Reads and adds album art ) ) audio.save() log.log("> Added album art")
def sync_by_api(): total = 0 for table in config.tables: log_msg = "start processing table:" + table log.log_success(log_msg) conf_table = config.tables[table] get_url = conf_table['get_url'] # get compare flag cmp_field = conf_table[ 'cmp_field'] if 'cmp_field' in conf_table else None cmp_arg = conf_table['cmp_arg'] if 'cmp_arg' in conf_table else None cmp_field_second = conf_table[ 'cmp_field_second'] if 'cmp_field_second' in conf_table else None cmp_arg_second = conf_table[ 'cmp_arg_second'] if 'cmp_arg_second' in conf_table else None # get last data from webservice if cmp_field_second: last_data, last_data_second = req.get_last_flag( get_url, cmp_arg, cmp_arg_second) elif cmp_field: last_data = req.get_last_flag(get_url, cmp_arg) last_data_second = None else: last_data_second, last_data = None, None while True: try: # get newer data from mysql data = db.get_next_newer_data( table, cmp_field=cmp_field, cmp_value=last_data, num=config.cache_size, cmp_field_second=cmp_field_second, cmp_value_second=last_data_second) if not data: break except Exception as e: log.log_error("get_next_newer_data:" + str(e)) break # mapping filed and argument table_map = conf_table['map'] post_data_list, count = map_dict(data, table_map, conf_table['strict'], conf_table['lower']) try: req.post_data(conf_table['post_url'], post_data_list) except Exception as e: log.log_error("unknow error:" + str(e)) finally: total += count post_data_list.clear() log_msg = "processed table:%s __callback, total:%d success:%s" % ( table, total, req.success_count) log.log_success(log_msg) req.success_count = 0 db.reset_cursor()
def playing_idol_on_event_playing_actor_enter(message_type, channel, channel_type, serialize): # 获取事件交互代理 communicator_proxy = variable_table.get_variable( ccvariable.ttypes.Variable.COMMUNICATOR_PROXY) # 获取请求代理 request_proxy = variable_table.get_variable( ccvariable.ttypes.Variable.REQUEST_PROXY) # 事件消息 message = ccevent.playing.ttypes.EventPlayingActorEnter() # 反序列化 TSerialization.deserialize(message, serialize) # 关注玩家杀死NPC事件、角色被杀死事件 communicator_proxy.follow(ccevent.ttypes.EventType.EVENT_ACTOR_KILL_NPC, \ message.actor_, ccevent.ttypes.ChannelType.CHANNEL_ACTOR, \ "playing_idol_on_event_actor_kill_npc") communicator_proxy.follow(ccevent.ttypes.EventType.EVENT_ROLE_KILLED, \ message.actor_, ccevent.ttypes.ChannelType.CHANNEL_ACTOR, \ "playing_idol_on_event_actor_killed") communicator_proxy.follow(ccevent.ttypes.EventType.EVENT_PLAYING_ACTOR_REQUEST_COMPLETE,\ message.actor_, ccevent.ttypes.ChannelType.CHANNEL_ACTOR,\ "playing_idol_on_event_playing_actor_request_complete") # 获取副本对象 playing = idol_types.PlayingManager.get(message.playing_) if playing == None: log.log_error("idol副本 获取 playing(%d) 失败" % message.playing_) return None now = time.time() # 获取玩家对象 actor = playing.get_actor(message.actor_) if actor == None: # 玩家不存在时,创建并加入副本管理器中 actor = idol_types.Actor(message.actor_, now) playing.add_actor(actor) # 副本管理器中加入一个玩家ID到副本ID的对应关系 idol_types.PlayingManager.add_actor(message.actor_, message.playing_) # 请求初始化玩家 request = ccrequest.playing.ttypes.RequestPlayingInitializeActor() request.actor_ = message.actor_ request.spend_time_ = now - actor.get_start_time() request.scores_ = [] request.datas_ = [] # 序列化消息 request_data = TSerialization.serialize(request) # 发送请求 request_proxy.request(ccrequest.ttypes.RequestType.REQUEST_PLAYING_INITIALIZE_ACTOR, \ request_data, len(request_data)) log.log_debug("玩家(%d) 进入 idol副本(id=%d,template=%d)" % \ (message.actor_, message.playing_, message.template_))
def SendJSONRPCCommand(host, port, method, params): try: http = httplib.HTTPConnection(host, port, timeout=20) except Exception, e: log_error('SendJSONRPCCommand: Error connecting to %s:%u: %s' % (host, port, str(e))) raise
def switch_actuator_axis(self): """ Toggles which device is responsible for x and y axis movement """ if self.__actuators: self.__actuators.switch_actuator_axis() else: log.log_error("Actuator have not been initialized" \ " with a com-port properly.")
def run_server(options): try: with execute_server(options) as server: while True: server.handle_request() except Exception as e: log_error("Unable to run server", exc_info=e)
def add_award(actor, template, score): log.log_debug("plot.add_award(%d, %d, %d)" % (actor, template, score)) playing_config = plot_types.Config.get(template) if playing_config == None: log.log_error("找不到日常副本配置(%d)" % template) return None request = ccrequest.playing.ttypes.RequestPlayingAddAward() request.actor_ = actor request.playing_template_ = template award_field = ccentity.playing.ttypes.PlayingAwardField() award_field.type_ = ccentity.resource.ttypes.ResourceType.RESOURCE request.awards_ = [] # 奖励 award_field.type_ = ccentity.resource.ttypes.ResourceType.ITEM for i in playing_config.get_awards(): request.awards_.append(i) # 抽奖奖励 draw_items = playing_config.get_draw_items() draw_items_size = len(draw_items) if draw_items_size > 0: request.draw_award_ = ccentity.playing.ttypes.PlayingAwardField( ccentity.resource.ttypes.ResourceType.ITEM, draw_items[random.randint(0, draw_items_size - 1)], 1 ) if proxy.Request.request(ccrequest.ttypes.RequestType.REQUEST_PLAYING_ADD_AWARD, request) == False: proxy.Logging.error("发送请求 REQUEST_PLAYING_ADD_AWARD 出错") return None proxy.Logging.debug("增加奖励(玩家=%d) 成功" % actor)
def create_trigger_all(self): sql = ''' DROP TABLE trigger_log; CREATE TABLE trigger_log( id int PRIMARY KEY auto_increment, table_name varchar(64), op varchar(8), detail text );''' try: self._db_cursor.execute(sql) except Exception as e: log.log_error(str(e)) for table in config.tables: conf_table = config.tables[table] unique_field = None event_type = conf_table['trigger'][ 'event_type'] if 'trigger' in conf_table else None if not event_type: event_type = ("insert", "update", "delete") if 'unique_field' in conf_table[ 'trigger'] or not conf_table['trigger']['unique_field']: unique_field = conf_table['trigger']['unique_field'] fields = unique_field if unique_field else self.get_table_fields( table) print("field: ", fields) for e in event_type: log.log_success("create trigger for table: " + table + " event:" + e) self.create_trigger(table, e, fields) self.close()
def write(self, data): global _output_to_log interpreter = None if "value" in dir(PythonScriptingInstance._interpreter): interpreter = PythonScriptingInstance._interpreter.value if interpreter is None: if _output_to_log: self.buffer += data while True: i = self.buffer.find('\n') if i == -1: break line = self.buffer[:i] self.buffer = self.buffer[i + 1:] if self.is_error: log.log_error(line) else: log.log_info(line) else: self.orig.write(data) else: PythonScriptingInstance._interpreter.value = None try: if self.is_error: interpreter.instance.error(data) else: interpreter.instance.output(data) finally: PythonScriptingInstance._interpreter.value = interpreter
def serial_read(self, hex_or_ascii): try: if self.is_connected: data = self.serial_port.read_all() if len(data) > 0: if hex_or_ascii == False: #HEX data_hex = ', '.join(hex(d) for d in data) log.log_data(self.gui, '\tRX: [%s]\n' % data_hex) else: #ASCII data_ascii = [] for d in data: if d < 128: data_ascii.append(chr(d)) else: data_ascii.append(str(d)) data_ascii = ', '.join(data_ascii) log.log_data(self.gui, "\tRX (ASCII): [%s]\n" % data_ascii) except Exception as e: log.log_error(self.gui, "!!! !!! !!! SERIAL READ ERROR:") log.log_error(self.gui, "%s" % str(e)) self.gui.ui.statusbar.showMessage('!!! SERIAL READ ERROR!') self.serial_flush_output() self.serial_port_close() return (ERROR, 0)
def playing_idol_on_event_playing_create(message_type, channel, channel_type, serialize): # 获取事件交互代理 communicator_proxy = variable_table.get_variable(ccvariable.ttypes.Variable.COMMUNICATOR_PROXY) # 事件消息 message = ccevent.playing.ttypes.EventPlayingCreate() # 反序列化 TSerialization.deserialize(message, serialize) # 关注玩家进入/退出副本事件 communicator_proxy.follow(ccevent.ttypes.EventType.EVENT_PLAYING_ACTOR_ENTER, \ message.template_, ccevent.ttypes.ChannelType.CHANNEL_PLAYING, \ "playing_idol_on_event_playing_actor_enter") communicator_proxy.follow(ccevent.ttypes.EventType.EVENT_PLAYING_ACTOR_LEAVE, \ message.template_, ccevent.ttypes.ChannelType.CHANNEL_PLAYING, \ "playing_idol_on_event_playing_actor_leave") # 创建副本对象并加入管理器中 playing = idol_types.Playing(message.playing_, message.template_, message.scene_) idol_types.PlayingManager.add(playing) # 获取副本配置 playing_config = idol_types.Config.get(message.template_) if playing_config == None: log.log_error("获取 副本配置失败(%d)" % message.template_) return None # 召唤一个BOSS facade_request.summon_npc(message.scene_, playing_config.get_pass_kill_npc(),\ playing_config.get_pass_npc_x(), playing_config.get_pass_npc_y()); log.log_debug("idol副本(id=%d,template=%d) 创建成功" % (message.playing_, message.template_))
def serve_forever(): listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #listen_socket = ssl.wrap_socket(listen_socket, certfile=cfg.parameters["certfile"], keyfile=cfg.parameters["keyfile"],server_side=True, ssl_version=ssl.PROTOCOL_TLSv1_2) ssl_socket = ssl.wrap_socket(listen_socket, certfile=cfg.parameters["certfile"], keyfile=cfg.parameters["keyfile"], server_side=True) ssl_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ssl_socket.bind(SERVER_ADDRESS) ssl_socket.listen(REQUEST_QUEUE_SIZE) executor = ThreadPoolExecutor(max_workers=50) log.log_info('MASTER Serving HTTPS on port {port} ...'.format(port=PORT)) while True: #client_connection, client_address = listen_socket.accept() try: client_connection, client_address = ssl_socket.accept() #log.log_info("client_user_address: " + str( client_address) ) #traffic.track(client_address[0], True) a = executor.submit(handle_request, client_connection, str(client_address[0]), client_address[1]) except: print("Unexpected error:", sys.exc_info()[0]) log.log_error("Error in try-catch of main server loop: " + str(sys.exc_info()[0])) if "KeyboardInterrupt" in str(sys.exc_info()[0]): exit()
def add_albumart(query, song_title): """ Adds the album art to a song by editing ID3 tags using Mutagen """ try: log.log_indented('* Trying to extract album art from Google.com') albumart = albumsearch.img_search_google(query) except: log.log_error('* Could not extract from Google, trying Bing') albumart = albumsearch.img_search_bing(query) try: img = urlopen(albumart) # Gets album art from url except Exception: log.log_error("* Could not add album art", indented=True) return None audio = EasyMP3(song_title, ID3=ID3) try: audio.add_tags() except _util.error: pass audio.tags.add( APIC( encoding=3, # UTF-8 mime='image/png', type=3, # 3 is for album art desc='Cover', data=img.read())) audio.save() log.log("> Added album art")
def CompatibilityCheck(): try: r = redis.Redis() if not r.pipeline: raise RuntimeError('pipeline call not found') p = r.pipeline() if not p.exists: raise RuntimeError('exists call not found') if not p.get: raise RuntimeError('get call not found') if not p.set: raise RuntimeError('set call not found') if not p.hexists: raise RuntimeError('hexists call not found') if not p.hget: raise RuntimeError('hget call not found') if not p.hgetall: raise RuntimeError('hgetall call not found') if not p.hset: raise RuntimeError('hset call not found') if not p.hincrby: raise RuntimeError('hincrby call not found') if not p.hdel: raise RuntimeError('hdel call not found') if not p.incrby: raise RuntimeError('incrby call not found') if not p.sadd: raise RuntimeError('sadd call not found') if not p.smembers: raise RuntimeError('smembers call not found') if not p.sismember: raise RuntimeError('sismember call not found') if not p.rpush: raise RuntimeError('rpush call not found') if not p.lpop: raise RuntimeError('lpop call not found') if not p.llen: raise RuntimeError('llen call not found') if not p.lindex: raise RuntimeError('lindex call not found') if not p.lset: raise RuntimeError('lset call not found') if not p.zincrby: raise RuntimeError('zincrby call not found') if not p.zscore: raise RuntimeError('zscore call not found') if not p.zrangebylex: raise RuntimeError('zrangebylex call not found') if not p.keys: raise RuntimeError('keys call not found') if not p.execute: raise RuntimeError('execute call not found') if not p.delete: raise RuntimeError('delete call not found') except Exception, e: log_error('Error checking redis compatibility: %s' % str(e)) exit(1)
def prompt(youtube_list): """ Prompts for song number from list of songs """ option = 0 while not option: try: option = int(input('\nEnter song number > ')) except ValueError: print('Value entered not a number. Try again.') try: song_url = list(youtube_list.values())[option - 1] song_title = list(youtube_list.keys())[option - 1] except IndexError: log.log_error('Invalid Input') exit() system(clear) print('Download Song: ') print(song_title) print('Y/N?') confirm = input('> ') if not confirm or confirm.lower() == 'y': pass elif confirm.lower() == 'n': exit() else: log.log_error('Invalid Input') exit() return song_url, song_title
def get_news_list(param): ob_url = param[1] page = param[0] doc = pq(page) try: trs = doc('div.border_tr td:eq(1) tr:eq(1) tr').items() # print(trs) news_list = [] for tr in trs: news = {} # 新闻日期 date = tr('td:eq(2)').text().replace('(', '').replace(')', '').strip() news['date'] = date # print(date) # 新闻url url = tr('td:eq(1) a').make_links_absolute( 'http://cmee.nuaa.edu.cn/').attr.href # print(url) news['url'] = url # 新闻标题 title = tr('td:eq(1) a').text() news['title'] = title news_list.append(news) if news_list: log.log_debug('fetch:解析列表成功' + str(news_list)) return news_list else: log.log_error('fetch:新闻列表为空' + ob_url + '网站规则可能发生变化') except: log.log_exception('fetch:解析列表错误' + ob_url + '网站规则可能发生变化')
def get_url(song_input, auto): """ Provides user with a list of songs to choose from returns the url of chosen song. """ youtube_list = OrderedDict() num = 0 # List of songs index html = requests.get('https://www.youtube.com/results', params={'search_query': song_input}) soup = BeautifulSoup(html.text, 'html.parser') # In all Youtube Search Results for i in soup.findAll('a', {'rel': YOUTUBECLASS}): song_url = 'https://www.youtube.com' + (i.get('href')) song_title = i.get('title') # Add title and song url to dictionary youtube_list.update({song_title: song_url}) if auto: print(song_title) return list(youtube_list.values())[0], list(youtube_list.keys())[0] num += 1 print("({0}) {1}".format(num, song_title)) # Prints list if not youtube_list: log.log_error('No match found on YouTube, try refining your search!') exit() # Gets and returns the demanded song url and title and url return prompt(youtube_list)
def UpdateCoin(daemon_host, daemon_port, wallet_host, wallet_port, full_history=False, paymentid=None, config_confirmations=6): txs = [] executed_txs = [] try: try: if full_history: scan_block_height = 0 else: scan_block_height = redis_get("scan_block_height") scan_block_height = long(scan_block_height) except Exception, e: log_error('Failed to get scan_block_height: %s' % str(e)) return None try: j = SendHTMLCommand(daemon_host, daemon_port, "getheight") except Exception, e: log_error('UpdateCoin: error getting height: %s' % str(e)) return None
def add_award(actor, template): log.log_debug("idol.add_award(%d, %d)" % (actor, template)) request_proxy = variable_table.get_variable(ccvariable.ttypes.Variable.REQUEST_PROXY) # 获取副本配置 playing_config = idol_types.Config.get(template) if playing_config == None: log.log_error("获取 副本配置失败(%d)" % template) return None # 请求增加副本奖励 request = ccrequest.playing.ttypes.RequestPlayingAddAward() request.actor_ = actor request.playing_template_ = template # 奖励 request.awards_ = playing_config.get_awards() # 抽奖 draw_awards = playing_config.get_draw_awards() draw_awards_size = len(draw_awards) if draw_awards_size > 0: request.draw_award_ = draw_awards[random.randint(0, draw_awards_size - 1)] else: request.draw_award_ = ccentity.playing.ttypes.PlayingAwardField(\ ccentity.resource.ttypes.ResourceType.MIN, 0, 0) # 序列化 request_data = TSerialization.serialize(request) # 发送请求 request_proxy.request(ccrequest.ttypes.RequestType.REQUEST_PLAYING_ADD_AWARD,\ request_data, len(request_data))
def _get_current_view(self, ctxt): try: view = self.get_current_view() except: log.log_error(traceback.format_exc()) view = "" return core.BNAllocString(view)
def navigate_maze(self, ir, sequence, inverted_x_axis, inverted_y_axis): if self.__actuators: self.__actuators.maze_navigate(ir, sequence, inverted_x_axis, inverted_y_axis) else: log.log_error("Actuators have not been initialized" \ " with a com-port properly.")
def add_award(actor, template): log.log_debug("idol.add_award(%d, %d)" % (actor, template)) request_proxy = variable_table.get_variable(ccvariable.ttypes.Variable.REQUEST_PROXY) # 获取副本配置 playing_config = idol_types.Config.get(template) if playing_config == None: log.log_error("获取 副本配置失败(%d)" % template) return None # 请求增加副本奖励 request = ccrequest.playing.ttypes.RequestPlayingAddAward() request.actor_ = actor request.playing_template_ = template # 奖励 request.awards_ = playing_config.get_awards() # 抽奖 draw_awards = playing_config.get_draw_awards() draw_awards_size = len(draw_awards) if draw_awards_size > 0: request.draw_award_ = draw_awards[random.randint(0, draw_awards_size - 1)] else: request.draw_award_ = ccentity.playing.ttypes.PlayingAwardField(ccentity.resource.ttypes.ResourceType.MIN, 0, 0) # 序列化 request_data = TSerialization.serialize(request) # 发送请求 request_proxy.request(ccrequest.ttypes.RequestType.REQUEST_PLAYING_ADD_AWARD, request_data, len(request_data))
def switch_actuator_axis(self): """ Toggles which device is responsible for x and y axis movement """ if self.__actuators: self.__actuators.switch_actuator_axis() else: log.log_error("Actuators have not been initialized" \ " with a com-port properly.")
def _address_action(cls, view, addr, action): try: file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view)) view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view)) action(view_obj, addr) except: log.log_error(traceback.format_exc())
def circle_path(self, inverted_x_axis, inverted_y_axis): if self.__actuators: self.__actuators.circle_path(inverted_x_axis, inverted_y_axis) else: log.log_error("Actuators have not been initialized" \ " with a com-port properly.")
def write(self, data): interpreter = None if hasattr(PythonScriptingInstance._interpreter, "value"): interpreter = PythonScriptingInstance._interpreter.value if interpreter is None: if log.is_output_redirected_to_log(): self.buffer += data while True: i = self.buffer.find('\n') if i == -1: break line = self.buffer[:i] self.buffer = self.buffer[i + 1:] if self.is_error: log.log_error(line) else: log.log_info(line) else: self.orig.write(data) else: PythonScriptingInstance._interpreter.value = None try: if self.is_error: interpreter.instance.error(data) else: interpreter.instance.output(data) finally: PythonScriptingInstance._interpreter.value = interpreter
def move_to_top_right(self, inverted_x_axis, inverted_y_axis): if self.__actuators: self.__actuators.move_to_top_right(inverted_x_axis, inverted_y_axis) else: log.log_error("Actuators have not been initialized" \ " with a com-port properly.")
def get_input(submission_id): '''从数据库获取input并写入data目录下对应的文件''' sql= 'SELECT input FROM ' + config.db_table_name + ' WHERE submission_id = ' + str(submission_id) + ';' data = db.run_sql(sql) input_data = data[0][0] file_name = str(submission_id) + '.in' try: data_path = os.path.join(config.data_dir, str(submission_id)) secure.low_level() os.mkdir(data_path) except OSError as e: if str(e).find('exist') > 0: # 文件夹已经存在 pass else: return False try: real_path = os.path.join(config.data_dir, str(submission_id), file_name) except KeyError as e: return False try: log.log_info('Importing input, %d' % submission_id) secure.low_level() f = open(real_path, 'w') try: f.write(input_data) except: f.close() log.log_error('Importing input failed, %d' % submission_id) return False f.close() except OSError as e: return False return True
def figure_eight(self, inverted_x_axis, inverted_y_axis): if self.__actuators: self.__actuators.figure_eight(inverted_x_axis, inverted_y_axis) #haven't implemented rotation yet else: log.log_error("Actuator have not been initialized" \ " with a com-port properly.")
def POST(self): try: args = web.input(track_id="", token=None) logging.debug("Vote request: %s" % args) sender = auth.get_id_by_token(args.token) if sender is None: raise web.forbidden("Bad token.") if args.track_id.isdigit(): track_id = int(args.track_id) else: track_id = tracks.get_last_track_id() weight = tracks.add_vote(track_id, sender, self.vote_value) if weight is None: return {"status": "error", "message": "No such track."} database.commit() message = 'OK, current weight of track #%u is %.04f.' % (track_id, weight) return { "status": "ok", "message": message, "id": track_id, "weight": weight, } except web.Forbidden: raise except Exception, e: log.log_error(str(e), e) return {"status": "error", "message": str(e)}
def get_details_letssingit(song_name): ''' Gets the song details if song details not found through spotify ''' song_name = improvename.songname(song_name) url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \ quote(song_name.encode('utf-8')) html = urlopen(url).read() soup = BeautifulSoup(html, "html.parser") link = soup.find('a', {'class': 'high_profile'}) try: link = link.get('href') link = urlopen(link).read() soup = BeautifulSoup(link, "html.parser") album_div = soup.find('div', {'id': 'albums'}) title_div = soup.find('div', {'id': 'content_artist'}).find('h1') try: lyrics = soup.find('div', {'id': 'lyrics'}).text lyrics = lyrics[3:] except AttributeError: lyrics = "" log.log_error("* Couldn't find lyrics", indented=True) try: song_title = title_div.contents[0] song_title = song_title[1:-8] except AttributeError: log.log_error("* Couldn't reset song title", indented=True) song_title = song_name try: artist = title_div.contents[1].getText() except AttributeError: log.log_error("* Couldn't find artist name", indented=True) artist = "Unknown" try: album = album_div.find('a').contents[0] album = album[:-7] except AttributeError: log.log_error("* Couldn't find the album name", indented=True) album = artist except AttributeError: log.log_error("* Couldn't find song details", indented=True) album = song_name song_title = song_name artist = "Unknown" lyrics = "" match_bool, score = matching_details(song_name, song_title, artist) return artist, album, song_title, lyrics, match_bool, score
def _write(self, ctxt, offset, src, length): try: data = ctypes.create_string_buffer(length) ctypes.memmove(data, src, length) return self.write(offset, data.raw) except: log.log_error(traceback.format_exc()) return 0
def figure_eight(self, inverted_x_axis, inverted_y_axis): if self.__actuators: self.__actuators.figure_eight(inverted_x_axis, inverted_y_axis) #haven't implemented rotation yet else: log.log_error("Actuators have not been initialized" \ " with a com-port properly.")
def _free_register_list(self, ctxt, regs): try: buf = ctypes.cast(regs, ctypes.c_void_p) if buf.value not in self._pending_reg_lists: raise ValueError("freeing register list that wasn't allocated") del self._pending_reg_lists[buf.value] except: log.log_error(traceback.format_exc())
def _free_parameters(self, params, count): try: buf = ctypes.cast(params, ctypes.c_void_p) if buf.value not in self._pending_param_lists: raise ValueError("freeing parameter list that wasn't allocated") del self._pending_param_lists[buf.value] except: log.log_error(traceback.format_exc())
def _get_global_pointer_reg(self, ctxt): try: if self.__class__.global_pointer_reg is None: return 0xffffffff return self.arch.regs[self.__class__.global_pointer_reg].index except: log.log_error(traceback.format_exc()) return False
def _get_float_return_reg(self, ctxt): try: if self.__class__.float_return_reg is None: return 0xffffffff return self.arch.regs[self.__class__.float_int_return_reg].index except: log.log_error(traceback.format_exc()) return False
def _function_action(cls, view, func, action): try: file_metadata = filemetadata.FileMetadata(handle = core.BNGetFileForView(view)) view_obj = binaryview.BinaryView(file_metadata = file_metadata, handle = core.BNNewViewReference(view)) func_obj = function.Function(view_obj, core.BNNewFunctionReference(func)) action(view_obj, func_obj) except: log.log_error(traceback.format_exc())
def get_frame(self): """ Get frame as an image """ rval, frame = self.__vc.read() if rval: return frame else: log.log_error("Could not get frame from video source.") return False
def _get_directory_name_input(self, ctxt, result, prompt, default_name): try: value = self.get_directory_name_input(prompt, default_name) if value is None: return False result[0] = core.BNAllocString(str(value)) return True except: log.log_error(traceback.format_exc())
def _get_int_input(self, ctxt, result, prompt, title): try: value = self.get_int_input(prompt, title) if value is None: return False result[0] = value return True except: log.log_error(traceback.format_exc())
def _show_html_report(self, ctxt, view, title, contents, plaintext): try: if view: view = binaryview.BinaryView(handle = core.BNNewViewReference(view)) else: view = None self.show_html_report(view, title, contents, plaintext) except: log.log_error(traceback.format_exc())
def run(self): """The main worker.""" logging.info("Scrobbler thread started.") while True: try: self.run_once() except Exception, e: log.log_error("Scrobbling failed: %s" % e, e) time.sleep(60)