def assign(request):
    if not 'id' in request.POST:
        return HttpResponse('{"Error": "No ID supplied."}', content_type='application/json', status=400)
    try:
        subject = Subject.objects.filter(subject_id=request.POST['id']).all()[0]
    except IndexError:
        subject = Subject(subject_id=request.POST['id'], group=assign_task_type())
        subject.save()
    if subject.results.count() >= min(AbstractTask.objects.count(), ConcreteTask.objects.count()):
        return HttpResponse('{"Error": "Tasks already completed. If you came you came to this from the pre-treatment, '
                            'please contact your survey company"}', content_type='application/json')
    if subject.is_abstract_group():
        task = AbstractTask.objects.all()[subject.results.count()]
    else:
        task = ConcreteTask.objects.all()[subject.results.count()]
    return HttpResponse(json.dumps({
        'task_id': task.pk,
        'description': task.description,
        1: {
            'card_id': task.first_card
        },
        2: {
            'card_id': task.second_card
        },
        3: {
            'card_id': task.third_card
        },
        4: {
            'card_id': task.fourth_card
        },
        'story': task.story,
        'task_number': min(AbstractTask.objects.count(), ConcreteTask.objects.count()),
        'progress': subject.results.count()
    }), content_type='application/json')
Exemple #2
0
def update(id):
    form = RegistrationForm()
    id = int(id.encode())
    if form.validate() is False:
        return render_template('blog/edit.html', form=form)
    else:
        post = Post.query.filter_by(id=id).first_or_404()
        post.title = form.title.data
        post.author = form.author.data
        post.text_content = form.text_content.data
        post.postage_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        subjects_names = form.subject.data.replace(', ', ',').split(',')
        num_subjects = len(post.subjects)

        for i in range(0, num_subjects):
            post.subjects.remove(post.subjects[0])

        for name in subjects_names:
            subject = Subject.query.filter_by(name=name).first()
            if (not subject):
                subject = Subject()
                subject.name = name
            post.subjects.append(subject)

        db.session.flush()
        if len(form.thumb.data.split(',')) > 1:
            upload_folder = os.path.join(app.config['UPLOAD_FOLDER'], mod.name, str(post.id), 'images')
            post.thumb = save_b64_image(form.thumb.data.split(',')[1], upload_folder, 'thumb')

        db.session.commit()

        message = u'Post editado com sucesso!'
        flash(message, 'success')
        return redirect(url_for('blog.admin'))
Exemple #3
0
def create():
    form = RegistrationForm()
    if form.validate() is False:
        return render_template('blog/new.html', form=form)
    else:
        post = Post()
        post.title = form.title.data
        post.author = form.author.data
        post.text_content = form.text_content.data
        post.text_call = form.text_call.data
        post.postage_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        post.active = 0

        subjects_names = form.subject.data.replace(', ', ',').split(',')

        for name in subjects_names:
            subject = Subject.query.filter_by(name=name).first()
            if (not subject):
                subject = Subject()
                subject.name = name
            post.subjects.append(subject)
        db.session.add(post)

        db.session.flush()
        if len(form.thumb.data.split(',')) > 1:
            upload_folder = os.path.join(app.config['UPLOAD_FOLDER'], mod.name, str(post.id), 'images')
            post.thumb = save_b64_image(form.thumb.data.split(',')[1], upload_folder, 'thumb')

        db.session.commit()

        message = u'Muito obrigado! Seu post foi submetido com sucesso!'
        flash(message, 'success')
        return redirect(url_for('blog.admin'))
Exemple #4
0
def add_prereq_to_subject(request,subject_id):
    context = {}
    context['user'] = request.user
    this_subject = Subject.objects.get(id=subject_id)
    context['subject'] = this_subject
    if request.method=="POST":
        subject_id = request.POST.get('subject_id','')
        prereq_number = request.POST.get('prereq_number','')
        prereq_name = request.POST.get('prereq_name','')
        prereq_description = request.POST.get('prereq_description','')
        prereq_creator_id = request.POST.get('prereq_creator_id','')
        if prereq_number=='' or prereq_name=='' or prereq_description=='' or prereq_creator_id=='' or subject_id=='':
            to_json = {
                'result': 'failed'
            }
            return HttpResponse(simplejson.dumps(to_json), content_type="application/json")
        else:
            prereq_creator = User.objects.get(id=prereq_creator_id)
            prereq = Subject(number=prereq_number,name=prereq_name,description=prereq_description,creator=prereq_creator)
            prereq.save()
            prereq.instructors.add(prereq_creator)
            this_subject.prerequisites.add(prereq)
            this_subject.save()
            to_json = {
                'result': 'succeeded',
            }
            return HttpResponse(simplejson.dumps(to_json), content_type="application/json")
    else:
        context['subjects'] = Subject.objects.all()
        context['subject_prereqs'] = this_subject.prerequisites.all()
        return render_to_response('add_prereq_to_subject.html', context, RequestContext(request,context))
    def get(self):
        subject = SubjectModel().get_current()
        if subject is None:
            logging.error("Cannot find currect subject")
            self.response.set_status(500)
            return self.response.out.write("Error")

        self.response.out.write(json.dumps({"subject": subject.to_dict(), "user": self.user.to_dict()}))
Exemple #6
0
 def test_optional_field(self):
     testsubject = Subject(name = "testname", description = "testdescription", link = "http://www.google.ro/")
     testsubject.save()
     now = datetime.datetime.utcnow().replace(tzinfo=utc)
     testassignment = Assignment(subject_id = testsubject, name="test", text = "asda", deadline = now)
     testassignment.save()
     testsubject.delete()
     testassignment.delete()
Exemple #7
0
def subject_upload_process_controller():
	file = request.files['file']
	rows = get_row_values(file)
	rows=rows[1:]
	for column in rows:
		new_subject = Subject(
					id=generate_key(),
					name=column[0])
		new_subject.put()
	return render_template('all_done.html')
Exemple #8
0
def initialize_subjects():
    subjects_in_db = Subject.query.all()

    if not subjects_in_db:
        with open('subjects.json', 'r', encoding="utf8") as file:
            subjects = json.loads(file.read())

        for (year, subjects_in_year) in enumerate(subjects, start=1):
            for subject_name in subjects_in_year:
                # print(subject_name)
                s = Subject(subject_name, year)
                s.save()
Exemple #9
0
def addTimetableDB(key, yhm, xnm, xqm):
    class_name = key['kcmc']
    day = key['xqjmc']
    time = key['jc']
    week = key['zcd']
    classroom = key['cdmc']
    teacher = key['xm']
    department = key['xqmc']
    length = re.findall(r"\d+\.?\d*", time)
    l = int(length[1]) - int(length[0]) + 1
    sub = Subject.query.filter(Subject.school_year == xnm).filter(Subject.school_term == xqm).filter(
    Subject.day == day).filter(
        Subject.class_name == class_name).filter(Subject.stu_id == yhm).first()
    if sub:
        sub.time = time
        sub.week = week
        sub.classroom = classroom
        sub.teacher = teacher
        sub.department = department
        sub.length = l
        db.session.commit()
    else:
        sub = Subject(xnm, xqm, class_name, day, time, week,
                      classroom, teacher, department, yhm, l)
        db.session.add(sub)
        db.session.commit()
Exemple #10
0
 def __update(self, option, item):
     option.description = item['description']
     option.link = item['link']
     option.source = item['source']
     for dbsubject in option.subjects:
         for subject in item['subjects']:
             if dbsubject.link == subject['link']:
                 break
         else:
             self._application.db.session.delete(dbsubject)
     for subject in item['subjects']:
         dbsubject = Subject.query \
             .filter(Subject.link == subject['link']) \
             .filter(Subject.option_id == option.id) \
             .first()
         if dbsubject is not None:
             dbsubject.source = subject['source']
             dbsubject.orientation = Orientation[subject['orientation']]
         else:
             dbsubject = Subject(
                 link=subject['link'],
                 source=subject['source'],
                 orientation=Orientation[subject['orientation']],
             )
             option.subjects.append(dbsubject)
Exemple #11
0
def subjectview(request, subject_id=None):
    if subject_id == None:
        subject = Subject()
    else:
        subject = get_object_or_404(Subject, pk=subject_id)
        old_subject_code = subject.subject_code

    if request.method == 'POST':
        form = SubjectForm(request.POST, instance=subject)
        if form.is_valid():
            cleaned_data = form.cleaned_data
            subject_code = cleaned_data['subject_code']
            if subject_id:
                if subject_code == old_subject_code:
                    form = form.save()
                    messages.success(request, 'Subject edited')
                    return redirect(index)
                else:
                    messages.error(request, 'The subject code cannot edited')
            else:
                subjects = Subject.objects.filter(subject_code=subject_code)
                if subjects.count() > 0:
                    messages.error(request, 'Subject already exists')
                else:
                    form = form.save()
                    messages.success(request, 'Subject added')
                    return redirect(index)
        else:
           form = SubjectForm(request.POST, auto_id=True)
    else:
        form = SubjectForm(instance=subject)

    return render(request, 'subjectview.html', {'form' : form})
Exemple #12
0
def flush():
    ndb.delete_multi(School.query().fetch(keys_only=True))
    ndb.delete_multi(QuestionInstance.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Question.query().fetch(keys_only=True))
    ndb.delete_multi(State.query().fetch(keys_only=True))
    ndb.delete_multi(Address.query().fetch(keys_only=True))
    ndb.delete_multi(Teacher.query().fetch(keys_only=True))
    ndb.delete_multi(Class.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(Student.query().fetch(keys_only=True))
    ndb.delete_multi(UserInfo.query().fetch(keys_only=True))
    ndb.delete
    _multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment.query().fetch(keys_only=True))
    ndb.delete_multi(Subject.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Subject_Topics.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Topic.query().fetch(keys_only=True))
    ndb.delete_multi(User.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(State_Types.query().fetch(keys_only=True))
Exemple #13
0
def get_subject_dict():
    user = users.get_current_user()
    subjects = Subject.query().filter(Subject.owner == user.user_id()).fetch()
    sub_dict = {
        "subject_list": subjects
    }
    return sub_dict
Exemple #14
0
def flush():
    ndb.delete_multi(School.query().fetch(keys_only=True))
    ndb.delete_multi(QuestionInstance.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Question.query().fetch(keys_only=True))
    ndb.delete_multi(State.query().fetch(keys_only=True))
    ndb.delete_multi(Address.query().fetch(keys_only=True))
    ndb.delete_multi(Teacher.query().fetch(keys_only=True))
    ndb.delete_multi(Class.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(Student.query().fetch(keys_only=True))
    ndb.delete_multi(UserInfo.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment.query().fetch(keys_only=True))
    ndb.delete_multi(Subject.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Subject_Topics.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Topic.query().fetch(keys_only=True))
    ndb.delete_multi(User.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(State_Types.query().fetch(keys_only=True))
Exemple #15
0
def parser(stu_id, html):
    # 根据HTML网页字符串创建BeautifulSoup
    soup = BeautifulSoup(
        html,  # HTML文档字符串
        'html.parser',  # HTML解析器
    )
    stu = Student.query.filter(Student.id == stu_id).first()
    tables = soup.findAll('table')
    tab = tables[0]
    count = 1
    lists = []
    for tr in tab.findAll('tr'):
        if count != 1:
            td = tr.findAll('td')
            for text in td:
                score = text.getText().strip()
                if score == '':
                    score = None
                lists.append(score)
            # 判断课程是否已存在于Subject表中
            sub_obj = Subject.query.filter(
                Subject.class_name == lists[3]).first()
            # 不存在则新插入该课程
            if sub_obj == None:
                sub = Subject(lists[0], lists[1], lists[2], lists[3], lists[4],
                              lists[6], lists[5], lists[9], lists[12],
                              lists[14], lists[15])
                db.session.add(sub)
                db.session.commit()
            # 判断学生没有拥有该课程
            if sub_obj not in stu.subject:
                sub = Subject.query.filter(
                    Subject.class_name == lists[3]).first()
                stu.subject.append(sub)
                db.session.add(stu)
                sub = Subject.query.filter(
                    Subject.class_name == lists[3]).first()
                score = Score(lists[8], lists[7], sub.id, stu_id, lists[10],
                              lists[11], lists[13])
                db.session.add(score)
                db.session.commit()
            # 如果拥有该课程,则更新数据
            else:
                for cla in stu.subject:
                    if cla == sub_obj:
                        cla.score[0].score = lists[8]
                        cla.score[0].GPA = lists[7]
                        cla.score[0].resit_score = lists[10]
                        cla.score[0].restudy_score = lists[11]
                        cla.score[0].note = lists[13]
                        cla.minor_tab = lists[9]
                        cla.resit_tab = lists[14]
                        db.session.commit()
                        break
            lists = []
        count = count + 1
Exemple #16
0
def create():
    form = AddForm(request.form)

    if form.validate_on_submit():
        subject = Subject(name=form.name.data, day_id=form.day_id.data.id)
        db.session.add(subject)
        db.session.commit()
        return redirect(url_for('subjects.view', id_subject=subject.id))

    return render_template('subjects/create.html', form=form)
def add_subject_to_db():
    subject_list = [
        'Математика', 'Статистика', 'Биология', 'География', 'Садоводство',
        'Спорт', 'Пение'
    ]
    for i in subject_list:
        to_db = Subject(i)
        db.session.add(to_db)

    db.session.commit()
Exemple #18
0
def schedule_add_controller():
    #this is the controller to add new model entries
    students = Student.query().fetch(1000)
    teachers = Teacher.query().fetch(1000)
    subjects = Subject.query().fetch(1000)
    return render_template('schedule_add.html',
                           title="Add New Entry",
                           students=students,
                           teachers=teachers,
                           subjects=subjects)
    def get(self):
        subjects = Subject.all().order('active_from').fetch(50)
        data = {
            'subjects': subjects,
            'today': str((subjects[len(subjects) - 1].active_to + datetime.timedelta(days=1)).date()),
            'today_3': str((subjects[len(subjects) - 1].active_to + datetime.timedelta(days=3)).date())
        }

        self.response.out.write(
            template.render(os.path.join(os.path.dirname(__file__), '../templates/subject.html'), data))
Exemple #20
0
def new_subject():
    form = AddSubjectForm()
    if form.validate_on_submit():
        subject_name = form.name.data
        db.session.add(Subject(subject_name))
        db.session.commit()
        flash('New subject was successfully added.  Thanks.')
    else:
        flash(form.errors)
    return redirect(url_for('questions'))
Exemple #21
0
def create_subject(topic, group, deadline, votetype, options, creator):
    if not get_group(group):
        raise Exception('Group not exist')
    if votetype not in ['0', '1']:
        raise Exception('Vote type error')
    options = [o for o in options if o]
    if not options:
        raise Exception('No options')
    subject = Subject.create(topic, deadline, votetype, group, creator)
    for option in options:
        Vote.create(subject.id, option)
    def __init__(self):
        current_subject = Subject().get_current()
        if current_subject is None:
            logging.error("Cannot find current subject!!!")

        now = datetime.datetime.now()
        if now <= current_subject.active_to:
            return

        # invalidate currect subject
        current_subject.is_current = False

        # new subject to pick
        new_subject = (
            Subject.all().filter("active_from =", datetime.datetime(now.year, now.month, now.day, 0, 0, 0)).get()
        )
        if new_subject is None:
            logging.error("Cannot find next subject!!!")
        new_subject.is_current = True

        s = SaveState().get_by_k("recalc_subject_id")
        if s is not None and s.v != "0":
            logging.error(
                "Cannot start recalculating new subject (%s), because old one (%s) is still active!!!"
                % (new_subject.key().id(), current_subject.key().id())
            )
            return

        # ready to go!
        current_subject.put()
        new_subject.put()

        s = SaveState().get_by_k("recalc_subject_id")
        if s is None:
            s = SaveState()
            s.k = "recalc_subject_id"
            s.v = str(current_subject.key().id())
            s.put()
        else:
            s.v = str(current_subject.key().id())
            s.put()

        s = SaveState().get_by_k("recalc_action")
        if s is None:
            s = SaveState()
            s.k = "recalc_action"
            s.v = "points"
            s.put()
        else:
            s.v = "points"
            s.put()
Exemple #23
0
    def _create_or_add_subject(self, subject_name, parentnode, extras):
        subject = Subject(parentnode=parentnode, short_name=subject_name, long_name=subject_name.capitalize())
        try:
            subject.full_clean()
            subject.save()
        except ValidationError:
            subject = Subject.objects.get(short_name=subject_name)

        # add the extras (only admins allowed in subject)
        for admin in extras['admin']:
            subject.admins.add(self._create_or_add_user(admin))

        # if a long_name is given, set it
        if extras['ln']:
            subject.long_name = extras['ln'][0]

        subject.full_clean()
        subject.save()

        vars(self)[subject.short_name] = subject
        return subject
    def post(self):
        if self.request.get('name'):
            s = Subject()
            s.name = self.request.get('name')
            if len(self.request.get('tags')) == 0 or self.request.get('tags') == '[]':
                s.tags = []
            else:
                s.tags = self.request.get('tags').split(',')
            # active from
            f_y, f_m, f_d = self.request.get('active_from').split('-')
            s.active_from = datetime.datetime(int(f_y), int(f_m), int(f_d), 0, 0, 0)
            # active to
            t_y, t_m, t_d = self.request.get('active_to').split('-')
            s.active_to = datetime.datetime(int(t_y), int(t_m), int(t_d), 23, 59, 59)
            s.is_current = False
            s.put()

        self.redirect('/admin/subject')
    def get(self, username):
        subjects = []

        current_subject = SubjectModel().get_current()
        current_best_photo = (
            Photo.all()
            .filter("user ="******"subject_id =", current_subject.key().id())
            .filter("is_active =", True)
            .filter("is_user_active =", True)
            .filter("is_blocked =", False)
            .order("-total_score")
            .get()
        )
        if current_best_photo:
            current_best_photo = current_best_photo.to_dict()

        subjects.append({"subject": current_subject.to_dict(), "best_photo": current_best_photo, "points": 0})
        for us in UserSubject().get_by_user(username):
            subjects.append(us.to_dict())

        self.response.out.write(json.dumps({"subjects": subjects}))
Exemple #26
0
def add_subject(request):
    context = {}
    context['user'] = request.user
    if request.method=="POST":
        subject_number = request.POST.get('subject_number','')
        subject_name = request.POST.get('subject_name','')
        subject_description = request.POST.get('subject_description','')
        subject_creator_id = request.POST.get('subject_creator_id','')
        if subject_number=='' or subject_name=='' or subject_description=='' or subject_creator_id=='':
            to_json = {
                'result': 'failed'
            }
            return HttpResponse(simplejson.dumps(to_json), content_type="application/json")
        else:
            subject_creator = User.objects.get(id=subject_creator_id)
            subject = Subject(number=subject_number,name=subject_name,description=subject_description,creator=subject_creator)
            subject.save()
            subject.instructors.add(subject_creator)
            to_json = {
                'result': 'succeeded',
                'new_subject_id': subject.id
            }
            return HttpResponse(simplejson.dumps(to_json), content_type="application/json")
    return render_to_response('add_subject.html', context, RequestContext(request,context))
Exemple #27
0
 def __insert(self, item):
     option = Option(
         name=item['name'],
         description=item['description'],
         link=item['link'],
         source=item['source'],
     )
     for subject in item['subjects']:
         subject = Subject(
             link=subject['link'],
             source=subject['source'],
             orientation=Orientation[subject['orientation']],
         )
         option.subjects.append(subject)
     return option
Exemple #28
0
 def post(self):
     user = users.get_current_user()
     if self.request.get("action") == "Add Subject" and self.request.get("subject_string") != '':
         subject_string = self.request.get("subject_string")
         subject = Subject(name=subject_string, owner=user.user_id())
         subject.put()
     else:
         key = self.request.get("subject-id")
         subject_list = Subject.query().filter(Subject.owner == user.user_id()).fetch()
         flag = False
         for subj in subject_list:
             if str(subj.key) == key:
                 selected_subject = subj
                 flag = True
         if flag:
             notes_to_delete = Note.query().filter(Note.subject == selected_subject.name and Note.owner == user.user_id())
             songs_to_delete = Song.query().filter(Song.subject == selected_subject.name and Song.owner == user.user_id())
             for note in notes_to_delete:
                 note.key.delete()
             for song in songs_to_delete:
                 song.key.delete()
             selected_subject.key.delete()
     time.sleep(0.1)
     self.redirect('/')
Exemple #29
0
 def add_subjects(self, subjects, study, create_folders=True):
     import os.path as osp
     import os
     from pluricent.models import Study, Subject
     ds = self.datasource()
     study_id = self.study_id(study)
     studydir = self.session.query(
         Study.directory).filter(Study.id == study_id).one()[0]
     assert (osp.isdir(osp.join(ds, studydir)))
     for s in subjects:
         if create_folders:
             assert (not osp.exists(osp.join(ds, studydir, s)))
             os.mkdir(osp.join(ds, studydir, s))
         new_subject = Subject(identifier=s, study_id=study_id)
         self.session.add(new_subject)
     self.session.commit()
def load_subjects(subjects):
    i = 0
    while i < len(subjects):
        newSubject = None
        existingSubject = db.session.query(Subject).filter(
            Subject.subjectname == subjects[i]['subjects']).first()
        if existingSubject == None:
            newSubject = Subject(subjectname=subjects[i]['subjects'])
            db.session.add(newSubject)
        else:
            newSubject = existingSubject
        book = db.session.query(Book).filter(
            Book.bibnum == int(subjects[i]['bibnum'])).first()
        if book is not None:
            newSubject.books.append(book)
        db.session.commit()
Exemple #31
0
def homePage():
    if request.method == 'GET':
        context = {
            'subjects': Subject.query.all()
        }
        #Article.query.order_by(create_time').all
        return render_template('HomePage.html', **context)
    else:
        subject_name = request.form.get('subject_name')
        subjectExist = Subject.query.filter(Subject.name == subject_name).first()
        if not subjectExist:
            subject = Subject(name=subject_name)
            db.session.add(subject)
            db.session.commit()
            return redirect(url_for('homePage'))
        else:
            return u'The subject already exist You can search it'
Exemple #32
0
    def __init__(self, session, subject=None):
        super().__init__()
        self.session = session
        if subject is None:
            self.subject = Subject()
        else:
            self.subject = subject

        self.timeslot_model = QStandardItemModel(12, 7)
        self.timeslot_model.setHorizontalHeaderLabels([
            "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
            "Sunday"
        ])
        for tp in self.subject.time_places:
            it = QStandardItem()
            it.setText(tp.place.name)
            self.timeslot_model.setItem(tp.slot, int(tp.day), it)
Exemple #33
0
def create_db():
    import os
    if os.path.exists(DB_PATH):
        return

    db.create_all()

    roles = [u'user', u'operator', u'administrator']
    subjects = [u'Programming']
    categories = [
        u'ASP.NET', u'Assembler', u'C', u'C#', u'C++', u'Delphi | Pascal',
        u'Java', u'HTML | CSS | JavaScript', u'Oracle', u'Python', u'QT',
        u'SQL | MySQL | MS SQL | PL/SQL', u'Visual Basic', u'Other'
    ]
    os_list = [u'Windows', u'Unix-like']

    task_statuses = [
        ('New',
         'Client submitted the new task and operator hasn\'t got it yet'),
        ('Discussion', 'Operator discussing details with Client'),
        ('Solving', 'Task went off to solving'),
        ('Pending', 'Payment is going to be delivered soon by PayPal'),
        ('Done', 'User received solution'),
    ]

    for r in roles:
        db.session.add(Role(r))
    db.session.commit()

    for s in subjects:
        db.session.add(Subject(s))
    db.session.commit()

    s = Subject.query.filter_by(name=u'Programming').first()

    for c in categories:
        db.session.add(Category(name=c, subject_id=s.id))

    for o in os_list:
        db.session.add(OS(n=o))

    for ts in task_statuses:
        db.session.add(TaskStatus(*ts))

    db.session.commit()
Exemple #34
0
def new_subject():
    # get subjID
    subjDlg = gui.Dlg(title="Image Viewing Study", pos=(-1.5, 0))
    subjDlg.addField('Subject ID:', 'demo')
    subjDlg.addField('Block Order:', 0)
    subjDlg.addField('Condition:', 0)
    subjDlg.show()

    if gui.OK:
        subject_id = subjDlg.data[0]
        block_order = int(subjDlg.data[1])
        visual_condition = int(subjDlg.data[2])
    else:
        sys.exit()

    subject_id = '%s_%s' % (subject_id,
                            datetime.today().strftime('%Y%m%d_%H%M%S'))

    subject = Subject(subject_id, block_order, visual_condition, BLOCK_LENGTH)

    return subject
Exemple #35
0
    def read(url,type,cod):

        subject = Subject()
        filter_subjects = Filter

        request = requests.get(url)
        soup = BeautifulSoup(request.content, "html.parser")
        list_all_codes = soup.find_all("table", class_="table table-striped table-bordered")

        list_subjects = []

        for tr in soup.find_all('tr'):

            for td in tr.find_all('td'):

                list_subjects.append(td.text)

        for list_td in list_all_codes:

            list = list_td.find_all("tr")
            for list_data in list:

                if list_data.next_element.name == "td":

                    subject.list_cods.append(list_data.next_element.text)

        list_subjects = filter_subjects.blank_space(list_subjects)
        list_subjects = filter_subjects.remove_word_event_note(list_subjects)
        list_subjects = filter_subjects.remove_hours(list_subjects)
        subject.list_codes = filter_subjects.remove_vogals(list_subjects)
        subject.list_names = filter_subjects.remove_cod_of_list_name(subject.list_codes, list_subjects)
        subject.list_names = filter_subjects.remove_accents(subject.list_names)
        subject.list_names = filter_subjects.upper_words(subject.list_names)
        subject.name_departament = type
        subject.cod_departament = cod

        return subject
Exemple #36
0
def subject_controller(id):
	name = request.values.get('name')

	if id:
		subject = Subject.query(Subject.id==id).get()
		if subject:
			if request.method == 'GET':
				if request.values.get('json'):
					return json.dumps(dict(subject=subject.json))
				return render_template('subject_view.html',subject = subject, title = "Subject List")
			elif request.method == 'PUT':
				subject = edit_parser(subject,request)
				subject.put()
				return 'Value Updated', 204
			elif request.method == 'DELETE':
				subject.key.delete()
				return 'Item deleted', 204
			else:
				return 'Method Not Allowed'
	else:
		if request.method == 'GET':
			subject_list = Subject.query().fetch(1000)
			entries=None
			if subject_list:
				entries = [subject.dto() for subject in subject_list]
			if request.values.get('json'):
				return json.dumps(dict(subject=entries))
			return render_template('subject.html',subject_entries = entries, title = "Subject List")
		elif request.method == 'POST':
			subject = Subject()
			subject = new_parser(subject,request)
			subject.put()
			url = '/subject/'
			if request.values.get('json'):
				url = '/subject/json=true'
			return redirect(url)
		else:
			return abort(405)
    def post(self):
        user = users.get_current_user()
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
        upload_files = self.get_uploads('file')  # 'file' is file upload field in the form
        timetable_ett=parse_timetable(upload_files[0])
        if not timetable_ett:
            self.response.out.write("Không đọc được dữ liệu")
            return
        random_key=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(30))
        student=Student.get_or_create_by_user()
        if not student.key:
            student.populate(code=timetable_ett.student_code, 
                         name=timetable_ett.student_name, 
                         student_class=timetable_ett.student_class)
            student.put()
        timetable=TimeTable()
        timetable.populate(random_key=random_key,
                           student=student.key)
        list_subject_class=[]
        for sub in timetable_ett.subjects:
            list_day=[]
            subject=Subject.get_or_create_by_code(sub['code'])
            if not subject.key:
                subject.populate(subject_name=sub['name'])
                subject.put()
            subject_class=SubjectClass()
            subject_class.populate(subject=subject.key,
#                                   timeTable=timetable.key,
                                  theory_class=sub['theory'],
                                  seminar_class=sub['seminar'],
                                  start_date=sub['start'],
                                  end_date=sub['end']
                                  
                                  )
            if sub['day_theories']:
                for d in sub['day_theories']:
                    day=SubjectStudyDay()
                    day.populate(
#                                  subject_class=subject_class.key,
                                 day_name=d['number'],
                                 day_hours="%s-%s" % (d['start'], d['end']),
                                 day_location="%s-%s" % (d['location'], d['room']),
                                 class_type='T')
                    day.put()
                    list_day.append(day.key)
            if sub['day_seminars']:
                for d in sub['day_seminars']:
                    day=SubjectStudyDay()
                    day.populate(
#                                  subject_class=subject_class.key,
                                 day_name=d['number'],
                                 day_hours="%s-%s" % (d['start'], d['end']),
                                 day_location="%s-%s" % (d['location'], d['room']),
                                 class_type='S')
                    day.put()
                    list_day.append(day.key)
            subject_class.subject_study_day=list_day
            subject_class.put()
            list_subject_class.append(subject_class.key)
        timetable.subject_class=list_subject_class
        timetable.put()
        self.response.out.write(random_key);
Exemple #38
0
def acquisition(request):
    record_data = {}
    record = None

    if request.GET.get('isbn'):
        isbn = request.GET.get('isbn')
        if isbnpy.isValid(isbn):
            url = 'http://openlibrary.org/api/volumes/brief/json/isbn:' + isbn
            response = urllib2.urlopen(url)
            # response = urllib2.urlopen('http://127.0.0.1/json/3.json')
            data = json.load(response)
            if isbnpy.isI10(isbn):
                isbn = isbnpy.convert(isbn)
            if data == {}:
                record_data['isbn13'] = isbn
                record_form = RecordForm(instance=record)
                return render(request, 'acquisition.html', {'data': record_data, 'form': record_form})
            data = data.itervalues().next()['records'].itervalues().next()

            try:
                record = Record.objects.get(isbn13=isbn)
                new_record = False
            except Record.DoesNotExist:
                record = Record(isbn13=isbn)
                new_record = True
                # pp(data)
            if record.book_id:
                book = record.book
            else:
                book = Book()

            book.title = data['data']['title']
            if data['details']['details'].has_key('subtitle'):
                book.subtitle = data['details']['details']['subtitle']
            book.save()

            if data['details']['details'].has_key('pagination'):
                record.pagination = data['data']['pagination']
            elif data['details']['details'].has_key('number_of_pages'):
                record.pagination = str(data['data']['number_of_pages']) + ' p.'

            if data['details']['details'].has_key('physical_format'):
                record.format = data['details']['details']['physical_format']
                if record.format.startswith('electronic'):
                    record.format = 'eBook'
                    # record.openlibrary_url = data['data']['url']

            if data['details']['details'].has_key('weight'):
                record.weight = data['details']['details'].get('weight')
            if data['details']['details'].has_key('physical_dimensions'):
                record.dimensions = data['details']['details'].get('physical_dimensions')

            if data['data'].has_key('classifications'):
                if data['data']['classifications'].has_key('dewey_decimal_class'):
                    record.ddc = data['data']['classifications'].get('dewey_decimal_class')[0]
                if data['data']['classifications'].has_key('lc_classifications'):
                    record.lcc = data['data']['classifications'].get('lc_classifications')[0]

            try:
                record.date_of_publication = datetime.strptime(data['data']['publish_date'], '%B %d, %Y').date()
                record.publication_has_month = True
                record.publication_has_day = True
            except ValueError:
                try:
                    record.date_of_publication = datetime.strptime(data['data']['publish_date'], '%Y').date()
                    record.publication_has_month = False
                    record.publication_has_day = False
                except ValueError:
                    try:
                        record.date_of_publication = datetime.strptime(data['data']['publish_date'], '%B %Y').date()
                        record.publication_has_day = False
                        record.publication_has_month = True
                    except ValueError:
                        record.date_of_publication = datetime.strptime(data['data']['publish_date'], '%m/%d/%Y').date()
                        record.publication_has_day = True
                        record.publication_has_month = True

            if data['data'].has_key('identifiers'):
                if data['data']['identifiers'].has_key('openlibrary'):
                    record.openlibrary_id = data['data']['identifiers']['openlibrary'][0]
                if data['data']['identifiers'].has_key('goodreads'):
                    record.goodreads_id = data['data']['identifiers']['goodreads'][0]
                if data['data']['identifiers'].has_key('librarything'):
                    record.librarything_id = data['data']['identifiers']['librarything'][0]
                if data['data']['identifiers'].has_key('oclc'):
                    record.oclc_id = data['data']['identifiers']['oclc'][0]
                if data['data']['identifiers'].has_key('lccn'):
                    record.lccn_id = data['data']['identifiers']['lccn'][0]

            if data['data'].has_key('by_statement'):
                record.by_statement = data['data'].get('by_statement')

            if data['data'].has_key('notes'):
                record.notes = data['data'].get('notes')

            if data['data'].has_key('excerpts'):
                record.excerpt = data['data'].get('excerpts')[0].get('text')

            record.book = book

            setting = LibrarySetting.get()
            record.type = setting.default_type

            if new_record:
                record.date_added = datetime.today()
            record.save()

            if data['details']['details'].has_key('languages'):
                record.languages.clear()
                for lang in data['details']['details']['languages']:
                    lang_key = lang['key'].replace('/languages/', '')
                    try:
                        book_lang = Language.objects.get(code=lang_key)
                    except Language.DoesNotExist:
                        try:
                            book_lang = Language.objects.get(code=lang_key[:-1])
                        except Language.DoesNotExist:
                            raise Exception(
                                "Please add a language with code " + lang_key + " or " + lang_key[:-1] + " first!")
                    record.languages.add(book_lang)

            if data['data'].has_key('publish_places'):
                record.published_places.clear()
                for place in data['data']['publish_places']:
                    try:
                        published_place = Place.objects.get(name=place['name'])
                    except Place.DoesNotExist:
                        published_place = Place(name=place['name'])
                    published_place.save()
                    record.published_places.add(published_place)

            record.authors.clear()
            if data['details']['details'].has_key('authors'):
                for author in data['details']['details']['authors']:
                    author_key = author['key'].replace('/authors/', '')
                    try:
                        book_author = Author.objects.get(identifier=author_key)
                    except Author.DoesNotExist:
                        book_author = Author(identifier=author_key)
                    book_author.name = author['name']
                    book_author.save()
                    record.authors.add(book_author)
            elif data['data'].has_key('authors'):
                for author in data['data']['authors']:
                    author_key = author['url'].replace('http://openlibrary.org/authors/', '')
                    try:
                        book_author = Author.objects.get(identifier=author_key)
                    except Author.DoesNotExist:
                        book_author = Author(identifier=author_key)
                    book_author.name = author['name']
                    book_author.save()
                    record.authors.add(book_author)

            if data['data'].has_key('ebooks'):
                if data['data']['ebooks'][0].has_key('formats'):
                    formats = data['data']['ebooks'][0]['formats']
                    for book_format in formats:
                        ebooks = record.ebooks(book_format)
                        for ebook in ebooks:
                            ebook.delete()
                        if formats[book_format].has_key('url'):
                            url = formats[book_format].get('url')
                            result = urllib.urlretrieve(url)
                            book_file = BookFile(record=record)
                            book_file.file.save(
                                os.path.basename(url),
                                File(open(result[0]))
                            )
                            book_file.save()

            subjects = None
            if data['details']['details'].has_key('subjects'):
                subjects = data['details']['details']['subjects']
            elif data['data'].has_key('subjects'):
                subjects = data['data']['subjects']
            if subjects:
                record.book.subjects.clear()
                for subject in subjects:
                    if type(subject) == dict:
                        subject = title_case(subject['name'])
                    try:
                        book_subject = Subject.objects.get(name=subject)
                    except Subject.DoesNotExist:
                        book_subject = Subject(name=subject)
                    book_subject.save()
                    record.book.subjects.add(book_subject)

            # record.publishers.clear()
            # for publisher in data['details']['details']['publishers']:
            #     try:
            #         book_publisher = Publisher.objects.get(name=publisher['name'])
            #     except Publisher.DoesNotExist:
            #         book_publisher = Publisher(name=publisher['name'])
            #         book_publisher.save()
            #     record.publishers.add(book_publisher)
            try:
                book_publisher = Publisher.objects.get(name=data['details']['details']['publishers'][0])
            except Publisher.DoesNotExist:
                book_publisher = Publisher(name=data['details']['details']['publishers'][0])
                book_publisher.save()
            record.publisher = book_publisher

            if data['data'].has_key('cover'):

                if data['data']['cover'].has_key('large'):
                    cover_url = data['data']['cover']['large']
                    result = urllib.urlretrieve(cover_url)
                    record.large_cover.save(
                        os.path.basename(cover_url),
                        File(open(result[0]))
                    )
                if data['data']['cover'].has_key('medium'):
                    cover_url = data['data']['cover']['medium']
                    result = urllib.urlretrieve(cover_url)
                    record.medium_cover.save(
                        os.path.basename(cover_url),
                        File(open(result[0]))
                    )

                if data['data']['cover'].has_key('small'):
                    cover_url = data['data']['cover']['small']
                    result = urllib.urlretrieve(cover_url)
                    record.small_cover.save(
                        os.path.basename(cover_url),
                        File(open(result[0]))
                    )

            # thumbnail_url = data['details']['thumbnail_url']
            # result = urllib.urlretrieve(thumbnail_url)
            # record.thumbnail.save(
            #     os.path.basename(thumbnail_url),
            #     File(open(result[0]))
            # )

            # import pdb
            #
            # pdb.set_trace()
            record_data = RecordSerializer(record).data

    record_form = RecordForm(instance=record)

    return render(request, 'acquisition.html', {'data': record_data, 'form': record_form})
Exemple #39
0
def create_subject(text: str) -> None:
    session.add(Subject(content=text))
    session.commit()
Exemple #40
0
def subjects_add():
    new_subject = Subject()
    db.session.add(new_subject)
    db.session.commit()
    return jsonify(status="success", id=new_subject.id)
Exemple #41
0
	def get_subject(self):
		from models import Subject
		subject = Subject.query(Subject.id==self.subject_id).get()
		return subject if subject else None
Exemple #42
0
	def save(self):
		subject = Subject(report = self.report , subject = self.cleaned_data['subject'] , grade= self.cleaned_data['grade'])
		subject.save()
Exemple #43
0
def subject_edit_controller(id):
	#this is the controller to edit model entries
	subject_item = Subject.query(Subject.id==id).get()
	return render_template('subject_edit.html', subject_item = subject_item, title = "Edit Entries")
Exemple #44
0
def create_from_path(path):
    """ Create a Node, Subject, Period, Assignment or AssignmentGroup from
    ``path``.

    Examples::

        assignmentgroup = create_from_path(
                'ifi:inf1100.spring05.oblig1.student1,student2')
        oblig1 = create_from_path(
                'ifi:inf1100.spring05.oblig1')
    """
    split = path.split(':', 1)
    nodes = split[0].split('.')
    for nodename in nodes:
        node = Node(short_name=nodename, long_name=nodename.capitalize())
        try:
            node.clean()
            node.save()
        except:
            node = Node.objects.get(short_name=nodename)
        last = node

    if len(split) != 2:
        return last
    pathsplit = split[1].split('.')

    # Subject
    subjectname = pathsplit[0]
    subject = Subject(parentnode=node, short_name=subjectname,
            long_name=subjectname.capitalize())
    try:
        subject.clean()
        subject.save()
    except:
        subject = Subject.objects.get(short_name=subjectname)
    last = subject

    # Period
    if len(pathsplit) > 1:
        periodname = pathsplit[1]
        period = Period(parentnode=subject, short_name=periodname,
                long_name=periodname.capitalize(), start_time=datetime.now(),
                end_time=datetime.now() + timedelta(10))
        try:
            period.clean()
            period.save()
        except:
            period = Period.objects.get(parentnode=subject,
                    short_name=periodname)
        last = period

    # Assignment
    if len(pathsplit) > 2:
        assignmentname = pathsplit[2]
        assignment = Assignment(parentnode=period, short_name=assignmentname,
                long_name=assignmentname.capitalize(), publishing_time=datetime.now())
        
        assignment.clean()
        try:
            assignment.save()
        except:
            assignment = Assignment.objects.get(parentnode=period,
                    short_name=assignmentname)
        last = assignment

    # Candidates
    if len(pathsplit) > 3:
        usernames = pathsplit[3].split(',')
        users = []
        for u in usernames:
            user = User(username=u)
            try:
                user.save()
            except:
                user = User.objects.get(username=u)
            users.append(user)
        assignment_group = AssignmentGroup(parentnode=assignment)
        assignment_group.clean()
        assignment_group.save()
        for user in users:
            assignment_group.candidates.add(Candidate(student=user))
        last = assignment_group
    return last
Exemple #45
0
def schedule_add_controller():
	#this is the controller to add new model entries
	students = Student.query().fetch(1000)
	teachers = Teacher.query().fetch(1000)
	subjects = Subject.query().fetch(1000)
	return render_template('schedule_add.html', title = "Add New Entry", students=students, teachers=teachers, subjects=subjects)
Exemple #46
0
def save_acquisition(request):
    if request.POST.get('book').isnumeric():
        book = Book.objects.get(id=request.POST.get('book'))
        new_book = False
    else:
        book = Book(title=request.POST.get('book'))
        new_book = True
    book.subtitle = request.POST.get('subtitle')
    book.save()

    if request.POST.get('isbn'):
        isbn = request.POST.get('isbn')
        if isbnpy.isValid(isbn):
            if isbnpy.isI10(isbn):
                isbn = isbnpy.convert(isbn)
            try:
                record = Record.objects.get(isbn13=isbn)
                new_record = False
            except Record.DoesNotExist:
                record = Record(isbn13=isbn)
                new_record = True
    else:
        if not new_book:
            try:
                record = Record.objects.get(book=book,
                                            edition=request.POST.get('book'))
                new_record = False
            except Record.DoesNotExist:
                record = Record(book=book)
                new_record = True
        else:
            record = Record(book=book)
            new_record = True

    record.book = book
    record.format = request.POST.get('format')
    if record.format != 'ebook':
        if new_record:
            record.quantity = request.POST.get('quantity')
        else:
            record.quantity += int(request.POST.get('quantity'))

    record.excerpt = request.POST.get('excerpt')
    record.edition = request.POST.get('edition')
    record.notes = request.POST.get('notes')
    record.ddc = request.POST.get('ddc')
    record.lcc = request.POST.get('lcc')
    record.pagination = request.POST.get('pagination')
    record.format = request.POST.get('format')
    record.type = request.POST.get('type')
    if record.format != 'eBook':
        record.quantity = request.POST.get('quantity')

    record.publication_has_month = False
    record.publication_has_day = False
    if request.POST.get('year'):
        dt = datetime(int(request.POST.get('year')), 1, 1)
        if request.POST.get('month'):
            record.publication_has_month = True
            dt = dt.replace(month=int(request.POST.get('month')))
            if request.POST.get('day'):
                record.publication_has_day = True
                dt = dt.replace(day=int(request.POST.get('day')))
        record.date_of_publication = dt
    else:
        record.date_of_publication = None

    if request.FILES.get('small_cover'):
        record.small_cover = request.FILES.get('small_cover')
    if request.FILES.get('medium_cover'):
        record.medium_cover = request.FILES.get('medium_cover')
    if request.FILES.get('large_cover'):
        record.large_cover = request.FILES.get('large_cover')

    if not record.date_added:
        record.date_added = datetime.today()

    record.save()

    if request.FILES.get('ebook'):
        ebooks = request.FILES.getlist('ebook')
        for ebook in ebooks:
            ebook_file = BookFile(record=record, file=ebook)
            existing_files = record.ebooks(ebook_file.format)
            for existing_file in existing_files:
                existing_file.delete()
            ebook_file.save()

    book.subjects.clear()
    for subject in request.POST.getlist('subjects'):
        if subject.isnumeric():
            book.subjects.add(Subject.objects.get(id=subject))
        else:
            new_subject = Subject(name=subject)
            new_subject.save()
            book.subjects.add(new_subject)

    record.authors.clear()
    for author in request.POST.getlist('authors'):
        if author.isnumeric():
            record.authors.add(Author.objects.get(id=author))
        else:
            new_author = Author(name=author)
            new_author.save()
            record.authors.add(new_author)

    record.languages.clear()
    for language in request.POST.getlist('languages'):
        record.languages.add(Language.objects.get(id=language))

    publisher = request.POST.get('publisher')
    if publisher:
        if publisher.isnumeric():
            record.publisher_id = publisher
        else:
            new_publisher = Publisher(name=publisher)
            new_publisher.save()
            record.publisher = new_publisher

    record.save()

    return redirect(reverse_lazy('view_record', kwargs={'pk': record.id}))
Exemple #47
0
def create_from_path(path):
    """ Create a Node, Subject, Period, Assignment or AssignmentGroup from
    ``path``.

    Examples::

        assignmentgroup = create_from_path(
                'ifi:inf1100.spring05.oblig1.student1,student2')
        oblig1 = create_from_path(
                'ifi:inf1100.spring05.oblig1')
    """
    split = path.split(':', 1)
    nodes = split[0].split('.')
    for nodename in nodes:
        node = Node(short_name=nodename, long_name=nodename.capitalize())
        try:
            node.clean()
            node.save()
        except:
            node = Node.objects.get(short_name=nodename)
        last = node

    if len(split) != 2:
        return last
    pathsplit = split[1].split('.')

    # Subject
    subjectname = pathsplit[0]
    subject = Subject(parentnode=node,
                      short_name=subjectname,
                      long_name=subjectname.capitalize())
    try:
        subject.clean()
        subject.save()
    except:
        subject = Subject.objects.get(short_name=subjectname)
    last = subject

    # Period
    if len(pathsplit) > 1:
        periodname = pathsplit[1]
        period = Period(parentnode=subject,
                        short_name=periodname,
                        long_name=periodname.capitalize(),
                        start_time=datetime.now(),
                        end_time=datetime.now() + timedelta(10))
        try:
            period.clean()
            period.save()
        except:
            period = Period.objects.get(parentnode=subject,
                                        short_name=periodname)
        last = period

    # Assignment
    if len(pathsplit) > 2:
        assignmentname = pathsplit[2]
        assignment = Assignment(parentnode=period,
                                short_name=assignmentname,
                                long_name=assignmentname.capitalize(),
                                publishing_time=datetime.now())

        assignment.clean()
        try:
            assignment.save()
        except:
            assignment = Assignment.objects.get(parentnode=period,
                                                short_name=assignmentname)
        last = assignment

    # Candidates
    if len(pathsplit) > 3:
        usernames = pathsplit[3].split(',')
        users = []
        for u in usernames:
            try:
                user = get_user_model().objects.get(shortname=u)
            except get_user_model().DoesNotExist:
                user = get_user_model().objects.create_user(username=u)
            users.append(user)
        assignment_group = AssignmentGroup(parentnode=assignment)
        assignment_group.clean()
        assignment_group.save()
        for user in users:
            assignment_group.candidates.add(Candidate(student=user))
        last = assignment_group
    return last
    def get(self):
        subject = SubjectModel().get_current()

        photos = (
            Photo.all()
            .filter("user ="******"subject_id =", subject.key().id())
            .filter("is_active =", True)
            .order("date_instagram")
        )

        blocked = []
        fetched_ids = []
        ps = {"active": [], "inactive": []}
        for p in photos:
            fetched_ids.append(p.instagram_id)

            if p.is_blocked:
                continue
            if p.is_active and p.is_user_active:
                ps["active"].append(p.to_dict())
            else:
                ps["inactive"].append(p.to_dict())

        # get latest photos from instagram
        url = (
            "https://api.instagram.com/v1/users/%s/media/recent/?access_token=%s&min_timestamp=%s&max_timestamp=%s"
            % (
                self.user.instagram_id,
                self.user.access_token,
                int(time.mktime(subject.active_from.utctimetuple())),
                int(time.mktime(subject.active_to.utctimetuple())),
            )
        )

        f = urlfetch.fetch(url)
        try:
            data = json.loads(f.content)
        except urlfetch.DownloadError:
            return self.response.out.write(json.dumps({"photos": ps}))

        # TODO: pagination

        if not data.has_key("data"):
            logging.error("No data in fetched url: %s" % url)
            return self.response.out.write(json.dumps({"photos": ps}))

        for photo in data["data"]:
            if photo["id"] in fetched_ids:
                continue
            d = datetime.datetime.fromtimestamp(float(photo["created_time"]))
            if d < subject.active_from or d > subject.active_to:
                continue
            # logging.info('%s < %s > %s' % (str(d), str(subject.active_from), str(subject.active_to)))

            p = Photo().to_dict(photo)
            if p["active"] and ["user_active"]:
                Photo().add_or_update(photo)
                ps["active"].append(p)
            else:
                ps["inactive"].append(p)

        self.response.out.write(json.dumps({"photos": ps}))
    def _create_or_add_subject(self, subject_name, parentnode, extras):
        subject = Subject(parentnode=parentnode,
                          short_name=subject_name,
                          long_name=subject_name.capitalize())
        try:
            subject.full_clean()
            subject.save()
        except ValidationError:
            subject = Subject.objects.get(short_name=subject_name)

        # add the extras (only admins allowed in subject)
        for admin in extras['admin']:
            subject.admins.add(self._create_or_add_user(admin))

        # if a long_name is given, set it
        if extras['ln']:
            subject.long_name = extras['ln'][0]

        subject.full_clean()
        subject.save()

        vars(self)[subject.short_name] = subject
        return subject
Exemple #50
0
def save_acquisition(request):
    if request.POST.get('book').isnumeric():
        book = Book.objects.get(id=request.POST.get('book'))
        new_book = False
    else:
        book = Book(title=request.POST.get('book'))
        new_book = True
    book.subtitle = request.POST.get('subtitle')
    book.save()

    if request.POST.get('isbn'):
        isbn = request.POST.get('isbn')
        if isbnpy.isValid(isbn):
            if isbnpy.isI10(isbn):
                isbn = isbnpy.convert(isbn)
            try:
                record = Record.objects.get(isbn13=isbn)
                new_record = False
            except Record.DoesNotExist:
                record = Record(isbn13=isbn)
                new_record = True
    else:
        if not new_book:
            try:
                record = Record.objects.get(book=book, edition=request.POST.get('book'))
                new_record = False
            except Record.DoesNotExist:
                record = Record(book=book)
                new_record = True
        else:
            record = Record(book=book)
            new_record = True

    record.book = book
    record.format = request.POST.get('format')
    if record.format != 'ebook':
        if new_record:
            record.quantity = request.POST.get('quantity')
        else:
            record.quantity += int(request.POST.get('quantity'))

    record.excerpt = request.POST.get('excerpt')
    record.edition = request.POST.get('edition')
    record.notes = request.POST.get('notes')
    record.ddc = request.POST.get('ddc')
    record.lcc = request.POST.get('lcc')
    record.pagination = request.POST.get('pagination')
    record.format = request.POST.get('format')
    record.type = request.POST.get('type')
    if record.format != 'eBook':
        record.quantity = request.POST.get('quantity')

    record.publication_has_month = False
    record.publication_has_day = False
    if request.POST.get('year'):
        dt = datetime(int(request.POST.get('year')), 1, 1)
        if request.POST.get('month'):
            record.publication_has_month = True
            dt = dt.replace(month=int(request.POST.get('month')))
            if request.POST.get('day'):
                record.publication_has_day = True
                dt = dt.replace(day=int(request.POST.get('day')))
        record.date_of_publication = dt
    else:
        record.date_of_publication = None

    if request.FILES.get('small_cover'):
        record.small_cover = request.FILES.get('small_cover')
    if request.FILES.get('medium_cover'):
        record.medium_cover = request.FILES.get('medium_cover')
    if request.FILES.get('large_cover'):
        record.large_cover = request.FILES.get('large_cover')

    if not record.date_added:
        record.date_added = datetime.today()

    record.save()

    if request.FILES.get('ebook'):
        ebooks = request.FILES.getlist('ebook')
        for ebook in ebooks:
            ebook_file = BookFile(record=record, file=ebook)
            existing_files = record.ebooks(ebook_file.format)
            for existing_file in existing_files:
                existing_file.delete()
            ebook_file.save()

    book.subjects.clear()
    for subject in request.POST.getlist('subjects'):
        if subject.isnumeric():
            book.subjects.add(Subject.objects.get(id=subject))
        else:
            new_subject = Subject(name=subject)
            new_subject.save()
            book.subjects.add(new_subject)

    record.authors.clear()
    for author in request.POST.getlist('authors'):
        if author.isnumeric():
            record.authors.add(Author.objects.get(id=author))
        else:
            new_author = Author(name=author)
            new_author.save()
            record.authors.add(new_author)

    record.languages.clear()
    for language in request.POST.getlist('languages'):
        record.languages.add(Language.objects.get(id=language))

    publisher = request.POST.get('publisher')
    if publisher:
        if publisher.isnumeric():
            record.publisher_id = publisher
        else:
            new_publisher = Publisher(name=publisher)
            new_publisher.save()
            record.publisher = new_publisher

    record.save()

    return redirect(reverse_lazy('view_record', kwargs={'pk': record.id}))
from models import Subject

if Subject.get_subject("Математика", 11, "5a") is None:
    math = Subject("subject", "Математика", "", 11, "11", "5a")
    math.save()

if Subject.get_subject("Биология", 1, "5a") is None:
    bio = Subject("subject", "Биология", "", 1, "1", "5a")
    bio.save()

if Subject.get_subject("Химия", 2, "5a") is None:
    bio = Subject("subject", "Химия", "", 2, "2", "5a")
    bio.save()

if Subject.get_subject("Физика", 3, "5a") is None:
    bio = Subject("subject", "Физика", "", 3, "3", "5a")
    bio.save()

if Subject.get_subject("Русский язык", 4, "5a") is None:
    bio = Subject("subject", "Русский язык", "", 4, "4", "5a")
    bio.save()

if Subject.get_subject("Литература", 5, "5a") is None:
    bio = Subject("subject", "Литература", "", 5, "5", "5a")
    bio.save()

if Subject.get_subject("История", 6, "5a") is None:
    bio = Subject("subject", "История", "", 6, "6", "5a")
    bio.save()

if Subject.get_subject("Информатика", 7, "5a") is None:
Exemple #52
0
 def test_if_optional(self):
     subject = Subject(name='Test name for subject')
     subject.save()
     subject.delete()
Exemple #53
0
def acquisition(request):
    record_data = {}
    record = None

    if request.GET.get('isbn'):
        isbn = request.GET.get('isbn')
        if isbnpy.isValid(isbn):
            url = 'http://openlibrary.org/api/volumes/brief/json/isbn:' + isbn
            response = urllib2.urlopen(url)
            # response = urllib2.urlopen('http://127.0.0.1/json/3.json')
            data = json.load(response)
            if isbnpy.isI10(isbn):
                isbn = isbnpy.convert(isbn)
            if data == {}:
                record_data['isbn13'] = isbn
                record_form = RecordForm(instance=record)
                return render(request, 'acquisition.html', {
                    'data': record_data,
                    'form': record_form
                })
            data = data.itervalues().next()['records'].itervalues().next()

            try:
                record = Record.objects.get(isbn13=isbn)
                new_record = False
            except Record.DoesNotExist:
                record = Record(isbn13=isbn)
                new_record = True
                # pp(data)
            if record.book_id:
                book = record.book
            else:
                book = Book()

            book.title = data['data']['title']
            if data['details']['details'].has_key('subtitle'):
                book.subtitle = data['details']['details']['subtitle']
            book.save()

            if data['details']['details'].has_key('pagination'):
                record.pagination = data['data']['pagination']
            elif data['details']['details'].has_key('number_of_pages'):
                record.pagination = str(
                    data['data']['number_of_pages']) + ' p.'

            if data['details']['details'].has_key('physical_format'):
                record.format = data['details']['details']['physical_format']
                if record.format.startswith('electronic'):
                    record.format = 'eBook'
                    # record.openlibrary_url = data['data']['url']

            if data['details']['details'].has_key('weight'):
                record.weight = data['details']['details'].get('weight')
            if data['details']['details'].has_key('physical_dimensions'):
                record.dimensions = data['details']['details'].get(
                    'physical_dimensions')

            if data['data'].has_key('classifications'):
                if data['data']['classifications'].has_key(
                        'dewey_decimal_class'):
                    record.ddc = data['data']['classifications'].get(
                        'dewey_decimal_class')[0]
                if data['data']['classifications'].has_key(
                        'lc_classifications'):
                    record.lcc = data['data']['classifications'].get(
                        'lc_classifications')[0]

            try:
                record.date_of_publication = datetime.strptime(
                    data['data']['publish_date'], '%B %d, %Y').date()
                record.publication_has_month = True
                record.publication_has_day = True
            except ValueError:
                try:
                    record.date_of_publication = datetime.strptime(
                        data['data']['publish_date'], '%Y').date()
                    record.publication_has_month = False
                    record.publication_has_day = False
                except ValueError:
                    try:
                        record.date_of_publication = datetime.strptime(
                            data['data']['publish_date'], '%B %Y').date()
                        record.publication_has_day = False
                        record.publication_has_month = True
                    except ValueError:
                        record.date_of_publication = datetime.strptime(
                            data['data']['publish_date'], '%m/%d/%Y').date()
                        record.publication_has_day = True
                        record.publication_has_month = True

            if data['data'].has_key('identifiers'):
                if data['data']['identifiers'].has_key('openlibrary'):
                    record.openlibrary_id = data['data']['identifiers'][
                        'openlibrary'][0]
                if data['data']['identifiers'].has_key('goodreads'):
                    record.goodreads_id = data['data']['identifiers'][
                        'goodreads'][0]
                if data['data']['identifiers'].has_key('librarything'):
                    record.librarything_id = data['data']['identifiers'][
                        'librarything'][0]
                if data['data']['identifiers'].has_key('oclc'):
                    record.oclc_id = data['data']['identifiers']['oclc'][0]
                if data['data']['identifiers'].has_key('lccn'):
                    record.lccn_id = data['data']['identifiers']['lccn'][0]

            if data['data'].has_key('by_statement'):
                record.by_statement = data['data'].get('by_statement')

            if data['data'].has_key('notes'):
                record.notes = data['data'].get('notes')

            if data['data'].has_key('excerpts'):
                record.excerpt = data['data'].get('excerpts')[0].get('text')

            record.book = book

            setting = LibrarySetting.get()
            record.type = setting.default_type

            if new_record:
                record.date_added = datetime.today()
            record.save()

            if data['details']['details'].has_key('languages'):
                record.languages.clear()
                for lang in data['details']['details']['languages']:
                    lang_key = lang['key'].replace('/languages/', '')
                    try:
                        book_lang = Language.objects.get(code=lang_key)
                    except Language.DoesNotExist:
                        try:
                            book_lang = Language.objects.get(
                                code=lang_key[:-1])
                        except Language.DoesNotExist:
                            raise Exception(
                                "Please add a language with code " + lang_key +
                                " or " + lang_key[:-1] + " first!")
                    record.languages.add(book_lang)

            if data['data'].has_key('publish_places'):
                record.published_places.clear()
                for place in data['data']['publish_places']:
                    try:
                        published_place = Place.objects.get(name=place['name'])
                    except Place.DoesNotExist:
                        published_place = Place(name=place['name'])
                    published_place.save()
                    record.published_places.add(published_place)

            record.authors.clear()
            if data['details']['details'].has_key('authors'):
                for author in data['details']['details']['authors']:
                    author_key = author['key'].replace('/authors/', '')
                    try:
                        book_author = Author.objects.get(identifier=author_key)
                    except Author.DoesNotExist:
                        book_author = Author(identifier=author_key)
                    book_author.name = author['name']
                    book_author.save()
                    record.authors.add(book_author)
            elif data['data'].has_key('authors'):
                for author in data['data']['authors']:
                    author_key = author['url'].replace(
                        'http://openlibrary.org/authors/', '')
                    try:
                        book_author = Author.objects.get(identifier=author_key)
                    except Author.DoesNotExist:
                        book_author = Author(identifier=author_key)
                    book_author.name = author['name']
                    book_author.save()
                    record.authors.add(book_author)

            if data['data'].has_key('ebooks'):
                if data['data']['ebooks'][0].has_key('formats'):
                    formats = data['data']['ebooks'][0]['formats']
                    for book_format in formats:
                        ebooks = record.ebooks(book_format)
                        for ebook in ebooks:
                            ebook.delete()
                        if formats[book_format].has_key('url'):
                            url = formats[book_format].get('url')
                            result = urllib.urlretrieve(url)
                            book_file = BookFile(record=record)
                            book_file.file.save(os.path.basename(url),
                                                File(open(result[0])))
                            book_file.save()

            subjects = None
            if data['details']['details'].has_key('subjects'):
                subjects = data['details']['details']['subjects']
            elif data['data'].has_key('subjects'):
                subjects = data['data']['subjects']
            if subjects:
                record.book.subjects.clear()
                for subject in subjects:
                    if type(subject) == dict:
                        subject = title_case(subject['name'])
                    try:
                        book_subject = Subject.objects.get(name=subject)
                    except Subject.DoesNotExist:
                        book_subject = Subject(name=subject)
                    book_subject.save()
                    record.book.subjects.add(book_subject)

            # record.publishers.clear()
            # for publisher in data['details']['details']['publishers']:
            #     try:
            #         book_publisher = Publisher.objects.get(name=publisher['name'])
            #     except Publisher.DoesNotExist:
            #         book_publisher = Publisher(name=publisher['name'])
            #         book_publisher.save()
            #     record.publishers.add(book_publisher)
            try:
                book_publisher = Publisher.objects.get(
                    name=data['details']['details']['publishers'][0])
            except Publisher.DoesNotExist:
                book_publisher = Publisher(
                    name=data['details']['details']['publishers'][0])
                book_publisher.save()
            record.publisher = book_publisher

            if data['data'].has_key('cover'):

                if data['data']['cover'].has_key('large'):
                    cover_url = data['data']['cover']['large']
                    result = urllib.urlretrieve(cover_url)
                    record.large_cover.save(os.path.basename(cover_url),
                                            File(open(result[0])))
                if data['data']['cover'].has_key('medium'):
                    cover_url = data['data']['cover']['medium']
                    result = urllib.urlretrieve(cover_url)
                    record.medium_cover.save(os.path.basename(cover_url),
                                             File(open(result[0])))

                if data['data']['cover'].has_key('small'):
                    cover_url = data['data']['cover']['small']
                    result = urllib.urlretrieve(cover_url)
                    record.small_cover.save(os.path.basename(cover_url),
                                            File(open(result[0])))

            # thumbnail_url = data['details']['thumbnail_url']
            # result = urllib.urlretrieve(thumbnail_url)
            # record.thumbnail.save(
            #     os.path.basename(thumbnail_url),
            #     File(open(result[0]))
            # )

            # import pdb
            #
            # pdb.set_trace()
            record_data = RecordSerializer(record).data

    record_form = RecordForm(instance=record)

    return render(request, 'acquisition.html', {
        'data': record_data,
        'form': record_form
    })
#     mr_burns,
#     mrs_jelenich,
#     mrs_levy
# ])
# db.session.commit()
''' READ '''
# print(Teacher.query.all())
'''''' '''''' '''''' '''''' '''''' '''''' '''''' '''''' '''''' '''''' '''''' '''''' '''''' ''
# Target first instance of teacher
''' CREATE '''  # Subjects
mrs_brown = Teacher.query.filter_by(teacher_name='Mrs. Brown').all()[0]
mr_burns = Teacher.query.filter_by(teacher_name='Mr. Burns').all()[0]
mrs_jelenich = Teacher.query.filter_by(teacher_name='Mrs. Jelenich').first()
mrs_levy = Teacher.query.filter_by(teacher_name='Mrs. Levy').first()

social_studies = Subject('Social Studies', mrs_brown.id)
literature = Subject('Literature', mr_burns.id)
science = Subject('Science', mrs_jelenich.id)
english = Subject('English', mrs_levy.id)

# db.session.add_all([
#     social_studies,
#     literature,
#     science,
#     english
# ])
# db.session.commit()
''' READ '''
# print(Subject.query.all())
print(
    Teacher.query.filter_by(teacher_name='Mrs. Brown').all()[0],