Exemple #1
0
    def test_contest(self):
        """test the contest table"""
        CONTEST_ARGS = {
            "name": "1620 bracket",
            "activate_time": model.str_to_dt('2017-01-25T10:45Z'),
            "start_time": model.str_to_dt('2017-01-25T11:00Z'),
            "freeze_time": model.str_to_dt('2017-01-25T16:00Z'),
            "end_time": model.str_to_dt('2017-01-25T16:45Z'),
            "deactivate_time": model.str_to_dt('2017-01-26T10:45Z'),
            "is_public": True,
        }
        user_args, user = get_user()
        problem_args, problem = get_problem()

        # create and add contest
        contest = model.Contest(**CONTEST_ARGS)
        contest.users.append(user)
        contest.problems.append(problem)

        db_session.add(contest)
        db_session.commit()

        # fetch contest
        results = model.Contest.query.filter_by(
            name=CONTEST_ARGS['name']).all()

        self.assertEqual(len(results), 1)
Exemple #2
0
def get_contest():
    """returns a test contest"""
    CONTEST_ARGS = {
        "name": "1620 bracket",
        "start_time": util.str_to_dt("2017-01-25T11:00:00Z"),
        "end_time": util.str_to_dt("2017-01-25T16:45:00Z"),
        "is_public": True,
    }

    # create and add contest
    contest = model.Contest(**CONTEST_ARGS)
    db_session.add(contest)
    db_session.commit()

    return CONTEST_ARGS, contest
Exemple #3
0
def setup_contest():
    roles = {x.name: x for x in model.UserRole.query.all()}
    test_contestant = model.User(
        "testuser", "Test User", "pass", user_roles=[roles["defendant"]]
    )
    test_executioner = model.User(
        "testexec", "Test Executioner", "epass", user_roles=[roles["executioner"]]
    )
    test_contest = model.Contest(
        "test_contest",
        util.str_to_dt("2017-02-05T22:04:00Z"),
        util.str_to_dt("2030-01-01T11:11:00Z"),
        True,
    )
    io_problem_type = model.ProblemType.query.filter_by(name="input-output").one()
    test_problem = model.Problem(
        io_problem_type,
        "fizzbuzz",
        "FizzBuzz",
        "## FizzBuzz\nPerform fizzbuzz up to the given number",
        "3",
        "1\n2\nFizz",
        "15",
        "1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\n9\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n",
    )
    test_contest.problems.append(test_problem)
    test_contest.users.append(test_contestant)

    python = model.Language.query.filter_by(name="python").one()
    test_run = model.Run(
        test_contestant,
        test_contest,
        python,
        test_problem,
        util.str_to_dt("2017-02-05T23:00:00Z"),
        'import sys\nn=raw_input()\nfor i in range(1, n+1): print("Fizz"*(i%3==0)+"Buzz"*(i%5==0) or i)',
        test_problem.secret_input,
        test_problem.secret_output,
        True,
    )

    db_session.add_all(
        [test_executioner, test_contestant, test_contest, test_problem, test_run]
    )
    db_session.commit()
Exemple #4
0
def get_contest():
    """returns a test contest"""
    CONTEST_ARGS = {
        "name": "1620 bracket",
        "activate_time": model.str_to_dt('2017-01-25T10:45Z'),
        "start_time": model.str_to_dt('2017-01-25T11:00Z'),
        "freeze_time": model.str_to_dt('2017-01-25T16:00Z'),
        "end_time": model.str_to_dt('2017-01-25T16:45Z'),
        "deactivate_time": model.str_to_dt('2017-01-26T10:45Z'),
        "is_public": True,
    }

    # create and add contest
    contest = model.Contest(**CONTEST_ARGS)
    db_session.add(contest)
    db_session.commit()

    return CONTEST_ARGS, contest
Exemple #5
0
def dev_populate_db():
    """Performs the initial database setup for the application
    """
    current_app.logger.info("Initializing tables with dev data")
    roles = {x.name: x for x in model.UserRole.query.all()}

    db_session.add_all([
        model.User(
            "*****@*****.**",
            "SuperUser",
            "pass",
            user_roles=list(roles.values())),
        model.User(
            "*****@*****.**",
            "ObserverUser",
            "pass",
            user_roles=[roles['observer']])
    ])

    contestants = []
    names = [
        "Fred", "George", "Jenny", "Sam", "Jo", "Joe", "Sarah", "Ben",
        "Josiah", "Micah"
    ]
    for i in range(1, 5):
        test_contestant = model.User(
            "testuser{}@example.org".format(i),
            names[i - 1],
            "pass",
            user_roles=[roles['defendant']])
        db_session.add(test_contestant)
        contestants.append(test_contestant)

    # create test contest
    now = datetime.datetime.utcnow()
    test_contest = model.Contest(
        name="test_contest",
        start_time=now,
        end_time=now + datetime.timedelta(minutes=30),
        is_public=True,
        activate_time=now,
        freeze_time=None,
        deactivate_time=None)
    test_contest.users += contestants
    db_session.add(test_contest)

    io_problem_type = model.ProblemType.query.filter_by(
        name="input-output").one()
    problems = []

    hello_world = model.Problem(io_problem_type, "hello-world",
                                "Hello, World!",
                                'Print the string "Hello, World!"', "",
                                "Hello, World!", "", "Hello, World!")
    problems.append(hello_world)
    test_contest.problems.append(hello_world)
    db_session.add(hello_world)

    hello_worlds = model.Problem(
        io_problem_type, "hello-worlds", "Hello, Worlds!",
        'Print the string "Hello, World!" n times', "2",
        "Hello, World!\nHello, World!", "5",
        "Hello, World!\nHello, World!\nHello, World!\nHello, World!\nHello, World!\n"
    )
    problems.append(hello_worlds)
    test_contest.problems.append(hello_worlds)
    db_session.add(hello_worlds)

    fizzbuzz = model.Problem(
        io_problem_type, "fizzbuzz", "FizzBuzz",
        "Perform fizzbuzz up to the given number\n\nMore info can be found [here](https://en.wikipedia.org/wiki/Fizz_buzz)",
        "3", "1\n2\nFizz", "15",
        "1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n"
    )
    problems.append(fizzbuzz)
    test_contest.problems.append(fizzbuzz)
    db_session.add(fizzbuzz)

    fibonacci = model.Problem(
        io_problem_type, "fibonoacci", "Fibonacci",
        "Give the nth number in the Fibonacci sequence", "4", "3", "5",
        "5")
    problems.append(fibonacci)
    test_contest.problems.append(fibonacci)
    db_session.add(fibonacci)

    ext_fibonacci = model.Problem(
        io_problem_type, "ext-fib", "Extended Fibonacci",
        "Give the the numbers of the Fibonacci sequence between 0 and n, inclusive.\nIf n is positive, the range is [0,n].\nIf n is negative, the range is [n,0].",
        "-3", "2\n-1\n1\n0", "-5", "5\n-3\n2\n-1\n1\n0")
    problems.append(ext_fibonacci)
    test_contest.problems.append(ext_fibonacci)
    db_session.add(ext_fibonacci)

    # insert submissions
    python = model.Language.query.filter_by(name="python").one()

    solutions = {
        "Hello, World!":
        "print('Hello, World!')",
        "Hello, Worlds!":
        "for i in range(int(input())):\n\tprint('Hello, World!')",
        "FizzBuzz":
        'print("\\n".join("Fizz"*(i%3==0)+"Buzz"*(i%5==0) or str(i) for i in range(1,int(input())+1)))',
        "Fibonacci":
        "fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2)\nprint(fib(int(input())))",
        "Extended Fibonacci":
        "print('5\\n-3\\n2\\n-1\\n1\\n0')"
    }

    problem_subs = []
    for problem in problems:
        for user in contestants:
            for _ in range(2):
                problem_subs.append((problem, user))

    random.shuffle(problem_subs)

    for problem, user in problem_subs:
        src_code = solutions[problem.name]
        is_submission = random.randint(1, 7) != 5

        is_priority = random.randint(1, 9) == 7
        is_correct = random.randint(1, 2) == 2
        if not is_correct:
            src_code = src_code + "\nprint('Wait this isn\\'t correct')"

        test_run = model.Run(user, test_contest, python, problem,
                             datetime.datetime.utcnow(), src_code,
                             problem.secret_input, problem.secret_output,
                             is_submission)
        test_run.is_correct = is_correct
        test_run.is_priority = is_priority
        test_run.state = "Judging"

        db_session.add(test_run)
    db_session.commit()
Exemple #6
0
def add_contest():
    """
    Adds or edits a contest

    Note:
        must be called from within a request context

    Returns:
        a redirect to the contest view page
    """
    name = request.form.get("name")
    activate_date = request.form.get("activate_date")
    activate_time = request.form.get("activate_time")
    start_date = request.form.get("start_date")
    start_time = request.form.get("start_time")
    freeze_date = request.form.get("freeze_date")
    freeze_time = request.form.get("freeze_time")
    end_date = request.form.get("end_date")
    end_time = request.form.get("end_time")
    deactivate_date = request.form.get("deactivate_date")
    deactivate_time = request.form.get("deactivate_time")
    is_public = request.form.get("is_public")
    user_usernames = request.form.get("users")
    problem_slugs = request.form.get("problems")

    if activate_date is not "" and activate_time is not "":
        activate_date_time = util.strs_to_dt(activate_date, activate_time)
    else:
        activate_date_time = None

    if freeze_date is not "" and freeze_time is not "":
        freeze_date_time = util.strs_to_dt(freeze_date, freeze_time)
    else:
        freeze_date_time = None

    if deactivate_date is not "" and deactivate_time is not "":
        deactivate_date_time = util.strs_to_dt(deactivate_date,
                                               deactivate_time)
    else:
        deactivate_date_time = None

    if name is None:
        error = "Failed to add contest due to undefined contest name."
        current_app.logger.info(error)
        flash(error, "danger")
        return redirect(url_for("contests.contests_view"))

    # convert is_public to a bool
    is_public_bool = util.checkbox_result_to_bool(is_public)
    if is_public_bool is None:
        error = "Failed to add contest '{}' due to invalid is_public check.".format(
            name)
        current_app.logger.info(error)
        flash(error, "danger")
        return redirect(url_for("contests.contests_view"))

    contest_id = util.i(request.form.get("contest_id"))
    if contest_id:  # edit
        contest = model.Contest.query.filter_by(id=int(contest_id)).one()
        contest.name = name
        contest.is_public = is_public_bool

        contest.activate_time = activate_date_time
        contest.start_time = util.strs_to_dt(start_date, start_time)
        contest.freeze_time = freeze_date_time
        contest.end_time = util.strs_to_dt(end_date, end_time)
        contest.deactivate_time = deactivate_date_time

        contest.users = users_from_usernames(user_usernames.split(), model)
        contest.problems = problems_from_slugs(problem_slugs.split(), model)
    else:  # add
        if is_dup_contest_name(name):
            error = "Failed to add contest '{}' as contest already exists.".format(
                name)
            current_app.logger.info(error)
            flash(error, "danger")
            return redirect(url_for("contests.contests_view"))

        contest = model.Contest(
            name=name,
            is_public=is_public_bool,
            activate_time=activate_date_time,
            start_time=util.strs_to_dt(start_date, start_time),
            freeze_time=freeze_date_time,
            end_time=util.strs_to_dt(end_date, end_time),
            deactivate_time=deactivate_date_time,
            users=users_from_usernames(user_usernames.split(), model),
            problems=problems_from_slugs(problem_slugs.split(), model),
        )
        db_session.add(contest)

    db_session.commit()

    # If a problem is added to a contest, the cached runs will be
    # inaccurate. Clear the run cache to fix this.
    util.invalidate_cache(util.RUN_CACHE_NAME)

    return redirect(url_for("contests.contests_view"))
Exemple #7
0
def populate_db():
    """Performs the initial database setup for the application
    """
    current_app.logger.info("Initializing db tables")

    db_session.add_all([
        model.UserRole("defendant"),
        model.UserRole("operator"),
        model.UserRole("judge"),
        model.UserRole("executioner"),
        model.UserRole("observer"),
    ])

    # TODO: extract these out into a folder
    db_session.add_all([
        model.Language(
            "python",
            "python",
            True,
            textwrap.dedent("""
                                    #!/bin/bash
                                    cat $input_file | python3 $program_file
                                    exit $?""").strip(),
        ),
        model.Language(
            "python2",
            "python",
            True,
            textwrap.dedent("""
                                    #!/bin/bash
                                    cat $input_file | python2 $program_file
                                    exit $?""").strip(),
        ),
        model.Language(
            "perl",
            "perl",
            True,
            textwrap.dedent("""
                                    #!/bin/bash
                                    cat $input_file | perl $program_file
                                    exit $?""").strip(),
        ),
        model.Language(
            "lua",
            "lua",
            True,
            textwrap.dedent("""
                                    #!/bin/bash
                                    cat $input_file | lua $program_file
                                    exit $?""").strip(),
        ),
        model.Language(
            "nodejs",
            "javascript",
            True,
            textwrap.dedent("""
                                    #!/bin/bash
                                    cat $input_file | node $program_file
                                    exit $?""").strip(),
        ),
        model.Language(
            "guile",
            "scheme",
            True,
            textwrap.dedent("""
                                    #!/bin/bash
                                    cat $input_file | guile --no-auto-compile $program_file
                                    exit $?""").strip(),
        ),
        model.Language(
            "fortran",
            "fortran",
            True,
            textwrap.dedent("""
                                #!/bin/bash
                                cp /share/program $scratch_dir/program.f

                                cd $scratch_dir

                                gfortran -o program $scratch_dir/program.f

                                if [[ $? != 0 ]]; then
                                  exit $?
                                fi

                                cat $input_file | ./program

                                exit $?""").strip(),
        ),
        model.Language(
            "c",
            "clike",
            True,
            textwrap.dedent("""
                                #!/bin/bash
                                cp $program_file $scratch_dir/program.c

                                cd $3

                                gcc -o program $scratch_dir/program.c

                                if [[ $? != 0 ]]; then
                                  exit $?
                                fi

                                cat $input_file | ./program

                                exit $?""").strip(),
            textwrap.dedent("""
                                #include <stdio.h>

                                int main(int argc, const char* argv[]) {
                                }"""),
        ),
        model.Language(
            "c++",
            "clike",
            True,
            textwrap.dedent("""
                                #!/bin/bash
                                cp $program_file $scratch_dir/program.cpp

                                cd $scratch_dir

                                g++ -o program $scratch_dir/program.cpp

                                if [[ $? != 0 ]]; then
                                  exit $?
                                fi

                                cat $input_file | ./program

                                exit $?""").strip(),
            textwrap.dedent("""
                                #include <iostream>

                                int main() {
                                  std::cout << "Hello World!";
                                }"""),
        ),
        model.Language(
            "java",
            "clike",
            True,
            textwrap.dedent("""
                                #!/bin/bash
                                export PATH=$PATH:/usr/lib/jvm/java-1.8-openjdk/bin

                                cp $program_file $scratch_dir/Main.java

                                cd $scratch_dir

                                javac Main.java

                                if [[ $? != 0 ]]; then
                                  exit $?
                                fi

                                cat $input_file | java Main

                                exit $?""").strip(),
            textwrap.dedent("""
                                public class Main {
                                    public static void main(String[] args) {

                                    }
                                }"""),
        ),
        model.Language(
            "ruby",
            "ruby",
            True,
            textwrap.dedent("""
                                        #!/bin/bash
                                        cat $input_file | ruby $program_file
                                        exit $?""").strip(),
        ),
        model.Language(
            "rust",
            "rust",
            True,
            textwrap.dedent("""
                                        #!/bin/bash
                                        cp /share/program $scratch_dir/main.rs

                                        cd $scratch_dir

                                        rustc $scratch_dir/main.rs

                                        if [[ $? != 0 ]]; then
                                          exit $?
                                        fi

                                        cat $input_file | ./main
                                        exit $?""").strip(),
            textwrap.dedent("""
                                        fn main() {
                                        }
                        """).strip(),
        ),
    ])

    db_session.add_all([
        model.Configuration("strict_whitespace_diffing", "False", "bool",
                            "admin"),
        model.Configuration("contestants_see_sample_output", "True", "bool",
                            "defendant"),
        model.Configuration("max_user_submissions", "5", "integer",
                            "defendant"),
        model.Configuration("user_submission_time_limit", "1", "integer",
                            "defendant"),
        model.Configuration("max_output_length", str(10 * 1024), "integer",
                            "defendant"),
        model.Configuration("run_refresh_interval_millseconds", 5000,
                            "integer", "defendant"),
        model.Configuration("score_refresh_interval_millseconds", 30000,
                            "integer", "defendant"),
        model.Configuration("misc_refresh_interval_millseconds", 12000,
                            "integer", "defendant"),
        model.Configuration("extra_signup_fields", "[]", "json", "defendant"),
    ])

    db_session.add_all(
        [model.ProblemType("input-output", '#!/bin/bash\ntest "$1" = "$2"')])
    db_session.commit()

    roles = {x.name: x for x in model.UserRole.query.all()}
    db_session.add_all([
        model.User("admin", "Admin", "pass", user_roles=[roles["operator"]]),
        model.User("exec",
                   "Executioner",
                   "epass",
                   user_roles=[roles["executioner"]]),
    ])

    db_session.commit()

    # Version scraper run

    with open("init_data/printver.py", "r") as f:
        src_code = "\n".join(f.readlines())

    executioner_user = model.User.query.filter_by(username="******").scalar()

    python = model.Language.query.filter_by(name="python").scalar()
    empty_input = ""

    version_contest = model.Contest(
        name="version_contest",
        start_time=datetime.datetime.utcnow(),
        end_time=datetime.datetime.utcnow() + datetime.timedelta(hours=1),
        is_public=True,
        activate_time=datetime.datetime.utcnow(),
        freeze_time=None,
        deactivate_time=None,
    )

    db_session.add(version_contest)
    db_session.commit()

    verscrape_run = model.Run(
        executioner_user,
        version_contest,
        python,
        None,
        datetime.datetime.utcnow(),
        src_code,
        empty_input,
        empty_input,
        True,
        None,
    )

    db_session.add(verscrape_run)

    db_session.commit()