def addLab(self,schedule): schedule = list(schedule) labs = [] # goes through each section in schedule for section_id in schedule: sectionQuery = "SELECT req_type,details FROM Sections,Courses,Requirements WHERE Sections.course_id = Courses.course_id and Courses.course_id = Requirements.course_id and Sections.section_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(sectionQuery % str(section_id)) labs = None for (req_type,details) in cursor: if req_type == "LAB": labs = ast.literal_eval(details) cursor.close() cnx.close() # find labs for this section and add them below if labs != None: added = False # goes through each potential lab for section for lab in labs: if not added: sectionQuery = "SELECT section_id FROM Sections WHERE name = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(sectionQuery % str("'"+lab+"'")) for (section_id) in cursor: lab_id = section_id[0] cursor.close() cnx.close() schedule.append(lab_id) # if the lab fits into schedule, it will be added if (not self.checkScheduleConflict(schedule)): added = True else: schedule = schedule[:-1] # if a lab was added, then added = True # if no lab fit into schedule, return False if added == False: return False # after all sections have labs added and they fit into schedule, return the new schedule return schedule
def checkLab(self,schedule): labs = [] # go through each section in schedule for section_id in schedule: sectionQuery = "SELECT req_type,details FROM Sections,Courses,Requirements WHERE Sections.course_id = Courses.course_id and Courses.course_id = Requirements.course_id and Sections.section_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(sectionQuery % str(section_id)) labs = None # check if there is a lab for (req_type,details) in cursor: if req_type == "LAB": labs = ast.literal_eval(details) cursor.close() cnx.close() # if there is a lab for any section, return True if labs != None: return True # if no lab for any section, return False return False
def checkBadCredits(self,schedule, maxCredits): # default to no credits credits = 0 for sect in schedule: sectionQuery = "SELECT min_credits FROM Sections WHERE section_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(sectionQuery % str(sect)) for (min_credits) in cursor: # add credits for each section credits += int(min_credits[0]) cursor.close() cnx.close() # if bad schedule if credits > maxCredits: return True # if good schedule return False
def checkScheduleConflict(self,section_ids): sections = [] # create dictionary for datetime days of week days_dict = {'M':'2','T':'3','W':'4','R':'5','F':'6'} # go through all sections in schedule for section_id in section_ids: # get start and end times of section sectionQuery = "SELECT start_time, end_time, days FROM SectionMeetings WHERE section_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(sectionQuery % str(section_id)) for (start_time, end_time, days) in cursor: start_time = start_time end_time = end_time days = days cursor.close() cnx.close() # if times of course are not listed, then these values with be nan # if thats the case there is no time to add if start_time == "nan" or end_time == "nan" or days == "nan": sections.append((None,None)) # there is a time and day listed for the section else: # create a list of datetime objects for each section meeting time times = [] for day in range(len(days)): d = str(days_dict[str(days[day])]) st = time.strptime(str(start_time)+' '+d, '%H:%M %w') et = time.strptime(str(end_time)+' '+d, '%H:%M %w') times.append((st,et)) # append list of times to list of sections sections.append((times,len(days))) # go through every section, comparing it to every other section # within each section, compare if there is a time conflict between each meeting time for section1 in range(len(sections)): for section2 in range(section1,len(sections)): if sections[section2] != (None,None) and sections[section1] != (None,None) and section1 != section2: # have one section comparing it to another, get every time they meet for time1 in range(sections[section1][-1]): for time2 in range(sections[section2][-1]): if self.checkTimeConflict(sections[section1][0][time1],sections[section2][0][time2]): return True # no time conflict was found in schedule, return False meaning its a valid schedule time wise return False
def get(self): genEdQuery = "SELECT gen_ed_id, name, abbreviation, also_fulfills FROM GenEds" gen_ed_abbreviations = request.args.get("alsoFulfills") abbreviation_list = [] if gen_ed_abbreviations != None: abbreviation_list = gen_ed_abbreviations.split(",") abbreviation_list = list(map(str, abbreviation_list)) genEdQuery += " WHERE also_fulfills = %s" for i in range(len(abbreviation_list) - 1): genEdQuery += " OR also_fulfills = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() if len(abbreviation_list) > 0: cursor.execute(genEdQuery, tuple(abbreviation_list)) else: cursor.execute(genEdQuery) genEds = [] for (gen_ed_id, name, abbreviation, also_fulfills) in cursor: if also_fulfills == "": genEd = GenEdObject(gen_ed_id, str(name), str(abbreviation), None) else: genEd = GenEdObject(gen_ed_id, str(name), str(abbreviation), str(also_fulfills)) genEds.append(genEd.__dict__) cursor.close() cnx.close() return genEds
def getSectionMeeting(self,section_id): sectionMeetingQuery = "SELECT room_id, start_time, end_time, days FROM SectionMeetings WHERE section_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(sectionMeetingQuery % str(section_id)) meetings = [] for (room_id, start_time, end_time, days) in cursor: room = self.getRoom(room_id) if start_time == "": start_time = None if end_time == "": end_time = None meet = SectionMeetingObject(room_id, start_time, end_time, days,room) meetings.append(meet.__dict__) cursor.close() cnx.close() return meetings
def checkSameCourse(self,schedule): course_ids = [] # go through each section in schedule for section_id in schedule: # get course id of section sectionQuery = "SELECT course_id FROM Sections WHERE section_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(sectionQuery % str(section_id)) for (course_id) in cursor: if course_id not in course_ids: # add course id to list of course ids in schedule course_ids.append(course_id) cursor.close() cnx.close() # if the amount of courses in schedule is different than the amount of sections, # then there are duplicate courses, so return True, meaning a bad schedule # if no two sections are the same course, then its valid schedule and return False if len(course_ids) != len(schedule): return True return False
def get(self): termQuery = "SELECT DISTINCT term FROM Sections" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(termQuery) terms = [] for term in cursor: terms.append(str(term[0])) cursor.close() cnx.close() return terms
def post(self): insertRecommendation = "INSERT INTO Recommendations (course_id, division_id) VALUES (%s, %s)" cnx = cnx_pool.get_connection() cursor = cnx.cursor() args = parser.parse_args() recommendations = args["recommendations"] for recommendation in recommendations: cursor.execute(insertRecommendation % (recommendation["courseId"], recommendation["divisionId"])) cnx.commit() cursor.close() cnx.close() return "The recommendations have been recorded"
def getRoom(self,room_id): roomQuery = "SELECT number, name, abbreviation FROM Rooms, Buildings WHERE Buildings.building_id = Rooms.building_id AND room_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(roomQuery % str(room_id)) room = [] for (number, name, abbreviation) in cursor: r = RoomObject(room_id, number, name, abbreviation) room.append(r.__dict__) cursor.close() cnx.close() return room
def get(self): divisionQuery = "SELECT name, division_id FROM Divisions" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(divisionQuery) divisions = [] for (name, division_id) in cursor: div = DivisionObject(str(name), division_id) divisions.append(div.__dict__) cursor.close() cnx.close() return divisions
def getRecommendations(course_id): recommendationQuery = "SELECT division_id, COUNT(division_id) AS count FROM Recommendations WHERE course_id = %s GROUP BY(division_id)" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(recommendationQuery % str(course_id)) recommendations = {} for (division_id, count) in cursor: recommendations[str(division_id)] = count cursor.close() cnx.close() if recommendations: return recommendations else: return None
def getRequirements(course_id): requirementQuery = "SELECT req_type, details FROM Requirements WHERE course_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(requirementQuery % str(course_id)) requirements = [] for (req_type, details) in cursor: requirement = RequirementObject(req_type, details) requirements.append(requirement.__dict__) cursor.close() cnx.close() if requirements: return requirements else: return None
def getFaculty(self, section_id): facultyQuery = "SELECT first_initial, last_name, Faculty.faculty_id FROM Faculty, FacultyAssignments WHERE Faculty.faculty_id = FacultyAssignments.faculty_id AND section_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(facultyQuery % str(section_id)) profs = [] for (first_initial, last_name, faculty_id) in cursor: fi = first_initial.split(',') ln = last_name.split(',') fid = faculty_id for p in range(len(ln)): faculty = FacultyObject(fi[p], ln[p],fid,fi[p]+". "+ln[p]) profs.append(faculty.__dict__) cursor.close() cnx.close() return profs
def getNumCredits(self, schedule): # default to no credits credits = 0 for sect in schedule: sectionQuery = "SELECT min_credits FROM Sections WHERE section_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(sectionQuery % str(sect)) for (min_credits) in cursor: # add credits for each section credits += int(min_credits[0]) cursor.close() cnx.close() return credits
def getGenEdFulfillment(self,section_id): genedQuery = "SELECT GenEds.gen_ed_id, comments, name, abbreviation, also_fulfills FROM GenEdFulfillments, GenEds WHERE GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id AND section_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(genedQuery % str(section_id)) ge = [] for (gen_ed_id, comments, name, abbreviation, also_fulfills) in cursor: if also_fulfills == "": also_fulfills = None gef = GenEdFulfillmentObject(gen_ed_id, comments, name, abbreviation,also_fulfills) ge.append(gef.__dict__) cursor.close() cnx.close() return ge
def get(self): # Get the URL params fields = request.args.get("fields") if fields == None: fields = ['comments','courseId','faculty','GenEdFulfillments','id','maxCredits','minCredits','name','sectionMeetings','sevenWeeks','shortTitle','term'] else: f = fields.split(",") fields = [] for i in f: fields.append(str(i).replace(" ","")) new_faculty_ids = [] def multipleNames(prof): count = 0 for letter in prof: if letter == " ": count += 1 if count == 1: return False return True def getMultiple(fi,ln): more_ids = [] for prof in allfaculty: if multipleNames(allfaculty[prof]): names = allfaculty[prof].split(" ") first = names[:len(names)//2] last = names[len(names)//2:] final_pos = 0 pos = 0 for l in first: l = l.replace(",","") if l == fi: final_pos = pos pos += 1 pos = 0 for n in last: n = n.replace(",","") if n == ln: if pos == final_pos: more_ids.append(prof) pos += 1 return more_ids allFaculty = "SELECT faculty_id, first_initial, last_name FROM Faculty" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(allFaculty) allfaculty = {} for (faculty_id, first_initial,last_name) in cursor: allfaculty[faculty_id] = str(first_initial)+" "+str(last_name) cursor.close() cnx.close() faculty_Query = "SELECT faculty_id, first_initial,last_name FROM Faculty" faculty_name = request.args.get("facutlyName") faculty_check = False if faculty_name != None: faculty_check = True n = faculty_name.split(",") faculty_Query += " WHERE first_initial = \'" + n[1] + "\' and last_name = \'" + n[0] + "\'" faculty_ids = request.args.get("facultyId") id_list = [] if faculty_ids != None: faculty_check = True id_list = faculty_ids.split(",") id_list = list(map(str, id_list)) faculty_Query += " WHERE faculty_id = %s" for i in range(len(id_list) - 1): faculty_Query += " OR faculty_id = %s" if faculty_check: cnx = cnx_pool.get_connection() cursor = cnx.cursor() if len(id_list) > 0: cursor.execute(faculty_Query, tuple(id_list)) else: cursor.execute(faculty_Query) faculty = [] more_ids = [] for (faculty_id, first_initial,last_name) in cursor: new_faculty_ids.append(faculty_id) more_ids = (getMultiple(str(first_initial),str(last_name))) cursor.close() cnx.close() if len(more_ids) > 0: cnx = cnx_pool.get_connection() cursor = cnx.cursor() for ids in more_ids: faculty_Query = "SELECT faculty_id, first_initial,last_name FROM Faculty WHERE faculty_id = " + str(ids) cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(faculty_Query) for (faculty_id, first_initial,last_name) in cursor: new_faculty_ids.append(faculty_id) cursor.close() cnx.close() faculty_ids = new_faculty_ids id_list2 = [] facultyQuery = "SELECT section_id from FacultyAssignments" check = False if faculty_ids != None and faculty_ids != []: check = True id_list2 = list(map(str, faculty_ids)) facultyQuery += " WHERE faculty_id = %s" for i in range(len(id_list2) - 1): facultyQuery += " OR faculty_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() if len(id_list2) > 0: cursor.execute(facultyQuery, tuple(id_list2)) else: cursor.execute(facultyQuery) sectIDS = [] for (section_id) in cursor: sectIDS.append(section_id[0]) cursor.close() cnx.close() # facultyQuery = "SELECT section_id from FacultyAssignments" # faculty_ids = request.args.get("facultyId") # id_list2 = [] # check = False # if faculty_ids != None: # check = True # id_list2 = faculty_ids.split(",") # id_list2 = list(map(str, id_list2)) # facultyQuery += " WHERE faculty_id = %s" # for i in range(len(id_list2) - 1): # facultyQuery += " OR faculty_id = %s" # cnx = cnx_pool.get_connection() # cursor = cnx.cursor() # if len(id_list2) > 0: # cursor.execute(facultyQuery, tuple(id_list2)) # else: # cursor.execute(facultyQuery) # sectIDS = [] # for (section_id) in cursor: # sectIDS.append(section_id[0]) sectionQuery = "SELECT term, name, short_title, min_credits, max_credits, comments, seven_weeks, course_id, section_id FROM Sections" course = request.args.get("courses") id_list = [] if course != None: id_list = course.split(",") id_list = list(map(str, id_list)) sectionQuery += " WHERE course_id = %s" for i in range(len(id_list) - 1): sectionQuery += " OR course_id = %s" if check: sectionQuery += " and (section_id = %s" for i in range(len(sectIDS) - 1): sectionQuery += " OR section_id = %s" sectionQuery += ")" id_list += sectIDS else: if check: sectionQuery += " WHERE section_id = %s" for i in range(len(sectIDS) - 1): sectionQuery += " OR section_id = %s" id_list = sectIDS cnx = cnx_pool.get_connection() cursor = cnx.cursor() if len(id_list) > 0: cursor.execute(sectionQuery, tuple(id_list)) else: cursor.execute(sectionQuery) obj = { 'comments':None, 'courseId':None, 'faculty':None, 'GenEdFulfillments':None, 'id':None, 'maxCredits':None, 'minCredits':None, 'name':None, 'sectionMeetings':None, 'sevenWeeks':None, 'shortTitle':None, 'term':None } sections = [] for (term, name, short_title, min_credits, max_credits, comments, seven_weeks, course_id, section_id) in cursor: if "faculty" in fields: prof = self.getFaculty(section_id) obj['faculty'] = prof if "sectionMeetings" in fields: sect_meeting = self.getSectionMeeting(section_id) obj["sectionMeetings"] = sect_meeting if "GenEdFulfillments" in fields: gef = self.getGenEdFulfillment(section_id) obj['GenEdFulfillments'] = gef if "term" in fields: obj['term'] = term if "sevenWeeks" in fields: obj['sevenWeeks'] = seven_weeks if "id" in fields: obj['id'] = section_id if "courseId" in fields: obj['courseId'] = course_id if comments != "nan" and "comments" in fields: obj['comments'] = comments if name != "nan" and "name" in fields: obj['name'] = name if short_title != "nan" and "shortTitle" in fields: obj['shortTitle'] = short_title if min_credits != "nan" and "minCredits" in fields: obj['minCredits'] = min_credits if max_credits != "nan" and "maxCredits" in fields: obj['maxCredits'] = max_credits sect = SectionObject( obj['term'], obj['name'], obj['shortTitle'], obj['minCredits'], obj['maxCredits'], obj['comments'], obj['sevenWeeks'], obj['id'], obj['courseId'], obj['faculty'], obj['sectionMeetings'], obj['GenEdFulfillments'] ) sections.append(sect.__dict__) cursor.close() cnx.close() return sections
def get(self,sectionId): # Get the URL params fields = request.args.get("fields") if fields == None: fields = ['comments','courseId','faculty','GenEdFulfillments','id','maxCredits','minCredits','name','sectionMeetings','sevenWeeks','shortTitle','term'] else: f = fields.split(",") fields = [] for i in f: fields.append(str(i).replace(" ","")) sectionQuery = "SELECT term, name, short_title, min_credits, max_credits, comments, seven_weeks, course_id, section_id FROM Sections" section_id = sectionId id_list = [] if section_id != None: id_list = section_id.split(",") id_list = list(map(str, id_list)) sectionQuery += " WHERE section_id = %s" for i in range(len(id_list) - 1): sectionQuery += " OR section_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() if len(id_list) > 0: cursor.execute(sectionQuery, tuple(id_list)) else: cursor.execute(sectionQuery) obj = { 'comments':None, 'courseId':None, 'faculty':None, 'GenEdFulfillments':None, 'id':None, 'maxCredits':None, 'minCredits':None, 'name':None, 'sectionMeetings':None, 'sevenWeeks':None, 'shortTitle':None, 'term':None } sections = [] for (term, name, short_title, min_credits, max_credits, comments, seven_weeks, course_id, section_id) in cursor: if "faculty" in fields: prof = self.getFaculty(section_id) obj['faculty'] = prof if "sectionMeetings" in fields: sect_meeting = self.getSectionMeeting(section_id) obj["sectionMeetings"] = sect_meeting if "GenEdFulfillments" in fields: gef = self.getGenEdFulfillment(section_id) obj['GenEdFulfillments'] = gef if "term" in fields: obj['term'] = term if "sevenWeeks" in fields: obj['sevenWeeks'] = seven_weeks if "id" in fields: obj['id'] = section_id if "courseId" in fields: obj['courseId'] = course_id if comments != "nan" and "comments" in fields: obj['comments'] = comments if name != "nan" and "name" in fields: obj['name'] = name if short_title != "nan" and "shortTitle" in fields: obj['shortTitle'] = short_title if min_credits != "nan" and "minCredits" in fields: obj['minCredits'] = min_credits if max_credits != "nan" and "maxCredits" in fields: obj['maxCredits'] = max_credits sect = SectionObject( obj['term'], obj['name'], obj['shortTitle'], obj['minCredits'], obj['maxCredits'], obj['comments'], obj['sevenWeeks'], obj['id'], obj['courseId'], obj['faculty'], obj['sectionMeetings'], obj['GenEdFulfillments'] ) sections.append(sect.__dict__) cursor.close() cnx.close() return sections[0]
def get(self): # checks if limit is empty lim = request.args.get("limit") # if not empty, it is int if lim != None: limit = int(lim) # if empty, default to 20 else: limit = 20 # checks if max credits are empty maxnc = request.args.get("maxNumCredits") # if not empty, it is int if maxnc != None: maxNumCredits = int(maxnc) # if empty, default to 18 else: maxNumCredits = 18 # checks if requirements are empty r = request.args.get("requiredCourses") # if not empty, create list if r != None: required = (r).split(',') # if empty, make empty list else: required = [] # check if preferred are empty p = request.args.get("preferredCourses") # if not empty, create list if p != None: preferred = (p).split(',') # if empty, make empty list else: preferred = [] # check if geneds are empty g = request.args.get("requiredGenEds") # if not empty create list if g != None: req_geneds = (g).split(',') # if empty, make empty list else: req_geneds = [] # check if geneds are empty g = request.args.get("preferredGenEds") # if not empty create list if g != None: preferred_geneds = (g).split(',') # if empty, make empty list else: preferred_geneds = [] # check if num of courses are empty n = request.args.get("numCourses") # if not empty, make it an int if n != None: num_courses = int(n) # if empty, default to 4 courses else: num_courses = 4 # check if division is empty d = request.args.get("division") # if not empty, make int if d != None: division = int(d) # if empty, make None else: division = None # check if index is empty i = request.args.get("index") # if not empty, make int if i != None: index = int(i) # if empty, default to -1 else: index = -1 # go through requirements and make int instead of unicode new_r = [] for x in required: new_r.append(int(x)) required = new_r # go through preferred and make int instead of unicode new_p = [] for x in preferred: new_p.append(int(x)) preferred = new_p # go through geneds and make string instead of unicode new_ge = [] for x in preferred_geneds: new_ge.append(str(x)) preferred_geneds = new_ge # go through geneds and make string instead of unicode new_ge = [] for x in req_geneds: new_ge.append(str(x)) req_geneds = new_ge # add all sections of required courses temp = required lst = [] for c in temp: classQuery = "SELECT section_id from Sections where course_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(classQuery % (str(c))) sects = [] for (section_id) in cursor: sects.append(section_id[0]) lst.append(sects) cursor.close() cnx.close() # add all sections of preferred courses temp = preferred for c in temp: classQuery = "SELECT section_id from Sections where course_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(classQuery % (str(c))) sects = [] for (section_id) in cursor: sects.append(section_id[0]) lst.append(sects) cursor.close() cnx.close() # Create all possible schedules from required and preferred. ps = list(itertools.product(*lst)) possible_sections = [] for c in ps: possible_sections.append(list(c)) # all possible schedules all_combos = [] # for each possible schedule with req/preferred for option in possible_sections: best = option required = best[:len(required)] preferred = best[len(required):] # if the best schedule is valid if self.verify(best, maxNumCredits) != False: best = self.verify(best, maxNumCredits) # if the best schedule has amount of sections wanted, add schedule if (len(best) == num_courses): all_combos += [best] # if more courses are needed elif (len(best) < num_courses): num_needed = num_courses - len(best) # if gen eds are wanted, add gen eds if len(req_geneds) + len(preferred_geneds) > 0: # checks if req/preferred classes cover any gen eds required. for gened in range(len(req_geneds)): for section in best: classQuery = "SELECT abbreviation from GenEdFulfillments, GenEds where ((GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and abbreviation = %s) or (GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and also_fulfills = %s)) and GenEdFulfillments.section_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(classQuery % (str("'"+req_geneds[gened]+"'"),str("'"+req_geneds[gened]+"'"),str("'"+str(section)+"'"))) abbs = [] for (abbreviation) in cursor: abbs.append(str(abbreviation[0])) for ge in abbs: if ge in req_geneds: req_geneds.remove(ge) if ge in preferred_geneds: preferred_geneds.remove(ge) cursor.close() cnx.close() # find all classes that cover required gen eds possible_gened_classes = {} for gened in range(len(req_geneds)): classQuery = "SELECT section_id from GenEdFulfillments, GenEds where (GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and abbreviation = %s) or (GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and also_fulfills = %s)" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(classQuery % (str("'"+req_geneds[gened]+"'"),str("'"+req_geneds[gened]+"'"))) classes = [] for (section_id) in cursor: classes.append(section_id[0]) possible_gened_classes[req_geneds[gened]] = classes cursor.close() cnx.close() # find all classes that cover preferred gen eds for gened in range(len(preferred_geneds)): classQuery = "SELECT section_id from GenEdFulfillments, GenEds where (GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and abbreviation = %s) or (GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and also_fulfills = %s)" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(classQuery % (str("'"+preferred_geneds[gened]+"'"),str("'"+preferred_geneds[gened]+"'"))) classes = [] for (section_id) in cursor: classes.append(section_id[0]) possible_gened_classes[preferred_geneds[gened]] = classes cursor.close() cnx.close() # find common geneds doubles = {} for ge in possible_gened_classes: for ge2 in possible_gened_classes: if ge != ge2: for class1 in possible_gened_classes[ge]: for class2 in possible_gened_classes[ge2]: if class1 == class2: key = ge+" "+ge2 if key in doubles: doubles[key].append(class1) else: doubles[key] = [class1] # remove duplicate strings that appear in different orders # for example HE,HB vs HB,HE keys = [] for key in doubles: one,two = key.split() new = set((one,two)) if new not in keys: keys.append(new) for k in keys: delKey = list(k)[0] + " " + list(k)[1] del doubles[delKey] combo = [] for b in best: combo.append([b]) for ge in doubles: one,two = ge.split() if num_needed > 0 and ((one in req_geneds) or (one in preferred_geneds)) and ((two in req_geneds) or (two in preferred_geneds)): combo.append(doubles[ge]) num_needed -= 1 if one in req_geneds: req_geneds.remove(one) if one in preferred_geneds: preferred_geneds.remove(one) if two in req_geneds: req_geneds.remove(two) if one in preferred_geneds: preferred_geneds.remove(two) for x in possible_gened_classes: if num_needed > 0 and x in req_geneds: combo.append(possible_gened_classes[x]) num_needed -= 1 for x in possible_gened_classes: if num_needed > 0 and x in preferred_geneds: combo.append(possible_gened_classes[x]) num_needed -= 1 all_combos += list(itertools.product(*combo)) # if more is wanted after gen eds and best, look for recommendations if num_needed > 0: # check if they specified their division if division != None: # look for recommendations for division to fill schedule classes = [] for i in range(num_needed): classQuery = "SELECT Sections.section_id from Sections, Courses, Recommendations where Courses.course_id = Recommendations.course_id and Courses.course_id = Sections.course_id and Recommendations.division_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(classQuery % str(division)) classes = [] for (section_id) in cursor: classes.append(section_id[0]) cursor.close() cnx.close() temp = [] for x in classes: if num_needed > 0: temp.append(x) num_needed -= 1 new_all = [] for x in all_combos: new_all.append(list(x) + temp) all_combos += new_all # is best schedule is not valid for some reason else: best = required+preferred # remove courses from best until no conflict. while self.verify(best, maxNumCredits) == False: best = best[:-1] best = self.verify(best, maxNumCredits) if len(best) >= len(required): # if the best schedule has amount of sections wanted, add schedule if (len(best) == num_courses): all_combos += [best] # if more courses are needed elif (len(best) < num_courses): num_needed = num_courses - len(best) # if gen eds are wanted, add gen eds if len(req_geneds) + len(preferred_geneds) > 0: for gened in range(len(req_geneds)): for section in best: classQuery = "SELECT abbreviation from GenEdFulfillments, GenEds where ((GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and abbreviation = %s) or (GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and also_fulfills = %s)) and GenEdFulfillments.section_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(classQuery % (str("'"+req_geneds[gened]+"'"),str("'"+req_geneds[gened]+"'"),str("'"+str(section)+"'"))) abbs = [] for (abbreviation) in cursor: abbs.append(str(abbreviation[0])) for ge in abbs: if ge in req_geneds: req_geneds.remove(ge) if ge in preferred_geneds: preferred_geneds.remove(ge) cursor.close() cnx.close() possible_gened_classes = {} for gened in range(len(req_geneds)): classQuery = "SELECT section_id from GenEdFulfillments, GenEds where (GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and abbreviation = %s) or (GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and also_fulfills = %s)" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(classQuery % (str("'"+req_geneds[gened]+"'"),str("'"+req_geneds[gened]+"'"))) classes = [] for (section_id) in cursor: classes.append(section_id[0]) possible_gened_classes[req_geneds[gened]] = classes cursor.close() cnx.close() for gened in range(len(preferred_geneds)): classQuery = "SELECT section_id from GenEdFulfillments, GenEds where (GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and abbreviation = %s) or (GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and also_fulfills = %s)" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(classQuery % (str("'"+preferred_geneds[gened]+"'"),str("'"+preferred_geneds[gened]+"'"))) classes = [] for (section_id) in cursor: classes.append(section_id[0]) possible_gened_classes[preferred_geneds[gened]] = classes cursor.close() cnx.close() # find common geneds doubles = {} for ge in possible_gened_classes: for ge2 in possible_gened_classes: if ge != ge2: for class1 in possible_gened_classes[ge]: for class2 in possible_gened_classes[ge2]: if class1 == class2: key = ge+" "+ge2 if key in doubles: doubles[key].append(class1) else: doubles[key] = [class1] keys = [] for key in doubles: one,two = key.split() new = set((one,two)) if new not in keys: keys.append(new) for k in keys: delKey = list(k)[0] + " " + list(k)[1] del doubles[delKey] combo = [] for b in best: combo.append([b]) for ge in doubles: one,two = ge.split() if num_needed > 0 and ((one in req_geneds) or (one in preferred_geneds)) and ((two in req_geneds) or (two in preferred_geneds)): combo.append(doubles[ge]) num_needed -= 1 if one in req_geneds: req_geneds.remove(one) if one in preferred_geneds: preferred_geneds.remove(one) if two in req_geneds: req_geneds.remove(two) if one in preferred_geneds: preferred_geneds.remove(two) for x in possible_gened_classes: if num_needed > 0 and x in req_geneds: combo.append(possible_gened_classes[x]) num_needed -= 1 for x in possible_gened_classes: if num_needed > 0 and x in preferred_geneds: combo.append(possible_gened_classes[x]) num_needed -= 1 all_combos += list(itertools.product(*combo)) # if more is wanted after gen eds and best, look for recommendations if num_needed > 0: # check if they specified their division if division != None: # look for recommendations for division to fill schedule classes = [] for i in range(num_needed): classQuery = "SELECT Sections.section_id from Sections, Courses, Recommendations where Courses.course_id = Recommendations.course_id and Courses.course_id = Sections.course_id and Recommendations.division_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(classQuery % str(division)) classes = [] for (section_id) in cursor: classes.append(section_id[0]) cursor.close() cnx.close() temp = [] for x in classes: if num_needed > 0: temp.append(x) num_needed -= 1 new_all = [] for x in all_combos: new_all.append(list(x) + temp) all_combos += new_all # shuffle list of all potential schedules # set seed so it is the same everytime random.seed(0) random.shuffle(all_combos) schedules = [] pos = index for x in range(limit): if pos < len(all_combos)-1: pos += 1 # x for index current = all_combos[pos] while self.verify(current, maxNumCredits) == False and pos < len(all_combos)-1: pos += 1 current = all_combos[pos] if pos < len(all_combos)-1: schedule = ScheduleCreationObject(self.verify(current, maxNumCredits),pos) schedules.append(schedule.__dict__) if schedules == []: s = ScheduleCreationObject([],pos) schedules.append(s.__dict__) return (schedules)
def get(self): departments = request.args.get("departments") if departments == None: courseIdsByDept = [] else: departments = departments.split(",") getCoursesByDeptQuery = "SELECT course_id FROM Courses WHERE department_id = %s" deptsLen = len(departments) if deptsLen > 1: for i in range(deptsLen - 1): getCoursesByDeptQuery += " OR department_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() courseIdsByDept = [] cursor.execute(getCoursesByDeptQuery % tuple(departments)) for res in cursor: courseIdsByDept.append(res[0]) cursor.close() cnx.close() genEds = request.args.get("genEds") if genEds == None: courseIdsByGenEd = [] else: genEds = genEds.split(",") getCoursesByGenEdQuery = "SELECT DISTINCT (Courses.course_id) FROM Courses, Sections, GenEdFulfillments, GenEds WHERE (GenEds.gen_ed_id = %s" genEdsLen = len(genEds) if genEdsLen > 1: for i in range(genEdsLen - 1): getCoursesByGenEdQuery += " OR GenEds.gen_ed_id = %s" getCoursesByGenEdQuery += ") AND GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id AND GenEdFulfillments.section_id = Sections.section_id AND Sections.course_id = Courses.course_id" cnx = cnx_pool.get_connection() cursor = cnx.cursor() courseIdsByGenEd = [] cursor.execute(getCoursesByGenEdQuery % tuple(genEds)) for res in cursor: courseIdsByGenEd.append(res[0]) cursor.close() cnx.close() keywords = request.args.get("keywords") if keywords == None: coursesByKeyword = [] else: keywords = keywords.split(",") relevantCourses = relevance(keywords) coursesByKeyword = [result[0] for result in relevantCourses] relevanceNumber = [result[1] for result in relevantCourses] # Logic to decide how which courses whould be searched for useFilter = True courseIdsIntersection = [] relevantNums = [] if departments != None and genEds != None and keywords != None: deptSet = set(courseIdsByDept) genEdSet = set(courseIdsByGenEd) courseIdsIntersection = deptSet.intersection(genEdSet) courseIdsIntersection = list(courseIdsIntersection.intersection(coursesByKeyword)) for cId in courseIdsIntersection: relevantNums.append(relevanceNumber[coursesByKeyword.index(cId)]) elif departments != None and genEds != None: deptSet = set(courseIdsByDept) genEdSet = set(courseIdsByGenEd) courseIdsIntersection = list(deptSet.intersection(genEdSet)) elif departments != None and keywords != None: deptSet = set(courseIdsByDept) kwSet = set(coursesByKeyword) courseIdsIntersection = list(deptSet.intersection(kwSet)) for cId in courseIdsIntersection: relevantNums.append(relevanceNumber[coursesByKeyword.index(cId)]) elif genEds != None and keywords != None: genEdSet = set(courseIdsByGenEd) kwSet = set(coursesByKeyword) courseIdsIntersection = list(genEdSet.intersection(kwSet)) for cId in courseIdsIntersection: relevantNums.append(relevanceNumber[coursesByKeyword.index(cId)]) elif departments != None: courseIdsIntersection = courseIdsByDept elif genEds != None: courseIdsIntersection = courseIdsByGenEd elif keywords != None: courseIdsIntersection = coursesByKeyword relevantNums = relevanceNumber else: useFilter = False # Get the URL params fields = request.args.get("fields") if fields == None: showCourseId = True fields = ["title", "courseId", "description", "sameAs", "name", "departmentId", "requirements", "recommendations", "relevance"] else: fields = fields.split(",") if "courseId" not in fields and ("relevance" in fields or "recommendations" in fields or "requirements" in fields): showCourseId = False fields.append("courseId") else: showCourseId = True # Gather the terms for the course query. coursesTerms = [] for field in fields: if field in coursesDict: coursesTerms.append(coursesDict[field]) # Execute if there is anything needed from the course table if coursesTerms: # Build the course query courseQuery = "SELECT " termsLen = len(coursesTerms) addComma = termsLen - 1 for i in range(termsLen): courseQuery += coursesTerms[i] if i < addComma: courseQuery += ", " if useFilter: courseQuery += " FROM Courses WHERE course_id = %s" else: courseQuery += " FROM Courses" showRelevance = False if "relevance" in fields: showRelevance = True showRequirements = False if "requirements" in fields: showRequirements = True showRecommendations = False if "recommendations" in fields: showRecommendations = True; # Get a connecgtion and open up a cursor and execute the query cnx = cnx_pool.get_connection() cursor = cnx.cursor() relevantCount = 0 if useFilter: courses = [] for cId in courseIdsIntersection: cursor.execute(courseQuery % str(cId)) courses.append(buildCoursesJSON(cursor, coursesTerms, showRelevance, relevantNums, relevantCount, showRequirements, showRecommendations, showCourseId)) relevantCount += 1 else: cursor.execute(courseQuery) courses = buildCoursesJSON(cursor, coursesTerms, showRelevance, relevantNums, relevantCount, showRequirements, showRecommendations, showCourseId) # Close connection and cursor, then return the courses cursor.close() cnx.close() return courses
def get(self, courseId): # Get the URL params fields = request.args.get("fields") if fields == None: fields = ["title","courseId", "description", "sameAs", "name", "departmentId", "requirements", "recommendations", "relevance"] else: fields = fields.split(",") # Gather the terms for the course query. coursesTerms = [] for field in fields: if field in coursesDict: coursesTerms.append(coursesDict[field]) # Te,p object for storing the course info as the fields can be passed in in any order. tempObj = { "short_title": None, "course_id": None, "description": None, "same_as": None, "name": None, "department_id": None } # Get a connecgtion and open up a cursor and execute the query cnx = cnx_pool.get_connection() cursor = cnx.cursor() # Execute if there is anything needed from the course table if coursesTerms: # Build the course query courseQuery = "SELECT " termsLen = len(coursesTerms) addComma = termsLen - 1 for i in range(termsLen): courseQuery += coursesTerms[i] if i < addComma: courseQuery += ", " courseQuery += " FROM Courses WHERE course_id = %s" cursor.execute(courseQuery % str(courseId)) # Populate the temp object for result in cursor: for item, ct in zip(result, coursesTerms): tempObj[ct] = item if tempObj["same_as"] == "nan": tempObj["same_as"] = None # Get the relevance if asked for relevance = None if "relevance" in fields: pass # Get the requirements if asked for requirements = None if "requirements" in fields: requirements = getRequirements(courseId) # Get the recommendations is asked for recommendations = None if "recommendations" in fields: recommendations = getRecommendations(courseId) # Close the connection and cursor cursor.close() cnx.close() # Build the object to be returned returnCourse = CourseObject(tempObj["short_title"], tempObj["course_id"], tempObj["description"], tempObj["same_as"], tempObj["name"], tempObj["department_id"], relevance, requirements, recommendations) return returnCourse.__dict__
def get(self): # initalize error message error = "No errors" ####################################################### # checks if limit is empty lim = request.args.get("limit") # if not empty, it is int if lim != None: limit = int(lim) # if empty, default to 20 else: limit = 20 ####################################################### # checks if max credits are empty maxnc = request.args.get("maxCredits") # if not empty, it is int if maxnc != None: maxNumCredits = int(maxnc) # if empty, default to 18 else: maxNumCredits = 18 ####################################################### # checks if min credits are empty minnc = request.args.get("minCredits") # if not empty, it is int if minnc != None: minNumCredits = int(minnc) # if empty, default to 18 else: minNumCredits = 12 ####################################################### # checks if requirements are empty r = request.args.get("requiredCourses") # if not empty, create list if r != None: required_courses = (r).split(',') # if empty, make empty list else: required_courses = [] ####################################################### # check if preferred are empty p = request.args.get("preferredCourses") # if not empty, create list if p != None: preferred_courses = (p).split(',') # if empty, make empty list else: preferred_courses = [] ####################################################### # checks if requirements are empty r = request.args.get("requiredSections") # if not empty, create list if r != None: required_sections = (r).split(',') # if empty, make empty list else: required_sections = [] ####################################################### # check if preferred are empty p = request.args.get("preferredSections") # if not empty, create list if p != None: preferred_sections = (p).split(',') # if empty, make empty list else: preferred_sections = [] ####################################################### # check if preferred are empty rtb = request.args.get("requiredTimeBlock") # if not empty, create list if rtb != None: req_time_block = (rtb).split(',') # if empty, make empty list else: req_time_block = [] ####################################################### # check if geneds are empty g = request.args.get("requiredGenEds") # if not empty create list if g != None: req_geneds = (g).split(',') # if empty, make empty list else: req_geneds = [] ####################################################### # check if geneds are empty g = request.args.get("preferredGenEds") # if not empty create list if g != None: preferred_geneds = (g).split(',') # if empty, make empty list else: preferred_geneds = [] ####################################################### # check if index is empty i = request.args.get("index") # if not empty, make int if i != None: index = int(i) # if empty, default to -1 else: index = -1 ####################################################### ####################################################### ##################### Format input #################### ####################################################### ####################################################### # go through required courses and make int instead of unicode new_r = [] for x in required_courses: new_r.append(int(x)) required_courses = new_r # go through preferred courses and make int instead of unicode new_p = [] for x in preferred_courses: new_p.append(int(x)) preferred_courses = new_p # go through required Sections and make int instead of unicode new_r = [] for x in required_sections: new_r.append(int(x)) required_sections = new_r # go through preferred Sections and make int instead of unicode new_p = [] for x in preferred_sections: new_p.append(int(x)) preferred_sections = new_p # go through geneds and make string instead of unicode new_ge = [] for x in preferred_geneds: new_ge.append(str(x)) preferred_geneds = new_ge # go through geneds and make string instead of unicode new_ge = [] for x in req_geneds: new_ge.append(str(x)) req_geneds = new_ge # go through times and make string instead of unicode new_times = [] for x in req_time_block: new_times.append(str(x)) req_time_block = new_times ######################################################################## ######################################################################## ####################### Begin Creating Schedule ######################## ######################################################################## ######################################################################## # add all sections of required courses temp = copy.copy(required_courses) # list of (lists of sections for a given course) lst = [] # Add all required setions for sect in required_sections: lst.append([sect]) for c in temp: alreadyAdded = False classQuery = "SELECT section_id from Sections where course_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(classQuery % (str(c))) sects = [] for (section_id) in cursor: if [section_id[0]] in lst: alreadyAdded = True else: sects.append(section_id[0]) if section_id[0] in required_sections: required_courses.remove(c) if not alreadyAdded: lst.append(sects) cursor.close() cnx.close() c = copy.copy(preferred_sections) for sect in c: for possibles in lst: for x in possibles: if sect == x: preferred_sections.remove(sect) # Add all preferred setions for sect in preferred_sections: lst.append([sect]) # add all sections of preferred courses temp = copy.copy(preferred_courses) for c in temp: alreadyAdded = False classQuery = "SELECT section_id from Sections where course_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(classQuery % (str(c))) sects = [] for (section_id) in cursor: if [section_id[0]] in lst: alreadyAdded = True else: sects.append(section_id[0]) if not alreadyAdded: lst.append(sects) cursor.close() cnx.close() # Create all possible schedules from required and preferred courses and sections. ps = list(itertools.product(*lst)) possible_sections = [] for c in ps: possible_sections.append(list(c)) ########################################### # all possible schedules # master list of schedules ########################################### all_combos = [] # for each possible schedule with req/preferred for option in possible_sections: best = option required = best[:(len(required_courses) + len(required_sections))] preferred = best[(len(required_courses)+len(required_sections)):] # if the best schedule is valid best = self.verifyBest(best,req_time_block) if best != False: numCredits = self.getNumCredits(best) # if the best schedule has a valid amount of credits wanted, add schedule if minNumCredits <= numCredits <= maxNumCredits: all_combos += [best] # if more courses can be added if (numCredits < maxNumCredits): num_needed = maxNumCredits - numCredits # if gen eds are wanted, add gen eds if len(req_geneds) + len(preferred_geneds) > 0: # checks if req/preferred classes cover any gen eds required. for gened in range(len(req_geneds)): tmp_req_geneds = copy.copy(req_geneds) tmp_pref_geneds = copy.copy(preferred_geneds) for section in best: classQuery = "SELECT abbreviation from GenEdFulfillments, GenEds where ((GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and abbreviation = %s) or (GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and also_fulfills = %s)) and GenEdFulfillments.section_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(classQuery % (str("'"+req_geneds[gened]+"'"),str("'"+req_geneds[gened]+"'"),str("'"+str(section)+"'"))) abbs = [] for (abbreviation) in cursor: abbs.append(str(abbreviation[0])) for ge in abbs: if ge in tmp_req_geneds: req_geneds.remove(ge) if ge in tmp_pref_geneds: preferred_geneds.remove(ge) cursor.close() cnx.close() # find all classes that cover required gen eds possible_gened_classes = {} for gened in range(len(req_geneds)): classQuery = "SELECT section_id from GenEdFulfillments, GenEds where (GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and abbreviation = %s) or (GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and also_fulfills = %s)" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(classQuery % (str("'"+req_geneds[gened]+"'"),str("'"+req_geneds[gened]+"'"))) classes = [] for (section_id) in cursor: classes.append(section_id[0]) possible_gened_classes[req_geneds[gened]] = classes cursor.close() cnx.close() # find all classes that cover preferred gen eds for gened in range(len(preferred_geneds)): classQuery = "SELECT section_id from GenEdFulfillments, GenEds where (GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and abbreviation = %s) or (GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and also_fulfills = %s)" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(classQuery % (str("'"+preferred_geneds[gened]+"'"),str("'"+preferred_geneds[gened]+"'"))) classes = [] for (section_id) in cursor: classes.append(section_id[0]) possible_gened_classes[preferred_geneds[gened]] = classes cursor.close() cnx.close() # find common geneds doubles = {} for ge in possible_gened_classes: for ge2 in possible_gened_classes: if ge != ge2: for class1 in possible_gened_classes[ge]: for class2 in possible_gened_classes[ge2]: if class1 == class2: key = ge+" "+ge2 if key in doubles: doubles[key].append(class1) else: doubles[key] = [class1] # remove duplicate strings that appear in different orders # for example HE,HB vs HB,HE keys = [] for key in doubles: one,two = key.split() new = set((one,two)) if new not in keys: keys.append(new) for k in keys: delKey = list(k)[0] + " " + list(k)[1] del doubles[delKey] combo = [] for b in best: combo.append([b]) for ge in doubles: one,two = ge.split() if num_needed > 0 and ((one in req_geneds) or (one in preferred_geneds)) and ((two in req_geneds) or (two in preferred_geneds)): combo.append(doubles[ge]) num_needed -= 1 tmp_req_geneds = copy.copy(req_geneds) tmp_pref_geneds = copy.copy(preferred_geneds) if one in tmp_req_geneds: req_geneds.remove(one) if one in tmp_pref_geneds: preferred_geneds.remove(one) if two in tmp_req_geneds: req_geneds.remove(two) if two in tmp_pref_geneds: preferred_geneds.remove(two) for x in possible_gened_classes: if num_needed > 0 and x in req_geneds: combo.append(possible_gened_classes[x]) num_needed -= 1 for x in possible_gened_classes: if num_needed > 0 and x in preferred_geneds: combo.append(possible_gened_classes[x]) num_needed -= 1 all_combos += list(itertools.product(*combo)) # is best schedule is not valid for some reason else: bad = False best = required+preferred # remove courses from best until no conflict. while self.verifyBest(best,req_time_block) == False and len(best) >=1: best = best[:-1] if len(best) == len(required): error = "There was a conflict with required courses/sections" bad = True if len(best) == 0: error = "There was a conflict with required courses/sections" best = [] bad = True if not bad: best = self.verifyBest(best,req_time_block) if len(best) >= len(required): numCredits = self.getNumCredits(best) # if the best schedule has a valid amount of credits wanted, add schedule if minNumCredits <= numCredits <= maxNumCredits: all_combos += [best] # if more courses can be added if (numCredits < maxNumCredits): num_needed = maxNumCredits - numCredits # if gen eds are wanted, add gen eds if len(req_geneds) + len(preferred_geneds) > 0: for gened in range(len(req_geneds)): for section in best: tmp_req_geneds = req_geneds tmp_pref_geneds = preferred_geneds classQuery = "SELECT abbreviation from GenEdFulfillments, GenEds where ((GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and abbreviation = %s) or (GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and also_fulfills = %s)) and GenEdFulfillments.section_id = %s" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(classQuery % (str("'"+req_geneds[gened]+"'"),str("'"+req_geneds[gened]+"'"),str("'"+str(section)+"'"))) abbs = [] for (abbreviation) in cursor: abbs.append(str(abbreviation[0])) for ge in abbs: if ge in tmp_req_geneds: req_geneds.remove(ge) if ge in tmp_pref_geneds: preferred_geneds.remove(ge) cursor.close() cnx.close() possible_gened_classes = {} for gened in range(len(req_geneds)): classQuery = "SELECT section_id from GenEdFulfillments, GenEds where (GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and abbreviation = %s) or (GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and also_fulfills = %s)" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(classQuery % (str("'"+req_geneds[gened]+"'"),str("'"+req_geneds[gened]+"'"))) classes = [] for (section_id) in cursor: classes.append(section_id[0]) possible_gened_classes[req_geneds[gened]] = classes cursor.close() cnx.close() for gened in range(len(preferred_geneds)): classQuery = "SELECT section_id from GenEdFulfillments, GenEds where (GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and abbreviation = %s) or (GenEds.gen_ed_id = GenEdFulfillments.gen_ed_id and also_fulfills = %s)" cnx = cnx_pool.get_connection() cursor = cnx.cursor() cursor.execute(classQuery % (str("'"+preferred_geneds[gened]+"'"),str("'"+preferred_geneds[gened]+"'"))) classes = [] for (section_id) in cursor: classes.append(section_id[0]) possible_gened_classes[preferred_geneds[gened]] = classes cursor.close() cnx.close() # find common geneds doubles = {} for ge in possible_gened_classes: for ge2 in possible_gened_classes: if ge != ge2: for class1 in possible_gened_classes[ge]: for class2 in possible_gened_classes[ge2]: if class1 == class2: key = ge+" "+ge2 if key in doubles: doubles[key].append(class1) else: doubles[key] = [class1] keys = [] for key in doubles: one,two = key.split() new = set((one,two)) if new not in keys: keys.append(new) for k in keys: delKey = list(k)[0] + " " + list(k)[1] del doubles[delKey] combo = [] for b in best: combo.append([b]) tmp_req_geneds = req_geneds tmp_pref_geneds = preferred_geneds for ge in doubles: one,two = ge.split() if num_needed > 0 and ((one in req_geneds) or (one in preferred_geneds)) and ((two in req_geneds) or (two in preferred_geneds)): combo.append(doubles[ge]) num_needed -= 1 if one in tmp_req_geneds: req_geneds.remove(one) if one in tmp_pref_geneds: preferred_geneds.remove(one) if two in tmp_req_geneds: req_geneds.remove(two) if two in tmp_pref_geneds: preferred_geneds.remove(two) for x in possible_gened_classes: if num_needed > 0 and x in req_geneds: combo.append(possible_gened_classes[x]) num_needed -= 1 for x in possible_gened_classes: if num_needed > 0 and x in preferred_geneds: combo.append(possible_gened_classes[x]) num_needed -= 1 all_combos += list(itertools.product(*combo)) else: error = "There was a conflict with required courses/sections" # shuffle list of all potential schedules # set seed so it is the same everytime random.seed(0) random.shuffle(all_combos) schedules = [] pos = index for x in range(limit): if pos < len(all_combos)-1: pos += 1 # x for index current = all_combos[pos] while self.verify(current, maxNumCredits,minNumCredits,req_time_block) == False and pos < len(all_combos)-1: pos += 1 current = all_combos[pos] if pos <= len(all_combos)-1: if self.verify(current, maxNumCredits,minNumCredits,req_time_block) == False: if self.getNumCredits(current) < minNumCredits: error = "You do not meet the desired credits, either add more criteria or lower minimum credit amount" s = ScheduleCreationObject(current,pos,error) schedules.append(s.__dict__) else: error = "No valid schedules can be made from the given criteria" s = ScheduleCreationObject([],pos,error) else: error = "No errors" schedule = ScheduleCreationObject(self.verify(current, maxNumCredits,minNumCredits,req_time_block),pos,error) schedules.append(schedule.__dict__) if schedules == []: if error == "No errors": error = "No valid schedules can be made from the given criteria" s = ScheduleCreationObject([],pos,error) schedules.append(s.__dict__) return (schedules)