def getMatchesInCompetition(stage = None, competitionID = None): if competitionID: response = Match.getByCompetitionID(competitionID) else: response = Match.all() all_matches = {} aux = [] if stage is not None: aux = [match for match in response if match['round'] == int(stage) or match['round'] == int(stage)+1] else: aux = response response = aux for match in response: r = match['round'] match['result'] = Result.getByMatchID(match['match_id']) if r not in all_matches.keys(): all_matches[r] = [] # match['offset'] = 2**(match['round'] - 1) - 1 # match['height'] = 2**match['round'] - 1 # match['offset'] = 2**(len(all_matches) - 1) - 1 # match['height'] = 2**len(all_matches) - 1 match['offset'] = 2**(len(all_matches) - 1) - 1 match['height'] = len(all_matches)**2 - len(all_matches) all_matches[r].append(match) return prepare_response(all_matches)
def lineparse_statlog_start(line: Text, match: models.Match): match.data_version = line[1] match.mapname = line[2] match.start_datetime = format_timestamp(line[3]) match.end_datetime = format_timestamp(line[4]) match.round_length = (match.end_datetime - match.start_datetime).total_seconds()
def create_from_json(match_json): utc = pytz.UTC match = Match( match_id=match_json['match_id'], match_seq_num=match_json['match_seq_num'], radiant_win=match_json['radiant_win'], duration=match_json['duration'], #pylint: disable=no-value-for-parameter start_time=utc.localize(datetime.datetime.fromtimestamp(match_json['start_time'])), patch=match_json['patch'], tower_status_radiant=match_json['tower_status_radiant'], tower_status_dire=match_json['tower_status_dire'], barracks_status_radiant=match_json['barracks_status_radiant'], barracks_status_dire=match_json['barracks_status_dire'], cluster=match_json['cluster'], first_blood_time=match_json['first_blood_time'], lobby_type=LOBBY_TYPES[match_json['lobby_type']], human_players=match_json['human_players'], leagueid=match_json['leagueid'], game_mode=GAME_MODES[match_json['game_mode']], flags=match_json['flags'], engine=match_json['engine'], radiant_score=match_json['radiant_score'], dire_score=match_json['dire_score'], skill=match_json['skill'] ) match.save() for slot_json in match_json['players']: create_slot_from_json(slot_json, match) return match
def test_hook_update_comment_count(self): t = datetime.now().timetuple() seconds = local_to_utc(t) match = Match.find_match_by_id(4685) if match is not None: match.date = seconds + 100 match.reportTime = seconds + 200 match.disputeTime = seconds + 300 match.source_id = 3 else: match = Match(id=4685, public=1, date=seconds + 100, reportTime=seconds + 200, disputeTime=seconds + 300, source_id=3) db.session.add(match) db.session.commit() # Test email is null with self.client: params = {"commentNumber": 8, "objectId": 'outcome_id_4685'} response = self.client.post('/hook/comment-count', data=json.dumps(params), content_type='application/json') data = json.loads(response.data.decode()) self.assertTrue(data['status'] == 1)
def parse(filepath: Text, filename: Text) -> bool: f = open(filepath, 'r+') js = json.load(f) f.close() try: m = Match() db.add(m) m.parsed_file = filename # Okay let's get started parse_matchdata(js, m) parse_deaths(js, m) parse_survivors(js, m) parse_uplink_buys(js, m) parse_explosions(js, m) parse_antag_objectives(js, m) parse_badass_buys(js, m) parse_population_snapshots(js, m) db.commit() except: db.rollback() raise return True
def create_match(): """Create a new match instance.""" json_data = request.get_json() if not json_data: return jsonify({'error': 'No required input data provided.'}), 400 data, errors = Match.from_dict(json_data) if errors: return jsonify(errors), 400 # Create new match match = Match(data) # Update players data # FIXME: improve updating players for player in data.get('players'): match_player = Scoreboard(player_data=player, match_id=match.id) player_for_upd = db.session.query(Player).filter( Player.nickname == player.get('nickname')).with_for_update().one() player_for_upd.kills += player.get('kills') player_for_upd.deaths += player.get('deaths') player_for_upd.assists += player.get('assists') match.players.append(match_player) db.session.commit() response = match.to_dict() return jsonify(response), 201
def form_valid(self, form): data = form.cleaned_data requeriment = Requirement.objects.get(id=self.kwargs['requeriment_id']) requeriment.name = data['name_item'] requeriment.description = data['description'] common_user = self.object.commonuser common_user.cpf = data['cpf'] common_user.phone = data['phone'] common_user.anonymous = data['anonymous'] common_user.save() new_item = Item(owner=self.request.user, description=requeriment.description, name_item=requeriment.name) new_item.save() new_object = Object(item=new_item, type=requeriment.type) new_object.save() messages.success(self.request, "Novo Objeto cadastrado com sucesso!") match = Match(requirement=requeriment, item=new_item) match.save() notification = Notification(user=requeriment.owner, match=match) notification.save() donation = Donation( donator=self.request.user, institute=requeriment.owner, item=new_item, data=datetime.datetime.today().strftime('%Y-%m-%d'), is_completed=False) donation.save() messages.success(self.request, 'Muito Obrigado pela sua Doação!') return super(DonatorRequerimentView, self).form_valid(form)
def setUp(self): # create match match = Match.find_match_by_id(1) if match is None: match = Match(id=1) db.session.add(match) db.session.commit()
def load_matches(): with open('app/matches.json') as data_file: matches_data = json.load(data_file) print('Preparing and validating match data sets...', end='', flush=True) prep_datas = [] for match_data in matches_data: prep_data = { 'id': match_data['match'], 'datetime': match_data['when'], 'finished': True if match_data['closed'] == '1' else False, 'event': match_data['event'], 'bestof': match_data['format'], } prep_data['team1'], _ = Team.objects.get_or_create( name=match_data['a']) prep_data['team2'], _ = Team.objects.get_or_create( name=match_data['b']) if match_data['winner'] == 'a': prep_data['winner'] = prep_data['team1'] elif match_data['winner'] == 'b': prep_data['winner'] = prep_data['team2'] match = Match(**prep_data) match.full_clean() prep_datas.append(prep_data) print('Ok') print('{} matches prepared'.format(len(prep_datas))) print('Creating matches...', end='', flush=True) for prep_data in prep_datas: Match.objects.create(**prep_data) print('Ok')
def search_matches(**kwargs): reqs = Requirement.objects.filter(status=True) for req in reqs: if req.type == kwargs['type']: match = Match(requirement=req, item=Item.objects.get(id=kwargs['pk_item'])) match.save() notification = Notification(user=req.owner, match=match) notification.save()
def test_bettor_won(self): # BETTOR WON match3 = self.u1.list_matches()[0] match4 = self.u1.list_matches()[1] match3.committed = True match4.committed = True db.session.add(match3) db.session.add(match4) db.session.commit() for m in self.u1.list_matches()[0:2]: if Match.predicted_winner( user=self.u1, match=m.match).team_winner_id == m.match.actual_winner: # user guessed it correctly self.assertTrue(m.bettor_won, 'User predicted match result correctly') else: self.assertFalse( m.bettor_won, 'User has not predicted match result correctly') # change the settings so user predicts draw match_specific_settings = [0.6, 0.3, 0.1] mss1 = ModuleUserMatchSettings(user_id=self.u1.id, match_id=match4.match.id, module_id=1, weight=match_specific_settings[0]) mss2 = ModuleUserMatchSettings(user_id=self.u1.id, match_id=match4.match.id, module_id=2, weight=match_specific_settings[1]) mss3 = ModuleUserMatchSettings(user_id=self.u1.id, match_id=match4.match.id, module_id=3, weight=match_specific_settings[2]) db.session.add(mss1) db.session.add(mss2) db.session.add(mss3) db.session.commit() for m in self.u1.list_matches()[0:2]: if Match.predicted_winner( user=self.u1, match=m.match).team_winner_id == m.match.actual_winner: # user guessed it correctly self.assertTrue(m.bettor_won, 'User predicted match result correctly') else: self.assertFalse( m.bettor_won, 'User has not predicted match result correctly')
def check_results(matchID = None): if matchID is None: matches = Match.all() else: matches = Match.getById(matchID) for match in matches: match['results'] = Result.getByMatchID(match['match_id']) calculate_winner(match['player_a'], match['player_b'], match['results'], match['match_id']) return prepare_response(True)
def deploy(): """Deployment tasks""" #migrate database to latest revision upgrade() #create user roles Role.insert_roles() #insert matches from the data file Team.insert_teams() #insert modules PredictionModule.insert_modules() #insert matches from the data file Match.update_all_matches()
def test_match_specific_prediction_settings(self): # TESTING MATCH SPECIFIC USER CONFIGURATION # TESTCASE-1 USER HAS ONLY MATCH SETTINGS match_specific_settings = [0.11, 0.38, 0.51] match1 = self.u1.list_matches()[0].match u1 = self.u1 mss1 = ModuleUserMatchSettings(user_id=self.u1.id, match_id=match1.id, module_id=1, weight=match_specific_settings[0]) mss2 = ModuleUserMatchSettings(user_id=self.u1.id, match_id=match1.id, module_id=2, weight=match_specific_settings[1]) mss3 = ModuleUserMatchSettings(user_id=self.u1.id, match_id=match1.id, module_id=3, weight=match_specific_settings[2]) db.session.add(mss1) db.session.add(mss2) db.session.add(mss3) db.session.commit() self.assertEqual(len(u1.list_match_specific_settings(match_id=match1.id)), 3, "Length of the list containing match specific settings is equal to 3") for i in range(0, len(match_specific_settings)): self.assertEqual(ModuleUserMatchSettings.query.filter_by(user_id=self.u1.id).all()[i].weight, match_specific_settings[i], "Check that the match specific values are in database") # Check that for the calculation are used match specific settings probability = match1.prediction_league_position * mss1.weight \ + match1.prediction_form * mss2.weight \ + match1.prediction_homeaway * mss3.weight self.assertAlmostEqual(probability, Match.predicted_winner(match1, u1).probability) # TESTCASE-2 USER HAS BOTH USER DEFAULT AND MATCH SPECIFIC SETTINGS # default configuration user_default_settings = [0.12, 0.32, 0.56] us1 = ModuleUserSettings(user_id=self.u1.id, module_id=1, weight=user_default_settings[0]) us2 = ModuleUserSettings(user_id=self.u1.id, module_id=2, weight=user_default_settings[1]) us3 = ModuleUserSettings(user_id=self.u1.id, module_id=3, weight=user_default_settings[2]) db.session.add(us1) db.session.add(us2) db.session.add(us3) db.session.commit() for i in range(0, len(user_default_settings)): self.assertEqual(ModuleUserSettings.query.filter_by(user_id=self.u1.id).all()[i].weight, user_default_settings[i], "Check that the user default weights are in database") self.assertEqual(len(u1.list_prediction_settings()), 3, "List user default prediction settings is not empty") # Check that for the calculation are still used match specific settings, as they have priority self.assertAlmostEqual(probability, Match.predicted_winner(match1, u1).probability)
def match_edit(id): match = Match.query.filter_by(id=id).first() form = EditMatchForm(match=match) all_teams = Team.query.order_by(Team.name).all() team_choices = [('', '-Select Opponent-')] + [(t.name, t.name) for t in all_teams] form.opponent.choices = team_choices all_matches = Match.query.order_by(Match.date).all() if form.submit_new.data and form.validate(): newmatch = Match( date=form.date.data, opponent=Team.query.filter_by(name=form.opponent.data).first(), home_away=form.home_away.data, match_type=form.match_type.data) newmatch.set_location() db.session.add(newmatch) db.session.commit() flash('Match {} {} {} added!'.format(newmatch.date, form.opponent.data, form.home_away.data)) return redirect(url_for('main.match_edit')) if form.submit_edit.data and form.validate() and match is not None: match.date = form.date.data match.opponent = Team.query.filter_by(name=form.opponent.data).first() match.home_away = form.home_away.data match.match_type = form.match_type.data match.set_location() db.session.add(match) db.session.commit() flash('Match {} {} {} modified!'.format(form.date.data, form.opponent.data, form.home_away.data)) return redirect(url_for('main.match_edit', id=match.id)) if form.submit_delete.data and match is not None: match.delete_all_games() db.session.delete(match) db.session.commit() flash( 'Match {} {} {} and all associated games deleted!'.format( form.date.data, form.opponent.data, form.home_away.data), 'danger') return redirect(url_for('main.match_edit')) if request.method == 'GET' and match is not None: form.load_match(match) return render_template('edit_match.html', title='Match Editor', form=form, match=match, all_matches=all_matches)
def __store_to_db(self, content): try: Match.objects.get( external_identifier=content['external_identifier']) except Match.DoesNotExist: match_to_add = Match( external_identifier=content['external_identifier'], home_team_external_id=content['home_team_external_id'], away_team_external_id=content['away_team_external_id'], home_team_goals=content['home_team_goals'], away_team_goals=content['away_team_goals']) match_to_add.save()
def setup(self): app.config['TESTING'] = True app.config['CSRF_ENABLED'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'test.db') self.app = app.test_client() db.create_all() u1 = User(nickname='amy', email='*****@*****.**') u2 = User(nickname='bob', email='*****@*****.**') u3 = User(nickname='cat', email='*****@*****.**') self.users = [u1, u2, u3] self.games = [Match(name='one'), Match(name='two')]
def lineparse_cultstats(line: Text, match: models.Match): match.cult_runes_written = line[1] match.cult_runes_fumbled = line[2] match.cult_runes_nulled = line[3] match.cult_converted = line[4] match.cult_tomes_created = line[5] match.cult_narsie_summoned = truefalse(line[6]) match.cult_narsie_corpses_fed = line[7] match.cult_surviving_cultists = line[8] match.cult_deconverted = line[9]
def setUp(self): # create contract contract = Contract.find_contract_by_id(1) if contract is None: contract = Contract(id=1, contract_name="contract1", contract_address="0x123", json_name="name1") db.session.add(contract) db.session.commit() # create match match = Match.find_match_by_id(1) if match is None: match = Match(id=1) db.session.add(match) db.session.commit() # create user user = User.find_user_with_id(88) if user is None: user = User(id=88) db.session.add(user) db.session.commit() user = User.find_user_with_id(99) if user is None: user = User(id=99) db.session.add(user) db.session.commit() user = User.find_user_with_id(66) if user is None: user = User(id=66) db.session.add(user) db.session.commit() # create outcome outcome = Outcome.find_outcome_by_id(88) if outcome is None: outcome = Outcome(id=88, match_id=1, hid=88, contract_id=contract.id) db.session.add(outcome) db.session.commit() else: outcome.contract_id = contract.id
def test_user_default_prediction_settings(self): # TESTING USER DEFAULT CONFIGURATION self.assertTrue(self.u1.list_matches(), 'User saved matches to the dashboard') match1 = self.u1.list_matches()[0].match user_default_settings = [0.12, 0.32, 0.56] # user default settings us1 = ModuleUserSettings(user_id=self.u1.id, module_id=1, weight=user_default_settings[0]) us2 = ModuleUserSettings(user_id=self.u1.id, module_id=2, weight=user_default_settings[1]) us3 = ModuleUserSettings(user_id=self.u1.id, module_id=3, weight=user_default_settings[2]) db.session.add(us1) db.session.add(us2) db.session.add(us3) db.session.commit() for i in range(0, len(user_default_settings)): self.assertEqual(ModuleUserSettings.query.filter_by(user_id=self.u1.id).all()[i].weight, user_default_settings[i], "Check that the user default values are in database") # Check that for the calculation are used user default settings probability = match1.prediction_league_position * us1.weight \ + match1.prediction_form * us2.weight \ + match1.prediction_homeaway * us3.weight self.assertAlmostEqual(probability, Match.predicted_winner(match1, self.u1).probability)
def create_match(): creating_match = True form = MatchForm() if form.validate_on_submit(): match = Match( home_team=form.home_team.data, guest_team=form.guest_team.data, home_points=form.home_points.data, guest_points=form.guest_points.data, ) try: db.session.add(match) db.session.commit() flash("Partida cadastrada com sucesso!", "success") except Exception as e: flash(f"{e}", "error") db.session.rollback() finally: db.session.close() return redirect(url_for("admin.matchs")) return render_template("admin/matchs/match.html", form=form, creating_match=creating_match, title="Cadastrar partida")
def test_user_hunch_module_contrib_to_draw(self): # TEST user hunch contrib to DRAW u1 = self.u1 match1 = self.u1.list_matches()[0] match2 = self.u1.list_matches()[1] match1.committed = True match2.committed = True db.session.add(match1) db.session.add(match2) db.session.commit() match_specific_settings = [0.0, 0.0, 0.0, 1.0] mss1 = ModuleUserMatchSettings(user_id=u1.id, match_id=match1.match.id, module_id=1, weight=match_specific_settings[0]) mss2 = ModuleUserMatchSettings(user_id=u1.id, match_id=match1.match.id, module_id=2, weight=match_specific_settings[1]) mss3 = ModuleUserMatchSettings(user_id=u1.id, match_id=match1.match.id, module_id=3, weight=match_specific_settings[2]) mss4 = ModuleUserMatchSettings(user_id=u1.id, match_id=match1.match.id, module_id=4, weight=match_specific_settings[3]) db.session.add(mss1) db.session.add(mss2) db.session.add(mss3) db.session.add(mss4) db.session.commit() # module user hunch changed the result to draw self.assertEqual(Match.predicted_winner(match1.match, u1).team_winner_id, -1, 'User hunch contributed to Draw result')
def post(self, community): if 'teams' not in request.json: return { "message" : "missing required dict: teams"}, 400 teams = request.json['teams'] if not isinstance(teams, list): return { "message" : "missing required dict: teams"}, 400 if len(teams) != 2: return { "message" : "incorrect number of teams"}, 400 team0 = TeamService.find_or_create(community, teams[0]) if team0 is None: return { "message" : "teams[0]: not found"}, 400 team1 = TeamService.find_or_create(community, teams[1]) if team1 is None: return { "message" : "teams[1]: not found"}, 400 if team0.id == team1.id: return { "message" : "teams are the same"}, 400 match = Match.create(community, team0, team1) db.session.add(match) db.session.commit() return match.serialize
def createTournament(name, set, entities, typeLiteral): type = getTypeFromLiteral(typeLiteral) newTournament = Tournament(name=name, set_id=set, date=date.today(), type=type) db.session.add(newTournament) db.session.commit() for idx, pairing in enumerate(combinations(entities, 2)): newMatch = Match(tournament_id=newTournament.id) db.session.add(newMatch) db.session.commit() db.session.add( MatchParticipant(match_id=newMatch.id, entity_id=pairing[0], game_wins=0)) db.session.add( MatchParticipant(match_id=newMatch.id, entity_id=pairing[1], game_wins=0)) db.session.commit() rebuildStatistics(newTournament.id)
def test_add_outcome(self): t = datetime.now().timetuple() seconds = local_to_utc(t) arr_match = [] Uid = 66 source1 = Source.find_source_by_id(1) if source1 is None: source1 = Source(id=1, name="Source", url="htpp://www.abc.com", approved=1) db.session.add(source1) db.session.commit() match = Match(public=1, date=seconds + 100, reportTime=seconds + 200, disputeTime=seconds + 300, source_id=source1.id) arr_match.append(match) db.session.add(match) db.session.commit() with self.client: params = [{ "name": "outcome test", "match_id": match.id, "hid": 88 }] response = self.client.post('/outcome/add/{}'.format(match.id), data=json.dumps(params), content_type='application/json', headers={ "Uid": "{}".format(Uid), "Fcm-Token": "{}".format(123), "Payload": "{}".format(123), }) data = json.loads(response.data.decode()) self.assertTrue(data['status'] == 1) data_json = data['data'] self.assertTrue( data_json[0]['approved'] == CONST.OUTCOME_STATUS['PENDING']) response = self.client.get('/match/{}'.format(match.id), content_type='application/json', headers={ "Uid": "{}".format(Uid), "Fcm-Token": "{}".format(123), "Payload": "{}".format(123), }) data = json.loads(response.data.decode()) self.assertTrue(data['status'] == 1) data_json = data['data'] self.assertTrue(len(data_json['outcomes']) == 0) for item in arr_match: db.session.delete(item) db.session.commit()
def match(): try: candidate_ids = session['candidates'] role_ids = session['roles'] except KeyError: # return redirect(url_for('matching.trial')) cands = Candidate.query.all() roles = Role.query.all() requested_data = 50 candidate_ids = random.sample([c.id for c in cands], requested_data) role_ids = random.sample([r.id for r in roles], int(requested_data*1.5)) ag = Algorithm(weighted_dict={'location': 5, 'skills': 10, 'private office': 10, 'organisation': 5}, candidate_ids=candidate_ids, role_ids=role_ids) candidates = Candidate.query.filter(Candidate.id.in_(candidate_ids)).all() roles = Role.query.filter(Role.id.in_(role_ids)).all() matches = [Match(r, c) for r in roles for c in candidates] sorted_matches = sorted(matches, key=lambda m: m.role_id) m = munkres.Munkres() table_of_objects = [sorted_matches[i:i + len(roles)] for i in range(0, len(matches), len(roles))] table_of_totals = [[sys.maxsize - m.total for m in row] for row in table_of_objects] best_match_indices = m.compute(table_of_totals) best_matches = [table_of_objects[row][column] for row, column in best_match_indices] aggregate = sum([m.total for m in best_matches]) totals = [m.total for m in best_matches] median_average = "{:.1%}".format(statistics.median(totals)/50) return render_template('matching/match.html', aggregate=aggregate, matches=best_matches, average=median_average)
def test_report_match(self): self.clear_data_before_test() t = datetime.now().timetuple() seconds = local_to_utc(t) match = Match.find_match_by_id(1) if match is not None: match.date = seconds - 1000 match.reportTime = seconds + 1000 match.disputeTime = seconds + 2000 with self.client: response = self.client.post( 'admin/match/report/1', headers={ "Authorization": "Bearer {}".format( create_access_token(identity=app.config.get("EMAIL"), fresh=True)), "Uid": "{}".format(1000), "Fcm-Token": "{}".format(123), "Payload": "{}".format(123), }) data = json.loads(response.data.decode()) self.assertTrue(data['status'] == 0)
def review_market(market_id): """ " Admin approve/reject user market. """ try: data = request.json outcome_id = data.get("outcome_id", -1) status = data.get("status", CONST.OUTCOME_STATUS['APPROVED']) match = None if outcome_id == -1: match = Match.find_match_by_id(market_id) if match is not None: for o in match.outcomes: if o.approved == CONST.OUTCOME_STATUS['PENDING'] and o.hid is None: o.approved = status db.session.flush() if status == CONST.OUTCOME_STATUS['APPROVED']: task = admin_bl.add_create_market_task(match) if task is not None: db.session.add(task) db.session.flush() else: return response_error(MESSAGE.CONTRACT_EMPTY_VERSION, CODE.CONTRACT_EMPTY_VERSION) else: send_email_event_verification_failed.delay(match.id, match.created_user_id) else: return response_error(MESSAGE.MATCH_NOT_FOUND, CODE.MATCH_NOT_FOUND) else: outcome = db.session.query(Outcome).filter(and_(Outcome.id==outcome_id, Outcome.match_id==market_id)).first() if outcome is None: return response_error(MESSAGE.OUTCOME_INVALID, CODE.OUTCOME_INVALID) if outcome.approved == CONST.OUTCOME_STATUS['PENDING'] and outcome.hid is None: outcome.approved = status db.session.flush() match = outcome.match if status == CONST.OUTCOME_STATUS['APPROVED']: task = admin_bl.add_create_market_task(match) if task is not None: db.session.add(task) db.session.flush() else: return response_error(MESSAGE.CONTRACT_EMPTY_VERSION, CODE.CONTRACT_EMPTY_VERSION) else: send_email_event_verification_failed.delay(match.id, match.created_user_id) else: return response_error(MESSAGE.MATCH_HAS_BEEN_REVIEWED, CODE.MATCH_HAS_BEEN_REVIEWED) db.session.commit() return response_ok(match.to_json()) except Exception, ex: db.session.rollback() return response_error(ex.message)
def make_new_match(winners, losers, w_score, l_score, importance, user_creating_match=None): approved_winner, approved_loser = False, False if user_creating_match in winners: approved_winner = True elif user_creating_match in losers: approved_loser = True match = Match(winner_score=w_score, loser_score=l_score, importance=importance, approved_winner=approved_winner, approved_loser=approved_loser) db.session.add(match) db.session.flush() for w in winners: user_match = UserMatch(user=w, match=match, win=True) db.session.add(user_match) for l in losers: user_match = UserMatch(user=l, match=match, win=False) db.session.add(user_match) db.session.flush() update_match_ratings(match) db.session.commit() return match
def get_server_matches(endpoint): """Return all existing matches for a specify server.""" page = request.args.get('page', 1, type=int) matches = Match.get_server_matches(endpoint) response = paginate_response(matches, page) return jsonify(response), 200
def get_player_matches(nickname): """Retrieve player matches from database.""" page = request.args.get('page', 1, type=int) matches = Match.get_player_matches(nickname) response = paginate_response(matches, page) return jsonify(response), 200
def save(): if isSession(): email = session.get('username') user_id = session.get('user_id') if request.method == 'POST': company = request.form['company'] location = request.form['location'] location_cn = request.form['location_cn'] introduce = request.form['introduce'] service = request.form.getlist('service') service_cn = request.form.getlist('service_cn') service_cnn = '' topics = request.form.getlist('topic') for ser in service_cn: service_cnn = (service_cnn + ser) + ',' dbcnn() cursor = g.cnn.cursor() try: sql = "update userinfo set company=%s, location=%s, service=%s, introduce=%s where email=%s" data = (company, location_cn, service_cnn, introduce, email) cursor.execute(sql, data) g.cnn.commit() db.session.query(Match).filter_by(sup_id=user_id).delete() db.session.commit() service.append(location) for ser in service: for topic in topics: db.session.add(Match(user_id, int(ser), int(topic))) db.session.commit() except Exception as e: print('update error!{}'.format(e)) return redirect(url_for('auth.index')) return redirect(url_for('auth.login'))
def generateResults(stage = None): response = Match.all() results = [] for match in response: if match['round'] == int(stage): if match['player_a'] == str(-1) or match['player_b'] == str(-1): continue set_count = 0 w_a = 0 w_b = 0 while set_count < match['sets']: set_count += 1 result = generate_result() if result[0] > result[1]: w_a += 1 else: w_b += 1 r = Result(match_id = match['match_id'], set_id = set_count, result_a = result[0], result_b = result[1]) results.append(r.serialize()) db.session.add(r) if w_a == 3 or w_b == 3: break try: db.session.commit() except: print sys.exc_info() return prepare_response(None, "Error while inserting") return prepare_response(True)
def is_exceed_closing_time(match_id): match = Match.find_match_by_id(match_id) if match.date is not None: t = datetime.now().timetuple() seconds = local_to_utc(t) if seconds > match.date: return True return False
def get_match(id): """Return single match instance in JSON representation.""" match = Match.get(id) if match is None: return jsonify({'message': 'Match instance could not be found.'}), 404 response = match.to_dict() return jsonify(response), 200
def user_subscribe(): """ " 3 use cases: " Popup subscribe email will appear after user plays on match_id. " Popup subscribe email will appear at the first time. " Popup subscribe email will apear when user click on referral link. """ try: data = request.json if data is None: return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA) if 'email' not in data or is_valid_email(data["email"]) is False: return response_error(MESSAGE.USER_INVALID_EMAIL, CODE.USER_INVALID_EMAIL) if user_bl.is_email_subscribed(data['email']): return response_error(MESSAGE.EMAIL_ALREADY_SUBSCRIBED, CODE.EMAIL_ALREADY_SUBSCRIBED) match = Match.find_match_by_id(data.get('match_id', -1)) email = data["email"] uid = int(request.headers["Uid"]) referral_code = data.get('referral_code', None) user = User.find_user_with_id(uid) user.email = email user.is_user_disable_popup = 0 user.is_subscribe = 1 if referral_code is not None: r = Referral.find_referral_by_code(referral_code) if r is not None and r.user_id != uid: user.invited_by_user = r.user_id db.session.flush() # issue referral code for user if any referral_bl.issue_referral_code_for_user(user) db.session.commit() # send email result, code_1, code_2 = user_bl.claim_redeem_code_for_user(user) if result: subscribe_email_to_claim_redeem_code.delay( email, code_1, code_2, request.headers["Fcm-Token"], request.headers["Payload"], uid) elif match is not None: subscribe_email.delay(email, match.id, request.headers["Fcm-Token"], request.headers["Payload"], uid) return response_ok(user.to_json()) except Exception, ex: db.session.rollback() return response_error(ex.message)
def calculate_matches(user): """Given a user object, return a list of matches, ordered by score""" #me calculating random stuff all_users = User.query.filter(User.id != user.id).all() print(all_users) target_users = random.sample(all_users, 1) ret = [] for target in target_users: match = Match() data = { 'sender_id': user.id, 'target_id': target.id, 'score': random.random() } match.populate(data) ret.append(match) return ret
def form_valid(self, form): data = form.cleaned_data user_data = {} common_data = {} user_data['last_name'] = data['last_name'] user_data['first_name'] = data['first_name'] user_data['email'] = data['email'] user_data['username'] = data['username'] user_data['password'] = data['password'] common_data['cpf'] = data['cpf'] common_data['phone'] = data['phone'] if data['username'] and data['password']: new_user = User.objects.create_user(**user_data) new_common_user = CommonUser(user=new_user, **common_data) new_common_user.save() messages.success(self.request, 'Novo usuário cadastrado com sucesso.') else: return self.form_invalid(form) requeriment = Requirement.objects.get(id=self.kwargs['requeriment_id']) requeriment.name = data['name_item'] requeriment.description = data['description'] new_item = Item(owner=new_user, description=requeriment.description, name_item=requeriment.name) new_item.save() new_object = Object(item=new_item, type=requeriment.type) new_object.save() messages.success(self.request, "Novo Objeto cadastrado com sucesso!") match = Match(requirement=requeriment, item=new_item) match.save() notification = Notification(user=requeriment.owner, match=match) notification.save() donation = Donation( donator=new_user, institute=requeriment.owner, item=new_item, data=datetime.datetime.today().strftime('%Y-%m-%d'), is_completed=False) donation.save() messages.success(self.request, 'Muito Obrigado pela sua Doação!') return super(DonatorRequerimentViewAnonymous, self).form_valid(form)
def report_match(match_id): """ "" report: report outcomes "" input: "" match_id """ try: uid = int(request.headers['Uid']) data = request.json response = [] if data is None: return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA) match = Match.find_match_by_id(match_id) if match is not None: result = data['result'] if result is None: return response_error(MESSAGE.MATCH_RESULT_EMPTY, CODE.MATCH_RESULT_EMPTY) if not match_bl.is_exceed_closing_time(match.id): return response_error(MESSAGE.MATCH_CANNOT_SET_RESULT, CODE.MATCH_CANNOT_SET_RESULT) for item in result: if 'side' not in item: return response_error(MESSAGE.OUTCOME_INVALID_RESULT, CODE.OUTCOME_INVALID_RESULT) if 'outcome_id' not in item: return response_error(MESSAGE.OUTCOME_INVALID, CODE.OUTCOME_INVALID) outcome = Outcome.find_outcome_by_id(item['outcome_id']) if outcome is not None and outcome.created_user_id == uid: message, code = match_bl.is_able_to_set_result_for_outcome( outcome) if message is not None and code is not None: return message, code outcome.result = CONST.RESULT_TYPE['PROCESSING'] outcome_json = outcome.to_json() response.append(outcome_json) else: return response_error(MESSAGE.OUTCOME_INVALID, CODE.OUTCOME_INVALID) return response_ok(response) else: return response_error(MESSAGE.MATCH_NOT_FOUND, CODE.MATCH_NOT_FOUND) except Exception, ex: return response_error(ex.message)
def testCascadeUserMatch(self): # user -> match firstUser = User(username=u'FirstUser', password='******') db.session.add(firstUser) db.session.commit() firstMatch = Match(initiator=firstUser) db.session.add(firstMatch) db.session.commit() assert len(firstUser.matches) == 1 # cascade update firstUser.username = u'FirstUserUpdated' db.session.commit() assert firstMatch.users[0].username == u'FirstUserUpdated' # cascade delete db.session.delete(firstUser) db.session.commit() assert len(firstMatch.users) == 0 db.session.delete(firstMatch) db.session.commit() # match -> user secondUser = User(username=u'SecondUser', password='******') db.session.add(secondUser) db.session.commit() secondMatch = Match(initiator=secondUser) db.session.add(secondMatch) db.session.commit() assert len(secondUser.matches) == 1 # cascade update secondMatch.finished = True db.session.commit() assert models.User.query.get(secondUser.id).matches[0].finished == True # cascade delete db.session.delete(secondMatch) db.session.commit() assert len(secondUser.matches) == 0 app.logger.debug('testCascadeUserMatch - OK')
def test_bettor_won(self): # BETTOR WON match3 = self.u1.list_matches()[0] match4 = self.u1.list_matches()[1] match3.committed = True match4.committed = True db.session.add(match3) db.session.add(match4) db.session.commit() for m in self.u1.list_matches()[0:2]: if Match.predicted_winner(user=self.u1,match=m.match).team_winner_id == m.match.actual_winner: # user guessed it correctly self.assertTrue(m.bettor_won, 'User predicted match result correctly') else: self.assertFalse(m.bettor_won, 'User has not predicted match result correctly') # change the settings so user predicts draw match_specific_settings = [0.6, 0.3, 0.1] mss1 = ModuleUserMatchSettings(user_id=self.u1.id, match_id=match4.match.id, module_id=1, weight=match_specific_settings[0]) mss2 = ModuleUserMatchSettings(user_id=self.u1.id, match_id=match4.match.id, module_id=2, weight=match_specific_settings[1]) mss3 = ModuleUserMatchSettings(user_id=self.u1.id, match_id=match4.match.id, module_id=3, weight=match_specific_settings[2]) db.session.add(mss1) db.session.add(mss2) db.session.add(mss3) db.session.commit() for m in self.u1.list_matches()[0:2]: if Match.predicted_winner(user=self.u1,match=m.match).team_winner_id == m.match.actual_winner: # user guessed it correctly self.assertTrue(m.bettor_won, 'User predicted match result correctly') else: self.assertFalse(m.bettor_won, 'User has not predicted match result correctly')
def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() #create user roles Role.insert_roles() #insert matches from the data file Team.insert_teams() #insert modules PredictionModule.insert_modules() #insert matches from the data file Match.update_all_matches() self.u1 = User(email='*****@*****.**', password='******') self.u1.confirmed = True db.session.add(self.u1) db.session.commit() matches = Match.query.all() # couple of non-played matches self.match1 = Match.query.all()[len(matches) - 2] self.match2 = Match.query.all()[len(matches) - 1] # some played matches self.match3 = Match.query.all()[12] self.match4 = Match.query.all()[16] # draw match self.match5 = Match.query.all()[14] self.u1.save_match(self.match1) self.u1.save_match(self.match2) self.u1.save_match(self.match3) self.u1.save_match(self.match4) self.u1.save_match(self.match5) db.session.add(self.u1) db.session.commit()
import datetime import csv from app.models import Player,Match,PlayertoMatch,Person # this file is used to add matches and playerto match entries., to run this file, follow the same instruction as in load.py c1=input("Enter Country 1\n") c2=input("Entry Country 2\n") date_entry=input("Enter Date in YYYY-MM-DD format \n") year,month,day=map(int,date_entry.split('-')) date1=datetime.date(year,month,day) print(c1,c2,date1) m=Match(country1=c1,country2=c2,day=date1,can_edit=True) m.save() for i in Player.objects.all(): if i.country==c1 or i.country==c2: p=PlayertoMatch(match=m,player=i) p.save()
def test_multiple_users_match_predictions(self): # this is tested match match1 = self.u1.list_matches()[0].match u1 = self.u1 # add another user u2 = User(email='*****@*****.**', password='******') u2.confirmed = True db.session.add(u2) db.session.commit() # TESTING MULTIPLE USERS CONFIGURATION # TESTCASE-1 USERS HAVE ONLY MATCH SETTINGS user1_match_specific_settings = [0.09, 0.40, 0.51] user2_match_specific_settings = [0.08, 0.40, 0.52] # specific match settings for user 1 mss1_1 = ModuleUserMatchSettings(user_id=self.u1.id, match_id=match1.id, module_id=1, weight=user1_match_specific_settings[0]) mss2_1 = ModuleUserMatchSettings(user_id=self.u1.id, match_id=match1.id, module_id=2, weight=user1_match_specific_settings[1]) mss3_1 = ModuleUserMatchSettings(user_id=self.u1.id, match_id=match1.id, module_id=3, weight=user1_match_specific_settings[2]) # specific match settings for user 2 mss1_2 = ModuleUserMatchSettings(user_id=u2.id, match_id=match1.id, module_id=1, weight=user2_match_specific_settings[0]) mss2_2 = ModuleUserMatchSettings(user_id=u2.id, match_id=match1.id, module_id=2, weight=user2_match_specific_settings[1]) mss3_2 = ModuleUserMatchSettings(user_id=u2.id, match_id=match1.id, module_id=3, weight=user2_match_specific_settings[2]) db.session.add(mss1_1) db.session.add(mss2_1) db.session.add(mss3_1) db.session.add(mss1_2) db.session.add(mss2_2) db.session.add(mss3_2) db.session.commit() self.assertEqual(len(u1.list_match_specific_settings(match_id=match1.id)), 3, "List user1 match specific settings contains 3 matches") for i in range(0, len(user1_match_specific_settings)): self.assertEqual(ModuleUserMatchSettings.query.filter_by(user_id=u1.id).all()[i].weight, user1_match_specific_settings[i], "Check that user1 match specific weights are saved") self.assertIsNotNone(u2.list_match_specific_settings(match_id=match1.id), "List user2 match specific settings contains 3 matches") for i in range(0, len(user2_match_specific_settings)): self.assertEqual(ModuleUserMatchSettings.query.filter_by(user_id=u2.id).all()[i].weight, user2_match_specific_settings[i], "Check that user2 match specific weights are in saved") # make sure that different set of weights are used for two different users in the application probability_user_1 = match1.prediction_league_position * mss1_1.weight \ + match1.prediction_form * mss2_1.weight \ + match1.prediction_homeaway * mss3_1.weight self.assertAlmostEqual(probability_user_1, Match.predicted_winner(match1, u1).probability) probability_user2 = match1.prediction_league_position * mss1_2.weight \ + match1.prediction_form * mss2_2.weight \ + match1.prediction_homeaway * mss3_2.weight self.assertAlmostEqual(probability_user2, Match.predicted_winner(match1, u2).probability)
def test_user_hunch_module_contrib_to_change_result(self): # TEST user hunch contrib to DRAW, contrib to changing result # TEST user hunch contrib to DRAW prediction_result = '' u1 = self.u1 match1 = self.u1.list_matches()[1] match2 = self.u1.list_matches()[1] match1.committed = True match2.committed = True db.session.add(match1) db.session.add(match2) db.session.commit() # module user hunch changed the result to draw if Match.predicted_winner(match1.match, u1).team_winner_id == match1.match.hometeam_id: # home win prediction_result = 1 elif Match.predicted_winner(match1.match, u1).team_winner_id == match1.match.awayteam_id: # away win prediction_result = -1 else: # draw prediction_result = 0 match_specific_settings = [0.0, 0.0, 0.0, 1.0] mss1 = ModuleUserMatchSettings(user_id=u1.id, match_id=match1.match.id, module_id=1, weight=match_specific_settings[0]) mss2 = ModuleUserMatchSettings(user_id=u1.id, match_id=match1.match.id, module_id=2, weight=match_specific_settings[1]) mss3 = ModuleUserMatchSettings(user_id=u1.id, match_id=match1.match.id, module_id=3, weight=match_specific_settings[2]) mss4 = ModuleUserMatchSettings(user_id=u1.id, match_id=match1.match.id, module_id=4, weight=match_specific_settings[3]) db.session.add(mss1) db.session.add(mss2) db.session.add(mss3) db.session.add(mss4) db.session.commit() # module user hunch changed the result to draw if prediction_result == 1: match1.user_hunch = -100 db.session.add(match1) db.session.commit() self.assertEqual(Match.predicted_winner(match1.match, u1, match1.user_hunch).team_winner_id, match1.match.awayteam_id, 'User hunch changed the prediction') elif prediction_result == -1: match1.user_hunch = 100 db.session.add(match1) db.session.commit() self.assertEqual(Match.predicted_winner(match1.match, u1, match1.user_hunch).team_winner_id, match1.match.hometeam_id, 'User hunch changed the prediction') else: match1.user_hunch = 100 db.session.add(match1) db.session.commit() self.assertEqual(Match.predicted_winner(match1.match, u1, match1.user_hunch).team_winner_id, match1.match.hometeam_id, 'User hunch changed the prediction')
def createTestData(cls): db.drop_all() db.create_all() ############################################# create Users john_user = User(username=u'John', password=u'123', avatar_image_name='avatar_axe.png', wallpapers_image_name='wallpaper_antimage_1.jpg', mmr=4125) peter_user = User(username=u'Peter', password=u'123', avatar_image_name='avatar_nature_prophet.png', wallpapers_image_name='wallpaper_bloodseeker_1.jpg', mmr=3940) jack_user = User(username=u'Jack', password=u'123', avatar_image_name='avatar_tinker.png', wallpapers_image_name='wallpaper_bloodseeker_1.jpg', mmr=3870) # add Users to session db.session.add(john_user) db.session.add(peter_user) db.session.add(jack_user) db.session.commit() ############################################### adding friends john_user.sendRequest(peter_user) john_user.sendRequest(jack_user) jack_user.acceptRequest(john_user) # ############################################# making themes lore_theme = Theme(name=u'lore', image_name=u'theme_lore.png') tournaments_theme = Theme(name=u'tournaments', image_name=u'theme_tournaments.png') mechanics_theme = Theme(name=u'mechanics', image_name=u'theme_mechanics.png') # add to session db.session.add(lore_theme) db.session.add(tournaments_theme) db.session.add(mechanics_theme) db.session.commit() # upload questions Database_queries.uploadQuestionFromPath(questiondir) ############################################## create Match first_match = Match(initiator=john_user) second_match = Match(initiator=peter_user) # add users to match first_match.setOpponent(peter_user) second_match.setOpponent(john_user) third_match = Match(initiator=peter_user) third_match.setOpponent(john_user) fourth_match = Match(initiator=john_user) fifth_match = Match(initiator=jack_user) # [1] FINISHED for r in first_match.rounds: for quest in r.questions: user_answer = UserAnswer() user_answer.round = r user_answer.user = first_match.users[0] user_answer.answer = random.choice(quest.answers) db.session.add(user_answer) user2_answer = UserAnswer() user2_answer.round = r user2_answer.user = first_match.users[1] user2_answer.answer = random.choice(quest.answers) db.session.add(user2_answer) first_match.finished = True # [!1] # [2] RUNNING for r in second_match.rounds[0:2]: for quest in r.questions: user_answer = UserAnswer() user_answer.round = r user_answer.user = second_match.users[0] user_answer.answer = random.choice(quest.answers) db.session.add(user_answer) user2_answer = UserAnswer() user2_answer.round = r user2_answer.user = second_match.users[1] user2_answer.answer = random.choice(quest.answers) db.session.add(user2_answer) # [!2] # [3] TIME_ELAPSED for r in third_match.rounds: for quest in r.questions[0:2]: user_answer = UserAnswer() user_answer.round = r user_answer.user = third_match.users[0] user_answer.question = quest user_answer.answer = random.choice(quest.answers) db.session.add(user_answer) user2_answer = UserAnswer() user2_answer.round = r user2_answer.user = third_match.users[1] user2_answer.question = quest user2_answer.answer = random.choice(quest.answers) db.session.add(user2_answer) third_match.finished = True # [!3] # [4] NOT_STARTED # add match to session db.session.add(first_match) db.session.add(second_match) db.session.add(third_match) db.session.add(fourth_match) db.session.add(fifth_match) db.session.commit()