예제 #1
0
 def setUp(self):
     """
     Extend the BaseTest setUp method by setting up
     two categories and three questions
     """
     super(TestQuestion, self).setUp()
     with self.app_context:
         self.c_1 = Category(type="Test Category 1")
         self.c_1.insert_record()
         self.c_2 = Category(type="Test Category 2")
         self.c_2.insert_record()
         self.q_1 = Question(
             question="Test Question 1?",
             answer="Test Answer 1",
             difficulty=1,
             category_id=self.c_1.id,
         )
         self.q_1.insert_record()
         self.q_2 = Question(
             question="Test Question 2?",
             answer="Test Answer 2",
             difficulty=2,
             category_id=self.c_2.id,
         )
         self.q_2.insert_record()
         self.q_3 = Question(
             question="Test Question 3?",
             answer="Test Answer 3",
             difficulty=3,
             category_id=self.c_2.id,
         )
         self.q_3.insert_record()
예제 #2
0
def createTopic(question, accountId, answerStatusId, isPoll):

    qst = Question()

    qst.Question = question
    qst.AccountId = accountId
    qst.TimeStamp = datetime.date.today()
    qst.AnswerStatusId = answerStatusId
    qst.IsPoll = isPoll
    qst.Score = 0

    db.session.add(qst)
    db.session.commit()
예제 #3
0
 def create_question(self, quiz_id, temp_question):
     """create a new question and add it to the store and to the quiz"""
     new_question = Question(**temp_question)
     self.get_quiz_by_id(quiz_id).add_question_by_id(
         new_question.question_id)
     self.questions[new_question.question_id] = new_question
     return new_question.question_id
    def find_best_split(self, rows):
        """ Find the best question to ask by iterating over every feature / value
        and calculating the information gain. """
        best_gain = 0  # keep track of the best information gain
        best_question = None  # keep train of the feature / value that produced it
        current_uncertainty = self.gini(rows)
        n_features = len(rows[0]) - 1  # number of columns minus one

        for col in range(1, n_features + 1):  # for each feature
            values = set([row[col]
                          for row in rows])  # unique values in the column

            for val in values:  # for each value
                question = Question(self.__header, col, val)

                # try splitting the dataset
                true_rows, false_rows = self.partition(rows, question)

                # Skip this split if it doesn't divide the dataset.
                if len(true_rows) == 0 or len(false_rows) == 0:
                    continue

                # Calculate the information gain from this split
                gain = self.info_gain(true_rows, false_rows,
                                      current_uncertainty)

                if gain >= best_gain:
                    best_gain, best_question = gain, question

        return best_gain, best_question
예제 #5
0
 def test_was_published_recently_with_old_question(self):
     """
     was_published_recently() should return False for an old question, older that 1 day old
     """
     in_the_past = timezone.now() - datetime.timedelta(days=2)
     q = Question(pub_date=in_the_past, question_text="anything")
     self.assertIs(q.was_published_recently(), False)
예제 #6
0
 def build_question(article) -> Question:
     return Question(title=get_title(article),
                     time=get_time(article),
                     time_relative=get_time_relative(article),
                     who_asked=get_who_asked(article),
                     answer=get_answer(article),
                     image_url=get_image_url(article))
예제 #7
0
 def test_was_published_recently_with_future_question(self):
     """
     was_published_recently() returns False for questions whose pub_date is in the future
     """
     in_the_future = timezone.now() + datetime.timedelta(days=30)
     q = Question(pub_date=in_the_future, question_text="anything")
     self.assertIs(q.was_published_recently(), False)
예제 #8
0
def update_poll(id):
    poll = Question.query.filter_by(id=id).first()
    form = QuestionForm(
        question=poll.question,
        option1=poll.options[0],
        option2=poll.options[1],
        option3=poll.options[2],
        option4=poll.options[3],
    )
    if form.validate_on_submit():
        question = form.data['question']
        option1 = form.data['option1']
        option2 = form.data['option2']
        option3 = form.data['option3']
        option4 = form.data['option4']
        poll = Question(question=question,
                        options=[
                            Options(choice=option1),
                            Options(choice=option2),
                            Options(choice=option3),
                            Options(choice=option4)
                        ])
        db.session.add(poll)
        db.session.commit()
        flash('Your poll is update now')
        return redirect(url_for(f'polls/{id}'))
    return render_template('polls/update_poll.html', poll_data=poll, form=form)
예제 #9
0
def new_poll() -> Response:
    form = QuestionForm()
    if form.validate_on_submit() and 'cover' in request.files:
        if 'cover' not in request.files:
            flash('No file')
            return redirect(request.url)

        cover = request.files['cover']
        if cover and allowed_file(cover.filename):
            filename = secure_filename(cover.filename)
            cover.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

        question = form.data['question']
        option1 = form.data['option1']
        option2 = form.data['option2']
        option3 = form.data['option3']
        option4 = form.data['option4']

        question = Question(question=question,
                            cover=secure_filename(cover.filename),
                            options=[
                                Options(choice=option1),
                                Options(choice=option2),
                                Options(choice=option3),
                                Options(choice=option4)
                            ])
        db.session.add(question)
        db.session.commit()

        flash('Your poll is added now')
        return redirect(url_for('main'))
    return render_template('polls/newpoll.html', form=form)
예제 #10
0
 def test_was_published_recently_with_recent_question(self):
     """
     was_published_recently() should return True for a question published within the last day
     """
     in_the_past = timezone.now() - datetime.timedelta(
         days=1) + datetime.timedelta(seconds=1)
     q = Question(pub_date=in_the_past, question_text="anything")
     self.assertIs(q.was_published_recently(), True)
예제 #11
0
파일: main.py 프로젝트: yamap55/peing_clone
def add_user():

    def create_user(name, password):
        salt = create_salt()
        password_hash = calculate_password_hash(password, salt)
        return User(name=name, password_hash=password_hash, salt=salt)

    db.create_all()

    user1 = create_user('a', "aa")
    user2 = create_user('b', "bb")
    user3 = create_user('c', "cc")
    db.session.add(user1)
    db.session.add(user2)
    db.session.add(user3)
    user1.questions = [Question(detail='x?', answer='yy!'), Question(detail='z?')]
    user2.questions = [Question(detail='aaa?', answer='bbb!')]
    db.session.commit()
예제 #12
0
파일: service.py 프로젝트: drootnar/Gabbie
 def add_message(self, room_id, data):
     schema = MessageSchema()
     result = schema.load(data)
     if result.errors:
         abort(400, result.errors)
     question = Question(result.data)
     self.db.session.add(question)
     self.db.session.commit()
     return question
 def __build_question(post):
     if not post:
         return None
     return Question(title=post['title'],
                     time=post['time'],
                     time_relative=None,
                     who_asked=post['who_asked'],
                     answer=post['answer'],
                     image_url=post['image_url'])
예제 #14
0
def generate_questions(conf, group_conf):
    df = group_conf['df']
    name = f"Comité exécutif {group_conf['semester']}"
    description = "Pour cette section, seulement une personne peut-être élue par poste."
    group = Group(name, description)
    postes = conf['postes_exec']

    questions = []
    questions_map = {}

    # clean poste vise
    for poste in postes:
        df.loc[df[POSTE_VISE].str.
               contains(pat=f"(?:^{postes[poste]}|{poste})", regex=True),
               POSTE_VISE] = poste

    applied_posts = [
        poste for poste in postes if poste in df[POSTE_VISE].unique().tolist()
    ]

    for i, poste in enumerate(applied_posts):
        question = Question(
            code=poste + group_conf['semester'],
            gid=group.gid,
            title=f"Qui voulez-vous au poste de {postes[poste]}?",
            qtype='L',
            order=i)

        questions.append(question)
        questions_map[poste] = question

    if 'unused_posts' not in group_conf.keys():
        group_conf['unused_posts'] = []

    for poste in postes:
        if poste not in applied_posts:
            group_conf['unused_posts'].append(poste)

    for _, candidat in df.iterrows():
        poste = candidat[POSTE_VISE]
        option = Option(nom=candidat[NOM_USUEL],
                        promotion=candidat[PROMOTION],
                        concentration=candidat[CONCENTRATION],
                        order=questions_map[poste].answer_count(),
                        description=candidat[TEXTE_DESCRIPTIF],
                        image=candidat[PHOTO])

        questions_map[poste].add_answer(option)
        questions_map[poste].add_option(option)

    for poste in questions_map:
        lachaise = Option.add_chaise(questions_map[poste].answer_count())
        questions_map[poste].add_answer(lachaise)
        questions_map[poste].add_option(lachaise)

    return group, questions
예제 #15
0
 def test_init(self):
     """Test the __init__ method for the Question class."""
     self.q = Question(
         question="Test Question?",
         answer="Test Answer",
         difficulty="1",
         category_id="2",
     )
     self.assertEqual(self.q.question, "Test Question?")
     self.assertEqual(self.q.answer, "Test Answer")
     self.assertEqual(int(self.q.difficulty), 1)
     self.assertEqual(int(self.q.category_id), 2)
예제 #16
0
파일: main.py 프로젝트: yamap55/peing_clone
def show_user_profile(user_name):
    question_form = QuestionForm()
    users = User.query.filter_by(name=user_name).all()
    if len(users) == 0:
        user = None
    else:
        user = users[0]
        if question_form.validate_on_submit():
            print('question : {}'.format(question_form.question.data))
            question = Question(detail=question_form.question.data, user_id=user.id)
            db.session.add(question)
            db.session.commit()
    return render_template('user_profile.html', user=user, form=question_form)
예제 #17
0
def getLevel(identifier):
    """Get a level with its questions and their responses"""

    # Get the connection
    conn = getConnection()

    # Get the question
    question_cursor = executeRequest(
        """SELECT Level.Id, Level.Title, Question.Id, Question.Question, Response.Value, Response.Response, Response.Id
        FROM Level 
        INNER JOIN Question ON Level.Id = Question.IdLevel 
        INNER JOIN Response ON Question.Id = Response.IdQuestion 
        WHERE Level.Id = """ + identifier + """
        ORDER BY Question.Id, Response.Value""", conn)

    if question_cursor is not None:
        level = None
        current_question = None
        for row in question_cursor.fetchall():
            # Title
            if level is None:
                level = Level()
                level.id = row[0]
                level.title = row[1]

            # Question
            if current_question is None or current_question.id != row[1]:
                current_question = Question()
                current_question.id = row[2]
                current_question.question = row[3]
                current_question.id_level = level.id
                level.questions.append(current_question)

            # Responses
            Level.Id, Level.Title, Question.Id, Question.Question, Response.Value, Response.Response, Response.Id
            response = Response()
            response.value = row[4]
            response.response = row[5]
            response.id = row[6]
            response.id_question = current_question.id
            current_question.responses.append(response)

        # Set the result
        result = getHTTPResponse(200, level)
    else:
        # Level does not exist
        result = getHTTPResponse(500, "This level does not exist", False)

    conn.close()

    return result
예제 #18
0
def select_all():
    questions = []
    sql = "SELECT * FROM questions"
    results = run_sql(sql)
    for result in results:
        difficulty = difficulty_repository.select(result["difficulty_id"])
        topic = topic_repository.select(result["topic_id"])
        user_topic = user_topic_repository.select(result["user_topic_id"])
        question = Question(result["the_question"], result["correct_answer"],
                            result["alt_ans_1"], result["alt_ans_2"],
                            result["alt_ans_3"], difficulty, topic, user_topic,
                            result["used"], result["id"])
        questions.append(question)
    return questions
예제 #19
0
    def test_load_question_from_index(self):
        question = Question(pub_date=timezone.now() -
                            datetime.timedelta(days=3),
                            question_text='Foo Bar')
        question.save()

        self.selenium.get('%s%s' %
                          (self.live_server_url, reverse('polls:index')))
        self.selenium.find_element_by_css_selector(
            'a[data-question-id="{}"]'.format(question.id)).click()
        # Wait until the response is received
        WebDriverWait(
            self.selenium,
            2).until(lambda driver: driver.find_element_by_tag_name('body'))
예제 #20
0
def select(id):
    question = None
    sql = "SELECT * FROM questions WHERE id = %s"
    values = [id]
    result = run_sql(sql, values)[0]
    difficulty = difficulty_repository.select(result["difficulty_id"])
    topic = topic_repository.select(result["topic_id"])
    user_topic = user_topic_repository.select(result["user_topic_id"])

    if result is not None:
        question = Question(result["the_question"], result["correct_answer"],
                            result["alt_ans_1"], result["alt_ans_2"],
                            result["alt_ans_3"], difficulty, topic, user_topic,
                            result["used"], result["id"])
    return question
예제 #21
0
    def post(self):
        try:
            '''
            validate the answer of the question.
            '''
            player_answer = self.get_argument('answer', None)
            cur_quest_id = self._get_argument('question_id', None)
            if player_answer and cur_quest_id:
                if Question().validate_question(cur_quest_id, player_answer):
                    self.add_current_pass()
                self.add_current_quests()

            if self.is_game_continue():
                return self.redirect('/play')
        except:
            return self.write_response("Validate new question Fail!")
    async def addMessage(self, ctx, *args):
        """Submit a new question"""

        talk_id = DB.get_channel_talk(ctx.message.guild.id,
                                      ctx.message.channel.id)

        if (talk_id == None):
            await ctx.send('This channel is not bound to a conference')
            return

        talk_id = talk_id[0]

        question = Question(" ".join(args), ctx.message.author.display_name,
                            str(ctx.message.author.id), datetime.now())

        FB.addQuestion(talk_id, question)
예제 #23
0
    def get(self):
        try:
            '''
            if pass < 6 or questions <= 10, web pages display the new question.
            else return the result.
            '''
            if self.is_game_continue():
                old_questions = self.get_old_quests()
                new_question = Question().get_new_question(old_questions)
                if new_question:
                    new_question['num'] = len(old_questions) + 1
                    return self.render('play.html', question=new_question)

                return self.redirect('/play')
        except:
            return self.write_response("Get new question Fail!")
예제 #24
0
    def create_question():
        data = request.get_json()
        question = Question(**data)
        result = question.insert_record()

        if result["error"]:
            abort(500)

        _id = result["id"]
        questions = Question.get_by_page(request, QUESTIONS_PER_PAGE)

        return jsonify({
            "created": _id,
            "questions": questions,
            "total_questions": len(Question.get_all()),
            "success": True,
        })
예제 #25
0
def questions(survey_id):
    form = QuestionForm(request.form)
    if (request.method == 'GET'):
        return render_template(
            'questions.html',
            survey_id=survey_id,
            questions=session.query(Question).order_by(
                Question.id_).filter(Question.survey_id_ == survey_id).all())

    if (request.method == 'POST') and (form.validate()):
        newQuestion = Question(form.type_.data, form.title_.data, survey_id,
                               form.optional_.data)
        session.add(newQuestion)
        session.commit()
        return redirect("/surveys/" + str(survey_id) + "/questions")
    else:
        return render_template('edit_question.html', form=form)
예제 #26
0
def getAll():
    """Get all levels with their questions and their responses"""

    # Get the connection
    conn = getConnection()

    # Get the question
    question_cursor = executeRequest(
        """SELECT Level.Id, Level.Title, Question.Id, Question.Question, Response.Value, Response.Response, Response.Id
        FROM Level 
        INNER JOIN Question ON Level.Id = Question.IdLevel 
        INNER JOIN Response ON Question.Id = Response.IdQuestion 
        ORDER BY Level.Id, Question.Id, Response.Value""", conn)
    levels = []
    current_level = None
    current_question = None
    for row in question_cursor.fetchall():
        # New level with title
        if current_level is None or current_level.id != row[0]:
            current_level = Level()
            current_level.id = row[0]
            current_level.title = row[1]
            levels.append(current_level)

        # Question
        if current_question is None or current_question.id != row[2]:
            current_question = Question()
            current_question.id = row[2]
            current_question.id_level = current_level.id
            current_question.question = row[3]
            current_level.questions.append(current_question)

        # Responses
        response = Response()
        response.value = row[4]
        response.response = row[5]
        response.id = row[6]
        response.id_question = current_question.id
        current_question.responses.append(response)

    # Set the result
    result = getHTTPResponse(200, levels)
    conn.close()

    return result
    def __find_questions(self, paragraphs: list) -> list:
        questions = []
        for index, paragraph in enumerate(paragraphs):

            is_list = paragraph.style.name == 'List Paragraph'
            has_question_number = re.match('^[0-9]\.', paragraph.text)
            has_start = re.search('@start', paragraph.text)

            if is_list or has_question_number or has_start:
                leng = len(questions)
                if leng != 0:
                    questions[leng - 1].end = index - 1
                q = Question()
                q.start = index
                questions.append(q)
                self.__format_paragraphs(paragraph, len(questions))
        questions[len(questions) - 1].end = len(paragraphs)
        return questions
예제 #28
0
def generate_questions(group_conf):
    df = group_conf['df']
    name = f"Conseil d'administration {group_conf['semester']}"
    if group_conf['semester'] == 'Annuel':
        description = "Vote de confiance pour les postes annuels au conseil d'administration de l'AGEG."
        code = f"CA{group_conf['semester']}"
        title = "Qui voulez-vous comme administrateurs annuels de l'AGEG?"
    else:
        description = "Vote de confiance pour les postes saisonniers au conseil d'administration de l'AGEG."
        code = "CAS" + group_conf['semester']
        title = "Qui voulez-vous comme administrateurs saisonniers de l'AGEG?"
    group = Group(name, description)

    question_admin = Question(code=code, gid=group.gid, title=title, qtype='F')

    question_admin.add_answer(
        Answer(qid=question_admin.qid, value="Oui", code="A1", order=1))
    question_admin.add_answer(
        Answer(qid=question_admin.qid, value="Non", code="A2", order=2))
    question_admin.add_answer(
        Answer(qid=question_admin.qid,
               value="Non confiance",
               code="A3",
               order=3))

    sous_questions = []
    for index, candidat in df.iterrows():
        subquestion = Subquestion(parent=question_admin.qid,
                                  gid=question_admin.gid,
                                  code=f"SQ{index + 1:02}",
                                  value=candidat[NOM_USUEL],
                                  order=index,
                                  qtype='T')
        sous_questions.append(subquestion)

        question_admin.add_option(
            Option(nom=candidat[NOM_USUEL],
                   promotion=candidat[PROMOTION],
                   concentration=candidat[CONCENTRATION],
                   order=index,
                   description=candidat[TEXTE_DESCRIPTIF],
                   image=candidat[PHOTO]))

    return group, question_admin, sous_questions
예제 #29
0
def create(post_data):
    question_text = post_data.get("question_text")
    sample_input = post_data.get("sample_input")
    sample_output = post_data.get("sample_output")
    explanation = post_data.get("explanation")
    question_type = post_data.get("question_type")
    q = Question(question_id=shortuuid.uuid(),
                 question_text=question_text,
                 sample_input=sample_input,
                 sample_output=sample_output,
                 explanation=explanation,
                 question_type=question_type)
    try:
        obj = q.save()
        log.debug("## Question Added: ID {}".format(obj.question_id))
        return_dict = obj.to_dict()
        return return_dict
    except Exception as e:
        log.error(e)
        return response.failure({"status": "Failure occurred."})
예제 #30
0
    def create_question(storage):
        text = input('Enter question text: ')
        answers = []

        print('Enter correct answers (# - stop): ')

        while True:
            curr_answer = input('- ')

            if curr_answer in ('#', ''):
                break

            answers.append(curr_answer.lower())

        storage.max_id += 1

        storage.questions.append(Question(storage.max_id, text, answers))

        storage.fill_json()

        input('Question created!')