def autoscroll(threshhold):
if threshhold==0: # alway scroll !not good
javastring = '''
IPython.OutputArea.prototype._should_scroll = function(lines) {
return true;
}
'''
elif threshhold==-1: # never scroll !not good
javastring = '''
IPython.OutputArea.prototype._should_scroll = function(lines) {
return false;
}
'''
else:
javastring = 'IPython.OutputArea.auto_scroll_threshold = ' + str(threshhold)
display(Javascript(javastring))
python类Javascript()的实例源码
def publish_notebook(extra=None):
# If we do this then the Javascript object shows up in the notebook
# js = Javascript('IPython.notebook.save_checkpoint();')
# display(js)
file = Idv.getname()
if file is None:
return
isl = '<isl><publish file="' + file + '"/></isl>'
DrilsdownUI.status("Make sure you do 'File->Save and Checkpoint'. Check your IDV to publish the file")
result = Idv.run_isl(isl);
if not result.ok():
print("Publication failed")
return
if result.get_results().strip()!="":
print("Publication successful")
print("URL: " + result.get_results())
return
print("Publication failed")
def run_next_cells(n):
if n=='all':
n = 'NaN'
elif n<1:
return
js_code = """
var num = {0};
var run = false;
var current = $(this)[0];
$.each(IPython.notebook.get_cells(), function (idx, cell) {{
if ((cell.output_area === current) && !run) {{
run = true;
}} else if ((cell.cell_type == 'code') && !(num < 1) && run) {{
cell.execute();
num = num - 1;
}}
}});
""".format(n)
display(Javascript(js_code))
def init_data(self):
# check if window.graph_data already exists
# if so then return True
# else create window.graph_data = {} then return false
js_code = """
window.graph_data = [];
window.current_graph_id = -1;
window.current_graph_id2 = 0;
/*
require(['d3'], function(d3){
window.d3 = d3;
});
*/
"""
return Javascript(js_code)
def display_cell(text):
"""Remove cells that start with "# Temp" and add a new one
Arguments:
* `text` -- new cell content
"""
encoded_code = bytes_to_str(base64.b64encode(str_to_bytes(text)))
display(Javascript("""
$('span:contains("# Temp")').closest('.cell').remove();
var code = IPython.notebook.insert_cell_{0}('code');
code.set_text(atob("{1}"));
""".format('below', encoded_code)))
def to_jupyter(graph, width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT, color_map=None, replace_cnames=False):
"""Displays the BEL graph inline in a Jupyter notebook.
To use successfully, make run as the last statement in a cell inside a Jupyter notebook.
:param pybel.BELGraph graph: A BEL graph
:param int width: The width of the visualization window to render
:param int height: The height of the visualization window to render
:param dict color_map: A dictionary from PyBEL internal node functions to CSS color strings like #FFEE00. Defaults
to :data:`default_color_map`
:return: An IPython notebook Javascript object
:rtype: :class:`IPython.display.Javascript`
"""
from IPython.display import Javascript
return Javascript(to_jupyter_str(
graph,
width=width,
height=height,
color_map=color_map,
replace_cnames=replace_cnames
))
def wavejson_to_wavedrom(wavejson, width=None, skin='default'):
'''
Create WaveDrom display from WaveJSON data.
This code is from https://github.com/witchard/ipython-wavedrom.
Inputs:
width: Width of the display window in pixels. If left as None, the entire
waveform will be squashed into the width of the page. To prevent
this, set width to a large value. The display will then become scrollable.
skin: Selects the set of graphic elements used to draw the waveforms.
Allowable values are 'default' and 'narrow'.
'''
# Set the width of the waveform display.
style = ''
if width != None:
style = ' style="width: {w}px"'.format(w=str(int(width)))
# Generate the HTML from the JSON.
htmldata = '<div{style}><script type="WaveDrom">{json}</script></div>'.format(
style=style, json=json.dumps(wavejson))
DISP.display_html(DISP.HTML(htmldata))
# Trigger the WaveDrom Javascript that creates the graphical display.
DISP.display_javascript(
DISP.Javascript(
data='WaveDrom.ProcessAll();',
lib=[
'http://wavedrom.com/wavedrom.min.js',
'http://wavedrom.com/skins/{skin}.js'.format(skin=skin)
]))
# The following allows the display of WaveDROM in the HTML files generated by nbconvert.
# It's disabled because it makes Github's nbconvert freak out.
setup = '''
<script src="http://wavedrom.com/skins/{skin}.js" type="text/javascript"></script>
<script src="http://wavedrom.com/wavedrom.min.js" type="text/javascript"></script>
<body onload="WaveDrom.ProcessAll()">
'''.format(skin=skin)
#DISP.display_html(DISP.HTML(setup))
def ipython_config(self):
temp_config = _Configuration(self.config_path)
if temp_config.has('p12') and 'path' in temp_config.get('p12'):
pass
else:
if _in_ipython:
from IPython.display import display, Javascript
display(Javascript("MyPKI.init({'no_verify':true, configure:true});"))
print('Configuring .mypki via JavaScript .p12 dialog...')
while True:
temp_config = _Configuration(self.config_path)
if temp_config.has('p12') and 'path' in temp_config.get('p12'):
break
else:
sleep(2)
def display(self, columns=[], msg=None):
data = self.data if len(self.data) <= 100 else self.data[:49] + [['...'] * (len(self.data[0]))] + self.data[-49:]
table_str = HTMLTable([columns] + data, self.id_)._repr_html_(n_rows=100, length=len(self.data))
table_str = table_str.replace('<table', '<table class="table-striped table-hover table-bordered"').replace("'", "\\'").replace('\n','')
display(
HTML(
"""
<script type="text/Javascript">
$('#dbinfo{id}').append('{msg}');
$('#table{id}').append('{table}');
</script>
""".format(msg=str(msg), table=table_str, id=self.id_)
)
)
def load_js_files():
display(Javascript(
load_js_scripts()
))
return None
def __call__(self, parameterized, **params):
self.p = param.ParamOverrides(self, params)
if self.p.initializer:
self.p.initializer(parameterized)
self._widgets = {}
self.parameterized = parameterized
widgets, views = self.widgets()
layout = ipywidgets.Layout(display='flex', flex_flow=self.p.layout)
if self.p.close_button:
layout.border = 'solid 1px'
widget_box = ipywidgets.VBox(children=widgets, layout=layout)
if views:
view_box = ipywidgets.VBox(children=views, layout=layout)
layout = self.p.view_position
if layout in ['below', 'right']:
children = [widget_box, view_box]
else:
children = [view_box, widget_box]
box = ipywidgets.VBox if layout in ['below', 'above'] else ipywidgets.HBox
widget_box = box(children=children)
display(Javascript(WIDGET_JS))
display(widget_box)
self._widget_box = widget_box
for view in views:
p_obj = self.parameterized.params(view.name)
value = getattr(self.parameterized, view.name)
if value is not None:
self._update_trait(view.name, p_obj.renderer(value))
# Keeps track of changes between button presses
self._changed = {}
if self.p.on_init:
self.execute()
def __init__(self, shell, require_interaction=False):
super(JupyterNotifyMagics, self).__init__(shell)
with open(resource_filename("jupyternotify", "js/init.js")) as jsFile:
jsString = jsFile.read()
display(Javascript(jsString))
self.options = {
"requireInteraction": require_interaction,
"icon": "/static/base/images/favicon.ico",
}
def display_notification(self, options=None, notification_uuid=None):
if options is None:
options = self.options
if notification_uuid is None:
notification_uuid = uuid.uuid4()
# display our browser notification using javascript
with open(resource_filename("jupyternotify", "js/notify.js")) as jsFile:
jsString = jsFile.read()
display(Javascript(jsString % {
"notification_uuid": notification_uuid,
"options": json.dumps(options),
}))
def select_url(self, url):
self.selected_url = url
display(Javascript("""
var run = false, current = $(this)[0];
$.each(IPython.notebook.get_cells(), function (idx, cell) {
if (!run && (cell.output_area === current)) {
run = true;
} else if (cell.cell_type == 'code') {
cell.execute();
}
});
"""))
def clear(self):
"""Clear cell and output"""
if self.disable_show:
return
self.to_display = []
display(Javascript(
"""$('span:contains("# Temp")').closest('.cell').remove();"""))
self.output_widget.clear_output()
def display(self, *args):
"""Display interactive graph"""
if self._display_stack:
if not self.delayed:
self._display_stack -= 1
if self._display_stack:
# Skip display if other widgets will invoke display soon
return False
self.output_widget.clear_output()
with self.output_widget:
work_list, references = self.graph()
display(self._svg_name)
svg = SVG(self._svg_name)
svg._data = svg._data[:4] + ' class="refgraph"' + svg._data[4:]
display(svg)
interaction = """
$(".hoverable polyline, .hoverable line").mouseenter(
function(e) {
//e.stopPropagation();
$(this).css("stroke", "blue");
$(this).css("stroke-width", "3px");
}).mouseleave(
function() {
$(this).css("stroke", "black");
$(this).css("stroke-width", "inherit");
});
"""
display(Javascript(interaction))
display(HTML("""
<script type="text/javascript">
%s
require(["./svg-pan-zoom"], function(svgPanZoom) {
svgPanZoom('.refgraph', {'minZoom': 0.1});
});
</script>
""" % (
open(
Path(__file__) / ".." / ".." /
"resources" / "svg-pan-zoom.min.js"
).read(),
)))
return True
def to_jupyter_str(graph, width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT, color_map=None, replace_cnames=False):
"""Returns the string to be javascript-ified by the Jupyter notebook function :class:`IPython.display.Javascript`
:param pybel.BELGraph graph: A BEL graph
:param int width: The width of the visualization window to render
:param int height: The height of the visualization window to render
:param dict color_map: A dictionary from PyBEL internal node functions to CSS color strings like #FFEE00. Defaults
to :data:`default_color_map`
:return: The javascript string to turn into magic
:rtype: str
"""
add_canonical_names(graph, replace=replace_cnames)
gjson = to_jsons(graph)
d3_code = render_template('pybel_vis.js')
chart_id = generate_id()
color_map = default_color_map if color_map is None else color_map
javascript_vars = """
var chart = "{}";
var width = {};
var height = {};
var graph = {};
const color_map = {};
""".format(chart_id, width, height, gjson, color_map)
require_code = """
require.config({
paths: {
d3: '//cdnjs.cloudflare.com/ajax/libs/d3/4.5.0/d3.min'
}
});
var elementInnerHTML = "<div id='" + chart + "'></div>";
element.append(elementInnerHTML);
var chartQualified = "#" + chart;
require(['d3'], function(d3) {
return init_d3_force(d3, graph, chartQualified, width, height, color_map);
});
"""
result = d3_code + javascript_vars + require_code
return result