コード例 #1
0
def install_nbextension(ip):
    """install the gist javascript extension, and load it in custom.js"""

    gist_js = os.path.join(ip.ipython_dir, 'nbextensions', 'gistcomm.js')
    url = "http://rawgithub.com/minrk/ipython_extensions/master/nbextensions/gistcomm.js"
    here = os.path.dirname(__file__)
    if not os.path.exists(gist_js):
        local_gist_js = os.path.join(here, 'gistcomm.js')
        if os.path.exists(local_gist_js):
            print("installing gistcomm.js from %s" % local_gist_js)
            gist_f = open(local_gist_js)
        else:
            print("installing gistcomm.js from %s" % url)
            gist_f = urllib2.urlopen(url)
        with open(gist_js, 'w') as f:
            f.write(gist_f.read())
        gist_f.close()

    custom_js = os.path.join(ip.profile_dir.location, 'static', 'custom',
                             'custom.js')
    already_required = False
    if os.path.exists(custom_js):
        with open(custom_js, 'r') as f:
            js = f.read()
        already_required = "nbextensions/gist" in js

    if not already_required:
        print("loading gist button into custom.js")
        with open(custom_js, 'a') as f:
            f.write(load_js)
        display_javascript(load_js, raw=True)
コード例 #2
0
 def _ipython_display_(self):
     js = """
       require(["https://rawgit.com/caldwell/renderjson/master/renderjson.js"], function() {
       renderjson.set_show_to_level(1)
       renderjson.set_sort_objects(true)
       renderjson.set_icons('▶', '▼')
       document.getElementById('%s').appendChild(renderjson(%s))
     });
     """ % (self.uuid, self.json_str)
     css = """
       .renderjson a { text-decoration: none; }
       .renderjson .disclosure { color: grey; text-decoration: none; }
       .renderjson .syntax { color: grey; }
       .renderjson .string { color: darkred; }
       .renderjson .number { color: darkcyan; }
       .renderjson .boolean { color: blueviolet; }
       .renderjson .key    { color: darkblue; }
       .renderjson .keyword { color: blue; }
       .renderjson .object.syntax { color: lightseagreen; }
       .renderjson .array.syntax  { color: orange; }
       """
     display_html(
         '<style>{}</style><div id="{}" style="height: 100%; width:100%;"></div>'
         .format(css, self.uuid),
         raw=True)
     display_javascript(js, raw=True)
コード例 #3
0
ファイル: nvd3.py プロジェクト: marcogiusti/nvd3_py
    def _ipython_display_(self):
        from IPython.display import display_javascript, display_html
        from IPython.display import Javascript

        jscode = self.js()
        display_javascript(Javascript(jscode, lib=[D3, NVD3], css=[NVD3_CSS]))
        display_html(self.html(), raw=True)
コード例 #4
0
ファイル: __init__.py プロジェクト: zvasicek/renderjson
    def _ipython_display_(self):
        display_html("""<style>
                        .renderjson {background:%s;padding:10px;color:%s}
                        .renderjson a              { color:lightblue; text-decoration: none; }
                        .renderjson .disclosure    { color: crimson; font-size: 80%%; }
                        .xrenderjson .syntax        { color: blue; }
                        .renderjson .string        { color: #90a959; }
                        .renderjson .number        { color: plum; }
                        .renderjson .boolean       { color: #d28445; }
                        .renderjson .key           { color: #90a959; }
                        .renderjson .keyword       { color: #d28445; }
                        .xrenderjson .object.syntax { color: #ddd; }
                        .renderjson .array.syntax  { color: #fff; }
                        </style>
                        <div id="%s" style="width:100%%;"></div>""" %
                     (self.bg_color, self.text_color, self.uuid),
                     raw=True)

        display_javascript("""
        require(["https://rawgit.com/caldwell/renderjson/master/renderjson.js"], function(r) {
            var node = document.getElementById('%s');
            node.innerHTML = ''; // vola se 2x neznamo proc
            node.appendChild(renderjson.set_icons('\u25BA', '\u25BC').set_show_to_level(%s)(%s));
            return true;
        });
        """ % (self.uuid, self.show_to_level, self.json_str),
                           raw=True)
コード例 #5
0
def init_plotly_online_mode():
    from IPython.display import display_javascript
    from plotly import offline
    offline.offline.__PLOTLY_OFFLINE_INITIALIZED = True
    jscode = """
    require.config({
      paths: {
        d3: 'http://cdnjs.cloudflare.com/ajax/libs/d3/3.5.16/d3.min',
        plotly: 'http://cdn.plot.ly/plotly-1.10.0.min',
        jquery: 'https://code.jquery.com/jquery-migrate-1.4.1.min'
      },

      shim: {
        plotly: {
          deps: ['d3', 'jquery'],
          exports: 'plotly'
        }
      }
    });

    require(['d3', 'plotly'], function(d3, plotly) {
        window.Plotly = plotly;
    });
    """
    display_javascript(jscode, raw=True)
コード例 #6
0
 def _ipython_display_(self):
     display_html('<div id="{}" style="height: 600px; width:100%;"></div>'.format(self.uuid), raw=True)
     display_javascript("""
     require(["https://rawgit.com/caldwell/renderjson/master/renderjson.js"], function() {
     document.getElementById('%s').appendChild(renderjson(%s))
     });
     """ % (self.uuid, self.json_str), raw=True)
コード例 #7
0
ファイル: grid.py プロジェクト: jamalsenouci/qgrid
    def _ipython_display_(self):
        try:
            column_types_json = json.dumps(self.column_types)
            data_frame_json = self.df_copy.to_json(
                orient='records',
                date_format='iso',
                double_precision=self.precision,
            )
            options_json = json.dumps(self.grid_options)

            if self.remote_js:
                cdn_base_url = \
                    "https://cdn.rawgit.com/quantopian/qgrid/72d356cb123fab413dba73ec46616e4916fbd827/qgrid/qgridjs/"
            else:
                cdn_base_url = "/nbextensions/qgridjs"

            raw_html = SLICK_GRID_CSS.format(
                div_id=self.div_id,
                cdn_base_url=cdn_base_url,
            )
            raw_js = SLICK_GRID_JS.format(
                cdn_base_url=cdn_base_url,
                div_id=self.div_id,
                data_frame_json=data_frame_json,
                column_types_json=column_types_json,
                options_json=options_json,
            )

            display_html(raw_html, raw=True)
            display_javascript(raw_js, raw=True)
        except Exception as err:
            display_html('ERROR: {}'.format(str(err)), raw=True)
コード例 #8
0
def load_ipython_extension(ipython):
    # Change input cell syntax highlighting to SQL
    js = "IPython.CodeCell.options_default.highlight_modes['magic_sql'] = {'reg':[/^%%sqlflow/]};"
    display_javascript(js, raw=True)

    magics = SqlFlowMagic(ipython)
    ipython.register_magics(magics)
コード例 #9
0
ファイル: __init__.py プロジェクト: djsutherland/vaex
    def ____ipython_display_(self):
        #base64 = file(os.path.join(base_path, "data.png")).read().encode("base64").replace("\n", "")
        #base64_colormap  = file(os.path.join(base_path, "colormap.png")).read().encode("base64").replace("\n", "")
        #print base64[:10]
        #code = "base64 = '" + base64 + "'; base64_colormap = '" + base64_colormap + "';"
        display_javascript(open(os.path.join(base_path, "all.js")).read(),
                           raw=True)
        display_javascript(file(
            os.path.join(base_path, "vaex_volumerendering.js")).read(),
                           raw=True)
        display_html(file(os.path.join(base_path, "snippet.js")).read(),
                     raw=True)
        html1 = file(os.path.join(base_path, "snippet.html")).read()
        display_html(html1, raw=True)
        #print "ok"
        display_html("""<div>BLAAT</div> """, raw=True)

        if 0:
            js1 = file(os.path.join(base_path, "snippet.js")).read()
            js2 = file(os.path.join(base_path,
                                    "vaex_volumerendering.js")).read()
            js_lib = file(os.path.join(base_path, "all.js")).read()
            html1 = file(os.path.join(base_path, "snippet.html")).read()
            HTML("<script>" + js_lib + "\n" + code + "</script>" + "<script>" +
                 js2 + "</script>" + html1 + js1)
コード例 #10
0
ファイル: gist.py プロジェクト: B-Rich/ipython_extensions
def install_nbextension(ip):
    """install the gist javascript extension, and load it in custom.js"""
    
    gist_js = os.path.join(ip.ipython_dir, 'nbextensions', 'gistcomm.js')
    url = "http://rawgithub.com/minrk/ipython_extensions/master/nbextensions/gistcomm.js"
    here = os.path.dirname(__file__)
    if not os.path.exists(gist_js):
        local_gist_js = os.path.join(here, 'gistcomm.js')
        if os.path.exists(local_gist_js):
            print ("installing gistcomm.js from %s" % local_gist_js)
            gist_f = open(local_gist_js)
        else:
            print ("installing gistcomm.js from %s" % url)
            gist_f = urllib2.urlopen(url)
        with open(gist_js, 'w') as f:
            f.write(gist_f.read())
        gist_f.close()
    
    custom_js = os.path.join(ip.profile_dir.location, 'static', 'custom', 'custom.js')
    already_required = False
    if os.path.exists(custom_js):
        with open(custom_js, 'r') as f:
            js = f.read()
        already_required = "nbextensions/gist" in js
    
    if not already_required:
        print("loading gist button into custom.js")
        with open(custom_js, 'a') as f:
            f.write(load_js)
        display_javascript(load_js, raw=True);
コード例 #11
0
ファイル: myhdlpeek.py プロジェクト: juhasch/myhdlpeek
def wavejson_to_wavedrom(wavejson, width=None):
    '''
    Create WaveDrom display from WaveJSON data.

    This code is from https://github.com/witchard/ipython-wavedrom.
    '''

    # 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/default.js'
            ]))

    # 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 = '''
コード例 #12
0
 def set_extra_text(self, text):
     super(ProgressBarIPyNb, self).set_extra_text(text)
     if self.quiet:
         return
     display_javascript('$("#%s > .text > .extra").text("|||| %s")' %
                        (self.html_id, text),
                        raw=True)
コード例 #13
0
ファイル: grid.py プロジェクト: douglas-larocca/qgrid
    def _ipython_display_(self):
        try:
            column_types_json = json.dumps(self.column_types)
            data_frame_json = self.df_copy.to_json(
                orient='records',
                date_format='iso',
                double_precision=self.precision,
            )

            if self.remote_js:
                cdn_base_url = \
                    "https://cdn.rawgit.com/quantopian/qgrid/ddf33c0efb813cd574f3838f6cf1fd584b733621/qgrid/qgridjs/"
            else:
                cdn_base_url = "/nbextensions/qgridjs"

            raw_html = SLICK_GRID_CSS.format(
                div_id=self.div_id,
                cdn_base_url=cdn_base_url,
            )
            raw_js = SLICK_GRID_JS.format(
                cdn_base_url=cdn_base_url,
                div_id=self.div_id,
                data_frame_json=data_frame_json,
                column_types_json=column_types_json,
            )

            display_html(raw_html, raw=True)
            display_javascript(raw_js, raw=True)
        except Exception as err:
            display_html('ERROR: {}'.format(str(err)), raw=True)
コード例 #14
0
def init_plotly_offline_mode():
    from IPython.display import display_javascript
    import shutil
    from plotly import offline
    from os import path
    offline.offline.__PLOTLY_OFFLINE_INITIALIZED = True
    shutil.copy(path.join(offline.__path__[0], "plotly.min.js"), ".")

    jscode = """
    require.config({
      paths: {
        plotly: "/files/" + Jupyter.notebook.notebook_path + "/../" + "plotly.min"
      },

      shim: {
        plotly: {
          deps: [],
          exports: 'plotly'
        }
      }
    });

    require(['plotly'], function(plotly) {
        window.Plotly = plotly;
        console.log("Plotly loaded");
    });
    """
    display_javascript(jscode, raw=True)
コード例 #15
0
ファイル: __init__.py プロジェクト: jessesar/uva-questions
def set_metadata_answer(question, field):
    q = str(question)
    answer = field.value

    display_javascript(
        Javascript(
            "if('%s' in saveTimers) { clearTimeout(saveTimers['%s']); } saveTimers['%s'] = setTimeout(function() { if(!('uva_answers' in IPython.notebook.metadata)) { IPython.notebook.metadata['uva_answers'] = {} } IPython.notebook.metadata['uva_answers']['%s'] = '%s'; IPython.notebook.save_checkpoint(); }, 500)"
            % (q, q, q, q, str(answer))))
コード例 #16
0
def make_markdown_cell(s):
    display_javascript("""var t_cell = IPython.notebook.get_selected_cell()
    t_cell.set_text('<!--\\n' + t_cell.get_text() + '\\n--> \\n{}');
    var t_index = IPython.notebook.get_cells().indexOf(t_cell);
    IPython.notebook.to_markdown(t_index);
    IPython.notebook.get_cell(t_index).render();""".format(
        s.replace('\n', '\\n')),
                       raw=True)
コード例 #17
0
ファイル: bqplot.py プロジェクト: tboch/vaex
def patch(force=False):
    # return
    global patched
    if not patched or force:
        display_javascript(open(os.path.join(base_path,
                                             "bqplot_ext.js")).read(),
                           raw=True)
    patched = True
コード例 #18
0
def run_js(jscmd, force):
    if (force):
        jsf = Javascript(jscmd)
    else:
        jsf = Javascript("// Graffiti javascript\n" +
                         "if (window.Graffiti !== undefined) {\n" + jscmd +
                         "\n}\n")
    display_javascript(jsf)
コード例 #19
0
ファイル: api.py プロジェクト: OpenVSP/OpenVSP
    def _ipython_display_(self):
        if display_html is not None:
            display_html('<div id="{}" style="height: 600px; width:100%;"></div>'.format(self.__uuid), raw=True)

            display_javascript("""
                require(["https://rawgit.com/caldwell/renderjson/master/renderjson.js"], function() {
                  document.getElementById('%s').appendChild(renderjson(%s))
                });
                """ % (self.__uuid, self.json), raw=True)
コード例 #20
0
ファイル: rsp.py プロジェクト: xwq610728213/colorwave
 def _ipython_display_(self):
     display_html('<div id="{}" style="height: 150px; width:100%;"></div>'.format(self.uuid),
         raw=True
     )
     display_javascript("""
     require(["http://localhost:8080/files/renderjson.js"], function() {
       document.getElementById('%s').appendChild(renderjson(%s))
     });
     """ % (self.uuid, self.json_str), raw=True)
コード例 #21
0
def stopSparkStatus():
    js = """
    for (var i in window.myTimers) {
        clearInterval(window.myTimers[i])
    }
    window.myTimers = []
    $("#sparkStatusFooter").remove()
    """
    display_javascript(Javascript(js))
コード例 #22
0
def make_cell(s):

    display_javascript("""
    var t_cell = IPython.notebook.insert_cell_below()
    t_cell.set_text(  '{}');
    var t_index = IPython.notebook.get_cells().indexOf(t_cell);
    IPython.notebook.get_cell(t_index).render();
     """.format(s.replace('\n', '\\n')),
                       raw=True)
コード例 #23
0
ファイル: __init__.py プロジェクト: maartenbreddels/vaex
 def set(self, **kwargs):
     settings = json.dumps(kwargs)
     js_code = """var o = $('#%s').data('vr');
     var new_settings = JSON.parse('%s');
     console.log(new_settings);
     console.log($.extend(o.settings, new_settings));
     o.update_transfer_function_array()
     o.drawScene();
     """ % (self.id, settings)
     display_javascript(js_code, raw=True)
コード例 #24
0
    def _ipython_display_(self):
        display_html(html_content.replace("{{{#uuid#}}}", self.uuid).replace("{{{#domheight#}}}", self.domheight),
            raw=True
        )

                
        display_javascript("var title="+"'" + self.title + "';\n"+\
                            "var data="+self.json_str+";\n"+\
                           "var uuid='"+self.uuid+"';\n"+\
                           javascript_content , raw=True)
コード例 #25
0
ファイル: __init__.py プロジェクト: djsutherland/vaex
    def set(self, **kwargs):
        settings = json.dumps(kwargs)
        js_code = """var o = $('#%s').data('vr');
		var new_settings = JSON.parse('%s');
		console.log(new_settings);
		console.log($.extend(o.settings, new_settings));
		o.update_transfer_function_array()
		o.drawScene();
		""" % (self.id, settings)
        display_javascript(js_code, raw=True)
コード例 #26
0
 def _ipython_display_(self):
     json_already = json.dumps(self.already_run)
     json_to_run = json.dumps(self.to_run)
     display_html(
         '<div id="{}" style="height: 300px; width:80%;"'
         'data-already-run=\'{}\' '
         'data-to-run=\'{}\'></div>'.format(self.uuid, json_already,
                                          json_to_run),
         raw=True)
     display_javascript('window.turtle("{}");'.format(self.uuid),
                        raw=True)
コード例 #27
0
ファイル: render_nb_js.py プロジェクト: waternk/HecHms
 def _ipython_display_(self):
     """
     overloads method
     `_ipython_display_ <http://ipython.readthedocs.io/en/stable/config/integrating.html?highlight=Integrating%20>`_.
     """
     ht, js = self.generate_html()
     if js is None:
         display_html(ht, raw=True)
     else:
         display_html(ht, raw=True)
         display_javascript(js, raw=True)
コード例 #28
0
 def _ipython_display_(self):
     display_html(
         '<head><link rel="stylesheet" type="text/css" href="json_formatter.css"></head><body><div id="{}" style="background-color: black;"></div></body>'
         .format(self.uuid),
         raw=True)
     display_javascript("""
     require(["https://rawgit.com/caldwell/renderjson/master/renderjson.js"], function() {
       document.getElementById('%s').appendChild(renderjson(%s))
     });
     """ % (self.uuid, self.json_str),
                        raw=True)
コード例 #29
0
ファイル: __init__.py プロジェクト: gopinath678/superPy
def load_ipython_extension(ipython):
    """Called by IPython when this module is loaded as an IPython extension."""
    from .magics import _cell_magic
    from IPython.display import display_javascript

    ipython.register_magic_function(_cell_magic,
                                    magic_kind="cell",
                                    magic_name="superquery")

    # Enable syntax highlighting
    js = "IPython.CodeCell.options_default.highlight_modes['magic_sql'] = {'reg':[/^%%superquery/]};"
    display_javascript(js, raw=True)
コード例 #30
0
    def prompt_user(self):
        self.description_store.before_prompt()

        prompt_description_js = dedent("""\
        // Guard against re-execution.
        if (IPython.notebook.kernel) {
            console.log("beginning of js");
            var handle_output = function(out){
                console.log(out.msg_type);
                console.log(out);

                var res = null;
                if (out.msg_type == "stream"){
                    res = out.content.text;
                }
                // if output is a python object
                else if(out.msg_type === "execute_result"){
                    res = out.content.data["text/plain"];
                }
                // if output is a python error
                else if(out.msg_type == "error"){
                    res = out.content.ename + ": " + out.content.evalue;
                }
                // if output is something we haven't thought of
                else{
                    res = "[out type not implemented]";  
                }
                console.log(res);
            };
            var callback = {
                iopub: {
                    output : handle_output,
                }
            };
            var options = {
                silent : false,
            };

            var description = prompt("Set description", "default");
            var command = "a.description_store.set_description('" + description + "')";
            console.log("executing " + command);
            var kernel = IPython.notebook.kernel
            kernel.execute(command, callback, options);

            console.log("end of js");
        }
        """)
        jso = Javascript(prompt_description_js)
        display_javascript(jso)

        description = self.description_store.get_description()
        print("Description: {}".format(description))
        return description
コード例 #31
0
ファイル: magic.py プロジェクト: Yancey1989/pysqlflow
def load_ipython_extension(ipython):
    out_handler = logging.StreamHandler(sys.stdout)
    out_handler.setLevel(logging.INFO)
    _LOGGER.addHandler(out_handler)
    _LOGGER.setLevel(logging.INFO)

    # Change input cell syntax highlighting to SQL
    js = "IPython.CodeCell.options_default.highlight_modes['magic_sql'] = {'reg':[/^%%sqlflow/]};"
    display_javascript(js, raw=True)

    magics = SqlFlowMagic(ipython)
    ipython.register_magics(magics)
コード例 #32
0
ファイル: __init__.py プロジェクト: djsutherland/vaex
    def _ipython_display_(self):
        display_javascript(open(
            os.path.join(base_path, "glMatrix-0.9.5.min.js")).read(),
                           raw=True)
        display_javascript(open(os.path.join(base_path,
                                             "volumerenderer.js")).read(),
                           raw=True)
        #cube64 = b64encode(file(os.path.join(base_path, "cube.png")).read())
        colormap64 = b64encode(
            open(os.path.join(base_path, "colormap.png"),
                 "rb").read()).decode("ascii")
        src = """
		window.colormap_src = 'data:image/png;base64,%s';
		""" % (colormap64, )
        #print(src)
        display_javascript(src, raw=True)

        js_code = "window.shader_cache = [];\n"
        for name in ["cube", "texture", "volr"]:
            for type in ["fragment", "vertex"]:
                text = open(
                    os.path.join(base_path, "shaders",
                                 name + "-" + type + ".shader")).read()
                text = text.replace("\n", "\\n").replace("'", "\\'")
                js_code += "window.shader_cache['{name}_{type}'] = '{text}';\n".format(
                    **locals())
        display_javascript(js_code, raw=True)
コード例 #33
0
ファイル: __init__.py プロジェクト: wami12/JupyTEPIDE
 def InsertTemplate(self):
     from IPython.display import display_javascript
     config = configparser.ConfigParser()
     config.read('config.ini')
     wps_deploy_path = config['PATH']['wpsdeploypath']
     with open(wps_deploy_path + 'template.py', 'r') as content_file:
         s = content_file.read()
     text = s.replace('\n', '\\n').replace("\"", "\\\"").replace("'", "\\'")
     text2 = """var t_cell = IPython.notebook.get_selected_cell()
    t_cell.set_text('{}');
    var t_index = IPython.notebook.get_cells().indexOf(t_cell);
    IPython.notebook.to_code(t_index);
    IPython.notebook.get_cell(t_index).render();""".format(text)
     display_javascript(text2, raw=True)
コード例 #34
0
ファイル: recdict.py プロジェクト: Python3pkg/MPContribs
 def _ipython_display_(self):
     json_str, uuid_str = json.dumps(self), str(uuid.uuid4())
     display_html(
         "<div id='{}' style='width:100%;'></div>".format(uuid_str),
         raw=True)
     display_javascript("""
     require(["json.human"], function(JsonHuman) {
       "use strict";
       var data = JSON.parse('%s');
       var node = JsonHuman.format(data);
       document.getElementById('%s').appendChild(node);
     });
     """ % (json_str, uuid_str),
                        raw=True)
コード例 #35
0
ファイル: ipy.py プロジェクト: chmp/flowly
def add_toc():  # pragma: no cover
    """Add a dynamic table of contents to an ipython notebook.

    Any heading element (h1, h2, ...) in the DOM will add a link to the table of
    contents. The easiest way to add the headers is via IPythons markdown cells.
    Any edits or deletes of these cells will automatically be reflected in the
    generated table of contents.

    Usage::

        from flowly.ipy import add_toc
        add_toc()
    """
    from IPython.display import display_javascript, Javascript
    display_javascript(Javascript(js_source))
コード例 #36
0
def prepareSparkStatus():
    style = "background-color: rgba(255,255,255,0.9); z-index:100;" +\
            "position: fixed;" +\
            "left: 0; right: 0; bottom: 0; height: 45px;" +\
            "padding: 10px"
    js = """
    if (typeof(window.myTimers) == "undefined") {
        window.myTimers = []
    }

    $("#sparkStatusFooter").remove()

    $('body').append('<div id="sparkStatusFooter" style="%s"></div>');
    """ % style
    display_javascript(Javascript(js))
コード例 #37
0
def loadNVD3(nvd3version="1.8.2", d3version="3.5.17"):

    folder = os.path.dirname(__file__)
    with open(os.path.join(folder, "../js", "loadLibraries.js"), "r") as fd:
        loadLibraries = fd.read()

    js = """
        (function() {
            var loadLibraries = %s
            loadLibraries("%s", "%s", function(msg) { element.append("<div>" + msg + "</div>"); },
                                      function(msg) { element.append("<div style='color:red'>Error: " + msg + "</div>"); })
        })();
    """ % (loadLibraries, d3version, nvd3version)

    display_javascript(Javascript(js))
コード例 #38
0
ファイル: __init__.py プロジェクト: dpiparo/ROOTaaS
def iPythonize():
    utils.setStyle()
    for capture in utils.captures: capture.register()
    ExtensionManager(get_ipython()).load_extension("ROOTaaS.iPyROOT.cppmagic")
    ExtensionManager(get_ipython()).load_extension("ROOTaaS.iPyROOT.dclmagic")

    # Make sure clike JS lexer is loaded
    display.display_javascript("require(['codemirror/mode/clike/clike'], function(Clike) { console.log('ROOTaaS - C++ CodeMirror module loaded'); });", raw=True)
    # Define highlight mode for %%cpp and %%dcl magics
    display.display_javascript(utils.jsMagicHighlight.format(cppMIME = utils.cppMIME), raw=True)

    ROOT.toCpp = utils.toCpp
    ROOT.enableJSVis = utils.enableJSVis
    ROOT.disableJSVis = utils.disableJSVis

    #ROOT.toCpp()
    utils.welcomeMsg()
コード例 #39
0
ファイル: grid.py プロジェクト: Imperssonator/qgrid
    def export(self, value=None):
        if self._dirty:
            self._update_table()
        base_url = REMOTE_URL
        div_id = str(uuid.uuid4())
        grid_options = self.grid_options
        grid_options["editable"] = False

        raw_html = SLICK_GRID_CSS.format(div_id=div_id, cdn_base_url=base_url)
        raw_js = SLICK_GRID_JS.format(
            cdn_base_url=base_url,
            div_id=div_id,
            data_frame_json=self._df_json,
            column_types_json=self._column_types_json,
            options_json=json.dumps(grid_options),
        )

        display_html(raw_html, raw=True)
        display_javascript(raw_js, raw=True)
コード例 #40
0
ファイル: __init__.py プロジェクト: maartenbreddels/vaex
    def _ipython_display_(self):
        f = StringIO()
        # filename = os.path.join(base_path, "cube.png")
        if self.data is not None:
            cube_png(self.data, file=f)
        else:
            self.subspace_gridded.cube_png(file=f)
        # cube64 = "'data:image/png;base64," + b64encode(file(filename).read()) + "'"
        cube64 = "'data:image/png;base64," + b64encode(f.getvalue()).decode("ascii") + "'"
        # display_javascript("""
        # window.cube_src = 'data:image/png;base64,%s';
        # """ % (cube64, colormap64), raw=True)

        self.id = id = uuid.uuid1()
        display_html("<canvas id='{id}' width=512 height=512  style='display: inline;'/>".format(**locals()), raw=True)
        display_javascript(""" $('#%s').vr(
                $.extend({cube:%s, colormap:window.colormap_src}, %s)
                )
                """ % (id, cube64, json.dumps(self.settings)), raw=True)
コード例 #41
0
ファイル: __init__.py プロジェクト: maartenbreddels/vaex
    def ____ipython_display_(self):
        # base64 = file(os.path.join(base_path, "data.png")).read().encode("base64").replace("\n", "")
        # base64_colormap  = file(os.path.join(base_path, "colormap.png")).read().encode("base64").replace("\n", "")
        # print base64[:10]
        # code = "base64 = '" + base64 + "'; base64_colormap = '" + base64_colormap + "';"
        display_javascript(open(os.path.join(base_path, "all.js")).read(), raw=True)
        display_javascript(file(os.path.join(base_path, "vaex_volumerendering.js")).read(), raw=True)
        display_html(file(os.path.join(base_path, "snippet.js")).read(), raw=True)
        html1 = file(os.path.join(base_path, "snippet.html")).read()
        display_html(html1, raw=True)
        # print "ok"
        display_html("""<div>BLAAT</div> """, raw=True)

        if 0:
            js1 = file(os.path.join(base_path, "snippet.js")).read()
            js2 = file(os.path.join(base_path, "vaex_volumerendering.js")).read()
            js_lib = file(os.path.join(base_path, "all.js")).read()
            html1 = file(os.path.join(base_path, "snippet.html")).read()
            HTML("<script>" + js_lib + "\n" + code + "</script>" + "<script>" + js2 + "</script>" + html1 + js1)
コード例 #42
0
ファイル: ipy.py プロジェクト: chmp/flowly
def set_default_indent(num_spaces):
    """Only takes effect for new cells.
    """
    from IPython.display import Javascript, display_javascript
    display_javascript(Javascript('''
        (function() {
            "use strict";

            if(require('base/js/namespace').notebook._fully_loaded){
                run();
            }
            else{
                require('base/js/events').on('notebook_loaded.Notebook', run);
            }

            function run() {
                require("notebook/js/cell").Cell.options_default.cm_config.indentUnit = %s;
            }
        })()
    ''' % json.dumps(num_spaces)))
コード例 #43
0
ファイル: qgrid.py プロジェクト: gitter-badger/qgrid
    def _ipython_display_(self):
        try:
            column_types_json = json.dumps(self.column_types)
            data_frame_json = self.df_copy.to_json(orient='records', date_format='iso', double_precision=self.precision)

            if qgrid.remote_mode:
                cdn_base_url = "https://rawgit.com/quantopian/qgrid/master/nbextensions/qgridjs"
            else:
                cdn_base_url = "/nbextensions/qgridjs"

            raw_html = SLICK_GRID_CSS.format(div_id=self.div_id, cdn_base_url=cdn_base_url)
            raw_js = SLICK_GRID_JS.format(cdn_base_url=cdn_base_url,
                                            div_id=self.div_id,
                                            data_frame_json=data_frame_json,
                                            column_types_json=column_types_json)

            display_html(raw_html, raw=True)
            display_javascript(raw_js, raw=True)
        except Exception, err:
            display_html('ERROR: {}'.format(str(err)), raw=True)
コード例 #44
0
ファイル: grid.py プロジェクト: FinQuest/qgrid
    def export(self, value=None):
        self.update_table()
        self.remote_js = True
        div_id = str(uuid.uuid4())
        grid_options = json.loads(self.grid_options)
        grid_options['editable'] = False

        raw_html = SLICK_GRID_CSS.format(
            div_id=div_id,
            cdn_base_url=self._cdn_base_url,
        )
        raw_js = SLICK_GRID_JS.format(
            cdn_base_url=self._cdn_base_url,
            div_id=div_id,
            data_frame_json=self._df_json,
            column_types_json=self._column_types_json,
            options_json=json.dumps(grid_options),
        )

        display_html(raw_html, raw=True)
        display_javascript(raw_js, raw=True)
コード例 #45
0
ファイル: grid.py プロジェクト: a-campbell/qgrid
    def update_view_after_filter(self):

        # trigger an update of the df json
        self._bz_data_changed()
        self.remote_js = True
        div_id = str(uuid.uuid4())
        grid_options = json.loads(self.grid_options)
        grid_options['editable'] = False

        raw_html = SLICK_GRID_CSS.format(
            div_id=div_id,
            cdn_base_url=self._cdn_base_url,
        )
        raw_js = SLICK_GRID_JS.format(
            cdn_base_url=self._cdn_base_url,
            div_id=div_id,
            data_frame_json=self._df_json,
            column_types_json=self._column_types_json,
            options_json=json.dumps(grid_options),
        )
        clear_output()
        display_html(raw_html, raw=True)
        display_javascript(raw_js, raw=True)
コード例 #46
0
    def coffeescript(self, line, cell):
        opts = parse_argstring(self.coffeescript, line)
        ps = subprocess.Popen(('coffee','-sc'), stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
        ps.stdin.write(cell)
        ps.stdin.close()
        return_code = ps.wait()
        output = ps.stdout.read()
        if return_code!=0:
            print(ps.stderr.read())
            return
        if opts.verbose:
            pretty = highlight(output, self.lexer, HtmlFormatter(full=True))
            display.display_html("%s" % (pretty), raw=True)

        return display.display_javascript(output, raw=True)
コード例 #47
0
ファイル: __init__.py プロジェクト: maartenbreddels/vaex
    def _ipython_display_(self):
        display_javascript(open(os.path.join(base_path, "glMatrix-0.9.5.min.js")).read(), raw=True)
        display_javascript(open(os.path.join(base_path, "volumerenderer.js")).read(), raw=True)
        # cube64 = b64encode(file(os.path.join(base_path, "cube.png")).read())
        colormap64 = b64encode(open(os.path.join(base_path, "colormap.png"), "rb").read()).decode("ascii")
        src = """
        window.colormap_src = 'data:image/png;base64,%s';
        """ % (colormap64,)
        # print(src)
        display_javascript(src, raw=True)

        js_code = "window.shader_cache = [];\n"
        for name in ["cube", "texture", "volr"]:
            for type in ["fragment", "vertex"]:
                text = open(os.path.join(base_path, "shaders", name + "-" + type + ".shader")).read()
                text = text.replace("\n", "\\n").replace("'", "\\'")
                js_code += "window.shader_cache['{name}_{type}'] = '{text}';\n".format(**locals())
        display_javascript(js_code, raw=True)
コード例 #48
0
ファイル: __init__.py プロジェクト: gaulinmp/tqdm
from ._tqdm_gui import tgrange
from ._tqdm_pandas import tqdm_pandas
from ._main import main
from ._version import __version__  # NOQA
from ._tqdm import TqdmTypeError, TqdmKeyError, TqdmDeprecationWarning

try:
    from IPython import get_ipython
    from IPython.terminal.interactiveshell import TerminalInteractiveShell as TIShell
    ip = get_ipython()
    if ip is not None and not isinstance(ip, TIShell):
        # Then we might be in ipython notebook. Check.
        from IPython import display
        # WARNING: terrible hack below
        display.display_javascript("""IPython.notebook.kernel.execute(
                'from IPython import get_ipython;get_ipython().has_js=True');""",
                 raw=True)
        try:
            from ipywidgets import FloatProgress, Text
        except ImportError:
            from IPython.html.widgets import FloatProgress, Text
except (ImportError, AssertionError):
    # Not using IPython notebook. Default to text displays
    pass


__all__ = ['tqdm', 'tqdm_gui', 'trange', 'tgrange', 'tqdm_pandas',
           'tqdm_notebook', 'tnrange', 'main',
           'TqdmTypeError', 'TqdmKeyError', 'TqdmDeprecationWarning',
           '_tqdm', '_tqdm_notebook', '__version__']
コード例 #49
0
ファイル: bqplot_image.py プロジェクト: maartenbreddels/vaex
def patch(force=False):
    # return
    global patched
    if not patched or force:
        display_javascript(open(os.path.join(base_path, "bqplot_ext.js")).read(), raw=True)
    patched = True
コード例 #50
0
ファイル: nbtoc.py プロジェクト: mardukbp/dotfiles
def nbtoc(line):
    """add a table of contents to an IPython Notebook"""
    display_html(nbtoc_html, raw=True)
    display_javascript(nbtoc_js, raw=True)
コード例 #51
0
 def _remove(self):
     display_javascript(Javascript(
     """var elem = document.getElementById('{id}'); elem.parentNode.removeChild(elem);""".format(id = self.bar_id)))
コード例 #52
0
 def _update(self):
     display_javascript(Javascript("$('progress#{id}').val('{progress}')"\
                 .format(id = self.bar_id, progress = self.progress)))
コード例 #53
0
ファイル: gist.py プロジェクト: B-Rich/ipython_extensions
def gist(line=''):
    display_javascript("IPython.gist_button.publish_gist()", raw=True)
コード例 #54
0
 def _ipython_display_(self):
     display_html(HTML(self.genhtml(refresh=False)))
     from IPython.display import Javascript,display_javascript
     a = Javascript('jump(\'#endofpage\')')
     display_javascript(a)
コード例 #55
0
ファイル: newturtle.py プロジェクト: denisgarci/ipythonturtle
 def _ipython_display_(self):
     json_data = json.dumps({'already': self.already_run, 'to_run': self.to_run})
     display_html('<div id="{}" style="height: 300px; width:80%;" data-already-run="{}" data-to-run="{}"></div><script>window.turtle("{}");</script>'.format(self.uuid, self.already_run, self.to_run, self.uuid), raw=True)
     display_javascript('alert("hi!"); console.log({})'.format(json_data))
コード例 #56
0
$([IPython.events]).on('status_started.Kernel notebook_loaded.Notebook', launch_first_cell);
</script>

<p>Press this button to show/hide the code used in the notebook:
<input type="button" class="ui-button ui-widget ui-state-default \
ui-corner-all ui-button-text-only" value="Hide input" id="onoff" \
onclick="onoff();"></p>
"""

hide_outside_ipython = """<script type=text/javascript>
$(document).ready(function (){if(!("IPython" in window)){onoff();}})
</script>"""

# In order to make the notebooks readable through nbviewer we want to hide the
# code by default. However the same code is executed by the students, and in
# that case we don't want to hide the code. So we check if the code is executed
# by one of the mooc developers. Here we do by simply checking for some files that
# belong to the internal mooc repository, but are not published.
# This is a temporary solution, and should be improved in the long run.

if os.path.exists(os.path.join(module_dir, os.path.pardir, 'scripts')):
    nb_html_header += hide_outside_ipython

display_html(display.HTML(nb_html_header))

with open(os.path.join(module_dir, 'make_toc.js')) as f:
    js = f.read()
js += "$([IPython.events]).on('status_started.Kernel notebook_loaded.Notebook', table_of_contents);"
display.display_javascript(display.Javascript(js))
コード例 #57
0
ファイル: secnum.py プロジェクト: dcherian/configs
def secnum(line):
    """add a table of contents to an IPython Notebook"""
    display_javascript(secnum_js, raw=True)
コード例 #58
0
ファイル: __init__.py プロジェクト: thedataincubator/ihtml
# Copyright 2016 The Data Incubator
# ihtml is distributed under the terms of the BSD 3-Clause License
# https://github.com/thedataincubator/ihtml

from IPython.display import display_javascript
from .ihtmlmagic import IHtmlMagics


get_ipython().register_magics(IHtmlMagics)
display_javascript("""
function add_highlight_mode(mode, pattern) {
    var modes = Jupyter.CodeCell.options_default.highlight_modes;
    var mode_name = 'magic_' + mode;
    if (!modes[mode_name])
        modes[mode_name] = {};
    if (!modes[mode_name]['reg'])
        modes[mode_name]['reg'] = [];
    modes[mode_name]['reg'].push(pattern);
}
add_highlight_mode('html', /^%%ihtml/);
add_highlight_mode('javascript', /^%%jsdoc/);
add_highlight_mode('css', /^%%cssdoc/);
""", raw=True)
コード例 #59
0
ファイル: helpers.py プロジェクト: gsi-upm/sitc
The tests in the notebooks rely on the `LAST_QUERY` variable, which is updated by the `%%sparql` magic after every query.
This variable contains the full query used (`LAST_QUERY["query"]`), the endpoint it was sent to (`LAST_QUERY["endpoint"]`), and a dictionary with the response of the endpoint (`LAST_QUERY["results"]`).
For convenience, the results are also given as tuples (`LAST_QUERY["tuples"]`), and as a dictionary of of `{column:[values]}` (`LAST_QUERY["columns"]`).
'''
from IPython.core.magic import (register_line_magic, register_cell_magic,
                                register_line_cell_magic)
from IPython.display import HTML, display, Image, display_javascript
from urllib.request import Request, urlopen
from urllib.parse import quote_plus, urlencode
from urllib.error import HTTPError

import json
import sys

js = "IPython.CodeCell.options_default.highlight_modes['magic_sparql'] = {'reg':[/^%%sparql/]};"
display_javascript(js, raw=True)


def send_query(query, endpoint):
    FORMATS = ",".join(["application/sparql-results+json", "text/javascript", "application/json"])

    data = {'query': query}
    # b = quote_plus(query)

    r = Request(endpoint,
                data=urlencode(data).encode('utf-8'),
                headers={'content-type': 'application/x-www-form-urlencoded',
                         'accept': FORMATS},
                method='POST')
    res = urlopen(r)
    data = res.read().decode('utf-8')