• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python v4.new_code_cell函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中nbformat.v4.new_code_cell函数的典型用法代码示例。如果您正苦于以下问题:Python new_code_cell函数的具体用法?Python new_code_cell怎么用?Python new_code_cell使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了new_code_cell函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_html_collapsible_headings

 def test_html_collapsible_headings(self):
     """Test exporter for inlining collapsible_headings"""
     nb = v4.new_notebook(cells=[
         v4.new_markdown_cell(source=('# level 1 heading')),
         v4.new_code_cell(source='a = range(1,10)'),
         v4.new_markdown_cell(source=('## level 2 heading')),
         v4.new_code_cell(source='a = range(1,10)'),
         v4.new_markdown_cell(source=('### level 3 heading')),
         v4.new_code_cell(source='a = range(1,10)'),
     ])
     self.check_stuff_gets_embedded(
         nb, 'html_ch', to_be_included=['collapsible_headings'])
开发者ID:hagne,项目名称:IPython-notebook-extensions,代码行数:12,代码来源:test_exporters.py


示例2: lines_to_notebook

def lines_to_notebook(lines, name=None):
    """
    Convert the lines of an m file into an IPython notebook

    Parameters
    ----------
    lines : list
        A list of strings. Each element is a line in the m file

    Returns
    -------
    notebook : an IPython NotebookNode class instance, containing the
    information required to create a file


    """
    source = []
    md = np.empty(len(lines), dtype=object)
    new_cell = np.empty(len(lines), dtype=object)
    for idx, l in enumerate(lines):
        new_cell[idx], md[idx], this_source = format_line(l)
        # Transitions between markdown and code and vice-versa merit a new
        # cell, even if no newline, or "%%" is found. Make sure not to do this
        # check for the very first line!
        if idx>1 and not new_cell[idx]:
            if md[idx] != md[idx-1]:
                new_cell[idx] = True

        source.append(this_source)
    # This defines the breaking points between cells:
    new_cell_idx = np.hstack([np.where(new_cell)[0], -1])

    # Listify the sources:
    cell_source = [source[new_cell_idx[i]:new_cell_idx[i+1]]
                   for i in range(len(new_cell_idx)-1)]
    cell_md = [md[new_cell_idx[i]] for i in range(len(new_cell_idx)-1)]
    cells = []

    # Append the notebook with loading matlab magic extension
    notebook_head = "import pymatbridge as pymat\n" + "ip = get_ipython()\n" \
                    + "pymat.load_ipython_extension(ip)"
    cells.append(nbformat.new_code_cell(notebook_head))#, language='python'))

    for cell_idx, cell_s in enumerate(cell_source):
        if cell_md[cell_idx]:
            cells.append(nbformat.new_markdown_cell(cell_s))
        else:
            cell_s.insert(0, '%%matlab\n')
            cells.append(nbformat.new_code_cell(cell_s))#, language='matlab'))

    #ws = nbformat.new_worksheet(cells=cells)
    notebook = nbformat.new_notebook(cells=cells)
    return notebook
开发者ID:JasonCLu,项目名称:python-matlab-bridge,代码行数:53,代码来源:publish.py


示例3: test_html_collapsible_headings

    def test_html_collapsible_headings(self):
        """Test exporter for inlining collapsible_headings"""
        nb = v4.new_notebook(cells=[
            v4.new_markdown_cell(source=('# level 1 heading')),
            v4.new_code_cell(source='a = range(1,10)'),
            v4.new_markdown_cell(source=('## level 2 heading')),
            v4.new_code_cell(source='a = range(1,10)'),
            v4.new_markdown_cell(source=('### level 3 heading')),
            v4.new_code_cell(source='a = range(1,10)'),
        ])

        def check(byte_string, root_node):
            assert b'collapsible_headings' in byte_string

        self.check_html(nb, 'html_ch', check_func=check)
开发者ID:codegenerator-tools,项目名称:jupyter_contrib_nbextensions,代码行数:15,代码来源:test_exporters.py


示例4: test_pretty_print_code_cell

def test_pretty_print_code_cell():
    cell = v4.new_code_cell(source='def foo():\n    return 4',
        execution_count=3,
        outputs=[
            v4.new_output('stream', name='stdout', text='some\ntext'),
            v4.new_output('display_data', {'text/plain': 'hello display'}),
        ]
    )

    io = StringIO()
    pp.pretty_print_value_at(cell, "/cells/0", "+", io)
    text = io.getvalue()
    lines = text.splitlines()

    assert lines == [
        '+code cell:',
        '+  execution_count: 3',
        '+  source:',
        '+    def foo():',
        '+        return 4',
        '+  outputs:',
        '+    output 0:',
        '+      output_type: stream',
        '+      name: stdout',
        '+      text:',
        '+        some',
        '+        text',
        '+    output 1:',
        '+      output_type: display_data',
        '+      data:',
        '+        text/plain: hello display',
    ]
开发者ID:jupyter,项目名称:nbdime,代码行数:32,代码来源:test_prettyprint.py


示例5: notebook

    def notebook(self, s):
        """Export and convert IPython notebooks.

        This function can export the current IPython history to a notebook file.
        For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".

        The -e or --export flag is deprecated in IPython 5.2, and will be
        removed in the future.
        """
        args = magic_arguments.parse_argstring(self.notebook, s)

        from nbformat import write, v4

        cells = []
        hist = list(self.shell.history_manager.get_range())
        if(len(hist)<=1):
            raise ValueError('History is empty, cannot export')
        for session, execution_count, source in hist[:-1]:
            cells.append(v4.new_code_cell(
                execution_count=execution_count,
                source=source
            ))
        nb = v4.new_notebook(cells=cells)
        with io.open(args.filename, 'w', encoding='utf-8') as f:
            write(nb, f, version=4)
开发者ID:BarnetteME1,项目名称:DnD-stuff,代码行数:25,代码来源:basic.py


示例6: build_notebook

    def build_notebook(self, with_json_outputs=False):
        """Build a notebook in memory for use with preprocessor tests"""

        outputs = [
            nbformat.new_output("stream", name="stdout", text="a"),
            nbformat.new_output("display_data", data={'text/plain': 'b'}),
            nbformat.new_output("stream", name="stdout", text="c"),
            nbformat.new_output("stream", name="stdout", text="d"),
            nbformat.new_output("stream", name="stderr", text="e"),
            nbformat.new_output("stream", name="stderr", text="f"),
            nbformat.new_output("display_data", data={'image/png': 'Zw=='}), # g
            nbformat.new_output("display_data", data={'application/pdf': 'aA=='}), # h
        ]
        if with_json_outputs:
            outputs.extend([
                nbformat.new_output(
                    "display_data", data={'application/json': [1, 2, 3]}
                ), # j
                nbformat.new_output(
                    "display_data", data={'application/json': {'a': 1, 'c': {'b': 2}}}
                ), # k
                nbformat.new_output(
                    "display_data", data={'application/json': 'abc'}
                ), # l
                nbformat.new_output(
                    "display_data", data={'application/json': 15.03}
                ), # m
            ])

        cells=[nbformat.new_code_cell(source="$ e $", execution_count=1, outputs=outputs),
               nbformat.new_markdown_cell(source="$ e $")]

        return nbformat.new_notebook(cells=cells)
开发者ID:jupyter,项目名称:nbconvert,代码行数:33,代码来源:base.py


示例7: create_notebook

def create_notebook(name, cells):
    nb = new_notebook()
    for cell in cells:
        nb.cells.append(new_code_cell(source=cell))

    with open(name, "w") as fh:
        write(nb, fh, 4)
开发者ID:alaindomissy,项目名称:nbflow,代码行数:7,代码来源:util.py


示例8: build_notebook

    def build_notebook(self):
        """Build a reveal slides notebook in memory for use with tests.
        Overrides base in PreprocessorTestsBase"""

        outputs = [nbformat.new_output(output_type="stream", name="stdout", text="a")]

        slide_metadata = {'slideshow' : {'slide_type': 'slide'}}
        subslide_metadata = {'slideshow' : {'slide_type': 'subslide'}}

        cells=[nbformat.new_code_cell(source="", execution_count=1, outputs=outputs),
               nbformat.new_markdown_cell(source="", metadata=slide_metadata),
               nbformat.new_code_cell(source="", execution_count=2, outputs=outputs),
               nbformat.new_markdown_cell(source="", metadata=slide_metadata),
               nbformat.new_markdown_cell(source="", metadata=subslide_metadata)]

        return nbformat.new_notebook(cells=cells)
开发者ID:alope107,项目名称:nbconvert,代码行数:16,代码来源:test_revealhelp.py


示例9: test_preprocessor_collapsible_headings

def test_preprocessor_collapsible_headings():
    """Test collapsible_headings preprocessor."""
    # check import shortcut
    from jupyter_contrib_nbextensions.nbconvert_support import CollapsibleHeadingsPreprocessor  # noqa
    cells = []
    for lvl in range(6, 1, -1):
        for collapsed in (True, False):
            cells.extend([
                nbf.new_markdown_cell(
                    source='{} {} heading level {}'.format(
                        '#' * lvl,
                        'Collapsed' if collapsed else 'Uncollapsed',
                        lvl),
                    metadata={'heading_collapsed': True} if collapsed else {}),
                nbf.new_markdown_cell(source='\n'.join([
                    'want hidden' if collapsed else 'want to see',
                    'what I mean',
                ])),
                nbf.new_code_cell(source='\n'.join([
                    'want hidden' if collapsed else 'want to see',
                    'what I mean',
                ])),
            ])
    notebook_node = nbf.new_notebook(cells=cells)
    body, resources = export_through_preprocessor(
        notebook_node, CollapsibleHeadingsPreprocessor, RSTExporter, 'rst')
    assert_not_in('hidden', body, 'check text hidden by collapsed headings')
    assert_in('want to see', body, 'check for text under uncollapsed headings')
开发者ID:flipphillips,项目名称:IPython-notebook-extensions,代码行数:28,代码来源:test_preprocessors.py


示例10: create_code_cell

def create_code_cell():
    source = """print("something")
### BEGIN SOLUTION
print("hello")
### END SOLUTION"""
    cell = new_code_cell(source=source)
    return cell
开发者ID:DrFrankieD,项目名称:nbgrader-peer_assessment,代码行数:7,代码来源:__init__.py


示例11: test_raw_template_dynamic_attr_reversed

    def test_raw_template_dynamic_attr_reversed(self):
        """
        Test that template_file and raw_template traitlets play nicely together.
        - source assigns raw_template default first, then template_file
        - checks that the raw_template overrules template_file if set
        - checks that once raw_template is set to '', template_file returns
        """
        nb = v4.new_notebook()
        nb.cells.append(v4.new_code_cell("some_text"))

        class AttrDynamicExporter(TemplateExporter):
            @default('raw_template')
            def _raw_template_default(self):
                return raw_template

            @default('template_file')
            def _template_file_default(self):
                return "rst.tpl"

        exporter_attr_dynamic = AttrDynamicExporter()
        output_attr_dynamic, _ = exporter_attr_dynamic.from_notebook_node(nb)
        assert "blah" in output_attr_dynamic
        exporter_attr_dynamic.raw_template = ''
        assert exporter_attr_dynamic.template_file == "rst.tpl"
        output_attr_dynamic, _ = exporter_attr_dynamic.from_notebook_node(nb)
        assert "blah" not in output_attr_dynamic
开发者ID:jupyter,项目名称:nbconvert,代码行数:26,代码来源:test_templateexporter.py


示例12: setUp

    def setUp(self):
        nbdir = self.notebook_dir
        
        if not os.path.isdir(pjoin(nbdir, 'foo')):
            subdir = pjoin(nbdir, 'foo')

            os.mkdir(subdir)

            # Make sure that we clean this up when we're done.
            # By using addCleanup this will happen correctly even if we fail
            # later in setUp.
            @self.addCleanup
            def cleanup_dir():
                shutil.rmtree(subdir, ignore_errors=True)

        nb = new_notebook()
        
        nb.cells.append(new_markdown_cell(u'Created by test ³'))
        cc1 = new_code_cell(source=u'print(2*6)')
        cc1.outputs.append(new_output(output_type="stream", text=u'12'))
        cc1.outputs.append(new_output(output_type="execute_result",
            data={'image/png' : png_green_pixel},
            execution_count=1,
        ))
        nb.cells.append(cc1)
        
        with io.open(pjoin(nbdir, 'foo', 'testnb.ipynb'), 'w',
                     encoding='utf-8') as f:
            write(nb, f, version=4)

        self.nbconvert_api = NbconvertAPI(self.request)
开发者ID:BarnetteME1,项目名称:DnD-stuff,代码行数:31,代码来源:test_nbconvert_handlers.py


示例13: test_preprocessor_codefolding

def test_preprocessor_codefolding():
    """Test codefolding preprocessor."""
    # check import shortcut
    from jupyter_contrib_nbextensions.nbconvert_support import CodeFoldingPreprocessor  # noqa
    notebook_node = nbf.new_notebook(cells=[
        nbf.new_code_cell(source='\n'.join(["# Codefolding test 1",
                                            "'AXYZ12AXY'"]),
                          metadata={"code_folding": [0]}),
        nbf.new_code_cell(source='\n'.join(["# Codefolding test 2",
                                            "def myfun():",
                                            "    'GR4CX32ZT'"]),
                          metadata={"code_folding": [1]}),
    ])
    body, resources = export_through_preprocessor(
        notebook_node, CodeFoldingPreprocessor, RSTExporter, 'rst')
    assert_not_in('AXYZ12AXY', body, 'check firstline fold has worked')
    assert_not_in('GR4CX32ZT', body, 'check function fold has worked')
开发者ID:flipphillips,项目名称:IPython-notebook-extensions,代码行数:17,代码来源:test_preprocessors.py


示例14: test_htmltoc2

 def test_htmltoc2(self):
     """Test exporter for adding table of contents"""
     nb = v4.new_notebook(cells=[
         v4.new_code_cell(source="a = 'world'"),
         v4.new_markdown_cell(source="# Heading"),
     ])
     self.check_stuff_gets_embedded(
         nb, 'html_toc', to_be_included=['toc2'])
开发者ID:hagne,项目名称:IPython-notebook-extensions,代码行数:8,代码来源:test_exporters.py


示例15: get

    def get(self, cid):
        """Retrieve (and build) notebook for a single contribution [internal].
        ---
        operationId: get_entry
        parameters:
            - name: cid
              in: path
              type: string
              pattern: '^[a-f0-9]{24}$'
              required: true
              description: contribution ID (ObjectId)
        responses:
            200:
                description: single notebook
                schema:
                    $ref: '#/definitions/NotebooksSchema'
        """
        try:
            nb = Notebooks.objects.get(id=cid)
            nb.restore()
        except DoesNotExist:
            cells = [
                nbf.new_code_cell(
                    "# provide apikey to `load_client` in order to connect to api.mpcontribs.org\n"
                    "# or use bravado (see https://mpcontribs.org/api)\n"
                    "from mpcontribs.client import load_client\n"
                    "client = load_client()"
                ), nbf.new_code_cell(
                    "from mpcontribs.io.archieml.mpfile import MPFile\n"
                    f"result = client.contributions.get_entry(cid='{cid}').response().result\n"
                    "mpfile = MPFile.from_contribution(result)"
                )
            ]
            for typ in ['h', 't', 'g', 's']:
                cells.append(nbf.new_code_cell(f"mpfile.{typ}data"))
            nb = nbf.new_notebook()
            nb['cells'] = cells
            exprep.preprocess(nb, {})
            nb = Notebooks(**nb)
            nb.id = cid # to link to the according contribution
            nb.save() # calls Notebooks.clean()

        del nb.id
        return nb
开发者ID:materialsproject,项目名称:MPContribs,代码行数:44,代码来源:views.py


示例16: test_embedhtml

 def test_embedhtml(self):
     """Test exporter for embedding images into HTML"""
     nb = v4.new_notebook(cells=[
         v4.new_code_cell(source="a = 'world'"),
         v4.new_markdown_cell(
             source="![testimage]({})".format(path_in_data('icon.png'))
         ),
     ])
     self.check_stuff_gets_embedded(
         nb, 'html_embed', to_be_included=['base64'])
开发者ID:hagne,项目名称:IPython-notebook-extensions,代码行数:10,代码来源:test_exporters.py


示例17: test_raw_template_assignment

 def test_raw_template_assignment(self):
     """
     Test `raw_template` assigned after the fact on non-custom Exporter.
     """
     nb = v4.new_notebook()
     nb.cells.append(v4.new_code_cell("some_text"))
     exporter_assign = TemplateExporter()
     exporter_assign.raw_template = raw_template
     output_assign, _ = exporter_assign.from_notebook_node(nb)
     assert "blah" in output_assign
开发者ID:jupyter,项目名称:nbconvert,代码行数:10,代码来源:test_templateexporter.py


示例18: test_raw_template_constructor

    def test_raw_template_constructor(self):
        """
        Test `raw_template` as a keyword argument in the exporter constructor.
        """
        nb = v4.new_notebook()
        nb.cells.append(v4.new_code_cell("some_text"))

        output_constructor, _ = TemplateExporter(
            raw_template=raw_template).from_notebook_node(nb)
        assert "blah" in output_constructor
开发者ID:jupyter,项目名称:nbconvert,代码行数:10,代码来源:test_templateexporter.py


示例19: test_present_code_cell

def test_present_code_cell():
    cell = v4.new_code_cell(source='def foo()',
        outputs=[
            v4.new_output('stream', name='stdout', text='some\ntext'),
            v4.new_output('display_data', {'text/plain': 'hello display'}),
        ]
    )
    lines = pp.present_value('+ ', cell)
    assert lines[0] == ''
    assert lines[1] == '+ code cell:'
开发者ID:gahjelle,项目名称:nbdime,代码行数:10,代码来源:test_prettyprint.py


示例20: py_to_ipynb

def py_to_ipynb(source, dest):
    # Create the code cells by parsing the file in input
    cells = []
    for c in parse_py(source):
        cells.append(new_code_cell(source=c))

    # This creates a V4 Notebook with the code cells extracted above
    nb0 = new_notebook(cells=cells, metadata={"language": "python"})

    with codecs.open(dest, encoding="utf-8", mode="w") as f:
        nbformat.write(nb0, f, 4)
开发者ID:ChunHungLiu,项目名称:tensorflow_tutorials,代码行数:11,代码来源:convert.py



注:本文中的nbformat.v4.new_code_cell函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python v4.new_markdown_cell函数代码示例发布时间:2022-05-27
下一篇:
Python nbformat.writes函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap