Exemple #1
0
def get_or_create_server(s_name, s_url, u_email, u_password, s_token=None):
    if s_token is None:
        s_token = uuid4()
    server_admin_role = user_datastore.find_role(SERVER_ADMIN_ROLE.name)
    server_admin = get_or_create_user(u_email, u_password, server_admin_role, confirmed_at=datetime.datetime.now())
    server = GoServer.query.filter(GoServer.name==s_name).first()
    if not server:
        server = GoServer(name=s_name, url=s_url, token=s_token)
    server.admins.append(server_admin)
    db.session.add(server)
    db.session.commit()
    return server
Exemple #2
0
def create_extra_data():
    #Make a bunch of example users
    role_user = user_datastore.find_role('user')
    users = []
    for i in range(60):
        u = User(email='*****@*****.**'%i, aga_id = 100000+i, password=encrypt_password('test'))
        user_datastore.add_role_to_user(u,role_user)
        db.session.add(u)
        users.append(u)
    db.session.commit()

    for u in users:
        for j in range(2):
            db.session.add(Player(name="Player-%d-%d" % (u.id,j), server_id=1, user_id=u.id, token="Player-%d-%d" % (u.id,j)))

    db.session.commit()

    users = User.query.all()
    p_priors = {user.id: random.randint(0,40) for user in users}
    print("Prior ratings")
    for p in sorted(p_priors, key=lambda k: p_priors[k]):
        print("%d: %f" % (p,p_priors[p]))

    import rating.rating_math as rm
    def choose_pair():
        while True:
            pair = random.sample(users, 2)
            diff = abs(p_priors[pair[0].id] - p_priors[pair[1].id])
            if len(pair[0].players) > 0 and len(pair[1].players) > 0 and diff < 10:
                break
        return pair

    def make_game():
        user_pair = choose_pair()
        ps = (random.choice(user_pair[0].players).id, random.choice(user_pair[1].players).id)
        result = "B+5" if random.random() < rm.expect(p_priors[user_pair[0].id], p_priors[user_pair[1].id], 0, 6.5) else "W+5"
        g = Game(server_id=1, white_id=ps[0], black_id=ps[1],
                rated=False, result=result, game_record=sgf_data,
                date_played=datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0,10000000)))
        return g

    print("Games...")
    games = [make_game() for i in range(2000)]
    print("Saving games...")
    for g in games:
        db.session.add(g)
    db.session.commit() 
    strongest = max(p_priors, key = lambda k: p_priors[k])
    strongest_games = [str(g) for g in games if g.white.user_id == strongest or g.black.user_id == strongest]
    print("Strongest, %d (%f):\n%s"% (strongest, p_priors[strongest], strongest_games))
Exemple #3
0
def get_or_create_server(s_name, s_url, u_email, u_password, s_token=None):
    if s_token is None:
        s_token = uuid4()
    server_admin_role = user_datastore.find_role(SERVER_ADMIN_ROLE.name)
    server_admin = get_or_create_user(u_email,
                                      u_password,
                                      server_admin_role,
                                      confirmed_at=datetime.datetime.now())
    server = GoServer.query.filter(GoServer.name == s_name).first()
    if not server:
        server = GoServer(name=s_name, url=s_url, token=s_token)
    server.admins.append(server_admin)
    db.session.add(server)
    db.session.commit()
    return server
def get_users():
    _role = request.args.get('role', None)
    if not _role:
        return jsonify({'message': 'Specify class of fields to retrieve'})
    if type(_role) != str or (_role != 'all' and
                              user_datastore.find_role(role=_role) is None):
        return jsonify({'message': 'Non-existent role'})
    if _role == 'all':
        return jsonify({'message': User.retrieve_users(User.query.all())})
    users = [
        User.retrieve_users(
            User.query.filter_by(user_id=role.user_id).all())[0]
        for role in db.session.query(user_roles).filter_by(
            role_id=Role.query.filter_by(name=_role).first().id).all()
    ]
    return jsonify({'message': users})
def register():
    if request.method == 'POST':
        try:
            # Get sent data
            data, message, status, response_code = request.form.to_dict(
            ), '', 0, 202

            # no data sent
            if not data:
                return make_response(
                    jsonify({
                        'message': 'Data is missing',
                        'status': -1
                    })), response_code

            fullname, phone_number, id_number = data['official_names'], data[
                'phone_number'], data['id_number']
            residency, gender = data.get(
                'residency', 'Nairobi'), data.get('gender', '') or ''
            role, relative, caregiver = data['role'], data.get(
                'relative', ''), data.get('caregiver', '')

            # Ensure the key details are not missing
            if not role:
                return make_response(
                    jsonify({
                        'message': 'Role is missing',
                        'status': 1
                    })), response_code
            if not fullname:
                return make_response(
                    jsonify({
                        'message': 'Official names are missing',
                        'status': 1
                    })), response_code
            if not phone_number:
                return make_response(
                    jsonify({
                        'message': 'Phone number is missing',
                        'status': 1
                    })), response_code
            if not id_number:
                return make_response(
                    jsonify({
                        'message': "ID number is missing",
                        'status': 1
                    })), response_code

            # Confirm role given is valid
            if user_datastore.find_role(role=role) is None:
                return make_response(
                    jsonify({
                        'message': 'Non-existent role',
                        'status': -3
                    })), 401

            if role == 'patient':
                if not relative:
                    return jsonify({
                        'message': 'At least 1 relative required',
                        'status': 1
                    }), response_code
                if not User.query.filter(User.user_id == relative).first():
                    return jsonify(
                        {'message':
                         'Relative provided not registered'}), response_code
                if not caregiver:
                    return jsonify({
                        'message': 'At least 1 caregiver required',
                        'status': 1
                    }), response_code
                if not User.query.filter(User.user_id == caregiver).first():
                    return jsonify(
                        {'message':
                         'Caregiver provided not registered'}), response_code

            # Check format of phone number
            message, status = validate_phone_number(phone_number)
            if status:
                return make_response(jsonify({
                    'message': message,
                    'status': 7
                })), 202
            parts = [x.strip() for x in message.split('.')]
            phone_number = parts[1].split(':')[-1].strip()

            # check if user is already registered
            if User.query.filter_by(phoneNumber=phone_number).first():
                return make_response(
                    jsonify({
                        'message': 'Phone Number already registered',
                        'status': 5
                    })), 202

            # receive profile picture
            message, status = upload_file(request.files,
                                          fullname,
                                          file_type='image',
                                          tag="profile_picture")
            if status or type(message) == str:
                return jsonify({'message': message, "status": -4}), 401
            else:
                profile_picture = message['http_url']

            if role == 'caregiver' or role == 'admin':
                # receive ID picture
                message, status = upload_file(request.files,
                                              fullname,
                                              file_type='image',
                                              tag="identification_picture")
                if status or type(message) == str:
                    return jsonify({'message': message, "status": -4}), 401
                else:
                    identification_picture = message['http_url']
            else:
                identification_picture = ''

            # Create user with given role
            user_id = User.generate_user_id(role)
            try:
                user_datastore.create_user(
                    user_id=user_id,
                    fullname=fullname,
                    phoneNumber=phone_number,
                    profile_picture=profile_picture,
                    identification_number=id_number,
                    roles=[role],
                    identification_picture=identification_picture,
                    gender=gender,
                    residence=residency,
                )
                if role == 'patient':
                    db.session.add(
                        PatientRelative(relative=relative,
                                        patient=user_id,
                                        tag='primary'))
                    db.session.add(
                        PatientCaregiver(caregiver=caregiver,
                                         patient=user_id,
                                         tag='primary'))

                db.session.commit()
            except Exception as err:
                print(err)
                db.session.rollback()
                system_logging(msg=err, exception=True)
                return make_response(
                    jsonify({
                        'message': "Error saving user",
                        'status': 9
                    })), 202

            user = User.query.filter(User.phoneNumber == phone_number).first()
            user.launch_task('send_account_confirmation_sms',
                             'Sending account confirmation OTP SMS',
                             phone_number)

            return make_response(
                jsonify({
                    'message': 'Successful user addition',
                    'status': status
                })), 200
        except Exception as err:
            print(err)
            system_logging(err, exception=True)
            message = "Error during user registration"
            return make_response(jsonify({
                'message': message,
                'status': -2
            })), 401
def create_extra_data():
    basedir = os.path.abspath(os.path.dirname(__file__))
    with open(os.path.join(basedir, 'tests/testsgf.sgf')) as sgf_file:
        sgf_data = "\n".join(sgf_file.readlines()).encode()
    role_user = user_datastore.find_role('user')
    users = []
    for i in range(60):
        u = User(email='*****@*****.**' % i,
                 aga_id=100000 + i,
                 password=encrypt_password('test'))
        user_datastore.add_role_to_user(u, role_user)
        db.session.add(u)
        users.append(u)
    db.session.commit()

    for u in users:
        for j in range(2):
            db.session.add(
                Player(name="Player-%d-%d" % (u.id, j),
                       server_id=1,
                       user_id=u.id,
                       token="Player-%d-%d" % (u.id, j)))

    db.session.commit()

    users = User.query.all()
    players = Player.query.all()
    p_priors = {user.id: random.randint(0, 40) for user in users}
    print("Prior ratings")
    for p in sorted(p_priors, key=lambda k: p_priors[k]):
        print("%d: %f" % (p, p_priors[p]))

    import rating.rating_math as rm

    def choose_pair():
        while True:
            pair = random.sample(users, 2)
            diff = abs(p_priors[pair[0].id] - p_priors[pair[1].id])
            if len(pair[0].players) > 0 and len(
                    pair[1].players) > 0 and diff < 10:
                break
        return pair

    def make_game():
        user_pair = choose_pair()
        ps = (random.choice(user_pair[0].players).id,
              random.choice(user_pair[1].players).id)
        result = "B+5" if random.random() < rm.expect(
            p_priors[user_pair[0].id], p_priors[user_pair[1].id], 0,
            6.5) else "W+5"
        g = Game(server_id=1,
                 white_id=ps[0],
                 black_id=ps[1],
                 rated=False,
                 result=result,
                 game_record=sgf_data,
                 date_played=datetime.datetime.now() -
                 datetime.timedelta(seconds=random.randint(0, 10000000)))
        return g

    print("Games...")
    games = [make_game() for i in range(2000)]
    print("Saving games...")
    for g in games:
        db.session.add(g)
    db.session.commit()
    strongest = max(p_priors, key=lambda k: p_priors[k])
    strongest_games = [
        str(g) for g in games
        if g.white.user_id == strongest or g.black.user_id == strongest
    ]
    print("Strongest, %d (%f):\n%s" %
          (strongest, p_priors[strongest], strongest_games))

    def make_tournament():
        t = Tournament(event_name="The Ultimate Go-ing Championship",
                       start_date=datetime.datetime.now(),
                       venue="LasVegas",
                       director="Donald J. Trump",
                       director_phone="555-5555",
                       director_email="*****@*****.**",
                       pairing="McMahon",
                       rule_set="AGA",
                       time_controls="required field",
                       basic_time="required field",
                       overtime_format="required field",
                       overtime_conditions="required field",
                       komi="7",
                       tie_break1="SOS",
                       tie_break2="SODOS")
        return t

    print("Tournament...")
    t = make_tournament()
    print("Saving tournament...")
    db.session.add(t)
    db.session.commit()
Exemple #7
0
def create_extra_data():
    #Make a bunch of example users
    role_user = user_datastore.find_role('user')
    users = []
    for i in range(60):
        u = User(email='*****@*****.**' % i,
                 aga_id=100000 + i,
                 password=encrypt_password('test'))
        user_datastore.add_role_to_user(u, role_user)
        db.session.add(u)
        users.append(u)
    db.session.commit()

    for u in users:
        for j in range(2):
            db.session.add(
                Player(name="Player-%d-%d" % (u.id, j),
                       server_id=1,
                       user_id=u.id,
                       token="Player-%d-%d" % (u.id, j)))

    db.session.commit()

    users = User.query.all()
    p_priors = {user.id: random.randint(0, 40) for user in users}
    print("Prior ratings")
    for p in sorted(p_priors, key=lambda k: p_priors[k]):
        print("%d: %f" % (p, p_priors[p]))

    import rating.rating_math as rm

    def choose_pair():
        while True:
            pair = random.sample(users, 2)
            diff = abs(p_priors[pair[0].id] - p_priors[pair[1].id])
            if len(pair[0].players) > 0 and len(
                    pair[1].players) > 0 and diff < 10:
                break
        return pair

    def make_game():
        user_pair = choose_pair()
        ps = (random.choice(user_pair[0].players).id,
              random.choice(user_pair[1].players).id)
        result = "B+5" if random.random() < rm.expect(
            p_priors[user_pair[0].id], p_priors[user_pair[1].id], 0,
            6.5) else "W+5"
        g = Game(server_id=1,
                 white_id=ps[0],
                 black_id=ps[1],
                 rated=False,
                 result=result,
                 game_record=sgf_data,
                 date_played=datetime.datetime.now() -
                 datetime.timedelta(seconds=random.randint(0, 10000000)))
        return g

    print("Games...")
    games = [make_game() for i in range(2000)]
    print("Saving games...")
    for g in games:
        db.session.add(g)
    db.session.commit()
    strongest = max(p_priors, key=lambda k: p_priors[k])
    strongest_games = [
        str(g) for g in games
        if g.white.user_id == strongest or g.black.user_id == strongest
    ]
    print("Strongest, %d (%f):\n%s" %
          (strongest, p_priors[strongest], strongest_games))
def create_extra_data():
    basedir = os.path.abspath(os.path.dirname(__file__))
    with open(os.path.join(basedir, 'tests/testsgf.sgf')) as sgf_file:
        sgf_data = "\n".join(sgf_file.readlines()).encode()
    role_user = user_datastore.find_role('user')
    users = []
    for i in range(60):
        u = User(email='*****@*****.**'%i, aga_id = 100000+i, password=encrypt_password('test'))
        user_datastore.add_role_to_user(u,role_user)
        db.session.add(u)
        users.append(u)
    db.session.commit()

    for u in users:
        for j in range(2):
            db.session.add(Player(name="Player-%d-%d" % (u.id,j), server_id=1, user_id=u.id, token="Player-%d-%d" % (u.id,j)))

    db.session.commit()

    users = User.query.all()
    players = Player.query.all()
    p_priors = {user.id: random.randint(0,40) for user in users}
    print("Prior ratings")
    for p in sorted(p_priors, key=lambda k: p_priors[k]):
        print("%d: %f" % (p,p_priors[p]))

    import rating.rating_math as rm
    def choose_pair():
        while True:
            pair = random.sample(users, 2)
            diff = abs(p_priors[pair[0].id] - p_priors[pair[1].id])
            if len(pair[0].players) > 0 and len(pair[1].players) > 0 and diff < 10:
                break
        return pair

    def make_game():
        user_pair = choose_pair()
        ps = (random.choice(user_pair[0].players).id, random.choice(user_pair[1].players).id)
        result = "B+5" if random.random() < rm.expect(p_priors[user_pair[0].id], p_priors[user_pair[1].id], 0, 6.5) else "W+5"
        g = Game(server_id=1, white_id=ps[0], black_id=ps[1],
                rated=False, result=result, game_record=sgf_data,
                date_played=datetime.datetime.now() - datetime.timedelta(seconds=random.randint(0,10000000)))
        return g

    print("Games...")
    games = [make_game() for i in range(2000)]
    print("Saving games...")
    for g in games:
        db.session.add(g)
    db.session.commit()
    strongest = max(p_priors, key = lambda k: p_priors[k])
    strongest_games = [str(g) for g in games if g.white.user_id == strongest or g.black.user_id == strongest]
    print("Strongest, %d (%f):\n%s"% (strongest, p_priors[strongest], strongest_games))

    def make_tournament():
        t = Tournament(event_name="The Ultimate Go-ing Championship",
                       start_date=datetime.datetime.now(),
                       venue="LasVegas",
                       director="Donald J. Trump",
                       director_phone="555-5555",
                       director_email="*****@*****.**",
                       pairing="McMahon",
                       rule_set="AGA",
                       time_controls="required field",
                       basic_time="required field",
                       overtime_format="required field",
                       overtime_conditions="required field",
                       komi="7",
                       tie_break1="SOS",
                       tie_break2="SODOS")
        return t

    print("Tournament...")
    t = make_tournament()
    print("Saving tournament...")
    db.session.add(t)
    db.session.commit()