Example #1
0
def updateprofile():
    email    = request.form['email']
    username = request.form['username']
    pass1    = request.form['pass1']
    pass2    = request.form['pass2']

    # check passwords are the same
    if pass1 != pass2:
        flash('Passwords do not match', 'error')
        return redirect(url_for('profile'))

    # check username does not already exist
    username_check = query_db('''select id from users where username = ? and id != ?''',[username, session['userid']], one=True)
    if username_check is not None:
        flash('Username is already taken','error')
        return redirect(url_for('profile'))

    # check email does not already exist
    email_check = query_db('''select id from users where email = ? and id != ?''',[email, session['userid']], one=True)
    if email_check is not None:
        flash('Email is already taken','error')
        return redirect(url_for('profile'))

    if pass1 != "" and pass2 != "":
        user_pass = query_db('''select salt from users where id = ?''',[session['userid']], one=True)
        hashed_password = hashlib.sha512(pass1 + user_pass[0]).hexdigest()
        update_db('''update users set username = ?, email = ?, password = ? where id = ?''', [username, email, hashed_password, session['userid']])

    else:
        update_db('''update users set username = ?, email = ? where id = ?''', [username, email, session['userid']])

    session['user'] = username
    return redirect(url_for('profile'))
Example #2
0
def updateprofilepic():
    file = request.files['file']
    # save the file
    if file and allowed_file(file.filename):
        imagename = str(session['userid'])+"_profilepic."+file.filename.rsplit('.', 1)[1]
        file.save(os.path.join(os.getcwd()+"/dvjudge/static", imagename))
        session['image']=imagename;

        update_db('''update users set image = ? where id = ?''', [imagename, session['userid']])
    else:
        flash('That file type is not supported','error')

    return redirect(url_for('profile'))
Example #3
0
def updateprofilepic():
    file = request.files["file"]
    # save the file
    if file and allowed_file(file.filename):
        imagename = str(session["userid"]) + "_profilepic." + file.filename.rsplit(".", 1)[1]
        file.save(os.path.join(os.getcwd() + "/dvjudge/static", imagename))
        session["image"] = imagename

        update_db("""update users set image = ? where id = ?""", [imagename, session["userid"]])
    else:
        flash("That file type is not supported", "error")

    return redirect(url_for("profile"))
Example #4
0
def community_browse_post():
    
    cur = query_db('select id, name, submitter_id from challenges where com_flag = 1')
    # Produce an array of hashes that looks something like:
    # [{id->'1', name->'some challenge name'}, {other hash}]  
    challenges = [dict(id=row[0],name=row[1],submitter_id=row[2]) for row in cur]
    # Retrieve category names
    cur = query_db('select name from categories');
    if cur:
        categories = [dict(name=row[0]) for row in cur]

    if request.form.get('add') is not None:
        # Admin request to move challenges
        if session['user'] == "admin":
            for challenge in challenges:
                move_name = request.form.get(challenge['name'])
                if move_name:
                    move = "update challenges set com_flag=0 where name=?;"
                    update_db(move, [challenge['name']])
            cur = query_db('select id, name, submitter_id from challenges where com_flag = 1')
            challenges = [dict(id=row[0],name=row[1],submitter_id=row[2]) for row in cur]
    # Admin request to delete challenge
    elif request.form.get('delete_chal') is not None:
        if session['user'] == "admin":
            update_db('delete from challenges where name=?',[request.form.get('delete_chal')])
            cur = query_db('select id, name, submitter_id from challenges where com_flag = 1')
            # Produce an array of hashes that looks something like:
            # [{id->'1', name->'some challenge name'}, {other hash}]  
            challenges = [dict(id=row[0],name=row[1],submitter_id=row[2]) for row in cur]

    # Convert user_ids to usernames
    for challenge in challenges:
        lookup = query_db("select username from users where id = ?", [challenge['submitter_id']], one=True)
        if lookup is not None:
            challenge['submitter_id'] = lookup[0]
        else:
            challenge['submitter_id'] = "DvJudge"

    vals = do_browse_post(com=True)
    return render_template('browse.html', challenges=vals[0], searchterm=vals[1], categories=vals[2], no_completed=vals[3], com_flag=True)
Example #5
0
def updateprofile():
    email = request.form["email"]
    username = request.form["username"]
    pass1 = request.form["pass1"]
    pass2 = request.form["pass2"]

    # check passwords are the same
    if pass1 != pass2:
        flash("Passwords do not match", "error")
        return redirect(url_for("profile"))

    # check username does not already exist
    username_check = query_db(
        """select id from users where username = ? and id != ?""", [username, session["userid"]], one=True
    )
    if username_check is not None:
        flash("Username is already taken", "error")
        return redirect(url_for("profile"))

    # check email does not already exist
    email_check = query_db("""select id from users where email = ? and id != ?""", [email, session["userid"]], one=True)
    if email_check is not None:
        flash("Email is already taken", "error")
        return redirect(url_for("profile"))

    if pass1 != "" and pass2 != "":
        user_pass = query_db("""select salt from users where id = ?""", [session["userid"]], one=True)
        hashed_password = hashlib.sha512(pass1 + user_pass[0]).hexdigest()
        update_db(
            """update users set username = ?, email = ?, password = ? where id = ?""",
            [username, email, hashed_password, session["userid"]],
        )

    else:
        update_db("""update users set username = ?, email = ? where id = ?""", [username, email, session["userid"]])

    session["user"] = username
    return redirect(url_for("profile"))
Example #6
0
def submit_specific_challenge():
    
    skip = False 
    language = request.form.get('language')
    #if user is logged in the compiled file will be under the username
    if 'user' in session:
        username = session['user']
        user_id = query_db('select id from users where username = ?',[username], one=True)[0]
    else:
        username = '******'
        skip = True

    #do database stuff
    challenge_id = request.args.get('challenge_id')
    cur = query_db('select * from challenges where id = ?', [challenge_id], one=True)
    
    if cur is not None:
        challenge_id  = cur[0]
        name        = cur[1]
        description = cur[2]
        input_tests = cur[3]
        expected_output = cur[4]
        sample_tests= cur[5]
        input_desc  = cur[6]
        output_desc = cur[7]

    else:
        abort(404)
    
    challenge_info = {'challenge_id': challenge_id, 'name': name, 'description': description, 'sample_tests': sample_tests, 'input_desc': input_desc, 'output_desc': output_desc}
     # get the code from the form
    code = request.form['editor']
    session['code'] = code
    session['language'] = language
    # create a directory for current submission
    directory = subprocess.Popen(['sudo','mkdir', path + username], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    directory.wait()
    directory = subprocess.Popen(['sudo','chown', 'azureuser:azureuser', path + username], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    directory.wait()
    if language == 'C':
        result = run_c(code=code, username = username, input_tests = input_tests, expected_output = expected_output)
    elif language == 'C++':
        result = run_c_plus(code=code, username = username, input_tests = input_tests, expected_output = expected_output)
    elif language == 'Python':
        result = run_python(code=code, username = username, input_tests = input_tests, expected_output = expected_output)
    elif language == 'Java':
        result = run_java(code=code, username = username, input_tests = input_tests, expected_output = expected_output)
    else:
        result = {'output': 'Unknown language', 'status':'Error'}
    # if not a default user, the one that is just trying out the website

    new_solved_challenges = ""
    if not skip:
        update_db("insert into submissions (user_id, challenge_id, status, status_info, language, code) values (?, ?, ?, ?, ?, ?)",
            [user_id,challenge_id,result['status'],result['output'],language,code])
        # Check to see if the user has completed this challenge
        lookup = query_db("select solved_challenges from users where id = ?", [user_id], one=True)
        done = False
        if lookup is not None and lookup[0] is not None:
            new_solved_challenges = lookup[0]
            for challenge_done in lookup[0].split('|'):
                if int(challenge_done) == challenge_id:
                    done = True
                    break

        # If they haven't done it before, append it to their done list
        if done == False:
            if new_solved_challenges == "":
                new_solved_challenges = challenge_info["challenge_id"]
            else:
                new_solved_challenges += "|" + str(challenge_info["challenge_id"])

            update_db("update users set solved_challenges = ? where id = ?", [new_solved_challenges, user_id])
    #clean up
    subprocess.Popen(['sudo','rm', '-rf', path + username], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)   
    if len(result['output']) > 2069:
        result['output'] = result['output'][:2069] 
    session['output'] = result['output']
    return redirect(url_for('browse_specific_challenge', challenge_name=name))
Example #7
0
def upload():
    # Retrieve category names
    cur = query_db('select name from categories')
    if cur:
        categories = [dict(name=row[0]) for row in cur]

    # Initialise alert flags
    flags = {}

    # Someone is trying to submit a new challenge
    if request.method == 'POST':
        if 'user' not in session:
            abort(401)

        # Find out who's submitting a problem.
        lookup = query_db("select id from users where username = ?",
                          [session['user']],
                          one=True)
        user_id = lookup[0]
        if user_id is None:
            abort(401)

        challenge_name = request.form.get('challenge_name')
        description = request.form.get('description')
        input_ = request.form.get('input_')
        output_ = request.form.get('output_')
        tests = request.form.get('tests')
        input_desc = request.form.get('input_desc')
        output_desc = request.form.get('output_desc')

        flags['empty'] = False
        flags['length'] = False
        flags['special'] = False
        flags['conflict'] = False
        flags['success'] = False
        flags['inempty'] = False
        flags['outempty'] = False

        # Check if challenge_name is empty
        temp = re.sub('[\s+]', '', challenge_name)
        in_temp = re.sub('[\s+]', '', input_)
        out_temp = re.sub('[\s+]', '', output_)
        if not challenge_name or not temp:
            flags['empty'] = True
        elif len(challenge_name) > 70:
            flags['length'] = True
        elif not whitelist(challenge_name):
            flags['special'] = True
        elif not input_ or not in_temp:
            flags['inempty'] = True
        elif not output_ or not out_temp:
            flags['outempty'] = True

        if flags['empty'] or flags['length'] or flags['special'] or flags[
                'inempty'] or flags['outempty']:
            return render_template('upload_challenge.html',
                                   challenge_name=challenge_name,
                                   description=description,
                                   input_=input_,
                                   output_=output_,
                                   tests=tests,
                                   input_desc=input_desc,
                                   output_desc=output_desc,
                                   categories=categories,
                                   flags=flags)

        # Check if the challenge_name already exists in the db
        cur = query_db('select * from challenges where name = ?',
                       [challenge_name],
                       one=True)
        if cur is None:
            add_challenge(challenge_name, description, input_, output_, tests,
                          input_desc, output_desc, user_id)
            # Get new challenge instance
            cur = query_db('select * from challenges where name = ?',
                           [challenge_name],
                           one=True)
            # Check if adding to a category
            if cur is not None:
                for category in categories:
                    category_name = request.form.get(category['name'])
                    if category_name:
                        cur2 = query_db(
                            'select * from categories where name = ?',
                            [category_name],
                            one=True)
                        if cur2 is not None:
                            challenge_ids = cur2[1]
                            if challenge_ids:
                                challenge_ids += "|" + str(cur[0])
                            else:
                                challenge_ids = str(cur[0])

                        new_chal = "update categories set challenges=? where name=?;"
                        update_db(new_chal, [challenge_ids, category_name])

            flags['success'] = True
            return render_template('upload_challenge.html',
                                   categories=categories,
                                   flags=flags)

        # If the challenge_name is not fresh, leave the user's details in the page
        else:
            flags['conflict'] = True
            render_template('upload_challenge.html',
                            challenge_name=challenge_name,
                            description=description,
                            input_=input_,
                            output_=output_,
                            tests=tests,
                            input_desc=input_desc,
                            output_desc=output_desc,
                            categories=categories,
                            flags=flags)

    return render_template('upload_challenge.html',
                           categories=categories,
                           flags=flags)
Example #8
0
def do_browse_post(com=False):
    # User is searching
    if request.form.get('searchterm') is not None: # Search passes a search term
        name = request.form.get('searchterm')
        if com is False:
            cur = query_db('select id, name, submitter_id from challenges where com_flag = 0 or com_flag = 2')
        else:
            cur = query_db('select id, name, submitter_id from challenges where com_flag = 1')
        # Produce an array of hashes that looks something like:
        # [{id->'1', name->'some challenge name'}, {other hash}]  
        challenges = [dict(id=row[0],name=row[1],submitter_id=row[2]) for row in cur]
        # Iterate over challenges, and only keep hashes (i.e. challenges) where the names match up
        results = [challenge for challenge in challenges if name.lower() in challenge["name"].lower()]

        # Add completion status
        if 'user' in session:
            lookup = query_db("select solved_challenges from users where username = ?", [session['user']], one=True)
            if lookup is not None and lookup[0] is not None:
                for completed_challenge in lookup[0].split('|'):
                    for displayed_challenge in challenges:
                        if str(displayed_challenge["id"]) == completed_challenge:
                            displayed_challenge["completed"] = 1 # The HTML page just checks for the existance of this key-value pair
        
        # Convert user_ids to usernames
        for challenge in challenges:
            lookup = query_db("select username from users where id = ?", [challenge["submitter_id"]], one=True)
            if lookup is not None:
                challenge["submitter_id"] = lookup[0]
            else:
                challenge["submitter_id"] = "DvJudge"

            
        cur = query_db('select name from categories');
        if cur:
            categories = [dict(name=row[0]) for row in cur]
        # Pass only those on
        return (results, request.form.get('searchterm'), categories, None)

    # Admin request to move challenges
    elif request.form.get('remove') is not None:
        if session['user'] == "admin":
            if com is False:
                cur = query_db('select id, name from challenges where com_flag = 0 or com_flag = 2')
            else:
                cur = query_db('select id, name from challenges where com_flag = 1')
            # Produce an array of hashes that looks something like:
            # [{id->'1', name->'some challenge name'}, {other hash}]  
            challenges = [dict(id=row[0],name=row[1]) for row in cur]
            cur = query_db('select name from categories');
            if cur:
                categories = [dict(name=row[0]) for row in cur]

            for challenge in challenges:
                move_name = request.form.get(challenge['name'])
                if move_name:
                    move = "update challenges set com_flag=1 where name=?;"
                    update_db(move, [challenge['name']])
            if com is False:
                cur = query_db('select id, name from challenges where com_flag = 0 or com_flag = 2')
            else:
                cur = query_db('select id, name from challenges where com_flag = 1')
            challenges = [dict(id=row[0],name=row[1]) for row in cur]
            return (challenges, None, categories, None)

    # Admin request to delete challenge
    elif request.form.get('delete_chal') is not None:
        if session['user'] == "admin":
            update_db('delete from challenges where name=?',[request.form.get('delete_chal')])
            if com is False:
                cur = query_db('select id, name from challenges where com_flag = 0 or com_flag = 2')
            else:
                cur = query_db('select id, name from challenges where com_flag = 1')
            # Produce an array of hashes that looks something like:
            # [{id->'1', name->'some challenge name'}, {other hash}]  
            challenges = [dict(id=row[0],name=row[1]) for row in cur]
            cur = query_db('select name from categories');
            if cur:
                categories = [dict(name=row[0]) for row in cur]

            return (challenges, None, categories, None)

    else: # If there's no searchterm and we get a post, it's probably filtering.
        
        # Retrieve category names
        cur = query_db('select name from categories');
        categories = ""
        if cur:
            categories = [dict(name=row[0]) for row in cur]
        else:
            categories = None  

        # Set categories
        matching_problems = []
        
        # Check Completed filter
        no_completed = False
        if request.form.get("no_completed") is not None:
            no_completed = True

        # Check the ret of the filters, Figure out which ones were set, and keep them set
        no_filters = True
        for category in categories:
            if request.form.get(category["name"]) is not None:
                no_filters = False
                category["checked"] = True
                # Look it up in the DB to get problems in this category
                cur = query_db('select challenges from categories where name = ?', [category["name"]], one=True)
                if cur is not None:
                    for category_problem in cur[0].split('|'):
                        if category_problem != "" and int(category_problem) not in matching_problems:
                            # Remember all the problems that match any filter
                            matching_problems.append(int(category_problem))
                else:
                    abort(500)

        # Now pull all the problems and only keep matching_problems
        if com is False:
            cur = query_db('select id, name, submitter_id from challenges where com_flag = 0 or com_flag = 2')
        else:
            cur = query_db('select id, name, submitter_id from challenges where com_flag = 1')
        # Produce an array of hashes that looks something like:
        # [{id->'1', name->'some challenge name'}, {other hash}]  
        challenges = [dict(id=row[0],name=row[1],submitter_id=row[2]) for row in cur]

        # List comprehension, for each item in challenges, only keep ones that are in the matching_problems set
        if no_filters == False:
            challenges = [x for x in challenges if x["id"] in matching_problems]
        
        # If completed is turned on, we need to remove any matching_problems that are complete
        # Add completion status
        if no_completed == True and 'user' in session:
            lookup = query_db("select solved_challenges from users where username = ?", [session['user']], one=True)
            if lookup is not None and lookup[0] is not None:
                # List comprehension: Matching problems only
                challenges = [x for x in challenges if str(x["id"]) not in lookup[0].split('|')] 
        
        # Convert user_ids to usernames
        for challenge in challenges:
            lookup = query_db("select username from users where id = ?", [challenge["submitter_id"]], one=True)
            if lookup is not None:
                challenge["submitter_id"] = lookup[0]
            else:
                challenge["submitter_id"] = "DvJudge"

        # Also figure out what to put in the completed column for the page, for the displayed problems
        if 'user' in session:
            lookup = query_db("select solved_challenges from users where username = ?", [session['user']], one=True)
            if lookup is not None and lookup[0] is not None:
                for completed_challenge in lookup[0].split('|'):
                    for displayed_challenge in challenges:
                        if str(displayed_challenge["id"]) == completed_challenge:
                            displayed_challenge["completed"] = 1 # The HTML page just checks for the existance of this key-value pair

        return (challenges, None, categories, None)
Example #9
0
def submit_specific_challenge():

    skip = False
    language = request.form.get('language')
    #if user is logged in the compiled file will be under the username
    if 'user' in session:
        username = session['user']
        user_id = query_db('select id from users where username = ?',
                           [username],
                           one=True)[0]
    else:
        username = '******'
        skip = True

    #do database stuff
    challenge_id = request.args.get('challenge_id')
    cur = query_db('select * from challenges where id = ?', [challenge_id],
                   one=True)

    if cur is not None:
        challenge_id = cur[0]
        name = cur[1]
        description = cur[2]
        input_tests = cur[3]
        expected_output = cur[4]
        sample_tests = cur[5]
        input_desc = cur[6]
        output_desc = cur[7]

    else:
        abort(404)

    challenge_info = {
        'challenge_id': challenge_id,
        'name': name,
        'description': description,
        'sample_tests': sample_tests,
        'input_desc': input_desc,
        'output_desc': output_desc
    }
    # get the code from the form
    code = request.form['editor']
    session['code'] = code
    session['language'] = language
    # create a directory for current submission
    directory = subprocess.Popen(['sudo', 'mkdir', path + username],
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.STDOUT)
    directory.wait()
    directory = subprocess.Popen(
        ['sudo', 'chown', 'azureuser:azureuser', path + username],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT)
    directory.wait()
    if language == 'C':
        result = run_c(code=code,
                       username=username,
                       input_tests=input_tests,
                       expected_output=expected_output)
    elif language == 'C++':
        result = run_c_plus(code=code,
                            username=username,
                            input_tests=input_tests,
                            expected_output=expected_output)
    elif language == 'Python':
        result = run_python(code=code,
                            username=username,
                            input_tests=input_tests,
                            expected_output=expected_output)
    elif language == 'Java':
        result = run_java(code=code,
                          username=username,
                          input_tests=input_tests,
                          expected_output=expected_output)
    else:
        result = {'output': 'Unknown language', 'status': 'Error'}
    # if not a default user, the one that is just trying out the website

    new_solved_challenges = ""
    if not skip:
        update_db(
            "insert into submissions (user_id, challenge_id, status, status_info, language, code) values (?, ?, ?, ?, ?, ?)",
            [
                user_id, challenge_id, result['status'], result['output'],
                language, code
            ])
        # Check to see if the user has completed this challenge
        lookup = query_db("select solved_challenges from users where id = ?",
                          [user_id],
                          one=True)
        done = False
        if lookup is not None and lookup[0] is not None:
            new_solved_challenges = lookup[0]
            for challenge_done in lookup[0].split('|'):
                if int(challenge_done) == challenge_id:
                    done = True
                    break

        # If they haven't done it before, append it to their done list
        if done == False:
            if new_solved_challenges == "":
                new_solved_challenges = challenge_info["challenge_id"]
            else:
                new_solved_challenges += "|" + str(
                    challenge_info["challenge_id"])

            update_db("update users set solved_challenges = ? where id = ?",
                      [new_solved_challenges, user_id])
    #clean up
    subprocess.Popen(['sudo', 'rm', '-rf', path + username],
                     stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)
    if len(result['output']) > 2069:
        result['output'] = result['output'][:2069]
    session['output'] = result['output']
    return redirect(url_for('browse_specific_challenge', challenge_name=name))
Example #10
0
def do_browse_post(com=False):
    # User is searching
    if request.form.get(
            'searchterm') is not None:  # Search passes a search term
        name = request.form.get('searchterm')
        if com is False:
            cur = query_db(
                'select id, name, submitter_id from challenges where com_flag = 0 or com_flag = 2'
            )
        else:
            cur = query_db(
                'select id, name, submitter_id from challenges where com_flag = 1'
            )
        # Produce an array of hashes that looks something like:
        # [{id->'1', name->'some challenge name'}, {other hash}]
        challenges = [
            dict(id=row[0], name=row[1], submitter_id=row[2]) for row in cur
        ]
        # Iterate over challenges, and only keep hashes (i.e. challenges) where the names match up
        results = [
            challenge for challenge in challenges
            if name.lower() in challenge["name"].lower()
        ]

        # Add completion status
        if 'user' in session:
            lookup = query_db(
                "select solved_challenges from users where username = ?",
                [session['user']],
                one=True)
            if lookup is not None and lookup[0] is not None:
                for completed_challenge in lookup[0].split('|'):
                    for displayed_challenge in challenges:
                        if str(displayed_challenge["id"]
                               ) == completed_challenge:
                            displayed_challenge[
                                "completed"] = 1  # The HTML page just checks for the existance of this key-value pair

        # Convert user_ids to usernames
        for challenge in challenges:
            lookup = query_db("select username from users where id = ?",
                              [challenge["submitter_id"]],
                              one=True)
            if lookup is not None:
                challenge["submitter_id"] = lookup[0]
            else:
                challenge["submitter_id"] = "DvJudge"

        cur = query_db('select name from categories')
        if cur:
            categories = [dict(name=row[0]) for row in cur]
        # Pass only those on
        return (results, request.form.get('searchterm'), categories, None)

    # Admin request to move challenges
    elif request.form.get('remove') is not None:
        if session['user'] == "admin":
            if com is False:
                cur = query_db(
                    'select id, name from challenges where com_flag = 0 or com_flag = 2'
                )
            else:
                cur = query_db(
                    'select id, name from challenges where com_flag = 1')
            # Produce an array of hashes that looks something like:
            # [{id->'1', name->'some challenge name'}, {other hash}]
            challenges = [dict(id=row[0], name=row[1]) for row in cur]
            cur = query_db('select name from categories')
            if cur:
                categories = [dict(name=row[0]) for row in cur]

            for challenge in challenges:
                move_name = request.form.get(challenge['name'])
                if move_name:
                    move = "update challenges set com_flag=1 where name=?;"
                    update_db(move, [challenge['name']])
            if com is False:
                cur = query_db(
                    'select id, name from challenges where com_flag = 0 or com_flag = 2'
                )
            else:
                cur = query_db(
                    'select id, name from challenges where com_flag = 1')
            challenges = [dict(id=row[0], name=row[1]) for row in cur]
            return (challenges, None, categories, None)

    # Admin request to delete challenge
    elif request.form.get('delete_chal') is not None:
        if session['user'] == "admin":
            update_db('delete from challenges where name=?',
                      [request.form.get('delete_chal')])
            if com is False:
                cur = query_db(
                    'select id, name from challenges where com_flag = 0 or com_flag = 2'
                )
            else:
                cur = query_db(
                    'select id, name from challenges where com_flag = 1')
            # Produce an array of hashes that looks something like:
            # [{id->'1', name->'some challenge name'}, {other hash}]
            challenges = [dict(id=row[0], name=row[1]) for row in cur]
            cur = query_db('select name from categories')
            if cur:
                categories = [dict(name=row[0]) for row in cur]

            return (challenges, None, categories, None)

    else:  # If there's no searchterm and we get a post, it's probably filtering.

        # Retrieve category names
        cur = query_db('select name from categories')
        categories = ""
        if cur:
            categories = [dict(name=row[0]) for row in cur]
        else:
            categories = None

        # Set categories
        matching_problems = []

        # Check Completed filter
        no_completed = False
        if request.form.get("no_completed") is not None:
            no_completed = True

        # Check the ret of the filters, Figure out which ones were set, and keep them set
        no_filters = True
        for category in categories:
            if request.form.get(category["name"]) is not None:
                no_filters = False
                category["checked"] = True
                # Look it up in the DB to get problems in this category
                cur = query_db(
                    'select challenges from categories where name = ?',
                    [category["name"]],
                    one=True)
                if cur is not None:
                    for category_problem in cur[0].split('|'):
                        if category_problem != "" and int(
                                category_problem) not in matching_problems:
                            # Remember all the problems that match any filter
                            matching_problems.append(int(category_problem))
                else:
                    abort(500)

        # Now pull all the problems and only keep matching_problems
        if com is False:
            cur = query_db(
                'select id, name, submitter_id from challenges where com_flag = 0 or com_flag = 2'
            )
        else:
            cur = query_db(
                'select id, name, submitter_id from challenges where com_flag = 1'
            )
        # Produce an array of hashes that looks something like:
        # [{id->'1', name->'some challenge name'}, {other hash}]
        challenges = [
            dict(id=row[0], name=row[1], submitter_id=row[2]) for row in cur
        ]

        # List comprehension, for each item in challenges, only keep ones that are in the matching_problems set
        if no_filters == False:
            challenges = [
                x for x in challenges if x["id"] in matching_problems
            ]

        # If completed is turned on, we need to remove any matching_problems that are complete
        # Add completion status
        if no_completed == True and 'user' in session:
            lookup = query_db(
                "select solved_challenges from users where username = ?",
                [session['user']],
                one=True)
            if lookup is not None and lookup[0] is not None:
                # List comprehension: Matching problems only
                challenges = [
                    x for x in challenges
                    if str(x["id"]) not in lookup[0].split('|')
                ]

        # Convert user_ids to usernames
        for challenge in challenges:
            lookup = query_db("select username from users where id = ?",
                              [challenge["submitter_id"]],
                              one=True)
            if lookup is not None:
                challenge["submitter_id"] = lookup[0]
            else:
                challenge["submitter_id"] = "DvJudge"

        # Also figure out what to put in the completed column for the page, for the displayed problems
        if 'user' in session:
            lookup = query_db(
                "select solved_challenges from users where username = ?",
                [session['user']],
                one=True)
            if lookup is not None and lookup[0] is not None:
                for completed_challenge in lookup[0].split('|'):
                    for displayed_challenge in challenges:
                        if str(displayed_challenge["id"]
                               ) == completed_challenge:
                            displayed_challenge[
                                "completed"] = 1  # The HTML page just checks for the existance of this key-value pair

        return (challenges, None, categories, None)
Example #11
0
def browse_specific_challenge(challenge_name):
    
    supported_languages = {'C', 'Python', 'Java', 'C++'}
    data = {'C':"// enter code here", 'Python':"# enter code here", 'Java':"// enter code here", 'C++':"// enter code here"}

    cur = query_db('select * from challenges where name = ?', [challenge_name], one=True)
    if cur is not None:
        challenge_id  = cur[0]
        name          = cur[1]
        description   = cur[2]
        sample_tests  = cur[5]
        input_desc    = cur[6]
        output_desc   = cur[7]
        com_flag      = cur[8]
    else:
        abort(404)

    challenge_info = {'challenge_id': challenge_id, 'name': name, 'description': description, 'sample_tests': sample_tests, 
                'input_desc': input_desc, 'output_desc': output_desc, 'languages':supported_languages, 'com_flag':com_flag}

    #check for posted comment
    if request.method == 'POST':
        comment = request.form['comment']
        if comment:
            post_comment(session['user'], challenge_id, comment)
  
    #Check if it's a redirect from submission and the program 
    #has produced output
    #Stored in session cookie
    if 'output' in session:
        info = session['output']
        session.pop('output', None)
    else:
        info = None
    #check for submitted code from user
    if 'code' in session:
        code = session['code']
        session.pop('code', None)
    else:
        code = None

    if 'language' in session:
        language = session['language']
        session.pop('language', None)
    else:
        language = 'C'

    # Variables for playlist add
    exists = False
    playlist_name = request.args.get('playlist_name')

    # Prepare playlist information for the dropdown if user logged in
    playlists = {} 
    if 'user' in session:
        username = session['user']
        # Convert user session to user ID
        cur = query_db('select id from users where username = ?', [username], one=True)
        if cur is not None:
            user_id = cur[0]
            # Retrieve the playlists available to this user
            cur = query_db('select * from playlists where owner_id = ?', [cur[0]])
            
            # Build a dictionary to pass to the page later
            playlists = [dict(id=row[0],name=row[1]) for row in cur]

            # Selected to add to playlist
            if playlist_name:
                add_list = query_db('select * from playlists where owner_id = ? and name = ?',
                    [user_id, playlist_name], one=True)
                # Check if playlist name exists
                if add_list is not None:
                    challenge_ids = add_list[3]
                    # Check that challenge IDs is not an empty string
                    if challenge_ids:
                        id_list = [int(s) for s in challenge_ids.split('|')]
                        if challenge_id not in id_list:
                            challenge_ids += "|" + str(challenge_id)
                        # if challenge id is in list, set the exists flag for the alert
                        else:
                            exists = True

                    # Add id to playlist
                    else:
                        challenge_ids = str(challenge_id)
                    add_str = "update playlists set challenges=? where name=? and owner_id=?;"
                    update_db(add_str, [challenge_ids,playlist_name,user_id])
                # Playlist name not found
                else:
                    playlist_name = ""
        else:
           abort(401)
  
    #insert the comments section
    question_comments = get_comments(challenge_id)
      
    return render_template('challenge.html', challenge_info=challenge_info, output=info, code=code, playlists=playlists,
        language=language, comments=question_comments, data=json.dumps(data), playlist_name=playlist_name, exists=exists)
Example #12
0
def browse_specific_challenge(challenge_name):

    supported_languages = {'C', 'Python', 'Java', 'C++'}
    data = {
        'C': "// enter code here",
        'Python': "# enter code here",
        'Java': "// enter code here",
        'C++': "// enter code here"
    }

    cur = query_db('select * from challenges where name = ?', [challenge_name],
                   one=True)
    if cur is not None:
        challenge_id = cur[0]
        name = cur[1]
        description = cur[2]
        sample_tests = cur[5]
        input_desc = cur[6]
        output_desc = cur[7]
        com_flag = cur[8]
    else:
        abort(404)

    challenge_info = {
        'challenge_id': challenge_id,
        'name': name,
        'description': description,
        'sample_tests': sample_tests,
        'input_desc': input_desc,
        'output_desc': output_desc,
        'languages': supported_languages,
        'com_flag': com_flag
    }

    #check for posted comment
    if request.method == 'POST':
        comment = request.form['comment']
        if comment:
            post_comment(session['user'], challenge_id, comment)

    #Check if it's a redirect from submission and the program
    #has produced output
    #Stored in session cookie
    if 'output' in session:
        info = session['output']
        session.pop('output', None)
    else:
        info = None
    #check for submitted code from user
    if 'code' in session:
        code = session['code']
        session.pop('code', None)
    else:
        code = None

    if 'language' in session:
        language = session['language']
        session.pop('language', None)
    else:
        language = 'C'

    # Variables for playlist add
    exists = False
    playlist_name = request.args.get('playlist_name')

    # Prepare playlist information for the dropdown if user logged in
    playlists = {}
    if 'user' in session:
        username = session['user']
        # Convert user session to user ID
        cur = query_db('select id from users where username = ?', [username],
                       one=True)
        if cur is not None:
            user_id = cur[0]
            # Retrieve the playlists available to this user
            cur = query_db('select * from playlists where owner_id = ?',
                           [cur[0]])

            # Build a dictionary to pass to the page later
            playlists = [dict(id=row[0], name=row[1]) for row in cur]

            # Selected to add to playlist
            if playlist_name:
                add_list = query_db(
                    'select * from playlists where owner_id = ? and name = ?',
                    [user_id, playlist_name],
                    one=True)
                # Check if playlist name exists
                if add_list is not None:
                    challenge_ids = add_list[3]
                    # Check that challenge IDs is not an empty string
                    if challenge_ids:
                        id_list = [int(s) for s in challenge_ids.split('|')]
                        if challenge_id not in id_list:
                            challenge_ids += "|" + str(challenge_id)
                        # if challenge id is in list, set the exists flag for the alert
                        else:
                            exists = True

                    # Add id to playlist
                    else:
                        challenge_ids = str(challenge_id)
                    add_str = "update playlists set challenges=? where name=? and owner_id=?;"
                    update_db(add_str, [challenge_ids, playlist_name, user_id])
                # Playlist name not found
                else:
                    playlist_name = ""
        else:
            abort(401)

    #insert the comments section
    question_comments = get_comments(challenge_id)

    return render_template('challenge.html',
                           challenge_info=challenge_info,
                           output=info,
                           code=code,
                           playlists=playlists,
                           language=language,
                           comments=question_comments,
                           data=json.dumps(data),
                           playlist_name=playlist_name,
                           exists=exists)
Example #13
0
def show_playlists():
    if 'user' in session:
        username = session['user']
        # Convert user session to user ID
        cur = query_db('select id from users where username = ?', [username],
                       one=True)
        if cur is not None:
            owner_id = str(cur[0])
            # Check if selected 'Delete Playlist'
            del_name = request.form.get('delete_list')
            if del_name:
                update_db('delete from playlists where owner_id=? and name=?',
                          [owner_id, del_name])

            # Retrieve the playlists available to this user
            cur = query_db('select * from playlists where owner_id = ?',
                           [cur[0]])

            # Build a dictionary to pass to the page later
            # Dictionary contains playlist name, id, and which challenges belong to it
            playlists = [
                dict(id=row[0], name=row[1], challenges=row[3]) for row in cur
            ]
            if playlists:
                selected_name = request.form.get('selected_name')
                selection = playlists[0]
                if selected_name is not None:
                    for play in playlists:
                        if play['name'] == selected_name:
                            selection = play

                cur = query_db('select id, name, submitter_id from challenges')
                challenges = [
                    dict(id=row[0], name=row[1], submitter_id=row[2])
                    for row in cur
                ]
                challenge_list = []
                # Determine whether Submit Changes was pressed
                auto_reorder = request.form.get('auto')
                if auto_reorder:
                    reorder_entry = {}
                    # Match each challenge to their new order
                    for challenge in challenges:
                        if request.form.get(challenge['name']):
                            chal_order = int(
                                request.form.get(challenge['name']))
                            chal_id = int(challenge['id'])
                            reorder_entry[chal_order] = chal_id

                    # Generate an order string to insert into the database
                    new_order = ""
                    for key in reorder_entry:
                        if not new_order:
                            new_order = str(reorder_entry[key])
                        else:
                            new_order += "|" + str(reorder_entry[key])

                    reorder_str = "update playlists set challenges=? where name=? and owner_id=?;"
                    update_db(reorder_str,
                              [new_order, selection['name'], owner_id])
                    challenge_ids = new_order
                else:
                    challenge_ids = selection['challenges']

                if challenge_ids:
                    # Obtain a list of in order challenge ids for a playlist
                    id_list = [int(s) for s in challenge_ids.split('|')]

                    for id in id_list:
                        for challenge in challenges:
                            if challenge['id'] == id:
                                # Convert user_ids to usernames
                                lookup = query_db(
                                    "select username from users where id = ?",
                                    [challenge["submitter_id"]],
                                    one=True)
                                if lookup is not None:
                                    challenge["submitter_id"] = lookup[0]
                                else:
                                    challenge["submitter_id"] = "DvJudge"
                                # Add challenges to list
                                challenge_list.append(challenge)
                                break

            else:
                playlists = None
                selection = None
                challenge_list = None

            # Passing playlists.html all the playilst info in a hash
            return render_template('playlists.html',
                                   playlists=playlists,
                                   selection=selection,
                                   challenge_list=challenge_list)
        else:
            abort(401)
    else:
        abort(401)
Example #14
0
def upload():
    # Retrieve category names
    cur = query_db('select name from categories');
    if cur:
        categories = [dict(name=row[0]) for row in cur]

    # Initialise alert flags
    flags = {}

    # Someone is trying to submit a new challenge
    if request.method == 'POST':
        if 'user' not in session:
            abort(401)

        # Find out who's submitting a problem.
        lookup = query_db("select id from users where username = ?", [session['user']], one=True)
        user_id = lookup[0]
        if user_id is None:
            abort(401)

        challenge_name  = request.form.get('challenge_name')
        description     = request.form.get('description')
        input_          = request.form.get('input_')
        output_         = request.form.get('output_')
        tests           = request.form.get('tests')
        input_desc      = request.form.get('input_desc')
        output_desc     = request.form.get('output_desc')

        flags['empty'] = False
        flags['length'] = False
        flags['special']  = False
        flags['conflict'] = False
        flags['success'] = False
        flags['inempty'] = False
        flags['outempty'] = False

        # Check if challenge_name is empty
        temp = re.sub('[\s+]', '', challenge_name)
        in_temp = re.sub('[\s+]', '', input_)
        out_temp = re.sub('[\s+]', '', output_)
        if not challenge_name or not temp:
            flags['empty'] = True
        elif len(challenge_name) > 70:
            flags['length'] = True
        elif not whitelist(challenge_name):
            flags['special']  = True
        elif not input_ or not in_temp:
            flags['inempty'] = True
        elif not output_ or not out_temp:
            flags['outempty'] = True

        if flags['empty'] or flags['length'] or flags['special'] or flags['inempty'] or flags['outempty']:
            return render_template('upload_challenge.html', challenge_name=challenge_name, description=description, input_=input_,
                output_=output_, tests=tests, input_desc=input_desc, output_desc=output_desc, categories=categories, flags=flags)
        
        # Check if the challenge_name already exists in the db
        cur = query_db('select * from challenges where name = ?', [challenge_name], one=True)
        if cur is None:
            add_challenge (challenge_name, description, input_, output_, tests,input_desc, output_desc, user_id) 
            # Get new challenge instance
            cur = query_db('select * from challenges where name = ?', [challenge_name], one=True)
            # Check if adding to a category
            if cur is not None:
                for category in categories:
                    category_name = request.form.get(category['name'])
                    if category_name:
                        cur2 = query_db('select * from categories where name = ?', [category_name], one=True)
                        if cur2 is not None:
                            challenge_ids = cur2[1]
                            if challenge_ids:
                                challenge_ids += "|" + str(cur[0])
                            else:
                                challenge_ids = str(cur[0])

                        new_chal = "update categories set challenges=? where name=?;"
                        update_db(new_chal, [challenge_ids,category_name])

            flags['success'] = True
            return render_template('upload_challenge.html', categories=categories, flags=flags)

        # If the challenge_name is not fresh, leave the user's details in the page
        else:
            flags['conflict'] = True
            render_template('upload_challenge.html', challenge_name=challenge_name, description=description, input_=input_,
                output_=output_, tests=tests, input_desc=input_desc, output_desc=output_desc, categories=categories, flags=flags)

    return render_template('upload_challenge.html', categories=categories, flags=flags) 
Example #15
0
def community_browse_post():

    cur = query_db(
        'select id, name, submitter_id from challenges where com_flag = 1')
    # Produce an array of hashes that looks something like:
    # [{id->'1', name->'some challenge name'}, {other hash}]
    challenges = [
        dict(id=row[0], name=row[1], submitter_id=row[2]) for row in cur
    ]
    # Retrieve category names
    cur = query_db('select name from categories')
    if cur:
        categories = [dict(name=row[0]) for row in cur]

    if request.form.get('add') is not None:
        # Admin request to move challenges
        if session['user'] == "admin":
            for challenge in challenges:
                move_name = request.form.get(challenge['name'])
                if move_name:
                    move = "update challenges set com_flag=0 where name=?;"
                    update_db(move, [challenge['name']])
            cur = query_db(
                'select id, name, submitter_id from challenges where com_flag = 1'
            )
            challenges = [
                dict(id=row[0], name=row[1], submitter_id=row[2])
                for row in cur
            ]
    # Admin request to delete challenge
    elif request.form.get('delete_chal') is not None:
        if session['user'] == "admin":
            update_db('delete from challenges where name=?',
                      [request.form.get('delete_chal')])
            cur = query_db(
                'select id, name, submitter_id from challenges where com_flag = 1'
            )
            # Produce an array of hashes that looks something like:
            # [{id->'1', name->'some challenge name'}, {other hash}]
            challenges = [
                dict(id=row[0], name=row[1], submitter_id=row[2])
                for row in cur
            ]

    # Convert user_ids to usernames
    for challenge in challenges:
        lookup = query_db("select username from users where id = ?",
                          [challenge['submitter_id']],
                          one=True)
        if lookup is not None:
            challenge['submitter_id'] = lookup[0]
        else:
            challenge['submitter_id'] = "DvJudge"

    vals = do_browse_post(com=True)
    return render_template('browse.html',
                           challenges=vals[0],
                           searchterm=vals[1],
                           categories=vals[2],
                           no_completed=vals[3],
                           com_flag=True)
Example #16
0
def show_playlists():
    if "user" in session:
        username = session["user"]
        # Convert user session to user ID
        cur = query_db("select id from users where username = ?", [username], one=True)
        if cur is not None:
            owner_id = str(cur[0])
            # Check if selected 'Delete Playlist'
            del_name = request.form.get("delete_list")
            if del_name:
                update_db("delete from playlists where owner_id=? and name=?", [owner_id, del_name])

            # Retrieve the playlists available to this user
            cur = query_db("select * from playlists where owner_id = ?", [cur[0]])

            # Build a dictionary to pass to the page later
            # Dictionary contains playlist name, id, and which challenges belong to it
            playlists = [dict(id=row[0], name=row[1], challenges=row[3]) for row in cur]
            if playlists:
                selected_name = request.form.get("selected_name")
                selection = playlists[0]
                if selected_name is not None:
                    for play in playlists:
                        if play["name"] == selected_name:
                            selection = play

                cur = query_db("select id, name, submitter_id from challenges")
                challenges = [dict(id=row[0], name=row[1], submitter_id=row[2]) for row in cur]
                challenge_list = []
                # Determine whether Submit Changes was pressed
                auto_reorder = request.form.get("auto")
                if auto_reorder:
                    reorder_entry = {}
                    # Match each challenge to their new order
                    for challenge in challenges:
                        if request.form.get(challenge["name"]):
                            chal_order = int(request.form.get(challenge["name"]))
                            chal_id = int(challenge["id"])
                            reorder_entry[chal_order] = chal_id

                    # Generate an order string to insert into the database
                    new_order = ""
                    for key in reorder_entry:
                        if not new_order:
                            new_order = str(reorder_entry[key])
                        else:
                            new_order += "|" + str(reorder_entry[key])

                    reorder_str = "update playlists set challenges=? where name=? and owner_id=?;"
                    update_db(reorder_str, [new_order, selection["name"], owner_id])
                    challenge_ids = new_order
                else:
                    challenge_ids = selection["challenges"]

                if challenge_ids:
                    # Obtain a list of in order challenge ids for a playlist
                    id_list = [int(s) for s in challenge_ids.split("|")]

                    for id in id_list:
                        for challenge in challenges:
                            if challenge["id"] == id:
                                # Convert user_ids to usernames
                                lookup = query_db(
                                    "select username from users where id = ?", [challenge["submitter_id"]], one=True
                                )
                                if lookup is not None:
                                    challenge["submitter_id"] = lookup[0]
                                else:
                                    challenge["submitter_id"] = "DvJudge"
                                # Add challenges to list
                                challenge_list.append(challenge)
                                break

            else:
                playlists = None
                selection = None
                challenge_list = None

            # Passing playlists.html all the playilst info in a hash
            return render_template(
                "playlists.html", playlists=playlists, selection=selection, challenge_list=challenge_list
            )
        else:
            abort(401)
    else:
        abort(401)