Advertisement
Guest User

app.py for contest

a guest
Nov 7th, 2018
342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 57.35 KB | None | 0 0
  1. import ClassesList
  2. import datetime
  3. import os
  4. import time
  5. import FunctionList
  6.  
  7. from flask import Flask, render_template, request
  8. from flask import flash
  9. from flask import redirect, url_for, session, Session
  10. from flask_ckeditor import CKEditor, CKEditorField
  11. from flask_codemirror import CodeMirror
  12. from flask_codemirror.fields import CodeMirrorField
  13. from flask_pymongo import PyMongo
  14. from flask_wtf import FlaskForm
  15. from werkzeug.utils import secure_filename
  16. from wtforms import Form, IntegerField, StringField, PasswordField, validators
  17. from wtforms.fields import SubmitField, TextAreaField
  18. from wtforms.fields.html5 import EmailField
  19. from FunctionList import giveedge, givenode, edge_list, node_list, f, allowed_file, graph, adapter, jsonstring, \
  20.     problem_user_submissions, pair
  21. from forms import IssueForm, CommentForm, UploadForm, graph_input, create_article_form, LoginForm, RegisterForm
  22. from ClassesList import *
  23.  
  24. app = Flask(__name__)
  25. UPLOAD_FOLDER = os.path.dirname(os.path.realpath(__file__)) + '/static/uploads'
  26. ALLOWED_EXTENSIONS = set(['txt', 'pdf'])
  27. ALLOWED_CATEGORY = set(['ACM', 'IOI'])
  28. import uuid
  29.  
  30. app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
  31. app.config['MONGO_URI'] = 'mongodb://red44:omi123@ds131963.mlab.com:31963/purpleoj'
  32. app.config['CKEDITOR_SERVE_LOCAL'] = True
  33. app.config['CKEDITOR_HEIGHT'] = 400
  34. ckeditor = CKEditor(app)
  35. mongo = PyMongo(app)
  36.  
  37. app.secret_key = "super secret key"
  38. sess = Session()
  39.  
  40.  
  41. @app.route('/upload', methods=['GET', 'POST'])
  42. def upload_file():
  43.     nameform = UploadForm(request.form)
  44.     if request.method == 'POST':
  45.         # check if the post request has the file part
  46.         sbcnt = nameform.count.data
  47.         if not valid(strr='file', request=request):
  48.             return redirect(request.url)
  49.         if sbcnt >= 1:
  50.             if not valid(strr='ifile1', request=request) or not valid(strr='ofile1',
  51.                                                                       request=request) or nameform.point1.data == None:
  52.                 return redirect(request.url)
  53.         if sbcnt >= 2:
  54.             if not valid(strr='ifile2', request=request) or not valid(strr='ofile2',
  55.                                                                       request=request) or nameform.point2.data == None:
  56.                 return redirect(request.url)
  57.         if sbcnt >= 3:
  58.             if not valid(strr='ifile3', request=request) or not valid(strr='ofile3',
  59.                                                                       request=request) or nameform.point3.data == None:
  60.                 return redirect(request.url)
  61.  
  62.         gpb = uuid.uuid4().__str__()
  63.         file = request.files['file']
  64.         filename = gpb + '.pdf'  # secure_filename(file.filename)
  65.         file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
  66.         for i in range(1, sbcnt + 1):
  67.             inp = 'ifile' + str(i)
  68.             out = 'ofile' + str(i)
  69.             file = request.files[inp]
  70.             filename = gpb + 'in' + str(i) + '.txt'
  71.             file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
  72.             file = request.files[out]
  73.             filename = gpb + 'out' + str(i) + '.txt'
  74.             file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
  75.         pnt1, pnt2, pnt3 = 0, 0, 0
  76.         if not nameform.point1 == None:
  77.             pnt1 = nameform.point1.data
  78.         if not nameform.point1 == None:
  79.             pnt2 = nameform.point2.data
  80.         if not nameform.point1 == None:
  81.             pnt3 = nameform.point3.data
  82.  
  83.         pb = problem(sbcnt, gpb, pnt1, pnt2, pnt3, nameform.time_limit.data, nameform.memory_limit.data,
  84.                      nameform.category.data, nameform.name.data, 0, 0, session['username'])
  85.         problemdb = mongo.db.problems
  86.         problemdb.insert({
  87.             'sub_task_count': pb.sub_task_count,
  88.             'myid': pb.id,
  89.             'pnt1': pb.pnt1,
  90.             'pnt2': pb.pnt2,
  91.             'pnt3': pb.pnt3,
  92.             'author': session['username'],
  93.             'name': nameform.name.data,
  94.             'time_limit': pb.time_limit,
  95.             'memory_limit': pb.memory_limit,
  96.             'stylee': pb.stylee,
  97.             'acsub': 0,
  98.             'sub': 0,
  99.             'setter': session['username']
  100.         })
  101.  
  102.         return redirect(url_for('upload_file', filename=filename))
  103.  
  104.     if not ('username' in session):
  105.         return redirect(url_for('login'))
  106.     return render_template('upload_problem.html', nameform=nameform)
  107.  
  108.  
  109. def valid(strr, request):
  110.     if strr not in request.files:
  111.         return False
  112.     filee = request.files[strr]
  113.     if filee.filename == '':
  114.         return False
  115.     if filee and allowed_file(filee.filename):
  116.         print("Something")
  117.         return True
  118.     return False
  119.  
  120.  
  121. def upload_prev():
  122.     nameform = UploadForm(request.form)
  123.     if request.method == 'POST':
  124.         # check if the post request has the file part
  125.         if 'file' not in request.files:
  126.             flash('No file part')
  127.             return redirect(request.url)
  128.         file = request.files['file']
  129.         # if user does not select file, browser also
  130.         # submit an empty part without filename
  131.         if file.filename == '':
  132.             flash('No selected file')
  133.             return redirect(request.url)
  134.         if file and allowed_file(file.filename):
  135.             filename = secure_filename(file.filename)
  136.             file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
  137.             return redirect(url_for('upload_file', filename=filename))
  138.     return render_template('upload_problem.html', nameform=nameform)
  139.  
  140.  
  141. @app.route('/')
  142. def index():
  143.     contest_db = mongo.db.contests
  144.     problem_db = mongo.db.problems
  145.     list = []
  146.     postdb = mongo.db.posts
  147.     existing_post = postdb.find({}).sort('_id')
  148.     contest_db = mongo.db.contests
  149.     contest_cursor = contest_db.find({}).sort('Start Date')
  150.     pclist = []
  151.     for pc in contest_cursor:
  152.         starting_datetime = pc['Start Date'] + "T" + pc['Start Time'] + ":00+06:00"
  153.         ending_date = pc['Start Date'] + "T" + pc['End Time'] + ":00+06:00"
  154.         id = pc['_id']
  155.         name = pc['Contest Title']
  156.         dt = datetime.datetime.now()
  157.         pcet = pc['End Time']
  158.         rep = ''
  159.         flag = 0
  160.         for i in range(0, len(pcet)):
  161.             if flag == 1:
  162.                 rep += pcet[i]
  163.             if pcet[i] == '.':
  164.                 flag = 1
  165.         pcet.replace(rep, '')
  166.         ds = datetime.datetime.strptime(pc['Start Date'] + ' ' + pcet, "%Y-%m-%d %H:%M")
  167.         xx = dt.strftime("%Y-%m-%d %H:%M")
  168.  
  169.         cd = datetime.datetime.strptime(xx, "%Y-%m-%d %H:%M")
  170.         print(ending_date)
  171.         print(ds)
  172.         print(cd)
  173.         if ds >= dt:
  174.             pclist.append(tripled(starting_datetime, ending_date, id, name))
  175.     i = 0
  176.     for posts in existing_post:
  177.         print(posts)
  178.         posttitle = posts['TITLE']
  179.         posttext = posts['TEXT']
  180.         postuser = posts['USER']
  181.         postdate = posts['DATE']
  182.         postid = posts['_id']
  183.         ppp = postob(posttitle, posttext, postdate, postuser, postid)
  184.         list.append(ppp)
  185.         print(list[i].dt)
  186.         i = i + 1
  187.     list.reverse()
  188.     print(len(list))
  189.  
  190.     error = 'You are not logged in'
  191.     dumb = 'dumb'
  192.     if 'username' in session:
  193.         msg = 'You are Logged in as ' + session['username']
  194.         return render_template('home.html', msg=msg, posts=list, PC=pclist)
  195.     return render_template('home.html', error=error, dumb=dumb, posts=list, PC=pclist)
  196.  
  197.  
  198. @app.route('/register', methods=['GET', 'POST'])
  199. def register():
  200.     form = RegisterForm(request.form)
  201.     if request.method == 'POST' and form.validate():
  202.         names = form.name.data
  203.         emails = form.email.data
  204.         usernames = form.username.data
  205.         passwords = form.password.data
  206.         user = mongo.db.userlist
  207.         existing_user = user.find_one({'USERNAME': usernames})
  208.         dialoge = 'Your Account Is created Successfully'
  209.         if existing_user:
  210.             dialoge = 'There is alredy an account in this username'
  211.             return render_template('register.html', form=form, dialoge=dialoge)
  212.         else:
  213.             user.insert({'NAMES': names,
  214.                          'USERNAME': usernames,
  215.                          'MAIL': emails,
  216.                          'PASSWORDS': passwords})
  217.         return redirect(url_for('index'))
  218.     return render_template('register.html', form=form)
  219.  
  220.  
  221. @app.route('/login', methods=['GET', 'POST'])
  222. def login():
  223.     print('st')
  224.     form = LoginForm(request.form)
  225.     if request.method == 'POST':
  226.         username = form.username.data
  227.         password = form.password.data
  228.         user = mongo.db.userlist
  229.         existing_user = user.find_one({'USERNAME': username})
  230.         print(username)
  231.         if existing_user:
  232.             if existing_user['PASSWORDS'] == password:
  233.                 print('Password Matched')
  234.                 session['logged_in'] = True
  235.                 session['username'] = username
  236.                 print(session['username'])
  237.                 return redirect(url_for('index'))
  238.             else:
  239.                 error = 'You are not logged in';
  240.                 if 'username' in session:
  241.                     msg = 'You are Logged in as ' + session['username']
  242.                 dialogue = 'Wrong Password'
  243.                 # flash('Wrong password','error')
  244.                 if 'username' in session:
  245.                     return render_template('login.html', msg=msg, form=form, dialogue=dialogue)
  246.  
  247.                 return render_template('login.html', error=error, form=form, dialogue=dialogue)
  248.         else:
  249.             app.logger.info('No User')
  250.             error = 'No such username exist'
  251.             if 'username' in session:
  252.                 msg = 'You are Logged in as ' + session['username']
  253.             if 'username' in session:
  254.                 return render_template('login.html', msg=msg, form=form, dialogue=error)
  255.             # flash('Wrong Usename Or password', error)
  256.             return render_template('login.html', error=error, form=form, dialogue=error)
  257.     elif 'username' in session:
  258.         msg = 'You are Logged in as ' + session['username']
  259.         return render_template('login.html', msg=msg, form=form)
  260.     else:
  261.         error = 'You are not logged in'
  262.         dialogue = 'Wrong password'
  263.         return render_template('login.html', error=error, form=form)
  264.  
  265.  
  266. @app.route('/logout')
  267. def logout():
  268.     session.pop('username', None)
  269.     return redirect(url_for('index'))
  270.  
  271.  
  272. @app.route('/post', methods=['GET', 'POST'])
  273. def post():
  274.     form = create_article_form(request.form)
  275.  
  276.     if request.method == 'POST':
  277.         title = form.title.data
  278.         print("Reach")
  279.         text = form.text.data
  280.         dt = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
  281.         ppt = mongo.db.posts
  282.         user_ = session['username']
  283.         gpb = uuid.uuid4().__str__()
  284.         gpb = 'static/posts/' + gpb + '.html'
  285.         f = open(gpb, "w")
  286.         print(text, file=f)
  287.         f.close()
  288.         # postt = postob(title=title,text=text,dt=dt,user_=user_)
  289.         ppt.insert({
  290.             'TITLE': title,
  291.             'TEXT': gpb,
  292.             'DATE': dt,
  293.             'USER': user_
  294.         })
  295.     if not ('username' in session):
  296.         return redirect(url_for('login'))
  297.     return render_template('create_post.html', form=form)
  298.  
  299.  
  300. @app.route('/about/<id>/submit/')
  301. def prob_submit(id):
  302.     return 'Submit ' + id
  303.  
  304.  
  305. @app.route('/about/<id>/')
  306. def pdfviewers(id):
  307.     pbdb = mongo.db.problems
  308.     pb = pbdb.find_one({'myid': id})
  309.     pbds = prob_struct(pb['name'], pb['time_limit'], pb['memory_limit'], id)
  310.     if not ('username' in session):
  311.         return redirect(url_for('login'))
  312.     Previous = problem_user_submissions(mongo, session['username'], id)
  313.     for i in range(0, len(Previous)):
  314.         print(Previous[i].first)
  315.     # Previous=[]
  316.     Previous.reverse()
  317.     return render_template("pdfviewer.html", pdf_src='/static/uploads/' + id + '.pdf', pbds=pbds, Previous=Previous)
  318.  
  319.  
  320. @app.route('/about')
  321. def postab():
  322.     problemsdb = mongo.db.problems
  323.     list = []
  324.     existing_posts = problemsdb.find({})
  325.     i = 0
  326.     for existing_post in existing_posts:
  327.         ppp = problem(existing_post['sub_task_count'],
  328.                       existing_post['myid'],
  329.                       existing_post['pnt1'],
  330.                       existing_post['pnt2'],
  331.                       existing_post['pnt3'],
  332.                       existing_post['time_limit'],
  333.                       existing_post['memory_limit'],
  334.                       existing_post['stylee'],
  335.                       existing_post['name'],
  336.                       existing_post['acsub'],
  337.                       existing_post['sub'],
  338.                       existing_post['setter'])
  339.         list.append(ppp)
  340.         i = i + 1
  341.     print(len(list))
  342.     # lol
  343.     if not ('username' in session):
  344.         return redirect(url_for('login'))
  345.     return render_template('problem_list.html', obj=list)
  346.  
  347.  
  348. # *******************************************
  349. #   ASIF AHMED*******************************
  350. @app.route('/profile/<id>')
  351. def profile(id):
  352.     from profile import profileCall
  353.     if not ('username' in session):
  354.         return redirect(url_for("login"))
  355.     user, form = profileCall(id)
  356.     userNow = session['username']
  357.     canEdit = 0
  358.     if userNow == id or id == 'myself':
  359.         canEdit = 1
  360.  
  361.     print(canEdit)
  362.     return render_template('profile.html', form=form, user=user, canEdit=canEdit)
  363.  
  364.  
  365. @app.route('/posts/<id>')
  366. def posts(id):
  367.     if not ('username' in session):
  368.         return redirect(url_for('login'))
  369.  
  370.     from profile import profilePostCall
  371.     post_array, user = profilePostCall(id)
  372.     return render_template('user_post.html', post_array=post_array, user=user)
  373.  
  374.  
  375. @app.route('/issues', methods=['GET', 'POST'])
  376. def issues():
  377.     from issue import issueCall
  378.     form, issue_array = issueCall()
  379.     return render_template('issues.html', form=form, issue_array=issue_array)
  380.  
  381.  
  382. @app.route('/issues/<id>', methods=['GET', 'POST'])
  383. def singleIssue(id):
  384.     from issue import singleIssueCall
  385.     form, comment_array, issue = singleIssueCall(id)
  386.     return render_template('issue_page.html', form=form, comment_array=comment_array, issue=issue)
  387.  
  388.  
  389. @app.route('/news')
  390. def news():
  391.     from newsScrapping import newsCall
  392.     return render_template('news.html', article_array=newsCall())
  393.  
  394.  
  395. @app.route('/submission/<id>')
  396. def submissions(id):
  397.     if not ('username' in session):
  398.         return redirect(url_for('login'))
  399.     from profile import profileSubmissionCall
  400.     submission_array, user = profileSubmissionCall(id)
  401.     return render_template('user_submission.html', submission_array=submission_array, user=user)
  402.  
  403.  
  404. @app.route('/contests/<id>')
  405. def userContests(id):
  406.     from profile import profileContestsCall
  407.     user = profileContestsCall(id)
  408.     return render_template('user_contests.html', user=user)
  409.  
  410.  
  411. @app.route('/issue/<id>')
  412. def userIssues(id):
  413.     from profile import profileIssueCall
  414.     user, issue_array = profileIssueCall(id)
  415.     return render_template('user_issues.html', user=user, issue_array=issue_array)
  416.  
  417.  
  418. #   ASIF AHMED*******************************
  419. # ***************************************************************************
  420. languages = ["Java", "C", "Python"]
  421. # CODEMIRROR_LANGUAGES = ['python','c']
  422. #
  423. # CODEMIRROR_THEME = 'base16-dark'
  424. #
  425. # CODEMIRROR_ADDONS = (
  426. #
  427. #     ('display', 'placeholder'),
  428. #     ('hint', 'anyword-hint'),
  429. #     ('hint', 'show-hint'),
  430. #
  431. # )
  432. # app.config.from_object(__name__)
  433. # codemirror = CodeMirror(app)
  434. from codemirrorform import CodemirrorForm
  435.  
  436.  
  437. def runPython(auxForm):
  438.     form = CodemirrorForm(auxForm)
  439.     text = form.source_code.data
  440.     now = time.time()
  441.     then = time.time()
  442.     fout = open(getProgramFileName("Python"), "w")
  443.     print(text, file=fout)
  444.     fout.close()
  445.  
  446.     if auxForm.get("custom_input") != None:
  447.         inputs = form.inputs.data
  448.         finputs = open(getCustomInputsFileName(), "w")
  449.         print(inputs, file=finputs)
  450.         finputs.close()
  451.         now = time.time()
  452.         os.system("python3 " + getProgramFileName("Python") + " < " + getCustomInputsFileName() + " 1>" +
  453.                   getOutputFileName() + " 2>"
  454.                   + getErrorFileName())
  455.         then = time.time()
  456.  
  457.     else:
  458.         now = time.time()
  459.         os.system("python3 " + getProgramFileName(
  460.             "Python") + " 1>" + getOutputFileName() + " 2>"
  461.                   + getErrorFileName())
  462.         then = time.time()
  463.     finputs = open(getOutputFileName(), "r")
  464.     timeElapsed = then - now
  465.     outputs = finputs.readlines()
  466.     outputs.append("Time elapsed during execution: " + str(round(timeElapsed, 3)) + " s")
  467.     finputs.close()
  468.     finputs = open(getErrorFileName(), "r")
  469.     errors = finputs.readlines()
  470.     finputs.close()
  471.     # os.system("rm -r submissions/" + getUserId())
  472.     if len(errors) == 0:
  473.         # print(outputs)
  474.         return render_template('editor.html', form=form, status="Program Output", outputs=outputs, languages=languages)
  475.     else:
  476.         print(errors)
  477.         return render_template('editor.html', form=form, status="Program Compiled with errors", outputs=errors,
  478.                                languages=languages)
  479.  
  480.  
  481. def runJava(auxForm):
  482.     form = CodemirrorForm(auxForm)
  483.     text = form.source_code.data
  484.     now = time.time()
  485.     then = time.time()
  486.     fout = open(getProgramFileName("Java"), "w")
  487.     print(text, file=fout)
  488.     fout.close()
  489.     # compiling the program
  490.     os.system("javac " + getProgramFileName("Java") + " 2>" + getErrorFileName())
  491.     # reading errors
  492.     finputs = open(getErrorFileName(), "r")
  493.     errors = finputs.readlines()
  494.     finputs.close()
  495.     print(errors)
  496.     # running with user defined inputs
  497.     if auxForm.get("custom_input") != None:
  498.         inputs = form.inputs.data
  499.         finputs = open(getCustomInputsFileName(), "w")
  500.         print(inputs, file=finputs)
  501.         finputs.close()
  502.         if len(errors) == 0:
  503.             now = time.time()
  504.             os.system("java -cp " + getExecutibleFileName("Java") + " Main <" + getCustomInputsFileName() +
  505.                       " 1> " + getOutputFileName() + " 2> " + getErrorFileName())
  506.             then = time.time()
  507.         else:
  508.             print(errors)
  509.             # os.system("rm -r submissions/" + getUserId())
  510.             return render_template('editor.html', form=form, status="Program Compiled with errors", outputs=errors,
  511.                                    languages=languages)
  512.     # running without inputs
  513.     else:
  514.         if len(errors) == 0:
  515.             now = time.time()
  516.             os.system("java -cp " + getExecutibleFileName("Java") + " Main " + " 1> " +
  517.                       getOutputFileName() + " 2> " + getErrorFileName())
  518.             then = time.time()
  519.  
  520.         else:
  521.             print(errors)
  522.             # os.system("rm -r submissions/" + getUserId())
  523.             return render_template('editor.html', form=form, status="Program Compiled with errors", outputs=errors,
  524.                                    languages=languages)
  525.     finputs = open(getOutputFileName(), "r")
  526.     outputs = finputs.readlines()
  527.     finputs.close()
  528.     timeElapsed = then - now
  529.     # outputs=list("")
  530.     outputs.append("Time elapsed during execution: " + str(round(timeElapsed, 3)) + " s")
  531.     finputs = open(getErrorFileName(), "r")
  532.     # print(finputs)
  533.     errors = finputs.readlines()
  534.     finputs.close()
  535.     # os.system("rm -r submissions/" + getUserId())
  536.     if len(errors) == 0:
  537.         print(outputs)
  538.         return render_template('editor.html', form=form, status="Program Output", outputs=outputs, languages=languages)
  539.     else:
  540.         print(errors)
  541.         return render_template('editor.html', form=form, status="Program Compiled with errors", outputs=errors,
  542.                                languages=languages)
  543.  
  544.  
  545. def runC(auxForm):
  546.     form = CodemirrorForm(auxForm)
  547.     text = form.source_code.data
  548.     now = time.time()
  549.     then = time.time()
  550.     fout = open(getProgramFileName("C"), "w")
  551.     print(text, file=fout)
  552.     fout.close()
  553.     # compiling the program
  554.     os.system(" g++ -o " + getExecutibleFileName("C") + " " + getProgramFileName("C") + " 2>" + getErrorFileName())
  555.     # reading errors
  556.     finputs = open(getErrorFileName(), "r")
  557.     errors = finputs.readlines()
  558.     finputs.close()
  559.     print(errors)
  560.     # running with user defined inputs
  561.     if auxForm.get("custom_input") != None:
  562.         inputs = form.inputs.data
  563.         finputs = open(getCustomInputsFileName(), "w")
  564.         print(inputs, file=finputs)
  565.         finputs.close()
  566.         # checking for compile errors
  567.         if len(errors) == 0:
  568.             now = time.time()
  569.             os.system(" ./" + getExecutibleFileName("C") + " < " + getCustomInputsFileName() +
  570.                       " 1> " + getOutputFileName() + " 2> " + getErrorFileName())
  571.             then = time.time()
  572.  
  573.         else:
  574.             # os.system("rm -r submissions/" + getUserId())
  575.             return render_template('editor.html', form=form, status="Program Compiled with errors", outputs=errors,
  576.                                    languages=languages)
  577.     # running without inputs
  578.     else:
  579.         if len(errors) == 0:
  580.             now = time.time()
  581.             os.system(" ./" + getExecutibleFileName("C") + " 1> " + getOutputFileName() + " 2> " + getErrorFileName())
  582.             then = time.time()
  583.         else:
  584.             # os.system("rm -r submissions/" + getUserId())
  585.             return render_template('editor.html', form=form, status="Program Compiled with errors", outputs=errors,
  586.                                    languages=languages)
  587.     # reading program outputs
  588.     finputs = open(getOutputFileName(), "r")
  589.     outputs = finputs.readlines()
  590.     finputs.close()
  591.     timeElapsed = then - now
  592.     outputs.append("Time elapsed during execution: " + str(round(timeElapsed, 3)) + " s")
  593.     # reading RTE
  594.     finputs = open(getErrorFileName(), "r")
  595.     errors = finputs.readlines()
  596.     finputs.close()
  597.     # os.system("rm -r submissions/" + getUserId())
  598.     # checking for RTE
  599.     if len(errors) == 0:
  600.         print(outputs)
  601.         return render_template('editor.html', form=form, status="Program Output", outputs=outputs, languages=languages)
  602.     else:
  603.         print(errors)
  604.         return render_template('editor.html', form=form, status="Program Compiled with errors", outputs=errors,
  605.                                languages=languages)
  606.  
  607.  
  608. def getProblemSolution():
  609.     return 12
  610.  
  611.  
  612. def getProgramFileName(language):
  613.     if language == "Python":
  614.         return "submissions/" + getUserId() + "/" + getProblemId() + "/1.py"
  615.     elif language == "Java":
  616.         return "submissions/" + getUserId() + "/" + getProblemId() + "/Main.java"
  617.     else:
  618.         return "submissions/" + getUserId() + "/" + getProblemId() + "/1.cpp"
  619.  
  620.  
  621. def getExecutibleFileName(language):
  622.     if language == "Python":
  623.         return "submissions/" + getUserId() + "/" + getProblemId() + "/a"
  624.     elif language == "Java":
  625.         return "submissions/" + getUserId() + "/" + getProblemId()
  626.     else:
  627.         return "submissions/" + getUserId() + "/" + getProblemId() + "/a"
  628.  
  629.  
  630. def getOutputFileName():
  631.     return "submissions/" + getUserId() + "/" + getProblemId() + "/outputs/1.txt"
  632.  
  633.  
  634. def getErrorFileName():
  635.     return "submissions/" + getUserId() + "/" + getProblemId() + "/outputs/error.txt"
  636.  
  637.  
  638. def getCustomInputsFileName():
  639.     return "submissions/" + getUserId() + "/" + getProblemId() + "/custom_inputs/1.txt"
  640.  
  641.  
  642. def getUserId():
  643.     return session['username']
  644.  
  645.  
  646. def getProblemId():
  647.     return "TestProblem"
  648.  
  649.  
  650. def getExpectedOutputFileName(problemId):
  651.     return "static/uploads/" + problemId + "out1.txt"
  652.  
  653.  
  654. def getTestCaseFileName(problemId):
  655.     return "static/uploads/" + problemId + "in1.txt"
  656.  
  657.  
  658. def doesOutputMatch(userOutputFile, expectedOutputFile):
  659.     try:
  660.         userOutput = open(userOutputFile)
  661.     except:
  662.         return False
  663.     expectedOutput = open(expectedOutputFile)
  664.     for (x, y) in zip(userOutput.readlines(), expectedOutput.readlines()):
  665.         if x != y:
  666.             userOutput.close()
  667.             expectedOutput.close()
  668.             return False
  669.     userOutput.close()
  670.     expectedOutput.close()
  671.     return True
  672.  
  673.  
  674. def makeSubmissionFolders():
  675.     os.system("mkdir submissions/" + getUserId())
  676.     os.system("mkdir submissions/" + getUserId() + "/" + getProblemId())
  677.     os.system("mkdir submissions/" + getUserId() + "/" + getProblemId() + "/outputs")
  678.     os.system("mkdir submissions/" + getUserId() + "/" + getProblemId() + "/custom_inputs")
  679.  
  680.  
  681. def runCode(form):
  682.     selectedLanguage = form.get('languages')
  683.     print(selectedLanguage)
  684.     makeSubmissionFolders()
  685.     if selectedLanguage == "Python":
  686.         return runPython(form)
  687.     elif selectedLanguage == "C":
  688.         return runC(form)
  689.     elif selectedLanguage == "Java":
  690.         return runJava(form)
  691.  
  692.  
  693. def submitCode(auxform, problemId):
  694.     selectedLanguage = auxform.get('languages')
  695.     print(selectedLanguage)
  696.     makeSubmissionFolders()
  697.     submissionInfo = dict()
  698.     submissionInfo["Language"] = selectedLanguage
  699.     submissionInfo["Submission Time"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
  700.     form = CodemirrorForm(auxform)
  701.     text = form.source_code.data.replace("\t", "    ")
  702.     submissionInfo["Code"] = text
  703.     now = time.time()
  704.     then = time.time()
  705.     fout = open(getProgramFileName(selectedLanguage), "w")
  706.     print(text, file=fout)
  707.     fout.close()
  708.     # compiling
  709.     if selectedLanguage == "Java":
  710.         os.system("javac " + getProgramFileName("Java") + " 2>" + getErrorFileName())
  711.     elif selectedLanguage == "C":
  712.         os.system(" g++ -o " + getExecutibleFileName("C") + " " + getProgramFileName("C") + " 2>" + getErrorFileName())
  713.     # reading compile errors
  714.     if selectedLanguage != "Python":
  715.         finputs = open(getErrorFileName(), "r")
  716.         errors = finputs.readlines()
  717.         finputs.close()
  718.  
  719.         if (len(errors) != 0):
  720.             print(errors)
  721.             submissionInfo["Comilation Status"] = "CE"
  722.             return submissionInfo
  723.     # running the program
  724.     if selectedLanguage == "Python":
  725.         now = time.time()
  726.         os.system("python3 " + getProgramFileName("Python") + " < " + getTestCaseFileName(problemId) + " 1>" +
  727.                   getOutputFileName() + " 2>" + getErrorFileName())
  728.         then = time.time()
  729.     elif selectedLanguage == "Java":
  730.         now = time.time()
  731.         os.system("java -cp " + getExecutibleFileName("Java") + " Main <" + getTestCaseFileName(problemId) +
  732.                   " 1> " + getOutputFileName() + " 2> " + getErrorFileName())
  733.         then = time.time()
  734.     elif selectedLanguage == "C":
  735.         now = time.time()
  736.         os.system(" ./" + getExecutibleFileName("C") + " < " + getTestCaseFileName(problemId) +
  737.                   " 1> " + getOutputFileName() + " 2> " + getErrorFileName())
  738.         then = time.time()
  739.  
  740.     # reading runtime errors
  741.     finputs = open(getErrorFileName(), "r")
  742.     errors = finputs.readlines()
  743.     finputs.close()
  744.     if len(errors) != 0:
  745.         submissionInfo["Run Status"] = "RTE"
  746.         return submissionInfo
  747.     timeElapsed = then - now
  748.     submissionInfo["Execution Time"] = timeElapsed
  749.     # if timeElapsed>2:
  750.     #     return "TLE"
  751.     if doesOutputMatch(getExpectedOutputFileName(problemId), getOutputFileName()) == False:
  752.         submissionInfo["Result Verdict"] = "WA"
  753.         return submissionInfo
  754.     else:
  755.         submissionInfo["Result Verdict"] = "Passed"
  756.         return submissionInfo
  757.  
  758.  
  759. def cleanup():
  760.     os.system("rm -r submissions/" + getUserId())
  761.  
  762.  
  763. from bson.objectid import ObjectId
  764.  
  765.  
  766. def getProblemNumber(problemId, contestId):
  767.     print(ObjectId(contestId))
  768.     contest = mongo.db.contests.find({"_id": ObjectId(contestId)})[0]
  769.     problemList = contest.get('Problem ID')
  770.     for x in problemList:
  771.         for y, z in x.items():
  772.             if z == problemId:
  773.                 return y
  774.         # return x
  775.     print(problemList)
  776.  
  777.  
  778. @app.route('/editor/<problemId>', methods=['GET', 'POST'])
  779. def editor(problemId):
  780.     print("not for contest")
  781.     problemsDatabase = mongo.db.problems
  782.     submissionDatabase = mongo.db.submissions
  783.     problemsdb = ProblemsDatabase()
  784.     if request.method == 'POST':
  785.         if "run" in request.form:
  786.             template = runCode(request.form)
  787.             cleanup()
  788.             return template
  789.  
  790.         elif "submit" in request.form:
  791.             submissionInfo = submitCode(request.form, problemId)
  792.             problemsdb.incrementSumissionCount(problemsDatabase, problemId)
  793.             print(submissionInfo)
  794.             problemTimeLimit = problemsDatabase.find_one({"myid": problemId}).get("time_limit")
  795.             verdict = dict()
  796.             verdict["Submission Time"] = submissionInfo.get("Submission Time")
  797.             verdict["Language"] = submissionInfo.get("Language")
  798.             if submissionInfo.get("Compilation Status") != None:
  799.                 verdict["Status"] = submissionInfo.get("Compilation Status")
  800.             elif submissionInfo.get("Run Status") != None:
  801.                 verdict["Status"] = submissionInfo.get("Run Status")
  802.             else:
  803.                 if float(problemTimeLimit) < float(submissionInfo.get("Execution Time")):
  804.                     verdict["Status"] = "TLE"
  805.                 else:
  806.                     if submissionInfo.get("Result Verdict") == "Passed":
  807.                         verdict["Status"] = "AC"
  808.                         problemsdb.incrementSumissionCount(problemsDatabase, problemId)
  809.                     else:
  810.                         verdict["Status"] = "WA"
  811.             verdict["Execution Time"] = submissionInfo.get("Execution Time")
  812.             verdict["Problem Id"] = problemId
  813.             verdict["User Id"] = session["username"]
  814.             verdict["Code"] = submissionInfo.get("Code")
  815.             verdict["Contest Id"] = ""
  816.             verdict["Submission Id"] = uuid.uuid4().__str__()
  817.             print(submissionDatabase.insert(verdict))
  818.             print(verdict)
  819.             cleanup()
  820.             return render_template('editor.html', form=CodemirrorForm(request.form), status=verdict.get("Status"),
  821.                                    languages=languages, check_submissions="Check Submissions")
  822.     return render_template('editor.html', form=CodemirrorForm(request.form), languages=languages)
  823.  
  824.  
  825. @app.route('/editor/<contestId>/<problemId>', methods=['GET', 'POST'])
  826. def contestEditor(problemId, contestId):
  827.     problemsDatabase = mongo.db.problems
  828.     submissionDatabase = mongo.db.submissions
  829.     problemsdb = ProblemsDatabase()
  830.     print("for contest")
  831.     if request.method == 'POST':
  832.         if "run" in request.form:
  833.             template = runCode(request.form)
  834.             cleanup()
  835.             return template
  836.  
  837.         elif "submit" in request.form:
  838.             submissionInfo = submitCode(request.form, problemId)
  839.             problemsdb.incrementSumissionCount(problemsDatabase, problemId)
  840.             print(submissionInfo)
  841.             problemTimeLimit = problemsDatabase.find_one({"myid": problemId}).get("time_limit")
  842.             verdict = dict()
  843.             verdict["Submission Time"] = submissionInfo.get("Submission Time")
  844.             verdict["Language"] = submissionInfo.get("Language")
  845.             if submissionInfo.get("Compilation Status") != None:
  846.                 verdict["Status"] = submissionInfo.get("Compilation Status")
  847.             elif submissionInfo.get("Run Status") != None:
  848.                 verdict["Status"] = submissionInfo.get("Run Status")
  849.             else:
  850.                 if float(problemTimeLimit) < float(submissionInfo.get("Execution Time")):
  851.                     verdict["Status"] = "TLE"
  852.                 else:
  853.                     if submissionInfo.get("Result Verdict") == "Passed":
  854.                         verdict["Status"] = "AC"
  855.                         problemsdb.incrementAcSumissionCount(problemsDatabase, problemId)
  856.                     else:
  857.                         verdict["Status"] = "WA"
  858.             verdict["Execution Time"] = submissionInfo.get("Execution Time")
  859.             verdict["Problem Id"] = problemId
  860.             verdict["Problem Number"] = getProblemNumber(problemId, contestId)
  861.             verdict["User Id"] = session["username"]
  862.             verdict["Code"] = submissionInfo.get("Code")
  863.             verdict["Contest Id"] = contestId
  864.             verdict["Submission Id"] = uuid.uuid4().__str__()
  865.             submissionDatabase.insert(verdict)
  866.             return render_template('editor.html', form=CodemirrorForm(request.form), status=verdict.get("Status"),
  867.                                    languages=languages, check_submissions="Check Submissions")
  868.     return render_template('editor.html', form=CodemirrorForm(request.form), languages=languages,
  869.                            check_submissions="Check Submissions")
  870.  
  871.  
  872. from Submission import Submission
  873.  
  874.  
  875. @app.route('/submissions', methods=['GET', 'POST'])
  876. def view_submissions():
  877.     submissionsDatabase = mongo.db.submissions
  878.     problemsDatabase = mongo.db.problems
  879.     print(submissionsDatabase)
  880.     submissionsCursor = submissionsDatabase.find({}).limit(50).sort([('Submission Time', 1)])
  881.     submissions = list()
  882.     for submission in submissionsCursor:
  883.         submissions.append(Submission(submission, problemsDatabase))
  884.         print(submissions[0].submissionId)
  885.  
  886.     return render_template('submissions.html', submissions=submissions)
  887.  
  888.  
  889. @app.route('/submissions/<submissionId>', methods=['GET', 'POST'])
  890. def view_submission_details(submissionId):
  891.     file = open("static/css/styles/styles.txt", "r")
  892.     themes = list()
  893.     for line in file:
  894.         themes.append(line[:-1])
  895.     file.close()
  896.     # print(request.form)
  897.     if request.form.get("themes") != None:
  898.         preferedTheme = request.form.get("themes")
  899.     else:
  900.         preferedTheme = "atom-one-dark"
  901.     submissionsDatabase = mongo.db.submissions
  902.     submission = Submission(submissionsDatabase.find({"Submission Id": submissionId})[0], mongo.db.problems)
  903.     language = str(submission.language).lower()
  904.     return render_template('submitted_Code_viewer.html', submission=submission, language=language, themes=themes,
  905.                            preferedTheme=preferedTheme)
  906.  
  907.  
  908. @app.route('/user/<userName>', methods=['GET', 'POST'])
  909. def userProfile(userName):
  910.     class User:
  911.         def __init__(self, name, username, mail):
  912.             self.name = name
  913.             self.username = username
  914.             self.mail = mail
  915.  
  916.     users = mongo.db.userlist
  917.     existing_user = users.find_one({'USERNAME': userName})
  918.     user = User(existing_user['NAMES'], existing_user['USERNAME'], existing_user['MAIL'])
  919.     return render_template('profile.html', user=user)
  920.  
  921.  
  922. @app.route('/onlineide', methods=['GET', 'POST'])
  923. def onlineide():
  924.     if request.method == 'POST':
  925.         if "run" in request.form:
  926.             template = runCode(request.form)
  927.             cleanup()
  928.             print(CodemirrorForm(request.form).source_code.data)
  929.             return template
  930.     return render_template('editor.html', form=CodemirrorForm(request.form), languages=languages)
  931.  
  932.  
  933. @app.route('/udebug', methods=['GET', 'POST'])
  934. def problemList():
  935.     problemsdb = mongo.db.problems
  936.     list = []
  937.     existing_posts = problemsdb.find({})
  938.     i = 0
  939.     for existing_post in existing_posts:
  940.         ppp = problem(existing_post['sub_task_count'],
  941.                       existing_post['myid'],
  942.                       existing_post['pnt1'],
  943.                       existing_post['pnt2'],
  944.                       existing_post['pnt3'],
  945.                       existing_post['time_limit'],
  946.                       existing_post['memory_limit'],
  947.                       existing_post['stylee'],
  948.                       existing_post['name'],
  949.                       existing_post['acsub'],
  950.                       existing_post['sub'],
  951.                       existing_post['setter'])
  952.         list.append(ppp)
  953.         i = i + 1
  954.     print(len(list))
  955.     # lol
  956.     if not ('username' in session):
  957.         return redirect(url_for('login'))
  958.     return render_template('problem_list_for_udebug.html', obj=list)
  959.  
  960.  
  961. def runForUbebug(inputs, text):
  962.     makeSubmissionFolders()
  963.     fout = open(getProgramFileName("C"), "w")
  964.     print(text, file=fout)
  965.     fout.close()
  966.     # compiling the program
  967.     os.system(" g++ -o " + getExecutibleFileName("C") + " " + getProgramFileName("C") + " 2>" + getErrorFileName())
  968.     # reading errors
  969.     finputs = open(getErrorFileName(), "r")
  970.     errors = finputs.readlines()
  971.     finputs.close()
  972.     print(errors)
  973.     # running with user defined inputs
  974.     if True:
  975.         finputs = open(getCustomInputsFileName(), "w")
  976.         print(inputs, file=finputs)
  977.         finputs.close()
  978.         # checking for compile errors
  979.         if len(errors) == 0:
  980.  
  981.             os.system(" ./" + getExecutibleFileName("C") + " < " + getCustomInputsFileName() +
  982.                       " 1> " + getOutputFileName() + " 2> " + getErrorFileName())
  983.  
  984.  
  985.         else:
  986.             # os.system("rm -r submissions/" + getUserId())
  987.             return errors
  988.  
  989.     # reading program outputs
  990.     finputs = open(getOutputFileName(), "r")
  991.     outputs = finputs.readlines()
  992.     finputs.close()
  993.     # reading RTE
  994.     finputs = open(getErrorFileName(), "r")
  995.     errors = finputs.readlines()
  996.     finputs.close()
  997.     # os.system("rm -r submissions/" + getUserId())
  998.     # checking for RTE
  999.     output = ""
  1000.     cleanup()
  1001.     for x in outputs:
  1002.         output += x
  1003.     if len(errors) == 0:
  1004.         print(output)
  1005.         return output
  1006.     else:
  1007.         print(errors)
  1008.         return errors
  1009.  
  1010.  
  1011. def getCode(filename):
  1012.     codelist = open(filename).readlines()
  1013.     code = ""
  1014.     for x in codelist:
  1015.         code += x + "\n"
  1016.     return code
  1017.  
  1018.  
  1019. def getInputFileListForUdebug(problemId):
  1020.     os.system("cd static/inputs_for_udebug &&ls | grep " + problemId + ">" + getUserId() + ".txt")
  1021.     return open("static/inputs_for_udebug/" + getUserId() + ".txt").readlines()
  1022.  
  1023.  
  1024. def getInputsForUdebug(filename):
  1025.     codelist = open(filename).readlines()
  1026.     code = ""
  1027.     for x in codelist:
  1028.         code += x
  1029.     return code
  1030.  
  1031.  
  1032. def extractInputName(x, problemId):
  1033.     return x.replace(problemId, "").replace(".txt", "")
  1034.  
  1035.  
  1036. @app.route('/udebug/<problemId>', methods=['GET', 'POST'])
  1037. def udebug(problemId):
  1038.     acceptedOutput = ""
  1039.     yourOutputs = ""
  1040.     inputs = ""
  1041.     mismatchNumber = -1
  1042.     results = list()
  1043.     inputFiles = getInputFileListForUdebug(problemId)
  1044.     selectedinputFile = ""
  1045.     usableInputFiles = list()
  1046.     for x in inputFiles:
  1047.         usableInputFiles.append(extractInputName(x, problemId))
  1048.     print(inputFiles)
  1049.     if "get_accepted_output_button" in request.form:
  1050.         acceptedOutput = request.form["accepted_output_textarea"]
  1051.         inputs = request.form["input_textarea"]
  1052.         code = getCode("static/solutions/" + problemId + ".c")
  1053.         acceptedOutput = runForUbebug(inputs, code)
  1054.         print(code)
  1055.         print(acceptedOutput)
  1056.  
  1057.     elif "compare_outputs_button" in request.form:
  1058.         print(request.form)
  1059.         acceptedOutput = request.form["accepted_output_textarea"]
  1060.         inputs = request.form["input_textarea"]
  1061.         yourOutputs = request.form["your_output_textarea"]
  1062.         code = getCode("static/solutions/" + problemId + ".c")
  1063.         acceptedOutput = runForUbebug(inputs, code)
  1064.         # print(code)
  1065.         # print(acceptedOutput)
  1066.         yourOutputList = list()
  1067.         acceptedOutputList = list()
  1068.         for x in acceptedOutput.split("\n"):
  1069.             if x == None:
  1070.                 acceptedOutputList.append("")
  1071.             else:
  1072.                 acceptedOutputList.append(x)
  1073.         for x in yourOutputs.split("\n"):
  1074.             if x == None:
  1075.                 yourOutputList.append("")
  1076.             else:
  1077.                 yourOutputList.append(x)
  1078.         acceptedOutputLineNumber = len(acceptedOutputList)
  1079.         yourOutputLineNumber = len(yourOutputList)
  1080.         if (len(acceptedOutputList) > len(yourOutputList)):
  1081.             for i in range(len(acceptedOutputList) - len(yourOutputList)):
  1082.                 yourOutputList.append("")
  1083.         elif (len(acceptedOutputList) < len(yourOutputList)):
  1084.             for i in range(-len(acceptedOutputList) + len(yourOutputList)):
  1085.                 acceptedOutputList.append("")
  1086.         outputpair = zip(acceptedOutputList, yourOutputList)
  1087.         mismatchNumber = 0
  1088.         for i, (x, y) in enumerate(outputpair):
  1089.             if x != y[:-1]:
  1090.                 mismatchNumber += 1
  1091.                 if (i < acceptedOutputLineNumber and i < yourOutputLineNumber):
  1092.                     results.append((int(i + 1), x, int(i + 1), y))
  1093.                 elif (i < acceptedOutputLineNumber):
  1094.                     results.append((int(i + 1), x, "", y))
  1095.                 else:
  1096.                     results.append(("", x, int(i + 1), y))
  1097.     if "inputstorer" in request.form and len(request.form["inputstorer"]) > 0:
  1098.         selectedinputFile = "static/inputs_for_udebug/" + problemId + str(request.form["inputstorer"]).replace("\n",
  1099.                                                                                                                "").replace(
  1100.             "\r", "").strip(" ") + ".txt"
  1101.         inputs = getInputsForUdebug(selectedinputFile)
  1102.     return render_template('udebug.html', selectedinput=inputs, acceptedOutput=acceptedOutput, yourOutput=yourOutputs,
  1103.                            results=results, mismatchNumber=mismatchNumber, inputs=usableInputFiles)
  1104.  
  1105.  
  1106. # *****************************************************************************************
  1107.  
  1108. class lol:
  1109.     def __init__(self, id, name, acc, sc, box):
  1110.         self.id = id
  1111.         self.name = name
  1112.         self.acc = acc
  1113.         self.sc = sc
  1114.         self.box = box
  1115.  
  1116.  
  1117. class create_contest_form(Form):
  1118.     contestname = StringField("Contest Name", [validators.DataRequired()])
  1119.  
  1120.  
  1121. def forward_letter(letter, positions):
  1122.     if letter.islower():
  1123.         unicode_point = ord('a')
  1124.     else:
  1125.         unicode_point = ord('A')
  1126.     start = ord(letter) - unicode_point
  1127.     offset = ((start + positions)) + unicode_point
  1128.     current_letter = chr(offset)
  1129.     return current_letter
  1130.  
  1131.  
  1132. @app.route('/contest', methods=['GET', 'POST'])
  1133. def contest():
  1134.     form = create_contest_form(request.form)
  1135.  
  1136.     problemdb = mongo.db.problems
  1137.     list = []
  1138.     existing_pbs = problemdb.find({})
  1139.     for existing_pb in existing_pbs:
  1140.         list.append(lol(existing_pb['myid'], existing_pb['name'], existing_pb['acsub'], existing_pb['sub'],
  1141.                         existing_pb['myid']))
  1142.     if request.method == 'POST':
  1143.         print(request.form[form.contestname.name])
  1144.         cnt = 0;
  1145.         selected_problem_id = []
  1146.         name = 'A'
  1147.         for prblm in list:
  1148.             if request.form.get(prblm.id):
  1149.                 cnt += 1
  1150.                 selected_problem_id.append({forward_letter(name, cnt - 1): prblm.id});
  1151.                 print(prblm.name)
  1152.         if cnt == 0:
  1153.             flash('You have to Choose at least 1 problem to set a contest.', 'failure')
  1154.             return render_template('create_contest.html', obj=list, form=form)
  1155.         else:
  1156.             contests = mongo.db.contests
  1157.             contests.insert({'Contest Title': form.contestname.data, 'Start Date': request.form['date'],
  1158.                              'Start Time': request.form['start_time'], 'End Time': request.form['end_time'],
  1159.                              'Password': request.form['password'], 'Problem Count': cnt,
  1160.                              'Problem ID': selected_problem_id})
  1161.             return redirect(url_for('contests'))
  1162.  
  1163.     return render_template('create_contest.html', obj=list, form=form)
  1164.  
  1165.  
  1166. @app.route('/currentcontest/<contestID>/ranklist')
  1167. def ranklist(contestID):
  1168.     # #total_problem=['A','B','C','D','E','F']
  1169.     # submission_history=[{'name':'A','status':'AC','total_submission':3}]
  1170.     # submission_history.append({'name':'B','status':'WA','total_submission':2})
  1171.     # submission_history.append({'name': 'E', 'status': 'RTE', 'total_submission': 6})
  1172.     # submission_history.append({'name': 'C', 'status': 'WA', 'total_submission': 2})
  1173.     # submission_history.append({'name': 'D', 'status': 'TLE', 'total_submission': 2})
  1174.     # submission_history.append({'name': 'F', 'status': 'NS', 'total_submission': 0})
  1175.     # contestant1={'name':'SALAM','acc':3,'penalty':120,'submission_history':submission_history}
  1176.     # contestant2 = {'name': 'Borkot', 'acc': 2, 'penalty': 110, 'submission_history': submission_history}
  1177.     # Total_contestant=[contestant1,contestant2]
  1178.     Total_contestant = []
  1179.     submission = mongo.db.submissions
  1180.     contestant_wise_submission = submission_formatter(submission, contestID)
  1181.     contests = mongo.db.contests
  1182.     contt = contests.find({'_id': ObjectId(contestID)})
  1183.  
  1184.     problem_cnt = 0
  1185.     contestant_start_date = ""
  1186.     contestant_start_time = ""
  1187.     for cont in contt:
  1188.         problem_cnt = cont['Problem Count']
  1189.         contestant_start_date = cont['Start Date']
  1190.         contestant_start_time = cont['Start Time']
  1191.     print(problem_cnt)
  1192.     total_problem = problem_subname_generator(problem_cnt, submission.find({'Contest Id': contestID}))
  1193.  
  1194.     for eachcontestant in contestant_wise_submission:
  1195.         Total_contestant.append(
  1196.             contestant_wise_submission_formatter(eachcontestant, total_problem, contestant_start_date,
  1197.                                                  contestant_start_time))
  1198.  
  1199.     return render_template('ranklist.html', total_problem=total_problem, Total_contestant=Total_contestant)
  1200.  
  1201.  
  1202. def problem_subname_generator(problem_cnt, all_submission):
  1203.     total = []
  1204.     for i in range(0, problem_cnt):
  1205.         total.append(forward_letter('A', i))
  1206.     total_with_cnt = []
  1207.     submission = []
  1208.     for each in all_submission:
  1209.         submission.append(each)
  1210.     for eachproblem in total:
  1211.         cnt = 0
  1212.         ac_cnt = 0
  1213.         for each in submission:
  1214.             if each['Problem Number'] == eachproblem:
  1215.                 cnt += 1
  1216.                 if each['Status'] == 'AC':
  1217.                     ac_cnt += 1
  1218.             print(eachproblem)
  1219.         total_with_cnt.append({'problem_name': eachproblem, 'ac_cnt': ac_cnt, 'total_cnt': cnt})
  1220.     return total_with_cnt
  1221.  
  1222.  
  1223. def submission_formatter(submission, contestID):
  1224.     contestant_wise_submission = []
  1225.     User = []
  1226.     total = 0
  1227.     all_submission = submission.find({'Contest Id': contestID})
  1228.     for dict in all_submission:
  1229.         submissions = submission.find({'Contest Id': contestID, 'User Id': dict["User Id"]})
  1230.         if dict['User Id'] not in User:
  1231.             contestant_wise_submission.append(submissions)
  1232.             User.append(dict['User Id'])
  1233.  
  1234.     return contestant_wise_submission
  1235.  
  1236.  
  1237. def contestant_wise_submission_formatter(submissions, total_problem, contest_start_date, contest_start_time):
  1238.     submission_history = []
  1239.     penalty = 0
  1240.     acc = 0
  1241.     name = ""
  1242.     submission = []
  1243.     for each in submissions:
  1244.         submission.append(each)
  1245.     for eachproblem in total_problem:
  1246.  
  1247.         each_prboblem_sub = []
  1248.         for each in submission:
  1249.             if each['Problem Number'] == eachproblem['problem_name']:
  1250.                 each_prboblem_sub.append(each)
  1251.  
  1252.         status = "NS"
  1253.         submission_time = 0
  1254.         cnt = 0
  1255.         execution_time = 0
  1256.         all_submissions = []
  1257.         for eachsub in each_prboblem_sub:
  1258.             all_submissions.append({'Status': eachsub['Status'], 'Submission_time': eachsub['Submission Time']})
  1259.  
  1260.         for eachsub in each_prboblem_sub:
  1261.             name = eachsub['User Id']
  1262.             if eachsub['Status'] == 'AC':
  1263.                 status = 'AC'
  1264.                 submission_time = eachsub['Submission Time']
  1265.                 acc += 1
  1266.                 execution_time = eachsub['Execution Time']
  1267.                 penalty += 20 * cnt + execution_time * 100 - 100
  1268.                 cnt += 1
  1269.                 break
  1270.             cnt += 1
  1271.             status = eachsub['Status']
  1272.  
  1273.         if submission_time != 0:
  1274.             dif = get_datetime_to_sec(submission_time, contest_start_date, contest_start_time)
  1275.             penalty += dif / 60
  1276.  
  1277.         submission_history.append({'name': eachproblem['problem_name'], 'status': status, 'total_submission': cnt,
  1278.                                    'all_submissions': all_submissions})
  1279.     contestant = {'name': name, 'acc': acc, 'penalty': int(penalty), 'submission_history': submission_history}
  1280.     return contestant
  1281.  
  1282.  
  1283. def get_datetime_to_sec(submission_time, contest_start_date, contest_start_time):
  1284.     dt = submission_time.split()
  1285.  
  1286.     subd = dt[0].split('-')
  1287.     subt = dt[1].split(':')
  1288.     startd = contest_start_date.split('-')
  1289.     startt = contest_start_time.split(':')
  1290.     dt1 = datetime.datetime(int(subd[0]), int(subd[1]), int(subd[2]), int(subt[0]), int(subt[1]))
  1291.     dt2 = datetime.datetime(int(startd[0]), int(startd[1]), int(startd[2]), int(startt[0]), int(startt[1]))
  1292.  
  1293.     subsec = time.mktime(dt1.timetuple())
  1294.     startsec = time.mktime(dt2.timetuple())
  1295.     return subsec - startsec
  1296.  
  1297.  
  1298. ############################################
  1299.  
  1300.  
  1301. class contest:
  1302.     def __init__(self, c_id, title, start_date, start_time, end_time, IDs):
  1303.         self.c_id = c_id
  1304.         self.title = title
  1305.         self.start_date = start_date
  1306.         self.start_time = start_time
  1307.         self.end_time = end_time
  1308.         self.IDs = IDs
  1309.  
  1310.  
  1311. class contestdata:
  1312.     def __init__(self, c_id, title, time):
  1313.         self.c_id = c_id
  1314.         self.title = title
  1315.         self.time = time
  1316.  
  1317.  
  1318. @app.route('/contests')
  1319. def contests():
  1320.     contest_db = mongo.db.contests
  1321.     contest_list = []
  1322.     loaded_contests = contest_db.find({})
  1323.     for contest_curr in loaded_contests:
  1324.         time_string = contest_curr['Start Date'] + ' ' + contest_curr['Start Time']
  1325.         # time_obj = datetime.strptime(time_string, '%Y-%m-%d %H:%M')
  1326.         subd = contest_curr['Start Date'].split('-')
  1327.         subt = contest_curr['Start Time'].split(':')
  1328.         dt1 = datetime.datetime(int(subd[0]), int(subd[1]), int(subd[2]), int(subt[0]), int(subt[1]))
  1329.         new_contest = contestdata(contest_curr['_id'],
  1330.                                   contest_curr['Contest Title'],
  1331.                                   dt1)
  1332.         contest_list.append(new_contest)
  1333.     contest_list.sort(key=lambda r: r.time, reverse=True)
  1334.     if not ('username' in session):
  1335.         return redirect(url_for('login'))
  1336.     return render_template('contests.html', obj=contest_list)
  1337.  
  1338.  
  1339. class PasswordForm(Form):
  1340.     password = StringField('Password')
  1341.  
  1342.  
  1343. # Password check for contest
  1344. @app.route('/contest/<id>/verify', methods=['GET', 'POST'])
  1345. def verify_contest(id):
  1346.     form = PasswordField(request.form)
  1347.     contest_db = mongo.db.contests
  1348.     contest_now = contest_db.find({"_id": ObjectId(id)})[0]
  1349.     c_pass = contest_now.get('Password')
  1350.     c_name = contest_now.get('Contest Title')
  1351.     print("p : " + c_pass)
  1352.     if not c_pass:
  1353.         print("no password")
  1354.         url = "http://127.0.0.1:5000/currentcontest/" + id + "/landing"
  1355.         return redirect(url, 302)
  1356.     if request.method == 'POST':
  1357.         password = request.form['password']
  1358.         print(password)
  1359.         print(c_pass)
  1360.         if c_pass == password:
  1361.             url = "http://127.0.0.1:5000/currentcontest/" + id + "/landing"
  1362.             return redirect(url, 302)
  1363.         else:
  1364.             error = "You need to enter the password for this contest"
  1365.             return render_template('contest_verify.html', error=error, form=form, name=c_name)
  1366.     else:
  1367.         return render_template('contest_verify.html', form=form, name=c_name)
  1368.  
  1369.  
  1370. # Contest Page
  1371. @app.route('/currentcontest/<cc_id>')
  1372. def load_contest(cc_id):
  1373.     contest_db = mongo.db.contests
  1374.     problem_db = mongo.db.problems
  1375.     contest_now = contest_db.find({"_id": ObjectId(cc_id)})[0]
  1376.     starting_datetime = contest_now.get('Start Date') + "T" + contest_now.get('Start Time') + ":00+06:00"
  1377.     ending_datetime = contest_now.get('Start Date') + "T" + contest_now.get('End Time') + ":00+06:00"
  1378.     cc_name = contest_now.get('Contest Title')
  1379.     print(starting_datetime)
  1380.     print(ending_datetime)
  1381.     problems = contest_now.get('Problem ID')
  1382.     problem_list = []
  1383.     for p in problems:
  1384.         for x, y in p.items():
  1385.             i = problem_db.find_one({'myid': y})
  1386.             print(i)
  1387.             new_prob = problem(i['sub_task_count'], i['myid'], i['pnt1'], i['pnt2'], i['pnt3'], i['time_limit'],
  1388.                                i['memory_limit'], i['stylee'], i['name'], i['acsub'], i['sub'], i['setter'])
  1389.             problem_list.append(new_prob)
  1390.     if not ('username' in session):
  1391.         return redirect(url_for('login'))
  1392.     return render_template('contest.html', obj=problem_list, id=cc_id, name=cc_name, sdto=starting_datetime,
  1393.                            edto=ending_datetime)
  1394.  
  1395.  
  1396. # Problem pages of contest
  1397. @app.route('/currentcontest/<contest_id>/<id2>')
  1398. def load_contest_problem(contest_id, id2):
  1399.     pbdb = mongo.db.problems
  1400.     pb = pbdb.find_one({'myid': id2})
  1401.     pbds = prob_struct(pb['name'], pb['time_limit'], pb['memory_limit'], id2)
  1402.  
  1403.     contest_db = mongo.db.contests
  1404.     contest_now = contest_db.find({"_id": ObjectId(contest_id)})[0]
  1405.     end_time = contest_now.get('Start Date') + "T" + contest_now.get('End Time') + ":00+06:00"
  1406.     if not ('username' in session):
  1407.         return redirect(url_for('login'))
  1408.     return render_template("problem_viewer.html", pdf_src='/static/uploads/' + id2 + '.pdf', pbds=pbds, cid=contest_id,
  1409.                            et=end_time)
  1410.  
  1411.  
  1412. # landing page if contest is not started yet
  1413. @app.route('/currentcontest/<contst_id>/landing')
  1414. def check_contest(contst_id):
  1415.     current_time = datetime.datetime.now()
  1416.     print(current_time)
  1417.     contest_db = mongo.db.contests
  1418.     contest_now = contest_db.find({"_id": ObjectId(contst_id)})[0]
  1419.     cc_name = contest_now.get('Contest Title')
  1420.     starting_datetime = contest_now.get('Start Date') + "T" + contest_now.get('Start Time') + ":00+06:00"
  1421.     time_string = contest_now.get('Start Date') + " " + contest_now.get('Start Time')
  1422.     start_time_p = datetime.datetime.strptime(time_string, "%Y-%m-%d %H:%M")
  1423.     if not ('username' in session):
  1424.         return redirect(url_for('login'))
  1425.     if start_time_p < current_time:
  1426.         url = "http://127.0.0.1:5000/currentcontest/" + contst_id
  1427.         return redirect(url, 302)
  1428.     else:
  1429.         return render_template("contest_landing.html", cid=contst_id, st=starting_datetime, name=cc_name)
  1430.  
  1431.  
  1432. # submission list in contest
  1433. @app.route('/currentcontest/<contest_id>/submissions')
  1434. def load_my_contest_submissions(contest_id):
  1435.     return "my contest list"
  1436.  
  1437. ######################################################################################################
  1438.  
  1439. @app.route('/graph', methods=['GET', 'POST'])
  1440. def graphbuild():
  1441.     form = graph_input(request.form)
  1442.     if request.method == 'POST':
  1443.         directed = True
  1444.         if request.form.get('choice') == 'Undirected':
  1445.             directed = False
  1446.         if directed == True:
  1447.             idd = uuid.uuid4().__str__()
  1448.             fst = open('static/graph/samplestart.txt', "r")
  1449.             stst = fst.read()
  1450.             fed = open('static/graph/sampleend.txt', "r")
  1451.             sted = fed.read()
  1452.             f = open('templates/' + idd + '.html', "w+")
  1453.             f1 = open('templates/' + 'checker.txt', "w+")
  1454.             print(stst, file=f)
  1455.  
  1456.             nd_list = FunctionList.node_list(st=form.nodes_desc.data.replace('\n', ' '), nd_cnt=form.nodes_cnt.data)
  1457.             ed_list = FunctionList.edge_list(st=form.ed_desc.data.replace('\n', ' '), ed_cnt=form.ed_cnt.data)
  1458.             gp = FunctionList.graph(nd_list, ed_list)
  1459.             ad = FunctionList.adapter(gp)
  1460.             js = FunctionList.jsonstring(ad)
  1461.             print(js.getstring(), file=f)
  1462.  
  1463.             print(sted, file=f)
  1464.             print(form.nodes_desc.data)
  1465.             f.close()
  1466.             return render_template(idd + '.html')
  1467.         else:
  1468.             idd = uuid.uuid4().__str__()
  1469.             fst = open('static/graph/undirectedstart.txt', "r")
  1470.             stst = fst.read()
  1471.             fed = open('static/graph/undirectedent.txt', "r")
  1472.             sted = fed.read()
  1473.             f = open('templates/' + idd + '.html', "w+")
  1474.             f1 = open('templates/' + 'checker.txt', "w+")
  1475.             print(stst, file=f)
  1476.  
  1477.             nd_list = FunctionList.node_list(st=form.nodes_desc.data.replace('\n', ' '), nd_cnt=form.nodes_cnt.data)
  1478.             ed_list = FunctionList.edge_list(st=form.ed_desc.data.replace('\n', ' '), ed_cnt=form.ed_cnt.data)
  1479.             sz = len(ed_list)
  1480.             for i in range(0, sz, 2):
  1481.                 if ed_list[i] <= ed_list[i + 1]:
  1482.                     xx = ed_list[i]
  1483.                     ed_list[i] = ed_list[i + 1]
  1484.                     ed_list[i + 1] = xx
  1485.             gp = FunctionList.graph(nd_list, ed_list)
  1486.             ad = FunctionList.adapter(gp)
  1487.             js = FunctionList.jsonstring(ad)
  1488.             print(js.getstring(), file=f)
  1489.  
  1490.             print(sted, file=f)
  1491.             print(form.nodes_desc.data)
  1492.             f.close()
  1493.             return render_template(idd + '.html')
  1494.  
  1495.     return render_template('input_graph.html', form=form)
  1496.  
  1497.  
  1498. from ProblemsDatabase import ProblemsDatabase
  1499.  
  1500.  
  1501. @app.route('/test')
  1502. def test():
  1503.     problemsDatabase = ProblemsDatabase()
  1504.     problemsDatabase.incrementSumissionCount(mongo.db.problems, 'ceed47bd-95a0-4297-bc75-6b46cc2b54c7')
  1505.     print("done")
  1506.     return "done"
  1507.  
  1508.  
  1509. if __name__ == '__main__':
  1510.     app.secret_key = 'SUPER SECRET KEY'
  1511.     app.config['SESSION_TYPE'] = 'filesystem'
  1512.     # sess.init_app(app) # uncomment this
  1513.  
  1514.     app.debug = True
  1515.     app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement