cx_freeze include css file and image in dash app - css

I have some difficulties to apply a css file to my dash app when using cx_freeze. If I run python app.py the layout is properly applied, however not if I am executing the .exe generated by cx_freeze. Then the default html layout is displayed. The css and the image appear in the same directory where the .exe is located.
This is how my setup.py looks like.
from setuptools import find_packages
from cx_Freeze import setup, Executable
options = {
'build_exe': {
'includes': [
'cx_Logging', 'idna', 'idna.idnadata'
],
'packages': [
'asyncio', 'flask', 'jinja2', 'dash', 'plotly', 'waitress'
],
'excludes': ['tkinter'],
'include_files': [
'assets/logo.jpg', 'assets/style.css'
],
}
}
executables = [
Executable('server.py',
base='console',
targetName='dash_app.exe')
]
setup(
name='BI_Report',
packages=find_packages(),
version='0.0.1',
description='rig',
executables=executables,
options=options
)
To load the external files I use a helper function as suggested here:
def find_data_file(filename):
if getattr(sys, 'frozen', False):
# The application is frozen
datadir = os.path.dirname(sys.executable)
else:
# The application is not frozen
# Change this bit to match where you store your data files:
datadir = os.path.dirname(__file__)
return os.path.join(datadir, filename)
app = dash.Dash(__name__,
assets_folder=find_data_file('assets/'))
I am using:
Python 3.7.6
dash 1.9.1
cx-freeze 6.1
Any help much appreciated!

Related

nx adds dist/packages to my paths mappings

Question: Why does TypeScript/Nx add dist/packages to my path mappings?
I'm converting my polyrepo project to nx monorepo. In my polyrepo, I have a repo mpg-common with src folder, and all other repos import from it: import { Bla } from 'mpg-common/lib/services/.... I want to preserve this import syntax when moving to monorepo, so in tsconfig.base.json I put compilerOptions: { "paths": { "mpg-common/lib/*": ["packages/mpg-common/src/*"]
However, these imports fail. To debug I set "traceResolution": true, and then I see:
Module name 'mpg-common/lib/inversify.config', matched pattern 'mpg-common/lib/*'.
Trying substitution 'dist/packages/mpg-common/lib/*', candidate module location: 'dist/packages/mpg-common/lib/inversify.config'.
So, question: Why does TypeScript/Nx add these dist/packages to my path mappings?
Turns out my package.json had "name": "mpg-common", which caused nx to auto-map mpg-common => dist/packages/mpg-common, which is taken from packages/mpg-common/project.json => targets/build/options/outputPath.
So, solution: change in package.json to "name": "#myworkspace/mpg-common"

How to use rules_webtesting?

I want to use https://github.com/bazelbuild/rules_webtesting. I am using Bazel 5.2.0.
The whole project can be found here.
My WORKSPACE.bazel file looks like this:
load("#bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "io_bazel_rules_webtesting",
sha256 = "3ef3bb22852546693c94e9b0b02c2570e74abab6f800fd58e0cbe79492e49c1b",
urls = [
"https://github.com/bazelbuild/rules_webtesting/archive/581b1557e382f93419da6a03b91a45c2ac9a9ec8/rules_webtesting.tar.gz",
],
)
load("#io_bazel_rules_webtesting//web:repositories.bzl", "web_test_repositories")
web_test_repositories()
My BUILD.bazel file looks like this:
load("#io_bazel_rules_webtesting//web:py.bzl", "py_web_test_suite")
py_web_test_suite(
name = "browser_test",
srcs = ["browser_test.py"],
browsers = [
"#io_bazel_rules_webtesting//browsers:chromium-local",
],
local = True,
deps = ["#io_bazel_rules_webtesting//testing/web"],
)
browser_test.py looks like this:
import unittest
from testing.web import webtest
class BrowserTest(unittest.TestCase):
def setUp(self):
self.driver = webtest.new_webdriver_session()
def tearDown(self):
try:
self.driver.quit()
finally:
self.driver = None
# Your tests here
if __name__ == "__main__":
unittest.main()
When I try to do a bazel build //... I get (under Ubuntu 20.04 and macOS):
INFO: Invocation ID: 74c03efd-9caa-4174-9fda-42f7ff37e38b
ERROR: error loading package '': Every .bzl file must have a corresponding package, but '#io_bazel_rules_webtesting//web:repositories.bzl' does not have one. Please create a BUILD file in the same or any parent directory. Note that this BUILD file does not need to do anything except exist.
INFO: Elapsed time: 0.038s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (0 packages loaded)
The error message does not make sense to me, since there is a BUILD file in
https://github.com/bazelbuild/rules_webtesting/blob/581b1557e382f93419da6a03b91a45c2ac9a9ec8/BUILD.bazel
and https://github.com/bazelbuild/rules_webtesting/blob/581b1557e382f93419da6a03b91a45c2ac9a9ec8/web/BUILD.bazel.
I also tried a different version of Bazel - but with the same result.
Any ideas on how to get this working?
You need to add a strip_prefix = "rules_webtesting-581b1557e382f93419da6a03b91a45c2ac9a9ec8" in your http_archive call.
For debugging, you can look in the folder where Bazel extracts it: bazel-out/../../../external/io_bazel_rules_webtesting. #io_bazel_rules_webtesting//web translates to bazel-out/../../../external/io_bazel_rules_webtesting/web, so if that folder doesn't exist things won't work.

A module requiring 'fs' does not work inside storybook, but does work in-browser

I've got a basic create-react-app setup. A part of the CRA application is a lexer and a parser generated by antlr4ts.
In-browser, everything runs fine.
However, Storybook (installed via npx sb init) refuses to build, throwing:
ERROR in ./node_modules/antlr4ts/misc/InterpreterDataReader.js
Module not found: Error: Can't resolve 'fs' in '/home/rijndael/projects/antlr-truth-table-generator/node_modules/antlr4ts/misc'
# ./node_modules/antlr4ts/misc/InterpreterDataReader.js 16:11-24
# ./node_modules/antlr4ts/misc/index.js
# ./src/antlr/index.ts
# ./src/store/slices/tables/index.ts
# ./src/components/TruthTable/index.tsx
# ./src/components/TruthTable/stories/index.stories.tsx
# ./src sync ^\.(?:(?:^|\/|(?:(?:(?!(?:^|\/)\.).)*?)\/)stories\/(?!\.)(?=.)[^/]*?\.stories\.(js|jsx|ts|tsx))$
# ./.storybook/generated-stories-entry.js
# multi ./node_modules/#storybook/core/dist/server/common/polyfills.js ./node_modules/#storybook/core/dist/server/preview/globals.js ./.storybook/storybook-init-framework-entry.js ./.storybook/preview.js-generated-config-entry.js ./.storybook/generated-stories-entry.js ./node_modules/webpack-hot-middleware/client.js?reload=true&quiet=false&noInfo=undefined
Indeed, a module I'm requiring has import { Interval } from "antlr4ts/misc";.
However, antlr4ts/misc/index.js doesn't seem to require InterpreterDataReader. Perhaps one of its children does, however why it's then not listed in the require stack trace?
antlr4ts/misc/index.js
__export(require("./ANTLRInputStream"));
__export(require("./BailErrorStrategy"));
__export(require("./BufferedTokenStream"));
__export(require("./CharStreams"));
__export(require("./CodePointBuffer"));
__export(require("./CodePointCharStream"));
__export(require("./CommonToken"));
__export(require("./CommonTokenFactory"));
__export(require("./CommonTokenStream"));
__export(require("./ConsoleErrorListener"));
__export(require("./DefaultErrorStrategy"));
__export(require("./Dependents"));
__export(require("./DiagnosticErrorListener"));
__export(require("./FailedPredicateException"));
__export(require("./InputMismatchException"));
__export(require("./InterpreterRuleContext"));
__export(require("./IntStream"));
__export(require("./Lexer"));
__export(require("./LexerInterpreter"));
__export(require("./LexerNoViableAltException"));
__export(require("./ListTokenSource"));
__export(require("./NoViableAltException"));
__export(require("./Parser"));
__export(require("./ParserInterpreter"));
__export(require("./ParserRuleContext"));
__export(require("./ProxyErrorListener"));
__export(require("./ProxyParserErrorListener"));
__export(require("./RecognitionException"));
__export(require("./Recognizer"));
__export(require("./RuleContext"));
__export(require("./RuleContextWithAltNum"));
__export(require("./RuleDependency"));
__export(require("./RuleVersion"));
__export(require("./Token"));
__export(require("./TokenStreamRewriter"));
__export(require("./VocabularyImpl"));
Inside InterpreterDataReader.js we indeed do have a const fs = require("fs");. However, it's no less weird, as everything does run when built by react-scripts.
How do I make it run inside Storybook as well?
Why does it run when built by react-scripts, but not inside Storybook?
.storybook/main.js:
module.exports = {
"stories": [
"../src/**/stories/*.stories.mdx",
"../src/**/stories/*.stories.#(js|jsx|ts|tsx)"
],
"addons": [
]
}
Update
I fixed it by importing directly import { Interval } from "antlr4ts/misc/Interval";, thus omitting the giant require block in antlr4ts/misc/index.js. However, I'm no less interested in why it runs inside the browser, but not in Storybook.

Keyboard shortcut to expand code snippets in JupyterLab

Does anyone know how to make a shortcut that would paste a certain code to the selected cell or expand a snippet into a chunk of code?
For example I would like to fill a cell with a list of useful imports when pressing something like Ctrl+Shift+M. This would expand the cell content to:
import numpy as np
import pandas as pd
(...) .
Optionally this could work also like text completion tools available in some IDEs. For example when I write something like:
;imp + TAB .
it would expand into the same list as above.
Any ideas how this could be defined in JupyterLab?
I saw this answer, but it does not work for me (returning javascript error)
In JupyterLab 2.1+ you can add a shortcut to insert a snippet using the following settings:
{
"shortcuts": [
{
"command": "apputils:run-first-enabled",
"selector": "body",
"keys": ["Accel Shift M"],
"args": {
"commands": [
"console:replace-selection",
"fileeditor:replace-selection",
"notebook:replace-selection",
],
"args": {"text": "import numpy as np\nimport pandas as pd\n"}
}
}
]
}
For more detailed instruction see my new answer to the question you linked.
Another option is to use one of the code snippet extensions for JupyterLab:
jupyterlab-code-snippets from CalPoly
jupyterlab-snippets from QuantStack
elyra-code-snippet-extension from Elyra IBM team (with multiple contributions from the CalPoly team)
For emmet-style expansion of snippets in IPython, you can use:
from IPython import get_ipython
def import_completer(ipython, event):
return [
'import numpy as np\nimport pandas as pd\n',
'import tensorflow as tf\nimport autokeras as ak\n'
]
ipython = get_ipython()
ipython.set_hook('complete_command', import_completer, re_key='.*imp')

How to add/edit code snippets in jupyer notebook?

I tried to follow the instructions given in the README file of the extension.
Im using Windows and to open my notebooks I use the jupyter-notebook.exe stored in the directory
..\Anaconda3\Scripts
Within the Anaconda3 directory I go to the subdirectory
Anaconda3\Lib\site-packages\jupyter_contrib_nbextensions\nbextensions\snippets
and there change the code of the file "snippets.json" from
{
"snippets" : [
{
"name" : "example",
"code" : [
"# This is an example snippet!",
"# To create your own, add a new snippet block to the",
"# snippets.json file in your jupyter data directory under nbextensions:",
"# $(jupyter --data-dir)/nbextensions/snippets/snippets.json",
"import this"
]
}
]
}
to
{
"snippets" : [
{
"name" : "example",
"code" : [
"# This is a test if something changed",
]
]
}
Then I restart my notebook and insert the example snippet. But my changes weren't adopted, I still get the original example snipped.
What I am doing wrong?
If you are using Anaconda, you don't necessarily need to go searching for directories. There is a template embedded in the "Nbextensions" tab.
Check "Snippets Menu" box
Scroll down to 'Parameters' and check the "Include custom menu...JSON string below" box
Insert whatever sample snippet you want
Refresh your notebook
Check out one of my snippets:
{
"name" : "My favorites",
"sub-menu" : [
{
"name" : "import packages",
"snippet" : ["# import various packages"
"import os"
"import scipy"
"import pandas as pd"
"import numpy as np"
"import seaborn as sns"
"import matplotlib.pyplot as plt"
"%matplotlib inline"
"# plot settings"
"from pandas.plotting import register_matplotlib_converters"
"register_matplotlib_converters()"
"plt.rcParams['agg.path.chunksize'] = 10000"]
},
{
"name" : "TeX can be written in menu labels $\\alpha_W e\\int_0 \\mu \\epsilon$",
"snippet" : ["another_new_command(2.78)"]
}
]
}
Also, be careful with the quotations and commas. Additional help on that can be found here.
In windows(os) jupyter notebook extension are hidden in programData folder (C:\ProgramData\jupyter\nbextensions\snippets)
To make changes in snippet just edit the snippets.JSON file accordingly:
I think you are searching in the wrong directory.
In windows, run command jupyter --paths in anaconda prompt
this will return the locations of config: data: & runtime:
search for the file snippets.json in the data: locations
in my case it is C:\ProgramData\jupyter\nbextensions\snippets
change and save the content in snippets.json and then restart your jupyter notebook
it will work!

Resources