def session_record_landing(): if not check_login(): return redirect('/') if 'session_id' not in session: session['message'] = 'Failed to join session' return redirect('/dashboard') db = get_db() query = 'UPDATE syncing_logs SET is_active=0 WHERE user_id={};'.format(session['user']) du.db_query(db, query) args = dict() args['session_code'] = str(session['session_code']) args['class_code'] = str(session['class_code']) args['coding_template_name'] = str(session['coding_template_name']) args['timer_seconds'] = int(session['timer_seconds']) args['strict_timer'] = int(session['strict_timer']) args['randomize_order'] = int(session['randomize_order']) args['student_id'] = session['student_id'] query = 'UPDATE coding_logs SET coding_time=now() WHERE id={};'.format(session['coding_log_id']) du.db_query(db, query) return render_template('coding.html', args=args)
def join_session(): if not check_login(): return redirect('/') # get database handle db = get_db() session_id = int('0x' + request.form['session_code'][2:], 0) query = 'SELECT * FROM sessions WHERE id = {}'.format(session_id) res = du.db_query(db, query) if len(res) == 0: session['message'] = 'Session not found' return redirect('/dashboard') class_id = res[0][1] # leave any existing sessions query = 'UPDATE session_logs SET is_active=0 WHERE user_id={};'.format(session['user']) du.db_query(db, query) # join the session query = 'INSERT INTO session_logs (session_id, user_id) VALUES ({},{});'.format(session_id, session['user']) du.db_query(db, query) session['session_id'] = session_id session['class_id'] = class_id return redirect('/session/dashboard')
def dashboard(): # TODO: display recent sessions # TODO: add new 'session info' page to display inforamtion and stats on recent sessions if not check_login(): session['message'] = 'You must be logged in to view the dashboard!' return redirect('/') if session.get('session_id'): session.pop('session_id') remove_nonpersistent() # clean leftover syncing requests from previous sessions db = get_db() query = 'UPDATE session_logs SET is_active=0 WHERE user_id = {} and is_active = 1;'.format(session['user']) du.db_query(db, query) query = 'UPDATE syncing_logs SET is_active=0 WHERE user_id = {} and is_active = 1;'.format(session['user']) du.db_query(db, query) # display message if available msg = '' if 'message' in session: msg = session['message'] session['message'] = '' # render dashboard page return render_template('dashboard.html', message=msg)
def add_class_landing(): # ensure user is logged in and redirect if not if 'user' not in session: return redirect('/dashboard') # get database handle db = get_db() # find the last unfinished class entry from the current user and use this if found query = 'SELECT * FROM classrooms WHERE code IS NULL AND creator_user_id = {};'.format(session['user']) res = du.db_query(db, query) if len(res) == 0: # no unfinished logs were found, create a new log query = 'INSERT INTO classrooms (creator_user_id) VALUES ({});'.format(session['user']) du.db_query(db, query) # select the newly added row (id will be used for class code) query = 'SELECT * FROM classrooms WHERE code IS NULL AND creator_user_id = {};'.format(session['user']) res = du.db_query(db, query) # generate the class code: simply 'CL' followed by the hex of row id from the classrooms table code = 'CL' + hex(res[0][0])[2:] # render class creation page return render_template('addclass.html', code=code)
def force_start_sync_call(): args=dict() db = get_db() print("I AM IN FORCE SYNC CALL") query='SELECT coder_user_id from sync_session_records where session_id={} and ready=\'{}\';'.format(session['coding_session'],'no') res = du.db_query(db, query) not_ready_users=[] for i in range(len(res)): t=res[i] print(t[0]) not_ready_users.append(t[0]) args['not_ready_users']= not_ready_users s=session['coding_session'] query='DELETE from sync_session_records where session_id={} and ready=\'{}\' and role={};'.format(session['coding_session'],'no',2) du.db_query(db, query) for i in not_ready_users: query='INSERT INTO kicked_out (coder_user_id,session_id) ' \ 'VALUES ({},{});'.format(i, session['coding_session']) du.db_query(db, query) print("Finished kicking out") args['action'] = '2' # syncing args['class_id'] = session['class_code'] args['student_id'] = session['current'] args['role']=1 print(args) return render_template('session.html', args=args)
def earliest_action_time(db, date, class_section): _vars, _query = du.read_var_text_file(SQL_FOLDER + 'earliest_action_time.sql', sep=' ') _vars[':student_class_section_id'] = str(class_section) _vars[':date'] = date print("STR:", str(du.db_query(db, _query, _vars))) return str(du.db_query(db, _query, _vars)[0][0])
def session_observe(): if not check_login(): return redirect('/') if 'session_id' not in session: session['message'] = 'Failed to join session' return redirect('/dashboard') if 'coding_log_id' in session: session.pop('coding_log_id') if 'syncing_id' in session: session.pop('syncing_id') db = get_db() query = 'UPDATE syncing_logs SET is_active=0 WHERE user_id={};'.format(session['user']) du.db_query(db, query) # determine who to display and show the observing menu (pre timer) args = dict() args['session_code'] = str(session['session_code']) args['class_code'] = str(session['class_code']) args['coding_template_name'] = str(session['coding_template_name']) if 'n_students' not in session: query = 'SELECT * FROM classrooms WHERE id = {};'.format(session['class_id']) res = du.db_query(db, query) session['n_students'] = int(res[0][6]) if 'student_id' not in session: session['student_id'] = 1 if not session['randomize_order'] else \ np.random.randint(1, session['n_students'] + 1, 1)[0] else: if len(request.args) > 0 or 'recorded' in session: session['student_id'] = session['student_id'] + 1 if not session['randomize_order'] else \ np.random.randint(1, session['n_students'] + 1, 1)[0] if session['student_id'] > session['n_students']: session['student_id'] = 1 if 'recorded' in session: session.pop('recorded') session['student_id'] = int(session['student_id']) args['student_id'] = session['student_id'] query = 'SELECT * FROM student_aliases ' \ 'WHERE class_id = {} AND student_id = {};'.format(session['class_id'],session['student_id']) res = du.db_query(db, query) alias_id = res[0][0] query = 'INSERT INTO coding_logs (session_id, class_id, user_id, student_id, student_alias_id) ' \ 'VALUES ({},{},{},{},{}) RETURNING id;'.format(session['session_id'], session['class_id'], session['user'], session['student_id'], alias_id) res = du.db_query(db, query) session['coding_log_id'] = int(res[0][0]) return render_template('observe.html', args=args)
def session_sync_landing(): if not check_login(): return redirect('/') if 'session_id' not in session: session['message'] = 'Failed to join session' return redirect('/dashboard') if 'student_id' not in session: session['message'] = 'Failed to join session' return redirect('/dashboard') db = get_db() # clean up any hanging syncing rows query = 'UPDATE syncing SET is_active=0 WHERE session_id={} ' \ 'AND (started_at IS NOT NULL OR now() > created_at + interval \'5 minutes\' ' \ 'OR id NOT IN (' \ 'SELECT id FROM ( ' \ 'SELECT s.id, sum(sg.is_active) AS n_active FROM syncing s ' \ 'LEFT OUTER JOIN syncing_logs sg ON sg.syncing_id = s.id ' \ 'GROUP BY s.id ' \ ') AS active WHERE n_active IS NOT NULL AND n_active > 0 ' \ '));'.format(session['session_id']) du.db_query(db, query) query = 'UPDATE syncing_logs SET is_active=0 WHERE user_id={};'.format(session['user']) du.db_query(db, query) # look for any active syncing query = 'SELECT * FROM syncing WHERE session_id={} AND is_active=1;'.format(session['session_id']) res = du.db_query(db, query) args = dict() args['is_leader'] = 0 # if none is found, create one if len(res) == 0: query = 'INSERT INTO syncing (session_id, creator_user_id, student_id) VALUES ({},{},{}) RETURNING id;'.format( session['session_id'], session['user'],session['student_id']) res = du.db_query(db, query) session['syncing_id'] = res[0][0] query = 'INSERT INTO syncing_logs (syncing_id, user_id, is_leader) VALUES ({},{},1)'.format( session['syncing_id'], session['user']) du.db_query(db, query) args['is_leader'] = 1 elif len(res) > 0: session['syncing_id'] = res[0][0] query = 'INSERT INTO syncing_logs (syncing_id, user_id, is_leader) VALUES ({},{},0)'.format( session['syncing_id'], session['user']) du.db_query(db, query) return render_template('sync.html', args=args)
def log_session(): # TODO: (very low priority) define codings in database table and create a coding builder # TODO: allow for offline recording of coding logs and update when reconnected args = dict() db = get_db() # get all the fields of the request form (observation codings) for i in request.form: args[i] = request.form[i] # define the string variables for easier sql generation str_vars = ['student_name', 'affect_state', 'focus'] args['class_id'] = session['class_id'] args['coder_user_id'] = session['user'] # find most recent empty log from user (will correspond with the row generated in the previous state) query = 'SELECT * FROM coding_logs WHERE log_state < 0 ORDER BY coding_timestamp DESC;' res = du.db_query(db,query) if len(res) == 0: # if no log is found, generate the full row var_list = list(args.keys())[0] val_list = '\'{}\''.format(args[list(args.keys())[0]]) if list(args.keys())[0] in str_vars else '{}'.format( args[list(args.keys())[0]]) for i in range(1, len(args.keys())): var_list += ',' + list(args.keys())[i] val_list += ',\'{}\''.format(args[list(args.keys())[i]]) if list(args.keys())[ i] in str_vars else ',{}'.format( args[list(args.keys())[i]]) query = 'INSERT INTO coding_logs (' + var_list + ') VALUES (' + val_list + ');' du.db_query(db,query) else: # empty corresponding log is found, fill in the missing information (and flip the sign of the log state) set_list = 'submission_timestamp=now(),log_state={}'.format(-1*res[0][17]) for i in range(len(args.keys())): set_list += ',' + list(args.keys())[i] + '=' + \ ('\'{}\''.format( args[list(args.keys())[i]]) if list(args.keys())[i] in str_vars else '{}'.format( args[list(args.keys())[i]])) query = 'UPDATE coding_logs SET {} WHERE id = {};'.format(set_list, res[0][0]) du.db_query(db,query) # redirect to the session landing return redirect('/session?class_code={}'.format(session['class_code']))
def start(): args=dict() db = get_db() print("IN START FUNCTION") if 'action2' in request.args: print("printing args") print(request.args) if request.args['action2'] == '2': print("action 2") role=session['role'] if (role == 1): print("IN LEAVE FUNCTION") query='UPDATE syncing1 set started_sync=\'{}\',aborted=\'{}\' where coding_session_id={};'.format('yes','yes',session['coding_session']); du.db_query(db, query) args['role']=1 args['action']='11' print("Role 1 done from leave") if(role == 2): print("In leave function role 2") query='DELETE from sync_session_records where session_id={} and role={};'.format(session['coding_session'],2) du.db_query(db, query) print("role 2 done leaving") args['action']='11' args['role']=2 args['class_id'] = session['class_code'] args['student_id'] = session['current'] print(args) return render_template('session.html', args=args) if request.args['action2']=='1': query='UPDATE syncing1 set started_sync=\'{}\' where coding_session_id={};'.format('yes',session['coding_session']); du.db_query(db, query) ready_users=[] query='SELECT coder_user_id from sync_session_records where session_id={} and ready=\'{}\';'.format(session['coding_session'],'yes') res = du.db_query(db, query) print("Select coder id result") print(res) for i in range(len(res)): t=res[i] print(t[0]) query1='select first_name from user_details where user_id={};'.format(t[0]) names=du.db_query(db,query1) ready_users.append(names[0][0]) args['ready_users'] = ready_users print("Ready USers:",ready_users) args['class_id'] = session['class_code'] args['role']=session['role'] args['student_id'] = session['current'] args['action']='2' # render session page in 'waiting' state return render_template('session.html', args=args)
def get_all_actions(db, date, class_section): _vars, _query = du.read_var_text_file(SQL_FOLDER + 'get_all_actions.sql', sep=' ') _vars[':student_class_section_id'] = str(class_section) _vars[':date'] = date res, headers = du.db_query(db, _query, _vars, return_column_names=True) return {'headers': np.array(headers), 'data': np.array(res)}
def seconds_to_time(db, time, date): _vars, _query = du.read_var_text_file(SQL_FOLDER + 'seconds_from_midnight_to_time.sql', sep=' ') _vars[':seconds_from_midnight'] = time _vars[':date'] = str(date) return str(du.db_query(db, _query, _vars)[0][0])
def login(): # get database handle db = get_db() args = [] print("USER ID Entered by teacher:", request.form['userid']) # search database for the user query = 'select distinct student_class_id,student_class_section_id from enrollments where student_class_id in (select distinct student_class_id \ from teacher_classes where teacher_id=(select id from user_roles where user_id={} and type=\'Teacher\' ));'.format( request.form['userid']) print("QUERY") print(query) res = du.db_query(db, query) print(res) class_num = 1 data = [] for i in range(len(res)): print("i:", i) student_class = res[i] class_id = str(student_class[0]) section_id = str(student_class[1]) item = {"class_id": class_id, "section": section_id} data.append(item) jsonData = json.dumps(data) print(jsonData) return render_template('live_choose_class.html', jsonData=jsonData)
def get_kappa(): if 'coder' not in request.args: return jsonify([]) db = get_db() query = 'WITH x AS ( WITH logs AS (SELECT *,row_number() OVER (PARTITION BY coding_section_id, syncing_id) AS r ' \ 'FROM coding_logs cl LEFT OUTER JOIN recorded_codings rc ON rc.coding_log_id = cl.id ' \ 'LEFT OUTER JOIN codings c ON c.id = rc.coding_id LEFT OUTER JOIN coding_sections cs ' \ 'ON cs.id = rc.coding_section_id WHERE cl.submission_time IS NOT NULL AND cl.syncing_id IS NOT NULL ' \ 'AND rc.recorded_value = 1 AND c.code_value != \'-1\' AND session_id = {} ' \ 'AND user_id IN ({}, {}) ORDER BY coding_section_id, syncing_id, user_id) ' \ 'SELECT * FROM ( SELECT l.*,m.mr FROM logs l ' \ 'LEFT OUTER JOIN (SELECT coding_section_id, syncing_id, max(r) AS mr ' \ 'FROM logs GROUP BY coding_section_id, syncing_id) AS m ' \ 'ON (l.coding_section_id, l.syncing_id) = (m.coding_section_id, m.syncing_id) ) AS f ' \ 'WHERE f.mr = 2 ) SELECT * FROM ( SELECT DISTINCT syncing_id, coding_section_id, ' \ 'section_name FROM x ) AS a ' \ 'LEFT OUTER JOIN (SELECT display_name, coding_section_id, syncing_id FROM x WHERE user_id = 1) AS u1 ' \ 'ON (u1.coding_section_id, u1.syncing_id) = (a.coding_section_id, a.syncing_id) ' \ 'LEFT OUTER JOIN (SELECT display_name, coding_section_id, syncing_id FROM x WHERE user_id = 2) AS u2 ' \ 'ON (u2.coding_section_id, u2.syncing_id) = ' \ '(a.coding_section_id, a.syncing_id) ' \ 'LEFT OUTER JOIN coding_section_template_associations cta ON cta.coding_section_id = a.coding_section_id ' \ 'ORDER BY cta.section_position'.format(session['session_id'],session['user'], request.args['coder']) res = np.array(du.db_query(db, query)) ret = [] _, ind = np.unique(res[:,1], return_index=True) sec = res[ind,1] for i in range(len(sec)): query = 'SELECT DISTINCT display_name FROM coding_section_coding_associations cca ' \ 'LEFT OUTER JOIN codings c ON c.id = cca.coding_id ' \ 'WHERE coding_section_id={} AND c.code_value != \'-1\''.format(sec[i]) cls = np.array(du.db_query(db, query))[:,0] kpa = dict() sub = res[np.argwhere(res[:,1] == sec[i]).ravel(),:] print(np.array(du.one_hot(sub, cls, 3))[:,-len(cls):]) kpa['section'] = sub[0,2] kpa['kappa'] = '{:.3f}'.format(eval.cohen_kappa_multiclass(np.array(du.one_hot(sub, cls, 3))[:,-len(cls):], np.array(du.one_hot(sub, cls, 6))[:,-len(cls):])) for j in range(len(sub[:,3])): print('{} : {}'.format(sub[j,3],sub[j,6])) print(kpa['kappa']) ret.append(kpa) return jsonify(ret)
def add_class(): # get database handle db = get_db() # get the class id from the generated class code class_id = int('0x' + request.form['cl_code'][2:], 0) # update the row with the form information query = 'UPDATE classrooms SET teacher_name=\'{}\', class_name=\'{}\', grade=\'{}\',subject=\'{}\',n_students={},' \ 'code=\'{}\', created_at=now() WHERE id = {};'.format(request.form['teacher'], request.form['classname'], request.form['grade'], request.form['subject'], request.form['nstudents'], request.form['cl_code'], class_id) du.db_query(db, query) # return to the dashboard and display the created class code for user feedback and reference session['message'] = 'Class "{}" has been created!'.format(request.form['cl_code']) return redirect('/dashboard')
def get_session_coders(): if 'session_id' not in session: return jsonify([]) query = 'SELECT DISTINCT first_name || \' \' || last_name, sl.user_id FROM session_logs sl ' \ 'LEFT OUTER JOIN user_details ud ON ud.user_id = sl.user_id ' \ 'WHERE sl.session_id={} AND sl.user_id != {};'.format(session['session_id'], session['user']) res = np.array(du.db_query(get_db(), query))[:, [0, 1]] return jsonify(res.tolist())
def login(): # get database handle db = get_db() # search database for the user query = 'SELECT * FROM users WHERE email=\'{}\';'.format(request.form['Email']) res = du.db_query(db, query) if len(res) == 0: # user was not found session['message'] = 'Incorrect email or password!' return redirect('/') else: # user was found, check password against encoded password and salt enc = res[0][2] salt = res[0][3] matching = du.compare_salted(request.form['lg_password'],enc,salt) if not matching: # password did not match session['message'] = 'Incorrect email or password!' return redirect('/') else: # proceed with login - get user details from database query = 'SELECT * FROM user_details WHERE user_id = {};'.format(res[0][0]) detail = du.db_query(db, query) session['fname'] = detail[0][2] session['mi'] = detail[0][3] session['lname'] = detail[0][4] # session object is persistent - existence of email and user indicate user is logged in session['email'] = res[0][1] session['user'] = res[0][0] query = 'UPDATE users SET last_login=now() WHERE id = {};'.format(res[0][0]) du.db_query(db, query) session['message'] = 'Welcome ' + detail[0][2] + '!' p = list(session.keys()) p.append('persistent') session['persistent'] = p # attempt to go to dashboard (will redirect to root if unsuccessful login) return redirect('/dashboard')
def session_record_coding(): if not check_login(): return redirect('/') if 'session_id' not in session: session['message'] = 'Failed to join session' return redirect('/dashboard') if 'coding_log_id' not in session: return redirect('/session/dashboard') for i in request.form: print('{} : {}'.format(i,request.form[i])) db = get_db() query = 'UPDATE syncing_logs SET is_active=0 WHERE user_id={};'.format(session['user']) du.db_query(db, query) query = 'UPDATE coding_logs SET submission_time=now() WHERE id={};'.format(session['coding_log_id']) du.db_query(db, query) template = 'INSERT INTO recorded_codings (coding_log_id, coding_section_id, coding_id, recorded_value) ' \ 'VALUES ({}, {}, {}, {});' for sec in session['coding_sections']: for c in sec['coding']: key = sec['section_name'] if sec['type_name'] == 'radio' else c['name'] query = template.format(session['coding_log_id'], sec['section_id'], c['coding_id'], int(key in request.form and request.form[key] == c['value'])) du.db_query(db, query) session['recorded'] = 1 return redirect('/session/observe')
def saveLayout(): db = get_db() print("Saved class layout") input = request.json print(type(input)) print(type(input[0])) #jsonD=json.dumps(input) #print(type(jsonD)) for i in range(len(input)): print(input[i]['user_id']) print("Printing the layout") #print(input) table = session['table_name'] print("Table name:", table) query = 'CREATE TABLE IF NOT EXISTS {}(user_id integer,first_name varchar(60),last_name varchar(60),position_x varchar(10),position_y varchar(10));'.format( table) print(query) res = du.db_query(db, query) count = 'select count(*) from {};'.format(table) count = count[0][0] print("COUNT") print(count) type(count) #if(count[0][0]>0): # print("Update operation") #else: for i in range(len(input)): uid = input[i]['user_id'] fname = input[i]['first_name'] lname = input[i]['last_name'] x = input[i]['x'] y = input[i]['y'] query = 'INSERT INTO {} (user_id, first_name, last_name,position_x,position_y) VALUES ({},\'{}\',\'{}\',\'{}\',\'{}\');'.format( table, uid, fname, lname, x, y) print(query) res = du.db_query(db, query) print("DONE Inserting") return render_template('seating_chart.html')
def dashboard(): # TODO: display recent sessions # TODO: add new 'session info' page to display inforamtion and stats on recent sessions # if the user information is not in the session object, redirect to root if not ('email' in session and len(session['email']) > 0): session['message'] = 'You must be logged in to view the dashboard!' return redirect('/') # clean leftover syncing requests from previous sessions db = get_db() query = 'DELETE FROM syncing WHERE coder_user_id={};'.format(session['user']) du.db_query(db, query) # display message if available msg = '' if 'message' in session: msg = session['message'] session['message'] = '' # render dashboard page return render_template('dashboard.html', message=msg)
def login(): # get database handle db = get_db() # search database for the user query = 'SELECT * FROM users WHERE email=\'{}\';'.format(request.form['Email']) res = du.db_query(db, query) if len(res) == 0: # user was not found session['message'] = 'Incorrect email or password!' else: # user was found, check password against encoded password and salt enc = res[0][2] salt = res[0][3] matching = du.compare_salted(request.form['lg_password'],enc,salt) if not matching: # password did not match session['message'] = 'Incorrect email or password!' else: # proceed with login - get user details from database # TODO: check that user_details entry exists and fill with default values if not found query = 'SELECT * FROM user_details WHERE user_id = {};'.format(res[0][0]) detail = du.db_query(db, query) session['fname'] = detail[0][2] session['mi'] = detail[0][3] session['lname'] = detail[0][4] # session object is persistent - existence of email and user indicate user is logged in # TODO: add login timestamp to session object to implement login expiration session['email'] = res[0][1] session['user'] = res[0][0] session['message'] = 'Welcome ' + detail[0][2] + '!' # attempt to go to dashboard (will redirect to root if unsuccessful login) return redirect('/dashboard')
def register(): # get database handle db = get_db() # check to see if the user already exists using the entered email address query = 'SELECT * FROM users WHERE email=\'{}\';'.format(request.form['Email']) res = du.db_query(db, query) if len(res) > 0: # redirect to login page with message if user is found session['message'] = 'A user with that email is already registered!' return redirect('/') # if not found, generate encrypted password and salt and add entry to the database password, salt = du.get_salted(request.form['password']) query = 'INSERT INTO users (email, encrypted_password, salt) VALUES (\'{}\',\'{}\',\'{}\');'.format( request.form['Email'], password, salt) if du.db_query(db,query) is None: session['message'] = 'Oops! We are unable to connect to the database.' else: # check to ensure that the user was added query = 'SELECT * FROM users WHERE email=\'{}\';'.format(request.form['Email']) res = du.db_query(db, query) if len(res) == 0: # if the user is not found, redirect to login page with message session['message'] = 'Oops! Something went wrong trying to register your account.' redirect('/') else: session['message'] = 'You are now registered!' # add associated user details to database (low priority, no additional check made) query = 'INSERT INTO user_details (user_id, first_name, middle_initial, last_name) VALUES ' \ '({},\'{}\',\'{}\',\'{}\');'.format(res[0][0], request.form['fname'], request.form['mi'], request.form['lname']) du.db_query(db, query) # return to the login page return redirect('/')
def leave(): db = get_db() args=dict() role=session['role'] if (role == 1): print("IN LEAVE FUNCTION") query='UPDATE syncing1 set started_sync=\'{}\' where coding_session_id={};'.format('yes',session['coding_session']); du.db_query(db, query) args['role']=1 args['action']='11' print("Role 1 done from leave") if(role == 2): print("In leave function role 2") query='DELETE from sync_session_records where session_id={} and role={};'.format(session['coding_session'],2) du.db_query(db, query) print("role 2 done leaving") args['action']='11' args['role']=2 args['class_id'] = session['class_code'] args['student_id'] = session['current'] print(args) return render_template('session.html', args=args)
def ready_update_db(): args=dict() db = get_db() for i in range(0,1): print("I AM in ready_update_db") print("Role:",session['role']) print("I am User:"******"Coding session:",session['coding_session']) role=session['role'] coder_id=session['user'] session_id=session['coding_session'] query='select coder_user_id from kicked_out where session_id={}'.format(session_id) res=du.db_query(db,query) kicked_out=[] for i in range(len(res)): t=res[i] print(t[0]) kicked_out.append(t[0]) #Checking if the coder has to be kicked out of the sync session if coder_id in kicked_out: print("YOU GOT KICKED OUT:",coder_id) args['action']='11' args['student_id'] = session['current'] args['class_id']=session['class_code'] args['role']=session['role'] return render_template('session.html', args=args) if(session['role']==2): print("Updating db for ready=yes") query='UPDATE sync_session_records SET ready=\'{}\' WHERE coder_user_id={} and session_id={} ;'.format('yes',coder_id,session_id) du.db_query(db,query) query='select student_id,class_id from sync_session_records WHERE session_id={} and role={} ;'.format(session_id,1) res=du.db_query(db,query) query2='UPDATE sync_session_records SET student_id={} WHERE coder_user_id={} and session_id={} ;'.format(res[0][0],coder_id,session_id) du.db_query(db,query2) args['student_id']=res[0][0] args['class_id']=res[0][1] print("Done update, going to redirect to /start_sync_call") args['action'] = '2' #args['update'] = 'success' args['role']=session['role'] return render_template('session.html', args=args) else: print("Something wrong!no other role can be calling this funciton") args['action']= '15' #args['update']='failed' # waiting #Tell update done #args=default_args_setter_helper(args) return render_template('session2.html', args=args)
def find_sb(): db = get_db() query = 'SELECT id FROM class_assignments WHERE assignment_type_id = 1 AND sequence_id IN \ (SELECT id FROM sequences WHERE head_section_id IN (SELECT id FROM sections WHERE position(\'astery\' IN type) > 0) AND id IN (\ SELECT ns.sequence_id FROM (SELECT sequence_id, count(*) AS nsec FROM sections GROUP BY sequence_id) AS ns \ LEFT OUTER JOIN ( SELECT sequence_id, count(*) AS npr FROM sections WHERE type=\'ProblemSection\' GROUP BY sequence_id ) AS np ON ns.sequence_id = np.sequence_id \ WHERE ns.nsec = np.npr+1 ))' result = du.db_query(db, query) for i in range(len(result)): row = result[i] id = row[0] skill_builders.append(id) print("Retrieved all skill builders:")
def start_timer(): if not check_login(): return redirect('/') if 'session_id' not in session: session['message'] = 'Failed to join session' return redirect('/dashboard') if 'coding_log_id' not in session: return redirect('/session/dashboard') db = get_db() if 'syncing_id' in session: query = 'UPDATE coding_logs SET syncing_id={} WHERE id={};'.format(session['syncing_id'], session['coding_log_id']) du.db_query(db, query) query = 'SELECT (started_at IS NULL)::INT FROM syncing WHERE id={};'.format(session['syncing_id']) res = du.db_query(db, query) if int(res[0][0]) == 1: query = 'UPDATE syncing SET started_at=now() WHERE id={};'.format(session['syncing_id']) du.db_query(db, query) session.pop('syncing_id') query = 'UPDATE syncing_logs SET is_active=0 WHERE user_id={};'.format(session['user']) du.db_query(db, query) args = dict() args['session_code'] = str(session['session_code']) args['class_code'] = str(session['class_code']) args['coding_template_name'] = str(session['coding_template_name']) args['timer_seconds'] = int(session['timer_seconds']) args['strict_timer'] = int(session['strict_timer']) args['student_id'] = session['student_id'] query = 'UPDATE coding_logs SET timer_start=now() WHERE id={};'.format(session['coding_log_id']) du.db_query(db, query) return render_template('timer.html', args=args)
def get_recent_actions(db, date, class_section, time, offset=1, source=None): if source is None: _vars, _query = du.read_var_text_file(SQL_FOLDER + 'recent_actions.sql', sep='\n') _vars[':seconds_from_midnight'] = time _vars[':student_class_section_id'] = str(class_section) _vars[':date'] = str(date) _vars[':time_offset'] = offset return du.db_query(db, _query, _vars, return_column_names=True) else: if source is not dict and (not len(source['data'].shape) == 2 or not source['data'].shape[-1] == 18): raise ValueError( 'Source must be the result of a get_all_actions call or None') return source['data'][np.argwhere([time-offset < i <= time for i in source['data'][:, -1]]).ravel(), :-1],\ source['headers']
def check_login(): if 'user' in session: db = get_db() query = 'SELECT (last_login-now() < interval \'7 days\')::INT FROM users WHERE id={}'.format(session['user']) try: res = du.db_query(db,query,None,False) if not res[0][0]: session.clear() session['message'] = 'Your session has expired. Please log in again.' return 0 else: return 1 except IndexError: session.clear() return 0 else: return 0
def time_to_seconds(db, time): _vars, _query = du.read_var_text_file(SQL_FOLDER + 'time_to_seconds_from_midnight.sql', sep=' ') _vars[':time'] = str(time) return du.db_query(db, _query, _vars)[0][0]
def chooseClass(): db = get_db() class_section = str(request.form['classid']) arr = class_section.split(' ') print("Class:", arr[0]) print("Section:", arr[1]) class_ = arr[0] section_ = arr[1] print("Class by teacher:", request.form['classid']) global class_time class_time = request.form['classDateTime'] stripped_time = datetime.datetime.strptime(class_time, '%Y-%m-%d' + 'T' + '%H:%M') print("stripped_time:", stripped_time) stripped_time = stripped_time + datetime.timedelta(milliseconds=1) stripped_time = stripped_time.strftime("%Y-%m-%d %H:%M:%S.%f") print("Class time :", class_time) #query = 'select distinct student_class_id,student_class_section_id from enrollments where student_class_id=(select student_class_id \ # from teacher_classes where teacher_id=(select id from user_roles where user_id={} and type=\'Teacher\'));'.format(request.form['userid']) query = 'select user_id,first_name,last_name from user_details where user_id in (select user_id from user_roles where type=\'Student\' and id in ( \ select distinct(student_id) from enrollments where student_class_id={} and student_class_section_id={}));'.format( int(arr[0]), int(arr[1])) print("QUERY") print(query) res = du.db_query(db, query) print(res) session['table_name'] = "class_" + arr[0] + "_" + arr[1] #After obtaining the names, send it in json to html to populate buttons data = [] query = 'CREATE TABLE IF NOT EXISTS {}(user_id integer,first_name varchar(60),last_name varchar(60),position_x varchar(10),position_y varchar(10));'.format( session['table_name']) du.db_query(db, query) query = 'SELECT count(*) from {}'.format(session['table_name']) count = du.db_query(db, query) print("Count:", count) exists = count[0][0] print(exists) data = [] if (exists == 0): print("Creating class") for i in range(len(res)): print("i:", i) student_info = res[i] user_id = int(student_info[0]) all_studentids.append(user_id) first_name = str(student_info[1]) last_name = str(student_info[2]) item = { "user_id": user_id, "first_name": first_name, "last_name": last_name } all_student_objects[user_id] = Student.Stud( user_id, first_name, last_name) data.append(item) #data.append({"dat":stripped_time}) jsonData = json.dumps(data) print(jsonData) else: print("Table already exists shhould grab from them") query = 'SELECT count(*) from {}'.format(session['table_name']) res = du.db_query(db, query) print("we have so many student:", res[0][0]) query = 'SELECT * from {}'.format(session['table_name']) res = du.db_query(db, query) for i in range(len(res)): student_info = res[i] user_id = int(student_info[0]) first_name = str(student_info[1]) last_name = str(student_info[2]) pos_x = str(student_info[3]) pos_y = str(student_info[4]) item = { "user_id": user_id, "first_name": first_name, "last_name": last_name, "x": pos_x, "y": pos_y } all_student_objects[user_id] = Student.Stud( user_id, first_name, last_name) all_studentids.append(user_id) data.append(item) #data.append({"dat":stripped_time}) jsonData = json.dumps(data) print("Created objects in python") return render_template('seating_chart_with_names.html', jsonData=jsonData)