INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
DELETE request | def DELETE(self, *args, **kwargs):
""" DELETE request """
return self._handle_api(self.API_DELETE, args, kwargs) |
PATCH request | def PATCH(self, *args, **kwargs):
""" PATCH request """
return self._handle_api(self.API_PATCH, args, kwargs) |
HEAD request | def HEAD(self, *args, **kwargs):
""" HEAD request """
return self._handle_api(self.API_HEAD, args, kwargs) |
OPTIONS request | def OPTIONS(self, *args, **kwargs):
""" OPTIONS request """
return self._handle_api(self.API_OPTIONS, args, kwargs) |
Handle call to subclasses and convert the output to an appropriate value | def _handle_api(self, handler, handler_args, handler_kwargs):
""" Handle call to subclasses and convert the output to an appropriate value """
try:
status_code, return_value = handler(*handler_args, **handler_kwargs)
except APIError as error:
return error.send()
... |
Guess the method implemented by the subclass | def _guess_available_methods(self):
""" Guess the method implemented by the subclass"""
available_methods = []
for m in ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]:
self_method = getattr(type(self), "API_{}".format(m))
super_method = getattr(APIPage, "API... |
Verify that the user is authenticated | def _verify_authentication(self, handler, args, kwargs):
""" Verify that the user is authenticated """
if not self.user_manager.session_logged_in():
raise APIForbidden()
return handler(*args, **kwargs) |
Send the API Exception to the client | def send(self):
""" Send the API Exception to the client """
web.ctx.status = _convert_http_status(self.status_code)
return _api_convert_output(self.return_value) |
Callback called by Client when a job is done. Updates the submission in the database with the data returned after the completion of the
job | def _job_done_callback(self, submissionid, task, result, grade, problems, tests, custom, state, archive, stdout, stderr, newsub=True):
""" Callback called by Client when a job is done. Updates the submission in the database with the data returned after the completion of the
job """
submission = ... |
Called before any new submission is inserted into the database. Allows you to modify obj, the new document that will be inserted into the
database. Should be overridden in subclasses.
:param task: Task related to the submission
:param inputdata: input of the student
:param debug: True, ... | def _before_submission_insertion(self, task, inputdata, debug, obj):
"""
Called before any new submission is inserted into the database. Allows you to modify obj, the new document that will be inserted into the
database. Should be overridden in subclasses.
:param task: Task related to t... |
Called after any new submission is inserted into the database, but before starting the job. Should be overridden in subclasses.
:param task: Task related to the submission
:param inputdata: input of the student
:param debug: True, False or "ssh". See add_job.
... | def _after_submission_insertion(self, task, inputdata, debug, submission, submissionid):
"""
Called after any new submission is inserted into the database, but before starting the job. Should be overridden in subclasses.
:param task: Task related to the submission
... |
Replay a submission: add the same job in the queue, keeping submission id, submission date and input data
:param submission: Submission to replay
:param copy: If copy is true, the submission will be copied to admin submissions before replay
:param debug: If debug is true, more debug data will be... | def replay_job(self, task, submission, copy=False, debug=False):
"""
Replay a submission: add the same job in the queue, keeping submission id, submission date and input data
:param submission: Submission to replay
:param copy: If copy is true, the submission will be copied to admin subm... |
Get a submission from the database | def get_submission(self, submissionid, user_check=True):
""" Get a submission from the database """
sub = self._database.submissions.find_one({'_id': ObjectId(submissionid)})
if user_check and not self.user_is_submission_owner(sub):
return None
return sub |
Add a job in the queue and returns a submission id.
:param task: Task instance
:type task: inginious.frontend.tasks.WebAppTask
:param inputdata: the input as a dictionary
:type inputdata: dict
:param debug: If debug is true, more debug data will be saved
:type debug: boo... | def add_job(self, task, inputdata, debug=False):
"""
Add a job in the queue and returns a submission id.
:param task: Task instance
:type task: inginious.frontend.tasks.WebAppTask
:param inputdata: the input as a dictionary
:type inputdata: dict
:param debug: If ... |
Deletes exceeding submissions from the database, to keep the database relatively small | def _delete_exceeding_submissions(self, username, task, max_submissions_bound=-1):
""" Deletes exceeding submissions from the database, to keep the database relatively small """
if max_submissions_bound <= 0:
max_submissions = task.get_stored_submissions()
elif task.get_stored_submi... |
Get the input of a submission. If only_input is False, returns the full submissions with a dictionnary object at the key "input".
Else, returns only the dictionnary. | def get_input_from_submission(self, submission, only_input=False):
"""
Get the input of a submission. If only_input is False, returns the full submissions with a dictionnary object at the key "input".
Else, returns only the dictionnary.
"""
inp = bson.BSON.decode(self._gr... |
Get the input of a submission. If only_input is False, returns the full submissions with a dictionnary object at the key "input".
Else, returns only the dictionnary.
If show_everything is True, feedback normally hidden is shown. | def get_feedback_from_submission(self, submission, only_feedback=False, show_everything=False, translation=gettext.NullTranslations()):
"""
Get the input of a submission. If only_input is False, returns the full submissions with a dictionnary object at the key "input".
Else, returns only... |
Tells if a submission is running/in queue | def is_running(self, submissionid, user_check=True):
""" Tells if a submission is running/in queue """
submission = self.get_submission(submissionid, user_check)
return submission["status"] == "waiting" |
Tells if a submission is done and its result is available | def is_done(self, submissionid_or_submission, user_check=True):
""" Tells if a submission is done and its result is available """
# TODO: not a very nice way to avoid too many database call. Should be refactored.
if isinstance(submissionid_or_submission, dict):
submission = submissio... |
Attempt to kill the remote job associated with this submission id.
:param submissionid:
:param user_check: Check if the current user owns this submission
:return: True if the job was killed, False if an error occurred | def kill_running_submission(self, submissionid, user_check=True):
""" Attempt to kill the remote job associated with this submission id.
:param submissionid:
:param user_check: Check if the current user owns this submission
:return: True if the job was killed, False if an error occurred
... |
Returns true if the current user is the owner of this jobid, false else | def user_is_submission_owner(self, submission):
""" Returns true if the current user is the owner of this jobid, false else """
if not self._user_manager.session_logged_in():
raise Exception("A user must be logged in to verify if he owns a jobid")
return self._user_manager.session_u... |
Get all the user's submissions for a given task | def get_user_submissions(self, task):
""" Get all the user's submissions for a given task """
if not self._user_manager.session_logged_in():
raise Exception("A user must be logged in to get his submissions")
cursor = self._database.submissions.find({"username": self._user_manager.se... |
Get last submissions of a user | def get_user_last_submissions(self, limit=5, request=None):
""" Get last submissions of a user """
if request is None:
request = {}
request.update({"username": self._user_manager.session_username()})
# Before, submissions were first sorted by submission date, then grouped
... |
:param submissions: a list of submissions
:param sub_folders: possible values:
[]: put all submissions in /
['taskid']: put all submissions for each task in a different directory /taskid/
['username']: put all submissions for each user in a different directory /username/
... | def get_submission_archive(self, submissions, sub_folders, aggregations, archive_file=None):
"""
:param submissions: a list of submissions
:param sub_folders: possible values:
[]: put all submissions in /
['taskid']: put all submissions for each task in a different direct... |
Handles the creation of a remote ssh server | 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":... |
Returns a dictionnary of {"fs_name": fs_class}, for each usable FileSystemProvider | def get_filesystems_providers():
""" Returns a dictionnary of {"fs_name": fs_class}, for each usable FileSystemProvider"""
providers = {"local": LocalFSProvider}
plugged_providers = pkg_resources.iter_entry_points("inginious.filesystems")
for pp in plugged_providers:
providers[pp.name] = pp.load... |
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. | 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 fil... |
Given a partially configured argparse parser, containing all the wanted data BUT the filesystem, this function will configure the parser
to get the correct FS from the commandline, and return a tuple (args, filesystem_provider). | def get_args_and_filesystem(parser):
"""Given a partially configured argparse parser, containing all the wanted data BUT the filesystem, this function will configure the parser
to get the correct FS from the commandline, and return a tuple (args, filesystem_provider).
"""
filesystem_providers = get_f... |
Close all the running tasks watching for a container timeout. All references to
containers are removed: any attempt to was_killed after a call to clean() will return None. | async def clean(self):
""" Close all the running tasks watching for a container timeout. All references to
containers are removed: any attempt to was_killed after a call to clean() will return None.
"""
for x in self._running_asyncio_tasks:
x.cancel()
self._contai... |
This method has to be called *once, and only once* for each container registered in `register_container`.
:param container_id: the container id to check
:return: a string containing "timeout" if the container was killed. None if it was not (std format for container errors) | async def was_killed(self, container_id):
"""
This method has to be called *once, and only once* for each container registered in `register_container`.
:param container_id: the container id to check
:return: a string containing "timeout" if the container was killed. None if it was not (s... |
Check timeout with docker stats
:param container_id:
:param timeout: in seconds (cpu time) | async def _handle_container_timeout(self, container_id, timeout):
"""
Check timeout with docker stats
:param container_id:
:param timeout: in seconds (cpu time)
"""
try:
docker_stats = await self._docker_interface.get_stats(container_id)
source = A... |
Kills a container (should be called with loop.call_later(hard_timeout, ...)) and displays a message on the log
:param container_id:
:param hard_timeout:
:return: | async def _handle_container_hard_timeout(self, container_id, hard_timeout):
"""
Kills a container (should be called with loop.call_later(hard_timeout, ...)) and displays a message on the log
:param container_id:
:param hard_timeout:
:return:
"""
if container_id in... |
Kill a container, 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.... |
:param ignore_session: Ignore the cookieless session_id that should be put in the URL
:param force_cookieless: Force the cookieless session; the link will include the session_creator if needed. | def get_homepath(self, ignore_session=False, force_cookieless=False):
"""
:param ignore_session: Ignore the cookieless session_id that should be put in the URL
:param force_cookieless: Force the cookieless session; the link will include the session_creator if needed.
"""
if not i... |
Load the session from the store.
session_id can be:
- None: load from cookie
- '': create a new cookieless session_id
- a string which is the session_id to be used. | def load(self, session_id=None):
""" Load the session from the store.
session_id can be:
- None: load from cookie
- '': create a new cookieless session_id
- a string which is the session_id to be used.
"""
if session_id is None:
cookie_name = self._co... |
Generate a random id for session | def _generate_session_id(self):
"""Generate a random id for session"""
while True:
rand = os.urandom(16)
now = time.time()
secret_key = self._config.secret_key
session_id = hashlib.sha1(("%s%s%s%s" % (rand, now, utils.safestr(web.ctx.ip), secret_key)).enc... |
Cleanup the stored sessions | 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 |
Called when an expired session is atime | def expired(self):
"""Called when an expired session is atime"""
self._data["_killed"] = True
self.save()
raise SessionExpired(self._config.expired_message) |
Delete account from DB | 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,
... |
GET request | def GET_AUTH(self): # pylint: disable=arguments-differ
""" GET request """
userdata = self.database.users.find_one({"username": self.user_manager.session_username()})
if not userdata or not self.app.allow_deletion:
raise web.notfound()
return self.template_helper.get_rende... |
POST request | def POST_AUTH(self): # pylint: disable=arguments-differ
""" POST request """
userdata = self.database.users.find_one({"username": self.user_manager.session_username()})
if not userdata or not self.app.allow_deletion:
raise web.notfound()
msg = ""
error = False
... |
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()... | 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, t... |
Util to remove parsable text from a dict, recursively | 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_par... |
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": ""... | 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", ... |
Open existing input file | def load_input():
""" Open existing input file """
file = open(_input_file, 'r')
result = json.loads(file.read().strip('\0').strip())
file.close()
return result |
Returns the specified problem answer in the form
problem: problem id
Returns string, or bytes if a file is loaded | def get_input(problem):
"""" Returns the specified problem answer in the form
problem: problem id
Returns string, or bytes if a file is loaded
"""
input_data = load_input()
pbsplit = problem.split(":")
problem_input = input_data['input'][pbsplit[0]]
if isinstance(problem_input... |
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 | 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
"""
... |
Send a ClientGetQueue message to the backend, if one is not already sent | 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... |
Returns a function that is only callable once; any other call will do nothing | 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 |
Handles a BackendGetQueue containing a snapshot of the job queue | 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
... |
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 signatur... | 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:... |
Kills a running 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))) |
Display main course list page | def show_page(self):
""" Display main course list page """
username = self.user_manager.session_username()
user_info = self.database.users.find_one({"username": username})
all_courses = self.course_factory.get_all_courses()
# Display
open_courses = {courseid: course for... |
Generates rst codeblock for given text and language | 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 |
Generates rst raw block for given image filename and format | 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<im... |
Generates rst admonition block given a bootstrap alert css class, title, and text | 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():
rs... |
Indent (or de-indent) text | def indent_block(amount, text, indent_char='\t'):
""" Indent (or de-indent) text"""
rst = ""
for line in text.splitlines():
if amount > 0:
rst += indent_char*amount + line + "\n"
else:
rst += ''.join([c for i,c in enumerate(line) if (c == indent_char and (i+1) > abs(a... |
From a bytestring given by a (distant) call to Message.dump(), retrieve the original message
:param bmessage: bytestring given by a .dump() call on a message
:return: the original message | def load(cls, bmessage):
"""
From a bytestring given by a (distant) call to Message.dump(), retrieve the original message
:param bmessage: bytestring given by a .dump() call on a message
:return: the original message
"""
message_dict = msgpack.loads(bmessage, encoding="ut... |
Install gettext with the default parameters | 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:
gette... |
Returns {"authenticated": false} or {"authenticated": true, "username": "your_username"} (always 200 OK) | def API_GET(self): # pylint: disable=arguments-differ
"""
Returns {"authenticated": false} or {"authenticated": true, "username": "your_username"} (always 200 OK)
"""
if self.user_manager.session_logged_in():
return 200, {"authenticated": True, "username": self.user_mana... |
Authenticates the remote client. Takes as input:
auth_method_id
an id for an auth method as returned be /api/v0/auth_methods
input_key_1
the first input key and its value
input_key_2
the first input key and its value
...... | def API_POST(self): # pylint: disable=arguments-differ
"""
Authenticates the remote client. Takes as input:
auth_method_id
an id for an auth method as returned be /api/v0/auth_methods
input_key_1
the first input key and its value
... |
Returns all the auth methods available. (200 OK)
Response: list of auth methods. The value of the dict is an auth method, represented by:
id
id of the auth method
name
the name of the authentication method, typically displayed by the webapp
... | def API_GET(self):
"""
Returns all the auth methods available. (200 OK)
Response: list of auth methods. The value of the dict is an auth method, represented by:
id
id of the auth method
name
the name of the authentication method,... |
GET request | def GET_AUTH(self, courseid): # pylint: disable=arguments-differ
""" GET request """
course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=False)
return self.page(course) |
POST request | def POST_AUTH(self, courseid): # pylint: disable=arguments-differ
""" POST request """
course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=False)
errors = []
course_content = {}
try:
data = web.input()
course_content = self.course_fac... |
Get all data and display the page | def page(self, course, errors=None, saved=False):
""" Get all data and display the page """
return self.template_helper.get_renderer().course_admin.settings(course, errors, saved) |
Copy src to dest, recursively and with file 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.... |
Init the plugin
Available configuration:
::
plugins:
- plugin_module: inginious.frontend.plugins.git_repo
repo_directory: "./repo_submissions" | 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(p... |
Add a new submission to the repo (add the to queue, will be saved async) | def add(self, submission, archive, _):
""" Add a new submission to the repo (add the to queue, will be saved async)"""
self.queue.put((submission, submission["result"], submission["grade"], submission["problems"], submission["tests"], submission["custom"], archive)) |
saves a new submission in the repo (done async) | def save(self, submission, result, grade, problems, tests, custom, archive): # pylint: disable=unused-argument
""" saves a new submission in the repo (done async) """
# Save submission to repo
self._logger.info("Save submission " + str(submission["_id"]) + " to git repo")
# Verify that ... |
Returns the description of this tag
translated=True can be use to avoid getting garbage when calling _() with an empty string since the description of a tag CAN be empty | def get_description(self, translated=False):
"""
Returns the description of this tag
translated=True can be use to avoid getting garbage when calling _() with an empty string since the description of a tag CAN be empty
"""
if translated and self._description != "":
... |
Return a textual description of the type | 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... |
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 | 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... |
Check the tags arg only contains valid type for tags
:param tags: output of create_tags_from_dict
:return: True if correct format, False otherwise | def check_format(cls, tags):
"""
Check the tags arg only contains valid type for tags
:param tags: output of create_tags_from_dict
:return: True if correct format, False otherwise
"""
common, _, _ = tags
for tag in common:
if tag.get_type() != 0: # Un... |
GET request | def GET_AUTH(self, courseid, aggregationid): # pylint: disable=arguments-differ
""" GET request """
course, __ = self.get_course_and_check_rights(courseid)
if course.is_lti():
raise web.notfound()
return self.page(course, aggregationid) |
Get all data and display the page | def page(self, course, aggregationid):
""" Get all data and display the page """
aggregation = self.database.aggregations.find_one({"_id": ObjectId(aggregationid)})
data = list(self.database.submissions.aggregate(
[
{
"$match":
... |
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. | 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.__backen... |
Check if the last timeout is too old. If it is, kills the run_listen task | 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_re... |
Listen to the backend | async def __run_listen(self):
""" Listen to the backend """
while True:
message = await ZMQUtils.recv(self.__backend_socket)
await self.__handle_backend_message(message) |
Dispatch messages received from clients to the right handlers | async def __handle_backend_message(self, message):
""" Dispatch messages received from clients to the right handlers """
message_handlers = {
BackendNewJob: self.__handle_new_job,
BackendKillJob: self.kill_job,
Ping: self.__handle_ping
}
try:
... |
Handle a Ping message. Pong the backend | 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()) |
Send info about the SSH debug connection to the backend/client. Must be called *at most once* for each job.
:exception JobNotRunningException: is raised when the job is not running anymore (send_job_result already called)
:exception TooManyCallsException: is raised when this function has been called mor... | async def send_ssh_job_info(self, job_id: BackendJobId, host: str, port: int, key: str):
"""
Send info about the SSH debug connection to the backend/client. Must be called *at most once* for each job.
:exception JobNotRunningException: is raised when the job is not running anymore (send_job_resu... |
Send the result of a job back to the backend. Must be called *once and only once* for each job
:exception JobNotRunningException: is raised when send_job_result is called more than once for a given job_id | async def send_job_result(self, job_id: BackendJobId, result: str, text: str = "", grade: float = None, problems: Dict[str, SPResult] = None,
tests: Dict[str, Any] = None, custom: Dict[str, Any] = None, state: str = "", archive: Optional[bytes] = None,
stdout:... |
Calls self._loop.create_task with a safe (== with logged exception) coroutine. When run() ends, these tasks
are automatically cancelled | def _create_safe_task(self, coroutine):
""" Calls self._loop.create_task with a safe (== with logged exception) coroutine. When run() ends, these tasks
are automatically cancelled"""
task = self._loop.create_task(coroutine)
self.__asyncio_tasks_running.add(task)
task.add_done... |
Returns the content of a CSV file with the data of the dict/list data | def make_csv(data):
""" Returns the content of a CSV file with the data of the dict/list data """
# Convert sub-dicts to news cols
for entry in data:
rval = entry
if isinstance(data, dict):
rval = data[entry]
todel = []
toadd = {}
for key, val in rval.item... |
Returns the HTML of the menu used in the administration. ```current``` is the current page of section | 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... |
Returns the course with id ``courseid`` and the task with id ``taskid``, and verify the rights of the user.
Raise web.notfound() when there is no such course of if the users has not enough rights.
:param courseid: the course on which to check rights
:param taskid: If not None, retur... | def get_course_and_check_rights(self, courseid, taskid=None, allow_all_staff=True):
""" Returns the course with id ``courseid`` and the task with id ``taskid``, and verify the rights of the user.
Raise web.notfound() when there is no such course of if the users has not enough rights.
:p... |
Returns the submissions that have been selected by the admin
:param course: course
:param filter_type: users or aggregations
:param selected_tasks: selected tasks id
:param users: selected usernames
:param aggregations: selected aggregations
:param stype: single or all su... | def get_selected_submissions(self, course, filter_type, selected_tasks, users, aggregations, stype):
"""
Returns the submissions that have been selected by the admin
:param course: course
:param filter_type: users or aggregations
:param selected_tasks: selected tasks id
:... |
Writes a row to the CSV file | 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)
s... |
GET request | def GET_AUTH(self, courseid): # pylint: disable=arguments-differ
""" GET request """
course, __ = self.get_course_and_check_rights(courseid)
if self.user_manager.session_username() in course.get_tutors():
raise web.seeother(self.app.get_homepath() + '/admin/{}/tasks'.format(courseid... |
Get the default 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 |
Create a template renderer on templates in the directory specified, and returns it.
:param dir_path: the path to the template dir. If it is not absolute, it will be taken from the root of the inginious package.
:param layout: can either be True (use the base layout of the running app), False (use no lay... | def get_custom_renderer(self, dir_path, layout=True):
"""
Create a template renderer on templates in the directory specified, and returns it.
:param dir_path: the path to the template dir. If it is not absolute, it will be taken from the root of the inginious package.
:param layout: can ... |
Add javascript links for the current page and for the plugins | 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 ... |
Add CSS links for the current page and for the plugins | 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='" + ent... |
Get web.ctx object for the Template helper | 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) |
A generic hook that links the TemplateHelper with PluginManager | 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) |
Make a json dump of `data`, that can be used directly in a `<script>` tag. Available as json() inside templates | def _json_safe_dump(self, data):
""" Make a json dump of `data`, that can be used directly in a `<script>` tag. Available as json() inside templates """
return json.dumps(data).replace(u'<', u'\\u003c') \
.replace(u'>', u'\\u003e') \
.replace(u'&', u'\\u0026') \
.repl... |
GET request | def GET_AUTH(self, courseid): # pylint: disable=arguments-differ
""" GET request """
course, __ = self.get_course_and_check_rights(courseid)
if course.is_lti():
raise web.notfound()
if "download" in web.input():
web.header('Content-Type', 'text/x-yaml', unique=... |
POST request | def POST_AUTH(self, courseid): # pylint: disable=arguments-differ
""" POST request """
course, __ = self.get_course_and_check_rights(courseid)
if course.is_lti():
raise web.notfound()
error = False
try:
if self.user_manager.has_admin_rights_on_course(co... |
Get all data and display the page | def page(self, course, msg="", error=False):
""" Get all data and display the page """
aggregations = OrderedDict()
taskids = list(course.get_tasks().keys())
for aggregation in self.user_manager.get_course_aggregations(course):
aggregations[aggregation['_id']] = dict(list(ag... |
Runs a new job. It works exactly like the Client class, instead that there is no callback | 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,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.