Поиск по блогу

воскресенье, 15 ноября 2015 г.

Здесь пытался понять, как лучше использовать Jupyter для отладкт javascript

Надо было подобрать и настроить ява скрипты для сайта. Если делать это в NOtebook, то можно сразу и отладить и записать варианты настройки. Заманчиво... но как это сделать? Как загружать на страницу jypyter кастомные js скрипты и стили? Оказывается, что вариантов несколько, в зависимости от того, что нам надо. Для глобальных задач есть специальная папка .ipython\profile_default\static\custom\custom.js, файл custom.js автоматически вставляется в тег head страницы. Для тетирования фрагментов кода предусмотрены объекты в IPython.display (Display, HTML, Javascript, IFrame ...), а еще есть магики %%html %%javascript В сочетании с возможностью загрузки внешних скриптов $.getScript('/static/custom/util.js'); и обращения к element.append(myvar) (Use the element variable for printing in the cell output area) все это надо осваивать. Здесь примеры и ссылки.

Сначала посмотрим на файл custom.js

In [1]:
from IPython.display import HTML, Javascript, display
In [ ]:
# %load C:\\Users\\alter_000\\.ipython\\profile_default\\static\\custom\\custom.js
// leave at least 2 line with only a star on it below, or doc generation fails
/**
 *
 *
 * Placeholder for custom user javascript
 * mainly to be overridden in profile/static/custom/custom.js
 * This will always be an empty file in IPython
 *
 * User could add any javascript in the `profile/static/custom/custom.js` file.
 * It will be executed by the ipython notebook at load time.
 *
 * Same thing with `profile/static/custom/custom.css` to inject custom css into the notebook.
 *
 *
 * The object available at load time depend on the version of IPython in use.
 * there is no guaranties of API stability.
 *
 * The example below explain the principle, and might not be valid.
 *
 * Instances are created after the loading of this file and might need to be accessed using events:
 *     define([
 *        'base/js/namespace',
 *        'base/js/events'
 *     ], function(IPython, events) {
 *         events.on("app_initialized.NotebookApp", function () {
 *             IPython.keyboard_manager....
 *         });
 *     });
 *
 * __Example 1:__
 *
 * Create a custom button in toolbar that execute `%qtconsole` in kernel
 * and hence open a qtconsole attached to the same kernel as the current notebook
 *
 *    define([
 *        'base/js/namespace',
 *        'base/js/events'
 *    ], function(IPython, events) {
 *        events.on('app_initialized.NotebookApp', function(){
 *            IPython.toolbar.add_buttons_group([
 *                {
 *                    'label'   : 'run qtconsole',
 *                    'icon'    : 'icon-terminal', // select your icon from http://fortawesome.github.io/Font-Awesome/icons
 *                    'callback': function () {
 *                        IPython.notebook.kernel.execute('%qtconsole')
 *                    }
 *                }
 *                // add more button here if needed.
 *                ]);
 *        });
 *    });
 *
 * __Example 2:__
 *
 * At the completion of the dashboard loading, load an unofficial javascript extension
 * that is installed in profile/static/custom/
 *
 *    define([
 *        'base/js/events'
 *    ], function(events) {
 *        events.on('app_initialized.DashboardApp', function(){
 *            require(['custom/unofficial_extension.js'])
 *        });
 *    });
 *
 * __Example 3:__
 *
 *  Use `jQuery.getScript(url [, success(script, textStatus, jqXHR)] );`
 *  to load custom script into the notebook.
 *
 *    // to load the metadata ui extension example.
 *    $.getScript('/static/notebook/js/celltoolbarpresets/example.js');
 *    // or
 *    // to load the metadata ui extension to control slideshow mode / reveal js for nbconvert
 *    $.getScript('/static/notebook/js/celltoolbarpresets/slideshow.js');
 *
 *
 * @module IPython
 * @namespace IPython
 * @class customjs
 * @static
 */

Я понадеялся было, что все файлы из папки Custom вставляются в хидер страницы, быстренько добавил туда custom_se.js и создал новую страницу... Не тут то было, в коде страницы среди прочего красовались custom.css custom.js, а моего файла не было.

First, in .ipython/profile/static/custom/myScript.js, we do some require.js magic:

In [ ]:
define(function(){

    var foo = function(){
            console.log('bar');
        }

    return {
        foo : foo
    }
});

Copy this pattern for as many functions as you like. Then, in .ipython/profile/static/custom/custom.js, drag those out into something persistent:

In [ ]:
$([IPython.events]).on('notebook_loaded.Notebook', function(){

    require(['custom/myScript'], function(custom){
        window.foo = custom.foo;
    } );

});

Yes, I am a horrible person for throwing stuff on the window object, namespace things as you deem appropriate. But now in the notebook, a cell like

In [ ]:
%%javascript

foo();

should do exactly what it looks like it should, without the user having to explicitly import your JS. I would love to see a simpler solution for this

In [ ]:
$.getScript('/static/custom/util.js'); 

in custom.js to load up a bunch of global JS functions) - but this is the best I've got for now. This singing and dancing aside, HUGE ups to the IPython notebook team, this is an awesome platform!

As a very short-term solution, you can make use of the IPython display() and HTML() functions to inject some JavaScript into the page.

In [ ]:
from IPython.display import display, HTML
js = "<script>alert('Hello World!');</script>"
display(HTML(js))

Although I do not recommend this over the official custom.js method, I do sometimes find it useful to quickly test something or to dynamically generate a small JavaScript snippet.

In [ ]:
Exact path and instruction depends on what version of IPython you are running. And that would be
In [ ]:
 $.getScript("static/Gl.js") 
In [ ]:
#and 
~/.ipython/profile_default/static/[custom]/GI.js. 

I would suggest doing a search for IPython custom.js, ask/search on ml/hipchat, because I'm afraid stackoverflow will be a little too limiting to give you all the explanation necessary

In [9]:
!chcp 65001
!dir
Active code page: 65001
 Volume in drive F is MYLINUXLIVE
 Volume Serial Number is CE7F-8134

 Directory of F:\IPython Notebooks\2015_11

31.10.2015  10:48    <DIR>          .
31.10.2015  10:48    <DIR>          ..
15.11.2015  18:45             2В 699 15_jqyt.ipynb
11.11.2015  17:00    <DIR>          s-trado
05.11.2015  18:50            66В 354 JSInteraction.ipynb
12.11.2015  18:28    <DIR>          .ipynb_checkpoints
11.11.2015  13:45             9В 644 10_backup.ipynb
11.11.2015  16:25            27В 715 10_backup.html
11.11.2015  17:11            76В 844 JSInteraction.html
12.11.2015  16:28             6В 073 12_icons.ipynb
12.11.2015  19:21             3В 027 12_css_autodesk.ipynb
13.11.2015  12:04            16В 874 13_TensorFlow .ipynb
15.11.2015  21:16    <DIR>          files
15.11.2015  19:15             8В 051 15_adobe.ipynb
17.11.2015  10:14            17В 916 15_display.ipynb
17.11.2015  09:26            32В 218 15_display-Copy1.ipynb
17.11.2015  10:06                78 Untitled.ipynb
13.11.2015  10:27             5В 956 8_imagick.ipynb
13.11.2015  10:39             4В 102 13_anim.ipynb
              14 File(s)        277В 551 bytes
               5 Dir(s)   4В 463В 697В 920 bytes free

You can use the %%javascript magic function for running javascript in IPython notebook. For example Paste the following code in a IPython cell and run it. You should see the output in your browser's javascript console.

In [ ]:
%%javascript
console.log("Hello World!")


#For global variables, you can add an attribute to the windows object 
#for example, in a cell run the following code:
%%javascript
window.myvar = 12;


#In another cell, run the following code and check browser's javascript console. 
#The variable's value should be printed.
%%javascript
console.log(myvar)


#Use the element variable for printing in the cell output area as shown below:
%%javascript
element.append(myvar)
In [7]:
%%javascript
console.log("hi")
In [ ]:
#Use the element variable for printing in the cell output area as shown below:
%%javascript
element.append(myvar)

Приложение пример-подсказка

In [ ]:
display(HTML("""
<p id="demo">A Paragraph.</p>
<button id="something">Try it</button>
"""))

js = """
$(document).ready(
function() {
    $("#something").click(function() {
        $('#demo').text("Changed text");
        $('#something').text('Change button');
        });
    });
"""
js = Javascript(js)
display(js)
In [ ]:
HTML(filename='myhtml.html')


Посты чуть ниже также могут вас заинтересовать

Комментариев нет:

Отправить комментарий