def assessment(self, app):
     with app.app_context():
         db.session.add(
             Assessment(id=100, supplier_domain_id=100, active=True))
         db.session.add(
             Assessment(id=101, supplier_domain_id=101, active=False))
         db.session.commit()
         yield db.session.query(Assessment).all()
Esempio n. 2
0
def assessments(app, supplier_domains):
    with app.app_context():
        for sd in supplier_domains:
            db.session.add(Assessment(supplier_domain_id=sd.id))
            db.session.flush()
        db.session.commit()
        yield Assessment.query.all()
Esempio n. 3
0
def addAssessment():
    if not current_user.is_admin:
        return redirect(url_for('index'))

    assessment_form = AddAssessmentForm()

    if assessment_form.validate_on_submit():
        assessment = Assessment(
            question=assessment_form.question.data, 
            answer=assessment_form.answer.data)

        db.session.add(assessment)
        assessment.link_to_users()
        db.session.commit()
        flash("Successfully created assessment.")
        return redirect(url_for('index'))

    return render_template('AddAssessment.html', assessment_form=assessment_form)
def assessments(app, request, supplier_domains, briefs):
    with app.app_context():
        for i in range(1, 6):
            supplier_domain = supplier_domains[i]
            db.session.add(
                Assessment(supplier_domain=supplier_domain, briefs=briefs))
            db.session.flush()

        db.session.commit()
        yield Assessment.query.all()
 def domain_assessments(self, app):
     with app.app_context():
         db.session.add(Assessment(id=1, supplier_domain_id=1, active=True))
         db.session.add(Assessment(id=2, supplier_domain_id=2, active=True))
         db.session.add(Assessment(id=3, supplier_domain_id=3,
                                   active=False))
         db.session.add(Assessment(id=4, supplier_domain_id=4, active=True))
         db.session.add(Assessment(id=5, supplier_domain_id=5, active=True))
         db.session.add(Assessment(id=6, supplier_domain_id=6, active=True))
         db.session.add(Assessment(id=7, supplier_domain_id=7, active=True))
         yield db.session.query(Assessment).all()
Esempio n. 6
0
def send_assessment():
    user_id = int(session["userid"])
    cur_week = int(request.form.get('week_id'))
    assqt_id = int(request.form.get('assqt_id'))
    answers_cou = request.form.get('answers_cou')

    _aq = Assqt.query.get(assqt_id)
    if _aq:
        for _c in _aq.checked_by:
            if _c.id == user_id:
                flash("You've already assessed this assignment")
                return redirect('/')

    for i in range(1, int(answers_cou) + 1):
        _a = Assessment()
        _a.answer = Answer.query.get(
            int(request.form.get('ans_id_{}'.format(i))))
        if _a.answer.user.id == user_id:
            flash("It's impossible to assess your own assignment")
            return redirect('/')
        _a.assessed_by = User.query.get(int(session["userid"]))
        _a.score = request.form.get('rg2_{}'.format(i))
        _a.descr = request.form.get('ans_desc_{}'.format(i))
        db.session.add(_a)

    if _aq:
        _aq.checked_by.append(User.query.get(user_id))
        _aq.checks_left -= 1

        for lock in _aq.alocks:
            if lock.user_id == user_id:
                db.session.delete(lock)
        if _aq.checks_left == 0:
            db.session.delete(_aq)

    _ck = Check.query.filter(
        and_(Check.user_id == user_id, Check.week_id == cur_week)).first()

    if _ck is None:
        _ck = Check()
        _ck.user = User.query.get(user_id)
        _ck.week = Week.query.get(cur_week)
        _ck.checks_count = 0
        db.session.add(_ck)

    _ck.checks_count += 1

    if _ck.checks_count == checks_by_user:
        _ck.is_all_done = True

    db.session.commit()

    return redirect('/')
Esempio n. 7
0
def index():  ## this is run when the URLs are called ('view function')
    form = SurveyForm() ## instantiating our SurveyForm(), values taken from the users

    if form.validate_on_submit():  ## if form passed via submit in html

        address = Address(form.raw_address.data)  ## instantiating our Address class from address.py with the raw_address data passed from html (via SurveyForm)

        ## assigning the input values to our Assessment database in models.py
        assessment = Assessment(raw_address=form.raw_address.data,
                                lat = address.lat,
                                lng = address.lng,
                                street_number = address.street_number,
                                street_name = address.street_name,
                                city_name = address.city_name,
                                state_abr = address.state_abr,
                                postal_code = address.postal_code,
                                formatted_address = address.formatted_address,
                                agent_est = form.agent_est.data,
                                applicant_est = form.applicant_est.data,
                                google_place_id = address.google_place_id,
                                street_pic = address.street_pic,
                                zillow_estimate = address.zillow_estimate,
                                zillow_baths = address.zillow_baths,
                                zillow_bedrooms = address.zillow_bedrooms,
                                damage = form.damage.data,
                                other_damage = form.other_damage.data,
                                exterior = form.exterior.data,
                                interior = form.interior.data,
                                other_exterior = form.other_exterior.data,
                                other_interior = form.other_interior.data,
                                disaster_type = form.disaster_type.data,
                                disaster_name = form.disaster_name.data,
                                comments = form.comments.data,
                                author=current_user)
        db.session.add(assessment)  ## adding assessment to the db
        db.session.commit()  ## committing this addition
        flash('You have logged an assessment')  ## displaying success
        return redirect(url_for('index'))  ## redirecting to index URL

    ## conducting query from User db (in models.py) to access all assessments
    assessments = current_user.assessment_list().all()

    ## we return, to the html file in our template folder the forms and assessments
    return render_template('index.html', title='Home Page', form=form, assessments=assessments)
Esempio n. 8
0
def assessment():
    assessment: Assessment = Assessment.get_new_assessment(current_user.id)
    
    if assessment is None:
        flash("No more assessments!")
        return redirect(url_for('index' ))

    userAssessment: UserAssessment = UserAssessment.query.filter_by(user_id=current_user.id, assessment_id=assessment.id).first()
    answer_form = AnswerForm()

    if answer_form.validate_on_submit():
        if answer_form.answer.data == assessment.answer:
            flash("Correct!")
            userAssessment.completed = True
            userAssessment.correct = True
        else:
            flash("Incorrect!")
            userAssessment.completed = True
            userAssessment.correct = False

        db.session.commit()
        return redirect(url_for('assessment'))

    return render_template('AssessmentPage.html', assessment=assessment, answer_form=answer_form)
Esempio n. 9
0
    def create(self, validated_data):
        del validated_data['user']

        assessment = Assessment(**validated_data)
        assessment.save()
        return Assessment
Esempio n. 10
0
from app import db
from app.models import Assessment

# Initialise list of assessments
assessments = list()

# Add a bunch of assessments
assessments.append(Assessment(
    question="""If a person running with an inital speed of 5m/s slows down
with an acceleration of 0.5m/s^2,
how long does it take for them to stop moving/ have a final speed of 0. Do not put units in your answer.""", 
    answer="10"))


assessments.append(Assessment(
    question="""If a cat had an initial velocity 3m/s,
speeds up with an acceleration of 1 m/s^2, and travels 10m,
what is its final velocity at the end of the 10 meters?
Do not put units in your answer, use 3 decimal places in your answer.""", 
    answer="5.385"))

assessments.append(Assessment(
    question="""If a comet has an initial velocity 1000m/s,
and has a final velocity of 3000m/s,
if there was 30 seconds between the comet having the intial speed and the final speed,
how far did it travel? Do not put units in your answer.""", 
    answer="60000"))

assessments.append(Assessment(
    question="""If a car had an initial velocity 10m/s,
speeds up with an acceleration of 1 m/s^2 for 10 seconds
Esempio n. 11
0
def assessment():
    form = AssessmentForm(obj=request.form)

    if request.method == 'POST':
        if form.validate_on_submit():
            rate = (form.loan_apr.data / 100 / 12)
            monthly_repayments = round(
                (form.loan_amount.data * rate) /
                (1 - (1 + rate)**(-1 * int(form.loan_term.data))), 2)
            initial_month_interest = round(form.loan_amount.data * rate, 2)
            initial_month_capital = round(
                monthly_repayments - initial_month_interest, 2)

            def loan_reason_score(i):
                switcher = {
                    '0': 3.0,
                    '1': 2.5,
                    '2': 3.0,
                    '3': 2.0,
                    '4': 4.0,
                    '5': 3.0,
                    '6': 2.5
                }
                return switcher.get(i, 0.0)

            def loan_term_score(d, i):
                if int(d) < 37:
                    i = '0'  # 2
                elif int(d) < 73:
                    i = '1'  # 3.5
                else:
                    i = '2'  # 2
                switcher = {'0': 2.0, '1': 3.5, '2': 2.0}

                return switcher.get(i, 0.0)

            details = Assessment(
                age_band=form.age_band.data,
                job_security=form.job_security.data,
                country=form.country.data,
                available_savings=form.available_savings.data,
                monthly_income=form.monthly_income.data,
                monthly_expenses=form.monthly_expenses.data,
                loan_reason=form.loan_reason.data,
                loan_term=int(form.loan_term.data),
                loan_apr=form.loan_apr.data,
                loan_amount=form.loan_amount.data,
                lender_id=form.lender.data.id,
                monthly_repayments=monthly_repayments,
                monthly_interest_repayments=initial_month_interest,
                monthly_capital_repayments=initial_month_capital,
                total_amount_payable=monthly_repayments *
                int(form.loan_term.data),
                total_interest_payable=(monthly_repayments *
                                        int(form.loan_term.data)) -
                form.loan_amount.data,
                new_monthly_expenses=form.monthly_expenses.data +
                monthly_repayments,
                new_monthly_surplus=0.00,
                total_capital_payable=initial_month_capital *
                int(form.loan_term.data),
                loan_reason_score=loan_reason_score(form.loan_reason.data),
                loan_term_score=loan_term_score(form.loan_term.data, '0'))
            db.session.add(details)
            db.session.commit()
            assessment_record_id = details.id
            flash('Thank you for completing the assessment', 'success')
            assessment_data = Assessment.query.get_or_404(assessment_record_id)
            form = SummaryForm()
            if form.validate_on_submit():
                pass
            return render_template('summary.html',
                                   title='Assessment Summary',
                                   assessment=assessment_data,
                                   form=form)
    return render_template('assessment.html', title='Assessment', form=form)
def assessment(app, supplier_domain):
    with app.app_context():
        db.session.add(Assessment(id=1, supplier_domain_id=1))
        yield db.session.query(Assessment).filter(Assessment.id == 1).first()
Esempio n. 13
0
def assessment_creator(self, serializer):
    """Method responsible for creating new assessments

    Raises:
        MultiValueDictKeyError -- Raised when not enough arguments have been passed

    Returns:
        HttpResponse -- Whether resource has been successfully created or not
    """

    try:
        user = self.request.user
        name = self.request.POST.get("name", "")
        course_id = self.request.POST.get("course_id", "")
        description = self.request.POST.get("description", "")
        additional_help = self.request.POST.get("additional_help", "")

        deadline = self.request.POST.get('deadline', "")

        dynamic_input = self.request.POST["dynamicInput"]
        static_input = self.request.POST["staticInput"]

        languages = [
            x for x in json.loads(self.request.POST.get('languages', ""))
        ]
        selected_language = self.request.POST.get('selected_language', "")
        num_of_static = int(self.request.POST.get('numOfStatic', ""))

        if static_input == "true":
            for i in range(int(num_of_static)):
                if 'inputFile' + str(
                        i) not in self.request.FILES or 'outputFile' + str(
                            i) not in self.request.FILES:
                    raise MultiValueDictKeyError
    except MultiValueDictKeyError:
        return HttpResponseBadRequest(
            "Looks like you have an empty field or an unknown file type.")
    except Exception as e:
        logger.error(e)
        return HttpResponseBadRequest("Unexpected error.")

    if name == "" or description == "":
        return HttpResponseBadRequest("Looks like you have an empty field.")

    if not user.is_staff:
        return HttpResponseForbidden(
            "You are not allowed to create assessments")

    course = Course.objects.get(pk=course_id)

    assessment = Assessment(name=name,
                            description=description,
                            additional_help=additional_help,
                            course=course,
                            languages=languages,
                            deadline=deadline,
                            static_input=json.loads(static_input),
                            dynamic_input=json.loads(dynamic_input),
                            num_of_static=num_of_static)

    assessment.save()

    if static_input == "true":
        for i in range(int(num_of_static)):
            os.makedirs(os.path.join(settings.MEDIA_ROOT, str(assessment.id),
                                     'static_inputs'),
                        exist_ok=True)
            os.makedirs(os.path.join(settings.MEDIA_ROOT, str(assessment.id),
                                     'expected_static_outputs'),
                        exist_ok=True)

            fs = FileSystemStorage(location=os.path.join(
                settings.MEDIA_ROOT, str(assessment.id), 'static_inputs'))
            static_file = self.request.FILES['inputFile' + str(i)]
            fs.save(str(i), static_file)

            fs = FileSystemStorage(
                location=os.path.join(settings.MEDIA_ROOT, str(assessment.id),
                                      'expected_static_outputs'))
            static_file = self.request.FILES['outputFile' + str(i)]
            fs.save(str(i), static_file)

    if dynamic_input == "true":

        resource_file = self.request.FILES['resource']

        resource = Resource(filename=resource_file.name,
                            status="start",
                            assessment=assessment,
                            language=selected_language)
        resource.save()

        os.makedirs(os.path.join(settings.MEDIA_ROOT, str(assessment.id),
                                 'model_solutions', str(resource.id)),
                    exist_ok=True)
        fs = FileSystemStorage(
            location=os.path.join(settings.MEDIA_ROOT, str(assessment.id),
                                  'model_solutions', str(resource.id)))

        fs.save(resource_file.name, resource_file)

        input_generator_file = self.request.FILES['input_generator']

        input_generator = InputGenerator(filename=input_generator_file.name,
                                         assessment=assessment,
                                         language=selected_language)
        input_generator.save()

        os.makedirs(os.path.join(settings.MEDIA_ROOT, str(assessment.id),
                                 'input_generators', str(input_generator.id)),
                    exist_ok=True)
        fs = FileSystemStorage(
            location=os.path.join(settings.MEDIA_ROOT, str(assessment.id),
                                  'input_generators', str(input_generator.id)))

        fs.save(input_generator_file.name, input_generator_file)

        assessment.input_generator = input_generator

        assessment.resource = resource

    assessment.save()

    return Response(assessment.id, 201)
Esempio n. 14
0
def adminAssessment():
    if request.method == "POST":

        # Add new assessment to db
        newAssessment = Assessment(category=request.form['assessmentName'])
        db.session.add(newAssessment)

        number_of_question = 0
        questions_from_form = []
        for key in request.form.keys():

            # Add questions to db
            if 'question' in key:
                newQuestion = request.form[key]
                questions_from_form.append(newQuestion)
                number_of_question += 1

        # Get the scores
        scores = []
        for value in request.form.getlist('score'):
            scores.append(value)

        # Get the answers
        answers = []
        for value in request.form.getlist('answer'):
            answers.append(value)

        a1, a2, a3, a4 = 0, 1, 2, 3
        for i in range(number_of_question):

            # Add answers and correct answers to db
            answer = Answers(question=questions_from_form[i],
                             answer1=answers[a1],
                             answer2=answers[a2],
                             answer3=answers[a3],
                             answer4=answers[a4],
                             correctAnswer=answers[a4],
                             mark=scores[i])
            db.session.add(answer)

            # Set the values for DB
            newAssessment.answer.append(answer)

            a1 += 4
            a2 += 4
            a3 += 4
            a4 += 4

        # Sum up scores to get the final result
        result = sum([int(i) for i in scores])
        newAssessment.score = result
        db.session.commit()

        assessments = Assessment.query.order_by(
            Assessment.dateCreated.desc())[:10]
        category = []
        for assessment in assessments:
            category.append(assessment.category)
        return render_template("adminAssessment.html",
                               page='admin',
                               assessmentLen=len(assessments),
                               assessment=category)

    else:
        assessments = Assessment.query.order_by(
            Assessment.dateCreated.desc())[:10]
        category = []
        for assessment in assessments:
            category.append(assessment.category)
        if assessments is not None:
            return render_template("adminAssessment.html",
                                   page='admin',
                                   assessmentLen=len(assessments),
                                   assessment=category)
        else:
            return render_template("adminAssessment.html",
                                   page='admin',
                                   assessmentLen=0)
def create_assessment():
    updater_json = validate_and_return_updater_request()
    json_payload = get_json_from_request()
    json_has_required_keys(json_payload, ['assessment'])
    data = json_payload['assessment']
    json_has_required_keys(data, ['supplier_code'])
    json_has_required_keys(data, ['domain_name'])
    supplier_code = data['supplier_code']
    updated_by = updater_json['updated_by']

    existing_assessment = db.session.query(
        Assessment
    ).join(
        SupplierDomain, Supplier, Domain
    ).filter(
        Supplier.code == supplier_code,
        Domain.name == data['domain_name'],
        Assessment.active
    ).first()

    if existing_assessment:
        send_assessment_requested_notification(existing_assessment, updated_by)
        publish_tasks.assessment.delay(
            publish_tasks.compress_assessment(existing_assessment),
            'existing',
            updated_by=updated_by
        )

        return jsonify(assessment=existing_assessment.serializable), 201

    assessment = Assessment()
    assessment.update_from_json(json_payload['assessment'])
    db.session.add(assessment)

    try:
        db.session.commit()
    except IntegrityError:
        abort(400)

    db.session.add(AuditEvent(
        audit_type=AuditTypes.create_assessment,
        user=updated_by,
        data={},
        db_object=assessment
    ))

    if current_app.config['JIRA_FEATURES']:
        application = db.session.query(Application).filter(
            Application.supplier_code == supplier_code,
            Application.type == 'edit',
            Application.status == 'submitted'
        ).one_or_none()

        mj = get_marketplace_jira()
        mj.create_domain_approval_task(assessment, application)

    send_assessment_requested_notification(assessment, updater_json['updated_by'])

    publish_tasks.assessment.delay(
        publish_tasks.compress_assessment(assessment),
        'created',
        updated_by=updated_by
    )

    return jsonify(assessment=assessment.serializable), 201
def test_new_assessment():
    new_assessment = Assessment('question', '56')
    assert new_assessment.question == 'question'
    assert new_assessment.answer == '56'