bokeh issue on loading katex in jupyter notebook - jupyter-notebook

I'm trying to replicate the bokeh latex example mentioned at https://docs.bokeh.org/en/latest/docs/user_guide/extensions_gallery/latex.html#userguide-extensions-examples-latex in jupyter notebook for LabelSet. I could see the katex.min.js being loaded from web console. However when the LatexLabel renders, it states katex not defined.
Katex JS doc says, it should be available globally once js is loaded.
import * as p from "core/properties"
import {LabelSet, LabelSetView} from "models/annotations/label_set"
declare const katex: any
export class LatexLabelSetView extends LabelSetView {
model: LatexLabelSet
render(): void {
const draw = this._v_css_text.bind(this)
const {ctx} = this.plot_view.canvas_view
const [sx, sy] = this._map_data()
for (let i = 0, end = this._text.length; i < end; i++) {
try {
draw(ctx, i, this._text[i], sx[i] + this._x_offset[i], sy[i] - this._y_offset[i], this._angle[i])
katex.render(this._text[i], this.el, {displayMode: true})
}
catch(e) {
console.log( 'Error: ' + e);
}
}
}
}
class LatexLabelSet(LabelSet):
__javascript__ = ["https://cdn.jsdelivr.net/npm/katex#0.11.1/dist/katex.min.js"]
__css__ = ["https://cdn.jsdelivr.net/npm/katex#0.11.1/dist/katex.min.css"]
__implementation__ = TypeScript(TS_CODE)
Also tried adding the script element into document root. No luck though.
export class LatexLabelSet extends LabelSet {
properties: LatexLabelSet.Props
constructor(attrs?: Partial<LatexLabelSet.Attrs>) {
super(attrs)
}
static init_LatexLabelSet() {
let jsNode = document.createElement('script')
jsNode.id = 'bokeh-katex-js'
jsNode.src = "https://cdn.jsdelivr.net/npm/katex#0.11.1/dist/katex.min.js"
let cssNode = document.createElement('link')
cssNode.id = 'bokeh-katex-css'
cssNode.rel= 'stylesheet'
cssNode.href = "https://cdn.jsdelivr.net/npm/katex#0.11.1/dist/katex.min.css"
document.getElementsByClassName('bk-root')[0].appendChild(cssNode)
document.getElementsByClassName('bk-root')[0].appendChild(jsNode)
this.prototype.default_view = LatexLabelSetView
}
}
Any directions would be helpful.

Bokeh 2.4 adds support for LaTeX (and MathML) to some elements in Bokeh directly (no need to use an extension). Currently, you can use LaTeX on axis labels, tick labels, div widgets, and paragraph widgets, and this also works in Jupyter notebooks. LaTeX support for more elements should be added soon. For more information about the new math text feature and how to use them, see the Bokeh 2.4 release blogpost, the new blackbody radiation example, and the Bokeh user guide!

Note from maintainers: Initial built in LaTeX support was added in version 2.4, see this new answer https://stackoverflow.com/a/69198423/3406693
As stated in https://docs.bokeh.org/en/latest/docs/user_guide/embed.html#components, this is not possible to achieve within the notebook.
It says
Note that in Jupyter Notebooks, it is not possible to use components and show in the same notebook cell.
Indeed, if you use the code below, it opens a new tab with the plot and the formula, but if you call output_notebook(), the text does not appear and the browser console throws Uncaught ReferenceError: katex is not defined.
p = figure(title="LaTex Demonstration")
p.line([0,0,1,1,0],[0,1,1,0,0])
latex = LatexLabel(text=r"e^{i\pi}+1=0",
x=0.4, y=0.55,
render_mode='css', text_font_size='16pt',
background_fill_alpha=0)
p.add_layout(latex)
show(p)
Working in new tab:
Not working inside notebook:

Related

How i can to raise QFileDialog to the foreground if functions raise(),activeWindow() and other didn't work?

I'm using go-qt bindings (therecipe).
I faced such a problem that I cannot bring the window with the file dialog forward, I tried all the functions (and their combinations) that I could find on the Internet, but none of them did not help bring the dialog up.
I try to use this function:
fileDialog.SetWindowFlag(core.Qt__WindowStaysOnTopHint,true)
fileDialog.ActivateWindow()
fileDialog.SetWindowState(core.Qt__WindowActive)
fileDialog.SetWindowState(core.Qt__WindowMinimized|core.Qt__WindowActive)
fileDialog.Raise()
fileDialog.SetFocus2()
I also noticed a feature that if you call the dialog again after fileDialog.Exec (), then it will be displayed on top of all windows as needed.
code for this case
var fileDialog = widgets.NewQFileDialog2(nil, "Open Directory", "", "")
if fileDialog.Exec() != int(widgets.QDialog__Accepted) {
return
}
if fileDialog.Exec() != int(widgets.QDialog__Accepted) {
return
}
Code for function where I'm using Dialog:
func choseFile(){
var fileDialog = widgets.NewQFileDialog2(nil, "Open Directory", "", "")
fileDialog.SetAcceptMode(widgets.QFileDialog__AcceptOpen)
fileDialog.SetFileMode(widgets.QFileDialog__ExistingFile)
fileDialog.SetWindowFlag(core.Qt__WindowStaysOnTopHint,true)
if fileDialog.Exec() != int(widgets.QDialog__Accepted) {
return
}
fmt.Println(fileDialog.SelectedFiles()[0])
}
Problem might be related to native dialogs (in my case I am using ubuntu), so I put the flag DontUseNativeDialog. Then the problem was solved.
filename := widgets.QFileDialog_GetOpenFileName(ac.MainWindow,"Open Directory","","","",widgets.QFileDialog__DontUseNativeDialog)
upd: Its works even if the first argument is nil.

Adding # to formula after =

When I add the formula FORECAST.ETS, it adds an # after the equal symbol, like this: = #FORECAST.ETS. Why is this happening?
The code snippet is:
ws.cell(column=1, row=2, value="=FORECAST.ETS(...)"
When I open it with Excel (latest Office 365 version), it shows as =#FORECAST.ETS(..)
I have hit the same issue, but not with Python and openpyxl, but with dotnet Core C# and EPPLUS. What follows is perhaps a workaround based on my findings... but not ideal. I suspect it will work with openpyxl too.
Re-creating the problem
I have written a simplified C# console app that firstly creates a new XLSX (foo.xlsx), writes out some data and my formula, and then outputs the cell with the formula and the value to the Console. It then saves and closes the XLSX, and reopens it and again outputs the formula cell and its value. The code is as follows:
using OfficeOpenXml;
using System;
using System.IO;
namespace TestFormula
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Test starts");
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
if (File.Exists($".\\foo.xlsx"))
{
File.Delete($".\\foo.xlsx");
}
using (var ep = new ExcelPackage(new FileInfo($".\\foo.xlsx")))
{
ExcelWorkbook wb = ep.Workbook;
ExcelWorksheet wsTest = null;
wsTest = wb.Worksheets.Add("Test");
// Add some look up data...
for (int row = 1; row <= 5; row++)
{
wsTest.Cells[row, 1].Value = row;
wsTest.Cells[row, 2].Value = $"Name {row}";
}
wsTest.Cells[1, 4].Formula = $"=XLOOKUP($A3,$A:$A,$B:$B))";
Console.WriteLine($"Add: formula=\"{wsTest.Cells[1, 4].Formula}\"");
Console.WriteLine($"Add: value=\"{wsTest.Cells[1, 4].Value}\"");
ep.Save();
ep.Dispose();
}
using (var ep = new ExcelPackage(new FileInfo($".\\foo.xlsx")))
{
ExcelWorkbook wb = ep.Workbook;
ExcelWorksheet wsTest = null;
wsTest = wb.Worksheets["Test"];
Console.WriteLine($"Open: formula=\"{wsTest.Cells[1, 4].Formula}\"");
Console.WriteLine($"Open: value=\"{wsTest.Cells[1, 4].Value}\"");
ep.Dispose();
}
Console.WriteLine("Test ends");
}
}
}
The output from the above looks like this...
Note that the formula after closing and re-opening the XLSX with EPPLUS reads just as it was written.
However, if I open the file with Excel I can see that an # has been inserted after the = sign.
If I then double click on the formula cell, I get an Excel error message...
I answered "no" to this question because I wanted to continue to experiment with what was happening behind the scenes.
After double clicking the formula cell to edit it, when I now hit ENTER with the # in the formula, it works. At this point I save the XLSX with the change made.
If I now delete some of my code and just run...
using OfficeOpenXml;
using System;
using System.IO;
namespace TestFormula
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Test starts");
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (var ep = new ExcelPackage(new FileInfo($".\\foo.xlsx")))
{
ExcelWorkbook wb = ep.Workbook;
ExcelWorksheet wsTest = null;
wsTest = wb.Worksheets["Test"];
Console.WriteLine($"Open: formula=\"{wsTest.Cells[1, 4].Formula}\"");
Console.WriteLine($"Open: value=\"{wsTest.Cells[1, 4].Value}\"");
ep.Dispose();
}
Console.WriteLine("Test ends");
}
}
}
I get the following output...
What's particularly interesting about the output is that the formula has been modified by Excel and has been prefixed with _alfn.SINGLE.
Research
It is worth declaring here that I am running Microsoft 365 and I always have patches and updates automatically applied as soon as they become available. So my version of Excel is the latest version.
Google-ing for _alfn.SINGLE provides a number of hits (see References below) and from these I have concluded the following:
In Aug 2019 Microsoft released an update that introduced a new formula keyword called XLOOKUP... intended to replace VLOOKUP and HLOOKUP. As such, the XLSX file format was updated to allow for this new feature. The second reference below mentions dates of the introduction of other formulas around Sep 2018.
I'm guessing that the EPLUS library (and probably the openpyxl) have not updated their file format to compensate for the addition of these new/changed features.
When Excel opens an older file version and detects a more recent formula keyword (i.e. a keyword that was not available in the earlier file version), it does not automatically resolve the formula, but instead throws the error I mentioned above, and then resolves the problem by prefixing the new formula keyword with _alfn.SINGLE.
Solution
It's dirty and short term until the EPPLUS/openpyxl libraries catch up. In my case, in code simply replace...
wsTest.Cells[1, 4].Formula = $"=XLOOKUP($A3,$A:$A,$B:$B)";
... with ...
wsTest.Cells[1, 4].Formula = $"_xlfn.SINGLE(_xlfn.XLOOKUP($A3,$A:$A,$B:$B))";
References
Issue: An _xlfn. prefix is displayed in front of a formula by Microsoft
XLOOKUP XMATCH FILTER RANDARRAY SEQUENCE SORT SORTBY UNIQUE CONCAT IFS MAXIFS MINIFS SWITCH TEXTJOIN by Andreas Killer

How to build a simple widget or app in jupyter notebook/lab to interactively extract a substring from text?

I want iterate over a list of string, output the string as plain text in jupyter lab then interactively highlight a substring to get easily the start index of the substring and the length. The goal is to do a quick annotation of text and get the coordinates of the substring.
Is it easy or even possible to do something like this with jupyter notebook (lab)? If then How?
I had a look at ipywidgets but couldn't find something for this use case.
Here's an example with the RangeSlider:
import ipywidgets
input_string = 'averylongstring'
widg = ipywidgets.IntRangeSlider(
value = [0, len(input_string)],
min=0, max=len(input_string)
)
output_widg = ipywidgets.Text()
display(widg)
display(output_widg)
def chomp_string(widg):
start,end = tuple(widg['new'])
output_widg.value = input_string[start: end]
widg.observe(chomp_string, names='value')
You can implement this using jp_proxy_widgets. See the following screenshot:
Note that there are warnings about compatibility for selection protocols -- I only tested this on Chrome on a Mac. Also I don't know why the indices are off by one
(select_callback(startOffset+1, endOffset+1);)
Please see https://github.com/AaronWatters/jp_proxy_widget for more information
Edit: Here is the pastable text as requested:
import jp_proxy_widget
select_widget = jp_proxy_widget.JSProxyWidget()
txt = """
Never gonna give you up.
Never gonna let you down.
Never gonna run around and
desert you.
"""
selected_text = None
def select_callback(startOffset, endOffset):
global selected_text
selected_text = txt[startOffset: endOffset]
print ("Selected", startOffset, endOffset, repr(selected_text))
select_widget.js_init("""
// (Javascript) Add a text area.
element.empty()
$("<h3>please select text:</h3>").appendTo(element);
var textarea = $('<textarea cols="50" rows="5">' + txt + "</textarea>").appendTo(element);
// Attach a select handler that calls back to select_callback.
var select_handler = function(event) {;
var target = event.target;
var startOffset = target.selectionStart;
var endOffset = target.selectionEnd;
select_callback(startOffset+1, endOffset+1);
};
textarea[0].addEventListener('select', select_handler);
""", txt=txt, select_callback=select_callback)
# display the widget
select_widget.debugging_display()

SyntaxError: Parse error - Wkhtmltopdf with react-pdf-js lib

I am using wkhtmltopdf version 0.12.2.1 (with patched qt) to render my reactJs app! It worked fine, until I added the react-pdf-js lib to render the pdf generated inside my app. I followed the code described on react-pdf-js documentation (see https://www.npmjs.com/package/react-pdf-js) to make it work.
The pdf is rendered inside my page, and it looks pretty cool indeed. But when I try to run wkhtmltopdf again, to generate a pdf of any page of my app, the following error is returned:
desenv01#desenv01-PC:~$ wkhtmltopdf -O Landscape --print-media-type --debug-javascript http://localhost:3000/report/1 report.pdfLoading pages (1/6)
Warning: undefined:0 ReferenceError: Can't find variable: Float64Array
Warning: http://localhost:3000/assets/js/app.js:46789 SyntaxError: Parse error
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done
Then, I went to my app.js to see what's on line 46789:
set href(href) {
clear.call(this);
parse.call(this, href);
},
get protocol() {
return this._scheme + ':';
},
set protocol(protocol) {
if (this._isInvalid)
return;
parse.call(this, protocol + ':', 'scheme start');
},
The error happens on the line that says parse.call(this, href);, which is part of pdf.combined.js script.
I could not find any solution online so I wondered if there is anyone who might know if I did something wrong or a way to work around it.
Thanks..
I ran into this using wkthmltopdf 12.3 and 12.4 because I have my IDE set to nag me for using var instead of let. The problem is the older Qt engine powering those versions of the program doesn't recognize new-style, ES6 keywords. Not sure if you can down-convert React. Otherwise you can try the bleeding edge versions which use a newer Qt.
I have same problem. I fixed it by modify some code that i think it is new in JS. let keyword (ES5) and template literals (ES6).
generateRandomColor= function () {
let maxVal = 0xFFFFFF; // 16777215
let randomNumber = Math.random() * maxVal;
randomNumber = Math.floor(randomNumber);
randomNumber = randomNumber.toString(16);
let randColor = randomNumber.padStart(6, 0);
return `#${randColor.toUpperCase()}`
}
I modify above code into below
generateRandomColor = function () {
var maxVal = 0xFFFFFF;
var randomNumber = Math.random() * maxVal;
randomNumber = Math.floor(randomNumber);
randomNumber = randomNumber.toString(16);
var randColor = randomNumber.padStart(6, 0);
return "#" + randColor.toUpperCase();
}

box2d CreateFixture with b2FixtureDef gives pure virtual function call

i have this code that gives me run time error in the line :
body->CreateFixture(&boxDef)
im using cocos2d-x 2.1.5 with box2d 2.2.1 in windows
CCSprite *sprite = CCSprite::create(imageName.c_str());
this->addChild(sprite,1);
b2BodyDef bodyDef;
bodyDef.type = isStatic?b2_staticBody:b2_dynamicBody;
bodyDef.position.Set((position.x+sprite->getContentSize().width/2.0f)/PTM_RATIO,
(position.y+sprite->getContentSize().height/2.0f)/PTM_RATIO);
bodyDef.angle = CC_DEGREES_TO_RADIANS(rotation);
bodyDef.userData = sprite;
b2Body *body = world->CreateBody(&bodyDef);
b2FixtureDef boxDef;
if (isCircle)
{
b2CircleShape circle;
circle.m_radius = sprite->getContentSize().width/2.0f/PTM_RATIO;
boxDef.shape = &circle;
}
else
{
b2PolygonShape box;
box.SetAsBox(sprite->getContentSize().width/2.0f/PTM_RATIO, sprite->getContentSize().height/2.0f/PTM_RATIO);
boxDef.shape = &box;
}
if (isEnemy)
{
boxDef.userData = (void*)1;
enemies->insert(body);
}
boxDef.density = 0.5f;
body->CreateFixture(&boxDef) //<-- HERE IS THE RUN TIME ERROR
;
when i debug the box2d code im getting to b2Fixture.cpp
in the method :
void b2Fixture::Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def)
in the line :
m_shape = def->shape->Clone(allocator);
getting the runtime error :
R6025 pure virtual function call
Tricky one. I ran into this myself a couple times. It has to do with variable scope.
The boxDef.shape is the problem. You create the shapes as local variables in the if/else blocks and then assign them to boxDef. As soon as execution leaves the if/else block scope those local variables will be garbage. The boxDef.shape now points to freed memory.
The solution is to keep the shape variables in scope by moving the circle and box shape declarations before the if/else block.

Resources