def updateContestNotice(request, cId, cnId): try: u = User.getSessionUser(request.session) if not u: raise Exception(Const.NOT_LOGGED_IN) c = Contest.getById(cId) cn = ContestNotice.getById(cnId) c.canBeManaged(u) if request.method == 'POST': form = contestNoticeForm(request.POST) if form.is_valid(): cnTitle = form.cleaned_data['title'] cnContent = form.cleaned_data['content'] cn.updateNotice(cnTitle, cnContent) return redirect('Contest:show_contest_notice', cId, cn.id) else: return render(request, 'newtpl/contest/updateContestNotice.html', {'form': form, 'cid': cId, 'cnid': cnId, 'tpl':{'has_priv': True, 'sp': True, 'nav_act':'contest',}}) else: form = contestNoticeForm( initial={ 'title': cn.notice_title, 'content': cn.notice_content, } ) return render(request, 'newtpl/contest/updateContestNotice.html', {'form': form, 'cid': cId, 'cnid': cnId, 'tpl':{'has_priv': True, 'sp': True, 'nav_act':'contest',}}) except Exception as e: return render(request, Const.ERROR_PAGE, {'errmsg': unicode(e), })
def answerClarification(request, clar_id): logger.info(str(request).replace("\n","\t")) try: u = User.getSessionUser(request.session) if not u: raise Exception(Const.NOT_LOGGED_IN) clar = Clarification.getById(clar_id) if not clar: raise Exception('No such Clarification!') c = clar.contest if not c: raise Exception(Const.CONTEST_NOT_EXIST) try: c.canBeManaged(u) except: raise Exception('No Privilege!') if request.method != 'POST': return render(request, 'newtpl/contest/answerClar.html', {'clar': clar}) form = AnswerClarificationForm(request.POST) try: if form.is_valid(): answer = form.cleaned_data['answer'] clar.updateAnswer(answer, u) return redirect('Contest:view_all_clars', c.cid) else: raise Exception('Invalid Answer!') except Exception as e: raise e except Exception as e: logger.error(unicode(e).replace('\n', '\t')) return render(request, Err.ERROR_PAGE, {'errmsg': unicode(e)})
def listProblem(request, pageId="1"): # modified logger.info(str(request).replace("\n","\t")) try: pageId = int(pageId) u = User.getSessionUser(request.session) if not u: raise Err(request, 'not login') tres = Problem.problemList(u) if (pageId-1)*Const.PROBLEM_PER_PAGE>=len(tres): raise Err(request, 'unknown err') res = tres[(pageId-1)*Const.PROBLEM_PER_PAGE:pageId*Const.PROBLEM_PER_PAGE] res = tres probs = [] for p in res: all_submits = GeneralSubmission.objects.filter(problem = p) all_accepts = all_submits.filter(status = 'Accepted') submits = all_submits.count() accepts = all_accepts.count() ratio = 0 if submits == 0 else 100 * accepts / submits probs.append({'accepts': accepts, 'submits': submits, 'ratio': ratio, 'prob': p}) paginator = Paginator(probs, Const.PROBLEM_PER_PAGE) pageId = min(max(int(pageId), 1), paginator.num_pages) #return render(request,"newtpl/problem/problemList.html",{'tpl':{'sp':False}, 'problems': probs}) return render(request,"newtpl/problem/problemList.html",{'tpl':{'sp':False}, 'problems': paginator.page(pageId)}) except Exception as e: logger.error(str(e).replace("\n","\t")) return render(request, Err.ERROR_PAGE)
def addRecord(request, cid): try: u = User.getSessionUser(request.session) if not u: raise Err(request, err='not login') c = Contest.getById(cid) try: c.canBeManaged(u) except: raise Err(request, err='no priv') cp = c.getContestProblem() if request.method == 'POST': form = ChooseProbForm(cp, request.POST) if form.is_valid(): Cheat.addRecord(cp_set=form.cleaned_data['contest_problem']) Cheat.antiCheat() return redirect('Cheat:show_cheat_result', cid=c.cid) else: raise Err(request, err='unknown err') else: form = ChooseProbForm(cp) return render(request, 'newtpl/cheat/addRecord.html', {'tpl':{'sp':True,}, 'contest':c, 'form':form,}) except Exception as e: return render(request, Err.ERROR_PAGE)
def listContestByAuthor(request, pageId='1'): """ view used to list all contest created by the specific user """ try: u = User.getSessionUser(request.session) if not u: messages.info(request, u'请先登录') return render(request, 'newtpl/contest/contestListByAuthor.html') contestList = Contest.getByAuthor(u) now = datetime.now() for c in contestList: c.course_class_name = unicode(c.course_class.getFullName()) c.title = unicode(c.contest_title) if c.start_time+timedelta(minutes=c.length)<now: c.status = 'ended' elif c.start_time > now: c.status = 'scheduled' else: c.status = 'running' paginator = Paginator(contestList, Const.CONTEST_PER_PAGE) pageId = min(max(int(pageId), 1), paginator.num_pages) return render(request, 'newtpl/contest/contestListByAuthor.html', { 'contest_list': paginator.page(pageId), 'tpl':{'has_priv': True, 'nav_act':'contest',}}) except Exception as e: return render(request, Const.ERROR_PAGE, {'errmsg': unicode(e), })
def listContestByPriv(request, ccId, pageId='1'): """ view used to list all contest a user can manage, course_class restricted """ try: u = User.getSessionUser(request.session) if not u: messages.info(request, u'请先登录') return render(request, 'newtpl/contest/contestListByPriv.html') cc = CourseClass.getById(ccId) if not Contest.hasPriv(cc, u): raise Exception(Const.NOT_PVLG) contestList = Contest.getByCourseClass(cc) now = datetime.now() for c in contestList: c.course_class_name = unicode(c.course_class.getFullName()) c.title = unicode(c.contest_title) if c.start_time+timedelta(minutes=c.length)<now: c.status = 'ended' elif c.start_time > now: c.status = 'scheduled' else: c.status = 'running' paginator = Paginator(contestList, Const.CONTEST_PER_PAGE) pageId = min(max(int(pageId), 1), paginator.num_pages) return render(request, 'newtpl/contest/contestListByPriv.html', {'contest_list': paginator.page(pageId), 'course_class': cc, 'tpl':{'has_priv': True, 'nav_act':'contest',}}) except Exception as e: return render(request, Const.ERROR_PAGE, {'errmsg': unicode(e), })
def rejudgeGeneralSubmission( request, gsid): """ rejudge the very general submission with the specific id """ try: gsid = int( gsid) u = User.getSessionUser( request.session) if not u: raise Err( request, err='not login') try: g_s = GeneralSubmission.getById( gsid) except: raise Err( request, err='no generalsubmission', log_format=( '{0}'.format( gsid), ''), user_format=( u'{0}'.format( gsid), u'别扯了!!'), ) # fake if u.priv == 'student': raise Err( request, err = 'no priv') GeneralSubmission.rejudgeGeneralSubmission( g_s) return redirect( 'Submission:status') except Exception as e: return render( request, Const.NEW_ERROR_PAGE, { 'errmsg': unicode(e), }, )
def previewTestData(request, problem_id, case_id, mode): # mode = 0: view input mode = 1: view output logger.info(str(request).replace("\n","\t")) try: u = User.getSessionUser(request.session) if not u: raise Err(request, 'not login') if not problem_id: raise Err(request, 'problem illegal') try: p = Problem.getById(int(problem_id)) except: raise Err(request, 'problem illegal') if not p.canManageProblem(u): raise Err(request, 'no priv') case_id = int(case_id) if case_id >= p.data_count: # [0, data_count) raise Err(request, 'testdata illegal') mode = int(mode) if mode != 0 and mode != 1: raise Err(request, 'testdata mode illegal') data_preview = p.generateTestDataPreview(case_id, mode) return render(request, 'newtpl/problem/previewTestData.html', {'data_preview': data_preview}) except Exception as e: logger.error(str(e).replace('\n','\t')) return render(request, Err.ERROR_PAGE)
def viewAllClarifications(request, cid): logger.info(str(request).replace("\n","\t")) try: u = User.getSessionUser(request.session) if not u: raise Exception(Const.NOT_LOGGED_IN) c = Contest.getById(cid) if not c: raise Exception(Const.CONTEST_NOT_EXIST) cs = Clarification.getByContestId(cid) try: c.canEnterContest(u) can_add_clar = True except: can_add_clar = False try: c.canBeManaged(u) can_update_clar = True except: can_update_clar = False return render(request, 'newtpl/contest/viewAllClars.html', {'clars': cs, 'contest': c, 'can_add_clar': can_add_clar, 'can_update_clar': can_update_clar}) except Exception as e: logger.error(unicode(e).replace('\n', '\t')) return render(request, Err.ERROR_PAGE, {'errmsg': unicode(e)})
def rejudgeSubmission( request, sid): logger.info(str(request).replace("\n\r","\t")) """ rejudge the very submission with the specific sid """ try: sid = int( sid) u = User.getSessionUser( request.session) if not u: raise Err( request, err='not login') try: s = Submission.getById( sid) except: raise Err( request, err='no submission', log_format=( '{0}'.format( sid), ''), user_format=( u'{0}'.format( sid), u'不要搞笑!!'), ) if not s.problem_index.contest.course_class.canBeManaged( u): raise Err( request, err = 'no priv') Submission.rejudgeSubmission( s) return redirect( 'Submission:contest_status', contest_id=s.problem_index.contest.cid) except Exception as e: logger.error(str(e).replace("\n\r","\t")) return render( request, Const.NEW_ERROR_PAGE, { 'errmsg': unicode(e), }, )
def generalSubmissionList(request, page_id='1'): """ @view: list general submission """ try: page_id = int(page_id) u = User.getSessionUser(request.session) if not u: raise Err( request, err='not login') # fake if u.priv == 'university': has_priv = True else: has_priv = False user = u if not has_priv else None lang_list = [('gcc','GNU C'), ('g++','GNU C++'), ('java','java')] form = generalListForm( lang_list, request.GET) if form.is_valid(): if form.cleaned_data['problem_id']: try: p = Problem.getById( form.cleaned_data['problem_id']) except: raise Err( request, err='request err', log_format=( 'form invalid', 'problem_id error'), user_format=( u'输入的内容不合法', u'没有这道题!') ) else: p = None else: raise Err( request, err='example err', log_format=( 'form invalid', ''), user_format=( u'输入的内容不合法', '') ) g_subs = GeneralSubmission.generalSubmissionList( u=user, p=p, uname=form.cleaned_data['username'], language=form.cleaned_data['language'], status_selected=form.cleaned_data['status'], university=u.university) if 'rejudge' in request.GET: if has_priv: map( lambda x: GeneralSubmission.rejudgeGeneralSubmission( x), g_subs) else: raise Err( request, err = 'no priv') paginator = Paginator( g_subs, Const.STATUS_PER_PAGE) page_id = min(max(int(page_id), 1), paginator.num_pages) g_s = paginator.page(page_id) for g_s_index in g_s: g_s_index.status_color = Const.STATUS_COLOR[g_s_index.status] if g_s_index.status in Const.STATUS_COLOR else '' g_s_index.status_cn = Const.STATUS_CN[ g_s_index.status] return render(request, 'newtpl/submission/general/status.html', {'general_list': g_s, 'form':form, 'tpl':{'can_manage': True if has_priv else False}}) except Exception as e: return render(request, Err.ERROR_PAGE, { 'errmsg': unicode(e) } )
def addContest(request, ccId): try: u = User.getSessionUser(request.session) if not u: raise Err(request, 'not login') try: cc = CourseClass.getById(ccId) except: raise Err(request, 'no resource') try: Contest.canAddContest(cc, u) except: raise Err(request, 'no priv') recentProblem = Problem.problemListByAuthor(u) if request.method == 'POST': form = contestForm(request.POST) pIdList = request.POST.getlist('problem_id') #pIdList = Problem.problemList(u) pTitleList = request.POST.getlist('problem_title_custom') pCnt = len(pIdList) if form.is_valid(): for i in xrange(pCnt): p = Problem.getById(pIdList[i]) if not p.canViewProblem(u): raise Err(request, 'no problem priv') pInfos = [(pIdList[i], pTitleList[i], chr(65+i)) for i in xrange(pCnt)] cTitle = form.cleaned_data['title'] cDesc = form.cleaned_data['desc'] cStartDate = form.cleaned_data['start_date'] cStartTime = form.cleaned_data['start_time'] cLength = form.cleaned_data['length'] cBoardStop = form.cleaned_data['board_stop'] cType = form.cleaned_data['contest_type'] cBoardType = form.cleaned_data['board_type'] permitLang = reduce(add, [Const.LANG_MASK[lang] for lang in form.cleaned_data['lang_limit']]) c = Contest.addContest(u, cc, cTitle, pInfos, datetime.combine(cStartDate, cStartTime), cDesc, cLength, cBoardStop, cType, cBoardType, permitLang) return redirect('Contest:show_contest', c.cid) else: problemList = [{'pid': pIdList[x], 'title': pTitleList[x], 'origTitle':Problem.getById(pIdList[x]).prob_title} for x in xrange(pCnt)] return render(request, 'newtpl/contest/addContest.html', {'cc':cc, 'form': form, 'recent_problem': recentProblem, 'problem_list': problemList, 'tpl':{'has_priv': True, 'sp': True, }}) else: form = contestForm() return render(request, 'newtpl/contest/addContest.html', {'cc':cc, 'form': form, 'recent_problem': recentProblem, 'tpl':{'has_priv': True, 'sp': True, }}) except Exception as e: messages.info(request, unicode(e)) return render(request, Err.ERROR_PAGE)
def chooseCourseClass(request): try: u = User.getSessionUser(request.session) if not u: raise Err(request, 'not login') if u.isStudent(): raise Err(request, 'no priv') cc_list = CourseClass.getAllManagedClasses(u) return render(request,'newtpl/contest/chooseCourseClass.html',{'list': cc_list, 'tpl':{'sp':True}}) except Exception as e: return render(request, Err.ERROR_PAGE)
def showResult(request, cid, page='1'): try: u = User.getSessionUser(request.session) if not u: raise Err(request, err='not login') c = Contest.getById(int(cid)) try: c.canBeManaged(u) except: raise Err(request, err='no priv') if ('threshold' in request.GET) and request.GET['threshold']: threshold = float(request.GET['threshold']) else: threshold = Const.CHEAT_DEFAULT_THRESHOLD cheatList = Cheat.getCheatList(contest=c, threshold=threshold) paginator = Paginator(cheatList, Const.CHEAT_PER_PAGE) page = min(max(int(page), 1), paginator.num_pages) cl = paginator.page(page) ipa = [] ipb = [] for idx, element in enumerate(cl): info_a = eval(element.sub1.other_info) info_b = eval(element.sub2.other_info) #cl[idx] = {'c': element, 'ip_a': info_a['submit_ip'], 'ip_b': info_b['submit_ip']} ipa.append(info_a['submit_ip']) ipb.append(info_b['submit_ip']) return render(request, 'newtpl/cheat/showResult.html', {'tpl':{'sp':True,}, 'contest':c, 'cheat_list':cl, 'ipa':ipa,'ipb':ipb }) except Exception as e: return render(request, Err.ERROR_PAGE) # def codeDiff(request, ctid): # try: # u = User.getSessionUser(request.session) # if not u: # raise Err(request, err='not login') # ct = Cheat.objects.select_related('sub1__user', 'sub2__user').get(ctid=ctid) # # try: # ct.contest.canBeManaged(u) # except: # raise Err(request, err='no priv') # # return render(request, 'newtpl/cheat/codeDiff.html', {'tpl':{'sp':True,}, 'sub1':ct.sub1, 'sub2':ct.sub2}) # # # except Exception as e: # return render(request, Err.ERROR_PAGE) """
def showContestNotice(request, cId, cnId): try: u = User.getSessionUser(request.session) if not u: raise Exception(Const.NOT_LOGGED_IN) c = Contest.getById(cId) cn = ContestNotice.getById(cnId) c.canEnterContest(u) return render(request, 'newtpl/contest/showContestNotice.html', {'cid': cId, 'contest_notice': cn, 'tpl': {'has_priv': Contest.hasPriv(c.course_class, u), 'sp': True, 'nav_act':'contest',}}) except Exception as e: return render(request, Const.ERROR_PAGE, {'errmsg': unicode(e), })
def chooseCourse(request): logger.info(str(request).replace("\n","\t")) try: u = User.getSessionUser(request.session) if not u: raise Err(request, 'not login') if u.isStudent(): raise Err(request, 'no priv') cs_list = Course.getAllManagedCourses(u) return render(request,'newtpl/problem/chooseCourse.html',{'list': cs_list, 'tpl':{'sp':True}}) except Exception as e: logger.error(str(e).replace("\n","\t")) return render(request, Err.ERROR_PAGE)
def showProblem(request,p_id): # modified logger.info(str(request).replace("\n","\t")) try: u = User.getSessionUser(request.session) if not u: raise Err(request, 'not login') p_id = int(p_id) p = Problem.getById(p_id) if not p.canViewProblem(u): raise Err(request, 'no priv') p.desc=json.loads(p.prob_desc) return render(request, "newtpl/problem/showProblem.html", { 'p':p, 'tpl':{'sp':True}}) except Exception as e: logger.error(str(e).replace("\n","\t")) return render(request, Err.ERROR_PAGE)
def listProblem(request, pageId="1"): # modified logger.info(str(request).replace("\n","\t")) try: pageId = int(pageId) u = User.getSessionUser(request.session) if not u: raise Err(request, 'not login') tres = Problem.problemList(u) if (pageId-1)*Const.PROBLEM_PER_PAGE>=len(tres): raise Err(request, 'unknown err') res = tres[(pageId-1)*Const.PROBLEM_PER_PAGE:Const.PROBLEM_PER_PAGE] return render(request,"newtpl/problem/problemList.html",{'res': res,'tpl':{'sp':True}}) except Exception as e: logger.error(str(e).replace("\n","\t")) return render(request, Err.ERROR_PAGE)
def listContestByUser(request, pageId='1'): """ view used to list all contest a user can participate """ logger.info(str(request).replace("\n","\t")) tpl = {'nav_act':'contest'} try: u = User.getSessionUser(request.session) if not u: messages.info(request, u'请先登录') contestList = None else: now = datetime.now() if u.priv == 'student': contestList = Contest.getByStudent(u) else: contestList = Contest.getByAdmin(u) for c in contestList: c.course_class_name = unicode(c.course_class.getFullName()) c.title = unicode(c.contest_title) if c.start_time+timedelta(minutes=c.length)<now: c.status = 'ended' elif c.start_time > now: c.status = 'scheduled' else: c.status = 'running' paginator = Paginator(contestList, Const.CONTEST_PER_PAGE) pageId = min(max(int(pageId), 1), paginator.num_pages) if contestList and contestList.count>0: return render(request, 'newtpl/contest/contestListByUser.html', { 'contest_list': paginator.page(pageId), 'tpl':tpl}) else: return render(request, 'newtpl/contest/contestListByUser.html', { 'tpl':tpl, 'err_msg_list': [ u'您暂时没有可以参加的测验。', u'不如走出教室,呼吸一下新鲜空气,给家人打个电话,陪陪妹子?' ]}) except Exception as e: return render(request, Const.ERROR_PAGE, {'errmsg': unicode(e), })
def addRecord2(request, cid): try: u = User.getSessionUser(request.session) if not u: raise Err(request, err='not login') c = Contest.getById(cid) try: c.canBeManaged(u) except: raise Err(request, err='no priv') cp = c.getContestProblem() Cheat.addRecord(cp_set=cp) Cheat.antiCheat() return redirect('Cheat:show_cheat_result', cid=c.cid) except Exception as e: return render(request, Err.ERROR_PAGE)
def deleteProblem(request, problem_id): logger.info(str(request).replace("\n","\t")) try: user = User.getSessionUser(request.session) if not user: raise Err(request, 'not login') try: prob = Problem.getById(int(problem_id)) except: raise Err(request, 'problem illegal') if not prob.author.university.isAdmin(user): raise Err(request, 'no priv') prob.deleteProblem() messages.add_message(request, messages.SUCCESS, u'删除题目%d成功' % int(problem_id)) return redirect('Problem:manage') except Exception as e: return render(request, Err.ERROR_PAGE, {'errmsg': unicode(e)})
def showContestProblem(request,c_id,idx): # modified logger.info(str(request).replace("\n","\t")) try: u = User.getSessionUser(request.session) if not u: raise Err(request, 'not login') c_id = int(c_id) c = Contest.getById(c_id) cn = c.getContestNotice() cp = ContestProblem.getBy(c=c, idx=idx) try: c.canEnterContest(u) except: raise Err(request, 'no priv') can_manage = True try: c.canBeManaged(u) except: can_manage = False if (not c.canEnterWithTime(u)) and (not can_manage): raise Err(request, 'contest not started') c.course_class_name = unicode(c.course_class.getFullName()) p = cp.problem p.idx = cp.problem_index p.title = unicode(cp.problem_title) p.desc=json.loads(p.prob_desc) cp_list = c.getContestProblem() for cp, cp_res, cp_user_res in zip(cp_list, getContestResult(c=c), getContestUserResult(c=c, u=u)): cp.ac = cp_res['ac_cnt'] cp.sub = cp_res['sub_cnt'] cp.user_res = cp_user_res return render(request, "newtpl/problem/showContestProblem.html", {'c':c, 'cp_list':cp_list,'contest_notice_list':cn, 'p':p, 'status_query':queryString(problem_index=p.idx), 'tpl':{'sp':True, 'can_manage':can_manage}}) except Exception as e: logger.error(str(e).replace("\n","\t")) return render(request, Err.ERROR_PAGE)
def showContest(request, cId): try: u = User.getSessionUser(request.session) if not u: raise Err(request, 'not login') c = Contest.getById(cId) cn = c.getContestNotice() try: c.canEnterContest(u) except: raise Err(request, 'no priv') c.course_class_name = unicode(c.course_class.getFullName()) c.description = unicode(c.contest_description) c.title = unicode(c.contest_title) now = datetime.now() c.time_passed = min(max(int((now-c.start_time).total_seconds())/60, 0), c.length) c.time_passed_percent = 100*c.time_passed/c.length c.time_left = c.length-c.time_passed if c.start_time+timedelta(minutes=c.length)<now: c.status = 'ended' elif c.start_time > now: c.status = 'scheduled' else: c.status = 'running' priv = Contest.hasPriv(c.course_class, u) problemList = c.getContestProblem() for cp, cp_res, cp_user_res in zip(problemList, getContestResult(c=c), getContestUserResult(c=c, u=u)): cp.index = cp.problem_index cp.title = unicode(cp.problem_title) cp.tlim = cp.problem.prob_time cp.mlim = cp.problem.prob_memory cp.ac = cp_res['ac_cnt'] cp.sub = cp_res['sub_cnt'] cp.ratio = cp_res['ac_ratio'] cp.user_res = cp_user_res return render(request, 'newtpl/contest/showContest.html', {'contest': c, 'problem_list': problemList, 'contest_notice_list':cn,'ccid': c.course_class.id, 'tpl':{'has_priv': priv, 'nav_act':'contest',}}) except Exception as e: return render(request, Err.ERROR_PAGE, {'errmsg': unicode(e), })
def showContestProblemStatistics( request, p_index=None, cid=None): logger.info(str(request).replace("\n","\t")) """ view used to show statistics of a problem in a contest """ try: u = User.getSessionUser(request.session) if not u: raise Err( request, err='not login') cid = int(cid) c = Contest.getById(cid) p_index = p_index if p_index else '' try: contest_problem = ContestProblem.getBy( c, p_index) except: raise Err( request, err='no contestproblem', log_format=( '{0}'.format(p_index), ''), user_format=( u'{0}'.format( p_index), u'搞错了什么吧!'), ) if not contest_problem.contest.course_class.canBeManaged( u): raise Err( request, err = 'no priv') all_submissions = Submission.submissionList( cp=contest_problem ) submissions = all_submissions.filter( status='Accepted').order_by('run_time')[:20] status_list = [] for i in Const.STATUS_CN.iterkeys(): status_list.append( { 'name': Const.STATUS_CN[i], 'number': all_submissions.filter( status=i).count()} ) for sub_s in submissions: sub_s.status_color = Const.STATUS_COLOR[sub_s.status] if sub_s.status in Const.STATUS_COLOR else '' sub_s.status_cn = Const.STATUS_CN[ sub_s.status] return render( request, 'newtpl/statistic/contest_problem.html', { 'submissions': submissions, 'contest_problem': contest_problem, 'status_list': status_list, 'tpl': { 'sp': True } }) except Exception as e: logger.error(str(e).replace("\n","\t")) return render(request, Err.ERROR_PAGE, { 'errmsg': unicode(e) } )
def releaseBoardTime(request, cId): try: u = User.getSessionUser(request.session) if not u: raise Exception(Const.NOT_LOGGED_IN) try: c = Contest.getById(cId) except: raise Err(request, 'no resource') try: c.canBeManaged(u) except: raise Err(request, err='no priv') c = Contest.getById(cId) c.board_stop = c.length c.save() return redirect('Contest:show_contest', cId) except Exception as e: return render(request, Const.ERROR_PAGE, {'errmsg': unicode(e), })
def showBoardByDynamicScore(request, cId): logger.info(str(request).replace("\n","\t")) try: u = User.getSessionUser(request.session) if not u: raise Err(request, 'not login') try: c = Contest.getById(cId) except: raise Err(request, 'no resource') try: c.canEnterContest(u) except: raise Err(request, 'no priv') return render(request,"newtpl/statistic/board_dynamic_score.html", {'contest': c, 'tpl': {'has_priv': Contest.hasPriv(c.course_class, u)}}) except Exception as e: logger.error(str(e).replace("\n","\t")) return render(request, Err.ERROR_PAGE)
def _showContest(request, cId): cId = int(cId) try: u = User.getSessionUser(request.session) if not u: raise Exception(u'请先登录') c = Contest.getById(cId) c.canEnterContest(u) #cc = c.course_class c.course_class_name = unicode(c.course_class.getFullName()) c.description = unicode(c.contest_description) c.title = unicode(c.contest_title) now = datetime.now() if c.start_time+timedelta(minutes=c.length) < now: c.status = 'ended' elif c.start_time > now: c.status = 'scheduled' else: c.status = 'running' c.time_passed = min(max(int((now-c.start_time).total_seconds())/60, 0), c.length) c.time_passed_percent = 100*c.time_passed/c.length c.time_left = c.length-c.time_passed cn = c.getContestNotice() if c.status != 'scheduled' or c.canUpdateContest(u): problemList = c.getContestProblem() for cp in problemList: cp.index = cp.problem_index cp.title = unicode(cp.problem_title) cp.tlim = cp.problem.prob_time cp.mlim = cp.problem.prob_memory return render(request, 'newtpl/contest/showContest.html', {'contest': c, 'problem_list': problemList, 'contest_notice_list': cn, 'ccid': c.course_class.id, 'tpl':{'has_priv': Contest.hasPriv(c.course_class, u),}}) except Exception as e: return render(request, Const.ERROR_PAGE, {'errmsg':unicode(e),})
def showCourseClass(request) : user = User.getSessionUser(request.session) courseClass = list() ''' if user == False : errmsg = u'请先登录' return render(request, 'error.html', {'errmsg' : e, 'user' : user}) if user.isCourseClassAdmin == True : courseClass = CourseClass.getByAdmin(user) admin = user elif user.isStudent == True : courseClass = CourseClass.getByStudent(user) student = user else : errmsg = u'您既不是课程管理员也不是学生,无权限访问该页面' return render(request, 'error.html', {'errmsg' : e, 'user' : user}) ''' return render(request, 'lyy/showCourseClass.html', {'courseClass' : courseClass, 'user' : user})
def addClarification(request, cid): logger.info(str(request).replace("\n","\t")) try: u = User.getSessionUser(request.session) if not u: raise Exception(Const.NOT_LOGGED_IN) c = Contest.getById(cid) if not c: raise Exception(Const.CONTEST_NOT_EXIST) has_priv = False try: c.canBeManaged(u) has_priv = True except: pass try: c.canEnterContest(u) has_priv = True except: pass if not has_priv: raise Exception('No Privilege!') if request.method != 'POST': return render(request, 'newtpl/contest/addClar.html', {'contest': c}) form = ClarificationForm(request.POST) try: if form.is_valid(): question = form.cleaned_data['question'] Clarification.addClarification(question, u, c) return redirect('Contest:view_all_clars', cid) else: raise except: raise Exception('Invalid Question') except Exception as e: logger.error(unicode(e).replace('\n', '\t')) return render(request, Err.ERROR_PAGE, {'errmsg': unicode(e)})
def deleteClarification(request, clar_id): logger.info(str(request).replace("\n","\t")) try: u = User.getSessionUser(request.session) if not u: raise Exception(Const.NOT_LOGGED_IN) clar = Clarification.getById(clar_id) if not clar: raise Exception('No such Clarification!') c = clar.contest if not c: raise Exception(Const.CONTEST_NOT_EXIST) try: c.canBeManaged(u) except: raise Exception('No Privilege!') clar.deleteClarification() return redirect('Contest:view_all_clars', c.pk) except Exception as e: logger.error(unicode(e).replace('\n', '\t')) return render(request, Err.ERROR_PAGE, {'errmsg': unicode(e)})
def listContestByAuthor(request, pageId='1'): """ view used to list all contest created by the specific user """ try: u = User.getSessionUser(request.session) if not u: messages.info(request, u'请先登录') return render(request, 'newtpl/contest/contestListByAuthor.html') contestList = Contest.getByAuthor(u) now = datetime.now() for c in contestList: c.course_class_name = unicode(c.course_class.getFullName()) c.title = unicode(c.contest_title) if c.start_time + timedelta(minutes=c.length) < now: c.status = 'ended' elif c.start_time > now: c.status = 'scheduled' else: c.status = 'running' paginator = Paginator(contestList, Const.CONTEST_PER_PAGE) pageId = min(max(int(pageId), 1), paginator.num_pages) return render( request, 'newtpl/contest/contestListByAuthor.html', { 'contest_list': paginator.page(pageId), 'tpl': { 'has_priv': True, 'nav_act': 'contest', } }) except Exception as e: return render(request, Const.ERROR_PAGE, { 'errmsg': unicode(e), })
def rejudgeGeneralSubmission(request, gsid): """ rejudge the very general submission with the specific id """ try: gsid = int(gsid) u = User.getSessionUser(request.session) if not u: raise Err(request, err='not login') try: g_s = GeneralSubmission.getById(gsid) except: raise Err( request, err='no generalsubmission', log_format=('{0}'.format(gsid), ''), user_format=(u'{0}'.format(gsid), u'别扯了!!'), ) # fake if u.priv == 'student': raise Err(request, err='no priv') GeneralSubmission.rejudgeGeneralSubmission(g_s) return redirect('Submission:status') except Exception as e: return render( request, Const.NEW_ERROR_PAGE, { 'errmsg': unicode(e), }, )
def showContest(request, cId): try: u = User.getSessionUser(request.session) if not u: raise Err(request, 'not login') c = Contest.getById(cId) try: c.canEnterContest(u) except: raise Err(request, 'no priv') """ cache_key = 'Contest' + str(cId) cache_result = cache.get(cache_key) if cache_result: return cache_result """ cn = c.getContestNotice() c.course_class_name = unicode(c.course_class.getFullName()) c.description = unicode(c.contest_description) c.title = unicode(c.contest_title) now = datetime.now() c.time_passed = min( max(int((now - c.start_time).total_seconds()) / 60, 0), c.length) c.time_passed_percent = 100 * c.time_passed / c.length c.time_left = c.length - c.time_passed if c.start_time + timedelta(minutes=c.length) < now: c.status = 'ended' elif c.start_time > now: c.status = 'scheduled' else: c.status = 'running' priv = Contest.hasPriv(c.course_class, u) cache_key = 'Contestdict' + str(cId) res = cache.get(cache_key) if res: res['contest'] = c res['tpl'] = { 'has_priv': priv, 'nav_act': 'contest', } return render(request, 'newtpl/contest/showContest.html', res) problemList = c.getContestProblem() for cp, cp_res, cp_user_res in zip(problemList, getContestResult(c=c), getContestUserResult(c=c, u=u)): cp.index = cp.problem_index cp.title = unicode(cp.problem_title) cp.tlim = cp.problem.prob_time cp.mlim = cp.problem.prob_memory cp.ac = cp_res['ac_cnt'] cp.sub = cp_res['sub_cnt'] cp.ratio = cp_res['ac_ratio'] #cp.user_res = cp_user_res res = { 'contest': c, 'problem_list': problemList, 'contest_notice_list': cn, 'ccid': c.course_class.id, 'tpl': { 'has_priv': priv, 'nav_act': 'contest', } } cache.set(cache_key, res, Const.CACHE_TIME_FIRST) return render(request, 'newtpl/contest/showContest.html', res) #res = render(request, 'newtpl/contest/showContest.html', {'contest': c, 'problem_list': problemList, 'contest_notice_list':cn,'ccid': c.course_class.id, 'tpl':{'has_priv': priv, 'nav_act':'contest',}}) #cache.set(cache_key, res, 5 ) #return res except Exception as e: return render(request, Err.ERROR_PAGE, { 'errmsg': unicode(e), })
def user(request): u = User.getSessionUser(request.session) if u!=None and u!=False: return {'user':u} else: return {'user':None}
def addSubmission(request, contest_id=None, problem_index=None): logger.info(str(request).replace("\n\r", "\t")) """ view used to add submission """ try: contest_id = int(contest_id) u = User.getSessionUser(request.session) if not u: raise Err(request, err='not login') if not contest_id: raise Err( request, err='request err', log_format=('contest id', 'UNDEFINED'), user_format=(u'考试编号', u'你吃了么!!!'), ) elif not problem_index: raise Err( request, err='request err', log_format=('problem index', 'UNDEFINED'), user_format=(u'题目序号', u'哪里去了!!'), ) else: try: c = Contest.getById(contest_id) except: raise Err( request, err='no contest', log_format=('{0}'.format(cid), ''), user_format=(u'{0}'.format(cid), u'别做坏事!'), ) try: p_index = ContestProblem.getBy(c=c, idx=problem_index) except: raise Err( request, err='no contest problem', log_format=('{0}'.format(problem_index), ''), user_format=(u'{0}'.format(problem_index), u'别乱写好么!!'), ) p = p_index.problem if not Submission.canSubmitCode(u, p_index): raise Err( request, err='submit err', log_format=( 'no priv to submit', 'contest ended or no priv to attend the contest'), user_format=(u'您没有提交该题的权限', u'考试已结束或者您没有参加本场考试的权限')) lang_list = [] if c.lang_limit & 1 == 1: lang_list.append(('gcc', 'GNU C')) if (c.lang_limit >> 1) & 1 == 1: lang_list.append(('g++', 'GNU C++')) if (c.lang_limit >> 2) & 1 == 1: lang_list.append(('java', 'JAVA')) if request.method == 'POST': form = addSubmissionForm(lang_list, request.POST) if form.is_valid(): sub_name = str(datetime.now()) time_str = sub_name.split('.') time_str.pop() for i in ['-', ':', '.', ' ']: sub_name = sub_name.replace(i, '_') import os code_file_path = os.path.join( Const.SUBMISSION_TMP_PATH, "{0:010d}_{1}".format(u.uid, sub_name)) code_length = 0 # head_details: details of the submission added at the head of the code file head_details = '' head_details += '/*\n' head_details += 'USER_ID: ' + str(u) + '\n' head_details += 'PROBLEM: ' + str(p.pid) + '\n' head_details += 'SUBMISSION_TIME: ' + time_str[0] + '\n' head_details += '*/\n' if 'code_file' in request.FILES: default_storage.save(code_file_path, request.FILES['code_file']) else: if form.cleaned_data['code']: default_storage.save( code_file_path, ContentFile(head_details + form.cleaned_data['code'])) else: raise Err( request, err='request err', log_format=('code', 'no input'), user_format=(u'代码呢!', u'不写代码交什么交!!'), ) code_length = default_storage.size(code_file_path) sub_lang = form.cleaned_data['language'] if sub_lang not in map(lambda x: x[0], lang_list): raise Err( request, err='illegal language', log_format=('{0}'.format(sub_lang), 'blabla'), user_format=(u'{0}'.format(sub_lang), u'别瞎搞成不!!'), ) x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') additional = {'submit_ip': ip} Submission.addSubmission(u, p_index, code_file_path, sub_lang, code_length, additional, c.board_type == 2) return redirect('Submission:contest_status', contest_id=contest_id) # could it be okay? else: raise Exception(u'form invalid') # the usage of url.name in urls.py # not POST method else: form = addSubmissionForm(lang_list) return render( request, 'newtpl/submission/submit.html', { 'form': form, 'tpl': { 'sp': True }, 'contest': c, 'cp': p_index }, ) # 'test_info': form.cleaned_data['language']}) except Exception as e: logger.error(str(e).replace("\n\r", "\t")) return render( request, Err.ERROR_PAGE, { 'errmsg': unicode(e), }, )
def addProblem(request, course_id): # modified logger.info(str(request).replace("\n", "\t")) try: u = User.getSessionUser(request.session) if not u: raise Err(request, 'not login') if course_id == None: return redirect('/problem/addProblem/') try: course_id = int(course_id) cs = Course.getById(course_id) except: raise Exception(u'课程号非法') if not Problem.canAddCourseProblem(cs, u): raise Err(request, 'no priv') if request.method == 'POST': form = addProblemForm(request.POST) if form.is_valid(): prb = Problem.addProblem(u.uid, form.cleaned_data['prob_priv'], form.cleaned_data['prob_title'], form.cleaned_data['prob_time'], form.cleaned_data['prob_memory'], form.cleaned_data['prob_codelength'], form.cleaned_data['prob_desc'], form.cleaned_data['is_spj'], 0, course_id, "") data_count = 0 case_info = "" if form.cleaned_data['change_data'] == "1": dataInList = request.FILES.getlist('data_in') dataOutList = request.FILES.getlist('data_out') dataScrList = request.POST.getlist('data_scr') if len(dataInList) != len(dataOutList) or len( dataInList) != len(dataScrList): raise Exception(u'上传文件有误') for idx, nowData in enumerate(dataInList): path = Const.PROBLEM_DATA_PATH + str( prb.pid) + "/" + str(idx) + ".in" if default_storage.exists(path): default_storage.delete(path) default_storage.save(path, nowData) for idx, nowData in enumerate(dataOutList): path = Const.PROBLEM_DATA_PATH + str( prb.pid) + "/" + str(idx) + ".out" if default_storage.exists(path): default_storage.delete(path) default_storage.save(path, nowData) dict = {} for idx, nowScr in enumerate(dataScrList): dict[str(idx)] = nowScr case_info = json.dumps(dict) data_count = len(dataInList) dict = {} dict['desc'] = form.cleaned_data['prob_desc'] dict['input_desc'] = form.cleaned_data['prob_input_desc'] dict['output_desc'] = form.cleaned_data['prob_output_desc'] dict['input_sample'] = form.cleaned_data['prob_input_sample'] dict['output_sample'] = form.cleaned_data['prob_output_sample'] prob_desc = json.dumps(dict) prb.updateProblem(u.uid, form.cleaned_data['prob_priv'], form.cleaned_data['prob_title'], form.cleaned_data['prob_time'], form.cleaned_data['prob_memory'], form.cleaned_data['prob_codelength'], prob_desc, form.cleaned_data['is_spj'], data_count, course_id, case_info) return redirect("/problem/p/" + str(prb.pid) + "/") else: raise Err(request, 'problem info illegal') else: form = addProblemForm() return render(request, 'newtpl/problem/modifyProblem.html', { 'form': form, 'course': cs, 'tpl': { 'sp': True } }) except Exception as e: logger.error(str(e).replace("\n", "\t")) return render(request, Err.ERROR_PAGE)
def addContest(request, ccId): try: u = User.getSessionUser(request.session) if not u: raise Err(request, 'not login') try: cc = CourseClass.getById(ccId) except: raise Err(request, 'no resource') try: Contest.canAddContest(cc, u) except: raise Err(request, 'no priv') recentProblem = Problem.problemListByAuthor(u) if request.method == 'POST': form = contestForm(request.POST) pIdList = request.POST.getlist('problem_id') pTitleList = request.POST.getlist('problem_title_custom') pCnt = len(pIdList) if form.is_valid(): for i in xrange(pCnt): p = Problem.getById(pIdList[i]) if not p.canManageProblem(u): raise Err(request, 'no problem priv') pInfos = [(pIdList[i], pTitleList[i], chr(65 + i)) for i in xrange(pCnt)] cTitle = form.cleaned_data['title'] cDesc = form.cleaned_data['desc'] cStartDate = form.cleaned_data['start_date'] cStartTime = form.cleaned_data['start_time'] cLength = form.cleaned_data['length'] cBoardStop = form.cleaned_data['board_stop'] cType = form.cleaned_data['contest_type'] cBoardType = form.cleaned_data['board_type'] permitLang = reduce(add, [ Const.LANG_MASK[lang] for lang in form.cleaned_data['lang_limit'] ]) c = Contest.addContest( u, cc, cTitle, pInfos, datetime.combine(cStartDate, cStartTime), cDesc, cLength, cBoardStop, cType, cBoardType, permitLang) return redirect('Contest:show_contest', c.cid) else: problemList = [{ 'pid': pIdList[x], 'title': pTitleList[x], 'origTitle': Problem.getById(pIdList[x]).prob_title } for x in xrange(pCnt)] return render( request, 'newtpl/contest/addContest.html', { 'cc': cc, 'form': form, 'recent_problem': recentProblem, 'problem_list': problemList, 'tpl': { 'has_priv': True, 'sp': True, } }) else: form = contestForm() return render( request, 'newtpl/contest/addContest.html', { 'cc': cc, 'form': form, 'recent_problem': recentProblem, 'tpl': { 'has_priv': True, 'sp': True, } }) except Exception as e: return render(request, Err.ERROR_PAGE)
def showCodeDiff(request, ct_id): """ show codes of the two diffed submission """ try: u = User.getSessionUser( request.session) if not u: raise Err( request, err='not login') ct_id = int( ct_id) ct = Cheat.objects.select_related('sub1__user', 'sub2__user').get(ctid=ct_id) # try: # ct.contest.canBeManaged(u) # except: # raise Err(request, err='no priv') s_a = ct.sub1 s_b = ct.sub2 #sid_a = int( sid_a) #sid_b = int( sid_b) #try: # s_a = Submission.getById( sid_a) #except: # raise Err( request, err='no submission', # log_format=( '{0}'.format( sid_a), ''), # user_format=( u'{0}'.format( sid_a), u'不要搞笑!!'), # ) #try: # s_b = Submission.getById( sid_b) #except: # raise Err( request, err='no submission', # log_format=( '{0}'.format( sid_b), ''), # user_format=( u'{0}'.format( sid_b), u'不要搞笑!!'), # ) if not Submission.canViewCode( s_a, u): raise Err( request, err = 'no priv') if not Submission.canViewCode( s_b, u): raise Err( request, err = 'no priv') info_a = eval( s_a.other_info) info_b = eval( s_b.other_info) ip_a = info_a['submit_ip'] ip_b = info_b['submit_ip'] brush_a = Const.BRUSH[s_a.code_language] brush_b = Const.BRUSH[s_b.code_language] # brush_a = s_a.code_language # brush_b = s_b.code_language # info['status_cn'] = Const.STATUS_CN[info['status']] #if 'case_result' in info: # for seq in info['case_result']: # seq['res_cn'] = JUDGE_RES_CN[seq['res']] return render( request, 'newtpl/cheat/code_diff.html', { 'ct_obj': ct, 'sub_a': s_a, 'sub_b': s_b, 'code_a': default_storage.open(s_a.code_file).read().decode('utf-8', 'ignore'), 'code_b': default_storage.open(s_b.code_file).read().decode('utf-8', 'ignore'), 'tpl': { 'sp': True }, 'brush_a': brush_a, 'brush_b': brush_b, 'ip_a': ip_a, 'ip_b': ip_b}) except Exception as e: return render( request, Err.ERROR_PAGE, { 'errmsg': unicode(e), }, )
def board(request): cid = request.GET.get('cid', 1) contest = Contest.getById(cid) ''' if contest == False : errmsg = u'不存在考试编号为' + str(cid) + u'的考试' return render(request, 'error.html', {'errmsg' : errmsg, 'user' : User.getSessionUser(request.session)}) contestProblem = contest.getContestProblem() startTime = contest.start_time ''' submission = Submission.submissionList(cid=cid) problemIndex = list() problemIndex.append('A') # problemIndex.append('B') # ''' for i in contestProblem: problemIndex.append(i.problem_index) ''' problemIndex.sort() data = dict() cnt = 0 now = datetime.now() now = now - now for i in submission: if i.user.username not in data: data[i.user.username] = [cnt, i.user.username, 0, now ] #id, username, solved, time, A, B, etc cnt = cnt + 1 for j in problemIndex: data[i.user.username].append({'ac': 0, 'pd': 0, 'other': 0}) tmp = data[i.user.username] tp = tmp[i.problem_index.problem_index + 3] if tp['ac'] == 0: if ('Accepted', 'Accepted') in i.status: tp['ac'] = 1 tp['other'] = tp['other'] + 1 tmp[3] += datetime.timedelta( (tp['pd'] + tp['ac'] + tp['other']) * 20) + (i.submission_time - startTime) tmp[2] += 1 elif ('Pending', 'Pending') in i.status: tp['pd'] = tp['tp'] + 1 else: tp['other'] = tp['other'] + 1 out = list() for i in data: out.append(data[i]) out.append([ 0, 'zhangzhou', 12, -(datetime.now() - datetime.now()), { 'ac': 0, 'pd': 2, 'other': 0 }, { 'ac': 0, 'pd': 0, 'other': 0 } ]) # out.append([ -1, 'lyy', 12, -(datetime.now() - datetime.now()), { 'ac': 1, 'pd': 2, 'other': 3 }, { 'ac': 0, 'pd': 0, 'other': 0 } ]) # out.sort(cmp=mycmp) cnt = 1 for i in out: i[0] = cnt cnt = cnt + 1 i[3] = (datetime(2000, 1, 1, 0, 0, 0, 0) + i[3]).strftime("%H:%M:%S") return render( request, 'lyy/board.html', { 'out': out, 'problemIndex': problemIndex, 'user': User.getSessionUser(request.session) })
def showBoardByStatus(request, cId, balloon=False): df = open("/home/buptacm/log.txt", "w") print >> df, "111" logger.info(str(request).replace("\n", "\t")) try: u = User.getSessionUser(request.session) if not u: raise Err(request, 'not login') try: cId = int(cId) c = Contest.getById(cId) except: raise Err(request, 'no resource') can_manage = True try: c.canBeManaged(u) except: can_manage = False try: c.canEnterContest(u) except: raise Err(request, 'no priv') print >> df, "1" res = cache.get(cId) if res != None: info, rank, allProb = res if not can_manage and not c.contest_type == 0: rank = filter(lambda x: u.uid == x['uid'], info) if can_manage and balloon: return render( request, "newtpl/statistic/board_test.html", { 'info': info, 'board_body': render_to_response("newtpl/statistic/board_body.html", { 'rank': rank }).content, 'allProb': allProb, 'contest': c }) #return render(request,"newtpl/statistic/board2.html", {'info': info, 'rank': rank,'allProb': allProb, 'contest': c}) else: return render(request, "newtpl/statistic/board.html", { 'info': info, 'rank': rank, 'allProb': allProb, 'contest': c }) #return render(request,"newtpl/statistic/board_test.html", {'info': info, 'board_body': render_to_response("newtpl/statistic/board_body.html", {'rank': rank}).content,'allProb': allProb, 'contest': c}) print >> df, "2" board_stop_time = c.start_time + timedelta(minutes=c.board_stop) allSub = Submission.submissionList( c=c, board_stop_time=board_stop_time).order_by('sid') #allSub = Submission.submissionList(c=c) #allSub = allSub.filter(submission_time < board_stop_time).order_by('sid') #allSub = Submission.objects.filter(c=c).filter(submission_time < board_stop_time).order_by('sid') allUser = c.course_class.getAllStudents() allProb = c.getContestProblem() pInfoDict = { pinfo.problem_index: { 'idx': pinfo.problem_index, 'ac': 0, 'pen': 0, 'sub': 0 } for pinfo in allProb } info = { uinfo.uid: { 'uid': uinfo.uid, 'username': uinfo.username, 'nickname': uinfo.nickname, 'ac': 0, 'pen': 0, 'sub': 0, 'pinfo': copy.deepcopy(pInfoDict) } for uinfo in allUser } print >> df, "3" if c.board_type == 0: # acm style board for sinfo in allSub: if not sinfo.user.uid in info: continue uid = sinfo.user.uid idx = sinfo.problem_index.problem_index if info[uid]['pinfo'][idx]['ac'] > 0: continue if sinfo.status in [ 'Pending', 'Rejudging', 'Compiling', 'System Error' ]: continue td = sinfo.submission_time - c.start_time info[uid]['pinfo'][idx]['sub'] += 1 if sinfo.status == "Accepted": info[uid]['pinfo'][idx][ "ac"] = 1 - info[uid]['pinfo'][idx]["ac"] info[uid]['pinfo'][idx]["ac_time"] = int( math.ceil(td.total_seconds() / 60)) info[uid]['pinfo'][idx]["pen"] += int( math.ceil(td.total_seconds() / 60)) if (not 'fb_time' in pInfoDict[idx] ) or td < pInfoDict[idx]['fb_time']: pInfoDict[idx]['fb_time'] = td pInfoDict[idx]['fb_uid'] = uid else: info[uid]['pinfo'][idx]["ac"] -= 1 info[uid]['pinfo'][idx]["pen"] += 20 for idx, pinfo in pInfoDict.iteritems(): if 'fb_time' in pinfo: info[pinfo['fb_uid']]['pinfo'][idx]['fb'] = True info = info.values() for i in info: i['pinfo'] = i['pinfo'].values() i['pinfo'].sort(key=lambda x: x['idx']) if u.university_id != 5: i['sub'] = 1 for pinfo in i['pinfo']: if pinfo['ac'] > 0: i['ac'] += 1 i['pen'] += pinfo['pen'] i['sub'] += pinfo['sub'] else: for sinfo in allSub: if not sinfo.user.uid in info: continue uid = sinfo.user.uid idx = sinfo.problem_index.problem_index other_info = eval(sinfo.other_info) tscore = int(other_info['score']) if info[uid]['pinfo'][idx]['ac'] >= tscore: continue if sinfo.status in [ 'Pending', 'Rejudging', 'Compiling', 'System Error' ]: continue td = sinfo.submission_time - c.start_time info[uid]['pinfo'][idx]['sub'] += 1 info[uid]['pinfo'][idx]['ac'] = tscore info[uid]['pinfo'][idx]["pen"] += int( math.ceil(td.total_seconds() / 60)) - info[uid]['pinfo'][idx].get("ac_time", 0) info[uid]['pinfo'][idx]["ac_time"] = int( math.ceil(td.total_seconds() / 60)) info[uid]['pinfo'][idx]['idx'] = idx if sinfo.status == "Accepted": if (not 'fb_time' in pInfoDict[idx] ) or td < pInfoDict[idx]['fb_time']: pInfoDict[idx]['fb_time'] = td pInfoDict[idx]['fb_uid'] = uid for idx, pinfo in pInfoDict.iteritems(): if 'fb_time' in pinfo: info[pinfo['fb_uid']]['pinfo'][idx]['fb'] = True info = info.values() for i in info: if u.university_id != 5: i['sub'] = 1 i['pinfo'] = i['pinfo'].values() for pinfo in i['pinfo']: if pinfo['ac'] > 0: i['ac'] += pinfo['ac'] i['pen'] += pinfo['pen'] i['sub'] += pinfo['sub'] print >> df, "4" info.sort( key=lambda x: x['ac'] * 262144 * 2 - x['pen'] * 2 + bool(x['sub']), reverse=True) for r, i in enumerate(info, 1): i['rank'] = r rank = info cache.set(cId, (info, rank, allProb), 5) print >> df, "5" if not can_manage and not c.contest_type == 0: rank = filter(lambda x: u.uid == x['uid'], info) print >> df, "6" if can_manage and balloon: return render( request, "newtpl/statistic/board_test.html", { 'info': info, 'board_body': render_to_response("newtpl/statistic/board_body.html", { 'rank': rank }).content, 'allProb': allProb, 'contest': c }) #return render(request,"newtpl/statistic/board2.html", {'info': info, 'rank': rank,'allProb': allProb, 'contest': c}) else: print >> df, info print >> df, rank print >> df, allProb print >> df, c return render( request, "newtpl/statistic/board_test.html", { 'info': info, 'board_body': render_to_response("newtpl/statistic/board_body.html", { 'rank': rank }).content, 'allProb': allProb, 'contest': c }) #return render(request,"newtpl/statistic/board.html", {'info': info, 'rank': rank,'allProb': allProb, 'contest': c}) except Exception as e: logger.error(str(e).replace("\n", "\t")) return render(request, Err.ERROR_PAGE)
def showResult(request, cid, page='1'): try: u = User.getSessionUser(request.session) if not u: raise Err(request, err='not login') c = Contest.getById(int(cid)) try: c.canBeManaged(u) except: raise Err(request, err='no priv') if ('threshold' in request.GET) and request.GET['threshold']: threshold = float(request.GET['threshold']) else: threshold = Const.CHEAT_DEFAULT_THRESHOLD cheatList = Cheat.getCheatList(contest=c, threshold=threshold) paginator = Paginator(cheatList, Const.CHEAT_PER_PAGE) page = min(max(int(page), 1), paginator.num_pages) cl = paginator.page(page) ipa = [] ipb = [] for idx, element in enumerate(cl): info_a = eval(element.sub1.other_info) info_b = eval(element.sub2.other_info) #cl[idx] = {'c': element, 'ip_a': info_a['submit_ip'], 'ip_b': info_b['submit_ip']} ipa.append(info_a['submit_ip']) ipb.append(info_b['submit_ip']) return render( request, 'newtpl/cheat/showResult.html', { 'tpl': { 'sp': True, }, 'contest': c, 'cheat_list': cl, 'ipa': ipa, 'ipb': ipb }) except Exception as e: return render(request, Err.ERROR_PAGE) # def codeDiff(request, ctid): # try: # u = User.getSessionUser(request.session) # if not u: # raise Err(request, err='not login') # ct = Cheat.objects.select_related('sub1__user', 'sub2__user').get(ctid=ctid) # # try: # ct.contest.canBeManaged(u) # except: # raise Err(request, err='no priv') # # return render(request, 'newtpl/cheat/codeDiff.html', {'tpl':{'sp':True,}, 'sub1':ct.sub1, 'sub2':ct.sub2}) # # # except Exception as e: # return render(request, Err.ERROR_PAGE) """
def viewCodeAndInfo(request, sid): logger.info(str(request).replace("\n\r", "\t")) """ view used to see details of the very submission """ try: sid = int(sid) u = User.getSessionUser(request.session) if not u: raise Err(request, err='not login') try: s = Submission.getById(sid) except: raise Err( request, err='no submission', log_format=('{0}'.format(sid), ''), user_format=(u'{0}'.format(sid), u'不要搞笑!!'), ) if not Submission.canViewCode(s, u): raise Err(request, err='no priv') info = eval(s.other_info) if 'ce' in info: info['ce'] = info['ce'].replace('/${TOKISAKI_KURUMI}', '') info['brush'] = Const.BRUSH[s.code_language] info['lang'] = Const.LANG_REFLECT[s.code_language] info['judger'] = Const.JUDGER_NAME info['user'] = s.user.uid info['judge_time'] = str(s.submission_time) info['status_cn'] = Const.STATUS_CN[info['status']] info['status_color'] = Const.STATUS_COLOR[ info['status']] if info['status'] in Const.STATUS_COLOR else '' # info['submit_ip'] = request.META['REMOTE_ADDR'] if 'score_sum' not in info: case_dict = json.loads(s.problem_index.problem.case_info) # score_sum = 0 # for score in case_dict: # score_sum += int( score) score_sum = sum(map(int, case_dict.values())) info['score_sum'] = score_sum s.other_info = str(info) s.save() if 'case_result' in info: score_obtained = 0 for seq in info['case_result']: seq['res_cn'] = JUDGE_RES_CN[seq['res']] temp_res = 'status-' + seq['res'] seq['res_color'] = temp_res if 'score' in seq: score_obtained += int(seq['score']) info['score_obtained'] = score_obtained # seq['res_color'] = Const.STATUS_COLOR[temp_res] if temp_res in Const.STATUS_COLOR else '' return render( request, 'newtpl/submission/code_and_info.html', { 'submission': s, 'info': info, 'code_content': default_storage.open(s.code_file).read().decode( 'utf-8', 'ignore'), 'tpl': { 'sp': True }, }, ) except Exception as e: logger.error(str(e).replace("\n\r", "\t")) return render( request, Err.ERROR_PAGE, { 'errmsg': unicode(e), }, )
def submissionList(request, contest_id=None, page_id='1'): logger.info(str(request).replace("\n\r", "\t")) """ @view: list submission of some contest """ try: page_id = int(page_id) u = User.getSessionUser(request.session) if not u: raise Err(request, err='not login') cid = int(contest_id) try: c = Contest.getById(cid) except: raise Err( request, err='no contest', log_format=('{0}'.format(cid), ''), user_format=(u'{0}'.format(cid), u'别做坏事!'), ) c.course_class_name = unicode(c.course_class.getFullName()) c.description = unicode(c.contest_description) c.title = unicode(c.contest_title) now = datetime.now() if c.start_time + timedelta(minutes=c.length) < now: c.status = 'ended' elif c.start_time > now: c.status = 'scheduled' else: c.status = 'running' c.time_passed = min( max(int((now - c.start_time).total_seconds()) / 60, 0), c.length) c.time_passed_percent = 100 * c.time_passed / c.length c.time_left = c.length - c.time_passed isManager = c.course_class.canBeManaged(u) user = u if not isManager else None # privilege for showing all submissions idxList = [(cp.problem_index, cp.problem_index) for cp in c.getContestProblem()] langList = [('gcc', 'GNU C'), ('g++', 'GNU C++'), ('java', 'java')] form = submissionListForm(idxList, langList, request.GET) if form.is_valid(): if form.cleaned_data['problem_index']: try: contestProb = ContestProblem.getBy( c, form.cleaned_data['problem_index']) except: contestProb = None # raise Exception(u'contest problem not found') else: contestProb = None else: raise Err(request, err='example err', log_format=('form invalid', ''), user_format=(u'输入的内容不合法', '')) #sub_all_c = getSUB() #submissions = bigfilter( u=user, c=c, cp=contestProb, uname=form.cleaned_data['username'], lang=form.cleaned_data['language'], sta=form.cleaned_data['status']) submissions = Submission.submissionList( u=user, c=c, cp=contestProb, uname=form.cleaned_data['username'], lang=form.cleaned_data['language'], sta=form.cleaned_data['status']) submissions = Submission.submissionList( u=user, c=c, cp=contestProb, uname=form.cleaned_data['username'], lang=form.cleaned_data['language'], sta=form.cleaned_data['status']) if isManager and 'rejudge' in request.GET and c.board_type != 2: map(lambda x: Submission.rejudgeSubmission(x), submissions) paginator = Paginator(submissions, Const.STATUS_PER_PAGE) page_id = min(max(int(page_id), 1), paginator.num_pages) s = paginator.page(page_id) for sub_s in s: sub_s.status_color = Const.STATUS_COLOR[ sub_s.status] if sub_s.status in Const.STATUS_COLOR else '' sub_s.status_cn = Const.STATUS_CN[sub_s.status] return render( request, 'newtpl/submission/status.html', { 'sList': s, 'form': form, 'c': c, 'tpl': { 'can_manage': True if isManager else False } }) #return render(request, 'newtpl/submission/status.html', {'sList':s, 'form':form, 'c':c}) except Exception as e: logger.error(str(e).replace("\n\r", "\t")) return render(request, Err.ERROR_PAGE, {'errmsg': unicode(e)})
def OLDaddSubmission(request, contest_id=None, problem_index=None): # problem_id=None, logger.info(str(request).replace("\n\r", "\t")) """ @view: add submission to some contest """ template_tags = { 'show_cid': True, 'show_problem_index': True } # 'is_contest': False, 'show_pid': True, u = None try: u = User.getSessionUser(request.session) if not u: return render( request, 'error.html', {'errmsg': Const.NOT_LOGGED_IN}, ) if request.method == 'POST': form = addSubmissionForm(request.POST) if form.is_valid(): sub_name = str(datetime.now()) for i in ['-', ':', '.', ' ']: sub_name = sub_name.replace(i, '_') code_file_path = "{0}/{1}_{2}".format( Const.SUBMISSION_TMP_PATH, u.uid, sub_name) code_length = 0 if 'code_file' in request.FILES: #return render( request, 'error.html', { 'errmsg': u'请选择要上传的文件!', 'user': u }, ) default_storage.save(code_file_path, request.FILES['code_file']) # code_file = request.FILES['code_file'] # dest = open( code_file_path, 'wb+') # for chunk in code_file.chunks(): # code_length += len(chunk) # dest.write(chunk.encode('utf')) # chinese encoding # dest.write(chunk) else: if not form.cleaned_data['code']: return render( request, 'error.html', { 'errmsg': u'请填写要提交的代码!', 'user': u }, ) default_storage.save( code_file_path, ContentFile(form.cleaned_data['code'])) code_length = default_storage.size(code_file_path) #dest = open( code_file_path, 'wb+') #code_length = len(request.POST['code']) #for chunk in request.POST['code']: # dest.write(chunk.encode('utf')) # chinese encoding #dest.close() # before we tran the very file object, we should turn it off first!!!!(bugs here! but solved) no_judge = False if not contest_id: return render( request, 'error.html', { 'errmsg': u'该选择要提交题目的考试!', 'user': u }, ) else: c = Contest.getById(contest_id) if not c: return render( request, 'error.html', { 'errmsg': u'编号为{0}的考试不存在!'.format(contest_id), 'user': u }, ) p_index = ContestProblem.getByContestAndProblemIndex( contest_id, form.cleaned_data['problem_index']) if not p_index: return render( request, 'error.html', { 'errmsg': u'序号为{0}的题目不存在于考试{1}中!'.format( form.cleaned_data['problem_index'], contest_id), 'user': u }, ) no_judge = c.board_type == 2 p = p_index.problem if not Submission.canSubmitCode(u, p.pid, contest_id): return render( request, 'error.html', { 'errmsg': u'您没有提交本题的权限!', 'user': u }, ) Submission.addSubmission(u, p_index, p.data_count, code_file_path, form.cleaned_data['language'], code_length, no_judge) return redirect('Submission:contest_status', contest_id=contest_id) # could it be okay? # the usage of url.name in urls.py # not POST method else: form = addSubmissionForm() if not contest_id: return render( request, 'error.html', { 'errmsg': u'该选择要提交题目的考试!', 'user': u }, ) else: c = Contest.getById(contest_id) if not c: return render( request, 'error.html', { 'errmsg': u'编号为{0}的考试不存在!'.format(contest_id), 'user': u }, ) if problem_index: form.fields['problem_index'].initial = problem_index else: form.fields['problem_index'].initial = '' return render( request, 'Submission/Submit.html', { 'form': form, 'show_tags': template_tags, 'user': u, 'contest': c, 'problem_index': problem_index }, ) # 'test_info': form.cleaned_data['language']}) except Exception as e: logger.error(str(e).replace("\n\r", "\t")) return render( request, 'error.html', { 'errmsg': unicode(e), 'user': u }, )
def updateProblemSubmit(request, p_id): logger.info(str(request).replace("\n", "\t")) try: u = User.getSessionUser(request.session) if not u: raise Err(request, 'not login') if not p_id: raise Exception(u'题号错误') p_id = int(p_id) ep = Problem.getById(p_id) if not ep: raise Exception(u'题号错误') if not ep.canManageProblem(u): raise Err(request, 'no priv') p = request.POST if request.method == 'POST': form = addProblemForm(request.POST) if not form.is_valid(): raise Exception(u'数据输入有误') prb = ep data_count = prb.data_count case_info = prb.case_info if p['change_data'] == "1": dataInList = request.FILES.getlist('data_in') dataOutList = request.FILES.getlist('data_out') dataScrList = request.POST.getlist('data_scr') if len(dataInList) != len(dataOutList) or len(dataInList) != len( dataScrList): raise Exception(u'上传文件有误') for idx, nowData in enumerate(dataInList): path = Const.PROBLEM_DATA_PATH + str( prb.pid) + "/" + str(idx) + ".in" if default_storage.exists(path): default_storage.delete(path) default_storage.save(path, nowData) for idx, nowData in enumerate(dataOutList): path = Const.PROBLEM_DATA_PATH + str( prb.pid) + "/" + str(idx) + ".out" if default_storage.exists(path): default_storage.delete(path) default_storage.save(path, nowData) dict = {} for idx, nowScr in enumerate(dataScrList): dict[str(idx)] = nowScr case_info = json.dumps(dict) data_count = len(dataInList) dict = {} dict['desc'] = p['prob_desc'] dict['input_desc'] = p['prob_input_desc'] dict['output_desc'] = p['prob_output_desc'] dict['input_sample'] = p['prob_input_sample'] dict['output_sample'] = p['prob_output_sample'] prob_desc = json.dumps(dict) prb.updateProblem(prb.author.uid, p['prob_priv'], p['prob_title'], p['prob_time'], p['prob_memory'], p['prob_codelength'], prob_desc, p['is_spj'], data_count, p['course_id'], case_info) return redirect("/problem/p/" + str(prb.pid) + "/") except Exception as e: logger.error(str(e).replace("\n", "\t")) return render(request, Err.ERROR_PAGE)
def updateProblem(request, p_id): logger.info(str(request).replace("\n", "\t")) try: u = User.getSessionUser(request.session) if not u: raise Err(request, 'not login') try: p_id = int(p_id) p = Problem.getById(p_id) except: logger.error(str(e).replace("\n", "\t")) raise Err(request, 'unknown err') if not p.canManageProblem(u): raise Err(request, 'no priv') if request.method == 'POST': form = addProblemForm(request.POST) if form.is_valid(): data_count = p.data_count case_info = p.case_info if form.cleaned_data['change_data'] == "1": dataInList = request.FILES.getlist('data_in') dataOutList = request.FILES.getlist('data_out') dataScrList = request.POST.getlist('data_scr') if len(dataInList) != len(dataOutList) or len( dataInList) != len(dataScrList): raise Err(request, 'unknown err') for idx, nowData in enumerate(dataInList): path = Const.PROBLEM_DATA_PATH + str( p.pid) + "/" + str(idx) + ".in" if default_storage.exists(path): default_storage.delete(path) default_storage.save(path, nowData) for idx, nowData in enumerate(dataOutList): path = Const.PROBLEM_DATA_PATH + str( p.pid) + "/" + str(idx) + ".out" if default_storage.exists(path): default_storage.delete(path) default_storage.save(path, nowData) dict = {} for idx, nowScr in enumerate(dataScrList): dict[str(idx)] = nowScr case_info = json.dumps(dict) data_count = len(dataInList) dict = {} dict['desc'] = form.cleaned_data['prob_desc'] dict['input_desc'] = form.cleaned_data['prob_input_desc'] dict['output_desc'] = form.cleaned_data['prob_output_desc'] dict['input_sample'] = form.cleaned_data['prob_input_sample'] dict['output_sample'] = form.cleaned_data['prob_output_sample'] prob_desc = json.dumps(dict) p.updateProblem(u.uid, form.cleaned_data['prob_priv'], form.cleaned_data['prob_title'], form.cleaned_data['prob_time'], form.cleaned_data['prob_memory'], form.cleaned_data['prob_codelength'], prob_desc, form.cleaned_data['is_spj'], data_count, p.course_id, case_info) return redirect("/problem/p/" + str(p.pid) + "/") else: raise Err(request, 'unknown err') else: desc = json.loads(p.prob_desc) form = addProblemForm( initial={ 'prob_title': p.prob_title, 'prob_priv': p.prob_priv, 'prob_time': p.prob_time, 'prob_memory': p.prob_memory, 'prob_codelength': p.prob_codelength, 'prob_desc': desc['desc'], 'prob_input_desc': desc['input_desc'], 'prob_output_desc': desc['output_desc'], 'prob_input_sample': desc['input_sample'], 'prob_output_sample': desc['output_sample'], 'is_spj': p.is_spj, 'change_data': 0 }) cases = range(p.data_count) return render( request, 'newtpl/problem/modifyProblem.html', { 'problem': p, 'form': form, 'tpl': { 'sp': True }, 'update': True, 'cases': cases }) except Exception as e: logger.error(str(e).replace("\n", "\t")) return render(request, Err.ERROR_PAGE)
def addGeneralSubmission(request, problem_id=None): """ view used to add general submission """ try: if not problem_id: raise Err( request, err='request err', log_format=('problem index', 'UNDEFINED'), user_format=(u'题目序号', u'哪里去了!!'), ) problem_id = int(problem_id) try: p = Problem.getById(problem_id) except: raise Err( request, err='no problem', log_format=('{0}'.format(problem_id), ''), user_format=(u'{0}'.format(problem_id), u'啥乱七八糟的!!!'), ) u = User.getSessionUser(request.session) if not u: raise Err(request, err='not login') if not GeneralSubmission.canSubmitCode(u, p): raise Err(request, err='no priv') if request.method == 'POST': lang_list = [('gcc', 'GNU C'), ('g++', 'GNU C++'), ('java', 'JAVA')] form = addGeneralForm(lang_list, request.POST) if form.is_valid(): sub_name = str(datetime.now()) time_str = sub_name.split('.') time_str.pop() for i in ['-', ':', '.', ' ']: sub_name = sub_name.replace(i, '_') head_details = '' head_details += '/*\n' head_details += 'USER_ID: ' + str(u) + '\n' head_details += 'PROBLEM: ' + str(p.pid) + '\n' head_details += 'SUBMISSION_TIME: ' + time_str[0] + '\n' head_details += '*/\n' import os code_file_path = os.path.join( Const.SUBMISSION_TMP_PATH, "{0:010d}_{1}_{2}".format(u.uid, sub_name, 'general')) code_length = 0 if 'code_file' in request.FILES: default_storage.save(code_file_path, request.FILES['code_file']) else: if form.cleaned_data['code']: default_storage.save( code_file_path, ContentFile(head_details + form.cleaned_data['code'])) else: raise Err( request, err='request err', log_format=('code', 'no input'), user_format=(u'代码呢!', u'不写代码交什么交!!'), ) code_length = default_storage.size(code_file_path) sub_lang = form.cleaned_data['language'] if sub_lang not in map(lambda x: x[0], lang_list): raise Err( request, err='illegal language', log_format=('{0}'.format(sub_lang), 'blabla'), user_format=(u'{0}'.format(sub_lang), u'别瞎搞成不!!'), ) x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') additional = {'submit_ip': ip} GeneralSubmission.addGeneralSubmission( u, p, code_file_path, form.cleaned_data['language'], code_length) return redirect('Submission:status') # could it be okay? else: raise Exception(u'form invalid') # not POST method else: lang_list = [('gcc', 'GNU C'), ('g++', 'GNU C++'), ('java', 'JAVA')] form = addGeneralForm(lang_list) return render( request, 'newtpl/submission/general/submit.html', { 'form': form, 'tpl': { 'sp': True }, 'problem': p }, ) except Exception as e: return render( request, Err.ERROR_PAGE, { 'errmsg': unicode(e), }, )
def addProblemSubmit(request): logger.info(str(request).replace("\n", "\t")) try: u = User.getSessionUser(request.session) if not u: raise Err(request, 'not login') p = request.POST if request.method == 'POST': form = addProblemForm(request.POST) if not form.is_valid(): raise Exception(u'数据输入有误') course_id = int(p['course_id']) if course_id == None: raise Exception(u'课程非法') cs = Course.getById(course_id) if not cs: raise Exception(u'课程号非法') if not Problem.canAddCourseProblem(cs, u): raise Err(request, 'no priv') prb = Problem.addProblem(u.uid, p['prob_priv'], p['prob_title'], p['prob_time'], p['prob_memory'], p['prob_codelength'], p['prob_desc'], p['is_spj'], 0, p['course_id'], "") data_count = 0 case_info = "" #If file not exist, Create an empty file. open(Const.PROBLEM_DATA_PATH + str(prb.pid) + "/" + "0.in", 'a').close() open(Const.PROBLEM_DATA_PATH + str(prb.pid) + "/" + "0.out", 'a').close() if p['change_data'] == "1": dataInList = request.FILES.getlist('data_in') dataOutList = request.FILES.getlist('data_out') dataScrList = request.POST.getlist('data_scr') if len(dataInList) != len(dataOutList) or len(dataInList) != len( dataScrList): raise Exception(u'上传文件有误') for idx, nowData in enumerate(dataInList): path = Const.PROBLEM_DATA_PATH + str( prb.pid) + "/" + str(idx) + ".in" if default_storage.exists(path): default_storage.delete(path) default_storage.save(path, nowData) for idx, nowData in enumerate(dataOutList): path = Const.PROBLEM_DATA_PATH + str( prb.pid) + "/" + str(idx) + ".out" if default_storage.exists(path): default_storage.delete(path) default_storage.save(path, nowData) dict = {} for idx, nowScr in enumerate(dataScrList): dict[str(idx)] = nowScr case_info = json.dumps(dict) data_count = len(dataInList) dict = {} dict['desc'] = p['prob_desc'] dict['input_desc'] = p['prob_input_desc'] dict['output_desc'] = p['prob_output_desc'] dict['input_sample'] = p['prob_input_sample'] dict['output_sample'] = p['prob_output_sample'] prob_desc = json.dumps(dict) prb.updateProblem(u.uid, p['prob_priv'], p['prob_title'], p['prob_time'], p['prob_memory'], p['prob_codelength'], prob_desc, p['is_spj'], data_count, p['course_id'], case_info) return redirect("/problem/p/" + str(prb.pid) + "/") except Exception as e: logger.error(str(e).replace("\n", "\t")) return render(request, Err.ERROR_PAGE, {'errmsg': unicode(e)})
def viewCodeAndInfo(request, gsid): """ view used to show the detail of some general submission """ try: gsid = int(gsid) u = User.getSessionUser(request.session) if not u: raise Err(request, err='not login') try: g_s = GeneralSubmission.getById(gsid) except: raise Err( request, err='no generalsubmission', log_format=('{0}'.format(gsid), ''), user_format=(u'{0}'.format(gsid), u'别扯了!!'), ) if not GeneralSubmission.canViewCode(g_s, u): raise Err(request, err='no priv') info = eval(g_s.other_info) info['brush'] = Const.BRUSH[g_s.code_language] info['status_cn'] = Const.STATUS_CN[info['status']] info['status_color'] = Const.STATUS_COLOR[ info['status']] if info['status'] in Const.STATUS_COLOR else '' info['lang'] = Const.LANG_REFLECT[g_s.code_language] info['judge_time'] = str(g_s.submission_time) info['judger'] = Const.JUDGER_NAME if 'ce' in info: info['ce'] = info['ce'].replace('/${TOKISAKI_KURUMI}', '') info['score_obtained'] = 0 if 'score_sum' not in info: case_dict = json.loads(g_s.problem.case_info) score_sum = sum(map(int, case_dict.values())) info['score_sum'] = score_sum #g_s.other_info = str( info) #g_s.save() if 'case_result' in info: score_obtained = 0 for seq in info['case_result']: seq['res_cn'] = JUDGE_RES_CN[seq['res']] temp_res = 'status-' + seq['res'] seq['res_color'] = temp_res if 'score' in seq: score_obtained += int(seq['score']) info['score_obtained'] = score_obtained # info['submit_ip'] = request.META['REMOTE_ADDR'] # if 'score_sum' not in info: # case_dict = json.loads(s.problem.case_info) # # score_sum = 0 # # for score in case_dict: # # score_sum += int( score) # score_sum = sum( map( int, case_dict.values())) # info['score_sum'] = score_sum # s.other_info = str( info) # s.save() #if 'case_result' in info: # for seq in info['case_result']: # seq['res_cn'] = JUDGE_RES_CN[seq['res']] return render( request, 'newtpl/submission/general/code_and_info.html', { 'submission': g_s, 'info': info, 'code_content': default_storage.open(g_s.code_file).read(), 'tpl': { 'sp': True } }, ) except Exception as e: return render( request, Err.ERROR_PAGE, { 'errmsg': unicode(e), }, )
def generalSubmissionList(request, page_id='1'): """ @view: list general submission """ try: page_id = int(page_id) u = User.getSessionUser(request.session) if not u: raise Err(request, err='not login') # fake if u.priv == 'university': has_priv = True else: has_priv = False user = u if not has_priv else None lang_list = [('gcc', 'GNU C'), ('g++', 'GNU C++'), ('java', 'java')] form = generalListForm(lang_list, request.GET) if form.is_valid(): if form.cleaned_data['problem_id']: try: p = Problem.getById(form.cleaned_data['problem_id']) except: raise Err(request, err='request err', log_format=('form invalid', 'problem_id error'), user_format=(u'输入的内容不合法', u'没有这道题!')) else: p = None else: raise Err(request, err='example err', log_format=('form invalid', ''), user_format=(u'输入的内容不合法', '')) g_subs = GeneralSubmission.generalSubmissionList( u=user, p=p, uname=form.cleaned_data['username'], language=form.cleaned_data['language'], status_selected=form.cleaned_data['status'], university=u.university) if 'rejudge' in request.GET: if has_priv: map(lambda x: GeneralSubmission.rejudgeGeneralSubmission(x), g_subs) else: raise Err(request, err='no priv') paginator = Paginator(g_subs, Const.STATUS_PER_PAGE) page_id = min(max(int(page_id), 1), paginator.num_pages) g_s = paginator.page(page_id) for g_s_index in g_s: g_s_index.status_color = Const.STATUS_COLOR[ g_s_index. status] if g_s_index.status in Const.STATUS_COLOR else '' g_s_index.status_cn = Const.STATUS_CN[g_s_index.status] return render( request, 'newtpl/submission/general/status.html', { 'general_list': g_s, 'form': form, 'tpl': { 'can_manage': True if has_priv else False } }) except Exception as e: return render(request, Err.ERROR_PAGE, {'errmsg': unicode(e)})
def showResult(request, cid, page='1'): try: u = User.getSessionUser(request.session) if not u: raise Err(request, err='not login') c = Contest.getById(int(cid)) try: c.canBeManaged(u) except: raise Err(request, err='no priv') if ('threshold' in request.GET) and request.GET['threshold']: threshold = float(request.GET['threshold']) else: threshold = Const.CHEAT_DEFAULT_THRESHOLD #------------form------------- idxList = [(cp.problem_index, cp.problem_index) for cp in c.getContestProblem()] langList = [('gcc','GNU C'), ('g++','GNU C++'), ('java','java')] form = submissionListForm(idxList, langList, request.GET) if form.is_valid(): if form.cleaned_data['problem_index']: try: contestProb = ContestProblem.getBy( c, form.cleaned_data['problem_index']) except: contestProb=None # raise Exception(u'contest problem not found') else: contestProb=None else: raise Err( request, err='example err', log_format=( 'form invalid', ''), user_format=( u'输入的内容不合法', '') ) #------------form-------------- cheatList = Cheat.getCheatList(contest=c, threshold=0) #------------filter------------ if contestProb: cheatList = cheatList.filter(contest_problem=contestProb) if form.cleaned_data['username']: cheatList1 = cheatList.filter(sub1__user__username__icontains=form.cleaned_data['username']) cheatList2 = cheatList.filter(sub2__user__username__icontains=form.cleaned_data['username']) cheatList = cheatList1 | cheatList2 #------------filter------------ paginator = Paginator(cheatList, Const.CHEAT_PER_PAGE) page = min(max(int(page), 1), paginator.num_pages) cl = paginator.page(page) ipa = [] ipb = [] for idx, element in enumerate(cl): info_a = eval(element.sub1.other_info) info_b = eval(element.sub2.other_info) #cl[idx] = {'c': element, 'ip_a': info_a['submit_ip'], 'ip_b': info_b['submit_ip']} ipa.append(info_a['submit_ip']) ipb.append(info_b['submit_ip']) return render(request, 'newtpl/cheat/showResult.html', {'tpl':{'sp':True,}, 'contest':c, 'cheat_list':cl, 'ipa':ipa,'ipb':ipb, 'form':form }) except Exception as e: return render(request, Err.ERROR_PAGE) # def codeDiff(request, ctid): # try: # u = User.getSessionUser(request.session) # if not u: # raise Err(request, err='not login') # ct = Cheat.objects.select_related('sub1__user', 'sub2__user').get(ctid=ctid) # # try: # ct.contest.canBeManaged(u) # except: # raise Err(request, err='no priv') # # return render(request, 'newtpl/cheat/codeDiff.html', {'tpl':{'sp':True,}, 'sub1':ct.sub1, 'sub2':ct.sub2}) # # # except Exception as e: # return render(request, Err.ERROR_PAGE) """
def showBoardByStatus(request, cId): logger.info(str(request).replace("\n", "\t")) try: u = User.getSessionUser(request.session) if not u: raise Err(request, 'not login') try: cId = int(cId) c = Contest.getById(cId) except: raise Err(request, 'no resource') can_manage = True try: c.canBeManaged(u) except: can_manage = False try: c.canEnterContest(u) except: raise Err(request, 'no priv') allSub = Submission.submissionList(c=c).order_by('sid') allUser = c.course_class.getAllStudents() allProb = c.getContestProblem() pInfoDict = { pinfo.problem_index: { 'idx': pinfo.problem_index, 'ac': 0, 'pen': 0, 'sub': 0 } for pinfo in allProb } info = { uinfo.uid: { 'uid': uinfo.uid, 'username': uinfo.username, 'nickname': uinfo.nickname, 'ac': 0, 'pen': 0, 'pinfo': copy.deepcopy(pInfoDict) } for uinfo in allUser } if c.board_type == 0: # acm style board for sinfo in allSub: if not sinfo.user.uid in info: continue uid = sinfo.user.uid idx = sinfo.problem_index.problem_index if info[uid]['pinfo'][idx]['ac'] > 0: continue if sinfo.status in [ 'Pending', 'Rejudging', 'Compiling', 'System Error' ]: continue td = sinfo.submission_time - c.start_time info[uid]['pinfo'][idx]['sub'] += 1 if sinfo.status == "Accepted": info[uid]['pinfo'][idx][ "ac"] = 1 - info[uid]['pinfo'][idx]["ac"] info[uid]['pinfo'][idx]["ac_time"] = int( math.ceil(td.total_seconds() / 60)) info[uid]['pinfo'][idx]["pen"] += int( math.ceil(td.total_seconds() / 60)) if (not 'fb_time' in pInfoDict[idx] ) or td < pInfoDict[idx]['fb_time']: pInfoDict[idx]['fb_time'] = td pInfoDict[idx]['fb_uid'] = uid else: info[uid]['pinfo'][idx]["ac"] -= 1 info[uid]['pinfo'][idx]["pen"] += 20 for idx, pinfo in pInfoDict.iteritems(): if 'fb_time' in pinfo: info[pinfo['fb_uid']]['pinfo'][idx]['fb'] = True info = info.values() for i in info: i['pinfo'] = i['pinfo'].values() i['pinfo'].sort(key=lambda x: x['idx']) for pinfo in i['pinfo']: if pinfo['ac'] > 0: i['ac'] += 1 i['pen'] += pinfo['pen'] else: for sinfo in allSub: if not sinfo.user.uid in info: continue uid = sinfo.user.uid idx = sinfo.problem_index.problem_index other_info = eval(sinfo.other_info) tscore = int(other_info['score']) if info[uid]['pinfo'][idx]['ac'] >= tscore: continue if sinfo.status in [ 'Pending', 'Rejudging', 'Compiling', 'System Error' ]: continue td = sinfo.submission_time - c.start_time info[uid]['pinfo'][idx]['sub'] += 1 info[uid]['pinfo'][idx]['ac'] = tscore info[uid]['pinfo'][idx]["pen"] += int( math.ceil(td.total_seconds() / 60)) - info[uid]['pinfo'][idx].get("ac_time", 0) info[uid]['pinfo'][idx]["ac_time"] = int( math.ceil(td.total_seconds() / 60)) if sinfo.status == "Accepted": if (not 'fb_time' in pInfoDict[idx] ) or td < pInfoDict[idx]['fb_time']: pInfoDict[idx]['fb_time'] = td pInfoDict[idx]['fb_uid'] = uid for idx, pinfo in pInfoDict.iteritems(): if 'fb_time' in pinfo: info[pinfo['fb_uid']]['pinfo'][idx]['fb'] = True info = info.values() for i in info: i['pinfo'] = i['pinfo'].values() for pinfo in i['pinfo']: if pinfo['ac'] > 0: i['ac'] += pinfo['ac'] i['pen'] += pinfo['pen'] info.sort(key=lambda x: x['ac'] * 262144 - x['pen'], reverse=True) for r, i in enumerate(info, 1): i['rank'] = r if can_manage or c.contest_type == 0: rank = info else: rank = filter(lambda x: u.uid == x['uid'], info) return render(request, "newtpl/statistic/board.html", { 'info': info, 'rank': rank, 'allProb': allProb, 'contest': c }) except Exception as e: logger.error(str(e).replace("\n", "\t")) return render(request, Err.ERROR_PAGE)
def updateContest(request, cId): try: u = User.getSessionUser(request.session) if not u: #raise Exception(Const.NOT_LOGGED_IN) raise Err(request, err='not login') try: c = Contest.getById(cId) except: raise Err(request, 'no resource') cc = c.course_class try: c.canBeManaged(u) except: raise Err(request, err='no priv') started = c.isStarted(5) if started: recentProblem = None else: recentProblem = Problem.problemListByAuthor(u) problemList = [{ 'pid': cp.problem.pid, 'title': cp.problem_title, 'origTitle': cp.problem.prob_title } for cp in c.getContestProblem()] if request.method == 'POST': POST = request.POST.copy() if started: POST['start_date'] = c.start_time.date() POST['start_time'] = c.start_time.time() POST['started'] = started form = contestForm(POST) if started: form.fields['start_date'].widget.attrs['disabled'] = True form.fields['start_time'].widget.attrs['disabled'] = True if started: pIdList = [cp['pid'] for cp in problemList] pTitleList = [cp['title'] for cp in problemList] pass else: pIdList = request.POST.getlist('problem_id') pTitleList = request.POST.getlist('problem_title_custom') pCnt = len(pIdList) if form.is_valid(): for i in xrange(pCnt): p = Problem.getById(pIdList[i]) if not p.canManageProblem(u): raise Err(request, 'no problem priv') pInfos = [(pIdList[i], pTitleList[i], chr(65 + i)) for i in xrange(pCnt)] cTitle = form.cleaned_data['title'] cDesc = form.cleaned_data['desc'] cStartDate = form.cleaned_data['start_date'] cStartTime = form.cleaned_data['start_time'] cLength = form.cleaned_data['length'] cBoardStop = form.cleaned_data['board_stop'] cType = form.cleaned_data['contest_type'] cBoardType = form.cleaned_data['board_type'] permitLang = reduce(add, [ Const.LANG_MASK[lang] for lang in form.cleaned_data['lang_limit'] ]) c.updateContest(cTitle, pInfos, datetime.combine(cStartDate, cStartTime), cDesc, cLength, cBoardStop, cType, cBoardType, permitLang) return redirect('Contest:show_contest', cId) else: problemList = [{ 'pid': pIdList[x], 'title': pTitleList[x], 'origTitle': Problem.getById(pIdList[x]).prob_title } for x in xrange(pCnt)] return render( request, 'newtpl/contest/updateContest.html', { 'c': c, 'cc': cc, 'form': form, 'started': started, 'hehe': pCnt, 'recent_problem': recentProblem, 'problem_list': problemList, 'tpl': { 'has_priv': True, 'sp': True, } }) else: form = contestForm( initial={ 'title': c.contest_title, 'desc': c.contest_description, 'start_date': c.start_time.date(), 'start_time': c.start_time.time(), 'length': c.length, 'board_stop': c.board_stop, 'contest_type': c.contest_type, 'board_type': c.board_type, 'lang_limit': c.permittedLangs(), 'started': started, }) if started: form.fields['start_date'].widget.attrs['disabled'] = True form.fields['start_time'].widget.attrs['disabled'] = True return render( request, 'newtpl/contest/updateContest.html', { 'c': c, 'cc': cc, 'form': form, 'started': started, 'recent_problem': recentProblem, 'problem_list': problemList, 'tpl': { 'has_priv': True, 'sp': True, 'nav_act': 'contest', } }) #return render(request, Const.ERROR_PAGE, {'errmsg': unicode(e), }) except Exception as e: return render(request, Const.ERROR_PAGE, { 'errmsg': unicode(e), })