idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
229,800
def _handle_ssh_callback ( self , submission_id , host , port , password ) : if host is not None : obj = { "ssh_host" : host , "ssh_port" : port , "ssh_password" : password } self . _database . submissions . update_one ( { "_id" : submission_id } , { "$set" : obj } )
Handles the creation of a remote ssh server
229,801
def filesystem_from_config_dict ( config_fs ) : if "module" not in config_fs : print ( "Key 'module' should be defined for the filesystem provider ('fs' configuration option)" , file = sys . stderr ) exit ( 1 ) filesystem_providers = get_filesystems_providers ( ) if config_fs [ "module" ] not in filesystem_providers : ...
Given a dict containing an entry module which contains a FSProvider identifier parse the configuration and returns a fs_provider . Exits if there is an error .
229,802
async def _kill_it_with_fire ( self , container_id ) : if container_id in self . _watching : self . _watching . remove ( container_id ) self . _container_had_error . add ( container_id ) try : await self . _docker_interface . kill_container ( container_id ) except : pass
Kill a container with fire .
229,803
def _cleanup ( self ) : current_time = time . time ( ) timeout = self . _config . timeout if current_time - self . _last_cleanup_time > timeout : self . store . cleanup ( timeout ) self . _last_cleanup_time = current_time
Cleanup the stored sessions
229,804
def expired ( self ) : self . _data [ "_killed" ] = True self . save ( ) raise SessionExpired ( self . _config . expired_message )
Called when an expired session is atime
229,805
def delete_account ( self , data ) : error = False msg = "" username = self . user_manager . session_username ( ) result = self . database . users . find_one_and_delete ( { "username" : username , "email" : data . get ( "delete_email" , "" ) } ) if not result : error = True msg = _ ( "The specified email is incorrect."...
Delete account from DB
229,806
def dump ( data , stream = None , ** kwds ) : class OrderedDumper ( SafeDumper ) : pass def _dict_representer ( dumper , data ) : return dumper . represent_mapping ( original_yaml . resolver . BaseResolver . DEFAULT_MAPPING_TAG , list ( data . items ( ) ) ) def _long_str_representer ( dumper , data ) : if data . find (...
Serialize a Python object into a YAML stream . If stream is None return the produced string instead . Dict keys are produced in the order in which they appear in OrderedDicts .
229,807
def _check_for_parsable_text ( self , val ) : if isinstance ( val , ParsableText ) : return val . original_content ( ) if isinstance ( val , list ) : for key , val2 in enumerate ( val ) : val [ key ] = self . _check_for_parsable_text ( val2 ) return val if isinstance ( val , dict ) : for key , val2 in val . items ( ) :...
Util to remove parsable text from a dict recursively
229,808
def API_GET ( self , courseid , taskid = None ) : try : course = self . course_factory . get_course ( courseid ) except : raise APINotFound ( "Course not found" ) if not self . user_manager . course_is_open_to_user ( course , lti = False ) : raise APIForbidden ( "You are not registered to this course" ) if taskid is No...
List tasks available to the connected client . Returns a dict in the form
229,809
def load_input ( ) : file = open ( _input_file , 'r' ) result = json . loads ( file . read ( ) . strip ( '\0' ) . strip ( ) ) file . close ( ) return result
Open existing input file
229,810
def parse_template ( input_filename , output_filename = '' ) : data = load_input ( ) with open ( input_filename , 'rb' ) as file : template = file . read ( ) . decode ( "utf-8" ) if not 'input' in data : raise ValueError ( "Could not find 'input' in data" ) for field in data [ 'input' ] : subs = [ "filename" , "value" ...
Parses a template file Replaces all occurences of
229,811
def _callable_once ( func ) : def once ( * args , ** kwargs ) : if not once . called : once . called = True return func ( * args , ** kwargs ) once . called = False return once
Returns a function that is only callable once ; any other call will do nothing
229,812
async def _ask_queue_update ( self ) : try : while True : await asyncio . sleep ( self . _queue_update_timer ) if self . _queue_update_last_attempt == 0 or self . _queue_update_last_attempt > self . _queue_update_last_attempt_max : if self . _queue_update_last_attempt : self . _logger . error ( "Asking for a job queue ...
Send a ClientGetQueue message to the backend if one is not already sent
229,813
async def _handle_job_queue_update ( self , message : BackendGetQueue ) : self . _logger . debug ( "Received job queue update" ) self . _queue_update_last_attempt = 0 self . _queue_cache = message new_job_queue_cache = { } for ( job_id , is_local , _ , _2 , _3 , _4 , max_end ) in message . jobs_running : if is_local : ...
Handles a BackendGetQueue containing a snapshot of the job queue
229,814
def new_job ( self , task , inputdata , callback , launcher_name = "Unknown" , debug = False , ssh_callback = None ) : job_id = str ( uuid . uuid4 ( ) ) if debug == "ssh" and ssh_callback is None : self . _logger . error ( "SSH callback not set in %s/%s" , task . get_course_id ( ) , task . get_id ( ) ) callback ( ( "cr...
Add a new job . Every callback will be called once and only once .
229,815
def kill_job ( self , job_id ) : self . _loop . call_soon_threadsafe ( asyncio . ensure_future , self . _simple_send ( ClientKillJob ( job_id ) ) )
Kills a running job
229,816
def get_codeblock ( language , text ) : rst = "\n\n.. code-block:: " + language + "\n\n" for line in text . splitlines ( ) : rst += "\t" + line + "\n" rst += "\n" return rst
Generates rst codeblock for given text and language
229,817
def get_imageblock ( filename , format = '' ) : _ , extension = os . path . splitext ( filename ) with open ( filename , "rb" ) as image_file : encoded_string = base64 . b64encode ( image_file . read ( ) ) . decode ( 'utf-8' ) return '\n\n.. raw:: html\n\n\t<img src="data:image/' + ( format if format else extension [ 1...
Generates rst raw block for given image filename and format
229,818
def get_admonition ( cssclass , title , text ) : rst = ( "\n\n.. admonition:: " + title + "\n" ) if title else "\n\n.. note:: \n" rst += "\t:class: alert alert-" + cssclass + "\n\n" for line in text . splitlines ( ) : rst += "\t" + line + "\n" rst += "\n" return rst
Generates rst admonition block given a bootstrap alert css class title and text
229,819
def init ( ) : if "_" not in builtins . __dict__ : os . environ [ "LANGUAGE" ] = inginious . input . get_lang ( ) if inginious . DEBUG : gettext . install ( "messages" , get_lang_dir_path ( ) ) else : gettext . install ( "messages" , get_lang_dir_path ( ) )
Install gettext with the default parameters
229,820
def _recursive_overwrite ( self , src , dest ) : if os . path . isdir ( src ) : if not os . path . isdir ( dest ) : os . makedirs ( dest ) files = os . listdir ( src ) for f in files : self . _recursive_overwrite ( os . path . join ( src , f ) , os . path . join ( dest , f ) ) else : shutil . copyfile ( src , dest , fo...
Copy src to dest recursively and with file overwrite .
229,821
def init ( plugin_manager , _ , _2 , config ) : submission_git_saver = SubmissionGitSaver ( plugin_manager , config ) submission_git_saver . daemon = True submission_git_saver . start ( )
Init the plugin
229,822
def get_type_as_str ( self ) : if self . get_type ( ) == 0 : return _ ( "Skill" ) elif self . get_type ( ) == 1 : return _ ( "Misconception" ) elif self . get_type ( ) == 2 : return _ ( "Category" ) else : return _ ( "Unknown type" )
Return a textual description of the type
229,823
def create_tags_from_dict ( cls , tag_dict ) : tag_list_common = [ ] tag_list_misconception = [ ] tag_list_organisational = [ ] for tag in tag_dict : try : id = tag_dict [ tag ] [ "id" ] name = tag_dict [ tag ] [ "name" ] visible = tag_dict [ tag ] [ "visible" ] description = tag_dict [ tag ] [ "description" ] type = t...
Build a tuple of list of Tag objects based on the tag_dict . The tuple contains 3 lists . - The first list contains skill tags - The second list contains misconception tags - The third list contains category tags
229,824
async def run ( self ) : self . _logger . info ( "Agent started" ) self . __backend_socket . connect ( self . __backend_addr ) self . _logger . info ( "Saying hello to the backend" ) await ZMQUtils . send ( self . __backend_socket , AgentHello ( self . __friendly_name , self . __concurrency , self . environments ) ) se...
Runs the agent . Answer to the requests made by the Backend . May raise an asyncio . CancelledError in which case the agent should clean itself and restart completely .
229,825
async def __check_last_ping ( self , run_listen ) : if self . __last_ping < time . time ( ) - 10 : self . _logger . warning ( "Last ping too old. Restarting the agent." ) run_listen . cancel ( ) self . __cancel_remaining_safe_tasks ( ) else : self . _loop . call_later ( 1 , self . _create_safe_task , self . __check_las...
Check if the last timeout is too old . If it is kills the run_listen task
229,826
async def __run_listen ( self ) : while True : message = await ZMQUtils . recv ( self . __backend_socket ) await self . __handle_backend_message ( message )
Listen to the backend
229,827
async def __handle_ping ( self , _ : Ping ) : self . __last_ping = time . time ( ) await ZMQUtils . send ( self . __backend_socket , Pong ( ) )
Handle a Ping message . Pong the backend
229,828
def get_menu ( course , current , renderer , plugin_manager , user_manager ) : default_entries = [ ] if user_manager . has_admin_rights_on_course ( course ) : default_entries += [ ( "settings" , "<i class='fa fa-cog fa-fw'></i>&nbsp; " + _ ( "Course settings" ) ) ] default_entries += [ ( "stats" , "<i class='fa fa-area...
Returns the HTML of the menu used in the administration . current is the current page of section
229,829
def writerow ( self , row ) : self . writer . writerow ( row ) data = self . queue . getvalue ( ) self . stream . write ( data ) self . queue . truncate ( 0 ) self . queue . seek ( 0 )
Writes a row to the CSV file
229,830
def get_renderer ( self , with_layout = True ) : if with_layout and self . is_lti ( ) : return self . _default_renderer_lti elif with_layout : return self . _default_renderer else : return self . _default_renderer_nolayout
Get the default renderer
229,831
def _javascript_helper ( self , position ) : if position not in [ "header" , "footer" ] : position = "footer" if position == "header" : entries = [ entry for entry in self . _plugin_manager . call_hook ( "javascript_header" ) if entry is not None ] else : entries = [ entry for entry in self . _plugin_manager . call_hoo...
Add javascript links for the current page and for the plugins
229,832
def _css_helper ( self ) : entries = [ entry for entry in self . _plugin_manager . call_hook ( "css" ) if entry is not None ] entries += self . _get_ctx ( ) [ "css" ] entries = [ "<link href='" + entry + "' rel='stylesheet'>" for entry in entries ] return "\n" . join ( entries )
Add CSS links for the current page and for the plugins
229,833
def _get_ctx ( self ) : if self . _WEB_CTX_KEY not in web . ctx : web . ctx [ self . _WEB_CTX_KEY ] = { "javascript" : { "footer" : [ ] , "header" : [ ] } , "css" : [ ] } return web . ctx . get ( self . _WEB_CTX_KEY )
Get web . ctx object for the Template helper
229,834
def _generic_hook ( self , name , ** kwargs ) : entries = [ entry for entry in self . _plugin_manager . call_hook ( name , ** kwargs ) if entry is not None ] return "\n" . join ( entries )
A generic hook that links the TemplateHelper with PluginManager
229,835
def new_job ( self , task , inputdata , launcher_name = "Unknown" , debug = False ) : bjobid = uuid . uuid4 ( ) self . _waiting_jobs . append ( str ( bjobid ) ) self . _client . new_job ( task , inputdata , ( lambda result , grade , problems , tests , custom , archive , stdout , stderr : self . _callback ( bjobid , res...
Runs a new job . It works exactly like the Client class instead that there is no callback
229,836
def _callback ( self , bjobid , result , grade , problems , tests , custom , archive , stdout , stderr ) : self . _jobs_done [ str ( bjobid ) ] = ( result , grade , problems , tests , custom , archive , stdout , stderr ) self . _waiting_jobs . remove ( str ( bjobid ) )
Callback for self . _client . new_job
229,837
def init ( plugin_manager , _ , _2 , conf ) : encryption = conf . get ( "encryption" , "none" ) if encryption not in [ "none" , "ssl" , "tls" ] : raise Exception ( "Unknown encryption method {}" . format ( encryption ) ) if encryption == "none" : conf [ "encryption" ] = None if conf . get ( "port" , 0 ) == 0 : conf [ "...
Allow to connect through a LDAP service
229,838
def cleanup ( self , timeout ) : cutoff = time ( ) - timeout self . collection . remove ( { _atime : { '$lt' : cutoff } } )
Removes all sessions older than timeout seconds . Called automatically on every session access .
229,839
def load ( self , client , webpy_app , course_factory , task_factory , database , user_manager , submission_manager , config ) : self . _app = webpy_app self . _task_factory = task_factory self . _database = database self . _user_manager = user_manager self . _submission_manager = submission_manager self . _loaded = Tr...
Loads the plugin manager . Must be done after the initialisation of the client
229,840
def add_page ( self , pattern , classname ) : if not self . _loaded : raise PluginManagerNotLoadedException ( ) self . _app . add_mapping ( pattern , classname )
Add a new page to the web application . Only available after that the Plugin Manager is loaded
229,841
def add_task_file_manager ( self , task_file_manager ) : if not self . _loaded : raise PluginManagerNotLoadedException ( ) self . _task_factory . add_custom_task_file_manager ( task_file_manager )
Add a task file manager . Only available after that the Plugin Manager is loaded
229,842
def register_auth_method ( self , auth_method ) : if not self . _loaded : raise PluginManagerNotLoadedException ( ) self . _user_manager . register_auth_method ( auth_method )
Register a new authentication method
229,843
def dump_course ( self , courseid ) : filepath = os . path . join ( self . backup_dir , courseid , datetime . datetime . now ( ) . strftime ( "%Y%m%d.%H%M%S" ) + ".zip" ) if not os . path . exists ( os . path . dirname ( filepath ) ) : os . makedirs ( os . path . dirname ( filepath ) ) with zipfile . ZipFile ( filepath...
Create a zip file containing all information about a given course in database and then remove it from db
229,844
def delete_course ( self , courseid ) : self . wipe_course ( courseid ) self . course_factory . delete_course ( courseid ) filepath = os . path . join ( self . backup_dir , courseid ) if os . path . exists ( os . path . dirname ( filepath ) ) : for backup in glob . glob ( os . path . join ( filepath , '*.zip' ) ) : os ...
Erase all course data
229,845
def show_input ( self , template_helper , language , seed ) : header = ParsableText ( self . gettext ( language , self . _header ) , "rst" , translation = self . _translations . get ( language , gettext . NullTranslations ( ) ) ) return str ( DisplayableCodeProblem . get_renderer ( template_helper ) . tasks . code ( se...
Show BasicCodeProblem and derivatives
229,846
def show_input ( self , template_helper , language , seed ) : choices = [ ] limit = self . _limit if limit == 0 : limit = len ( self . _choices ) rand = Random ( "{}#{}#{}" . format ( self . get_task ( ) . get_id ( ) , self . get_id ( ) , seed ) ) random_order_choices = list ( self . _choices ) rand . shuffle ( random_...
Show multiple choice problems
229,847
def _parse_lti_data ( self , courseid , taskid ) : post_input = web . webapi . rawinput ( "POST" ) self . logger . debug ( '_parse_lti_data:' + str ( post_input ) ) try : course = self . course_factory . get_course ( courseid ) except exceptions . CourseNotFoundException as ex : raise web . notfound ( str ( ex ) ) try ...
Verify and parse the data for the LTI basic launch
229,848
def _find_realname ( self , post_input ) : if "lis_person_name_full" in post_input : return post_input [ "lis_person_name_full" ] if "lis_person_name_given" in post_input and "lis_person_name_family" in post_input : return post_input [ "lis_person_name_given" ] + post_input [ "lis_person_name_family" ] if "lis_person_c...
Returns the most appropriate name to identify the user
229,849
def fast_stats ( data ) : total_submission = len ( data ) total_submission_best = 0 total_submission_best_succeeded = 0 for submission in data : if "best" in submission and submission [ "best" ] : total_submission_best = total_submission_best + 1 if "result" in submission and submission [ "result" ] == "success" : tota...
Compute base statistics about submissions
229,850
def _register_transaction ( self , send_msg , recv_msg , coroutine_recv , coroutine_abrt , get_key = None , inter_msg = None ) : if get_key is None : get_key = lambda x : None if inter_msg is None : inter_msg = [ ] self . _msgs_registered [ send_msg . __msgtype__ ] = ( [ recv_msg . __msgtype__ ] + [ x . __msgtype__ for...
Register a type of message to be sent . After this message has been sent if the answer is received callback_recv is called . If the remote server becomes dones calls callback_abrt .
229,851
async def _reconnect ( self ) : for msg_class in self . _transactions : _1 , _2 , _3 , coroutine_abrt , _4 = self . _msgs_registered [ msg_class ] if coroutine_abrt is not None : for key in self . _transactions [ msg_class ] : for args , kwargs in self . _transactions [ msg_class ] [ key ] : self . _loop . create_task ...
Called when the remote server is innacessible and the connection has to be restarted
229,852
async def client_start ( self ) : await self . _start_socket ( ) await self . _on_connect ( ) self . _ping_count = 0 task_socket = self . _loop . create_task ( self . _run_socket ( ) ) task_ping = self . _loop . create_task ( self . _do_ping ( ) ) self . _restartable_tasks . append ( task_ping ) self . _restartable_tas...
Starts the client
229,853
async def _run_socket ( self ) : try : while True : message = await ZMQUtils . recv ( self . _socket ) msg_class = message . __msgtype__ if msg_class in self . _handlers_registered : self . _loop . create_task ( self . _handlers_registered [ msg_class ] ( message ) ) elif msg_class in self . _transactions : _1 , get_ke...
Task that runs this client .
229,854
def load_feedback ( ) : result = { } if os . path . exists ( _feedback_file ) : f = open ( _feedback_file , 'r' ) cont = f . read ( ) f . close ( ) else : cont = '{}' try : result = json . loads ( cont ) if cont else { } except ValueError as e : result = { "result" : "crash" , "text" : "Feedback file has been modified ...
Open existing feedback file
229,855
def save_feedback ( rdict ) : if not os . path . exists ( _feedback_dir ) : os . makedirs ( _feedback_dir ) jcont = json . dumps ( rdict ) f = open ( _feedback_file , 'w' ) f . write ( jcont ) f . close ( )
Save feedback file
229,856
def set_problem_result ( result , problem_id ) : rdict = load_feedback ( ) if not 'problems' in rdict : rdict [ 'problems' ] = { } cur_val = rdict [ 'problems' ] . get ( problem_id , '' ) rdict [ 'problems' ] [ problem_id ] = [ result , cur_val ] if type ( cur_val ) == str else [ result , cur_val [ 1 ] ] save_feedback ...
Set problem specific result value
229,857
def set_global_feedback ( feedback , append = False ) : rdict = load_feedback ( ) rdict [ 'text' ] = rdict . get ( 'text' , '' ) + feedback if append else feedback save_feedback ( rdict )
Set global feedback in case of error
229,858
def set_problem_feedback ( feedback , problem_id , append = False ) : rdict = load_feedback ( ) if not 'problems' in rdict : rdict [ 'problems' ] = { } cur_val = rdict [ 'problems' ] . get ( problem_id , '' ) rdict [ 'problems' ] [ problem_id ] = ( cur_val + feedback if append else feedback ) if type ( cur_val ) == str...
Set problem specific feedback
229,859
def _display_big_warning ( self , content ) : print ( "" ) print ( BOLD + WARNING + "--- WARNING ---" + ENDC ) print ( WARNING + content + ENDC ) print ( "" )
Displays a BIG warning
229,860
def _ask_local_config ( self ) : options = { "backend" : "local" , "local-config" : { } } while True : concurrency = self . _ask_with_default ( "Maximum concurrency (number of tasks running simultaneously). Leave it empty to use the number of " "CPU of your host." , "" ) if concurrency == "" : break try : concurrency =...
Ask some parameters about the local configuration
229,861
def ask_backend ( self ) : response = self . _ask_boolean ( "Do you have a local docker daemon (on Linux), do you use docker-machine via a local machine, or do you use " "Docker for macOS?" , True ) if ( response ) : self . _display_info ( "If you use docker-machine on macOS, please see " "http://inginious.readthedocs....
Ask the user to choose the backend
229,862
def try_mongodb_opts ( self , host = "localhost" , database_name = 'INGInious' ) : try : mongo_client = MongoClient ( host = host ) except Exception as e : self . _display_warning ( "Cannot connect to MongoDB on host %s: %s" % ( host , str ( e ) ) ) return None try : database = mongo_client [ database_name ] except Exc...
Try MongoDB configuration
229,863
def configure_task_directory ( self ) : self . _display_question ( "Please choose a directory in which to store the course/task files. By default, the tool will put them in the current " "directory" ) task_directory = None while task_directory is None : task_directory = self . _ask_with_default ( "Task directory" , "."...
Configure task directory
229,864
def download_containers ( self , to_download , current_options ) : if current_options [ "backend" ] == "local" : self . _display_info ( "Connecting to the local Docker daemon..." ) try : docker_connection = docker . from_env ( ) except : self . _display_error ( "Cannot connect to local Docker daemon. Skipping download....
Download the chosen containers on all the agents
229,865
def configure_containers ( self , current_options ) : containers = [ ( "default" , "Default container. For Bash and Python 2 tasks" ) , ( "cpp" , "Contains gcc and g++ for compiling C++" ) , ( "java7" , "Contains Java 7" ) , ( "java8scala" , "Contains Java 8 and Scala" ) , ( "mono" , "Contains Mono, which allows to run...
Configures the container dict
229,866
def configure_backup_directory ( self ) : self . _display_question ( "Please choose a directory in which to store the backup files. By default, the tool will them in the current " "directory" ) backup_directory = None while backup_directory is None : backup_directory = self . _ask_with_default ( "Backup directory" , "....
Configure backup directory
229,867
def ldap_plugin ( self ) : name = self . _ask_with_default ( "Authentication method name (will be displayed on the login page)" , "LDAP" ) prefix = self . _ask_with_default ( "Prefix to append to the username before db storage. Usefull when you have more than one auth method with " "common usernames." , "" ) ldap_host ...
Configures the LDAP plugin
229,868
def configure_authentication ( self , database ) : options = { "plugins" : [ ] , "superadmins" : [ ] } self . _display_info ( "We will now create the first user." ) username = self . _ask_with_default ( "Enter the login of the superadmin" , "superadmin" ) realname = self . _ask_with_default ( "Enter the name of the sup...
Configure the authentication
229,869
def _close_app ( app , mongo_client , client ) : app . stop ( ) client . close ( ) mongo_client . close ( )
Ensures that the app is properly closed
229,870
async def _init_clean ( self ) : self . _containers_running = { } self . _container_for_job = { } self . _student_containers_running = { } self . _student_containers_for_job = { } self . _containers_killed = dict ( ) try : await self . _ashutil . rmtree ( self . _tmp_dir ) except OSError : pass try : await self . _aos ...
Must be called when the agent is starting
229,871
async def _end_clean ( self ) : await self . _timeout_watcher . clean ( ) async def close_and_delete ( container_id ) : try : await self . _docker . remove_container ( container_id ) except : pass for container_id in self . _containers_running : await close_and_delete ( container_id ) for container_id in self . _studen...
Must be called when the agent is closing
229,872
async def _watch_docker_events ( self ) : try : source = AsyncIteratorWrapper ( self . _docker . sync . event_stream ( filters = { "event" : [ "die" , "oom" ] } ) ) async for i in source : if i [ "Type" ] == "container" and i [ "status" ] == "die" : container_id = i [ "id" ] try : retval = int ( i [ "Actor" ] [ "Attrib...
Get raw docker events and convert them to more readable objects and then give them to self . _docker_events_subscriber
229,873
async def handle_student_job_closing ( self , container_id , retval ) : try : self . _logger . debug ( "Closing student %s" , container_id ) try : job_id , parent_container_id , socket_id , write_stream = self . _student_containers_running [ container_id ] del self . _student_containers_running [ container_id ] except ...
Handle a closing student container . Do some cleaning verify memory limits timeouts ... and returns data to the associated grading container
229,874
async def kill_job ( self , message : BackendKillJob ) : try : if message . job_id in self . _container_for_job : self . _containers_killed [ self . _container_for_job [ message . job_id ] ] = "killed" await self . _docker . kill_container ( self . _container_for_job [ message . job_id ] ) else : self . _logger . warni...
Handles kill messages . Kill things .
229,875
def get_user_lists ( self , course , aggregationid = '' ) : tutor_list = course . get_staff ( ) student_list = list ( self . database . aggregations . aggregate ( [ { "$match" : { "courseid" : course . get_id ( ) } } , { "$unwind" : "$students" } , { "$project" : { "classroom" : "$_id" , "students" : 1 , "grouped" : { ...
Get the available student and tutor lists for aggregation edition
229,876
def update_aggregation ( self , course , aggregationid , new_data ) : student_list = self . user_manager . get_course_registered_users ( course , False ) if aggregationid == 'None' : del new_data [ '_id' ] new_data [ "courseid" ] = course . get_id ( ) result = self . database . aggregations . insert_one ( new_data ) ag...
Update aggregation and returns a list of errored students
229,877
def POST_AUTH ( self ) : username = self . user_manager . session_username ( ) user_info = self . database . users . find_one ( { "username" : username } ) user_input = web . input ( ) success = None if "register_courseid" in user_input and user_input [ "register_courseid" ] != "" : try : course = self . course_factory...
Parse course registration or course creation and display the course list page
229,878
async def _restart_on_cancel ( logger , agent ) : while True : try : await agent . run ( ) except asyncio . CancelledError : logger . exception ( "Restarting agent" ) pass
Restarts an agent when it is cancelled
229,879
def GET ( self , * args , ** kwargs ) : if self . user_manager . session_logged_in ( ) : if not self . user_manager . session_username ( ) and not self . __class__ . __name__ == "ProfilePage" : raise web . seeother ( "/preferences/profile" ) if not self . is_lti_page and self . user_manager . session_lti_info ( ) is no...
Checks if user is authenticated and calls GET_AUTH or performs logout . Otherwise returns the login template .
229,880
def normpath ( self , path ) : path2 = posixpath . normpath ( urllib . parse . unquote ( path ) ) if path . endswith ( "/" ) : path2 += "/" return path2
Normalize the path
229,881
def _get_submissions ( course_factory , submission_manager , user_manager , translations , courseid , taskid , with_input , submissionid = None ) : try : course = course_factory . get_course ( courseid ) except : raise APINotFound ( "Course not found" ) if not user_manager . course_is_open_to_user ( course , lti = Fals...
Helper for the GET methods of the two following classes
229,882
def API_GET ( self , courseid , taskid , submissionid ) : with_input = "input" in web . input ( ) return _get_submissions ( self . course_factory , self . submission_manager , self . user_manager , self . app . _translations , courseid , taskid , with_input , submissionid )
List all the submissions that the connected user made . Returns list of the form
229,883
def is_registration_possible ( self , user_info ) : return self . get_accessibility ( ) . is_open ( ) and self . _registration . is_open ( ) and self . is_user_accepted_by_access_control ( user_info )
Returns true if users can register for this course
229,884
def get_accessibility ( self , plugin_override = True ) : vals = self . _hook_manager . call_hook ( 'course_accessibility' , course = self , default = self . _accessible ) return vals [ 0 ] if len ( vals ) and plugin_override else self . _accessible
Return the AccessibleTime object associated with the accessibility of this course
229,885
def is_user_accepted_by_access_control ( self , user_info ) : if self . get_access_control_method ( ) is None : return True elif not user_info : return False elif self . get_access_control_method ( ) == "username" : return user_info [ "username" ] in self . get_access_control_list ( ) elif self . get_access_control_met...
Returns True if the user is allowed by the ACL
229,886
def allow_unregister ( self , plugin_override = True ) : vals = self . _hook_manager . call_hook ( 'course_allow_unregister' , course = self , default = self . _allow_unregister ) return vals [ 0 ] if len ( vals ) and plugin_override else self . _allow_unregister
Returns True if students can unregister from course
229,887
def get_name ( self , language ) : return self . gettext ( language , self . _name ) if self . _name else ""
Return the name of this course
229,888
def get_description ( self , language ) : description = self . gettext ( language , self . _description ) if self . _description else '' return ParsableText ( description , "rst" , self . _translations . get ( language , gettext . NullTranslations ( ) ) )
Returns the course description
229,889
def get_all_tags_names_as_list ( self , admin = False , language = "en" ) : if admin : if self . _all_tags_cache_list_admin != { } and language in self . _all_tags_cache_list_admin : return self . _all_tags_cache_list_admin [ language ] else : if self . _all_tags_cache_list != { } and language in self . _all_tags_cache...
Computes and cache two list containing all tags name sorted by natural order on name
229,890
def update_all_tags_cache ( self ) : self . _all_tags_cache = None self . _all_tags_cache_list = { } self . _all_tags_cache_list_admin = { } self . _organisational_tags_to_task = { } self . get_all_tags ( ) self . get_all_tags_names_as_list ( ) self . get_organisational_tags_to_task ( )
Force the cache refreshing
229,891
def get_app ( config ) : mongo_client = MongoClient ( host = config . get ( 'mongo_opt' , { } ) . get ( 'host' , 'localhost' ) ) database = mongo_client [ config . get ( 'mongo_opt' , { } ) . get ( 'database' , 'INGInious' ) ] if "tasks_directory" not in config : raise RuntimeError ( "WebDav access is only supported if...
Init the webdav app
229,892
def getDomainRealm ( self , inputURL , environ ) : if inputURL . startswith ( "/" ) : inputURL = inputURL [ 1 : ] parts = inputURL . split ( "/" ) return parts [ 0 ]
Resolve a relative url to the appropriate realm name .
229,893
def isRealmUser ( self , realmname , username , environ ) : try : course = self . course_factory . get_course ( realmname ) ok = self . user_manager . has_admin_rights_on_course ( course , username = username ) return ok except : return False
Returns True if this username is valid for the realm False otherwise .
229,894
def getRealmUserPassword ( self , realmname , username , environ ) : return self . user_manager . get_user_api_key ( username , create = True )
Return the password for the given username for the realm .
229,895
def getResourceInst ( self , path , environ ) : self . _count_getResourceInst += 1 fp = self . _locToFilePath ( path ) if not os . path . exists ( fp ) : return None if os . path . isdir ( fp ) : return FolderResource ( path , environ , fp ) return FileResource ( path , environ , fp )
Return info dictionary for path .
229,896
def contains_is_html ( cls , data ) : for key , val in data . items ( ) : if isinstance ( key , str ) and key . endswith ( "IsHTML" ) : return True if isinstance ( val , ( OrderedDict , dict ) ) and cls . contains_is_html ( val ) : return True return False
Detect if the problem has at least one xyzIsHTML key
229,897
def parse_problem ( self , problem_content ) : del problem_content [ "@order" ] return self . task_factory . get_problem_types ( ) . get ( problem_content [ "type" ] ) . parse_problem ( problem_content )
Parses a problem modifying some data
229,898
def wipe_task ( self , courseid , taskid ) : submissions = self . database . submissions . find ( { "courseid" : courseid , "taskid" : taskid } ) for submission in submissions : for key in [ "input" , "archive" ] : if key in submission and type ( submission [ key ] ) == bson . objectid . ObjectId : self . submission_ma...
Wipe the data associated to the taskid from DB
229,899
def _exception_free_callback ( self , callback , * args , ** kwargs ) : try : return callback ( * args , ** kwargs ) except Exception : self . _logger . exception ( "An exception occurred while calling a hook! " , exc_info = True ) return None
A wrapper that remove all exceptions raised from hooks