def __init__(self, series, data): """ Get all games of a series through this. https://records.nhl.com/site/api/playoff-series?cayenneExp=playoffSeriesLetter="A" and seasonId=20182019 This is off from the nhl record api. Not sure if it will update as soon as the day is over. """ matchupTeams = series.matchupTeams top, bottom = get_team_position(matchupTeams) top_team_abbrev = data.teams_info[top.team.id].abbreviation bottom_team_abbrev = data.teams_info[bottom.team.id].abbreviation try: self.conference = series.conference.name except: self.conference = "" self.series_number = series.seriesNumber self.series_code = series.seriesCode #To use with the nhl records API self.matchup_short_name = series.names.matchupShortName self.top_team = SeriesTeam(top, top_team_abbrev) self.bottom_team = SeriesTeam(bottom, bottom_team_abbrev) self.current_game = series.currentGame.seriesSummary self.current_game_id = series.currentGame.seriesSummary.gamePk self.short_status = series.currentGame.seriesSummary.seriesStatusShort self.current_game_date = convert_time( self.current_game.gameTime).strftime("%Y-%m-%d") self.current_game_start_time = convert_time( self.current_game.gameTime).strftime(data.config.time_format) self.games = nhl_api.series_game_record(self.series_code, data.playoffs.season)
def __init__(self, data, matrix, sleepEvent): self.data = data self.matrix = matrix try: self.data.covid19.get_all() self.data.network_issues = False except ValueError as e: print( "NETWORK ERROR, COULD NOT GET NEW COVID 19 DATA: {}".format(e)) self.data.network_issues = True self.worldwide_data = self.data.covid19.all self.layout = self.data.config.config.layout.get_board_layout( 'covid_19') self.sleepEvent = sleepEvent self.sleepEvent.clear() self.last_update = convert_time( (datetime(1970, 1, 1) + timedelta(milliseconds=self.worldwide_data['updated']) ).strftime("%Y-%m-%dT%H:%M:%SZ")).strftime("%m/%d %H:%M:%S") for case in self.worldwide_data: if case == "updated": break self.draw_count(case, self.worldwide_data[case], self.last_update) self.sleepEvent.wait(5)
def fetch_game_time(team_id): """ Function to get the selected team game time only. """ # Set URL depending on team selected url = '{0}schedule?teamId={1}'.format(NHL_API_URL, team_id) try: game_data = requests.get(url) game_data = game_data.json() home_team_id = int( game_data['dates'][0]['games'][0]['teams']['home']['team']['id']) away_team_id = int( game_data['dates'][0]['games'][0]['teams']['away']['team']['id']) game_time = convert_time( game_data["dates"][0]["games"][0]["gameDate"]).strftime("%H:%M:%S") debug.info(str(game_time)) scheduled_game_time = {'game_time': game_time} scheduled_game_time_str = str(scheduled_game_time) return scheduled_game_time_str except KeyError: print( "missing data from the game. Game has not begun or is not scheduled today." )
def user_datetime_data(): """ GET Server Status API endpoint Args: Returns: dict: A JSON object containing the nfvacc server status information """ data = flask.request.get_json() user_id = data.get('user') LOG.info(data) conv_datetime = utils.convert_time(data.get('datetime'), data.get('offset')) LOG.info(conv_datetime) user = mongo.find_one_match('users', {"user_id": user_id}) if user is not None: mongo.insert_one_in('users', {"user_id": user_id}, {'datetime': conv_datetime}) mongo.insert_one_in('users', {"user_id": user_id}, {'offset': data.get('offset')}) # user = mongo.find_one_match('users', {"user_id": user_id}) # utils.start_scheduler_task(user) response_data = {} status = 200 if response_data is not None else 403 js = json.dumps(response_data, indent=2) return flask.Response(js, status=status, mimetype='application/json')
def fetch_fav_team_schedule(team_id): """ Function to get the summary of a scheduled game. """ # Set URL depending on team selected url = '{0}schedule?teamId={1}'.format(NHL_API_URL, team_id) try: game_data = requests.get(url) game_data = game_data.json() home_team_id = int( game_data['dates'][0]['games'][0]['teams']['home']['team']['id']) away_team_id = int( game_data['dates'][0]['games'][0]['teams']['away']['team']['id']) game_time = convert_time( game_data["dates"][0]["games"][0]["gameDate"]).strftime("%I:%M") current_game_schedule = { 'home_team_id': home_team_id, 'away_team_id': away_team_id, 'game_time': game_time } return current_game_schedule except requests.exceptions.RequestException: print("Error encountered, Can't reach the NHL API") return 0 except KeyError: print( "missing data from the game. Game has not begun or is not scheduled today." )
def traite_chrono(self, m) : f = self.frame temps = m.param if temps > 0 : self.tour_on = True f.timer.SetLabel(utils.convert_time(temps)) if temps == 0 : reactor.callLater(0.2, self.envoi_msg, "tick")
def create_entry(self, name, day, s_time, e_time, p_L): # initialize start and end as the number 0 start = 0 end = 0 # create id for entry # id is sha256 hash of current processor time with pid and clock time concat on end entry_id = hashlib.sha256(str(time.time()).encode()).hexdigest() + str(self.pid) + str(self.clock + 1).zfill(3) # convert day part of start and end start += utils.convert_day(day) end += utils.convert_day(day) # convert time part of start and end start += utils.convert_time(s_time) end += utils.convert_time(e_time) return [name.lower(), entry_id, str(start).zfill(3), str(end).zfill(3), p_L]
def traite_chrono(self, m): f = self.frame temps = m.param if temps > 0: self.tour_on = True f.timer.SetLabel(utils.convert_time(temps)) if temps == 0: reactor.callLater(0.2, self.envoi_msg, "tick")
def train_translation_model(start, trainedmodelfile, p, r, b, source_indices, source_train, target_train, vectors, layer_size, epochs): print("Training translation model.") #If no model is incoming, create one: if not os.path.isfile(trainedmodelfile) or os.path.getsize(trainedmodelfile) <=0: print("File not found") print("Initiating an empty model") translation_model = NeuralNetwork(p, r) startpoint = 0 start_i = random.randint(0,len(target_train)-b) # random start position end_i = start_i+b X_list, Y_list = generate_translation_vectors(target_train[start_i:end_i], source_train[start_i:end_i], vectors, source_indices) # Train translation model translation_model.start(X_list, Y_list, layer_size, len(Y_list[0])) else: with open(trainedmodelfile, 'rb') as mf: print("Loading model from file {}.".format(mf)) content = pickle.load(mf) startpoint = content[0] translation_model = content[1] #For each batch... for i in range(startpoint, len(target_train), b): print("Sentences {} - {} out of {}".format(i, i+b, len(target_train))) X_list, Y_list = generate_translation_vectors(target_train[i:i+b], source_train[i:i+b], vectors, source_indices) translation_model.train(X_list, Y_list, epochs) #...write model to file print("Writing model to {}, having processed {} sentences.".format(trainedmodelfile, i+b)) with open(trainedmodelfile, 'wb') as tmf: pickle.dump([i+b, translation_model], tmf) t = time.time() h, m, s = (convert_time(start, t)) print("Time passed: {}:{}:{}\n".format(h, m, s)) stop = time.time() hour, minute, second = (convert_time(start, stop)) print("Ran {} sentences on {} hours, {} minutes and {} seconds".format(len(target_train), hour, minute, second)) print("A translation model is saved to the file {}".format(trainedmodelfile))
def train_language_model(start, trainedmodelfile, p, r, b, target_trigrams, target_indices, vectors, layer_size, epochs): print("Training language model.") # If no model is incoming, create one: if not os.path.isfile(trainedmodelfile) or os.path.getsize(trainedmodelfile) <=0: print("Initializing an empty model") trigram_target_model = NeuralNetwork(p, r) startpoint = 0 init_sample = random.sample(target_trigrams, b) # Initiate network weights from sample X, Y = gen_tri_vec_split(init_sample, vectors, target_indices) # Train language model trigram_target_model.start(X, Y, layer_size, len(Y[0])) else: with open(trainedmodelfile, 'rb') as mf: print("Loading model from file {}.".format(mf)) content = pickle.load(mf) startpoint = content[0] trigram_target_model = content[1] # For each batch... for i in range(startpoint, len(target_trigrams), b): print("Trigrams {} - {} out of {}".format(i, i+b, len(target_trigrams))) X, Y = gen_tri_vec_split(target_trigrams[i:i+b], vectors, target_indices) trigram_target_model.train(X, Y, epochs) # ...write model to file print("Writing model to {}, having processed {} trigrams.".format(trainedmodelfile, i+b)) with open(trainedmodelfile, 'wb') as tmf: pickle.dump([i+b, trigram_target_model], tmf) t = time.time() h, m, s = (convert_time(start, t)) print("Time passed: {}:{}:{}\n".format(h, m, s)) stop = time.time() hour, minute, second = (convert_time(start, stop)) print("Trained {} sentences on {} hours, {} minutes and {} seconds".format(len(target_trigrams), hour, minute, second)) print("A trigram model is saved to the file {}".format(trainedmodelfile))
def container_details(request): if request.method == 'GET': if 'id' in request.GET: if 'save' in request.GET: # Call function to convert existing container to image utils.branch_container(request.GET.get('id'), request.GET.get('id')+"branch") return HttpResponseRedirect('/manager/images/') elif 'start' in request.GET: # Call function to start a stopped or paused container utils.resume_container(request.GET.get('id')) pass elif 'pause' in request.GET: # Call function to pause a started container utils.stop_container(request.GET.get('id')) pass elif 'stop' in request.GET: # Call function to stop a started or paused container utils.remove_container(request.GET.get('id')) pass # Get detailed information for container info = utils.get_info(request.GET['id'])[0] # Most useful information container_details = {} container_details['cpu_shares'] = info['Config']['CpuShares'] container_details['memory'] = info['Config']['Memory'] container_details['memory_swap'] = info['Config']['MemorySwap'] container_details['created_time'] = utils.convert_time(info['Created']) container_details['id'] = info['Id'][:12] # Use first 12 digits container_details['image'] = info['Image'][:12] # Use first 12 digits container_details['name'] = info['Name'][1:] # First char is always '/' container_details['ip'] = info['NetworkSettings']['IPAddress'] container_details['is_running'] = info['State']['Running'] container_details['start_time'] = utils.convert_time(info['State']['StartedAt']) container_details['is_paused'] = info['State']['Paused'] container_details['finish_time'] = utils.convert_time(info['State']['FinishedAt']) return render_to_response('manager/container_details.html', { 'details': container_details, 'id': request.GET['id'] }) return HttpResponseRedirect('/manager/containers/')
def _insert_halfhour_slots_and_convert_to_datetime(hour_cells): hours = [] for h in hour_cells: if h.string: hours.append(convert_time(h.string)) else: last_added_hour = hours[-1] hours.append(datetime(last_added_hour.year, last_added_hour.month, last_added_hour.day, last_added_hour.hour, 30)) return hours
def callback(data, args): global df1 T = rospy.Time.from_sec(time.time()).to_sec() Tn = int(str(T - int(T))[2:9]) df1 = df1.append( { 'Time': convert_time(T, Tn), 'Topic': args[0], 'Message': data.data, 'Color': df2.loc[args[0]].Color }, ignore_index=True)
def user_daily_notification(user_id): """ GET Server Status API endpoint Args: Returns: dict: A JSON object containing the nfvacc server status information """ user = mongo.find_one_match('users', {"user_id": user_id}) datetime = user.get('datetime') offset = -int(user.get('offset')) datetime = utils.convert_time(datetime, offset) message = 'You will be notified daily @ {} for the companies you have selected'.\ format(datetime) buttons = [] block = 'News' button_title = "Today's News" button_dict_tmpl = { "type": "show_block", "block_name": block, "title": button_title } buttons.append(button_dict_tmpl) extra_button = {} extra_button['type'] = "web_url" extra_button['title'] = 'Edit Notifications' extra_button['url'] = "{}/scrader/companies/{}".format(Server_url, user_id) buttons.append(extra_button) response_data = { "messages": [{ "text": message }, { "attachment": { "type": "template", "payload": { "template_type": "button", "text": "Now how would you like to continue?", "buttons": buttons } } }] } status = 200 if response_data is not None else 403 js = json.dumps(response_data, indent=2) return flask.Response(js, status=status, mimetype='application/json')
def __init__(self, overview, data): time_format = data.config.time_format linescore = overview.linescore away = linescore.teams.away home = linescore.teams.home away_abbrev = data.teams_info[away.team.id].abbreviation home_abbrev = data.teams_info[home.team.id].abbreviation self.away_team = Team(away.team.id, away_abbrev, away.team.name, away.goals, away.shotsOnGoal, away.powerPlay, away.numSkaters, away.goaliePulled) self.home_team = Team(home.team.id, home_abbrev, home.team.name, home.goals, home.shotsOnGoal, home.powerPlay, home.numSkaters, home.goaliePulled) self.date = convert_time(overview.game_date).strftime("%Y-%m-%d") self.start_time = convert_time( overview.game_date).strftime(time_format) self.status = overview.status self.periods = Periods(overview) self.intermission = linescore.intermissionInfo.inIntermission if data.status.is_final(overview.status): self.winning_team = overview.w_team self.loosing_team = overview.l_team
def fetch_overview(team_id): """ Function to get the score of the game live depending on the chosen team. Inputs the team ID and returns the score found on web. """ # Set URL depending on team selected url = '{0}schedule?expand=schedule.linescore&teamId={1}'.format( NHL_API_URL, team_id) try: game_data = requests.get(url) game_data = game_data.json() period = game_data['dates'][0]['games'][0]['linescore'][ 'currentPeriodOrdinal'] time = game_data['dates'][0]['games'][0]['linescore'][ 'currentPeriodTimeRemaining'] home_team_id = int( game_data['dates'][0]['games'][0]['teams']['home']['team']['id']) home_score = int( game_data['dates'][0]['games'][0]['teams']['home']['score']) away_team_id = int( game_data['dates'][0]['games'][0]['teams']['away']['team']['id']) away_score = int( game_data['dates'][0]['games'][0]['teams']['away']['score']) game_status = int( game_data['dates'][0]['games'][0]['status']['statusCode']) game_time = convert_time( game_data["dates"][0]["games"][0]["gameDate"]).strftime("%I:%M") current_game_overview = { 'period': period, 'time': time, 'home_team_id': home_team_id, 'home_score': home_score, 'away_team_id': away_team_id, 'away_score': away_score, 'game_status': game_status, 'game_time': game_time } return current_game_overview except requests.exceptions.RequestException: print("Error encountered, Can't reach the NHL API") return 0 except KeyError: print( "missing data from the game. Game has not begun or is not scheduled today." )
def time_limit(self, username="******", mac="", days="Everyday", start="1", end="24"): ''' Restricts user from using internet for limited time. Creates a user profile containing mac, days, start_time, end_time. - username: Create a profile for time limit of the provided username. - mac: Device mac address on which time limit is applied. - days: Day/days on which the time limit is applied. # Time is 24-hour format. - start: Start time of device connection limit. - end: End time of device connection limit. Example: Creates a profile named as User-1 and sets time limit for mac [x] at Monday beginning from 3 am to 6 pm. >>> papi.time_limit(username="******", mac="xx:xx...", days="Mon", start=3, end=6) Sets time limit from Monday to Friday. >>> papi.time_limit(username="******", mac="xx:xx...", days="Mon-Fri", start=3, end=6) ''' # The day field in the request takes the power of 2 for the corresponding day in week. # Monday is 2^0 # Tuesday is 2^1 # Wednesday is 2^2 gen_params = lambda days: { 'username': username, 'days': days, 'start_time': start, 'end_time': end, 'token': self.get_token() } start, end = utils.convert_time(start_time=start, end_time=end) days = days.split('-') if days and len(days) < 3: if len(days) == 1: self.session.get(self.gateway + 'todmngr.tod?action=add&mac={}'.format(mac), params=gen_params(days=week_days[days[0]])) elif len(days) == 2 and days[0] in week_days and days[1] in week_days: if days[0] == days[1]: self.session.get(self.gateway + 'todmngr.tod?action=add&mac={}'.format(mac), params=gen_params(days=week_days["Everyday"])) elif days[0] != days[1]: self.session.get(self.gateway + 'todmngr.tod?action=add&mac={}'.format(mac), params=gen_params(days=str(week_days[days[1]]))) else: print("Specified day is not in week_days.") return 'Successful'
def get_user_datetime_data(user_id): """ GET Server Status API endpoint Args: Returns: dict: A JSON object containing the nfvacc server status information """ user = mongo.find_one_match('users', {"user_id": user_id}) datetime = '' if user is not None: datetime = user.get('datetime', False) if datetime: offset = -int(user.get('offset', 0)) datetime = utils.convert_time(datetime, offset) response_data = datetime status = 200 if response_data is not None else 403 js = json.dumps(response_data, indent=2) return flask.Response(js, status=status, mimetype='application/json')
def get_age(self, z1, z2, units='gyrs'): """ age = ezgal.get_age(z1, z2, units='gyrs') returns the time difference between z1 and z2. z2 can be a list or numpy array. See ezgal.utils.to_years for available output units """ # need to pass an array is_scalar = False if type(z2) != type([]) and type(z2) != type(np.array([])): is_scalar = True z2 = np.array([z2]) # z/age grids are stored in the filter grid objects to_return = utils.convert_time(self.filters[self.filter_order[0]].get_zf_grid(z1).get_ages(z2), incoming='yrs', outgoing=units) if is_scalar: return to_return[0] return to_return
def index(logis_id): """ 中通 """ html_doc = requests.get("http://www.zto.com/GuestService/Bill?model.TxtBill=" + logis_id) soup = BeautifulSoup(html_doc.text, 'lxml') status_dom = soup.find(id="Status") if not status_dom: return info_not_found() else: status = status_dom.get("value") duration = soup.find("div", class_="text3").get_text() routes = [] for li in soup.find_all('li', class_="pr"): routes.append({ 'remark': li.find("div").get_text(), 'scanTime': utils.convert_time(li.find("div", class_="time").get_text(strip=True)) }) return jsonify(status=status, duration=duration, routes=routes, id=logis_id)
def index(logis_id): """ 申通 """ html_doc = requests.get("http://q1.sto.cn/chaxun/result?express_no=" + logis_id) soup = BeautifulSoup(html_doc.text, 'lxml') status = soup.find("ul", class_="info-list").find(class_="tip_info_bg").get_text() route_dom = soup.find("ul", class_="result-list-info") if not route_dom: return info_not_found() routes = [] for item in route_dom.children: routes.append({ "scanTime": utils.convert_time(item.find("div", class_="fl-left").get_text(strip=True)), "remark": item.find("div", class_="fl-right").get_text(strip=True) }) return jsonify(status=status, routes=routes, id=logis_id)
def fetch_fav_team_lastgame(team_id): """ Function to get the summary of the last game played. """ # Set URL depending on team selected url = '{0}teams/{1}?expand=team.schedule.previous'.format( NHL_API_URL, team_id) try: game_data = requests.get(url) game_data = game_data.json() home_team_id = int( game_data['teams'][0]['previousGameSchedule']['dates'][0]['games'] [0]['teams']['home']['team']['id']) away_team_id = int( game_data['teams'][0]['previousGameSchedule']['dates'][0]['games'] [0]['teams']['away']['team']['id']) game_status = int(game_data['teams'][0]['previousGameSchedule'] ['dates'][0]['games'][0]['status']['statusCode']) home_score = int(game_data['teams'][0]['previousGameSchedule']['dates'] [0]['games'][0]['teams']['home']['score']) away_score = int(game_data['teams'][0]['previousGameSchedule']['dates'] [0]['games'][0]['teams']['away']['score']) game_date = convert_time( game_data['teams'][0]['previousGameSchedule']["dates"][0]["games"] [0]["gameDate"]).strftime("%b %d") last_game = { 'home_team_id': home_team_id, 'home_score': home_score, 'away_team_id': away_team_id, 'away_score': away_score, 'game_status': game_status, 'game_date': game_date } return last_game except requests.exceptions.RequestException: print("Error encountered, Can't reach the NHL API") return 0 except KeyError: print( "missing data from the game. Game has not begun or is not scheduled today." )
def index(logis_id): """ returns "[]" if results was null """ r = requests.get('http://www.sf-express.com/sf-service-web/service/bills/' + logis_id + '/routes?app=bill&lang=sc®ion=cn&translate=') resp_text = re.sub(r'<.+?>', '', r.text) if resp_text == "[]": return info_not_found() resp = r.json()[0] routes = [] ## filter unnecessary content for rou in resp['routes']: tmp = {} if 'remark' in rou: tmp['remark'] = re.sub(r'<.+?>', '', rou['remark']) if 'scanDateTime' in rou: tmp['scanTime'] = utils.convert_time(rou['scanDateTime']) routes.append(tmp) return jsonify(status=resp['expressState'], routes=routes, id=resp['id'])
print("Generating vocabulary for source text.") source_vocab = get_vocabulary(source_data) print("Generating vocabulary for target text.") target_vocab = get_vocabulary(target_data) print("Generating word indices.") source_indices = generate_indices(source_vocab) target_indices = generate_indices(target_vocab) print("Fetching vectors from model.") vectors = get_w2v_vectors(pre_trained_model, target_vocab) print("Loading language model.") with open(args.languagemodel, 'rb') as lmf: trigram_target_model = pickle.load(lmf)[1] print("Loading translation model.") with open(args.translationmodel, 'rb') as tmf: translation_model = pickle.load(tmf)[1] test_translation(target_test, source_test, target_vocab, source_vocab, vectors, target_indices, source_indices, trigram_target_model, translation_model, p, args.top_predicted) stop = time.time() hour, minute, second = (convert_time(start, stop)) print("Predicted {} sentences on {} hours, {} minutes and {} seconds".format( len(source_test), hour, minute, second))
def __init__(self, args, **kw): super().__init__(args, **kw) self.waitsec = utils.convert_time(self.time)
def __init__(self, parent, app, title) : wx.Frame.__init__(self, parent, title=title) self.app = app s = self.app.settings self.SetIcon(wx.Icon(app.settings["files_icone"], wx.BITMAP_TYPE_ICO)) self.panel = wx.Panel(self) self.max_props = app.settings["max_props"] self.tour = 0 fill = s["size_fill"] self.Bind(wx.EVT_CLOSE, self.app.exit) #Creation et dessin du timer timer_sizer = self.cree_box_sizer("Temps") self.timer = wx.StaticText(self.panel, -1, str(utils.convert_time(0))) font = wx.Font(s["size_font_chrono"], wx.SWISS, wx.NORMAL, wx.NORMAL) self.timer.SetFont(font) timer_sizer.Add(self.timer, 0, wx.ALL|wx.EXPAND, fill) #Creation et dessin du tirage self.tirage = tirage.tirage(self.panel, self.app) tirage_sizer = self.cree_box_sizer("Tirage") tirage_sizer.Add((fill,0),0) tirage_sizer.Add(self.tirage, 1, wx.ALL|wx.EXPAND, fill) tirage_sizer.Add((fill,0),0) #Creation et dessin de la grille self.grille = grille.grille(self.panel, self.app) grille_sizer = self.cree_box_sizer("Grille") grille_sizer.Add(self.grille, 0, wx.ALL|wx.EXPAND, 0) #Creation des items dans la box messages msgs_sizer = self.cree_box_sizer("Messages") self.msgs = wx.TextCtrl(self.panel, -1, "", size=(app.settings["size_chat_size"], -1), style=wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_RICH) self.set_police_msgs(s["size_font_msgs"]) msgs_sizer.Add(self.msgs, 1, wx.ALL|wx.EXPAND, fill) #Creation box proposition props_sizer = self.cree_box_sizer("Propositions", flag = wx.HORIZONTAL) self.props = wx.ComboBox(self.panel, -1, style=wx.CB_READONLY) props_sizer.Add(self.props, 1, wx.ALL, fill) self.buttonpose = wx.Button(self.panel, -1, "Poser", size=app.settings["size_button"]) self.buttonpose.Enable(False) self.buttonpose.SetDefault() # important pour Windows pour capter la touche Entrée props_sizer.Add(self.buttonpose, 0, wx.ALL|wx.ALIGN_RIGHT, fill) self.props.Bind(wx.EVT_COMBOBOX, self.props_click, self.props) self.buttonpose.Bind(wx.EVT_BUTTON, self.pose, self.buttonpose) self.buttonpose.Bind(wx.EVT_KEY_DOWN, self.app.OnKey) #Creation box score score_sizer = self.cree_box_sizer("Score", flag = wx.HORIZONTAL) self.score = wx.StaticText(self.panel, -1, "") font = wx.Font(s["size_font_score"], wx.SWISS, wx.NORMAL, wx.NORMAL) self.score.SetFont(font) score_sizer.Add(self.score, 1, wx.ALL, fill) buttscore = wx.Button(self.panel, -1, "Scores", size=app.settings["size_button"]) score_sizer.Add(buttscore, 0, wx.ALL|wx.ALIGN_RIGHT, fill) buttscore.Bind(wx.EVT_BUTTON, self.show_score, buttscore) #Creation du chat chat_sizer = self.cree_box_sizer("Chat", flag = wx.HORIZONTAL) self.txtchatin = wx.TextCtrl(self.panel, -1, "", style=wx.TE_PROCESS_ENTER) chat_sizer.Add(self.txtchatin,1, wx.ALL, fill) self.txtchatin.Bind(wx.EVT_TEXT_ENTER, self.chat_enter, self.txtchatin) # cadres boutons bouton_sizer = self.cree_box_sizer("Commandes", flag = wx.HORIZONTAL) #box = wx.StaticBox(self.panel, label = "Commandes") boutons = [ ("Restart", self.button_restart), ("Alpha", self.button_alpha), ("Random", self.button_random), ("Next", self.button_next), ("Précédent", self.button_pose_last), ] if s["user_admin"] : boutons.insert(3, ("Chrono", self.button_chrono)) bouton_in_sizer = wx.GridSizer(rows=1, cols=len(boutons), hgap=fill, vgap=fill) for label, handler in boutons : bouton = wx.Button(self.panel, label=label, size=app.settings["size_button"]) bouton_in_sizer.Add(bouton, flag = wx.ALIGN_CENTER) bouton.Bind(wx.EVT_BUTTON, handler, bouton) bouton_sizer.Add(bouton_in_sizer, proportion=1, flag = wx.EXPAND) #Barre de menu if s["view_menu"] : menubar = wx.MenuBar() menu1 = wx.Menu() menu1.Append(101,"Quitter\tCtrl-Q") self.Bind(wx.EVT_MENU, self.app.exit, id=101) menubar.Append(menu1,"Fichier") menupol = wx.Menu() for i in range(8,14) : menupol.Append(200+i,str(i),"Changer la police des messages serveur", wx.ITEM_RADIO) self.Bind(wx.EVT_MENU, self.menu_police, id=200+i) pset = s["size_font_msgs"] menupol.Check(200+pset, True) self.set_police_msgs(pset) menu2 = wx.Menu() menu2.AppendMenu(299,"Taille police", menupol) menubar.Append(menu2,"Options") menu3 = wx.Menu() menu3.Append(301,"A propos") menubar.Append(menu3,"Aide") self.Bind(wx.EVT_MENU, self.about, id=301) self.SetMenuBar(menubar) #Barre de status if s["view_status"] : self.st = self.CreateStatusBar() self.st.SetFieldsCount(4) self.st.SetStatusWidths(s['size_status']) self.set_status_next(0) self.set_status_restart(0) #Sizers sizer1 = wx.BoxSizer(wx.HORIZONTAL) sizer2 = wx.BoxSizer(wx.VERTICAL) sizer2.Add(msgs_sizer, 1, wx.EXPAND) sizer2.Add(props_sizer, 0, wx.EXPAND) sizer2.Add(score_sizer, 0, wx.EXPAND) sizer2.Add(bouton_sizer, 0, wx.EXPAND) sizer2.Add(chat_sizer, 0, wx.EXPAND) sizer2.Add( (fill,fill), 0) sizer = wx.GridBagSizer(hgap=fill, vgap=fill) if s["view_layout"] == "alt" : sizer1.Add(tirage_sizer, 1, flag = wx.EXPAND) sizer1.Add( (fill,fill)) sizer1.Add(timer_sizer, flag = wx.EXPAND) sizer.Add(grille_sizer, pos=(0,0)) sizer2.Add(sizer1, flag = wx.EXPAND) sizer.Add(sizer2, pos=(0,1), flag = wx.EXPAND) sizer.AddGrowableCol(1) else : sizer1.Add(timer_sizer, flag = wx.EXPAND) sizer1.Add((fill,fill)) sizer1.Add(tirage_sizer, 1, flag = wx.EXPAND) sizer.Add(sizer1, pos=(0,0), flag = wx.EXPAND) sizer.Add(grille_sizer, pos=(1,0)) sizer.Add(sizer2, pos=(0,1), span=(2,1), flag = wx.EXPAND) sizer.AddGrowableCol(1) self.panel.SetSizer(sizer) sizer.Fit(self)
def __init__(self, overview, data): time_format = data.config.time_format linescore = overview.linescore away = linescore.teams.away away_abbrev = data.teams_info[away.team.id].abbreviation self.away_roster = data.teams_info[away.team.id].roster home = linescore.teams.home home_abbrev = data.teams_info[home.team.id].abbreviation self.home_roster = data.teams_info[home.team.id].roster away_goal_plays = [] home_goal_plays = [] away_penalties = [] home_penalties = [] if hasattr(overview, "plays"): plays = overview.plays away_scoring_plays, away_penalty_play, home_scoring_plays, home_penalty_play = filter_plays( plays, away.team.id, home.team.id) # Get the Away Goal details # If the request to the API fails or is missing who scorer and the assists are, return an empty list of goal plays # This method is there to prevent the goal board to display the wrong info for play in away_scoring_plays: try: players = get_goal_players(play['players'], self.away_roster, self.home_roster) away_goal_plays.append(Goal(play, players)) except KeyError: debug.error( "Failed to get Goal details for current live game. will retry on data refresh" ) away_goal_plays = [] break # Get the Home Goal details # If the request to the API fails or is missing who scorer and the assists are, return an empty list of goal plays # This method is there to prevent the goal board to display the wrong info for play in home_scoring_plays: try: players = get_goal_players(play['players'], self.home_roster, self.away_roster) home_goal_plays.append(Goal(play, players)) except KeyError: debug.error( "Failed to get Goal details for current live game. will retry on data refresh" ) home_goal_plays = [] break for play in away_penalty_play: try: player = get_penalty_players(play['players'], self.away_roster) away_penalties.append(Penalty(play, player)) except KeyError: debug.error( "Failed to get Goal details for current live game. will retry on data refresh" ) away_penalties = [] break for play in home_penalty_play: try: player = get_penalty_players(play['players'], self.home_roster) home_penalties.append(Penalty(play, player)) except KeyError: debug.error( "Failed to get Goal details for current live game. will retry on data refresh" ) home_penalties = [] break self.away_team = TeamScore(away.team.id, away_abbrev, away.team.name, away.goals, away.shotsOnGoal, away_penalties, away.powerPlay, away.numSkaters, away.goaliePulled, away_goal_plays) self.home_team = TeamScore(home.team.id, home_abbrev, home.team.name, home.goals, home.shotsOnGoal, home_penalties, home.powerPlay, home.numSkaters, home.goaliePulled, home_goal_plays) self.date = convert_time(overview.game_date).strftime("%Y-%m-%d") self.start_time = convert_time( overview.game_date).strftime(time_format) self.status = overview.status self.periods = Periods(overview) self.intermission = linescore.intermissionInfo.inIntermission if data.status.is_final(overview.status) and hasattr( overview, "w_score") and hasattr(overview, "l_score"): self.winning_team = overview.w_team self.winning_score = overview.w_score self.loosing_team = overview.l_team self.loosing_score = overview.l_score
def __init__(self, data, matrix, sleepEvent): self.data = data self.matrix = matrix self.data.covid19.get_all() self.layout = self.data.config.config.layout.get_board_layout('covid_19') self.sleepEvent = sleepEvent self.sleepEvent.clear() self.time_format = self.data.config.time_format if data.config.covid_ww_board_enabled or (not data.config.covid_ww_board_enabled and not data.config.covid_country_board_enabled and not data.config.covid_us_state_board_enabled and not data.config.covid_canada_board_enabled): try: self.worldwide_data = self.data.covid19.ww self.last_update = convert_time((datetime(1970, 1, 1) + timedelta(milliseconds=self.worldwide_data['updated'])).strftime("%Y-%m-%dT%H:%M:%SZ")).strftime(self.get_time_format(self.time_format)) self.data.network_issues = False for case in self.worldwide_data: if case not in ("cases", "deaths", "recovered"): continue self.draw_count(case, self.worldwide_data[case], self.last_update, "WW") self.sleepEvent.wait(5) except ValueError as e: print("NETWORK ERROR, COULD NOT GET NEW COVID 19 DATA: {}".format(e)) self.data.network_issues = True self.last_update = datetime.now().strftime(self.get_time_format(self.time_format)) if data.config.covid_country_board_enabled: self.country = data.config.covid_country count = 0 for i in self.country: try: self.data.network_issues = False self.country_data = self.data.covid19.countrydict[self.country[count]] for case in self.country_data: if case not in ("cases", "todayCases", "deaths","todayDeaths", "recovered","critical"): continue if case == "todayDeaths": self.draw_count("Todays Deaths", self.country_data[case], self.last_update, self.country[count][0:3]) self.sleepEvent.wait(3) elif case == "todayCases": self.draw_count("Today's Cases", self.country_data[case], self.last_update, self.country[count][0:3]) self.sleepEvent.wait(3) else: self.draw_count(case, self.country_data[case], self.last_update, self.country[count][0:3]) self.sleepEvent.wait(3) except ValueError as e: print("NETWORK ERROR, COULD NOT GET NEW COVID 19 DATA: {}".format(e)) self.data.network_issues = True count += 1 if data.config.covid_us_state_board_enabled: self.us_state = data.config.covid_us_state count = 0 for i in self.us_state: try: self.data.network_issues = False self.us_state_data = self.data.covid19.us_state_dict[self.us_state[count]] for case in self.us_state_data: if case not in ("cases", "todayCases", "deaths","todayDeaths"): continue if case == "todayDeaths": self.draw_count("Todays Deaths", self.us_state_data[case], self.last_update, self.us_state[count]) self.sleepEvent.wait(3) elif case == "todayCases": self.draw_count("Today's Cases", self.us_state_data[case], self.last_update, self.us_state[count]) self.sleepEvent.wait(3) else: self.draw_count(case, self.us_state_data[case], self.last_update, self.us_state[count]) self.sleepEvent.wait(3) except ValueError as e: print("NETWORK ERROR, COULD NOT GET NEW COVID 19 DATA: {}".format(e)) self.data.network_issues = True count += 1 if data.config.covid_canada_board_enabled: self.canada_prov = data.config.covid_canada_prov count = 0 for i in self.canada_prov: try: self.data.network_issues = False self.canada_prov_data = self.data.covid19.canada_prov_dict[self.canada_prov[count]] self.canada_location = self.canada_prov_data['province'] for case in self.canada_prov_data['stats']: if case not in ("confirmed", "deaths", "recovered"): continue else: self.draw_count(case, self.canada_prov_data['stats'][case], self.last_update, self.canada_location) self.sleepEvent.wait(3) except ValueError as e: print("NETWORK ERROR, COULD NOT GET NEW COVID 19 DATA: {}".format(e)) self.data.network_issues = True count += 1
def fetch_games(): """ Function to get a list of games request stats in json form from the schedule section of the NHL API URL create a list to store all the games loop through the games received and store the info in the created list: - for each games: - the ID of the game - the link to the complete stats of that game - the Home team - the Home team score - the Away team - the Away team score - game status finally return the list of games game_list = list of all the games and the number of games. url = the location where we can find the list of games. """ url = '{0}schedule'.format(NHL_API_URL) game_list = [] try: game_data = requests.get(url) game_data = game_data.json() games = game_data['dates'][0]['games'] for game in range(len(games)): live_stats_link = game_data['dates'][0]['games'][game]['link'] game_id = int(game_data['dates'][0]['games'][game]['gamePk']) home_team_id = int(game_data['dates'][0]['games'][game]['teams'] ['home']['team']['id']) home_score = int( game_data['dates'][0]['games'][game]['teams']['home']['score']) away_team_id = int(game_data['dates'][0]['games'][game]['teams'] ['away']['team']['id']) away_score = int( game_data['dates'][0]['games'][game]['teams']['away']['score']) game_status = int( game_data['dates'][0]['games'][0]['status']['statusCode']) game_time = convert_time(game_data["dates"][0]["games"][game] ["gameDate"]).strftime("%I:%M") gameInfo = { "gameid": game_id, "full_stats_link": live_stats_link, "home_team_id": home_team_id, "home_score": home_score, "away_team_id": away_team_id, "away_score": away_score, 'game_status': game_status, 'game_time': game_time } game_list.append(gameInfo) return game_list except requests.exceptions.RequestException: print("Error encountered, Can't reach the NHL API") return 0 except IndexError: print("No Game today") return game_list
def expected_time(self): cur_state = self.cur_state_index return self.start_time + datetime.timedelta( *convert_time(self.config[cur_state][0]))
def _extract_table(self, html): '''parse html page and process the calendar table intermediate python structure (event list) is returned''' soup = BeautifulSoup(html) tables = soup.html.body.findAll(name='table',recursive=False) #jump to the calendar table cal = tables[1] lines = cal.findAll(name='tr',recursive=False) #isolate first tab line with hours hours_line = lines[0].findAll(name='td',recursive=False) hours = [] for h in hours_line[1:]: if h.string: hours.append(convert_time(h.string)) else: last_added_hour = hours[-1] hours.append(datetime(last_added_hour.year, last_added_hour.month, last_added_hour.day, last_added_hour.hour, 30)) #process all lines #search the number of row for that day n_rows = [] for (no_line,line) in enumerate(lines[1:]): slots = line.findAll(name='td',recursive=False) #search the number of row for that day if slots[0].has_key('rowspan'): n_rows.append(int(slots[0]['rowspan'])) else: n_rows.append(0) event_list = [] day = -1 n = 0 for (no_line,line) in enumerate(lines[1:]): if not n: n = n_rows[no_line] day += 1 current_time = -1 else: current_time = 0 n -= 1 slots = line.findAll(name='td',recursive=False) for s in slots: cell = s.findAll(name='table',recursive=False) # event found if len(cell)>1: event_data = { 'day': day, 'start_time': hours[current_time], 'duration': int(s['colspan']) } #duration in hours is extract from the colspan #compute end time (1 colspan=1/2 hour) delta = timedelta(hours=event_data['duration']/2) event_data['stop_time'] = hours[current_time]+delta td = cell[0].tr.findAll(name='td',recursive=False) # Gehol weeks when the event occurs event_data['weeks'] = split_weeks(td[0].contents[0].string) # location event_data['location'] = td[1].contents[0].string if not event_data['location']: event_data['location'] = '' # activity event_data['type'] = cell[1].tr.td.contents[0].string current_time = current_time + event_data['duration'] event_data['organizer'] = "" event_data['title'] = "%s - %s" % (self.metadata['mnemo'], self.metadata['title']) course_event = CourseEvent(**event_data) event_list.append(course_event) else: current_time += 1 return event_list
def __init__(self, parent, app, title) : super().__init__(parent=None, title=title, size=(1000, 800)) # wx.Frame.__init__(self, parent, title=title) self.app = app s = self.app.settings self.SetIcon(wx.Icon(app.settings["files_icone"], wx.BITMAP_TYPE_ICO)) self.panel = wx.Panel(self) self.max_props = app.settings["max_props"] self.tour = 0 fill = s["size_fill"] self.Bind(wx.EVT_CLOSE, self.exit) #Creation et dessin du timer timer_sizer = self.cree_box_sizer("Temps") self.timer = wx.StaticText(self.panel, -1, str(utils.convert_time(0))) font = wx.Font(s["size_font_chrono"], wx.SWISS, wx.NORMAL, wx.NORMAL) self.timer.SetFont(font) timer_sizer.Add(self.timer, 0, wx.ALL|wx.EXPAND, fill) #Creation et dessin du tirage self.tirage = tirage.tirage(self.panel, self.app) tirage_sizer = self.cree_box_sizer("Tirage") tirage_sizer.Add((fill,0),0) tirage_sizer.Add(self.tirage, 1, wx.ALL|wx.EXPAND, fill) tirage_sizer.Add((fill,0),0) #Creation et dessin de la grille self.grille = grille.grille(self.panel, self.app) grille_sizer = self.cree_box_sizer("Grille") grille_sizer.Add(self.grille, 0, wx.ALL|wx.EXPAND, 0) #Creation des items dans la box messages msgs_sizer = self.cree_box_sizer("Messages") self.msgs = wx.TextCtrl(self.panel, -1, "", size=(app.settings["size_chat_size"], -1), style=wx.TE_MULTILINE|wx.TE_READONLY) # self.set_police_msgs(s["size_font_msgs"]) msgs_sizer.Add(self.msgs, 1, wx.ALL|wx.EXPAND, fill) #Creation box proposition props_sizer = self.cree_box_sizer("Propositions", flag = wx.HORIZONTAL) self.props = wx.ComboBox(self.panel, -1, style=wx.CB_READONLY) props_sizer.Add(self.props, 1, wx.ALL, fill) self.buttonpose = wx.Button(self.panel, -1, "Poser", size=app.settings["size_button"]) self.buttonpose.Enable(False) self.buttonpose.SetDefault() # important pour Windows pour capter la touche Entrée props_sizer.Add(self.buttonpose, 0, wx.ALL|wx.ALIGN_RIGHT, fill) self.props.Bind(wx.EVT_COMBOBOX, self.props_click, self.props) self.buttonpose.Bind(wx.EVT_BUTTON, self.pose, self.buttonpose) self.buttonpose.Bind(wx.EVT_KEY_DOWN, self.app.OnKey) #Creation box score score_sizer = self.cree_box_sizer("Score", flag = wx.HORIZONTAL) self.score = wx.StaticText(self.panel, -1, "") font = wx.Font(s["size_font_score"], wx.SWISS, wx.NORMAL, wx.NORMAL) self.score.SetFont(font) score_sizer.Add(self.score, 1, wx.ALL, fill) buttscore = wx.Button(self.panel, -1, "Scores", size=app.settings["size_button"]) score_sizer.Add(buttscore, 0, wx.ALL|wx.ALIGN_RIGHT, fill) buttscore.Bind(wx.EVT_BUTTON, self.show_score, buttscore) #Creation du chat chat_sizer = self.cree_box_sizer("Chat", flag = wx.HORIZONTAL) self.txtchatin = wx.TextCtrl(self.panel, -1, "", style=wx.TE_PROCESS_ENTER) chat_sizer.Add(self.txtchatin,1, wx.ALL, fill) self.txtchatin.Bind(wx.EVT_TEXT_ENTER, self.chat_enter, self.txtchatin) # cadres boutons bouton_sizer = self.cree_box_sizer("Commandes", flag = wx.HORIZONTAL) #box = wx.StaticBox(self.panel, label = "Commandes") boutons = [ ("Restart", self.button_restart), ("Alpha", self.button_alpha), ("Random", self.button_random), ("Next", self.button_next), ("Précédent", self.button_pose_last), ] if s["user_admin"] : boutons.insert(3, ("Chrono", self.button_chrono)) bouton_in_sizer = wx.GridSizer(rows=1, cols=len(boutons), hgap=fill, vgap=fill) for label, handler in boutons : bouton = wx.Button(self.panel, label=label, size=app.settings["size_button"]) bouton_in_sizer.Add(bouton, flag = wx.ALIGN_CENTER) bouton.Bind(wx.EVT_BUTTON, handler, bouton) bouton_sizer.Add(bouton_in_sizer, proportion=1, flag = wx.EXPAND) #Barre de menu if s["view_menu"] : menubar = wx.MenuBar() menu1 = wx.Menu() menu1.Append(101,"Quitter\tCtrl-Q") self.Bind(wx.EVT_MENU, self.app.exit, id=101) menubar.Append(menu1,"Fichier") menupol = wx.Menu() for i in range(8,14) : menupol.Append(200+i,str(i),"Changer la police des messages serveur", wx.ITEM_RADIO) self.Bind(wx.EVT_MENU, self.menu_police, id=200+i) pset = s["size_font_msgs"] menupol.Check(200+pset, True) self.set_police_msgs(pset) menu2 = wx.Menu() menu2.Append(299,"Taille police", menupol) menubar.Append(menu2,"Options") menu3 = wx.Menu() menu3.Append(301,"A propos") menubar.Append(menu3,"Aide") self.Bind(wx.EVT_MENU, self.about, id=301) self.SetMenuBar(menubar) #Barre de status if s["view_status"] : self.st = self.CreateStatusBar() self.st.SetFieldsCount(4) self.st.SetStatusWidths(s['size_status']) self.set_status_next(0) self.set_status_restart(0) #Sizers sizer1 = wx.BoxSizer(wx.HORIZONTAL) sizer2 = wx.BoxSizer(wx.VERTICAL) sizer2.Add(msgs_sizer, 1, wx.EXPAND) sizer2.Add(props_sizer, 0, wx.EXPAND) sizer2.Add(score_sizer, 0, wx.EXPAND) sizer2.Add(bouton_sizer, 0, wx.EXPAND) sizer2.Add(chat_sizer, 0, wx.EXPAND) sizer2.Add( (fill,fill), 0) sizer = wx.GridBagSizer(hgap=fill, vgap=fill) if s["view_layout"] == "alt" : sizer1.Add(tirage_sizer, 1, flag = wx.EXPAND) sizer1.Add( (fill,fill)) sizer1.Add(timer_sizer, flag = wx.EXPAND) sizer.Add(grille_sizer, pos=(0,0)) sizer2.Add(sizer1, flag = wx.EXPAND) sizer.Add(sizer2, pos=(0,1), flag = wx.EXPAND) sizer.AddGrowableCol(1) else : sizer1.Add(timer_sizer, flag = wx.EXPAND) sizer1.Add((fill,fill)) sizer1.Add(tirage_sizer, 1, flag = wx.EXPAND) sizer.Add(sizer1, pos=(0,0), flag = wx.EXPAND) sizer.Add(grille_sizer, pos=(1,0)) sizer.Add(sizer2, pos=(0,1), span=(2,1), flag = wx.EXPAND) sizer.AddGrowableCol(1) self.panel.SetSizer(sizer) sizer.Fit(self)