_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q230300
Client.new_job
train
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:...
python
{ "resource": "" }
q230301
Client.kill_job
train
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
{ "resource": "" }
q230302
get_codeblock
train
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
{ "resource": "" }
q230303
get_imageblock
train
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...
python
{ "resource": "" }
q230304
get_admonition
train
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...
python
{ "resource": "" }
q230305
init
train
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...
python
{ "resource": "" }
q230306
LocalFSProvider._recursive_overwrite
train
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....
python
{ "resource": "" }
q230307
init
train
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...
python
{ "resource": "" }
q230308
Tag.get_type_as_str
train
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...
python
{ "resource": "" }
q230309
Tag.create_tags_from_dict
train
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...
python
{ "resource": "" }
q230310
Agent.run
train
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...
python
{ "resource": "" }
q230311
Agent.__check_last_ping
train
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...
python
{ "resource": "" }
q230312
Agent.__run_listen
train
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
{ "resource": "" }
q230313
Agent.__handle_ping
train
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
{ "resource": "" }
q230314
get_menu
train
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...
python
{ "resource": "" }
q230315
UnicodeWriter.writerow
train
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...
python
{ "resource": "" }
q230316
TemplateHelper.get_renderer
train
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
{ "resource": "" }
q230317
TemplateHelper._javascript_helper
train
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 ...
python
{ "resource": "" }
q230318
TemplateHelper._css_helper
train
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...
python
{ "resource": "" }
q230319
TemplateHelper._get_ctx
train
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
{ "resource": "" }
q230320
TemplateHelper._generic_hook
train
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
{ "resource": "" }
q230321
ClientBuffer.new_job
train
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, ...
python
{ "resource": "" }
q230322
ClientBuffer._callback
train
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
{ "resource": "" }
q230323
init
train
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, ...
python
{ "resource": "" }
q230324
MongoStore.cleanup
train
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
{ "resource": "" }
q230325
PluginManager.load
train
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 ...
python
{ "resource": "" }
q230326
PluginManager.add_page
train
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
{ "resource": "" }
q230327
PluginManager.add_task_file_manager
train
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
{ "resource": "" }
q230328
PluginManager.register_auth_method
train
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 "...
python
{ "resource": "" }
q230329
CourseDangerZonePage.dump_course
train
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(f...
python
{ "resource": "" }
q230330
CourseDangerZonePage.delete_course
train
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...
python
{ "resource": "" }
q230331
DisplayableCodeProblem.show_input
train
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(DisplayableCod...
python
{ "resource": "" }
q230332
DisplayableMultipleChoiceProblem.show_input
train
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)) ...
python
{ "resource": "" }
q230333
LTILaunchPage._parse_lti_data
train
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 exce...
python
{ "resource": "" }
q230334
LTILaunchPage._find_realname
train
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_fa...
python
{ "resource": "" }
q230335
fast_stats
train
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_s...
python
{ "resource": "" }
q230336
BetterParanoidPirateClient._register_transaction
train
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 ca...
python
{ "resource": "" }
q230337
BetterParanoidPirateClient._reconnect
train
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 ...
python
{ "resource": "" }
q230338
BetterParanoidPirateClient.client_start
train
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 = s...
python
{ "resource": "" }
q230339
BetterParanoidPirateClient._run_socket
train
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 ...
python
{ "resource": "" }
q230340
load_feedback
train
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: ...
python
{ "resource": "" }
q230341
save_feedback
train
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
{ "resource": "" }
q230342
set_problem_result
train
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 [res...
python
{ "resource": "" }
q230343
set_global_feedback
train
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
{ "resource": "" }
q230344
set_problem_feedback
train
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 fe...
python
{ "resource": "" }
q230345
Installer._display_big_warning
train
def _display_big_warning(self, content): """ Displays a BIG warning """ print("") print(BOLD + WARNING + "--- WARNING ---" + ENDC) print(WARNING + content + ENDC) print("")
python
{ "resource": "" }
q230346
Installer._ask_local_config
train
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 simultaneou...
python
{ "resource": "" }
q230347
Installer.ask_backend
train
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._displa...
python
{ "resource": "" }
q230348
Installer.try_mongodb_opts
train
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))) retu...
python
{ "resource": "" }
q230349
Installer.configure_task_directory
train
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_direc...
python
{ "resource": "" }
q230350
Installer.download_containers
train
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(...
python
{ "resource": "" }
q230351
Installer.configure_containers
train
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"), ("java8sca...
python
{ "resource": "" }
q230352
Installer.configure_backup_directory
train
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_...
python
{ "resource": "" }
q230353
Installer.ldap_plugin
train
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...
python
{ "resource": "" }
q230354
Installer.configure_authentication
train
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...
python
{ "resource": "" }
q230355
_close_app
train
def _close_app(app, mongo_client, client): """ Ensures that the app is properly closed """ app.stop() client.close() mongo_client.close()
python
{ "resource": "" }
q230356
DockerAgent._init_clean
train
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...
python
{ "resource": "" }
q230357
DockerAgent._end_clean
train
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 con...
python
{ "resource": "" }
q230358
DockerAgent._watch_docker_events
train
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...
python
{ "resource": "" }
q230359
DockerAgent.handle_student_job_closing
train
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", conta...
python
{ "resource": "" }
q230360
DockerAgent.kill_job
train
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(se...
python
{ "resource": "" }
q230361
CourseEditAggregation.get_user_lists
train
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":...
python
{ "resource": "" }
q230362
CourseEditAggregation.update_aggregation
train
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 c...
python
{ "resource": "" }
q230363
MyCoursesPage.POST_AUTH
train
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() ...
python
{ "resource": "" }
q230364
_restart_on_cancel
train
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
{ "resource": "" }
q230365
INGIniousAuthPage.GET
train
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__ ...
python
{ "resource": "" }
q230366
StaticMiddleware.normpath
train
def normpath(self, path): """ Normalize the path """ path2 = posixpath.normpath(urllib.parse.unquote(path)) if path.endswith("/"): path2 += "/" return path2
python
{ "resource": "" }
q230367
_get_submissions
train
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("Cou...
python
{ "resource": "" }
q230368
APISubmissionSingle.API_GET
train
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", ...
python
{ "resource": "" }
q230369
WebAppCourse.is_registration_possible
train
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
{ "resource": "" }
q230370
WebAppCourse.get_accessibility
train
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 sel...
python
{ "resource": "" }
q230371
WebAppCourse.is_user_accepted_by_access_control
train
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": ...
python
{ "resource": "" }
q230372
WebAppCourse.allow_unregister
train
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
{ "resource": "" }
q230373
WebAppCourse.get_name
train
def get_name(self, language): """ Return the name of this course """ return self.gettext(language, self._name) if self._name else ""
python
{ "resource": "" }
q230374
WebAppCourse.get_description
train
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
{ "resource": "" }
q230375
WebAppCourse.get_all_tags_names_as_list
train
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...
python
{ "resource": "" }
q230376
WebAppCourse.update_all_tags_cache
train
def update_all_tags_cache(self): """ Force the cache refreshing """ self._all_tags_cache = None self._all_tags_cache_list = {} self._all_tags_cache_list_admin = {} self._organisational_tags_to_task = {} self.get_all_tags() self.get_all_tags_n...
python
{ "resource": "" }
q230377
get_app
train
def get_app(config): """ Init the webdav app """ mongo_client = MongoClient(host=config.get('mongo_opt', {}).get('host', 'localhost')) database = mongo_client[config.get('mongo_opt', {}).get('database', 'INGInious')] # Create the FS provider if "tasks_directory" not in config: raise Runtime...
python
{ "resource": "" }
q230378
INGIniousDAVDomainController.getDomainRealm
train
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("/") ...
python
{ "resource": "" }
q230379
INGIniousDAVDomainController.isRealmUser
train
def isRealmUser(self, realmname, username, environ): """Returns True if this username is valid for the realm, False otherwise.""" try: course = self.course_factory.get_course(realmname) ok = self.user_manager.has_admin_rights_on_course(course, username=username) retur...
python
{ "resource": "" }
q230380
INGIniousDAVDomainController.getRealmUserPassword
train
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
{ "resource": "" }
q230381
INGIniousFilesystemProvider.getResourceInst
train
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): ...
python
{ "resource": "" }
q230382
CourseEditTask.contains_is_html
train
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): ...
python
{ "resource": "" }
q230383
CourseEditTask.parse_problem
train
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
{ "resource": "" }
q230384
CourseEditTask.wipe_task
train
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...
python
{ "resource": "" }
q230385
HookManager._exception_free_callback
train
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) ...
python
{ "resource": "" }
q230386
HookManager.add_hook
train
def add_hook(self, name, callback, prio=0): """ Add a new hook that can be called with the call_hook function. `prio` is the priority. Higher priority hooks are called before lower priority ones. This function does not enforce a particular order between hooks with the same priorities. ...
python
{ "resource": "" }
q230387
Task.input_is_consistent
train
def input_is_consistent(self, task_input, default_allowed_extension, default_max_size): """ Check if an input for a task is consistent. Return true if this is case, false else """ for problem in self._problems: if not problem.input_is_consistent(task_input, default_allowed_extension, default...
python
{ "resource": "" }
q230388
Task.get_limits
train
def get_limits(self): """ Return the limits of this task """ vals = self._hook_manager.call_hook('task_limits', course=self.get_course(), task=self, default=self._limits) return vals[0] if len(vals) else self._limits
python
{ "resource": "" }
q230389
Task.allow_network_access_grading
train
def allow_network_access_grading(self): """ Return True if the grading container should have access to the network """ vals = self._hook_manager.call_hook('task_network_grading', course=self.get_course(), task=self, default=self._network_grading) return vals[0] if len(vals) else self._network_gr...
python
{ "resource": "" }
q230390
Task._create_task_problem
train
def _create_task_problem(self, problemid, problem_content, task_problem_types): """Creates a new instance of the right class for a given problem.""" # Basic checks if not id_checker(problemid): raise Exception("Invalid problem _id: " + problemid) if problem_content.get('type'...
python
{ "resource": "" }
q230391
course_menu
train
def course_menu(course, template_helper): """ Displays the link to the scoreboards on the course page, if the plugin is activated for this course """ scoreboards = course.get_descriptor().get('scoreboard', []) if scoreboards != []: return str(template_helper.get_custom_renderer('frontend/plugins/sc...
python
{ "resource": "" }
q230392
task_menu
train
def task_menu(course, task, template_helper): """ Displays the link to the scoreboards on the task page, if the plugin is activated for this course and the task is used in scoreboards """ scoreboards = course.get_descriptor().get('scoreboard', []) try: tolink = [] for sid, scoreboard in enum...
python
{ "resource": "" }
q230393
CourseEditClassroom.get_user_lists
train
def get_user_lists(self, course, classroomid): """ Get the available student and tutor lists for classroom edition""" tutor_list = course.get_staff() # Determine if user is grouped or not in the classroom student_list = list(self.database.classrooms.aggregate([ {"$match": {"...
python
{ "resource": "" }
q230394
CourseEditClassroom.update_classroom
train
def update_classroom(self, course, classroomid, new_data): """ Update classroom and returns a list of errored students""" student_list, tutor_list, other_students, _ = self.get_user_lists(course, classroomid) # Check tutors new_data["tutors"] = [tutor for tutor in map(str.strip, new_dat...
python
{ "resource": "" }
q230395
ParsableText.parse
train
def parse(self, debug=False): """Returns parsed text""" if self._parsed is None: try: if self._mode == "html": self._parsed = self.html(self._content, self._show_everything, self._translation) else: self._parsed = self.r...
python
{ "resource": "" }
q230396
CourseTaskFiles.POST_AUTH
train
def POST_AUTH(self, courseid, taskid): # pylint: disable=arguments-differ """ Upload or modify a file """ if not id_checker(taskid): raise Exception("Invalid task id") self.get_course_and_check_rights(courseid, allow_all_staff=False) request = web.input(file={}) if...
python
{ "resource": "" }
q230397
CourseTaskFiles.show_tab_file
train
def show_tab_file(self, courseid, taskid, error=None): """ Return the file tab """ return self.template_helper.get_renderer(False).course_admin.edit_tabs.files( self.course_factory.get_course(courseid), taskid, self.get_task_filelist(self.task_factory, courseid, taskid), error)
python
{ "resource": "" }
q230398
CourseTaskFiles.action_edit
train
def action_edit(self, courseid, taskid, path): """ Edit a file """ wanted_path = self.verify_path(courseid, taskid, path) if wanted_path is None: return "Internal error" try: content = self.task_factory.get_task_fs(courseid, taskid).get(wanted_path).decode("utf-8"...
python
{ "resource": "" }
q230399
CourseTaskFiles.action_edit_save
train
def action_edit_save(self, courseid, taskid, path, content): """ Save an edited file """ wanted_path = self.verify_path(courseid, taskid, path) if wanted_path is None: return json.dumps({"error": True}) try: self.task_factory.get_task_fs(courseid, taskid).put(want...
python
{ "resource": "" }