def get_course_class_list(self): from algorithm.models import School, Department, Class, Prerequisite, Building, Room, Period, Lecturer, ClassInstance, ClassLab, Person, Role, PersonRole from course_class import CourseClass # This section takes values from the database and stores them in course clas list print "This will print out all of the course classes currently in the database" self.classes_list = [] all_course_class = ClassInstance.objects.all() for ClassInstance in all_course_class: lecturer = ClassInstance.idLecturer new_prof = Professor() new_prof.name = lecturer.Name new_prof.id = lecturer.idLecturer Class = ClassInstance.idClass new_course = Course() new_course.id = Class.idClass new_course.name = Class.Class new_course_class = CourseClass() new_course_class.professor = new_prof new_course_class.course = new_course new_course_class.duration = 1 new_course_class.lab = False new_course_class.id = ClassInstance.idClassInstance self.classes_list.append(new_course_class) self.num_classes += 1 for course_class in self.classes_list: print "(Professer: %s Course: %s Durration: %d Lab: %d)" % (course_class.professor, course_class.course, course_class.duration, course_class.lab)
class TestCourseAddPrereq(unittest.TestCase): def setUp(self): self.c1 = Course('Highschoolcalc') self.c2 = Course('MAT136') self.c3 = Course('MAT137', [self.c1]) self.c4 = Course('MAT237', [self.c2, self.c3]) def test_add_prereq_no_prereqs(self): prereq = Course('MAT223') self.c1.add_prereq(prereq) self.assertEqual([prereq], self.c1.prereqs) def test_add_prereqs_many_prereqs(self): prereq = Course('MAT136') self.c1.add_prereq(prereq) self.assertEqual(prereq.name, self.c1.prereqs[-1].name) def test_error_in_tree(self): self.assertRaises(PrerequisiteError, self.c3.add_prereq, self.c1) self.assertRaises(PrerequisiteError, self.c4.add_prereq, self.c1) def test_error_in_prereq_tree(self): self.assertRaises(PrerequisiteError, self.c1.add_prereq, self.c3) self.assertRaises(PrerequisiteError, self.c1.add_prereq, self.c4) def test_error_add_self(self): self.assertRaises(PrerequisiteError, self.c3.add_prereq, self.c3)
class TestCourseMissingPrereqs(unittest.TestCase): def setUp(self): self.c1 = Course('CSC108') self.c2 = Course('CSC148', [self.c1]) self.c3 = Course('CSC207', [self.c2]) self.c4 = Course('CSC208', [self.c3]) self.c5 = Course('CSC209', [self.c4]) self.c6 = Course('CSC301', [self.c5]) self.c7 = Course('CSC302', [self.c6]) def test_missing_prereqs_one_missing(self): self.assertEqual(['CSC108'], self.c2.missing_prereqs()) def test_missing_prereqs_many_missing(self): lst = ['CSC108', 'CSC148', 'CSC207', 'CSC208', 'CSC209', 'CSC301'] self.assertEqual(lst, self.c7.missing_prereqs()) def test_not_missing_prereq(self): self.c1.taken = True self.c2.taken = True self.c3.taken = True self.c4.taken = True self.c5.taken = True self.c6.taken = True self.assertEqual([], self.c7.missing_prereqs())
class TestCourseIsTakeable(unittest.TestCase): def setUp(self): self.c1 = Course('CSC108') self.c2 = Course('CSC148', [self.c1]) def test_takeable_one_prereq_satisfied(self): self.c1.taken = True self.assertTrue(self.c2.is_takeable) def test_takeable_many_prereqs_satisfied(self): self.c1 = Course('CSC108') self.c2 = Course('CSC148', [self.c1]) self.c3 = Course('CSC165', [self.c1]) self.c4 = Course('CSC207', [self.c1, self.c2, self.c3]) self.c1.taken = True self.assertTrue(self.c2.is_takeable()) self.assertTrue(self.c3.is_takeable()) self.c2.taken = True self.c3.taken = True self.assertTrue(self.c4.is_takeable()) def test_not_takeable(self): self.c1 = Course('CSC108') self.c2 = Course('CSC148', [self.c1]) self.assertFalse(self.c2.is_takeable()) def test_takeable_taken(self): self.c1 = Course('CSC108') self.c1.taken = True self.assertTrue(self.c1.is_takeable())
def __make_schedule(requirements, current_schedule): if len(requirements) == 0: return current_schedule requirement = requirements[0] requirements = requirements[1:] for course in requirement.valid_courses: if len(Course.get_all_by_crn(course)) == 0: raise Exception("No class in catalog; %s" % course) for c in Course.get_all_by_crn(course): # Check to see if this course conflicts with anything conflicts = False for c2 in current_schedule: if c.timeslot.conflicts(c2.timeslot): conflicts = True break if not conflicts: # Make sure we can take it, then recurse schedule = [] if not c.can_take(current_schedule, credit_hour_limit=max_credits): schedule = __make_schedule(requirements, current_schedule) if schedule == False: continue # If we still can't take it, continue if not c.can_take(schedule, credit_hour_limit=max_credits): continue schedule += [c] else: schedule = __make_schedule(requirements, current_schedule + [c]) if schedule != False: return schedule return False
def parse_course_table (p, tree, table): courses = [] course_type_path = tree.getpath (table) + "/descendant::a[contains(@class, 'title')]/text()" course_type = tree.xpath(course_type_path)[0] codes_path = tree.getpath (table) + "/descendant::td[contains(@class, 'code')]/a" codes = tree.xpath (codes_path) codes_title_path = tree.getpath (table) + "/descendant::td[contains(@class, 'title')]/a/text()" codes_title = tree.xpath (codes_title_path) if len(codes) != len(codes_title): print ("Error: lengths don't match with codes and codes_title") return [] for i in range (len (codes)): c = Course(codes[i].text) c.type = parse_course_type (course_type) c.name = codes_title[i] c.link = codes[i].get ("href") for e in codes_title[i].getparent().itersiblings(): if e.tag == "span" and e.get ("class") == "comment": for p in e.iterchildren(): if p.tag == "p": c.comment = p.text courses.append (c) return courses
class Boarding(GameState): def __init__(self): super(Boarding, self).__init__() def startup(self, persistent): self.persist = persistent name = self.persist["course_name"] filepath = os.path.join("resources", "courses", "{}.json".format(name)) with open(filepath, "r") as f: course_info = json.load(f) self.course = Course(course_info) x, y = self.course.map_rect.centerx, 50 self.player = Snowboarder((x, y)) pg.mouse.set_visible(False) pg.mixer.music.load(prepare.MUSIC["wind"]) pg.mixer.music.set_volume(.7) pg.mixer.music.play(-1) def get_event(self, event): if event.type == pg.KEYUP: if event.key == pg.K_ESCAPE: self.done = True self.next_state = "MAIN_MENU" pg.mouse.set_visible(True) pg.mixer.music.fadeout(3000) def update(self, dt): keys = pg.key.get_pressed() self.player.update(dt, keys, self.course.map_rect) self.course.update(dt, self.player) def draw(self, surface): surface.fill(pg.Color(242, 255, 255)) self.course.draw(surface, self.player)
class TestCourseTake(unittest.TestCase): def setUp(self): self.c1 = Course('CSC108') self.c2 = Course('CSC148', [self.c1]) self.c3 = Course('CSC207', [self.c2]) def test_take_prereq_satisfied(self): self.c1.taken = True self.assertFalse(self.c2.taken) self.c2.take() self.assertTrue(self.c2.taken) def test_take_taken(self): self.c1.taken = True self.c1.take() self.assertTrue(self.c1.taken) def test_take_many_in_a_row(self): self.c1.take() self.c2.take() self.c3.take() self.assertTrue(self.c3.taken) def test_take_error(self): self.c1.taken = False self.assertRaises(UntakeableError, self.c2.take)
class Editor(GameState): """Allows the user to edit a course.""" def __init__(self): super(Editor, self).__init__() self.next_state = "MAIN_MENU" def startup(self, persistent): """Creates a Course object from the previously selected JSON file.""" self.persist = persistent name = self.persist["course_name"] filepath = os.path.join("resources", "courses", "{}.json".format(name)) with open(filepath, "r") as f: course_info = json.load(f) self.course = Course(course_info) self.scroll_speed = .25 self.view_center = list(self.course.view_rect.center) def save_to_json(self): """Saves location of all course objects to be loaded for future use.""" course_info = { "map_name": self.course.map_name, "map_size": self.course.map_size, "obstacles": [[x.name, x.rect.midbottom] for x in self.course.obstacles] } filepath = os.path.join("resources", "courses", "{}.json".format(self.course.map_name)) with open(filepath, "w") as f: json.dump(course_info, f) def get_event(self, event): if event.type == pg.QUIT: self.save_to_json() self.done = True elif event.type == pg.KEYUP: if event.key == pg.K_ESCAPE: self.save_to_json() self.done = True def scroll(self, dt, mouse_pos): """Move the view rect when the mouse is at the edge of the screen.""" speed = self.scroll_speed * dt x, y = mouse_pos w, h = prepare.SCREEN_SIZE if x < 20: self.view_center[0] -= speed elif x > w - 20: self.view_center[0] += speed if y < 20: self.view_center[1] -= speed elif y > h - 20: self.view_center[1] += speed self.course.view_rect.center = self.view_center def update(self, dt): mouse_pos = pg.mouse.get_pos() self.scroll(dt, mouse_pos) def draw(self, surface): surface.fill(pg.Color(242, 255, 255)) self.course.draw(surface)
def create_program (): p = Program("Dummy Program") for t, d in data: c = Course (t) c.short_desc = d p.courses.append (c) return p
def setUp(self): self.c1 = Course('CSC108') self.c2 = Course('CSC148', [self.c1]) self.c3 = Course('CSC207', [self.c2]) self.c4 = Course('CSC208', [self.c3]) self.c5 = Course('CSC209', [self.c4]) self.c6 = Course('CSC301', [self.c5]) self.c7 = Course('CSC302', [self.c6])
class TestCourseAddPrereq(unittest.TestCase): def setUp(self): self.c3 = Course('alone101') def test_add_prereq_no_prereqs(self): prereq = Course('MAT223') self.c3.add_prereq(prereq) self.assertEqual([prereq], self.c3.prereqs)
class TestCourseTake(unittest.TestCase): def setUp(self): self.c1 = Course('CSC108') self.c2 = Course('CSC148', [self.c1]) def test_take_prereq_satisfied(self): self.c1.taken = True self.assertFalse(self.c2.taken) self.c2.take() self.assertTrue(self.c2.taken)
def test_takeable_many_prereqs_satisfied(self): self.c1 = Course('CSC108') self.c2 = Course('CSC148', [self.c1]) self.c3 = Course('CSC165', [self.c1]) self.c4 = Course('CSC207', [self.c1, self.c2, self.c3]) self.c1.taken = True self.assertTrue(self.c2.is_takeable()) self.assertTrue(self.c3.is_takeable()) self.c2.taken = True self.c3.taken = True self.assertTrue(self.c4.is_takeable())
def get(self): user = self.get_current_user() if not user: self.redirect("/") return key = db.Key(encoded=self.request.get("key")) course = Course.get(key) class_key = db.Key(encoded=self.request.get("class")) goto = self.request.get("goto") if goto == None or goto == "": goto = "/" # if class is different copy list to the new class if class_key != course.parent_key(): aclass = Class.get(class_key) newCourse = Course(parent=aclass) newCourse.name = course.name newCourse.chapters = course.chapters newCourse.count_questions() newCourse.put() self.stop_edit_course() self.redirect(goto)
def parse(self): """Return a list of all courses formatted from the html file.""" tree = make_tree(self.url) is_summer = (self.semester == 'summer') tree = clean_html(tree, is_summer) tables = tree.xpath('//table') courses = [] for t in tables: td = t.xpath("td[contains(@class, 'cusistabledata')]") # Since it is not possible to find the tr elements using # lxml we find all the td elements and make a 2 dimensional # array representing the table. rows = [td[i:i + 8] for i in xrange(0, len(td), 8)] course_term = [] seen_course = {} # result = None for row in rows: course = Course() # Course name ex: COMP + 352 / 1 course_name = '{} {}'.format(row[2].text, row[3].text) # Group same course together. # result, seen_course = self.same_course( # course_name, seen_course) ((course.colorid, course.summary), seen_course) = self.same_course(course_name, seen_course) course.datetime_day = row[0].text course.time = row[1].text course.room = row[5].text course.campus = row[6].text course.professor = row[7].text course.section = row[4].text course.semester = self.semester # Append the summer section to the semester. if is_summer: course.semester += get_summer_section( course.section.split(' ')[1][0]) # Append the buildings address of a specific course and format # the data. course.format_data(self.buildings) course_term.append(course) # Make sure to not to have 2 instances of the same course. course_term = recurent_event_factor(course_term) courses.append(course_term) return courses
def test_course_can_take(self): ts1 = Timeslot('FA12', {'M': ['09:00', '11:00'], 'R': ['09:00', '11:00']}) ts2 = Timeslot('FA13', {'M': ['09:00', '11:00'], 'R': ['09:00', '11:00']}) ts3 = Timeslot('FA14', {'M': ['09:00', '11:00'], 'R': ['09:00', '11:00']}) c1 = Course("CS101", ts1) c2 = Course("CS201", ts2, ["CS101"]) c3 = Course("CS101", ts3) self.assertFalse(c2.can_take([])) self.assertTrue(c2.can_take([c1])) self.assertFalse(c2.can_take([c3]))
def create_courses(roster_data, keep_df=None): """ Create Course objects by doing one pass of roster file and using info from fields StudentID, coursename, TeacherID. Based on the 'keeplist', determine whether a course in mandatry Return data frame with new column that contains list of Course objects """ # Track courses (Course objects) that are created; will eventually be added to main roster dataframe course_list = [] for ix, row in roster_data.iterrows(): # Info for the course sid = row["StudentID"] course = row["coursename"] teachID = row["TeacherID"] subject = row["subject"] # Does Course already exist exists = False for course_obj in course_list: course_name = course_obj.course_name teach_id = course_obj.teacher_id if course == course_name and teachID == teach_id: course_obj.add(sid) course_list.append(course_obj) exists = True break # Continue if course existed if exists: continue else: # Check if there is a keep list and, if so, check if this course shoudl be listed as mandatory keep = False if isinstance(keep_df, pd.DataFrame): if course in keep_df["coursename"].tolist() or subject in keep_df["subject"].tolist(): keep = True # Create new course new_course = Course(course, teachID, subject, keep) new_course.add(sid) course_list.append(new_course) roster_data["Course"] = course_list return roster_data
def generate(self, student_id): # This is the URL where the source of schedule come from. course_table_url = self.__get_url() + "/StudentQuery/CtrlViewQueryCourseTable" # Create the request to get the raw data of schedule. request = Request(url=course_table_url, data=urlencode({'studentNo': student_id}).encode('utf-8')) # Get and return the raw data. data = self.__opener.open(request).read().decode('utf-8') # First extract data from HTML. initial_data = re.findall(pattern=r"<tr>(.+?)</tr>", string=data, flags=re.S) # Create a list of a list of course info. course_list = [] for extracted_data in initial_data: items = re.findall(pattern=r"<td>(.*?)</td>", string=extracted_data, flags=re.S) course_items = [item.strip() for item in items] if len(course_items) != 11: continue course = Course(course_items[2], course_items[6], course_items[4], course_items[1], course_items[5], course_items[7], course_items[9], course_items[10]) course_list.append(course) events = [] for course in course_list: events += course.get_events(self.__weekday_table, self.__course_time_table) cal = Calendar() cal.add("calscale", "GREGORIAN") cal.add("version", "2.0") cal.add("X-WR-CALNAME", "SHU Course Schedule") cal.add("X-WR-TIMEZONE", "Asia/Shanghai") for event in events: cal.add_component(event) cal_path = os.path.join(os.getcwd(), "Course Schedule.ics") f = open(cal_path, "wb") f.write(cal.to_ical()) f.close() cros_platopen(cal_path)
def get(self): user = self.get_current_student() if not user: self.redirect('/') return key = db.Key(encoded=self.request.get('course')) course = Course.get(key) chapters = [] chapter_keys = [] for q in course.chapters: chapter = Chapter.get(q) if chapter: chapters.append(chapter) chapter_keys.append(str(chapter.key())) goto = self.request.get("goto") if goto == None or goto == '': goto = '/' template_values = {'course': course, 'chapters': chapters, 'chapter_keys': chapter_keys, 'goto': goto, } write_template(self, user, 'student_course.html', template_values)
def __init__(self): self.user = User() self.course = Course() self.category = Category() self.quiz = Quiz() self.announcement = Announcement() self.discussion = Discussion()
class TestCourseMissingPrereqs(unittest.TestCase): def setUp(self): self.c1 = Course('CSC108') self.c2 = Course('CSC148', [self.c1]) def test_missing_prereqs_one_missing(self): self.assertEqual(['CSC108'], self.c2.missing_prereqs())
def get_course_list(self): from algorithm.models import School, Department, Class, Prerequisite, Building, Room, Period, Lecturer, ClassInstance, ClassLab, Person, Role, PersonRole from course import Course print "This will print out all the courses currently in the database" self.course_list = [] all_courses = Class.objects.all() for Class in all_courses: new_course = Course() new_course.id = Class.idClass new_course.name = Class.Class self.course_list.append(new_course) self.num_courses += 1 for Course in self.course_list: Course.print_course()
def test_get_courses_by_crn(self): # Timeslot can be empty for this c1 = Course("CSCI2121", None) c2 = Course("CSCI2121", None) c3 = Course("CSCI2121", None) c4 = Course("CSCI2122", None) self.assertEquals(3, len(Course.get_all_by_crn("CSCI2121")))
class TestCourseIsTakeable(unittest.TestCase): def setUp(self): self.c1 = Course('CSC108') self.c2 = Course('CSC148', [self.c1]) def test_takeable_one_prereq_satisfied(self): self.c1.taken = True self.assertTrue(self.c2.is_takeable())
def startup(self, persistent): """Creates a Course object from the previously selected JSON file.""" self.persist = persistent name = self.persist["course_name"] filepath = os.path.join("resources", "courses", "{}.json".format(name)) with open(filepath, "r") as f: course_info = json.load(f) self.course = Course(course_info) self.scroll_speed = .25 self.view_center = list(self.course.view_rect.center)
def process_courses(req_number, index, output_file, rest): print ("PROCESSING COURSES") indx = int(index) if rest: print("WRITING DATA FILE and PROCESSING via REST, this will take a minute or so...") else: print("WRITING DATA FILE ONLY - you must process via SIS Framework...") with open(output_file+"_COURSES-"+datetime.datetime.now().strftime('%Y%m%d-%H%M%S')+".txt", "w") as text_file: text_file.write("\n##### DELETE THIS LINE....THE FOLLOWING IS A COURSE SNAPSHOT FLAT FILE FOR STORE OR DELETE #####\n") text_file.write("##### DELETE THIS LINE.... DATASOURCEKEY %s #####\n" % DSKEXTERNALID) text_file.write("COURSE_ID|EXTERNAL_COURSE_KEY|COURSE_NAME\n") for num in range( 0, int(req_number)): json_payload = {} externalId = "%s_%d" % (COURSEEXTERNALIDSTEM, indx) text_file.write("%s|%s|%s\n" % (externalId, externalId, externalId)) if rest: externalId = "%s_%d" % (COURSEEXTERNALIDSTEM, indx) dataSourceId = "externalId:%s" % DSKEXTERNALID courseId = "%s_%d" % (COURSEEXTERNALIDSTEM, indx) name = "%s_%d" % (COURSEEXTERNALIDSTEM, indx) description = "Course created by LearnObjGen" allowGuests = "true" readOnly = "false" availability = { "duration":"continuous"} json_payload["externalId"] = externalId json_payload["dataSourceId"] = dataSourceId json_payload["courseId"] = courseId json_payload["name"] = name json_payload["description"] = description json_payload["allowGuests"] = allowGuests json_payload["readOnly"] = readOnly json_payload["availability"] = availability #print (json.dumps(json_payload, indent=4, separators=(',', ': '))) global authorized_session course_session = Course(rest, authorized_session.getToken()) course_session.createCourse(DSKEXTERNALID, json.dumps(json_payload), authorized_session.getToken()) indx = indx+1
def startup(self, persistent): self.persist = persistent name = self.persist["course_name"] filepath = os.path.join("resources", "courses", "{}.json".format(name)) with open(filepath, "r") as f: course_info = json.load(f) self.course = Course(course_info) x, y = self.course.map_rect.centerx, 50 self.player = Snowboarder((x, y)) pg.mouse.set_visible(False) pg.mixer.music.load(prepare.MUSIC["wind"]) pg.mixer.music.set_volume(.7) pg.mixer.music.play(-1)
class Admin(object): db = None ''' classdocs ''' #constructor def __init__(self): self.user = User() self.course = Course() self.category = Category() self.quiz = Quiz() self.announcement = Announcement() self.discussion = Discussion() def resetDB(self): self.user.reset() self.course.reset() self.category.reset() self.quiz.reset() self.announcement.reset() self.discussion.reset()
def make_grouping(self, course: Course, survey: Survey) -> Grouping: """ Return a grouping for all students in <course>. Students should be assigned to groups randomly. All groups in this grouping should have exactly self.group_size members except for one group which may have fewer than self.group_size members if that is required to make sure all students in <course> are members of a group. """ # TODO: complete the body of this method roster = course.get_students() roster_random = random.shuffle(roster) return roster_random
def make_grouping(self, course: Course, survey: Survey) -> Grouping: """ Return a grouping for all students in <course>. Starting with a tuple of all students in <course> obtained by calling the <course>.get_students() method, create groups of students using the following algorithm: 1. select the first student in the tuple that hasn't already been put into a group and put this student in a new group. 2. select the student in the tuple that hasn't already been put into a group that, if added to the new group, would increase the group's score the most (or reduce it the least), add that student to the new group. 3. repeat step 2 until there are N students in the new group where N is equal to self.group_size. 4. repeat steps 1-3 until all students have been placed in a group. In step 2 above, use the <survey>.score_students method to determine the score of each group of students. The final group created may have fewer than N members if that is required to make sure all students in <course> are members of a group. """ temp_list = list(course.get_students()) student_tuple = sort_students(temp_list, 'id') student_list = list(student_tuple) grouping = Grouping() for student in student_tuple: # step 1 if student in student_list: temp_group = [student] student_list.remove(student) while self.group_size > len(temp_group) and \ len(student_list) > 0: max_score = 0.0 max_student = student_list[0] for student1 in student_list: temp_score = survey.score_students \ (temp_group + [student1]) if temp_score > max_score: max_score = temp_score max_student = student1 temp_group.append(max_student) student_list.remove(max_student) grouping.add_group(Group(temp_group)) return grouping
class InstructorOfficeLocation(QuestionTemplate): """ Ex: "What is the office location of cmpe 273 instructor?" "Where is the office of cmpe 273 instructor?" "Where is the office of cmpe 273 instructor located?" """ regex = Lemmas("what be") + Question(Pos("DT")) + Lemma("office") + Question(Lemma("location")) + Pos("IN") + Course() + Lemma("instructor") + Question(Pos(".")) | \ Lemmas("where be") + Question(Pos("DT")) + Lemma("office") + Pos("IN") + Course() + Lemma("instructor") + Question(Lemma("locate")) + Question(Pos(".")) def interpret(self, match): answer = "The instructor's office for %s is %s" instructor_office = IsInstructorInfoRelated( ) + match.course + HasFields( 'office_location'.decode('utf-8')) + HasAnswer( answer.decode('utf-8')) return instructor_office
def add_course(self): course = input("课程:").strip() period = input("周期:").strip() price = input("价格:").strip() school_data = File(setting.school_file).file_load() # 读取school_file文件 course_data = school_data[self.school][self.address][ "course"] # 读取课程数据 if course not in course_data: # 判断course不存在 course_data[course] = Course(course, period, price).__dict__ # 添加cours信息 # self.course = course_data # 添加到self.course中 File(setting.school_file).file_dump(school_data) # 写入school_file文件 print("\033[32;1m课程【%s】在【%s】学校【%s】分校创建成功\033[0m" % (course, self.school, self.address)) else: print("\033[41;1m【%s】课程已经存在\033[0m" % course)
def check_enroll(): dept, courseNum = 'BME','150' section_type = 'Dis' course_codes = '13610,13612,13613' checker = Checker(dept,courseNum,section_type,course_codes) enroller = Enroller(3,headless=True) run_login_config(enroller) enrolled = False while not enrolled: course_codes = run_check(checker) course = Course(checker.get_name(), course_codes['Lec'], course_codes[checker.get_section_type()]) enrolled = run_enrollment(enroller,course) if enrolled: enroller.email_notif_enroller("*****@*****.**")
def parser(file, course_list): """ Parse text of filepath file """ course_data = [] filelines = file.readlines() for line in filelines: course_data = [] lineparsed = line_parse(line) for part in lineparsed: course_data.append(part) course = Course(int(course_data[0]), course_data[1], float(course_data[2]), float(course_data[3])) course_list.insert(course) return course_list
def make_grouping(self, course: Course, survey: Survey) -> Grouping: """ Return a grouping for all students in <course>. Starting with a tuple of all students in <course> obtained by calling the <course>.get_students() method, create groups of students using the following algorithm: 1. Get the windows of the list of students who have not already been put in a group. 2. For each window in order, calculate the current window's score as well as the score of the next window in the list. If the current window's score is greater than or equal to the next window's score, make a group out of the students in current window and start again at step 1. If the current window is the last window, compare it to the first window instead. In step 2 above, use the <survey>.score_students to determine the score of each window (list of students). In step 1 and 2 above, use the windows function to get the windows of the list of students. If there are any remaining students who have not been put in a group after repeating steps 1 and 2 above, put the remaining students into a new group. """ students = list(course.get_students()) grouping = Grouping() while len(students) != 0: window = windows(students, self.group_size) if len(window) == 1: group = Group(window[0]) grouping.add_group(group) for student in window[0]: students.remove(student) for index in range(len(window)): first = window[index] if index == len(window) - 1: second = window[0] else: second = window[index + 1] first_score = survey.score_students(first) second_score = survey.score_students(second) if first_score >= second_score: group = Group(first) grouping.add_group(group) for student in first: students.remove(student) break return grouping
def test_add_lecture(self): pass lecturer = Lecturer('Benjamin Kommey', 4564541, 'Mr') course = Course('Embedded Systems', 'COE 361') section = Section('ED CoE', 25, 3, 'Electrical and Electronics Engineering', 'Computer Engineering') c_item = CurriculumItem(section, course, lecturer) lecture = Lecture(c_item, 60) ttslot = TimetableSlot('Monday', Classroom('LT ', 45, 'PBOO2'), TimeSlot('8:00', '9:00')) ttslot1 = TimetableSlot('Tuesday', Classroom(' A110', 300, 'Libary'), TimeSlot('9:00', '10:00')) ttslot2 = TimetableSlot('Thursday', Classroom('Room C', 67, 'N1'), TimeSlot('10:00', '11:00')) ttslot3 = TimetableSlot('Friday', Classroom('LT ', 45, 'PBOO2'), TimeSlot('11:00', '12:00')) ttslot4 = TimetableSlot('Monday', Classroom('LT ', 45, 'PBOO2'), TimeSlot('10:00', '11:00')) print(self.timetable) self.assertTrue(self.timetable.add_lecture('Monday', lecture, ttslot)) self.assertTrue( self.timetable.timetableslot('Monday', ttslot1.room, ttslot1.time_slot).is_occupied, True) self.assertTrue(self.timetable.add_lecture('Tuesday', lecture, ttslot1)) self.assertTrue( self.timetable.add_lecture('Thursday', lecture, ttslot2)) self.assertTrue(self.timetable.add_lecture('Friday', lecture, ttslot3)) print( '############################### Add Lecture ############################' ) print(self.timetable) self.timetable.timetable['Monday'].remove_time_table_slot( Classroom('LT ', 45, 'PBOO2'), TimeSlot('9:00', '10:00')) print( '####################################################################' ) print(self.timetable) self.timetable.timetable['Monday'].move_lecture(ttslot, ttslot4) print(self.timetable.timetable) self.assertNotEqual(self.timetable.timetable['Monday'], self.timetable.timetable['Tuesday'])
def test_course_exists(self): """ 030A - Valid Course Exists """ test_course_1 = Course("ACIT2515", "123456", "CIT") test_course_1.add_student("A010000056") test_course_2 = Course("COMP1510", "456321", "CST") test_course_2.add_student("A010000056") test_course_2.add_student("A010450012") test_school = School("Computing and Academic Studies") test_school.add_course(test_course_1) test_school.add_course(test_course_2) self.assertTrue(test_school.course_exists("ACIT2515"), "Course ACIT2515 must exist") self.assertTrue(test_school.course_exists("COMP1510"), "Course COMP1510 must exist")
def make_grouping(self, course: Course, survey: Survey) -> Grouping: """ Return a grouping for all students in <course>. Starting with a tuple of all students in <course> obtained by calling the <course>.get_students() method, create groups of students using the following algorithm: 1. select the first student in the tuple that hasn't already been put into a group and put this student in a new group. 2. select the student in the tuple that hasn't already been put into a group that, if added to the new group, would increase the group's score the most (or reduce it the least), add that student to the new group. 3. repeat step 2 until there are N students in the new group where N is equal to self.group_size. 4. repeat steps 1-3 until all students have been placed in a group. In step 2 above, use the <survey>.score_students method to determine the score of each group of students. The final group created may have fewer than N members if that is required to make sure all students in <course> are members of a group. """ students_list = list(course.get_students()) return_grouping = Grouping() while len(students_list) > 0: st = students_list.pop(0) group_students = [st] for _ in range(1, self.group_size): # Find a list of tuples of (student, score) scores = [(other_st, survey.score_students(group_students + [other_st])) for j, other_st in enumerate(students_list)] # Find max student (max_st, _) = max(scores, key=lambda item: item[1]) # Then add it (also remove from original list) students_list.remove(max_st) group_students.append(max_st) return_grouping.add_group(Group(group_students)) return return_grouping
def test_course_exists_not_existent_course(self): """ 030C - Valid Course Does Not Exist """ test_course_1 = Course("ACIT2515", "123456", "CIT") test_course_1.add_student("A010000056") test_course_2 = Course("COMP1510", "456321", "CST") test_course_2.add_student("A010000056") test_course_2.add_student("A010450012") test_school = School("Computing and Academic Studies") test_school.add_course(test_course_1) test_school.add_course(test_course_2) self.assertFalse(test_school.course_exists("ACIT1234"), "Course ACIT1234 must NOT exist") self.assertFalse(test_school.course_exists("COMP4321"), "Course4321 must NOT exist")
def writeCourses(ws): # build a list of courses and output a worksheet global document global currentKnowledgeArea global courses global default_format for p in document.paragraphs: #print(p.text.strip()) if p.style.name == constant.STYLE_NORMAL: if knowledgeAreas.count(p.text.strip()) == 1: currentKnowledgeArea = knowledgeAreas[knowledgeAreas.index( p.text.strip())] else: currentKnowledgeArea = currentKnowledgeArea else: currentKnowledgeArea = "" if currentKnowledgeArea != "" and p.text.strip() != "": course = Course() course.setKnowledgeArea(currentKnowledgeArea) course.setTOCEntry(p.text.strip()) course.setTitle(p.text.strip().rstrip(string.digits)) courses.append(course) row = 0 col = 0 ws.write(row, col, 'Knowledge Area') col += 1 ws.write(row, col, 'Course Title') col = 0 row += 1 for course in courses: if course.getKnowledgeArea() != course.getTitle(): ws.write(row, col, course.getKnowledgeArea()) col += 1 ws.write(row, col, course.getTitle()) col += 1 ws.write(row, col, course.getDescription()) col = 0 row += 1 ws.set_column(0, 0, 35, default_format) ws.set_column(1, 1, 50, default_format)
class UnitsQuestion(QuestionTemplate): """ Ex: "How many units are there for cmpe 273?" How many credits are there for cmpe 287? What number of units are there for cmpe 273? """ regex = Lemmas("what be") + Lemma("number") + Question( Pos("DT")) + Lemma("units") + Pos("IN") + Course() + Question(Pos(".")) # Lemma("who") + Lemma("teach") + Course() + Question(Pos("."))| \ # Pos("IN") + Lemmas("whom be") + Course() + Lemma("taught") + Question(Pos(".")) def interpret(self, match): answer = "The units awarded for %s is %s" units = IsClassRelated() + match.course + HasFields( 'units'.decode('utf-8')) + HasAnswer(answer.decode('utf-8')) return units
def make_grouping(self, course: Course, survey: Survey) -> Grouping: """ Return a grouping for all students in <course>. Starting with a tuple of all students in <course> obtained by calling the <course>.get_students() method, create groups of students using the following algorithm: 1. Get the windows of the list of students who have not already been put in a group. 2. For each window in order, calculate the current window's score as well as the score of the next window in the list. If the current window's score is greater than or equal to the next window's score, make a group out of the students in current window and start again at step 1. If the current window is the last window, compare it to the first window instead. In step 2 above, use the <survey>.score_students to determine the score of each window (list of students). In step 1 and 2 above, use the windows function to get the windows of the list of students. If there are any remaining students who have not been put in a group after repeating steps 1 and 2 above, put the remaining students into a new group. """ students = list(course.get_students()) grouping = Grouping() while len(students) > 0: wins = windows(students, self.group_size) next_wins = None for i in range(len(wins)): score = survey.score_students(wins[i]) if i == len(wins) - 1: next_score = survey.score_students(wins[0]) else: next_score = survey.score_students(wins[i + 1]) if score >= next_score: grouping.add_group(Group(wins[i])) next_wins = wins[i] break for student in next_wins: students.remove(student) return grouping
def _get_courses_in_page(url) -> [Course]: """ Given a WebSoc search URL, creates a generator over each Course in the results page """ # Get the page that lists the courses in a table with urllib.request.urlopen(url) as source: soup = bs.BeautifulSoup(source, "html.parser") # Iterate over each course, which is each row in the results for row in soup.find_all("tr"): # Get the values of each column cells = [td.string for td in row.find_all("td")] # Convert this row to a Course object if len(cells) in {15, 16, 17}: yield Course(cells)
def handle_score_page(self, scores_page): """处理分数页面 把结果保存到student的courses数组中""" bs_obj = BeautifulSoup(scores_page, 'html5lib') course_tags = bs_obj.find_all('tr', attrs={'class': "odd"}) score_tags = bs_obj.find_all('p') if course_tags: for course_tag in course_tags: course_name = course_tag.contents[5].contents[0].strip() course_credit = course_tag.contents[9].contents[0].strip() c = Course(course_name, course_credit) self.student.courses.append(c) for score, course in zip(score_tags, self.student.courses): grade = score.contents[0].strip() course.set_score(grade) else: print("Error, please check your student number or retry")
class Admin: studentScheduler = StudentScheduler() studentList = [] number = int(input("Enter the total number of students you want to add:")) for i in range(0, number): student = Student() student.setName(raw_input("Enter the name of the student")) student.setRollNumber(input("Enter the roll number of the student")) noOfCourses = int(raw_input("How many courses you want to add:")) for j in range(0, noOfCourses): course = Course() course.setCourseName(raw_input("Enter the Course")) student.setCourseNames(course) studentScheduler.addStudent(student) list = studentScheduler.showStudents() for k in range(0, len(list)): print(list[i])
def test(): reqargs = request.args.getlist('clsl') department_string = request.args.get('dep') course_name_filter_string = request.args.get('cnf') prof_name_filter_string = request.args.get('pnf') course_day_filter_string = request.args.get('cdf') course_time_filter_string = request.args.get('ctf') sex_filter_int = (request.args.get('jens') and int(request.args.get('jens'))) or 0 dep_filter = department_filter(department_string) course_name_filter = parse_courfilter_string(course_name_filter_string) prof_name_filter = parse_proffilter_string(prof_name_filter_string) course_day_filter = parse_dayfilter_string(course_day_filter_string) course_time_filter = parse_timefilter_string(course_time_filter_string) sex_filt = sex_filter(sex_filter_int) final_filter = and_filter(course_name_filter, prof_name_filter, course_day_filter, course_time_filter, dep_filter, sex_filt) selected_courses = Course.select_courses(courses, reqargs) user = '' if 'username' in session: user = session['username'] if selected_courses: selected_user_courses[user] = selected_courses unselected_courses = [ cour for cour in courses if not cour in selected_courses] return render_template('main_template.html', selected_courses=selected_courses, unselected_courses=filter( final_filter, unselected_courses), user=user, filter_strings=[course_name_filter_string, prof_name_filter_string, course_day_filter_string, course_time_filter_string, department_string, sex_filter_int], departments=departments)
def get(self): user = self.get_current_student() if not user: self.redirect('/') return encoded_chapter_key = self.request.get('chapter') chapter, encoded_chapter_key = get_chapter_by_encoded_key(encoded_chapter_key) encoded_course_key = self.request.get('course') course = Course.get(db.Key(encoded=encoded_course_key)) if not course.has_chapter(chapter): self.redirect('/studentcoursepage?course='+encoded_course_key) subchapters = chapter.subchapters() subchapters_empty = len(subchapters) == 0 parents = list_parents(chapter) parents.reverse() if chapter.text != None: chapter_formatted_text = mymarkdown(chapter.text) else: chapter_formatted_text = '' questions = list_questions(chapter) for q in questions: q.result = get_result(user,q) q.formatted_text = mymarkdown(q.text) has_questions = len(questions) > 0 template_values = { 'subchapters': subchapters, 'subchapters_empty': subchapters_empty, 'parents' : parents, 'chapter_formatted_text' : chapter_formatted_text, 'questions' : questions, 'has_questions' : has_questions, 'course' : course, } add_chapter_values(template_values, chapter) write_template(self, user, 'student_chapter.html',template_values)
def make_grouping(self, course: Course, survey: Survey) -> Grouping: """ Return a grouping for all students in <course>. Starting with a tuple of all students in <course> obtained by calling the <course>.get_students() method, create groups of students using the following algorithm: 1. select the first student in the tuple that hasn't already been put into a group and put this student in a new group. 2. select the student in the tuple that hasn't already been put into a group that, if added to the new group, would increase the group's score the most (or reduce it the least), add that student to the new group. 3. repeat step 2 until there are N students in the new group where N is equal to self.group_size. 4. repeat steps 1-3 until all students have been placed in a group. In step 2 above, use the <survey>.score_students method to determine the score of each group of students. The final group created may have fewer than N members if that is required to make sure all students in <course> are members of a group. """ tup_students = course.get_students() free_students = list(tup_students) grouping = Grouping() while len(free_students) > self.group_size: first_student = free_students.pop(0) group = [first_student] while not len(group) == self.group_size: group_scores = {} for student in free_students: try_group = group + [student] score = survey.score_students(try_group) group_scores[score] = student max_score = max(group_scores.keys()) next_student = group_scores[max_score] group.append(next_student) free_students.remove(next_student) group = Group(group) grouping.add_group(group) last_group = Group(free_students) grouping.add_group(last_group) return grouping
def read_course(line): """ ------------------------------------------------------- Creates and returns a Course object from a line of string data. Use: course = read_course(line) ------------------------------------------------------- Preconditions: line - a comma-delimited line of Course data in the format "code,title,credit,term" (str) Postconditions: returns course - contains the data from line (Course) ------------------------------------------------------- """ line = line.split(",") c = Course(line[0], line[1], line[2], line[3]) return c
class ExamQuestion(QuestionTemplate): """ Ex: "When is the final exam for cmpe 273?" "When is the midterm exam for cmpe 273?" "What time is the final exam for cmpe 273?" "What time is the midterm exam for cmpe 273?" """ opening = Lemmas("what time be") | Lemmas("when be") exam = Group(Plus(Lemmas("final exam") | Lemmas("midterm exam")), "exam") regex = opening + Question( Pos("DT")) + exam + Pos("IN") + Course() + Question(Pos(".")) def interpret(self, match): exam = "The %s" % match.exam.tokens answer = exam + " for %s is on %s" exam_time = IsExamRelated() + match.course + HasFields( match.exam.tokens) + HasAnswer(answer.decode('utf-8')) return exam_time
def make_grouping(self, course: Course, survey: Survey) -> Grouping: """ Return a grouping for all students in <course>. Students should be assigned to groups randomly. All groups in this grouping should have exactly self.group_size members except for one group which may have fewer than self.group_size members if that is required to make sure all students in <course> are members of a group. """ student_list = list(course.get_students()) random.shuffle(student_list) student_list = slice_list(student_list, self.group_size) new_grouping = Grouping() for group in student_list: new_grouping.add_group(Group(group)) return new_grouping
def init_course(driver, page, section_link, course_grades_link): """Initialize Course with section_id, activity, course_name, and link to the course""" header = "" for t in driver.find_elements_by_xpath("/html/body/div[2]/div[4]/h4"): header += t.text pivot = -1 if len(str(header).split()) < 5 else -2 section_id = " ".join(str(header).split()[:pivot]) activity = " ".join(str(header).split()[pivot:])[1:-1] course_name = "" for t in driver.find_elements_by_xpath("/html/body/div[2]/div[4]/h5"): course_name += t.text # pivot = -1 if len(str(page.select("body > div.container > div.content.expand > h4")[0].text).split()) < 5 else -2 # section_id = " ".join(str(page.select("body > div.container > div.content.expand > h4")[0].text).split()[:pivot]) # activity = " ".join(str(page.select("body > div.container > div.content.expand > h4")[0].text).split()[pivot:])[1:-1] # course_name = page.select("body > div.container > div.content.expand > h5")[0].text return Course(section_link, section_id, activity, course_name, course_grades_link)
def getCourseClasses(req): classes = [] coursePageURL = courseMainURL + "?fb=" + req try: coursePage = requests.get(coursePageURL, headers=headers) courseSoup = BeautifulSoup(coursePage.content, "lxml") coursePrg = courseSoup.find("table", attrs={ "class": "dersprg" }).findAll("tr") except Exception as e: print(e) print(e.args) coursePrg.pop(0) coursePrg.pop(0) for row in coursePrg: columns = row.findAll("td") classes.append(Course(*[c.text for c in columns])) return classes
def search_course(self): course_obj_list=[] sql='SELECT * FROM course_table' info,reslut=self.excute_cmd(sql) if reslut: for course in info: course_obj = Course(course_id=course[0], course_name=course[1], start_date=course[2].strftime("%Y-%m-%d"), end_date=course[3].strftime("%Y-%m-%d"), lesson_weekday= course[4], start_time=str(course[5]), end_time=str(course[6]), effectiveness=course[7]) course_obj_list.append(course_obj) return course_obj_list,reslut else: return info,reslut
def main(): """Function that runs the the assignments for project 3""" # Reading in the data.txt file into a list of course objects course_lyst = [] with open("data.txt", 'r') as file: for line in file: # List is created at top of each loop so linked list can be a nested list temp_lyst = [] temp_lyst.append(line.split(',')) for i in temp_lyst: temp_lyst = [j.replace('\n', '') for j in i] course = Course(int(temp_lyst[0]), temp_lyst[1], float(temp_lyst[2]), float(temp_lyst[3])) course_lyst.append(course) # Creating a linked list for course objects head = None for i in course_lyst: head = CourseList(i, head)
def get_oscar(subject, course, term): subject = subject.upper() data = [ ("term_in", term), ("subj_in", subject), ("crse_in", course), ("schd_in", "%"), ] response = requests.post( "https://oscar.gatech.edu/pls/bprod/bwckctlg.p_disp_listcrse?", data=data) soup = BeautifulSoup(response.text, "html.parser") # this is terrible, don't do this in real life. tables = soup.findAll( "table", { "summary": "This table lists the scheduled meeting times and assigned instructors for this class.." }, ) headings = soup.findAll("th", {"class": "ddtitle"}) course_objects = [Course("", "", "") for i in range(0, len(tables))] for k, i in enumerate(tables): rows = i.findAll("tr") for j in rows: elements = j.findAll("td") if len(elements) != 0: course_objects[k].term = term course_objects[k].course = course course_objects[k].subject = subject index = elements[6].text.find(" (P)") names = elements[6].text[:index].split(" ", 2) names = [name.strip().title() for name in names] course_objects[k].professor = names[0] + " " + names[ len(names) - 1] head = headings[k].find("a") classes = head.text classes_split = classes.split(" - ", 4) course_objects[k].section = classes_split[3].strip() # Returns list of professors return course_objects
def test_get_course(self): """ 050A - Valid Get Course """ test_course_1 = Course("ACIT2515", "123456", "CIT") test_course_1.add_student("A010000056") test_course_2 = Course("COMP1510", "456321", "CST") test_course_2.add_student("A010000056") test_course_2.add_student("A010450012") test_school = School("Computing and Academic Studies") test_school.add_course(test_course_1) test_school.add_course(test_course_2) retrieved_course = test_school.get_course("ACIT2515") self.assertEqual(retrieved_course.get_course_id(), "ACIT2515", "Course must have course ID ACIT2515") self.assertEqual(retrieved_course.get_crn(), "123456", "Course must have CRN 123456") self.assertEqual(retrieved_course.get_program(), "CIT", "Course must be in CIT program")
def test_add_course(self): """ 020A - Valid Add Course """ test_course_1 = Course("ACIT2515", "123456", "CIT") test_course_1.add_student("A010000056") test_course_2 = Course("COMP1510", "456321", "CST") test_course_2.add_student("A010000056") test_course_2.add_student("A010450012") test_school = School("Computing and Academic Studies") self.assertEqual(test_school.get_num_courses(), 0, "School must have no courses") test_school.add_course(test_course_1) self.assertEqual(test_school.get_num_courses(), 1, "School must have 1 course") test_school.add_course(test_course_2) self.assertEqual(test_school.get_num_courses(), 2, "School must have 2 courses")
def test_remove_non_existent_course(self): """ 040C - Invalid Remove Course Non-Existent """ test_course_1 = Course("ACIT2515", "123456", "CIT") test_course_1.add_student("A010000056") test_course_2 = Course("COMP1510", "456321", "CST") test_course_2.add_student("A010000056") test_course_2.add_student("A010450012") test_school = School("Computing and Academic Studies") test_school.add_course(test_course_1) test_school.add_course(test_course_2) self.assertEqual(test_school.get_num_courses(), 2, "School must have 2 courses") self.assertTrue(test_school.course_exists("ACIT2515")) self.assertTrue(test_school.course_exists("COMP1510")) test_school.remove_course("ACIT1234") self.assertEqual(test_school.get_num_courses(), 2, "School must have 2 courses")