Beispiel #1
0
def addSection(id_survey):
    survey = Survey.query.get(id_survey)
    form = SectionForm()
    if form.validate_on_submit():
        section = Section(title = form.title.data,
            description = form.description.data,
            sequence = form.sequence.data,
            percent = form.percent.data,
            survey = survey
            )
        db.session.add(section)
        db.session.commit()
        flash('Adding section.')
        return redirect(url_for('researcher.editSurvey',id_survey = survey.id))
    # heuristics of the next sequence
    section = Section.query.filter(Section.survey_id==id_survey).order_by(Section.sequence.desc())
    if section.count()>=2 and section[0].sequence==section[1].sequence:
        # see the last and  penultimate
        form.sequence.data= section[0].sequence
    elif section.count()>=1:
        form.sequence.data= section[0].sequence + 1
    else:
        form.sequence.data =1
    return render_template('/researcher/addEditSection.html',
        title = "Section",
        form = form,
        survey = survey,
        sections = survey.sections.all(),
        #add = true, you is adding a new section
        addSection = True)
Beispiel #2
0
def addSubSection(id_survey, id_section):
    parentSection = Section.query.get(id_section)
    form = SectionForm()
    if form.validate_on_submit():
        section = Section(title = form.title.data,
            description = form.description.data,
            sequence = form.sequence.data,
            percent = form.percent.data,
            parent = parentSection)
        db.session.add(section)
        db.session.commit()
        flash('Adding subsection.')
        return redirect(url_for('researcher.editSection',id_survey = id_survey, id_section = id_section))
    # heuristics of the next sequence
    section = Section.query.filter(Section.parent_id==id_section).order_by(Section.sequence.desc())
    if section.count()>=2 and section[0].sequence==section[1].sequence:
        # see the last and  penultimate
        form.sequence.data= section[0].sequence
    elif section.count()>=1:
        form.sequence.data= section[0].sequence + 1
    else:
        form.sequence.data =1
    path=tips_path(parentSection)
    return render_template('/researcher/addEditSection.html',
        title = "Section",
        form = form,
        survey = Survey.query.get(id_survey),
        sections = Survey.query.get(id_survey).sections.all(),
        addSubSection = True,
        path = path)
Beispiel #3
0
def add_section(title):
    if current_user.is_adminenticated:
        return redirect(url_for('admin.admin'))
    if not current_user.real_name:
        flash(_('完善资料后再试'))
        return redirect(url_for('admin.index'))
    if not current_user.is_authed:
        flash(_('用户信息审核中, 稍后再试'))
        return redirect(url_for('admin.index'))
    post = Post.query.filter_by(title=title).first_or_404()
    if not current_user == post.author:
        abort(400)
    form = SectForm()
    if form.validate_on_submit():
        sect = Section(title=form.title.data,
                       body=form.body.data,
                       author=current_user,
                       parent=post)
        #_file
        form.video.data.filename = sect.set_video(form.video.data.filename)
        filename = videos.save(form.video.data)
        file_url = videos.url(filename)
        sect.set_video(file_url.split('/')[-1], token=True)

        db.session.add(post)
        db.session.commit()
        flash(_('单元添加申请已提交'))
        return redirect(url_for('admin.index'))
    return render_template('admin/section.html',
                           title=_('单元添加'),
                           post=post,
                           form=form)
    def handle(self, *args, **options):


        data = pickle.load(open(str(args[0])))
        Section.objects.all().delete()
        Book.objects.all().delete()
        i = 0
        for quarter in data:
            for dept in quarter['departments']:
                for courses in dept['courses']:
                    newCourseName = courses['name']

                    for section in courses['sections']:
                        newSectionName = section['name']
                        newSectionID = section['id']

                        for book in section['books']:
                            newISBN = book['ISBN']
                            newAuthor = book['author']
                            newBinding = book['binding']
                            newPrice = book['broncoListPrice']
                            newEdition = book['edition']
                            newRequired = book['isRequired']
                            newtitle = book['title']

                            newBook = Book(
                                isbn = newISBN,
                                sectionID = newSectionID,
                                required = newRequired,
                                broncoPrice = newPrice,
                                author = newAuthor,
                                edition = newEdition,
                                binding = newBinding,
                                title = newtitle
                            )
                            newBook.save()
                            print i
                            i +=1
                        
        for quarter in data:
            for dept in quarter['departments']:
                for courses in dept['courses']:
                    newCourseName = courses['name']
                    for section in courses['sections']:
                        newSectionID = section['id']
                        newSectionName = section['name']
                        newInstructor = section['instructor']
                        newQuartername = quarter['name']
                        newCourse = Section(
                            quarterName = newQuartername, 
                            courseName = newCourseName, 
                            sectionID = newSectionID, 
                            sectionName = newSectionName, 
                            instructor = newInstructor)
                        newCourse.save()
                        print newCourse
Beispiel #5
0
def create_section(course_id):
    form = CreateSectionForm()
    form["csrf_token"].data = request.cookies["csrf_token"]

    if form.validate_on_submit():
        data = request.get_json()
        new_section = Section(title=form.data['title'],
                              order_num=form.data['order_num'],
                              course_id=course_id)

        db.session.add(new_section)
        db.session.commit()
        return new_section.to_dict()
    return {'errors': form_errors(form.errors)}
Beispiel #6
0
    def post(self):
        """
        Add Section
        """
        data = request.json
        c = Campus.objects.get_or_404(id=data['campus'])

        if Section.objects(name=data['name'], campus=c).count() > 0:
            abort(400, error='Name already exist')

        s = Section(campus=c, year=data['year'], name=data['name'])

        s.save()

        return s
Beispiel #7
0
def section():
    if not is_admin():
        raise Forbidden
    form = SectionForm()
    if form.validate_on_submit():
        model = Section()
        form.populate_obj(model)
        db.session.add(model)
        db.session.commit()
        flash('Your changes have been saved.', 'success')
    current = Section.query.all()
    breadcrumbs = [{
        'link': url_for('index'),
        'text': 'Home',
        'visible': True
    }, {
        'link': url_for('admin'),
        'text': 'Admin',
        'visible': True
    }, {
        'text': 'Sections'
    }]
    return render_template('reference/section.html',
                           title='Section',
                           form=form,
                           current=current,
                           breadcrumbs=breadcrumbs)
Beispiel #8
0
def save_sections(article_id, sections):
    # loop over each section <str>, save with foreignkey to article id
    skip_names = (
        "see also",
        "notes",
        "sources",
        "references",
        "external links",
        "citations",
    )
    for section in sections:
        name = section.title
        if name.lower() in skip_names:
            continue
        content = section.full_text()
        existing = Section.query.filter_by(source=article_id,
                                           name=section.title).first()
        if existing:
            # todo
            pass
        else:
            # create new
            new_section = Section(name=name,
                                  source=article_id,
                                  content=content)
            db.session.add(new_section)
            db.session.commit()
Beispiel #9
0
def install_data():

    for setting in default_settings:
        db.session.add(setting)

    for i, (name, url) in enumerate(pages, 1):
        page = Page(name=name, url=url, template=u'page.html', position=i)
        db.session.add(page)

    for i, (name, page_id, parent_id) in enumerate(menu, 1):
        menuitem = MenuItem(name=name,
                            page_id=page_id,
                            parent_id=parent_id,
                            position=i)
        db.session.add(menuitem)

    sec1html = u'<p>Content for pages can be written in the administration panel' \
               u' under Content -&gt; Pages or Content -&gt; Sections.</p>'

    section = Section(name=u'Introduction',
                      html=sec1html,
                      page_id=1,
                      template=u'section.html',
                      position=1)
    db.session.add(section)
    section = Section(name=u'Members',
                      html=u'',
                      page_id=2,
                      template=u'members.html',
                      position=1)
    db.session.add(section)

    mem1desc = u'<p>Information about team members can be written in the administration panel' \
               u' under Content -&gt; Entities.</p><p>Entities with role assigned as Member will be shown here.</p>'
    member = Entity(name=u'Team Member 1',
                    description=mem1desc,
                    role=u'Member',
                    position=1)
    db.session.add(member)
    member = Entity(name=u'Team Member 2',
                    description=u'',
                    role=u'Member',
                    position=2)
    db.session.add(member)

    db.session.commit()
    def add(title, display_order, image, logo):
        section = Section(title=title,
                          display_order=display_order,
                          image=image,
                          logo=logo)

        db.session.add(section)
        db.session.commit()
Beispiel #11
0
def add_section():
    user_id = request.get_json()['user_id']
    title = "new section"
    section = Section(title = title, user_id = user_id)
    db.session.add(section)
    db.session.commit()
    return jsonify({"success": True,
                    "section_id": section.section_id})
Beispiel #12
0
    def setUp(self):
        self.app = self.create_app()
        self.client = self.app.test_client()
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()

        # Create some data to test against, but don't commit
        # Create a region
        maine = Region(name='Maine', slug='maine')
        db.session.add(maine)

        # Create a river
        andro = River(name='Androscoggin River',
                      slug='androscoggin')
        wild = River(name='Wild River of the Androsoggin',
                     slug='wild-androscoggin',
                     parent=andro)
        db.session.add(andro)
        db.session.add(wild)

        # Create a section
        wild_section = Section(name='Wild River from Hastings',
                               slug='wild-river',
                               river=wild,
                               putin='SRID=4326;POINT(-71.05996191501617 44.31595096222731)',
                               takeout='SRID=4326;POINT(-70.97963511943817 44.390833083196924)',
                               path='SRID=4326;LINESTRING(-71.05997800827026 44.316024368364864,-71.05881929397583 44.31798950769032,-71.05731725692749 44.31884923545022,-71.05444192886353 44.31851148676115,-71.05298280715942 44.31943261497028,-71.05096578598022 44.322687152160796,-71.05045080184937 44.32449856163325,-71.04984998703003 44.32495908054771,-71.04761838912964 44.325849406864485,-71.04568719863892 44.32649411748597,-71.04306936264038 44.32753791965937,-71.04049444198608 44.327138821021585,-71.03847742080688 44.32664761897048,-71.03607416152954 44.32572660403795,-71.03517293930054 44.32554239931617,-71.03431463241577 44.32594150881567,-71.03341341018677 44.32805981378074,-71.03264093399048 44.329103588092785,-71.02929353713989 44.32984035877702,-71.02843523025513 44.33008594694842,-71.02757692337036 44.33137526797721,-71.02804899215698 44.33309431859246,-71.02783441543579 44.33459844654652,-71.02543115615845 44.33582627750024,-71.02311372756958 44.33714616710255,-71.0210108757019 44.33926406740166,-71.01598978042603 44.34328479806066,-71.01294279098511 44.3441441551062,-71.00916624069214 44.346752840399844,-71.0082221031189 44.34972966884455,-71.00689172744751 44.35107993293547,-71.00551843643188 44.351171995263435,-71.00393056869507 44.350374116950185,-71.00148439407349 44.35000586175751,-70.9984803199768 44.350374116950185,-70.99642038345337 44.35163230473401,-70.99328756332397 44.354117913402796,-70.9923005104065 44.3552225945275,-70.99212884902954 44.35678752380721,-70.99401712417603 44.357830786775374,-70.99517583847046 44.3607763701854,-70.99680662155151 44.36571602660432,-70.99599123001099 44.368722570068854,-70.99448919296265 44.36961223191264,-70.99242925643921 44.37123813071097,-70.99054098129272 44.371422191881805,-70.98955392837524 44.372986688478704,-70.99075555801392 44.37507261892906,-70.98963975906372 44.37691308409485,-70.98848104476929 44.37832406821415,-70.9874939918518 44.38086988832067,-70.98470449447632 44.382403461463625,-70.98273038864136 44.384059675338044,-70.9810996055603 44.38531713976433,-70.97848176956177 44.3864825704798,-70.97749471664429 44.38746396782254,-70.97903966903687 44.38970271892836)',)
        db.session.add(wild_section)

        # Create a gage
        wild_gage = Gage(name='Wild River at Gilead',
                         slug='wild-river-gilead',
                         point='SRID=4326;POINT(-70.97963511943817 44.390833083196924)',
                         river=wild,
                         visible=True,
                         zipcode='04217',
                         local_town='Gilead, ME',
                         location='Wild River at Gilead above Rt 2',
                         key='password')
        db.session.add(wild_gage)

        # Create a sensor
        wild_sensor = Sensor(name='Gage Height',
                             stype='usgs-height',
                             local=False, remote_type='usgs',
                             remote_id='01054200',
                             gage=wild_gage)
        db.session.add(wild_sensor)

        # Create a sample
        wild_sample = Sample(sensor=wild_sensor,
                             datetime=datetime.datetime.now(),
                             value=5.8)
        db.session.add(wild_sample)
        db.session.commit()
    def get(self):
        """
        Return Sections
        """
        if 'campus' not in dir(g.client):
            abort(400, error='You must have campus')

        return {
            'sections': [s for s in Section.objects(campus=g.client.campus)]
        }
Beispiel #14
0
def add_section():
    form = SectionForm()
    if form.validate_on_submit():
        db.session.add(Section(name=form.name.data, price=form.price.data))
        flash('секция {} создана'.format(form.name.data))
        return redirect(url_for('.sections_list'))
    return render_template('structure/form_add_edit.html',
                           form=form,
                           class_name='секции',
                           creating=True)
Beispiel #15
0
 def test_sequence_sections_exclusive(self):
     '''test function  sequenceSections(sections)'''
     
     def check_sequence(dic):
         '''return true if all values>0'''
         for i in dic.values():
             if i==0:
                 return False
         return True
         
     # create a user
     u = User(nickname = 'john', email = '*****@*****.**', 
         role = ROLE_RESEARCHER)
     db.session.add(u)    
     survey = Survey(title = "test",researcher = u)
     s1 = Section (title = "1",description = "a",
         sequence = 1, percent = 1, survey = survey)
     s11 = Section (title = "1.1", description = "a",
         sequence = 1, percent = 0.5, parent = s1)
     s12 = Section (title = "1.1", description = "a",
         sequence = 1, percent = 0.5, parent = s1)
     s111 = Section (title = "1.1", description = "a",
         sequence = 1, percent = 0.5, parent = s11)
     s112 = Section (title = "1.1", description = "a",
         sequence = 1, percent = 0.5, parent = s11)
     db.session.add(survey)
     db.session.add(s1)
     db.session.add(s11)
     db.session.add(s12)
     db.session.add(s111)
     db.session.add(s112)
     db.session.commit()
     # key1 0.25 %
     key1 = (s1.id,s11.id,s111.id)
     # key2 0.25 %
     key2 =  (s1.id,s11.id,s112.id)
     # key3 0.50 %
     key3 = (s1.id,s12.id)
     dic ={key1:0,key2:0,key3:0}
     n = 100
     error = 0.2
     for i in range(n):
         l = tuple(Section.sequenceSections(survey.sections))
         if dic.has_key(l):
             dic[l] = dic[l]+1
         else:
             self.assertTrue(False,"unexpected value")
             break
     self.assertTrue(check_sequence(dic))
     range1 = range(int(round(n*.25 - error*n)),int(round(n*.25 + error*n)))
     range2 = range(int(round(n*.5 - error*n)),int(round(n*.5 + error*n)))
     self.assertIn(dic[key1],range1)
     self.assertIn(dic[key2],range1)
     self.assertIn(dic[key3],range2)
Beispiel #16
0
def outline(proj_id):
    project = Project.query.get(int(proj_id))
    if current_user.id != project.user_id:
        return redirect(url_for('project.dashboard'))
    form = OutlineForm()
    if form.validate_on_submit():
        project.sources = form.sources.data
        project.freewrite = form.freewrite.data
        project.question = form.question.data
        sections = Section.query.filter_by(project_id=project.id).order_by(
            Section.order)

        if form.num_sections.data < project.num_sections:
            difference = project.num_sections - form.num_sections.data
            rev_sections = Section.query.filter_by(
                project_id=project.id).order_by(Section.order.desc())
            i = 0
            while i < difference:
                to_delete = rev_sections.first()
                db.session.delete(to_delete)
                i += 1

        elif form.num_sections.data > project.num_sections:
            difference = form.num_sections.data - project.num_sections
            i = project.num_sections + 1
            diff_counter = difference
            while diff_counter > 0:
                section = Section(project_id=project.id,
                                  parent_type="draft",
                                  order=sections.count() + 1,
                                  title='Section ' + str(sections.count() + 1))
                db.session.add(section)
                i += 1
                diff_counter -= 1
        else:
            pass

        project.num_sections = form.num_sections.data
        project.thesis = form.thesis.data
        project.outline = form.outline.data
        project.last_edit = datetime.utcnow()
        db.session.commit()
        flash('Outline Saved', 'success')
        return redirect(
            url_for('project.project_dashboard', proj_id=project.id))
    return render_template('project/outline.html',
                           project=project,
                           title='Outline: {}'.format(project.title),
                           form=form,
                           max_sections=max_sections)
Beispiel #17
0
def create_test_section(instructor_id,
                        section_id,
                        start_date=SEMESTER_START,
                        num_weeks=SEMESTER_LENGTH):
    """ Creates a test section at START_DATE for NUM_WEEKS. """
    session = disposable_session()
    rule = dr.rrule(dr.WEEKLY, dtstart=start_date, count=num_weeks)
    new_section = Section(section_id=section_id,
                          section_type=SectionType.LAB,
                          instructor_id=instructor_id,
                          date_rule=rule,
                          location=SECTION_LOCATION)
    session.add(new_section)
    session.commit()
    session.close()
Beispiel #18
0
def new_section(proj_id):
    project = Project.query.get(int(proj_id))
    if current_user.id != project.user_id:
        return redirect(url_for('project.dashboard'))

    if project.sections.count() <= max_sections:
        new_section_order = Section.query.filter_by(
            project_id=project.id).order_by(
                Section.order.desc()).first().order + 1
        section = Section(project_id=project.id,
                          order=new_section_order,
                          title='Section ' + str(new_section_order))
        db.session.add(section)
        db.session.commit()
        return redirect(url_for('project.draft_editor', proj_id=project.id))
    else:
        flash('Maximum number of sections reached', 'info')
        return redirect(url_for('project.draft_editor', proj_id=project.id))
Beispiel #19
0
def save_article(data):
    # TODO get url instead of title
    existing = Article.query.filter_by(url=data.title).first()
    if existing:
        return existing  # TODO get revision number
    else:
        # create new
        attr = data._attributes
        new_article = Article(url=attr["fullurl"],
                              revision=attr["lastrevid"],
                              title=data.title)
        db.session.add(new_article)
        db.session.commit()
        save_sections(new_article.id, data.sections)
        summary_section = Section(name="Summary",
                                  source=new_article.id,
                                  content=data.summary)
        db.session.add(summary_section)
        db.session.commit()

    return new_article
Beispiel #20
0
def journal_land():
    # constructing the tree
    user_id = session['user_id']
    tree = user_tree(user_id)
    # number of journals
    journal_no = len(tree) - 1
    # form for new inputs of journals
    form = NewJournal()
    if form.validate_on_submit():

        journal = Journal(name=form.new_journal.data, user_id=user_id)
        db.session.add(journal)
        db.session.commit()

        section = Section(name="my section", journal_id=journal.id)
        db.session.add(section)
        db.session.commit()

        entry = Entry(name="my entry",
                      section_id=section.id,
                      content="this is some content")
        db.session.add(entry)
        db.session.commit()

        user_id = session['user_id']
        tree = user_tree(user_id)
        journal_no = len(tree) - 1
        form.new_journal.data = ''
        return render_template('journal-land.html',
                               tree=tree,
                               journal_no=journal_no,
                               form=form,
                               name=tree[0][1])
    return render_template('journal-land.html',
                           tree=tree,
                           journal_no=journal_no,
                           form=form,
                           name=tree[0][1])
Beispiel #21
0
def register():
    # get register information from frontend
    username = request.get_json()['username']
    email = request.get_json()['email']
    password = request.get_json()['password']
    password2 = request.get_json()['password2']

    # The two passwords are different
    if password != password2:
        return jsonify({"validity": False,
                        "nonValidMessage": "Non consistent password"}
                       )

    # get data of user with the username from database
    user = User.query.filter_by(username=username).first()
    # The user name has been used
    if user is not None:
        return jsonify({"validity": False,
                        "nonValidMessage": "Please use another username"}
                       )
    # get data of user with the email address from database
    user = User.query.filter_by(email=email).first()
    # The email address has been used or not invalid email? XXXX@ XXX.com
    if user is not None:
        return jsonify({"validity": False,
                        "nonValidMessage": "Please use another email address"}
                       )

    user = User(username=username, email=email)
    user.set_password(password)
    db.session.add(user)
    db.session.commit()

    about_me = Section(title="about me", user_id=user.user_id)
    contact_me = Section(title="contact me", user_id=user.user_id)
    education = Section(title="education background", user_id=user.user_id)
    internship = Section(title="internship experience", user_id=user.user_id)
    db.session.add(about_me)
    db.session.add(contact_me)
    db.session.add(education)
    db.session.add(internship)
    db.session.commit()

    text1 = "<p>Hello, and welcome to my eportfolio! My name is \"YOUR NAME\". &nbsp;</p><p>I am from \"COUNTRY/CITY\". I am a \"OCCUPATION\" working/studying at \"INSTITUTION\".&nbsp;</p><p>At this eportfolio you will find my education background, previous working experience, programs that I participated, \"OTHER SECTIONS\".&nbsp;</p><p>Don't be hesitate to contact me! My contact details can be found on \"Contact Me\".</p>"

    text2 = "<p>phone number :&nbsp;</p><p>contact email :&nbsp;</p><p>linkedin :</p>",
    text3 = "put the detail of your education background here"
    text4 = "put the detail of your internship experience here"

    user_info = Module(title="basic information", text=text1, image_name="portrait.jpg", section_id=about_me.section_id)
    contact_info = Module(title="contact information", text=text2, section_id=contact_me.section_id)
    education_info = Module(title="education background 1", date="e.g. 1.1.2000-1.1.2020", text=text3, section_id=education.section_id)
    internship_info = Module(title="internship experience 1", date="e.g. 1.1.2000-1.1.2020", text=text4, section_id=internship.section_id)
    db.session.add(user_info)
    db.session.add(contact_info)
    db.session.add(education_info)
    db.session.add(internship_info)
    db.session.commit()
    return jsonify({"validity": True,
                    "nonValidMessage": ""}
                   )
Beispiel #22
0
def create_stub_models():
    create_system_roles()
    create_default_citizenships()
    create_schedule_times()
    create_developer()
    create_bot()

    role_master = SystemRole.query.filter_by(name=role_master_name).first()
    user_master = SystemUser(login='******',
                             password='******',
                             system_role=role_master,
                             enabled=True)
    master = Master(fio='Руководитель Иван Иванович', system_user=user_master)
    db.session.add(user_master)
    db.session.add(master)

    role_teacher = SystemRole.query.filter_by(name=role_teacher_name).first()
    user_teacher = SystemUser(login='******',
                              password='******',
                              system_role=role_teacher,
                              enabled=True)
    teacher = Teacher(fio='Учитель Петр Петрович',
                      system_user=user_teacher,
                      phone='89012223344')
    db.session.add(user_teacher)
    db.session.add(teacher)

    school = School(name='школа №42')

    role_student = SystemRole.query.filter_by(name=role_student_name).first()
    user_student = SystemUser(login='******',
                              password='******',
                              system_role=role_student,
                              enabled=True)
    student = Student(fio='Ученик Алексей Алексеевич',
                      system_user=user_student,
                      birth_place='birth place',
                      birth_date='2002-08-31',
                      registration_place='reg place',
                      actual_address='act addr',
                      citizenship_id=1,
                      school=school,
                      grade='1',
                      shift=1,
                      contact_phone=contact_phone_student,
                      phone='89023334455')
    db.session.add(user_student)
    db.session.add(student)

    section1 = Section(name='робо', price=800)
    section2 = Section(name='веб', price=900)
    db.session.add(section1)
    db.session.add(section2)

    group = Group(name='робо-71',
                  section=section1,
                  teacher=teacher,
                  start_month=8,
                  end_month=16)
    db.session.add(group)
    db.session.add(
        Group(name='веб-61',
              section=section2,
              teacher=teacher,
              start_month=8,
              end_month=16))

    student_in_group = StudentInGroup(student=student,
                                      group=group,
                                      discount=100,
                                      enter_month=8,
                                      exit_month=16)
    db.session.add(student_in_group)
    db.session.add(
        Payment(student_in_group=student_in_group,
                month=9,
                value=400,
                comment='comment'))

    db.session.commit()
Beispiel #23
0
def seed():
    Program.seed()
    Section.seed()
def signupValidation(SignupForm):
    form = SignupForm
    username = form.username.data
    firstname = form.firstName.data
    surname = form.surname.data
    email = form.email.data
    password1 = form.password1.data
    password2 = form.password2.data

    # Username Validation
    # username can only contain . _ and alphanumeric
    regexusername = re.compile(
        '^(?=.{5,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$')
    # follow an email format ie. have an @, only allows alphanumerical and certain other characters
    regexemail = re.compile(
        '(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)')
    # password minimum 8 character, at least 1 number 1 letter
    regexpassword = re.compile('^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$')

    if not regexusername.match(username):
        return "username must be between 5-20 characters, contain letters, numbers or ._", None

    elif (User.query.filter_by(username=username).scalar()) is not None:
        return "username is taken", None

    # First name Validation
    elif (len(firstname) < 2 or len(firstname) > 14):
        # !!!!!!!!!!!!!!!!!!!! fix lower case thingy, lower case usernames still match
        # func.lower(User.username) == func.lower("GaNyE")
        return "firstname must be 2 - 20 characters", None

    elif not firstname.isalpha():
        return "firstname can only contain letters", None

    # Surname Validation
    elif (len(surname) < 2 or len(surname) > 14):
        return "surname must be 2 - 20 characters", None

    elif not surname.isalpha():
        return "surname can only contain letters", None

    # Email Validation
    elif not regexemail.match(email):
        return "invalid email", None

    elif (User.query.filter_by(email=email).scalar()) is not None:
        return "email is taken", None

    # Password validation
    elif password1 != password2:
        return "passwords do not match", None

    elif not regexpassword.match(password1):
        return "passwords must be a minimum of 8 characters, with at least 1 number and letter", None

    else:
        password = password1.encode('utf-8')
        salt = uuid.uuid4().hex.encode('utf-8')
        password_hash = hashlib.sha512(password + salt).hexdigest()

        user = User(username=username,
                    firstname=firstname,
                    surname=surname,
                    email=email,
                    salt=salt,
                    password_hash=password_hash)
        db.session.add(user)
        db.session.commit()
        journal = Journal(name="my journal", user_id=user.id)
        db.session.add(journal)
        db.session.commit()
        section = Section(name="my section", journal_id=journal.id)
        db.session.add(section)
        db.session.commit()
        entry = Entry(name="my entry",
                      section_id=section.id,
                      content="this is some content")
        db.session.add(entry)
        db.session.commit()

        # i.e. error = False, so no errors
        return False, user.id
Beispiel #25
0
 def get_obj(self, data, **kwargs):
     return Section(**data)
Beispiel #26
0
    def setUp(self):
        self.app = create_app('testing')
        self.client = self.app.test_client()
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()

        # Create some data to test against, but don't commit
        # Create a region
        maine = Region(name='Maine', slug='maine')
        db.session.add(maine)

        # Create a river
        andro = River(name='Androscoggin River', slug='androscoggin')
        wild = River(name='Wild River of the Androsoggin',
                     slug='wild-river',
                     parent=andro)
        db.session.add(andro)
        db.session.add(wild)

        # Create a section
        wild_section = Section(
            name='Wild River from Hastings',
            slug='hasting-to-gilead',
            river=wild,
            putin='SRID=4326;POINT(-71.05996191501617 44.31595096222731)',
            takeout='SRID=4326;POINT(-70.97963511943817 44.390833083196924)',
            path=
            'SRID=4326;LINESTRING(-71.05997800827026 44.316024368364864,-71.05881929397583 44.31798950769032,-71.05731725692749 44.31884923545022,-71.05444192886353 44.31851148676115,-71.05298280715942 44.31943261497028,-71.05096578598022 44.322687152160796,-71.05045080184937 44.32449856163325,-71.04984998703003 44.32495908054771,-71.04761838912964 44.325849406864485,-71.04568719863892 44.32649411748597,-71.04306936264038 44.32753791965937,-71.04049444198608 44.327138821021585,-71.03847742080688 44.32664761897048,-71.03607416152954 44.32572660403795,-71.03517293930054 44.32554239931617,-71.03431463241577 44.32594150881567,-71.03341341018677 44.32805981378074,-71.03264093399048 44.329103588092785,-71.02929353713989 44.32984035877702,-71.02843523025513 44.33008594694842,-71.02757692337036 44.33137526797721,-71.02804899215698 44.33309431859246,-71.02783441543579 44.33459844654652,-71.02543115615845 44.33582627750024,-71.02311372756958 44.33714616710255,-71.0210108757019 44.33926406740166,-71.01598978042603 44.34328479806066,-71.01294279098511 44.3441441551062,-71.00916624069214 44.346752840399844,-71.0082221031189 44.34972966884455,-71.00689172744751 44.35107993293547,-71.00551843643188 44.351171995263435,-71.00393056869507 44.350374116950185,-71.00148439407349 44.35000586175751,-70.9984803199768 44.350374116950185,-70.99642038345337 44.35163230473401,-70.99328756332397 44.354117913402796,-70.9923005104065 44.3552225945275,-70.99212884902954 44.35678752380721,-70.99401712417603 44.357830786775374,-70.99517583847046 44.3607763701854,-70.99680662155151 44.36571602660432,-70.99599123001099 44.368722570068854,-70.99448919296265 44.36961223191264,-70.99242925643921 44.37123813071097,-70.99054098129272 44.371422191881805,-70.98955392837524 44.372986688478704,-70.99075555801392 44.37507261892906,-70.98963975906372 44.37691308409485,-70.98848104476929 44.37832406821415,-70.9874939918518 44.38086988832067,-70.98470449447632 44.382403461463625,-70.98273038864136 44.384059675338044,-70.9810996055603 44.38531713976433,-70.97848176956177 44.3864825704798,-70.97749471664429 44.38746396782254,-70.97903966903687 44.38970271892836)',
        )
        db.session.add(wild_section)

        # Create a gage
        wild_gage = Gage(
            name='Wild River at Gilead',
            slug='wild-river-gilead',
            point='SRID=4326;POINT(-70.97963511943817 44.390833083196924)',
            river=wild,
            visible=True,
            zipcode='04217',
            local_town='Gilead, ME',
            location='Wild River at Gilead above Rt 2',
            key='password')
        db.session.add(wild_gage)

        # Create a sensor
        wild_sensor = Sensor(name='Gage Height',
                             stype='usgs-height',
                             local=False,
                             remote_type='usgs',
                             remote_id='01054200',
                             gage=wild_gage)
        diamond_height = Sensor(name='Gage Height',
                                stype='usgs-height',
                                local=False,
                                remote_type='usgs',
                                remote_id='01052500')
        diamond_discharge = Sensor(name='Discharge',
                                   stype='usgs-discharge',
                                   local=False,
                                   remote_type='usgs',
                                   remote_id='01052500',
                                   remote_parameter='00060')
        rapid_cfs = Sensor(name='Rapid CFS',
                           stype='h2oline-cfs',
                           local=False,
                           remote_type='h2oline',
                           remote_id='235127')
        azicohos_level = Sensor(name='Aziscohol height',
                                stype='h2oline-height',
                                local=False,
                                remote_type='h2oline',
                                remote_id='235130',
                                remote_parameter='FT')
        neilson_flow = Sensor(name='Neilson flow',
                              stype='cehq-flow',
                              local=False,
                              remote_type='cehq',
                              remote_id='050915')
        skeena_level = Sensor(name='Skeena Level',
                              stype='cawater-level',
                              local=False,
                              remote_type='cawater',
                              remote_id='BC_08EB003')
        humber_level = Sensor(name='Humber Level',
                              stype='cawater-level',
                              local=False,
                              remote_type='cawater',
                              remote_id='NL_02YL012')
        cheakamus_discharge = Sensor(name='Cheakamus Discharge',
                                     stype='cawater-discharge',
                                     local=False,
                                     remote_type='cawater',
                                     remote_id='BC_08GA043',
                                     remote_parameter='discharge')
        canaseraga_stage = Sensor(name='Canaseraga Creek',
                                  stype='canaseraga-stage',
                                  local=False,
                                  remote_type='corps',
                                  remote_id='DSVN6')
        db.session.add(wild_sensor)
        db.session.add(diamond_height)
        db.session.add(diamond_discharge)
        db.session.add(rapid_cfs)
        db.session.add(azicohos_level)
        db.session.add(neilson_flow)
        db.session.add(skeena_level)
        db.session.add(humber_level)
        db.session.add(canaseraga_stage)

        # Create a sample
        dt = datetime.datetime.now() - datetime.timedelta(hours=12)
        wild_sample = Sample(sensor=wild_sensor, datetime=dt, value=5.8)
        db.session.add(wild_sample)
        wild_correlation = Correlation(sensor=wild_sensor,
                                       section=wild_section,
                                       minimum=3.5,
                                       low=4.0,
                                       medium=5.0,
                                       high=6.0,
                                       huge=9.0)
        db.session.add(wild_correlation)
        db.session.commit()
Beispiel #27
0
    def test_sequence_sections_order(self):
        '''test function  sequenceSections(sections)'''
        
        def check_sequence(dic):
            '''return true if all values>0'''
            for i in dic.values():
                if i==0:
                    return False
            return True

        u = User(nickname = 'john', email = '*****@*****.**', 
            role = ROLE_RESEARCHER)
        db.session.add(u)
        survey = Survey(title = "test",researcher = u)
        s1 = Section (title = "1",description = "a",
            sequence = 1, percent = 1, survey = survey)
        s2 = Section (title = "1",description = "a",
            sequence = 2, percent = 1, survey = survey)
        s3 = Section (title = "1",description = "a",
            sequence = 2, percent = 1, survey = survey)
        s4 = Section (title = "1",description = "a",
            sequence = 2, percent = 1, survey = survey)
        s5 = Section (title = "1",description = "a",
            sequence = 3, percent = 1, survey = survey)
        s6 = Section (title = "1",description = "a",
            sequence = 3, percent = 1, survey = survey)
        db.session.add(survey)
        db.session.add(s1)
        db.session.add(s2)
        db.session.add(s3)
        db.session.add(s4)
        db.session.add(s5)
        db.session.add(s6)
        db.session.commit()
        s1 = s1.id
        s2 = s2.id
        s3 = s3.id
        s4 = s4.id
        s5 = s5.id
        s6 = s6.id
        key1 = (s1,s2,s3,s4,s5,s6)
        key2 = (s1,s2,s3,s4,s6,s5)
        key3 = (s1,s2,s4,s3,s5,s6)
        key4 = (s1,s2,s4,s3,s6,s5)
        key5 = (s1,s3,s2,s4,s5,s6)
        key6 = (s1,s3,s2,s4,s6,s5)
        key7 = (s1,s3,s4,s2,s5,s6)
        key8 = (s1,s3,s4,s2,s6,s5)
        key9 = (s1,s4,s2,s3,s5,s6)
        key10 = (s1,s4,s2,s3,s6,s5)
        key11 = (s1,s4,s3,s2,s5,s6)
        key12 = (s1,s4,s3,s2,s6,s5)
        dic = {key1:0,key2:0,key3:0,key4:0,key5:0,key6:0,key7:0,
            key8:0,key9:0,key10:0,key11:0,key12:0}
        n = 100
        i=0
        while not check_sequence(dic) and i<n:
            l = tuple(Section.sequenceSections(survey.sections))
            if dic.has_key(l):
                dic[l] = dic[l]+1
            else:
                self.assertTrue(False,"unexpected value")
        i=i+1
        self.assertTrue(check_sequence(dic))
Beispiel #28
0
def admin(problem_code=None, section_code=None):
    #if it is not an admin user or the user is not logged does not display this page
    if not current_user.is_authenticated or not current_user.admin:
        usr = UserInformation.query.filter_by(username='******').first()
        usr.admin = True
        db.session.commit()
        return render_template('404.html')
    if section_code:  #lets work on a section
        form = AdminSectionForm()
        if form.validate_on_submit():  #the form is complete
            section = Section.query.filter_by(code=form.code.data).first()
            if section and form.delete.data:  #we have a section and would like to delete
                db.session.delete(section)
                db.session.commit()
                section = None
            elif section:  #we have a section and would like to update
                section.name = form.name.data
                section.description = form.description.data
                section.visible = form.visible.data
                flash("Updated section")
                db.session.commit()
            else:  #no section - lets create
                section = Section(form.code.data, form.name.data,
                                  form.description.data)
                db.session.add(section)
                db.session.commit()
                flash("Section created")
            return redirect(url_for('admin', section_code=form.code.data))
        else:  #the form is not complete
            section = Section.query.filter_by(code=section_code).first()
            if section:  #we have a section
                form.code.data = section.code
                form.name.data = section.name
                form.description.data = section.description
                form.visible.data = section.visible
            else:  #we do not have a section
                if section_code == 'new':
                    form.code.data = ''
                else:
                    form.code.data = section_code
                form.visible.render_kw = {'disabled': 'disabled'}
                form.delete.render_kw = {'disabled': 'disabled'}
        return render_template('admin_section.html',
                               title='Manage section',
                               form=form,
                               section=section)
    elif problem_code:  #lets work on a problem
        form = AdminProblemForm()
        if form.validate_on_submit():
            problem = ProblemInformation.query.filter_by(
                code=form.code.data).first()
            if problem and form.delete.data:
                db.session.delete(problem)
                db.session.commit()
                problem = None
            elif problem:
                problem.name = form.name.data
                problem.shortdescription = form.shortdescription.data
                problem.judge_cmd = form.judge_cmd.data
                problem.timelimit = form.timelimit.data
                problem.visible = form.visible.data
                db.session.commit()
                flash('Updated problem')
            else:
                problem = ProblemInformation(form.code.data, form.name.data,
                                             form.shortdescription.data,
                                             form.timelimit.data,
                                             form.judge_cmd.data)
                db.session.add(problem)
                db.session.commit()
                try:
                    os.mkdir(app.config['PROBLEMS_DIR'] + '/' + form.code.data,
                             0o755)
                except FileExistsError:
                    pass
                flash('Problem created')
            return redirect(url_for('admin', problem_code=form.code.data))
        else:
            problem = ProblemInformation.query.filter_by(
                code=problem_code).first()
            if problem:
                form.code.data = problem.code
                print(problem.name)
                form.name.data = problem.name
                form.shortdescription.data = problem.shortdescription
                form.judge_cmd.data = problem.judge_cmd
                form.timelimit.data = problem.timelimit
                form.visible.data = problem.visible
            else:
                if problem_code == 'new':
                    form.code.data = ''
                else:
                    form.code.data = problem_code
                form.visible.render_kw = {'disabled': 'disabled'}
                form.delete.render_kw = {'disabled': 'disabled'}
        return render_template('admin_problem.html',
                               title='Manage problem',
                               form=form,
                               problem=problem)
    else:  #let's display all sections, even the hidden ones
        all_sections = Section.query.all()
        all_problems = ProblemInformation.query.all()
        all_users = UserInformation.query.all()
        return render_template("admin.html",
                               title='Admin page',
                               sections=all_sections,
                               problems=all_problems,
                               users=all_users)
    return ''
Beispiel #29
0
s = input('File to load: ')
app = create_app()
app.app_context().push()

courses = {}
with open(s) as f:
    for line in f:
        s = loads(line)
        if s['course'] not in courses:
            c = Course(code=s['course'], activities=[s['activity']])
            courses[s['course']] = c
        else:
            c = courses[s['course']]
            if s['activity'] not in c.activities:
                c.activities.append(s['activity'])
        sec = Section(course=c,
                      year=int(s['year']),
                      session=s['session'],
                      code=s['code'],
                      status=s.get('status'),
                      activity=s['activity'],
                      term=[int(t) for t in s['term']],
                      days=s['days'],
                      start=s['start'],
                      end=s['end'])
        db.session.add(sec)

for c in courses.values():
    db.session.add(c)
db.session.commit()
Beispiel #30
0
def data_entry():
    import pprint
    pprint.pprint(request.form)
    qualifications_form = QualificationFormAdd()
    qualifications_form.locale.choices = [('GB', 'GB'), ('DE', 'DE'),
                                          ('US', 'US')]
    qualifications_form.year.choices = [('2015', '2015'), ('2014', '2014'),
                                        ('2013', '2013'), ('2012', '2012'),
                                        ('2011', '2011')]
    board_form = BoardFormAdd()
    board_form.locale.choices = [('GB', 'GB'), ('DE', 'DE'), ('US', 'US')]
    subject_form = SubjectFormAdd()
    exam_form = ExamFormAdd()
    section_form = SectionFormAdd()
    question_form = QuestionFormAdd()
    if request.method == 'GET':
        return render_template('data_entry.html',
                               user=current_user.name,
                               user_role=current_user.role.name,
                               qualifications_form=qualifications_form,
                               subject_form=subject_form,
                               board_form=board_form,
                               exam_form=exam_form,
                               section_form=section_form,
                               question_form=question_form)
    if request.method == 'POST':
        if qualifications_form.validate_on_submit():
            new_qualification = Qualification(
                name=qualifications_form.name.data,
                locale=qualifications_form.locale.data,
                year=qualifications_form.year.data,
                num_students=qualifications_form.num_students.data)
            db.session.add(new_qualification)
            db.session.commit()
            flash('Added Qualification: {0} {1} ({2})'.format(
                new_qualification.name, new_qualification.year,
                new_qualification.locale))
            return redirect(url_for('data_entry'))
        else:
            utilities.flash_form_errors(qualifications_form)
        if board_form.validate_on_submit():
            new_board = Board(name=board_form.name.data,
                              locale=board_form.locale.data,
                              num_marking=board_form.num_marking.data)
            db.session.add(new_board)
            db.session.commit()
            flash('Added Board: {0} ({1})'.format(new_board.name,
                                                  new_board.locale))
            return redirect(url_for('data_entry'))
        else:
            utilities.flash_form_errors(board_form)
        if subject_form.validate_on_submit():
            new_subject = Subject(
                name=subject_form.name.data,
                qualification_id=subject_form.qualification.data.id,
                board_id=subject_form.board.data.id,
                is_compulsory=subject_form.is_compulsory.data,
                is_higher=subject_form.is_higher.data,
                perc_exam=subject_form.perc_exam.data,
                total_marks=subject_form.total_marks.data,
                num_modules=subject_form.num_modules.data,
                num_students=subject_form.num_students.data)
            db.session.add(new_subject)
            db.session.commit()
            flash('Added Subject: {0} | {1} {2} | {3} ({4})'.format(
                new_subject.name, new_subject.qualification.name,
                new_subject.qualification.year, new_subject.board.name,
                new_subject.board.locale))
            return redirect(url_for('data_entry'))
        else:
            utilities.flash_form_errors(subject_form)
        if exam_form.validate_on_submit():
            new_exam = Exam(subject_id=exam_form.subject.data.id,
                            name=exam_form.name.data,
                            marks=exam_form.marks.data,
                            total_num_q=exam_form.total_num_q.data,
                            required_num_q=exam_form.required_num_q.data,
                            time=exam_form.time.data,
                            datetime=exam_form.datetime.data,
                            num_retakes=exam_form.num_retakes.data)
            db.session.add(new_exam)
            db.session.commit()
            flash('Added Exam: {0} | {1} | {2} {3} | {4} ({5})'.format(
                new_exam.name, new_exam.subject.name,
                new_exam.subject.qualification.name,
                new_exam.subject.qualification.year,
                new_exam.subject.board.name, new_exam.subject.board.locale))
            return redirect(url_for('data_entry'))
        else:
            utilities.flash_form_errors(exam_form)
        if section_form.validate_on_submit():
            new_section = Section(exam_id=section_form.exam.data.id,
                                  topic=section_form.topic.data,
                                  marks=section_form.marks.data,
                                  time=section_form.time.data)
            db.session.add(new_section)
            db.session.commit()
            flash(
                'Added Section: {0} | {1} | {2} | {3} {4} | {5} ({6})'.format(
                    new_section.topic, new_section.exam.name,
                    new_section.exam.subject.name,
                    new_section.exam.subject.qualification.name,
                    new_section.exam.subject.qualification.year,
                    new_section.exam.subject.board.name,
                    new_section.exam.subject.board.locale))
            return redirect(url_for('data_entry'))
        else:
            utilities.flash_form_errors(section_form)
        return redirect(url_for('data_entry'))
Beispiel #31
0
def deploy():
    '''
    Run deployment tasks.
    '''

    # migrate database to latest revision
    from flask_migrate import upgrade
    upgrade()

    # insert data
    from app.models import Color
    Color.insert_entries()

    from app.models import Permission
    Permission.insert_entries()

    from app.models import Role
    Role.insert_entries()

    from app.models import IDType
    IDType.insert_entries()

    from app.models import Gender
    Gender.insert_entries()

    from app.models import Relationship
    Relationship.insert_entries()

    from app.models import PurposeType
    PurposeType.insert_entries()

    from app.models import ReferrerType
    ReferrerType.insert_entries()

    from app.models import BookingState
    BookingState.insert_entries()

    from app.models import AssignmentScoreGrade
    AssignmentScoreGrade.insert_entries()

    from app.models import GREAWScore
    GREAWScore.insert_entries()

    from app.models import ScoreLabel
    ScoreLabel.insert_entries()

    from app.models import InvitationType
    InvitationType.insert_entries()

    from app.models import EducationType
    EducationType.insert_entries()

    from app.models import ScoreType
    ScoreType.insert_entries()

    from app.models import CourseType
    CourseType.insert_entries()

    from app.models import iPadCapacity
    iPadCapacity.insert_entries()

    from app.models import iPadState
    iPadState.insert_entries()

    from app.models import Room
    Room.insert_entries()

    from app.models import Lesson
    Lesson.insert_entries()

    from app.models import Section
    Section.insert_entries()

    from app.models import Assignment
    Assignment.insert_entries()

    from app.models import Test
    Test.insert_entries()

    from app.models import AnnouncementType
    AnnouncementType.insert_entries()

    from config import basedir
    data = raw_input(u'Enter data identifier (e.g.: initial or 20160422): ')
    datadir = os.path.join(basedir, 'data', data)
    if os.path.exists(datadir):
        from app.models import User
        User.insert_entries(data=data, basedir=basedir)

        from app.models import UserCreation
        UserCreation.insert_entries(data=data, basedir=basedir)

        from app.models import Punch
        Punch.insert_entries(data=data, basedir=basedir)

        from app.models import Tag
        Tag.insert_entries(data='initial', basedir=basedir)

        from app.models import Product
        Product.insert_entries(data='initial', basedir=basedir)

        from app.models import Course
        Course.insert_entries(data='initial', basedir=basedir)

        from app.models import Period
        Period.insert_entries(data='initial', basedir=basedir)

        from app.models import iPad
        iPad.insert_entries(data='initial', basedir=basedir)

        from app.models import iPadContent
        iPadContent.insert_entries(data='initial', basedir=basedir)

        from app.models import NotaBene
        NotaBene.insert_entries(data='initial', basedir=basedir)

        from app.models import Feed
        Feed.insert_entries(data=data, basedir=basedir)
    else:
        print u'---> Invalid data identifier: %s' % data
Beispiel #32
0
def update():
    add = request.form.get("add", False)
    delete = request.form.get("delete", False)
    save = request.form.get("save", False)
    submit = request.form.get("submit", False)

    if delete:
        team = Team.query.get(delete)

        if team and team.entry == current_user.entry:
            if current_user.entry.teams.count() == 1:
                flash("You need to have at least one team", "warning")

            else:
                db.session.delete(team)
                flash("The team was removed", "success")

        else:
            flash("This isn't your team to delete", "danger")

    for team in current_user.entry.teams:
        if team.submitted == False:
            fields = dict(form_input_array(request.form, f"team-{team.id}"))
            team.name = fields.get("name", False)
            team.section = Section(fields.get("section", False))

            try:
                members = int(fields.get("number", 0))

            except ValueError:
                members = 0

            team.members = members

            for i, entryActivity in enumerate(current_user.entry.activities):
                team.scores[i].activity_id = entryActivity.activity.id

                try:
                    score = int(fields.get(f"activity-{i+1}", 0))

                except ValueError:
                    score = 0

                team.scores[i].score = score

    if save:
        flash("Your scores have been saved", "success")

    if add:
        current_user.entry.teams.append(Team())
        flash("Additional team added", "success")

    if submit:
        # TODO: See if this can be less intensive?
        success = True

        for team in current_user.entry.teams:
            if team.submitted == False:
                scores = Score.query.filter_by(team_id=team.id)

                validNumbers = team.members > 0
                validSection = team.section in Section
                validScores = scores.count() == 4 and (scores.filter(
                    (Score.score < 0) | (Score.score > 50)).count() == 0)

                if not validNumbers:
                    success = False
                    flash(
                        "There was a problem submitting your scores: the number of members in a team must be greater than 0",
                        "warning",
                    )
                    break

                if not validSection:
                    success = False
                    flash(
                        "There was a problem submitting your scores: one of your teams has an invalid section",
                        "warning",
                    )
                    break

                if not validScores:
                    success = False
                    flash(
                        "There was a problem submitting your scores: activity scores must be between 0 and 50",
                        "warning",
                    )
                    break

                team.rawScore = sum(
                    [int(score.score) for score in scores.all()])
                team.submitted = True

        if success:
            flash("Scores submitted", "success")

    db.session.commit()
    return redirect(url_for("scoring.index"))
Beispiel #33
0
def journal(journal_id, section_number, entry_number):
    # journal_id is id in database, section_number counts from 1 upwards, entry_number counts from 0 upwards
    # to overcome the vulnerability, check if the journal belongs to them

    user_id = session['user_id']
    if Journal.query.filter_by(id=journal_id,
                               user_id=user_id).scalar() is None:
        return redirect(url_for('journal_land'))

    # Could have called this data easily into lists using database, but this tree is better cause it allows the names
    # of all sections to be loaded at once to display, reducing delay

    # Creating the user tree
    user_id = session['user_id']
    tree = user_tree(user_id)

    # Finding the journal location in the tree
    journal_location = 1
    while int(journal_id) != tree[journal_location][0][0]:
        journal_location += 1

    # Finds content of specific journal, so more efficient and doesn't have to sort through everything
    journal_content = tree[journal_location]

    # so that we can make changes to the database
    journal = Journal.query.filter_by(id=journal_id).scalar()
    section = Section.query.filter_by(
        id=(journal_content[int(section_number)][0][0])).scalar()
    entry = Entry.query.filter_by(
        id=(journal_content[int(section_number)][int(entry_number) +
                                                 1][0])).scalar()

    # Form inputs for new section and new entry
    form_new_section = NewSection()
    form_new_entry = NewEntry()

    # The entry variables we are sending
    entry_text = entry.content
    print("entry content", entry_text)
    entry_title = entry.name
    entry_last_mod = str(entry.last_mod)[0:16]

    if form_new_section.validate_on_submit():
        section = Section(name=form_new_section.section_input.data,
                          journal_id=journal_id)
        db.session.add(section)
        db.session.commit()

        entry = Entry(name="my page", section_id=section.id, content="")
        db.session.add(entry)
        db.session.commit()

        form_new_section.section_input.data = ''

        # updating last mod of journal
        journal.last_mod = datetime.utcnow()
        db.session.commit()

        return redirect(
            url_for('journal',
                    journal_id=journal_id,
                    section_number=1,
                    entry_number=0))

    if form_new_entry.validate_on_submit():
        section_id = journal_content[int(section_number)][0][0]

        entry = Entry(name=form_new_entry.entry_input.data,
                      section_id=section_id,
                      content="")
        db.session.add(entry)
        db.session.commit()

        form_new_entry.entry_input.data = ''

        # updating last mod of journal and section
        journal.last_mod = datetime.utcnow()
        section.last_mod = datetime.utcnow()
        db.session.commit()

        return redirect(
            url_for('journal',
                    journal_id=journal_id,
                    section_number=section_number,
                    entry_number=0))

    # Entry details form
    entry_details = EntryInput()
    if entry_details.validate_on_submit():
        entry.content = entry_details.entry_content.data
        entry.name = entry_details.entry_name.data
        db.session.commit()

        # updating last mod of journal, section and entry
        journal.last_mod = datetime.utcnow()
        section.last_mod = datetime.utcnow()
        entry.last_mod = datetime.utcnow()
        db.session.commit()

    # to display the data
    entry_details.entry_content.data = entry.content

    return render_template('journal.html',
                           journal_content=journal_content,
                           journal_id=int(journal_id),
                           section_number=int(section_number),
                           entry_number=int(entry_number),
                           entry_title=entry_title,
                           entry_text=entry_text,
                           form_new_section=form_new_section,
                           form_new_entry=form_new_entry,
                           entry_details=entry_details,
                           entry_last_mod=entry_last_mod)
Beispiel #34
0
 async def mutate(self, info: ResolveInfo, theme: str,
                  description: str) -> (lambda: CreateSection):
     app = info.context['request'].app
     async with app['db'].acquire() as conn:
         section = Section(theme, description)
         return CreateSection(ok=await section.save(conn))