Esempio n. 1
0
def format_docstring(func):
    docstring = (func.__doc__ or "Undocumented").rstrip()
    docstring = indent(dedent(docstring))
    # Sphinx complains if indented bits have rst headings in, so strip out
    # any underlines in the docstring.
    lines = [_strip_underline(l) for l in docstring.splitlines()]
    return "\n".join(lines)
Esempio n. 2
0
def _function_magic_marker(magic_kind):
    """Decorator factory for standalone functions.
    """
    validate_type(magic_kind)

    # This is a closure to capture the magic_kind.  We could also use a class,
    # but it's overkill for just that one bit of state.
    def magic_deco(arg):
        call = lambda f, *a, **k: f(*a, **k)

        # Find get_ipython() in the caller's namespace
        caller = sys._getframe(1)
        for ns in ["f_locals", "f_globals", "f_builtins"]:
            get_ipython = getattr(caller, ns).get("get_ipython")
            if get_ipython is not None:
                break
        else:
            raise NameError("Decorator can only run in context where " "`get_ipython` exists")

        ip = get_ipython()

        if callable(arg):
            # "Naked" decorator call (just @foo, no args)
            func = arg
            name = func.func_name
            ip.register_magic_function(func, magic_kind, name)
            retval = decorator(call, func)
        elif isinstance(arg, basestring):
            # Decorator called with arguments (@foo('bar'))
            name = arg

            def mark(func, *a, **kw):
                ip.register_magic_function(func, magic_kind, name)
                return decorator(call, func)

            retval = mark
        else:
            raise TypeError("Decorator can only be called with " "string or function")
        return retval

    # Ensure the resulting decorator has a usable docstring
    ds = _docstring_template.format("function", magic_kind)

    ds += dedent(
        """
    Note: this decorator can only be used in a context where IPython is already
    active, so that the `get_ipython()` call succeeds.  You can therefore use
    it in your startup files loaded after IPython initializes, but *not* in the
    IPython configuration file itself, which is executed before IPython is
    fully up and running.  Any file located in the `startup` subdirectory of
    your configuration profile will be OK in this sense.
    """
    )

    magic_deco.__doc__ = ds
    return magic_deco
Esempio n. 3
0
    def _magic_docs(self, brief=False, rest=False):
        """Return docstrings from magic functions."""
        mman = self.shell.magics_manager
        docs = mman.lsmagic_docs(brief, missing='No documentation')

        if rest:
            format_string = '**%s%s**::\n\n%s\n\n'
        else:
            format_string = '%s%s:\n%s\n'

        return ''.join(
            [format_string % (magic_escapes['line'], fname,
                              indent(dedent(fndoc)))
             for fname, fndoc in sorted(docs['line'].items())]
            +
            [format_string % (magic_escapes['cell'], fname,
                              indent(dedent(fndoc)))
             for fname, fndoc in sorted(docs['cell'].items())]
        )
Esempio n. 4
0
    def _magic_docs(self, brief=False, rest=False):
        """Return docstrings from magic functions."""
        mman = self.shell.magics_manager
        docs = mman.lsmagic_docs(brief, missing="No documentation")

        if rest:
            format_string = "**%s%s**::\n\n%s\n\n"
        else:
            format_string = "%s%s:\n%s\n"

        return "".join(
            [
                format_string % (magic_escapes["line"], fname, indent(dedent(fndoc)))
                for fname, fndoc in sorted(docs["line"].items())
            ]
            + [
                format_string % (magic_escapes["cell"], fname, indent(dedent(fndoc)))
                for fname, fndoc in sorted(docs["cell"].items())
            ]
        )
Esempio n. 5
0
 def print_flag_help(self):
     """Print the flag part of the help."""
     if not self.flags:
         return
     
     lines = []
     for m, (cfg,help) in self.flags.iteritems():
         lines.append('--'+m)
         lines.append(indent(dedent(help.strip())))
     # lines.append('')
     print os.linesep.join(lines)
Esempio n. 6
0
    def print_flag_help(self):
        """Print the flag part of the help."""
        if not self.flags:
            return

        lines = []
        for m, (cfg, help) in iteritems(self.flags):
            prefix = '--' if len(m) > 1 else '-'
            lines.append(prefix + m)
            lines.append(indent(dedent(help.strip())))
        # lines.append('')
        print(os.linesep.join(lines))
Esempio n. 7
0
    def print_examples(self):
        """Print usage and examples.

        This usage string goes at the end of the command line help string
        and should contain examples of the application's usage.
        """
        if self.examples:
            print("Examples")
            print("--------")
            print()
            print(indent(dedent(self.examples.strip())))
            print()
Esempio n. 8
0
 def print_subcommands(self):
     """Print the subcommand part of the help."""
     if not self.subcommands:
         return
     
     lines = ["Subcommands"]
     lines.append('-'*len(lines[0]))
     for subc, (cls,help) in self.subcommands.items():
         lines.append("%s : %s"%(subc, cls))
         if help:
             lines.append(indent(dedent(help.strip())))
     lines.append('')
     print('\n'.join(lines))
Esempio n. 9
0
    def print_subcommands(self):
        """Print the list of subcommands under this application"""

        if not self.subcommands:
            return

        lines = ["Subcommands"]
        lines.append("-" * len(lines[0]))
        for subc, (cls, help) in self.subcommands.iteritems():
            lines.append(subc)
            if help:
                lines.append(indent(dedent(help.strip())))
        lines.append("")

        print(os.linesep.join(lines))
Esempio n. 10
0
    def print_subcommands(self):
        """Print the subcommand part of the help."""
        if not self.subcommands:
            return

        lines = ["Subcommands"]
        lines.append('-' * len(lines[0]))
        lines.append('')
        for p in wrap_paragraphs(self.subcommand_description):
            lines.append(p)
            lines.append('')
        for subc, (cls, help) in self.subcommands.iteritems():
            lines.append(subc)
            if help:
                lines.append(indent(dedent(help.strip())))
        lines.append('')
        print os.linesep.join(lines)
Esempio n. 11
0
 def print_flag_help(self):
     """Print the flag part of the help."""
     if not self.flags:
         return
     
     lines = ['Flags']
     lines.append('-'*len(lines[0]))
     lines.append('')
     for p in wrap_paragraphs(self.flag_description):
         lines.append(p)
         lines.append('')
     
     for m, (cfg,help) in self.flags.items():
         lines.append('--'+m)
         lines.append(indent(dedent(help.strip())))
     lines.append('')
     print('\n'.join(lines))
Esempio n. 12
0
    def print_subcommands(self):
        """Print the subcommand part of the help."""
        if not self.subcommands:
            return

        lines = ["Subcommands"]
        lines.append('-' * len(lines[0]))
        lines.append('')
        for p in wrap_paragraphs(self.subcommand_description):
            lines.append(p)
            lines.append('')
        for subc, (cls, help) in iteritems(self.subcommands):
            lines.append(subc)
            if help:
                lines.append(indent(dedent(help.strip())))
        lines.append('')
        print(os.linesep.join(lines))
Esempio n. 13
0
    def print_flag_help(self):
        """Print the flag part of the help."""
        if not self.flags:
            return

        lines = ['Flags']
        lines.append('-' * len(lines[0]))
        lines.append('')
        for p in wrap_paragraphs(self.flag_description):
            lines.append(p)
            lines.append('')

        for m, (cfg, help) in self.flags.iteritems():
            lines.append('--' + m)
            lines.append(indent(dedent(help.strip())))
        lines.append('')
        print '\n'.join(lines)
Esempio n. 14
0
def document_config_options(classes):
    lines = []
    for cls in classes:
        classname = cls.__name__
        for k, trait in sorted(cls.class_traits(config=True).items()):
            ttype = trait.__class__.__name__

            termline = classname + '.' + trait.name

            # Choices or type
            if 'Enum' in ttype:
                # include Enum choices
                termline += ' : ' + '|'.join(repr(x) for x in trait.values)
            else:
                termline += ' : ' + ttype
            lines.append(termline)

            # Default value
            try:
                dv = trait.get_default_value()
                dvr = repr(dv)
            except Exception:
                dvr = dv = None  # ignore defaults we can't construct
            if (dv is not None) and (dvr is not None):
                if len(dvr) > 64:
                    dvr = dvr[:61] + '...'
                # Double up backslashes, so they get to the rendered docs
                dvr = dvr.replace('\\n', '\\\\n')
                lines.append('    Default: `%s`' % dvr)
                lines.append('')

            help = trait.get_metadata('help')
            if help is not None:
                lines.append(indent(dedent(help), 4))
            else:
                lines.append('    No description')

            lines.append('')
    return '\n'.join(lines)
Esempio n. 15
0
def document_config_options(classes):
    lines = []
    for cls in classes:
        classname = cls.__name__
        for k, trait in sorted(cls.class_traits(config=True).items()):
            ttype = trait.__class__.__name__

            termline = classname + '.' + trait.name

            # Choices or type
            if 'Enum' in ttype:
                # include Enum choices
                termline += ' : ' + '|'.join(repr(x) for x in trait.values)
            else:
                termline += ' : ' + ttype
            lines.append(termline)

            # Default value
            try:
                dv = trait.get_default_value()
                dvr = repr(dv)
            except Exception:
                dvr = dv = None # ignore defaults we can't construct
            if (dv is not None) and (dvr is not None):
                if len(dvr) > 64:
                    dvr = dvr[:61]+'...'
                # Double up backslashes, so they get to the rendered docs
                dvr = dvr.replace('\\n', '\\\\n')
                lines.append('    Default: `%s`' % dvr)
                lines.append('')

            help = trait.get_metadata('help')
            if help is not None:
                lines.append(indent(dedent(help), 4))
            else:
                lines.append('    No description')

            lines.append('')
    return '\n'.join(lines)
Esempio n. 16
0
def test_expr_questionmark_pinfo(tmp_path, capsys, RichIPdb):
    from IPython.utils.text import dedent

    rpdb = RichIPdb(stdout=sys.stdout)
    tmp_file = import_tmp_file(rpdb, tmp_path)
    # pinfo
    rpdb.onecmd(rpdb.precmd("foo?"))
    magic_foo_qmark_output = capsys.readouterr().out
    untagged = untag(magic_foo_qmark_output).strip()
    expected_pinfo = re.compile(
        dedent(rf""".*Signature: foo\(arg\)
    Docstring: Foo docstring
    File:      /tmp/.*/{tmp_file.name}
    Type:      function"""))
    assert expected_pinfo.fullmatch(untagged), f"untagged = {untagged!r}"

    # pinfo2
    rpdb.onecmd(rpdb.precmd("foo??"))
    magic_foo_qmark2_output = capsys.readouterr().out
    rpdb.onecmd(rpdb.precmd("%pinfo2 foo"))
    magic_pinfo2_foo_output = capsys.readouterr().out
    assert magic_pinfo2_foo_output == magic_foo_qmark2_output
        plot_mime_type = _mimetypes.get(plot_format, 'image/png')

        for image in images:
            display_data.append((key, {plot_mime_type: image}))

        if args.output:
            for output in ','.join(args.output).split(','):
                output = unicode_to_str(output)
                self.shell.push({output: self._sci.pull(output)})

        for source, data in display_data:
            # source is deprecated in IPython 3.0.
            # specify with kwarg for backward compatibility.
            self._publish_display_data(source=source, data=data)

        if return_output:
            return value


__doc__ = __doc__.format(
    SCILAB_DOC=dedent(ScilabMagics.scilab.__doc__),
    SCILAB_PUSH_DOC=dedent(ScilabMagics.scilab_push.__doc__),
    SCILAB_PULL_DOC=dedent(ScilabMagics.scilab_pull.__doc__)
)


def load_ipython_extension(ip):
    """Load the extension in IPython."""
    ip.register_magics(ScilabMagics)
Esempio n. 18
0
def test_IPython_Pdb_magics_implementation(tmp_path, capsys, RichIPdb):
    """
    We test do_{magic} methods that are concretely implemented by
    IPython.core.debugger.Pdb, and don't default to IPython's
    'InteractiveShell.run_line_magic()' like the other magics.
    """
    from IPython.utils.text import dedent

    rpdb = RichIPdb(stdout=sys.stdout)
    tmp_file = import_tmp_file(rpdb, tmp_path)

    # pdef
    rpdb.do_pdef("foo")
    do_pdef_foo_output = capsys.readouterr().out
    untagged = untag(do_pdef_foo_output).strip()
    assert untagged.endswith("foo(arg)"), untagged
    rpdb.onecmd("%pdef foo")
    magic_pdef_foo_output = capsys.readouterr().out
    untagged = untag(magic_pdef_foo_output).strip()
    assert untagged.endswith("foo(arg)"), untagged

    # pdoc
    rpdb.onecmd("%pdoc foo")
    magic_pdef_foo_output = capsys.readouterr().out
    untagged = untag(magic_pdef_foo_output).strip()
    expected_docstring = dedent("""Class docstring:
        Foo docstring
    Call docstring:
        Call self as a function.""")
    assert untagged == expected_docstring, untagged

    # pfile
    rpdb.onecmd("%pfile foo")
    magic_pfile_foo_output = capsys.readouterr().out
    untagged = untag(magic_pfile_foo_output).strip()
    tmp_file_content = Path(tmp_file).read_text().strip()
    assert untagged == tmp_file_content

    # pinfo
    rpdb.onecmd("%pinfo foo")
    magic_pinfo_foo_output = capsys.readouterr().out
    untagged = untag(magic_pinfo_foo_output).strip()
    expected_pinfo = dedent(f"""Signature: foo(arg)
    Docstring: Foo docstring
    File:      {tmp_file.absolute()}
    Type:      function""")
    assert untagged == expected_pinfo, untagged

    # pinfo2
    rpdb.onecmd("%pinfo2 foo")
    magic_pinfo2_foo_output = capsys.readouterr().out
    untagged = untag(magic_pinfo2_foo_output).strip()
    expected_pinfo2 = re.compile(
        dedent(rf"""Signature: foo\(arg\)
    Source:\s*
    %s
    File:      {tmp_file.absolute()}
    Type:      function""") % re.escape(tmp_file_content))
    assert expected_pinfo2.fullmatch(untagged), untagged

    # psource
    rpdb.onecmd("%psource foo")
    magic_psource_foo_output = capsys.readouterr().out
    untagged = untag(magic_psource_foo_output).strip()
    expected_psource = '''def foo(arg):
    """Foo docstring"""
    pass'''
    assert untagged == expected_psource, untagged
Esempio n. 19
0
            gist_url, jsf_url = _create_gist_fiddle(code_tmp)
            gist_html = """<br><a href="{}" target="_blank">gist link</a>\n"""
            code += gist_html.format(gist_url)
            jsf_html = """<br><a href="{}" target="_blank">jsfiddle link</a>\n"""
            code += jsf_html.format(jsf_url)

        # If embedfiddle is selected then create an iframe with  ##
        # the final result from jsfiddle.net
        if args.embedfiddle:
            code += """<br><iframe src="{}" style="height:400px; width: 100%;"></iframe>""".format(
                jsf_url)

        # Display the results in the output area
        try:
            display(HTML(code))
            if args.print:
                print(code_print)
        except:
            print("Something went wrong.")
            print(
                "Please, see your browser javascript console for more details."
            )


__doc__ = __doc__.format(BRYTHON_DOC=dedent(BrythonMagics.brython.__doc__))


def load_ipython_extension(ip):
    """Load the extension in IPython."""
    ip.register_magics(BrythonMagics)
Esempio n. 20
0
        dist = Distribution()
        config_files = dist.find_config_files()
        try:
            config_files.remove("setup.cfg")
        except ValueError:
            pass
        dist.parse_config_files(config_files)
        build_extension = build_ext(dist)
        build_extension.finalize_options()
        return build_extension

    @staticmethod
    def clean_annotated_html(html):
        """Clean up the annotated HTML source.

        Strips the link to the generated C or C++ file, which we do not
        present to the user.
        """
        r = re.compile('<p>Raw output: <a href="(.*)">(.*)</a>')
        html = "\n".join(l for l in html.splitlines() if not r.match(l))
        return html


__doc__ = __doc__.format(
    # rST doesn't see the -+ flag as part of an option list, so we
    # hide it from the module-level docstring.
    CYTHON_DOC=dedent(CythonMagics.cython.__doc__.replace("-+, --cplus", "--cplus    ")),
    CYTHON_INLINE_DOC=dedent(CythonMagics.cython_inline.__doc__),
    CYTHON_PYXIMPORT_DOC=dedent(CythonMagics.cython_pyximport.__doc__),
)
Esempio n. 21
0
        if args.output:
            for output in ','.join(args.output).split(','):
                output = unicode_to_str(output)
                self.shell.push({output: self._oct.get(output)})

        for source, data in display_data:
            self._publish_display_data(source, data)

        if return_output:
            ans = self._oct.get('_')

            # Unfortunately, Octave doesn't have a "None" object,
            # so we can't return any NaN outputs
            if np.isscalar(ans) and np.isnan(ans):
                ans = None

            return ans


__doc__ = __doc__.format(
    OCTAVE_DOC = dedent(OctaveMagics.octave.__doc__),
    OCTAVE_PUSH_DOC = dedent(OctaveMagics.octave_push.__doc__),
    OCTAVE_PULL_DOC = dedent(OctaveMagics.octave_pull.__doc__)
    )


def load_ipython_extension(ip):
    """Load the extension in IPython."""
    ip.register_magics(OctaveMagics)
Esempio n. 22
0
            publish_display_data(data=disp_d, source=tag)

        # this will keep a reference to the display_data
        # which might be useful to other objects who happen to use
        # this method

        if self.cache_display_data:
            self.display_cache = display_data

        # if in line mode and return_output, return the result as an ndarray
        if return_output and not args.noreturn:
            if result != ri.NULL:
                return self.Rconverter(result, dataframe=False)

__doc__ = __doc__.format(
    R_DOC=dedent(RMagics.R.__doc__),
    RPUSH_DOC=dedent(RMagics.Rpush.__doc__),
    RPULL_DOC=dedent(RMagics.Rpull.__doc__),
    RGET_DOC=dedent(RMagics.Rget.__doc__)
)


def load_ipython_extension(ip):
    """Load the extension in IPython."""
    warnings.warn("The rmagic extension in IPython is deprecated in favour of "
                  "rpy2.ipython. If available, that will be loaded instead.\n"
                  "http://rpy.sourceforge.net/")
    try:
        import rpy2.ipython
    except ImportError:
        pass  # Fall back to our own implementation for now
Esempio n. 23
0
        dist = Distribution()
        config_files = dist.find_config_files()
        try:
            config_files.remove('setup.cfg')
        except ValueError:
            pass
        dist.parse_config_files(config_files)
        build_extension = build_ext(dist)
        build_extension.finalize_options()
        return build_extension

    @staticmethod
    def clean_annotated_html(html):
        """Clean up the annotated HTML source.

        Strips the link to the generated C or C++ file, which we do not
        present to the user.
        """
        r = re.compile('<p>Raw output: <a href="(.*)">(.*)</a>')
        html = '\n'.join(l for l in html.splitlines() if not r.match(l))
        return html

__doc__ = __doc__.format(
                # rST doesn't see the -+ flag as part of an option list, so we
                # hide it from the module-level docstring.
                CYTHON_DOC = dedent(CythonMagics.cython.__doc__\
                            .replace('-+, --cplus','--cplus    ')),
                CYTHON_INLINE_DOC = dedent(CythonMagics.cython_inline.__doc__),
                CYTHON_PYXIMPORT_DOC = dedent(CythonMagics.cython_pyximport.__doc__),
)
Esempio n. 24
0
        for tag, disp_d in display_data:
            publish_display_data(data=disp_d, source=tag)

        # this will keep a reference to the display_data
        # which might be useful to other objects who happen to use
        # this method

        if self.cache_display_data:
            self.display_cache = display_data

        # if in line mode and return_output, return the result as an ndarray
        if return_output and not args.noreturn:
            if result != ri.NULL:
                return self.Rconverter(result, dataframe=False)

__doc__ = __doc__.format(
                R_DOC = dedent(RMagics.R.__doc__),
                RPUSH_DOC = dedent(RMagics.Rpush.__doc__),
                RPULL_DOC = dedent(RMagics.Rpull.__doc__),
                RGET_DOC = dedent(RMagics.Rget.__doc__)
)


def load_ipython_extension(ip):
    """Load the extension in IPython."""
    ip.register_magics(RMagics)
    # Initialising rpy2 interferes with readline. Since, at this point, we've
    # probably just loaded rpy2, we reset the delimiters. See issue gh-2759.
    if ip.has_readline:
        ip.readline.set_completer_delims(ip.readline_delims)
Esempio n. 25
0
            # Each cell is a *single* input, regardless of how many lines it has
            ipself.execution_count += 1
        if re.search(r'get_ipython\(\)\.magic\(u?["\']%?autopx', cell):
            self._disable_autopx()
            return False
        else:
            try:
                result = self.view.execute(cell, silent=False, block=False)
            except:
                ipself.showtraceback()
                return True
            else:
                if self.view.block:
                    try:
                        result.get()
                    except:
                        self.shell.showtraceback()
                        return True
                    else:
                        with ipself.builtin_trap:
                            result.display_outputs()
                return False


__doc__ = __doc__.format(
                AUTOPX_DOC = dedent(ParallelMagics.autopx.__doc__),
                PX_DOC = dedent(ParallelMagics.px.__doc__),
                RESULT_DOC = dedent(ParallelMagics.result.__doc__),
                CONFIG_DOC = dedent(ParallelMagics.pxconfig.__doc__),
)
            for key in params['input'].keys():
                pre_call += "{0} = {1}\n".format(key, params['input'][key])
            pre_call += "## End of variables defined in the IPython namespace\n\n"

        post_call = "\n</script>\n"
        post_call += """<script type="text/javascript">brython({0});</script>\n""".format(options)
        post_call += """<div id="{0}">{1}</div>""".format(str(params['container']), 
                                                          markup)
        ################################
        ## Create the final HTML code ##
        ################################
        code = ''.join((pre_call, code, post_call))
        
        ############################################
        ## Display the results in the output area ##
        ############################################
        try:
            display(HTML(code))
            if args.print:
                print(code)
        except:
            print("Something went wrong.")
            print("Please, see your browser javascript console for more details.")

__doc__ = __doc__.format(
    BRYTHON_DOC = dedent(BrythonMagics.brython.__doc__))

def load_ipython_extension(ip):
    """Load the extension in IPython."""
    ip.register_magics(BrythonMagics)
Esempio n. 27
0
            display(
                HTML(
                    data=(
                        '<div class="text-center"><strong>'
                        '<a style="{0}" target="_" href={1}>Python Tutor</a>'
                        '</strong></div>'.format(css, url)
                    )
                )
            )
        elif args.tab:
            # Open up a new tab in the browser to pythontutor URL
            webbrowser.open_new_tab(url)
        else:
            # Display the results in the output area
            if args.height:
                display(IFrame(
                    url, height = int(args.height[0]), width = "100%"
                ))
            else:
                display(IFrame(url, height = 350, width = "100%"))
        if args.run:
			# Run cell like normal
            self.shell.run_cell(cell)

__doc__ = __doc__.format(
    tutormagic_DOC = dedent(TutorMagics.tutor.__doc__))

def load_ipython_extension(ip):
    """Load the extension in IPython."""
    ip.register_magics(TutorMagics)
Esempio n. 28
0
        build_extension.finalize_options()
        if temp_dir:
            temp_dir = py3compat.cast_bytes_py2(temp_dir, encoding=sys.getfilesystemencoding())
            build_extension.build_temp = temp_dir
        if lib_dir:
            lib_dir = py3compat.cast_bytes_py2(lib_dir, encoding=sys.getfilesystemencoding())
            build_extension.build_lib = lib_dir
        if extension is not None:
            build_extension.extensions = [extension]
        return build_extension

    @staticmethod
    def clean_annotated_html(html):
        """Clean up the annotated HTML source.

        Strips the link to the generated C or C++ file, which we do not
        present to the user.
        """
        r = re.compile('<p>Raw output: <a href="(.*)">(.*)</a>')
        html = '\n'.join(l for l in html.splitlines() if not r.match(l))
        return html

__doc__ = __doc__.format(
    # rST doesn't see the -+ flag as part of an option list, so we
    # hide it from the module-level docstring.
    CYTHON_DOC=dedent(CythonMagics.cython.__doc__\
                                  .replace('-+, --cplus', '--cplus    ')),
    CYTHON_INLINE_DOC=dedent(CythonMagics.cython_inline.__doc__),
    CYTHON_PYXIMPORT_DOC=dedent(CythonMagics.cython_pyximport.__doc__),
)
Esempio n. 29
0
                )
        else:
            lang = "python3"

        url = "http://pythontutor.com/iframe-embed.html#code="
        url += quote(cell)
        url += "&origin=opt-frontend.js&cumulative=false&heapPrimitives=false"
        url += "&textReferences=false&"
        if lang == "python3":
            url += "py=3&rawInputLstJSON=%5B%5D&curInstr=0&codeDivWidth=50%25&codeDivHeight=100%25"
        if lang == "python2":
            url += "py=2&rawInputLstJSON=%5B%5D&curInstr=0&codeDivWidth=50%25&codeDivHeight=100%25"
        if lang == "java":
            url += "py=java&rawInputLstJSON=%5B%5D&curInstr=0&codeDivWidth=50%25&codeDivHeight=100%25"
        if lang == "javascript":
            url += "py=js&rawInputLstJSON=%5B%5D&curInstr=0&codeDivWidth=50%25&codeDivHeight=100%25"

        # Display the results in the output area
        if args.height:
            display(IFrame(url, height=int(args.height[0]), width="100%"))
        else:
            display(IFrame(url, height=350, width="100%"))


__doc__ = __doc__.format(tutormagic_DOC=dedent(TutorMagics.tutor.__doc__))


def load_ipython_extension(ip):
    """Load the extension in IPython."""
    ip.register_magics(TutorMagics)
Esempio n. 30
0
                raise ValueError(
                    "{} not supported. Only the following options are allowed: "
                    "'python2', 'python3', 'java', 'javascript'".format(
                        args.lang[0]))
        else:
            lang = "python3"

        url = "http://pythontutor.com/iframe-embed.html#code="
        url += quote(cell)
        url += "&origin=opt-frontend.js&cumulative=false&heapPrimitives=false"
        url += "&textReferences=false&"
        if lang == "python3":
            url += "py=3&rawInputLstJSON=%5B%5D&curInstr=0&codeDivWidth=50%25&codeDivHeight=100%25"
        if lang == "python2":
            url += "py=2&rawInputLstJSON=%5B%5D&curInstr=0&codeDivWidth=50%25&codeDivHeight=100%25"
        if lang == "java":
            url += "py=java&rawInputLstJSON=%5B%5D&curInstr=0&codeDivWidth=50%25&codeDivHeight=100%25"
        if lang == "javascript":
            url += "py=js&rawInputLstJSON=%5B%5D&curInstr=0&codeDivWidth=50%25&codeDivHeight=100%25"

        # Display the results in the output area
        display(IFrame(url, height=350, width="90%"))


__doc__ = __doc__.format(tutormagic_DOC=dedent(TutorMagics.tutor.__doc__))


def load_ipython_extension(ip):
    """Load the extension in IPython."""
    ip.register_magics(TutorMagics)
Esempio n. 31
0
                try:
                    size = (plot_width, plot_height)
                    image = self._fix_gnuplot_svg_size(image, size=size)
                except Exception:
                    pass
            display_data.append((key, {plot_mime_type: image}))

        if args.output:
            for output in ','.join(args.output).split(','):
                output = unicode_to_str(output)
                self.shell.push({output: self._oct.pull(output)})

        for source, data in display_data:
            # source is deprecated in IPython 3.0.
            # specify with kwarg for backward compatibility.
            self._publish_display_data(source=source, data=data)

        if return_output:
            return value


__doc__ = __doc__.format(
    OCTAVE_DOC=dedent(OctaveMagics.octave.__doc__),
    OCTAVE_PUSH_DOC=dedent(OctaveMagics.octave_push.__doc__),
    OCTAVE_PULL_DOC=dedent(OctaveMagics.octave_pull.__doc__))


def load_ipython_extension(ip):
    """Load the extension in IPython."""
    ip.register_magics(OctaveMagics)
Esempio n. 32
0
 def _fill_text(self, text, width, indent):
     return argparse.RawDescriptionHelpFormatter._fill_text(self, dedent(text), width, indent)
Esempio n. 33
0
        code = code_print

        # If fiddle is selected then create a gist and a fiddle
        if args.fiddle or args.embedfiddle:
            gist_url, jsf_url = create_gist_fiddle(code_tmp)
            gist_html = """<br><a href="{}" target="_blank">gist link</a>\n"""
            code += gist_html.format(gist_url)
            jsf_html = """<br><a href="{}" target="_blank">jsfiddle link</a>\n"""
            code += jsf_html.format(jsf_url)

        # If embedfiddle is selected then create an iframe with  ##
        # the final result from jsfiddle.net
        if args.embedfiddle:
            code += """<br><iframe src="{}" style="height:400px; width: 100%;"></iframe>""".format(jsf_url)

        # Display the results in the output area
        try:
            display(HTML(code))
            if args.print:
                print(code_print)
        except:
            print("Something went wrong.")
            print("Please, see your browser javascript console for more details.")

__doc__ = __doc__.format(
    BRYTHON_DOC = dedent(BrythonMagics.brython.__doc__))

def load_ipython_extension(ip):
    """Load the extension in IPython."""
    ip.register_magics(BrythonMagics)
Esempio n. 34
0
 def _fill_text(self, text, width, indent):
     return argparse.RawDescriptionHelpFormatter._fill_text(
         self, dedent(text), width, indent)
Esempio n. 35
0
            if args.lang[0] in ['python2', 'python3', 'java', 'javascript']:
                lang = args.lang[0]
            else:
                raise ValueError("{} not supported. Only the following options are allowed: "
                                 "'python2', 'python3', 'java', 'javascript'".format(args.lang[0]))
        else:
            lang = "python3"
        
        url = "http://pythontutor.com/iframe-embed.html#code="
        url += quote(cell)
        url += "&origin=opt-frontend.js&cumulative=false&heapPrimitives=false"
        url += "&textReferences=false&"
        if lang == "python3":
            url += "py=3&rawInputLstJSON=%5B%5D&curInstr=0&codeDivWidth=50%25&codeDivHeight=100%25"
        if lang == "python2":
            url += "py=2&rawInputLstJSON=%5B%5D&curInstr=0&codeDivWidth=50%25&codeDivHeight=100%25"
        if lang == "java":
            url += "py=java&rawInputLstJSON=%5B%5D&curInstr=0&codeDivWidth=50%25&codeDivHeight=100%25"
        if lang == "javascript":
            url += "py=js&rawInputLstJSON=%5B%5D&curInstr=0&codeDivWidth=50%25&codeDivHeight=100%25"
        
        # Display the results in the output area
        display(IFrame(url, height = 350, width = "90%"))
        
__doc__ = __doc__.format(
    tutormagic_DOC = dedent(TutorMagics.tutor.__doc__))

def load_ipython_extension(ip):
    """Load the extension in IPython."""
    ip.register_magics(TutorMagics)