def getlevelpb(userid, gameid, levelid, catid, varis): """ Returns the pb of the given user and the given game, level, category and with the subcategories Returns: place(int), formated_time(str) place on the leaderboard and the time """ response = _requests_get_srcomapi( 'users/{user}/personal-bests'.format(user=userid), params={'game': gameid}) if response.status_code == 200: runs = response.json()['data'] match = list( filter( lambda item: _varcheck(varis, item['run']['values']), filter( lambda item: item['run']['category'] == catid and item[ 'run']['level'] == levelid, runs))) if len(match) < 1: return None, None elif len(match) == 1: place = match[0]['place'] formated_time = format_time(match[0]['run']['times']['primary_t']) return place, formated_time else: sort = sorted( map( lambda run: (run['run']['times']['primary_t'], run['place']), match)) return sort[0][1], format_time(sort[0][0]) else: return None, None
def update_times(self, total_time, record_time): if total_time: self.total_time_label.text = '+{}'.format( util.format_time(total_time)) else: self.total_time_label.text = '' self.level_record_label.text = util.format_time(record_time)
def print_pr(pr): if pr.error: print(pr.error) exit() else: pr.verify() print() print("Payment request data") print("Network: " + pr.details.network) print("Requestor: " + pr.get_requestor()) print("Memo: " + pr.get_memo()) print("Expiration: " + util.format_time(pr.get_expiration_date())) print("Creation Time: " + util.format_time(pr.details.time)) print("Verification Status: " + pr.get_verify_status()) print("Merchant Data: " + str(pr.details.merchant_data)) print("Outputs:") for out in pr.get_outputs(): if out[0] == util.TYPE_ADDRESS: print(" Type: Address") print(" Address: " + out[1]) elif out[0] == util.TYPE_PUBKEY: print(" Type: Public Key") print(" Public Key: " + out[1]) elif out[0] == util.TYPE_SCRIPT: print(" Type: Script") print(" Script: " + out[1]) else: print(" Type: Unknown") print(" Data: " + out[1]) print(" Amount: " + util.format_satoshis(out[2]) + " BTC") # Prompt to send transaction print( "To continue, send the necessary amounts of Bitcoin to the addresses specified in the 'Outputs' field above. Once broadcast, press ENTER to continue or CTRL+C to exit." ) input() # Only do this if there is a Payment URL if pr.details.payment_url: # Get raw tx and refund address for Payment message raw_tx = input( "Enter the hex of the transaction that was just made: ").strip( ) ref_addr = input("Enter a refund address: ").strip() # Send payment message and wait for ACK result = pr.send_ack(raw_tx, ref_addr) if result[0]: print(result[1]) else: print(result[1]) exit()
def print_info(self): data = {"op": 1323} res = util.send_data(data, "integral") # print json.dumps(res, sort_keys = False, indent = 4) print "Order: %d" % (res.get("order", 0) or 0) print "Integral: %s" % (res["integral"]) print "Award: %d" % (res["award"]) print "IsGet: %s" % ("True" if res["isGet"] == "1" else "False") print "ServerTime: %s" % (util.format_time(res["serverTime"])) print "EndTime: %s" % (util.format_time(res["endTime"])) print "OrderList:" for pp in res["orderList"] or []: print "\tOrder:%d\tIntegle:%s\tName:%s" % (pp["order"], pp["integle"], pp["userName"])
def do_action(cmd, p): bc = cmd.client if bc.container: ls = bc.list_blobs(p.prefix.value) else: ls = bc.list_containers(p.prefix.value) cs = 0 #coutainer count bs = 0 #blob count ts = 0 #total_size(blob) formatter = '%s \t%s \t%s' path_idx = len(string.join(bc.paths, bc.path_separator)) if path_idx: path_idx += 1 for l in ls: if isinstance(l, Container): cs += 1 size = '<DIR>' name = l.name else: bs += 1 size = l.properties.content_length ts += size size = util.format_size(size) name = l.name[path_idx:] time = l.properties.last_modified time = util.format_time(time) cmd.info(formatter, time, size, name) cmd.hightlight('\tcontainer(s):%s\tblob(s):%s\tblob size:%s', cs, bs, util.format_size(ts))
def make_ffmpeg_args(in_file: str, out_file: str, from_time: str, to_time: str) -> t.Tuple[str, ...]: args = DEFAULT_ARGS.copy() from_time = parse_time(from_time) from_time_formatted = format_time(from_time) args[10] = f'-ss {from_time_formatted}' args[20] = f'-i "{in_file}"' try: to_time = parse_time(to_time) except ValueError: pass else: duration_formatted = format_timedelta(get_duration(from_time, to_time)) args[30] = f'-to {duration_formatted}' _, in_file_name = split_path(in_file) in_file_extension = get_extension(in_file_name) args[50] = f'"{add_extension(out_file, extension=in_file_extension)}"' sorted_args = tuple(v for _, v in sorted(args.items())) return sorted_args
def do_action(cmd,p): bc=cmd.client if bc.container: ls=bc.list_blobs(p.prefix.value) else: ls=bc.list_containers(p.prefix.value) cs=0 #coutainer count bs=0 #blob count ts=0 #total_size(blob) formatter='%s \t%s \t%s' path_idx=len(string.join(bc.paths,bc.path_separator)) if path_idx: path_idx+=1 for l in ls: if isinstance(l,Container): cs+=1 size='<DIR>' name=l.name else: bs+=1 size=l.properties.content_length ts+=size size=util.format_size(size) name=l.name[path_idx:] time=l.properties.last_modified time=util.format_time(time) cmd.info(formatter,time,size,name) cmd.hightlight('\tcontainer(s):%s\tblob(s):%s\tblob size:%s',cs,bs,util.format_size(ts))
def get_team(url): """ Gets list of players given team url """ heads = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36' } response = requests.get(url, headers=heads) soup = BeautifulSoup(response.text, "lxml") # Find player tags tab = soup.find_all("a", class_="spielprofil_tooltip") links = {} players = set() for i in tab: links[i.text] = i['href'] name_item = i.findNext("td", {"class": "hide"}) dob_item = i.findNext("td", {"class": "zentriert"}) position_item = dob_item.find_previous("tr") if name_item is not None and dob_item is not None: players.add((name_item.text, format_time(dob_item.text), position_item.text)) data = [] for a, b, c in players: data.append([format_name(a), b, c, links[a]]) coach_item = soup.find_all("div", class_="container-hauptinfo")[0].findNext("a") coach = (format_name(coach_item.text), coach_item["href"]) return ((data, coach))
def getwr(gameid, categoryid, variables): """ Get the wr for a category in a game with variables Params: gameid (str): ID of the game categoryid (str): ID of the category variables (list of (Variable, (valueid, valuename))): Variables to include, can be an empty list Returns: names(list(str)), time(str) Name of the runner and the time """ varstring = '' for var, val in variables: varstring += '&var-' + var.id + '=' + val[0] response = _requests_get_srcomapi( 'leaderboards/{gameid}/category/{catid}?top=1&embed=players{vars}'. format(gameid=gameid, catid=categoryid, vars=varstring)) if response.status_code != 200: return None, None data = response.json()['data'] if len(data['runs']) == 0: return None, None run = data['runs'][0]['run'] time = run['times']['primary_t'] formated_time = format_time(time) player = data['players']['data'][0] def player_to_name(player): if player['rel'] == 'guest': return player['name'] else: return player['names']['international'] names = list(map(player_to_name, data['players']['data'])) return names, formated_time
def merge(self, other): if other.total_buy_month == 0: return if other.qq != self.qq and other.qq not in self.game_qqs: self.game_qqs.append(other.qq) for qq in other.game_qqs: if qq not in self.game_qqs: self.game_qqs.append(qq) self.total_buy_month += other.total_buy_month records = [*self.buy_records, *other.buy_records] # type: List[BuyRecord] records.sort(key=lambda br: br.buy_at) # 重新计算时长 expired_at = parse_time(records[0].buy_at) for record in records: now = parse_time(record.buy_at) if now > expired_at: # 已过期,从当前时间开始重新计算 start_time = now else: # 续期,从之前结束时间叠加 start_time = expired_at expired_at = start_time + record.buy_month * timedelta(days=31) self.expire_at = format_time(expired_at) self.buy_records = records
def main(): # volume, album, songid, repeat, consume, song, track, random, pos, # elapsed, playlistlength, date, single, albumartist, file, duration, # bitrate, nextsongid, nextsong, mixrampdb, playlist, artist, title, id, # state, disc, time, lastmodified, audio, genre with open_mpd_client() as client: data = client.currentsong() data.update(client.status()) data.update({ 'duration': format_time(data['duration']) if data.get('duration') else 'N/A', 'elapsed': format_time(data['elapsed']) if data.get('elapsed') else 'N/A', 'lastmodified': data.get('last-modified', 'N/A'), }) print(alfred_json(data.get('title', ''), variables=data))
def __init__(self, app, level_name, best_time, mode, color): self.app = app GridLayout.__init__(self, color=color) self.mode = mode self.ids['level_name'].text = level_name self.ids['best_time'].text = util.format_time(best_time)
def save_buy_timestamp(qq): db = load_db() if key_buy_time not in db: db[key_buy_time] = {} db[key_buy_time][str(qq)] = format_time(datetime.now()) save_db(db)
def collect(self): time_start = datetime.utcnow() collected_data = self.collect_fn() time_end = datetime.utcnow() data = { 'nick': self.nick, 'time_start': epoch_time(time_start), 'time_end': epoch_time(time_end), 'time_start_pretty': format_time(time_start), 'time_end_pretty': format_time(time_end), 'data': collected_data } log('%s: Collected the following data: %s' % (self.name, json.dumps(data, indent=2)), self.verbose) self.upload_queue.append(data) self.upload()
def get_coach_info(url): heads = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'} response = requests.get(url,headers=heads) soup = BeautifulSoup(response.text, "lxml") dob_item = soup.find_all("th", string="Date of Birth:")[0].findNext("td") cob_item = soup.find_all("th", string="Citizenship:")[0].findNext("td") return [format_time(dob_item.text),cob_item.text.strip()]
def validate(self): try: self.validating_lock.acquire() if self.ready in ['yes', 'validated']: return True # if self.ready == 'failed': # self.validating_lock.release() # return False # if os.path.exists(self.path): self.ready = "yes" return True # Check if this url is banned if var.db.has_option('url_ban', self.url): raise ValidationFailedError(tr('url_ban', url=self.url)) # avoid multiple process validating in the meantime info = self._get_info_from_url() if not info: return False # Check if the song is too long and is not whitelisted max_duration = var.config.getint('bot', 'max_track_duration') * 60 if max_duration and \ not var.db.has_option('url_whitelist', self.url) and \ self.duration > max_duration: log.info("url: " + self.url + " has a duration of " + str(self.duration / 60) + " min -- too long") raise ValidationFailedError( tr('too_long', song=self.format_title(), duration=format_time(self.duration), max_duration=format_time(max_duration))) else: self.ready = "validated" self.version += 1 # notify wrapper to save me return True finally: self.validating_lock.release()
def download(self, logger=None): if logger is None: logger = logging.getLogger("pakfire") downloads = self.get_downloads() # If there are no downloads, we can just stop here. if not downloads: return # Get free space of the download location. path = os.path.realpath(REPO_CACHE_DIR) while not os.path.ismount(path): path = os.path.dirname(path) path_stat = os.statvfs(path) if self.download_size >= path_stat.f_bavail * path_stat.f_bsize: raise DownloadError, _("Not enough space to download %s of packages.") \ % util.format_size(self.download_size) logger.info(_("Downloading packages:")) time_start = time.time() counter = 0 counter_downloads = len(downloads) for step in downloads: counter += 1 # Download the package file. step.binary_pkg = step.pkg.download(text="(%d/%d): " % (counter, counter_downloads), logger=logger) # Write an empty line to the console when there have been any downloads. width, height = util.terminal_size() # Print a nice line. logger.info("-" * width) # Format and calculate download information. time_stop = time.time() download_time = time_stop - time_start download_speed = self.download_size / download_time download_speed = util.format_speed(download_speed) download_size = util.format_size(self.download_size) download_time = util.format_time(download_time) line = "%s | %5sB %s " % \ (download_speed, self.download_size, download_time) line = " " * (width - len(line)) + line logger.info(line) logger.info("")
def download(self, logger=None): if logger is None: logger = logging.getLogger("pakfire") downloads = self.get_downloads() # If there are no downloads, we can just stop here. if not downloads: return # Get free space of the download location. path = os.path.realpath(REPO_CACHE_DIR) while not os.path.ismount(path): path = os.path.dirname(path) path_stat = os.statvfs(path) if self.download_size >= path_stat.f_bavail * path_stat.f_bsize: raise DownloadError, _("Not enough space to download %s of packages.") \ % util.format_size(self.download_size) logger.info(_("Downloading packages:")) time_start = time.time() counter = 0 counter_downloads = len(downloads) for step in downloads: counter += 1 # Download the package file. step.binary_pkg = step.pkg.download( text="(%d/%d): " % (counter, counter_downloads), logger=logger) # Write an empty line to the console when there have been any downloads. width, height = util.terminal_size() # Print a nice line. logger.info("-" * width) # Format and calculate download information. time_stop = time.time() download_time = time_stop - time_start download_speed = self.download_size / download_time download_speed = util.format_speed(download_speed) download_size = util.format_size(self.download_size) download_time = util.format_time(download_time) line = "%s | %5sB %s " % \ (download_speed, self.download_size, download_time) line = " " * (width - len(line)) + line logger.info(line) logger.info("")
def uptime(username, message, channel, tags): stream = self.bot.twitch_api.get_stream( self.bot.twitch_api.twitch_id) if stream == None: #Not live return start = datetime.strptime(stream['created_at'], '%Y-%m-%dT%H:%M:%SZ') delta = datetime.utcnow() - start self.irc.sendprivmsg( channel, '@{user}, I\'ve been live for {time}'.format( user=username, time=format_time(int(delta.total_seconds()))))
def format_print(self): print "Get %d heros" % (len(self.hid_dict)) for hid in self.get_hero_ids(): cur_exp = self.calc_cur_exp_by_id(hid) print "Hero: %s" % (self.get_name_by_id(hid)) print "\tID: %s" % (hid) print "\tLevel: %s\tGrade: %s" % (self.get_level_by_id(hid), self.get_grade_by_id(hid)) if cur_exp > 0: print "\tExp: %d/%d" % ( self.calc_cur_exp_by_id(hid), LEVEL_EXP_MAP.get(int(self.get_level_by_id(hid)), 0), ) print "\tArmy: %s" % (self.get_currUnit_by_id(hid)) print "\t统:%s\t勇:%s\t智:%s" % ( self.get_leadership_by_id(hid), self.get_tactics_by_id(hid), self.get_magic_by_id(hid), ) print "\tNextRebirthLevel: %s" % (self.get_nextrebirthlevel_by_id(hid)) if self.get_trainingEndTime_by_id(hid) <> "0": print "\tTrainingEndTime: %s" % (util.format_time(self.get_trainingEndTime_by_id(hid))) if self.get_nextUpgrade_by_id(hid) <> "0": print "\tNextUpgrade: %s" % (util.format_time(self.get_nextUpgrade_by_id(hid)))
def show_room(player_id): room = next((r for r in rooms if r.has_player(player_id)), None) if not room: abort(404) resp = { 'id': room.id, 'created_time': format_time(room.created_time), } if room.game and room.game.has_started(): resp.update({'game': room.game.to_json(player_id)}) return resp
async def remind_worker(): csr = bot.database.execute( "SELECT * FROM reminders WHERE expired = 0 AND remind_timestamp < ?", (util.timestamp(), )) to_expire = [] async with csr as cursor: async for row in cursor: rid, remind_timestamp, created_timestamp, reminder_text, _, extra = row try: remind_timestamp = datetime.utcfromtimestamp( remind_timestamp) created_timestamp = datetime.utcfromtimestamp( created_timestamp).replace(tzinfo=timezone.utc) extra = json.loads(extra) uid = extra["author_id"] tz = await util.get_user_timezone( util.AltCtx(util.IDWrapper(uid), util.IDWrapper(extra.get("guild_id")), bot)) print(created_timestamp, tz, created_timestamp.astimezone(tz)) created_time = util.format_time( created_timestamp.astimezone(tz)) text = f"<@{uid}> Reminder queued at {created_time}: {reminder_text}" for method_name, func in remind_send_methods: print("trying", method_name, rid) try: await func(extra, text) metrics.reminders_fired.inc() to_expire.append((1, rid)) # 1 = expired normally break except Exception as e: logging.warning("Failed to send %d to %s", rid, method_name, exc_info=e) except Exception as e: logging.warning("Could not send reminder %d", rid, exc_info=e) #to_expire.append((2, rid)) # 2 = errored for expiry_type, expiry_id in to_expire: logging.info("Expiring reminder %d", expiry_id) await bot.database.execute( "UPDATE reminders SET expired = ? WHERE id = ?", (expiry_type, expiry_id)) await bot.database.commit()
def html_log(events): html = '''<div id='events'> <table width="95%" border=0 cellpadding=4> <tr> <td width="10%"><h1>Time</h1></td> <td width="82%"><h1>Log ('''+str(len(events))+''')</h1></td> <td width="8%"></td> </tr>''' for (idx, event) in enumerate(events): (rid, category, time0, lat, lng, log_string) = event col = "DDDDEE" if idx%2==0 else "FFFFFF" timestamp = util.format_time(time0) if lat is None: actions = '<a href="/edit/?id='+str(rid)+'">[e]</a>' else: actions = '''<a href="https://maps.google.com/maps?q='''+str(lat)+''','''+str(lng)+'''">[m]</a> <a href="javascript:SetEditLog('''+str(rid)+''');">[e]</a>''' links = re.compile('[~!@#\^][^ \'.?,!\(\)]+').findall(log_string) for link in links: log_string = re.sub(link, '<a href="?keyword='+link[1:]+'">'+link+'</a>', log_string) #weblinks = re.compile('\^\((.+)\)').findall(log_string) #for link in weblinks: # log_string = re.sub(link, '<a href="http://'+link+'">[web]</a>', log_string) html += ''' <tr bgcolor="'''+col+'''"> <td>'''+ timestamp +'''</td> <td>'''+ log_string +'''</td> <td>'''+ actions +'''</td> </tr>''' html += '</table>' html += '</div>' # modify log viewbox html += '<div id="modifylog" style="display:none; z-index:1;"></div>' html += '''<script> function HideModifyLog() { document.getElementById('modifylog').style.display = 'none'; } function SetEditLog(idx) { document.getElementById('modifylog').style.display = 'block'; document.getElementById('modifylog').innerHTML = '<iframe src="/edit/?id='+idx+'" width="100%" height="100%"></iframe><br/><a href="javascript:HideModifyLog();"> [close]</a>'; } </script>''' return html
async def fire_reminder(self, id): remind_send_methods = [("original channel", self.send_to_channel), ("direct message", self.send_by_dm), ("originating guild", self.send_to_guild)] row = await self.bot.database.execute_fetchone( "SELECT * FROM reminders WHERE id = ?", (id, )) to_expire = [] rid, remind_timestamp, created_timestamp, reminder_text, _, extra = row try: remind_timestamp = datetime.utcfromtimestamp(remind_timestamp) created_timestamp = datetime.utcfromtimestamp( created_timestamp).replace(tzinfo=timezone.utc) extra = json.loads(extra) uid = extra["author_id"] tz = await util.get_user_timezone( util.AltCtx(util.IDWrapper(uid), util.IDWrapper(extra.get("guild_id")), self.bot)) created_time = util.format_time(created_timestamp.astimezone(tz)) text = f"<@{uid}> Reminder queued at {created_time}: {reminder_text}" for method_name, func in remind_send_methods: try: await func(extra, text) metrics.reminders_fired.inc() to_expire.append((1, rid)) # 1 = expired normally break except Exception as e: logging.warning("Failed to send %d to %s", rid, method_name, exc_info=e) except Exception as e: logging.warning("Could not send reminder %d", rid, exc_info=e) #to_expire.append((2, rid)) # 2 = errored for expiry_type, expiry_id in to_expire: logging.info("Expiring reminder %d", expiry_id) await self.bot.database.execute( "UPDATE reminders SET expired = ? WHERE id = ?", (expiry_type, expiry_id)) await self.bot.database.commit()
def display_final_time(self): self.record_grid.clear_widgets() l = sorted(self.app.score_manager.run_scores.iteritems(), key=lambda i: i[0]) total_time = 0 for i, data in enumerate(l): level_name, score = data if i % 2: color = .2, .2, .2, 1 else: color = .2, .2, .4, 1 result = LevelResult( level_name, score, self.app.score_manager.best_scores.get(level_name, -1), color) self.record_grid.add_widget(result) total_time += score self.win_label.text = util.format_time(total_time)
def add_notice( self, title, message, sender="风之凌殇", send_at: str = "", show_type=NoticeShowType.ONCE, open_url="", valid_duration: Optional[timedelta] = None, show_only_before_version="", ): send_at = send_at or format_now() valid_duration = valid_duration or timedelta(days=7) if show_type not in valid_notice_show_type: logger.error( f"无效的show_type={show_type},有效值为{valid_notice_show_type}") return for old_notice in self.notices: if old_notice.title == title and old_notice.message == message and old_notice.sender == sender: logger.error( f"发现内容完全一致的公告,请确定是否是误操作,若非误操作请去文本直接修改。\n{old_notice}") return notice = Notice() notice.title = title notice.message = message notice.sender = sender notice.send_at = send_at notice.show_type = show_type notice.open_url = open_url notice.expire_at = format_time(get_now() + valid_duration) notice.show_only_before_version = show_only_before_version self.notices.append(notice) logger.info(f"添加公告:{notice}")
def update(self, dt): if self.state == FADE_OUT: self.fade.opacity += dt * .4 if self.fade.opacity > 1: self.fade.opacity = 1 self.set_state(IDLE) self.app.score_manager.log_score( self.app.level_manager.get_level_name(), round(self.timer, 3)) self.reset_timer() self.app.level_manager.load() else: self.timer += dt self.time_label.text = util.format_time(self.timer) if self.state == IDLE: if self.damage_timer > 0: self.damage_timer -= dt * 2 * self.damage_time if self.damage_timer < 0: self.damage_timer = 0 d = self.damage_timer self.health_bar.color = 1, d, d, 1 if self.powerup_bar.size_hint_x > 0: self.powerup_timer -= dt if self.powerup_timer < 0: self.powerup_timer += 1 d = self.powerup_timer self.powerup_bar.color = d, d, 1, 1 elif self.state == FADE_IN: self.fade.opacity -= dt * .5 if self.fade.opacity < 0: self.fade.opacity = 0 self.set_state(IDLE)
def get_appointment_time(self): return format_time(self.appointment_time)
def is_last_day(self) -> bool: act_info = get_not_ams_act("集卡") day_fmt = "%Y-%m-%d" return format_time(parse_time(act_info.dtEndTime), day_fmt) == format_now(day_fmt)
class DnfHeiyaInfo(ConfigInterface): def __init__(self): self.lottery_count = 0 self.box_score = 0 if __name__ == '__main__': a = BuyInfo() a.qq = "11" a.game_qqs = ["12", "13"] a.total_buy_month = 3 a.buy_records = [ BuyRecord().auto_update_config({"buy_at": "2020-02-06 12:30:15"}), BuyRecord().auto_update_config({"buy_at": "2021-02-08 12:30:15", "buy_month": 2}), ] a.expire_at = format_time(parse_time("2020-02-06 12:30:15") + timedelta(days=31 * 3)) b = BuyInfo() b.qq = "11" b.game_qqs = ["12", "14"] b.total_buy_month = 2 b.buy_records = [ BuyRecord().auto_update_config({"buy_at": "2020-02-06 12:30:15"}), BuyRecord().auto_update_config({"buy_at": "2021-02-08 12:30:15"}), ] b.expire_at = format_time(parse_time("2020-02-06 12:30:15") + timedelta(days=31 * 2)) print(a) print(b) a.merge(b)
def display_pr(self, pr): if pr.error: print(pr.error) exit() else: pr.verify() self.payment_data_box.setTitle("Payment Request Data") pr_data_layout = QGridLayout() pr_data_layout.addWidget(QLabel("Network:"), 0, 0) network_lbl = QLabel(pr.details.network) network_lbl.setTextInteractionFlags(Qt.TextSelectableByMouse) pr_data_layout.addWidget(network_lbl, 0, 1) pr_data_layout.addWidget(QLabel("Requestor:"), 1, 0) requestor_lbl = QLabel(pr.get_requestor()) requestor_lbl.setTextInteractionFlags(Qt.TextSelectableByMouse) pr_data_layout.addWidget(requestor_lbl, 1, 1) pr_data_layout.addWidget(QLabel("Memo:"), 2, 0) memo_lbl = QLabel(pr.get_memo()) memo_lbl.setTextInteractionFlags(Qt.TextSelectableByMouse) pr_data_layout.addWidget(memo_lbl, 2, 1) pr_data_layout.addWidget(QLabel("Expiration:"), 3, 0) expire_lbl = QLabel(util.format_time(pr.get_expiration_date())) expire_lbl.setTextInteractionFlags(Qt.TextSelectableByMouse) pr_data_layout.addWidget(expire_lbl, 3, 1) pr_data_layout.addWidget(QLabel("Creation Time:"), 4, 0) creation_lbl = QLabel(util.format_time(pr.details.time)) creation_lbl.setTextInteractionFlags(Qt.TextSelectableByMouse) pr_data_layout.addWidget(creation_lbl, 4, 1) pr_data_layout.addWidget(QLabel("Verification status:"), 5, 0) verification_lbl = QLabel(pr.get_verify_status()) verification_lbl.setTextInteractionFlags(Qt.TextSelectableByMouse) pr_data_layout.addWidget(verification_lbl, 5, 1) pr_data_layout.addWidget(QLabel("Merchant Data:"), 6, 0) merch_lbl = QLabel(str(pr.details.merchant_data)) merch_lbl.setTextInteractionFlags(Qt.TextSelectableByMouse) pr_data_layout.addWidget(merch_lbl, 6, 1) pr_data_layout.addWidget(QLabel("Outputs:"), 7, 0) i = 0 for out in pr.get_outputs(): type_lbl = QLabel() if out[0] == util.TYPE_ADDRESS: pr_data_layout.addWidget(QLabel(" Type:"), 8 + i, 0) type_lbl.setText("Address") pr_data_layout.addWidget(QLabel(" Address:"), 8 + i + 1, 0) elif out[0] == util.TYPE_PUBKEY: pr_data_layout.addWidget(QLabel(" Type:"), 8 + i, 0) type_lbl.setText("Public Key") pr_data_layout.addWidget(QLabel(" Public Key:"), 8 + i + 1, 0) elif out[0] == util.TYPE_SCRIPT: pr_data_layout.addWidget(QLabel(" Type:"), 8 + i, 0) type_lbl.setText("Script") pr_data_layout.addWidget(QLabel(" Script:"), 8 + i + 1, 0) else: pr_data_layout.addWidget(QLabel(" Type:"), 8 + i, 0) type_lbl.setText("Unknown") pr_data_layout.addWidget(QLabel(" Data:"), 8 + i + 1, 0) type_lbl.setTextInteractionFlags(Qt.TextSelectableByMouse) pr_data_layout.addWidget(type_lbl, 8 + i, 1) data_lbl = QLabel(out[1]) data_lbl.setTextInteractionFlags(Qt.TextSelectableByMouse) pr_data_layout.addWidget(data_lbl, 8 + i + 1, 1) amt_lbl = QLabel(util.format_satoshis(out[2]) + " BTC") amt_lbl.setTextInteractionFlags(Qt.TextSelectableByMouse) pr_data_layout.addWidget(QLabel(" Amount:"), 8 + i + 2, 0) pr_data_layout.addWidget(amt_lbl, 8 + i + 2, 1) i += 3 next_button = QPushButton("Next") next_button.clicked.connect(self.make_further_instructions(pr)) pr_data_layout.addWidget(next_button, 8 + i, 0) self.payment_data_box.setLayout(pr_data_layout)
def get_player_info(url): heads = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36' } response = requests.get(url, headers=heads) soup = BeautifulSoup(response.text, "lxml") # Find player tags tab = soup.find_all("tr", class_="zeile-transfer") transfers = [] for i in tab: season_item = i.findNext("td", class_="zentriert") date_item = season_item.findNext("td", class_="zentriert") out_team_item = date_item.findNext( "td", class_="hauptlink no-border-links hide-for-small vereinsname") in_team_item = out_team_item.findNext( "td", class_="hauptlink no-border-links hide-for-small vereinsname") transfers.append([ season_item.text, format_time(date_item.text), out_team_item.text.strip(), in_team_item.text.strip() ]) try: name_ob = soup.find_all( "th", string=re.compile("Name in home country:"))[0].findNext("td").text except: name_ob = "" try: city_item = soup.find_all("th", string=re.compile("Place of birth:"))[0] country_ob = city_item.findNext("img")["title"] city_ob = city_item.findNext("span").text.strip() except: city_ob, country_ob = "unknown", "unknown" citizen_holder = soup.find_all( "th", string=re.compile("Citizenship:"))[0].find_next_siblings() citizen_items = citizen_holder[0].find_all("img", recursive=False) citizen = [] for i in citizen_items: citizen.append(i['title']) try: height = format_height( soup.find_all("th", string=re.compile("Height:"))[0].findNext("td").text) except: height = -1 try: foot = soup.find_all("th", string=re.compile("Foot:"))[0].findNext("td").text except: foot = "unknown" return [name_ob, (city_ob, country_ob), citizen, height, foot, transfers]
def is_last_day(self): return format_time(parse_time(self.dtEndTime), "%Y%m%d") == get_today()
import time from collections import OrderedDict from data import * import warnings warnings.filterwarnings("ignore") import torch import torch.nn as nn # config config = util.read_config('./configs/train_model.yaml') torch.manual_seed(config.seed) # log log_path = config.log + util.format_time(time.localtime()) + '/' # log_path = config.log + '2018-10-20-12:17:22/' if not os.path.exists(log_path): os.mkdir(log_path) logging = util.logging(log_path + 'log.txt') # 记录本次运行的记录 logging_csv = util.logging_csv(log_path + 'record.csv') # 记录模型训练的指标数据 # checkpoint if config.checkpoint_restore: print('loading checkpoint from {}...'.format(config.checkpoint_restore)) # map_location={'cuda:1':'cuda:0'} checkpoints = torch.load(config.checkpoint_restore) # cuda use_cuda = torch.cuda.is_available() and len(config.gpus) > 0 #use_cuda = True
def is_last_day(self): from util import format_time, get_today, parse_time return format_time(parse_time(self.dtEndTime), "%Y%m%d") == get_today()
def get_fix_time(self): return format_time(self.fix_time)
def format_print(self): print '%s:'%(self.get_user_name()) print '\tSeason: %s'%(SEASON_MAP[self.get_season()]) print '\tMagic: %d'%(self.get_magic()) print '\tLevel: %d'%(self.get_level()) print '\tTraining Status: %d/%d'%(self.get_training_hero_num(), self.get_max_training_hero_num()) print '\tLevy Status: %d/%d'%(self.get_levy_times(), self.get_levy_times()+self.get_levy_remain()) print '\tEnforce Levy Times: %d, Total Times: %d'%(self.get_enforce_levy_times(), self.get_levy_times()+self.get_enforce_levy_times()) print '\tDaily Task Status: %d/6'%(self.get_task_finish_num()) print '\tSilver Status: %d/%d'%(self.get_cur_silver(), self.get_max_silver()) print '\tMobility Status: %d/%d'%(self.get_cur_mobility(), self.get_max_mobility()) print '\tBattle Times: %d'%(self.get_battleTimes()) print '\tGoldCoin: %d'%(self.get_gold_num()) print '\tExploit: %d'%(self.get_exploit()) print '\tRepute: %d'%(self.get_repute()) print '\tJewelryPoint: %d'%(self.get_jewelryPoint()) print '\tFree Appoint Remain: %d'%(self.get_freeappoint_num()) print '\tTurntable Remain: %d'%(self.get_turntable_time()) print '\tSalary Remain: %d'%(1-self.get_salary_collected()) print '\tArenaReward Remain: %d'%(1-self.get_arenaReward()) print '\tReceiveCaravan: %d'%(self.get_userReceiveCaravan()) print '\tServerTime: %s'%(util.format_time(self.get_serverTime())) print '\tNext Jianzhu CD Time: %s'%(util.format_time(self.get_next_CDTime())) print '\tTax CD Time: %s'%(util.format_time(self.get_tax_CDTime())) print '\tKeji CD Time: %s'%(util.format_time(self.get_next_keji_CDTime())) print '\tTufei CD Time: %s'%(util.format_time(self.get_tufei_CDTime())) print '\tMobility CD Time: %s'%(util.format_time(self.get_mobility_CDTime())) print '\tWeipai CD Time: %s'%(util.format_time(self.get_weipai_CDTime())) print '\tZhuangbei CD Time: %s'%(util.format_time(self.get_zuangbei_CDTime())) print '\tTouzi CD Time: %s'%(util.format_time(self.get_touzi_CDTime())) print '\tBlock CD Time: %s'%(util.format_time(self.get_block_CDTime())) print '\tXiongsou CD Time: %s'%(util.format_time(self.get_xiongsou_CDTime()))
def getNpcInfo(self): global FirstTime nid = NPC_ID[Npc_String] if FirstTime: FirstTime = False times = 1 else: times = 15 for i in range(times): ni = NpcInfo(nid) remain_times = ni.getNumber() logger.info('%s remain number %d, serverTime: %s'%(Npc_String, remain_times, util.format_time(ni.getServerTime()))) if remain_times > 0: return ni time.sleep(2) return ni
def format_print(self): print 'Sucen Info:' for sid in self.getSucenIds(): print '\tName:%s\tLevel:%d\tLastTime:%s\tContribute:%d'%(self.getNameById(sid), self.getLevelById(sid), util.format_time(self.getLastContributeById(sid)), self.getContributeById(sid))