def run(self, contest, Runner, Judge): result = { 'status' : True, 'points' : 0, 'message' : '', 'judges' : [], } r = Session.query(Runner).filter_by(lang=self.getType()).first() if not r: result['status'] = False result['message'] = _("Unknown file type") return result judges = Session.query(Judge).filter_by(task_id=self.task_id).all() for judge in judges: resultJudge = r.exe(self, judge) if not resultJudge['status']: result['status'] = False result['judges'].append(resultJudge['message']) else: if contest.mode == 2: # codex result['judges'].append(_('OK (%s points)') % (judge.points)) else: result['judges'].append(_('OK')) result['points'] += judge.points if result['status']: result['message'] = _('The task was solved') else: result['message'] = _('The task was not solved') return result
def run(self, contest, Runner, Judge): result = { 'status': True, 'points': 0, 'message': '', 'judges': [], } r = Session.query(Runner).filter_by(lang=self.getType()).first() if not r: result['status'] = False result['message'] = _("Unknown file type") return result judges = Session.query(Judge).filter_by(task_id=self.task_id).all() for judge in judges: resultJudge = r.exe(self, judge) if not resultJudge['status']: result['status'] = False result['judges'].append(resultJudge['message']) else: if contest.mode == 2: # codex result['judges'].append( _('OK (%s points)') % (judge.points)) else: result['judges'].append(_('OK')) result['points'] += judge.points if result['status']: result['message'] = _('The task was solved') else: result['message'] = _('The task was not solved') return result
def check(self): c.success = False c.errors = [] form = self.getPost() if not form['login']: c.errors.append(_("Enter your login")) if Session.query(User).filter_by(login=form['login']).count() != 0: c.errors.append(_("This login name is already used")) if form['password'] != form['cpassword'] or not form['password']: c.errors.append(_("Passwords are empty or wrong")) if not form['mail'] or form['mail'] == "@": c.errors.append(_("Enter your e-mail")) if Session.query(User).filter_by(mail=form['mail']).count() != 0: c.errors.append(_("E-mail is already registered")) if len(c.errors) == 0: if not self.register(form): c.errors.append( _("Registration failed. Sorry. Please, contact us.")) else: c.success = True return render('/registration.mako') return self.index()
def _upload(self): if request.POST['type']: response.set_cookie('source_type', request.POST['type']) try: file = request.POST['source'] if request.POST['type'] != '*': file.filename += "."+request.POST['type'] size = len(file.value) fileName = file.filename.replace(" ", "_").encode('ascii', 'ignore') fileValue = file.value except: if request.POST['code'] != '' and request.POST['type'] != '*': fileName = b16encode(request.POST['code'])[:16]+"."+request.POST['type'] fileValue = request.POST['code'] size = len(fileValue) else: return False if size>1024*10: # 10 kB return False if not self.source: self.source = Source(self.task.contest_id, self.task.id, self.user.id, fileName) Session.add(self.source) self.source.file = fileName self.source.source = fileValue self.source.commit() return True
def save(self): self.auth() id = self.user.id user = Session.query(User).filter_by(id=id).first() l = request.params if l['password'] == l['cpassword'] and l['password'] != "": user.password = hash(l['password']) if l['mail'] != "": user.mail = l['mail'] user.fname = l['fname'] user.lname = l['lname'] user.cls = l['cls'] Session.commit() del session['user'] request.environ['REMOTE_USER'] = user request.environ['REMOTE_USER_NAME'] = session.get('user_name') self.user = user session['user'] = user session.save() return self.index() #redirect_to(controller=None)
def top(self, id=10): self.auth() countShow = int(id) users = None if self.user: if self.user.admin: users = Session.query(User).all() if not users: users = Session.query(User).filter_by(admin=False).all() contests = Session.query(Contest).filter_by(is_running=True).all() runningContests = [] for contest in contests: runningContests.append(contest.id) c.users = [] for user in users: count = Session.query(Source).filter_by( user_id=user.id, status=True).filter( not_(Source.contest_id.in_(runningContests))).count() if count: c.users.append({'user': user, 'count': count}) c.users = sorted(c.users, key=lambda rank: (int(rank['count']), rank['user']), reverse=True)[:countShow] return render('top.mako')
def __call__(self, environ, start_response): """Invoke the Controller""" # WSGIController.__call__ dispatches to the Controller method # the request is routed to. This routing information is # available in environ['pylons.routes_dict'] try: return WSGIController.__call__(self, environ, start_response) finally: Session.remove()
def register(self, data): try: Session.add(User(data['login'], data['password'], data['mail'], data['fname'], data['lname'], data['cls'])) Session.commit() except: return False return True
def register(self, data): try: Session.add( User(data['login'], data['password'], data['mail'], data['fname'], data['lname'], data['cls'])) Session.commit() except: return False return True
def admin(self, id=None, param=None): self.auth(admin=True) if not id: c.list = self._getContestsList() return render('/admin/contestList.mako') if param=="remove": self._remove(id) return self.toIndex() if param=="reset": self._reset(id) return self.toIndex() if id=="_" and param=="create": id = self._create(request.params['name']) return self.toIndex(id=id) self._loadContest(id) if param=="save": self.contest.name = request.params['contest_name'] self.contest.mode = request.params['mode'] if request.params.has_key('results'): self.contest.results = True else: self.contest.results = False Session.commit() return redirect_to(param=None) if param=="start": self.contest.start() Session.commit() return self.toIndex() if param=="stop": self.contest.stop() Session.commit() return self.toIndex() if param=="create_task": t = Task(self.contest.id, request.params['name']) Session.add(t) Session.commit() return redirect_to(controller="admin", action="task", id=t.id, param=None) c.list = self._loadTasks() c.contest = self.contest return render('/admin/contestTasks.mako')
def admin(self, id=None, param=None): self.auth(admin=True) if param=="remove": Session.execute(runners_table.delete().where(runners_table.c.id==int(id))) Session.commit() if id=="save": self._save() c.list = Session.query(Runner).all() return render('/admin/runners.mako')
def getOutputFile(self): fileName = self._getFileName()+".output" if not os.path.exists(fileName): task = Session.query(Task).filter_by(id=self.task_id).one() runner = Session.query(Runner).filter_by(lang=task.filetype).one() runner.exe(task, self, onlyResult=True) shutil.move( os.path.join(config.get('task_dir'), str(task.contest_id), str(task.id)+"."+task.filetype+".out.output"), fileName ) return open(fileName, 'r')
def admin(self, id=None, param=None): self.auth(admin=True) if param == "remove": Session.execute( runners_table.delete().where(runners_table.c.id == int(id))) Session.commit() if id == "save": self._save() c.list = Session.query(Runner).all() return render('/admin/runners.mako')
def _adminSave(self, id, params): user = Session.query(User).filter_by(id=id).first() user.fname = params['fname'] user.lname = params['lname'] user.mail = params['mail'] user.cls = params['cls'] if params['password'] != '' and params['password'] == params[ 'cpassword']: user.password = hash(params['password']) if params.has_key('admin'): user.admin = True else: user.admin = False Session.commit()
def load(self): if os.path.exists(self._getFileName()): self.source = self.getSource() else: self.source = None self.judges = Session.query(Judge).filter_by(task_id=self.id).all()
def sources(self): self.auth() c.sources = Session.query(Source).filter_by(user_id=self.user.id).all() c.getTaskName = self._getTaskName return render('sources.mako')
def _taskExists(self, id): task = Session.query(Task).filter_by(id=id).first() print task.name if task: return True else: return False
def timeSolved(self, id): s = Session.query(Source).filter_by(task_id=id, user_id=self.user.id, status=True).first() if s: return s.datetime else: return "---"
def _save(self): self.task.description = request.POST['description'] self.task.example_in = request.POST['example_in'] self.task.example_out = request.POST['example_out'] self.task.filetype = request.POST['filetype'] if request.POST['source'] != '': self.task.saveSource(request.POST['source']) for i in range(int(request.POST['count'])): if self.contest.mode == 2: # codex points = request.POST['points['+str(i)+']'] else: points = 0 if request.POST.has_key('file_in['+str(i)+']') and request.POST['file_in['+str(i)+']'] != '': judge = Judge(self.task.id, points=points, time_limit=request.POST['time_limit['+str(i)+']'], memory_limit=request.POST['memory_limit['+str(i)+']']) Session.add(judge) Session.commit() judge.saveFile(request.POST['file_in['+str(i)+']']) elif request.POST.has_key('id['+str(i)+']'): judge = Session.query(Judge).filter_by(id=request.POST['id['+str(i)+']']).one() judge.points = points judge.time_limit = request.POST['time_limit['+str(i)+']'] judge.memory_limit = request.POST['memory_limit['+str(i)+']'] Session.commit() self.task.load()
def source(self, id=0): self.auth() c.source = Session.query(Source).filter_by( id=id, user_id=self.user.id).first() if not c.source: return redirect_to(action="sources", id=None) c.task_name = self._getTaskName(c.source.task_id) return render('source.mako')
def _run(self, file, lang, fileIn=None, i=None, nolimit=False): r = Session.query(Runner).filter_by(lang=lang).first() if r: if nolimit: get = r.exe(file, fileIn, i=i, time_limit=0, memory_limit=0) else: get = r.exe(file, fileIn, i=i, time_limit=self.task.time_limit, memory_limit=self.task.memory_limit) return get else: return {'errors': _("This script need support of *.%s") % lang, 'return' : '', 'status':'false', 'compile' : ''}
def show(self, id, param=None): self.auth() self._load(id) c.task = self.task c.runners = Session.query(Runner).all() c.contest = self.contest self.source = Session.query(Source).filter_by(user_id=self.user.id, task_id=id).first() if self.source: self.source.load() c.status = self.source.status if param=="upload": if self._upload(): c.result = self._runUserScript() self.source.status = c.result['status'] if int(self.source.points) < int(c.result['points']): self.source.points = c.result['points'] err = '' sum = len(c.result['judges']) for i, result in enumerate(c.result['judges']): err += '<li>%s/%s: %s</li>' % (i+1, sum, result) self.source.errors = err self.source.commit() c.source = self.source if c.source: c.status = c.source.status else: c.status = False self.task.description = self.task.description.replace("\n", "<br>").replace(" ", " "*4).strip("<br>") return render("task.mako")
def check(self): c.success = False c.errors = [] form = self.getPost() if not form['login']: c.errors.append(_("Enter your login")) if Session.query(User).filter_by(login=form['login']).count()!=0: c.errors.append(_("This login name is already used")) if form['password']!=form['cpassword'] or not form['password']: c.errors.append(_("Passwords are empty or wrong")) if not form['mail'] or form['mail']=="@": c.errors.append(_("Enter your e-mail")) if Session.query(User).filter_by(mail=form['mail']).count()!=0: c.errors.append(_("E-mail is already registered")) if len(c.errors)==0: if not self.register(form): c.errors.append(_("Registration failed. Sorry. Please, contact us.")) else: c.success = True return render('/registration.mako') return self.index()
def signin(self): try: login = request.params['login'] password = request.params['password'] except: return self.index() user = Session.query(User).filter_by(login=login, password=hash(password)).first() if user: session['user'] = user session.save() return self.index() else: c.error = _('Login failed') return render('/home.mako')
def admin(self, id=None, param=None, num=None): self.auth(admin=True) if param=="deljudge" and num is not None: Session.execute(judges_table.delete().where(judges_table.c.id==int(num))) Session.commit() self._load(id) if param=="download": if num is None: download = self.task.source name = str(self.task.id)+"."+self.task.filetype size = self.task.sourceSize() file = download else: download = Session.query(Judge).filter_by(id=num).one() name = download.name size = download.size() file = download.getFile() response.headers['Content-Type'] = "text/plain; name=%s" % (name) response.headers['Content-length'] = "%s" % (size) response.headers['Content-Disposition'] = "attachment; filename= %s" %(name) shutil.copyfileobj(file, response) return if param=="save": self._save() if param=="remove": contest_id = self.task.contest_id self._remove() return redirect_to(action="contest", id=contest_id, param=None) c.task = self.task if self.task.source: c.runner = Session.query(Runner).filter_by(lang=self.task.filetype).one() c.contest = self.contest c.runners = Session.query(Runner).all() return render('/admin/taskEdit.mako')
def getRank(self, showAdmin=False): ret = [] if showAdmin: users = Session.query(User) else: users = Session.query(User).filter_by(admin=False) for user in users: points = 0 time = 0 count = Session.query(Source).filter_by(user_id=user.id, contest_id=self.id, status=True).count() points = Session.query(func.sum(Source.points)).filter_by(user_id=user.id, contest_id=self.id).scalar() if count>0: if self.mode == 1: # pilsprog sources = Session.query(Source).filter_by(user_id=user.id, contest_id=self.id, status=True).all() time = self.timeStart count = 0 for source in sources: time = time+(source.datetime-self.timeStart) count = count+1 time = time-self.timeStart else: last, = Session.query(Source.datetime).filter_by(user_id=user.id, contest_id=self.id, status=True).order_by(sources_table.c.datetime.desc()).first() time = last - self.timeStart if count > 0 or (points > 0 and self.mode == 2): # codex ret.append({'user':user, 'count':count, 'points':points, 'time':time}) if self.mode == 2: #codex ret = sorted(ret, key = lambda user: user['points'], reverse=True) else: ret = sorted(ret, key = lambda user: user['time']) ret = sorted(ret, key = lambda user: user['count'], reverse=True) return ret
def start(self): self.is_running = True Session.execute(sources_table.delete().where(sources_table.c.contest_id==self.id)) self.timeStart = self.getTimeStart()
def render_body(context): context.caller_stack._push_frame() try: h = context.get('h', UNDEFINED) c = context.get('c', UNDEFINED) request = context.get('request', UNDEFINED) __M_writer = context.writer() # SOURCE LINE 5 __M_writer(u'\n\t<a href=') # SOURCE LINE 6 __M_writer(escape(h.url_for(controller="contest", action="tasks", id=c.task.contest_id))) __M_writer(u' class="back">zp\u011bt na sout\u011b\u017e</a>\n\t<h2>') # SOURCE LINE 7 __M_writer(escape(c.task.name)) __M_writer(u'</h2>\n\t') # SOURCE LINE 8 __M_writer(c.task.description ) __M_writer(u'\n\n\t<hr style="visibility:hidden;">\n\n\t<div id="example_in"><h3>P\u0159\xedklad vstupu:</h3><pre>') # SOURCE LINE 12 __M_writer(escape(c.task.example_in)) __M_writer(u'</pre></div>\n\t<div id="example_out"><h3>P\u0159\xedklad v\xfdstupu:</h3><pre>') # SOURCE LINE 13 __M_writer(escape(c.task.example_out)) __M_writer(u'</pre></div>\n') # SOURCE LINE 14 from devcontest.model import Contest from devcontest.model.meta import Session # SOURCE LINE 17 __M_writer(u'\n') # SOURCE LINE 18 if Session.query(Contest.is_running).filter_by(id=c.task.contest_id).first()[0]: # SOURCE LINE 19 __M_writer(u'\t<hr>\n') # SOURCE LINE 20 if not c.status or request.environ.get('REMOTE_USER').admin: # SOURCE LINE 21 __M_writer(u'\t ') __M_writer(escape(h.form_start(h.url_for(param="upload"), method="post", multipart=True))) __M_writer(u'\n\t ') # SOURCE LINE 22 __M_writer(escape(h.field("Zdroják", h.file(name="source")))) __M_writer(u'\n\t ') # SOURCE LINE 23 __M_writer(escape(h.field("", h.submit("submit", "Nahrát")))) __M_writer(u'\n\t ') # SOURCE LINE 24 __M_writer(escape(h.form_end())) __M_writer(u'\n') pass # SOURCE LINE 26 if c.status: # SOURCE LINE 27 __M_writer(u'\t\t<div class="success">\xdaloha vy\u0159e\u0161ena</div>\n') pass # SOURCE LINE 29 __M_writer(u'\n') # SOURCE LINE 30 if c.source: # SOURCE LINE 31 __M_writer(u'\t<h3>Posledn\xed verze</h3>\n\t') # SOURCE LINE 32 from pygments import highlight from pygments.lexers import guess_lexer from pygments.formatters import HtmlFormatter # SOURCE LINE 36 __M_writer(u'\n') # SOURCE LINE 37 if c.source.errors: # SOURCE LINE 38 __M_writer(u'\t<pre>') __M_writer(escape(c.source.errors)) __M_writer(u'</pre>\n') pass # SOURCE LINE 40 __M_writer(u'\n\t') # SOURCE LINE 41 __M_writer(highlight(c.source.source, guess_lexer(c.source.source), HtmlFormatter(linenos=True)) ) __M_writer(u'\n\n') pass pass return '' finally: context.caller_stack._pop_frame()
def _allUsers(self, task_id): return Session.query(Source).filter_by(task_id=task_id).count()
def _loadContest(self, id): self.contest = Session.query(Contest).filter_by(id=id).first()
def _loadTasks(self, id=None): if not id: id = self.contest.id return Session.query(Task).filter_by(contest_id=id).all()
def _okUsers(self, task_id): return Session.query(Source).filter_by(task_id=task_id, status=True).count()
def _create(self, name): c = Contest(name) Session.add(c) Session.commit() return c.id
def admin(self, id, param): self.auth(admin=True) if id == "remove" and param: Session.execute( users_table.delete().where(users_table.c.id == int(param))) Session.commit() if id == "save" and param: params = request.params self._adminSave(param, params) return redirect_to(id="edit") if id == "edit" and param: c.user = Session.query(User).filter_by(id=int(param)).first() return render("admin/userEdit.mako") if id == "source_rerun" and param: c.source = Session.query(Source).filter_by(id=int(param)).first() contest = Session.query(Contest).filter_by( id=c.source.contest_id).first() result = c.source.run(contest, Runner, Judge) c.source.status = result['status'] c.source.points = result['points'] c.source.errors = '' sum = len(result['judges']) for i, result in enumerate(result['judges']): c.source.errors += '<li>%s/%s: %s</li>' % (i + 1, sum, result) Session.commit() return redirect_to(id="source_view") if id == "source_view" and param: c.source = Session.query(Source).filter_by(id=int(param)).first() c.user = Session.query(User).filter_by(id=c.source.user_id).first() c.task_name = self._getTaskName(c.source.task_id) return render("admin/viewSource.mako") if id == "sources" and param: c.user = Session.query(User).filter_by(id=int(param)).first() c.sources = Session.query(Source).filter_by( user_id=int(param)).order_by( sources_table.c.datetime.desc()).all() c.getTaskName = self._getTaskName c.taskExists = self._taskExists return render("admin/userSources.mako") c.users = Session.query(User).order_by(users_table.c.lname, users_table.c.fname).all() return render('admin/user.mako')
def _getTaskName(self, id): task = Session.query(Task).filter_by(id=id).first() if task: return task.name
def commit(self): self._save(self.source) self.datetime = datetime.datetime.now() Session.commit()
def _remove(self): Session.execute(tasks_table.delete().where(tasks_table.c.id==self.task.id)) Session.execute(sources_table.delete().where(sources_table.c.task_id==self.task.id)) Session.commit()
def index(self): c.list = Session.query(Contest).filter_by(is_running=False).filter(Contest.timeStart!=None).all() return render('archiv.mako')
def _load(self, id): self.task = Session.query(Task).filter_by(id=id).first() self.contest = Session.query(Contest).filter_by(id=self.task.contest_id).one() self.task.load()
def _save(self): r = Runner(request.params['lang'], request.params['compile'], request.params['run']) Session.add(r) Session.commit()
def saveFile(self, file): self.name = file.filename Session.commit() f = open(self._getFileName(), 'w') f.write(file.value)
def _remove(self, id): Session.execute(contests_table.delete().where(contests_table.c.id==int(id))) Session.execute(tasks_table.delete().where(tasks_table.c.contest_id==int(id))) Session.execute(sources_table.delete().where(sources_table.c.contest_id==int(id))) Session.commit()
def _reset(self, id): self._loadContest(id) self.contest.timeStart = None Session.commit()
def _getContestsList(self): return Session.query(Contest).all()
def contest(self, id): c.list = Session.query(Task).filter_by(contest_id=id).all() c.okUsers = self._okUsers c.allUsers = self._allUsers return render('archivTasks.mako')