Пример #1
0
 def test_register_with_blog_option(self):
     """
     Unit test for blog publishing.
     """
     u1 = User(nickname='john', email='*****@*****.**')
     u2 = User(nickname='susan', email='*****@*****.**')
     u1.make_a_hash('john')
     u2.make_a_hash('susan')
     db.session.add(u1)
     db.session.add(u2)
     opt1 = Option(user=u1)
     opt2 = Option(user=u2)
     db.session.add(opt1)
     db.session.add(opt2)
     db.session.commit()
     # Test in setting side.
     assert opt1.is_blog_publishing() is True
     assert opt2.is_blog_publishing() is True
     opt1.set_blog_status(False)
     opt2.set_blog_status(False)
     assert opt1.is_blog_publishing() is False
     assert opt2.is_blog_publishing() is False
     # Test in user side.
     u1.opts.set_blog_status(True)
     assert u1.opts.is_blog_publishing() is True
     assert u2.opts.is_blog_publishing() is False
     u2.opts.set_blog_status(True)
     assert u2.opts.is_blog_publishing() is True
Пример #2
0
    def test_options_deleted_after_questions_deleted(self):
        '''
		When a question is deleted, its related options should be 
		deleted along with it.
		'''
        u = User('*****@*****.**')

        options = [
            Option(body='This in option 1', is_right=True),
            Option(body='This is option 2'),
            Option(body='This is option 3')
        ]

        ques = Question(body='test Question', user=u, options=options)

        db.session.add(ques)
        db.session.add(u)
        db.session.commit()

        ques_query_obj = Question.query.filter_by(id=ques.id).one()

        self.assertTrue(ques_query_obj)

        db.session.delete(ques)
        db.session.commit()

        opts = Option.query.all()

        self.assertTrue(opts == [])
Пример #3
0
def set_user_option (user, key, value):
    opt = user.get_option(key)
    if not opt:
        opt = Option (key=key, value=value)
        add_user_option (user, opt)
    else:
        opt.value = value
        db.session.commit()
Пример #4
0
    def insert_one(self, option):
        """Insert a New Option"""
        if self.get_one_by_key(option["key"]) is not False:
            return True

        option = Option(
            key=option["key"],
            value=option["value"],
            autoload=option["autoload"] if "autoload" in option else False)

        option.save()
        return False if option.pk is None else option
Пример #5
0
 def test_select_field(self):
     opt1 = Option("男", 1)
     opt2 = Option("女", 0)
     
     field = SelectField(True, [opt1, opt2])
     form = Form([field])
     self.db.session.add(form)
     self.db.session.commit()
     
     self.assertEquals(form.id, 1)
     self.assertEquals(opt1.id, 1)
     self.assertEquals(opt2.id, 2)
     self.assertEquals(field.multiple, True)
Пример #6
0
 def handle(self, *args, **options):
     try:
         Option(key='is_camera_on', value=False).save()
         Option(key='is_send_email', value=False).save()
         Option(key='with_photo', value=False).save()
         Option(key='is_minute', value=False).save()
         user = User(username='******',
                     first_name='Saye',
                     last_name='Banayee')
         user.set_password('123456')
         user.save()
     except IntegrityError as e:
         pass
Пример #7
0
    def post(self):
        form = request.form
        print(form)
        content = form.get("content")
        category_id = form.get("category_id")
        right_answer = form.get("right_answer")
        options = form.get("options")
        # 判断参数是否为空
        if not content or not right_answer or not category_id:
            return error.error_1001()

        # 判断right_answer是否合法
        answers_lst = right_answer.split(",")
        for answer in answers_lst:
            if answer not in ["A", "B", "C", "D", "E"]:
                return error.error_1007()

        # 判断题目是否重复
        content_count = Question.Query().filter_by(content=content).count()
        if content_count:
            return error.error_1002("题目不能重重")

        # 将题目添加到到数据库
        question = Question(form)
        db.session.add(question)
        db.session.flush()
        # 获取题目的临时id
        question_id = question.id

        # 解析选项
        options = json.loads(options)
        for r in options:
            r["question_id"] = question_id
            # 判断label是否合法
            if not r.get("label") or r.get("label") not in [
                    "A", "B", "C", "D", "E"
            ]:
                return error.error_1007()
            # 同一题目A,B,C,D,E出现两次
            label_count = Option.Query().filter_by(question_id=question_id,
                                                   label=r["label"]).count()
            print("label_count ", label_count)
            if label_count:
                return error.error_1002(r["label"] + "重复")
            option = Option(r)
            db.session.add(option)
        db.session.commit()
        return error.success()
Пример #8
0
def add_question(user, qn_text, options, answer, topicID):
    '''Adds a question to the database
    Input
    qn_text : str
    options : seq of str
    answer : int (1 to 4)
    topic : int
    '''
    # Generate item parameters from CatSim
    item = generate_item_bank(1)[0]

    # Add question
    question = Question(question=qn_text, discrimination=item[0], \
        difficulty=item[1], guessing=item[2], upper=item[3], topicID = topicID, userID=user.id)
    db.session.add(question)
    db.session.flush()

    qnID = question.id
    
    # Add options and answer
    for opt in options:
        o = Option(qnID=qnID,option=opt)
        answer -= 1
        db.session.add(o)
        db.session.flush()
        if answer == 0:
            optID = o.id
            question.answerID = optID
            db.session.flush()
    db.session.commit()
    return question
Пример #9
0
def add_qn(org_qns):
    '''Adds questions to the database, where questions are formatted to be in a dictionary
    {<question>:{'answer':<options>,'difficulty':<difficulty>}
    <questions> is str
    <options> is list of str
    <difficulty> is float (not added yet)
    '''
    if Question.query.all(): return
    for q in org_qns.keys():
        item = generate_item_bank(1)[0]
        qn = Question(question=q, discrimination=item[0], \
                    difficulty=item[1], guessing=item[2], upper=item[3], topicID=1)
        db.session.add(qn)
        db.session.commit()
        qid = qn.id
        b=True
        for o in org_qns[q]['answers']:
            opt=Option(qnID=qid,option=o)
            db.session.add(opt)
            if b:
                db.session.flush()
                qn.answerID = opt.id
                
                b=False
            
            db.session.commit()
Пример #10
0
    def query(self):
        id = request.args.get("id") or request.form.get("id")
        #判断参数是否存在
        if not id:
            return error.error_1001()

        row = Question.QueryJoinCategory().filter(Question.id == id).first()
        question = {}
        if row:
            opts = Option.Query().filter_by(question_id=row.Question.id).all()
            options = []
            for op in opts:
                option = {
                    "id": op.id,
                    "label": op.label,
                    "content": op.content,
                    "created_time": datetime.timestamp(op.created_time)
                }
                options.append(option)
            question = {
                "id": row.Question.id,
                "content": row.Question.content,
                "type": row.Question.type,
                "category_id": row.Question.category_id,
                "category_name": row.Category.name,
                "subject": row.Category.subject,
                "right_answer": row.Question.right_answer,
                "answer_analyze": row.Question.answer_analyze,
                "options": options,
                "created_time": datetime.timestamp(row.Question.created_time)
            }

        return error.success(question)
Пример #11
0
def options():
    form = OptionsForm()
    if request.method == 'POST' and form.validate():
        x = Option(option=request.form.get('option'),
                   level=request.form.get('level'))
        db.session.add(x)
        db.session.commit()
        return redirect('/options')
    options = Option.query.all()
    return render_template('options.html', form=form, options=options)
Пример #12
0
def add_option():
    id_question = request.form['id_question']
    label = request.form['label']

    option = Option(id_question=id_question, label=label)

    db.session.add(option)
    db.session.commit()

    return Response('{"data":"Option created successfully."}',
                    status=200,
                    mimetype='application/json')
Пример #13
0
def register_vote(token):

    user, payload = User.verify_user_token(token, task='vote')
    if not user:
        flash('Invalid token', 'danger')
        return redirect(url_for('main.index'))

    if user != current_user:
        flash('Login and try again', 'danger')
        return redirect(url_for('main.index'))

    if not 'match' in payload:
        flash('Invalid token payload', 'danger')
        return redirect(url_for('main.index'))

    match_id = payload['match']
    match = Match.query.filter_by(id=match_id).first()

    poll = match.poll
    if not poll:
        flash('Voting has not oppened for this match.', 'warning')
        return redirect(url_for('main.index'))

    if current_user in poll.users:
        flash('You have already voted for this match.', 'warning')
        return redirect(url_for('main.index'))
    else:
        poll.users.append(current_user)

    players = [
        Player.query.filter_by(id=c).first()
        for c in request.form.getlist('choices')
    ]
    for p in players:
        if not p:
            pass

        option = poll.options.filter_by(player_id=p.id).first()
        if option:
            option.votes += 1
        else:
            option = Option(poll_id=poll.id, player_id=p.id, votes=1)

        db.session.add(option)
        db.session.commit()

    flash('Thanks for voting!', 'success')
    return redirect(url_for('main.index'))
Пример #14
0
 def query(self):
     pageNo = int(
         request.args.get("pageNo") or request.form.get("pageNo") or 1)
     pageSize = int(
         request.args.get("pageSize") or request.form.get("pageSize") or 10)
     subject = request.args.get("subject") or request.form.get("subject")
     print(subject)
     # 获取答案和分类
     query = Question.QueryJoinCategory()
     if subject:
         query = query.filter(Category.subject == subject)
     rows = query.offset((pageNo - 1) * pageSize).limit(pageSize).all()
     count = query.count()
     pageCount = math.ceil(count / pageSize)
     questions = []
     for r in rows:
         # 查询选项
         ops = Option.Query().filter_by(question_id=r.Question.id).all()
         print(ops)
         options = []
         for op in ops:
             option = {
                 "id": op.id,
                 "label": op.label,
                 "content": op.content,
                 "created_time": datetime.timestamp(op.created_time)
             }
             options.append(option)
         # 整理question数据
         question = {
             "id": r.Question.id,
             "content": r.Question.content,
             "type": r.Question.type,
             "category_id": r.Question.category_id,
             "category_name": r.Category.name,
             "subject": r.Category.subject,
             "options": options,
             "created_time": datetime.timestamp(r.Question.created_time)
         }
         questions.append(question)
     return error.success({
         "list": questions,
         "page": {
             "total": count,
             "pageCount": pageCount
         }
     })
Пример #15
0
    def post(self):
        form = request.form
        # 获取参数
        id = form.get("id")
        content = form.get("content")
        category_id = form.get("category_id")
        right_answer = form.get("right_answer")
        options = form.get("options")
        answer_analyze = form.get("answer_analyze")
        print(answer_analyze)
        #判断参数是否为空
        if not id:
            return error.error_1001()
        # 查询数据库
        question = Question.Query().filter_by(id=id).first()
        # 判断需要修改的数据
        # 修改题目标题
        if content:
            question.content = content
        # 修改题目分类
        if category_id:
            question.category_id = category_id
        # 修改正确答案
        if right_answer:
            question.right_answer = right_answer
            answers_lst = right_answer.split(",")
            length = len(answers_lst)
            type = "single"
            if length > 1:
                type = "double"
            question.type = type
        # 修改题目选项
        if options:
            options = json.loads(options)
            for op in options:
                option = Option.Query().filter_by(id=op.get("id")).first()
                option.content = op.get("content")
                option.label = op.get("label")
                db.session.add(option)
        # 修改题目答案解析
        if answer_analyze:
            question.answer_analyze = answer_analyze

        # 提交到数据库
        db.session.add(question)
        db.session.commit()
        return error.success()
Пример #16
0
    def query(self):
        subject = request.args.get("subject") or request.form.get("subject")
        # 判断是否选择学科
        if not subject:
            return error.error_1001()

        # 查询用户已答题
        user_id = g.uid
        user_answered = Answer.Query().filter_by(user_id=user_id).all()
        user_answered_ids = []
        for r in user_answered:
            user_answered_ids.append(r.question_id)
        print(user_answered_ids)
        user_answered_ids_t = tuple(user_answered_ids)

        # 查出没有答过的题目
        res = Question.QueryJoinCategory().filter(
            Category.subject == subject).filter(
                not_(Question.id.in_(user_answered_ids_t))).order_by(
                    func.rand()).first()
        count = Question.QueryJoinCategory().filter(
            Category.subject == subject).filter(
                not_(Question.id.in_(user_answered_ids_t))).count()
        print(count)

        question = {}
        if res:
            # 获取题目选项
            rows = Option.Query().filter_by(question_id=res.Question.id).all()
            options = []
            for r in rows:
                option = {"id": r.id, "label": r.label, "content": r.content}
                options.append(option)

            question = {
                "id": res.Question.id,
                "type": res.Question.type,
                "content": res.Question.content,
                "category_name": res.Category.name,
                "category_id": res.Category.id,
                "options": options
            }

        return error.success(question)
Пример #17
0
def insert_qns(path):
    '''Inserts questions formatted as a json file
    {<number>:
    {'answer':<extra text><answer>,
    'option_texts':<extra text><options>, 
    'question_text':<extra text><question><extra text>}}
    all are strings
    '''
    qn_dict = {}
    for filename in glob.glob(os.path.join(path, '*.json')):
        print("===")
        print(filename)
        print("===")
        with open(filename, 'r') as f: # open in readonly mode
            data = json.load(f)
            for qn_set in data.values():
                qn_txt = qn_set["question_text"]
                n, qn_text = qn_txt.split(")",1)
                options = qn_set["option_texts"]
                options = [[o[0], o[6:]] for o in options]
                
                answer = qn_set["answer"]
                a, answer = answer.split("Answer / Explanation :\n\nAnswer : ", 1)
                answer, explanation = answer.split(".", 1)

                item = generate_item_bank(1)[0]

                question = Question(question=qn_text, discrimination=item[0], \
                    difficulty=item[1], guessing=item[2], upper=item[3], topicID=1)
                db.session.add(question)
                db.session.flush()
                qid = question.id

                for opt in options:
                    o = Option(qnID=qid, option=opt[1])
                    db.session.add(o)
                    if opt[0] == answer:
                        db.session.flush()
                        optID = o.id
                        question.answerID = optID

                db.session.commit()
Пример #18
0
for faction in factions:
    c = 0
    for i in range(5):
        q = Question(text='%s q.no. %d' % (faction.name, (c + 1)),
                     for_first_round=False,
                     duration=15,
                     faction_id=faction.id)
        db.session.add(q)
        c += 1
db.session.commit()

questions = Question.query.all()
for question in questions:
    c = 0
    for i in range(4):
        o = Option(question=question, text='option no. %d' % c)
        db.session.add(o)
        c += 1
db.session.commit()
#########################################################
for k, v in lists.items():
    q = Question(text=k, for_first_round=True, duration=15)
    db.session.add(q)
db.session.commit()
for k, v in lists.items():
    q = Question.query.filter(Question.text == k).first()
    for i in range(4):
        o = Option(question=q, text=v[i])
        db.session.add(o)
db.session.commit()
#########################################################
Пример #19
0
    def test_for_building_database1(self):
        option1 = Option(option_body='World of Warcraft')
        option2 = Option(option_body='Team Fortress 2')
        option3 = Option(option_body='Steam')
        option4 = Option(option_body='Dota 2')
        question1 = Question(question_body='which one is a moba game?')
        option1.question = question1
        option2.question = question1
        option4.correct = True
        option4.question = question1
        option3.question = question1
        user1 = User(username='******', email='*****@*****.**')
        quiz1 = Quiz(usersesh=user1)

        db.session.add(quiz1)
        db.session.add(question1)
        db.session.commit()

        for question in db.session.query(Question).all():
            for option in question.options:
                print("test_for_building_database1 option: " +
                      option.option_body)

        print(
            "test_for_building_database1 quiz to user relationship (expected answer 1) user_id is: "
            + str(db.session.query(User).first().quiz[0].user_id))
for faction in factions:
    c = 0
    for i in range(15):
        q = Question(text='%s q.no. %d' % (faction.name, (c + 1)),
                     for_first_round=False,
                     duration=20,
                     faction_id=faction.id)
        db.session.add(q)
        c += 1
db.session.commit()

questions = Question.query.all()
for question in questions:
    c = 0
    for i in range(4):
        o = Option(question=question, text='option no. %d' % c)
        db.session.add(o)
        c += 1
db.session.commit()

options = Option.query.join(Question).filter(Question.for_first_round == True)
c = 0
for option in options:
    if c % 4 == 0:
        w = Weight(option=option, f1=60, f2=20, f3=10, f4=0, f5=0)
    elif c % 4 == 1:
        w = Weight(option=option, f1=0, f2=70, f3=0, f4=50, f5=20)
    elif c % 4 == 2:
        w = Weight(option=option, f1=20, f2=10, f3=70, f4=20, f5=40)
    elif c % 4 == 3:
        w = Weight(option=option, f1=20, f2=0, f3=20, f4=30, f5=60)