def getname():
    """Get the current notebook's name. This is actually a javascript command and
    requires some time before the name is stored in the global namespace as ```this_notebook```
    """
    # TODO: Save the contents of the current notebook
    IP.display(
        IP.Javascript(
            'Jupyter.notebook.kernel.execute("this_notebook = " + "\'"+Jupyter.notebook.notebook_name+"\'");'
        ))

    IP.display(IP.Javascript("IPython.notebook.save_notebook()"),
               include=['application/javascript'])
def load_ipython_extension(ip):
    """Load the extension in IPython."""
    ip.register_magics(PigMagics)

    # enable Pig highlight
    js = display.Javascript(data=js_string)
    display.display_javascript(js)

    # some custom CSS to augment the syntax highlighting
    css = display.HTML(css_string)
    display.display_html(css)
Exemple #3
0
def load_ipython_extension(ip):
    """Load the extension in IPython."""
    ip.register_magics(FortranMagics)

    # enable fortran highlight
    patch = ("IPython.config.cell_magic_highlight['magic_fortran'] = "
             "{'reg':[/^%%fortran/]};")
    js = display.Javascript(data=patch,
                            lib=["https://raw.github.com/marijnh/CodeMirror/master/mode/"
                                 "fortran/fortran.js"])
    display.display_javascript(js)
Exemple #4
0
def test_displayobject_repr():
    h = display.HTML('<br />')
    nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')
    h._show_mem_addr = True
    nt.assert_equal(repr(h), object.__repr__(h))
    h._show_mem_addr = False
    nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')

    j = display.Javascript('')
    nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>')
    j._show_mem_addr = True
    nt.assert_equal(repr(j), object.__repr__(j))
    j._show_mem_addr = False
    nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>')
Exemple #5
0
def load_ipython_extension(ip):
    """
    register magics function, can be called from a notebook
    """
    #ip = get_ipython()
    ip.register_magics(CustomMagics)
    # enable C# (CSHARP) highlight
    patch = ("IPython.config.cell_magic_highlight['clrmagic'] = "
             "{'reg':[/^%%CS/]};")
    js = display.Javascript(
        data=patch,
        lib=[
            "https://github.com/codemirror/CodeMirror/blob/master/mode/clike/clike.js"
        ])
    def makestudent(self, tags=None, studentfolder=''):
        """Make a Student Version of the notebook"""

        instructor_fn = self.filename

        instructorfile = nbfilename(instructor_fn)

        # TODO: check all links in the directory for name change.
        if not str(instructorfile) == instructor_fn:
            print(
                f"WARNING: Instructor file name is wrong {instructorfile} != {instructor_fn}"
            )

        IP.display(IP.Javascript("IPython.notebook.save_notebook()"),
                   include=['application/javascript'])

        studentfile = nbfilename(instructor_fn)

        if studentfile.isDate:
            tags['DUE_DATE'] = studentfile.getlongdate()
            tags['MMDD'] = studentfile.prefix

        self.removecells(searchstring="#ANSWER#", verbose=False)
        self.stripoutput()

        # Remove INSTRUCTOR from name
        studentfile.isInstructor = False
        self.filename = str(studentfile)

        tags['NEW_ASSIGNMENT'] = str(studentfile)
        print(tags['NEW_ASSIGNMENT'])
        self.mergetags(tags)

        student_fn = f"{studentfolder}{studentfile}"

        if Path(instructor_fn) == Path(student_fn):
            print("ERROR: student file will overrite instructor. Aborting")
            print(f"   {instructor_fn} --> {student_fn}")
            return

        # Make a link for review
        IP.display(
            HTML(f"<a href={student_fn} target=\"blank\">{student_fn}</a>"))

        return student_fn
def makestudent(filename, studentfolder='./', tags={}):
    """Make a student from an instructor noatebook

    Parameters
    ----------
    filename : string
        Current name of the Instructor notebook with the date prefix
    studentfolder : string
        Name of folder to save the student notebook
    tags: dictionary
        Dictionary of Tag values (key) and replacment text (values).
    """
    IP.display(IP.Javascript("IPython.notebook.save_notebook()"),
               include=['application/javascript'])

    nb = InstructorNB(filename=filename)

    studentfile = nb.makestudent(tags=tags, studentfolder=studentfolder)

    nb.writenotebook(studentfile)

    return studentfile
def convert(this_notebook, studentfolder='./'):
    import os
    from IPython.core.display import Javascript, HTML
    from IPython.display import display

    print("Save Current Notebook")
    IP.display(IP.Javascript("Python.notebook.save_notebook()"),
               include=['application/javascript'])

    #Calculate Destination name
    ASSIGNMENT = this_notebook
    ind = ASSIGNMENT.index("INST")
    ext = ASSIGNMENT.index(".ipynb")
    NEW_ASSIGNMENT = ASSIGNMENT[:ind] + "STUDENT" + ASSIGNMENT[ext:]

    print("Removing existing student version")
    command = f"rm {studentfolder}{NEW_ASSIGNMENT}"
    os.system(command)

    print("Stripping out ANSWER fields")
    command = f"python ./instruct/makeStudentVersion.py {this_notebook}"
    os.system(command)

    #Move to the working directory
    print("Moving to working directory")
    command = f"mv {NEW_ASSIGNMENT} {studentfolder}"
    os.system(command)

    #Strip output
    print("Striping output cells")
    command = f"python ./instruct/nbstripout {studentfolder}{NEW_ASSIGNMENT}"
    os.system(command)

    # Make a link for review
    display(
        HTML(
            f"<a href={studentfolder}{NEW_ASSIGNMENT} target=\"_blank\">{NEW_ASSIGNMENT}</a>"
        ))
def cleanNsave():
    """Run javascript in the current notebook to clear all output and save the notebook."""
    IP.display(IP.Javascript("IPython.notebook.clear_all_output()"),
               include=['application/javascript'])
    IP.display(IP.Javascript("IPython.notebook.save_notebook()"),
               include=['application/javascript'])
def merge(this_notebook, studentfolder='./', tags={}):
    import os
    from IPython.core.display import Javascript, HTML
    from IPython.display import display
    import csv
    import datetime
    import calendar

    IP.display(IP.Javascript("IPython.notebook.save_notebook()"),
               include=['application/javascript'])

    #Calculate Destination name
    ASSIGNMENT = this_notebook
    ind = ASSIGNMENT.index("INST") - 1
    ext = ASSIGNMENT.index(".ipynb")
    #NEW_ASSIGNMENT = ASSIGNMENT[:ind] + "STUDENT" + ASSIGNMENT[ext:]
    NEW_ASSIGNMENT = ASSIGNMENT[:ind] + ASSIGNMENT[ext:]

    try:
        month = int(NEW_ASSIGNMENT[0:2])
        day = int(NEW_ASSIGNMENT[2:4])

        print(f"TESTING {day} {month}")
        my_date = datetime.datetime(2019, month, day)
        #my_date = date.today()
        weekday = calendar.day_name[my_date.weekday()]

        mnth = calendar.month_name[month]
        tags['DUE_DATE'] = f'{weekday} {mnth} {day}'
        tags['MMDD'] = NEW_ASSIGNMENT[0:4]
    except:
        print("Date not found")

    print("Removing existing student version")
    command = f"rm {studentfolder}{NEW_ASSIGNMENT}"
    os.system(command)

    with open(ASSIGNMENT, 'r+', encoding="utf-8") as file:
        lines = file.readlines()

    new_lines = []
    LIMIT = len(lines)

    i = 0
    while i < LIMIT:
        if '"code"' in lines[i]:
            found = False
            next_ind = i

            while not found:
                if '"source"' in lines[next_ind]:
                    found = True
                next_ind += 1

            if "ANSWER" in lines[next_ind]:
                del new_lines[-1]
                temp = lines[i:]
                i = i + temp.index("  },\n") + 1
            else:
                new_lines.append(lines[i])
                i += 1

        if '"markdown"' in lines[i]:
            found = False
            next_ind = i

            while not found:
                if '"source"' in lines[next_ind]:
                    found = True
                next_ind += 1

            if "ANSWER" in lines[next_ind]:
                del new_lines[-1]
                temp = lines[i:]
                i = i + temp.index("  },\n") + 1
            else:
                new_lines.append(lines[i])
                i += 1
        else:
            new_lines.append(lines[i])
            i += 1

    print("Finding and replacing mailmerge tags")
    lines = []
    for row in new_lines:
        for key in tags:
            if (key in row):
                row = row.replace(f"###{key}###", tags[key])
                print(row)
        lines.append(row)

    with open(NEW_ASSIGNMENT, 'w+', encoding="utf-8") as f:
        for l in lines:
            f.write(l)

    for line in lines:
        if "ANSWER" in line:
            print(
                "WARNING! Some answer content may remain in the file. Please double check file contents before administering to students."
            )
            break

    #Move to the working directory
    print("Moving to working directory")
    command = f"mv {NEW_ASSIGNMENT} {studentfolder}"
    os.system(command)

    #Strip output
    print("Striping output cells")
    command = f"python ./instruct/nbstripout {studentfolder}{NEW_ASSIGNMENT}"
    os.system(command)

    # Make a link for review
    display(
        HTML(
            f"<a href={studentfolder}{NEW_ASSIGNMENT} target=\"blank\">{NEW_ASSIGNMENT}</a>"
        ))
def getname():
    IP.display(
        IP.Javascript(
            'Jupyter.notebook.kernel.execute("this_notebook = " + "\'"+Jupyter.notebook.notebook_name+"\'");'
        ))