IPython Notebook previous cell content - ipython

Is it possible in an IPython-Notebook cell to get the previous (above) cell content ?
I can see previous output with %capture magic function but I don't find how to get the previous cell content.

%recall jupyter_notebook_cell_number
Should give you the code that was last executed in indicated particular notebook cell, jupyter_notebook_cell_number

I didn't find how to get the previous content cell in a cell.
But I found another solution, creating a custom magic notebook function to capture the cell content and work with that.

The documentation for the input catching system is rather informative.
The returned output (not cell output content) is stored in _oh dictionary and the returned output is added to the page within the .output_area DOM element as a div element with the classes .output_subarea, .output_text and uniquely .output_result. Printed or displayed (IPython.display.display also have the first two classes and print in particular has .output_stream .output_stdout.
_oh is a dictionary and the integer is the same as that you can see on the left of the input (.input_prompt div).
In other words the cell content is rather formatted as expected. And you can in fact add your own HTML.
from IPython.display import display, HTML
display(HTML('<h1>HELLO WORLD</h1>'))
display(HTML(<script>alert("hello world");</script>'))
This shows you can add JS within a Python cells —but this has a big flaw. Likewise, in JS you can execute python code.
IPython.notebook.kernel.execute("python_variable="+JSON.stringify(jsVariable));
However, a JS IPython call is executed when the kernel is idle. Therefore you have to wait for the cell to finish before accessing python_variable. So there's no point doing it all in one cell and regular cell magic works.
Consequently, the following JS magic will give a output dictionary whose keys are cell numbers and values are the content. As mentioned the cell content is formatted, so if you want to change the following based on the class of the element in the cell you can refer to the aforementioned CSS classes.
// querySelectorAll returns a NodeList which lacks most Array functions
// so destructuring into array
const outputs=[...document.querySelectorAll(".cell")].map(
cell=> {
const RawCellN=cell.querySelector(".input_prompt").innerText;
// \xa0 is star. current: skip.
if (RawCellN.match(/\[(\d+)\]/) === null) return null;
const cellN = parseInt(RawCellN.match(/\[(\d+)\]/)[1]);
const outputs= [...cell.querySelectorAll(".output_subarea")].map(
subarea => subarea.innerText.trim());
return [cellN, outputs.filter(out => out.length !== 0)];
}
).filter(value => value !== null); // star cell was skipped.
// pass on the data to python
IPython.notebook.kernel.execute("outputs=dict("+JSON.stringify(outputs)+")")

Related

How to get `length` of Matlab GUI popup menu strings

I want to get how many strings exist in the popup menu, how can this be done? This code that I have written does not seem to work.
length(get(handles.popupMenu,'Value'))
Value is the index of the currently selected item in the menu so it will only ever be a scalar. You instead want to check the length of the String property which contains a cell array of strings (one for each item).
nOptions = numel(get(handles.popupMenu, 'String'));

Modify cell's metadata

I want to store the values of my IPython.html.widgets in my ipython notebook somehow.
Is there a way to modify the metadata of the current cell from the code within the cell itself?
I don't know how to do this from within the notebook, but I found a way to do it with a custom preprocessor and nbconvert.
You can create a class that extends nbconvert.preprocessors.ExecutePreprocessor. In the preprocess (or preprocess_cell) method, add logic for storing the relevant output in the cell metadata.
Something like:
class MyExecutePreprocessor(ExecutePreprocessor):
def preprocess_cell(self, cell, resources, index):
# Execute the cell normally
cell, resources = super().preprocess_cell(cell, resources, index)
# Add your magic here
cell.metadata['widgets'] = {'stuff':'that is cool'}
return cell, resources
You can then execute this preprocessor programatically, or as an argument to nbconvert.
If I understand what you are looking for:
from the Cell Toolbar (top right of the ipython notebook toolbar), select Edit Metadata from the drop-down list.

GWT DataTable TextInputCell is not showing the correct value

I have a DataGrid with a TextInputCell column, using a ListDataProvider. When the value in a cell is changed I am creating a RequestContext and calling RequestContext#edit with the original entity for the row that is being edited. I then set the field in the mutable version of the proxy to the value from the edited cell. This all works nicely, and I can save the change successfully to the database. However, on the server I modify the value before saving the change, and send the modified entity (DTO) back to the client. In the Receiver#onSuccess method I store the new entity in the list data provider, and then call ListDataProvider#refresh. But the value that is shown in the DataGrid doesn't change to reflect the modification on the server. I've looked at the value that is supplied to the TextInputCell#getValue method, and it is correct, that is, it is the value that contains the modification applied on the server.
I tried creating another column in the grid that is just a TextCell, and supplied the same value in getValue for that cell; in this case the displayed value is correctly updated by the refresh, reflecting the modified value that was returned from the server.
So, my question is: where does the cell get its value? When I look at the value returned by my TextInputCell#getValue method it appears to be the correct value, but that value is not being shown on the screen (the value shown on the screen is the value that was in the proxy object prior to sending the request to the server).
Note: I looked at this question, but it did not work in my situation.
I have a very similar problem.
I have a page showing a grid with two column: the first one has check boxes instead of text.
The value of the check box is given by:
public Boolean getValue(Item item) {
return selectedItems.contains(item);
}
When the user checks a check box, I store the value in a map (selectedItems).
At the bottom of the page there is a "Clear" button that reset the map and calls the table redraw, but the status of the check boxes does not revert to the original status (i.e. the check boxes stay selected).
Debugging the code I've found that getValue() returns the correct value, but is like the table caches the cells.
The only workaround I have found, without rebuilding the whole table, was to remove the check boxes' cell and add it again on "Clear".
itemsTable.removeColumn(0);
itemsTable.insertColumn(0, makeSelectionColumn());
The method makeSelectionColumn() must return a new cell.

How do I change a header cell when the page changes?

I have a PdfPTable in my document being written using iTextSharp. There are some header rows which get repeated whenever the table overflows to another page. One of those rows contains a cell with some text, e.g. "John Doe".
What I want is for that text to change to "John Doe (continued)" on each subsequent page. From what I can tell, I need to do something in the OnEndPage event that somehow manipulates the instance of the header cell for that page, but I'm struggling to find out how exactly to find the cell in the written content and then manipulate it.
How do I achieve this goal?
After some trial and error, I was able to get a working solution. I implemented the IPdfCellEvent which declares a single method, CellLayout. As per the iText documentation, this is called after the cell has been rendered, which means, the first time it is called it has rendered the cell for the very first page of the table. So, I use this call to add the extra text so that all subsequent renderings will include the additional text.
This is my interface implementation:
private class ContinuedCellEvent : IPdfPCellEvent
{
public void CellLayout( PdfPCell cell, Rectangle position, PdfContentByte[] canvases )
{
if ( !_continuationApplied )
{
// This is called AFTER cell rendering so this should set the cell for the next time it is rendered
// which will always be on a continuation.
cell.Phrase.Add( new Chunk( " Continued" ) );
_continuationApplied = true;
}
}
private bool _continuationApplied;
}
It is used when defining the cell:
cell.CellEvent = new ContinuedCellEvent();
Using onEndPage() could work, but I would implement the PdfPTableEventSplit interface if I were you. I'd use a membervariable cellContent and set it to "John Doe" upon creating the event instance. I would draw the content of cellContent in the tableLayout() method and change its content to "John Doe (continued)" in the splitTable() method.
Try it out and share your code. If it works, others will be helped; if it doesn't, I'll take a look to see what goes wrong (but please understand that I'm not a C# developer; I wrote iText in Java; I had to hire people to port it to C#).

d3 bar chart selectAll before appending

I've been learning more about the d3 visualization library, and I've seen a few examples of bar charts that have a snippet that looks like
chart.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("y", y)
.attr("width", x)
.attr("height", y.rangeBand());
My confusion is with the first selectAll line. What is the purpose of selecting all rects before they exist since we'll be appending new rects on data enter? Does what goes in the selectAll matter if none of those elements exist?
It is part of the declarative nature of the D3 language. The Thinking with Joins article explains it in detail. An excerpt:
But what’s with the selectAll("circle")? Why do you have to select
elements that don’t exist in order to create new ones? WAT.
Here’s the deal: instead of telling D3 how to do something, tell D3
what you want. In this case, you want the circle elements to
correspond to data: you want one circle per datum. Instead of
instructing D3 to create circles, then, tell D3 that the selection
"circle" should correspond to data—and describe how to get there. This
concept is called the data-join:
This Venn diagram illustrates the data-join. Data bound to existing
elements produce the update (inner) selection. Unbound data produce
the enter selection (left), and unbound elements produce the exit
selection (right). Data Enter Update Elements Exit Thinking with joins
reveals the mystery behind the sequence:
The selectAll("circle") returns the empty selection, since the SVG
container element (svg) is empty. No magic here.
The empty selection is joined to data: data(data). The data method
binds data to elements, producing three virtual selections: enter,
update and exit. The enter selection contains placeholders for any
missing elements. The update selection contains existing elements,
bound to data. Any remaining elements end up in the exit selection for
removal.
Since the selection was empty, all data ends up as placeholder nodes
in enter().
This is the same append as in the first example, but applied to
multiple placeholders; selection methods implicitly iterate over
selected elements. The missing elements are added to the SVG container
by append("circle").
So that’s it. You wanted the selection "circle" to correspond to data,
and you described how to create the missing elements.
In your example selectAll("rect") is called first. But it returns an empty selection.
data(data) will bind the empty selection with the data. It creates new empty selections.
.enter() identifies any DOM elements that needs to be added when the joined array is longer than the selection.
append("rect") appends a rectangle to each empty selection, which is no longer empty
It is well explained and detailed on this section: D3.js data binding, How it works?