def problem(): form = ProblemForm() if form.validate_on_submit(): if int(form.class_level.data) > 11: flash("Выберите коректный класс") return render_template('problem.html', form=form) image = MathTextConverter.getImage(form.expression.data) current_problem = Problem(body=form.body.data, expression=form.expression.data, class_level=form.class_level.data, image=image, author=current_user) current_problem.value = TokenCalculator().calculate_task_value( current_problem) current_problem.section = form.sections.data print(current_user.tokens, current_problem.value) if current_user.tokens >= current_problem.value: current_user.tokens -= current_problem.value db.session.add(current_problem) db.session.commit() flash( f"Задача успешно создана! Она оценина в {current_problem.value} токенов \nУ вас осталось {current_user.tokens}" ) else: flash(f"Стоимость задачи {current_problem.value}") flash(f"У вас не хватает токенов") flash(f"Ваш текущий баланс {current_user.tokens} токенов") return render_template('problem.html', form=form)
def resetdb(): from app.utils import timedelta import datetime db.drop_all() db.create_all() Problem.import_from_hustoj() Role.insert_role() admin = User(email = '*****@*****.**', username = '******', password = '******', confirmed = True, role = Role.query.filter_by(name = "Administrator").first()) db.session.add(admin) db.session.commit() judger = User(email = "*****@*****.**", username = "******", password = "******", confirmed = True, role = Role.query.filter_by(name = "Judger").first()) db.session.add(judger) db.session.commit() judger = User(email = "*****@*****.**", username = "******", password = "******", confirmed = True, role = Role.query.filter_by(name = "Judger").first()) db.session.add(judger) db.session.commit() contest = Contest(title = "test", begin_time = datetime.datetime.utcnow() - timedelta(hours = 10), end_time = datetime.datetime.utcnow() + timedelta(hours = 10)) db.session.add(contest) for i in range(8): cp = ContestProblem(contest_id = 1, problem_id = i + 1, problem_relative_id = i) db.session.add(cp) db.session.commit()
def setUp(self): # establish application context and test client TestConfig.SOLUTIONS_TO_SHOW = 5 self.app = create_app(TestConfig) self.app_context = self.app.app_context() self.app_context.push() self.test_client = self.app.test_client() # create in-memory database structure db.create_all() # add a User object self.user1 = User(username='******') self.user1.set_password('pass1') db.session.add(self.user1) # add a Language object self.language1 = Language(language_id=1, language='Python', extension='py') self.language2 = Language(language_id=2, language='C++', extension='cpp') self.language3 = Language(language_id=3, language='F#', extension='fs') self.language4 = Language(language_id=4, language='F#', extension='fsx') db.session.add_all([self.language1, self.language2, self.language3, self.language4]) # add Problem objects for _ in range(10): p1 = Problem(contents="contents", language_id=self.language1.language_id, title="title") p2 = Problem(contents="contents", language_id=self.language2.language_id, title="title") db.session.add_all([p1, p2]) f1 = Problem(contents='contents', language_id=self.language3.language_id, title='title') f2 = Problem(contents='contents', language_id=self.language4.language_id, title='title') db.session.add_all([f1, f2]) db.session.commit()
def setUp(self): # establish application context and test client self.app = create_app(TestConfig) self.app_context = self.app.app_context() self.app_context.push() self.test_client = self.app.test_client() # create in-memory database structure db.create_all() # add a Language object self.language = Language(language_id=1, language='Python', extension='py') db.session.add(self.language) # add a Problem object self.problem1 = Problem(contents="arbitrary solution to problem1", language_id=self.language.language_id, title="problem1") self.problem2 = Problem(contents="arbitrary solution to problem2", language_id=self.language.language_id, title="problem2") self.problem3 = Problem(contents="arbitrary [ ] to problem3", language_id=self.language.language_id, title="problem3") db.session.add_all((self.problem1, self.problem2, self.problem3)) db.session.commit()
def test_problem_generates_correct_blocks(self): p1 = Problem(solution='(+ (- 3 2) (* 2 5))', evaluates_to='11', points=5) b1 = p1.generate_initial_data()['blocks'] self.assertEqual(b1, [['(', '<nt>', '<nt>', '<nt>', ')'], ['+'], ['(', '<nt>', '<nt>', '<nt>', ')'], ['-'], ['3'], ['2'], ['(', '<nt>', '<nt>', '<nt>', ')'], ['*'], ['2'], ['5']]) p2 = Problem(solution='(sqrt 16)', evaluates_to='11', points=5) p2 = Problem(solution='(sqrt 16)', evaluates_to='11', points=5) b2 = p2.generate_initial_data()['blocks'] self.assertEqual(b2, [['(', '<nt>', '<nt>', ')'], ['sqrt'], ['16']])
def test_to_json(self): ''' test for to_json func is good :return: None ''' oj = OJList(name='test') db.session.add(oj) db.session.commit() problem = Problem(remote_id=1, oj_id=1, title='test') db.session.add(problem) db.session.commit() problem_json = problem.to_json() self.assertTrue(problem_json['id'] == 1)
def test_problem_in_oj(self): ''' test for problem with oj is good :return: None ''' oj = OJList(name='test') db.session.add(oj) db.session.commit() problem = Problem() problem.oj_id = oj.id db.session.add(problem) db.session.commit() self.assertTrue(problem.oj.name == 'test')
def create_problem(): data = request.json problem = Problem(cui=data["cui"], patient_id=data["patient"], provider_id=data['provider_id'], name=data['problemName'], created_at=datetime.now(), type=data['type'], note=data['instructions'], current=data['current']) db.session.add(problem) db.session.commit() format_problem = problem.to_dict() return {"problem": format_problem}
def test_problem_after_delete_oj(self): ''' test for ping func is good :return: None ''' oj = OJList(name='test') db.session.add(oj) db.session.commit() problem = Problem() problem.oj_id = oj.id db.session.add(problem) db.session.commit() db.session.delete(oj) db.session.commit() self.assertTrue(Problem.query.count() == 0)
def test_problem_list(self): ''' test admin problem_list is good :return: None ''' response = self.client.get(url_for('admin.problem_list')) self.assertTrue(response.status_code == 403) u = User(username='******', password='******', email='*****@*****.**', confirmed=True) u.role_id = Role.query.filter_by(permission=0xff).first().id db.session.add(u) db.session.commit() p = Problem(title='thisisatest') db.session.add(p) db.session.commit() response = self.client.post(url_for('auth.login'), data={ 'username': '******', 'password': '******' }, follow_redirects=True) response = self.client.get(url_for('admin.problem_list')) self.assertTrue(response.status_code == 200) self.assertTrue(b'Problem List' in response.data) self.assertTrue(b'thisisatest' in response.data)
def test_user_add_problem_with_tag(self): """测试用户的添加错题功能(带标签)""" u = User() p = Problem(author=u) t = Tag(owner=u) t.add_problem(p) self.assertIn(p, t.problems.all())
def add_problem(request): if request.method == 'GET': return render(request, 'admin/create_problem.html') elif request.method == 'POST': name = request.session['email'] user = Users.objects.get(email=name) title = request.POST.get('title', '') explain = request.POST.get('my-editormd-html-code', '') cinput = request.POST.get('cinput') coutput = request.POST.get('coutput') sinput = request.POST.get('sinput') soutput = request.POST.get('soutput') hint = request.POST.get('hint') source = request.POST.get('source') public = request.POST.get('public') label = request.POST.get('label') problem = Problem(email=user, title=title, description=explain, cinput=cinput, coutput=coutput, sinput=sinput, soutput=soutput, hint=hint, source=source, public=public, label=label).save() return redirect('add_problem') return render(request, 'admin/create_problem.html')
def test_problem_timestamp(self): """测试错题的时间截""" u = User() p = Problem(author=u) db.session.add(p) db.session.commit() self.assertTrue((datetime.utcnow() - p.timestamp).total_seconds() < 3)
def test_problem_detail(self): ''' test problem_detail is good :return: None ''' p = Problem(title='test') db.session.add(p) db.session.commit() response = self.client.get(url_for('problem.problem_detail', problem_id=p.id)) self.assertTrue(response.status_code == 404) p.visible = True db.session.add(p) db.session.commit() response = self.client.get(url_for('problem.problem_detail', problem_id=p.id)) self.assertTrue(response.status_code == 200)
def test_user_add_problem_with_tag_but_deleted(self): """测试用户的添加错题功能(带标签,但错题在标签加入后被移除了)""" u = User() p = Problem(author=u) t = Tag(owner=u) t.add_problem(p) t.remove_problem(p) self.assertNotIn(p, t.problems.all())
def test_follow_problems(self): # create four users u1 = User(username='******', email='*****@*****.**') u2 = User(username='******', email='*****@*****.**') u3 = User(username='******', email='*****@*****.**') u4 = User(username='******', email='*****@*****.**') db.session.add_all([u1, u2, u3, u4]) # create four posts now = datetime.utcnow() p1 = Problem(grade=1, color='green', setter=u1, timestamp=now + timedelta(seconds=1)) p2 = Problem(grade=2, color='blue', setter=u2, timestamp=now + timedelta(seconds=4)) p3 = Problem(grade=3, color='orange', setter=u3, timestamp=now + timedelta(seconds=3)) p4 = Problem(grade=4, color='purple', setter=u4, timestamp=now + timedelta(seconds=2)) db.session.add_all([p1, p2, p3, p4]) db.session.commit() # setup the followers u1.follow(u2) # john follows susan u1.follow(u4) # john follows david u2.follow(u3) # susan follows mary u3.follow(u4) # mary follows david db.session.commit() # check the followed posts of each user f1 = u1.followed_problems().all() f2 = u2.followed_problems().all() f3 = u3.followed_problems().all() f4 = u4.followed_problems().all() self.assertEqual(f1, [p2, p4, p1]) self.assertEqual(f2, [p2, p3]) self.assertEqual(f3, [p3, p4]) self.assertEqual(f4, [p4])
def test_initial_data(self): """ Test that the initial data JSON generated by the problem is correct. """ p1 = Problem(pk=1, solution='(+ 3 (- 2 5))', points=4, evaluates_to='0') p1_initial_data = {} p1_initial_data['problem_number'] = 1 p1_initial_data['solution'] = '(+ 3 (- 2 5))' p1_initial_data['blocks'] = [['(', '<nt>', '<nt>', '<nt>', ')'], ['+'], ['3'], ['(', '<nt>', '<nt>', '<nt>', ')'], ['-'], ['2'], ['5']] p1_initial_data['evaluates_to'] = '0' p2 = Problem(pk=2131312, solution='(+ (- 3 2) (* 2 5))', points=6, evaluates_to='11') p2_initial_data = {} p2_initial_data['problem_number'] = 2131312 p2_initial_data['solution'] = '(+ (- 3 2) (* 2 5))' p2_initial_data['blocks'] = [['(', '<nt>', '<nt>', '<nt>', ')'], ['+'], ['(', '<nt>', '<nt>', '<nt>', ')'], ['-'], ['3'], ['2'], ['(', '<nt>', '<nt>', '<nt>', ')'], ['*'], ['2'], ['5']] p2_initial_data['evaluates_to'] = '11' self.assertEqual(p2_initial_data, p2.generate_initial_data())
def test_user_find_problem_with_tag(self): """测试用户根据标签寻找错题的功能""" u = User() p = Problem(author=u) t = Tag(owner=u) t.add_problem(p) self.assertEqual(0, t.find_problem(p)) t.remove_problem(p) self.assertIsNone(t.find_problem(p))
def test_problem_add_new(self): ''' test to insert into a new oj to database :return: None ''' problem = Problem() db.session.add(problem) db.session.commit() self.assertTrue(Problem.query.count() == 1)
def _add_problem(problems, title, line=None): from app.models import Problem if line: tmp = "%s: [%s]" % (title, line) else: tmp = title for problem in problems: if problem.description == tmp: return problems.append(Problem('invalid-release-description', tmp))
def create_solution(): """Route controlling creation of new solutions""" # dynamically load allowed file extensions file_upload_form = FileUploadForm() for extension in db.session.query(Language.extension).all(): file_upload_form.allowed_extensions.append(extension[0]) if file_upload_form.is_submitted(): if file_upload_form.validate(): problem_id = file_upload_form.data.get('problem_selection') # check problem_id doesn't already exist if Problem.query.filter_by(problem_id=problem_id).first() is not None: flash("A solution for that problem already exists - please specify an unsolved " "problem or update the solution", "warning") else: title = file_upload_form.data.get('problem_title') contents = file_upload_form.file_upload.data.read() contents = contents.decode('utf-8').replace('\r\n', '\n') # check content is not null if not contents: flash("File must not be empty", "warning") else: # create objects to add to database extension = file_upload_form.file_upload.data.filename.split('.')[-1] language = Language.query.filter_by(extension=extension).first() language_id = language.language_id problem = Problem(problem_id=problem_id, contents=contents, language_id=language_id, title=title) # add objects to database db.session.add(problem) db.session.commit() # clear form values file_upload_form.problem_selection.raw_data = [''] file_upload_form.problem_title.data = None flash("Solution created", "success") else: error_messages = [f.process_errors[0] for f in file_upload_form._fields.values() if f.process_errors] if error_messages: flash(error_messages[0], "warning") else: flash("An error was encountered - please review inputs and try again", "warning") return render_template('create_solution.html', file_upload_form=file_upload_form)
def create_problem(): form = CreateProblemForm() if form.validate_on_submit(): problem = Problem(title=form.title.data, body=form.body.data, time_limit=form.time_limit.data, memory_limit=form.memory_limit.data, author=current_user) db.session.add(problem) db.session.commit() flash('Your problem is now live!') return redirect(url_for('problem.problem', problem_id=problem.id)) return render_template('problem/create.html', form=form)
def save_review_list(self): Problem.query.filter_by(dataset_id=self.dataset_id).delete() commit() for corr in self.review_list: prob = Problem( dataset_id=self.dataset_id, problem=corr.problem, article_id=corr.article_id, compound_id=corr.compound_id, ) db_add_commit(prob) self.logger.info("Saved %d problems to DB", len(self.review_list))
def secret(): form = ProblemForm() if form.validate_on_submit(): problem = Problem(grade=form.grade.data, color=form.color.data, risk=form.risk.data, intensity=form.intensity.data, complexity=form.complexity.data, setter=current_user) db.session.add(problem) db.session.commit() flash('Your problem has been recorded!') return redirect(url_for('secret')) problems = Problem.query.filter_by(user_id=current_user.id) return render_template('secret.html', problems=problems, form=form)
def test_from_json(self): ''' test for from_json func is good :return: None ''' problem_dict = { 'remote_id': 1, 'title': 'test', 'description': 'test', 'oj_id': '1', } problem = Problem().from_json(problem_dict) db.session.add(problem) db.session.commit() self.assertTrue(Problem.query.get(1).title == 'test')
def test_submission(self): ''' test status part :return: None ''' u = User(username='******', password='******', email='*****@*****.**', confirmed=True) u.role_id = Role.query.filter_by(permission=0xff).first().id db.session.add(u) db.session.commit() response = self.client.post(url_for('auth.login'), data={ 'username': '******', 'password': '******' }, follow_redirects=True) p = Problem(title='test', visible=True) db.session.add(p) db.session.commit() response = self.client.post(url_for('problem.submit', problem_id=p.id), data={ 'problem_id': p.id, 'language': '1', 'code': 'helloworldsdfsdf' }, follow_redirects=True) self.assertTrue(response.status_code == 200) self.assertTrue(b'G++' in response.data) self.client.get(url_for('admin.submission_status_list')) self.assertTrue(b'G++' in response.data) self.client.get( url_for('admin.submission_status_detail', submission_id=1)) self.assertTrue(b'G++' in response.data) response = self.client.get( url_for('admin.submission_status_edit', submission_id=1)) response = self.client.post(url_for('admin.submission_status_edit', submission_id=1), data={ 'status': '1', 'exec_time': '1', 'exec_memory': '1' }, follow_redirects=True) self.assertTrue(b'Accepted' in response.data)
def test_status_with_problem_delete(self): ''' test for if the problem delete, status delete together :return: None ''' problem = Problem() db.session.add(problem) db.session.commit() status = SubmissionStatus(problem_id=problem.id) db.session.add(status) db.session.commit() self.assertTrue(status.problem_id == problem.id) db.session.delete(problem) db.session.commit() self.assertTrue(SubmissionStatus.query.count() == 0)
def test_to_json(self): ''' test for to_json func is good :return: None ''' oj = OJList() db.session.add(oj) problem = Problem(oj_id=1) db.session.add(problem) db.session.commit() status = SubmissionStatus(problem_id=problem.id) db.session.add(status) db.session.commit() status = status.to_json() self.assertTrue(status['id'] == 1)
def test_from_json_false(self): ''' test for from_json func is good :return: None ''' problem_dict = { 'remote_id': 1, 'title': 'test', 'description': 'test', } try: problem = Problem().from_json(problem_dict) db.session.add(problem) db.session.commit() except ValidationError: self.assertFalse(Problem.query.count() == 1)
def index(): form = ProblemForm() if form.validate_on_submit(): problem = Problem(grade=form.grade.data, color=form.color.data, risk=form.risk.data, intensity=form.intensity.data, complexity=form.complexity.data, setter=current_user) db.session.add(problem) db.session.commit() flash('Your problem has been recorded!') return redirect(url_for('main.index')) problems = current_user.followed_problems().all() return render_template('index.html', title='Index', problems=problems, form=form)
def test_tag_with_problem(self): ''' test insert a tag with a problem :return: None ''' tag = Tag() db.session.add(tag) db.session.commit() problem = Problem() db.session.add(problem) db.session.commit() problem_tag = TagProblem(tag=tag, problem=problem) db.session.add(problem_tag) db.session.commit() self.assertTrue(problem.tags.first().tag.id == tag.id) db.session.delete(tag) db.session.commit() self.assertTrue(problem.tags.count() == 0)
def test_contest_problem(self): ''' test for add problem to contest is good :return: None ''' contest = Contest() db.session.add(contest) db.session.commit() problem = Problem() db.session.add(problem) db.session.commit() contest_problem = ContestProblem(contest=contest, problem=problem) db.session.add(contest_problem) db.session.commit() self.assertTrue(contest.problems.first().problem.id == problem.id) db.session.delete(contest_problem) db.session.commit() self.assertTrue(contest.problems.count() == 0)
def addquestion(): data = request.get_json() # input validation if data["question"] == "": return ("ERROR: Empty Question") try: if float(data["time"]) <= 0: return ("ERROR: Please enter time > 0") except: return ("ERROR: Invalid time please enter a positive real number > 0") problem = Problem.query.filter_by(title=data["title"]).first() if problem is not None: return ("ERROR: Problem Already Exists") urltitle = ''.join((data["title"]).split()).lower() problem = Problem.query.filter_by(urlTitle=urltitle).first() if problem is not None: return ("ERROR: Problem Name to Similar to Another Problem") # add the problem p = Problem(\ title=data["title"],\ urlTitle=''.join((data["title"]).split()).lower(),\ body=data["question"],\ difficulty = data["diff"],\ timeLimit = float(data["time"]),\ ) db.session.add(p) # add all its test cases tests = data["testcases"] for i in tests: if i["input"] == "" or i["output"] == "": return ("ERROR: Empty Test Case") testcase = ProblemTestCases(\ problem = p,\ input = i["input"],\ output = i["output"], ) db.session.add(testcase) db.session.commit() return ("Succesfully Added Question")