def display_in_notebook(image, max_val=None): """ A helper function to display images in an IPython notebook Must be run from within an IPython notebook, or else it will raise a YTNotInsideNotebook exception. Parameters ---------- image : array_like This is an (unscaled) array of floating point values, shape (N,N,3) or (N,N,4) to display in the notebook. The first three channels will be scaled automatically. max_val : float, optional The upper limit to clip values of the image. Only applies to the first three channels. """ if "__IPYTHON__" in dir(builtins): from IPython.core.displaypub import publish_display_data data = write_bitmap(image, None, max_val=max_val) publish_display_data( data={'image/png': data}, source='yt.visualization.image_writer.display_in_notebook', ) else: raise YTNotInsideNotebook
def pencolor(self, color): """ Change the color of the line drawn by the turtle to the parameter color. """ command = " penColor " + color publish_display_data('pacturtle.pencolor', {'turtle':command}) penColor = color;
def bibFile(self, line, robust=False): '''Opening bibliography file''' bibliography = biblist.BibList() bibliography.import_bibtex(line, normalize=False) for key in bibliography.bib.keys(): curArt = bibliography.bib[key] curAuth = zip(*curArt['author'])[1:3] if len(curAuth[0]) > 1: if len(curAuth[0]) > self.etal: curAuth = curAuth[0][0] + ' et. al.' else: curAuth = ', '.join( curAuth[0][:-1]) + ' and ' + curAuth[0][-1] else: curAuth = curAuth[0][0] self.cite['t'][bibliography.bib[key] ['_code']] = '{0} ({1})'.format( curAuth, curArt['year']) self.cite['p'][bibliography.bib[key]['_code']] = '{0}, {1}'.format( curAuth, curArt['year']) if robust: publish_display_data( 'printTex', { 'text/plain': '{0} loaded, there are {1} keys ({2})'.format( line, len(self.cite['t'].keys()), ', '.join( self.cite['t'].keys())), 'text/html': markdown('_{0}_ loaded<br/>There are __{1}__ keys:<br/>{2}' .format(line, len(self.cite['t'].keys()), ', '.join(self.cite['t'].keys()))) })
def ferret_putdata(self, line): ''' Line-level magic to put data to ferret. In [31]: import numpy as np ....: b = {} ....: b['name']='myvar' ....: b['name']='myvar' ....: x=np.linspace(-np.pi*4, np.pi*4, 500) ....: b['data']=np.sin(x)/x ....: b.keys() Out[31]: ['data', 'name'] In [32]: %ferret_putdata --axis_pos (1,0,2,3,4,5) b ....: Message: b is now available in ferret as myvar ''' args = parse_argstring(self.ferret_putdata, line) ferretvariable = unicode_to_str(args.code[0]) if args.axis_pos: axis_pos_variable = eval(args.axis_pos) else: axis_pos_variable = None pyferret.putdata(self.shell.user_ns[ferretvariable], axis_pos=axis_pos_variable) publish_display_data('ferretMagic.ferret', {'text/html': '<pre style="background-color:#F2F5A9; border-radius: 4px 4px 4px 4px; font-size: smaller">' + 'Message: ' + ferretvariable + ' is now available in ferret as ' + self.shell.user_ns[ferretvariable]['name'] + '</pre>' })
def display_in_notebook(image, max_val=None): """ A helper function to display images in an IPython notebook Must be run from within an IPython notebook, or else it will raise a YTNotInsideNotebook exception. Parameters ---------- image : array_like This is an (unscaled) array of floating point values, shape (N,N,3) or (N,N,4) to display in the notebook. The first three channels will be scaled automatically. max_val : float, optional The upper limit to clip values of the image. Only applies to the first three channels. """ if "__IPYTHON__" in dir(builtins): from IPython.core.displaypub import publish_display_data data = write_bitmap(image, None, max_val=max_val) publish_display_data( data={"image/png": data}, source="yt.visualization.image_writer.display_in_notebook", ) else: raise YTNotInsideNotebook
def backward(self, distance): """ Move the turtle backward relative to the current angle by the parameter distance. """ #calculate endpoints self.turtleAngle = -self.turtleAngle radians = math.radians(self.turtleAngle) endx = math.cos(radians) endy = math.sin(radians) endx = -distance * endx endy = -distance * endy endy = endy #y goes down endx = self.startx - endx endy = self.starty + endy stringx = str(endx); stringy = str(endy); command = " backward "+ stringx + " " + stringy publish_display_data('pacturtle.backward', {'turtle':command}) #set up new startpoints self.startx = endx self.starty = endy #reset angle self.turtleAngle = -self.turtleAngle
def notebooksources(self): import IPython.core.displaypub as displaypub html = self.html(template="basediv.html", script_paths = dump.notebookscript_paths, html_snippets=["<p>Bokeh Sources</p>"]) displaypub.publish_display_data('bokeh', {'text/html': html}) return None
def notebooksources(self): import IPython.core.displaypub as displaypub jsstr = inline_scripts(dump.notebook_script_paths) cssstr = inline_css(dump.css_paths) template = get_template('source_block.html') if self.bbclient: split = urlparse.urlsplit(self.root_url) host = split.netloc protocol = split.scheme html = template.render( script_block=jsstr.decode('utf-8'), css_block=cssstr.decode('utf-8'), connect=True, host=host, protocol=protocol, wsprotocol="wss" if protocol == 'https' else "ws", docid=self.bbclient.docid ) else: html = template.render(script_block=jsstr.decode('utf-8'), css_block=cssstr.decode('utf-8'), connect=False ) displaypub.publish_display_data('bokeh', {'text/html': html}) return None
def notebooksources(self): import IPython.core.displaypub as displaypub html = self.html(template="basediv.html", script_paths=dump.notebookscript_paths, html_snippets=["<p>Bokeh Sources</p>"]) displaypub.publish_display_data('bokeh', {'text/html': html}) return None
def knitr(line, cell=None): tmpd = tempfile.mkdtemp() Rmd_file = open("%s/code.Rmd" % tmpd, "w") md_filename = Rmd_file.name.replace("Rmd", "md") Rmd_file.write(""" ``` {r fig.path="%s"} %s ``` """ % (tmpd, cell.strip())) Rmd_file.close() Reval("library(knitr); knit('%s','%s')" % (Rmd_file.name, md_filename)) sys.stdout.flush(); sys.stderr.flush() json_str = '[' + open(md_filename, 'r').read().strip()[:-1].replace('\n','\\n') + ']' md_output = json.loads(json_str) display_data = [] # flush text streams before sending figures, helps a little with output for mime, fname in md_output: # synchronization in the console # (though it's a bandaid, not a real sln) sys.stdout.flush(); sys.stderr.flush() data = open(fname).read() os.remove(fname) if data: display_data.append(('RMagic.R', {mime: data})) # kill the temporary directory rmtree(tmpd) for tag, disp_d in display_data: publish_display_data(tag, disp_d)
def ferret_putdata(self, line): ''' Line-level magic to put data to ferret. In [31]: import numpy as np ....: b = {} ....: b['name']='myvar' ....: b['name']='myvar' ....: x=np.linspace(-np.pi*4, np.pi*4, 500) ....: b['data']=np.sin(x)/x ....: b.keys() Out[31]: ['data', 'name'] In [32]: %ferret_putdata --axis_pos (1,0,2,3,4,5) b ....: Message: b is now available in ferret as myvar ''' args = parse_argstring(self.ferret_putdata, line) ferretvariable = unicode_to_str(args.code[0]) if args.axis_pos: axis_pos_variable = eval(args.axis_pos) else: axis_pos_variable = None pyferret.putdata(self.shell.user_ns[ferretvariable], axis_pos=axis_pos_variable) publish_display_data({'text/html': '<pre style="background-color:#F2F5A9; border-radius: 4px 4px 4px 4px; font-size: smaller">' + 'Message: ' + ferretvariable + ' is now available in ferret as ' + self.shell.user_ns[ferretvariable]['name'] + '</pre>' })
def show(self): "Main show function, it shows the plot in file, server and notebook outputs." global _notebook_loaded if self.filename: if self.filename is True: filename = "untitled" else: filename = self.filename with open(filename, "w") as f: f.write(file_html(self.doc, INLINE, self.title)) print("Wrote %s" % filename) view(filename) elif self.filename is False and self.server is False and self.notebook is False: print("You have a provide a filename (filename='foo' or" " .filename('foo')) to save your plot.") if self.server: self.session.use_doc(self.servername) self.session.load_document(self.doc) self.session.show(self.plot) if self.notebook: import IPython.core.displaypub as displaypub from bokeh.embed import notebook_div displaypub.publish_display_data('bokeh', {'text/html': notebook_div(self.plot)})
def notebook_connect(self): if self.docname is None: raise RuntimeError("usedoc() must be called before notebook_connect()") import IPython.core.displaypub as displaypub js = self._load_template("connect.js").render( username=self.username, root_url=self.root_url, docid=self.docid, docapikey=self.apikey, ws_conn_string=self.ws_conn_string(), ) msg = """<p>Connecting notebook to document "%s" at server %s</p>""" % (self.docname, self.root_url) js_paths = self.js_files # script_paths = self.js_paths() css_paths = self.css_paths() html = self._load_template("basediv.html").render( rawjs=self._inline_scripts(js_paths).decode("utf8"), rawcss=self._inline_css(css_paths).decode("utf8"), js_snippets=[js], html_snippets=[msg], ) displaypub.publish_display_data("bokeh", {"text/html": html}) return None
def ferret_getdata(self, line): ''' Line-level magic to get data from ferret. In [18]: %%ferret ....: use levitus_climatology In [19]: %ferret_getdata tempdict = temp ....: Message: tempdict is now available in python as a dictionary containing the variable's metadata and data array. In [20]: print(tempdict.keys()) ....: ['axis_coords', 'axis_types', 'data_unit', 'axis_units', 'title', 'axis_names', 'missing_value', 'data'] ''' args = parse_argstring(self.ferret_getdata, line) code = unicode_to_str(''.join(args.code)) pythonvariable = code.split('=')[0] ferretvariable = code.split('=')[1] exec('%s = pyferret.getdata("%s", %s)' % (pythonvariable, ferretvariable, args.create_mask) ) self.shell.push("%s" % pythonvariable) publish_display_data({'text/html': '<pre style="background-color:#F2F5A9; border-radius: 4px 4px 4px 4px; font-size: smaller">' + 'Message: ' + pythonvariable + " is now available in python as a dictionary containing the variable's metadata and data array." '</pre>' })
def write_line(self, line): displaypub.publish_display_data( u'IPython.core.displaypub.publish_javascript', { 'application/javascript': 'document.%s.append($("<div>%s</div>"));' % (self.output_id, cgi.escape(line)) })
def write_chars(self, chars): displaypub.publish_display_data( u'IPython.core.displaypub.publish_javascript', { 'application/javascript': 'document.%s.append($("<span>%s</span>"));' % (self.output_id, cgi.escape(chars)) })
def ferret_getdata(self, line): ''' Line-level magic to get data from ferret. In [18]: %%ferret ....: use levitus_climatology In [19]: %ferret_getdata tempdict = temp ....: Message: tempdict is now available in python as a dictionary containing the variable's metadata and data array. In [20]: print tempdict.keys() ....: ['axis_coords', 'axis_types', 'data_unit', 'axis_units', 'title', 'axis_names', 'missing_value', 'data'] ''' args = parse_argstring(self.ferret_getdata, line) code = unicode_to_str(''.join(args.code)) pythonvariable = code.split('=')[0] ferretvariable = code.split('=')[1] exec('%s = pyferret.getdata("%s", %s)' % (pythonvariable, ferretvariable, args.create_mask) ) self.shell.push("%s" % pythonvariable) publish_display_data('ferretMagic.ferret', {'text/html': '<pre style="background-color:#F2F5A9; border-radius: 4px 4px 4px 4px; font-size: smaller">' + 'Message: ' + pythonvariable + " is now available in python as a dictionary containing the variable's metadata and data array." '</pre>' })
def tikz(self, line, cell): args = magic_arguments.parse_argstring(self.tikz, line) fmt = Format(args.format) tikz_options = ' '.join(args.options) mapping = {'options': tikz_options, 'code': cell} tikz_picture = tikz_picture_template.substitute(mapping) latex_packages = [] for package in args.package: latex_packages.append(r'\usepackage{' + package + '}') tikz_libraries = [] for library in args.library + DEFAULT_LIBRARIES: tikz_libraries.append(r'\usetikzlibrary{' + library + '}') mapping = {'packages': '\n'.join(latex_packages), 'libraries': '\n'.join(tikz_libraries), 'code': tikz_picture} latex_document = latex_template.substitute(mapping) pdf_content = run_latex(latex_document) if args.save: with open(args.save, 'wb') as save_pdf: save_pdf.write(pdf_content) if fmt is Format.SVG: data = {'image/svg+xml': convert_pdf2svg(pdf_content)} displaypub.publish_display_data(data=data, metadata={'isolated' : 'true'}) elif fmt is Format.PNG: return display.Image(convert_pdf2png(pdf_content))
def pendown(self): """ Change the state of the pen, If the pen is down then the turtle will not draw when it moves. """ strone = str(1) command = " penStatus " + strone publish_display_data('pacturtle.pendown', {'turtle':command}) self.penStatus = 1
def pensize(self, size): """ Change the size of the line drawn by the turtle to the parameter size """ strsize = str(size); command = " penSize " + strsize publish_display_data('pacturtle.pensize', {'turtle':command}) penSize = size;
def notebook_connect(self): if self.docname is None: raise RuntimeError("usedoc() must be called before notebook_connect()") import IPython.core.displaypub as displaypub msg = """<p>Connecting notebook to document "%s" at server %s</p>""" % \ (self.docname, self.root_url) displaypub.publish_display_data('bokeh', {'text/html': msg}) return None
def penup(self): """ Change the state of the pen, If the pen is up then the turtle will no longer draw when it moves. """ strzero = str(0); command = " penStatus " + strzero publish_display_data('pacturtle.penup', {'turtle':command}) self.penDrawing = 0
def right(self, angle): """ Rotate the turtle clockwise by the parameter angle measured in Euler angles. """ stringangle = str(angle) command = " rotate " + stringangle publish_display_data('pacturtle.rotate', {'turtle':command}) self.turtleAngle = self.turtleAngle + angle
def speed(self, speed): """ Setter for the speed that the turtle animates. """ stringspeed = str(speed) command = " speed " + stringspeed publish_display_data('pacturtle.speed', {'turtle':command}) self.turtleSpeed = speed
def notebook_connect(self): if self.docname is None: raise RuntimeError("usedoc() must be called before notebook_connect()") import IPython.core.displaypub as displaypub msg = """<p>Connecting notebook to document "%s" at server %s</p>""" % \ (self.docname, self.root_url) displaypub.publish_display_data('bokeh', {'text/html': msg}) return None
def diag(self, line, cell, command): """Create sequence diagram using supplied diag methods.""" code = cell + u'\n' # if inkscape is available create SVG for either case if self.inkscape_available(): global _draw_mode _draw_mode = 'SVG' try: tmpdir = tempfile.mkdtemp() fd, diag_name = tempfile.mkstemp(dir=tmpdir) f = os.fdopen(fd, "wb") f.write(code.encode('utf-8')) f.close() format = _draw_mode.lower() draw_name = diag_name + '.' + format saved_argv = sys.argv argv = [diag_name, '-T', format, '-o', draw_name] # if os.path.exists(fontpath): # sys.argv += ['-f', fontpath] # do not use PIL library when rendering to SVG # this allows avoid problem with handling unicode in diagram if _draw_mode == 'SVG': argv += [''] # Run command command.main(argv) if _draw_mode == 'SVG' and _publish_mode == 'PNG': # render SVG with inkscape self.svg2png(diag_name) file_name = diag_name + '.' + _publish_mode.lower() with io.open(file_name, 'rb') as f: data = f.read() f.close() finally: for file in os.listdir(tmpdir): os.unlink(tmpdir + "/" + file) os.rmdir(tmpdir) if _publish_mode == 'SVG': publish_display_data( u'IPython.core.displaypub.publish_svg', None, {'image/svg+xml':data} ) else: publish_display_data( {'image/png':data}, None, u'IPython.core.displaypub.publish_png', )
def __init__(self): self.output_id = 'ipython_nose_%s' % uuid.uuid4().hex displaypub.publish_display_data( u'IPython.core.displaypub.publish_html', {'text/html':'<div id="%s"></div>' % self.output_id}) displaypub.publish_display_data( u'IPython.core.displaypub.publish_javascript', {'application/javascript': 'document.%s = $("#%s");' % (self.output_id, self.output_id)})
def notebooksources(self): import IPython.core.displaypub as displaypub template = get_template('source_block.html') html = template.render( rawjs = dump.inline_scripts(dump.script_paths).decode('utf8'), rawcss = dump.inline_css(dump.css_paths).decode('utf8') ) displaypub.publish_display_data('bokeh', {'text/html': html}) return None
def cry(self, line, cell=None): ''' Add the code to the current module in the Cryptol2 context. ''' if None == cell: out = "" else: out = self.cryptol.addModuleFragment(cell) publish_display_data("cryptol2magic", {'text/plain' : out})
def __init__(self): self.output_id = 'ipython_nose_%s' % uuid.uuid4().hex displaypub.publish_display_data( u'IPython.core.displaypub.publish_html', {'text/html': '<div id="%s"></div>' % self.output_id}) displaypub.publish_display_data( u'IPython.core.displaypub.publish_javascript', { 'application/javascript': 'document.%s = $("#%s");' % (self.output_id, self.output_id) })
def _run_and_display(self, compiled_code): display_data = self.generate_plots(compiled_code) for tag, disp_d in display_data: if self.plot_format == 'svg': # isolate data in an iframe, to prevent clashing glyph declarations in SVG publish_display_data(source=tag, data=disp_d, metadata={'isolated': 'true'}) else: publish_display_data(source=tag, data=disp_d, metadata=None)
def cry(self, line, cell=None): ''' Add the code to the current module in the Cryptol2 context. ''' if None == cell: out = "" else: out = self.cryptol.addModuleFragment(cell) publish_display_data("cryptol2magic", {'text/plain': out})
def show(browser=None, new="tab", url=None): """ 'shows' the current plot, by auto-raising the window or tab displaying the current plot (for file/server output modes) or displaying it in an output cell (IPython notebook). Args: browser (str, optional) : browser to show with (default: None) For systems that support it, the **browser** argument allows specifying which browser to display in, e.g. "safari", "firefox", "opera", "windows-default". (See the webbrowser module documentation in the standard lib for more details.) new (str, optional) : new file output mode (default: "tab") For file-based output, opens or raises the browser window showing the current output file. If **new** is 'tab', then opens a new tab. If **new** is 'window', then opens a new window. """ filename = _default_file['filename'] if _default_file else None session = cursession() notebook = _default_notebook # Map our string argument to the webbrowser.open argument new_param = {'tab': 2, 'window': 1}[new] controller = browserlib.get_browser_controller(browser=browser) plot = curplot() if not plot: warnings.warn( "No current plot to show. Use renderer functions (circle, rect, etc.) to create a current plot (see http://bokeh.pydata.org/index.html)" ) return if notebook and session: import IPython.core.displaypub as displaypub push(session=session) snippet = autoload_server(plot, cursession()) displaypub.publish_display_data('bokeh', {'text/html': snippet}) elif notebook: import IPython.core.displaypub as displaypub displaypub.publish_display_data('bokeh', {'text/html': notebook_div(plot)}) elif session: push() if url: controller.open(url, new=new_param) else: controller.open(session.object_link(curdoc()._plotcontext)) elif filename: save(filename) controller.open("file://" + os.path.abspath(filename), new=new_param)
def icry(self, line, cell=None): ''' Execute code in Cryptol2 and return results including errors if there are any. ''' if None == cell: out = "" else: out = self.cryptol.runInteractive(cell) publish_display_data("cryptol2magic", {'text/plain' : out})
def cryauto(self, line, cell=None): """ Execute code in either module or interactive mode in Cryptol 2, depending on which one successfully parses. """ if None == cell: out = "" else: out = self.cryptol.runAuto(cell) publish_display_data("cryptol2magic", {'text/plain' : out})
def notebooksources(self): import IPython.core.displaypub as displaypub js_paths = self.js_paths() css_paths = self.css_paths() html = self._load_template(self.html_template).render( rawjs=self._inline_files(js_paths), rawcss=self._inline_files(css_paths), js_snippets=[], html_snippets=["<p>Configuring embedded BokehJS mode.</p>"]) displaypub.publish_display_data('bokeh', {'text/html': html}) return None
def publish(self): # if self.html: # IPython.core.displaypub.publish_html(self._repr_html_()) # else: # IPython.core.displaypub.publish_pretty(self.txt) if self.html: publish_display_data("ipython_doctester", {'text/html': self._repr_html_()}) else: publish_display_data("ipython_doctester", {'text/plain': self.txt})
def notebooksources(self): import IPython.core.displaypub as displaypub js_paths = self.js_paths() css_paths = self.css_paths() html = self._load_template(self.html_template).render( rawjs=self._inline_files(js_paths), rawcss=self._inline_files(css_paths), js_snippets=[], html_snippets=["<p>Configuring embedded BokehJS mode.</p>"]) displaypub.publish_display_data('bokeh', {'text/html': html}) return None
def notebooksources(self): import IPython.core.displaypub as displaypub script_paths = NotebookSession.notebookscript_paths css_paths = self.css_paths() html = self._load_template("basediv.html").render( rawjs=self._inline_scripts(script_paths).decode('utf8'), rawcss=self._inline_css(css_paths).decode('utf8'), js_snippets=[], html_snippets=["<p>Bokeh Sources</p>"]) displaypub.publish_display_data('bokeh', {'text/html': html}) return None
def notebooksources(self): import IPython.core.displaypub as displaypub script_paths = NotebookSession.notebookscript_paths css_paths = self.css_paths() html = self._load_template("basediv.html").render( rawjs=self._inline_scripts(script_paths).decode('utf8'), rawcss=self._inline_css(css_paths).decode('utf8'), js_snippets=[], html_snippets=["<p>Bokeh Sources</p>"]) displaypub.publish_display_data('bokeh', {'text/html': html}) return None
def icry(self, line, cell=None): ''' Execute code in Cryptol2 and return results including errors if there are any. ''' if None == cell: out = "" else: out = self.cryptol.runInteractive(cell) publish_display_data("cryptol2magic", {'text/plain': out})
def cryauto(self, line, cell=None): """ Execute code in either module or interactive mode in Cryptol 2, depending on which one successfully parses. """ if None == cell: out = "" else: out = self.cryptol.runAuto(cell) publish_display_data("cryptol2magic", {'text/plain': out})
def cite(self, line, cell): if len(line)>0: cell=line+'\n'+cell for c in self.citeRe.finditer(cell): refs=[self.cite['p'][ref.strip()] if c.group('mode')=='p' else self.cite['t'][ref.strip()] for ref in c.group('cite').split(',')] cell=cell.replace('\\'+c.group('all'), '; '.join(refs) if c.group('mode')!='p' else '('+'; '.join(refs)+')') publish_display_data('printTex', { 'text/html': markdown(cell), 'text/plain': self.wrapText(cell) })
def publish(self): # if self.html: # IPython.core.displaypub.publish_html(self._repr_html_()) # else: # IPython.core.displaypub.publish_pretty(self.txt) if self.html: publish_display_data("ipython_doctester", {'text/html': self._repr_html_()}) else: publish_display_data("ipython_doctester", {'text/plain': self.txt})
def show(self, *objects): """ Displays the given objects, or all objects currently associated with the session, inline in the IPython Notebook. Basicall we return a dummy object that implements _repr_html. The reason to do this instead of just having this session object implement _repr_html directly is because users will usually want to just see one or two plots, and not all the plots and models associated with the session. """ import IPython.core.displaypub as displaypub displaypub.publish_display_data('bokeh', {'text/html': self.dumps(*objects)})
def show(self, *objects): """ Displays the given objects, or all objects currently associated with the session, inline in the IPython Notebook. Basicall we return a dummy object that implements _repr_html. The reason to do this instead of just having this session object implement _repr_html directly is because users will usually want to just see one or two plots, and not all the plots and models associated with the session. """ import IPython.core.displaypub as displaypub displaypub.publish_display_data('bokeh', {'text/html': self.dumps(*objects)})
def show(browser=None, new="tab", url=None): """ 'shows' the current plot, by auto-raising the window or tab displaying the current plot (for file/server output modes) or displaying it in an output cell (IPython notebook). Args: browser (str, optional) : browser to show with (default: None) For systems that support it, the **browser** argument allows specifying which browser to display in, e.g. "safari", "firefox", "opera", "windows-default". (See the webbrowser module documentation in the standard lib for more details.) new (str, optional) : new file output mode (default: "tab") For file-based output, opens or raises the browser window showing the current output file. If **new** is 'tab', then opens a new tab. If **new** is 'window', then opens a new window. """ filename = _default_file['filename'] if _default_file else None session = cursession() notebook = _default_notebook # Map our string argument to the webbrowser.open argument new_param = {'tab': 2, 'window': 1}[new] controller = browserlib.get_browser_controller(browser=browser) plot = curplot() if not plot: warnings.warn("No current plot to show. Use renderer functions (circle, rect, etc.) to create a current plot") return if notebook and session: import IPython.core.displaypub as displaypub push(session=session) snippet = autoload_server(plot, cursession()) displaypub.publish_display_data('bokeh', {'text/html': snippet}) elif notebook: import IPython.core.displaypub as displaypub displaypub.publish_display_data('bokeh', {'text/html': notebook_div(plot)}) elif session: push() if url: controller.open(url, new=new_param) else: controller.open(session.object_link(curdoc()._plotcontext)) elif filename: save(filename) controller.open("file://" + os.path.abspath(filename), new=new_param)
def initialize(): from IPython.core.displaypub import publish_display_data js = ('js9support.js', 'js9.js', 'js9plugins.js') css = ('js9support.css', 'js9.css') for file_ in js: data = open(path.join(STATIC, file_), 'rb').read() publish_display_data(data={'application/javascript': data}) for file_ in css: data = open(path.join(STATIC, file_), 'r').read() data = '<style>' + data + '</style>' publish_display_data(data={'text/html': data})
def notebook(self): import IPython.core.displaypub as displaypub html = self.plotclient.make_html( self.allmodels(), model=self.gridmodel, inline=True, template="plot.html", script_paths=[], css_paths=[] ) html = html.encode('utf-8') displaypub.publish_display_data('bokeh', {'text/html': html}) return None
def publish_display_data(data, source='bokeh'): """Compatibility wrapper for IPython publish_display_data which removes the `source` (first) argument in later versions. Parameters ---------- source : str data : dict """ import IPython.core.displaypub as displaypub try: displaypub.publish_display_data(source, data) except TypeError: displaypub.publish_display_data(data)
def notebooksources(self): import IPython.core.displaypub as displaypub # Normally this would call self.js_paths() to build a list of # scripts or get a reference to the unified/minified JS file, # but our static JS build process produces a single unified # bokehJS file for inclusion in the notebook. js_paths = self.js_files css_paths = self.css_paths() html = self._load_template(self.html_template).render( rawjs=self._inline_scripts(js_paths).decode('utf8'), rawcss=self._inline_css(css_paths).decode('utf8'), js_snippets=[], html_snippets=["<p>Configuring embedded BokehJS mode.</p>"]) displaypub.publish_display_data('bokeh', {'text/html': html}) return None
def send_svg_figure(fig): """Draw the current figure and send it as an SVG payload. """ # For an empty figure, don't even bother calling figure_to_svg, to avoid # big blank spaces in the qt console if not fig.axes: return svg = figure_to_svg(fig) # flush text streams before sending figures, helps a little with output # synchronization in the console (though it's a bandaid, not a real sln) sys.stdout.flush() sys.stderr.flush() publish_display_data('IPython.zmq.pylab.backend_inline.send_svg_figure', 'Matplotlib Plot', {'image/svg+xml': svg})
def notebook_connect(self): import IPython.core.displaypub as displaypub js = get_template('connect.js').render( username=self.username, root_url=self.root_url, docid=self.docid, docapikey=self.apikey, ws_conn_string=self.ws_conn_string) msg = """ <p>Connection Information for this %s document, only share with people you trust </p> """ % self.docname html = self.html(script_paths=[], css_paths=[], js_snippets=[js], html_snippets=[msg], template="basediv.html") displaypub.publish_display_data('bokeh', {'text/html': html}) return None
def send_figure(fig): """Draw the given figure and send it as a PNG payload. """ fmt = InlineBackend.instance().figure_format data = print_figure(fig, fmt) # print_figure will return None if there's nothing to draw: if data is None: return mimetypes = {'png': 'image/png', 'svg': 'image/svg+xml'} mime = mimetypes[fmt] # flush text streams before sending figures, helps a little with output # synchronization in the console (though it's a bandaid, not a real sln) sys.stdout.flush() sys.stderr.flush() publish_display_data('IPython.zmq.pylab.backend_inline.send_figure', {mime: data})
def publish_display_data(data, source='bokeh'): ''' Compatibility wrapper for IPython ``publish_display_data`` Later versions of IPython remove the ``source`` (first) argument. This function insulates Bokeh library code from this change. Args: source (str, optional) : the source arg for IPython (default: "bokeh") data (dict) : the data dict to pass to ``publish_display_data`` Typically has the form ``{'text/html': html}`` ''' import IPython.core.displaypub as displaypub try: displaypub.publish_display_data(source, data) except TypeError: displaypub.publish_display_data(data)
def cite(self, line, cell): if len(line) > 0: cell = line + '\n' + cell for c in self.citeRe.finditer(cell): refs = [ self.cite['p'][ref.strip()] if c.group('mode') == 'p' else self.cite['t'][ref.strip()] for ref in c.group('cite').split(',') ] cell = cell.replace( '\\' + c.group('all'), '; '.join(refs) if c.group('mode') != 'p' else '(' + '; '.join(refs) + ')') publish_display_data('printTex', { 'text/html': markdown(cell), 'text/plain': self.wrapText(cell) })
def send_figure(fig): """Draw the current figure and send it as a PNG payload. """ # For an empty figure, don't even bother calling figure_to_svg, to avoid # big blank spaces in the qt console if not fig.axes: return fmt = InlineBackendConfig.instance().figure_format data = print_figure(fig, fmt) mimetypes = {'png': 'image/png', 'svg': 'image/svg+xml'} mime = mimetypes[fmt] # flush text streams before sending figures, helps a little with output # synchronization in the console (though it's a bandaid, not a real sln) sys.stdout.flush() sys.stderr.flush() publish_display_data('IPython.zmq.pylab.backend_inline.send_figure', 'Matplotlib Plot', {mime: data})
def doLine(self,line,no_result = False): """Method to convert and print one line """ #check for assignment i = line.find("=") if i<0 or line[i+1]=='=': # no assignment : print expression = result result = self.shell.ev(line) publish_display_data('PrettyPrint', {'text/latex': "$$"+self.py2tex(line)+" = "+self.numericToString(result)+"$$", 'text/plain': line+" = "+self.numericToString(result)}) else: # expression was assignment variable = line[:i].strip() expression = line[i+1:].strip() result = self.shell.ev(expression) self.shell.push({variable: result}) temp = re.findall('[-+]?\d*\.\d+[eE][-+]?\d+|[-+]?\d*\.\d+|[-+]?\d+', expression.strip()) try: temp=float(expression) # assignment: variable = number publish_display_data('PrettyPrint', {'text/latex': "$$"+self.parseVariable(variable.strip())+" = "+self.py2tex(expression)+"$$", 'text/plain': line}) except ValueError: if no_result: # assignment: variable = expression publish_display_data('PrettyPrint', {'text/latex': "$$"+self.parseVariable(variable.strip())+" = "+self.py2tex(expression)+"$$", 'text/plain': line}) else: # assignment: variable = expression = number # unit is always an expression so test first if self.isUnumAssignment(expression): #unit assignment, print only result publish_display_data('PrettyPrint', {'text/latex': "$$"+self.parseVariable(variable.strip())+" = "+self.numericToString(self.shell.ev(expression))+"$$", 'text/plain': line+" = "+self.numericToString(self.shell.ev(variable.strip()))}) else: # assignment: variable = expression = number publish_display_data('PrettyPrint', {'text/latex': "$$"+self.parseVariable(variable.strip())+" = "+self.py2tex(expression)+" = "+self.numericToString(self.shell.ev(variable.strip()))+"$$", 'text/plain': line+" = "+self.numericToString(self.shell.ev(variable.strip()))})
def notebook_connect(self): import IPython.core.displaypub as displaypub js = self._load_template('connect.js').render( username=self.username, root_url = self.root_url, docid=self.docid, docapikey=self.apikey, ws_conn_string=self.ws_conn_string() ) msg = """ <p>Connection Information for this %s document, only share with people you trust </p> """ % self.docname script_paths = self.js_paths() css_paths = self.css_paths() html = self._load_template("basediv.html").render( rawjs=self._inline_scripts(script_paths).decode('utf8'), rawcss=self._inline_css(css_paths).decode('utf8'), js_snippets=[js], html_snippets=[msg]) displaypub.publish_display_data('bokeh', {'text/html': html}) return None
def generate_plots(self, compiled_code): display_data = [] with make_tempdir() as plot_dir: latex_log = run_latex(compiled_code, plot_dir, self.encoding) # If the latex error log exists, then image generation has failed. # Publish error log and return immediately if latex_log: publish_display_data(source=self._key, data={'text/plain': latex_log}) else: _convert_img_format(plot_dir, self.plot_format) image_filename = "%s/tikz.%s" % (plot_dir, self.plot_format) img = self._publish_image(image_filename) if img is not None: display_data.append((self._key, img)) self._save_if_requested(image_filename) return display_data