Ejemplo n.º 1
0
 def testLesson(self):
     les1 = models.Lesson((1,2),"", None, u"Жож",
                        "lec", "412-3", u"Калашников")
     models.Lesson((1,2),"", 2, u"Жож",
                        "lec", "412-3",u"Калашников")
     with self.assertRaises(ValueError):
         models.Lesson((1,"a"),"", 2, u"Жож",
                        "lec", "412-3", u"Калашников")
     with self.assertRaises(ValueError):
         models.Lesson((1,2),"", "a", u"Жож",
                        "lec", "412-3", u"Калашников")
Ejemplo n.º 2
0
async def create_html_lessons(lang='en'):
    for a_dir in os.listdir("./lesson_source/"):
        if a_dir.startswith('.') or a_dir.startswith('_'):
            continue
        path = os.path.abspath('lesson_source/{}'.format(a_dir)) + '/'
        images = path + 'images'
        path += lang
        l_path = path + '.md'
        e_path = path + '.exercises'
        m_path = path + '.meta'
        with open(l_path) as file:
            html = markdown.markdown(file.read(), extensions=['markdown.extensions.codehilite'])
        with open('static/lessons/{}.html'.format(a_dir), 'w') as file:
            file.write(HEADER + html + FOOTER)
        with open(m_path) as file:
            meta = yaml.load(file.read())
        meta['author'] = 1
        lesson = models.Lesson(**meta)
        lid = await lesson.update_or_create(*meta.keys())
        with open(e_path) as file:
            exe = yaml.load(file.read())
        if exe:
            for _, val in exe.items():
                exercise = models.Exercise(lesson=lid, **val)
                await exercise.update_or_create(*val.keys())
        dest = os.path.abspath('static/lessons/images/')
        if os.path.exists(images):
            for file in os.listdir(images):
                src = os.path.join(images, file)
                if os.path.isfile(src):
                    dst = dest + '/' + file
                    shutil.copy(src, dst)
                    print(src + ' copied')
                else:
                    print(src + ' NOT copied')
Ejemplo n.º 3
0
 def testStudyWeek(self):
     les = models.Lesson((1,2),"", None,u"Жож",
                        "lec", "412-3", u"Калашников"
                         )
     day = models.StudyDay([les, les], u"Суббота")
     week = models.StudyWeek([day])
     for day in week:
         for lesson in day:
             self.assertEqual(lesson, les)
Ejemplo n.º 4
0
 def getLesson(self, groupId='', dateValue='', timeValue='', lessonId=''):
     cursor = self.connection.cursor(buffered=True)
     get_query = '''SELECT
                     lessonId,
                     groupId,
                     classroom, 
                     dateValue, 
                     timeValue
                 FROM lessons WHERE (groupId = %s AND dateValue = %s AND timeValue = %s) OR lessonId = %s'''
     cursor.execute(get_query, (groupId, dateValue, timeValue, lessonId))
     result = cursor.fetchone()
     lesson = models.Lesson(lessonId=result[0],
                            groupId=result[1],
                            classroom=result[2],
                            dateValue=result[3],
                            timeValue=result[4])
     cursor.close()
     return lesson
Ejemplo n.º 5
0
    def getLessons(self,
                   groupId,
                   date_start="",
                   date_stop="",
                   limit=20,
                   index=0):
        cursor = self.connection.cursor()
        get_query = ''' SELECT 
                    lessons.lessonId,
                    lessons.groupId,
                    lessons.classroom,
                    lessons.dateValue,
                    lessons.timeValue,
                    subjects.name,
                    DAYOFWEEK(lessons.dateValue)
                    FROM ((groups
                    INNER JOIN lessons ON groups.groupId = lessons.groupId)
                    INNER JOIN subjects ON groups.subjectId = subjects.subjectId)
                    WHERE lessons.groupId = %s AND lessons.dateValue BETWEEN CAST(%s AS DATE) AND CAST(%s AS DATE) 
                    LIMIT %s OFFSET %s'''

        cursor.execute(get_query,
                       (groupId, date_start, date_stop, limit, index))
        lessons = cursor.fetchall()

        if not lessons:
            cursor.close()
            return None
        tab = []
        for lesson in lessons:
            l = models.Lesson(lessonId=lesson[0],
                              groupId=lesson[1],
                              classroom=lesson[2],
                              dateValue=lesson[3],
                              timeValue=lesson[4],
                              subject=lesson[5],
                              dayOfWeek=lesson[6])
            tab.append(l)
        cursor.close()
        return tab
Ejemplo n.º 6
0
def parse(tablestring):
    u'''Распарсить таблицу в объект StudyWeek'''
    root = etree.HTML(tablestring)
    table = root.xpath(".//table")
    if not table:
        return None
    table = table[0]
    days = table.xpath("//tr")
    days = days[1:]
    st_days = []
    for day in days:
        name = day.xpath("td[1]")[0]
        ##        print name.text
        weeks = [week.text for week in day.xpath("td[2]")[0]]
        ##        print weeks
        times = [time.text for time in day.xpath("td[3]")[0]]
        ##        print times
        subgroups = [subgroup.text for subgroup in day.xpath("td[4]")[0]]
        ##        print subgroups
        subjects = [subject.text for subject in day.xpath("td[5]")[0]]
        ##        print subjects
        lesson_types = [
            lessontype.text for lessontype in day.xpath("td[6]")[0]
        ]
        ##        print lessontypes
        places = [place.text for place in day.xpath("td[7]")[0]]
        ##        print places
        lecturers = [lecturer.text for lecturer in day.xpath("td[8]")[0]]
        ##        print lecturers
        lessons = []
        for i in range(len(subjects)):

            les = models.Lesson(weeks[i], times[i], subgroups[i], subjects[i],
                                lesson_types[i], places[i], lecturers[i])
            lessons.append(les)
        st_day = models.StudyDay(lessons, name.text)
        st_days.append(st_day)
    st_week = models.StudyWeek(st_days)
    return st_week
    def post(self, template="admin_lessons_created.html"):
        
        groupId = request.form.get("groupId", "")
        date = request.form.get("firstDay", "")
        quantity = request.form.get("quantity", "")
        classroom = request.form.get("classroom", "")
        timeValue = request.form.get("timeValue", "")
        lessons_list = []
         
        format =  '%Y-%m-%d'
        for i in range(int(quantity)):
            datestr = datetime.strptime(date, format) + timedelta(days=7*i)
            lesson_date = str(datestr.year)+'-'+str(datestr.month)+'-'+str(datestr.day)
            lesson = models.Lesson(groupId = groupId, classroom = classroom, dateValue = lesson_date, timeValue = timeValue)
            try:
                self.db.insertLesson(lesson)
                lessons_list.append(self.db.getLesson(groupId=groupId, dateValue=lesson_date, timeValue=timeValue))
            except Exception as e:
                print(e)
                logging.exception("Connection to database failed")
                return flask.redirect("/")
        
        try:
            matches = self.db.getMatches(groupId)
            for lesson in lessons_list:
                for match in matches:
                    a=models.Attendance(
                                        studentId=match.studentId,
                                        lessonId = lesson.lessonId)
                    self.db.insertAttendance(a)
        except Exception as e:
                print(e)
                logging.exception("Connection to database failed")
                return flask.redirect("/")

        return render_template(template, firstName=session['first_name'], lastName=session['last_name'])
Ejemplo n.º 8
0
 async def process(a_dir, lang=lang):
     less_counter = LessonCounter()
     if a_dir.startswith('.') or a_dir.startswith('_'):
         return
     path = os.path.abspath('../lesson_source/{}'.format(a_dir)) + '/'
     images = path + 'images'
     path += lang
     l_path = path + '.md'
     e_path = path + '.exercises'
     m_path = path + '.meta'
     q_path = path + '.quiz'
     try:  # lesson generation will be deprecated in future
         with open(l_path) as file:
             html = markdown.markdown(file.read(),
                                      extensions=[
                                          'markdown.extensions.codehilite',
                                          'markdown.extensions.tables'
                                      ])
     except FileNotFoundError:
         return
     with open(m_path) as file:
         meta = yaml.load(file.read())
     meta['author'] = DEFAULT_USER
     meta['file'] = '{}.html'.format(a_dir)
     meta['lesson_no'] = int(a_dir)
     try:
         with open(q_path) as file:
             questions = yaml.load(file.read())
         less_counter.quiz_outcome = 'found'
     except Exception as err:
         questions = False
         less_counter.quiz_outcome = 'none'
     if questions:
         quiz = models.Quiz(title=meta['title'],
                            users=DEFAULT_USER,
                            description=meta['description'])
         quiz_id = await quiz.update_or_create('title')
         meta['quiz'] = quiz_id
         question_order = 1
         for _, val in questions.items():
             try:
                 question = models.Question(**val)
                 qid = await question.update_or_create(*val.keys())
                 qq = models.QuizQuestions(quiz=quiz_id,
                                           question=qid,
                                           question_order=question_order)
                 question_order += 1
                 await qq.update_or_create('question', 'quiz')
                 less_counter.quiz_details_done += 1
             except Exception as err:
                 print(err)
                 less_counter.quiz_details_error += 1
     try:
         lesson = models.Lesson(**meta)
         lid, updated = await lesson.update_or_create('lesson_no',
                                                      verbose=True)
         less_counter.lesson_outcome = 'found'
         if updated:
             less_counter.lesson_outcome = 'updated'
             counter.updated_lessons += 1
         else:
             less_counter.lesson_outcome = 'created'
             counter.added_lessons += 1
     except Exception as err:
         print(err)
         less_counter.lesson_outcome += 'error'
         counter.error_lessons += 1
     try:
         with open(e_path) as file:
             exe = yaml.load(file)
             less_counter.exercise_outcome = 'found'
     except Exception as err:
         exe = False
         less_counter.exercise_outcome = 'not found'
         print(err)
     if exe:
         try:
             for val in exe.values():
                 exercise = models.Exercise(lesson=lid, **val)
                 id, updated = await exercise.update_or_create('title',
                                                               verbose=True)
                 if updated:
                     less_counter.exercise_details_updated += 1
                 else:
                     less_counter.exercise_details_created += 1
         except Exception as err:
             print('error creating exercise')
             less_counter.exercise_details_error += 1
             print(exe)
             print(err)
     dest = os.path.abspath('static/images/')
     if os.path.exists(images):
         for file in os.listdir(images):
             src = os.path.join(images, file)
             if os.path.isfile(src):
                 dst = dest + '/' + file
                 shutil.copy(src, dst)
                 less_counter.lesson_imgs_done += 1
             else:
                 less_counter.lesson_imgs_errors += 1
     return less_counter
Ejemplo n.º 9
0
 async def process(a_dir, lang=lang):
     if a_dir.startswith('.') or a_dir.startswith('_'):
         return
     path = os.path.abspath('lesson_source/{}'.format(a_dir)) + '/'
     images = path + 'images'
     path += lang
     l_path = path + '.md'
     e_path = path + '.exercises'
     m_path = path + '.meta'
     q_path = path + '.quiz'
     try:
         with open(l_path) as file:
             html = markdown.markdown(
                 file.read(), extensions=['markdown.extensions.codehilite'])
     except FileNotFoundError:
         return
     with open('static/lessons/{}.html'.format(a_dir), 'w') as file:
         file.write(HEADER + html + FOOTER)
     with open(m_path) as file:
         meta = yaml.load(file.read())
     meta['author'] = 1
     meta['file'] = '{}.html'.format(a_dir)
     try:
         with open(q_path) as file:
             questions = yaml.load(file.read())
         print('found quiz')
     except Exception as err:
         questions = False
         print(err)
     if questions:
         quiz = models.Quiz(title=meta['title'],
                            users=14,
                            description=meta['description'])
         quiz_id = await quiz.update_or_create('title')
         meta['quiz'] = quiz_id
         question_order = 1
         for _, val in questions.items():
             qustion = models.Question(**val)
             qid = await qustion.update_or_create(*val.keys())
             qq = models.QuizQuestions(quiz=quiz_id,
                                       question=qid,
                                       question_order=question_order)
             question_order += 1
             await qq.update_or_create('question', 'quiz')
             print('question created')
     lesson = models.Lesson(**meta)
     lid = await lesson.update_or_create(*meta.keys())
     try:
         with open(e_path) as file:
             exe = yaml.load(file.read())
     except:
         exe = False
     if exe:
         try:
             for _, val in exe.items():
                 exercise = models.Exercise(lesson=lid, **val)
                 await exercise.update_or_create(*val.keys())
         except Exception as err:
             print('error creating exercise')
             print(exe)
             print(val)
             print(err)
     dest = os.path.abspath('static/images/')
     if os.path.exists(images):
         for file in os.listdir(images):
             src = os.path.join(images, file)
             if os.path.isfile(src):
                 dst = dest + '/' + file
                 shutil.copy(src, dst)
                 print(src + ' copied')
             else:
                 print(src + ' NOT copied')
Ejemplo n.º 10
0
 def testLessonWeekStr(self):
     les1 = models.Lesson("1,3,4","", None, u"Жож",
                        "lec", "412-3", u"Калашников")
     self.assertEqual(unicode(les1), u"1,3,4    Жож lec 412-3 Калашников" )