Example #1
0
def holdContest(request):
	
	f=HoldContestForm()
	dc = {'form':f}
	context = RequestContext(request, dc)
	if request.method == "POST":
		f=HoldContestForm(request.POST)
		if not f.is_valid():
			dc = {'form':f}
			context = RequestContext(request, dc)
			#raise Http404
			return render_to_response('holdContest.html',context)
		else:
			contest=Contest()
			context = RequestContext(request,dc)
		#	contest.adminID = User.objects.filter(User.username="******")[0]
			contest.contestName_f = f.cleaned_data['contestName']
			contest.contestpwd_f = f.cleaned_data['contestpwd']
			contest.termsCond = f.cleaned_data['termsCond']
			contest.contestFromDate = f.cleaned_data['contestFromDate']
			contest.contestToDate = f.cleaned_data['contestToDate']
			contest.contestFromTime = f.cleaned_data['contestFromTime']
			contest.contestToTime = f.cleaned_data['contestToTime']
			#contest.isApproved = False
			contest.save()
			f=HoldContestForm()
			#contestID = contest.contestID
			
			return HttpResponse("Your contest is send to admin for approval%s"%request.path)
	else:
		return render_to_response('holdContest.html',context)
Example #2
0
File: views.py Project: YLAsce/oj
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)
Example #3
0
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), })
Example #4
0
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)
Example #5
0
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')

        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'

        cn = c.getContestNotice()
        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),
        })
Example #6
0
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),
        })
Example #7
0
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),
        })
Example #8
0
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), })
Example #9
0
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)
Example #10
0
def getContestNoticeList(request):
    cId = request.POST['cid']
    c = Contest.getById(cId)
    f = lambda cn: '<a href="' + reverse('Contest:show_contest_notice',
                                         args=[cId, cn.id]
                                         ) + '">' + cn.notice_title + '</a>'
    return HttpResponse(' '.join([f(cn) for cn in c.getContestNotice()]))
Example #11
0
File: views.py Project: YLAsce/oj
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)})
Example #12
0
File: views.py Project: YLAsce/oj
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)})    
Example #13
0
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), })
Example #14
0
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), })
Example #15
0
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)})
Example #16
0
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)})
Example #17
0
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), })
Example #18
0
File: views.py Project: YLAsce/oj
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)
        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']}

        return render(request, 'newtpl/cheat/showResult.html', {
            'tpl': {
                'sp': True,
            },
            'contest': c,
            'cheat_list': cl
        })
    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)
    """
Example #19
0
File: views.py Project: YLAsce/oj
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)
Example #20
0
File: views.py Project: YLAsce/oj
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), })
Example #21
0
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),
        })
Example #22
0
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), })
Example #23
0
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),})
Example #24
0
File: views.py Project: YLAsce/oj
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)
    """
Example #25
0
File: views.py Project: YLAsce/oj
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),
        })
Example #26
0
def listContestNotice(request, cId):
    try:
        u = User.getSessionUser(request.session)
        if not u:
            raise Exception(Const.NOT_LOGGED_IN)

        c = Contest.getById(cId)
        c.canEnterContest(u)
        cn = c.getContestNotice()
        return render(
            request, 'newtpl/contest/contestNoticeList.html', {
                'cid': cId,
                'contest_notice_list': c.getContestNotice(),
                'tpl': {
                    'has_priv': Contest.hasPriv(c.course_class, u),
                    'nav_act': 'contest',
                }
            })
    except Exception as e:
        return render(request, Const.ERROR_PAGE, {
            'errmsg': unicode(e),
        })
Example #27
0
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),
        })
Example #28
0
def boardDetail(request, cid):
    try:
        cdata = cache.get(make_key(cid, 'board'))
        if cdata:
            return JSONResponse(eval(zlib.decompress(cdata)))
        c = Contest.getById(cid)
        b = Board()
        b.contest = c
        if request.method == 'GET':
            serializer = BoardSerializer(b)
            data = serializer.data
            cache.set(make_key(cid, 'board'), zlib.compress(str(data)), 60)
            return JSONResponse(data)
    except Exception as e:
        return HttpResponse(e)
Example #29
0
def boardDetail(request, cid):
    try:
        cdata = cache.get(make_key(cid, 'board'))
        if cdata:
            return JSONResponse(eval(zlib.decompress(cdata)))
        c = Contest.getById(cid)
        b = Board()
        b.contest = c
        if request.method == 'GET':
            serializer = BoardSerializer(b)
            data = serializer.data
            cache.set(make_key(cid, 'board'), zlib.compress(str(data)), 60)
            return JSONResponse(data)
    except Exception as e:
        return HttpResponse(e)
Example #30
0
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)
Example #31
0
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)
Example #32
0
File: views.py Project: vapour18/oj
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) } )
Example #33
0
File: views.py Project: YLAsce/oj
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)
Example #34
0
File: views.py Project: YLAsce/oj
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)})
Example #35
0
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)})    
Example #36
0
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),
        })
Example #37
0
File: views.py Project: YLAsce/oj
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)
        })
Example #38
0
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)
Example #39
0
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),
            },
        )
Example #40
0
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 =  Problem.problemList(u)
                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.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.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:
        messages.info(request, unicode(e))
        return render(request, Const.ERROR_PAGE, {'errmsg': unicode(e), })
Example #41
0
File: views.py Project: YLAsce/oj
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 contestproblem', 
                        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)

                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), }, )
Example #42
0
File: views.py Project: YLAsce/oj
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)

                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 }, )
                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)

                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}, )
Example #43
0
File: views.py Project: vapour18/oj
def showBoardByScore(request, cId):# modified
    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:{'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}

        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)
Example #44
0
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),
        })
Example #45
0
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)
    """
Example #46
0
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)
Example #47
0
File: views.py Project: YLAsce/oj
def showBoardByStatus(request, cId, balloon = False):
    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')

        key = str(cId)
        if not can_manage and not c.contest_type==0:
            key = str(cId) + ","+ str(u.uid)

        res = cache.get(key)
        if res!=None:
            info, allProb, board_body = res

            if can_manage and balloon:
                return render(request,"newtpl/statistic/board2.html", {'info': info, 'board_body': board_body, 'allProb': allProb, 'contest': c})
            else:
                return render(request,"newtpl/statistic/board_test.html", {'info': info, 'board_body': board_body, 'allProb': allProb, 'contest': c})

        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')
        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}


        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']


        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
        key = str(cId)
        if not can_manage and not c.contest_type==0:
            rank = filter(lambda x:u.uid==x['uid'], info)
            key = str(cId) + ","+ str(u.uid)

        board_body = render_to_response("newtpl/statistic/board_body.html", {'rank': rank}).content

        cache.set(key, (info, allProb, board_body), 10)

        if can_manage and balloon:
            return render(request,"newtpl/statistic/board2.html", {'info': info, 'board_body': board_body, 'allProb': allProb, 'contest': c})
        else:
            return render(request,"newtpl/statistic/board_test.html", {'info': info, 'board_body': board_body,'allProb': allProb, 'contest': c})
    except Exception as e:
        logger.error(str(e).replace("\n","\t"))
        return render(request, Err.ERROR_PAGE)
Example #48
0
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
            },
        )
Example #49
0
def getContestNoticeList(request):
    cId = request.POST['cid']
    c = Contest.getById(cId)
    f = lambda cn: '<a href="' + reverse('Contest:show_contest_notice', args=[cId, cn.id]) + '">' + cn.notice_title + '</a>'
    return HttpResponse(' '.join([f(cn) for cn in c.getContestNotice()]))
Example #50
0
File: views.py Project: YLAsce/oj
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'输入的内容不合法', '')
                    )

        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:
            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}})

    except Exception as e:
        logger.error(str(e).replace("\n\r","\t"))
        return render(request, Err.ERROR_PAGE, { 'errmsg': unicode(e) } )
Example #51
0
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)
Example #52
0
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)})