def create_accepted_scrim(): from consts import UGC_PLATINUM from consts import SCRIM_ACCEPTED from datetime import datetime, timedelta team1 = Team() team1.name = "Team Test Finished Scrim1" team1.skill_level = UGC_PLATINUM team1.time_zone = "CET" db.session.add(team1) team2 = Team() team2.name = "Team Test Finished Scrim2" team2.skill_level = UGC_PLATINUM team2.time_zone = "CET" db.session.add(team2) now = datetime.utcnow() past_day = now - timedelta(days=now.weekday() - 4) scrim_accepted = Scrim() scrim_accepted.date = past_day scrim_accepted.map1 = "Map1" scrim_accepted.map2 = "Map2" scrim_accepted.team1_id = team1.id scrim_accepted.team1 = team1 scrim_accepted.team2_id = team2.id scrim_accepted.team2 = team2 scrim_accepted.type = "Accepted scrim" scrim_accepted.state = SCRIM_ACCEPTED db.session.add(scrim_accepted) db.session.commit() return team1.id
def create_team(self, defense_player, attack_player): cur = self.con.cursor() team_dict = dict(defense_player=defense_player, attack_player=attack_player) team_dict_sql = dict(defense_player_id=defense_player.player_id, attack_player_id=attack_player.player_id) cur.execute( "SELECT team_id, defense_player_id, attack_player_id, team_stats_id FROM teams WHERE defense_player_id=:defense_player_id AND attack_player_id=:attack_player_id", team_dict_sql) team_exists = cur.fetchone() if team_exists: team_id, _, _, team_stats_id = team_exists return Team(team_id=team_id, team_stats=self.get_stats(team_stats_id), **team_dict) else: cur.execute( "INSERT INTO teams(defense_player_id, attack_player_id) VALUES(:defense_player_id, :attack_player_id)", team_dict_sql) self.con.commit() team_id = cur.lastrowid team_stats = self.add_first_stats(team_id=team_id) self.update_team_stats(team_id=team_id, team_stats_id=team_stats.stats_id) return Team(team_id=team_id, team_stats=team_stats, **team_dict)
def readMatchData(season): """Converts a particular season's csv file into more usable python formats.""" matchDict = {} teamDict = {} # A dictionary of Team objects indexed by name seasonFile = open('match_data/' + season + '.csv') seasonReader = csv.reader(seasonFile) seasonData = list(seasonReader) for i in range(1, 381): # Gets all the data from rows 1-380 # Only works for a 380-game season homeTeam = seasonData[i][2] awayTeam = seasonData[i][3] matchup = (homeTeam, awayTeam) if homeTeam not in teamDict: teamDict[homeTeam] = Team(homeTeam) if awayTeam not in teamDict: teamDict[awayTeam] = Team(awayTeam) teamDict[homeTeam].addFixture(matchup) teamDict[awayTeam].addFixture(matchup) matchDict[matchup] = { 'date': convertDate(seasonData[i][1]), 'homeGoals': int(seasonData[i][4]), 'awayGoals': int(seasonData[i][5]), 'resultChar': seasonData[i][6] } return matchDict, teamDict
def setUp(self): """Define the test client and other test variables""" user = User.objects.create(username="******") self.team_name = "Barcelona" self.team1 = Team(name=self.team_name, owner=user) self.team_name2 = "ManchesterUnited" self.members = [ User.objects.create(username="******"), User.objects.create(username="******") ] self.team2 = Team(name=self.team_name2, owner=user)
def post_team(jwt): try: team_data = request.get_json() name = team_data.get('name') home_city = team_data.get('home_city') losses = team_data.get('losses') or 0 wins = team_data.get('wins') or 0 logo = team_data.get('logo') or '' team = Team( name=name, home_city=home_city, losses=losses, wins=wins, logo=logo ) team.insert() return jsonify({ 'success': True, 'team': team.format() }), 200 except Exception: print(sys.exc_info()) abort(400)
def index(user_name): teams = Team.query.filter(Team.members.any( User.user_name == user_name)).order_by(Team.name).all() form = TeamForm() form.team_members.choices = [ (u.id, u.user_name) for u in User.query.filter( User.user_name != user_name).order_by('name') ] if form.validate_on_submit(): team_name = form.team_name.data team_members = form.team_members.data list(set(team_members)) new_team = Team(name=team_name, admin=user_name) new_team.members.append( User.query.filter(User.user_name == user_name).first()) for team_member in team_members: user1 = User.query.get(team_member) if user1: new_team.members.append(user1) app_db.session.add(new_team) app_db.session.commit() return redirect('/index/' + user_name) return render_template('index.html', teams=teams, user=user_name, form=form)
def admin_create_team(userid): user = User.query.get(userid) if request.method == 'POST': team_name = request.form.get("newteam") # If team exists in database if Team.query.filter(team_name == Team.team_name).all(): return render_template('teams.html', team_exist=True) else: old_team_id = user.team_id if old_team_id: user.team_id = None if Team.query.get(old_team_id).member_count == 1: db.session.delete(Team.query.get(old_team_id)) else: old_team = Team.query.get(old_team_id) old_team.member_count = old_team.member_count - 1 old_team.progress = old_team.team_progress() if old_team.progress >= 100: old_team.date_completed = datetime.datetime.now() else: old_team.date_completed = None team = Team(team_name=team_name, member_count=1, status='pending') db.session.add(team) db.session.commit() user.team_id = Team.query.filter( team_name == Team.team_name).first().id user.team.progress = user.team.team_progress() if user.team.progress >= 100: user.team.date_completed = datetime.datetime.now() else: user.team.date_completed = None db.session.commit() return redirect(url_for("admin_dashboard"))
def parse_team(self, homeaway='home'): # Extract pertinent contents of boxscore.xml. We'll keep one record for # each Team per season, to allow for changing team names and/or cities. # Since this will usually be an update (not an insert), merge it here # instead of adding it to the list of objects to be added at once. if self.boxscore is None: logging.warn('{}: No boxscore available'.format(self.game_id)) return # Hold the parsed contents in a dictionary. We'll drop None values # before creating a Game instance. team = {} team['team_id'] = try_int(self.boxscore.get(homeaway + '_id')) team['season'] = self.season team['name'] = self.boxscore.get(homeaway + '_fname') team['short_name'] = self.boxscore.get(homeaway + '_sname') # League is a two-character code (e.g., 'AN' for 'American vs. # National'), with the home team's league first and the away team second. # If away, use the second character (True ~ 1). Otherwise, use the # first (False ~ 0). team['league'] = self.linescore.get('league', ' ')[homeaway == 'away'] team['division'] = self.linescore.get(homeaway + '_division', '') # Drop None values team = dict((k, v) for k, v in team.items() if v is not None) if 'team_id' in team: self.session.merge(Team(**team)) self.session.commit()
def post(self): args = team_parser.parse_args() if 'id' not in args: highest = Team.query.order_by(Team.id).last() team_id = highest + 1 else: team_id = args['id'] team = Team(id=team_id, name=args['name'], division=args['division'], league=args['league']) if args['player_id'] is not None: player = Player.query.filter_by(id=args['player_id']).first() if player is None: abort(404, "Player %s: not found." % args['player_id']) team.players.append(player) coach = Coach.query.filter_by(id=id).first() if not coach: abort(404, "Coach %s: not found." % id) team.coaches.append(coach) db.session.add(team) db.session.commit() return team, 201
def add_team(): if 'user_id' in session: user_id = session['user_id'] user = User.query.get(user_id) else: return redirect(url_for('index')) if request.method == 'POST': team = Team(title=request.form['title'], intro=request.form['intro']) image_url = request.form['image_url'] if image_url: team.image_url = image_url else: team.image_url = app.config['DEFAULT_TEAM_IMG'] team.admins.append(user) user.teams.append(team) db.session.add(team) db.session.commit() # add tags add_tags = request.form['tags'].split(',') for t in add_tags: t = t.strip() if Tag.query.filter_by(title=t).count() == 0 and t: new_t = Tag(title=t) db.session.add(new_t) team.tags.append(new_t) db.session.commit() return redirect(url_for('profile')) return render_template('add_team.html', title='add_team')
def check_team(): if request.method == 'POST': teamNumber = [] toTeam = [] for i in range(0, 9): teamNumber.append(int(request.form['memberId' + str(i)])) user = User.query.filter_by(id=teamNumber[1]).first() if any(teamNumber.count(tn) > 1 for tn in teamNumber) == False: team = Team(members=len(teamNumber)) db.session.add(team) db.session.commit() for i in range(0, 9): user = User.query.filter_by(id=teamNumber[i]).first() user.team_id = team.__getitem__(id) db.session.add(user) db.session.commit() return str(Team.query.all()) else: error = "Dublicates" users = User.query.all() us = [] for user in users: if user.team_id is None or user.team_id == 0: us.append(user) return render_template('create_team.html', users=us, error=error)
def get_teams(self): groups_container = self.teams_soup.find("div", {"class": "groups-container"}) table = groups_container.find("table") rows = table.find_all("tr") for row in rows: if not row.has_attr("class"): continue anchor = row.find("a") dictTeam = {} dictTeam["id"] = int(re.search(self.regex_teamid, anchor["href"]).group(1)) dictTeam["name"] = anchor.text if dictTeam["id"] in self.teams.keys(): self.teams[dictTeam["id"]].set(**dictTeam) else: team = Team(**dictTeam) self.teams[dictTeam["id"]] = team self.session.add(team) if dictTeam["id"] in self.definitions.keys(): self.definitions[dictTeam["id"]].set(TEAM_ID=dictTeam["id"], DEF_HLTV=dictTeam["name"]) else: definiton = Definition(DEF_TYPE="team", TEAM_ID=dictTeam["id"], DEF_HLTV=dictTeam["name"], DEF_SHEET=dictTeam["name"]) self.definitions[dictTeam["id"]] = definiton self.session.add(definiton)
def put_team(): # get the name first, if no name then fail team_name = request.form.get("team_name") association = request.form.get("association") division = request.form.get("division") city_id = request.form.get("city_id") if not team_name: return make_response( jsonify({ "code": 403, "msg": "Cannot put team. Missing mandatory fields." }), 403) team_id = request.form.get("id") if not team_id: t = Team(team_name=team_name, association=association, division=division, city_id=city_id) db.session.add(t) else: t = Team.query.get(team_id) t.team_name = team_name t.association = association t.division = division t.city_id = city_id try: db.session.commit() except sqlalchemy.exc.SQLAlchemyError as e: error = "Cannot put team. " print(app.config.get("DEBUG")) if app.config.get("DEBUG"): error += str(e) return make_response(jsonify({"code": 404, "msg": error}), 404) return jsonify({"code": 200, "msg": "success"})
def create_team_and_user(campaign_id, neighborhood_id): """ Create a team of detonators and the corespondent user :param campaign_id: :param neighborhood_id: :return: New user's login info """ # Create new team new_team = Team(campaign_id=campaign_id, neighborhood_id=int(neighborhood_id)) db.session.add(new_team) db.session.commit() # Create new user team_user = User(username="******".format(team_id=new_team.id), password=None, is_admin=False, is_active=True) team_user.set_password(DEFAULT_TEAM_USER_PASSWORD) team_user.team_id = new_team.id db.session.add(team_user) db.session.commit() return { 'username': team_user.username, 'password': DEFAULT_TEAM_USER_PASSWORD }
def create_teams(session, bracket_info): for team_info in bracket_info: team_name = team_info["team"] team = session.query(Team.id).filter(Team.name == team_name).first() if team is None: team = Team(name=team_name) session.add(team)
def process_players(): teams_dic = {} players_json_path = os.path.join(base_folder, 'resources', 'players.json') with open(players_json_path, 'r', encoding='utf8') as f: data_store = json.load(f) player_ids = data_store['data'].keys() for player_id in player_ids: if 'stats' in data_store['data'][player_id] and 'shirtNumber' in \ data_store['data'][player_id] \ and '902' in data_store['data'][player_id]['stats'] and '19/20' in \ data_store['data'][player_id]['stats']['902']: team = data_store['data'][player_id]['teamId'] if team: if team['id'] not in teams_dic: team_id = int(team['id']) teams_dic[team_id] = Team(team_id, team) current_team = teams_dic[team['id']] current_team.add_player(int(player_id), data_store['data'][player_id]) teams_json_path = os.path.join(base_folder, 'resources', 'teams.json') with open(teams_json_path, 'r', encoding='utf8') as f: data_store = json.load(f) team_ids = data_store['data'].keys() for team_id in team_ids: if int(team_id) in teams_dic: season = data_store['data'][team_id]['stats']['902']['19/20'] teams_dic[int(team_id)].set_possession(season) lst_to_delete = list( map(str, list(teams_dic.keys())) - data_store['data'].keys()) for to_del in lst_to_delete: del teams_dic[int(to_del)] process_latest_lineups(teams_dic) return teams_dic
def post(self): post = self.request.POST team = Team(name=post['team_name']) team.save() self.response.out.write("submitted")
def wsAddNewTeam(request): user = User.objects.get(pk=request.session['userid']) newTeam = Team(name=request.POST['teamName'], description=request.POST['teamDescription'], owner=user) newTeam.save() return JsonResponse({'status': 'success'})
def create_team(request): if not request.form.get('create_tname'): flash('Please enter a team name.', 'warning') return redirect(request.url) if current_user.team_id is not None: flash('You cannot create a team if you are already in one!', 'error') return redirect(request.url) # Create team tname = request.form.get('create_tname') team = Team.query.filter_by(tname=tname).first() # Team can be created if team is None: g.log.info('Creating a team') g.log = g.log.bind(tname=tname) current_user.time_team_join = datetime.utcnow() team = Team(tname, current_user) try: DB.session.add(team) DB.session.add(current_user) DB.session.commit() except Exception as e: g.log.error('error occurred while creating team: {}'.format(e)) flash( 'The team you were trying to create already exists. If this error occurs multiple times, please contact us', 'error') return redirect(request.url) g.log.info('Successfully created team') flash('Successfully created team!', 'success') return redirect(url_for('team')) # Team cannot be created else: flash('This team name already exists! Please try another name.', 'warning') return redirect(request.url)
def _create_or_get_team(team_name): logging.info('create_or_get_team: {}'.format(team_name)) team = Team.query().filter(Team.name == team_name).get() if not team: team = Team(name=team_name) logging.info('returning {}'.format(team)) return team
def create_team_submission(jwt): error = False body = {} try: body = request.get_json() name = body['name'] city = body['city'] image = body['image'] color1 = body['color1'] color2 = body['color2'] team = Team(name=name, city=city, image=image, color1=color1, color2=color2) team.insert() except(): error = True if error: abort(500) else: teamsarray = [] teamsarray.append(team.format()) return jsonify ({ 'success': True, 'created_team': teamsarray })
def teams(): form = TeamForm() if 'username' not in session: return redirect(url_for('signin')) user = session['username'] teams = db.session.query(Team).order_by(Team.Number).all() if user is None: redirect(url_for('signin')) else: if request.method == 'POST': if not form.validate(): return render_template('teams.html', teams=teams, form=form) else: newteam = Team(number=form.number.data, name=form.name.data, website=form.website.data, timestamp=datetime.datetime.now()) db.session.add(newteam) db.session.commit() flash('Team successfully added.') return redirect(url_for('teams')) elif request.method == 'GET' : return render_template('teams.html', teams=teams, form=form)
def create_team(current_user): data = request.get_json() new_team = Team(name=data['team_name'], captain_id=current_user.id) db.session.add(new_team) db.session.flush() db.session.commit() return {'New team id': new_team.team_id}
def create_new_team(): """We're gonna show a form and handle the business of folks who already registered,""" if not g.user: flash("Access unauthorized.", "danger") return redirect('/') user = g.user form = TeamForm() if form.validate_on_submit(): try: team = Team(name=form.name.data, team_image=form.team_image.data or Team.team_image.default.arg, user_id=user.username) db.session.add(team) db.session.commit() except IntegrityError: db.session.rollback() form.team_name.errors = ["Team name already exists"] return render_template('users/createTeam.html', form=form) return redirect(f'/users/{user.username}') return render_template('users/createTeam.html', form=form)
def create_teams(df): n_nodes = 0 for _, row in df.iterrows(): team = Team(name=row["team"]) team.save() n_nodes += 1 print("created {} nodes".format(n_nodes))
def suggest_team(team_number, pick_number): # check if logged in w/ google if not google_auth.is_logged_in(): return (redirect(url_for("google_auth.login"))) user_info = google_auth.get_user_info() user = User.query.filter(User.user_id == user_info["id"]).first() team = Team.query.filter_by(team_number=team_number).first() if not team: team = Team(team_number=team_number) db.session.add(team) alliance_suggestion = AllianceSuggestion.query.filter( AllianceSuggestion.team_id == team.id, AllianceSuggestion.pick_number == pick_number).first() if alliance_suggestion: db.session.delete(alliance_suggestion) db.session.commit() else: alliance_suggestion = AllianceSuggestion(team_id=team.id, user_id=user.id, pick_number=pick_number) db.session.add(alliance_suggestion) db.session.commit() return (redirect(url_for("team.profile", team_number=team_number)))
def add_teams(): team_names = set(stats_table['home_team']) | set(stats_table['away_team']) for team_name in team_names: team = Team() team.name = team_name db.session.add(team) db.session.commit()
def _json_to_team(data): team = Team(data[TEAMNAME_LABEL]) jsonroster = data[ROSTER_LABEL] for jsonplayer in jsonroster: player = _json_to_player(jsonplayer) team.add_player(player) return team
def form_to_dao(self, team_id): team = None players = [] if team_id is not None and len(team_id) > 1: team = self.teamDao.get_record(long(team_id)) else: team = Team() team.name = self.form.name.data team.alias = utils.slugify(self.form.name.data) team.sport = self.form.sport.data team.category = self.form.category.data players = self.upload_players() sel_player = self.request.get_all('player') logger.debug('sel_player: ' + str(sel_player)) if len(sel_player) > 0: players_count = len(sel_player) logger.debug('No of Selected Players %s' % players_count) for x in xrange(players_count): players.append(self.profileDao.get_record(sel_player[x]).key) logger.info('Total No of Players Mapped %s' % len(players)) logger.debug('Total Players Data: ' + str(players)) team.players = players return team
def createTeam(league_id): """Create a Team""" league = session.query(League).filter_by(slug=league_id).first() # If league is not found, try by slug if league is None: try: league = session.query(League).get(league_id) except Exception: return render_template('404.html') # Authorization to check if league owner if league.user_id != login_session['user_id']: flash("You do not have authorization to perform this action.") return render_template('denied.html') # If method is POST if request.method == 'POST': # Check if a team exists with this slug slug = slugify(request.form['name']) try: team = session.query(Team).filter_by(slug=slug, league=league).first() except Exception: pass if team is not None: flash("A team with this name already exists.") return redirect(url_for('createTeam', league_id=league.id)) # Create a new team team = Team(name=request.form['name'], league_id=league.id) session.add(team) session.commit() flash("Successfully added the {} to {}".format(team.name, team.league.name)) return redirect(url_for('showLeague', league_id=team.league.slug)) return render_template('create_team.html', league=league)