INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Returns True if students can unregister from course
def allow_unregister(self, plugin_override=True): """ Returns True if students can unregister from course """ 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
Return the name of this course
def get_name(self, language): """ Return the name of this course """ return self.gettext(language, self._name) if self._name else ""
Returns the course description
def get_description(self, language): """Returns the course description """ description = self.gettext(language, self._description) if self._description else '' return ParsableText(description, "rst", self._translations.get(language, gettext.NullTranslations()))
Return a tuple of lists ([common_tags], [anti_tags], [organisational_tags]) all tags of all tasks of this course Since this is an heavy procedure, we use a cache to cache results. Cache should be updated when a task is modified.
def get_all_tags(self): """ Return a tuple of lists ([common_tags], [anti_tags], [organisational_tags]) all tags of all tasks of this course Since this is an heavy procedure, we use a cache to cache results. Cache should be updated when a task is modified. """ if self....
Computes and cache two list containing all tags name sorted by natural order on name
def get_all_tags_names_as_list(self, admin=False, language="en"): """ Computes and cache two list containing all tags name sorted by natural order on name """ if admin: if self._all_tags_cache_list_admin != {} and language in self._all_tags_cache_list_admin: return self._all...
This build a dict for fast retrive tasks id based on organisational tags. The form of the dict is: { 'org_tag_1': ['task_id', 'task_id', ...], 'org_tag_2' : ['task_id', 'task_id', ...], ... }
def get_organisational_tags_to_task(self): """ This build a dict for fast retrive tasks id based on organisational tags. The form of the dict is: { 'org_tag_1': ['task_id', 'task_id', ...], 'org_tag_2' : ['task_id', 'task_id', ...], ... } """ i...
Force the cache refreshing
def update_all_tags_cache(self): """ Force the cache refreshing """ 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_n...
Init the webdav app
def get_app(config): """ Init the webdav app """ mongo_client = MongoClient(host=config.get('mongo_opt', {}).get('host', 'localhost')) database = mongo_client[config.get('mongo_opt', {}).get('database', 'INGInious')] # Create the FS provider if "tasks_directory" not in config: raise Runtime...
Resolve a relative url to the appropriate realm name.
def getDomainRealm(self, inputURL, environ): """Resolve a relative url to the appropriate realm name.""" # we don't get the realm here, its already been resolved in # request_resolver if inputURL.startswith("/"): inputURL = inputURL[1:] parts = inputURL.split("/") ...
Returns True if this username is valid for the realm, False otherwise.
def isRealmUser(self, realmname, username, environ): """Returns True if this username is valid for the realm, False otherwise.""" try: course = self.course_factory.get_course(realmname) ok = self.user_manager.has_admin_rights_on_course(course, username=username) retur...
Return the password for the given username for the realm. Used for digest authentication.
def getRealmUserPassword(self, realmname, username, environ): """Return the password for the given username for the realm. Used for digest authentication. """ return self.user_manager.get_user_api_key(username, create=True)
Returns True if this username/password pair is valid for the realm, False otherwise. Used for basic authentication.
def authDomainUser(self, realmname, username, password, environ): """Returns True if this username/password pair is valid for the realm, False otherwise. Used for basic authentication.""" try: apikey = self.user_manager.get_user_api_key(username, create=None) return apike...
Return info dictionary for path. See DAVProvider.getResourceInst()
def getResourceInst(self, path, environ): """Return info dictionary for path. See DAVProvider.getResourceInst() """ self._count_getResourceInst += 1 fp = self._locToFilePath(path) if not os.path.exists(fp): return None if os.path.isdir(fp): ...
GET request
def GET_AUTH(self, courseid): # pylint: disable=arguments-differ """ GET request """ course, __ = self.get_course_and_check_rights(courseid) return self.page(course)
POST request
def POST_AUTH(self, courseid): # pylint: disable=arguments-differ """ POST request """ course, __ = self.get_course_and_check_rights(courseid, None, False) data = web.input() if "remove" in data: try: if data["type"] == "all": aggregations...
Get all data and display the page
def page(self, course, error="", post=False): """ Get all data and display the page """ users = sorted(list(self.user_manager.get_users_info(self.user_manager.get_course_registered_users(course, False)).items()), key=lambda k: k[1][0] if k[1] is not None else "") users = ...
GET request
def GET_AUTH(self, submissionid): # pylint: disable=arguments-differ """ GET request """ course, task, submission = self.fetch_submission(submissionid) return self.page(course, task, submission)
Get all data and display the page
def page(self, course, task, submission): """ Get all data and display the page """ submission = self.submission_manager.get_input_from_submission(submission) submission = self.submission_manager.get_feedback_from_submission( submission, show_everything=True, ...
Edit a task
def GET_AUTH(self, courseid, taskid): # pylint: disable=arguments-differ """ Edit a task """ if not id_checker(taskid): raise Exception("Invalid task id") course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=False) try: task_data = self.task_...
Detect if the problem has at least one "xyzIsHTML" key
def contains_is_html(cls, data): """ Detect if the problem has at least one "xyzIsHTML" key """ 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): ...
>>> from collections import OrderedDict >>> od = OrderedDict() >>> od["problem[q0][a]"]=1 >>> od["problem[q0][b][c]"]=2 >>> od["problem[q1][first]"]=1 >>> od["problem[q1][second]"]=2 >>> AdminCourseEditTask.dict_from_prefix("problem",od) ...
def dict_from_prefix(cls, prefix, dictionary): """ >>> from collections import OrderedDict >>> od = OrderedDict() >>> od["problem[q0][a]"]=1 >>> od["problem[q0][b][c]"]=2 >>> od["problem[q1][first]"]=1 >>> od["problem[q1][second]"]=2 ...
Parses a problem, modifying some data
def parse_problem(self, problem_content): """ Parses a problem, modifying some data """ del problem_content["@order"] return self.task_factory.get_problem_types().get(problem_content["type"]).parse_problem(problem_content)
Wipe the data associated to the taskid from DB
def wipe_task(self, courseid, taskid): """ Wipe the data associated to the taskid from DB""" submissions = self.database.submissions.find({"courseid": courseid, "taskid": taskid}) for submission in submissions: for key in ["input", "archive"]: if key in submission and...
Edit a task
def POST_AUTH(self, courseid, taskid): # pylint: disable=arguments-differ """ Edit a task """ if not id_checker(taskid) or not id_checker(courseid): raise Exception("Invalid course/task id") course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=False) data...
Display main course list page
def GET(self): # pylint: disable=arguments-differ """ Display main course list page """ if not self.app.welcome_page: raise web.seeother("/courselist") return self.show_page(self.app.welcome_page)
Display main course list page
def POST(self): # pylint: disable=arguments-differ """ Display main course list page """ if not self.app.welcome_page: raise web.seeother("/courselist") return self.show_page(self.app.welcome_page)
GET request
def GET_AUTH(self, courseid): # pylint: disable=arguments-differ """ GET request """ course = self.course_factory.get_course(courseid) username = self.user_manager.session_username() error = False change = False msg = "" data = web.input() if self.user_...
A wrapper that remove all exceptions raised from hooks
def _exception_free_callback(self, callback, *args, **kwargs): """ A wrapper that remove all exceptions raised from hooks """ try: return callback(*args, **kwargs) except Exception: self._logger.exception("An exception occurred while calling a hook! ",exc_info=True) ...
Add a new hook that can be called with the call_hook function. `prio` is the priority. Higher priority hooks are called before lower priority ones. This function does not enforce a particular order between hooks with the same priorities.
def add_hook(self, name, callback, prio=0): """ Add a new hook that can be called with the call_hook function. `prio` is the priority. Higher priority hooks are called before lower priority ones. This function does not enforce a particular order between hooks with the same priorities. ...
Call all hooks registered with this name. Returns a list of the returns values of the hooks (in the order the hooks were added)
def call_hook(self, name, **kwargs): """ Call all hooks registered with this name. Returns a list of the returns values of the hooks (in the order the hooks were added)""" return [y for y in [x(**kwargs) for x, _ in self._hooks.get(name, [])] if y is not None]
Call all hooks registered with this name. Each hook receives as arguments the return value of the previous hook call, or the initial params for the first hook. As such, each hook must return a dictionary with the received (eventually modified) args. Returns the modified args.
def call_hook_recursive(self, name, **kwargs): """ Call all hooks registered with this name. Each hook receives as arguments the return value of the previous hook call, or the initial params for the first hook. As such, each hook must return a dictionary with the received (eventually mod...
Check if an input for a task is consistent. Return true if this is case, false else
def input_is_consistent(self, task_input, default_allowed_extension, default_max_size): """ Check if an input for a task is consistent. Return true if this is case, false else """ for problem in self._problems: if not problem.input_is_consistent(task_input, default_allowed_extension, default...
Return the limits of this task
def get_limits(self): """ Return the limits of this task """ vals = self._hook_manager.call_hook('task_limits', course=self.get_course(), task=self, default=self._limits) return vals[0] if len(vals) else self._limits
Return True if the grading container should have access to the network
def allow_network_access_grading(self): """ Return True if the grading container should have access to the network """ vals = self._hook_manager.call_hook('task_network_grading', course=self.get_course(), task=self, default=self._network_grading) return vals[0] if len(vals) else self._network_gr...
Verify the answers in task_input. Returns six values 1st: True the input is **currently** valid. (may become invalid after running the code), False else 2nd: True if the input needs to be run in the VM, False else 3rd: Main message, as a list (that can be join with \n or <br/> for ex...
def check_answer(self, task_input, language): """ Verify the answers in task_input. Returns six values 1st: True the input is **currently** valid. (may become invalid after running the code), False else 2nd: True if the input needs to be run in the VM, False else ...
Creates a new instance of the right class for a given problem.
def _create_task_problem(self, problemid, problem_content, task_problem_types): """Creates a new instance of the right class for a given problem.""" # Basic checks if not id_checker(problemid): raise Exception("Invalid problem _id: " + problemid) if problem_content.get('type'...
Init logging :param log_level: An integer representing the log level or a string representing one
def init_logging(log_level=logging.DEBUG): """ Init logging :param log_level: An integer representing the log level or a string representing one """ logging.root.handlers = [] # remove possible side-effects from other libs logger = logging.getLogger("inginious") logger.setLevel(log_level) ...
Displays the link to the scoreboards on the course page, if the plugin is activated for this course
def course_menu(course, template_helper): """ Displays the link to the scoreboards on the course page, if the plugin is activated for this course """ scoreboards = course.get_descriptor().get('scoreboard', []) if scoreboards != []: return str(template_helper.get_custom_renderer('frontend/plugins/sc...
Displays the link to the scoreboards on the task page, if the plugin is activated for this course and the task is used in scoreboards
def task_menu(course, task, template_helper): """ Displays the link to the scoreboards on the task page, if the plugin is activated for this course and the task is used in scoreboards """ scoreboards = course.get_descriptor().get('scoreboard', []) try: tolink = [] for sid, scoreboard in enum...
Init the plugin. Available configuration in configuration.yaml: :: - plugin_module: "inginious.frontend.plugins.scoreboard" Available configuration in course.yaml: :: - scoreboard: #you can define multiple scoreboards - content: "taskid1" #creat...
def init(plugin_manager, _, _2, _3): """ Init the plugin. Available configuration in configuration.yaml: :: - plugin_module: "inginious.frontend.plugins.scoreboard" Available configuration in course.yaml: :: - scoreboard: #you can define multiple sc...
GET request
def GET_AUTH(self, courseid): # pylint: disable=arguments-differ """ GET request """ course = self.course_factory.get_course(courseid) scoreboards = course.get_descriptor().get('scoreboard', []) try: names = {i: val["name"] for i, val in enumerate(scoreboards)} exce...
GET request
def GET_AUTH(self, courseid, scoreboardid): # pylint: disable=arguments-differ """ GET request """ course = self.course_factory.get_course(courseid) scoreboards = course.get_descriptor().get('scoreboard', []) try: scoreboardid = int(scoreboardid) scoreboard_name...
Fixes a bug in web.py. See #208. PR is waiting to be merged upstream at https://github.com/webpy/webpy/pull/419 TODO: remove me once PR is merged upstream.
def fix_webpy_cookies(): """ Fixes a bug in web.py. See #208. PR is waiting to be merged upstream at https://github.com/webpy/webpy/pull/419 TODO: remove me once PR is merged upstream. """ try: web.webapi.parse_cookies('a="test"') # make the bug occur except NameError: # monkey...
Get the available student and tutor lists for classroom edition
def get_user_lists(self, course, classroomid): """ Get the available student and tutor lists for classroom edition""" tutor_list = course.get_staff() # Determine if user is grouped or not in the classroom student_list = list(self.database.classrooms.aggregate([ {"$match": {"...
Update classroom and returns a list of errored students
def update_classroom(self, course, classroomid, new_data): """ Update classroom and returns a list of errored students""" student_list, tutor_list, other_students, _ = self.get_user_lists(course, classroomid) # Check tutors new_data["tutors"] = [tutor for tutor in map(str.strip, new_dat...
Edit a classroom
def GET_AUTH(self, courseid, classroomid): # pylint: disable=arguments-differ """ Edit a classroom """ course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=True) if course.is_lti(): raise web.notfound() student_list, tutor_list, other_students, users_info...
Edit a classroom
def POST_AUTH(self, courseid, classroomid): # pylint: disable=arguments-differ """ Edit a classroom """ course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=True) if course.is_lti(): raise web.notfound() error = False data = web.input(tutors=[], ...
Returns parsed text
def parse(self, debug=False): """Returns parsed text""" if self._parsed is None: try: if self._mode == "html": self._parsed = self.html(self._content, self._show_everything, self._translation) else: self._parsed = self.r...
Parses HTML
def html(cls, string, show_everything=False, translation=gettext.NullTranslations()): # pylint: disable=unused-argument """Parses HTML""" out, _ = tidylib.tidy_fragment(string) return out
Parses reStructuredText
def rst(cls, string, show_everything=False, translation=gettext.NullTranslations(), initial_header_level=3, debug=False): """Parses reStructuredText""" overrides = { 'initial_header_level': initial_header_level, 'doctitle_xform': False, 'syntax_highlight': 'none', ...
POST request
def POST_AUTH(self, courseid): # pylint: disable=arguments-differ """ POST request """ course, __ = self.get_course_and_check_rights(courseid) data = web.input(task=[]) if "task" in data: # Change tasks order for index, taskid in enumerate(data["task"]): ...
Get all data and display the page
def page(self, course): """ Get all data and display the page """ data = list(self.database.user_tasks.aggregate( [ { "$match": { "courseid": course.get_id(), "username": {"$in...
Edit a task
def GET_AUTH(self, courseid, taskid): # pylint: disable=arguments-differ """ Edit a task """ if not id_checker(taskid): raise Exception("Invalid task id") self.get_course_and_check_rights(courseid, allow_all_staff=False) request = web.input() if request.get("action...
Upload or modify a file
def POST_AUTH(self, courseid, taskid): # pylint: disable=arguments-differ """ Upload or modify a file """ if not id_checker(taskid): raise Exception("Invalid task id") self.get_course_and_check_rights(courseid, allow_all_staff=False) request = web.input(file={}) if...
Return the file tab
def show_tab_file(self, courseid, taskid, error=None): """ Return the file tab """ return self.template_helper.get_renderer(False).course_admin.edit_tabs.files( self.course_factory.get_course(courseid), taskid, self.get_task_filelist(self.task_factory, courseid, taskid), error)
Returns a flattened version of all the files inside the task directory, excluding the files task.* and hidden files. It returns a list of tuples, of the type (Integer Level, Boolean IsDirectory, String Name, String CompleteName)
def get_task_filelist(cls, task_factory, courseid, taskid): """ Returns a flattened version of all the files inside the task directory, excluding the files task.* and hidden files. It returns a list of tuples, of the type (Integer Level, Boolean IsDirectory, String Name, String CompleteName) ...
Return the real wanted path (relative to the INGInious root) or None if the path is not valid/allowed
def verify_path(self, courseid, taskid, path, new_path=False): """ Return the real wanted path (relative to the INGInious root) or None if the path is not valid/allowed """ task_fs = self.task_factory.get_task_fs(courseid, taskid) # verify that the dir exists if not task_fs.exists(): ...
Edit a file
def action_edit(self, courseid, taskid, path): """ Edit a file """ wanted_path = self.verify_path(courseid, taskid, path) if wanted_path is None: return "Internal error" try: content = self.task_factory.get_task_fs(courseid, taskid).get(wanted_path).decode("utf-8"...
Save an edited file
def action_edit_save(self, courseid, taskid, path, content): """ Save an edited file """ wanted_path = self.verify_path(courseid, taskid, path) if wanted_path is None: return json.dumps({"error": True}) try: self.task_factory.get_task_fs(courseid, taskid).put(want...
Upload a file
def action_upload(self, courseid, taskid, path, fileobj): """ Upload a file """ # the path is given by the user. Let's normalize it path = path.strip() if not path.startswith("/"): path = "/" + path wanted_path = self.verify_path(courseid, taskid, path, True) ...
Delete a file or a directory
def action_create(self, courseid, taskid, path): """ Delete a file or a directory """ # the path is given by the user. Let's normalize it path = path.strip() if not path.startswith("/"): path = "/" + path want_directory = path.endswith("/") wanted_path = sel...
Delete a file or a directory
def action_rename(self, courseid, taskid, path, new_path): """ Delete a file or a directory """ # normalize path = path.strip() new_path = new_path.strip() if not path.startswith("/"): path = "/" + path if not new_path.startswith("/"): new_path = "...
Delete a file or a directory
def action_delete(self, courseid, taskid, path): """ Delete a file or a directory """ # normalize path = path.strip() if not path.startswith("/"): path = "/" + path wanted_path = self.verify_path(courseid, taskid, path) if wanted_path is None: ret...
Download a file or a directory
def action_download(self, courseid, taskid, path): """ Download a file or a directory """ wanted_path = self.verify_path(courseid, taskid, path) if wanted_path is None: raise web.notfound() task_fs = self.task_factory.get_task_fs(courseid, taskid) (method, mimetype_...
Load JSON or YAML depending on the file extension. Returns a dict
def load_json_or_yaml(file_path): """ Load JSON or YAML depending on the file extension. Returns a dict """ with open(file_path, "r") as f: if os.path.splitext(file_path)[1] == ".json": return json.load(f) else: return inginious.common.custom_yaml.load(f)
Load JSON or YAML depending on the file extension. Returns a dict
def loads_json_or_yaml(file_path, content): """ Load JSON or YAML depending on the file extension. Returns a dict """ if os.path.splitext(file_path)[1] == ".json": return json.loads(content) else: return inginious.common.custom_yaml.load(content)
Write JSON or YAML depending on the file extension.
def write_json_or_yaml(file_path, content): """ Write JSON or YAML depending on the file extension. """ with codecs.open(file_path, "w", "utf-8") as f: f.write(get_json_or_yaml(file_path, content))
Generate JSON or YAML depending on the file extension.
def get_json_or_yaml(file_path, content): """ Generate JSON or YAML depending on the file extension. """ if os.path.splitext(file_path)[1] == ".json": return json.dumps(content, sort_keys=False, indent=4, separators=(',', ': ')) else: return inginious.common.custom_yaml.dump(content)
:param fileobj: a file object :return: a hash of the file content
def hash_file(fileobj): """ :param fileobj: a file object :return: a hash of the file content """ hasher = hashlib.md5() buf = fileobj.read(65536) while len(buf) > 0: hasher.update(buf) buf = fileobj.read(65536) return hasher.hexdigest()
:param directory: directory in which the function list the files :return: dict in the form {file: (hash of the file, stat of the file)}
def directory_content_with_hash(directory): """ :param directory: directory in which the function list the files :return: dict in the form {file: (hash of the file, stat of the file)} """ output = {} for root, _, filenames in os.walk(directory): for filename in filenames: p =...
:param from_directory: dict in the form {file: (hash of the file, stat of the file)} from directory_content_with_hash :param to_directory: dict in the form {file: (hash of the file, stat of the file)} from directory_content_with_hash :return: a tuple containing two list: the files that should be uploaded to "to...
def directory_compare_from_hash(from_directory, to_directory): """ :param from_directory: dict in the form {file: (hash of the file, stat of the file)} from directory_content_with_hash :param to_directory: dict in the form {file: (hash of the file, stat of the file)} from directory_content_with_hash :re...
Init the session. Preserves potential LTI information.
def _set_session(self, username, realname, email, language): """ Init the session. Preserves potential LTI information. """ self._session.loggedin = True self._session.email = email self._session.username = username self._session.realname = realname self._session.language...
Destroy the session
def _destroy_session(self): """ Destroy the session """ self._session.loggedin = False self._session.email = None self._session.username = None self._session.realname = None self._session.token = None self._session.lti = None
Creates an LTI cookieless session. Returns the new session id
def create_lti_session(self, user_id, roles, realname, email, course_id, task_id, consumer_key, outcome_service_url, outcome_result_id, tool_name, tool_desc, tool_url, context_title, context_label): """ Creates an LTI cookieless session. Returns the new session id""" self._de...
Authenticate the user in database :param username: Username/Login :param password: User password :return: Returns a dict represrnting the user
def auth_user(self, username, password): """ Authenticate the user in database :param username: Username/Login :param password: User password :return: Returns a dict represrnting the user """ password_hash = hashlib.sha512(password.encode("utf-8")).hexdigest() ...
Opens a session for the user :param username: Username :param realname: User real name :param email: User email
def connect_user(self, username, realname, email, language): """ Opens a session for the user :param username: Username :param realname: User real name :param email: User email """ self._database.users.update_one({"email": email}, {"$set": {"realname": realname, ...
Disconnects the user currently logged-in :param ip_addr: the ip address of the client, that will be logged
def disconnect_user(self): """ Disconnects the user currently logged-in :param ip_addr: the ip address of the client, that will be logged """ if self.session_logged_in(): self._logger.info("User %s disconnected - %s - %s - %s", self.session_username(), self.session_re...
:param usernames: a list of usernames :return: a dict, in the form {username: val}, where val is either None if the user cannot be found, or a tuple (realname, email)
def get_users_info(self, usernames): """ :param usernames: a list of usernames :return: a dict, in the form {username: val}, where val is either None if the user cannot be found, or a tuple (realname, email) """ retval = {username: None for username in usernames} remainin...
Get the API key of a given user. API keys are generated on demand. :param username: :param create: Create the API key if none exists yet :return: the API key assigned to the user, or None if none exists and create is False.
def get_user_api_key(self, username, create=True): """ Get the API key of a given user. API keys are generated on demand. :param username: :param create: Create the API key if none exists yet :return: the API key assigned to the user, or None if none exists and create is ...
:param username: :return: a tuple (realname, email) if the user can be found, None else
def get_user_info(self, username): """ :param username: :return: a tuple (realname, email) if the user can be found, None else """ info = self.get_users_info([username]) return info[username] if info is not None else None
:param username: List of username for which we want info. If usernames is None, data from all users will be returned. :param course: A Course object :return: Returns data of the specified users for a specific course. users is a list of username. The returned value is a dict: ...
def get_course_caches(self, usernames, course): """ :param username: List of username for which we want info. If usernames is None, data from all users will be returned. :param course: A Course object :return: Returns data of the specified users for a specific course. users i...
Shorthand for get_task_caches([username], courseid, taskid)[username]
def get_task_cache(self, username, courseid, taskid): """ Shorthand for get_task_caches([username], courseid, taskid)[username] """ return self.get_task_caches([username], courseid, taskid)[username]
:param usernames: List of username for which we want info. If usernames is None, data from all users will be returned. :param courseid: the course id :param taskid: the task id :return: A dict in the form: :: { "username": { ...
def get_task_caches(self, usernames, courseid, taskid): """ :param usernames: List of username for which we want info. If usernames is None, data from all users will be returned. :param courseid: the course id :param taskid: the task id :return: A dict in the form: :...
Set in the database that the user has viewed this task
def user_saw_task(self, username, courseid, taskid): """ Set in the database that the user has viewed this task """ self._database.user_tasks.update({"username": username, "courseid": courseid, "taskid": taskid}, {"$setOnInsert": {"username": username, "courseid"...
Update stats with a new submission
def update_user_stats(self, username, task, submission, result_str, grade, state, newsub): """ Update stats with a new submission """ self.user_saw_task(username, submission["courseid"], submission["taskid"]) if newsub: old_submission = self._database.user_tasks.find_one_and_update(...
Returns true if the task is visible by the user :param lti: indicates if the user is currently in a LTI session or not. - None to ignore the check - True to indicate the user is in a LTI session - False to indicate the user is not in a LTI session - "auto" to enab...
def task_is_visible_by_user(self, task, username=None, lti=None): """ Returns true if the task is visible by the user :param lti: indicates if the user is currently in a LTI session or not. - None to ignore the check - True to indicate the user is in a LTI session - F...
returns true if the user can submit his work for this task :param only_check : only checks for 'groups', 'tokens', or None if all checks :param lti: indicates if the user is currently in a LTI session or not. - None to ignore the check - True to indicate the user is in a ...
def task_can_user_submit(self, task, username=None, only_check=None, lti=None): """ returns true if the user can submit his work for this task :param only_check : only checks for 'groups', 'tokens', or None if all checks :param lti: indicates if the user is currently in a LTI session or ...
Returns a list of the course aggregations
def get_course_aggregations(self, course): """ Returns a list of the course aggregations""" return natsorted(list(self._database.aggregations.find({"courseid": course.get_id()})), key=lambda x: x["description"])
Returns the classroom whose username belongs to :param course: a Course object :param username: The username of the user that we want to register. If None, uses self.session_username() :return: the classroom description
def get_course_user_aggregation(self, course, username=None): """ Returns the classroom whose username belongs to :param course: a Course object :param username: The username of the user that we want to register. If None, uses self.session_username() :return: the classroom description ...
Register a user to the course :param course: a Course object :param username: The username of the user that we want to register. If None, uses self.session_username() :param password: Password for the course. Needed if course.is_password_needed_for_registration() and force != True :param...
def course_register_user(self, course, username=None, password=None, force=False): """ Register a user to the course :param course: a Course object :param username: The username of the user that we want to register. If None, uses self.session_username() :param password: Password ...
Unregister a user to the course :param course: a Course object :param username: The username of the user that we want to unregister. If None, uses self.session_username()
def course_unregister_user(self, course, username=None): """ Unregister a user to the course :param course: a Course object :param username: The username of the user that we want to unregister. If None, uses self.session_username() """ if username is None: use...
Checks if a user is can access a course :param course: a Course object :param username: The username of the user that we want to check. If None, uses self.session_username() :param lti: indicates if the user is currently in a LTI session or not. - None to ignore the check ...
def course_is_open_to_user(self, course, username=None, lti=None): """ Checks if a user is can access a course :param course: a Course object :param username: The username of the user that we want to check. If None, uses self.session_username() :param lti: indicates if the user i...
Checks if a user is registered :param course: a Course object :param username: The username of the user that we want to check. If None, uses self.session_username() :return: True if the user is registered, False else
def course_is_user_registered(self, course, username=None): """ Checks if a user is registered :param course: a Course object :param username: The username of the user that we want to check. If None, uses self.session_username() :return: True if the user is registered, False else...
Get all the users registered to a course :param course: a Course object :param with_admins: include admins? :return: a list of usernames that are registered to the course
def get_course_registered_users(self, course, with_admins=True): """ Get all the users registered to a course :param course: a Course object :param with_admins: include admins? :return: a list of usernames that are registered to the course """ l = [entry['student...
:param username: the username. If None, the username of the currently logged in user is taken :return: True if the user is superadmin, False else
def user_is_superadmin(self, username=None): """ :param username: the username. If None, the username of the currently logged in user is taken :return: True if the user is superadmin, False else """ if username is None: username = self.session_username() retu...
Check if a user can be considered as having admin rights for a course :type course: webapp.custom.courses.WebAppCourse :param username: the username. If None, the username of the currently logged in user is taken :param include_superadmins: Boolean indicating if superadmins should be taken into ...
def has_admin_rights_on_course(self, course, username=None, include_superadmins=True): """ Check if a user can be considered as having admin rights for a course :type course: webapp.custom.courses.WebAppCourse :param username: the username. If None, the username of the currently logged i...
Check if a user can be considered as having staff rights for a course :type course: webapp.custom.courses.WebAppCourse :param username: the username. If None, the username of the currently logged in user is taken :param include_superadmins: Boolean indicating if superadmins should be taken into ...
def has_staff_rights_on_course(self, course, username=None, include_superadmins=True): """ Check if a user can be considered as having staff rights for a course :type course: webapp.custom.courses.WebAppCourse :param username: the username. If None, the username of the currently logged i...
Get the accessible time of this task
def get_accessible_time(self, plugin_override=True): """ Get the accessible time of this task """ vals = self._hook_manager.call_hook('task_accessibility', course=self.get_course(), task=self, default=self._accessible) return vals[0] if len(vals) and plugin_override else self._accessible
Returns a string containing the deadline for this task
def get_deadline(self): """ Returns a string containing the deadline for this task """ if self.get_accessible_time().is_always_accessible(): return _("No deadline") elif self.get_accessible_time().is_never_accessible(): return _("It's too late") else: ...
Get the context(description) of this task
def get_context(self, language): """ Get the context(description) of this task """ context = self.gettext(language, self._context) if self._context else "" vals = self._hook_manager.call_hook('task_context', course=self.get_course(), task=self, default=context) return ParsableText(vals[0...