repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager._handle_ssh_callback
def _handle_ssh_callback(self, submission_id, host, port, password): """ Handles the creation of a remote ssh server """ if host is not None: # ignore late calls (a bit hacky, but...) obj = { "ssh_host": host, "ssh_port": port, "ssh_password": password } self._database.submissions.update_one({"_id": submission_id}, {"$set": obj})
python
def _handle_ssh_callback(self, submission_id, host, port, password): """ Handles the creation of a remote ssh server """ if host is not None: # ignore late calls (a bit hacky, but...) obj = { "ssh_host": host, "ssh_port": port, "ssh_password": password } self._database.submissions.update_one({"_id": submission_id}, {"$set": obj})
[ "def", "_handle_ssh_callback", "(", "self", ",", "submission_id", ",", "host", ",", "port", ",", "password", ")", ":", "if", "host", "is", "not", "None", ":", "# ignore late calls (a bit hacky, but...)", "obj", "=", "{", "\"ssh_host\"", ":", "host", ",", "\"ss...
Handles the creation of a remote ssh server
[ "Handles", "the", "creation", "of", "a", "remote", "ssh", "server" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L569-L577
train
229,800
UCL-INGI/INGInious
inginious/common/entrypoints.py
filesystem_from_config_dict
def filesystem_from_config_dict(config_fs): """ 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. """ 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: print("Unknown filesystem provider "+config_fs["module"], file=sys.stderr) exit(1) fs_class = filesystem_providers[config_fs["module"]] fs_args_needed = fs_class.get_needed_args() fs_args = {} for arg_name, (arg_type, arg_required, _) in fs_args_needed.items(): if arg_name in config_fs: fs_args[arg_name] = arg_type(config_fs[arg_name]) elif arg_required: print("fs option {} is required".format(arg_name), file=sys.stderr) exit(1) try: return fs_class.init_from_args(**fs_args) except: print("Unable to load class " + config_fs["module"], file=sys.stderr) raise
python
def filesystem_from_config_dict(config_fs): """ 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. """ 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: print("Unknown filesystem provider "+config_fs["module"], file=sys.stderr) exit(1) fs_class = filesystem_providers[config_fs["module"]] fs_args_needed = fs_class.get_needed_args() fs_args = {} for arg_name, (arg_type, arg_required, _) in fs_args_needed.items(): if arg_name in config_fs: fs_args[arg_name] = arg_type(config_fs[arg_name]) elif arg_required: print("fs option {} is required".format(arg_name), file=sys.stderr) exit(1) try: return fs_class.init_from_args(**fs_args) except: print("Unable to load class " + config_fs["module"], file=sys.stderr) raise
[ "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", ")", "e...
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.
[ "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", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/entrypoints.py#L20-L48
train
229,801
UCL-INGI/INGInious
inginious/agent/docker_agent/_timeout_watcher.py
TimeoutWatcher._kill_it_with_fire
async def _kill_it_with_fire(self, container_id): """ Kill a container, with fire. """ 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
python
async def _kill_it_with_fire(self, container_id): """ Kill a container, with fire. """ 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
[ "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", "...
Kill a container, with fire.
[ "Kill", "a", "container", "with", "fire", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/docker_agent/_timeout_watcher.py#L95-L105
train
229,802
UCL-INGI/INGInious
inginious/frontend/cookieless_app.py
CookieLessCompatibleSession._cleanup
def _cleanup(self): """Cleanup the stored sessions""" 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
python
def _cleanup(self): """Cleanup the stored sessions""" 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
[ "def", "_cleanup", "(", "self", ")", ":", "current_time", "=", "time", ".", "time", "(", ")", "timeout", "=", "self", ".", "_config", ".", "timeout", "if", "current_time", "-", "self", ".", "_last_cleanup_time", ">", "timeout", ":", "self", ".", "store",...
Cleanup the stored sessions
[ "Cleanup", "the", "stored", "sessions" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/cookieless_app.py#L255-L261
train
229,803
UCL-INGI/INGInious
inginious/frontend/cookieless_app.py
CookieLessCompatibleSession.expired
def expired(self): """Called when an expired session is atime""" self._data["_killed"] = True self.save() raise SessionExpired(self._config.expired_message)
python
def expired(self): """Called when an expired session is atime""" self._data["_killed"] = True self.save() raise SessionExpired(self._config.expired_message)
[ "def", "expired", "(", "self", ")", ":", "self", ".", "_data", "[", "\"_killed\"", "]", "=", "True", "self", ".", "save", "(", ")", "raise", "SessionExpired", "(", "self", ".", "_config", ".", "expired_message", ")" ]
Called when an expired session is atime
[ "Called", "when", "an", "expired", "session", "is", "atime" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/cookieless_app.py#L263-L267
train
229,804
UCL-INGI/INGInious
inginious/frontend/pages/preferences/delete.py
DeletePage.delete_account
def delete_account(self, data): """ Delete account from DB """ error = False msg = "" username = self.user_manager.session_username() # Check input format 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.") else: self.database.submissions.remove({"username": username}) self.database.user_tasks.remove({"username": username}) all_courses = self.course_factory.get_all_courses() for courseid, course in all_courses.items(): if self.user_manager.course_is_open_to_user(course, username): self.user_manager.course_unregister_user(course, username) self.user_manager.disconnect_user() raise web.seeother("/index") return msg, error
python
def delete_account(self, data): """ Delete account from DB """ error = False msg = "" username = self.user_manager.session_username() # Check input format 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.") else: self.database.submissions.remove({"username": username}) self.database.user_tasks.remove({"username": username}) all_courses = self.course_factory.get_all_courses() for courseid, course in all_courses.items(): if self.user_manager.course_is_open_to_user(course, username): self.user_manager.course_unregister_user(course, username) self.user_manager.disconnect_user() raise web.seeother("/index") return msg, error
[ "def", "delete_account", "(", "self", ",", "data", ")", ":", "error", "=", "False", "msg", "=", "\"\"", "username", "=", "self", ".", "user_manager", ".", "session_username", "(", ")", "# Check input format", "result", "=", "self", ".", "database", ".", "u...
Delete account from DB
[ "Delete", "account", "from", "DB" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/preferences/delete.py#L15-L41
train
229,805
UCL-INGI/INGInious
inginious/common/custom_yaml.py
dump
def dump(data, stream=None, **kwds): """ 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. Safe version. If objects are not "conventional" objects, they will be dumped converted to string with the str() function. They will then not be recovered when loading with the load() function. """ # Display OrderedDicts correctly class OrderedDumper(SafeDumper): pass def _dict_representer(dumper, data): return dumper.represent_mapping( original_yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, list(data.items())) # Display long strings correctly def _long_str_representer(dumper, data): if data.find("\n") != -1: # Drop some uneeded data # \t are forbidden in YAML data = data.replace("\t", " ") # empty spaces at end of line are always useless in INGInious, and forbidden in YAML data = "\n".join([p.rstrip() for p in data.split("\n")]) return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') else: return dumper.represent_scalar('tag:yaml.org,2002:str', data) # Default representation for some odd objects def _default_representer(dumper, data): return _long_str_representer(dumper, str(data)) OrderedDumper.add_representer(str, _long_str_representer) OrderedDumper.add_representer(str, _long_str_representer) OrderedDumper.add_representer(OrderedDict, _dict_representer) OrderedDumper.add_representer(None, _default_representer) s = original_yaml.dump(data, stream, OrderedDumper, encoding='utf-8', allow_unicode=True, default_flow_style=False, indent=4, **kwds) if s is not None: return s.decode('utf-8') else: return
python
def dump(data, stream=None, **kwds): """ 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. Safe version. If objects are not "conventional" objects, they will be dumped converted to string with the str() function. They will then not be recovered when loading with the load() function. """ # Display OrderedDicts correctly class OrderedDumper(SafeDumper): pass def _dict_representer(dumper, data): return dumper.represent_mapping( original_yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, list(data.items())) # Display long strings correctly def _long_str_representer(dumper, data): if data.find("\n") != -1: # Drop some uneeded data # \t are forbidden in YAML data = data.replace("\t", " ") # empty spaces at end of line are always useless in INGInious, and forbidden in YAML data = "\n".join([p.rstrip() for p in data.split("\n")]) return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') else: return dumper.represent_scalar('tag:yaml.org,2002:str', data) # Default representation for some odd objects def _default_representer(dumper, data): return _long_str_representer(dumper, str(data)) OrderedDumper.add_representer(str, _long_str_representer) OrderedDumper.add_representer(str, _long_str_representer) OrderedDumper.add_representer(OrderedDict, _dict_representer) OrderedDumper.add_representer(None, _default_representer) s = original_yaml.dump(data, stream, OrderedDumper, encoding='utf-8', allow_unicode=True, default_flow_style=False, indent=4, **kwds) if s is not None: return s.decode('utf-8') else: return
[ "def", "dump", "(", "data", ",", "stream", "=", "None", ",", "*", "*", "kwds", ")", ":", "# Display OrderedDicts correctly", "class", "OrderedDumper", "(", "SafeDumper", ")", ":", "pass", "def", "_dict_representer", "(", "dumper", ",", "data", ")", ":", "r...
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. Safe version. If objects are not "conventional" objects, they will be dumped converted to string with the str() function. They will then not be recovered when loading with the load() function.
[ "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", ...
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/custom_yaml.py#L40-L87
train
229,806
UCL-INGI/INGInious
inginious/frontend/pages/api/tasks.py
APITasks._check_for_parsable_text
def _check_for_parsable_text(self, val): """ Util to remove parsable text from a dict, recursively """ 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(): val[key] = self._check_for_parsable_text(val2) return val
python
def _check_for_parsable_text(self, val): """ Util to remove parsable text from a dict, recursively """ 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(): val[key] = self._check_for_parsable_text(val2) return val
[ "def", "_check_for_parsable_text", "(", "self", ",", "val", ")", ":", "if", "isinstance", "(", "val", ",", "ParsableText", ")", ":", "return", "val", ".", "original_content", "(", ")", "if", "isinstance", "(", "val", ",", "list", ")", ":", "for", "key", ...
Util to remove parsable text from a dict, recursively
[ "Util", "to", "remove", "parsable", "text", "from", "a", "dict", "recursively" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/tasks.py#L17-L28
train
229,807
UCL-INGI/INGInious
inginious/frontend/pages/api/tasks.py
APITasks.API_GET
def API_GET(self, courseid, taskid=None): # pylint: disable=arguments-differ """ List tasks available to the connected client. Returns a dict in the form :: { "taskid1": { "name": "Name of the course", #the name of the course "authors": [], "deadline": "", "status": "success" # can be "succeeded", "failed" or "notattempted" "grade": 0.0, "grade_weight": 0.0, "context": "" # context of the task, in RST "problems": # dict of the subproblems { # see the format of task.yaml for the content of the dict. Contains everything but # responses of multiple-choice and match problems. } } #... } If you use the endpoint /api/v0/courses/the_course_id/tasks/the_task_id, this dict will contain one entry or the page will return 404 Not Found. """ 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 None: tasks = course.get_tasks() else: try: tasks = {taskid: course.get_task(taskid)} except: raise APINotFound("Task not found") output = [] for taskid, task in tasks.items(): task_cache = self.user_manager.get_task_cache(self.user_manager.session_username(), task.get_course_id(), task.get_id()) data = { "id": taskid, "name": task.get_name(self.user_manager.session_language()), "authors": task.get_authors(self.user_manager.session_language()), "deadline": task.get_deadline(), "status": "notviewed" if task_cache is None else "notattempted" if task_cache["tried"] == 0 else "succeeded" if task_cache["succeeded"] else "failed", "grade": task_cache.get("grade", 0.0) if task_cache is not None else 0.0, "grade_weight": task.get_grading_weight(), "context": task.get_context(self.user_manager.session_language()).original_content(), "problems": [] } for problem in task.get_problems(): pcontent = problem.get_original_content() pcontent["id"] = problem.get_id() if pcontent["type"] == "match": del pcontent["answer"] if pcontent["type"] == "multiple_choice": pcontent["choices"] = {key: val["text"] for key, val in enumerate(pcontent["choices"])} pcontent = self._check_for_parsable_text(pcontent) data["problems"].append(pcontent) output.append(data) return 200, output
python
def API_GET(self, courseid, taskid=None): # pylint: disable=arguments-differ """ List tasks available to the connected client. Returns a dict in the form :: { "taskid1": { "name": "Name of the course", #the name of the course "authors": [], "deadline": "", "status": "success" # can be "succeeded", "failed" or "notattempted" "grade": 0.0, "grade_weight": 0.0, "context": "" # context of the task, in RST "problems": # dict of the subproblems { # see the format of task.yaml for the content of the dict. Contains everything but # responses of multiple-choice and match problems. } } #... } If you use the endpoint /api/v0/courses/the_course_id/tasks/the_task_id, this dict will contain one entry or the page will return 404 Not Found. """ 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 None: tasks = course.get_tasks() else: try: tasks = {taskid: course.get_task(taskid)} except: raise APINotFound("Task not found") output = [] for taskid, task in tasks.items(): task_cache = self.user_manager.get_task_cache(self.user_manager.session_username(), task.get_course_id(), task.get_id()) data = { "id": taskid, "name": task.get_name(self.user_manager.session_language()), "authors": task.get_authors(self.user_manager.session_language()), "deadline": task.get_deadline(), "status": "notviewed" if task_cache is None else "notattempted" if task_cache["tried"] == 0 else "succeeded" if task_cache["succeeded"] else "failed", "grade": task_cache.get("grade", 0.0) if task_cache is not None else 0.0, "grade_weight": task.get_grading_weight(), "context": task.get_context(self.user_manager.session_language()).original_content(), "problems": [] } for problem in task.get_problems(): pcontent = problem.get_original_content() pcontent["id"] = problem.get_id() if pcontent["type"] == "match": del pcontent["answer"] if pcontent["type"] == "multiple_choice": pcontent["choices"] = {key: val["text"] for key, val in enumerate(pcontent["choices"])} pcontent = self._check_for_parsable_text(pcontent) data["problems"].append(pcontent) output.append(data) return 200, output
[ "def", "API_GET", "(", "self", ",", "courseid", ",", "taskid", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "try", ":", "course", "=", "self", ".", "course_factory", ".", "get_course", "(", "courseid", ")", "except", ":", "raise", "APINotFound"...
List tasks available to the connected client. Returns a dict in the form :: { "taskid1": { "name": "Name of the course", #the name of the course "authors": [], "deadline": "", "status": "success" # can be "succeeded", "failed" or "notattempted" "grade": 0.0, "grade_weight": 0.0, "context": "" # context of the task, in RST "problems": # dict of the subproblems { # see the format of task.yaml for the content of the dict. Contains everything but # responses of multiple-choice and match problems. } } #... } If you use the endpoint /api/v0/courses/the_course_id/tasks/the_task_id, this dict will contain one entry or the page will return 404 Not Found.
[ "List", "tasks", "available", "to", "the", "connected", "client", ".", "Returns", "a", "dict", "in", "the", "form" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/tasks.py#L30-L103
train
229,808
UCL-INGI/INGInious
base-containers/base/inginious/input.py
load_input
def load_input(): """ Open existing input file """ file = open(_input_file, 'r') result = json.loads(file.read().strip('\0').strip()) file.close() return result
python
def load_input(): """ Open existing input file """ file = open(_input_file, 'r') result = json.loads(file.read().strip('\0').strip()) file.close() return result
[ "def", "load_input", "(", ")", ":", "file", "=", "open", "(", "_input_file", ",", "'r'", ")", "result", "=", "json", ".", "loads", "(", "file", ".", "read", "(", ")", ".", "strip", "(", "'\\0'", ")", ".", "strip", "(", ")", ")", "file", ".", "c...
Open existing input file
[ "Open", "existing", "input", "file" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/input.py#L14-L19
train
229,809
UCL-INGI/INGInious
base-containers/base/inginious/input.py
parse_template
def parse_template(input_filename, output_filename=''): """ Parses a template file Replaces all occurences of @@problem_id@@ by the value of the 'problem_id' key in data dictionary input_filename: file to parse output_filename: if not specified, overwrite input file """ data = load_input() with open(input_filename, 'rb') as file: template = file.read().decode("utf-8") # Check if 'input' in data if not 'input' in data: raise ValueError("Could not find 'input' in data") # Parse template for field in data['input']: subs = ["filename", "value"] if isinstance(data['input'][field], dict) and "filename" in data['input'][field] and "value" in data['input'][field] else [""] for sub in subs: displayed_field = field + (":" if sub else "") + sub regex = re.compile("@([^@]*)@" + displayed_field + '@([^@]*)@') for prefix, postfix in set(regex.findall(template)): if sub == "value": text = open(data['input'][field][sub], 'rb').read().decode('utf-8') elif sub: text = data['input'][field][sub] else: text = data['input'][field] rep = "\n".join([prefix + v + postfix for v in text.splitlines()]) template = template.replace("@{0}@{1}@{2}@".format(prefix, displayed_field, postfix), rep) if output_filename == '': output_filename=input_filename # Ensure directory of resulting file exists try: os.makedirs(os.path.dirname(output_filename)) except OSError as e: pass # Write file with open(output_filename, 'wb') as file: file.write(template.encode("utf-8"))
python
def parse_template(input_filename, output_filename=''): """ Parses a template file Replaces all occurences of @@problem_id@@ by the value of the 'problem_id' key in data dictionary input_filename: file to parse output_filename: if not specified, overwrite input file """ data = load_input() with open(input_filename, 'rb') as file: template = file.read().decode("utf-8") # Check if 'input' in data if not 'input' in data: raise ValueError("Could not find 'input' in data") # Parse template for field in data['input']: subs = ["filename", "value"] if isinstance(data['input'][field], dict) and "filename" in data['input'][field] and "value" in data['input'][field] else [""] for sub in subs: displayed_field = field + (":" if sub else "") + sub regex = re.compile("@([^@]*)@" + displayed_field + '@([^@]*)@') for prefix, postfix in set(regex.findall(template)): if sub == "value": text = open(data['input'][field][sub], 'rb').read().decode('utf-8') elif sub: text = data['input'][field][sub] else: text = data['input'][field] rep = "\n".join([prefix + v + postfix for v in text.splitlines()]) template = template.replace("@{0}@{1}@{2}@".format(prefix, displayed_field, postfix), rep) if output_filename == '': output_filename=input_filename # Ensure directory of resulting file exists try: os.makedirs(os.path.dirname(output_filename)) except OSError as e: pass # Write file with open(output_filename, 'wb') as file: file.write(template.encode("utf-8"))
[ "def", "parse_template", "(", "input_filename", ",", "output_filename", "=", "''", ")", ":", "data", "=", "load_input", "(", ")", "with", "open", "(", "input_filename", ",", "'rb'", ")", "as", "file", ":", "template", "=", "file", ".", "read", "(", ")", ...
Parses a template file Replaces all occurences of @@problem_id@@ by the value of the 'problem_id' key in data dictionary input_filename: file to parse output_filename: if not specified, overwrite input file
[ "Parses", "a", "template", "file", "Replaces", "all", "occurences", "of" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/input.py#L49-L92
train
229,810
UCL-INGI/INGInious
inginious/client/client.py
_callable_once
def _callable_once(func): """ Returns a function that is only callable once; any other call will do nothing """ def once(*args, **kwargs): if not once.called: once.called = True return func(*args, **kwargs) once.called = False return once
python
def _callable_once(func): """ Returns a function that is only callable once; any other call will do nothing """ def once(*args, **kwargs): if not once.called: once.called = True return func(*args, **kwargs) once.called = False return once
[ "def", "_callable_once", "(", "func", ")", ":", "def", "once", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "once", ".", "called", ":", "once", ".", "called", "=", "True", "return", "func", "(", "*", "args", ",", "*", "*", ...
Returns a function that is only callable once; any other call will do nothing
[ "Returns", "a", "function", "that", "is", "only", "callable", "once", ";", "any", "other", "call", "will", "do", "nothing" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client.py#L17-L26
train
229,811
UCL-INGI/INGInious
inginious/client/client.py
Client._ask_queue_update
async def _ask_queue_update(self): """ Send a ClientGetQueue message to the backend, if one is not already sent """ 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 update despite previous update not yet received") else: self._logger.debug("Asking for a job queue update") self._queue_update_last_attempt = 1 await self._simple_send(ClientGetQueue()) else: self._logger.error("Not asking for a job queue update as previous update not yet received") except asyncio.CancelledError: return except KeyboardInterrupt: return
python
async def _ask_queue_update(self): """ Send a ClientGetQueue message to the backend, if one is not already sent """ 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 update despite previous update not yet received") else: self._logger.debug("Asking for a job queue update") self._queue_update_last_attempt = 1 await self._simple_send(ClientGetQueue()) else: self._logger.error("Not asking for a job queue update as previous update not yet received") except asyncio.CancelledError: return except KeyboardInterrupt: return
[ "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", ".", "_q...
Send a ClientGetQueue message to the backend, if one is not already sent
[ "Send", "a", "ClientGetQueue", "message", "to", "the", "backend", "if", "one", "is", "not", "already", "sent" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client.py#L144-L162
train
229,812
UCL-INGI/INGInious
inginious/client/client.py
Client._handle_job_queue_update
async def _handle_job_queue_update(self, message: BackendGetQueue): """ Handles a BackendGetQueue containing a snapshot of the job queue """ self._logger.debug("Received job queue update") self._queue_update_last_attempt = 0 self._queue_cache = message # Do some precomputation new_job_queue_cache = {} # format is job_id: (nb_jobs_before, max_remaining_time) for (job_id, is_local, _, _2, _3, _4, max_end) in message.jobs_running: if is_local: new_job_queue_cache[job_id] = (-1, max_end - time.time()) wait_time = 0 nb_tasks = 0 for (job_id, is_local, _, _2, timeout) in message.jobs_waiting: if timeout > 0: wait_time += timeout if is_local: new_job_queue_cache[job_id] = (nb_tasks, wait_time) nb_tasks += 1 self._queue_job_cache = new_job_queue_cache
python
async def _handle_job_queue_update(self, message: BackendGetQueue): """ Handles a BackendGetQueue containing a snapshot of the job queue """ self._logger.debug("Received job queue update") self._queue_update_last_attempt = 0 self._queue_cache = message # Do some precomputation new_job_queue_cache = {} # format is job_id: (nb_jobs_before, max_remaining_time) for (job_id, is_local, _, _2, _3, _4, max_end) in message.jobs_running: if is_local: new_job_queue_cache[job_id] = (-1, max_end - time.time()) wait_time = 0 nb_tasks = 0 for (job_id, is_local, _, _2, timeout) in message.jobs_waiting: if timeout > 0: wait_time += timeout if is_local: new_job_queue_cache[job_id] = (nb_tasks, wait_time) nb_tasks += 1 self._queue_job_cache = new_job_queue_cache
[ "async", "def", "_handle_job_queue_update", "(", "self", ",", "message", ":", "BackendGetQueue", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Received job queue update\"", ")", "self", ".", "_queue_update_last_attempt", "=", "0", "self", ".", "_queue_ca...
Handles a BackendGetQueue containing a snapshot of the job queue
[ "Handles", "a", "BackendGetQueue", "containing", "a", "snapshot", "of", "the", "job", "queue" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client.py#L164-L185
train
229,813
UCL-INGI/INGInious
inginious/client/client.py
Client.new_job
def new_job(self, task, inputdata, callback, launcher_name="Unknown", debug=False, ssh_callback=None): """ Add a new job. Every callback will be called once and only once. :type task: Task :param inputdata: input from the student :type inputdata: Storage or dict :param callback: a function that will be called asynchronously in the client's process, with the results. it's signature must be (result, grade, problems, tests, custom, archive), where: result is itself a tuple containing the result string and the main feedback (i.e. ('success', 'You succeeded'); grade is a number between 0 and 100 indicating the grade of the users; problems is a dict of tuple, in the form {'problemid': result}; test is a dict of tests made in the container custom is a dict containing random things set in the container archive is either None or a bytes containing a tgz archive of files from the job :type callback: __builtin__.function or __builtin__.instancemethod :param launcher_name: for informational use :type launcher_name: str :param debug: Either True(outputs more info), False(default), or "ssh" (starts a remote ssh server. ssh_callback needs to be defined) :type debug: bool or string :param ssh_callback: a callback function that will be called with (host, port, password), the needed credentials to connect to the remote ssh server. May be called with host, port, password being None, meaning no session was open. :type ssh_callback: __builtin__.function or __builtin__.instancemethod or None :return: the new job id """ 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(("crash", "SSH callback not set."), 0.0, {}, {}, {}, None, "", "") return # wrap ssh_callback to ensure it is called at most once, and that it can always be called to simplify code ssh_callback = _callable_once(ssh_callback if ssh_callback is not None else lambda _1, _2, _3: None) environment = task.get_environment() if environment not in self._available_containers: self._logger.warning("Env %s not available for task %s/%s", environment, task.get_course_id(), task.get_id()) ssh_callback(None, None, None) # ssh_callback must be called once callback(("crash", "Environment not available."), 0.0, {}, {}, "", {}, None, "", "") return enable_network = task.allow_network_access_grading() try: limits = task.get_limits() time_limit = int(limits.get('time', 20)) hard_time_limit = int(limits.get('hard_time', 3 * time_limit)) mem_limit = int(limits.get('memory', 200)) except: self._logger.exception("Cannot retrieve limits for task %s/%s", task.get_course_id(), task.get_id()) ssh_callback(None, None, None) # ssh_callback must be called once callback(("crash", "Error while reading task limits"), 0.0, {}, {}, "", {}, None, "", "") return msg = ClientNewJob(job_id, task.get_course_id(), task.get_id(), inputdata, environment, enable_network, time_limit, hard_time_limit, mem_limit, debug, launcher_name) self._loop.call_soon_threadsafe(asyncio.ensure_future, self._create_transaction(msg, task=task, callback=callback, ssh_callback=ssh_callback)) return job_id
python
def new_job(self, task, inputdata, callback, launcher_name="Unknown", debug=False, ssh_callback=None): """ Add a new job. Every callback will be called once and only once. :type task: Task :param inputdata: input from the student :type inputdata: Storage or dict :param callback: a function that will be called asynchronously in the client's process, with the results. it's signature must be (result, grade, problems, tests, custom, archive), where: result is itself a tuple containing the result string and the main feedback (i.e. ('success', 'You succeeded'); grade is a number between 0 and 100 indicating the grade of the users; problems is a dict of tuple, in the form {'problemid': result}; test is a dict of tests made in the container custom is a dict containing random things set in the container archive is either None or a bytes containing a tgz archive of files from the job :type callback: __builtin__.function or __builtin__.instancemethod :param launcher_name: for informational use :type launcher_name: str :param debug: Either True(outputs more info), False(default), or "ssh" (starts a remote ssh server. ssh_callback needs to be defined) :type debug: bool or string :param ssh_callback: a callback function that will be called with (host, port, password), the needed credentials to connect to the remote ssh server. May be called with host, port, password being None, meaning no session was open. :type ssh_callback: __builtin__.function or __builtin__.instancemethod or None :return: the new job id """ 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(("crash", "SSH callback not set."), 0.0, {}, {}, {}, None, "", "") return # wrap ssh_callback to ensure it is called at most once, and that it can always be called to simplify code ssh_callback = _callable_once(ssh_callback if ssh_callback is not None else lambda _1, _2, _3: None) environment = task.get_environment() if environment not in self._available_containers: self._logger.warning("Env %s not available for task %s/%s", environment, task.get_course_id(), task.get_id()) ssh_callback(None, None, None) # ssh_callback must be called once callback(("crash", "Environment not available."), 0.0, {}, {}, "", {}, None, "", "") return enable_network = task.allow_network_access_grading() try: limits = task.get_limits() time_limit = int(limits.get('time', 20)) hard_time_limit = int(limits.get('hard_time', 3 * time_limit)) mem_limit = int(limits.get('memory', 200)) except: self._logger.exception("Cannot retrieve limits for task %s/%s", task.get_course_id(), task.get_id()) ssh_callback(None, None, None) # ssh_callback must be called once callback(("crash", "Error while reading task limits"), 0.0, {}, {}, "", {}, None, "", "") return msg = ClientNewJob(job_id, task.get_course_id(), task.get_id(), inputdata, environment, enable_network, time_limit, hard_time_limit, mem_limit, debug, launcher_name) self._loop.call_soon_threadsafe(asyncio.ensure_future, self._create_transaction(msg, task=task, callback=callback, ssh_callback=ssh_callback)) return job_id
[ "def", "new_job", "(", "self", ",", "task", ",", "inputdata", ",", "callback", ",", "launcher_name", "=", "\"Unknown\"", ",", "debug", "=", "False", ",", "ssh_callback", "=", "None", ")", ":", "job_id", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ...
Add a new job. Every callback will be called once and only once. :type task: Task :param inputdata: input from the student :type inputdata: Storage or dict :param callback: a function that will be called asynchronously in the client's process, with the results. it's signature must be (result, grade, problems, tests, custom, archive), where: result is itself a tuple containing the result string and the main feedback (i.e. ('success', 'You succeeded'); grade is a number between 0 and 100 indicating the grade of the users; problems is a dict of tuple, in the form {'problemid': result}; test is a dict of tests made in the container custom is a dict containing random things set in the container archive is either None or a bytes containing a tgz archive of files from the job :type callback: __builtin__.function or __builtin__.instancemethod :param launcher_name: for informational use :type launcher_name: str :param debug: Either True(outputs more info), False(default), or "ssh" (starts a remote ssh server. ssh_callback needs to be defined) :type debug: bool or string :param ssh_callback: a callback function that will be called with (host, port, password), the needed credentials to connect to the remote ssh server. May be called with host, port, password being None, meaning no session was open. :type ssh_callback: __builtin__.function or __builtin__.instancemethod or None :return: the new job id
[ "Add", "a", "new", "job", ".", "Every", "callback", "will", "be", "called", "once", "and", "only", "once", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client.py#L253-L311
train
229,814
UCL-INGI/INGInious
inginious/client/client.py
Client.kill_job
def kill_job(self, job_id): """ Kills a running job """ self._loop.call_soon_threadsafe(asyncio.ensure_future, self._simple_send(ClientKillJob(job_id)))
python
def kill_job(self, job_id): """ Kills a running job """ self._loop.call_soon_threadsafe(asyncio.ensure_future, self._simple_send(ClientKillJob(job_id)))
[ "def", "kill_job", "(", "self", ",", "job_id", ")", ":", "self", ".", "_loop", ".", "call_soon_threadsafe", "(", "asyncio", ".", "ensure_future", ",", "self", ".", "_simple_send", "(", "ClientKillJob", "(", "job_id", ")", ")", ")" ]
Kills a running job
[ "Kills", "a", "running", "job" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client.py#L313-L317
train
229,815
UCL-INGI/INGInious
base-containers/base/inginious/rst.py
get_codeblock
def get_codeblock(language, text): """ Generates rst codeblock for given text and language """ rst = "\n\n.. code-block:: " + language + "\n\n" for line in text.splitlines(): rst += "\t" + line + "\n" rst += "\n" return rst
python
def get_codeblock(language, text): """ Generates rst codeblock for given text and language """ rst = "\n\n.. code-block:: " + language + "\n\n" for line in text.splitlines(): rst += "\t" + line + "\n" rst += "\n" return rst
[ "def", "get_codeblock", "(", "language", ",", "text", ")", ":", "rst", "=", "\"\\n\\n.. code-block:: \"", "+", "language", "+", "\"\\n\\n\"", "for", "line", "in", "text", ".", "splitlines", "(", ")", ":", "rst", "+=", "\"\\t\"", "+", "line", "+", "\"\\n\""...
Generates rst codeblock for given text and language
[ "Generates", "rst", "codeblock", "for", "given", "text", "and", "language" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/rst.py#L9-L16
train
229,816
UCL-INGI/INGInious
base-containers/base/inginious/rst.py
get_imageblock
def get_imageblock(filename, format=''): """ Generates rst raw block for given image filename and 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:]) + ';base64,' + encoded_string +'">\n'
python
def get_imageblock(filename, format=''): """ Generates rst raw block for given image filename and 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:]) + ';base64,' + encoded_string +'">\n'
[ "def", "get_imageblock", "(", "filename", ",", "format", "=", "''", ")", ":", "_", ",", "extension", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "image_file", ":", "encoded_s...
Generates rst raw block for given image filename and format
[ "Generates", "rst", "raw", "block", "for", "given", "image", "filename", "and", "format" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/rst.py#L18-L25
train
229,817
UCL-INGI/INGInious
base-containers/base/inginious/rst.py
get_admonition
def get_admonition(cssclass, title, text): """ Generates rst admonition block given a bootstrap alert css class, title, and 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
python
def get_admonition(cssclass, title, text): """ Generates rst admonition block given a bootstrap alert css class, title, and 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
[ "def", "get_admonition", "(", "cssclass", ",", "title", ",", "text", ")", ":", "rst", "=", "(", "\"\\n\\n.. admonition:: \"", "+", "title", "+", "\"\\n\"", ")", "if", "title", "else", "\"\\n\\n.. note:: \\n\"", "rst", "+=", "\"\\t:class: alert alert-\"", "+", "c...
Generates rst admonition block given a bootstrap alert css class, title, and text
[ "Generates", "rst", "admonition", "block", "given", "a", "bootstrap", "alert", "css", "class", "title", "and", "text" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/rst.py#L27-L35
train
229,818
UCL-INGI/INGInious
base-containers/base/inginious/lang.py
init
def init(): """ Install gettext with the default parameters """ if "_" not in builtins.__dict__: # avoid installing lang two times 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())
python
def init(): """ Install gettext with the default parameters """ if "_" not in builtins.__dict__: # avoid installing lang two times 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())
[ "def", "init", "(", ")", ":", "if", "\"_\"", "not", "in", "builtins", ".", "__dict__", ":", "# avoid installing lang two times", "os", ".", "environ", "[", "\"LANGUAGE\"", "]", "=", "inginious", ".", "input", ".", "get_lang", "(", ")", "if", "inginious", "...
Install gettext with the default parameters
[ "Install", "gettext", "with", "the", "default", "parameters" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/lang.py#L22-L29
train
229,819
UCL-INGI/INGInious
inginious/common/filesystems/local.py
LocalFSProvider._recursive_overwrite
def _recursive_overwrite(self, src, dest): """ Copy src to dest, recursively and with file overwrite. """ 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, follow_symlinks=False)
python
def _recursive_overwrite(self, src, dest): """ Copy src to dest, recursively and with file overwrite. """ 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, follow_symlinks=False)
[ "def", "_recursive_overwrite", "(", "self", ",", "src", ",", "dest", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "src", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "dest", ")", ":", "os", ".", "makedirs", "(", "dest", ...
Copy src to dest, recursively and with file overwrite.
[ "Copy", "src", "to", "dest", "recursively", "and", "with", "file", "overwrite", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/filesystems/local.py#L134-L146
train
229,820
UCL-INGI/INGInious
inginious/frontend/plugins/git_repo/__init__.py
init
def init(plugin_manager, _, _2, config): """ Init the plugin Available configuration: :: plugins: - plugin_module: inginious.frontend.plugins.git_repo repo_directory: "./repo_submissions" """ submission_git_saver = SubmissionGitSaver(plugin_manager, config) submission_git_saver.daemon = True submission_git_saver.start()
python
def init(plugin_manager, _, _2, config): """ Init the plugin Available configuration: :: plugins: - plugin_module: inginious.frontend.plugins.git_repo repo_directory: "./repo_submissions" """ submission_git_saver = SubmissionGitSaver(plugin_manager, config) submission_git_saver.daemon = True submission_git_saver.start()
[ "def", "init", "(", "plugin_manager", ",", "_", ",", "_2", ",", "config", ")", ":", "submission_git_saver", "=", "SubmissionGitSaver", "(", "plugin_manager", ",", "config", ")", "submission_git_saver", ".", "daemon", "=", "True", "submission_git_saver", ".", "st...
Init the plugin Available configuration: :: plugins: - plugin_module: inginious.frontend.plugins.git_repo repo_directory: "./repo_submissions"
[ "Init", "the", "plugin" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugins/git_repo/__init__.py#L97-L111
train
229,821
UCL-INGI/INGInious
inginious/common/tags.py
Tag.get_type_as_str
def get_type_as_str(self): """ Return a textual description of the type """ 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")
python
def get_type_as_str(self): """ Return a textual description of the type """ 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")
[ "def", "get_type_as_str", "(", "self", ")", ":", "if", "self", ".", "get_type", "(", ")", "==", "0", ":", "return", "_", "(", "\"Skill\"", ")", "elif", "self", ".", "get_type", "(", ")", "==", "1", ":", "return", "_", "(", "\"Misconception\"", ")", ...
Return a textual description of the type
[ "Return", "a", "textual", "description", "of", "the", "type" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/tags.py#L58-L67
train
229,822
UCL-INGI/INGInious
inginious/common/tags.py
Tag.create_tags_from_dict
def create_tags_from_dict(cls, tag_dict): """ 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 """ 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 = tag_dict[tag]["type"] if type == 2: tag_list_organisational.insert(int(tag), Tag(id, name, description, visible, type)) elif type == 1: tag_list_misconception.insert(int(tag), Tag(id, name, description, visible, type)) else: tag_list_common.insert(int(tag), Tag(id, name, description, visible, type)) except KeyError: pass return tag_list_common, tag_list_misconception, tag_list_organisational
python
def create_tags_from_dict(cls, tag_dict): """ 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 """ 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 = tag_dict[tag]["type"] if type == 2: tag_list_organisational.insert(int(tag), Tag(id, name, description, visible, type)) elif type == 1: tag_list_misconception.insert(int(tag), Tag(id, name, description, visible, type)) else: tag_list_common.insert(int(tag), Tag(id, name, description, visible, type)) except KeyError: pass return tag_list_common, tag_list_misconception, tag_list_organisational
[ "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"...
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
[ "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", "miscon...
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/tags.py#L73-L100
train
229,823
UCL-INGI/INGInious
inginious/agent/__init__.py
Agent.run
async def run(self): """ 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. """ self._logger.info("Agent started") self.__backend_socket.connect(self.__backend_addr) # Tell the backend we are up and have `concurrency` threads available self._logger.info("Saying hello to the backend") await ZMQUtils.send(self.__backend_socket, AgentHello(self.__friendly_name, self.__concurrency, self.environments)) self.__last_ping = time.time() run_listen = self._loop.create_task(self.__run_listen()) self._loop.call_later(1, self._create_safe_task, self.__check_last_ping(run_listen)) await run_listen
python
async def run(self): """ 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. """ self._logger.info("Agent started") self.__backend_socket.connect(self.__backend_addr) # Tell the backend we are up and have `concurrency` threads available self._logger.info("Saying hello to the backend") await ZMQUtils.send(self.__backend_socket, AgentHello(self.__friendly_name, self.__concurrency, self.environments)) self.__last_ping = time.time() run_listen = self._loop.create_task(self.__run_listen()) self._loop.call_later(1, self._create_safe_task, self.__check_last_ping(run_listen)) await run_listen
[ "async", "def", "run", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"Agent started\"", ")", "self", ".", "__backend_socket", ".", "connect", "(", "self", ".", "__backend_addr", ")", "# Tell the backend we are up and have `concurrency` threads a...
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.
[ "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", ...
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/__init__.py#L100-L117
train
229,824
UCL-INGI/INGInious
inginious/agent/__init__.py
Agent.__check_last_ping
async def __check_last_ping(self, run_listen): """ Check if the last timeout is too old. If it is, kills the run_listen task """ 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_last_ping(run_listen))
python
async def __check_last_ping(self, run_listen): """ Check if the last timeout is too old. If it is, kills the run_listen task """ 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_last_ping(run_listen))
[ "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.\"", ...
Check if the last timeout is too old. If it is, kills the run_listen task
[ "Check", "if", "the", "last", "timeout", "is", "too", "old", ".", "If", "it", "is", "kills", "the", "run_listen", "task" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/__init__.py#L119-L126
train
229,825
UCL-INGI/INGInious
inginious/agent/__init__.py
Agent.__run_listen
async def __run_listen(self): """ Listen to the backend """ while True: message = await ZMQUtils.recv(self.__backend_socket) await self.__handle_backend_message(message)
python
async def __run_listen(self): """ Listen to the backend """ while True: message = await ZMQUtils.recv(self.__backend_socket) await self.__handle_backend_message(message)
[ "async", "def", "__run_listen", "(", "self", ")", ":", "while", "True", ":", "message", "=", "await", "ZMQUtils", ".", "recv", "(", "self", ".", "__backend_socket", ")", "await", "self", ".", "__handle_backend_message", "(", "message", ")" ]
Listen to the backend
[ "Listen", "to", "the", "backend" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/__init__.py#L128-L132
train
229,826
UCL-INGI/INGInious
inginious/agent/__init__.py
Agent.__handle_ping
async def __handle_ping(self, _ : Ping): """ Handle a Ping message. Pong the backend """ self.__last_ping = time.time() await ZMQUtils.send(self.__backend_socket, Pong())
python
async def __handle_ping(self, _ : Ping): """ Handle a Ping message. Pong the backend """ self.__last_ping = time.time() await ZMQUtils.send(self.__backend_socket, Pong())
[ "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
[ "Handle", "a", "Ping", "message", ".", "Pong", "the", "backend" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/__init__.py#L147-L150
train
229,827
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/utils.py
get_menu
def get_menu(course, current, renderer, plugin_manager, user_manager): """ Returns the HTML of the menu used in the administration. ```current``` is the current page of section """ 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-chart fa-fw'></i>&nbsp; " + _("Stats")), ("students", "<i class='fa fa-user fa-fw'></i>&nbsp; " + _("Students"))] if not course.is_lti(): default_entries += [("aggregations", "<i class='fa fa-group fa-fw'></i>&nbsp; " + (_("Classrooms") if course.use_classrooms() else _("Teams")))] default_entries += [("tasks", "<i class='fa fa-tasks fa-fw'></i>&nbsp; " + _("Tasks")), ("submissions", "<i class='fa fa-search fa-fw'></i>&nbsp; " + _("View submissions")), ("download", "<i class='fa fa-download fa-fw'></i>&nbsp; " + _("Download submissions"))] if user_manager.has_admin_rights_on_course(course): if web.ctx.app_stack[0].webdav_host: default_entries += [("webdav", "<i class='fa fa-folder-open fa-fw'></i>&nbsp; " + _("WebDAV access"))] default_entries += [("replay", "<i class='fa fa-refresh fa-fw'></i>&nbsp; " + _("Replay submissions")), ("danger", "<i class='fa fa-bomb fa-fw'></i>&nbsp; " + _("Danger zone"))] # Hook should return a tuple (link,name) where link is the relative link from the index of the course administration. additional_entries = [entry for entry in plugin_manager.call_hook('course_admin_menu', course=course) if entry is not None] return renderer.course_admin.menu(course, default_entries + additional_entries, current)
python
def get_menu(course, current, renderer, plugin_manager, user_manager): """ Returns the HTML of the menu used in the administration. ```current``` is the current page of section """ 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-chart fa-fw'></i>&nbsp; " + _("Stats")), ("students", "<i class='fa fa-user fa-fw'></i>&nbsp; " + _("Students"))] if not course.is_lti(): default_entries += [("aggregations", "<i class='fa fa-group fa-fw'></i>&nbsp; " + (_("Classrooms") if course.use_classrooms() else _("Teams")))] default_entries += [("tasks", "<i class='fa fa-tasks fa-fw'></i>&nbsp; " + _("Tasks")), ("submissions", "<i class='fa fa-search fa-fw'></i>&nbsp; " + _("View submissions")), ("download", "<i class='fa fa-download fa-fw'></i>&nbsp; " + _("Download submissions"))] if user_manager.has_admin_rights_on_course(course): if web.ctx.app_stack[0].webdav_host: default_entries += [("webdav", "<i class='fa fa-folder-open fa-fw'></i>&nbsp; " + _("WebDAV access"))] default_entries += [("replay", "<i class='fa fa-refresh fa-fw'></i>&nbsp; " + _("Replay submissions")), ("danger", "<i class='fa fa-bomb fa-fw'></i>&nbsp; " + _("Danger zone"))] # Hook should return a tuple (link,name) where link is the relative link from the index of the course administration. additional_entries = [entry for entry in plugin_manager.call_hook('course_admin_menu', course=course) if entry is not None] return renderer.course_admin.menu(course, default_entries + additional_entries, current)
[ "def", "get_menu", "(", "course", ",", "current", ",", "renderer", ",", "plugin_manager", ",", "user_manager", ")", ":", "default_entries", "=", "[", "]", "if", "user_manager", ".", "has_admin_rights_on_course", "(", "course", ")", ":", "default_entries", "+=", ...
Returns the HTML of the menu used in the administration. ```current``` is the current page of section
[ "Returns", "the", "HTML", "of", "the", "menu", "used", "in", "the", "administration", ".", "current", "is", "the", "current", "page", "of", "section" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/utils.py#L252-L278
train
229,828
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/utils.py
UnicodeWriter.writerow
def writerow(self, row): """ Writes a row to the CSV file """ self.writer.writerow(row) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() # write to the target stream self.stream.write(data) # empty queue self.queue.truncate(0) self.queue.seek(0)
python
def writerow(self, row): """ Writes a row to the CSV file """ self.writer.writerow(row) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() # write to the target stream self.stream.write(data) # empty queue self.queue.truncate(0) self.queue.seek(0)
[ "def", "writerow", "(", "self", ",", "row", ")", ":", "self", ".", "writer", ".", "writerow", "(", "row", ")", "# Fetch UTF-8 output from the queue ...", "data", "=", "self", ".", "queue", ".", "getvalue", "(", ")", "# write to the target stream", "self", ".",...
Writes a row to the CSV file
[ "Writes", "a", "row", "to", "the", "CSV", "file" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/utils.py#L175-L184
train
229,829
UCL-INGI/INGInious
inginious/frontend/template_helper.py
TemplateHelper.get_renderer
def get_renderer(self, with_layout=True): """ Get the default renderer """ 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
python
def get_renderer(self, with_layout=True): """ Get the default renderer """ 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
[ "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_rend...
Get the default renderer
[ "Get", "the", "default", "renderer" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/template_helper.py#L63-L70
train
229,830
UCL-INGI/INGInious
inginious/frontend/template_helper.py
TemplateHelper._javascript_helper
def _javascript_helper(self, position): """ Add javascript links for the current page and for the plugins """ if position not in ["header", "footer"]: position = "footer" # Load javascript files from plugins 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_hook("javascript_footer") if entry is not None] # Load javascript for the current page entries += self._get_ctx()["javascript"][position] entries = ["<script src='" + entry + "' type='text/javascript' charset='utf-8'></script>" for entry in entries] return "\n".join(entries)
python
def _javascript_helper(self, position): """ Add javascript links for the current page and for the plugins """ if position not in ["header", "footer"]: position = "footer" # Load javascript files from plugins 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_hook("javascript_footer") if entry is not None] # Load javascript for the current page entries += self._get_ctx()["javascript"][position] entries = ["<script src='" + entry + "' type='text/javascript' charset='utf-8'></script>" for entry in entries] return "\n".join(entries)
[ "def", "_javascript_helper", "(", "self", ",", "position", ")", ":", "if", "position", "not", "in", "[", "\"header\"", ",", "\"footer\"", "]", ":", "position", "=", "\"footer\"", "# Load javascript files from plugins", "if", "position", "==", "\"header\"", ":", ...
Add javascript links for the current page and for the plugins
[ "Add", "javascript", "links", "for", "the", "current", "page", "and", "for", "the", "plugins" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/template_helper.py#L117-L130
train
229,831
UCL-INGI/INGInious
inginious/frontend/template_helper.py
TemplateHelper._css_helper
def _css_helper(self): """ Add CSS links for the current page and for the plugins """ entries = [entry for entry in self._plugin_manager.call_hook("css") if entry is not None] # Load javascript for the current page entries += self._get_ctx()["css"] entries = ["<link href='" + entry + "' rel='stylesheet'>" for entry in entries] return "\n".join(entries)
python
def _css_helper(self): """ Add CSS links for the current page and for the plugins """ entries = [entry for entry in self._plugin_manager.call_hook("css") if entry is not None] # Load javascript for the current page entries += self._get_ctx()["css"] entries = ["<link href='" + entry + "' rel='stylesheet'>" for entry in entries] return "\n".join(entries)
[ "def", "_css_helper", "(", "self", ")", ":", "entries", "=", "[", "entry", "for", "entry", "in", "self", ".", "_plugin_manager", ".", "call_hook", "(", "\"css\"", ")", "if", "entry", "is", "not", "None", "]", "# Load javascript for the current page", "entries"...
Add CSS links for the current page and for the plugins
[ "Add", "CSS", "links", "for", "the", "current", "page", "and", "for", "the", "plugins" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/template_helper.py#L132-L138
train
229,832
UCL-INGI/INGInious
inginious/frontend/template_helper.py
TemplateHelper._get_ctx
def _get_ctx(self): """ Get web.ctx object for the Template helper """ 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)
python
def _get_ctx(self): """ Get web.ctx object for the Template helper """ 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)
[ "def", "_get_ctx", "(", "self", ")", ":", "if", "self", ".", "_WEB_CTX_KEY", "not", "in", "web", ".", "ctx", ":", "web", ".", "ctx", "[", "self", ".", "_WEB_CTX_KEY", "]", "=", "{", "\"javascript\"", ":", "{", "\"footer\"", ":", "[", "]", ",", "\"h...
Get web.ctx object for the Template helper
[ "Get", "web", ".", "ctx", "object", "for", "the", "Template", "helper" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/template_helper.py#L140-L146
train
229,833
UCL-INGI/INGInious
inginious/frontend/template_helper.py
TemplateHelper._generic_hook
def _generic_hook(self, name, **kwargs): """ A generic hook that links the TemplateHelper with PluginManager """ entries = [entry for entry in self._plugin_manager.call_hook(name, **kwargs) if entry is not None] return "\n".join(entries)
python
def _generic_hook(self, name, **kwargs): """ A generic hook that links the TemplateHelper with PluginManager """ entries = [entry for entry in self._plugin_manager.call_hook(name, **kwargs) if entry is not None] return "\n".join(entries)
[ "def", "_generic_hook", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "entries", "=", "[", "entry", "for", "entry", "in", "self", ".", "_plugin_manager", ".", "call_hook", "(", "name", ",", "*", "*", "kwargs", ")", "if", "entry", "is",...
A generic hook that links the TemplateHelper with PluginManager
[ "A", "generic", "hook", "that", "links", "the", "TemplateHelper", "with", "PluginManager" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/template_helper.py#L148-L151
train
229,834
UCL-INGI/INGInious
inginious/client/client_buffer.py
ClientBuffer.new_job
def new_job(self, task, inputdata, launcher_name="Unknown", debug=False): """ Runs a new job. It works exactly like the Client class, instead that there is no callback """ 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, result, grade, problems, tests, custom, archive, stdout, stderr)), launcher_name, debug) return bjobid
python
def new_job(self, task, inputdata, launcher_name="Unknown", debug=False): """ Runs a new job. It works exactly like the Client class, instead that there is no callback """ 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, result, grade, problems, tests, custom, archive, stdout, stderr)), launcher_name, debug) return bjobid
[ "def", "new_job", "(", "self", ",", "task", ",", "inputdata", ",", "launcher_name", "=", "\"Unknown\"", ",", "debug", "=", "False", ")", ":", "bjobid", "=", "uuid", ".", "uuid4", "(", ")", "self", ".", "_waiting_jobs", ".", "append", "(", "str", "(", ...
Runs a new job. It works exactly like the Client class, instead that there is no callback
[ "Runs", "a", "new", "job", ".", "It", "works", "exactly", "like", "the", "Client", "class", "instead", "that", "there", "is", "no", "callback" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client_buffer.py#L19-L27
train
229,835
UCL-INGI/INGInious
inginious/client/client_buffer.py
ClientBuffer._callback
def _callback(self, bjobid, result, grade, problems, tests, custom, archive, stdout, stderr): """ Callback for self._client.new_job """ self._jobs_done[str(bjobid)] = (result, grade, problems, tests, custom, archive, stdout, stderr) self._waiting_jobs.remove(str(bjobid))
python
def _callback(self, bjobid, result, grade, problems, tests, custom, archive, stdout, stderr): """ Callback for self._client.new_job """ self._jobs_done[str(bjobid)] = (result, grade, problems, tests, custom, archive, stdout, stderr) self._waiting_jobs.remove(str(bjobid))
[ "def", "_callback", "(", "self", ",", "bjobid", ",", "result", ",", "grade", ",", "problems", ",", "tests", ",", "custom", ",", "archive", ",", "stdout", ",", "stderr", ")", ":", "self", ".", "_jobs_done", "[", "str", "(", "bjobid", ")", "]", "=", ...
Callback for self._client.new_job
[ "Callback", "for", "self", ".", "_client", ".", "new_job" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client_buffer.py#L29-L32
train
229,836
UCL-INGI/INGInious
inginious/frontend/plugins/auth/ldap_auth.py
init
def init(plugin_manager, _, _2, conf): """ Allow to connect through a LDAP service Available configuration: :: plugins: - plugin_module": "inginious.frontend.plugins.auth.ldap_auth", host: "ldap.test.be", port: 0, encryption: "ssl", base_dn: "o=test,c=be", request: "(uid={})", name: "LDAP Login" *host* The host of the ldap server *encryption* Encryption method used to connect to the LDAP server Can be either "none", "ssl" or "tls" *request* Request made to the server in order to find the dn of the user. The characters "{}" will be replaced by the login name. """ 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["port"] = None the_method = LdapAuthMethod(conf.get("id"), conf.get('name', 'LDAP'), conf.get("imlink", ""), conf) plugin_manager.add_page(r'/auth/page/([^/]+)', LDAPAuthenticationPage) plugin_manager.register_auth_method(the_method)
python
def init(plugin_manager, _, _2, conf): """ Allow to connect through a LDAP service Available configuration: :: plugins: - plugin_module": "inginious.frontend.plugins.auth.ldap_auth", host: "ldap.test.be", port: 0, encryption: "ssl", base_dn: "o=test,c=be", request: "(uid={})", name: "LDAP Login" *host* The host of the ldap server *encryption* Encryption method used to connect to the LDAP server Can be either "none", "ssl" or "tls" *request* Request made to the server in order to find the dn of the user. The characters "{}" will be replaced by the login name. """ 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["port"] = None the_method = LdapAuthMethod(conf.get("id"), conf.get('name', 'LDAP'), conf.get("imlink", ""), conf) plugin_manager.add_page(r'/auth/page/([^/]+)', LDAPAuthenticationPage) plugin_manager.register_auth_method(the_method)
[ "def", "init", "(", "plugin_manager", ",", "_", ",", "_2", ",", "conf", ")", ":", "encryption", "=", "conf", ".", "get", "(", "\"encryption\"", ",", "\"none\"", ")", "if", "encryption", "not", "in", "[", "\"none\"", ",", "\"ssl\"", ",", "\"tls\"", "]",...
Allow to connect through a LDAP service Available configuration: :: plugins: - plugin_module": "inginious.frontend.plugins.auth.ldap_auth", host: "ldap.test.be", port: 0, encryption: "ssl", base_dn: "o=test,c=be", request: "(uid={})", name: "LDAP Login" *host* The host of the ldap server *encryption* Encryption method used to connect to the LDAP server Can be either "none", "ssl" or "tls" *request* Request made to the server in order to find the dn of the user. The characters "{}" will be replaced by the login name.
[ "Allow", "to", "connect", "through", "a", "LDAP", "service" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugins/auth/ldap_auth.py#L127-L165
train
229,837
UCL-INGI/INGInious
inginious/frontend/session_mongodb.py
MongoStore.cleanup
def cleanup(self, timeout): ''' Removes all sessions older than ``timeout`` seconds. Called automatically on every session access. ''' cutoff = time() - timeout self.collection.remove({_atime: {'$lt': cutoff}})
python
def cleanup(self, timeout): ''' Removes all sessions older than ``timeout`` seconds. Called automatically on every session access. ''' cutoff = time() - timeout self.collection.remove({_atime: {'$lt': cutoff}})
[ "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.
[ "Removes", "all", "sessions", "older", "than", "timeout", "seconds", ".", "Called", "automatically", "on", "every", "session", "access", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/session_mongodb.py#L114-L120
train
229,838
UCL-INGI/INGInious
inginious/frontend/plugin_manager.py
PluginManager.load
def load(self, client, webpy_app, course_factory, task_factory, database, user_manager, submission_manager, config): """ Loads the plugin manager. Must be done after the initialisation of the client """ self._app = webpy_app self._task_factory = task_factory self._database = database self._user_manager = user_manager self._submission_manager = submission_manager self._loaded = True for entry in config: module = importlib.import_module(entry["plugin_module"]) module.init(self, course_factory, client, entry)
python
def load(self, client, webpy_app, course_factory, task_factory, database, user_manager, submission_manager, config): """ Loads the plugin manager. Must be done after the initialisation of the client """ self._app = webpy_app self._task_factory = task_factory self._database = database self._user_manager = user_manager self._submission_manager = submission_manager self._loaded = True for entry in config: module = importlib.import_module(entry["plugin_module"]) module.init(self, course_factory, client, entry)
[ "def", "load", "(", "self", ",", "client", ",", "webpy_app", ",", "course_factory", ",", "task_factory", ",", "database", ",", "user_manager", ",", "submission_manager", ",", "config", ")", ":", "self", ".", "_app", "=", "webpy_app", "self", ".", "_task_fact...
Loads the plugin manager. Must be done after the initialisation of the client
[ "Loads", "the", "plugin", "manager", ".", "Must", "be", "done", "after", "the", "initialisation", "of", "the", "client" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugin_manager.py#L28-L38
train
229,839
UCL-INGI/INGInious
inginious/frontend/plugin_manager.py
PluginManager.add_page
def add_page(self, pattern, classname): """ Add a new page to the web application. Only available after that the Plugin Manager is loaded """ if not self._loaded: raise PluginManagerNotLoadedException() self._app.add_mapping(pattern, classname)
python
def add_page(self, pattern, classname): """ Add a new page to the web application. Only available after that the Plugin Manager is loaded """ if not self._loaded: raise PluginManagerNotLoadedException() self._app.add_mapping(pattern, classname)
[ "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
[ "Add", "a", "new", "page", "to", "the", "web", "application", ".", "Only", "available", "after", "that", "the", "Plugin", "Manager", "is", "loaded" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugin_manager.py#L40-L44
train
229,840
UCL-INGI/INGInious
inginious/frontend/plugin_manager.py
PluginManager.add_task_file_manager
def add_task_file_manager(self, task_file_manager): """ Add a task file manager. Only available after that the Plugin Manager is loaded """ if not self._loaded: raise PluginManagerNotLoadedException() self._task_factory.add_custom_task_file_manager(task_file_manager)
python
def add_task_file_manager(self, task_file_manager): """ Add a task file manager. Only available after that the Plugin Manager is loaded """ if not self._loaded: raise PluginManagerNotLoadedException() self._task_factory.add_custom_task_file_manager(task_file_manager)
[ "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
[ "Add", "a", "task", "file", "manager", ".", "Only", "available", "after", "that", "the", "Plugin", "Manager", "is", "loaded" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugin_manager.py#L46-L50
train
229,841
UCL-INGI/INGInious
inginious/frontend/plugin_manager.py
PluginManager.register_auth_method
def register_auth_method(self, auth_method): """ Register a new authentication method name the name of the authentication method, typically displayed by the webapp input_to_display Only available after that the Plugin Manager is loaded """ if not self._loaded: raise PluginManagerNotLoadedException() self._user_manager.register_auth_method(auth_method)
python
def register_auth_method(self, auth_method): """ Register a new authentication method name the name of the authentication method, typically displayed by the webapp input_to_display Only available after that the Plugin Manager is loaded """ if not self._loaded: raise PluginManagerNotLoadedException() self._user_manager.register_auth_method(auth_method)
[ "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 name the name of the authentication method, typically displayed by the webapp input_to_display Only available after that the Plugin Manager is loaded
[ "Register", "a", "new", "authentication", "method" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugin_manager.py#L52-L65
train
229,842
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/danger_zone.py
CourseDangerZonePage.dump_course
def dump_course(self, courseid): """ Create a zip file containing all information about a given course in database and then remove it from db""" 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, "w", allowZip64=True) as zipf: aggregations = self.database.aggregations.find({"courseid": courseid}) zipf.writestr("aggregations.json", bson.json_util.dumps(aggregations), zipfile.ZIP_DEFLATED) user_tasks = self.database.user_tasks.find({"courseid": courseid}) zipf.writestr("user_tasks.json", bson.json_util.dumps(user_tasks), zipfile.ZIP_DEFLATED) submissions = self.database.submissions.find({"courseid": courseid}) zipf.writestr("submissions.json", bson.json_util.dumps(submissions), zipfile.ZIP_DEFLATED) submissions.rewind() for submission in submissions: for key in ["input", "archive"]: if key in submission and type(submission[key]) == bson.objectid.ObjectId: infile = self.submission_manager.get_gridfs().get(submission[key]) zipf.writestr(key + "/" + str(submission[key]) + ".data", infile.read(), zipfile.ZIP_DEFLATED) self._logger.info("Course %s dumped to backup directory.", courseid) self.wipe_course(courseid)
python
def dump_course(self, courseid): """ Create a zip file containing all information about a given course in database and then remove it from db""" 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, "w", allowZip64=True) as zipf: aggregations = self.database.aggregations.find({"courseid": courseid}) zipf.writestr("aggregations.json", bson.json_util.dumps(aggregations), zipfile.ZIP_DEFLATED) user_tasks = self.database.user_tasks.find({"courseid": courseid}) zipf.writestr("user_tasks.json", bson.json_util.dumps(user_tasks), zipfile.ZIP_DEFLATED) submissions = self.database.submissions.find({"courseid": courseid}) zipf.writestr("submissions.json", bson.json_util.dumps(submissions), zipfile.ZIP_DEFLATED) submissions.rewind() for submission in submissions: for key in ["input", "archive"]: if key in submission and type(submission[key]) == bson.objectid.ObjectId: infile = self.submission_manager.get_gridfs().get(submission[key]) zipf.writestr(key + "/" + str(submission[key]) + ".data", infile.read(), zipfile.ZIP_DEFLATED) self._logger.info("Course %s dumped to backup directory.", courseid) self.wipe_course(courseid)
[ "def", "dump_course", "(", "self", ",", "courseid", ")", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "backup_dir", ",", "courseid", ",", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "\"%Y%m%d.%H%M...
Create a zip file containing all information about a given course in database and then remove it from db
[ "Create", "a", "zip", "file", "containing", "all", "information", "about", "a", "given", "course", "in", "database", "and", "then", "remove", "it", "from", "db" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/danger_zone.py#L39-L65
train
229,843
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/danger_zone.py
CourseDangerZonePage.delete_course
def delete_course(self, courseid): """ Erase all course data """ # Wipes the course (delete database) self.wipe_course(courseid) # Deletes the course from the factory (entire folder) self.course_factory.delete_course(courseid) # Removes backup 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.remove(backup) self._logger.info("Course %s files erased.", courseid)
python
def delete_course(self, courseid): """ Erase all course data """ # Wipes the course (delete database) self.wipe_course(courseid) # Deletes the course from the factory (entire folder) self.course_factory.delete_course(courseid) # Removes backup 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.remove(backup) self._logger.info("Course %s files erased.", courseid)
[ "def", "delete_course", "(", "self", ",", "courseid", ")", ":", "# Wipes the course (delete database)", "self", ".", "wipe_course", "(", "courseid", ")", "# Deletes the course from the factory (entire folder)", "self", ".", "course_factory", ".", "delete_course", "(", "co...
Erase all course data
[ "Erase", "all", "course", "data" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/danger_zone.py#L93-L107
train
229,844
UCL-INGI/INGInious
inginious/frontend/task_problems.py
DisplayableCodeProblem.show_input
def show_input(self, template_helper, language, seed): """ Show BasicCodeProblem and derivatives """ header = ParsableText(self.gettext(language,self._header), "rst", translation=self._translations.get(language, gettext.NullTranslations())) return str(DisplayableCodeProblem.get_renderer(template_helper).tasks.code(self.get_id(), header, 8, 0, self._language, self._optional, self._default))
python
def show_input(self, template_helper, language, seed): """ Show BasicCodeProblem and derivatives """ header = ParsableText(self.gettext(language,self._header), "rst", translation=self._translations.get(language, gettext.NullTranslations())) return str(DisplayableCodeProblem.get_renderer(template_helper).tasks.code(self.get_id(), header, 8, 0, self._language, self._optional, self._default))
[ "def", "show_input", "(", "self", ",", "template_helper", ",", "language", ",", "seed", ")", ":", "header", "=", "ParsableText", "(", "self", ".", "gettext", "(", "language", ",", "self", ".", "_header", ")", ",", "\"rst\"", ",", "translation", "=", "sel...
Show BasicCodeProblem and derivatives
[ "Show", "BasicCodeProblem", "and", "derivatives" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/task_problems.py#L66-L70
train
229,845
UCL-INGI/INGInious
inginious/frontend/task_problems.py
DisplayableMultipleChoiceProblem.show_input
def show_input(self, template_helper, language, seed): """ Show multiple choice problems """ choices = [] limit = self._limit if limit == 0: limit = len(self._choices) # no limit rand = Random("{}#{}#{}".format(self.get_task().get_id(), self.get_id(), seed)) # Ensure that the choices are random # we *do* need to copy the choices here random_order_choices = list(self._choices) rand.shuffle(random_order_choices) if self._multiple: # take only the valid choices in the first pass for entry in random_order_choices: if entry['valid']: choices.append(entry) limit = limit - 1 # take everything else in a second pass for entry in random_order_choices: if limit == 0: break if not entry['valid']: choices.append(entry) limit = limit - 1 else: # need to have ONE valid entry for entry in random_order_choices: if not entry['valid'] and limit > 1: choices.append(entry) limit = limit - 1 for entry in random_order_choices: if entry['valid'] and limit > 0: choices.append(entry) limit = limit - 1 rand.shuffle(choices) header = ParsableText(self.gettext(language, self._header), "rst", translation=self._translations.get(language, gettext.NullTranslations())) return str(DisplayableMultipleChoiceProblem.get_renderer(template_helper).tasks.multiple_choice( self.get_id(), header, self._multiple, choices, lambda text: ParsableText(self.gettext(language, text) if text else "", "rst", translation=self._translations.get(language, gettext.NullTranslations()))))
python
def show_input(self, template_helper, language, seed): """ Show multiple choice problems """ choices = [] limit = self._limit if limit == 0: limit = len(self._choices) # no limit rand = Random("{}#{}#{}".format(self.get_task().get_id(), self.get_id(), seed)) # Ensure that the choices are random # we *do* need to copy the choices here random_order_choices = list(self._choices) rand.shuffle(random_order_choices) if self._multiple: # take only the valid choices in the first pass for entry in random_order_choices: if entry['valid']: choices.append(entry) limit = limit - 1 # take everything else in a second pass for entry in random_order_choices: if limit == 0: break if not entry['valid']: choices.append(entry) limit = limit - 1 else: # need to have ONE valid entry for entry in random_order_choices: if not entry['valid'] and limit > 1: choices.append(entry) limit = limit - 1 for entry in random_order_choices: if entry['valid'] and limit > 0: choices.append(entry) limit = limit - 1 rand.shuffle(choices) header = ParsableText(self.gettext(language, self._header), "rst", translation=self._translations.get(language, gettext.NullTranslations())) return str(DisplayableMultipleChoiceProblem.get_renderer(template_helper).tasks.multiple_choice( self.get_id(), header, self._multiple, choices, lambda text: ParsableText(self.gettext(language, text) if text else "", "rst", translation=self._translations.get(language, gettext.NullTranslations()))))
[ "def", "show_input", "(", "self", ",", "template_helper", ",", "language", ",", "seed", ")", ":", "choices", "=", "[", "]", "limit", "=", "self", ".", "_limit", "if", "limit", "==", "0", ":", "limit", "=", "len", "(", "self", ".", "_choices", ")", ...
Show multiple choice problems
[ "Show", "multiple", "choice", "problems" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/task_problems.py#L153-L199
train
229,846
UCL-INGI/INGInious
inginious/frontend/pages/lti.py
LTILaunchPage._parse_lti_data
def _parse_lti_data(self, courseid, taskid): """ Verify and parse the data for the LTI basic launch """ 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: test = LTIWebPyToolProvider.from_webpy_request() validator = LTIValidator(self.database.nonce, course.lti_keys()) verified = test.is_valid_request(validator) except Exception: self.logger.exception("...") self.logger.info("Error while validating LTI request for %s", str(post_input)) raise web.forbidden(_("Error while validating LTI request")) if verified: self.logger.debug('parse_lit_data for %s', str(post_input)) user_id = post_input["user_id"] roles = post_input.get("roles", "Student").split(",") realname = self._find_realname(post_input) email = post_input.get("lis_person_contact_email_primary", "") lis_outcome_service_url = post_input.get("lis_outcome_service_url", None) outcome_result_id = post_input.get("lis_result_sourcedid", None) consumer_key = post_input["oauth_consumer_key"] if course.lti_send_back_grade(): if lis_outcome_service_url is None or outcome_result_id is None: self.logger.info('Error: lis_outcome_service_url is None but lti_send_back_grade is True') raise web.forbidden(_("In order to send grade back to the TC, INGInious needs the parameters lis_outcome_service_url and " "lis_outcome_result_id in the LTI basic-launch-request. Please contact your administrator.")) else: lis_outcome_service_url = None outcome_result_id = None tool_name = post_input.get('tool_consumer_instance_name', 'N/A') tool_desc = post_input.get('tool_consumer_instance_description', 'N/A') tool_url = post_input.get('tool_consumer_instance_url', 'N/A') context_title = post_input.get('context_title', 'N/A') context_label = post_input.get('context_label', 'N/A') session_id = self.user_manager.create_lti_session(user_id, roles, realname, email, courseid, taskid, consumer_key, lis_outcome_service_url, outcome_result_id, tool_name, tool_desc, tool_url, context_title, context_label) loggedin = self.user_manager.attempt_lti_login() return session_id, loggedin else: self.logger.info("Couldn't validate LTI request") raise web.forbidden(_("Couldn't validate LTI request"))
python
def _parse_lti_data(self, courseid, taskid): """ Verify and parse the data for the LTI basic launch """ 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: test = LTIWebPyToolProvider.from_webpy_request() validator = LTIValidator(self.database.nonce, course.lti_keys()) verified = test.is_valid_request(validator) except Exception: self.logger.exception("...") self.logger.info("Error while validating LTI request for %s", str(post_input)) raise web.forbidden(_("Error while validating LTI request")) if verified: self.logger.debug('parse_lit_data for %s', str(post_input)) user_id = post_input["user_id"] roles = post_input.get("roles", "Student").split(",") realname = self._find_realname(post_input) email = post_input.get("lis_person_contact_email_primary", "") lis_outcome_service_url = post_input.get("lis_outcome_service_url", None) outcome_result_id = post_input.get("lis_result_sourcedid", None) consumer_key = post_input["oauth_consumer_key"] if course.lti_send_back_grade(): if lis_outcome_service_url is None or outcome_result_id is None: self.logger.info('Error: lis_outcome_service_url is None but lti_send_back_grade is True') raise web.forbidden(_("In order to send grade back to the TC, INGInious needs the parameters lis_outcome_service_url and " "lis_outcome_result_id in the LTI basic-launch-request. Please contact your administrator.")) else: lis_outcome_service_url = None outcome_result_id = None tool_name = post_input.get('tool_consumer_instance_name', 'N/A') tool_desc = post_input.get('tool_consumer_instance_description', 'N/A') tool_url = post_input.get('tool_consumer_instance_url', 'N/A') context_title = post_input.get('context_title', 'N/A') context_label = post_input.get('context_label', 'N/A') session_id = self.user_manager.create_lti_session(user_id, roles, realname, email, courseid, taskid, consumer_key, lis_outcome_service_url, outcome_result_id, tool_name, tool_desc, tool_url, context_title, context_label) loggedin = self.user_manager.attempt_lti_login() return session_id, loggedin else: self.logger.info("Couldn't validate LTI request") raise web.forbidden(_("Couldn't validate LTI request"))
[ "def", "_parse_lti_data", "(", "self", ",", "courseid", ",", "taskid", ")", ":", "post_input", "=", "web", ".", "webapi", ".", "rawinput", "(", "\"POST\"", ")", "self", ".", "logger", ".", "debug", "(", "'_parse_lti_data:'", "+", "str", "(", "post_input", ...
Verify and parse the data for the LTI basic launch
[ "Verify", "and", "parse", "the", "data", "for", "the", "LTI", "basic", "launch" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/lti.py#L145-L197
train
229,847
UCL-INGI/INGInious
inginious/frontend/pages/lti.py
LTILaunchPage._find_realname
def _find_realname(self, post_input): """ Returns the most appropriate name to identify the user """ # First, try the full name 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"] # Then the email if "lis_person_contact_email_primary" in post_input: return post_input["lis_person_contact_email_primary"] # Then only part of the full name if "lis_person_name_family" in post_input: return post_input["lis_person_name_family"] if "lis_person_name_given" in post_input: return post_input["lis_person_name_given"] return post_input["user_id"]
python
def _find_realname(self, post_input): """ Returns the most appropriate name to identify the user """ # First, try the full name 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"] # Then the email if "lis_person_contact_email_primary" in post_input: return post_input["lis_person_contact_email_primary"] # Then only part of the full name if "lis_person_name_family" in post_input: return post_input["lis_person_name_family"] if "lis_person_name_given" in post_input: return post_input["lis_person_name_given"] return post_input["user_id"]
[ "def", "_find_realname", "(", "self", ",", "post_input", ")", ":", "# First, try the full name", "if", "\"lis_person_name_full\"", "in", "post_input", ":", "return", "post_input", "[", "\"lis_person_name_full\"", "]", "if", "\"lis_person_name_given\"", "in", "post_input",...
Returns the most appropriate name to identify the user
[ "Returns", "the", "most", "appropriate", "name", "to", "identify", "the", "user" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/lti.py#L199-L218
train
229,848
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/statistics.py
fast_stats
def fast_stats(data): """ Compute base statistics about submissions """ 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": total_submission_best_succeeded += 1 statistics = [ (_("Number of submissions"), total_submission), (_("Evaluation submissions (Total)"), total_submission_best), (_("Evaluation submissions (Succeeded)"), total_submission_best_succeeded), (_("Evaluation submissions (Failed)"), total_submission_best - total_submission_best_succeeded), # add here new common statistics ] return statistics
python
def fast_stats(data): """ Compute base statistics about submissions """ 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": total_submission_best_succeeded += 1 statistics = [ (_("Number of submissions"), total_submission), (_("Evaluation submissions (Total)"), total_submission_best), (_("Evaluation submissions (Succeeded)"), total_submission_best_succeeded), (_("Evaluation submissions (Failed)"), total_submission_best - total_submission_best_succeeded), # add here new common statistics ] return statistics
[ "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", "...
Compute base statistics about submissions
[ "Compute", "base", "statistics", "about", "submissions" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/statistics.py#L172-L193
train
229,849
UCL-INGI/INGInious
inginious/client/_zeromq_client.py
BetterParanoidPirateClient._register_transaction
def _register_transaction(self, send_msg, recv_msg, coroutine_recv, coroutine_abrt, get_key=None, inter_msg=None): """ 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. :param send_msg: class of message to be sent :param recv_msg: message that the server should send in response :param get_key: receive a `send_msg` or `recv_msg` as input, and returns the "key" (global identifier) of the message :param coroutine_recv: callback called (on the event loop) when the transaction succeed, with, as input, `recv_msg` and eventually other args given to .send :param coroutine_abrt: callback called (on the event loop) when the transaction fails, with, as input, `recv_msg` and eventually other args given to .send :param inter_msg: a list of `(message_class, coroutine_recv)`, that can be received during the resolution of the transaction but will not finalize it. `get_key` is used on these `message_class` to get the key of the transaction. """ if get_key is None: get_key = lambda x: None if inter_msg is None: inter_msg = [] # format is (other_msg, get_key, recv_handler, abrt_handler,responsible_for) # where responsible_for is the list of classes whose transaction will be killed when this message is received. self._msgs_registered[send_msg.__msgtype__] = ([recv_msg.__msgtype__] + [x.__msgtype__ for x, _ in inter_msg], get_key, None, None, []) self._msgs_registered[recv_msg.__msgtype__] = ( [], get_key, coroutine_recv, coroutine_abrt, [recv_msg.__msgtype__] + [x.__msgtype__ for x, _ in inter_msg]) self._transactions[recv_msg.__msgtype__] = {} for msg_class, handler in inter_msg: self._msgs_registered[msg_class.__msgtype__] = ([], get_key, handler, None, []) self._transactions[msg_class.__msgtype__] = {}
python
def _register_transaction(self, send_msg, recv_msg, coroutine_recv, coroutine_abrt, get_key=None, inter_msg=None): """ 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. :param send_msg: class of message to be sent :param recv_msg: message that the server should send in response :param get_key: receive a `send_msg` or `recv_msg` as input, and returns the "key" (global identifier) of the message :param coroutine_recv: callback called (on the event loop) when the transaction succeed, with, as input, `recv_msg` and eventually other args given to .send :param coroutine_abrt: callback called (on the event loop) when the transaction fails, with, as input, `recv_msg` and eventually other args given to .send :param inter_msg: a list of `(message_class, coroutine_recv)`, that can be received during the resolution of the transaction but will not finalize it. `get_key` is used on these `message_class` to get the key of the transaction. """ if get_key is None: get_key = lambda x: None if inter_msg is None: inter_msg = [] # format is (other_msg, get_key, recv_handler, abrt_handler,responsible_for) # where responsible_for is the list of classes whose transaction will be killed when this message is received. self._msgs_registered[send_msg.__msgtype__] = ([recv_msg.__msgtype__] + [x.__msgtype__ for x, _ in inter_msg], get_key, None, None, []) self._msgs_registered[recv_msg.__msgtype__] = ( [], get_key, coroutine_recv, coroutine_abrt, [recv_msg.__msgtype__] + [x.__msgtype__ for x, _ in inter_msg]) self._transactions[recv_msg.__msgtype__] = {} for msg_class, handler in inter_msg: self._msgs_registered[msg_class.__msgtype__] = ([], get_key, handler, None, []) self._transactions[msg_class.__msgtype__] = {}
[ "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", ...
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. :param send_msg: class of message to be sent :param recv_msg: message that the server should send in response :param get_key: receive a `send_msg` or `recv_msg` as input, and returns the "key" (global identifier) of the message :param coroutine_recv: callback called (on the event loop) when the transaction succeed, with, as input, `recv_msg` and eventually other args given to .send :param coroutine_abrt: callback called (on the event loop) when the transaction fails, with, as input, `recv_msg` and eventually other args given to .send :param inter_msg: a list of `(message_class, coroutine_recv)`, that can be received during the resolution of the transaction but will not finalize it. `get_key` is used on these `message_class` to get the key of the transaction.
[ "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...
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/_zeromq_client.py#L49-L79
train
229,850
UCL-INGI/INGInious
inginious/client/_zeromq_client.py
BetterParanoidPirateClient._reconnect
async def _reconnect(self): """ Called when the remote server is innacessible and the connection has to be restarted """ # 1. Close all transactions 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(coroutine_abrt(key, *args, **kwargs)) self._transactions[msg_class] = {} # 2. Call on_disconnect await self._on_disconnect() # 3. Stop tasks for task in self._restartable_tasks: task.cancel() self._restartable_tasks = [] # 4. Restart socket self._socket.disconnect(self._router_addr) # 5. Re-do start sequence await self.client_start()
python
async def _reconnect(self): """ Called when the remote server is innacessible and the connection has to be restarted """ # 1. Close all transactions 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(coroutine_abrt(key, *args, **kwargs)) self._transactions[msg_class] = {} # 2. Call on_disconnect await self._on_disconnect() # 3. Stop tasks for task in self._restartable_tasks: task.cancel() self._restartable_tasks = [] # 4. Restart socket self._socket.disconnect(self._router_addr) # 5. Re-do start sequence await self.client_start()
[ "async", "def", "_reconnect", "(", "self", ")", ":", "# 1. Close all transactions", "for", "msg_class", "in", "self", ".", "_transactions", ":", "_1", ",", "_2", ",", "_3", ",", "coroutine_abrt", ",", "_4", "=", "self", ".", "_msgs_registered", "[", "msg_cla...
Called when the remote server is innacessible and the connection has to be restarted
[ "Called", "when", "the", "remote", "server", "is", "innacessible", "and", "the", "connection", "has", "to", "be", "restarted" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/_zeromq_client.py#L152-L178
train
229,851
UCL-INGI/INGInious
inginious/client/_zeromq_client.py
BetterParanoidPirateClient.client_start
async def client_start(self): """ Starts the client """ await self._start_socket() await self._on_connect() self._ping_count = 0 # Start the loops, and don't forget to add them to the list of asyncio task to close when the client restarts 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_tasks.append(task_socket)
python
async def client_start(self): """ Starts the client """ await self._start_socket() await self._on_connect() self._ping_count = 0 # Start the loops, and don't forget to add them to the list of asyncio task to close when the client restarts 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_tasks.append(task_socket)
[ "async", "def", "client_start", "(", "self", ")", ":", "await", "self", ".", "_start_socket", "(", ")", "await", "self", ".", "_on_connect", "(", ")", "self", ".", "_ping_count", "=", "0", "# Start the loops, and don't forget to add them to the list of asyncio task to...
Starts the client
[ "Starts", "the", "client" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/_zeromq_client.py#L180-L194
train
229,852
UCL-INGI/INGInious
inginious/client/_zeromq_client.py
BetterParanoidPirateClient._run_socket
async def _run_socket(self): """ Task that runs this client. """ try: while True: message = await ZMQUtils.recv(self._socket) msg_class = message.__msgtype__ if msg_class in self._handlers_registered: # If a handler is registered, give the message to it self._loop.create_task(self._handlers_registered[msg_class](message)) elif msg_class in self._transactions: # If there are transaction associated, check if the key is ok _1, get_key, coroutine_recv, _2, responsible = self._msgs_registered[msg_class] key = get_key(message) if key in self._transactions[msg_class]: # key exists; call all the coroutines for args, kwargs in self._transactions[msg_class][key]: self._loop.create_task(coroutine_recv(message, *args, **kwargs)) # remove all transaction parts for key2 in responsible: del self._transactions[key2][key] else: # key does not exist raise Exception("Received message %s for an unknown transaction %s", msg_class, key) else: raise Exception("Received unknown message %s", msg_class) except asyncio.CancelledError: return except KeyboardInterrupt: return
python
async def _run_socket(self): """ Task that runs this client. """ try: while True: message = await ZMQUtils.recv(self._socket) msg_class = message.__msgtype__ if msg_class in self._handlers_registered: # If a handler is registered, give the message to it self._loop.create_task(self._handlers_registered[msg_class](message)) elif msg_class in self._transactions: # If there are transaction associated, check if the key is ok _1, get_key, coroutine_recv, _2, responsible = self._msgs_registered[msg_class] key = get_key(message) if key in self._transactions[msg_class]: # key exists; call all the coroutines for args, kwargs in self._transactions[msg_class][key]: self._loop.create_task(coroutine_recv(message, *args, **kwargs)) # remove all transaction parts for key2 in responsible: del self._transactions[key2][key] else: # key does not exist raise Exception("Received message %s for an unknown transaction %s", msg_class, key) else: raise Exception("Received unknown message %s", msg_class) except asyncio.CancelledError: return except KeyboardInterrupt: return
[ "async", "def", "_run_socket", "(", "self", ")", ":", "try", ":", "while", "True", ":", "message", "=", "await", "ZMQUtils", ".", "recv", "(", "self", ".", "_socket", ")", "msg_class", "=", "message", ".", "__msgtype__", "if", "msg_class", "in", "self", ...
Task that runs this client.
[ "Task", "that", "runs", "this", "client", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/_zeromq_client.py#L202-L232
train
229,853
UCL-INGI/INGInious
base-containers/base/inginious/feedback.py
load_feedback
def load_feedback(): """ Open existing feedback file """ 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 by user !"} return result
python
def load_feedback(): """ Open existing feedback file """ 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 by user !"} return result
[ "def", "load_feedback", "(", ")", ":", "result", "=", "{", "}", "if", "os", ".", "path", ".", "exists", "(", "_feedback_file", ")", ":", "f", "=", "open", "(", "_feedback_file", ",", "'r'", ")", "cont", "=", "f", ".", "read", "(", ")", "f", ".", ...
Open existing feedback file
[ "Open", "existing", "feedback", "file" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/feedback.py#L18-L32
train
229,854
UCL-INGI/INGInious
base-containers/base/inginious/feedback.py
save_feedback
def save_feedback(rdict): """ Save feedback file """ # Check for output folder 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()
python
def save_feedback(rdict): """ Save feedback file """ # Check for output folder 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()
[ "def", "save_feedback", "(", "rdict", ")", ":", "# Check for output folder", "if", "not", "os", ".", "path", ".", "exists", "(", "_feedback_dir", ")", ":", "os", ".", "makedirs", "(", "_feedback_dir", ")", "jcont", "=", "json", ".", "dumps", "(", "rdict", ...
Save feedback file
[ "Save", "feedback", "file" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/feedback.py#L35-L44
train
229,855
UCL-INGI/INGInious
base-containers/base/inginious/feedback.py
set_problem_result
def set_problem_result(result, problem_id): """ Set problem specific result value """ 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(rdict)
python
def set_problem_result(result, problem_id): """ Set problem specific result value """ 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(rdict)
[ "def", "set_problem_result", "(", "result", ",", "problem_id", ")", ":", "rdict", "=", "load_feedback", "(", ")", "if", "not", "'problems'", "in", "rdict", ":", "rdict", "[", "'problems'", "]", "=", "{", "}", "cur_val", "=", "rdict", "[", "'problems'", "...
Set problem specific result value
[ "Set", "problem", "specific", "result", "value" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/feedback.py#L55-L62
train
229,856
UCL-INGI/INGInious
base-containers/base/inginious/feedback.py
set_global_feedback
def set_global_feedback(feedback, append=False): """ Set global feedback in case of error """ rdict = load_feedback() rdict['text'] = rdict.get('text', '') + feedback if append else feedback save_feedback(rdict)
python
def set_global_feedback(feedback, append=False): """ Set global feedback in case of error """ rdict = load_feedback() rdict['text'] = rdict.get('text', '') + feedback if append else feedback save_feedback(rdict)
[ "def", "set_global_feedback", "(", "feedback", ",", "append", "=", "False", ")", ":", "rdict", "=", "load_feedback", "(", ")", "rdict", "[", "'text'", "]", "=", "rdict", ".", "get", "(", "'text'", ",", "''", ")", "+", "feedback", "if", "append", "else"...
Set global feedback in case of error
[ "Set", "global", "feedback", "in", "case", "of", "error" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/feedback.py#L72-L76
train
229,857
UCL-INGI/INGInious
base-containers/base/inginious/feedback.py
set_problem_feedback
def set_problem_feedback(feedback, problem_id, append=False): """ Set problem specific feedback """ 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 else [cur_val[0], (cur_val[1] + feedback if append else feedback)] save_feedback(rdict)
python
def set_problem_feedback(feedback, problem_id, append=False): """ Set problem specific feedback """ 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 else [cur_val[0], (cur_val[1] + feedback if append else feedback)] save_feedback(rdict)
[ "def", "set_problem_feedback", "(", "feedback", ",", "problem_id", ",", "append", "=", "False", ")", ":", "rdict", "=", "load_feedback", "(", ")", "if", "not", "'problems'", "in", "rdict", ":", "rdict", "[", "'problems'", "]", "=", "{", "}", "cur_val", "...
Set problem specific feedback
[ "Set", "problem", "specific", "feedback" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/feedback.py#L79-L86
train
229,858
UCL-INGI/INGInious
inginious/frontend/installer.py
Installer._display_big_warning
def _display_big_warning(self, content): """ Displays a BIG warning """ print("") print(BOLD + WARNING + "--- WARNING ---" + ENDC) print(WARNING + content + ENDC) print("")
python
def _display_big_warning(self, content): """ Displays a BIG warning """ print("") print(BOLD + WARNING + "--- WARNING ---" + ENDC) print(WARNING + content + ENDC) print("")
[ "def", "_display_big_warning", "(", "self", ",", "content", ")", ":", "print", "(", "\"\"", ")", "print", "(", "BOLD", "+", "WARNING", "+", "\"--- WARNING ---\"", "+", "ENDC", ")", "print", "(", "WARNING", "+", "content", "+", "ENDC", ")", "print", "(", ...
Displays a BIG warning
[ "Displays", "a", "BIG", "warning" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/installer.py#L64-L69
train
229,859
UCL-INGI/INGInious
inginious/frontend/installer.py
Installer._ask_local_config
def _ask_local_config(self): """ Ask some parameters about the local configuration """ options = {"backend": "local", "local-config": {}} # Concurrency 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 = int(concurrency) except: self._display_error("Invalid number") continue if concurrency <= 0: self._display_error("Invalid number") continue options["local-config"]["concurrency"] = concurrency break # Debug hostname hostname = self._ask_with_default( "What is the external hostname/address of your machine? You can leave this empty and let INGInious " "autodetect it.", "") if hostname != "": options["local-config"]["debug_host"] = hostname self._display_info( "You can now enter the port range for the remote debugging feature of INGInious. Please verify that these " "ports are open in your firewall. You can leave this parameters empty, the default is 64100-64200") # Debug port range port_range = None while True: start_port = self._ask_with_default("Beginning of the range", "") if start_port != "": try: start_port = int(start_port) except: self._display_error("Invalid number") continue end_port = self._ask_with_default("End of the range", str(start_port + 100)) try: end_port = int(end_port) except: self._display_error("Invalid number") continue if start_port > end_port: self._display_error("Invalid range") continue port_range = str(start_port) + "-" + str(end_port) else: break if port_range != None: options["local-config"]["debug_ports"] = port_range return options
python
def _ask_local_config(self): """ Ask some parameters about the local configuration """ options = {"backend": "local", "local-config": {}} # Concurrency 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 = int(concurrency) except: self._display_error("Invalid number") continue if concurrency <= 0: self._display_error("Invalid number") continue options["local-config"]["concurrency"] = concurrency break # Debug hostname hostname = self._ask_with_default( "What is the external hostname/address of your machine? You can leave this empty and let INGInious " "autodetect it.", "") if hostname != "": options["local-config"]["debug_host"] = hostname self._display_info( "You can now enter the port range for the remote debugging feature of INGInious. Please verify that these " "ports are open in your firewall. You can leave this parameters empty, the default is 64100-64200") # Debug port range port_range = None while True: start_port = self._ask_with_default("Beginning of the range", "") if start_port != "": try: start_port = int(start_port) except: self._display_error("Invalid number") continue end_port = self._ask_with_default("End of the range", str(start_port + 100)) try: end_port = int(end_port) except: self._display_error("Invalid number") continue if start_port > end_port: self._display_error("Invalid range") continue port_range = str(start_port) + "-" + str(end_port) else: break if port_range != None: options["local-config"]["debug_ports"] = port_range return options
[ "def", "_ask_local_config", "(", "self", ")", ":", "options", "=", "{", "\"backend\"", ":", "\"local\"", ",", "\"local-config\"", ":", "{", "}", "}", "# Concurrency", "while", "True", ":", "concurrency", "=", "self", ".", "_ask_with_default", "(", "\"Maximum c...
Ask some parameters about the local configuration
[ "Ask", "some", "parameters", "about", "the", "local", "configuration" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/installer.py#L170-L230
train
229,860
UCL-INGI/INGInious
inginious/frontend/installer.py
Installer.ask_backend
def ask_backend(self): """ Ask the user to choose the backend """ 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.io/en/latest/install_doc/troubleshooting.html") return "local" else: self._display_info( "You will have to run inginious-backend and inginious-agent yourself. Please run the commands without argument " "and/or read the documentation for more info") return self._display_question("Please enter the address of your backend")
python
def ask_backend(self): """ Ask the user to choose the backend """ 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.io/en/latest/install_doc/troubleshooting.html") return "local" else: self._display_info( "You will have to run inginious-backend and inginious-agent yourself. Please run the commands without argument " "and/or read the documentation for more info") return self._display_question("Please enter the address of your backend")
[ "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", ...
Ask the user to choose the backend
[ "Ask", "the", "user", "to", "choose", "the", "backend" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/installer.py#L252-L265
train
229,861
UCL-INGI/INGInious
inginious/frontend/installer.py
Installer.try_mongodb_opts
def try_mongodb_opts(self, host="localhost", database_name='INGInious'): """ Try MongoDB configuration """ 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 Exception as e: self._display_warning("Cannot access database %s: %s" % (database_name, str(e))) return None try: GridFS(database) except Exception as e: self._display_warning("Cannot access gridfs %s: %s" % (database_name, str(e))) return None return database
python
def try_mongodb_opts(self, host="localhost", database_name='INGInious'): """ Try MongoDB configuration """ 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 Exception as e: self._display_warning("Cannot access database %s: %s" % (database_name, str(e))) return None try: GridFS(database) except Exception as e: self._display_warning("Cannot access gridfs %s: %s" % (database_name, str(e))) return None return database
[ "def", "try_mongodb_opts", "(", "self", ",", "host", "=", "\"localhost\"", ",", "database_name", "=", "'INGInious'", ")", ":", "try", ":", "mongo_client", "=", "MongoClient", "(", "host", "=", "host", ")", "except", "Exception", "as", "e", ":", "self", "."...
Try MongoDB configuration
[ "Try", "MongoDB", "configuration" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/installer.py#L271-L291
train
229,862
UCL-INGI/INGInious
inginious/frontend/installer.py
Installer.configure_task_directory
def configure_task_directory(self): """ Configure task directory """ 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", ".") if not os.path.exists(task_directory): self._display_error("Path does not exists") if self._ask_boolean("Would you like to retry?", True): task_directory = None if os.path.exists(task_directory): self._display_question("Demonstration tasks can be downloaded to let you discover INGInious.") if self._ask_boolean("Would you like to download them ?", True): try: filename, _ = urllib.request.urlretrieve( "https://api.github.com/repos/UCL-INGI/INGInious-demo-tasks/tarball") with tarfile.open(filename, mode="r:gz") as thetarfile: members = thetarfile.getmembers() commonpath = os.path.commonpath([tarinfo.name for tarinfo in members]) for member in members: member.name = member.name[len(commonpath) + 1:] if member.name: thetarfile.extract(member, task_directory) self._display_info("Successfully downloaded and copied demonstration tasks.") except Exception as e: self._display_error("An error occurred while copying the directory: %s" % str(e)) else: self._display_warning("Skipping copying the 'test' course because the task dir does not exists") return {"tasks_directory": task_directory}
python
def configure_task_directory(self): """ Configure task directory """ 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", ".") if not os.path.exists(task_directory): self._display_error("Path does not exists") if self._ask_boolean("Would you like to retry?", True): task_directory = None if os.path.exists(task_directory): self._display_question("Demonstration tasks can be downloaded to let you discover INGInious.") if self._ask_boolean("Would you like to download them ?", True): try: filename, _ = urllib.request.urlretrieve( "https://api.github.com/repos/UCL-INGI/INGInious-demo-tasks/tarball") with tarfile.open(filename, mode="r:gz") as thetarfile: members = thetarfile.getmembers() commonpath = os.path.commonpath([tarinfo.name for tarinfo in members]) for member in members: member.name = member.name[len(commonpath) + 1:] if member.name: thetarfile.extract(member, task_directory) self._display_info("Successfully downloaded and copied demonstration tasks.") except Exception as e: self._display_error("An error occurred while copying the directory: %s" % str(e)) else: self._display_warning("Skipping copying the 'test' course because the task dir does not exists") return {"tasks_directory": task_directory}
[ "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", ...
Configure task directory
[ "Configure", "task", "directory" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/installer.py#L326-L360
train
229,863
UCL-INGI/INGInious
inginious/frontend/installer.py
Installer.download_containers
def download_containers(self, to_download, current_options): """ Download the chosen containers on all the agents """ 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.") return for image in to_download: try: self._display_info("Downloading image %s. This can take some time." % image) docker_connection.images.pull(image + ":latest") except Exception as e: self._display_error("An error occurred while pulling the image: %s." % str(e)) else: self._display_warning( "This installation tool does not support the backend configuration directly, if it's not local. You will have to " "pull the images by yourself. Here is the list: %s" % str(to_download))
python
def download_containers(self, to_download, current_options): """ Download the chosen containers on all the agents """ 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.") return for image in to_download: try: self._display_info("Downloading image %s. This can take some time." % image) docker_connection.images.pull(image + ":latest") except Exception as e: self._display_error("An error occurred while pulling the image: %s." % str(e)) else: self._display_warning( "This installation tool does not support the backend configuration directly, if it's not local. You will have to " "pull the images by yourself. Here is the list: %s" % str(to_download))
[ "def", "download_containers", "(", "self", ",", "to_download", ",", "current_options", ")", ":", "if", "current_options", "[", "\"backend\"", "]", "==", "\"local\"", ":", "self", ".", "_display_info", "(", "\"Connecting to the local Docker daemon...\"", ")", "try", ...
Download the chosen containers on all the agents
[ "Download", "the", "chosen", "containers", "on", "all", "the", "agents" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/installer.py#L366-L385
train
229,864
UCL-INGI/INGInious
inginious/frontend/installer.py
Installer.configure_containers
def configure_containers(self, current_options): """ Configures the container dict """ 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 C#, F# and many other languages"), ("oz", "Contains Mozart 2, an implementation of the Oz multi-paradigm language, made for education"), ("php", "Contains PHP 5"), ("pythia0compat", "Compatibility container for Pythia 0"), ("pythia1compat", "Compatibility container for Pythia 1"), ("r", "Can run R scripts"), ("sekexe", "Can run an user-mode-linux for advanced tasks") ] default_download = ["default"] self._display_question( "The tool will now propose to download some base container image for multiple languages.") self._display_question( "Please note that the download of these images can take a lot of time, so choose only the images you need") to_download = [] for container_name, description in containers: if self._ask_boolean("Download %s (%s) ?" % (container_name, description), container_name in default_download): to_download.append("ingi/inginious-c-%s" % container_name) self.download_containers(to_download, current_options) wants = self._ask_boolean("Do you want to manually add some images?", False) while wants: image = self._ask_with_default("Container image name (leave this field empty to skip)", "") if image == "": break self._display_info("Configuration of the containers done.")
python
def configure_containers(self, current_options): """ Configures the container dict """ 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 C#, F# and many other languages"), ("oz", "Contains Mozart 2, an implementation of the Oz multi-paradigm language, made for education"), ("php", "Contains PHP 5"), ("pythia0compat", "Compatibility container for Pythia 0"), ("pythia1compat", "Compatibility container for Pythia 1"), ("r", "Can run R scripts"), ("sekexe", "Can run an user-mode-linux for advanced tasks") ] default_download = ["default"] self._display_question( "The tool will now propose to download some base container image for multiple languages.") self._display_question( "Please note that the download of these images can take a lot of time, so choose only the images you need") to_download = [] for container_name, description in containers: if self._ask_boolean("Download %s (%s) ?" % (container_name, description), container_name in default_download): to_download.append("ingi/inginious-c-%s" % container_name) self.download_containers(to_download, current_options) wants = self._ask_boolean("Do you want to manually add some images?", False) while wants: image = self._ask_with_default("Container image name (leave this field empty to skip)", "") if image == "": break self._display_info("Configuration of the containers done.")
[ "def", "configure_containers", "(", "self", ",", "current_options", ")", ":", "containers", "=", "[", "(", "\"default\"", ",", "\"Default container. For Bash and Python 2 tasks\"", ")", ",", "(", "\"cpp\"", ",", "\"Contains gcc and g++ for compiling C++\"", ")", ",", "(...
Configures the container dict
[ "Configures", "the", "container", "dict" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/installer.py#L387-L424
train
229,865
UCL-INGI/INGInious
inginious/frontend/installer.py
Installer.configure_backup_directory
def configure_backup_directory(self): """ Configure backup directory """ 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", ".") if not os.path.exists(backup_directory): self._display_error("Path does not exists") if self._ask_boolean("Would you like to retry?", True): backup_directory = None return {"backup_directory": backup_directory}
python
def configure_backup_directory(self): """ Configure backup directory """ 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", ".") if not os.path.exists(backup_directory): self._display_error("Path does not exists") if self._ask_boolean("Would you like to retry?", True): backup_directory = None return {"backup_directory": backup_directory}
[ "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", "ba...
Configure backup directory
[ "Configure", "backup", "directory" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/installer.py#L439-L451
train
229,866
UCL-INGI/INGInious
inginious/frontend/installer.py
Installer.ldap_plugin
def ldap_plugin(self): """ Configures the LDAP plugin """ 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 = self._ask_with_default("LDAP Host", "ldap.your.domain.com") encryption = 'none' while True: encryption = self._ask_with_default("Encryption (either 'ssl', 'tls', or 'none')", 'none') if encryption not in ['none', 'ssl', 'tls']: self._display_error("Invalid value") else: break base_dn = self._ask_with_default("Base DN", "ou=people,c=com") request = self._ask_with_default("Request to find a user. '{}' will be replaced by the username", "uid={}") require_cert = self._ask_boolean("Require certificate validation?", encryption is not None) return { "plugin_module": "inginious.frontend.plugins.auth.ldap_auth", "host": ldap_host, "encryption": encryption, "base_dn": base_dn, "request": request, "prefix": prefix, "name": name, "require_cert": require_cert }
python
def ldap_plugin(self): """ Configures the LDAP plugin """ 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 = self._ask_with_default("LDAP Host", "ldap.your.domain.com") encryption = 'none' while True: encryption = self._ask_with_default("Encryption (either 'ssl', 'tls', or 'none')", 'none') if encryption not in ['none', 'ssl', 'tls']: self._display_error("Invalid value") else: break base_dn = self._ask_with_default("Base DN", "ou=people,c=com") request = self._ask_with_default("Request to find a user. '{}' will be replaced by the username", "uid={}") require_cert = self._ask_boolean("Require certificate validation?", encryption is not None) return { "plugin_module": "inginious.frontend.plugins.auth.ldap_auth", "host": ldap_host, "encryption": encryption, "base_dn": base_dn, "request": request, "prefix": prefix, "name": name, "require_cert": require_cert }
[ "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 ...
Configures the LDAP plugin
[ "Configures", "the", "LDAP", "plugin" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/installer.py#L453-L481
train
229,867
UCL-INGI/INGInious
inginious/frontend/installer.py
Installer.configure_authentication
def configure_authentication(self, database): """ Configure the authentication """ 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 superadmin", "INGInious SuperAdmin") email = self._ask_with_default("Enter the email address of the superadmin", "superadmin@inginious.org") password = self._ask_with_default("Enter the password of the superadmin", "superadmin") database.users.insert({"username": username, "realname": realname, "email": email, "password": hashlib.sha512(password.encode("utf-8")).hexdigest(), "bindings": {}, "language": "en"}) options["superadmins"].append(username) while True: if not self._ask_boolean("Would you like to add another auth method?", False): break self._display_info("You can choose an authentication plugin between:") self._display_info("- 1. LDAP auth plugin. This plugin allows to connect to a distant LDAP host.") plugin = self._ask_with_default("Enter the corresponding number to your choice", '1') if plugin not in ['1']: continue elif plugin == '1': options["plugins"].append(self.ldap_plugin()) return options
python
def configure_authentication(self, database): """ Configure the authentication """ 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 superadmin", "INGInious SuperAdmin") email = self._ask_with_default("Enter the email address of the superadmin", "superadmin@inginious.org") password = self._ask_with_default("Enter the password of the superadmin", "superadmin") database.users.insert({"username": username, "realname": realname, "email": email, "password": hashlib.sha512(password.encode("utf-8")).hexdigest(), "bindings": {}, "language": "en"}) options["superadmins"].append(username) while True: if not self._ask_boolean("Would you like to add another auth method?", False): break self._display_info("You can choose an authentication plugin between:") self._display_info("- 1. LDAP auth plugin. This plugin allows to connect to a distant LDAP host.") plugin = self._ask_with_default("Enter the corresponding number to your choice", '1') if plugin not in ['1']: continue elif plugin == '1': options["plugins"].append(self.ldap_plugin()) return options
[ "def", "configure_authentication", "(", "self", ",", "database", ")", ":", "options", "=", "{", "\"plugins\"", ":", "[", "]", ",", "\"superadmins\"", ":", "[", "]", "}", "self", ".", "_display_info", "(", "\"We will now create the first user.\"", ")", "username"...
Configure the authentication
[ "Configure", "the", "authentication" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/installer.py#L483-L515
train
229,868
UCL-INGI/INGInious
inginious/frontend/app.py
_close_app
def _close_app(app, mongo_client, client): """ Ensures that the app is properly closed """ app.stop() client.close() mongo_client.close()
python
def _close_app(app, mongo_client, client): """ Ensures that the app is properly closed """ app.stop() client.close() mongo_client.close()
[ "def", "_close_app", "(", "app", ",", "mongo_client", ",", "client", ")", ":", "app", ".", "stop", "(", ")", "client", ".", "close", "(", ")", "mongo_client", ".", "close", "(", ")" ]
Ensures that the app is properly closed
[ "Ensures", "that", "the", "app", "is", "properly", "closed" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/app.py#L113-L117
train
229,869
UCL-INGI/INGInious
inginious/agent/docker_agent/__init__.py
DockerAgent._init_clean
async def _init_clean(self): """ Must be called when the agent is starting """ # Data about running containers self._containers_running = {} self._container_for_job = {} self._student_containers_running = {} self._student_containers_for_job = {} self._containers_killed = dict() # Delete tmp_dir, and recreate-it again try: await self._ashutil.rmtree(self._tmp_dir) except OSError: pass try: await self._aos.mkdir(self._tmp_dir) except OSError: pass # Docker self._docker = AsyncProxy(DockerInterface()) # Auto discover containers self._logger.info("Discovering containers") self._containers = await self._docker.get_containers() self._assigned_external_ports = {} # container_id : [external_ports] if self._address_host is None and len(self._containers) != 0: self._logger.info("Guessing external host IP") self._address_host = await self._docker.get_host_ip(next(iter(self._containers.values()))["id"]) if self._address_host is None: self._logger.warning( "Cannot find external host IP. Please indicate it in the configuration. Remote SSH debug has been deactivated.") self._external_ports = None else: self._logger.info("External address for SSH remote debug is %s", self._address_host) # Watchers self._timeout_watcher = TimeoutWatcher(self._docker)
python
async def _init_clean(self): """ Must be called when the agent is starting """ # Data about running containers self._containers_running = {} self._container_for_job = {} self._student_containers_running = {} self._student_containers_for_job = {} self._containers_killed = dict() # Delete tmp_dir, and recreate-it again try: await self._ashutil.rmtree(self._tmp_dir) except OSError: pass try: await self._aos.mkdir(self._tmp_dir) except OSError: pass # Docker self._docker = AsyncProxy(DockerInterface()) # Auto discover containers self._logger.info("Discovering containers") self._containers = await self._docker.get_containers() self._assigned_external_ports = {} # container_id : [external_ports] if self._address_host is None and len(self._containers) != 0: self._logger.info("Guessing external host IP") self._address_host = await self._docker.get_host_ip(next(iter(self._containers.values()))["id"]) if self._address_host is None: self._logger.warning( "Cannot find external host IP. Please indicate it in the configuration. Remote SSH debug has been deactivated.") self._external_ports = None else: self._logger.info("External address for SSH remote debug is %s", self._address_host) # Watchers self._timeout_watcher = TimeoutWatcher(self._docker)
[ "async", "def", "_init_clean", "(", "self", ")", ":", "# Data about running containers", "self", ".", "_containers_running", "=", "{", "}", "self", ".", "_container_for_job", "=", "{", "}", "self", ".", "_student_containers_running", "=", "{", "}", "self", ".", ...
Must be called when the agent is starting
[ "Must", "be", "called", "when", "the", "agent", "is", "starting" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/docker_agent/__init__.py#L57-L99
train
229,870
UCL-INGI/INGInious
inginious/agent/docker_agent/__init__.py
DockerAgent._end_clean
async def _end_clean(self): """ Must be called when the agent is closing """ 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._student_containers_running: await close_and_delete(container_id)
python
async def _end_clean(self): """ Must be called when the agent is closing """ 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._student_containers_running: await close_and_delete(container_id)
[ "async", "def", "_end_clean", "(", "self", ")", ":", "await", "self", ".", "_timeout_watcher", ".", "clean", "(", ")", "async", "def", "close_and_delete", "(", "container_id", ")", ":", "try", ":", "await", "self", ".", "_docker", ".", "remove_container", ...
Must be called when the agent is closing
[ "Must", "be", "called", "when", "the", "agent", "is", "closing" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/docker_agent/__init__.py#L101-L114
train
229,871
UCL-INGI/INGInious
inginious/agent/docker_agent/__init__.py
DockerAgent._watch_docker_events
async def _watch_docker_events(self): """ Get raw docker events and convert them to more readable objects, and then give them to self._docker_events_subscriber """ 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"]["Attributes"]["exitCode"]) except asyncio.CancelledError: raise except: self._logger.exception("Cannot parse exitCode for container %s", container_id) retval = -1 if container_id in self._containers_running: self._create_safe_task(self.handle_job_closing(container_id, retval)) elif container_id in self._student_containers_running: self._create_safe_task(self.handle_student_job_closing(container_id, retval)) elif i["Type"] == "container" and i["status"] == "oom": container_id = i["id"] if container_id in self._containers_running or container_id in self._student_containers_running: self._logger.info("Container %s did OOM, killing it", container_id) self._containers_killed[container_id] = "overflow" try: self._create_safe_task(self._docker.kill_container(container_id)) except asyncio.CancelledError: raise except: # this call can sometimes fail, and that is normal. pass else: raise TypeError(str(i)) except asyncio.CancelledError: pass except: self._logger.exception("Exception in _watch_docker_events")
python
async def _watch_docker_events(self): """ Get raw docker events and convert them to more readable objects, and then give them to self._docker_events_subscriber """ 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"]["Attributes"]["exitCode"]) except asyncio.CancelledError: raise except: self._logger.exception("Cannot parse exitCode for container %s", container_id) retval = -1 if container_id in self._containers_running: self._create_safe_task(self.handle_job_closing(container_id, retval)) elif container_id in self._student_containers_running: self._create_safe_task(self.handle_student_job_closing(container_id, retval)) elif i["Type"] == "container" and i["status"] == "oom": container_id = i["id"] if container_id in self._containers_running or container_id in self._student_containers_running: self._logger.info("Container %s did OOM, killing it", container_id) self._containers_killed[container_id] = "overflow" try: self._create_safe_task(self._docker.kill_container(container_id)) except asyncio.CancelledError: raise except: # this call can sometimes fail, and that is normal. pass else: raise TypeError(str(i)) except asyncio.CancelledError: pass except: self._logger.exception("Exception in _watch_docker_events")
[ "async", "def", "_watch_docker_events", "(", "self", ")", ":", "try", ":", "source", "=", "AsyncIteratorWrapper", "(", "self", ".", "_docker", ".", "sync", ".", "event_stream", "(", "filters", "=", "{", "\"event\"", ":", "[", "\"die\"", ",", "\"oom\"", "]"...
Get raw docker events and convert them to more readable objects, and then give them to self._docker_events_subscriber
[ "Get", "raw", "docker", "events", "and", "convert", "them", "to", "more", "readable", "objects", "and", "then", "give", "them", "to", "self", ".", "_docker_events_subscriber" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/docker_agent/__init__.py#L120-L155
train
229,872
UCL-INGI/INGInious
inginious/agent/docker_agent/__init__.py
DockerAgent.handle_student_job_closing
async def handle_student_job_closing(self, container_id, retval): """ Handle a closing student container. Do some cleaning, verify memory limits, timeouts, ... and returns data to the associated grading container """ 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 asyncio.CancelledError: raise except: self._logger.warning("Student container %s that has finished(p1) was not launched by this agent", str(container_id), exc_info=True) return # Delete remaining student containers if job_id in self._student_containers_for_job: # if it does not exists, then the parent container has closed self._student_containers_for_job[job_id].remove(container_id) killed = await self._timeout_watcher.was_killed(container_id) if container_id in self._containers_killed: killed = self._containers_killed[container_id] del self._containers_killed[container_id] if killed == "timeout": retval = 253 elif killed == "overflow": retval = 252 try: await self._write_to_container_stdin(write_stream, {"type": "run_student_retval", "retval": retval, "socket_id": socket_id}) except asyncio.CancelledError: raise except: pass # parent container closed # Do not forget to remove the container try: await self._docker.remove_container(container_id) except asyncio.CancelledError: raise except: pass # ignore except asyncio.CancelledError: raise except: self._logger.exception("Exception in handle_student_job_closing")
python
async def handle_student_job_closing(self, container_id, retval): """ Handle a closing student container. Do some cleaning, verify memory limits, timeouts, ... and returns data to the associated grading container """ 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 asyncio.CancelledError: raise except: self._logger.warning("Student container %s that has finished(p1) was not launched by this agent", str(container_id), exc_info=True) return # Delete remaining student containers if job_id in self._student_containers_for_job: # if it does not exists, then the parent container has closed self._student_containers_for_job[job_id].remove(container_id) killed = await self._timeout_watcher.was_killed(container_id) if container_id in self._containers_killed: killed = self._containers_killed[container_id] del self._containers_killed[container_id] if killed == "timeout": retval = 253 elif killed == "overflow": retval = 252 try: await self._write_to_container_stdin(write_stream, {"type": "run_student_retval", "retval": retval, "socket_id": socket_id}) except asyncio.CancelledError: raise except: pass # parent container closed # Do not forget to remove the container try: await self._docker.remove_container(container_id) except asyncio.CancelledError: raise except: pass # ignore except asyncio.CancelledError: raise except: self._logger.exception("Exception in handle_student_job_closing")
[ "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", ...
Handle a closing student container. Do some cleaning, verify memory limits, timeouts, ... and returns data to the associated grading container
[ "Handle", "a", "closing", "student", "container", ".", "Do", "some", "cleaning", "verify", "memory", "limits", "timeouts", "...", "and", "returns", "data", "to", "the", "associated", "grading", "container" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/docker_agent/__init__.py#L452-L499
train
229,873
UCL-INGI/INGInious
inginious/agent/docker_agent/__init__.py
DockerAgent.kill_job
async def kill_job(self, message: BackendKillJob): """ Handles `kill` messages. Kill things. """ 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.warning("Cannot kill container for job %s because it is not running", str(message.job_id)) except asyncio.CancelledError: raise except: self._logger.exception("Exception in handle_kill_job")
python
async def kill_job(self, message: BackendKillJob): """ Handles `kill` messages. Kill things. """ 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.warning("Cannot kill container for job %s because it is not running", str(message.job_id)) except asyncio.CancelledError: raise except: self._logger.exception("Exception in handle_kill_job")
[ "async", "def", "kill_job", "(", "self", ",", "message", ":", "BackendKillJob", ")", ":", "try", ":", "if", "message", ".", "job_id", "in", "self", ".", "_container_for_job", ":", "self", ".", "_containers_killed", "[", "self", ".", "_container_for_job", "["...
Handles `kill` messages. Kill things.
[ "Handles", "kill", "messages", ".", "Kill", "things", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/docker_agent/__init__.py#L629-L640
train
229,874
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/aggregation_edit.py
CourseEditAggregation.get_user_lists
def get_user_lists(self, course, aggregationid=''): """ Get the available student and tutor lists for aggregation edition""" tutor_list = course.get_staff() # Determine student list and if they are grouped student_list = list(self.database.aggregations.aggregate([ {"$match": {"courseid": course.get_id()}}, {"$unwind": "$students"}, {"$project": { "classroom": "$_id", "students": 1, "grouped": { "$anyElementTrue": { "$map": { "input": "$groups.students", "as": "group", "in": { "$anyElementTrue": { "$map": { "input": "$$group", "as": "groupmember", "in": {"$eq": ["$$groupmember", "$students"]} } } } } } } }} ])) student_list = dict([(student["students"], student) for student in student_list]) users_info = self.user_manager.get_users_info(list(student_list.keys()) + tutor_list) if aggregationid: # Order the non-registered students other_students = [student_list[entry]['students'] for entry in student_list.keys() if not student_list[entry]['classroom'] == ObjectId(aggregationid)] other_students = sorted(other_students, key=lambda val: (("0"+users_info[val][0]) if users_info[val] else ("1"+val))) return student_list, tutor_list, other_students, users_info else: return student_list, tutor_list, users_info
python
def get_user_lists(self, course, aggregationid=''): """ Get the available student and tutor lists for aggregation edition""" tutor_list = course.get_staff() # Determine student list and if they are grouped student_list = list(self.database.aggregations.aggregate([ {"$match": {"courseid": course.get_id()}}, {"$unwind": "$students"}, {"$project": { "classroom": "$_id", "students": 1, "grouped": { "$anyElementTrue": { "$map": { "input": "$groups.students", "as": "group", "in": { "$anyElementTrue": { "$map": { "input": "$$group", "as": "groupmember", "in": {"$eq": ["$$groupmember", "$students"]} } } } } } } }} ])) student_list = dict([(student["students"], student) for student in student_list]) users_info = self.user_manager.get_users_info(list(student_list.keys()) + tutor_list) if aggregationid: # Order the non-registered students other_students = [student_list[entry]['students'] for entry in student_list.keys() if not student_list[entry]['classroom'] == ObjectId(aggregationid)] other_students = sorted(other_students, key=lambda val: (("0"+users_info[val][0]) if users_info[val] else ("1"+val))) return student_list, tutor_list, other_students, users_info else: return student_list, tutor_list, users_info
[ "def", "get_user_lists", "(", "self", ",", "course", ",", "aggregationid", "=", "''", ")", ":", "tutor_list", "=", "course", ".", "get_staff", "(", ")", "# Determine student list and if they are grouped", "student_list", "=", "list", "(", "self", ".", "database", ...
Get the available student and tutor lists for aggregation edition
[ "Get", "the", "available", "student", "and", "tutor", "lists", "for", "aggregation", "edition" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/aggregation_edit.py#L21-L63
train
229,875
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/aggregation_edit.py
CourseEditAggregation.update_aggregation
def update_aggregation(self, course, aggregationid, new_data): """ Update aggregation and returns a list of errored students""" student_list = self.user_manager.get_course_registered_users(course, False) # If aggregation is new if aggregationid == 'None': # Remove _id for correct insertion del new_data['_id'] new_data["courseid"] = course.get_id() # Insert the new aggregation result = self.database.aggregations.insert_one(new_data) # Retrieve new aggregation id aggregationid = result.inserted_id new_data['_id'] = result.inserted_id aggregation = new_data else: aggregation = self.database.aggregations.find_one({"_id": ObjectId(aggregationid), "courseid": course.get_id()}) # Check tutors new_data["tutors"] = [tutor for tutor in new_data["tutors"] if tutor in course.get_staff()] students, groups, errored_students = [], [], [] # Check the students for student in new_data["students"]: if student in student_list: # Remove user from the other aggregation self.database.aggregations.find_one_and_update({"courseid": course.get_id(), "groups.students": student}, {"$pull": {"groups.$.students": student, "students": student}}) self.database.aggregations.find_one_and_update({"courseid": course.get_id(), "students": student}, {"$pull": {"students": student}}) students.append(student) else: # Check if user can be registered user_info = self.user_manager.get_user_info(student) if user_info is None or student in aggregation["tutors"]: errored_students.append(student) else: students.append(student) removed_students = [student for student in aggregation["students"] if student not in new_data["students"]] self.database.aggregations.find_one_and_update({"courseid": course.get_id(), "default": True}, {"$push": {"students": {"$each": removed_students}}}) new_data["students"] = students # Check the groups for group in new_data["groups"]: group["students"] = [student for student in group["students"] if student in new_data["students"]] if len(group["students"]) <= group["size"]: groups.append(group) new_data["groups"] = groups # Check for default aggregation if new_data['default']: self.database.aggregations.find_one_and_update({"courseid": course.get_id(), "default": True}, {"$set": {"default": False}}) aggregation = self.database.aggregations.find_one_and_update( {"_id": ObjectId(aggregationid)}, {"$set": {"description": new_data["description"], "students": students, "tutors": new_data["tutors"], "groups": groups, "default": new_data['default']}}, return_document=ReturnDocument.AFTER) return aggregation, errored_students
python
def update_aggregation(self, course, aggregationid, new_data): """ Update aggregation and returns a list of errored students""" student_list = self.user_manager.get_course_registered_users(course, False) # If aggregation is new if aggregationid == 'None': # Remove _id for correct insertion del new_data['_id'] new_data["courseid"] = course.get_id() # Insert the new aggregation result = self.database.aggregations.insert_one(new_data) # Retrieve new aggregation id aggregationid = result.inserted_id new_data['_id'] = result.inserted_id aggregation = new_data else: aggregation = self.database.aggregations.find_one({"_id": ObjectId(aggregationid), "courseid": course.get_id()}) # Check tutors new_data["tutors"] = [tutor for tutor in new_data["tutors"] if tutor in course.get_staff()] students, groups, errored_students = [], [], [] # Check the students for student in new_data["students"]: if student in student_list: # Remove user from the other aggregation self.database.aggregations.find_one_and_update({"courseid": course.get_id(), "groups.students": student}, {"$pull": {"groups.$.students": student, "students": student}}) self.database.aggregations.find_one_and_update({"courseid": course.get_id(), "students": student}, {"$pull": {"students": student}}) students.append(student) else: # Check if user can be registered user_info = self.user_manager.get_user_info(student) if user_info is None or student in aggregation["tutors"]: errored_students.append(student) else: students.append(student) removed_students = [student for student in aggregation["students"] if student not in new_data["students"]] self.database.aggregations.find_one_and_update({"courseid": course.get_id(), "default": True}, {"$push": {"students": {"$each": removed_students}}}) new_data["students"] = students # Check the groups for group in new_data["groups"]: group["students"] = [student for student in group["students"] if student in new_data["students"]] if len(group["students"]) <= group["size"]: groups.append(group) new_data["groups"] = groups # Check for default aggregation if new_data['default']: self.database.aggregations.find_one_and_update({"courseid": course.get_id(), "default": True}, {"$set": {"default": False}}) aggregation = self.database.aggregations.find_one_and_update( {"_id": ObjectId(aggregationid)}, {"$set": {"description": new_data["description"], "students": students, "tutors": new_data["tutors"], "groups": groups, "default": new_data['default']}}, return_document=ReturnDocument.AFTER) return aggregation, errored_students
[ "def", "update_aggregation", "(", "self", ",", "course", ",", "aggregationid", ",", "new_data", ")", ":", "student_list", "=", "self", ".", "user_manager", ".", "get_course_registered_users", "(", "course", ",", "False", ")", "# If aggregation is new", "if", "aggr...
Update aggregation and returns a list of errored students
[ "Update", "aggregation", "and", "returns", "a", "list", "of", "errored", "students" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/aggregation_edit.py#L65-L132
train
229,876
UCL-INGI/INGInious
inginious/frontend/pages/mycourses.py
MyCoursesPage.POST_AUTH
def POST_AUTH(self): # pylint: disable=arguments-differ """ Parse course registration or course creation and display the course list page """ username = self.user_manager.session_username() user_info = self.database.users.find_one({"username": username}) user_input = web.input() success = None # Handle registration to a course if "register_courseid" in user_input and user_input["register_courseid"] != "": try: course = self.course_factory.get_course(user_input["register_courseid"]) if not course.is_registration_possible(user_info): success = False else: success = self.user_manager.course_register_user(course, username, user_input.get("register_password", None)) except: success = False elif "new_courseid" in user_input and self.user_manager.user_is_superadmin(): try: courseid = user_input["new_courseid"] self.course_factory.create_course(courseid, {"name": courseid, "accessible": False}) success = True except: success = False return self.show_page(success)
python
def POST_AUTH(self): # pylint: disable=arguments-differ """ Parse course registration or course creation and display the course list page """ username = self.user_manager.session_username() user_info = self.database.users.find_one({"username": username}) user_input = web.input() success = None # Handle registration to a course if "register_courseid" in user_input and user_input["register_courseid"] != "": try: course = self.course_factory.get_course(user_input["register_courseid"]) if not course.is_registration_possible(user_info): success = False else: success = self.user_manager.course_register_user(course, username, user_input.get("register_password", None)) except: success = False elif "new_courseid" in user_input and self.user_manager.user_is_superadmin(): try: courseid = user_input["new_courseid"] self.course_factory.create_course(courseid, {"name": courseid, "accessible": False}) success = True except: success = False return self.show_page(success)
[ "def", "POST_AUTH", "(", "self", ")", ":", "# pylint: disable=arguments-differ", "username", "=", "self", ".", "user_manager", ".", "session_username", "(", ")", "user_info", "=", "self", ".", "database", ".", "users", ".", "find_one", "(", "{", "\"username\"", ...
Parse course registration or course creation and display the course list page
[ "Parse", "course", "registration", "or", "course", "creation", "and", "display", "the", "course", "list", "page" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/mycourses.py#L21-L47
train
229,877
UCL-INGI/INGInious
inginious/frontend/arch_helper.py
_restart_on_cancel
async def _restart_on_cancel(logger, agent): """ Restarts an agent when it is cancelled """ while True: try: await agent.run() except asyncio.CancelledError: logger.exception("Restarting agent") pass
python
async def _restart_on_cancel(logger, agent): """ Restarts an agent when it is cancelled """ while True: try: await agent.run() except asyncio.CancelledError: logger.exception("Restarting agent") pass
[ "async", "def", "_restart_on_cancel", "(", "logger", ",", "agent", ")", ":", "while", "True", ":", "try", ":", "await", "agent", ".", "run", "(", ")", "except", "asyncio", ".", "CancelledError", ":", "logger", ".", "exception", "(", "\"Restarting agent\"", ...
Restarts an agent when it is cancelled
[ "Restarts", "an", "agent", "when", "it", "is", "cancelled" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/arch_helper.py#L49-L56
train
229,878
UCL-INGI/INGInious
inginious/frontend/pages/utils.py
INGIniousAuthPage.GET
def GET(self, *args, **kwargs): """ Checks if user is authenticated and calls GET_AUTH or performs logout. Otherwise, returns the login template. """ 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 not None: #lti session self.user_manager.disconnect_user() return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods(), False) return self.GET_AUTH(*args, **kwargs) else: return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods(), False)
python
def GET(self, *args, **kwargs): """ Checks if user is authenticated and calls GET_AUTH or performs logout. Otherwise, returns the login template. """ 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 not None: #lti session self.user_manager.disconnect_user() return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods(), False) return self.GET_AUTH(*args, **kwargs) else: return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods(), False)
[ "def", "GET", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "user_manager", ".", "session_logged_in", "(", ")", ":", "if", "not", "self", ".", "user_manager", ".", "session_username", "(", ")", "and", "not", "se...
Checks if user is authenticated and calls GET_AUTH or performs logout. Otherwise, returns the login template.
[ "Checks", "if", "user", "is", "authenticated", "and", "calls", "GET_AUTH", "or", "performs", "logout", ".", "Otherwise", "returns", "the", "login", "template", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/utils.py#L135-L150
train
229,879
UCL-INGI/INGInious
inginious/frontend/static_middleware.py
StaticMiddleware.normpath
def normpath(self, path): """ Normalize the path """ path2 = posixpath.normpath(urllib.parse.unquote(path)) if path.endswith("/"): path2 += "/" return path2
python
def normpath(self, path): """ Normalize the path """ path2 = posixpath.normpath(urllib.parse.unquote(path)) if path.endswith("/"): path2 += "/" return path2
[ "def", "normpath", "(", "self", ",", "path", ")", ":", "path2", "=", "posixpath", ".", "normpath", "(", "urllib", ".", "parse", ".", "unquote", "(", "path", ")", ")", "if", "path", ".", "endswith", "(", "\"/\"", ")", ":", "path2", "+=", "\"/\"", "r...
Normalize the path
[ "Normalize", "the", "path" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/static_middleware.py#L66-L71
train
229,880
UCL-INGI/INGInious
inginious/frontend/pages/api/submissions.py
_get_submissions
def _get_submissions(course_factory, submission_manager, user_manager, translations, courseid, taskid, with_input, submissionid=None): """ Helper for the GET methods of the two following classes """ try: course = course_factory.get_course(courseid) except: raise APINotFound("Course not found") if not user_manager.course_is_open_to_user(course, lti=False): raise APIForbidden("You are not registered to this course") try: task = course.get_task(taskid) except: raise APINotFound("Task not found") if submissionid is None: submissions = submission_manager.get_user_submissions(task) else: try: submissions = [submission_manager.get_submission(submissionid)] except: raise APINotFound("Submission not found") if submissions[0]["taskid"] != task.get_id() or submissions[0]["courseid"] != course.get_id(): raise APINotFound("Submission not found") output = [] for submission in submissions: submission = submission_manager.get_feedback_from_submission( submission, show_everything=user_manager.has_staff_rights_on_course(course, user_manager.session_username()), translation=translations.get(user_manager.session_language(), gettext.NullTranslations()) ) data = { "id": str(submission["_id"]), "submitted_on": str(submission["submitted_on"]), "status": submission["status"] } if with_input: data["input"] = submission_manager.get_input_from_submission(submission, True) # base64 encode file to allow JSON encoding for d in data["input"]: if isinstance(d, dict) and d.keys() == {"filename", "value"}: d["value"] = base64.b64encode(d["value"]).decode("utf8") if submission["status"] == "done": data["grade"] = submission.get("grade", 0) data["result"] = submission.get("result", "crash") data["feedback"] = submission.get("text", "") data["problems_feedback"] = submission.get("problems", {}) output.append(data) return 200, output
python
def _get_submissions(course_factory, submission_manager, user_manager, translations, courseid, taskid, with_input, submissionid=None): """ Helper for the GET methods of the two following classes """ try: course = course_factory.get_course(courseid) except: raise APINotFound("Course not found") if not user_manager.course_is_open_to_user(course, lti=False): raise APIForbidden("You are not registered to this course") try: task = course.get_task(taskid) except: raise APINotFound("Task not found") if submissionid is None: submissions = submission_manager.get_user_submissions(task) else: try: submissions = [submission_manager.get_submission(submissionid)] except: raise APINotFound("Submission not found") if submissions[0]["taskid"] != task.get_id() or submissions[0]["courseid"] != course.get_id(): raise APINotFound("Submission not found") output = [] for submission in submissions: submission = submission_manager.get_feedback_from_submission( submission, show_everything=user_manager.has_staff_rights_on_course(course, user_manager.session_username()), translation=translations.get(user_manager.session_language(), gettext.NullTranslations()) ) data = { "id": str(submission["_id"]), "submitted_on": str(submission["submitted_on"]), "status": submission["status"] } if with_input: data["input"] = submission_manager.get_input_from_submission(submission, True) # base64 encode file to allow JSON encoding for d in data["input"]: if isinstance(d, dict) and d.keys() == {"filename", "value"}: d["value"] = base64.b64encode(d["value"]).decode("utf8") if submission["status"] == "done": data["grade"] = submission.get("grade", 0) data["result"] = submission.get("result", "crash") data["feedback"] = submission.get("text", "") data["problems_feedback"] = submission.get("problems", {}) output.append(data) return 200, output
[ "def", "_get_submissions", "(", "course_factory", ",", "submission_manager", ",", "user_manager", ",", "translations", ",", "courseid", ",", "taskid", ",", "with_input", ",", "submissionid", "=", "None", ")", ":", "try", ":", "course", "=", "course_factory", "."...
Helper for the GET methods of the two following classes
[ "Helper", "for", "the", "GET", "methods", "of", "the", "two", "following", "classes" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/submissions.py#L15-L73
train
229,881
UCL-INGI/INGInious
inginious/frontend/pages/api/submissions.py
APISubmissionSingle.API_GET
def API_GET(self, courseid, taskid, submissionid): # pylint: disable=arguments-differ """ List all the submissions that the connected user made. Returns list of the form :: [ { "id": "submission_id1", "submitted_on": "date", "status" : "done", #can be "done", "waiting", "error" (execution status of the task). "grade": 0.0, "input": {}, #the input data. File are base64 encoded. "result" : "success" #only if status=done. Result of the execution. "feedback": "" #only if status=done. the HTML global feedback for the task "problems_feedback": #only if status=done. HTML feedback per problem. Some pid may be absent. { "pid1": "feedback1", #... } } #... ] If you use the endpoint /api/v0/courses/the_course_id/tasks/the_task_id/submissions/submissionid, this dict will contain one entry or the page will return 404 Not Found. """ 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)
python
def API_GET(self, courseid, taskid, submissionid): # pylint: disable=arguments-differ """ List all the submissions that the connected user made. Returns list of the form :: [ { "id": "submission_id1", "submitted_on": "date", "status" : "done", #can be "done", "waiting", "error" (execution status of the task). "grade": 0.0, "input": {}, #the input data. File are base64 encoded. "result" : "success" #only if status=done. Result of the execution. "feedback": "" #only if status=done. the HTML global feedback for the task "problems_feedback": #only if status=done. HTML feedback per problem. Some pid may be absent. { "pid1": "feedback1", #... } } #... ] If you use the endpoint /api/v0/courses/the_course_id/tasks/the_task_id/submissions/submissionid, this dict will contain one entry or the page will return 404 Not Found. """ 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)
[ "def", "API_GET", "(", "self", ",", "courseid", ",", "taskid", ",", "submissionid", ")", ":", "# pylint: disable=arguments-differ", "with_input", "=", "\"input\"", "in", "web", ".", "input", "(", ")", "return", "_get_submissions", "(", "self", ".", "course_facto...
List all the submissions that the connected user made. Returns list of the form :: [ { "id": "submission_id1", "submitted_on": "date", "status" : "done", #can be "done", "waiting", "error" (execution status of the task). "grade": 0.0, "input": {}, #the input data. File are base64 encoded. "result" : "success" #only if status=done. Result of the execution. "feedback": "" #only if status=done. the HTML global feedback for the task "problems_feedback": #only if status=done. HTML feedback per problem. Some pid may be absent. { "pid1": "feedback1", #... } } #... ] If you use the endpoint /api/v0/courses/the_course_id/tasks/the_task_id/submissions/submissionid, this dict will contain one entry or the page will return 404 Not Found.
[ "List", "all", "the", "submissions", "that", "the", "connected", "user", "made", ".", "Returns", "list", "of", "the", "form" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/submissions.py#L81-L110
train
229,882
UCL-INGI/INGInious
inginious/frontend/courses.py
WebAppCourse.is_registration_possible
def is_registration_possible(self, user_info): """ Returns true if users can register for this course """ return self.get_accessibility().is_open() and self._registration.is_open() and self.is_user_accepted_by_access_control(user_info)
python
def is_registration_possible(self, user_info): """ Returns true if users can register for this course """ return self.get_accessibility().is_open() and self._registration.is_open() and self.is_user_accepted_by_access_control(user_info)
[ "def", "is_registration_possible", "(", "self", ",", "user_info", ")", ":", "return", "self", ".", "get_accessibility", "(", ")", ".", "is_open", "(", ")", "and", "self", ".", "_registration", ".", "is_open", "(", ")", "and", "self", ".", "is_user_accepted_b...
Returns true if users can register for this course
[ "Returns", "true", "if", "users", "can", "register", "for", "this", "course" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/courses.py#L88-L90
train
229,883
UCL-INGI/INGInious
inginious/frontend/courses.py
WebAppCourse.get_accessibility
def get_accessibility(self, plugin_override=True): """ Return the AccessibleTime object associated with the accessibility of this course """ 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
python
def get_accessibility(self, plugin_override=True): """ Return the AccessibleTime object associated with the accessibility of this course """ 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
[ "def", "get_accessibility", "(", "self", ",", "plugin_override", "=", "True", ")", ":", "vals", "=", "self", ".", "_hook_manager", ".", "call_hook", "(", "'course_accessibility'", ",", "course", "=", "self", ",", "default", "=", "self", ".", "_accessible", "...
Return the AccessibleTime object associated with the accessibility of this course
[ "Return", "the", "AccessibleTime", "object", "associated", "with", "the", "accessibility", "of", "this", "course" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/courses.py#L100-L103
train
229,884
UCL-INGI/INGInious
inginious/frontend/courses.py
WebAppCourse.is_user_accepted_by_access_control
def is_user_accepted_by_access_control(self, user_info): """ Returns True if the user is allowed by the ACL """ 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_method() == "email": return user_info["email"] in self.get_access_control_list() elif self.get_access_control_method() == "binding": return set(user_info["bindings"].keys()).intersection(set(self.get_access_control_list())) return False
python
def is_user_accepted_by_access_control(self, user_info): """ Returns True if the user is allowed by the ACL """ 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_method() == "email": return user_info["email"] in self.get_access_control_list() elif self.get_access_control_method() == "binding": return set(user_info["bindings"].keys()).intersection(set(self.get_access_control_list())) return False
[ "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_a...
Returns True if the user is allowed by the ACL
[ "Returns", "True", "if", "the", "user", "is", "allowed", "by", "the", "ACL" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/courses.py#L140-L152
train
229,885
UCL-INGI/INGInious
inginious/frontend/courses.py
WebAppCourse.allow_unregister
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
python
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
[ "def", "allow_unregister", "(", "self", ",", "plugin_override", "=", "True", ")", ":", "vals", "=", "self", ".", "_hook_manager", ".", "call_hook", "(", "'course_allow_unregister'", ",", "course", "=", "self", ",", "default", "=", "self", ".", "_allow_unregist...
Returns True if students can unregister from course
[ "Returns", "True", "if", "students", "can", "unregister", "from", "course" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/courses.py#L157-L160
train
229,886
UCL-INGI/INGInious
inginious/frontend/courses.py
WebAppCourse.get_name
def get_name(self, language): """ Return the name of this course """ return self.gettext(language, self._name) if self._name else ""
python
def get_name(self, language): """ Return the name of this course """ return self.gettext(language, self._name) if self._name else ""
[ "def", "get_name", "(", "self", ",", "language", ")", ":", "return", "self", ".", "gettext", "(", "language", ",", "self", ".", "_name", ")", "if", "self", ".", "_name", "else", "\"\"" ]
Return the name of this course
[ "Return", "the", "name", "of", "this", "course" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/courses.py#L162-L164
train
229,887
UCL-INGI/INGInious
inginious/frontend/courses.py
WebAppCourse.get_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()))
python
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()))
[ "def", "get_description", "(", "self", ",", "language", ")", ":", "description", "=", "self", ".", "gettext", "(", "language", ",", "self", ".", "_description", ")", "if", "self", ".", "_description", "else", "''", "return", "ParsableText", "(", "description...
Returns the course description
[ "Returns", "the", "course", "description" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/courses.py#L166-L169
train
229,888
UCL-INGI/INGInious
inginious/frontend/courses.py
WebAppCourse.get_all_tags_names_as_list
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_tags_cache_list_admin[language] #Cache hit else: if self._all_tags_cache_list != {} and language in self._all_tags_cache_list: return self._all_tags_cache_list[language] #Cache hit #Cache miss, computes everything s_stud = set() s_admin = set() (common, _, org) = self.get_all_tags() for tag in common + org: # Is tag_name_with_translation correct by doing that like that ? tag_name_with_translation = self.gettext(language, tag.get_name()) if tag.get_name() else "" s_admin.add(tag_name_with_translation) if tag.is_visible_for_student(): s_stud.add(tag_name_with_translation) self._all_tags_cache_list_admin[language] = natsorted(s_admin, key=lambda y: y.lower()) self._all_tags_cache_list[language] = natsorted(s_stud, key=lambda y: y.lower()) if admin: return self._all_tags_cache_list_admin[language] return self._all_tags_cache_list[language]
python
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_tags_cache_list_admin[language] #Cache hit else: if self._all_tags_cache_list != {} and language in self._all_tags_cache_list: return self._all_tags_cache_list[language] #Cache hit #Cache miss, computes everything s_stud = set() s_admin = set() (common, _, org) = self.get_all_tags() for tag in common + org: # Is tag_name_with_translation correct by doing that like that ? tag_name_with_translation = self.gettext(language, tag.get_name()) if tag.get_name() else "" s_admin.add(tag_name_with_translation) if tag.is_visible_for_student(): s_stud.add(tag_name_with_translation) self._all_tags_cache_list_admin[language] = natsorted(s_admin, key=lambda y: y.lower()) self._all_tags_cache_list[language] = natsorted(s_stud, key=lambda y: y.lower()) if admin: return self._all_tags_cache_list_admin[language] return self._all_tags_cache_list[language]
[ "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_cach...
Computes and cache two list containing all tags name sorted by natural order on name
[ "Computes", "and", "cache", "two", "list", "containing", "all", "tags", "name", "sorted", "by", "natural", "order", "on", "name" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/courses.py#L200-L225
train
229,889
UCL-INGI/INGInious
inginious/frontend/courses.py
WebAppCourse.update_all_tags_cache
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_names_as_list() self.get_organisational_tags_to_task()
python
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_names_as_list() self.get_organisational_tags_to_task()
[ "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", "=", "{...
Force the cache refreshing
[ "Force", "the", "cache", "refreshing" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/courses.py#L243-L253
train
229,890
UCL-INGI/INGInious
inginious/frontend/webdav.py
get_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 RuntimeError("WebDav access is only supported if INGInious is using a local filesystem to access tasks") fs_provider = LocalFSProvider(config["tasks_directory"]) course_factory, task_factory = create_factories(fs_provider, {}, None, WebAppCourse, WebAppTask) user_manager = UserManager(MongoStore(database, 'sessions'), database, config.get('superadmins', [])) config = dict(wsgidav_app.DEFAULT_CONFIG) config["provider_mapping"] = {"/": INGIniousFilesystemProvider(course_factory, task_factory)} config["domaincontroller"] = INGIniousDAVDomainController(user_manager, course_factory) config["verbose"] = 0 app = wsgidav_app.WsgiDAVApp(config) return app
python
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 RuntimeError("WebDav access is only supported if INGInious is using a local filesystem to access tasks") fs_provider = LocalFSProvider(config["tasks_directory"]) course_factory, task_factory = create_factories(fs_provider, {}, None, WebAppCourse, WebAppTask) user_manager = UserManager(MongoStore(database, 'sessions'), database, config.get('superadmins', [])) config = dict(wsgidav_app.DEFAULT_CONFIG) config["provider_mapping"] = {"/": INGIniousFilesystemProvider(course_factory, task_factory)} config["domaincontroller"] = INGIniousDAVDomainController(user_manager, course_factory) config["verbose"] = 0 app = wsgidav_app.WsgiDAVApp(config) return app
[ "def", "get_app", "(", "config", ")", ":", "mongo_client", "=", "MongoClient", "(", "host", "=", "config", ".", "get", "(", "'mongo_opt'", ",", "{", "}", ")", ".", "get", "(", "'host'", ",", "'localhost'", ")", ")", "database", "=", "mongo_client", "["...
Init the webdav app
[ "Init", "the", "webdav", "app" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/webdav.py#L120-L140
train
229,891
UCL-INGI/INGInious
inginious/frontend/webdav.py
INGIniousDAVDomainController.getDomainRealm
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("/") return parts[0]
python
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("/") return parts[0]
[ "def", "getDomainRealm", "(", "self", ",", "inputURL", ",", "environ", ")", ":", "# we don't get the realm here, its already been resolved in", "# request_resolver", "if", "inputURL", ".", "startswith", "(", "\"/\"", ")", ":", "inputURL", "=", "inputURL", "[", "1", ...
Resolve a relative url to the appropriate realm name.
[ "Resolve", "a", "relative", "url", "to", "the", "appropriate", "realm", "name", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/webdav.py#L30-L37
train
229,892
UCL-INGI/INGInious
inginious/frontend/webdav.py
INGIniousDAVDomainController.isRealmUser
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) return ok except: return False
python
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) return ok except: return False
[ "def", "isRealmUser", "(", "self", ",", "realmname", ",", "username", ",", "environ", ")", ":", "try", ":", "course", "=", "self", ".", "course_factory", ".", "get_course", "(", "realmname", ")", "ok", "=", "self", ".", "user_manager", ".", "has_admin_righ...
Returns True if this username is valid for the realm, False otherwise.
[ "Returns", "True", "if", "this", "username", "is", "valid", "for", "the", "realm", "False", "otherwise", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/webdav.py#L44-L51
train
229,893
UCL-INGI/INGInious
inginious/frontend/webdav.py
INGIniousDAVDomainController.getRealmUserPassword
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)
python
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)
[ "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. Used for digest authentication.
[ "Return", "the", "password", "for", "the", "given", "username", "for", "the", "realm", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/webdav.py#L53-L58
train
229,894
UCL-INGI/INGInious
inginious/frontend/webdav.py
INGIniousFilesystemProvider.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): return FolderResource(path, environ, fp) return FileResource(path, environ, fp)
python
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): return FolderResource(path, environ, fp) return FileResource(path, environ, fp)
[ "def", "getResourceInst", "(", "self", ",", "path", ",", "environ", ")", ":", "self", ".", "_count_getResourceInst", "+=", "1", "fp", "=", "self", ".", "_locToFilePath", "(", "path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "fp", ")", ...
Return info dictionary for path. See DAVProvider.getResourceInst()
[ "Return", "info", "dictionary", "for", "path", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/webdav.py#L105-L117
train
229,895
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/task_edit.py
CourseEditTask.contains_is_html
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): return True return False
python
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): return True return False
[ "def", "contains_is_html", "(", "cls", ",", "data", ")", ":", "for", "key", ",", "val", "in", "data", ".", "items", "(", ")", ":", "if", "isinstance", "(", "key", ",", "str", ")", "and", "key", ".", "endswith", "(", "\"IsHTML\"", ")", ":", "return"...
Detect if the problem has at least one "xyzIsHTML" key
[ "Detect", "if", "the", "problem", "has", "at", "least", "one", "xyzIsHTML", "key" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/task_edit.py#L73-L80
train
229,896
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/task_edit.py
CourseEditTask.parse_problem
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)
python
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)
[ "def", "parse_problem", "(", "self", ",", "problem_content", ")", ":", "del", "problem_content", "[", "\"@order\"", "]", "return", "self", ".", "task_factory", ".", "get_problem_types", "(", ")", ".", "get", "(", "problem_content", "[", "\"type\"", "]", ")", ...
Parses a problem, modifying some data
[ "Parses", "a", "problem", "modifying", "some", "data" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/task_edit.py#L113-L116
train
229,897
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/task_edit.py
CourseEditTask.wipe_task
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 type(submission[key]) == bson.objectid.ObjectId: self.submission_manager.get_gridfs().delete(submission[key]) self.database.aggregations.remove({"courseid": courseid, "taskid": taskid}) self.database.user_tasks.remove({"courseid": courseid, "taskid": taskid}) self.database.submissions.remove({"courseid": courseid, "taskid": taskid}) self._logger.info("Task %s/%s wiped.", courseid, taskid)
python
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 type(submission[key]) == bson.objectid.ObjectId: self.submission_manager.get_gridfs().delete(submission[key]) self.database.aggregations.remove({"courseid": courseid, "taskid": taskid}) self.database.user_tasks.remove({"courseid": courseid, "taskid": taskid}) self.database.submissions.remove({"courseid": courseid, "taskid": taskid}) self._logger.info("Task %s/%s wiped.", courseid, taskid)
[ "def", "wipe_task", "(", "self", ",", "courseid", ",", "taskid", ")", ":", "submissions", "=", "self", ".", "database", ".", "submissions", ".", "find", "(", "{", "\"courseid\"", ":", "courseid", ",", "\"taskid\"", ":", "taskid", "}", ")", "for", "submis...
Wipe the data associated to the taskid from DB
[ "Wipe", "the", "data", "associated", "to", "the", "taskid", "from", "DB" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/task_edit.py#L118-L130
train
229,898
UCL-INGI/INGInious
inginious/common/hook_manager.py
HookManager._exception_free_callback
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) return None
python
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) return None
[ "def", "_exception_free_callback", "(", "self", ",", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "callback", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", ":", "self", ".", "_logger", ...
A wrapper that remove all exceptions raised from hooks
[ "A", "wrapper", "that", "remove", "all", "exceptions", "raised", "from", "hooks" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/hook_manager.py#L18-L24
train
229,899