Example #1
0
    def submit_solution(self, problemid, language, code):
        # save the code into a file name like <problemid>.<anything>.ext
        # use tempfile here to create a temporary file
        # mkstemp returns (fd, fname) where fd is a filedescriptor
        _, fname = tempfile.mkstemp(prefix="%s." % problemid,
                                    suffix=".%s" % language)
        print "MADE TEMP FILE", fname
        with open(fname, "w") as f:
            f.write(code)

        # call leetcode CLI with leetcode submit <filename> and retrieve output
        try:
            output = run_leetcode_command(["submit", fname])
            if output.find("Accepted") != -1:
                print "ACCEPTED", output
                submission = Question.create(leetcode_id=problemid,
                                             submission=code,
                                             status=True)
            elif output.find("Wrong Answer") != -1:
                print "WRONG ANSWER", output
                submission = Question.create(leetcode_id=problemid,
                                             submission=code,
                                             status=False)
            else:
                print "UNKNOWN", output
                submission = Question.create(leetcode_id=problemid,
                                             submission=code,
                                             status=False)
            return output
        finally:
            print "REMOVING", fname
            os.remove(fname)
Example #2
0
def question(question_id):
    question = Question.getQuestion(app.database_url, question_id)
    if question == None:
        return redirect(url_for('finish'))
    if request.method == 'POST':
        Question.setAnswer(question_id, request.form)
        return redirect('/question/'+str(question_id+1))
    return render_template('question.html', question=question)
Example #3
0
def modifyQuestion(fs):
    """ modify fs to be properly consumed by Category() """
    # check for the existence of subcategory
    q = None
    if fs['id'] in ["deleteQuestion", 'editQuestion']:
        """ deactivates Category """
        q = Question(fs).updateQuestion()
    elif fs['id'] == "createQuestion":
        """ Creates new Category """
        q = Question(fs).newQuestion()

    returnJson(q)
Example #4
0
def test_null_question_title(db_handle):
    """
	Tests whether a question can be created without a title or not.
	"""
    questionnaire = _get_questionnaire()
    question1 = Question(questionnaire=questionnaire,
                         description="this is a non-title test")
    question2 = Question(title="test",
                         description="this is a non-questionnaire test")
    db.session.add(questionnaire)
    db.session.add(question1)
    db.session.add(question2)
    with pytest.raises(exc.IntegrityError):
        db.session.commit()
def _populate_db():
    """
    Pre-populate database with 2 questionnaires.One of the questionnaire has 3 questions 
    and 1 answer for each question. The other questionnaire has no question.
    """
    _questionnaire = Questionnaire(
        title="test-questionnaire-1",
        description="test-questionnaire"
    )
    db.session.add(_questionnaire)
    db.session.add(Questionnaire(
        title="test-questionnaire-2",
        description="test-questionnaire"
    ))
    for i in range(1, 4):
        q = Question(
            title="test-question-{}".format(i),
            description="test-question",
            questionnaire=_questionnaire
        )
        a = Answer(
            userName="******".format(i),
            content="test-answer",
            question=q
        )
        db.session.add(q)
        db.session.add(a)
    db.session.commit()
def create_question(_title, _questionnaire, _description=""):
    """
	Create a question with title and description.
	Titles are mandatory while descriptions are optional.
	It's also mandatory to put it into a specific questionnaire.
	"""
    if (_description != ""):
        question = Question(title=_title,
                            description=_description,
                            questionnaire=_questionnaire)
    else:
        question = Question(title=_title, questionnaire=_questionnaire)

    db.session.add(question)
    print("A new question is created.")
    print("Title: ", _title)
    print("Description: ", _description)
    print("--------------------")
    return question
Example #7
0
def _get_question(_questionnaire):
    """
	An example of question in a specific questionnaire.
	"""
    question = Question(
        title="Choose a date",
        description=
        "Between 1st of March and 4th of March, please tell us the dates you are available.",
        questionnaire=_questionnaire)

    return question
Example #8
0
def add_questions(question_file):
    with open(question_file) as f:
        for line in f:
            line = line.split(',')
            number = int(line[0])
            html = line[1].strip()
            lesson_title = line[-1].strip()
            lesson = Lesson.query.filter(Lesson.title == lesson_title).first()
            question = Question(number=number, html=html, lesson=lesson)
            db.session.add(question)
            db.session.commit()
Example #9
0
    def test_question(self):
        q = Question(question="ABCDEFG",
             label="ABC",
             a="A", 
             b="B", 
             c="C", 
             d="D", 
             answer=3)

        expected = "ABCDEFG"

        assert q.question == expected
Example #10
0
def publish_question(query, user_id, chat_id, msg_id):
    question = Question.query.filter_by(text=query).filter_by(
        user_fk=user_id).first()

    if not question:
        question = Question(text=query,
                            chat_id=chat_id,
                            user_fk=user_id,
                            msg_id=msg_id)
        db.session.add(question)
        db.session.commit()

    return question.id
Example #11
0
def getCategoryQuestionsByID(fs):
    returnObj = {}
    q = Question(fs).getQuestionsByCat()
    try:
        if 'error' not in q[0].keys():
            returnObj['questions'] = q
        else:
            returnObj = q
    except KeyError as e:
        returnObj = {
            'error': {
                'error': 'None',
                'msg': 'No question are available for this category'
            }
        }

    returnJson(returnObj)
Example #12
0
import csv
from app import db, Question, Answer

with open("data.csv", 'rU') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        question = row['Question']
        choices = row['Choices']
        answer = row['Answer']
        qid = row['QID']
        q = Question(question, choices, qid)
        db.session.add_all([q])
        db.session.commit()
        a = Answer(answer, qid)
        db.session.add_all([a])
        db.session.commit()
Example #13
0
    exit / e:    exit
"""


if __name__ == "__main__":
    engine = sa.create_engine(DATABASE_URL)
    session = sessionmaker(autoflush=True)
    session.configure(bind=engine)
    sess = session()
    if sys.argv[-1] != "add_question.py" and os.path.isfile(sys.argv[-1]):
        with open(sys.argv[-1]) as questions:
            for q in questions.read().split("\n"):
                q = unicode(q)
                if not sess.query(Question).filter(Question.text == q).all():
                    Question.new(q, sess)
                    print "Added ", q
                else:
                    print "Already in DB:", q
        if raw_input("Are you sure you want to commit? (Y/N)\n>").lower() in ["y", "yes"]:
            sess.commit()
            print "Commited"
        else:
            sess.rollback()
            print "Did not commit"
    else:
        for q in Question.all(sess):
            print q.id, ":", q.text
        while True:
            inp = raw_input("Enter Command:\n>").lower()
            if inp in ["new", "n"]:
Example #14
0
from mongoengine import *
from app import User, Question, Attempt

client = connect("psle_test")

# remove ALL the users in the database
User.drop_collection()
Question.drop_collection()
Attempt.drop_collection()

# create users
u1 = User(name="Joshua", email="*****@*****.**", password="******")
u1.save()
u2 = User(name="Isaac", email="*****@*****.**", password="******")
u2.save()
u3 = User(name="Cow", email="*****@*****.**", password="******")
u3.save()
u4 = User(name="moo", email="*****@*****.**", password="******")
u4.save()
# # create questions
q1 = Question(text="Joshua went the the market to buy ___head biscuits",
              options=["went", "arrow", "sheep", "cow"],
              answer=4,
              credit="oxcow university")
q1.save()
q2 = Question(text="Joshua and Isaac were eating ___head biscuits ",
              options=["cow", "arrow", "went", "sheep"],
              answer=1,
              credit="cowbridge university")
q2.save()
q3 = Question(text="Isaac exclamed that ___head biscuits were his favourite",
Example #15
0
def result():
    if 'id' not in session:
        return redirect(url_for('index'))
    result = Question.getResult(app.database_url)
    return render_template('result.html', result=result)
Example #16
0
def finish():
    if 'id' not in session or 'answers' not in session or session['answers']==[]:
        return redirect(url_for('index'))
    Question.setFinish(app.database_url)
    return render_template('finish.html')
from app import db
db.create_all()
from app import Question, Comment, Tag, Explanation
from app import MChoiceOption as MC
q = Question("H2G2 Q1", "What do you get when you multipyly 6 x 9?")
q.tags = ['h2g2']
q.options = [MC('0'), MC('1'), MC('42', True), MC('over 9000')]
q.rating = -1
q.explanations.append(Explanation("It's the answer to life, universe, and everything."))
q.comments.append(Comment("Douglas Adams is awesome."))
db.session.add(q)


q = Question("H2G2 Q2", "What is Zaphod Beeblebrox's favorite drink?")
q.tags = ['h2g2']
q.options = [MC('Liquid that is almost, but not quite, entirely unlike tea'),
			 MC('Pan-galactic gargle blaster', True),
			 MC('White Russian'),
			 MC('Diet Coke')]
q.rating = -1
q.explanations.append(Explanation("The effect of drinking a Pan Galactic Gargle Blaster is like having your brains smashed out by a slice of lemon wrapped around a large gold brick."))
db.session.add(q)

db.session.commit()
Example #18
0
import json
from app import db

db.create_all()
from app import Question, Comment, Tag, Explanation

with open("./questions2.json") as f:
    try:
        questions = json.load(f)
        for qdict in questions:
            q = Question.from_data(qdict)
            db.session.add(q)
    except Exception as e:
        print "Invalid JSON: %s" % e

db.session.commit()
Example #19
0
def test_try_save_question2db(client):
    nq = Question(file_name = 'test_file_name', file_url = '2', description = '3', cell_code = '4', cell_output = '5' )
    db.session.add(nq)
    db.session.commit()
    assert nq.id > 0
    assert nq.__repr__() == 'description 3'