Example #1
0
 def setUp(self):
     self.experiment1 = Experiment(orig_study_id=1)
     self.experiment2 = Experiment(orig_study_id=2)
     self.experiment3 = Experiment(orig_study_id=3)
     self.subject1 = Subject(orig_subject_id=1)
     self.subject2 = Subject(orig_subject_id=2)
     self.sample1 = Sample(orig_sample_id=1)
     self.sample2 = Sample(orig_sample_id=2)
     self.sample3 = Sample(orig_sample_id=3)
     self.sample4 = Sample(orig_sample_id=4)  # TODO: Delete?
     # Set up relationships
     self.subject1._samples = {self.sample1, self.sample2}
     self.subject2._samples = {self.sample3}
     self.sample1._subject = self.subject1
     self.sample2._subject = self.subject1
     self.sample3._subject = self.subject2
     self.experiment1._samples = {self.sample1, self.sample2}
     self.experiment1._subjects = {self.subject1}
     self.experiment2._samples = {self.sample1}
     self.experiment2._subjects = {self.subject1}
     self.experiment3._samples = {self.sample1, self.sample3}
     self.experiment3._subjects = {self.subject1, self.subject2}
     self.subject1._experiments = {
         self.experiment1, self.experiment2, self.experiment3
     }
     self.subject2._experiments = {self.experiment3}
     self.sample1._experiments = {
         self.experiment1, self.experiment2, self.experiment3
     }
     self.sample2._experiments = {self.experiment1}
     self.sample3._experiments = {self.experiment3}
Example #2
0
    def test_item_query(self):
        class Mock(SubjectSweepMonitor):
            SERVICE_NAME = "Mock"

        s1, ignore = Subject.lookup(self._db, Subject.DDC, "100", None)
        s2, ignore = Subject.lookup(self._db, Subject.TAG, None,
                                    "100 Years of Solitude")

        # By default, SubjectSweepMonitor handles every Subject
        # in the database.
        everything = Mock(self._db)
        eq_([s1, s2], everything.item_query().all())

        # But you can tell SubjectSweepMonitor to handle only Subjects
        # of a certain type.
        dewey_monitor = Mock(self._db, subject_type=Subject.DDC)
        eq_([s1], dewey_monitor.item_query().all())

        # You can also SubjectSweepMonitor to handle only Subjects
        # whose names or identifiers match a certain string.
        one_hundred_monitor = Mock(self._db, filter_string="100")
        eq_([s1, s2], one_hundred_monitor.item_query().all())

        specific_tag_monitor = Mock(self._db,
                                    subject_type=Subject.TAG,
                                    filter_string="Years")
        eq_([s2], specific_tag_monitor.item_query().all())
Example #3
0
 def setUp(self):
     self.experiment1 = Experiment()
     self.subject1 = Subject(orig_subject_id=1)
     self.subject2 = Subject(orig_subject_id=2)
     self.sample1 = Sample(orig_sample_id=1)
     self.sample2 = Sample(orig_sample_id=2)
     self.sample3 = Sample(orig_sample_id=3)
     self.sample4 = Sample(orig_sample_id=4)
     # Set up relationships
     self.subject1._samples = {self.sample1, self.sample2}
     self.subject2._samples = {self.sample3}
     self.sample1._subject = self.subject1
     self.sample2._subject = self.subject1
     self.sample3._subject = self.subject2
    def test_subject_query(self):
        s1, ignore = Subject.lookup(self._db, Subject.DDC, "100", None)
        s2, ignore = Subject.lookup(self._db, Subject.TAG, None,
                                    "100 Years of Solitude")

        dewey_monitor = SubjectSweepMonitor(self._db, "Test Monitor",
                                            Subject.DDC)
        eq_([s1], dewey_monitor.subject_query().all())

        one_hundred_monitor = SubjectSweepMonitor(self._db, "Test Monitor",
                                                  None, "100")
        eq_([s1, s2], one_hundred_monitor.subject_query().all())

        specific_tag_monitor = SubjectSweepMonitor(self._db, "Test Monitor",
                                                   Subject.TAG, "Years")
        eq_([s2], specific_tag_monitor.subject_query().all())
Example #5
0
def subject(id):
    if current_user.role_name != 'AdminUser':
        return render_error(403)
    if id == 'new':
        s = Subject()
    else:
        try:
            id = int(id)
        except ValueError:
            return render_error(400)
        s = db.session.query(Subject).filter(Subject.id == id).one_or_none()
        if s is None:
            return render_error(404)

    form = SubjectForm(request.form if request.method == 'POST' else None, obj=s)
    if form.button_delete.data:
        form.validate()
        if db.session.query(CurriculumUnit).filter(CurriculumUnit.subject_id == s.id).count() > 0:
            form.button_delete.errors.append('Невозможно удалить предмет, к которому привязаны единицы учебного плана')
        if len(form.button_delete.errors) == 0:
            db.session.delete(s)
            db.session.commit()
            db.session.flush()
            return redirect(url_for('subjects'))

    if form.button_save.data and form.validate():
        form.populate_obj(s)
        db.session.add(s)
        db.session.commit()
        if id == 'new':
            db.session.flush()
            return redirect(url_for('subject', id=s.id))

    return render_template('subject.html', subject=s, form=form)
Example #6
0
File: admin.py Project: Tydus/tsp
    def post(self):

        subject=self.get_argument('subject')
        student=self.get_argument('student')

        s=Subject.objects(id=ObjectId(subject)).first()
        if not s:
            return self.write({'err':'课题不存在'})
        if s.applied_to:
            return self.write({'err':'课题已被分配给'+s.applied_to.realname.encode('utf-8')})

        u=Student.objects(username=student).first()
        if not u:
            return self.write({'err':'学生不存在'})
        if u.applied_to:
            return self.write({'err':'学生已被分配'+u.applied_to.name.encode('utf-8')+'课题'})

        # Match Straightly
        s.selected_by=[]
        s.applied_to=u
        u.selected=None
        u.applied_to=s

        s.save()
        u.save()

        self.write({})
Example #7
0
    def post(self):

        subject=self.get_argument('subject')
        student=self.get_argument('student',default="")

        s=Subject.objects(id=ObjectId(subject)).first()
        if not s:
            return self.write({'err':'课题不存在'})

        if s.professor.username!=self.current_user.username:
            return self.write({'err':'不是你的课题'})

        if s.selected_by==[]:
            return self.write({'err':'不可改选上阶段选好的课题'})

        # Clear previous approvement
        if s.applied_to:
            u=Student.objects(username=s.applied_to.username).first()
            u.applied_to=None
            u.save()
            s.applied_to=None

        if student:
            for u_embedded in s.selected_by:
                u=Student.objects(username=u_embedded.username).first()
                if u.username==student:
                    # You are the one!
                    s.applied_to=u
                    u.applied_to=s
                u.save()

        s.save()

        self.write({})
Example #8
0
 def test_print_db(self):
     query = Subject.all()
     string = "database:\n"
     count = 0
     for result in query:
         string += str(count)+" "+result.description + "\n"
         count = count+1
     print string
Example #9
0
 def test_remove(self, name):
     print "removing "+name
     subjects = Subject.gql("WHERE description = :1", name)
     subject = subjects.get()
     try:
         db.delete(subject)
     except (Exception):
         print "can't find "+name+"\n"
Example #10
0
def result():
    username = request.get_cookie("username")
    user = User.get(User.id == int(username))
    subjects = Subject.select()
    # result = Result.select().where(Result.username==user,
    # 								Result.subject_code==subject)
    # print(result)
    return {"subjects": subjects}
Example #11
0
def result(subject_id):
    username = request.get_cookie("username")
    print(username)
    subject = Subject.get(Subject.id == subject_id)
    user = User.get(User.id == int(username))
    responses = Response.select().where(Response.user == user,
                                        Response.subject_code == subject)
    result = Result.get(Result.username == user,
                        Result.subject_code == subject)
    return {"result": result, "subject": subject, "responses": responses}
Example #12
0
def add_grade_():
    form = AddGradeForm()
    if form.validate_on_submit():
        try:
            with db.transaction():
                grade = Grade.create(
                    student=Student.get(Student.username == form.student_select.data),
                    subject=Subject.get(Subject.name == form.subject_select.data),
                    teacher=get_current_user(),
                    grade=form.grade.data
                )
        except DatabaseError:
            flash('An error occurred while adding a grade')
        else:
            flash('Grade ' + str(grade.grade) + ' assigned to student ' + str(grade.student))
            return redirect(url_for('groups', group=grade.student.username))
    flash_errors(form)
    students = Student.select()
    subjects = Subject.select()
    return render_template('add_grade.html', students=students, subjects=subjects, form=form)
Example #13
0
def set_up_domains():
    classes = []
    for i in subjects:
        lector = list(filter(lambda t: i["name"] in t["lector"], teachers))
        practices_teachers = list(
            filter(
                lambda t: i["name"] in t["lector"] or i["name"] in t[
                    "practices"], teachers))
        classes.append(
            Class(
                Subject(lector[0]["name"], i["name"], i["students"], 0,
                        i["groups"]), None))
        for j in range(i["groups"]):
            classes.append(
                Class(
                    Subject(
                        practices_teachers[random.randint(
                            0,
                            len(practices_teachers) - 1)]["name"], i["name"],
                        i["students"] // i["groups"], j + 1, i["groups"]),
                    None))
    return classes
Example #14
0
    def post(self):
        u=self.current_user

        subject=self.get_argument('id')
        s=Subject.objects(id=ObjectId(subject)).first()
        if not s:
            return self.write({'err':'课题不存在'})

        if s.professor.username!=self.current_user.username:
            return self.write({'err':'不是你的课题'})

        s.delete()

        self.write({})
Example #15
0
def sub2(subject_id):

    username = request.get_cookie("username")
    subject = Subject.get(Subject.id == subject_id)
    user = User.get(User.id == int(username))
    print(user)

    result = Result.select().where(Result.username == int(username))
    if (len(result) != 0) and (result[0].is_taken == True):
        return redirect("/result")

    for question in Question.filter(Question.subject_code == subject):
        res = request.forms.get(f"question-{question.id}")
        response = Response(qid=question.id,
                            subject_code=subject_id,
                            user=user,
                            response=res)
        response.save()

        try:
            result = Result.get(Result.username == user,
                                Result.subject_code == subject)
        except:
            result = Result(username=user, subject_code=subject, is_taken=True)

        if int(res) == question.right_option:
            result.marks_obtained += 1

            if result.marks_obtained == 20:
                result.grade = "A"
                result.state = "Outstanding!"

            elif result.marks_obtained > 13:
                result.grade = "B"
                result.state = "Good!"

            elif result.marks_obtained > 7:
                result.grade = "C"
                result.state = "Average!"

            else:
                result.grade = "D"
                result.state = "Poor!"
        else:
            result.marks_obtained += 0

        result.save()
        subject = subject.select()[0]

    return redirect("/choosesub")
Example #16
0
    def post(self):
        u=self.current_user

        name=self.get_argument('name')
        desc=self.get_argument('desc')
        type1=self.get_argument('type1')
        type2=self.get_argument('type2')
        source=self.get_argument('source')

        old_s=Subject.objects(name=name).first()
        if old_s and old_s.professor.username==u.username:
            return self.write({'err':'课题已存在'})

        s=Subject(
                name=name,
                desc=desc,
                type1=type1,
                type2=type2,
                source=source,
                professor=u,
        )
        s.save()

        return self.write({'id':str(s.id)})
def display_subject_graph():
    """displays subject information page"""

    last_subj_id = 138
    start_at = randint(1, last_subj_id - SHOW_NUMBER)
    stop_before = start_at + SHOW_NUMBER

    subject_data = Subject.get_subject_data(start_at=start_at,
                                            stop_before=stop_before)

    rough_subjects = db.session.query(Subject.subject, Subject.subject_id).all()

    all_subjects = {}
    for subject, subject_id in rough_subjects:
        all_subjects[subject] = subject_id

    return render_template("subjects.html", subject_data=subject_data,
                           all_subjects=all_subjects)
Example #18
0
 def __init__(self, _db=None, cmd_args=None):
     _db = _db or self._db
     args = self.parse_command_line(_db, cmd_args=cmd_args)
     self.identifier_type = args.identifier_type
     self.identifiers = args.identifiers
     subject_type = args.subject_type
     subject_identifier = args.subject_identifier
     subject_name = args.subject_name
     if not subject_name and not subject_identifier:
         raise ValueError(
             "Either subject-name or subject-identifier must be provided.")
     self.data_source = DataSource.lookup(_db, args.data_source)
     self.weight = args.weight
     self.subject, ignore = Subject.lookup(_db,
                                           subject_type,
                                           subject_identifier,
                                           subject_name,
                                           autocreate=args.create_subject)
Example #19
0
File: student.py Project: Tydus/tsp
    def post(self):
        subject=self.get_argument('subject',"")

        u=self.current_user
        if u.excluded:
            return self.write({'err':'你被从选课中排除'})
        if u.applied_to:
            return self.write({'err':'你已被'+u.applied_to.name.encode('utf-8')+'课题选中'})

        if not subject:
            # Clear Currently Selected
            if u.selected:
                old_s=u.selected
                #u.selected=None
                old_s.selected_by=[i for i in old_s.selected_by if i.id!=u.id]
                old_s.save()
                u.save()

	else:
            s=Subject.objects(id=ObjectId(subject)).first()
            if not s:
                return self.write({'err':'课题不存在'})
            if s.applied_to:
                return self.write({'err':'课题已被'+s.applied_to.realname.encode('utf-8')+'选中'})

            # Clear Currently Selected
            if u.selected:
                old_s=u.selected
                #u.selected=None
                old_s.selected_by=[i for i in old_s.selected_by if i.id!=u.id]
                old_s.save()

            # Beware if old_s==s
            s.reload()

            # Select New
            if subject:
                u.selected=s
                s.selected_by.append(u)
            s.save()

        u.save()

        self.write({})
def category_handler(subject_dict, book_object, subject_list, source):
    """Takes in categories returned from OpenLib or Google Books. 
    Normalizes category names & saves subjects to dictionary."""

    for category in subject_list:
        category = category.lower()

        delimiters = [" in fiction", "(", ", ", "=", "/"]
        for sep in delimiters:
            keep, delim, delete = category.partition(sep)
            category = keep

        is_subject = Subject.query.filter_by(subject=category).first()
        if is_subject == None:
            new_subject = Subject(subject=category, source=source)
            db.session.add(new_subject)

        if subject_dict.get(book_object.book_id, None):
            subject_dict[book_object.book_id].add(category)
        else:
            subject_dict[book_object.book_id] = {category}

    return subject_dict
Example #21
0
    def post(self):
        u=self.current_user

        subject=self.get_argument('id')
        name=self.get_argument('name',default="")
        desc=self.get_argument('desc',default="")
        type1=self.get_argument('type1',default="")
        type2=self.get_argument('type2',default="")
        source=self.get_argument('source',default="")

        s=Subject.objects(id=ObjectId(subject)).first()
        if not s:
            return self.write({'err':'课题不存在'})

        if s.professor.username!=self.current_user.username:
            return self.write({'err':'不是你的课题'})

        for i in ['name','desc','type1','type2','source']:
            value=self.get_argument(i,default="")
            if value:
                s[i]=value
        s.save()

        self.write({})
Example #22
0
def load_subjects(soup, poem):
    """loads subjects from poem meta tags"""
    poem_id = poem.poem_id

    subjects = Parse.parse_subjects(soup)

    if subjects:
        for subject in subjects:
            try:
                subject_id = Subject.query.filter(Subject.subject_name == subject).one().subject_id
            except NoResultFound:
                log_err('subject', f, subject)
                s = Subject(subject_name=subject)
                db.session.add(s)
                db.session.flush()
                subject_id = s.subject_id
            

            poemsubject = PoemSubject(poem_id=poem_id,
                                        subject_id=subject_id)

            db.session.add(poemsubject)

            db.session.flush()
Example #23
0
def parse_subject(row):
    subject = Subject()
    return subject
Example #24
0
def parse_subject(row, source=None):
    """Parse a row into a Subject.

    Parameters
    ----------
    row : dict-like
        Object whose keys are column headings and values are the row values.
    source : model.Source
        Source for the returned subject.

    Returns
    -------
    Subject
    """
    subject = Subject()
    subject.sex = get_sex(row)
    subject.country = get_country(row)
    subject.race = get_race(row)
    subject.csection = get_csection(row)
    subject.disease = get_disease(row)
    subject.dob = get_dob(row)

    # Initialize equality attrs
    if not source:
        subject.source = parse_source(row)
    elif isinstance(source, Source):
        subject.source = source
    else:
        raise TypeError(f'Given source was not of type {type(Source())!r}.')
    subject.orig_study_id = get_study_id(row)
    subject.orig_subject_id = get_subject_id(row)
    return subject
Example #25
0
def parse_subject(row, attr_map):
    subject = Subject()
    for index, attr in attr_map.items():
        setattr(subject, attr, row[index])
    return subject
Example #26
0
 def test_add(self,name):
     print "adding "+name
     subject = Subject()
     subject.description = name
     db.put(subject)
Example #27
0
 def test_modify(self,old_name,new_name):
     print "modifying "+old_name+" to "+new_name
     subjects = Subject.gql("WHERE description = :1", old_name)
     subject = subjects.get()
     subject.description = new_name
     db.put(subject)
Example #28
0
class ModelRemoveTest(unittest.TestCase):
    def setUp(self):
        self.experiment1 = Experiment(orig_study_id=1)
        self.experiment2 = Experiment(orig_study_id=2)
        self.experiment3 = Experiment(orig_study_id=3)
        self.subject1 = Subject(orig_subject_id=1)
        self.subject2 = Subject(orig_subject_id=2)
        self.sample1 = Sample(orig_sample_id=1)
        self.sample2 = Sample(orig_sample_id=2)
        self.sample3 = Sample(orig_sample_id=3)
        self.sample4 = Sample(orig_sample_id=4)  # TODO: Delete?
        # Set up relationships
        self.subject1._samples = {self.sample1, self.sample2}
        self.subject2._samples = {self.sample3}
        self.sample1._subject = self.subject1
        self.sample2._subject = self.subject1
        self.sample3._subject = self.subject2
        self.experiment1._samples = {self.sample1, self.sample2}
        self.experiment1._subjects = {self.subject1}
        self.experiment2._samples = {self.sample1}
        self.experiment2._subjects = {self.subject1}
        self.experiment3._samples = {self.sample1, self.sample3}
        self.experiment3._subjects = {self.subject1, self.subject2}
        self.subject1._experiments = {
            self.experiment1, self.experiment2, self.experiment3
        }
        self.subject2._experiments = {self.experiment3}
        self.sample1._experiments = {
            self.experiment1, self.experiment2, self.experiment3
        }
        self.sample2._experiments = {self.experiment1}
        self.sample3._experiments = {self.experiment3}

    def tearDown(self):
        del self.experiment1
        del self.experiment2
        del self.experiment3
        del self.subject1
        del self.subject2
        del self.sample1
        del self.sample2
        del self.sample3
        del self.sample4

    def test_remove_subject_from_experiment(self):
        # Attributes that should change
        expected_subject1_experiments = {self.experiment2, self.experiment3}
        expected_experiment1_subjects = set()
        expected_experiment1_samples = set()
        expected_sample1_experiments = {self.experiment2, self.experiment3}
        expected_sample2_experiments = set()
        # Attributes that should not be affected
        expected_subject2_experiments = self.subject2.experiments
        expected_experiment2_subjects = self.experiment2.subjects
        expected_experiment3_subjects = self.experiment3.subjects
        expected_experiment2_samples = self.experiment2.samples
        expected_experiment3_samples = self.experiment3.samples
        expected_sample3_experiments = self.sample3.experiments
        # Call the function
        self.experiment1.remove_subject(self.subject1)
        # Check
        self.assertEqual(self.subject1.experiments,
                         expected_subject1_experiments)
        self.assertEqual(self.experiment1.subjects,
                         expected_experiment1_subjects)
        self.assertEqual(self.experiment1.samples,
                         expected_experiment1_samples)
        self.assertEqual(self.sample1.experiments,
                         expected_sample1_experiments)
        self.assertEqual(self.sample2.experiments,
                         expected_sample2_experiments)
        self.assertEqual(self.subject2.experiments,
                         expected_subject2_experiments)
        self.assertEqual(self.experiment2.subjects,
                         expected_experiment2_subjects)
        self.assertEqual(self.experiment3.subjects,
                         expected_experiment3_subjects)
        self.assertEqual(self.experiment2.samples,
                         expected_experiment2_samples)
        self.assertEqual(self.experiment3.samples,
                         expected_experiment3_samples)
        self.assertEqual(self.sample3.experiments,
                         expected_sample3_experiments)

    def test_remove_experiment_from_subject(self):
        # Attributes that should change
        expected_subject1_experiments = {self.experiment2, self.experiment3}
        expected_experiment1_subjects = set()
        expected_experiment1_samples = set()
        expected_sample1_experiments = {self.experiment2, self.experiment3}
        expected_sample2_experiments = set()
        # Attributes that should not be affected
        expected_subject2_experiments = self.subject2.experiments
        expected_experiment2_subjects = self.experiment2.subjects
        expected_experiment3_subjects = self.experiment3.subjects
        expected_experiment2_samples = self.experiment2.samples
        expected_experiment3_samples = self.experiment3.samples
        expected_sample3_experiments = self.sample3.experiments
        # Call the function
        self.subject1.remove_experiment(self.experiment1)
        # Check
        self.assertEqual(self.subject1.experiments,
                         expected_subject1_experiments)
        self.assertEqual(self.experiment1.subjects,
                         expected_experiment1_subjects)
        self.assertEqual(self.experiment1.samples,
                         expected_experiment1_samples)
        self.assertEqual(self.sample1.experiments,
                         expected_sample1_experiments)
        self.assertEqual(self.sample2.experiments,
                         expected_sample2_experiments)
        self.assertEqual(self.subject2.experiments,
                         expected_subject2_experiments)
        self.assertEqual(self.experiment2.subjects,
                         expected_experiment2_subjects)
        self.assertEqual(self.experiment3.subjects,
                         expected_experiment3_subjects)
        self.assertEqual(self.experiment2.samples,
                         expected_experiment2_samples)
        self.assertEqual(self.experiment3.samples,
                         expected_experiment3_samples)
        self.assertEqual(self.sample3.experiments,
                         expected_sample3_experiments)

    def test_remove_sample_from_experiment(self):
        # Attributes that should change
        expected_experiment1_samples = {self.sample2}
        expected_sample1_experiments = {self.experiment2, self.experiment3}
        # Attributes that should not be affected
        expected_subject1_experiments = {
            self.experiment1, self.experiment2, self.experiment3
        }
        expected_subject2_experiments = self.subject2.experiments
        expected_experiment1_subjects = {self.subject1}
        expected_experiment2_subjects = self.experiment2.subjects
        expected_experiment3_subjects = self.experiment3.subjects
        expected_experiment2_samples = self.experiment2.samples
        expected_experiment3_samples = self.experiment3.samples
        expected_sample2_experiments = {self.experiment1}
        expected_sample3_experiments = self.sample3.experiments
        # Call the function
        self.experiment1.remove_sample(self.sample1)
        # Check
        self.assertEqual(self.subject1.experiments,
                         expected_subject1_experiments)
        self.assertEqual(self.experiment1.subjects,
                         expected_experiment1_subjects)
        self.assertEqual(self.experiment1.samples,
                         expected_experiment1_samples)
        self.assertEqual(self.sample1.experiments,
                         expected_sample1_experiments)
        self.assertEqual(self.sample2.experiments,
                         expected_sample2_experiments)
        self.assertEqual(self.subject2.experiments,
                         expected_subject2_experiments)
        self.assertEqual(self.experiment2.subjects,
                         expected_experiment2_subjects)
        self.assertEqual(self.experiment3.subjects,
                         expected_experiment3_subjects)
        self.assertEqual(self.experiment2.samples,
                         expected_experiment2_samples)
        self.assertEqual(self.experiment3.samples,
                         expected_experiment3_samples)
        self.assertEqual(self.sample3.experiments,
                         expected_sample3_experiments)

    def test_remove_experiment_from_sample(self):
        # Attributes that should change
        expected_experiment1_samples = {self.sample2}
        expected_sample1_experiments = {self.experiment2, self.experiment3}
        # Attributes that should not be affected
        expected_subject1_experiments = {
            self.experiment1, self.experiment2, self.experiment3
        }
        expected_subject2_experiments = self.subject2.experiments
        expected_experiment1_subjects = {self.subject1}
        expected_experiment2_subjects = self.experiment2.subjects
        expected_experiment3_subjects = self.experiment3.subjects
        expected_experiment2_samples = self.experiment2.samples
        expected_experiment3_samples = self.experiment3.samples
        expected_sample2_experiments = {self.experiment1}
        expected_sample3_experiments = self.sample3.experiments
        # Call the function
        self.sample1.remove_experiment(self.experiment1)
        # Check
        self.assertEqual(self.subject1.experiments,
                         expected_subject1_experiments)
        self.assertEqual(self.experiment1.subjects,
                         expected_experiment1_subjects)
        self.assertEqual(self.experiment1.samples,
                         expected_experiment1_samples)
        self.assertEqual(self.sample1.experiments,
                         expected_sample1_experiments)
        self.assertEqual(self.sample2.experiments,
                         expected_sample2_experiments)
        self.assertEqual(self.subject2.experiments,
                         expected_subject2_experiments)
        self.assertEqual(self.experiment2.subjects,
                         expected_experiment2_subjects)
        self.assertEqual(self.experiment3.subjects,
                         expected_experiment3_subjects)
        self.assertEqual(self.experiment2.samples,
                         expected_experiment2_samples)
        self.assertEqual(self.experiment3.samples,
                         expected_experiment3_samples)
        self.assertEqual(self.sample3.experiments,
                         expected_sample3_experiments)

    def test_remove_sample_from_subject(self):
        # Attributes that should change
        expected_subject1_samples = {self.sample2}
        expected_experiment1_samples = {self.sample2}
        expected_sample1_subject = None
        expected_sample1_experiments = set()
        expected_experiment3_samples = {self.sample3}
        expected_experiment3_subjects = {self.subject2}
        expected_experiment2_samples = set()
        expected_experiment2_subjects = set()
        # Attributes that should not be affected
        expected_subject1_experiments = self.subject1.experiments
        expected_subject2_experiments = self.subject2.experiments
        expected_experiment1_subjects = self.experiment1.subjects
        expected_sample2_experiments = self.sample2.experiments
        expected_sample3_experiments = self.sample3.experiments
        # Call the function
        self.subject1.remove_sample(self.sample1)
        # Check
        self.assertEqual(self.subject1.samples, expected_subject1_samples)
        self.assertEqual(self.sample1.subject, expected_sample1_subject)
        self.assertEqual(self.subject1.experiments,
                         expected_subject1_experiments)
        self.assertEqual(self.experiment1.subjects,
                         expected_experiment1_subjects)
        self.assertEqual(self.experiment1.samples,
                         expected_experiment1_samples)
        self.assertEqual(self.sample1.experiments,
                         expected_sample1_experiments)
        self.assertEqual(self.sample2.experiments,
                         expected_sample2_experiments)
        self.assertEqual(self.subject2.experiments,
                         expected_subject2_experiments)
        self.assertEqual(self.experiment2.subjects,
                         expected_experiment2_subjects)
        self.assertEqual(self.experiment3.subjects,
                         expected_experiment3_subjects)
        self.assertEqual(self.experiment2.samples,
                         expected_experiment2_samples)
        self.assertEqual(self.experiment3.samples,
                         expected_experiment3_samples)
        self.assertEqual(self.sample3.experiments,
                         expected_sample3_experiments)

    def test_remove_subject_from_sample(self):
        # Attributes that should change
        expected_subject1_samples = {self.sample2}
        expected_experiment1_samples = {self.sample2}
        expected_sample1_subject = None
        expected_sample1_experiments = set()
        expected_experiment3_samples = {self.sample3}
        expected_experiment3_subjects = {self.subject2}
        expected_experiment2_samples = set()
        expected_experiment2_subjects = set()
        # Attributes that should not be affected
        expected_subject1_experiments = self.subject1.experiments
        expected_subject2_experiments = self.subject2.experiments
        expected_experiment1_subjects = self.experiment1.subjects
        expected_sample2_experiments = self.sample2.experiments
        expected_sample3_experiments = self.sample3.experiments
        # Call the function
        del self.sample1.subject  # TODO What about self.sample1.subject = None?
        # Check
        self.assertEqual(self.subject1.samples, expected_subject1_samples)
        self.assertEqual(self.sample1.subject, expected_sample1_subject)
        self.assertEqual(self.subject1.experiments,
                         expected_subject1_experiments)
        self.assertEqual(self.experiment1.subjects,
                         expected_experiment1_subjects)
        self.assertEqual(self.experiment1.samples,
                         expected_experiment1_samples)
        self.assertEqual(self.sample1.experiments,
                         expected_sample1_experiments)
        self.assertEqual(self.sample2.experiments,
                         expected_sample2_experiments)
        self.assertEqual(self.subject2.experiments,
                         expected_subject2_experiments)
        self.assertEqual(self.experiment2.subjects,
                         expected_experiment2_subjects)
        self.assertEqual(self.experiment3.subjects,
                         expected_experiment3_subjects)
        self.assertEqual(self.experiment2.samples,
                         expected_experiment2_samples)
        self.assertEqual(self.experiment3.samples,
                         expected_experiment3_samples)
        self.assertEqual(self.sample3.experiments,
                         expected_sample3_experiments)
Example #29
0
def student_profile_foreign_(username):
    student = Student.get(Student.username == username)
    subjects = Subject.select()
    grades = Grade.select().where(Grade.student == student)
    return render_template('student_profile.html', student=student, subjects=subjects, grades=grades)
Example #30
0
class SampleParserTest(unittest.TestCase):
    sample_test_file = './data/test_data/samp_metadata/sample1.txt'

    row = OrderedDict([
        ('sample_name', '317.F10'), ('age', '22'), ('age_unit', 'years'),
        ('altitude', '0'), ('anatomical_body_site', 'FMA:Palm'),
        ('anonymized_name', 'F10'), ('body_habitat', 'UBERON:skin'),
        ('body_product', 'UBERON:sebum'),
        ('body_site', 'UBERON:zone of skin of hand'),
        ('collection_date', '11/12/2006'),
        ('country', 'GAZ:United States of America'), ('depth', '0'),
        ('description', 'human skin metagenome'), ('dna_extracted', 'true'),
        ('dominant_hand', ''), ('elevation', '1591.99'),
        ('env_biome', 'ENVO:human-associated habitat'),
        ('env_feature', 'ENVO:human-associated habitat'),
        ('host_common_name', 'human'), ('host_subject_id', 'F1'),
        ('host_taxid', '9606'), ('latitude', '40'), ('longitude', '-105'),
        ('palm_size', ''), ('physical_specimen_remaining', 'false'),
        ('public', 'true'), ('qiita_study_id', '317'),
        ('sample_type', 'XXQIITAXX'), ('sex', 'female'),
        ('time_since_last_wash', '0'),
        ('title',
         'The influence of sex handedness and washing on the diversity of hand surface bacteriaS1_V160'
         )
    ])
    dayfirst_dict = {'collection_date': False}

    # TODO Update details of source (when necessary)
    source1 = Source(name='qiita',
                     type_='Database (Public)',
                     url='https://qiita.ucsd.edu/study/description/0')
    experiment1 = Experiment(source=source1, orig_study_id='317')
    subject1 = Subject(
        source=source1,
        orig_study_id='317',
        orig_subject_id='F1',
        sex='female',
        country='United States of America',
        race=None,
        csection=None,
        disease=None,
        dob=None,
    )
    subject2 = Subject(
        source=source1,
        orig_study_id='317',
        orig_subject_id='F2',
        sex='female',
        country='United States of America',
        race=None,
        csection=None,
        disease=None,
        dob=None,
    )
    sampling_site = SamplingSite(
        uberon_habitat_term='UBERON:skin',
        uberon_product_term='UBERON:sebum',
        uberon_site_term='UBERON:zone of skin of hand',
        env_biom_term='ENVO:human-associated habitat',
        env_feature_term='ENVO:human-associated habitat')
    sampling_time = Time(timestamp=datetime.datetime(2006, 11, 12),
                         uncertainty=None,
                         date=datetime.date(2006, 11, 12),
                         time=None,
                         year=2006,
                         month=11,
                         day=12,
                         hour=None,
                         minute=None,
                         second=None,
                         season='autumn')
    sample1 = Sample(source=source1,
                     orig_study_id='317',
                     orig_subject_id='F1',
                     orig_sample_id='317.F10',
                     age_units=ureg.years,
                     age=22.0,
                     latitude=40.0,
                     longitude=-105.0,
                     elevation=1591.99,
                     height_units=ureg.metres,
                     height=None,
                     weight_units=ureg.kilograms,
                     weight=None,
                     bmi=None,
                     sample_date=datetime.date(2006, 11, 12),
                     sample_time=None,
                     sampling_site=sampling_site,
                     sampling_time=sampling_time)
    sample2 = Sample(source=source1,
                     orig_study_id='317',
                     orig_subject_id='F1',
                     orig_sample_id='317.F12',
                     age_units=ureg.years,
                     age=22.0,
                     latitude=40.0,
                     longitude=-105.0,
                     elevation=1591.99,
                     height_units=ureg.metres,
                     height=None,
                     weight_units=ureg.kilograms,
                     weight=None,
                     bmi=None,
                     sample_date=datetime.date(2006, 11, 12),
                     sample_time=None,
                     sampling_site=sampling_site,
                     sampling_time=sampling_time)
    sample3 = Sample(source=source1,
                     orig_study_id='317',
                     orig_subject_id='F2',
                     orig_sample_id='317.F20',
                     age_units=ureg.years,
                     age=None,
                     latitude=40.0,
                     longitude=-105.0,
                     elevation=1591.99,
                     height_units=ureg.metres,
                     height=None,
                     weight_units=ureg.kilograms,
                     weight=None,
                     bmi=None,
                     sample_date=datetime.date(2006, 11, 12),
                     sample_time=None,
                     sampling_site=sampling_site,
                     sampling_time=sampling_time)
    # Not necessary to establish these relationships for purpose of
    # test_parse_objects:
    sample1._subject = subject1
    sample2._subject = subject1
    sample3._subject = subject2
    subject1._samples = {sample1, sample2}
    subject2._samples = {sample3}
    experiment1._subjects = {subject1, subject2}
    experiment1._samples = {sample1, sample2, sample3}

    def test_parse_objects(self):
        experiment_ids = parse_objects(self.sample_test_file)
        self.assertIn('317', experiment_ids)
        experiment = experiment_ids['317']
        self.assertEqual(self.experiment1, experiment)
        self.assertIn(self.subject1, experiment.subjects)
        self.assertIn(self.subject2, experiment.subjects)
        self.assertIn(self.sample1, experiment.samples)
        self.assertIn(self.sample2, experiment.samples)
        self.assertIn(self.sample3, experiment.samples)

    # TODO: We will have to test without the source keyword at some point.
    def test_parse_sample(self):
        self.maxDiff = None
        blacklist_attrs = [
            '_sa_instance_state', 'source', 'counts', '_experiments',
            '_subject', '_preparations'
        ]
        sample = parse_sample(self.row,
                              self.dayfirst_dict,
                              source=self.source1)
        sample_attrs = set((key, value)
                           for key, value in sample.__dict__.items()
                           if key not in blacklist_attrs)
        expected_attrs = set((key, value)
                             for key, value in self.sample1.__dict__.items()
                             if key not in blacklist_attrs)
        self.assertEqual(sample_attrs, expected_attrs)
        self.assertEqual(sample.source, self.source1)
        self.assertEqual(sample.counts, self.sample1.counts)
        # When sample is parsed, it is not yet associated with subject/experiments
        self.assertEqual(sample._subject, None)
        self.assertEqual(sample._experiments, set())
        self.assertEqual(sample._preparations, set())

    def test_parse_subject(self):
        self.maxDiff = None
        blacklist_attrs = [
            '_sa_instance_state', 'source', 'counts', 'perturbation_facts',
            '_experiments', '_samples', '_perturbations'
        ]
        subject = parse_subject(self.row, source=self.source1)
        subject_attrs = set((key, value)
                            for key, value in subject.__dict__.items()
                            if key not in blacklist_attrs)
        expected_attrs = set((key, value)
                             for key, value in self.subject1.__dict__.items()
                             if key not in blacklist_attrs)
        self.assertEqual(subject_attrs, expected_attrs)
        self.assertEqual(subject.source, self.source1)
        self.assertEqual(subject.counts, self.subject1.counts)
        self.assertEqual(subject.perturbation_facts,
                         self.subject1.perturbation_facts)
        # When subject is parsed, it is not yet associated with samples/experiments
        self.assertEqual(subject._experiments, set())
        self.assertEqual(subject._samples, set())
        self.assertEqual(subject._perturbations, set())

    def test_parse_processing(self):
        self.maxDiff = None
        processing1 = Processing(parent=None,
                                 parameter_values='{}',
                                 orig_prep_id='577',
                                 orig_proc_id='2593')
        processing2 = Processing(parent=processing1,
                                 parameter_values='{'
                                 '"barcode_type":"golay_12",'
                                 '"command":"Split libraries (QIIMEq2 1.9.1)",'
                                 '"disable_bc_correction":"False",'
                                 '"disable_primers":"False",'
                                 '"generated on":"2016-01-14 17:01",'
                                 '"input_data":"2593",'
                                 '"max_ambig":"6",'
                                 '"max_barcode_errors":"1.5",'
                                 '"max_homopolymer":"6",'
                                 '"max_primer_mismatch":"0",'
                                 '"max_seq_len":"1000",'
                                 '"min_qual_score":"25",'
                                 '"min_seq_len":"200",'
                                 '"qual_score_window":"0",'
                                 '"reverse_primer_mismatches":"0",'
                                 '"reverse_primers":"disable",'
                                 '"trim_seq_length":"False",'
                                 '"truncate_ambi_bases":"False"'
                                 '}',
                                 orig_prep_id='577',
                                 orig_proc_id='310')
        processing3 = Processing(
            parent=processing2,
            parameter_values='{'
            '"command":"Pick closed-reference OTUs (QIIMEq2 1.9.1)",'
            '"generated on":"2015-06-30 14:06",'
            '"input_data":"310",'
            '"reference-seq":"/databases/gg/13_8/rep_set/97_otus.fasta",'
            '"reference-tax":"/databases/gg/13_8/taxonomy/97_otu_taxonomy.txt",'
            '"similarity":"0.97",'
            '"sortmerna_coverage":"0.97",'
            '"sortmerna_e_value":"1",'
            '"sortmerna_max_pos":"10000",'
            '"threads":"1"'
            '}',
            orig_prep_id='577',
            orig_proc_id='2594')
        expected_processings = {
            '2593': processing1,
            '310': processing2,
            '2594': processing3
        }
        processings = parse_processings('./data/test_data/proc1.json')
        # TODO: Implement workflows and parents as mocks?
        blacklist_attrs = ['_sa_instance_state', 'workflows', 'parent']
        for proc_id, processing in processings.items():
            self.assertIn(proc_id, expected_processings)
            processing_attrs = set(
                (key, value) for key, value in processing.__dict__.items()
                if key not in blacklist_attrs)
            expected_attrs = set(
                (key, value) for key, value in
                expected_processings[proc_id].__dict__.items()
                if key not in blacklist_attrs)
            self.assertEqual(processing_attrs, expected_attrs)
Example #31
0
def choosesub():
    subject = Subject.select()[0]
    return {"subject": subject}
Example #32
0
def sub2(subject_id):
    subject = Subject.get(Subject.id == subject_id)
    questions = Question.filter(Question.subject_code == subject)
    return {"subject": subject, "questions": questions}
Example #33
0
def student_profile_():
    student = get_current_user()
    subjects = Subject.select()
    grades = Grade.select().where(Grade.student == student)
    return render_template('student_profile.html', student=student, subjects=subjects, grades=grades)
Example #34
0
class ModelAddTest(unittest.TestCase):
    def setUp(self):
        self.experiment1 = Experiment()
        self.subject1 = Subject(orig_subject_id=1)
        self.subject2 = Subject(orig_subject_id=2)
        self.sample1 = Sample(orig_sample_id=1)
        self.sample2 = Sample(orig_sample_id=2)
        self.sample3 = Sample(orig_sample_id=3)
        self.sample4 = Sample(orig_sample_id=4)
        # Set up relationships
        self.subject1._samples = {self.sample1, self.sample2}
        self.subject2._samples = {self.sample3}
        self.sample1._subject = self.subject1
        self.sample2._subject = self.subject1
        self.sample3._subject = self.subject2

    def tearDown(self):
        del self.experiment1
        del self.subject1
        del self.subject2
        del self.sample1
        del self.sample2
        del self.sample3
        del self.sample4

    def test_add_subject_to_experiment(self):
        # Attributes that should change
        expected_subject_experiments = {self.experiment1}
        expected_experiment_subjects = {self.subject1}
        expected_experiment_samples = {self.sample1, self.sample2}
        expected_sample_experiments = {self.experiment1}
        # Call the function
        self.experiment1.add_subject(self.subject1)
        # Check
        self.assertEqual(self.subject1.experiments,
                         expected_subject_experiments)
        self.assertEqual(self.subject2.experiments, set())
        self.assertEqual(self.experiment1.subjects,
                         expected_experiment_subjects)
        self.assertEqual(self.experiment1.samples, expected_experiment_samples)
        self.assertEqual(self.sample1.experiments, expected_sample_experiments)
        self.assertEqual(self.sample2.experiments, expected_sample_experiments)

    def test_add_experiment_to_subject(self):
        # Attributes that should change
        expected_subject_experiments = {self.experiment1}
        expected_experiment_subjects = {self.subject1}
        expected_experiment_samples = {self.sample1, self.sample2}
        expected_sample_experiments = {self.experiment1}
        # Call the function
        self.subject1.add_experiment(self.experiment1)
        # Check
        self.assertEqual(self.subject1.experiments,
                         expected_subject_experiments)
        self.assertEqual(self.subject2.experiments, set())
        self.assertEqual(self.experiment1.subjects,
                         expected_experiment_subjects)
        self.assertEqual(self.experiment1.samples, expected_experiment_samples)
        self.assertEqual(self.sample1.experiments, expected_sample_experiments)
        self.assertEqual(self.sample2.experiments, expected_sample_experiments)

    def test_add_sample_to_experiment(self):
        # Attributes that should change
        expected_subject_experiments = {self.experiment1}
        expected_experiment_subjects = {self.subject1}
        expected_experiment_samples = {self.sample1}
        expected_sample_experiments = {self.experiment1}
        # Call the function
        self.experiment1.add_sample(self.sample1)
        # Check
        self.assertEqual(self.subject1.experiments,
                         expected_subject_experiments)
        self.assertEqual(self.subject2.experiments, set())
        self.assertEqual(self.experiment1.subjects,
                         expected_experiment_subjects)
        self.assertEqual(self.experiment1.samples, expected_experiment_samples)
        self.assertEqual(self.sample1.experiments, expected_sample_experiments)
        self.assertEqual(self.sample2.experiments, set())

    def test_add_experiment_to_sample(self):
        # Attributes that should change
        expected_subject_experiments = {self.experiment1}
        expected_experiment_subjects = {self.subject1}
        expected_experiment_samples = {self.sample1}
        expected_sample_experiments = {self.experiment1}
        # Call the function
        self.sample1.add_experiment(self.experiment1)
        # Check
        self.assertEqual(self.subject1.experiments,
                         expected_subject_experiments)
        self.assertEqual(self.subject2.experiments, set())
        self.assertEqual(self.experiment1.subjects,
                         expected_experiment_subjects)
        self.assertEqual(self.experiment1.samples, expected_experiment_samples)
        self.assertEqual(self.sample1.experiments, expected_sample_experiments)
        self.assertEqual(self.sample2.experiments, set())

    # Where the subject is not linked to any experiment
    def test_add_sample_to_subject(self):
        # Attributes that should change
        expected_sample_subject = self.subject1
        expected_subject_samples = {self.sample1, self.sample2, self.sample4}
        # Call the function
        self.subject1.add_sample(self.sample4)
        self.assertEqual(self.subject1.samples, expected_subject_samples)
        self.assertEqual(self.sample4.subject, expected_sample_subject)
        # Attributes that should not be affected
        self.assertEqual(self.subject2.samples, {self.sample3})
        self.assertEqual(self.subject1.experiments, set())
        self.assertEqual(self.subject2.experiments, set())
        self.assertEqual(self.experiment1.subjects, set())
        self.assertEqual(self.experiment1.samples, set())
        self.assertEqual(self.sample1.experiments, set())
        self.assertEqual(self.sample2.experiments, set())
        self.assertEqual(self.sample1.subject, self.subject1)
        self.assertEqual(self.sample3.subject, self.subject2)

    # Where the subject is not linked to any experiment
    def test_add_subject_to_sample(self):
        # Attributes that should change
        expected_sample_subject = self.subject1
        expected_subject_samples = {self.sample1, self.sample2, self.sample4}
        # Call the function (perform assignment)
        self.sample4.subject = self.subject1
        self.assertEqual(self.subject1.samples, expected_subject_samples)
        self.assertEqual(self.sample4.subject, expected_sample_subject)
        # Attributes that should not be affected
        self.assertEqual(self.subject2.samples, {self.sample3})
        self.assertEqual(self.subject1.experiments, set())
        self.assertEqual(self.subject2.experiments, set())
        self.assertEqual(self.experiment1.subjects, set())
        self.assertEqual(self.experiment1.samples, set())
        self.assertEqual(self.sample1.experiments, set())
        self.assertEqual(self.sample2.experiments, set())
        self.assertEqual(self.sample1.subject, self.subject1)
        self.assertEqual(self.sample3.subject, self.subject2)