Beispiel #1
0
def report_bug():
    form = BlankForm()
    seed = session.get('seed')
    user_answer = session.get('user_answer')
    question_name = session.get('question_name')
    if form.validate_on_submit():
        return send_report_bug_email(question_name, seed, user_answer)
    return redirect(url_for('library'))
Beispiel #2
0
def publish():
    from .mrsstest import convert
    import os
    import json
    import logging
    import boto3
    from botocore.exceptions import ClientError
    convert()
    """upload to S3"""
    bucket_name = 'mrsstest-022319'
    filename = 'rss2.xml'
    AWS_ACCESS_KEY_ID = os.environ.get('ACCESS_KEY')
    AWS_SECRET_ACCESS_KEY = os.environ.get('SECRET_KEY')

    s3 = boto3.resource('s3')
    bucket = s3.Bucket(bucket_name)
    bucket.upload_file(filename, filename, ExtraArgs={'ACL': 'public-read'})
    location = boto3.client('s3').get_bucket_location(
        Bucket=bucket_name)['LocationConstraint']
    url = "https://s3-%s.amazonaws.com/%s/%s" % (location, bucket_name,
                                                 filename)

    form = BlankForm()
    posts = []

    publish_message = url
    return render_template('posts.html',
                           title='Home Page',
                           form=form,
                           posts=posts,
                           publish_message=publish_message)
Beispiel #3
0
def unobserve(username):
    form = BlankForm()
    if form.validate_on_submit():
        user = Student.query.filter_by(username=username).first()
        if user is None:
            flash('User {} not found.'.format(username))
            return redirect(url_for('library'))
        if user == current_user:
            flash('You cannot un-observe yourself!')
            return redirect(url_for('user', username=username))
        current_user.unobserve(user)
        db.session.commit()
        flash('You are no longer an observer of {}.'.format(username))
        return redirect(url_for('user', username=username))
    else:
        return redirect(url_for('library'))
Beispiel #4
0
def name_as_observer(username):
    form = BlankForm()
    if form.validate_on_submit():
        user = Student.query.filter_by(username=username).first()
        if user is None:
            flash('User {} not found.'.format(username))
            return redirect(url_for('library'))
        if user == current_user:
            flash('You automatically observe yourself.')
            return redirect(url_for('user', username=username))
        current_user.name_as_observer(user)
        db.session.commit()
        flash('You are now observed by {}!'.format(username))
        return redirect(url_for('user', username=username))
    else:
        return redirect(url_for('library'))
Beispiel #5
0
def user(username):
    profile_user = Student.query.filter_by(username=username).first_or_404()
    # answers = StudentAnswer.query.filter_by(user_id=profile_user.id).all()
    # books = []
    # for answer in answers:
    #     answer = answer.__dict__
    #     book = answer.get('book')
    #     if book not in books and book is not None:
    #         books.append(book)
    # books = get_user_books(profile_user)
    grades = UserGradeInfo(profile_user)
    # book_names = grades.get_book_names()
    # print('book_names: ', book_names)
    # user_books = []
    # for book_name in book_names:
    #     book = getattr(books, book_name)
    #     user_books.append(book)
    user_books = grades.get_books()
    form = BlankForm()
    try:
        observed = current_user.observed_students.order_by(
            Student.lastname.asc(), Student.firstname.asc()).all()
    except AttributeError:
        observed = None
    return render_template('user.html',
                           user=profile_user,
                           form=form,
                           grades=grades,
                           user_books=user_books,
                           observed=observed)
Beispiel #6
0
def posts():
    form = BlankForm()

    if not os.path.isfile('MSNIngest.json'):
        posts = []
    else:
        with open('MSNIngest.json', mode='r', encoding='utf-8') as postsjson:
            posts = json.load(postsjson)

    return render_template('posts.html',
                           title='Home Page',
                           form=form,
                           posts=posts,
                           publish_message='')
Beispiel #7
0
def section(section_name):
    session['section_name'] = section_name  ## Added 12/16/2020
    section = getattr(books, section_name)
    template_path = section.template_path
    section_display_name = section.display_name
    questions = section.questions
    # print(questions)
    if questions != []:
        if current_user.is_authenticated:
            section_status = UserSectionStatus.query.filter_by(
                student=current_user, section_name=section_name).first()
            if section_status == None:
                section_status = UserSectionStatus(student=current_user,
                                                   section_name=section_name,
                                                   grade=0)
                db.session.commit()
            if section_status.underway:
                question_name = section_status.underway_question_name
                if question_name not in questions:
                    question_name = random.choice(questions)
            else:
                question_name = random.choice(questions)
        else:
            question_name = random.choice(questions)
    else:
        question_name = False
    # print(question_name)
    form = BlankForm(
    )  #I added this for testing purposes: looking to add interactives the section pages...
    if 'data' in request.form:
        return 'Flask says hi'
    return render_template(template_path + '.html',
                           section_display_name=section_display_name,
                           section=section,
                           form=form,
                           question_name=question_name)
Beispiel #8
0
def question(question_name):
    """
    A rewrite could
    include using only one 'form' of the type AnswerForm, but
    deciding whether to display an answer field or instead
    write to it secretly based on either multiple
    answer fields or based on interaction with a graph, etc.  ...
    An arbitrary page should also be used in place of
    question_page.html---that is, the template to be rendered
    should be a variable that is determined by the attribute
    question.template.  Of course, many of these templates
    could inherit from a common template, too!  Many other
    functions should be tossed to methods of the
    question = QuestionClass() object.  For instance, ajax
    handling could happen there.  Interpolator should be moved
    to the questions module...
    """
    # print('session at first', session)
    # if request.args.get('bug_id'):
    #     answer_id = request.args.get('bug_id')
    #     bug_answer = StudentAnswer.query.filter_by(id=answer_id).first()
    # print('bug_answer.seed', bug_answer.seed)
    # print(request.args)
    bug_form = ReportBugForm()
    book_info = {}
    session['question_name'] = question_name
    if current_user.is_authenticated:  ## Added 12/16/2020
        section_name = session.get('section_name')  ## Added 12/16/2020
        # print(section_name)
        if not session.get('tried'):
            if section_name is None:
                # print('this is untested')
                return redirect(url_for('logout'))
                # session['tried'] = True
            else:
                _section = getattr(books, section_name)
                # print('The section is', section_name)
                if question_name not in _section.questions:
                    # print('logged you out since question not in section')
                    flash(
                        'You need to navigate to or from the corresponding book section in order to get credit.  You have been logged out.'
                    )
                    # session['tried'] = True
                    return redirect(url_for('logout'))
        grade_info = UserSectionStatus.query.filter_by(
            student=current_user,
            section_name=section_name).first()  ## Added 12/16/2020;
        # if section_name is not None and grade_info is None:
        #     print('this is untested also')
        #     grade_info = UserSectionStatus(current_user, section_name, grade=0) #This is untested, but seems necessary...
    else:  ## Added 12/16/2020
        # print('no user!!!!!')
        grade_info = None  ## Added 12/16/2020
    if current_user.is_authenticated:
        user_book_names = json.loads(current_user.books)
        # user_books = [getattr(books, book_name) for book_name in user_book_names]
        books_info = []
        for book_name in user_book_names:
            book = getattr(books, book_name)
            info = book.get_skill_info(question_name)
            for occurrence in info:
                books_info.append({
                    'book': book.name_for_path,
                    'chapter': occurrence[0],
                    'section': occurrence[1]
                })
    if session.get('section'):
        book_name = session.get('book')
        book = getattr(books, book_name)
        main = book.subdivisions['main']
        chapter_number = int(session.get('chapter'))
        chapter = main.subdivisions[chapter_number - 1]
        section_number = int(session.get('section'))
        section = chapter.subdivisions[section_number - 1]
        book_info = {
            'book': book.name_for_path,
            'chapter': chapter_number,
            'section': section_number
        }
        # print('section: ', section)
        # print('book info: ', book_info)
    user_poly_points = ''
    graph = None
    correct_answer_poly_points = ''
    # if request.method == 'GET':
    parameters = None
    question_module = getattr(questions, question_name)
    if current_user.is_authenticated:
        user = current_user
    else:
        user = {'username': '******'}
    # validator = question_module.Question_Class.validator
    if question_module.prob_type == 'graph':
        # print("Working with a graph here")
        form = BlankForm()
        whether_graph = True
        parameters = interpolator.get_parameters()
        # print('parameters: ', parameters, '; type is ', type(parameters))
        # print('This is how I view form.validate_on_submit: ', form.validate_on_submit())
        if 'data' in request.form and not form.validate_on_submit():
            points = request.form["data"]
            shift_y = json.loads(request.form["shift_y"])
            print('shift_y', shift_y)
            # session['user_answer'] = points # for bug reporting
            # print('points straight from page: ', type(points))
            points = json.loads(points)
            # print(points)
            return_data = interpolator.get_dict_for_svg(points,
                                                        shift_y=shift_y)
            # graph = interpolator.Graph(points)
            # graph.gen_dict_for_svg()
            # return_data = graph.svg_data
            # print(return_data)
            #return json.dumps(data)
            # graph = interpolator.Graph(points)
            session['user_points'] = points
            session['shift_y'] = shift_y
            # print('session says the user answer is:', session['user_answer'])
            return json.dumps(return_data)
    elif question_module.prob_type == 'real_line_graph':
        form = question_module.form()
        real_line = True
        whether_graph = False
    else:
        validator = question_module.Question_Class.validator
        form = AnswerForm(validator)
        # print('form.answer.data just after (re)instantiation', form.answer.data)
        whether_graph = False
        real_line = False
    if request.method == 'GET':
        session['user_answer'] = json.dumps(None)
        if request.args.get('bug_id'):
            bug_id = request.args.get('bug_id')
            bug_answer = BugReport.query.filter_by(id=bug_id).first()
            session['tried'] = True
            session['seed'] = bug_answer.seed
            # print('session seed after bug assignment', session['seed'])
            if whether_graph:
                try:
                    session['user_points'] = json.loads(bug_answer.user_answer)
                except (json.decoder.JSONDecodeError, TypeError) as e:
                    session['user_points'] = []
            elif question_module.prob_type == 'real_line_graph':
                # print('Not my fault!')
                try:
                    user_answer = json.loads(bug_answer.user_answer)
                    user_points = user_answer['user_points']
                    user_intervals = user_answer['user_intervals']
                except:
                    return f'bug_id: {bug_id}, seed: {bug_answer.seed}, question_name: {bug_answer.question_name}'
            else:
                form.answer.data = bug_answer.user_answer
        elif request.args.get('ans_id'):
            # print('This worked!')
            ans_id = request.args.get('ans_id')
            answer = StudentAnswer.query.filter_by(id=ans_id).first()
            session['tried'] = True
            session['seed'] = answer.seed
            flash(
                'This is your original submission, but the problem is just for practice now.'
            )
            if whether_graph:
                try:
                    info = json.loads(answer.user_answer)
                    # session['user_points']
                    if type(info) == dict:
                        session['user_points'] = info.get('points')
                        session['shift_y'] = info.get('shift_y')
                    else:
                        session['user_points'] = info
                except (json.decoder.JSONDecodeError, TypeError) as e:
                    session['user_points'] = []
            elif question_module.prob_type == 'real_line_graph':
                question = question_module.Question_Class(seed=session['seed'])
                answer = json.loads(answer.user_answer)
                user_points = answer['user_points']
                user_intervals = answer['user_intervals']
                question.points = user_points
                question.intervals = user_intervals
            else:
                form.answer.data = answer.user_answer
        elif request.args.get('skip_to_exercises'):
            # print('It worked!')
            session['tried'] = True
            session['seed'] = random.random()
            question = question_module.Question_Class(seed=session['seed'])
            session['user_points'] = []
            flash(
                'This problem is just for practice.  If you want to work one for credit, navigate from a book section.'
            )
        elif current_user.is_authenticated and grade_info.underway:
            question = question_module.Question_Class(
                seed=grade_info.underway_seed)
            session['tried'] = False
            session['seed'] = grade_info.underway_seed
            session['user_points'] = []
        else:  # AttributeError:
            # print('Else anonymous!!!')
            session['tried'] = False
            session['seed'] = random.random()
            if current_user.is_authenticated:
                grade_info.underway = True
                grade_info.underway_question_name = question_name
                grade_info.underway_seed = session['seed']
                db.session.commit()
            session['user_points'] = []
        # form.seed.data = session['seed']

    try:
        question
    except NameError:
        try:
            question = question_module.Question_Class(seed=session['seed'])
        except:
            question = question_module.Question_Class()
    # print('session seed', session['seed'])

    if whether_graph:
        points = session.get('user_points')
        print(points)
        shift_y = session.get('shift_y')
        # print('These are the points in session: ', points)
        # print('This is what I think about the form: ', form)
        # graph = interpolator.Graph(points, shift_y=shift_y) # I don't actually use 'shift_y'... I did temporarily... It's a nice proof of concept for further use of ajax here, but I preferred another solution from a philosphical perspective.
        graph = interpolator.Graph(points)
        print('graph.vert is', graph.vert)
        if points != []:
            print('points is not []')
            if not graph.vert:
                print('thinks graph not vert')
                useranswer = graph.as_lambda
            else:
                print('graph.vert == True')
                useranswer = points[0][0]
            graph.gen_dict_for_svg()
            # if graph.piecewise:
            # #     print('yay!')
            #     user_poly_points = graph.
            # else:
            # #     print('still yay!')
            user_poly_points = graph.poly_points
            # user_answer_for_db = json.dumps({'points': points, 'shift_y': shift_y})
            user_answer_for_db = json.dumps(points)
        else:
            useranswer = None
            user_answer_for_db = json.dumps([])
        x_min = parameters['cart_x_min']
        x_max = parameters['cart_x_max']
        correct_answer_poly_points = question.get_svg_data([x_min, x_max])
        # print("session['useranswer']", session['user_answer'])
    elif question_module.prob_type == 'real_line_graph':
        if form.points.data:
            user_points = json.loads(form.points.data)
            question.points = user_points
        elif request.args.get('bug_id'):
            question.points = user_points
        else:
            user_points = []
        # for item in user_points:
        #     print('point:', item)
        #     print('type:', type(item))
        # print(user_points)
        if form.intervals.data:
            user_intervals = json.loads(form.intervals.data)
            question.intervals = user_intervals
        elif request.args.get('bug_id'):
            question.intervals = user_intervals
        else:
            user_intervals = []
        # for item in user_intervals:
        #     print('interval:', item)
        #     print('type:', type(item))
        useranswer = {
            'user_points': user_points,
            'user_intervals': user_intervals
        }
        user_answer_for_db = json.dumps(useranswer)
    else:
        useranswer = form.answer.data
        session['user_answer'] = form.answer.data or session.get(
            'user_answer')  #for bug report
        user_answer_for_db = useranswer
        correct_answer_poly_points = ''
    # print("request.args.get('form')", request.args.get('form'))
    # Added the request.args.get('form') == 'form' requirement in the process
    # of figuring out if I could have a second submit button---for submitting
    # requests for a preview of the math AnswerForm
    if form.validate_on_submit() and request.args.get(
            'form') == 'form' and not (whether_graph and points == []):
        correct = question.checkanswer(useranswer)
        if current_user.is_authenticated and not session['tried']:
            user = current_user
            now = datetime.datetime.utcnow()
            diff = now - grade_info.timestamp
            if diff > datetime.timedelta(0, 5, 0):
                grade_info.update_grade_after_user_attempt(
                    correct, now, commit=False)  ## Added 12/16/2020
                for book_info in books_info:
                    answer_event = StudentAnswer(
                        student=user,
                        skillname=question_name,
                        grade_category='check',
                        seed=session['seed'],
                        book=book_info.get('book'),
                        chapter=book_info.get('chapter'),
                        section=book_info.get('section'),
                        user_answer=user_answer_for_db)
                    db.session.add(answer_event)
                    if correct:  # Just in case you get clever and think you can just do answer_event.correct = correct, you might be wrong.... why I don't know!! ... oh, perhaps it is because of sympy returning special Boolean types rather than simple ones and sqlalchemy doesn't like them
                        answer_event.correct = True
                    else:
                        answer_event.correct = False
                    # answer_event.correct = correct
            grade_info.underway = False
            db.session.commit()
        if correct:
            message = 'You got it right!!'
            if session['tried'] == True:
                message += " But you'll have to try a new problem to earn credit."
        else:
            message = "Incorrect. You'll have to try a new problem."
            if whether_graph:
                message = 'The correct answer is in <span style="color:green">green</span>.'
            if question_module.prob_type == 'real_line_graph':
                message = 'The correct answer is in <span style="color:green">green</span>'
        # if current_user.is_authenticated and not session['tried']:
        #     db.session.commit()
        session['tried'] = True
    else:
        if request.method == 'POST':
            if session['tried'] == False:
                message = 'You can try again, since you just had a syntax error.'
                if (whether_graph and points == []):
                    message = "You left it blank!  You may try again."
            else:
                message = """You had a syntax error,
but you should try a different problem if you want credit."""
            if bug_form.validate_on_submit() and request.args.get(
                    'form') == 'bug_form':
                # print('bug_form_validated')
                flash(
                    'A bug report email was just sent to your friendly Ency-O Admin!'
                )
                # print('form.answer.data', form.answer.data)
                # try:
                #     bug_answer = form.answer.data
                # except:
                #     bug_answer = json.dumps(session.get('user_points'))
                # print('bug_form.user_answer.data:', bug_form.user_answer.data)
                answer = bug_form.user_answer.data or session['user_answer']
                bug_report = BugReport(user_answer=answer,
                                       seed=session['seed'],
                                       question_name=question_name)
                db.session.add(bug_report)
                db.session.commit()
                bug_report = BugReport.query.filter_by(
                    user_answer=answer,
                    seed=session['seed'],
                    question_name=question_name).all()[-1]
                report_id = bug_report.id
                # print('report_id', report_id)
                send_report_bug_email(report_id)
            # if preview_form.validate_on_submit() and request.args.get('form') == 'preview_form':
            #     return redirect(url_for('answer_previewer', question_name=question_name))
        else:
            message = "It's a brand new problem!!"
    # print('session user_points just before rendering', session.get('user_points'))
    # print('current book: ', session.get('book'))
    if session.get(
            'section'
    ):  # This can result in jumping to an unintended question if the page is accessed directly.
        new_question_name = random.choice(section.questions)
        # print('new_question_name: ', new_question_name)
    else:
        new_question_name = question_name

    ###############################
    #This is for the progress bar.   Commented out on 12/16/2020
    ###############################
    # if current_user.is_authenticated:
    #     book_info = books_info[0]
    #     # grades = UserGradeInfo(current_user)
    #     # print(current_user.username)
    #     # print('book', book_info.get('book'))
    #     # print('chapter', book_info.get('chapter'))
    #     # print('section', book_info.get('section'))
    #     grade_info = UserSectionGradeInfo(current_user,
    #                                     book_info.get('book'),
    #                                     book_info.get('chapter'),
    #                                     book_info.get('section'))
    #     # print('grade is:', grade_info.grade)
    # else:
    #     grade_info = None
    #
    #  ## Concludes comment from 12/16/2020
    ###############################
    return render_template(
        'question_page.html',
        user=user,
        title='Question',
        site_name=app.config['SITE_NAME'],
        form=form,
        question=question,
        tried=session['tried'],
        message=message,
        whether_graph=whether_graph,
        parameters=parameters,
        question_name=new_question_name,
        points=session.get('user_points'),
        graph=graph,
        correct_answer_poly_points=correct_answer_poly_points,
        user_poly_points=user_poly_points,
        grade_info=grade_info,
        bug_form=bug_form)