Example #1
0
    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')]
Example #2
0
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)
Example #3
0
 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()
Example #4
0
    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)
Example #5
0
    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)
Example #6
0
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 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
Example #8
0
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)
Example #9
0
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
Example #10
0
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 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')
Example #12
0
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 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()
Example #14
0
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()
Example #15
0
def zhuce():
    if request.method == 'POST':
        topics = request.form.getlist('topic')
        email = request.form['email']
        pwd = request.form['pwd']
        phone = request.form['phone']
        licence = request.form['licence']
        newlicence = (str(time.strftime(ISOTIMEFORMAT)) +
                      str(random.randint(1000, 9999)) +
                      os.path.splitext(licence)[1])
        path = getpath("licence")
        os.rename(os.path.join(path, licence), os.path.join(path, newlicence))
        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 = ''
        for ser in service_cn:
            service_cnn = (service_cnn + ser) + ','
        dbcnn()
        cursor = g.cnn.cursor()
        try:
            sql = "select email from userinfo where email = %s"
            data = (email, )
            cursor.execute(sql, data)
            result = cursor.fetchone()
            if result is not None and result[0] == email:
                msg = '邮箱已注册'
                return render_template('zhuce.html', message=msg)
            sql = "insert into userinfo (email, pwd, createtime, phone, " \
                  "licence, company, introduce, location, service) VALUES " \
                  "(%s, password(%s), now(), %s, %s, %s, %s, %s, %s)"
            data = (email, pwd, phone, newlicence, company, introduce,
                    location_cn, service_cnn[:-1])
            cursor.execute(sql, data)
            g.cnn.commit()
            sql = "select id from userinfo where email = %s"
            data = (email, )
            cursor.execute(sql, data)
            userid = cursor.fetchone()[0]
            service.append(location)
            for ser in service:
                for topic in topics:
                    db.session.add(Match(userid, int(ser), int(topic)))
            db.session.commit()
        except Exception as e:
            print('error!{}'.format(e))
            msg = "注册失败错误,错误原因%s" % e
            return render_template('zhuce.html', message=msg)
        return render_template('zhuce_success.html')
    else:
        return render_template('zhuce.html', topics=topic_dict)
Example #16
0
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)
Example #17
0
    def get_text_list_need_approve(self):
        t = datetime.now().timetuple()
        seconds = local_to_utc(t)
        items = []
        match = Match(public=1,
                      date=seconds - 100,
                      reportTime=seconds + 200,
                      disputeTime=seconds + 300,
                      source_id=3)
        db.session.add(match)
        db.session.commit()
        items.append(match)

        outcome = Outcome(match_id=match.id, name="test approve", approved=-1)
        db.session.add(outcome)
        items.append(outcome)
        db.session.commit()

        match1 = Match(public=0,
                       date=seconds - 100,
                       reportTime=seconds + 200,
                       disputeTime=seconds + 300,
                       source_id=3)
        db.session.add(match1)
        db.session.commit()
        items.append(match1)

        outcome1 = Outcome(match_id=match1.id,
                           name="test approve",
                           approved=-1)
        db.session.add(outcome1)
        db.session.commit()
        items.append(outcome1)

        text = match_bl.get_text_list_need_approve()
        for item in items:
            db.session.delete(item)
            db.session.commit()

        self.assertTrue(text != '')
Example #18
0
    def post(self):
        args = self.reqparse.parse_args()
        defender = User.query.filter_by(id=args['defender_id']).first()
        if not defender:
            return {'error' : 'no such defender'}
        sport = Sport.query.filter_by(name=args['sport']).first()
        if not sport:
            return {'error' : 'no such sport'}

        match = Match(challenger_id=current_user.id, defender_id=defender.id, sport_id=sport.id)
        db.session.add(match)
        db.session.commit()
        return {'message' : 'success'}
Example #19
0
    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()
Example #20
0
def init_matches(word_list):
    while word_list:  # removes words from array until empty
        pair = random.sample(word_list, k=2)
        word_list.remove(pair[0])
        word_list.remove(pair[1])

        word_1 = Word(word=pair[0], matched=True)
        word_2 = Word(word=pair[1], matched=True)
        db.session.add(word_1)
        db.session.add(word_2)

        match = Match(word_1=word_1.word, word_2=word_2.word)
        db.session.add(match)
    db.session.commit()
Example #21
0
    def test_get_list_match_resolve_by_admin(self):
        self.clear_data_before_test()
        arr_hs = []
        t = datetime.now().timetuple()
        seconds = local_to_utc(t)
        # -----

        match2 = Match(date=seconds - 200,
                       reportTime=seconds - 100,
                       disputeTime=seconds + 300,
                       created_user_id=88,
                       name="Dispute")
        db.session.add(match2)
        db.session.commit()

        # -----

        outcome1 = Outcome(match_id=match2.id,
                           hid=1,
                           result=CONST.RESULT_TYPE['DISPUTED'],
                           contract_id=1)
        db.session.add(outcome1)
        db.session.commit()

        with self.client:
            response = self.client.get(
                'admin/match/resolve',
                headers={
                    "Authorization":
                    "Bearer {}".format(
                        create_access_token(identity=app.config.get("EMAIL"),
                                            fresh=True)),
                    "Uid":
                    "{}".format(88),
                    "Fcm-Token":
                    "{}".format(123),
                    "Payload":
                    "{}".format(123),
                })

            data = json.loads(response.data.decode())
            self.assertTrue(data['status'] == 1)
            data_json = data['data']
            tmp = None
            for m in data_json:
                if m['id'] == match2.id:
                    tmp = m
                    break
            self.assertNotEqual(tmp, None)
Example #22
0
    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
Example #23
0
    def post(self, user_id):
        # Create match given mentor_id and timestamp
        _ = get_user(user_id)

        try:
            json_data = request.get_json()
            mentor_id = json_data['mentor_id']
            timestamp = json_data['timestamp']
        except Exception as why:
            # Log input strip or etc. errors.
            logging.info("Given Data is wrong. " + str(why))
            # Return invalid input errors
            message.set_data({"match": "Given match data is wrong format"})
            return message.INVALID_INPUT_422

        # Check if existing mentor
        if User.query.filter_by(id=mentor_id).first() is None:
            message.set_data({"mentor_id": "Mentor does not exist"})
            return message.NOT_FOUND_404

        # Use heart
        heart_json = Hearts.put(Resource, user_id)
        if heart_json[1] != 200:
            return heart_json
        heart_id = heart_json[0]['data']['id']

        # Create random match id
        id = uuid.uuid1()
        # Repeat if id already exists
        while (match_loader(id) is not None):
            id = uuid.uuid1()

        # Create a new match
        match = Match(id=id,
                      heart_id=heart_id,
                      student_id=user_id,
                      mentor_id=mentor_id,
                      timestamp=timestamp,
                      fulfilled=False)

        # Add match to session.
        db.session.add(match)

        # Commit session.
        db.session.commit()

        message.set_data({"id": match.id})
        return message.SUCCESS
Example #24
0
def matchadd():
    avatar = base64.b64encode ( current_user.avatar ).decode ( 'ascii' )
    '''if current_user.username != 'admin':
        return redirect(url_for('matchs'))
    form = MatchEditForm()
    if form.validate_on_submit():'''
    if request.method == 'POST':

        match = Match(team1=request.form.get('team1'), team2=request.form.get('team2'), timestamp=request.form.get('datetime'), t1_res=0,
                      t2_res=0)
        db.session.add(match)
        db.session.commit()
        flash('Матч добавлен')
        return redirect(url_for('matchs'))

    return render_template('matchadd.html', avatar=avatar) #form=form
Example #25
0
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
Example #26
0
    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)
Example #27
0
    def _create_match(tournament_id, match_id, next_match_id, flag=0):
        print("======= MATCH ========")
        print(f"tournament_id = {tournament_id}")
        print(f"match_id = {match_id} --> {next_match_id}")
        print(f"flag = {flag}")
        match = Match(
            match_id=match_id,
            tournament_id=tournament_id,
            next_match_id=next_match_id,
            flag=flag,
        )
        """
        user_id_1 = db.Column(db.Integer, db.ForeignKey('user.id'))
        user_id_2 = db.Column(db.Integer, db.ForeignKey('user.id'))

        results = db.Column(db.Text)
        results_by_user_id_1 = db.Column(db.Text)
        results_by_user_id_2 = db.Column(db.Text)
        """
        print("======================")
        return match
Example #28
0
 def insert_into_matches(self):
     # This one is specific so maybe I'll let it be
     for match in self.data.matches:
         serie = Serie.query.filter_by(api_id=match['serie_api_id']).first()
         bo = Bo.query.filter_by(name=match['bo']).first()
         status = Status.query.filter_by(name=match['status']).first()
         date = (match['date'])
         match_to_add = Match(
             api_id=match['api_id'],
             serie_id=serie.id,
             date=datetime(int(date[:4]), int(date[5:7]), int(date[8:10]),
                           int(date[11:13]), int(date[14:16]),
                           int(date[17:19])),  #flemme
             best_of=bo.id,
             match_status=status.id,
         )
         try:
             db.session.add(match_to_add)
             db.session.commit()
         except IntegrityError:
             db.session.rollback()
Example #29
0
 def form_valid(self, form):
     data = form.cleaned_data
     item = Item.objects.get(id=self.kwargs['item_id'])
     item.name_item = data['name']
     item.description = data['description']
     object = Object.objects.get(item=item)
     object.type = data['type']
     requeriment = Requirement(name=item.name_item, type=object.type,
                               status=True, owner=self.request.user,
                               description=item.description)
     requeriment.save()
     match = Match(requirement=requeriment, item=item)
     match.save()
     donation = Donation(donator=item.owner, institute=requeriment.owner, item=item,
                         data=datetime.datetime.today().strftime('%Y-%m-%d'), is_completed=False)
     donation.save()
     notification = Notification(user=requeriment.owner, match=match)
     notification.save()
     notification = Notification(user=item.owner, match=match)
     notification.save()
     messages.success(self.request, "Nova Necessidade cadastrada com sucesso!")
     return super(NewItemRequerimentView, 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()

        # create outcome
        outcome = Outcome.find_outcome_by_id(88)
        if outcome is None:
            outcome = Outcome(id=88,
                              match_id=1,
                              name="1",
                              hid=88,
                              created_user_id=66)
            db.session.add(outcome)
            db.session.commit()

        else:
            outcome.name = "1"
            outcome.created_user_id = 66
            db.session.commit()