def show_training(self, div_id, div_costs_curve, cost_values) :
#div_id = self.show(*args, **kwargs)
def change_frame(w) :
#print(w)
updates = self.get_frame(w-1)
script = ''
for i in range(len(updates[0])) :
jupdate = json.dumps(updates[0][i], cls=utils.PlotlyJSONEncoder)
jupdate_cost = json.dumps(dict(x = [[w]], y = [[cost_values[w-1]]]), cls=utils.PlotlyJSONEncoder)
script = script \
+ 'Plotly.restyle("{id}", {update}, [{index}]);'.format(
id=div_id,
update=jupdate, index = updates[1][i]) \
+ 'Plotly.restyle("{id}", {update}, [{index}]);'.format(
id=div_costs_curve,
update=jupdate_cost, index = 1)
update_str = (
'<script type="text/javascript">' +
'window.PLOTLYENV=window.PLOTLYENV || {{}};' +
'window.PLOTLYENV.BASE_URL="' + 'https://plot.ly' + '";' +
'{script}' +
'</script>').format(script=script)
#print(script)
display(HTML(update_str))
#print(self.frames)
maxframe = len(self.frames) - 1
play = Play(value=maxframe)
slider = IntSlider(min=1, max=maxframe, step=1, value=maxframe,continuous_update=False)
slider.layout.width = '100%'
#jslink((play, 'value'), (slider, 'value'))
traitlets.link((play, 'value'), (slider, 'value'))
hb = HBox([play, slider])
slider.observe((lambda iteration : change_frame(iteration['new'])), names='value')
change_frame(maxframe)
#play.observe((lambda iteration : print(iteration['new'])), names='value')
#display(hb)
return hb
python类HTML的实例源码
def my_iplot(figure_or_data, show_link=False, link_text='Export to plot.ly',
validate=True, image=None, filename='plot_image', image_width=800,
image_height=600) :
plot_html, plotdivid, width, height = _plot_html(
figure_or_data, show_link, link_text, validate,
'100%', 525, global_requirejs=True)
#display(HTML(plot_html))
wid = widgets.HTML(
value=plot_html,
placeholder='Some HTML',
description='Some HTML',
disabled=False
)
return (wid, plotdivid)
def wrap_animation(anim):
if not is_html_setup:
setup_html()
return HTML(anim.to_html5_video())
def show_image(image_path):
display(Image(image_path))
image_rel = image_path.replace(root,'')
caption = "Image " + ' - '.join(attributions[image_rel].split(' - ')[:-1])
display(HTML("<div>%s</div>" % caption))
def show_article(self, article, nwork, info):
"""Display article"""
citations = ""
text = "# Temp\n"
text += "insert('''"
if nwork is None:
text += info_to_code(info) + "\n"
if self.citation_var:
text += citation_text(
self.citation_var, info,
ref=article.get('citation_id', ''),
backward=self.backward
) + "\n"
citations = ", citations='{}'".format(self.citation_file)
text += "'''{});".format(citations)
if nwork:
for key, value in info.items():
if key in {'pyref', 'place1', '_work_type'}:
continue
if not hasattr(nwork, key):
text += "\nset_attribute('{}', '{}', '{}');".format(
info['pyref'], key, value
)
display_cell(text)
self.output_widget.clear_output()
with self.output_widget:
if self.to_display:
display("\n".join(self.to_display))
if 'div' in article:
display(HTML(repr(article['div'])))
elif 'name' in article:
print(article['name'])
display(HTML("<input value='{}.pdf' style='width: 100%'></input>".format(info['pyref'])))
if not 'place' in info:
display(HTML("<input value='{}' style='width: 100%'></input>".format(info['place1'])))
self.to_display = []
def show(self, b=None, clear=True):
"""Generic display"""
_up = self.update_info
reload()
self.next_article_widget.disabled = self.selector_widget.value == self.selector_widget.max
self.previous_article_widget.disabled = self.selector_widget.value == 0
if clear:
self.clear()
if self.disable_show or not self.articles:
return
article, _, _ = self.articles[self.selector_widget.value]
with self.output_widget:
if 'div' in article:
display(HTML(repr(article['div'])))
else:
print(article['name'])
for article, nwork, info in self.valid_articles([article], show=True):
if info.get("_work_type") == "Site":
self.show_site(article, nwork, info)
continue
if info.get("place", "") == "Lang":
self.work_type_widget.value = "WorkLang"
_up(info, 'due', self.due_widget)
_up(info, 'place', self.place_widget)
_up(info, "_work_type", self.work_type_widget, default="Work")
if _up(info, 'year', self.year_widget) or _up(info, 'display', self.prefix_widget):
set_pyref(info)
_up(info, 'file', self.file_field_widget, info["pyref"] + ".pdf", default=False)
_up(info, 'file', self.pdfpage_widget, info.get("file", "") + "#page={}".format(self.pdfpage_widget.value))
for widget in self.custom_widgets:
_up(info, widget._workattr, widget)
self.show_article(article, nwork, info)
def notify(self):
return display(HTML(self.template.format(self.message)))
def notify(self):
display(Audio(self.audio, autoplay=True))
time.sleep(3)
display(HTML(self.template.format(self.message)))
def print_frames(dataframes):
if not isinstance(dataframes, tuple):
return dataframes
border_style = u'\"border: none\"'
cells = [u'<td style={}> {} </td>'.format(border_style, df._repr_html_()) for df in dataframes]
table = '''<table style={}>
<tr style={}>'''.format(border_style, border_style) +\
'\n'.join(cells)+\
'''
</tr>
</table>'''
return HTML(table)
def publish_to_baas(self, url, study_name=None, username=None):
"""
Publishes a tree on a Boris as a Service instance.
:param url: url to a instance (e.g. http://transmart-arborist.thehyve.nl/).
:param study_name: a nice name.
:param username: if no username is given, you will be prompted for one.
:return: the url that points to the study you've just uploaded.
"""
study_name = study_name or self.study_name or input('Enter study name:')
json_data = self.concept_tree.jstree.json_data_string
new_url = arborist.publish_to_baas(url, json_data, study_name, username)
return HTML('<a target="_blank" href="{l}">{l}</a>'.format(l=new_url))
def display_styler_as_html(styler):
display(HTML(styler.render()))
def tableau(quadkeys, solution = None):
retVal = "<table>"
for row in grouper(quadkeys, 3):
html_row = "<tr>"
for quadkey in row:
html_row += "<td align=\"center\" style=\"text-align: center\">"
if quadkey is not None:
html_row += cell_renderer(quadkey, solution)
html_row += "</td>"
html_row += "</tr>"
retVal += html_row
retVal += "</table>"
display(HTML(retVal))
def __init__(self, **kwargs):
super(D3Magics, self).__init__(**kwargs)
self.max_id = 0 # Used to ensure that the current group selection is unique.
# self.initialized = True # Used to ensure that d3.js is only imported once.
# # The necessary substitutions to get a block working are theoretically possible, but too quirky for the moment
# to consider.
# @line_magic
# def block(self, line):
# user, gist_id = line.split("/")[-2:]
# r = requests.get("https://gist.github.com/{0}/{1}/download".format(user, gist_id))
# with zipfile.ZipFile(io.BytesIO(r.content)) as ar:
# ar.extractall(".blocks/{0}/".format(user, gist_id))
# # This creates e.g. ".blocks/mbostock/3885304-master" in the root directory.
# # The appended "-master" is due to the format of the zipped file.
# # It's a little unideal, but unsure about whether or not removing it would cause any issues I've kept it
# # for the time being (you could easily rename the folder).
# with open(".blocks/{0}/{1}-master/index.html".format(user, gist_id), "r") as f:
# source = f.read()
# # We need to perform a few substutions to make the figure work within a Jupyter Notebook file.
# # 1. <body> tags are not allowed within a D3 notebook (one has already been defined and HTML documents only
# # allow one <body> and one <head>), but are probably the most common initial selector of all for defining
# # the initial D3 frame. To fix:
# # >>> <body> --> <g>
# # >>> d3.select("body") --> d3.select("g")
# # >>> <body id="foo"> --> ???
# # >>> <body class="foo"> --> ???
# source = source.replace('<body', '<g')
# source = source.replace("select('body", "select(g")
# source = source.replace('d3.tsv("', 'd3.tsv("./.blocks/{0}/{1}-master/'.format(user, gist_id))
# print(HTML(source).data)
# display(HTML(source))
def d3(self, line, cell):
src = line if len(line) > 0 else "3.5.17"
s = """
<script>
requirejs.config({
paths: {
d3: "//cdnjs.cloudflare.com/ajax/libs/d3/""" + src + """/d3"
}
});
require(['d3'], function(d3) {
window.d3 = d3;
});
</script>
<script>
_select = d3.select;
d3.select""" + str(self.max_id) + """ = function(selection) {
return _select("#d3-cell-""" + str(self.max_id) + """").select(selection);
}
d3.selectAll""" + str(self.max_id) + """ = function(selection) {
return _select("#d3-cell-""" + str(self.max_id) + """").selectAll(selection);
}
</script>
<g id="d3-cell-""" + str(self.max_id) + """">
"""
cell = re.sub('d3.select\((?!this)', "d3.select" + str(self.max_id) + "(", cell)
cell = re.sub('d3.selectAll\((?!this)', "d3.selectAll" + str(self.max_id) + "(", cell)
s += cell + "\n</g>"
# print(s) # Useful for debugging.
h = HTML(s)
self.max_id += 1
display(h)
def drawFragmentsbyTopic(topicModel, topicIdx, n_top_frags=10, numRowsShown=4, cssTableName='fragTab', \
prior=-1.0, numColumns=4, tableHeader=''):
scores = topicModel.getTopicFragmentProbabilities()
numTopics, numFragments = scores.shape
if prior < 0:
prior = 1./numFragments
svgs=generateTopicRelatedFragmentSVGs(topicModel, topicIdx, n_top_frags=n_top_frags, prior=prior)
namesSVGs = list(map(lambda x: "Score %.2f" % x, \
filter(lambda y: y > prior, sorted(scores[topicIdx,:], reverse=True)[:n_top_frags])))
if tableHeader == '':
tableHeader = "Topic "+str(topicIdx)
return display(HTML(utilsDrawing.drawSVGsToHTMLGrid(svgs,tableHeader=tableHeader,cssTableName=cssTableName,\
namesSVGs=namesSVGs,size=(120,100),numRowsShown=numRowsShown,\
numColumns=numColumns)))
def play_video(path):
video = io.open(path, 'r+b').read()
encoded = base64.b64encode(video)
return HTML(data='''<video alt="test" controls>
<source src="data:video/mp4;base64,{0}" type="video/mp4" />
</video>'''.format(encoded.decode('ascii')))
def animation2HTML(anim, frame_rate):
print("animaiton to video...")
if not hasattr(anim, '_encoded_video'):
with NamedTemporaryFile(suffix='.mp4') as f:
anim.save(f.name, fps=frame_rate,
extra_args=['-vcodec', 'libx264',
'-pix_fmt', 'yuv420p',
'-crf', '28',
'-preset', 'veryfast'])
video = io.open(f.name, 'r+b').read()
encoded = base64.b64encode(video)
return HTML(data='''<video alt="test" controls>
<source src="data:video/mp4;base64,{0}" type="video/mp4" />
</video>'''.format(encoded.decode('ascii')))
def image_stack_to_movie(images, frames=None, vmin=None, vmax=None,
figsize=(6, 5), cmap='CMRmap', fps=10):
"""Convert image stack to movie and show in notebook.
Parameters
----------
images : array_like
Stack of images to show as a movie of shape (N, y, x).
frames : int
Number of frames to process
vmin : number
Minimum value to display for ``imshow``
vmax : number
Maximum value to display for ``imshow``
figsize : tuple
Figure size for each frame
cmap : string
Colormap to use for plotting image
fps : int
Framerate for created movie
"""
if frames is None:
frames = images.shape[0]
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111)
im = plt.imshow(images[1], vmin=vmin, vmax=vmax, cmap=cmap,
interpolation='none')
cbar = fig.colorbar(im)
cbar.ax.tick_params(labelsize=14)
cbar.set_label(r"Intensity [ADU]", size=14,)
for item in ([ax.xaxis.label, ax.yaxis.label] +
ax.get_xticklabels() + ax.get_yticklabels()):
item.set_fontsize(14)
item.set_fontweight('bold')
def animate(i):
im.set_array(images[i])
ax.set_title('Frame {}'.format(i), fontsize=16, fontweight='bold')
return im,
anim = animation.FuncAnimation(fig, animate, frames=frames,
interval=1, blit=True)
plt.close(anim._fig)
# return anim.to_html5_video()
return HTML(_anim_to_html(anim, fps))
def plot_state(self, **options):
"""Plot the GP surface.
This feature is still experimental and currently supports only 2D cases.
"""
f = plt.gcf()
if len(f.axes) < 2:
f, _ = plt.subplots(1, 2, figsize=(13, 6), sharex='row', sharey='row')
gp = self.target_model
# Draw the GP surface
visin.draw_contour(
gp.predict_mean,
gp.bounds,
self.parameter_names,
title='GP target surface',
points=gp.X,
axes=f.axes[0],
**options)
# Draw the latest acquisitions
if options.get('interactive'):
point = gp.X[-1, :]
if len(gp.X) > 1:
f.axes[1].scatter(*point, color='red')
displays = [gp._gp]
if options.get('interactive'):
from IPython import display
displays.insert(
0,
display.HTML('<span><b>Iteration {}:</b> Acquired {} at {}</span>'.format(
len(gp.Y), gp.Y[-1][0], point)))
# Update
visin._update_interactive(displays, options)
def acq(x):
return self.acquisition_method.evaluate(x, len(gp.X))
# Draw the acquisition surface
visin.draw_contour(
acq,
gp.bounds,
self.parameter_names,
title='Acquisition surface',
points=None,
axes=f.axes[1],
**options)
if options.get('close'):
plt.close()
def _plot_in_notebook(profiler):
"""Generate interactive (notebook) visualization of the current profile statistics
in `profiler`."""
from .pstats import Stats
import snakeviz
import snakeviz.stats
stats = Stats(profiler)
table_rows=snakeviz.stats.table_rows(stats)
callees=snakeviz.stats.json_stats(stats)
base = join(dirname(__file__), 'snakeviz')
template = join(base, 'template.jinja')
resources={}
resources['style_css'] = join(base, 'style.css')
base = join(dirname(snakeviz.__file__), 'static')
resources['snakeviz_js'] = join(base, 'snakeviz.js')
resources['drawsvg_js'] = join(base, 'drawsvg.js')
resources['datatables_css'] = join(base, 'vendor/jquery.dataTables.min.css')
resources['jquery_min_js'] = join(base, 'vendor/jquery-1.11.1.min.js')
resources['d3_min_js'] = join(base, 'vendor/d3.min.js')
resources['jquery_dt_js'] = join(base, 'vendor/jquery.dataTables.min.js')
resources['lodash_js'] = join(base, 'vendor/lodash.compat.min.js')
resources['immutable_js'] = join(base, 'vendor/immutable.min.js')
for r in resources:
with open(resources[r], 'r', encoding='utf-8') as f:
resources[r] = f.read()
with open(template, 'r', encoding='utf-8') as f:
template = Template(f.read())
html = template.render(table_rows=table_rows, callees=callees, **resources)
# We can't embed the snakeviz html because its js isn't (yet) compatible
# with the notebook's use of RequireJS, so we fall back to using an iframe
# until that's fixed.
with open("snakeviz.html", 'w', encoding='utf-8') as f:
f.write(html)
return HTML(data="""<div class="resizable" style="height:500px;">
<iframe src="./snakeviz.html" width="100%" height="100%"/>
</div>
<script type="text/javascript">
$(function() {
$('.resizable').resizable({
handles: 'n,s',
start: function(event, ui) {
$('iframe').css('pointer-events','none');
},
stop: function(event, ui) {
$('iframe').css('pointer-events','auto');
}
});
});
</script>
""")