def create_db(): question = Question( text="Who is you father?", choices={ "A": "Darth Vader", "B": "Emperor", "C": "Bail Organa", "D": "Obi-Wan Kenobi", "E": "None of the above" } ) question.save() luke = User(name='Luke') luke.save() luke_answer = Answer( choice="A", question=question, submitted_by=luke ) luke_answer.save() leia = User(name='Leia') leia.save() leia_answer = Answer( choice="C", question=question, submitted_by=leia ) leia_answer.save()
def load(): first_page = Page(url="http://www.example.com") first_page_key = first_page.put() first_q = Question( q="איפה זה האזור הממוזג?", who="קובי", page=first_page_key, answers=[ Answer(a="אנא עארף?", who="בניד"), Answer( a="לא יודע, אבל נשמע נעים", who="יוסי", ), ], ).put_async() second_q = Question( q="מה היה הנזק מסופת הטורנדו החזקה בהיסטוריה?", who="קובי", page=first_page_key, answers=[ Answer( a="לא יודע", who="בניד", ), ], ).put_async()
def seed(): reset_db() userlist = [ User(first_name='Max', last_name='HvA'), User(first_name='Menno', last_name='HvA'), User(first_name='Robert', last_name='HvA') ] for user in userlist: user.hash_password('qwerty') quizlist = [ Quiz(name='My first time using JavaScript', user_id=1), Quiz(name='JavaScript functions', user_id=2) ] questionlist = [ Question(name='Printing', description='Print out Hello World!', answer='Hello World!', quiz_id=1), Question( name='Adding up the numbers', description='Use your knowledge to add up the numbers 1 and 2', answer='3', quiz_id=1), Question(name='Multiplying numbers', description='Multiply 5 by 4', answer='20', quiz_id=1) ] answerlist = [ Answer(input='console.log("Hello World!")', user_id=1, question_id=1), Answer(input='1+2', user_id=1, question_id=2), Answer(input='5*4', user_id=1, question_id=3), ] for user in userlist: session.add(user) session.commit() for quiz in quizlist: session.add(quiz) session.commit() for question in questionlist: session.add(question) session.commit() for answer in answerlist: session.add(answer) session.commit()
def guardarResp(question, resp, attrib): """ Esta funcion guarda la respuesta :Param question: Object :Param resp: String :Param attrib: String or None """ if attrib is not None: a = Answer(respuesta=question, text_resp=resp, es_correcta=True) a.save() else: a = Answer(respuesta=question, text_resp=resp, es_correcta=False) a.save()
def guardar_resp_dict(resp_dict, question): """ Esta funcion guarda la respuesta :Param resp_dict: Dict :Param question: Object """ resp = resp_dict.get('correcta') if resp is not None: a = Answer(respuesta=question, text_resp=resp, es_correcta=True) a.save() else: resp = resp_dict.get('incorrecta') a = Answer(respuesta=question, text_resp=resp, es_correcta=False) a.save()
def gen_math(): operation = random.randint(0, 2) # 0 add 1 sub 2 mult if operation > 1: first_num = random.randint(1, 15) second_num = random.randint(1, 15) else: first_num = random.randint(1, 40) second_num = random.randint(1, 40) if operation is 0: question = "What is %d + %d" % (first_num, second_num) correct_answer = first_num + second_num other_answer1 = first_num * second_num other_answer2 = first_num - second_num other_answer3 = (first_num - random.randint(2, 4)) + second_num elif operation is 1: question = "What is %d - %d" % (first_num, second_num) correct_answer = first_num - second_num other_answer1 = first_num - (random.randint(2, 5) + second_num) other_answer2 = first_num + second_num other_answer3 = (first_num - random.randint(3, 6)) - second_num else: question = "What is %d * %d" % (first_num, second_num) correct_answer = first_num * second_num other_answer1 = first_num * (random.randint(2, 3) + second_num) other_answer2 = first_num + second_num other_answer3 = (first_num + random.randint(2, 5)) * second_num q = Question(text=question) db.session.add(q) db.session.flush() db.session.refresh(q) ca = Answer(text=str(correct_answer), question_id=q.id) oa1 = Answer(text=str(other_answer1), question_id=q.id) oa2 = Answer(text=str(other_answer2), question_id=q.id) oa3 = Answer(text=str(other_answer3), question_id=q.id) answers = [ca, oa1, oa2, oa3] random.shuffle(answers) for a in answers: db.session.add(a) db.session.flush() db.session.refresh(ca) q.correct_answer_id = ca.id db.session.add(q) db.session.commit()
def set_answer(puzzle_name, player_id, question, content_type, content): player = Player.get(Player.id == player_id) puzzle, _ = Puzzle.get_or_create(name=puzzle_name) try: answer = Answer.get((Answer.puzzle == puzzle) & (Answer.player == player)) except Answer.DoesNotExist: answer = Answer(puzzle=puzzle, player=player) answer.question = question if content_type == 'text': answer.value = content elif content_type == 'image': filename = '%s_%s.jpg' % (puzzle.id, player.id) path = '%s/images/%s' % (STATIC_DIR, filename) with open(path, 'wb') as fp: fp.write(content) answer.value = 'image:' + filename elif content_type == 'video': filename = '%s_%s.mp4' % (puzzle.id, player.id) path = '%s/videos/%s' % (STATIC_DIR, filename) with open(path, 'wb') as fp: fp.write(content) answer.value = 'video:' + filename answer.save()
def _answer_question(db): # Parse params answer = request.form.get('answer') to_number = request.form.get('to_number') from_number = request.form.get('from_number') # Get user who asked question web_user = db.session.query(User).filter_by(phone_number=to_number).first() # Get last question web_user asked question = db.session.query(Question).filter_by(user_id=web_user.id).all() question_id = question[-1].id # Instantiate Answer object answer = Answer(answer=answer, to_number=to_number, from_number=from_number, question_id=question_id) # Add answer to db db.session.add(answer) db.session.commit() return 'Answer submitted.'
def add_answer(): answer_content = request.form.get('answer_content') question_id = request.form.get('question_id') answer = Answer(content=answer_content, author=g.user, question_id=question_id) db.session.add(answer) db.session.commit() return redirect(url_for('detail', question_id=question_id))
def edit_question(question_id=-1): form = NewQuestionForm(request.form) #answerzip = zip(form.answers, form.validities) answers = [] if request.method == 'POST' and form.validate_on_submit(): for answer in form.answers: answers.append( Answer(text=answer.answer.data, is_correct=answer.is_correct.data)) question = Question.query.get(question_id) question.text = form.question.data Answer.query.filter(Answer.question_id == question.id).delete() question.answers = answers db.session.add(question) db.session.commit() return redirect(url_for('topic_questions', topic_id=question.topic.id)) question = Question.query.get(question_id) for i in range(2): form.answers.pop_entry() form.question.data = question.text for answer in question.answers: answer_form = AnswerForm() answer_form.answer = answer.text answer_form.is_correct = answer.is_correct form.answers.append_entry(answer_form) return render_template('question.html', title='New Question', form=form)
def text_ans(loads): ''' parse answers for text_ans question ''' #TODO:move to helpers answers = [Answer(text=i, right=True) for i in loads.get('answers', False)] return answers
def add_answer(): question_id = request.form.get('question_id') content = request.form.get('answer_content') answer = Answer(content=content, report_reasons_and_times='A@0|B@0|C@0|D@0', report_total=0) user_id = session.get('user_id') user = User.query.filter(User.id == user_id).first() user.number_of_comment = user.number_of_comment + 1 user.point = user.point + 10 if user.point >= 50 and user.point < 100: user.grade = 2 elif user.point >= 100 and user.point < 200: user.grade = 3 elif user.point >= 200 and user.point < 500: user.grade = 4 elif user.point < 50 and user.point >= 0: user.grade = 1 else: user.grade = 5 answer.author = user # answer.author_id = user_id answer.question = Question.query.filter(Question.id == question_id).first() db.session.add(answer) db.session.commit() return redirect(url_for('detail', question_id=question_id))
def load_question_blueprints() -> Sequence[QuestionBlueprint]: with open("db/questions.json") as f: data = json.load(f) question_types = [] for question_data in data: answers = [] for answer_data in question_data.get("answers", []): answers.append( Answer( text=answer_data.get("text"), imageUrl=answer_data.get("imageUrl"), audioUrl=answer_data.get("audioUrl"), traitValue=answer_data["traitValue"], ) ) question_types.append( QuestionBlueprint( questionId=question_data["questionId"], questionText=question_data["questionText"], questionFormat=question_data["questionFormat"], villagerTrait=question_data["villagerTrait"], answers=answers, generateSource=question_data.get("generateSource"), generateSourceCategory=question_data.get("generateSourceCategory"), ) ) return question_types
def upload_questions(): form = ImportQuestionsForm() if form.validate_on_submit(): Question.query.delete(synchronize_session='fetch') Answer.query.delete(synchronize_session='fetch') UserAnswer.query.delete(synchronize_session='fetch') User.query.update( { User.points: None, User.start_time: None, User.end_time: None }, synchronize_session='fetch') db.session.commit() with form.file.data.stream as ff: x = json.load(ff) for question in x: q = Question(id=question['num'], title=question['statement'], points=question['points'], text=question['extra'] or None, number=question['num'] * 10) for i, answer in enumerate(question['choices']): a = Answer(text=answer, is_correct=(i == question['correct']), question_id=question['num']) db.session.add(a) db.session.add(q) db.session.commit() flash('Успешно импортировано!', 'success') else: for err in form.file.errors: flash(err) return redirect(url_for('manage_questions'))
def save(self): self.cleaned_data['author'] = self._user self.cleaned_data['question'] = Question.objects.get( id=self.cleaned_data['question']) answer = Answer(**self.cleaned_data) answer.save() return answer
def question_detail_page(qid, subject): """ Show detail on question and all answers / if Post, handle answer """ form = AnswerForm() question = Question.query.get_or_404(qid) answers = db.session.query(Answer).filter_by(questionID=question.id).all() if form.validate_on_submit(): # handle answer form answer = Answer( content=form.answer.data, authorID=g.user.id, questionID=question.id, # upvotes=1 ) db.session.add(answer) db.session.commit() question.answered = True db.session.add(question) db.session.commit() return redirect(f'/q/{subject}/{qid}') return render_template('board/question-detail.html', question=question, answers=answers, form=form)
def manage_questions(): form = AddQuestionForm() import_form = ImportQuestionsForm() if form.validate_on_submit(): q = Question(title=form.question.data, text=form.caption.data, points=form.points.data, number=form.number.data) db.session.add(q) db.session.commit() for answer in form.answers.data.split('\n'): a = Answer(question_id=q.id) if answer.startswith('+'): answer = answer.replace('+', '', 1).lstrip() a.is_correct = True a.text = answer db.session.add(a) db.session.commit() return redirect(url_for('manage_questions')) q = Question.query.order_by(Question.number).all() if not q: form.number.data = 0 else: form.number.data = q[-1].number + 10 form.points.data = 1 return render_template('questions.html', form=form, questions=Question.query.all(), show_correct=True, editable=True, import_form=import_form, shuffle=(lambda x: x))
def admin_answer(key,question_id): sql = mysql() datakey = sql.select('keyword') length = len(datakey) all = 0 for i in range(length): if all > 10: break num = 0 for j in range(5): if datakey[i][j+3] in key: num += 1 if num > 2: all += 1 #content = datakey[i][1]+": "+datakey[i][2] content = '<span>'+datakey[i][1]+'<a href="'+ datakey[i][2]+'" target="_blank">点击查看</a></span>' answer = Answer(content=content) user = User.query.filter(User.isAdmin == 1).first() print user if user: answer.author = user question = Question.query.filter(Question.id == question_id).first() answer.question = question db.session.add(answer) db.session.commit()
def form_valid(self, form): Questions = form.instance.QuestionSet.Questions.all() request = self.request.POST form.clean() for question in Questions: if request.__contains__(str( question.pk)) and request.get(str(question.pk)) != '': if Answer.objects.filter(Question=question.pk, Survey=form.instance.pk).exists(): newAnswear = Answer.objects.get(Question=question.pk, Survey=form.instance.pk) newAnswear.Options.clear() else: newAnswear = Answer(Question=question, Survey=form.instance) newAnswear.save() if question.InputType.pk == settings.TEXT_ID: newAnswear.Text = request.get(str(question.pk)) if question.InputType.pk == settings.NUMERIC_ID: newAnswear.Numeric = request.get(str(question.pk)) if question.InputType.pk == settings.BOOL_ID: newAnswear.Bool = bool(int(request.get(str(question.pk)))) if question.InputType.pk == settings.OPTIONS_ID: for option in request.getlist(str(question.pk)): selectedOption = GetOption(option) newAnswear.Options.add(selectedOption) newAnswear.save() else: if Answer.objects.filter(Question=question.pk, Survey=form.instance.pk).exists(): Answer.objects.filter(Question=question.pk, Survey=form.instance.pk).delete() return super(FillSurvey, self).form_valid(form)
def test_three_questions_one_answer(self): for i in range(3): question = Question(text='Question {}?'.format(i)) db.session.add(question) db.session.commit() answer = Answer( question_id=question.id, text='My answer.', application_id=self.application.id, ) db.session.add(answer) db.session.commit() result = get_answers(self.applicant.id, current_user=self.recruiter) self.assertIsInstance(result, dict) self.assertEqual(len(result['questions']), 3) for question_id, answer_data in result['questions'].items(): self.assertIsInstance(question_id, int) self.assertIsInstance(answer_data['question'], str) self.assertIsInstance(answer_data['answer'], str) self.assertEqual(answer_data['user_id'], self.applicant.id) self.assertEqual(len(answer_data), 3, answer_data) if question_id != answer.question_id: self.assertEqual(answer_data['answer'], '', answer) self.assertEqual(result['questions'][answer.question_id]['answer'], 'My answer.')
def set_answers(user_id, answers=None, current_user=None): if not user_id: user_id = current_user.id if current_user else None if not current_user.id == user_id: raise ForbiddenException( f'User {current_user.id} is not permitted to answer for {user_id}') application = Application.get_for_user(user_id) if not application: raise ForbiddenException(f'User {user_id} is not an applicant') elif application.is_submitted: raise ForbiddenException( f'Cannot modify answers to a submitted application') for answer in answers: answer_record = Answer.query.filter_by( question_id=answer['question_id'], application_id=application.id).one_or_none() if not answer_record: answer_record = Answer(question_id=answer['question_id'], text=answer.get('text', ''), application_id=application.id) db.session.add(answer_record) else: answer_record.text = answer.get('text', '') db.session.commit() db.session.commit()
def topic_detail(id): user = checkUser() topics = Topic.query.filter_by(id=id).all() if len(topics) == 0: topic = '' else: topic = topics[0] if request.method == 'GET': page = request.args.get('page_ans', 1, type=int) pagination_ans = Answer.query.filter_by(topic_id=topic.id).paginate( page, per_page=1, error_out=False) writer = Users.query.filter_by(id=topic.user_id).all()[0] if len(pagination_ans.items) == 0: return render_template( 'topic.html', topic=topic, user=user, base64=base64, writer=writer, ) else: answer = pagination_ans.items[0] comments = Comments.query.filter_by(answer_id=answer.id).all() comment = [] for c in comments: c_user = Users.query.filter_by(id=c.user_id).all()[0] c.user_name = c_user.name comment.append(c) like = [] if len(user): like = Likes.query.filter( and_(Likes.user_id.like(user.id), Likes.comment_id.like(answer.id))).all() if len(like): answer.canLike = True else: answer.canLike = False u = Users.query.filter_by(id=answer.user_id).all()[0] answer.user_name = u.name answer.user_image = u.image return render_template('topic.html', topic=topic, user=user, base64=base64, writer=writer, anwsers=answer, pagination_ans=pagination_ans, comment=comment) if request.method == 'POST': content = request.form.get('content') answer_count = user.answer_count + 1 Users.query.filter_by(id=user.id).update( {'answer_count': answer_count}) ans = Answer(id=str(uuid1()), user_id=user.id, topic_id=id, content=content) db.session.add(ans) db.session.commit() return redirect('/topic/' + topic.id)
def test_answer_grade_retuns_1_when_correct(): """ Assumption: when an answer is correct it should return 1 else 0 :return: """ question = QuestionBuilder.create_question() answer = Answer(question, question._correct_choice) assert answer.grade() == Decimal(1)
def del_answer(): answer = Answer(id=request.form.get('answer_id')) answer_model = Answer.query.filter(Answer.id == answer.id).first() question_id = request.form.get('question_id') db.session.delete(answer_model) db.session.commit() return redirect(url_for('detail', question_id=question_id))
async def respond(self, ctx, *, response): global eightball current_answer_list = eightball.search(query.name == response) if len(current_answer_list) > 0: await ctx.send("Thats already a response") else: eightball.insert(vars(Answer(response))) await ctx.send("Registered new response!")
def post(self): # TODO(tavi) Error response if there's an issue. data = dict(request.json) answer = Answer(text=data[Answer.text.name], question_id=data[Answer.question_id.name]) db.session.add(answer) db.session.commit() return success_response()
def form_valid(self, form): for f in form.forms: answer = Answer(user=self.candidate, question=f.instance, answer=f.cleaned_data['answer']) answer.save() return super(GetTest, self).form_valid(form)
def add_answer(question_id, answer): session = Session() answerObj = Answer(question_id=question_id, answer=answer, created_at=utils.ctime()) session.add(answerObj) session.commit() return _get_current_ratio(question_id, answer)
def add_answer(): request_body = request.get_json() now = datetime.datetime.now() answer = Answer(id_question=request_body["id_question"], id_user=request_body["id_user"], description=request_body["description"], link=request_body["link"], created=now, last_update=now) answer.save() DBManager.commitSession() return jsonify({"status": "OK", "msg": "Answer added", "answer": answer.serialize()}), 200
def save(self, question): """ 保存表单数据 """ content = self.content.data user = current_user answer_obj = Answer(content=content, user=user, question=question) db.session.add(answer_obj) db.session.commit() return answer_obj