Esempio n. 1
0
 def change_sgstatus(self, sg_url):
     try:
         query = "SELECT SgStatus from `STUDY_GROUP` WHERE SgUrl = %s"
         self.sesh.cursor.execute(query, sg_url)
         result = self.sesh.cursor.fetchone()
         print(result)
         status = result['SgStatus']
         print("Current Status is: ", status)
         while(True):
             status = input("Enter Status [Completed/Active/Planned]: ")
             if(status == "Completed" or status == "Active" or status == "Planned"):
                 break
             else:
                 print("Invalid input. Try again!")
         update = "UPDATE `STUDY_GROUP` SET SgStatus = %s WHERE SgUrl = %s" 
         self.sesh.cursor.execute(update, (status, sg_url))
         self.sesh.connection.commit()
     
     except Exception as e:
         #print(e)
         univutil.ask_user_action(self.change_sgstatus)
     else:
         print("Status updated successfully!")
         input()
     return
Esempio n. 2
0
    def create_event(self, sg_url):
        try:
            query = "SELECT COUNT(*) FROM `SG_EVENT` WHERE SgUrl = %s"
            self.sesh.cursor.execute(query, sg_url)
            event_number = self.sesh.cursor.fetchone()["COUNT(*)"]
            attrE = {
                "Event Title" : "",
                "Event Info." : ""
            }
            for attribute in attrE:
                    while(attrE[attribute]==""):
                        attrE[attribute] = input(attribute+": ")
            
            query = "INSERT INTO `SG_EVENT` (SgUrl, EventNum, EventTitle, EventInfo) VALUES (%s, %s, %s, %s);"
            self.sesh.cursor.execute(query, (sg_url, event_number, attrE["Event Title"], attrE["Event Info."]))
            self.sesh.connection.commit()

        except Exception as e:
            #print(e)
            univutil.ask_user_action(self.create_event)

        else:
            selection = 0
            while(selection!="1" and selection!="2"):
                print("Enter 1 for Meet and 2 for Target: ")
                selection = input()
            
            if(selection=="1"):
                self.create_meet(sg_url, event_number)
            elif(selection=="2"):
                self.create_target(sg_url, event_number)
        input()
        return
Esempio n. 3
0
    def befriend(self):
        try:
            attributes = {
                "Friend2Name" : "",
                "Friend2DNum" : ""
            }
            for attribute in attributes:
                while(attributes[attribute]==""):
                    if(attribute == 'Friend2DNum'):
                        attributes[attribute] = int(input(attribute+": "))
                    else:
                        attributes[attribute] = input(attribute+": ")
                        
                        
            
            query = "INSERT INTO `FRIENDS_WITH` (Friend1Name,Friend1DNum,Friend2Name,Friend2DNum) VALUES (%s,%s,%s,%s)" 
            self.sesh.cursor.execute(query, (attributes["Friend2Name"],attributes["Friend2DNum"],self.current_user[0],self.current_user[1]))
            self.sesh.cursor.execute(query, (self.current_user[0],self.current_user[1], attributes["Friend2Name"],attributes["Friend2DNum"]))
            self.sesh.connection.commit()

        except Exception as e:    
            #print(e)
            univutil.ask_user_action(self.befriend)

        return
Esempio n. 4
0
    def rate_sg(self):
        try:
            sgquery = "SELECT SgUrl FROM MEMBER_OF WHERE UserSgRole = 'Member' AND UserName = '******' AND DNum = %d" % (self.current_user[0], self.current_user[1])
            self.sesh.cursor.execute(sgquery)
            if(self.sesh.cursor.rowcount==0):
                print("You are not a member of any group :(")
                return
            result = self.sesh.cursor.fetchall()
            print("You are a member of %d study groups" % (self.sesh.cursor.rowcount))
            for sg in result:
                print(sg["SgUrl"])

            sg_url = input("Enter URL of Study Group to rate: ")
            flag = 0
            for sg in result:
                if(sg["SgUrl"] == sg_url):
                    flag = 1

            if(flag==0):
                print("You are not a member of this group :(")
                return
            else:
                print("Member rights authenticated!")

            rating = -1
            while(rating < 0 or rating > 10):
                rating = int(input("Enter rating [0-10]: "))
            query = "UPDATE MEMBER_OF SET UserSgRating = %d WHERE UserName = '******' AND DNum = %d AND SgUrl = '%s'" % (rating, self.current_user[0], self.current_user[1], sg_url)
            self.sesh.cursor.execute(query)
            self.sesh.cursor.connection.commit()
            input()
        except Exception as e:
            #print(e)
            univutil.ask_user_action(self.rate_sg)
Esempio n. 5
0
    def update_interest(self):
        try:
            values = self.sesh.see_all("SUBJECT")
            choice = input("Pick subject index: ")
            while(True):
                try:
                    choice = int(choice)
                    SubName = values[choice-1]['SubName']
                    break
                except:
                    print("Error. Invalid index")
            InterestType = ""
            while(InterestType == ""):
                InterestType = input('Modified Interest Type["Research" ,"Professional" , "Major" ,"Minor" ,"Casual"]: ')
                if InterestType not in ["Research" ,"Professional" , "Major" ,"Minor" ,"Casual"]:
                    InterestType = ""
            query = "UPDATE `HAS_INTEREST_IN` SET InterestType = '%s' WHERE UserName = '******' and DNum = %d and SubName = '%s'" %(InterestType,self.current_user[0],self.current_user[1],SubName)
            self.sesh.cursor.execute(query)
            self.sesh.connection.commit()

        except Exception as e:    
            #print(e)
            univutil.ask_user_action(self.update_interest)

        return
Esempio n. 6
0
 def show_friends_details(self):
     try:
         name = input("Enter friends name: ")
         all_users =  f'SELECT CONCAT_WS(" ",FName, MName, SName) as Name, UserName, DNum FROM USER WHERE CONCAT(FName, MName, SName) like \'%{name}%\';'
         self.sesh.cursor.execute(all_users)
         result = self.sesh.cursor.fetchall()
         if(univutil.table_format(result) == 0):
             print("No user with that name")
         input()
     except Exception as e:
         univutil.ask_user_action(self.show_friends_details)
Esempio n. 7
0
 def view_user_posts(self):
     try:
         username = input("Enter UserName: "******"Enter DNum: "))
         query = "SELECT PostTitle, PostContent, TimeStamp FROM POST WHERE UserName = '******' AND DNum = %d" % (username, dnum)
         self.sesh.cursor.execute(query)
         result = self.sesh.cursor.fetchall()
         univutil.table_format(result)
         input()
     except Exception as e:
         #print(e)
         univutil.ask_user_action(self.view_user_posts)
 def delete_course(self):
     try:
         values = self.sesh.see_all("COURSE")
         choice = input("Enter course index: ")
         choice = int(choice)
         cname, corg, cplat = values[choice - 1]['CourseName'], values[
             choice - 1]['CourseOrg'], values[choice - 1]['CoursePlatform']
         sure = input("Are you sure? [y/n]: ")
         if (sure == "n"):
             return "Course not deleted"
         sql_query = "DELETE FROM `COURSE_DIFFICULTY` WHERE CourseName = %s AND CourseOrg = %s AND CoursePlatform = %s"
         self.sesh.cursor.execute(sql_query, (cname, corg, cplat))
         self.sesh.connection.commit()
     except:
         univutil.ask_user_action(self.delete_course)
Esempio n. 9
0
    def update_usercontrib(self, sg_url):
        try:
            os.system("clear")
            print("User List: ")
            userquery = "SELECT UserName, DNum, UserSgRole FROM MEMBER_OF WHERE SgUrl = '%s'" % (sg_url)
            self.sesh.cursor.execute(userquery)
            result = self.sesh.cursor.fetchall()
            univutil.table_format(result)
            
            roles = ["Member", "Admin"]
            roleidx = 0
            flag = 0
            while(flag==0):
                username = input("Enter username: "******"Enter dnum"))
                for r in result:
                    if(r["UserName"] == username and r["DNum"] == dnum):
                        flag = 1
                        if(r["UserSgRole"] == "Admin"):
                            roleidx = 1
                if(flag==0):
                    print("No such user in study group, try again!")

            contrib = -1
            while(contrib < 0 or contrib > 10):
                contrib = int(input("Contribution rating of user [1-10]: "))
            contribquery = "UPDATE MEMBER_OF SET UserSgContrib = %s WHERE SgUrl = %s AND UserName = %s AND DNum = %s;" 
            self.sesh.cursor.execute(contribquery, (contrib, sg_url, username, dnum))

            selection = 'X'
            while(selection != 'Y' and selection != 'N'):
                selection = input(f'Flip user role from {roles[roleidx]} to {roles[1-roleidx]} [Y/N]: ')
            if(selection == 'Y'):
                rolequery = "UPDATE MEMBER_OF SET UserSgRole = %s WHERE SgUrl = %s AND UserName = %s AND DNum = %s;"
                self.sesh.cursor.execute(rolequery, (roles[1-roleidx], sg_url, username, dnum))
            
            self.sesh.cursor.connection.commit()

        except Exception as e:
            #print(e)
            univutil.ask_user_action(self.update_usercontrib)

        else:
            print("Contribution updated succesfully!")
            input()

        return
Esempio n. 10
0
    def make_post(self):
        try:
            query = "SELECT COUNT(*) FROM `POST` WHERE UserName = %s AND DNum = %s"
            self.sesh.cursor.execute(query, (self.current_user[0], self.current_user[1]))
            post_number = self.sesh.cursor.fetchone()["COUNT(*)"]

            attrP = {
                "Post Title" : "",
                "Post Content" : ""
            }
            for attribute in attrP:
                while(attrP[attribute]==""):
                    attrP[attribute] = input(attribute+": ")

            post_type = ""
            while(post_type!="Review" and post_type!="Blog"):
                post_type = input("Type [Review/Blog]: ")
            sql = "INSERT INTO `POST` "
            
            if(post_type == "Review"):
                attrR = {
                    "CourseID" : "",
                    "Rate course [1-10]" : ""
                }
                for attribute in attrR:
                    while(attrR[attribute]==""):
                        attrR[attribute] = input(attribute+": ")
                sql += "(`UserName`, `DNum`, `PostNumber`, `PostTitle`, `PostContent`, "
                sql += "`Type`, `CourseID`, `ReviewRating`) VALUES ( %s, %s, %s, %s, %s, %s, %s, %s );"
                self.sesh.cursor.execute(sql, (self.current_user[0], self.current_user[1], post_number, attrP["Post Title"],
                                    attrP["Post Content"], post_type, attrR["CourseID"], attrR["Rate course [1-10]"]))
            else:
                sql += "(`UserName`, `DNum`, `PostNumber`, `PostTitle`, `PostContent`, `Type`) VALUES ( %s, %s, %s, %s, %s, %s );"
                self.sesh.cursor.execute(sql, (self.current_user[0], self.current_user[1], post_number, attrP["Post Title"],
                                    attrP["Post Content"], post_type))
                tag = input("Enter tag: ")
                tag_sql = "INSERT INTO BLOGTAG VALUES(%s, %s, %s, %s)"
                self.sesh.cursor.execute(tag, self.current_user[0], self.current_user[1], post_number)
            self.sesh.connection.commit()
            input()
        except Exception as e:
            #print(e)
            univutil.ask_user_action(self.make_post)

        return
Esempio n. 11
0
    def create_pin(self, sg_url):
        try:
            attrP = {
                "Pinned Info" : "",
            }
            for attribute in attrP:
                while(attrP[attribute]==""):
                    attrP[attribute] = input(attribute+": ")
            
            query = "INSERT INTO `PINS` (SgUrl, PinDetails) VALUES (%s, %s)"
            self.sesh.cursor.execute(query, (sg_url, attrP["Pinned Info"]))
            self.sesh.connection.commit()

        except Exception as e:
            #print(e)
            univutil.ask_user_action(self.create_pin)    
        input()
        return
Esempio n. 12
0
    def add_subject(self):
        try:
            print('ADDING SUBJECT')

            attributes = {"Subject Name: ": ""}

            for attribute in attributes:
                while (attributes[attribute] == ""):
                    attributes[attribute] = input(attribute)

            query = "INSERT INTO `SUBJECT` VALUES ('%s');" % (
                attributes["Subject Name: "])
            self.sesh.cursor.execute(query)
            self.sesh.connection.commit()
            return "Added subject"
        except Exception as e:
            ##print(e)
            univutil.ask_user_action(self.add_subject)
Esempio n. 13
0
    def add_user(self):
        try:
            os.system('clear')
            print("ADD NEW USER")
            username = input("Username*: ")
            dnum = self.sesh.get_number(username, "USER", "UserName")
            fname = input("First Name*: ")
            mname = input("Middle Name: ")
            if (mname == ""):
                mname = None
            lname = input("Last Name*: ")
            dob = input("Date of Birth (YYYY-MM-DD))*: ")
            email = input("Email*: ")
            password = input("Password*: ")
            sql = "INSERT INTO `USER` values (%s, %s, %s, %s, %s, %s, %s, %s);"
            self.sesh.cursor.execute(
                sql,
                (username, dnum, fname, mname, lname, dob, email, password))

            values = self.sesh.see_all("LANGUAGE")
            numberOfLanguagesKnown = 0
            while (numberOfLanguagesKnown <= 0):
                numberOfLanguagesKnown = int(
                    input("Enter Number of languages known[atleast one]: "))
            for _ in range(numberOfLanguagesKnown):
                self.add_languageKnown(username, dnum, values)

            values = self.sesh.see_all("SUBJECT")
            numberOfSubjectInterest = 0
            while numberOfSubjectInterest <= 0:
                numberOfSubjectInterest = int(
                    input("Enter Number of Subject Interest[atleast one]: "))
            for _ in range(numberOfSubjectInterest):
                self.add_subjectInterest(username, dnum, values)
            self.sesh.connection.commit()
            print(f'Registered succesfully! Username: {username} DNum: {dnum}')
            input()

        except Exception as e:
            #print(e)
            univutil.ask_user_action(self.add_user)

        return "Added user"
Esempio n. 14
0
    def create_target(self, sg_url, event_num):
        try:
            attrT = {
                "Deadline YYYY/MM/DD HH/MI/SS" : "",
            }
            for attribute in attrT:
                while(attrT[attribute]==""):
                    attrT[attribute] = input(attribute+": ")
                
            query = "INSERT INTO `TARGET` (SgUrl, EventNum, TargetDeadline) VALUES ('%s', '%s', '%s')" % (sg_url, event_num, attrT["Deadline YYYY/MM/DD HH/MI/SS"])
            self.sesh.cursor.execute(query)
            self.sesh.connection.commit()
            print("Added Event Succesfully!")
            input()

        except Exception as e:
            #print(e)
            univutil.ask_user_action(self.create_target)
        
        return
Esempio n. 15
0
    def add_language(self):
        try:
            print("ADDING LANGUAGE")
            attributes = {'LangCode': "", 'LangName': ""}

            for attribute in attributes:
                while (attributes[attribute] == ""):
                    attributes[attribute] = input(attribute + ": ")
                    if attribute == 'LangCode':
                        while (len(attributes[attribute]) != 3):
                            print("LangCode should be of 3 characters")
                            attributes[attribute] = input(attribute + ": ")

            query = "INSERT INTO `LANGUAGE` VALUES ('%s','%s')" % (
                attributes['LangCode'], attributes['LangName'])
            self.sesh.cursor.execute(query)
            self.sesh.connection.commit()
            return "Added subject"
        except Exception as e:
            #print(e)
            univutil.ask_user_action(self.add_language)
Esempio n. 16
0
    def create_meet(self, sg_url, event_num):
        try:
            attrM = {
                "Meet Time YYYY/MM/DD HH/MI/SS" : "",
                "Meet Duration (mins)" : ""
            }
            for attribute in attrM:
                while(attrM[attribute]==""):
                    attrM[attribute] = input(attribute+": ")
                
            query = "INSERT INTO `MEET` (SgUrl, EventNum, MeetTime, MeetDuration) VALUES ('%s', '%s', '%s', '%s')" % (sg_url, event_num, attrM["Meet Time YYYY/MM/DD HH/MI/SS"], attrM["Meet Duration (mins)"])
            self.sesh.cursor.execute(query)
            self.sesh.connection.commit()

        except Exception as e:
            #print(e)
            univutil.ask_user_action(self.create_meet)
        
        else:
            print("Added Event Succesfully!")
        input()
        return
Esempio n. 17
0
    def update_post(self):
        try:
            query = "SELECT `PostNumber`, `PostTitle`, `PostContent` FROM `POST` WHERE `UserName` = '%s' AND `DNum` = %d" % (self.current_user[0], self.current_user[1])
            self.sesh.cursor.execute(query)
            result = self.sesh.cursor.fetchall()
            num_posts = self.sesh.cursor.rowcount
            if(num_posts == 0):
                print("Sorry, no posts exist to be updated!")
                return
            print(num_posts, "posts currently exist!")
            
            post_num = num_posts
            univutil.table_format(result)
            while(post_num >= num_posts):
                post_num = int(input("Enter the post number: "))

            print("Post Title: ", result[post_num]["PostTitle"])
            print("Post Content: ", result[post_num]["PostContent"])
            print("Now, please enter your edited post details")

            attrP = {
                "Post Title" : "",
                "Post Content" : ""
            }
            for attribute in attrP:
                while(attrP[attribute]==""):
                    attrP[attribute] = input(attribute+": ")
            attrP["Post Title"] += " [edited]"

            update = "UPDATE `POST` SET `PostTitle` = %s, `PostContent` = %s WHERE `UserName` = %s AND `DNum` = '%s' AND `PostNumber` = '%s'"
            self.sesh.cursor.execute(update, (attrP["Post Title"], attrP["Post Content"], self.current_user[0], self.current_user[1], post_num))
            self.sesh.connection.commit()
            input()

        except Exception as e:
            #print(e)
            univutil.ask_user_action(self.update_post)
        
        return
Esempio n. 18
0
    def delete_post(self):
        try:
            query = "SELECT `PostNumber`, `PostTitle`, `PostContent` FROM `POST` WHERE `UserName` = '%s' AND `DNum` = %d" % (self.current_user[0], self.current_user[1])
            self.sesh.cursor.execute(query)
            result = self.sesh.cursor.fetchall()
            num_posts = self.sesh.cursor.rowcount
            if(num_posts == 0):
                print("Sorry, no posts exist to be deleted!")
                return
            print(num_posts, "posts currently exist!")
            
            univutil.table_format(result)
            post_num = num_posts
            while(post_num >= num_posts):
                post_num = int(input("Enter the post number to delete: "))
            
            print("Are you sure you want to delete the following post: ")
            print("Post Title: ", result[post_num]["PostTitle"])
            print("Post Content: ", result[post_num]["PostContent"])
            confirm = 'X'
            while(confirm != 'Y' and confirm != 'N'):
                confirm = input("I'm sure, delete [Y/N]: ")
            if(confirm == 'N'):
                return

            sql = "DELETE FROM `POST` "
            sql += "WHERE UserName = '******' AND DNum = '%s' AND PostNumber = '%s'" % (self.current_user[0], self.current_user[1], post_num)
            self.sesh.cursor.execute(sql)
            self.sesh.connection.commit()
            input()

        except Exception as e:
            #print(e)
            univutil.ask_user_action(self.delete_post)

        return
Esempio n. 19
0
    def add_course(self):
        try:
            os.system("clear")
            print("ADD NEW COURSE")
            attributes = {
                "Course Name: ": "",
                "Course Org: ": "",
                "Course Platform: ": "",
                "Weekly Course Hours: ": "",
                "Course Duration: ": ""
            }
            courseid_sql = "SELECT LAST_INSERT_ID();"

            coursedifficulty = ""
            for attribute in attributes:
                while (attributes[attribute] == ""):
                    attributes[attribute] = input(attribute)
            while (True):
                coursedifficulty = input(
                    "Course Difficulty [1. Beginner/2. Intermediate/3. Expert]: "
                )
                if (coursedifficulty in ["1", "2", "3"]):
                    coursedifficulty = ["Beginner", "Intermediate",
                                        "Expert"][int(coursedifficulty) - 1]
                    break
            sql_difficulty = "INSERT INTO `COURSE_DIFFICULTY` (`CourseName`, `CourseOrg`, `CoursePlatform`, `CourseDifficulty`) values (%s, %s, %s, %s);"
            sql_course = "INSERT INTO `COURSE` (`CourseName`, `CourseOrg`, `CoursePlatform`, `CourseHours`, `CourseDuration`) values (%s, %s, %s, %s, %s);"

            self.sesh.cursor.execute(
                sql_difficulty,
                tuple(attributes.values())[:3] + (coursedifficulty, ))
            self.sesh.cursor.execute(sql_course, tuple(attributes.values()))
            self.sesh.cursor.execute(courseid_sql)
            courseid = self.sesh.cursor.fetchone()['LAST_INSERT_ID()']

            while (True):
                subdub = ""
                values = self.sesh.see_all("LANGUAGE")
                choice = input("Pick language index: ")
                while (True):
                    try:
                        choice = int(choice)
                        lang = values[choice - 1]['LangCode']
                        break
                    except:
                        print("Error. Invalid index")
                while (subdub not in ["Native", "Sub", "Dub"]):
                    subdub = input("Language support [Native/Sub/Dub]: ")
                if (subdub == "Native"):
                    subdub = None
                sql_lang = "INSERT INTO `USED_FOR` values (%s, %s, %s)"
                self.sesh.cursor.execute(sql_lang, (lang, courseid, subdub))
                cont = input("More languages? [y/n]: ")
                if (cont == "n"):
                    break

            while (True):
                values = self.sesh.see_all("SUBJECT")
                choice = input("Pick subject index: ")
                while (True):
                    try:
                        choice = int(choice)
                        subject = values[choice - 1]['SubName']
                        break
                    except:
                        print("Error. Invalid index")
                sql_sub = "INSERT INTO `CONTAINS` values(%s, %s)"
                self.sesh.cursor.execute(sql_sub, (subject, courseid))
                cont = input("More subjects? [y/n]: ")
                if (cont == "n"):
                    break

            instructor = input("Add course instructor? [y/n]: ")
            while (instructor == "y"):
                courseinstructor = ""
                while (courseinstructor == ""):
                    courseinstructor = input("Instructor Name: ")
                sql_instructor = "INSERT INTO `COURSE_INSTRUCTOR` values (%s, %s)"
                self.sesh.cursor.execute(sql_instructor,
                                         (courseinstructor, courseid))
                if (input("More instructors? [y/n]: ") == "n"):
                    break

            prereq = input("Add course prerequisites? [y/n]: ")
            while (prereq == "y"):
                sql_query = f'SELECT CourseID, CourseName FROM `COURSE`;'
                self.sesh.cursor.execute(sql_query)
                result = self.sesh.cursor.fetchall()
                univutil.table_format(result)
                choice = input("Select course index: ")
                while (True):
                    try:
                        choice = int(choice)
                        courseprerequisite = values[choice - 1]['CourseID']
                        break
                    except:
                        print("Error. Invalid index")
                courseprerequisite_importance = ""
                while (courseprerequisite_importance
                       not in ["Helpful", "Essential"]):
                    courseprerequisite_importance = input(
                        "Prequisite importance [Helpful/Essential]: ")
                sql_instructor = "INSERT INTO `PREREQUISITE` values (%s, %s, %s)"
                self.sesh.cursor.execute(sql_instructor,
                                         (courseid, courseprerequisite,
                                          courseprerequisite_importance))
                if (input("More preqrequisites? [y/n]: ") == "n"):
                    break

            self.sesh.connection.commit()
        except Exception as e:
            #print(e)
            univutil.ask_user_action(self.add_course)
Esempio n. 20
0
    def enroll(self): # This would be a insertion into the quarternary relationship along with creating study_group if reqd.
        try:
            print("You can enroll in a new course (and a study group) or a new study group for a course already being taken.")
            result = self.sesh.see_all("COURSE")
            courseid = int(input("CourseID: "))
            while(courseid not in [(lambda x: result[x]["CourseID"])(i) for i in range(len(result))]):
                courseid = int(input("CourseID: "))
            coursequery = "INSERT IGNORE INTO `TAKES` (UserName, DNum, CourseID) VALUES (%s, %s, %s);" 
            self.sesh.cursor.execute(coursequery, (self.current_user[0], self.current_user[1], courseid)) # This ignores if entry in TAKES already exists^
            print("Available study groups for this course:")
            values = self.showSgForCourse(courseid)
            new_sg = 'X'
            if(values == 0):
                print("No study groups for this course.")
                while(True):
                    new_sg = input("Create new study group? [Y/N]")
                    if(new_sg == "N"):
                        return
                    elif(new_sg == "Y"):
                        new_sg = "N"
                        break
            while(new_sg != 'N' and new_sg != 'E'):
                new_sg = input("Do you want to create your own study group (N) or join an existing one [E]: ")
            if(new_sg == "E"):
                sg = input("Study Group URL: ")
                while(sg not in [(lambda x: values[x]["SgUrl"])(i) for i in range(len(values))]):
                    sg = input("Enter valid study group URL: ")

            if(new_sg == 'N'):
                sg = input("Study Group URL: ")
                while(True):
                    try:
                        sgcreate = "INSERT INTO STUDY_GROUP (`SgUrl`) VALUES (%s);"
                    except:
                        print("Invalid study group URL. It might already exist.")
                        input()
                    break
                self.sesh.cursor.execute(sgcreate, sg)
            sgquery = "INSERT IGNORE INTO `MEMBER_OF` (UserName, DNum, SgUrl, UserSgRole) VALUES (%s, %s, %s, %s);"
            self.sesh.cursor.execute(sgquery, (self.current_user[0], self.current_user[1], sg, "Admin"))
            print("Created a new study group succesfully!")
                
            print("Available languages for this study group")
            langquery = "SELECT DISTINCT LangCode FROM PARTICIPATES_IN WHERE SgUrl = '%s'" % (sg)
            self.sesh.cursor.execute(langquery)
            result = self.sesh.cursor.fetchall()
            lfound = 0
            if(univutil.table_format(result) == 0):
                values = self.sesh.see_all("LANGUAGE")
                while(True):
                    choice = input("Pick language index: ")
                    try:
                        choice = int(choice)
                        langcode = values[choice-1]['LangCode']
                        lfound = 1
                        break
                    except:
                        print("Error. Invalid index")
            while(lfound==0):
                langcode = input("Language to participate in study_group (langcode) [N for none]: ")
                if(langcode == "N"):
                    print("Let's find a new study group.")
                    input()
                    return
                for i in range(self.sesh.cursor.rowcount):
                    if(result[i]["LangCode"]==langcode):
                        lfound=1
            
            query = "INSERT INTO PARTICIPATES_IN VALUES (%s, %s, %s, %s, %s);"
            self.sesh.cursor.execute(query, (self.current_user[0], self.current_user[1], sg, langcode, courseid))
            self.sesh.connection.commit()
            print("Enrolled in Course: %d as a member of Study Group: %s in language: %s succesfully!" % (courseid, sg, langcode))
            input()
        except Exception as e:
            #print(e)
            univutil.ask_user_action(self.enroll)
        
        return   
Esempio n. 21
0
    def addoption_studygroup(self, sg_url):
        print("Choose a Course and it's corresponding discussion language! Atleast one must be new for the study group")
        courseid = -1
        langcode = ""
        
        try:        
            #[TODO:] Validate if CourseID and Lang exist in DB or Display possible choices
            coursequery = "SELECT DISTINCT `CourseID` FROM `PARTICIPATES_IN` WHERE `SgUrl` = '%s'" % sg_url
            self.sesh.cursor.execute(coursequery)
            course_count = self.sesh.cursor.rowcount
            course_sg = self.sesh.cursor.fetchall()
            langquery = "SELECT DISTINCT `LangCode` FROM `PARTICIPATES_IN` WHERE `SgUrl` = '%s'" % sg_url
            self.sesh.cursor.execute(langquery)
            lang_count = self.sesh.cursor.rowcount
            lang_sg = self.sesh.cursor.fetchall()
            lang_new_flag = 1
            course_new_flag = 1

            values = self.sesh.see_all("COURSE")
            while(True):
                try:
                    choice = input("Pick course index: ")
                    choice = int(choice)
                    courseid = values[choice-1]['CourseID']
                    break
                except:
                    print("Error. Invalid index")
 
            for i in range(course_count):
                if(course_sg[i]["CourseID"] == courseid):
                    course_new_flag = 0
                    break           
            values = self.sesh.see_all("LANGUAGE")
            while(True):
                try:
                    choice = input("Pick language index: ")
                    choice = int(choice)
                    langcode = values[choice-1]['LangCode']
                    break
                except:
                    print("Error. Invalid index")
            for i in range(lang_count):
                if(lang_sg[i]["LangCode"] == langcode):
                    lang_new_flag = 0
                    break
                     

            if(course_new_flag == 0 and lang_new_flag == 0):
                print("You aren't inserting anything new!")
                input()
                return

            query = "INSERT INTO `PARTICIPATES_IN` VALUES ('%s', %d, '%s', '%s', %d)" % (self.current_user[0], self.current_user[1], sg_url, langcode, courseid)
            self.sesh.cursor.execute(query)
            self.sesh.connection.commit()
            if(course_new_flag):
                print("Added a new course succesfully!")
            if(lang_new_flag):
                print("Added a new language succesfully!")
            input()
        except Exception as e:
            #print(e)
            univutil.ask_user_action(self.addoption_studygroup)

        else: # Also add User - Course to User TAKES Course
            try:
                coursequery = "INSERT INTO `TAKES` (UserName, DNum, CourseID VALUES) VALUES (%s, %d, %d)" % (self.current_user[0], self.current_user[1], courseid)
                self.sesh.cursor.execute(coursequery)
                self.sesh.connection.commit()
            except Exception as e:
                pass