def init(self): Question.clear() Answer.clear() q1 = Question.create(text="Preferred date", order=1) Answer.create(question_key=q1, text="Thu 18/02", order=1, value=1) Answer.create(question_key=q1, text="Fri 19/02", order=2, value=2) Answer.create(question_key=q1, text="Sat 20/02", order=3, value=3) Answer.create(question_key=q1, text="Sun 21/02", order=4, value=4) Answer.create(question_key=q1, text="Mon 22/02", order=5, value=5) Answer.create(question_key=q1, text="Tue 23/02", order=6, value=6) Answer.create(question_key=q1, text="Wed 24/02", order=7, value=7) Answer.create(question_key=q1, text="Thu 25/02", order=8, value=8) Answer.create(question_key=q1, text="Fri 26/02", order=9, value=9) q2 = Question.create(text="Preferred place", order=2) Answer.create(question_key=q2, text="Reading", order=1, value=1) Answer.create(question_key=q2, text="Staines", order=2, value=2) Answer.create(question_key=q2, text="London", order=3, value=3) User.create('Igor') User.create('Justin') User.create('Michael') User.create('Adam') User.create('Victor') User.create('Yargi') User.create('Varun') return 200
def mutate(root, info, question_data): errors = {} current_user = get_jwt_identity() user = UserModel.find_by_id(current_user["id"]) if not user: errors["user"] = "******" category = CategoryModel.find_by_id(question_data["category_id"]) if not category: errors["category"] = "not found" location = CityModel.find_by_id(question_data["location_id"]) if not location: errors["location"] = "not found" if errors: raise GraphQLError(json.dumps(errors)) del question_data["category_id"] del question_data["location_id"] question = QuestionModel(created_by=user, category=category, location=location, **question_data) question.save() return CreateQuestion(question=question, ok=True)
def test_sort_order(self): Question.create(text="This is question 1", order=2) Question.create(text="This is question 2", order=1) questions = Question.all() self.assertEquals(1, questions[0].order) self.assertEquals(2, questions[1].order)
def test_herding(self): Question(title="Pickles").put() Question(title="Mr. Sparkles").put() r = self.testapp.get('/questions') assert "Pickles" in r assert "Mr. Sparkles" in r
def post(self): form = ReportForm() if form.validate_on_submit(): question = Question(user_id=current_user.id, title=form.title.data, detail=form.detail.data) question.save() return redirect(url_for('user.report')) return render_template('user/question/report.html', form=form)
def import_questions(): for line in [line for line in questions.splitlines() if line != ""]: # Split by the first period. question_number, text = line.split('.', 1) question_category = None for category in category_mappings: if int(question_number) in category_mappings[category]: question_category = category # Create the new question. Question.create(text.strip(), question_category, int(question_number.strip()))
def mutate(root, info, question_id, answer_data): errors = {} current_user = get_jwt_identity() user = UserModel.find_by_id(current_user["id"]) if not user: errors["user"] = "******" question = QuestionModel.find_by_id(question_id) if not question: errors["question"] = "not found" if errors: raise GraphQLError(json.dumps(errors)) answer = AnswerModel(created_by=user, **answer_data) answer.save() if question.answers: question.answers.append(answer) else: question.answers = [answer] question.save() return AnswerQuestion(answer=answer, ok=True)
def mutate(root, info, question_id, file_name): errors = {} current_user = get_jwt_identity() user = UserModel.find_by_id(current_user["id"]) if not user: errors["user"] = "******" question = QuestionModel.find_by_id(question_id) if not question: errors["question"] = "not found" if user != question.created_by: errors["user"] = "******" if file_name not in question.images: errors["question"] = "does not have an image called {}".format( file_name) if errors: raise GraphQLError(json.dumps(errors)) file_path = ROOT_PATH + url_for("static", filename="img/{}".format(file_name)) os.remove(file_path) question.images.remove(file_name) question.save() return DeleteImg(question=question, ok=True)
def mutate(root, info, question_id, reaction_data): errors = {} current_user = get_jwt_identity() user = UserModel.find_by_id(current_user["id"]) if not user: errors["user"] = "******" question = QuestionModel.find_by_id(question_id) if not question: errors["question"] = "not found" if errors: raise GraphQLError(json.dumps(errors)) reaction = ReactionModel(user=user, **reaction_data) if not question.reactions: question.reactions = [reaction] else: old_reaction = list( filter(lambda r: r.user == reaction.user, question.reactions)) if old_reaction: if old_reaction[0].reaction != reaction.reaction: question.reactions.remove(old_reaction[0]) question.reactions.append(reaction) else: question.reactions.append(reaction) question.save() return ReactToQuestion(question=question, reactions=question.reactions, ok=True)
def question_detail(page=1, page_size=20): """回答详情""" g.page_type = '' g.title = u'回答详情' args = request.args question_id = toint(args.get('question_id', '0')) uid = toint(args.get('uid', '0')) check_type = toint(args.get('check_type', '1')) query_type = toint(args.get('query_type', '1')) user = User.get(uid) if not user: return u'找不到用户' question = Question.get(question_id) if not question: return u'找不到提问的问题' qa_query = QuestionAnswer.query.filter(QuestionAnswer.uid == uid).\ filter(QuestionAnswer.question_id == question_id) qa_count = get_count(qa_query) qa_list = qa_query.order_by(QuestionAnswer.add_time.desc()).\ offset((page-1)*page_size).limit(page_size).all() pagination = Pagination(None, page, page_size, qa_count, None) return render_template('user/question_detail.html.j2', f=question, **locals())
def upload_img(question_id): if 'img' not in request.files: print("'img' key not found") abort(404) # Not Found file = request.files['img'] if file.filename == '': abort(400) # Bad Request question = Question.find_by_id(question_id) if not question: print("Question not found") abort(404) # Not Found file_name = file.filename _, ext = file_name.rsplit('.', 1) if ext.lower() not in ALLOWED_FORMATS: abort(406) # Not Acceptable file_name = "{}.{}".format(token_urlsafe(16), ext) path = ROOT_PATH + url_for("static", filename="img/{}".format(file_name)) file.save(path) if question.images: question.images.append(file_name) else: question.images = [file_name] question.save() return redirect(url_for("web.img", file_name=file_name))
def bulk_create_question(db: Session, input: List[CreateQuestionInput]): questions = [] for inp in input: questions.append(Question(**inp.dict())) db.add_all(questions) db.commit() return questions
def setUp(self): super(QuestionModelTests, self).setUp() self.question1 = Question() self.question1.text = 'Fake text' self.question1.category = 'adm' self.question1.question_number = 120 self.question1.put() self.question2 = Question() self.question2.text = 'Fake text' self.question2.category = 'fai' self.question2.question_number = 121 self.question2.put() self.question3 = Question() self.question3.text = 'Fake text' self.question3.category = 'int' self.question3.question_number = 122 self.question3.put()
def create_question(): """Creates and returns the question that adheres to the content of the request. If there is an error, an error response will be returned instead. """ data = json.loads(request.data) if not ('text' in data): raise Exception('Error: Question text is required.') if not ('answer' in data): raise Exception('Error: Question answer is required.') if not ('choices' in data): raise Exception('Error: Question answer choices are required.') #validate question? yeesh... let's keep it simple for now... question = Question(text=str(data['text']), answer=str(data['answer']), choices=str(data['choices'])) db.session.add(question) db.session.commit() return json_response(question.to_dict(), 201)
def postInsertAlgoQuestion(): requestData = request.get_json() # Error in parameters if "filename" not in dict(requestData): # Response return jsonify({ 'success': False, "message": "Please provide the 'filename' field in the body" }) filename = requestData['filename'] # Other question propertiess questionObj = deepcopy(requestData) del questionObj["filename"] try: questions = readProgrammingQuestions(filename) for question in questions: status, msg, id = Question(question, type=QuestionType.ALGO).insert_one() questionObj["body"] = question['body'] if not status: Question({ "body": question['body'] }, type=QuestionType.ALGO).update_one(questionObj) print(f"-- {msg} ---") return jsonify({"success": True, "message": "Questions are obtained!"}) except Exception as e: raise e # Response return jsonify({"success": False, "message": str(e)})
def test_sorting_by_order(self): question_key = Question.create(text="Q1", order=1) Answer.create(question_key=question_key, text="Answer 1", value=1, order=3) Answer.create(question_key=question_key, text="Answer 2", value=2, order=1) Answer.create(question_key=question_key, text="Answer 3", value=3, order=2) answers = Answer.by_question(question_key) self.assertEquals(1, answers[0].order) self.assertEquals(2, answers[1].order) self.assertEquals(3, answers[2].order)
def get(self): questions = Question.objects() status = request.args.get('status') if status == QUESTION_STATUS['NO_ANSWER']: questions = Question.objects(response=None) elif status == QUESTION_STATUS['ANSWER']: questions = Question.objects(response__ne=None) else: status = QUESTION_STATUS['ALL'] questions = Question.objects() questions = sorted(questions, key=lambda k: k.create_time, reverse=False) return render_template('admin/question/list.html', questions=questions, QUESTION_STATUS=QUESTION_STATUS, status=status)
def create_and_save_question(title, text, is_mcq, answers, room): ''' Helper to create a question and save it to the graph :param name: the name of the question :param active: whether or not this question will be active by default :param admin_id: the user id representing the admin :param course_id: the course code / id representing the course that this question studies :return ValueError: raised if either the course or user cannot be found in the graph ''' new_question = Question(title=title, text=text, is_multiple_choice=is_mcq) new_question.save() new_question.room.connect(room) for a in answers: temp_answ = Answer(text=a.get('text'), correct=a.get('correct')) temp_answ.save() temp_answ.question.connect(new_question) return new_question
def post(self, question_id): form = ResponseForm() if form.validate_on_submit(): question = Question.objects(id=question_id).first() if question.response == None: question.response = form.response.data question.response_time = datetime.datetime.utcnow() question.save() return redirect(url_for('admin.response_list', status=QUESTION_STATUS["ANSWER"])) return render_template('admin/question/response.html', form=form)
class QuestionModelTests(GaeTestCase): def setUp(self): super(QuestionModelTests, self).setUp() self.question1 = Question() self.question1.text = 'Fake text' self.question1.category = 'adm' self.question1.question_number = 120 self.question1.put() self.question2 = Question() self.question2.text = 'Fake text' self.question2.category = 'fai' self.question2.question_number = 121 self.question2.put() self.question3 = Question() self.question3.text = 'Fake text' self.question3.category = 'int' self.question3.question_number = 122 self.question3.put() def test_pretty_category_returns_properly(self): self.assertEqual('Administration (Leadership)', self.question1.pretty_category) def test_get_all_questions_returns_all_questions(self): self.assertEqual(3, len(Question.get_all_questions())) def test_get_all_questions_ordered_returns_ascending_order(self): questions = Question.get_all_questions(True) self.assertEqual(120, questions[0].question_number) self.assertEqual(121, questions[1].question_number) self.assertEqual(122, questions[2].question_number)
def postInsertQuestion(): requestData = request.get_json() # Error in parameters if "filename" not in dict(requestData): # Response return jsonify({ 'success': False, "message": "Please provide the 'filename' field in the body" }) filename = requestData['filename'] # Other question propertiess questionObj = deepcopy(requestData) del questionObj["filename"] # Reading the questions from the given file questions = readQuestions(filename) try: for question in questions: questionObj["body"] = question status, msg, id = Question(questionObj).insert_one() if not status: Question({"body": question}).update_one(questionObj) print(f"-- {msg} ---") return jsonify({"success": True, "message": "Questions are obtained!"}) except Exception as e: # Response return jsonify({"success": False, "message": str(e)})
def _get_questions_for_survey_page(self, page_num): """ Gets a page of the survey. """ if not page_num: raise ValueError('page_num is required') if type(page_num) != int: page_num = int(page_num) if page_num <= 0: raise ValueError('page_num must be 1 or higher') from_number, to_number = self._calculate_from_and_to_for_page_number(page_num) return Question.get_questions_by_number_range(from_number, to_number)
def create_question(cid): course = Course.query.filter_by(cid=cid).first_or_404() form = QuestionCreateForm().validate_for_api() with db.auto_commit(): question = Question(title=form.title.data, content=form.content.data, course_id=course.cid, author_gid=g.user['gid'], update_time=int(datetime.now().timestamp())) history = History(root_question=question) for tag_name in form.tags.data: tag = Tag.get_or_create_tag(tag_name) question.tags.append(tag) db.session.add(question, history) return Success()
def post(self): form = ResponseForm() if form.validate_on_submit(): question = Question.objects(id=form.question_id.data).first() print(question.title) if question.response == None: question.response = form.response.data question.response_time = datetime.datetime.utcnow() question.save() return redirect( url_for('admin.question', status=QUESTION_STATUS["ANSWER"])) return render_template('admin/management/question.html', form=form)
def test_correct_questions_returned_for_page_higher_than_one(self, questions_mock): question21 = Question() question21.text = "Fake text" question21.category = "adm" question21.question_number = 21 question22 = Question() question22.text = "Fake text" question22.category = "fai" question22.question_number = 22 questions_mock.return_value = [ question21, question22 ] actual, _, _ = self.survey.get_survey_page(2) expected = [ {"question_number": 21, "text": "Fake text", "answer": None, "category": "adm"}, {"question_number": 22, "text": "Fake text", "answer": None, "category": "fai"} ] self.assertEqual(expected, actual)
def test_get_all_questions_ordered_returns_ascending_order(self): questions = Question.get_all_questions(True) self.assertEqual(120, questions[0].question_number) self.assertEqual(121, questions[1].question_number) self.assertEqual(122, questions[2].question_number)
def test_get_all_questions_returns_all_questions(self): self.assertEqual(3, len(Question.get_all_questions()))
def get(self): context = { 'questions': Question.get_all_questions(ordered=True) } self.render_response('superadmin/print_questions.html', **context)
def test_180_questions_created_after_migration(self): self.assertEqual(180, len(Question.get_all_questions()))
def get(self, question_id): form = ResponseForm() question = Question.objects(id=question_id).first() return render_template('admin/question/response.html', form=form, question=question)
def testQueries(self): # log in user one self.loginUser('*****@*****.**') # create two Questions Question1 = Question(title="Question 1") Question1.put() Question2 = Question(title="Question 2") Question2.put() # log in user two self.loginUser('*****@*****.**') # create two more Questions Question3 = Question(title="Question 3") Question3.put() Question4 = Question(title="Question 4") Question4.put() # Get all Questions all_Questions = list(Question.all_questions()) # Make sure there are 4 Questions in total assert len(all_Questions) == 4 # Make sure they're in the right order assert all_Questions == [Question4, Question3, Question2, Question1] # Make sure we only get two for user2, and that they're the right Questions user2_Questions = list(Question.all_questions_by_user()) assert len(user2_Questions) == 2 assert user2_Questions == [Question4, Question3] # Test all Questions shown up resp = self.testapp.get('/questions') assert 'Question 1' in resp.body assert 'Question 2' in resp.body assert 'Question 3' in resp.body assert 'Question 4' in resp.body # Test Questions_created_by_user resp = self.testapp.get('/questions?=mine') # assert 'Question 1' not in resp.body # assert 'Question 2' not in resp.body # assert 'Question 3' in resp.body # assert 'Question 4' in resp.body # Test 'edit' link exists assert 'Edit' in resp.body
def resolve_question(root, info, _id): question = QuestionModel.find_by_id(_id) return question
def api_all_questions(self): self.context['data'] = Question.all()
def initdb(): click.echo('Initializing the database...') User.drop_collection() Post.drop_collection() Question.drop_collection() click.echo('Generating the User..') # FIXME: for i in range(1, 10): u = User( email = fake.email(), username = fake.name(), avatar = f'http://192.168.1.106:8000/avatar/r{i}.png' ) u.set_password('helloworld') u.save() click.echo('Done') click.echo('Generating the Post..') for i in range(10): p = Post( title = fake.sentence(), content = fake.text(2000), category = random.choices(['Python', 'JavaScript','Golang', 'Flask','Vue', 'Django'])[0], tags = random.choices(['Python', 'JavaScript','Golang', 'Flask','Vue', 'Django']), ) p.save() click.echo('Done') click.echo('Generating the Comment..') for i in Post.objects.all(): for j in range(5): c = Comment( author = random.choice(User.objects.all()), content = fake.text(200), ) i.comments.append(c) i.save() click.echo('Done') click.echo('Generating the Reply..') for i in Post.objects.all(): for j in range(5): c = Comment( author = random.choice(User.objects.all()), content = fake.text(200), reply = random.choice(i.comments).cid ) i.comments.append(c) i.save() click.echo('Done') click.echo('Generating the Question..') for j in range(5): q = Question( title = fake.sentence(), author = random.choice(User.objects.all()), description = fake.text(200), tags = random.choices(['Python', 'JavaScript','Golang', 'Flask','Vue', 'Django']), ) q.save() click.echo('Done') click.echo('Generating the Answer Comment..') for i in Question.objects.all(): for j in range(5): c = Answer( author = random.choice(User.objects.all()), content = fake.text(200), ) i.answer.append(c) i.save() click.echo('Done') click.echo('Generating the Answer Reply..') for i in Question.objects.all(): for j in range(5): c = Answer( author = random.choice(User.objects.all()), content = fake.text(200), reply = random.choice(i.answer)._id ) i.answer.append(c) i.save() click.echo('Done')
def _get_questions_for_survey_page(self, page_num): from_num, to_num = self._calculate_from_and_to_for_page_number(page_num) questions = self.QUESTIONS[from_num - 1:to_num] return [Question.get_by_question_number(q_num) for q_num in questions]
def create_question(db: Session, input: CreateQuestionInput): c = Question(**input.dict()) db.add(c) db.commit() db.refresh(c) return c
def test_to_number_is_required(self): with self.assertRaises(ValueError): Question.get_questions_by_number_range(50, None)
def test_create_question(self): key = Question.create(text="This is question 1", order=1) print 'key:{0}'.format(key) self.assertEquals(1, Question.query().count())
def test_number_range_21_to_40_returns_20_questions(self): import_questions() quest_range = Question.get_questions_by_number_range(21, 40) self.assertEqual(20, len(quest_range))
def findSimilarQuestions(questionBody): try: # Analyzing the question entity_tags, topics, categories = analyzeQuestion(questionBody) # Search query query = {"$or": []} # Generating the query (topic) for topic in topics: query["$or"].append({ "topics": { "$elemMatch": { "label": { "$regex": topic["label"], "$options": "i" } } } }) # No topic is found if len(topics) == 0: return None # Results after checking topic similarity questionsFromSimilarTopic = Question.findGeneric(query) # Query returns None if not questionsFromSimilarTopic: return None # Score algorithm foundQuestions = [] for question in questionsFromSimilarTopic: questionTopics = question['topics'] currentVector, questionVector = createTwoVectorsFromTopics( topics, questionTopics) cosSimilarity = round( cosineSimilarity(currentVector, questionVector) * 100, 2) foundQuestions.append({ 'question': question, 'similarity_rate': cosSimilarity }) # Sorting according to the topic score foundQuestions = sorted(foundQuestions, key=lambda x: x['similarity_rate'], reverse=True) for i in range(len(foundQuestions)): # We do not need them in the response (probably) del foundQuestions[i]['question']['entity_tags'] del foundQuestions[i]['question']['topics'] del foundQuestions[i]['question']['categories'] return foundQuestions except Exception as e: raise e return []
def get(self): questions = Question.objects(user_id=current_user.id) return render_template('user/question/list.html', questions=questions)