本文整理汇总了Python中nbformat.v4.new_markdown_cell函数的典型用法代码示例。如果您正苦于以下问题:Python new_markdown_cell函数的具体用法?Python new_markdown_cell怎么用?Python new_markdown_cell使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了new_markdown_cell函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: add_sec_label
def add_sec_label(cell: NotebookNode, nbname) -> Sequence[NotebookNode]:
"""Adds a Latex \\label{} under the chapter heading.
This takes the first cell of a notebook, and expects it to be a Markdown
cell starting with a level 1 heading. It inserts a label with the notebook
name just underneath this heading.
"""
assert cell.cell_type == 'markdown', cell.cell_type
lines = cell.source.splitlines()
if lines[0].startswith('# '):
header_lines = 1
elif len(lines) > 1 and lines[1].startswith('==='):
header_lines = 2
else:
raise NoHeader
header = '\n'.join(lines[:header_lines])
intro_remainder = '\n'.join(lines[header_lines:]).strip()
res = [
new_markdown_cell(header),
new_latex_cell('\label{sec:%s}' % nbname)
]
res[0].metadata = cell.metadata
if intro_remainder:
res.append(new_markdown_cell(intro_remainder))
return res
开发者ID:takluyver,项目名称:bookbook,代码行数:26,代码来源:latex.py
示例2: 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
示例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)'),
])
self.check_stuff_gets_embedded(
nb, 'html_ch', to_be_included=['collapsible_headings'])
开发者ID:hagne,项目名称:IPython-notebook-extensions,代码行数:12,代码来源:test_exporters.py
示例4: 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
示例5: 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
示例6: test_very_long_cells
def test_very_long_cells(self):
"""
Torture test that long cells do not cause issues
"""
lorem_ipsum_text = textwrap.dedent("""\
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec
dignissim, ipsum non facilisis tempus, dui felis tincidunt metus,
nec pulvinar neque odio eget risus. Nulla nisi lectus, cursus
suscipit interdum at, ultrices sit amet orci. Mauris facilisis
imperdiet elit, vitae scelerisque ipsum dignissim non. Integer
consequat malesuada neque sit amet pulvinar. Curabitur pretium
ut turpis eget aliquet. Maecenas sagittis lacus sed lectus
volutpat, eu adipiscing purus pulvinar. Maecenas consequat
luctus urna, eget cursus quam mollis a. Aliquam vitae ornare
erat, non hendrerit urna. Sed eu diam nec massa egestas pharetra
at nec tellus. Fusce feugiat lacus quis urna sollicitudin volutpat.
Quisque at sapien non nibh feugiat tempus ac ultricies purus.
""")
lorem_ipsum_text = lorem_ipsum_text.replace("\n"," ") + "\n\n"
large_lorem_ipsum_text = "".join([lorem_ipsum_text]*3000)
notebook_name = "lorem_ipsum_long.ipynb"
nb = v4.new_notebook(
cells=[
v4.new_markdown_cell(source=large_lorem_ipsum_text)
]
)
with TemporaryDirectory() as td:
nbfile = os.path.join(td, notebook_name)
with open(nbfile, 'w') as f:
write(nb, f, 4)
(output, resources) = LatexExporter(template_file='article').from_filename(nbfile)
assert len(output) > 0
开发者ID:jhamrick,项目名称:nbconvert,代码行数:35,代码来源:test_latex.py
示例7: test_checkpoints_follow_file
def test_checkpoints_follow_file(self):
# Read initial file state
orig = self.api.read('foo/a.ipynb')
# Create a checkpoint of initial state
r = self.api.new_checkpoint('foo/a.ipynb')
cp1 = r.json()
# Modify file and save
nbcontent = json.loads(orig.text)['content']
nb = from_dict(nbcontent)
hcell = new_markdown_cell('Created by test')
nb.cells.append(hcell)
nbmodel = {'content': nb, 'type': 'notebook'}
self.api.save('foo/a.ipynb', body=json.dumps(nbmodel))
# Rename the file.
self.api.rename('foo/a.ipynb', 'foo/z.ipynb')
# Looking for checkpoints in the old location should yield no results.
self.assertEqual(self.api.get_checkpoints('foo/a.ipynb').json(), [])
# Looking for checkpoints in the new location should work.
cps = self.api.get_checkpoints('foo/z.ipynb').json()
self.assertEqual(cps, [cp1])
# Delete the file. The checkpoint should be deleted as well.
self.api.delete('foo/z.ipynb')
cps = self.api.get_checkpoints('foo/z.ipynb').json()
self.assertEqual(cps, [])
开发者ID:drastorguev,项目名称:pythondojo,代码行数:31,代码来源:test_contents_api.py
示例8: add_statistics
def add_statistics(plan, file):
cells = [nbf.new_markdown_cell('# Viajes correctos vs Incidencias\n## Se reportaron viajes para el plan: {}'.format(plan)),
nbf.new_code_cell('show(f)'),
nbf.new_code_cell('msj_estadisticaplan(\'{}\', viajes)'.format(plan)),
nbf.new_markdown_cell('# Plan {} de distribución (Sin Modificaciones)'.format(plan)),
nbf.new_code_cell('an.getkm(\'plan\', \'{}\')'.format(plan)),
nbf.new_code_cell('geojsonio.embed(an.gettrips(\'plan\', \'{}\').to_geojson())'.format(plan)),
nbf.new_markdown_cell('# Plan {} Modificado'.format(plan)),
nbf.new_code_cell('an.getkm(\'planm\', \'{}\')'.format(plan)),
nbf.new_code_cell('geojsonio.embed(an.gettrips(\'planm\', \'{}\').to_geojson())'.format(plan)),
]
noto = json.load(open(file))
noto['cells'] = noto['cells'] + cells
with open(file, 'w') as f:
json.dump(noto, f)
开发者ID:aretesw,项目名称:slides-viernes,代码行数:16,代码来源:misc.py
示例9: 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
示例10: 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
示例11: 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
示例12: add_markdown_cell
def add_markdown_cell(self, path):
# Load and update
model = self.contents.get(path=path)
model['content'].cells.append(
new_markdown_cell('Created by test: ' + path)
)
# Save and checkpoint again.
self.contents.save(model, path=path)
return model
开发者ID:pl31,项目名称:pgcontents,代码行数:10,代码来源:test_synchronization.py
示例13: 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
示例14: test_htmltoc2
def test_htmltoc2(self):
"""Test exporter for adding table of contents"""
with self.create_temp_cwd():
nb = v4.new_notebook(
cells=[v4.new_code_cell(source="a = 'world'"), v4.new_markdown_cell(source="# Heading")]
)
with io.open("notebook2.ipynb", "w", encoding="utf-8") as f:
write(nb, f, 4)
self.nbconvert("--to html_toc" ' "notebook2"')
assert os.path.isfile("notebook2.html")
开发者ID:juhasch,项目名称:IPython-notebook-extensions,代码行数:11,代码来源:test_exporters.py
示例15: build_notebook
def build_notebook(self):
notebook = super(TestRegexRemove, self).build_notebook()
# Add a few empty cells
notebook.cells.extend([
nbformat.new_code_cell(''),
nbformat.new_markdown_cell(' '),
nbformat.new_raw_cell('\n'),
nbformat.new_raw_cell('\t'),
])
return notebook
开发者ID:BarnetteME1,项目名称:DnD-stuff,代码行数:11,代码来源:test_regexremove.py
示例16: 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"),
])
def check(byte_string, root_node):
assert b'toc2' in byte_string
self.check_html(nb, 'html_toc', check_func=check)
开发者ID:codegenerator-tools,项目名称:jupyter_contrib_nbextensions,代码行数:11,代码来源:test_exporters.py
示例17: test_present_markdown_cell
def test_present_markdown_cell():
cell = v4.new_markdown_cell(source='# Heading\n\n*some markdown*')
lines = pp.present_value('+ ', cell)
text = '\n'.join(lines)
assert lines[0] == ''
assert lines[1] == '+ markdown cell:'
assert all(line.startswith('+ ') for line in lines if line)
assert 'source:' in text
assert '# Heading' in text
assert '' in lines
assert '*some markdown*' in text
开发者ID:briankflau,项目名称:nbdime,代码行数:11,代码来源:test_prettyprint.py
示例18: test_add_sec_label
def test_add_sec_label():
sample = ("# Foo\n"
"\n"
"Bar")
res = latex.add_sec_label(new_markdown_cell(sample), '05-test')
assert len(res) == 3
assert res[0].cell_type == 'markdown'
assert res[0].source.strip() == '# Foo'
assert res[1].cell_type == 'raw'
assert res[1].source.strip() == '\\label{sec:05-test}'
assert res[2].cell_type == 'markdown'
sample = ("Foo\n"
"===\n")
res = latex.add_sec_label(new_markdown_cell(sample), '05-test')
assert len(res) == 2
assert res[0].cell_type == 'markdown'
assert res[0].source.strip() == 'Foo\n==='
assert res[1].cell_type == 'raw'
assert res[1].source.strip() == '\\label{sec:05-test}'
开发者ID:michaelpacer,项目名称:bookbook,代码行数:20,代码来源:test_latex.py
示例19: parseBkr
def parseBkr(data):
nb = new_notebook()
evaluators = list((cell['evaluator']) for cell in data['cells'] if 'evaluator' in cell)
kernel_name = max(evaluators, key=evaluators.count) if evaluators else 'IPython'
if kernel_name in ['JavaScript', 'HTML', 'TeX']:
kernel_name = 'IPython'
if kernel_name == 'IPython':
kernel_spec = {"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
}}
else:
kernel_spec = {"kernelspec": {
"display_name": kernel_name,
"language": kernel_name.lower(),
"name": kernel_name.lower()
}}
nb.metadata = kernel_spec
for cell in data['cells']:
if cell['type'] == 'code':
metadata = {}
if 'initialization' in cell:
metadata['init_cell'] = True
if 'tags' in cell:
tags = [cell['tags']]
metadata['tags'] = tags
if cell['evaluator'] != kernel_name:
if cell['evaluator'] == 'TeX':
nb.cells.append(new_markdown_cell("${0}$".format(getFixedCodeText(cell['input']))))
else:
nb.cells.append(
new_code_cell(source='%%{0}\n{1}'.format(cell['evaluator'].lower(), getFixedCodeText(cell['input'])),
metadata=metadata))
else:
nb.cells.append(new_code_cell(source=getFixedCodeText(cell['input']), metadata=metadata))
if cell['type'] == 'markdown':
nb.cells.append(new_markdown_cell(getFixedCodeText(cell)))
if cell['type'] == 'section':
nb.cells.append(new_markdown_cell(setHeader(cell['level'], cell['title'])))
return nb
开发者ID:Jaykul,项目名称:beakerx,代码行数:41,代码来源:bkr2ipynb.py
示例20: 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
注:本文中的nbformat.v4.new_markdown_cell函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论