Esempio n. 1
0
  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
          })
Esempio n. 2
0
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')
Esempio n. 3
0
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')
Esempio n. 4
0
def register():
    """
    Registration form
    """
    from lib.forms.registration import RegistrationForm
    from lib.database import db_session
    form = RegistrationForm(request.form)
    if request.method == 'POST' and form.validate():
        from models import Team
        team = Team(form.team_name.data, form.institution.data,
                    form.team_members.data, md5(form.password.data).hexdigest())
        db_session.add(team)
        # trying to add to db
        try:
            db_session.flush()
        except:
            form.team_name.errors.append(u'Команда с таким названием уже зарегистрирована.')
        else:
            # if success, generate TEAM_ID
            team.generate_team_id()
            db_session.commit()
            # store session
            session['team_id'] = team.team_id
            return render_template('registration_success.html', team_id = team.team_id, active_register = True)
    return render_template('registration.html', form = form, active_registration = True)
Esempio n. 5
0
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)
Esempio n. 6
0
    def post(self):
        post = self.request.POST

        team = Team(name=post['team_name'])
        team.save()

        self.response.out.write("submitted")
Esempio n. 7
0
def consume():
    group_id = request.form.get('group_id')
    coupon_id = request.form.get('coupon')

    if group_id is None or coupon_id is None:
        raise Error("group_id and coupon required")

    try:
        coupon = Coupon.objects.with_id(coupon_id)
    except ValidationError:
        raise Error("invalid coupon id")

    if coupon is None:
        raise Error("invalid coupon id")

    if coupon.own_team is None:
        try:
            team = Team.objects(group_id=group_id).get()
        except DoesNotExist:
            raise Error("invalid team id")

        Team.objects(group_id=group_id).update_one(inc__coin=coupon.coin)
        team.reload()
        coupon.own_team = team
        coupon.save()
        bot.sendMessage(team.group_id, "{} {} {currency_name}\n{} 目前總計擁有 {} {currency_name}"
                        .format(coupon.description, coupon.coin, team.name, team.coin, currency_name=config.CURRENCY_NAME))

#         if len(set(map(lambda _: _.producer, Coupon.objects(own_team=team)))) == len(produce_permission.keys()):
#             bot.sendMessage(team.group_id, "「書靈 Lamp 想要幫助學徒尋找真相,因此靠著自己淵博的知識,發動了一個『真實之陣』\n真實之陣,信任正確之人,訴說你的信號,將會返回試金之結論」")

        return jsonify({'status': 'OK'})
    else:
        raise Error("Already used", status_code=409)
Esempio n. 8
0
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()
Esempio n. 9
0
    def bench_test(self):
        User.objects.create_user("dillen", "*****@*****.**", "letmein")
        
        team1 = Team(team_name="Winners",owner=User.objects.get(username__exact="dillen"))

        p1 = Player(full_name="abc1",position="WR",team=team1,benched=False)
        p2 = Player(full_name="abc2",position="WR",team=team1,benched=False)
        team1.wr_count = 2
        p3 = Player(full_name="abc3",position="WR",team=team1)
        p4 = Player(full_name="abc4",position="WR")
        
        team1.save()
        p1.save()
        p2.save()
        p3.save()
        p4.save()
        
        #Bench someone already benched
        self.assertEqual(bench(p3),False)
        self.assertEqual(team1.wr_count,2)
        self.assertEqual(p3.benched,True)
        
        #Bench someone not on a team
        self.assertEqual(bench(p4),False)
        self.assertEqual(team1.wr_count,2)
        self.assertEqual(p4.benched,True)
        
        #Bench a WR
        self.assertEqual(bench(p2),False)
        self.assertEqual(team1.wr_count,1)
        self.assertEqual(p1.benched,False)
        self.assertEqual(p2.benched,True)
Esempio n. 10
0
    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)
Esempio n. 11
0
    def create_test_data(self):
        user = User.get_or_create(123)
        user.admin = True
        User.get_or_create(12345)
        db.session.commit()

        team1 = Team.create(user, 'EnvyUs', 'EnvyUs', 'fr', 'nv',
                            ['76561198053858673'])
        team2 = Team.create(user, 'Fnatic', 'Fnatic', 'se', 'fntc',
                            ['76561198053858673'])
        server = GameServer.create(user, 'myserver1', '127.0.0.1', '27015',
                                   'password', False)
        server.in_use = True

        GameServer.create(user, 'myserver2', '127.0.0.1', '27016', 'password',
                          True)
        db.session.commit()
        season = Season.create(
            user, 'Season One Test', datetime.datetime.utcnow(),
            datetime.datetime.utcnow() + datetime.timedelta(days=1))
        db.session.commit()

        Match.create(user, team1.id, team2.id, '', '', 1, False,
                     'Map {MAPNUMBER}', ['de_dust2', 'de_cache', 'de_mirage'],
                     season.id, 'always_knife', 'CT', server.id)
        db.session.commit()

        vetoBan = Veto.create(1, 'EnvyUs', 'de_dust2', 'ban')
        vetoPick = Veto.create(1, 'EnvyUs', 'de_overpass', 'pick')
        db.session.commit()
Esempio n. 12
0
    def testAggregation(self):
        team = Team.create(name="Houkago Tea Time")
        team.members.append(first_name="Ritsu",
                            last_name="Tainaka",
                            part="Dr",
                            age=17)
        team.members.append(first_name="Mio",
                            last_name="Akiyama",
                            part="Ba",
                            age=17)
        team.members.append(first_name="Yui",
                            last_name="Hirasawa",
                            part="Gt1",
                            age=17)
        team.members.append(first_name="Tsumugi",
                            last_name="Kotobuki",
                            part="Kb",
                            age=16)
        team.members.append(first_name="Azusa",
                            last_name="Nakano",
                            part="Gt2",
                            age=17)

        a = ("Akiyama", "Hirasawa", "Kotobuki", "Nakano", "Tainaka")
        for i, m in enumerate(Team.get(1).members.order_by("last_name")):
            self.assertEqual(m.last_name, a[i])

        cnt = team.members.count()
        self.assertEqual(cnt, 5)

        sum_of_ages = team.members.all().aggregate(macaron.Sum("age"))
        self.assertEqual(sum_of_ages, 84)
Esempio n. 13
0
 def post(self):
     post = self.request.POST
     
     team = Team(name=post['team_name'])
     team.save()
     
     self.response.out.write("submitted")
Esempio n. 14
0
 def post(self, user_token):
   team = Team.all().filter('user_token =', user_token).get()
   if team is None:
     # just make sure this pledge exists
     user_info = config_NOCOMMIT.pledge_service.loadPledgeInfo(user_token)
     if user_info is None:
       return self.notfound()
   form = TeamForm(self.request.POST, team)
   if not form.validate():
     return self.render_template("new_from_pledge.html", form=form)
   if team is None:
     gravatar = "https://secure.gravatar.com/avatar/%s?%s" % (
       hashlib.md5(user_info['email'].lower()).hexdigest(),
       urllib.urlencode({'s': str('120')}))
     team = Team.create(title=form.title.data,
                        description=form.description.data,
                        zip_code=form.zip_code.data,
                        user_token=user_token,
                        gravatar=gravatar)
   else:
     form.populate_obj(team)
   self.add_to_user(team)
   team.primary_slug = Slug.new(team)  
   try:
     result = config_NOCOMMIT.pledge_service.updateMailchimp(team) 
   except Exception as e:
     logging.error('Exception updating mailChimp: ' + str(e))
     logging.info(traceback.format_exc())
   team.put()
   if self.logged_in:
     return self.redirect("/t/%s" % team.primary_slug)
   return self.redirect("/dashboard/add_admin_from_pledge/%s" % user_token)
Esempio n. 15
0
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
Esempio n. 16
0
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
Esempio n. 17
0
    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 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))
Esempio n. 19
0
def matched_keyword(keyword_str, group_id):
    keyword = Keyword.objects(keyword=keyword_str).get()

    if group_id in keyword.solved_team:
        return

    team = Team.objects(group_id=group_id).get()

#     if keyword_str == "238504":
#         bot.sendMessage(team.group_id, "「副市長是受小石信任之人,是心靈純潔之人」")
#     elif keyword_str == "15769":
#         bot.sendMessage(team.group_id, "「市長是小石害怕之人,是已經受到心靈扭曲影響之人」")

    coin = config.KEYWORD_MATCH_REWARD * keywords[keyword_str]

    if len(keyword.solved_team) == 0:
        coin *= 2

    coupon = generate_coupon(coin, "解開謎題 獲得", "System")

    Keyword.objects(keyword=keyword_str).update_one(push__solved_team=group_id)
    Team.objects(group_id=group_id).update_one(inc__coin=coupon.coin)
    team.reload()
    coupon.own_team = team
    coupon.save()
    bot.sendMessage(team.group_id, "{} {} {currency_name}\n{} 目前總計擁有 {} {currency_name}"
                    .format(coupon.description, coupon.coin, team.name, team.coin, currency_name=config.CURRENCY_NAME))
    app.logger.info("{}, {} solved keyword {} gain {} coin".format(str(datetime.now()), team.name, keyword_str, coupon.coin))
Esempio n. 20
0
 def post(self, user_token):
     team = Team.all().filter('user_token =', user_token).get()
     if team is None:
         # just make sure this pledge exists
         user_info = config_NOCOMMIT.pledge_service.loadPledgeInfo(
             user_token)
         if user_info is None:
             return self.notfound()
     form = TeamForm(self.request.POST, team)
     if not form.validate():
         return self.render_template("new_from_pledge.html", form=form)
     if team is None:
         gravatar = "https://secure.gravatar.com/avatar/%s?%s" % (
             hashlib.md5(user_info['email'].lower()).hexdigest(),
             urllib.urlencode({'s': str('120')}))
         team = Team.create(title=form.title.data,
                            description=form.description.data,
                            zip_code=form.zip_code.data,
                            user_token=user_token,
                            gravatar=gravatar)
     else:
         form.populate_obj(team)
     self.add_to_user(team)
     team.primary_slug = Slug.new(team)
     try:
         result = config_NOCOMMIT.pledge_service.updateMailchimp(team)
     except Exception as e:
         logging.error('Exception updating mailChimp: ' + str(e))
         logging.info(traceback.format_exc())
     team.put()
     if self.logged_in:
         return self.redirect("/t/%s" % team.primary_slug)
     return self.redirect("/dashboard/add_admin_from_pledge/%s" %
                          user_token)
 def get(self, first_eid):
     df = DatafeedUsfirstEvents()
     
     event = df.getEvent(first_eid)
     event = EventUpdater.createOrUpdate(event)
     
     teams = df.getEventRegistration(first_eid)
     eventteams_count = 0
     for team_dict in teams:
         # This could be refactored to do a lot fewer DB requests by batching the Team and EventTeam gets.
         # -gregmarra 5 Dec 2010
         team = Team.get_by_key_name("frc" + str(team_dict["number"]))
         if team is None:
             team = Team(
                 team_number = int(team_dict["number"]),
                 first_tpid = int(team_dict["tpid"]),
                 key_name = "frc" + str(team_dict["number"])
             )
             team.put()
         
         et = EventTeam.get_or_insert(
             key_name = event.key().name() + "_" + team.key().name(),
             event = event,
             team = team)
         eventteams_count = eventteams_count + 1
     
     template_values = {
         'event': event,
         'eventteams_count': eventteams_count,
     }
     
     path = os.path.join(os.path.dirname(__file__), '../templates/datafeeds/usfirst_event_get.html')
     self.response.out.write(template.render(path, template_values))
Esempio n. 22
0
def save_team():
    Team.PersistInstance(request.form['name'], [
        "members", request.form['members'], "contact", request.form['contact']
    ])
    while not len(Team.FindByName(request.form['name'])):
        pass
    Score.AddAllTeamTemplateScores()
Esempio n. 23
0
    def post(self):
        request_data = json.loads(self.request.body)
        logging.info(request_data)
        player = current_user_player()

        # VALIDATION
        if not validate_request_data(self.response, request_data, ['team_name']):
            return
        elif not validate_logged_inn(self.response):
            return
        elif not _validate_has_no_team(self.response, player):
            return

        # REGISTER TEAM
        new_team = Team(
            name=request_data['team_name'],
            owner=player.key
        ).put().get()

        # JOIN TEAM WITH PLAYER
        player.team = new_team.key
        player.put()

        ndb.get_context().clear_cache()  # Required to get the new player as part of the get_data
        set_json_response(self.response, {'team': new_team.get_data('full')})
Esempio n. 24
0
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
Esempio n. 25
0
    def setUp(self):
        """
        Delete existing users and teams, register a test user and test team and post to
        the db, and save the ID to this test instance for easy reference
        """
        User.query.delete()
        Team.query.delete()
        OpponentTeam.query.delete()

        user = User.register(username='******', password='******')
        other_user = User.register(username='******', password='******')
        db.session.add_all([user, other_user])
        db.session.commit()

        team = Team.create(name='Team', league='League', owner=user.username)
        other_team = Team.create(name='Others', league='Terrible', owner=other_user.username)

        team.add_players(['2544'])

        opp_team = OpponentTeam.create(name='Opponent', plays_against=team.id)
        other_opp = OpponentTeam.create(name='Other Opponent', plays_against=other_team.id)

        opp_team.add_players(['202355'])

        self.user = user
        self.other_user = other_user
        self.team = team
        self.team_player_ids = [player.player_id for player in team.players]
        self.other_team = other_team
        self.opp_team = opp_team
        self.opp_team_player_ids = [player.player_id for player in opp_team.players]
        self.other_opp = other_opp
        self.opp_team_id = opp_team.id
        self.other_opp_id = other_opp.id
Esempio n. 26
0
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'})
Esempio n. 27
0
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
Esempio n. 28
0
def accept_invitation(uname):
	user = user_manager.find_user_by_username(uname)
	if user.team_id:
		flash('This user has already formed a team with someone else. Please pick another teammate.', 'error')
		return redirect(url_for('user'))
	else:
		team = Team()
		team.members.append(current_user)
		team.members.append(user)
		team.name = current_user.username

		db.session.add(team)
		user.request_teammate = None
		current_user.request_teammate = None

		lst1 = db.session.query(User).filter(User.request_teammate==user.id).all()
		lst2 = db.session.query(User).filter(User.request_teammate==current_user.id).all()
		lst1.extend(lst2)

		for usr in lst1:
			usr.request_teammate = None
			send_mail(usr, 'fail_invitation')

		send_mail(user, 'new_team', u1=user, u2=current_user)
		send_mail(current_user, 'new_team', u1=user, u2=current_user)
		db.session.commit()

		team.name = "New Team No." + str(team.id)
		team.idea = Idea()
		db.session.commit()

		return redirect(url_for('team_page'))
Esempio n. 29
0
def generate_teams(num_teams):
    """ Generates teams by number """
    from models import Team, dbsession
    for i in range(0, num_teams):
        team = Team()
        team.name = 'Team ' + str(i + 1)
        dbsession.add(team)
        dbsession.flush()
    dbsession.commit()
Esempio n. 30
0
def generate_teams_by_name(team_names):
    """ Generates teams by their names """
    from models import Team, dbsession
    for i in range(0, len(team_names)):
        team = Team()
        team.name = team_names[i]
        dbsession.add(team)
        dbsession.flush()
    dbsession.commit()
Esempio n. 31
0
def addNewTeam(request):
    user = User.objects.get(pk=request.session['userid'])
    profile = UserProfile.objects.get(user=user)
    newTeam = Team(name=request.POST['teamName'],
                   description=request.POST['teamDescription'],
                   owner=user,
                   organization=profile.organization)
    newTeam.save()
    newTeam.members.add(request.session['userid'])
    return HttpResponseRedirect(reverse('retro:dashboard'))
Esempio n. 32
0
    def _create(self, args):
        draft_id = args[0]

        team = Team(draft_id=draft_id)
        self._update_fields(team, self.request_body_json)
        if team.order == 0:
            team.is_turn = True
        self.db.add(team)
        self.db.commit()

        return team.to_dict()
Esempio n. 33
0
 def form_to_dao_team_auto(self, player):
   try:
     team = Team()
     team.name = self.form.teamName.data
     #Create an automatic alias for the team
     team.alias = utils.slugify(self.form.teamName.data)
     team.sport = self.form.sport.data
   except StandardError as e:
     logger.error('Error occured, %s, for %s:%s' % (str(e), type, update['name']))
     raise
   return team
Esempio n. 34
0
 def form_to_dao_team_auto(self, team_alias_name, **update):
     try:
         team = Team()
         team.name = update['teamName']
         #Create an automatic alias for the team
         team.alias = team_alias_name
         team.sport = update['sport']
     except StandardError as e:
         logger.error('Error occured, %s, for %s:%s' %
                      (str(e), type, update['name']))
         raise
     return team
Esempio n. 35
0
def add_teams(current_user):
	result = []
	print(request.get_json())
	team_new = Team(nombre = request.form['nombre'],
					pais= request.form['pais'],
					bandera= request.files['files0'],
					escudo= request.files['files1'])
	try:
		team_new.save()
		return jsonify({'result': 'OK'})
	except(ValueError, KeyError, TypeError):		
		return jsonify({'result': 'error'})
Esempio n. 36
0
    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)
Esempio n. 37
0
def worker_add(request):
    if request.method == "POST":
        if request.POST.get('add_button') is not None:
            errors = {}
            data = {
                'middle_name': request.POST.get('middle_name'),
                'notes': request.POST.get('notes')
            }

            first_name = request.POST.get('first_name', '').strip()
            if not first_name:
                errors['first_name'] = u'Имя обязательное'
            else:
                data['first_name'] = first_name

            last_name = request.POST.get('last_name', '').strip()
            if not last_name:
                errors['last_name'] = u'Фамилия обязательна'
            else:
                data['last_name'] = last_name

            birthday = request.POST.get('birthday', '').strip()
            if not birthday:
                errors['birthday'] = u'Дата рождения обязательна'
            else:
                try:
                    datetime.strptime(birthday, '%Y-%m-%d')
                except Exception:
                    errors['birthday'] = u'Введите корректный вормат даты'
                else:
                    data['birthday'] = birthday

            position = request.POST.get('position', '').strip()
            if not position:
                errors['position'] = u'Должность обязательна'
            else:
                data['position'] = position

            photo = request.FILES.get('photo')
            if photo:
                data['photo'] = photo

            if not errors:
                worker = Team(**data)
                worker.save()
                return HttpResponseRedirect(reverse('home'))
            else:
                return render(request, 'worker_add.html', {'errors': errors})
        elif request.POST.get('cancel_button') is not None:
            return HttpResponseRedirect(reverse('home'))
    else:
        return render(request, 'worker_add.html', {})
Esempio n. 38
0
 def query_by_owner(self, user, status='all', no_record=8):
   logger.info('NdbTeamDao:: DBHIT: query_by_owner for %s ' % user.email)
   owner_query = Team.query()
   if not user_has_role(user, 'admin'):
     owner_query = Team.query(ndb.OR(Team.owners == user.key, Team.created_by == user.key, Team.updated_by == user.key))
   if status != 'all':
     status_value = STATUS_DICT.get(status)
     owner_query = owner_query.filter(status == status_value)    
   owner_query = owner_query.order(-Team.updated_on)
   if no_record > -1:
     return list(owner_query.fetch(no_record))
   else: #return all. simulating -1 for app engine
     return list(owner_query.fetch())
Esempio n. 39
0
def dashboard_create_team():
    form = TeamForm(request.form)
    if request.method == 'POST' and form.validate():
        team = Team()
        team.name = form.name.data
        user_ids = request.form.getlist('selected-users')
        users = User.query.filter(User.id.in_(user_ids)).all()
        for user in users:
            team.users.append(user)
        db_session.add(team)
        db_session.commit()
        return redirect(url_for('dashboard.dashboard_teams'))
    return render_template('create_team.html', form=form)
Esempio n. 40
0
def init_teams():
    '''
    Initialize the Team table with the team names retrieved from Kimono.
    It removes all the entries and re-adds them.
    '''
    logger.info('Initializing teams...')
    url = settings.KIMONO['teams_url']
    teams = _get_results_collection1(url)
    teams_name = [team['name'] for team in teams]
    for team_name in teams_name:
        if not Team.objects.filter(name__iexact=team_name).exists():
            t = Team()
            t.name = team_name
            t.save()
Esempio n. 41
0
def create_team(name, motto):
    if Team.by_name(name) is not None:
        logging.info("Team with name '%s' already exists, skipping" % (name))
        return Team.by_name(name)
    logging.info("Create Team: %s" % name)
    team = Team(
        name=unicode(name[:16]),
        motto=unicode(motto[:32]),
    )
    level_0 = GameLevel.all()[0]
    team.game_levels.append(level_0)
    dbsession.add(team)
    dbsession.flush()
    return team
 def getTeamInfo(self, team_key):
     """
     Return a Team dict with basic information.
     """
     memcache_key = "api_team_info_%s" % team_key
     team_dict = memcache.get(memcache_key)
     if team_dict is None:
         team = Team.get_by_key_name(team_key)
         if Team is not None:
             team_dict = dict()
             team_dict["key"] = team.key().name()
             team_dict["team_number"] = team.team_number
             team_dict["name"] = team.name
             team_dict["nickname"] = team.nickname
             team_dict["website"] = team.website
             team_dict["event_keys"] = [a.event.key().name() for a in team.events]
             team_dict["location"] = team.address
             
             try:
                 team.do_split_address()
                 team_dict["location"] = team.split_address["full_address"]
                 team_dict["locality"] = team.split_address["locality"]
                 team_dict["region"] = team.split_address["region"]
                 team_dict["country"] = team.split_address["country"]
             except Exception, e:
                 logging.error("Failed to include Address for api_team_info_%s" % team_key)
             
             memcache.set(memcache_key, team_dict, 3600)
         else:
             return None
Esempio n. 43
0
def team_create():
    if not g.user:
        return redirect('/login')

    form = TeamForm(request.form)

    if request.method == 'POST':
        num_teams = g.user.teams.count()
        max_teams = config_setting('USER_MAX_TEAMS', 0)
        if max_teams >= 0 and num_teams >= max_teams and not g.user.admin:
            flash('You already have the maximum number of teams ({}) stored'.format(num_teams))

        elif form.validate():
            data = form.data
            public_team = data['public_team']
            auths = form.get_auth_list()

            team = Team.create(g.user, data['name'],
                               data['country_flag'], data['logo'], auths, public_team)

            db.session.commit()
            app.logger.info(
                'User {} created team {}'.format(g.user.id, team.id))

            return redirect('/teams/{}'.format(team.user_id))

        else:
            get5.flash_errors(form)

    return render_template('team_create.html', user=g.user, form=form,
                           edit=False, is_admin=g.user.admin)
Esempio n. 44
0
def score_bots():
    ''' Award money for botnets '''
    logging.info("Scoring botnets, please wait ...")
    bot_manager = BotManager.Instance()
    config = ConfigManager.Instance()
    for team in Team.all():
        bots = bot_manager.by_team(team.name)
        reward = 0
        for bot in bots:
            try:
                reward += config.bot_reward
                bot.write_message({
                    'opcode': 'status',
                    'message': 'Collected $%d reward' % config.bot_reward
                })
            except:
                logging.info(
                    "Bot at %s failed to respond to score ping" % bot.remote_ip
                )
        if 0 < len(bots):
            logging.debug("%s was awarded $%d for controlling %s bot(s)" % (
                team.name, reward, len(bots),
            ))
            bot_manager.add_rewards(team.name, config.bot_reward)
            bot_manager.notify_monitors(team.name)
            team.money += reward
            dbsession.add(team)
            dbsession.flush()
Esempio n. 45
0
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
Esempio n. 46
0
 def edit_users(self):
     ''' Update user objects in the database '''
     form = Form(
         uuid="User not selected",
         account="Please enter an account name",
         handle="Please enter a handle name",
         hash_algorithm="Please select a hash algorithm",
         team_uuid="Please select a team",
     )
     if form.validate(self.request.arguments):
         errors = []
         user = User.by_uuid(self.get_argument('uuid'))
         if user is not None:
             # Update user account name
             if user.account != self.get_argument('account'):
                 if User.by_account(self.get_argument('account')) is None:
                     logging.info("Updated user account %s -> %s" %
                         (user.account, self.get_argument('account'),))
                     user.account = unicode(self.get_argument('account'))
                 else:
                     errors.append("Account name is already in use")
             # Update user handle
             if user.handle != self.get_argument('handle'):
                 if User.by_handle(self.get_argument('handle')) is None:
                     logging.info("Updated user handle %s -> %s" %
                         (user.handle, self.get_argument('handle'),))
                     user.handle = unicode(self.get_argument('handle'))
                 else:
                     errors.append("Handle is already in use")
             # Update hashing algoritm
             if self.get_argument('hash_algorithm') in user.algorithms:
                 if user.algorithm != self.get_argument('hash_algorithm'):
                     if 0 < len(self.get_argument('password', '')):
                         logging.info("Updated %s's hashing algorithm %s -> %s" %
                             (user.handle, user.algorithm, self.get_argument('hash_algorithm'),)
                         )
                         user.algorithm = self.get_argument('hash_algorithm')
                     else:
                         errors.append("You must provide a password when updating the hashing algorithm")
             else:
                 errors.append("Not a valid hash algorithm")
             # Update password
             if 0 < len(self.get_argument('password', '')):
                 user.password = self.get_argument('password')
             # Update team
             team = Team.by_uuid(self.get_argument('team_uuid'))
             if team is not None:
                 if user.team_id != team.id:
                     logging.info("Updated %s's team %s -> %s" %
                         (user.handle, user.team_id, team.name))
                     user.team_id = team.id
             else:
                 errors.append("Team does not exist in database")
             dbsession.add(user)
             dbsession.flush()
         else:
             errors.append("User does not exist")
         self.render("admin/view/user_objects.html", errors=errors)
     else:
         self.render("admin/view/user_objects.html", errors=form.errors)
Esempio n. 47
0
 def ls(self):
     current_user = self.get_current_user()
     if self.get_argument('data').lower() == 'accounts':
         data = {}
         for team in Team.all():
             if team == current_user.team:
                 continue
             else:
                 data[team.name] = {
                     'money': team.money, 
                     'flags': len(team.flags),
                     'bots': team.bot_count,
                 }
         self.write({'accounts': data})
     elif self.get_argument('data').lower() == 'users':
         data = {}
         target_users = User.not_team(current_user.team.id)
         for user in target_users:
             data[user.handle] = {
                 'account': user.team.name,
                 'algorithm': user.algorithm,
                 'password': user.bank_password,
             }
         self.write({'users': data})
     else:
         self.write({'Error': 'Invalid data type'})
     self.finish()
 def addTeamDetails(self, team_dict, year):
     """
     Consume a Team dict, and return it with a year's Events filtered and Matches added
     """
     
     # TODO Matches should live under Events - gregmarra 1 feb 2011
     # TODO Filter Events by year - gregmarra 1 feb 2011
     
     memcache_key = "api_team_details_%s_%s" % (team_dict["key"], year)
     matches_list = memcache.get(memcache_key)
     if matches_list is None:
         matches = list()
         team = Team.get_by_key_name(team_dict["key"])
         for e in [a.event for a in team.events]:
             match_list = e.match_set.filter("team_key_names =", team.key().name()).fetch(500)
             matches.extend(match_list)
         matches_list = list()
         for match in matches:
             match_dict = dict()
             match_dict["key"] = match.key().name()
             match_dict["event"] = match.event.key().name()
             match_dict["comp_level"] = match.comp_level
             match_dict["set_number"] = match.set_number
             match_dict["match_number"] = match.match_number
             match_dict["team_keys"] = match.team_key_names
             match_dict["alliances"] = simplejson.loads(match.alliances_json)
             matches_list.append(match_dict)
         
         memcache.set(memcache_key, matches_list, 600)
     
     team_dict["matches"] = matches_list
     return team_dict
 def get(self):
     df = DatafeedUsfirstTeams()
     df.flushTeams()
     
     team_count = Team.all().count()
     
     self.response.out.write("Teams flushed. " + str(team_count) + " teams remain. What have we done?!")
Esempio n. 50
0
 def post(self, *args, **kwargs):
     ''' Called to purchase an item '''
     uuid = self.get_argument('uuid', '')
     item = MarketItem.by_uuid(uuid)
     if not item is None:
         user = self.get_current_user()
         team = Team.by_id(user.team.id)  # Refresh object
         if user.has_item(item.name):
             self.render('market/view.html',
                 user=user,
                 errors=["You have already purchased this item."]
             )
         elif team.money < item.price:
             message = "You only have $%d" % (team.money,)
             self.render('market/view.html', user=user, errors=[message])
         else:
             logging.info("%s (%s) purchased the market item '%s' for $%d" % (
                 user.handle, team.name, item.name, item.price
             ))
             self.purchase_item(team, item)
             event = self.event_manager.create_purchased_item_event(user, item)
             self.new_events.append(event)
             self.redirect('/user/market')
     else:
         self.render('market/view.html',
             user=self.get_current_user(),
             errors=["Item does not exist."]
         )
Esempio n. 51
0
 def get(self, user_token):
   team = Team.all().filter('user_token =', user_token).get()
   if team is None:
     user_info = config_NOCOMMIT.pledge_service.loadPledgeInfo(user_token)
     if user_info is None:
       return self.notfound()
     user_pledge_dollars = int(user_info["pledge_amount_cents"]) / 100
     goal_dollars = user_pledge_dollars * 10
     if user_info["name"]:
       signature = "_Thank you,_\n\n_%s_" % user_info["name"]
     else:
       signature = "Thank you!"
     title = user_info["name"] or DEFAULT_TITLE
     form = TeamForm(data={
         "goal_dollars": str(goal_dollars),
         "title": title,
         "zip_code": str(user_info["zip_code"] or ""),
         "description": PREVIOUS_PLEDGE_DESC.format(
             pledge_dollars=user_pledge_dollars,
             signature=signature,
             title=title)})
   else:
     self.add_to_user(team)
     form = TeamForm(obj=team)
   self.render_template("new_from_pledge.html", form=form)
Esempio n. 52
0
    def test_play(self):
        User.objects.create_user("dillen", "*****@*****.**", "letmein")
        User.objects.create_user("eli", "*****@*****.**", "letmein")
        
        team1 = Team(team_name="Winners",owner=User.objects.get(username__exact="dillen"))

        p1 = Player(full_name="abc1",position="WR",team=team1,benched=False)
        team1.wr_count = 1
        p2 = Player(full_name="abc2",position="WR",team=team1)
        p3 = Player(full_name="abc3",position="WR")
        p4 = Player(full_name="abc4",position="QB",team=team1,benched=False)
        team1.qb_count = 1
        p5 = Player(full_name="abc5",position="QB",team=team1)
        
        team1.save()
        p1.save()
        p2.save()
        p3.save()
        p4.save()
        p5.save()
        
        #Wrong position
        self.assertEqual(play(p2,"QB"),False)
        self.assertEqual(p2.benched,True)
        self.assertEqual(team1.qb_count,1)
        
        #Already playing
        self.assertEqual(play(p1,"WR"),False)
        self.assertEqual(p1.benched,False)
        self.assertEqual(team1.wr_count,1)
        
        #Not on a team
        self.assertEqual(play(p3,"WR"),False)
        self.assertEqual(p3.team, None)
        self.assertEqual(p3.benched, True)
        self.assertEqual(team1.wr_count,1)
        
        #2 QB's at the same time
        self.assertEqual(play(p5,"QB"),False)
        self.assertEqual(p4.benched, False)
        self.assertEqual(p5.benched, True)
        self.assertEqual(team1.qb_count,1)
        
        #2 WR's at the same time (valid)
        self.assertEqual(play(p2,"WR"),True)
        self.assertEqual(p2.benched, False)
        self.assertEqual(team1.wr_count,2)
Esempio n. 53
0
 def bots(self):
     game_history = GameHistory.Instance()
     history = {}
     for team in Team.all():
         history[team.name] = game_history.get_bot_history_by_name(
             team.name, -30
         )
     self.render('scoreboard/history/bots.html', history=history)
Esempio n. 54
0
 def get(self, user_token):
   team = Team.all().filter('user_token =', user_token).get()
   if team is None:
     return self.notfound()
   if not self.logged_in:
     return self.render_template("add_admin_login.html", team=team)
   self.add_to_user(team)
   return self.redirect("/t/%s" % team.primary_slug)
Esempio n. 55
0
 def render(self, *args, **kwargs):
     session_manager = SessionManager.Instance()
     session = session_manager.get_session(
         self.handler.get_secure_cookie('auth'), self.request.remote_ip)
     if session is not None:
         return self.render_string('sidebar/user.html',
             ranks=Team.get_all()
         )
Esempio n. 56
0
    def testAggregation(self):
        team = Team.create(name="Houkago Tea Time")
        team.members.append(first_name="Ritsu"  , last_name="Tainaka" , part="Dr" , age=17)
        team.members.append(first_name="Mio"    , last_name="Akiyama" , part="Ba" , age=17)
        team.members.append(first_name="Yui"    , last_name="Hirasawa", part="Gt1", age=17)
        team.members.append(first_name="Tsumugi", last_name="Kotobuki", part="Kb" , age=16)
        team.members.append(first_name="Azusa"  , last_name="Nakano"  , part="Gt2", age=17)

        a = ("Akiyama", "Hirasawa", "Kotobuki", "Nakano", "Tainaka")
        for i, m in enumerate(Team.get(1).members.order_by("last_name")):
            self.assertEqual(m.last_name, a[i])

        cnt = team.members.count()
        self.assertEqual(cnt, 5)

        sum_of_ages = team.members.all().aggregate(macaron.Sum("age"))
        self.assertEqual(sum_of_ages, 84)
Esempio n. 57
0
    def create_test_data(self):
        user = User.get_or_create(123)
        User.get_or_create(12345)
        db.session.commit()

        team1 = Team.create(user, 'EnvyUs', 'fr', 'nv', ['76561198053858673'])
        team2 = Team.create(user, 'Fnatic', 'se', 'fntc',
                            ['76561198053858673'])
        server = GameServer.create(user, '127.0.0.1', '27015', 'password')
        server.in_use = True

        GameServer.create(user, '127.0.0.1', '27016', 'password')
        db.session.commit()

        Match.create(user, team1.id, team2.id, 1, False,
                     'Map {MAPNUMBER}', ['de_dust2', 'de_cache', 'de_mirage'], server.id)
        db.session.commit()
Esempio n. 58
0
def backdoor(request):
	war = war_gogo_or_404()
	thisround = round_gogo_or_404(war, '/time') #First round should be gogo
	if request.method == 'POST': 
		form = BackdoorLoginForm(request.POST) 
		if form.is_valid(): 
			team = Team(war=war, 
				name=form.cleaned_data['team_name'], 
				passed_open_round_at=datetime.now(), 
				confirmed=False)
			team.save()
			return render_to_response('codewars2013/success.html', {})
	else:
		form = BackdoorLoginForm() 
	return render_to_response('codewars2013/backdoor.html', {
		'form': form,
	}, context_instance=RequestContext(request))
Esempio n. 59
0
def build_teams():
    clubs = Club.objects.all()
    levels = Level.objects.all()
    for c in clubs:
        count_teams = randint(2,6)
        index = 0
        selected = []
        while index < count_teams:
            level = levels[randint(0, levels.count() - 1)]
            while level in selected:
                level = levels[randint(0, levels.count() - 1)]
            selected.append(level)
            team_name = '{club_name} {level_name}'.format(club_name=c.name, level_name=level.description)
            t = Team(name=team_name, club=c)
            t.save()
            t.level.add(level)
            index += 1