Exemplo n.º 1
0
def round_question(round_id):

    question = request.form.get('question')
    #tokenName = request.form.get('token name')
    #yesVal = request.form.get('yesVal')
    #noVal = request.form.get('noVal')

    if question == '':
        # no question, return to page
        return redirect(request.referrer)

    #get the round by id
    try:
        round = models.Round.objects.get(id=round_id)
    except:
        # error, return to where you came from
        return redirect(request.referrer)

    # create question
    question = models.Question()
    question.qText = request.form.get('question')
    #question.tokenName = request.form.get('token name')
    #token.yesVal = request.form.get('yes value')
    #token.noVal = request.form.get('no value')

    # append question to round
    round.questions.append(question)

    # save it
    round.save()

    return redirect('/rounds/%s' % round.slug)
Exemplo n.º 2
0
def create_game_question(db: Session, question: schemas.QuestionCreate,
                         item_id: int):
    db_question = models.Question(**question.dict(), item_id=item_id)
    db.add(db_question)
    db.commit()
    db.refresh(db_question)
    return db_question
Exemplo n.º 3
0
async def add_exam(e_path, verbose=False):
    try:
        with open(e_path) as file:
            meta = yaml.load(file.read())
        questions = meta['questions']
        del meta['questions']
    except (FileNotFoundError, FileExistsError):
        color_print('No exam found')
        return
    except Exception as err:
        print(err)
        color_print('Issue with reading exam data')
        return
    exam = models.Exam(title=meta['title'],
                       users=DEFAULT_USER,
                       description=meta['description'])
    exam, _ = await exam.update_or_create('title', get_insta=True)
    question_order = 1
    for _, val in questions.items():
        try:
            question = models.Question(**val)
            qid = await question.update_or_create('question')
            await exam.add_question(question_id=qid, order=question_order)
            question_order += 1
        except Exception as err:
            if UniqueViolationError:
                color_print('question already existed', color='blue')
                continue
            print(err)
            return
    color_print('Exam id: {} added with {} questions'.format(
        exam.id, len(questions)),
                color='green')
Exemplo n.º 4
0
def edit_paper(db, paper_id):
    if request.forms.qcount:
        qcount = int(request.forms.qcount)
        assert qcount > 0

        paper = db.query(m.Paper).filter(m.Paper.id == paper_id).one()

        new_qs = xrange(1, qcount + 1)
        old_qs = {q.number for q in paper.questions}

        to_remove = [q for q in paper.questions if q.number not in new_qs]
        to_add = [m.Question(number=n) for n in new_qs if n not in old_qs]
        for r in to_remove:
            db.delete(r)
        paper.questions += to_add

    else:
        for k, v in request.forms.items():
            mat = re.match(r'^q(\d+)-unlocked$', k)
            if not mat:
                continue
            v = datetime(*(int(x)
                           for x in re.findall(r'\d+', v))) if v else None

            print mat.groups(), v

            q = db.query(
                m.Question).filter(m.Question.paper_id == paper_id,
                                   m.Question.number == mat.group(1)).one()
            q.unlocked_at = v

    redirect(request.url)
Exemplo n.º 5
0
    def create_question():
        data = fsk.request.get_json()

        # Type-check
        types = {
            "question": str,
            "answer": str,
            "category": int,
            "difficulty": int,
        }

        data = valid_and_cast(data, types)

        # Sanity-check
        cid = data["category"]
        if models.Category.query.get(cid) is None or data["difficulty"] < 1:
            fsk.abort(422)

        # Create question
        qtn = models.Question(**data)
        db = models.db
        try:
            qtn.insert()
            q_data = qtn.format()
            logging.info(f"Created question: {q_data}")
            return fsk.jsonify({"success": True, "id": q_data["id"]})
        except BaseException:
            db.session.rollback()
            logging.exception(
                f"Failed to add new question with content: {data}")
            fsk.abort(500)
        finally:
            db.session.close()
Exemplo n.º 6
0
 def post(self):
     title = self.request.get('title')
     content = self.request.get('content')
     if title == '' or content == '':
         template_values = {'message': 'Both title and content cannot be empty!'}
         template = JINJA_ENVIRONMENT.get_template('template/message.html')
         self.response.write(template.render(template_values))
     else:
         question = models.Question()
         question.author = users.get_current_user()
         question.title = title
         question.content = content
         temp = self.request.get('tags')
         token = temp.split(";")
         tags = []
         for str in token:
             if str != '':
                 str = str.strip()
                 tags.append(str)
         question.tags = tags
         question.voteup = []
         question.votedown = []
         question.put()
         qid = question.key.id()
         temp = repr(int(qid))
         
         url = '/view?qid=' + temp
         self.redirect(url)
         '''
Exemplo n.º 7
0
    def test_quiz(self):
        q1 = models.Question(question='Test Question 1',
                             answers={
                                 'A': 'First Answer',
                                 'B': 'Second Answer'
                             },
                             correct_answer='B')

        q2 = models.Question(question='Test Question 2',
                             answers={
                                 'A': 'An Answer',
                                 'B': 'Another Answer'
                             },
                             correct_answer='A')

        test_quiz = models.Quiz(questions=[q1, q2],
                                code=8675309,
                                name='Test Quiz',
                                userid='test.user-ID')

        key = test_quiz.put()
        result = key.get()
        self.assertDictEqual(
            result.dict, {
                'questions': [{
                    'question': 'Test Question 1',
                    'answers': {
                        'A': 'First Answer',
                        'B': 'Second Answer'
                    }
                }, {
                    'question': 'Test Question 2',
                    'answers': {
                        'A': 'An Answer',
                        'B': 'Another Answer'
                    }
                }],
                'code':
                8675309,
                'name':
                'Test Quiz',
                'userid':
                'test.user-ID'
            })
Exemplo n.º 8
0
 def form_valid(self, form):
     question = models.Question(
         title=form.cleaned_data['title'],
         text=form.cleaned_data['text'],
         author=self.request.user.ask_user,
         created=datetime.now(),
     )
     question.save()
     self.question = question
     return super(Questions, self).form_valid(form)
Exemplo n.º 9
0
 def save(self):
     question = models.Question(title=self.cleaned_data['question_title'],
                                text=self.cleaned_data['question_text'])
     question.save()
     for field in self.fields:
         if field in ['question_title', 'question_text']:
             continue
         if self.cleaned_data[field]:
             choice = models.Choice(question=question,
                                    text=self.cleaned_data[field])
             choice.save()
     return question
 def post(self):
     q = models.Question()
     q.idSchema = request.json['idSchema']
     schema = models.Schema.query.get(q.idSchema)
     q.title = request.json['title']
     q.text = request.json['text']
     q.score = request.json['score']
     if q.idSchema is None or q.title is None or q.text is None or q.score is None:
         return get_shortage_error_dic("text title score"), HTTP_Bad_Request
     if schema is None:
         return get_common_error_dic("can't find schema")
     db.session.add(q)
     db.session.commit()
     return {}, HTTP_Created
Exemplo n.º 11
0
    def test_question(self):
        test_question = models.Question(question='Test Question',
                                        answers={
                                            'A': 'First Answer',
                                            'B': 'Second Answer'
                                        },
                                        correct_answer='B')

        key = test_question.put()
        result = key.get()
        self.assertEqual(result.correct_answer, 'B')
        self.assertDictEqual(
            result.dict, {
                'question': 'Test Question',
                'answers': {
                    'A': 'First Answer',
                    'B': 'Second Answer'
                }
            })
Exemplo n.º 12
0
def create_quiz(quiz: schemas.CreateQuizRequest):
    """Create a new quiz
    """
    new_quiz = models.Quiz(quiz.title, quiz.author)
    session.add(new_quiz)
    session.commit()

    for question in quiz.questions:
        new_question = models.Question(new_quiz.id, question.question_text,
                                       question.correct_answer,
                                       question.answer_one,
                                       question.answer_two,
                                       question.answer_three,
                                       question.answer_four)

        session.add(new_question)
    session.commit()
    session.refresh(new_quiz)

    return new_quiz
Exemplo n.º 13
0
def updateAdmin():
    categories = models.Category.objects()
    if request.method == "POST":
        newQ = models.Question()
        newQ.category = request.form.get('category-list')
        newQ.text = request.form.get('text')
        for c in categories:
            newQ.relations.append(c.title)
            yesValueName = c.title + "-yes"
            noValueName = c.title + "-no"
            newQ.yesValues.append(request.form.get(yesValueName))
            newQ.noValues.append(request.form.get(noValueName))
        newQ.yesResponse = request.form.get("yResponse")
        newQ.noResponse = request.form.get("nResponse")
        newQ.save()
        return redirect('/admin')
    else:
        q_form = models.QuestionForm(request.form)
        data = {'list': categories, 'form': q_form}
    return render_template('add.html', **data)
Exemplo n.º 14
0
async def add_question(qpath="../bootstrap_data/questions.question",
                       verbose=False):
    try:
        with open(qpath) as file:
            questions = yaml.load(file.read())
    except (FileNotFoundError, FileExistsError):
        color_print('No questions found')
        return
    except Exception as err:
        print(err)
        color_print('Issue with reading questions data')
        return
    for _, val in questions.items():
        try:
            question = models.Question(**val)
            await question.update_or_create('question')
        except Exception as err:
            if UniqueViolationError:
                color_print('question already existed', color='blue')
                continue
            print(err)
            return
    color_print('Created {} questions'.format(len(questions)), color='green')
Exemplo n.º 15
0
def parse_question(page_soup: BeautifulSoup):
    qtitle = page_soup.find('title').text
    question_block = page_soup.find('div', attrs={'class': 'question'})
    question_id = question_block['data-questionid']
    question_content_soup = question_block.find('div',
                                                attrs={'class': 'post-text'})
    # print(qcontent)

    question_code_snippets = question_content_soup.findAll('code')
    question_code_snippets_text = [
        code.text for code in question_code_snippets
    ]

    # remove all code tags from text
    [qct.replaceWith('') for qct in question_code_snippets]

    outlinks_soups = question_content_soup.findAll('a', href=True)
    outlinks = [a['href'] for a in outlinks_soups]

    question_text = question_content_soup.text  # this text wont contain code blocks

    answer_soups = page_soup.findAll('div', attrs={'class': 'answer'})
    answers = [parse_answer(ans) for ans in answer_soups]
    answers.sort(key=lambda a: a.upvotes, reverse=True)

    question_object = models.Question(
        url="",
        title=qtitle,
        question_id=question_id,
        text=question_text,
        code_snippets=question_code_snippets_text,
        out_links=outlinks,
        answers=answers,
        lang="java")

    return question_object
Exemplo n.º 16
0
def question(response, qText):
    qText = qText + "?"
    if response == '0':
        #reset everything
        mayor = models.Candidate.objects.get()

        #evaluate the current scores
        metrics = {}
        metrics = sorted(mayor.currScores,
                         key=lambda key: mayor.currScores[key])

        #pick a question from the category with the lowest score
        questions = models.Question.objects(category=metrics[0])
        questions.count()

        ranNum = random.randint(1, len(questions) - 1)
        app.logger.debug(ranNum)
        question = questions[ranNum - 1]
        app.logger.debug(question.text)

        response = "Let's get started. Looks like " + metrics[
            0] + " could use some attention."

        data = {
            'response': response,
            'currScores': mayor.currScores,
            'question': question
        }

    elif response == '1':  #Yes
        mayor = models.Candidate.objects.get()
        prevQuestion = models.Question.objects.get(text=qText)
        models.Question.objects.get(text=qText).delete()
        yesResponse = prevQuestion.yesResponse
        # save the currScores into prevScores before altering them
        mayor.prevScores = mayor.currScores

        # qet the yesValues for the previous question
        prevQYesValues = prevQuestion.yesValues

        # add them to the currScores
        counter = 0
        for i in mayor.currScores.keys():
            pScore = mayor.currScores[i]
            app.logger.debug("pScore= " + str(pScore))
            nScore = prevQYesValues[counter]
            app.logger.debug("qMatrix= " + str(nScore))
            adjScore = pScore + nScore
            app.logger.debug("adjScore= " + str(adjScore))
            mayor.currScores[i] = adjScore
            counter = counter + 1

        #evaluate the current scores
        metrics = {}
        metrics = sorted(mayor.currScores,
                         key=lambda key: mayor.currScores[key])

        #pick a question from the category with the lowest score
        questions = models.Question.objects(category=metrics[0])
        questions.count()

        if questions.count() > 1:
            ranNum = random.randint(1, questions.count())
            question = questions[ranNum - 1]
        elif questions.count() == 1:
            question = questions[0]
        else:
            yesResponse = "NO MORE QUESTIONS IN THIS CATEOGRY. PLEASE START OVER BY CLICKING THE HOME PAGE LINK IN THE UPPER LEFT OF YOUR WINDOW."
            question = models.Question()
            question.text = "GAME OVER. THANKS FOR PLAYING!"

        mayor.save()

        data = {
            'response': yesResponse,
            'currScores': mayor.currScores,
            'question': question
        }

    elif response == '2':  #No
        mayor = models.Candidate.objects.get()
        prevQuestion = models.Question.objects.get(text=qText)
        models.Question.objects.get(text=qText).delete()
        noResponse = prevQuestion.noResponse
        # save the currScores into prevScores before altering them
        mayor.prevScores = mayor.currScores

        # qet the yesValues for the previous question
        prevQNoValues = prevQuestion.noValues

        # add them to the currScores
        counter = 0
        for i in mayor.currScores.keys():
            pScore = mayor.currScores[i]
            app.logger.debug("pScore= " + str(pScore))
            nScore = prevQNoValues[counter]
            app.logger.debug("qMatrix= " + str(nScore))
            adjScore = pScore + nScore
            app.logger.debug("adjScore= " + str(adjScore))
            mayor.currScores[i] = adjScore
            counter = counter + 1

        #evaluate the current scores
        metrics = {}
        metrics = sorted(mayor.currScores,
                         key=lambda key: mayor.currScores[key])

        #pick a question from the category with the lowest score
        questions = models.Question.objects(category=metrics[0])
        questions.count()

        if questions.count() > 1:
            ranNum = random.randint(1, questions.count())
            question = questions[ranNum - 1]
        elif questions.count() == 1:
            question = questions[0]
        else:
            noResponse = "NO MORE QUESTIONS IN THIS CATEOGRY. PLEASE START OVER BY CLICKING THE HOME PAGE LINK IN THE UPPER LEFT OF YOUR WINDOW."
            question = models.Question()
            question.text = "GAME OVER. THANKS FOR PLAYING!"

        mayor.save()

        data = {
            'response': noResponse,
            'currScores': mayor.currScores,
            'question': question
        }

    return render_template("question.html", **data)
Exemplo n.º 17
0
def initEverything():
    #clear database - will not work for more than one user
    models.Question.objects.delete()
    models.Category.objects.delete()
    models.Candidate.objects.delete()

    #create default categories the long way
    titles = [
        "Tax", "Education", "Public Health", "Community Arts", "Unemployment",
        "Tourism"
    ]
    for t in titles:
        newCat = models.Category()
        newCat.title = t
        newCat.save()

#create default Questions the long way
    q1 = models.Question()
    q1.text = "Should you add a new stadium?"
    q1.category = "Tax"
    q1.relations = [
        "Tax", "Education", "Public Health", "Community Arts", "Unemployment",
        "Tourism"
    ]
    q1.yesValues = [2, -2, -2, -3, -2, 3]
    q1.noValues = [0, 2, -3, 3, 2, 0]
    q1.yesResponse = "You just created 2,000 jobs! Also, expect some good return on tourism when you open the stadium. Of course, you might want to invest in some infrastructure for all that new traffic. Oh, and some folks are angry with the higher taxes you'll be enforcing to pay for this."
    q1.noResponse = "Probably smart to save that money. You might lose out on some tourism and added seasonal income, but now you can focus on your aging infrastructure and maybe do something nice for the kids in school!"
    q1.save()

    q2 = models.Question()
    q2.text = "The roads need fixing. Should you do it this year?"
    q2.category = "Tax"
    q2.relations = [
        "Tax", "Education", "Public Health", "Community Arts", "Unemployment",
        "Tourism"
    ]
    q2.yesValues = [2, 0, 0, 0, -1, 1]
    q2.noValues = [0, 0, 0, 0, 0, -1]
    q2.yesResponse = "Good idea. You created 1,000 new jobs. Bit of a tax hike, though. Maybe you could justify it by allocating some of it for something else?"
    q2.noResponse = "It can wait. Those tour buses can take a few bumps, right?"
    q2.save()

    q3 = models.Question()
    q3.text = "Big business is pressuring you to lower taxes. Should you listen to them?"
    q3.category = "Tax"
    q3.relations = [
        "Tax", "Education", "Public Health", "Community Arts", "Unemployment",
        "Tourism"
    ]
    q3.yesValues = [-2, -1, -1, -2, 1, 1]
    q3.noValues = [-1, 0, -1, -1, 0, 1]
    q3.yesResponse = "Good idea. You created 1,000 new jobs. Bit of a tax hike, though. Maybe you could justify it by allocating some of it for something else?"
    q3.noResponse = "They are your biggest campaign contributors. You can do more in the long run, even though this will make some people angry in the short run."
    q3.save()

    q4 = models.Question()
    q4.text = "Start a new charter school program?"
    q4.category = "Education"
    q4.relations = [
        "Tax", "Education", "Public Health", "Community Arts", "Unemployment",
        "Tourism"
    ]
    q4.yesValues = [-2, 3, 0, 2, 3, 0]
    q4.noValues = [0, -2, 0, 0, 0, 0]
    q4.yesResponse = "Good idea. Jobs for teachers and staff while saving taxes. They can also sponser community programs."
    q4.noResponse = "You have your reasons. But the public school system isn't making any progress on standardized tests."
    q4.save()

    q5 = models.Question()
    q5.text = "Reward teachers based on standardized testing?"
    q5.category = "Education"
    q5.relations = [
        "Tax", "Education", "Public Health", "Community Arts", "Unemployment",
        "Tourism"
    ]
    q5.yesValues = [0, -3, 0, -2, 0, 0]
    q5.noValues = [0, 1, 0, 2, 0, 0]
    q5.yesResponse = "Oops, that backfired. Turns out they don't do so well as a whole. Teachers are frustrated and leaving. Let's hope tourist season is good, maybe some of them will want to stay."
    q5.noResponse = "Testing testers isn't the answer. Maybe funding more community programs when you have the chance will increase motivation for families to help their kids in school."
    q5.save()

    q6 = models.Question()
    q6.text = "Sponsor an after school program for kids with single parents?"
    q6.category = "Education"
    q6.relations = [
        "Tax", "Education", "Public Health", "Community Arts", "Unemployment",
        "Tourism"
    ]
    q6.yesValues = [-1, 1, -1, -2, -1, 0]
    q6.noValues = [1, 0, 1, 0, -1, 1, 0]
    q6.yesResponse = "Good news! The government has a funding program that will keep you from raising taxes. Smart move."
    q6.noResponse = "You could have created a few jobs, but at least you're saving the money for something else."
    q6.save()

    q7 = models.Question()
    q7.text = "The river is on the edge of being declared a superfund site. Pay to clean it up?"
    q7.category = "Public Health"
    q7.relations = [
        "Tax", "Education", "Public Health", "Community Arts", "Unemployment",
        "Tourism"
    ]
    q7.yesValues = [2, 0, 3, 0, 0, 0]
    q7.noValues = [-1, 0, -2, 0, 0, 0]
    q7.yesResponse = "Here's to public health! It's expensive, but at least a few jobs will be available. Might lose some of your infrastructure resources to cut costs, though."
    q7.noResponse = "Tell them you're applying for federal funds. It'll hold them off. It's not a superfund site yet..."
    q7.save()

    q8 = models.Question()
    q8.text = "Sponsor a city-wide marathon and an excercise campaign?"
    q8.category = "Public Health"
    q8.relations = [
        "Tax", "Education", "Public Health", "Community Arts", "Unemployment",
        "Tourism"
    ]
    q8.yesValues = [1, 1, 2, 0, 0, 2]
    q8.noValues = [-1, 0, 0, 0, 0, 0]
    q8.yesResponse = "It all goes swimmingly. That slight tax bump was offset by tourism money!"
    q8.noResponse = "Why strain a city that's already strained? Kids will learn to love apples...right?"
    q8.save()

    q9 = models.Question()
    q9.text = "Start a recycling program?"
    q9.category = "Public Health"
    q9.relations = [
        "Tax", "Education", "Public Health", "Community Arts", "Unemployment",
        "Tourism"
    ]
    q9.yesValues = [2, 0, 2, 0, -2, 0]
    q9.noValues = [-1, 0, -1, 0, 0, 0]
    q9.yesResponse = "People are willing to pay for a cleaner city. And more jobs! Let's hope Big Business doesn't start hollering about the tax hike."
    q9.noResponse = "You can use what you save with this decision on more pressing issues. But that landfill ain't getting any smaller, and it's right next to the river..."
    q9.save()

    q10 = models.Question()
    q10.text = "Start a Maker Faire?"
    q10.category = "Community Arts"
    q10.relations = [
        "Tax", "Education", "Public Health", "Community Arts", "Unemployment",
        "Tourism"
    ]
    q10.yesValues = [1, -2, 0, 2, 0, 1]
    q10.noValues = [0, 0, 0, 0, 0, -1]
    q10.yesResponse = "Great idea! You can bundle your community art funding here and invite all the organizations to participate! Might put a strain on your transit infrastructure, though."
    q10.noResponse = "Meh. Who needs a bunch of 3D printers and flame-throwing robots? You've got bigger things on your mind."
    q10.save()

    q11 = models.Question()
    q11.text = "Build a state-of-the-art community arts center downtown?"
    q11.category = "Community Arts"
    q11.relations = [
        "Tax", "Education", "Public Health", "Community Arts", "Unemployment",
        "Tourism"
    ]
    q11.yesValues = [1, 0, 0, 2, -2, -1]
    q11.noValues = [0, 0, 0, -1, -1, 0]
    q11.yesResponse = "A good move, but you'll have to improve your bus lines if you want everyone to have access. You get a few jobs out of this deal and the Nutcracker brings in folks from 5 counties!"
    q11.noResponse = "Probably best to focus on the neighborhood programs. Last thing you need is a strained transit system."
    q11.save()

    q12 = models.Question()
    q12.text = "Sponsor after-school program for aspiring entrepreneurs?"
    q12.category = "Community Arts"
    q12.relations = [
        "Tax", "Education", "Public Health", "Community Arts", "Unemployment",
        "Tourism"
    ]
    q12.yesValues = [1, 0, 0, 3, 0, 0]
    q12.noValues = [0, 0, 0, -1, 1, 0]
    q12.yesResponse = "Could lead to good things. Worth the investment and you're getting great press."
    q12.noResponse = "It isn't proven to help in the long run. You need something more engaging for everyone, not just kids. Maybe a big event...like a Maker Faire... "
    q12.save()

    q13 = models.Question()
    q13.text = "The Unions say the river cleanup will make the ports less accessible and are threatening to strike. Do you put off the cleanup?"
    q13.category = "Unemployment"
    q13.relations = [
        "Tax", "Education", "Public Health", "Community Arts", "Unemployment",
        "Tourism"
    ]
    q13.yesValues = [0, 0, -2, 0, 0, -2]
    q13.noValues = [0, 0, 2, 0, 0, 1]
    q13.yesResponse = "Dang. This is a loose-loose. You need that port and jobs are important in this economy. The river will have to wait. Let's hope it doesn't reach superfund status"
    q13.noResponse = "Public Health is important. You're taking care of tens-of-thousands in the long-run while angering just a few thousand in the short term. You can't please everyone. You might have to create some jobs to appease the Unions, though."
    q13.save()

    q14 = models.Question()
    q14.text = "Should you privatize the city's energy?"
    q14.category = "Unemployment"
    q14.relations = [
        "Tax", "Education", "Public Health", "Community Arts", "Unemployment",
        "Tourism"
    ]
    q14.yesValues = [1, 0, -1, 0, -2, 1]
    q14.noValues = [-2, 0, -1, 0, -1, 0]
    q14.yesResponse = "You're a tough negotiator and it pays off. You get more jobs, an updated infrastructure, and they're building a large park to offset their environmental impact. Let's hope you didn't put them too close to the river..."
    q14.noResponse = "Probably a safe bet. But your infrastructure hasn't been maintained well and your main subway line just went down. Looks like taxes will have to go up again."
    q14.save()

    q15 = models.Question()
    q15.text = "Should you open a high-security prison on the edge of town?"
    q15.category = "Unemployment"
    q15.relations = [
        "Tax", "Education", "Public Health", "Community Arts", "Unemployment",
        "Tourism"
    ]
    q15.yesValues = [-1, 0, 0, 0, -2, -2]
    q15.noValues = [0, 0, 0, 0, 2, 0]
    q15.yesResponse = "You just created thousands of jobs! The road repairs will have to wait and tourism will drop off, but hopefully the profit from the prison with help from federal funds should cover that...eventually."
    q15.noResponse = "You're right. You can find better jobs without risking tourism and diverting funds from your aging infrastructure."
    q15.save()

    q16 = models.Question()
    q16.text = "Make a bid to be the host city for 2018 Super Bowl?"
    q16.category = "Tourism"
    q16.relations = [
        "Tax", "Education", "Public Health", "Community Arts", "Unemployment",
        "Tourism"
    ]
    q16.yesValues = [1, 0, 0, 0, -2, 3]
    q16.noValues = [0, 0, 0, 0, 0, 0]
    q16.yesResponse = "You can't buy publicity like this...only you did because you had to spend some money shining up your public sites for the review committee. Let's hope you get it."
    q16.noResponse = "Risk nothing, gain nothing. In politics, that isn't a bad thing."
    q16.save()

    q17 = models.Question()
    q17.text = "Build a Convention Center?"
    q17.category = "Tourism"
    q17.relations = [
        "Tax", "Education", "Public Health", "Community Arts", "Unemployment",
        "Tourism"
    ]
    q17.yesValues = [1, 0, 0, 0, -1, 2]
    q17.noValues = [0, 0, 0, 0, 0, 0]
    q17.yesResponse = "Makes sense. More jobs, tourism, and a better infrastructure. Worth the tax hike."
    q17.noResponse = "OK. Maybe build invest somewhere else?"
    q17.save()

    q18 = models.Question()
    q18.text = "Build a modern art museum?"
    q18.category = "Tourism"
    q18.relations = [
        "Tax", "Education", "Public Health", "Community Arts", "Unemployment",
        "Tourism"
    ]
    q18.yesValues = [0, 0, 0, 0, 0, 2]
    q18.noValues = [0, 0, 0, 0, 0, 0]
    q18.yesResponse = "Temporary jobs and a slight bump in tourism is never a bad thing. Doesn't seem like the locals care as much about art as they do that river cleanup, though."
    q18.noResponse = "Could have livened things up, but you have more presseing issues that need attending to."
    q18.save()
Exemplo n.º 18
0
def db_init():

    models.db.drop_all()
    models.db.create_all()
    utls.display_tables()

    #populate Quiz table
    qz1 = models.Quiz( "Python Basics  ", "Simple  ", "Explanation", 1, 2)
    qz2 = models.Quiz( "Python Advanced", "Moderate", "No text    ", 1)
    models.db.session.add_all([qz1,qz2])

    #populate models.Questions table
    #Quiz 1
    ques1 = models.Question("What does 'def foo(): pass do", 
                     "A fn which does nothing",1,1)
    ques2 = models.Question("Is python an OOP l           ", 
                     "Yes python is an OOP l",1,1)
    ques3 = models.Question("What is operator overloading?", 
                     "Operator overloading is a concept in OOPS",1,1)
    ques4 = models.Question("Is python dynmaically typed? ", 
                     "Yes python is a dynmaically typed language",1,1)
    models.db.session.add_all([ques1, ques2, ques3, ques4])

    #Quiz 1
    ques5 = models.Question("What is the use of an assertion?",
                     "A fn which does nothing",2,1)
    ques6 = models.Question("What is python library scrapy used for?",
                     "Yes python is an OOP l",2,1)
    models.db.session.add_all([ques5, ques6])

    #populate Answer choices table
    #Quiz 1
    ans1  = models.Anschoice(1, 1, "(a) This function does nothing      ", True)
    ans2  = models.Anschoice(1, 1, "(b) This function returns a fn pass ", False)
    ans3  = models.Anschoice(1, 1, "(c) This function is not yet defined", False)
    ans4  = models.Anschoice(1, 2, "(a) Yes Python is object oriented   ", True)
    ans5  = models.Anschoice(1, 2, "(b) No Python is not object oriented", False)
    ans6  = models.Anschoice(1, 2, "(c) Python may not be used as OOP l ", False)
    ans7  = models.Anschoice(1, 3, "(a) This function does nothing      ", True)
    ans8  = models.Anschoice(1, 3, "(b) This function returns a fn pass ", False)
    ans9  = models.Anschoice(1, 3, "(c) This function is not yet defined", False)
    ans10  = models.Anschoice(1, 4, "(a) Yes Python is object oriented   ", True)
    ans11  = models.Anschoice(1, 4, "(b) No Python is not object oriented", False)
    ans12  = models.Anschoice(1, 4, "(c) Python may not be used as OOP l ", False)
    models.db.session.add_all([ans1, ans2, ans3, ans4, ans5, ans6, ans7, ans8,\
                        ans9, ans10, ans11, ans12])
    #Quiz 2
    ans13  = models.Anschoice(2, 5, "(a) This function does nothing      ", False)
    ans14  = models.Anschoice(2, 5, "(b) This function returns a fn pass ", True)
    ans15  = models.Anschoice(2, 5, "(c) This function is not yet defined", False)
    ans16  = models.Anschoice(2, 6, "(a) Yes Python is object oriented   ", False)
    ans17  = models.Anschoice(2, 6, "(b) No Python is not object oriented", True)
    ans18  = models.Anschoice(2, 6, "(c) Python may not be used as OOP l ", False)
    models.db.session.add_all([ans13, ans14, ans15, ans16, ans17, ans18])
    try:
        models.db.session.commit()
    except IntegrityError:
        print "Arch: Caught SQL Alchemy exception Integrity Error"
    except InvalidRequestError:
        print "Arch: Caught SQL Alchemy exception InvalidRequestError"

    return None
Exemplo n.º 19
0
 async def process(a_dir, lang=lang):
     less_counter = LessonCounter()
     if a_dir.startswith('.') or a_dir.startswith('_'):
         return
     path = os.path.abspath('../lesson_source/{}'.format(a_dir)) + '/'
     images = path + 'images'
     path += lang
     l_path = path + '.md'
     e_path = path + '.exercises'
     m_path = path + '.meta'
     q_path = path + '.quiz'
     try:  # lesson generation will be deprecated in future
         with open(l_path) as file:
             html = markdown.markdown(file.read(),
                                      extensions=[
                                          'markdown.extensions.codehilite',
                                          'markdown.extensions.tables'
                                      ])
     except FileNotFoundError:
         return
     with open(m_path) as file:
         meta = yaml.load(file.read())
     meta['author'] = DEFAULT_USER
     meta['file'] = '{}.html'.format(a_dir)
     meta['lesson_no'] = int(a_dir)
     try:
         with open(q_path) as file:
             questions = yaml.load(file.read())
         less_counter.quiz_outcome = 'found'
     except Exception as err:
         questions = False
         less_counter.quiz_outcome = 'none'
     if questions:
         quiz = models.Quiz(title=meta['title'],
                            users=DEFAULT_USER,
                            description=meta['description'])
         quiz_id = await quiz.update_or_create('title')
         meta['quiz'] = quiz_id
         question_order = 1
         for _, val in questions.items():
             try:
                 question = models.Question(**val)
                 qid = await question.update_or_create(*val.keys())
                 qq = models.QuizQuestions(quiz=quiz_id,
                                           question=qid,
                                           question_order=question_order)
                 question_order += 1
                 await qq.update_or_create('question', 'quiz')
                 less_counter.quiz_details_done += 1
             except Exception as err:
                 print(err)
                 less_counter.quiz_details_error += 1
     try:
         lesson = models.Lesson(**meta)
         lid, updated = await lesson.update_or_create('lesson_no',
                                                      verbose=True)
         less_counter.lesson_outcome = 'found'
         if updated:
             less_counter.lesson_outcome = 'updated'
             counter.updated_lessons += 1
         else:
             less_counter.lesson_outcome = 'created'
             counter.added_lessons += 1
     except Exception as err:
         print(err)
         less_counter.lesson_outcome += 'error'
         counter.error_lessons += 1
     try:
         with open(e_path) as file:
             exe = yaml.load(file)
             less_counter.exercise_outcome = 'found'
     except Exception as err:
         exe = False
         less_counter.exercise_outcome = 'not found'
         print(err)
     if exe:
         try:
             for val in exe.values():
                 exercise = models.Exercise(lesson=lid, **val)
                 id, updated = await exercise.update_or_create('title',
                                                               verbose=True)
                 if updated:
                     less_counter.exercise_details_updated += 1
                 else:
                     less_counter.exercise_details_created += 1
         except Exception as err:
             print('error creating exercise')
             less_counter.exercise_details_error += 1
             print(exe)
             print(err)
     dest = os.path.abspath('static/images/')
     if os.path.exists(images):
         for file in os.listdir(images):
             src = os.path.join(images, file)
             if os.path.isfile(src):
                 dst = dest + '/' + file
                 shutil.copy(src, dst)
                 less_counter.lesson_imgs_done += 1
             else:
                 less_counter.lesson_imgs_errors += 1
     return less_counter
Exemplo n.º 20
0
def load_quizzes():
    """
    Load sample quiz data.
    """
    quiz_list = ['drum_fill_friday.json']

    for quiz in quiz_list:
        with open('www/assets/data/%s' % quiz, 'rb') as readfile:
            quiz_json = dict(json.loads(readfile.read()))

        quiz = {
            'category': "Drum Fill Friday",
            'title': quiz_json['title'],
            'text': 'TKTK',
            'photo': None,
            'seamus_url': '',
            'author': 'Bob Boilen'
        }

        # Create photo
        if quiz_json['photo']:
            quiz['photo'] = _create_photo(quiz_json['photo'])

        # Create quiz
        qz = models.Quiz(**quiz)
        qz.save()

        print "Saved quiz: %s" % qz

        for question_index, question_json in enumerate(quiz_json['questions']):
            question = {
                'order': question_index,
                'quiz': qz,
                'text': question_json['text'],
                'photo': None,
                'audio': None
            }

            # Create photo
            if question_json['photo']:
                question['photo'] = _create_photo(question_json['photo'])

            # Create audio
            if question_json['audio']:
                question['audio'] = _create_audio(question_json['audio'])

            # Create question
            qn = models.Question(**question)
            qn.save()

            print "Saved question: %s" % qn

            for choice_index, choice_json in enumerate(
                    question_json['choices']):
                choice = {
                    'order': choice_index,
                    'question': qn,
                    'text': choice_json['text'],
                    'correct_answer': False,
                    'photo': None,
                    'audio': None,
                }

                if choice_index == question_json['answer']:
                    choice['correct_answer'] = True

                # Create photo
                if choice_json['photo']:
                    choice['photo'] = _create_photo(choice_json['photo'])

                # Create audio
                if choice_json['audio']:
                    choice['audio'] = _create_audio(choice_json['audio'])

                # Create choice
                ch = models.Choice(**choice)
                ch.save()

                print 'Saved choice: %s' % ch

        qz.deploy()
        print 'Deployed quiz: %s' % qz
Exemplo n.º 21
0
    def post(self, qzid):
        """Add question to quiz"""
        logs.debug_ ("_________________________________________________")
        logs.debug_ ("QuestionsAPI post fn: %s \nJson Request\n=============\n %s" 
                      %(request, request.json))

        # Get userid from hdr
        userid, username = utls.get_user_from_hdr()
        if 'username' not in session:
            response = handle_invalid_usage(InvalidUsageException
                        ('Error: No active session for this user found', 
                         status_code=404))
            return response

        # Get data from req
        args = self.reqparse.parse_args()
        for key, value in args.iteritems():
            if value is not None:
                if (key == 'ques_text'):
                    ques_text = request.json['ques_text']
                if (key == 'ans_text'):
                    ans_text = request.json['ans_text']
                if (key == 'anschoices'):
                    anschoices = request.json['anschoices']

        # Post new data to table
        qn_obj = models.Question(ques_text, ans_text, qzid, userid)
        models.db.session.add(qn_obj)

        # Update correspnoding relationship tables 
        #Quiz table
        L = models.Quiz.query.filter_by(qzid = qzid).first()
        models.Quiz.query.filter_by(qzid = qzid).update(dict(no_ques=
                                                      (L.no_ques+1)))

        # Ans choices table 
        ansidL = []
        for choice in range(len(anschoices)):
            ans_obj = models.Anschoice(qzid,
                                     qn_obj.qid,
                                     anschoices[choice]["answer"], 
                                     anschoices[choice]["correct"]
                                    )
            models.db.session.add(ans_obj)
        models.db.session.commit()

        # Return response
        location = "/quizzes/%s/questions/%s" % (qzid, qn_obj.qid)
        query_obj = models.Question.query.join(models.Anschoice).\
                         filter(models.Question.qid == qn_obj.qid).all()
        qid = qn_obj.qid
        ans_fields = {'ans_choice':fields.String,
                      'correct':fields.Boolean
                     }
        resource_fields =  {'ques_text':fields.String,
                           'ans_text':fields.String,
                           'qzid':fields.Integer,
                           'qid':fields.Integer,
                           'anschoices':fields.Nested(ans_fields)
                          }
                            
        question = marshal(query_obj, resource_fields)
        response = jsonify(question=question)
        response.location = location
        response.status_code = 201
        logs.info_(response)
        utls.display_tables()
        return response
Exemplo n.º 22
0
def new_balloon_handler(handler: "BaseMessageHandler"):
    if len(handler.message.text) < 50:
        handler.set_question(models.Question("new_balloon"))
        return handler.reply_message(strings.TOO_SHORT)

    if not remove_balloon(handler):
        return handler.reply_message(strings.NO_MORE_balloon)

    # update counter and store message
    handler.message.set_seq()
    models.balloons_table.put_item(Item=models.asddbdict(handler.message))

    # if first message in channel, stop
    if handler.message.seq == 1:
        handler.reply_message(
            strings.NO_MESSAGE_EVER + generate_status(handler),
            buttons=[buttons.new_balloon, buttons.trending],
        )
        return

    # get the previous one
    response = models.balloons_table.get_item(Key={
        "tags": handler.message.tags,
        "seq": handler.message.seq - 1
    })

    if "Item" not in response:
        response = poll_message(handler.message.tags, handler.message.seq)

    item = response["Item"]

    # if the previous one is from the same person, tell them
    if handler.message.user_id == item["user_id"]:
        handler.reply_message(
            strings.YOU_AGAIN + generate_status(handler),
            buttons=[buttons.new_balloon, buttons.trending],
        )
        return

    text = strings.MESSAGE_INTRO.format(
        item["sender_display_name"]) + item["text"]
    reply = handler.reply_message(
        text + generate_status(handler),
        buttons=[
            PostbackButton(
                text="💙 Give a free balloon",
                command=
                f"sendfreeballoon/{quote_plus(item['tags'])}/{item['seq']}",
            ),
            PostbackButton(
                text=f"↩️ Start a conversation",
                command=f"reply/{quote_plus(item['tags'])}/{item['seq']}",
            ),
            buttons.new_balloon,
        ],
    )

    # update sent_to on previous item
    models.balloons_table.update_item(
        Key={
            "tags": item["tags"],
            "seq": item["seq"]
        },
        UpdateExpression="SET sent_message_id = :sent_message_id",
        ExpressionAttributeValues={":sent_message_id": reply.id},
    )

    models.conversations_table.put_item(
        Item={
            "id": reply.id,
            "datetime": reply.datetime,
            "sent_for": item["user_id"],
            "original_message_id": item["id"],
        })

    if not handler.user.first_balloon:
        handler.reply_message(strings.BALLOONS_HELP)
        models.users_table.update_item(
            Key={"id": handler.user.id},
            UpdateExpression="SET first_balloon = :True",
            ExpressionAttributeValues={":True": True},
        )
Exemplo n.º 23
0
 async def process(a_dir, lang=lang):
     if a_dir.startswith('.') or a_dir.startswith('_'):
         return
     path = os.path.abspath('lesson_source/{}'.format(a_dir)) + '/'
     images = path + 'images'
     path += lang
     l_path = path + '.md'
     e_path = path + '.exercises'
     m_path = path + '.meta'
     q_path = path + '.quiz'
     try:
         with open(l_path) as file:
             html = markdown.markdown(
                 file.read(), extensions=['markdown.extensions.codehilite'])
     except FileNotFoundError:
         return
     with open('static/lessons/{}.html'.format(a_dir), 'w') as file:
         file.write(HEADER + html + FOOTER)
     with open(m_path) as file:
         meta = yaml.load(file.read())
     meta['author'] = 1
     meta['file'] = '{}.html'.format(a_dir)
     try:
         with open(q_path) as file:
             questions = yaml.load(file.read())
         print('found quiz')
     except Exception as err:
         questions = False
         print(err)
     if questions:
         quiz = models.Quiz(title=meta['title'],
                            users=14,
                            description=meta['description'])
         quiz_id = await quiz.update_or_create('title')
         meta['quiz'] = quiz_id
         question_order = 1
         for _, val in questions.items():
             qustion = models.Question(**val)
             qid = await qustion.update_or_create(*val.keys())
             qq = models.QuizQuestions(quiz=quiz_id,
                                       question=qid,
                                       question_order=question_order)
             question_order += 1
             await qq.update_or_create('question', 'quiz')
             print('question created')
     lesson = models.Lesson(**meta)
     lid = await lesson.update_or_create(*meta.keys())
     try:
         with open(e_path) as file:
             exe = yaml.load(file.read())
     except:
         exe = False
     if exe:
         try:
             for _, val in exe.items():
                 exercise = models.Exercise(lesson=lid, **val)
                 await exercise.update_or_create(*val.keys())
         except Exception as err:
             print('error creating exercise')
             print(exe)
             print(val)
             print(err)
     dest = os.path.abspath('static/images/')
     if os.path.exists(images):
         for file in os.listdir(images):
             src = os.path.join(images, file)
             if os.path.isfile(src):
                 dst = dest + '/' + file
                 shutil.copy(src, dst)
                 print(src + ' copied')
             else:
                 print(src + ' NOT copied')