How to use the nbgrader.preprocessors.NbGraderPreprocessor function in nbgrader

To help you get started, we’ve selected a few nbgrader examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jupyter / nbgrader / nbgrader / preprocessors / clearsolutions.py View on Github external
import re

from traitlets import Dict, Unicode, Bool, observe
from traitlets.config.loader import Config
from textwrap import dedent

from .. import utils
from . import NbGraderPreprocessor
from typing import Any, Tuple
from nbformat.notebooknode import NotebookNode
from nbconvert.exporters.exporter import ResourcesDict


class ClearSolutions(NbGraderPreprocessor):

    code_stub = Dict(
        dict(python="# YOUR CODE HERE\nraise NotImplementedError()",
             matlab="% YOUR CODE HERE\nerror('No Answer Given!')",
             octave="% YOUR CODE HERE\nerror('No Answer Given!')",
             java="// YOUR CODE HERE"),
        help="The code snippet that will replace code solutions"
    ).tag(config=True)

    text_stub = Unicode(
        "YOUR ANSWER HERE",
        help="The text snippet that will replace written solutions"
    ).tag(config=True)

    begin_solution_delimeter = Unicode(
        "BEGIN SOLUTION",
github jupyter / nbgrader / nbgrader / preprocessors / lockcells.py View on Github external
from traitlets import Bool

from .. import utils
from . import NbGraderPreprocessor
from nbconvert.exporters.exporter import ResourcesDict
from nbformat.notebooknode import NotebookNode
from typing import Tuple

class LockCells(NbGraderPreprocessor):
    """A preprocessor for making cells undeletable."""

    lock_solution_cells = Bool(
        True,
        help="Whether solution cells are locked (non-deletable and non-editable)"
    ).tag(config=True)

    lock_grade_cells = Bool(
        True,
        help="Whether grade cells are locked (non-deletable)"
    ).tag(config=True)

    lock_readonly_cells = Bool(
        True,
        help="Whether readonly cells are locked (non-deletable and non-editable)"
    ).tag(config=True)
github choldgraf / nbclean / nbclean / preprocessors.py View on Github external
from traitlets import Unicode, Bool
from nbgrader.preprocessors import NbGraderPreprocessor


class RemoveCells(NbGraderPreprocessor):
    """A helper class to remove cells from a notebook.

    This should not be used directly, instead, use the
    NotebookCleaner class.
    """

    tag = Unicode("None")
    search_text = Unicode("None")
    empty = Bool(False)

    def preprocess(self, nb, resources):
        if self.tag == 'None' and self.empty is False and self.search_text == 'None':
            raise ValueError("One of `tag`, `empty`, or `search_text` must be used.")
        new_cells = []
        for ii, cell in enumerate(nb['cells']):
            is_empty = len(cell['source']) == 0
github jupyter / nbgrader / nbgrader / preprocessors / execute.py View on Github external
from nbconvert.preprocessors import ExecutePreprocessor
from traitlets import Bool, List, Integer
from textwrap import dedent

from . import NbGraderPreprocessor
from nbconvert.exporters.exporter import ResourcesDict
from nbformat.notebooknode import NotebookNode
from typing import Any, Optional, Tuple


class UnresponsiveKernelError(Exception):
    pass


class Execute(NbGraderPreprocessor, ExecutePreprocessor):

    interrupt_on_timeout = Bool(True)
    allow_errors = Bool(True)
    raise_on_iopub_timeout = Bool(True)
    extra_arguments = List([], help=dedent(
        """
        A list of extra arguments to pass to the kernel. For python kernels,
        this defaults to ``--HistoryManager.hist_file=:memory:``. For other
        kernels this is just an empty list.
        """)
    ).tag(config=True)

    execute_retries = Integer(0, help=dedent(
        """
        The number of times to try re-executing the notebook before throwing
        an error. Generally, this shouldn't need to be set, but might be useful
github jupyter / nbgrader / nbgrader / preprocessors / getgrades.py View on Github external
from traitlets import List

from nbconvert.exporters.exporter import ResourcesDict
from nbformat.notebooknode import NotebookNode
from typing import Optional, Any, Tuple

from .. import utils
from ..api import Gradebook
from . import NbGraderPreprocessor


class GetGrades(NbGraderPreprocessor):
    """Preprocessor for saving grades from the database to the notebook"""

    display_data_priority = List(['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain'], config=True)

    def preprocess(self,
                   nb: NotebookNode,
                   resources: ResourcesDict,
                   ) -> Tuple[NotebookNode, ResourcesDict]:
        # pull information from the resources
        self.notebook_id = resources['nbgrader']['notebook']
        self.assignment_id = resources['nbgrader']['assignment']
        self.student_id = resources['nbgrader']['student']
        self.db_url = resources['nbgrader']['db_url']

        # connect to the database
        self.gradebook = Gradebook(self.db_url)
github jupyter / nbgrader / nbgrader / preprocessors / limitoutput.py View on Github external
from . import NbGraderPreprocessor

from traitlets import Integer
from nbformat.notebooknode import NotebookNode
from nbconvert.exporters.exporter import ResourcesDict
from typing import Tuple


class LimitOutput(NbGraderPreprocessor):
    """Preprocessor for limiting cell output"""

    max_lines = Integer(
        1000,
        help="maximum number of lines of output (-1 means no limit)"
    ).tag(config=True)

    max_traceback = Integer(
        100,
        help="maximum number of traceback lines (-1 means no limit)"
    ).tag(config=True)

    def _limit_stream_output(self, cell: NotebookNode) -> NotebookNode:
        if self.max_lines == -1 or cell.cell_type != "code":
            return cell
github jupyter / nbgrader / nbgrader / preprocessors / savecells.py View on Github external
from .. import utils
from ..api import Gradebook, MissingEntry
from . import NbGraderPreprocessor

class SaveCells(NbGraderPreprocessor):
    """A preprocessor to save information about grade and solution cells."""

    def _create_notebook(self):
        notebook_info = None

        try:
            notebook = self.gradebook.find_notebook(self.notebook_id, self.assignment_id)
        except MissingEntry:
            notebook_info = {}
        else:
            # pull out existing cell ids
            self.old_grade_cells = set(x.name for x in notebook.grade_cells)
            self.old_solution_cells = set(x.name for x in notebook.solution_cells)
            self.old_source_cells = set(x.name for x in notebook.source_cells)

            # throw an error if we're trying to modify a notebook that has
github jupyter / nbgrader / nbgrader / preprocessors / clearmarkingscheme.py View on Github external
import re

from traitlets import Bool, Unicode
from textwrap import dedent

from . import NbGraderPreprocessor
from .. import utils
from nbformat.notebooknode import NotebookNode
from nbconvert.exporters.exporter import ResourcesDict
from typing import Tuple


class ClearMarkScheme(NbGraderPreprocessor):

    begin_mark_scheme_delimeter = Unicode(
        "BEGIN MARK SCHEME",
        help="The delimiter marking the beginning of hidden tests cases"
    ).tag(config=True)

    end_mark_scheme_delimeter = Unicode(
        "END MARK SCHEME",
        help="The delimiter marking the end of hidden tests cases"
    ).tag(config=True)

    enforce_metadata = Bool(
        True,
        help=dedent(
            """
            Whether or not to complain if cells containing marking scheme regions
github jupyter / nbgrader / nbgrader / preprocessors / overwritekernelspec.py View on Github external
import json

from . import NbGraderPreprocessor
from ..api import Gradebook
from nbconvert.exporters.exporter import ResourcesDict
from nbformat.notebooknode import NotebookNode
from typing import Tuple


class OverwriteKernelspec(NbGraderPreprocessor):
    """A preprocessor for checking the notebook kernelspec metadata."""

    def preprocess(self, nb: NotebookNode, resources: ResourcesDict) -> Tuple[NotebookNode, ResourcesDict]:
        # pull information from the resources
        notebook_id = resources['nbgrader']['notebook']
        assignment_id = resources['nbgrader']['assignment']
        db_url = resources['nbgrader']['db_url']

        with Gradebook(db_url) as gb:
            kernelspec = json.loads(
                gb.find_notebook(notebook_id, assignment_id).kernelspec)
            self.log.debug("Source notebook kernelspec: {}".format(kernelspec))
            self.log.debug(
                "Submitted notebook kernelspec: {}"
                "".format(nb.metadata.get('kernelspec', None))
            )
github jupyter / nbgrader / nbgrader / preprocessors / clearoutput.py View on Github external
from nbconvert.preprocessors import ClearOutputPreprocessor
from . import NbGraderPreprocessor

class ClearOutput(NbGraderPreprocessor, ClearOutputPreprocessor):
    pass