Ejemplo n.º 1
0
 def post(self):
     per_page = app.config['SEARCH_RESULTS_PER_PAGE']
     args = search_parser.parse_args()
     args = dict([(key, value) for (key, value) in args.items()
                  if key is not None])
     if 'page' not in args:
         abort(400, message="must specify page")
     if not any(key in args
                for key in ['student_id', 'team_id', 'project_id']):
         abort(400, message="must have at least one query field")
     students = Student.objects(
         db.Q(team_id=args.get('team_id'))
         | db.Q(guc_id=args.get('guc_id')))
     if 'project_id' in args:
         if len(students) > 0:
             subs = (Submission.objects(
                 submitter__in=students,
                 project=Project.objects(id=args['project_id'])).order_by(
                     '-created_at').paginate(args['page'], per_page))
         else:
             subs = (Submission.objects(project=Project.objects(
                 id=args['project_id'])).order_by('-created_at').paginate(
                     args['page'], per_page))
     else:
         subs = Submission.objects(
             submitter__in=students).order_by('-created_at').paginate(
                 args['page'], per_page)
     return mongo_paginate_to_dict(subs, 'submissions')
Ejemplo n.º 2
0
 def post(self, name):
     """
     Creates a new project for this course.
     User must be a course Teacher.
     """
     course = Course.objects.get_or_404(name=name)
     if g.user not in course.teachers:
         abort(403, message='Must be course teacher to add a project.')
     args = project_parser.parse_args()
     name = args['name']
     language = args['language']
     due_date = args['due_date']
     if due_date is None or due_date == '':
         abort(400, message="Project must have due date.")
     try:
         due_date = dateutil.parser.parse(due_date).astimezone(
             dateutil.tz.gettz('UTC')).replace(tzinfo=None)
     except:
         abort(400, message="Incorrect due date format.")
     if len([p for p in course.projects if p.name == name]) != 0:
         abort(422, message="Request makes no sense, grab a programmer.")
     filenames = [f.filename for f in request.files.values()]
     if len(filenames) != len(set(filenames)):
         abort(400, message="Test file names must be unique.")
     project = Project(name=name,
                       language=language,
                       due_date=due_date,
                       course=course)
     if args['test_timeout'] != -1:
         project.test_timeout_seconds = args['test_timeout']
     for test_case in request.files.values():
         if allowed_test_file(test_case.filename):
             grid_file = db.GridFSProxy()
             grid_file.put(test_case,
                           filename=secure_filename(test_case.filename),
                           content_type=request.mimetype)
             project.tests.append(grid_file)
         else:
             abort(400,
                   message="{0} extension not allowed".format(
                       test_case.filename))
     if args['published'] == 'True':
         project.published = True
     elif args['published'] == 'False':
         project.published = False
     else:
         abort(400,
               message="published value must be True or False as string.")
     if args['is_quiz'] == 'True':
         project.is_quiz = True
     elif args['is_quiz'] == 'False':
         project.is_quiz = False
     else:
         abort(400,
               message="is_quiz value must be True or False as string.")
     project.save()
     course.projects.append(project)
     course.save()
     return marshal(project.to_dict(parent_course=course),
                    project_fields), 201
Ejemplo n.º 3
0
def deleteProject(project_id):
    project = Project.objects(_id = project_id).first()
    if project:
        deleted_project = DeletedProject(previous_id=project_id, project_name=project.project_name, description=project.description, user_id=project.user_id)
        deleted_project.save()
        new_project_id = deleted_project._id
        deleted_calcs = CalcInput.objects(project_id = project_id)
        for calc in deleted_calcs:
            deleteCalculation(calc._id, new_project_id=new_project_id)
        Project.objects(_id = project_id).delete()
Ejemplo n.º 4
0
    def setUp(self):
        self.app = application.app
        bcrypt = Bcrypt(self.app)

        # forcibly reconnect to testing db
        connection.disconnect()
        self.app.config['MONGO_CONFIG']['db_name'] = 'pipeline_testing'
        self.connection = connect(
            self.app.config['MONGO_CONFIG']['db_name']
            , host=self.app.config['MONGO_CONFIG']['host']
            , port=int(self.app.config['MONGO_CONFIG']['port'])
        )
        # drop any lingering test dbs
        self.connection.drop_database(
            self.app.config['MONGO_CONFIG']['db_name'])

        member_user = User(
            admin_rights = False
            , email = '*****@*****.**'
            , email_confirmation_code = 'goodday'
            , email_confirmed = True
            , last_login_time = datetime.datetime.utcnow()
            , password_hash = bcrypt.generate_password_hash('hola!')
            , registration_time = datetime.datetime.utcnow()
            , verified = True)
        member_user.save()

        ''' create a test org
        '''
        test_org = Organization(
            label = 'best-org'
            , name = 'best org')
        test_org.save()

        # save membership
        member_user.update(push__organizations = test_org)

        ''' create a test project
        '''
        test_project = Project(
            creation_time = datetime.datetime.utcnow()
            , label = 'best-project'
            , name = 'best project'
            , organization = test_org)
        test_project.save()
        test_org.update(push__projects=test_project)

        ''' create a data-less upload
        '''
        '''
Ejemplo n.º 5
0
    def decorator(*args, **kwargs):

        p = Project.get_by_id(kwargs['project_id'])
        if p is None:
            return "project not found", 404
        kwargs['project'] = p

        return f(*args, **kwargs)
Ejemplo n.º 6
0
def landing():
    if not session.get('username'):
        return redirect(url_for('index'))
    my_projects = getUserProjects(session.get('user_id'))

    if selected_project_id := request.form.get('selected_project_id'):
        session['current_project_id'] = selected_project_id
        selected_project = Project.objects(_id=selected_project_id).first()
        session['current_p_name'] = selected_project.project_name
        session['current_p_description'] = selected_project.description
Ejemplo n.º 7
0
def form_group():
    users = User.query.filter(User.id != current_user.id).all()
    superuser = User.query.filter_by(email='*****@*****.**').first()
    users.remove(superuser)
    form = FormGroupForm()
    if form.validate_on_submit():
        members = request.form.getlist('members')
        if members == []:
            flash('Must select at least one member', 'danger')
            return redirect(url_for('form_group'))
        message = checkMessage(form.content.data.split())
        mess = message[0]
        if message[1] == 1:
            user = User.query.filter_by(id=current_user.id).first()
            user.rating -= 1
            db.session.add(user)
            db.session.commit()
        project = Project(title=form.title.data, description=mess)
        db.session.add(project)
        db.session.commit()
        for member in members:
            b_user = User.query.filter_by(id=member).first()
            in_blacklist = Blacklist.query.filter(
                (Blacklist.user == b_user.username)
                & (Blacklist.black == current_user.username)).first()
            in_whitelist = Whitelist.query.filter(
                (Whitelist.user == b_user.username)
                & (Whitelist.white == current_user.username)).first()
            if in_blacklist is None:
                if in_whitelist is not None:
                    projmember = ProjectMember(project=form.title.data,
                                               member=member)
                    db.session.add(projmember)
                    db.session.commit()
                    flash('you are in ' + b_user.username + '\'s white list',
                          'success')
                else:
                    message = Message1(title=form.title.data,
                                       content=mess,
                                       from_user=current_user.username,
                                       to_user=member,
                                       mess_type='invite')
                    db.session.add(message)
                    db.session.commit()
                    flash('Invite has been sent to ' + b_user.username,
                          'success')
            else:
                flash('you got blocked by ' + b_user.username, 'warning')
        projmember2 = ProjectMember(project=form.title.data,
                                    member=current_user.id)
        db.session.add(projmember2)
        db.session.commit()
        return redirect(url_for('home'))
    return render_template('form_group.html', form=form, users=users)
Ejemplo n.º 8
0
    def receive(self, text_data=None):
        eventData = json.loads(text_data)
        eventName = eventData["type"]
        if eventName == "project_join_request":
            self.send(text_data=json.dumps({
                "type": "project_join_reply",
                "joined": "true",
                "name": "NAME",
                "users": "USERS",
                "code": "CODE",
                "modified": "MODIFIED"
            }))

        elif eventName == "project_create":

            code = "ahs8dj1k"

            project = Project(name="Name",
                              description="Desc",
                              code="a7sh1kf1",
                              workspace="",
                              user=self.scope["user"])
            project.save()

            self.send(text_data=json.dumps({
                "type": "project_create_reply",
                "created": "true"
            }))

        elif eventName == "project_remove":
            print(eventData["code"])

            #Projects.objecst.filter(id).delete()

            self.send(text_data=json.dumps({
                "type": "project_remove_reply",
                "removed": "true"
            }))

        elif eventName == "hello":
            self.send(text_data=json.dumps({"type": "hello_reply"}))
Ejemplo n.º 9
0
def create_projects():
    for _ in range(5):
        project = Project(
            title=fake.sentence(nb_words=3),
            subject=fake.words(nb=1),
            short_description=fake.sentence(nb_words=8),
            description=fake.paragraph(nb_sentences=8)
        )
        print(
            f'Dummy Project {project.title}: {project.short_description}')
        db.session.add(project)
    db.session.commit()
Ejemplo n.º 10
0
def create_project():
    members = User.query.all()
    form = ProjectForm()
    form.users.choices = members
    if form.validate_on_submit():
        new_project = Project(form.title.data, form.subject.data,
                              form.short_description.data,
                              form.description.data)
        save_data(new_project)
        return redirect(url_for('project.show_projects'))
    return render_template('project/creating.html',
                           title='Creating project',
                           form=form)
Ejemplo n.º 11
0
    def test_time_goal_and_time_contributed(self):
        steve = TestModels.create_steve()
        db.session.add(steve)
        db.session.commit()

        # create a project
        new_project = Project(user=steve.id, name='Learn Swedish')
        db.session.add(new_project)
        db.session.commit()

        # create a goal for this project
        # 30 minutes every day
        new_goal = Goal(project=new_project.id, days=0b1111111, time=30)
        db.session.add(new_goal)
        db.session.commit()

        # test Project.time_goal
        self.assertTrue(new_project.time_goal() == 30)

        # create another goal
        # 15 minutes on weekdays
        weekday_goal = Goal(project=new_project.id, days=0b0011111, time=15)
        db.session.add(weekday_goal)
        db.session.commit()

        # test Project.time_goal
        weekday = date(2015, 10, 26)
        weekend = date(2015, 10, 25)
        self.assertTrue(new_project.time_goal(weekday) == 45)
        self.assertTrue(new_project.time_goal(weekend) == 30)

        # create a new contribution
        new_contribution = Contribution(project=new_project.id, time=60)
        db.session.add(new_contribution)
        db.session.commit()

        self.assertTrue(new_project.time_contributed() == 60)

        # create an old contribution
        old_date = date(2015, 06, 10)
        contribution = Contribution(project=new_project.id,
                                    time=20,
                                    date=old_date)
        db.session.add(contribution)
        db.session.commit()

        self.assertTrue(new_project.time_contributed() == 80)

        # test time_contributed with date range
        start_date = date(2015, 06, 01)
        end_date = date(2015, 07, 01)
        self.assertTrue(
            new_project.time_contributed(start=start_date, end=end_date) == 20)
Ejemplo n.º 12
0
 def get(self, project_id, page=1, rerurn_submissions=False):
     """
     Retrieves all grades or single student grade.
     """
     project = Project.get_or_404(project_id)
     if isinstance(g.user, Student):
         return marshal(
             TeamProjectGrade.objects(project=project,
                                      team_id=g.user.team_id),
             team_project_grade_fields)
     else:
         if g.user not in project.course.teachers:
             abort(403, message="Must be course teacher to view grades")
         pages = (TeamProjectGrade.objects(project=project)
                  .paginate(page,
                            api.app.config['PROJECT_TEAM_GRADES_PER_PAGE']))
         return marshal(mongo_paginate_to_dict(pages, "grades"),
                        team_project_grade_page_fields)
Ejemplo n.º 13
0
    def setUp(self):
        self.app = application.app
        bcrypt = Bcrypt(self.app)

        # forcibly reconnect to testing db
        connection.disconnect()
        self.app.config['MONGO_CONFIG']['db_name'] = 'pipeline_testing'
        mongo_config = self.app.config['MONGO_CONFIG']
        mongodb_uri = 'mongodb://'
        if mongo_config['dbuser'] and mongo_config['dbpassword']:
            mongodb_uri += '%s:%s@' % (mongo_config['dbuser']
                    , mongo_config['dbpassword'])
        mongodb_uri += '%s/%s' % (mongo_config['hosts'], mongo_config['db_name'])
        self.connection = connect(mongo_config['db_name'], host=mongodb_uri)

        # drop any lingering test dbs
        self.connection.drop_database(
            self.app.config['MONGO_CONFIG']['db_name'])

        ''' create test user
        '''
        member_user = User(
            admin_rights = False
            , email = '*****@*****.**'
            , email_confirmation_code = 'goodday'
            , email_confirmed = True
            , last_login_time = datetime.utcnow()
            , password_hash = bcrypt.generate_password_hash('hola!')
            , registration_time = datetime.utcnow()
            , verified = True)
        member_user.save()

        ''' create test org
        '''
        test_org = Organization(
            label = 'euro-water'
            , name = 'Euro Water')
        test_org.save()
        # save membership
        member_user.update(push__organizations = test_org)

        ''' create test headers
        '''
        date_header = Header(data_type = 'datetime', name = 'date',
                label = 'date')
        date_header.save()

        pH_header = Header(data_type = 'number', name = 'pH', label = 'pH')
        pH_header.save()

        city_header = Header(data_type = 'string', name = 'city',
                label = 'city')
        city_header.save()
        headers = [date_header, pH_header, city_header]

        # save ref to this header for later test
        self.date_header_id = date_header.id

        ''' create test project
        '''
        test_project = Project(
            creation_time = datetime.utcnow()
            , label = 'water-quality'
            , name = 'water quality'
            , ordered_schema = headers
            , organization = test_org)
        test_project.save()
        test_org.update(push__projects=test_project)

        ''' update the headers with a ref to the project
        '''
        for header in headers:
            header.update(set__project = test_project)

        ''' create test datapoints
        '''
        test_data = [
            {'date': datetime(2012, 3, 4), 'pH': 2.2, 'city': 'Madrid'}
            , {'date': datetime(2012, 3, 5), 'pH': 3, 'city': 'Paris'}
            , {'date': datetime(2012, 3, 6), 'pH': 4, 'city': 'London'}
            , {'date': datetime(2012, 3, 6), 'pH': 3, 'city': 'London'}
            , {'date': datetime(2012, 3, 6), 'pH': None, 'city': 'London'}
        ]
        for datapoint in test_data:
            new_entry = Entry(
                project = test_project
                , unique = True
                , values = datapoint)
            new_entry.save()
Ejemplo n.º 14
0
    if selected_calc_id := request.form.get('selected_calc_id'):
        session['current_calc_id'] = selected_calc_id
        selected_calculation = CalcInput.objects(_id=selected_calc_id).first()
        session['current_c_name'] = selected_calculation.calc_name
        session['current_c_description'] = selected_calculation.description
        return redirect(url_for('design_dashboard'))

    ############------------ADD PROJECT FORM-----------##############
    pform = ProjectForm()
    if pform.validate_on_submit():
        project_name = pform.project_name.data
        description = pform.description.data

        project = Project(
            project_name=project_name,
            description=description,
            user_id=session.get('user_id'))  # user_id=ObjectId(),
        project.save()

        flash(f"You have saved {project_name}", "success")
        return redirect(url_for('landing'))

    ############------------CHANGE PROJECT NAME FORM-----------##############
    pnameform = ChangeProjectForm()
    if pnameform.validate_on_submit():
        new_project_name = pnameform.new_project_name.data
        new_description = pnameform.new_description.data

        project = Project.objects(_id=session['current_project_id']).first()
        project.project_name = new_project_name
        project.description = new_description
Ejemplo n.º 15
0
    def setUp(self):
        self.app = application.app
        bcrypt = Bcrypt(self.app)

        # forcibly reconnect to testing db
        connection.disconnect()
        self.app.config['MONGO_CONFIG']['db_name'] = 'pipeline_testing'
        mongo_config = self.app.config['MONGO_CONFIG']
        mongodb_uri = 'mongodb://'
        if mongo_config['dbuser'] and mongo_config['dbpassword']:
            mongodb_uri += '%s:%s@' % (mongo_config['dbuser']
                    , mongo_config['dbpassword'])
        mongodb_uri += '%s/%s' % (mongo_config['hosts'], mongo_config['db_name'])
        self.connection = connect(mongo_config['db_name'], host=mongodb_uri)

        # drop any lingering test dbs
        self.connection.drop_database(
            self.app.config['MONGO_CONFIG']['db_name'])

        admin_user = User(
            admin_rights = True
            , email = '*****@*****.**'
            , email_confirmation_code = 'goodday'
            , email_confirmed = True
            , last_login_time = datetime.datetime.utcnow()
            , password_hash = bcrypt.generate_password_hash('hola!')
            , registration_time = datetime.datetime.utcnow()
            , verified = True)
        admin_user.save()

        # same as verified but will push into an org for membership
        member_user = User(
            admin_rights = False
            , email = '*****@*****.**'
            , email_confirmation_code = 'goodday'
            , email_confirmed = True
            , last_login_time = datetime.datetime.utcnow()
            , password_hash = bcrypt.generate_password_hash('hola!')
            , registration_time = datetime.datetime.utcnow()
            , verified = True)
        member_user.save()

        verified_user = User(
            admin_rights = False
            , email = '*****@*****.**'
            , email_confirmation_code = 'goodday'
            , email_confirmed = True
            , last_login_time = datetime.datetime.utcnow()
            , password_hash = bcrypt.generate_password_hash('hola!')
            , registration_time = datetime.datetime.utcnow()
            , verified = True)
        verified_user.save()

        unverified_user = User(
            admin_rights = False
            , email = '*****@*****.**'
            , email_confirmation_code = 'goodday'
            , email_confirmed = True
            , last_login_time = datetime.datetime.utcnow()
            , password_hash = bcrypt.generate_password_hash('hola!')
            , registration_time = datetime.datetime.utcnow()
            , verified = False)
        unverified_user.save()

        ''' create a test org
        '''
        test_org = Organization(
            label = 'best-org'
            , name = 'best org')
        test_org.save()

        # save membership
        member_user.update(push__organizations = test_org)

        ''' create a test project
        '''
        test_project = Project(
            creation_time = datetime.datetime.utcnow()
            , label = 'best-project'
            , name = 'best project'
            , organization = test_org)
        test_project.save()
        test_org.update(push__projects=test_project)