Esempio n. 1
0
 def insert_curriculum(self):
     print(self.id_courses.get(), self.id_year.get(),
           self.id_semester.get(), self.courses[0], self.courses[1])
     curriculum = Courses(self.id_courses.get(), self.id_year.get(),
                          self.id_semester.get(), int(self.courses[0]),
                          int(self.courses[1]))
     curriculum.insert_courses()
Esempio n. 2
0
def getAllCourses():
    if request.method == 'GET':
        course = Courses(courseCollection)

        courses = course.getAllCourses()

        return courses
Esempio n. 3
0
    def delete(self) -> None:
        '''
    	Deletes the user entered item 

        Calls on the Courses.requestDelete() method to begin the deletion process
        of the entered item.

        Parameters
        ----------
        None

        Returns
        -------
        None
        
        '''
        courseObj = Courses(self.currentAccount)
        if self.option == 'Course':
            courseObj.requestDelete('GradebookCourses', self.option,
                                    self.deleteStatus,
                                    self.deleteName.get().strip())
        elif self.option == 'Student':
            courseObj.requestDelete('GradebookStudents', self.option,
                                    self.deleteStatus, self.courseName,
                                    self.deleteName.get().strip())
        elif self.option == 'Assignment':
            courseObj.requestDelete('GradebookCourses', self.option,
                                    self.deleteStatus, self.courseName,
                                    self.deleteName.get().strip())
        elif self.option == 'Category':
            courseObj.requestDelete('GradebookCourses', self.option,
                                    self.deleteStatus,
                                    self.deleteName.get().strip())
        self.deleteEntry.delete(0, END)
Esempio n. 4
0
    def add(self) -> None:
        '''
    	Attempts to create new items

        Creates a Courses object and attempts create the item entered by the user 
        using the object. Displays the result of the attempt.

        Parameters
        ----------
        None

        Returns
        -------
        None
        '''

        courseObj = Courses(self.currentAccount)
        if self.option == 'Category' or self.option == 'Assignment':
            self.addStatus.config(text=courseObj.createWeighted(
                self.addName.get().strip(),
                self.addWeighting.get().strip(), self.option, self.courseName))
            self.weightingEntry.delete(0, END)
        else:
            self.addStatus.config(text=courseObj.create(
                self.addName.get().strip(), self.courseName, self.option))
        self.addEntry.delete(0, END)
Esempio n. 5
0
    def __init__(self, major=None):
        """
    Creates an empty version of the Student object.
    """

        self.major = major
        self.major_reqs = Courses()
        self.taken_courses = Courses()

        #If the Major is specified, build the self.major_reqs list automatically.
        if (self.major is not None):
            self.defineMajorReqs()
Esempio n. 6
0
  def __init__(self, major=None):
    """
    Creates an empty version of the Student object.
    """

    self.major          = major
    self.major_reqs     = Courses()
    self.taken_courses  = Courses()

    #If the Major is specified, build the self.major_reqs list automatically.
    if(self.major is not None):
      self.defineMajorReqs()
Esempio n. 7
0
def main():
    course = Courses()
    students = Students()
    finish_operation = False
    while not finish_operation:
        print("""
        Welcome To EDUCEMY
        What would you like to do
        
        1. View Courses
        2. Enroll in course
        3. Display all students
        4. Display student information
        5. Update Student Information
        6. Delete Student Information
        7. Complete course for student
        8. Clear Display
        9. Exit Application 
        """)

        main_prompt = input('What would you like to do?')

        if main_prompt == '1':
            course.display_details()
        elif main_prompt == '2':
            students.enroll_student()
        elif main_prompt == '3':
            students.display_all_student_details()
        elif main_prompt == '4':
            students.display_student_information()
        elif main_prompt == '5':
            students.update_student_information()
        elif main_prompt == '6':
            students.delete_student_information()
        elif main_prompt == '7':
            students.complete_course()
        elif main_prompt == '8':
            Functions.clear()
        elif main_prompt == '9':
            sys.exit()
        else:
            print(f"""ERROR:\nInput must be in range 1-7""")
            continue

        finish_prompt = input('Would you like to perform more operations?(y/n)')
        if finish_prompt in ['n', 'N']:
            finish_operation = True
            Functions.clear()
            print("""
            Thank You for Visiting EDUCEMY.
            Have a good day
            """)
Esempio n. 8
0
def addNewCourse():
    if request.method == 'POST':
        course = Courses(courseCollection)

        data = request.get_json()
        courseName = data['courseName']
        courseCode = data['courseCode']

        obj = {'courseName': courseName, 'courseCode': courseCode}
        course.addNewCourse(obj)

        res = jsonify('New course added succesfully')
        return res
Esempio n. 9
0
class Students(LRUCache):

    def __init__(self, *args, **kwargs):
        super(Students, self).__init__(*args, **kwargs)
        self.courses = Courses()

    def insert(self, first_name, last_name, email):
        self._record_count += 1
        student = Student(self._record_count, first_name, last_name, email)
        super(Students, self).insert(student)

    def update(self, id, first_name=None, last_name=None, email=None):
        if first_name == last_name == email is None:
            raise ValueError('No new value was found to update.')
        student = self.retrieve(key=id)
        if first_name is not None:
            student.first_name = first_name
        if last_name is not None:
            student.last_name = last_name
        if email is not None:
            student.email = email
        super(Students, self).update(id, student)

    def enroll_to_course(self, student_id, course_id):
        student = self.retrieve(key=student_id)
        course = self.courses.retrieve(key=course_id)
        log.info("** Enrolling '{0}' to '{1}' **".format(student, course))
        if not student._enrolled_courses.has_key(course_id):
            student._enrolled_courses[course_id] = {'max_marks': course.max_marks, 'obtained_marks': 0}
            super(Students, self).update(student_id, student)

    def disenroll_from_course(self, student_id, course_id):
        student = self.retrieve(key=student_id)
        log.info("** Disenrolling '{0}' from Course id. '{1}' **".format(student, course_id))
        if not student._enrolled_courses.has_key(course_id):
            try:
                del student._enrolled_courses[course_id]
            except:
                pass
        super(Students, self).update(student_id, student)

    def set_marks(self, student_id, course_id, marks):
        student = self.retrieve(key=student_id)
        log.info("** Setting marks for '{0}' in Course id. '{1}' [marks={2}] **".format(student, course_id, marks))
        if student._enrolled_courses.has_key(course_id):
            student._enrolled_courses[course_id]['obtained_marks'] = marks
            super(Students, self).update(student_id, student)
        else:
            raise ValueError("'{0}' is not enrolled to '{1}'.".format(student, self.courses.retrieve(key=course_id)))
Esempio n. 10
0
def main():
    request = requests.get("https://hackbulgaria.com/api/students/")
    api_data = json.loads(request.text)

    students = Students()
    courses = Courses()

    for api_student in api_data:
        student_id = students.insert(api_student["name"],
                                     api_student["github"],
                                     api_student["available"])
        for api_course in api_student["courses"]:
            course_id = courses.insert(api_course["name"])
            students.assign_to_course(student_id, course_id,
                                      api_course["group"])
    def _generate_data(self, data):
        '''Generate data for the generation'''
        solution_fitness_items = []
        solution_items = {}
        solutions = []

        for i in range(0, self.population):
            rooms = Rooms(ROOMS_CSV)
            slots = Slots(rooms)
            courses = Courses(CLASSES_CSV)
            schedule = data[i] if data else Schedule(rooms, slots, courses)

            solutions.append(schedule)
            schedule_fitness = schedule.get_fitness()
            solution_fitness_items.append(schedule_fitness)
            solution_fitness_items.sort()

            if schedule_fitness in solution_items.keys():
                solution_items[schedule_fitness][schedule.id] = schedule
            else:
                solution_items[schedule_fitness] = {}
                solution_items[schedule_fitness][schedule.id] = schedule

        self.elites = self._generate_elite_list(solution_items)
        self.avg_solution_fitness = round(
            sum(solution_fitness_items) / len(solution_fitness_items))
        return solutions
Esempio n. 12
0
def init_courses(courses, config):
    for week in range(7):
        cours = []
        for cur_num in range(config.max_courses_each_day):
            cour = Courses(week, cur_num, config)
            cours.append(cour)
        courses.append(cours)
Esempio n. 13
0
	def test_should_only_find_course_links(self):
		#arrange
		html_code = """
			<a href="domain/mod/assignment/index.php">Assignments</a>
			<a href="domain/course/view.php?id=6704">Course 1</a>
		"""
		html = BeautifulSoup(html_code.encode("utf-8", 'ignore'))
		#System under Test + Act
		courses = Courses(html).all()

		#assert
		self.assertEqual(len(courses), 1)
		course = courses.pop()
		self.assertEqual(course.id, 6704)
		self.assertEqual(course.name, "Course 1")
		self.assertEqual(course.url, "domain/course/view.php?id=6704")
Esempio n. 14
0
    def add_major(self):
        window = Toplevel()
        window.wm_title("Major")

        l1 = Label(window, text="Major ID:")
        l1.grid(row=0, column=0)

        l2 = Label(window, text="Major name:")
        l2.grid(row=1, column=0)

        l3 = Label(window, text="Courses Curriculum:")
        l3.grid(row=2, column=0)

        self.id_major = StringVar()
        e1 = Entry(window, textvariable=self.id_major)
        e1.grid(row=0, column=1)

        self.name_major = StringVar()
        e2 = Entry(window, textvariable=self.name_major)
        e2.grid(row=1, column=1)

        b1 = Button(window, text="insert data", command=self.insert_major)
        b1.grid(row=3, column=0)

        self.variable = StringVar()

        if len(Courses.list_courses()) > 0:
            self.variable.set(Courses.list_courses()[0])  # default value

            courses = []

            # create a list of string to be used in the method below
            for i in Courses.list_courses():
                courses.append(str(*i))

            w = OptionMenu(window, self.variable, *courses)
            print("HEREEEEEEEEEEEE")
            print(self.variable.get())
            w.grid(row=2, column=1)
        else:
            self.variable.set("")
            w = OptionMenu(window, self.variable, "")
            w.grid(row=2, column=1)

        window.geometry("500x200")

        window.mainloop()
Esempio n. 15
0
 def get_offerings(self):
     offerings = self.__db_query(
         'SELECT ID, COURSE, SESSION FROM COURSE_OFFERING WHERE SURVEY_ID IS NULL ORDER BY SESSION, COURSE ASC',
         ())
     data = []
     seen = ''
     #courses = []
     for offering in offerings:
         #courses = ''
         if offering[2] != seen:
             print('seen')
             seen = offering[2]
             courses = Courses(offering[2])
             data.append(courses)
             #data.append(offering[1])
             #courses = []
             #data.append(courses)
         courses.add_course(Course(offering[0], offering[1], offering[2]))
         #courses.append(offering)
     return data
def list_courses():
    for course in Courses():
        ci = course.info
        table_row = [ci['title'], ci['short'], ci['year'], ci['semester'], ci['group'], ci['lang']]
        table.append(table_row)

    current = get_current_semester()
    c_semester = current['semester']
    c_year = current['year']
    print(colored(f'==> Listing all courses from semester {c_semester} of year {c_year}.', 'green'))
    print(tabulate(table, table_headers, tablefmt='fancy_grid'))
Esempio n. 17
0
    def calculate(self) -> list:
        '''
        Calculates the mark on the assignment and gets its weighting

        Calculates the mark of each category on the assignment then uses a weighted average
        to calculate the overall assignment mark. 

        Parameters
        ----------
        None
        
        Returns
        -------
        list
            List including the assignment mark and the weighting of the assignment
        '''
        
        cumulativeWeight = 0
        cumulativeMark = 0
        for x in Courses(self.username).docGet({'course name' : self.courseName},'GradebookCourses')['assignments']:
            if x['assignment name'] == self.assignmentMarks['assignment name']:
                assignmentTotal = x
                break
        weightings ={}
        for x in Courses(self.username).docsGet('GradebookCourses',{'category':{'$exists': True}}):
            weightings[x['category']] = x['weighting']

        for category in assignmentTotal.keys():
            if category != 'assignment name' and category != 'weighting' and category != 'adjusted weighting' and assignmentTotal[category] != 0:
                try:
                    cumulativeMark += weightings[category] * self.assignmentMarks[category]/assignmentTotal[category] *100
                    cumulativeWeight += weightings[category]
                except Exception as e:
                    pass
                    #print(e)
        return ([cumulativeMark/cumulativeWeight, assignmentTotal['weighting']])
Esempio n. 18
0
    def __init__(self, username, courseName, studentName):
        '''
        Constructor to build a Marks object

        Parameters
        ----------
        username : str
            Account username
        courseName : str
            Name of the course
        studentName : str
            Name of the student
        
        Raises
        -------
        KeyError
            If a document in 'GradebookStudents' does not have an 'assignments' key
        KeyError
            If an 'assignment' array item in a document in 'GradebookStudents' does not have an 'adjusted weighintg' key
        '''

        self.username = username
        self.courseName = courseName
        self.studentName = studentName
        self.assignmentList = []
        try:
            studentAssignments = Courses(self.username).docGet(
                {
                    'student name': studentName,
                    'course name': self.courseName
                }, 'GradebookStudents')['assignments']
            for assignment in studentAssignments:
                try:
                    self.assignmentList.append(
                        AssignmentsAdjusted(self.username, self.courseName,
                                            assignment, self.studentName,
                                            assignment['adjusted weighting']))
                except:
                    self.assignmentList.append(
                        Assignments(self.username, self.courseName, assignment,
                                    self.studentName))
        except:
            pass
Esempio n. 19
0
def main():
    courses = Courses()
    students = Students()
    teachers = Teachers()
    while True:
        print("\nMain Menu")
        print(f"{20 * '-'}")
        print("1. Manage Students")
        print("2. Manage Teachers")
        print("3. Manage Course")
        print("4. Exit")
        while True:
            choice = input("Pick one: ")
            if not choice.isdigit():
                print("Give a number please")
                continue
            choice = int(choice)
            if choice < 1 or choice > 4:
                print("Index out of borders")
            else:
                break
        if choice == 1:
            while True:
                print("\nManage Students")
                print(f"{20 * '-'}")
                print("1. Create Student")
                print("2. Add Course to Students")
                print("3. Read Students")
                print("4. Update Students")
                print("5. Delete Students")
                print("6. Back to Main Menu")
                while True:
                    manage_student_choice = input("Pick one: ")
                    if not manage_student_choice.isdigit():
                        print("Give a number please")
                        continue
                    manage_student_choice = int(manage_student_choice)
                    if manage_student_choice < 1 or manage_student_choice > 6:
                        print("Index out of borders")
                    else:
                        break

                if manage_student_choice == 1:  # CREATE STUDENT
                    print("\nINSERT STUDENT")
                    print(f"{20 * '-'}")
                    create_student(students)
                elif manage_student_choice == 2:  # ADD COURSE TO STUDENT
                    print("\nADD COURSE TO STUDENT")
                    print(f"{20 * '-'}")
                    add_course_to_student(students, courses)
                elif manage_student_choice == 3:  # READ STUDENTS
                    while True:
                        print("\nREAD STUDENTS")
                        print(f"{20 * '-'}")
                        print("1. Read a student id")
                        print("2. Read all students")
                        print("3. Back to Students Menu")
                        while True:
                            read_students_choice = input("Pick one: ")
                            if not read_students_choice.isdigit():
                                print("Give a number please")
                                continue
                            read_students_choice = int(read_students_choice)
                            if read_students_choice < 1 or read_students_choice > 3:
                                print("Index out of borders")
                            else:
                                break
                        if read_students_choice == 1:  # READ STUDENT BY ID
                            student_id = input("Give student id: ")
                            student = students.find_by_id(student_id)
                            if student is None:
                                print(f"There is no student with id {student_id}")
                            else:
                                print(student)
                        elif read_students_choice == 2:  # READ ALL STUDENTS
                            for student in students.students:
                                print(student)
                                print(f"{20 * '='}")
                        elif read_students_choice == 3:  # BACK TO STUDENTS MENU
                            break
                elif manage_student_choice == 4:  # UPDATE STUDENTS
                    print("\nUPDATE STUDENTS")
                    print(f"{20 * '-'}")
                    update_student(students)
                elif manage_student_choice == 5:  # DELETE STUDENTS
                    print("\nDELETE STUDENTS")
                    print(f"{20 * '-'}")
                    delete_student(students)
                elif manage_student_choice == 6:  # BACK TO MAIN MENU
                    break

        elif choice == 2:
            while True:
                print("\nManage Teachers")
                print(f"{20 * '-'}")
                print("1. Create Teacher")
                print("2. Add Course to Teacher")
                print("3. Read Teachers")
                print("4. Update Teachers")
                print("5. Delete Teachers")
                print("6. Back to Main Menu")
                while True:
                    manage_teacher_choice = input("Pick one: ")
                    if not manage_teacher_choice.isdigit():
                        print("Give a number please")
                        continue
                    manage_teacher_choice = int(manage_teacher_choice)
                    if manage_teacher_choice < 1 or manage_teacher_choice > 6:
                        print("Index out of borders")
                    else:
                        break
                if manage_teacher_choice == 1:  # CREATE TEACHER
                    print("\nINSERT ΤΕΑCHER")
                    print(f"{20 * '-'}")
                    insert_teacher(teachers)
                elif manage_teacher_choice == 2:  # ADD COURSE TO TEACHER
                    print("\nADD COURSE TO TEACHER")
                    print(f"{20 * '-'}")
                    add_course_to_teacher(teachers, courses)
                elif manage_teacher_choice == 3:  # READ TEACHER
                    while True:
                        print("\nREAD TEACHERS")
                        print(f"{20 * '-'}")
                        print("1. Read a teacher by id")
                        print("2. Read all teachers")
                        print("3. Back to Teachers Menu")
                        while True:
                            read_teachers_choice = input("Pick one: ")
                            if not read_teachers_choice.isdigit():
                                print("Give a number please")
                                continue
                            read_teachers_choice = int(read_teachers_choice)
                            if read_teachers_choice < 1 or read_teachers_choice > 3:
                                print("Index out of borders")
                            else:
                                break
                        if read_teachers_choice == 1:  # READ TEACHER BY ID
                            teacher_id = input("Give teacher id: ")
                            teacher = teachers.find_by_id(teacher_id)
                            if teacher is None:
                                print(f"There is no student with id {teacher_id}")
                            else:
                                print(teacher)
                        elif read_teachers_choice == 2:  # READ ALL TEACHERS
                            for teacher in teachers.teachers:
                                print(teacher)
                                print(f"{20 * '='}")
                        elif read_teachers_choice == 3:  # BACK TO STUDENTS MENU
                            break
                elif manage_teacher_choice == 4:  # UPDATE TEACHER
                    print("\nUPDATE TEACHER")
                    print(f"{20 * '-'}")
                    update_teacher(teachers)
                elif manage_teacher_choice == 5:  # DELETE TEACHER
                    print("\nDELETE TEACHER")
                    print(f"{20 * '-'}")
                    delete_teacher(teachers)
                elif manage_teacher_choice == 6:  # BACK TO MAIN MENU
                    break

        elif choice == 3:
            while True:
                print("\nManage Course")
                print(f"{20 * '-'}")
                print("1. Create Course")
                print("2. Read Courses")
                print("3. Update Course")
                print("4. Delete Course")
                print("5. Back to Main Menu")
                while True:
                    manage_course_choice = input("Pick one: ")
                    if not manage_course_choice.isdigit():
                        print("Give a number please")
                        continue
                    manage_course_choice = int(manage_course_choice)
                    if choice < 1 or choice > 5:
                        print("Index out of borders")
                    else:
                        break
                if manage_course_choice == 1:
                    print("\nCREATE COURSE")
                    print(f"{20 * '-'}")
                    create_course(courses)
                elif manage_course_choice == 2:
                    while True:
                        print("\nREAD COURSES")
                        print(f"{20 * '-'}")
                        print("1. Read a course by id")
                        print("2. Read a course by title")
                        print("3. Read all courses")
                        print("4. Back to Courses Menu")
                        while True:
                            read_courses_choice = input("Pick one: ")
                            if not read_courses_choice.isdigit():
                                print("Give a number please")
                                continue
                            read_courses_choice = int(read_courses_choice)
                            if choice < 1 or choice > 4:
                                print("Index out of borders")
                            else:
                                break

                        if read_courses_choice == 1:  # read course by id
                            course_id = input("Give course id: ")
                            course = courses.find_by_id(course_id)
                            if course is None:
                                print(f"There is no course with id {course_id}")
                            else:
                                print(course)
                        elif read_courses_choice == 2:  # Read course by title
                            course_title = input("Give course title: ")
                            course = courses.find_by_title(course_title)
                            if course is None:
                                print(f"There is no course with title {course_title}")
                            else:
                                print(course)
                        elif read_courses_choice == 3:  # Read all courses
                            print("University Courses")
                            print(f"{20 * '-'}")
                            courses.print_courses()
                        elif read_courses_choice == 4:  # Go back to courses menu
                            break
                elif manage_course_choice == 3:  # UPDATE COURSE
                    print("\nUPDATE COURSE")
                    print(f"{20 * '-'}")
                    update_course(courses)
                elif manage_course_choice == 4:  # DELETE COURSE
                    print("\nDELETE COURSE")
                    print(f"{20 * '-'}")
                    delete_course(courses)
                elif manage_course_choice == 5:
                    break

        elif choice == 4:
            courses.store_to_file()
            teachers.store_to_file()
            students.store_to_file()
            print("Bye bye")
            break
Esempio n. 20
0
class Student(object):
    """
  This is a class object holding information about a Wilkes University
  Student. A Wilkes Student has:
    - major: A two or three letter designation for the program they're
      enrolled in.
    - major_reqs: A list of Course objects (Courses) built from a CSV file
      related to the program they're enrolled in.
    - taken_courses: A list of Course objects (Courses) parsed from a
      cut-and-copy version of their unofficial transcript. 
  """
    def __init__(self, major=None):
        """
    Creates an empty version of the Student object.
    """

        self.major = major
        self.major_reqs = Courses()
        self.taken_courses = Courses()

        #If the Major is specified, build the self.major_reqs list automatically.
        if (self.major is not None):
            self.defineMajorReqs()

    def _returnFile(self, file):
        """
    Private Class method that builds a file path to the CSV that contains
    a major's requirements or throws an error if the specified major doesn't
    have a cooresponding file or throws an error we've reached here without the
    major being specified
    """
        if (self.major is not None):
            if (file is None):
                file = "DATA/required_" + self.major + "_courses.csv"

            if not os.path.isfile(file):
                raise IOError("File " + file + " cannot be opened.")
        else:
            raise ValueError(
                "Either set the student's major or specify a Major Requirements file to use."
            )

        return file

    def defineMajorReqs(self, file=None):
        """
    Opens a specified CVS file and builds a Courses list object of those
    classes.

    Arguments:
      - file (Optional[str]): The filename of the CSV file for the major.
          If not specified and the student's major is set, then file will be
          set automatically.
    """

        # Clear any previous Major information.
        self.major_reqs.clearAllCourses()

        with open((self._returnFile(file))) as csvfile:
            reader = csv.reader(csvfile)
            for line in reader:
                if (not re.search("^#", line[0])):
                    course_obj = Course(line[0], line[1], line[2], line[3],
                                        False, None, line[4], line[5])
                    self.major_reqs.addCourse(course_obj)

    def processMajorReqs(self, file):
        """
    Using the defined major requirments, parses the users transcript and 
    determines if this student has taken or is taking a required major course
    and sets information for that Course object.
    """

        with open(file) as student_file:
            for line in student_file:
                line.strip()
                for course in self.major_reqs.returnCourses():

                    (this_course,
                     course_num) = course.returnCourseId().split("-")

                    if (re.search(this_course + r'\s{1,3}' + course_num,
                                  line)):
                        course.setTaken(True)
                        returned_line = line.split()
                        if (returned_line[-1] == "TR"
                                or returned_line[-1] == "W"
                                or returned_line[-1] == "P"
                                or (FAPlib.is_number(returned_line[-1])
                                    and float(returned_line[-1]) >= 0.0
                                    and float(returned_line[-1]) <= 4.0)):
                            course.setGradeEarned(returned_line[-1])

    def parseTranscript(self, file):
        """
    Parses the student's unofficial transcript and builds a Courses object
    of all the classes in the transcript.
    """

        with open(file) as student_file:
            # Initialize Sentinel - For most classes Credit Hours appear on the
            # next line
            sentinel = 0
            # Initialize Sentinel_2 - Change from classes that are taken
            # to classes that are taking.
            sentinel_2 = False

            for line in student_file:
                line.strip()
                # Skip empty lines.
                if (re.match(r'^\s+$', line)):
                    continue

                # We've got the Credits from the 2nd line, so reset sentinel
                if (sentinel > 1):
                    sentinel = 0

                if (re.search(r'COURSES IN PROGRESS', line)):
                    sentinel_2 = True

                # Only process lines that start with a Course Identifier or
                #   when the sentinel is tripped.
                if (re.search(r'[A-Z]{2,3}\s{1,3}(?:\d{3}|ELE)\s', line)
                        or sentinel > 0):
                    if (sentinel == 0):
                        sl = line.split()

                        # Some lines have a UG indicating Undergraduate
                        #   Why? I don't know, but we need to ignore it.
                        if (sl[2] == "UG"):
                            course_name = " ".join(map(str, sl[3:-1]))
                        else:
                            course_name = " ".join(map(str, sl[2:-1]))

                        if (sentinel_2):
                            course_obj = Course(sl[0] + "-" + sl[1],
                                                " ".join(map(str, sl[3:])), 0,
                                                0, False, 0.0)
                        else:
                            course_obj = Course(sl[0] + "-" + sl[1],
                                                course_name, 0, 0, True,
                                                sl[-1])
                    # We're processing the 2nd line, which could, in fact be a
                    # continuation of the first line. We need special processing for it.
                    elif (sentinel == 1):
                        val = line.split()
                        if len(val) > 1:
                            course_obj.setGradeEarned(val[-1])
                            temp_course_title = course_obj.returnCourseName(
                            ) + " "
                            temp_course_title += " ".join(val[:-1])
                            course_obj.setCourseName(temp_course_title)
                            continue
                        else:
                            course_obj.setCredits(val[-1])

                        self.taken_courses.addCourse(course_obj)
                    sentinel += 1

    def compareMajorToTranscript(self):
        """
    Once the Major's requirements and the transcripts are added into their 
    respected lists, this function checks the Major requirements for
    completion and adds that information to the Major list.
    """

        for course in self.taken_courses.returnCourses():
            for major_req in self.major_reqs.returnCourses():
                if (course.returnCourseId() == major_req.returnCourseId()):
                    major_req.setGradeEarned(course.returnGradeEarned())
                    major_req.setTaken(True)

    """
  Setters
  """

    def setMajor(self, which_major):
        self.major = which_major
        self.defineMajorReqs(None)

    """
  Getters
  """

    def returnMajor(self):
        return self.major

    def returnMajorReqs(self):
        return self.major_reqs.returnCourses()

    def returnCourses(self):
        return self.taken_courses.returnCourses()

    """
  Print functions
  """

    def printMajorReqs(self):
        print("Major Requirements")
        for course_obj in self.major_reqs.returnCourses():
            print("\tCourse ID: " + course_obj.returnCourseId(), end=" ")

            print("\tCourse Name: " + course_obj.returnCourseName())

            print("\tCredits: " + course_obj.returnCredits(), end=" ")
            print("\t\tSemester: " + course_obj.returnSugSemester())

            print("\tClass taken: ", end=" ")
            print(course_obj.returnTaken(), end=" ")
            print("\tGrade earned: ", end=" ")
            print(course_obj.returnGradeEarned())

            # Need to loop through Courses List here.
            #print("Pre Requesites " + course_obj.returnCoursePrereqs())
            #print("Co Requesites " + course_obj.returnCourseCoreqs())
            print()

    def printCourses(self):
        self.taken_courses.printCourses()
Esempio n. 21
0
class Student(object):
  """
  This is a class object holding information about a Wilkes University
  Student. A Wilkes Student has:
    - major: A two or three letter designation for the program they're
      enrolled in.
    - major_reqs: A list of Course objects (Courses) built from a CSV file
      related to the program they're enrolled in.
    - taken_courses: A list of Course objects (Courses) parsed from a
      cut-and-copy version of their unofficial transcript. 
  """

  def __init__(self, major=None):
    """
    Creates an empty version of the Student object.
    """

    self.major          = major
    self.major_reqs     = Courses()
    self.taken_courses  = Courses()

    #If the Major is specified, build the self.major_reqs list automatically.
    if(self.major is not None):
      self.defineMajorReqs()

  def _returnFile(self, file):
    """
    Private Class method that builds a file path to the CSV that contains
    a major's requirements or throws an error if the specified major doesn't
    have a cooresponding file or throws an error we've reached here without the
    major being specified
    """
    if (self.major is not None):
      if (file is None):
        file = "DATA/required_" + self.major + "_courses.csv"

      if not os.path.isfile(file):
        raise IOError("File " + file + " cannot be opened.")
    else:
      raise ValueError("Either set the student's major or specify a Major Requirements file to use.")

    return file
    
  def defineMajorReqs(self, file=None):
    """
    Opens a specified CVS file and builds a Courses list object of those
    classes.

    Arguments:
      - file (Optional[str]): The filename of the CSV file for the major.
          If not specified and the student's major is set, then file will be
          set automatically.
    """

    # Clear any previous Major information.
    self.major_reqs.clearAllCourses()

    with open((self._returnFile(file))) as csvfile:
      reader = csv.reader(csvfile)
      for line in reader:
        if (not re.search("^#", line[0])):
          course_obj = Course(line[0], line[1], line[2], line[3], False, None,
                        line[4], line[5])
          self.major_reqs.addCourse(course_obj)

  def processMajorReqs(self, file):
    """
    Using the defined major requirments, parses the users transcript and 
    determines if this student has taken or is taking a required major course
    and sets information for that Course object.
    """

    with open(file) as student_file:
      for line in student_file:
        line.strip()
        for course in self.major_reqs.returnCourses():

          (this_course, course_num) = course.returnCourseId().split("-")

          if (re.search(this_course + r'\s{1,3}' + course_num, line)):
            course.setTaken(True)
            returned_line = line.split()
            if (returned_line[-1] == "TR" or returned_line[-1] == "W"
                or returned_line[-1] == "P"
             or (FAPlib.is_number(returned_line[-1])
                and float(returned_line[-1]) >= 0.0
                and float(returned_line[-1]) <= 4.0)):
              course.setGradeEarned(returned_line[-1])
  
  def parseTranscript(self, file):
    """
    Parses the student's unofficial transcript and builds a Courses object
    of all the classes in the transcript.
    """

    with open(file) as student_file:
      # Initialize Sentinel - For most classes Credit Hours appear on the
      # next line
      sentinel = 0
      # Initialize Sentinel_2 - Change from classes that are taken
      # to classes that are taking.
      sentinel_2 = False

      for line in student_file:
        line.strip()
        # Skip empty lines.
        if (re.match(r'^\s+$', line)):
          continue

        # We've got the Credits from the 2nd line, so reset sentinel
        if (sentinel > 1):
          sentinel = 0

        if (re.search(r'COURSES IN PROGRESS', line)):
            sentinel_2 = True

        # Only process lines that start with a Course Identifier or 
        #   when the sentinel is tripped.   
        if (re.search(r'[A-Z]{2,3}\s{1,3}(?:\d{3}|ELE)\s', line)
            or sentinel > 0):
          if (sentinel == 0):
            sl = line.split()

            # Some lines have a UG indicating Undergraduate
            #   Why? I don't know, but we need to ignore it.
            if (sl[2] == "UG"):
              course_name = " ".join(map(str, sl[3:-1]))
            else:
              course_name = " ".join(map(str, sl[2:-1]))

            if (sentinel_2):
                course_obj = Course(sl[0] + "-" + sl[1], " ".join(map(str, sl[3:])), 0, 0,
                                      False, 0.0)
            else:
                course_obj = Course(sl[0] + "-" + sl[1], course_name, 0, 0,
                                      True, sl[-1])
          # We're processing the 2nd line, which could, in fact be a
          # continuation of the first line. We need special processing for it.
          elif (sentinel == 1):
            val = line.split()
            if len(val) > 1:
                course_obj.setGradeEarned(val[-1])
                temp_course_title = course_obj.returnCourseName() + " "
                temp_course_title += " ".join(val[:-1])
                course_obj.setCourseName(temp_course_title)
                continue
            else:
                course_obj.setCredits(val[-1])

            self.taken_courses.addCourse(course_obj)
          sentinel += 1

  def compareMajorToTranscript(self):
    """
    Once the Major's requirements and the transcripts are added into their 
    respected lists, this function checks the Major requirements for
    completion and adds that information to the Major list.
    """

    for course in self.taken_courses.returnCourses():
      for major_req in self.major_reqs.returnCourses():
        if (course.returnCourseId() == major_req.returnCourseId()):
          major_req.setGradeEarned(course.returnGradeEarned())
          major_req.setTaken(True)

  """
  Setters
  """

  def setMajor(self, which_major):
    self.major = which_major
    self.defineMajorReqs(None)

  """
  Getters
  """

  def returnMajor(self):
    return self.major

  def returnMajorReqs(self):
    return self.major_reqs.returnCourses()

  def returnCourses(self):
    return self.taken_courses.returnCourses()

  """
  Print functions
  """

  def printMajorReqs(self):
    print("Major Requirements")
    for course_obj in self.major_reqs.returnCourses():
      print("\tCourse ID: " + course_obj.returnCourseId(), end=" ")

      print("\tCourse Name: " + course_obj.returnCourseName())

      print("\tCredits: " + course_obj.returnCredits(), end=" ")
      print("\t\tSemester: " + course_obj.returnSugSemester())

      print("\tClass taken: ", end=" ")
      print(course_obj.returnTaken(), end=" ")
      print("\tGrade earned: ", end=" ")
      print(course_obj.returnGradeEarned())

      # Need to loop through Courses List here.
      #print("Pre Requesites " + course_obj.returnCoursePrereqs())
      #print("Co Requesites " + course_obj.returnCourseCoreqs())
      print()

  def printCourses(self):
    self.taken_courses.printCourses()
Esempio n. 22
0
import sched
import datetime
import time
import pytz
from dateutil.parser import parse

import http.client as httplib

from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

from courses import Courses

courses = Courses()


def authenticate():
    print('Authenticating')
    # If modifying these scopes, delete the file token.pickle.
    SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)

    # If there are no (valid) credentials available, let the user log in.
Esempio n. 23
0
# all enrolled courses
import sys
from courses import Courses
from faculties import Faculties
from news import News
from students import Students
if len(sys.argv) == 1:
    exit(1)

if sys.argv[1] == '-c' or sys.argv[1] == '--courses':
    c = Courses()
    if len(sys.argv) == 2:
        c.show_courses()
    elif len(sys.argv) == 3 and (sys.argv[2] == '-a'
                                 or sys.argv[2] == '-autumn'):
        c.show_courses(in_autumn=True, in_spring=False)
    elif len(sys.argv) == 3 and (sys.argv[2] == '-s'
                                 or sys.argv[2] == '-spring'):
        c.show_courses(in_autumn=False, in_spring=True)
    elif len(sys.argv) == 3:
        c.show_filtered_courses(sys.argv[2])
    elif len(sys.argv) > 3:
        with_details = False
        with_description = False
        with_prereqs = False
        with_textrefs = False
        in_autumn = False
        in_spring = False
        for x in sys.argv[3]:
            if x == 'd':
                with_details = True
#!/usr/bin/python3
from rofi import rofi

from courses import Courses

courses = Courses()
current = courses.current

try:
    current_index = courses.index(current)
    args = ['-a', current_index]
except ValueError:
    args = []

code, index, selected = rofi(
    'Select course', [c.info['title'] for c in courses],
    ['-auto-select', '-no-custom', '-lines',
     len(courses)] + args)

if index >= 0:
    courses.current = courses[index]
Esempio n. 25
0
    def loadCourses(self) -> None:
        '''
    	Displays existing courses as buttons

        Creates a button for every course document found under the current account in the database.
        Each button has a course name as its text and they are displayed in alphanumeric order.

        Parameters
        ----------
        None

        Returns
        -------
        None

        Raises
        -------
        AttributeError
            If the MainScreen object (self) does not have a studentManageBtn or assignmentManageBtn attribute
        KeyError
            If a document in 'GradebookCourses' does not have an 'assignments' key
        '''
        self.clearBottomFrame()
        self.title('Courses')

        try:
            self.studentManageBtn.destroy()
            self.assignmentManageBtn.destroy()
        except Exception as e:
            pass
        courseObj = Courses(self.currentAccount)
        coursesList = courseObj.docsGet('GradebookCourses',
                                        {'course name': {
                                            '$exists': True
                                        }})
        row = 0
        for x in sorted(coursesList, key=lambda y: y['course name'].lower()):
            Button(
                self.bottomFrame,
                text=x['course name'],
                font=('Helvetica', 40),
                command=lambda y=x: self.courseClicked(y['course name'])).grid(
                    row=row, column=0, sticky='EW')
            try:
                Label(self.bottomFrame,
                      text=str(len(x['assignments'])) +
                      '\nAssignment(s)').grid(row=row, column=2, sticky='EW')
            except:
                Label(self.bottomFrame,
                      text='0\nAssignment(s)').grid(row=row,
                                                    column=2,
                                                    sticky='EW')
            studentCount = 0
            Label(self.bottomFrame,
                  text=str(
                      len(
                          courseObj.docsGet(
                              'GradebookStudents',
                              {'course name': x['course name']}))) +
                  '\nStudent(s)').grid(row=row, column=1, sticky='EW')

            row += 1
        self.courseManageBtn.config(
            text='Manage Courses',
            command=lambda: ManageScreen(self, 'Course', self.currentAccount))
Esempio n. 26
0
    def assignmentClicked(self,
                          assignmentName,
                          courseName,
                          assignmentType,
                          studentName='',
                          markObj=None) -> None:
        '''
    	Loads the page of a specific assignment

        Displays and allows for editing of course wide master assignments (which contain the total marks, weightings, etc.) 
        as well as student specific assignment results.

        Parameters
        ----------
        assignmentName : str
            Name of the assignment
        courseName : str
            Name of the course
        assignmentType : str
            Type of assignment clicked
        studentName : str, optional
            Name of the student who the assignment belongs to, if applicable
        markObj : Marks, optional
            Mark object containing the student's saved assignment info

        Returns
        -------
        None

        Raises
        -------
        KeyError
            If document in database does not contain 'assignments' key
        IndexError
            If markObj.assignmentList has a size of 0
        KeyError
            If existingAssignment does not contain a category name as a key
        KeyError
            If existingAssignment does not contain a 'adjusted weighting' as a key
        KeyError
            If existingAssignment does not contain a 'weighting' as a key
        '''
        self.clearBottomFrame()
        self.bottomFrame.grid_columnconfigure(0, weight=1)
        self.title(assignmentName)
        self.studentManageBtn.destroy()
        self.assignmentManageBtn.destroy()
        if assignmentType == 'Course':
            self.courseManageBtn.config(
                text='Return to ' + courseName,
                command=lambda: self.courseClicked(courseName))
            self.categoryManageBtn = Button(
                self.topFrame,
                text='Manage Categories',
                height=1,
                width=14,
                command=lambda: ManageScreen(self, 'Category', self.
                                             currentAccount, courseName,
                                             assignmentName))
            self.categoryManageBtn.grid(column=0, row=0)
            query = {'course name': courseName}
            database = 'GradebookCourses'
            Label(self.bottomFrame, text='Weighting',
                  font=('Helvetica', 20)).grid(column=1, row=0, sticky=EW)
        elif assignmentType == 'Student':
            self.courseManageBtn.config(
                text='Return to ' + studentName,
                command=lambda: self.studentClicked(studentName, courseName))
            query = {'course name': courseName, 'student name': studentName}
            database = 'GradebookStudents'
            Label(self.bottomFrame,
                  text="Student's Marks",
                  font=('Helvetica', 20)).grid(column=1, row=0, sticky=EW)

        row = 0
        Label(self.bottomFrame, text='Category',
              font=('Helvetica', 20)).grid(column=0, row=0, sticky=EW)
        Label(self.bottomFrame, text='Total Marks',
              font=('Helvetica', 20)).grid(column=2, row=0, sticky=EW)
        entries = {'assignment name': assignmentName}
        existingAssignment = {}
        if markObj == None:
            try:
                for x in Courses(self.currentAccount).docGet(
                        query, database)['assignments']:
                    if x['assignment name'] == assignmentName:
                        existingAssignment = x
                        break
            except:
                pass
        else:
            try:
                min = 0
                max = len(markObj.assignmentList)
                while max > min:
                    mid = floor((max + min) / 2)
                    if markObj.assignmentList[mid].assignmentMarks[
                            'assignment name'].lower() < assignmentName.lower(
                            ):
                        min = mid + 1
                    else:
                        max = mid
                if min == max and markObj.assignmentList[min].assignmentMarks[
                        'assignment name'].lower() == assignmentName.lower():
                    existingAssignment = markObj.assignmentList[
                        min].assignmentMarks
            except:
                pass

        if assignmentType == 'Course':
            categories = Courses(self.currentAccount).docsGet(
                'GradebookCourses', {'category': {
                    '$exists': True
                }})
            for x in sorted(categories, key=lambda y: y['category'].lower()):
                #try:
                row += 1
                Label(self.bottomFrame,
                      text=x['category'],
                      font=('Helvetica', 10)).grid(column=0,
                                                   row=row,
                                                   sticky=EW)
                Label(self.bottomFrame,
                      text=str(x['weighting']),
                      font=('Helvetica', 10)).grid(column=1,
                                                   row=row,
                                                   sticky=EW)
                entries[x['category']] = StringVar()
                try:
                    assignmentEntry = Entry(
                        self.bottomFrame, textvariable=entries[x['category']])
                    assignmentEntry.grid(column=2, row=row, sticky=EW)
                    assignmentEntry.insert(0,
                                           existingAssignment[x['category']])
                except:
                    assignmentEntry.insert(0, '0')

                #except:
                #    pass
            row += 1

            Label(self.bottomFrame,
                  text='Total assignment weighting',
                  font=('Helvetica', 10)).grid(column=0, row=row, sticky=EW)
            entries['weighting'] = StringVar()
            assignmentEntry = Entry(self.bottomFrame,
                                    textvariable=entries['weighting'])
            assignmentEntry.grid(column=1, row=row, sticky=EW)
            assignmentEntry.insert(0, existingAssignment['weighting'])

        elif assignmentType == 'Student':

            masterAssignment = {}
            try:
                for x in Courses(self.currentAccount).docGet(
                    {'course name': courseName},
                        'GradebookCourses')['assignments']:
                    if x['assignment name'] == assignmentName:
                        masterAssignment = x
                        break
            except:
                pass
            for x in sorted(list(masterAssignment.keys()),
                            key=lambda y: y.lower()):
                if x != 'assignment name' and x != 'weighting' and masterAssignment[
                        x] != '0' and masterAssignment[x] != 0:
                    row += 1
                    Label(self.bottomFrame, text=x,
                          font=('Helvetica', 10)).grid(column=0,
                                                       row=row,
                                                       sticky=EW)
                    entries[x] = StringVar()
                    try:
                        assignmentEntry = Entry(self.bottomFrame,
                                                textvariable=entries[x])
                        assignmentEntry.grid(column=1, row=row, sticky=EW)
                        assignmentEntry.insert(0, existingAssignment[x])
                    except:
                        assignmentEntry.insert(0, '0.0')
                    Label(self.bottomFrame,
                          text=masterAssignment[x],
                          font=('Helvetica', 10)).grid(column=2,
                                                       row=row,
                                                       sticky=EW)
            row += 1

            Label(self.bottomFrame,
                  text='Effective assignment weighting',
                  font=('Helvetica', 10)).grid(column=0, row=row, sticky=EW)
            entries['adjusted weighting'] = StringVar()
            entries['weighting'] = StringVar()
            try:
                assignmentEntry = Entry(
                    self.bottomFrame,
                    textvariable=entries['adjusted weighting'])
                assignmentEntry.grid(column=1, row=row, sticky=EW)
                assignmentEntry.insert(
                    0, existingAssignment['adjusted weighting'])
            except:
                try:
                    assignmentEntry.insert(0, existingAssignment['weighting'])
                except:
                    assignmentEntry.insert(0, masterAssignment['weighting'])
            row += 1
            Label(self.bottomFrame,
                  text='Default assignment weighting',
                  font=('Helvetica', 10)).grid(column=0, row=row, sticky=EW)
            assignmentEntry = Entry(self.bottomFrame,
                                    textvariable=entries['weighting'])
            assignmentEntry.grid(column=1, row=row, sticky=EW)
            assignmentEntry.insert(0, masterAssignment['weighting'])
            assignmentEntry.config(state=DISABLED)
        self.saveStatus = Label(self.bottomFrame, text='')
        Button(self.bottomFrame,
               text='Save',
               command=lambda: self.
               saveAssignment(assignmentName, courseName, assignmentType,
                              entries, studentName)).grid(column=1, sticky=EW)
        self.saveStatus.grid(column=1, sticky=EW)
Esempio n. 27
0
    def studentClicked(self, studentName, courseName) -> None:
        '''
    	Loads the page of a specific student

        Displays the student's assignments, assignment weightings and marks in the specified course

        Parameters
        ----------
        studentName : str
            Name of the student
        courseName : str
            Name of the course

        Returns
        -------
        ZeroDivisionError
            If there are no assignments with categories (with >0 weighting) assigned more than 0 marks
        KeyError
            If the document in 'GradebookCourses' does not have an 'assignments' key
        ZeroDivisionError
            If there is no instance of the assignment in the student's document (mark of 0 is divided by a weighting of 0)
        IndexError
            If index used on markObj.assignmentMarks is out of range
        KeyError
            If dict in markObj.assignmentList does not have an 'adjusted weighting' key
        '''
        self.clearBottomFrame()
        self.title(studentName)
        self.studentManageBtn.destroy()
        self.assignmentManageBtn.destroy()
        self.courseManageBtn.config(
            text='Return to ' + courseName,
            command=lambda: self.courseClicked(courseName))
        markObj = Marks(self.currentAccount, courseName, studentName)
        markObj.defaultSort()

        Label(self.bottomFrame, text='Default Mark(%)').grid(row=0,
                                                             column=1,
                                                             sticky=EW)
        Label(self.bottomFrame, text='Adjusted Mark(%)').grid(row=0,
                                                              column=2,
                                                              sticky=EW)
        Label(self.bottomFrame, text='Total Mark',
              font=('Helvetica', 40)).grid(row=1, column=0, sticky='EW')
        try:
            Label(self.bottomFrame,
                  text=str(round(markObj.totalMark(), 2)),
                  font=('Helvetica', 40)).grid(row=1, column=1, sticky='EW')
            Label(self.bottomFrame,
                  text=str(round(markObj.totalMarkAdjusted(), 2)),
                  font=('Helvetica', 40)).grid(row=1, column=2, sticky='EW')
        except Exception as e:
            #print (e)
            Label(self.bottomFrame, text='N/A',
                  font=('Helvetica', 40)).grid(row=1, column=1, sticky='EW')
            Label(self.bottomFrame, text='N/A',
                  font=('Helvetica', 40)).grid(row=1, column=2, sticky='EW')
        Label(self.bottomFrame, text='Assignments').grid(row=2,
                                                         column=0,
                                                         sticky=EW)
        Label(self.bottomFrame, text='Effective Weighting').grid(row=2,
                                                                 column=1,
                                                                 sticky=EW)
        Label(self.bottomFrame, text='Mark(%)').grid(row=2,
                                                     column=2,
                                                     sticky=EW)

        row = 3
        minIndex = 0
        try:
            for x in sorted(Courses(self.currentAccount).docGet(
                {'course name': courseName},
                    'GradebookCourses')["assignments"],
                            key=lambda y: y['assignment name'].lower()):
                try:
                    Button(self.bottomFrame,
                           text=x['assignment name'],
                           font=('Helvetica', 40),
                           command=lambda y=x: self.assignmentClicked(
                               y['assignment name'], courseName, 'Student',
                               studentName, markObj)).grid(row=row,
                                                           column=0,
                                                           sticky='EW')
                    if markObj.assignmentList[minIndex].assignmentMarks[
                            'assignment name'] == x['assignment name']:
                        Label(self.bottomFrame,
                              text=str(
                                  round(
                                      markObj.assignmentList[minIndex].
                                      calculate()[0], 2)),
                              font=('Helvetica', 40)).grid(row=row,
                                                           column=2,
                                                           sticky='EW')
                        try:
                            Label(
                                self.bottomFrame,
                                text=str(
                                    round(
                                        markObj.assignmentList[minIndex].
                                        assignmentMarks['adjusted weighting'],
                                        2)),
                                font=('Helvetica', 40)).grid(row=row,
                                                             column=1,
                                                             sticky='EW')
                        except:
                            Label(self.bottomFrame,
                                  text=str(round(x['weighting'], 2)),
                                  font=('Helvetica', 40)).grid(row=row,
                                                               column=1,
                                                               sticky='EW')
                        minIndex += 1
                    else:
                        Label(self.bottomFrame,
                              text='N/A',
                              font=('Helvetica', 40)).grid(row=row,
                                                           column=2,
                                                           sticky='EW')
                        Label(self.bottomFrame,
                              text='0',
                              font=('Helvetica', 40)).grid(row=row,
                                                           column=1,
                                                           sticky='EW')
                except ZeroDivisionError as e:
                    #print(e)
                    Label(self.bottomFrame, text='N/A',
                          font=('Helvetica', 40)).grid(row=row,
                                                       column=2,
                                                       sticky='EW')
                    Label(self.bottomFrame, text='0',
                          font=('Helvetica', 40)).grid(row=row,
                                                       column=1,
                                                       sticky='EW')
                    minIndex += 1
                except IndexError as e:
                    #print(e)
                    Label(self.bottomFrame, text='N/A',
                          font=('Helvetica', 40)).grid(row=row,
                                                       column=2,
                                                       sticky='EW')
                    Label(self.bottomFrame, text='0',
                          font=('Helvetica', 40)).grid(row=row,
                                                       column=1,
                                                       sticky='EW')
                row += 1
        except:
            pass
Esempio n. 28
0
    def courseClicked(self, courseName) -> None:
        '''
    	Loads the page of a specific course

        Displays the students, assignments and assignment weightings in the course

        Parameters
        ----------
        courseName : str
            Name of the course

        Returns
        -------
        None
        
        Raises
        -------
        AttributeError
            If the MainScreen object (self) does not have a categoryManageBtn attribute
        KeyError
            If the document in 'GradebookCourses' does not have an 'assignments' key
        '''

        self.clearBottomFrame()
        try:
            self.categoryManageBtn.destroy()
        except Exception as e:
            pass
        self.title(courseName)
        self.courseManageBtn.config(text='Return to courses',
                                    command=self.loadCourses)
        self.studentManageBtn = Button(
            self.topFrame,
            text='Manage Students ',
            height=1,
            width=14,
            command=lambda: ManageScreen(self, 'Student', self.currentAccount,
                                         courseName))
        self.studentManageBtn.grid(column=0, row=0)
        self.assignmentManageBtn = Button(
            self.topFrame,
            text='Manage Assignments',
            height=1,
            width=14,
            command=lambda: ManageScreen(self, 'Assignment', self.
                                         currentAccount, courseName))
        self.assignmentManageBtn.grid(column=2, row=0)
        studentInfo = Courses(self.currentAccount).docsGet(
            'GradebookStudents', {'course name': courseName})
        assignmentInfo = Courses(self.currentAccount).docGet(
            {'course name': courseName}, 'GradebookCourses')
        Label(self.bottomFrame, text='Students').grid(row=0,
                                                      column=0,
                                                      sticky=EW)
        row = 1
        for x in sorted(studentInfo, key=lambda y: y['student name'].lower()):
            #if x['course name'] == courseName:
            Button(self.bottomFrame,
                   text=x['student name'],
                   font=('Helvetica', 40),
                   command=lambda y=x: self.studentClicked(
                       y['student name'], courseName)).grid(row=row,
                                                            column=0,
                                                            sticky='EW')
            row += 1
        Label(self.bottomFrame, text='Assignments').grid(row=0,
                                                         column=1,
                                                         sticky=EW)
        Label(self.bottomFrame, text='Weightings').grid(row=0,
                                                        column=2,
                                                        sticky=EW)
        row = 1
        try:
            for x in sorted(assignmentInfo['assignments'],
                            key=lambda y: y['assignment name'].lower()):
                Button(self.bottomFrame,
                       text=x['assignment name'],
                       font=('Helvetica', 40),
                       command=lambda y=x: self.assignmentClicked(
                           y['assignment name'], courseName, 'Course')).grid(
                               row=row, column=1, sticky='EW')
                Label(self.bottomFrame,
                      text=x['weighting'],
                      font=('Helvetica', 40)).grid(row=row,
                                                   column=2,
                                                   sticky='EW')
                row += 1
        except:
            pass
Esempio n. 29
0
#!/usr/bin/python3
from courses import Courses
from rofi import rofi

lectures = Courses().current.lectures

commands = ['last', 'prev-last', 'all', 'prev']
options = [
    'Current lecture', 'Last two lectures', 'All lectures', 'Previous lectures'
]

key, index, selected = rofi('Select view', options,
                            ['-lines', 4, '-auto-select'])

if index >= 0:
    command = commands[index]
else:
    command = selected

lecture_range = lectures.parse_range_string(command)
lectures.update_lectures_in_master(lecture_range)
lectures.compile_master()
#!/usr/bin/python3
from courses import Courses
from rofi import rofi
from utils import generate_short_title, MAX_LEN

lectures = Courses().current.lectures

sorted_lectures = sorted(lectures, key=lambda l: -l.number)

options = [
    "{number: >2}. <b>{title: <{fill}}</b> <span size='smaller'>{date}  ({week})</span>".format(
        fill=MAX_LEN,
        number=lecture.number,
        title=generate_short_title(lecture.title),
        date=lecture.date.strftime('%a %d %b'),
        week=lecture.week
    )
    for lecture in sorted_lectures
]

key, index, selected = rofi('Select lecture', options, [
    '-lines', 5,
    '-markup-rows',
    '-kb-row-down', 'Down',
    '-kb-custom-1', 'Ctrl+n'
])

if key == 0:
    sorted_lectures[index].edit()
elif key == 1:
    new_lecture = lectures.new_lecture()
def list_all_courses():
    print('Listing all courses...')
    Courses().read_all_files()
from pathlib import Path
from os import path, mkdir
from shutil import copyfile
from util import printa, copydir

out_dir = path.join(Config().get('root_dir'), 'out')
courses_dir = path.join(out_dir, 'src')
courses_dir_path = Path(courses_dir).expanduser()

compiled_notes_dir = path.join(out_dir, 'lecture-notes')
#source_notes_dir = path.join(out_dir, 'source-notes')

if not path.isdir(courses_dir_path):
    mkdir(courses_dir_path)

for course in Courses():
    ci = course.info
    title, short, group = ci['title'], ci['short'], ci['group']

    print('-------------------------------------------------------------')
    printa(f'Compiling {title} master.tex file...')
    topics = course.topics
    topics.compile_master()

    printa(
        f'Copying \'{title} ({short} {group}).pdf\' to {compiled_notes_dir}/...'
    )
    compiled_master_path = path.join(course.path, 'master.pdf')
    dst_compiled_master_path = path.join(compiled_notes_dir,
                                         f'{title} ({short} {group}).pdf')
    copyfile(
Esempio n. 33
0
 def __init__(self, *args, **kwargs):
     super(Students, self).__init__(*args, **kwargs)
     self.courses = Courses()