问:
Deploying dash app on Heroku - Exception in worker process
I am trying to deploy my dash app with Heroku. I can deploy it on local host but it is not possible to deploy it with Heroku.

According to the logs (see below) it looks like there is something wrong with my Procfile.

This is the content of my Procfile:

```<code>web: gunicorn electricity_dashboard:server
</code>```

Code of electricity_dashboard.py is the following:

```<code>import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.express as px

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

url1 = 'url1.csv'
url2 = 'url2.csv'

df_hour = pd.read_csv(url1, index_col=0)
df_day = pd.read_csv(url2, index_col=0)

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
server = app.server

fig1 = px.bar(df_day, x="dayofweek", y="Consumption [Wh]")
fig2 = px.bar(df_hour, x="hour", y="Consumption [Wh]")

app.layout = html.Div(....)

if __name__ == '__main__':
    app.run_server()
</code>```

Besides the Procfile which I suspect to be erroneous there is also an error regarding the pandas read_csv method. It seems like reading from my Github URL is not working.

```<code>pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 148, saw 2
</code>```

These are the logs I got:

```<code>2022-02-06T21:20:54.046849+00:00 heroku[web.1]: Starting process with command `gunicorn electricity_dashboard:server`
2022-02-06T21:20:55.591730+00:00 app[web.1]: [2022-02-06 21:20:55 +0000] [4] [INFO] Starting gunicorn 20.1.0
2022-02-06T21:20:55.592181+00:00 app[web.1]: [2022-02-06 21:20:55 +0000] [4] [INFO] Listening at: http://0.0.0.0:28360 (4)
2022-02-06T21:20:55.592228+00:00 app[web.1]: [2022-02-06 21:20:55 +0000] [4] [INFO] Using worker: sync
2022-02-06T21:20:55.600422+00:00 app[web.1]: [2022-02-06 21:20:55 +0000] [9] [INFO] Booting worker with pid: 9
2022-02-06T21:20:55.671893+00:00 app[web.1]: [2022-02-06 21:20:55 +0000] [10] [INFO] Booting worker with pid: 10
2022-02-06T21:20:56.020715+00:00 heroku[web.1]: State changed from starting to up
2022-02-06T21:20:56.672424+00:00 app[web.1]: /app/electricity_dashboard.py:2: UserWarning:
2022-02-06T21:20:56.672445+00:00 app[web.1]: The dash_core_components package is deprecated. Please replace
2022-02-06T21:20:56.672446+00:00 app[web.1]: `import dash_core_components as dcc` with `from dash import dcc`
2022-02-06T21:20:56.672447+00:00 app[web.1]: import dash_core_components as dcc
2022-02-06T21:20:56.672586+00:00 app[web.1]: /app/electricity_dashboard.py:2: UserWarning:
2022-02-06T21:20:56.672586+00:00 app[web.1]: The dash_core_components package is deprecated. Please replace
2022-02-06T21:20:56.672587+00:00 app[web.1]: `import dash_core_components as dcc` with `from dash import dcc`
2022-02-06T21:20:56.672587+00:00 app[web.1]: import dash_core_components as dcc
2022-02-06T21:20:56.672980+00:00 app[web.1]: /app/electricity_dashboard.py:3: UserWarning:
2022-02-06T21:20:56.672982+00:00 app[web.1]: The dash_html_components package is deprecated. Please replace
2022-02-06T21:20:56.672982+00:00 app[web.1]: `import dash_html_components as html` with `from dash import html`
2022-02-06T21:20:56.672982+00:00 app[web.1]: import dash_html_components as html
2022-02-06T21:20:56.673497+00:00 app[web.1]: /app/electricity_dashboard.py:3: UserWarning:
2022-02-06T21:20:56.673498+00:00 app[web.1]: The dash_html_components package is deprecated. Please replace
2022-02-06T21:20:56.673499+00:00 app[web.1]: `import dash_html_components as html` with `from dash import html`
2022-02-06T21:20:56.673500+00:00 app[web.1]: import dash_html_components as html
2022-02-06T21:21:00.857089+00:00 app[web.1]: [2022-02-06 21:21:00 +0000] [9] [ERROR] Exception in worker process
2022-02-06T21:21:00.857103+00:00 app[web.1]: Traceback (most recent call last):
2022-02-06T21:21:00.857104+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker
2022-02-06T21:21:00.857104+00:00 app[web.1]: worker.init_process()
2022-02-06T21:21:00.857105+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process
2022-02-06T21:21:00.857105+00:00 app[web.1]: self.load_wsgi()
2022-02-06T21:21:00.857105+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi
2022-02-06T21:21:00.857106+00:00 app[web.1]: self.wsgi = self.app.wsgi()
2022-02-06T21:21:00.857107+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi
2022-02-06T21:21:00.857107+00:00 app[web.1]: self.callable = self.load()
2022-02-06T21:21:00.857107+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load
2022-02-06T21:21:00.857108+00:00 app[web.1]: return self.load_wsgiapp()
2022-02-06T21:21:00.857108+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp
2022-02-06T21:21:00.857108+00:00 app[web.1]: return util.import_app(self.app_uri)
2022-02-06T21:21:00.857109+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app
2022-02-06T21:21:00.857109+00:00 app[web.1]: mod = importlib.import_module(module)
2022-02-06T21:21:00.857109+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module
2022-02-06T21:21:00.857110+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level)
2022-02-06T21:21:00.857110+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
2022-02-06T21:21:00.857111+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
2022-02-06T21:21:00.857111+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
2022-02-06T21:21:00.857111+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
2022-02-06T21:21:00.857112+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 850, in exec_module
2022-02-06T21:21:00.857112+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
2022-02-06T21:21:00.857112+00:00 app[web.1]: File "/app/electricity_dashboard.py", line 15, in <module>
2022-02-06T21:21:00.857113+00:00 app[web.1]: df_hour = pd.read_csv(url1, index_col=0)
2022-02-06T21:21:00.857113+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/pandas/util/_decorators.py", line 311, in wrapper
2022-02-06T21:21:00.857113+00:00 app[web.1]: return func(*args, **kwargs)
2022-02-06T21:21:00.857114+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/pandas/io/parsers/readers.py", line 586, in read_csv
2022-02-06T21:21:00.857114+00:00 app[web.1]: return _read(filepath_or_buffer, kwds)
2022-02-06T21:21:00.857114+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/pandas/io/parsers/readers.py", line 488, in _read
2022-02-06T21:21:00.857114+00:00 app[web.1]: return parser.read(nrows)
2022-02-06T21:21:00.857114+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/pandas/io/parsers/readers.py", line 1047, in read
2022-02-06T21:21:00.857115+00:00 app[web.1]: index, columns, col_dict = self._engine.read(nrows)
2022-02-06T21:21:00.857115+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/pandas/io/parsers/c_parser_wrapper.py", line 224, in read
2022-02-06T21:21:00.857116+00:00 app[web.1]: chunks = self._reader.read_low_memory(nrows)
2022-02-06T21:21:00.857116+00:00 app[web.1]: File "pandas/_libs/parsers.pyx", line 801, in pandas._libs.parsers.TextReader.read_low_memory
2022-02-06T21:21:00.857116+00:00 app[web.1]: File "pandas/_libs/parsers.pyx", line 857, in pandas._libs.parsers.TextReader._read_rows
2022-02-06T21:21:00.857116+00:00 app[web.1]: File "pandas/_libs/parsers.pyx", line 843, in pandas._libs.parsers.TextReader._tokenize_rows
2022-02-06T21:21:00.857116+00:00 app[web.1]: File "pandas/_libs/parsers.pyx", line 1925, in pandas._libs.parsers.raise_parser_error
2022-02-06T21:21:00.857117+00:00 app[web.1]: pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 148, saw 2
2022-02-06T21:21:00.857117+00:00 app[web.1]:
2022-02-06T21:21:00.857243+00:00 app[web.1]: [2022-02-06 21:21:00 +0000] [9] [INFO] Worker exiting (pid: 9)
2022-02-06T21:21:00.858505+00:00 app[web.1]: [2022-02-06 21:21:00 +0000] [10] [ERROR] Exception in worker process
2022-02-06T21:21:00.858507+00:00 app[web.1]: Traceback (most recent call last):
2022-02-06T21:21:00.858507+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker
2022-02-06T21:21:00.858508+00:00 app[web.1]: worker.init_process()
2022-02-06T21:21:00.858509+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process
2022-02-06T21:21:00.858509+00:00 app[web.1]: self.load_wsgi()
2022-02-06T21:21:00.858510+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi
2022-02-06T21:21:00.858510+00:00 app[web.1]: self.wsgi = self.app.wsgi()
2022-02-06T21:21:00.858511+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi
2022-02-06T21:21:00.858511+00:00 app[web.1]: self.callable = self.load()
2022-02-06T21:21:00.858511+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load
2022-02-06T21:21:00.858512+00:00 app[web.1]: return self.load_wsgiapp()
2022-02-06T21:21:00.858512+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp
2022-02-06T21:21:00.858512+00:00 app[web.1]: return util.import_app(self.app_uri)
2022-02-06T21:21:00.858513+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app
2022-02-06T21:21:00.858513+00:00 app[web.1]: mod = importlib.import_module(module)
2022-02-06T21:21:00.858514+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module
2022-02-06T21:21:00.858514+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level)
2022-02-06T21:21:00.858515+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
2022-02-06T21:21:00.858515+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
2022-02-06T21:21:00.858516+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
2022-02-06T21:21:00.858516+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
2022-02-06T21:21:00.858516+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 850, in exec_module
2022-02-06T21:21:00.858517+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
2022-02-06T21:21:00.858517+00:00 app[web.1]: File "/app/electricity_dashboard.py", line 15, in <module>
2022-02-06T21:21:00.858518+00:00 app[web.1]: df_hour = pd.read_csv(url1, index_col=0)
2022-02-06T21:21:00.858518+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/pandas/util/_decorators.py", line 311, in wrapper
2022-02-06T21:21:00.858518+00:00 app[web.1]: return func(*args, **kwargs)
2022-02-06T21:21:00.858519+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/pandas/io/parsers/readers.py", line 586, in read_csv
2022-02-06T21:21:00.858519+00:00 app[web.1]: return _read(filepath_or_buffer, kwds)
2022-02-06T21:21:00.858519+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/pandas/io/parsers/readers.py", line 488, in _read
2022-02-06T21:21:00.858520+00:00 app[web.1]: return parser.read(nrows)
2022-02-06T21:21:00.858530+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/pandas/io/parsers/readers.py", line 1047, in read
2022-02-06T21:21:00.858530+00:00 app[web.1]: index, columns, col_dict = self._engine.read(nrows)
2022-02-06T21:21:00.858531+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/pandas/io/parsers/c_parser_wrapper.py", line 224, in read
2022-02-06T21:21:00.858532+00:00 app[web.1]: chunks = self._reader.read_low_memory(nrows)
2022-02-06T21:21:00.858532+00:00 app[web.1]: File "pandas/_libs/parsers.pyx", line 801, in pandas._libs.parsers.TextReader.read_low_memory
2022-02-06T21:21:00.858532+00:00 app[web.1]: File "pandas/_libs/parsers.pyx", line 857, in pandas._libs.parsers.TextReader._read_rows
2022-02-06T21:21:00.858533+00:00 app[web.1]: File "pandas/_libs/parsers.pyx", line 843, in pandas._libs.parsers.TextReader._tokenize_rows
2022-02-06T21:21:00.858533+00:00 app[web.1]: File "pandas/_libs/parsers.pyx", line 1925, in pandas._libs.parsers.raise_parser_error
2022-02-06T21:21:00.858534+00:00 app[web.1]: pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 148, saw 2
2022-02-06T21:21:00.858534+00:00 app[web.1]:
2022-02-06T21:21:00.858731+00:00 app[web.1]: [2022-02-06 21:21:00 +0000] [10] [INFO] Worker exiting (pid: 10)
2022-02-06T21:21:01.340085+00:00 app[web.1]: [2022-02-06 21:21:01 +0000] [4] [WARNING] Worker with pid 10 was terminated due to signal 15
2022-02-06T21:21:01.433301+00:00 app[web.1]: [2022-02-06 21:21:01 +0000] [4] [INFO] Shutting down: Master
2022-02-06T21:21:01.433358+00:00 app[web.1]: [2022-02-06 21:21:01 +0000] [4] [INFO] Reason: Worker failed to boot.
2022-02-06T21:21:01.597094+00:00 heroku[web.1]: Process exited with status 3
2022-02-06T21:21:01.657248+00:00 heroku[web.1]: State changed from up to crashed
</code>```

Thanks a lot in advance!

答:
The problem was regarding the read_csv method. I did not specify the path to the data in my GitHub-repository correctly. Furthermore, in my case I also removed index_col=0. As stated in the answer to this question I had to use the raw content: How to read CSV file from GitHub using pandas

This solved the problem and I could finally successfully deploy my dash app in Heroku.

Body:
I am trying to deploy my dash app with Heroku. I can deploy it on local host but it is not possible to deploy it with Heroku.

According to the logs (see below) it looks like there is something wrong with my Procfile.

This is the content of my Procfile:

web: gunicorn electricity_dashboard:server

Code of electricity_dashboard.py is the following:

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.express as px

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

url1 = 'url1.csv'
url2 = 'url2.csv'

df_hour = pd.read_csv(url1, index_col=0)
df_day = pd.read_csv(url2, index_col=0)

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
server = app.server

fig1 = px.bar(df_day, x="dayofweek", y="Consumption [Wh]")
fig2 = px.bar(df_hour, x="hour", y="Consumption [Wh]")

app.layout = html.Div(....)

if __name__ == '__main__':
    app.run_server()

Besides the Procfile which I suspect to be erroneous there is also an error regarding the pandas read_csv method. It seems like reading from my Github URL is not working.

pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 148, saw 2

These are the logs I got:

2022-02-06T21:20:54.046849+00:00 heroku[web.1]: Starting process with command `gunicorn electricity_dashboard:server`
2022-02-06T21:20:55.591730+00:00 app[web.1]: [2022-02-06 21:20:55 +0000] [4] [INFO] Starting gunicorn 20.1.0
2022-02-06T21:20:55.592181+00:00 app[web.1]: [2022-02-06 21:20:55 +0000] [4] [INFO] Listening at: http://0.0.0.0:28360 (4)
2022-02-06T21:20:55.592228+00:00 app[web.1]: [2022-02-06 21:20:55 +0000] [4] [INFO] Using worker: sync
2022-02-06T21:20:55.600422+00:00 app[web.1]: [2022-02-06 21:20:55 +0000] [9] [INFO] Booting worker with pid: 9
2022-02-06T21:20:55.671893+00:00 app[web.1]: [2022-02-06 21:20:55 +0000] [10] [INFO] Booting worker with pid: 10
2022-02-06T21:20:56.020715+00:00 heroku[web.1]: State changed from starting to up
2022-02-06T21:20:56.672424+00:00 app[web.1]: /app/electricity_dashboard.py:2: UserWarning:
2022-02-06T21:20:56.672445+00:00 app[web.1]: The dash_core_components package is deprecated. Please replace
2022-02-06T21:20:56.672446+00:00 app[web.1]: `import dash_core_components as dcc` with `from dash import dcc`
2022-02-06T21:20:56.672447+00:00 app[web.1]: import dash_core_components as dcc
2022-02-06T21:20:56.672586+00:00 app[web.1]: /app/electricity_dashboard.py:2: UserWarning:
2022-02-06T21:20:56.672586+00:00 app[web.1]: The dash_core_components package is deprecated. Please replace
2022-02-06T21:20:56.672587+00:00 app[web.1]: `import dash_core_components as dcc` with `from dash import dcc`
2022-02-06T21:20:56.672587+00:00 app[web.1]: import dash_core_components as dcc
2022-02-06T21:20:56.672980+00:00 app[web.1]: /app/electricity_dashboard.py:3: UserWarning:
2022-02-06T21:20:56.672982+00:00 app[web.1]: The dash_html_components package is deprecated. Please replace
2022-02-06T21:20:56.672982+00:00 app[web.1]: `import dash_html_components as html` with `from dash import html`
2022-02-06T21:20:56.672982+00:00 app[web.1]: import dash_html_components as html
2022-02-06T21:20:56.673497+00:00 app[web.1]: /app/electricity_dashboard.py:3: UserWarning:
2022-02-06T21:20:56.673498+00:00 app[web.1]: The dash_html_components package is deprecated. Please replace
2022-02-06T21:20:56.673499+00:00 app[web.1]: `import dash_html_components as html` with `from dash import html`
2022-02-06T21:20:56.673500+00:00 app[web.1]: import dash_html_components as html
2022-02-06T21:21:00.857089+00:00 app[web.1]: [2022-02-06 21:21:00 +0000] [9] [ERROR] Exception in worker process
2022-02-06T21:21:00.857103+00:00 app[web.1]: Traceback (most recent call last):
2022-02-06T21:21:00.857104+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker
2022-02-06T21:21:00.857104+00:00 app[web.1]: worker.init_process()
2022-02-06T21:21:00.857105+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process
2022-02-06T21:21:00.857105+00:00 app[web.1]: self.load_wsgi()
2022-02-06T21:21:00.857105+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi
2022-02-06T21:21:00.857106+00:00 app[web.1]: self.wsgi = self.app.wsgi()
2022-02-06T21:21:00.857107+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi
2022-02-06T21:21:00.857107+00:00 app[web.1]: self.callable = self.load()
2022-02-06T21:21:00.857107+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load
2022-02-06T21:21:00.857108+00:00 app[web.1]: return self.load_wsgiapp()
2022-02-06T21:21:00.857108+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp
2022-02-06T21:21:00.857108+00:00 app[web.1]: return util.import_app(self.app_uri)
2022-02-06T21:21:00.857109+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app
2022-02-06T21:21:00.857109+00:00 app[web.1]: mod = importlib.import_module(module)
2022-02-06T21:21:00.857109+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module
2022-02-06T21:21:00.857110+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level)
2022-02-06T21:21:00.857110+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
2022-02-06T21:21:00.857111+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
2022-02-06T21:21:00.857111+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
2022-02-06T21:21:00.857111+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
2022-02-06T21:21:00.857112+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 850, in exec_module
2022-02-06T21:21:00.857112+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
2022-02-06T21:21:00.857112+00:00 app[web.1]: File "/app/electricity_dashboard.py", line 15, in <module>
2022-02-06T21:21:00.857113+00:00 app[web.1]: df_hour = pd.read_csv(url1, index_col=0)
2022-02-06T21:21:00.857113+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/pandas/util/_decorators.py", line 311, in wrapper
2022-02-06T21:21:00.857113+00:00 app[web.1]: return func(*args, **kwargs)
2022-02-06T21:21:00.857114+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/pandas/io/parsers/readers.py", line 586, in read_csv
2022-02-06T21:21:00.857114+00:00 app[web.1]: return _read(filepath_or_buffer, kwds)
2022-02-06T21:21:00.857114+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/pandas/io/parsers/readers.py", line 488, in _read
2022-02-06T21:21:00.857114+00:00 app[web.1]: return parser.read(nrows)
2022-02-06T21:21:00.857114+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/pandas/io/parsers/readers.py", line 1047, in read
2022-02-06T21:21:00.857115+00:00 app[web.1]: index, columns, col_dict = self._engine.read(nrows)
2022-02-06T21:21:00.857115+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/pandas/io/parsers/c_parser_wrapper.py", line 224, in read
2022-02-06T21:21:00.857116+00:00 app[web.1]: chunks = self._reader.read_low_memory(nrows)
2022-02-06T21:21:00.857116+00:00 app[web.1]: File "pandas/_libs/parsers.pyx", line 801, in pandas._libs.parsers.TextReader.read_low_memory
2022-02-06T21:21:00.857116+00:00 app[web.1]: File "pandas/_libs/parsers.pyx", line 857, in pandas._libs.parsers.TextReader._read_rows
2022-02-06T21:21:00.857116+00:00 app[web.1]: File "pandas/_libs/parsers.pyx", line 843, in pandas._libs.parsers.TextReader._tokenize_rows
2022-02-06T21:21:00.857116+00:00 app[web.1]: File "pandas/_libs/parsers.pyx", line 1925, in pandas._libs.parsers.raise_parser_error
2022-02-06T21:21:00.857117+00:00 app[web.1]: pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 148, saw 2
2022-02-06T21:21:00.857117+00:00 app[web.1]:
2022-02-06T21:21:00.857243+00:00 app[web.1]: [2022-02-06 21:21:00 +0000] [9] [INFO] Worker exiting (pid: 9)
2022-02-06T21:21:00.858505+00:00 app[web.1]: [2022-02-06 21:21:00 +0000] [10] [ERROR] Exception in worker process
2022-02-06T21:21:00.858507+00:00 app[web.1]: Traceback (most recent call last):
2022-02-06T21:21:00.858507+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker
2022-02-06T21:21:00.858508+00:00 app[web.1]: worker.init_process()
2022-02-06T21:21:00.858509+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process
2022-02-06T21:21:00.858509+00:00 app[web.1]: self.load_wsgi()
2022-02-06T21:21:00.858510+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi
2022-02-06T21:21:00.858510+00:00 app[web.1]: self.wsgi = self.app.wsgi()
2022-02-06T21:21:00.858511+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi
2022-02-06T21:21:00.858511+00:00 app[web.1]: self.callable = self.load()
2022-02-06T21:21:00.858511+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load
2022-02-06T21:21:00.858512+00:00 app[web.1]: return self.load_wsgiapp()
2022-02-06T21:21:00.858512+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp
2022-02-06T21:21:00.858512+00:00 app[web.1]: return util.import_app(self.app_uri)
2022-02-06T21:21:00.858513+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app
2022-02-06T21:21:00.858513+00:00 app[web.1]: mod = importlib.import_module(module)
2022-02-06T21:21:00.858514+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module
2022-02-06T21:21:00.858514+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level)
2022-02-06T21:21:00.858515+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
2022-02-06T21:21:00.858515+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
2022-02-06T21:21:00.858516+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
2022-02-06T21:21:00.858516+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
2022-02-06T21:21:00.858516+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 850, in exec_module
2022-02-06T21:21:00.858517+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
2022-02-06T21:21:00.858517+00:00 app[web.1]: File "/app/electricity_dashboard.py", line 15, in <module>
2022-02-06T21:21:00.858518+00:00 app[web.1]: df_hour = pd.read_csv(url1, index_col=0)
2022-02-06T21:21:00.858518+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/pandas/util/_decorators.py", line 311, in wrapper
2022-02-06T21:21:00.858518+00:00 app[web.1]: return func(*args, **kwargs)
2022-02-06T21:21:00.858519+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/pandas/io/parsers/readers.py", line 586, in read_csv
2022-02-06T21:21:00.858519+00:00 app[web.1]: return _read(filepath_or_buffer, kwds)
2022-02-06T21:21:00.858519+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/pandas/io/parsers/readers.py", line 488, in _read
2022-02-06T21:21:00.858520+00:00 app[web.1]: return parser.read(nrows)
2022-02-06T21:21:00.858530+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/pandas/io/parsers/readers.py", line 1047, in read
2022-02-06T21:21:00.858530+00:00 app[web.1]: index, columns, col_dict = self._engine.read(nrows)
2022-02-06T21:21:00.858531+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/pandas/io/parsers/c_parser_wrapper.py", line 224, in read
2022-02-06T21:21:00.858532+00:00 app[web.1]: chunks = self._reader.read_low_memory(nrows)
2022-02-06T21:21:00.858532+00:00 app[web.1]: File "pandas/_libs/parsers.pyx", line 801, in pandas._libs.parsers.TextReader.read_low_memory
2022-02-06T21:21:00.858532+00:00 app[web.1]: File "pandas/_libs/parsers.pyx", line 857, in pandas._libs.parsers.TextReader._read_rows
2022-02-06T21:21:00.858533+00:00 app[web.1]: File "pandas/_libs/parsers.pyx", line 843, in pandas._libs.parsers.TextReader._tokenize_rows
2022-02-06T21:21:00.858533+00:00 app[web.1]: File "pandas/_libs/parsers.pyx", line 1925, in pandas._libs.parsers.raise_parser_error
2022-02-06T21:21:00.858534+00:00 app[web.1]: pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 148, saw 2
2022-02-06T21:21:00.858534+00:00 app[web.1]:
2022-02-06T21:21:00.858731+00:00 app[web.1]: [2022-02-06 21:21:00 +0000] [10] [INFO] Worker exiting (pid: 10)
2022-02-06T21:21:01.340085+00:00 app[web.1]: [2022-02-06 21:21:01 +0000] [4] [WARNING] Worker with pid 10 was terminated due to signal 15
2022-02-06T21:21:01.433301+00:00 app[web.1]: [2022-02-06 21:21:01 +0000] [4] [INFO] Shutting down: Master
2022-02-06T21:21:01.433358+00:00 app[web.1]: [2022-02-06 21:21:01 +0000] [4] [INFO] Reason: Worker failed to boot.
2022-02-06T21:21:01.597094+00:00 heroku[web.1]: Process exited with status 3
2022-02-06T21:21:01.657248+00:00 heroku[web.1]: State changed from up to crashed

Thanks a lot in advance!


来源: stackexchange

问:
Aggregate like Initialization without superfluous calls of constructors
I am trying to write mostly a reimplementation of std::array. But, I am not very happy about the rules for aggregate initialization (and some other minor details) and thus do not want to use it.

Things I do not like with aggregate initilization:

Having less than the necessary elements in the list, produces no error, this is particularly strange for aggregates of aggregates, e.g.

struct A { int x,y; };
std::array arr{1,2,3};
// produces A[0].x = 1, A[0].y = 2, A[1].x = 1, A[1].y = 0
```
</li>
<li>private/deleted ctors are still callable by the user
<pre class="lang-cpp prettyprint-override"><code>class B { B() = delete; };
B{};  // no compile time error
</code>```

What I have so far is the following:

#include <cstddef>
#include <type_traits>
#include <utility>

template< typename T, typename ... Ts >
inline constexpr bool areT_v = std::conjunction_v< std::is_same<T, Ts> ... >;

namespace ttt {
    template< typename T, int N >
    struct array
    {
        template< typename ... L >
        array( L && ... lst ) : content{ std::forward< L >( lst ) ... } {
            static_assert( sizeof...(L) == N || sizeof...(L)==0, ""  );
            static_assert( areT_v<T,L...>, "" );
        }
        array() = default;  // not sure whether I need this one

        using ContentType = typename std::conditional< N>=1 , T, char >::type;
        ContentType content[ N>=1 ? N : 1];

        /* member functions */
    };
}
```
<p>Actually I am quite happy with this implementation, apart from the following fact. Using
<code>ttt::array</code> I have more ctor calls then when using <code>std::array</code>. E.g.:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <array>
#include <iostream>

struct CLASS {
    int x, y;
    CLASS() {
        std::cout << "def-ctor" << std::endl;
    }
    CLASS(int x_,int y_) : x(x_), y(y_) {
        std::cout << "xy-ctor" << std::endl;
    }
    CLASS( CLASS const & other ) : x(other.x), y(other.y) {
        std::cout << "copy-ctor" << std::endl;
    }
};

int main() {
    std::array< CLASS, 1 > stda{CLASS{1,2}};  // calls xy-ctor
    ttt::array< CLASS, 1 > ttta{CLASS{1,2}};  // calls xy-ctor AND copy-ctor
}
</code>```

This seems to be connected with the reason that std::array is aggregate initialized (because it is an aggregate), but ttt::array is not.
This leads me to the question, is the compiler allowed to do something here (omitting one ctor call), I am not allowed to do?

And, is there a way around this?

答:
You could package the arguments that should be used to construct the elements in content in std::tuples and delay creation of the actual objects until it's time to initialize content.

An outline:

template <class T, std::size_t N>
struct array {
    template<class... Ts>
    constexpr array(Ts&&... args) :
        content{to_t(std::forward<Ts>(args),
                     std::make_index_sequence<std::tuple_size<Ts>::value>())...}
    {
        static_assert(sizeof...(Ts) == N, "wrong number of elements");
    }

private:
    // create one T from a tuple
    template<class... Ts, std::size_t... Idx>
    T to_t(std::tuple<Ts...>&& in, std::index_sequence<Idx...>) {
        return T{std::forward<Ts>(std::get<Idx>(in))...};
    }

    T content[N];
};
```
<p>Example type to put in an <code>array</code>:</p>
<pre class="lang-cpp prettyprint-override"><code>struct Foo {
    Foo() : a(0.), b(0) { std::cout << "Foo::Foo()\n"; }
    explicit Foo(double A, int B) : a(A), b(B) { std::cout << "Foo::Foo(double, int)\n"; }
    Foo(const Foo& o) : a(o.a), b(o.b) { std::cout << "Foo(const Foo&)\n"; }
    Foo(Foo&& o) : a(o.a), b(o.b) { std::cout << "Foo(Foo&&)\n"; }
    ~Foo() { std::cout << "Foo::~Foo() {" << a << ", " << b << "}\n"; }

private:
    double a;
    int b;
};
</code>```

You could then create your array without copying/moving your T:s (guaranteed in C++17, with copy/move elision in C++14, so not guaranteed but probable) by packaging them in tuples. It's a bit cumbersome to type. Hopefully someone else has an idea for how to get around that.

int main() {
    Foo f{3.3, 3};
    array<Foo, 4> x(std::forward_as_tuple(1.1, 1),
                    std::forward_as_tuple(),            // default constructor
                    std::forward_as_tuple(2.2, 2),
                    std::forward_as_tuple(std::move(f)) // move constructor
                   );
}
```

Demo

You can add the compiler option -fno-elide-constructors to see that it will move the elements when that optimization is turned off in C++14 mode.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to write mostly a reimplementation of std::array. But, I am not very happy about the rules for aggregate initialization (and some other minor details) and thus do not want to use it.

Things I do not like with aggregate initilization:

Having less than the necessary elements in the list, produces no error, this is particularly strange for aggregates of aggregates, e.g.

struct A { int x,y; };
std::array arr{1,2,3};
// produces A[0].x = 1, A[0].y = 2, A[1].x = 1, A[1].y = 0

private/deleted ctors are still callable by the user

class B { B() = delete; };
B{};  // no compile time error

What I have so far is the following:

#include <cstddef>
#include <type_traits>
#include <utility>

template< typename T, typename ... Ts >
inline constexpr bool areT_v = std::conjunction_v< std::is_same<T, Ts> ... >;

namespace ttt {
    template< typename T, int N >
    struct array
    {
        template< typename ... L >
        array( L && ... lst ) : content{ std::forward< L >( lst ) ... } {
            static_assert( sizeof...(L) == N || sizeof...(L)==0, ""  );
            static_assert( areT_v<T,L...>, "" );
        }
        array() = default;  // not sure whether I need this one

        using ContentType = typename std::conditional< N>=1 , T, char >::type;
        ContentType content[ N>=1 ? N : 1];

        /* member functions */
    };
}

Actually I am quite happy with this implementation, apart from the following fact. Using
ttt::array I have more ctor calls then when using std::array. E.g.:

#include <array>
#include <iostream>

struct CLASS {
    int x, y;
    CLASS() {
        std::cout << "def-ctor" << std::endl;
    }
    CLASS(int x_,int y_) : x(x_), y(y_) {
        std::cout << "xy-ctor" << std::endl;
    }
    CLASS( CLASS const & other ) : x(other.x), y(other.y) {
        std::cout << "copy-ctor" << std::endl;
    }
};

int main() {
    std::array< CLASS, 1 > stda{CLASS{1,2}};  // calls xy-ctor
    ttt::array< CLASS, 1 > ttta{CLASS{1,2}};  // calls xy-ctor AND copy-ctor
}

This seems to be connected with the reason that std::array is aggregate initialized (because it is an aggregate), but ttt::array is not.
This leads me to the question, is the compiler allowed to do something here (omitting one ctor call), I am not allowed to do?

And, is there a way around this?

Body:
You could package the arguments that should be used to construct the elements in content in std::tuples and delay creation of the actual objects until it's time to initialize content.

An outline:

template <class T, std::size_t N>
struct array {
    template<class... Ts>
    constexpr array(Ts&&... args) :
        content{to_t(std::forward<Ts>(args),
                     std::make_index_sequence<std::tuple_size<Ts>::value>())...}
    {
        static_assert(sizeof...(Ts) == N, "wrong number of elements");
    }

private:
    // create one T from a tuple
    template<class... Ts, std::size_t... Idx>
    T to_t(std::tuple<Ts...>&& in, std::index_sequence<Idx...>) {
        return T{std::forward<Ts>(std::get<Idx>(in))...};
    }

    T content[N];
};

Example type to put in an array:

struct Foo {
    Foo() : a(0.), b(0) { std::cout << "Foo::Foo()\n"; }
    explicit Foo(double A, int B) : a(A), b(B) { std::cout << "Foo::Foo(double, int)\n"; }
    Foo(const Foo& o) : a(o.a), b(o.b) { std::cout << "Foo(const Foo&)\n"; }
    Foo(Foo&& o) : a(o.a), b(o.b) { std::cout << "Foo(Foo&&)\n"; }
    ~Foo() { std::cout << "Foo::~Foo() {" << a << ", " << b << "}\n"; }

private:
    double a;
    int b;
};

You could then create your array without copying/moving your T:s (guaranteed in C++17, with copy/move elision in C++14, so not guaranteed but probable) by packaging them in tuples. It's a bit cumbersome to type. Hopefully someone else has an idea for how to get around that.

int main() {
    Foo f{3.3, 3};
    array<Foo, 4> x(std::forward_as_tuple(1.1, 1),
                    std::forward_as_tuple(),            // default constructor
                    std::forward_as_tuple(2.2, 2),
                    std::forward_as_tuple(std::move(f)) // move constructor
                   );
}

Demo

You can add the compiler option -fno-elide-constructors to see that it will move the elements when that optimization is turned off in C++14 mode.


问:
Custom "Basic" Authentication for my WCF services. REST and RIA. Possible?
My server side contains WCF4 REST services and I'm going to add RIA services for my future SL4 application.  Currently I'm doing Basic authentication like this:

```<code>var auth = HttpContext.Current.Request.Headers.GetValues("Authorization");
</code>```

And so on.. You get the idea.. I call this on every request. If header not present or I can't validate UN/Password - I do this:

```<code>outgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"Secure Area\"");
</code>```

That got me by so far but I'm refactoring my server side. Implementing IoC for linked services. Created custom ServiceHost, ServiceHostFactory, InstanceProvider and all is well.

Now I need to figure how to properly handle authentication and authorization with WCF so I don't have to manually inspect headers. I do have my custom MembershipProvider so there have to be some method that get's UN/PW to process.

Any pointers? I looked at http://www.codeproject.com/KB/WCF/BasicAuthWCFRest.aspx but it uses RequestInterceptor and it is not available in WCF4. I found ServiceAuthenticationManager and ServiceAuthorizationManager but there is no samples available on how to code and wire those..

Can anybody suggest which way I should go?

答:
I had all types of issues using the built-in annotations for WCF in a recent SOAP/C# project. I know this isn't the best solution, but for my purposes, I enabled basic authentication in IIS7 for my application, disabled anonymous authentication and created Active Directory users for the external clients that would call the web service endpoints. I then changed the application's permissions in IIS7 (it uses file system permissions) to allow a group containing those users. </p>

<p>This moves authentication outside your application, which may not be what you want, but does allow you to easily add users via the IIS7 console and deployment tools that can copy those permissions. The advantage is that you don't have to redeploy your application for permission changes. The disadvantage is you can't do fine grained permission control per function. </p>

ContentLicense: CC BY-SA 3.0

Body:
My server side contains WCF4 REST services and I'm going to add RIA services for my future SL4 application.  Currently I'm doing Basic authentication like this:

var auth = HttpContext.Current.Request.Headers.GetValues("Authorization");

And so on.. You get the idea.. I call this on every request. If header not present or I can't validate UN/Password - I do this:

outgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"Secure Area\"");

That got me by so far but I'm refactoring my server side. Implementing IoC for linked services. Created custom ServiceHost, ServiceHostFactory, InstanceProvider and all is well.

Now I need to figure how to properly handle authentication and authorization with WCF so I don't have to manually inspect headers. I do have my custom MembershipProvider so there have to be some method that get's UN/PW to process.

Any pointers? I looked at http://www.codeproject.com/KB/WCF/BasicAuthWCFRest.aspx but it uses RequestInterceptor and it is not available in WCF4. I found ServiceAuthenticationManager and ServiceAuthorizationManager but there is no samples available on how to code and wire those..

Can anybody suggest which way I should go?

Body:
I had all types of issues using the built-in annotations for WCF in a recent SOAP/C# project. I know this isn't the best solution, but for my purposes, I enabled basic authentication in IIS7 for my application, disabled anonymous authentication and created Active Directory users for the external clients that would call the web service endpoints. I then changed the application's permissions in IIS7 (it uses file system permissions) to allow a group containing those users.

This moves authentication outside your application, which may not be what you want, but does allow you to easily add users via the IIS7 console and deployment tools that can copy those permissions. The advantage is that you don't have to redeploy your application for permission changes. The disadvantage is you can't do fine grained permission control per function.


问:
how to get the text-underline from strapi articles to my gatsby frontend
I'm working on a support site with strapi(backend) and gatsbyjs/react (frontend).
I am trying to retrieve from my admin strapi the text I have underlined and display it in my frontend but it is not retrieving the  tag correctly and is displaying the  tag instead of the underlined text.
Is it because of my react-markdown?

here is my webview:
when I look at the element inspector I see inverted commas before my  tag which is why it doesn't work

and here is my code:

```<code>import React from "react";
import { graphql, PageProps } from "gatsby";
import ReactMarkdown from "react-markdown";

import { ArticleT } from "@faq/types";

import Layout from "@faq/components/Layout";

import * as s from "./Article.module.css";
import { toArticle, toCategory } from "@faq/utils/routes";

type ArticlePageProps = {
  strapiArticle: ArticleT;
  file: {
    publicURL: string;
  };
};

const Article: React.FC<PageProps<ArticlePageProps>> = ({
  data: { strapiArticle },
}) => {
  const { title, content, category, slug } = strapiArticle;

  return (
    <Layout
      seo={{ pageTitle: title, pageUrl: toArticle(category.slug, slug) }}
      breadcrumb={[
        { to: toCategory(category.slug), label: category.title },
        { label: title },
      ]}
    >
      <div className={s.wrapper}>
        <h1 className={s.title}>{title}</h1>
        <div className={s.author}>
          <div className={s.texts}>
            <div>
              <span className={s.light}>Écrit par</span> Nicolas
            </div>
          </div>
        </div>
        <ReactMarkdown children={content}
          className={s.content}
          transformImageUri={uri => uri.startsWith("http") ? uri : `${process.env.GATSBY_IMAGE_BASE_URL}${uri}`} />
      </div>
    </Layout>
  );
};

export default Article;

export const query = graphql`
  query ArticleQuery($id: Int!) {
    strapiArticle(strapiId: { eq: $id }) {
      title
      content
      slug
      category {
        title
        slug
      }
    }
  }
`;
</code>```

答:
Have you tried using your own rendering component (components)?

```<code>  <ReactMarkdown
    children={content}
    components={{
      u: ({node, ...props}) => <u style={{textDecoration: 'underline'}} {...props} />
    }}
   className={s.content}
   transformImageUri={uri => uri.startsWith("http") ? uri : `${process.env.GATSBY_IMAGE_BASE_URL}${uri}`}
  />
</code>```

More details about components property: https://github.com/remarkjs/react-markdown#appendix-b-components

You can even use a custom-styled
 instead of  if needed. The idea relies on parsing the  tag to add your own underlined component.

Apparently, it is needed to install rehype-raw plugin to allow ReactMarkdown to understand and interpret underlined tags ()

Body:
I'm working on a support site with strapi(backend) and gatsbyjs/react (frontend).
I am trying to retrieve from my admin strapi the text I have underlined and display it in my frontend but it is not retrieving the  tag correctly and is displaying the  tag instead of the underlined text.
Is it because of my react-markdown?

here is my webview:
when I look at the element inspector I see inverted commas before my  tag which is why it doesn't work

and here is my code:

import React from "react";
import { graphql, PageProps } from "gatsby";
import ReactMarkdown from "react-markdown";

import { ArticleT } from "@faq/types";

import Layout from "@faq/components/Layout";

import * as s from "./Article.module.css";
import { toArticle, toCategory } from "@faq/utils/routes";

type ArticlePageProps = {
  strapiArticle: ArticleT;
  file: {
    publicURL: string;
  };
};

const Article: React.FC<PageProps<ArticlePageProps>> = ({
  data: { strapiArticle },
}) => {
  const { title, content, category, slug } = strapiArticle;

  return (
    <Layout
      seo={{ pageTitle: title, pageUrl: toArticle(category.slug, slug) }}
      breadcrumb={[
        { to: toCategory(category.slug), label: category.title },
        { label: title },
      ]}
    >

{title}

              Écrit par Nicolas

        <ReactMarkdown children={content}
          className={s.content}
          transformImageUri={uri => uri.startsWith("http") ? uri : `${process.env.GATSBY_IMAGE_BASE_URL}${uri}`} />

    </Layout>
  );
};

export default Article;

export const query = graphql`
  query ArticleQuery($id: Int!) {
    strapiArticle(strapiId: { eq: $id }) {
      title
      content
      slug
      category {
        title
        slug
      }
    }
  }
`;

Body:
Have you tried using your own rendering component (components)?

  <ReactMarkdown
    children={content}
    components={{
      u: ({node, ...props}) => <u style={{textDecoration: 'underline'}} {...props} />
    }}
   className={s.content}
   transformImageUri={uri => uri.startsWith("http") ? uri : `${process.env.GATSBY_IMAGE_BASE_URL}${uri}`}
  />

More details about components property: https://github.com/remarkjs/react-markdown#appendix-b-components

You can even use a custom-styled <p> instead of <u> if needed. The idea relies on parsing the <u> tag to add your own underlined component.

Apparently, it is needed to install rehype-raw plugin to allow ReactMarkdown to understand and interpret underlined tags (<u>)


问:
How to install ag-Grid enterprise properly?
i have tested some components with ag-Grid community edition but it has limited supportability, such as to add set filters using SetFilterModule, so the filter boxes would appear under the column header name, cannot be done with community version, therefore i have uninstalled the community version and installed the enterprise version using npm command

```<code>npm i ag-grid-enterprise
</code>```

after installing package.json shows dependencies and node_modules folder shows Enterprise modules.

But when i tried to import AgGridModule from the import statement in the app.module.ts  it did not show AgGridModule on the drop down. As shown on the image below, it had only three options LicenseManager, SetFilter, VirtualList. so, It had given me the impression that it required a license. But according to agGrid website i can use the full enterprise version of the grid without a license and the only barriers it will add are water marks and the console error message.

https://www.ag-grid.com/license-pricing.php

But in order to at least see those console messages i have to install it properly. So i believe that i have not installed the agGrid properly yet.

Therefore can anyone provide me on the steps on how to install the agGrid enterprise version and run it without a license key ( with watermark and console error messages )?

答:
After messing around with trying to get Enterprise installed correctly, I finally found that I could do this:

```<code>import {LicenseManager} from "ag-grid-enterprise";
LicenseManager.setLicenseKey("KEY HERE");
</code>```

(Without the @ and no /core)

And that solved my issues.

Body:
i have tested some components with ag-Grid community edition but it has limited supportability, such as to add set filters using SetFilterModule, so the filter boxes would appear under the column header name, cannot be done with community version, therefore i have uninstalled the community version and installed the enterprise version using npm command

npm i ag-grid-enterprise

after installing package.json shows dependencies and node_modules folder shows Enterprise modules.

But when i tried to import AgGridModule from the import statement in the app.module.ts  it did not show AgGridModule on the drop down. As shown on the image below, it had only three options LicenseManager, SetFilter, VirtualList. so, It had given me the impression that it required a license. But according to agGrid website i can use the full enterprise version of the grid without a license and the only barriers it will add are water marks and the console error message.

https://www.ag-grid.com/license-pricing.php

But in order to at least see those console messages i have to install it properly. So i believe that i have not installed the agGrid properly yet.

Therefore can anyone provide me on the steps on how to install the agGrid enterprise version and run it without a license key ( with watermark and console error messages )?

Body:
After messing around with trying to get Enterprise installed correctly, I finally found that I could do this:

import {LicenseManager} from "ag-grid-enterprise";
LicenseManager.setLicenseKey("KEY HERE");

(Without the @ and no /core)

And that solved my issues.


问:
PHP 8.0+ how to append strings to unknown SESSION variables in a clean concise way without Warnings
Previously code would look like this in PHP 7.4 :

```<code>$_SESSION['message'] .= "Sorry; That file or location can not be found.";
</code>```

Which would append to an existing string or set as contents for a new string. And my error logs (with notices turned off) would be beautifully empty.

With PHP 8.0+ now, undefined array elements (amongst other things) are classed as warnings rather than Notices.

PHP Warning:  Undefined array key "message" in /index.php on line 29

I understand the conceptual logic behind this Warning but in the instance of the above code it presents the need for a verbose workaround; something like:

```<code>if(array_key_exists('message', $_SESSION)){
    $_SESSION['message'] .= "Sorry; That file or location can not be found.";
}
else {
    $_SESSION['message'] = "Sorry; That file or location can not be found.";
}
</code>```

Or possibly;

```<code>$_SESSION['message'] = (array_key_exists('message', $_SESSION)?$_SESSION['message']:"")
                       ."Sorry; That file or location can not be found.";
</code>```

Which for thousands of SESSION elements across dozens of websites is really cruddy looking; harder to read and generally a big bloat to avoid Warning messages that seem to serve no purpose.

I don't want to turn warning messages off.

Are there any possible workarounds; such as any way in the php.ini to avoid this trigger for concatenation actions (.=) ? Can we somehow escape superglobals or more specifically SESSION data (and POST data perhaps) which it's impossible to know it's value before concatenation.

答:
A more concise workaround can be:

```<code>$_SESSION['message'] = ($_SESSION['message'] ?? ''). " string here";
</code>```

Which is probably as good as it gets.

Body:
Previously code would look like this in PHP 7.4 :

$_SESSION['message'] .= "Sorry; That file or location can not be found.";

Which would append to an existing string or set as contents for a new string. And my error logs (with notices turned off) would be beautifully empty.

With PHP 8.0+ now, undefined array elements (amongst other things) are classed as warnings rather than Notices.

PHP Warning:  Undefined array key "message" in /index.php on line 29

I understand the conceptual logic behind this Warning but in the instance of the above code it presents the need for a verbose workaround; something like:

if(array_key_exists('message', $_SESSION)){
    $_SESSION['message'] .= "Sorry; That file or location can not be found.";
}
else {
    $_SESSION['message'] = "Sorry; That file or location can not be found.";
}

Or possibly;

$_SESSION['message'] = (array_key_exists('message', $_SESSION)?$_SESSION['message']:"")
                       ."Sorry; That file or location can not be found.";

Which for thousands of SESSION elements across dozens of websites is really cruddy looking; harder to read and generally a big bloat to avoid Warning messages that seem to serve no purpose.

I don't want to turn warning messages off.

Are there any possible workarounds; such as any way in the php.ini to avoid this trigger for concatenation actions (.=) ? Can we somehow escape superglobals or more specifically SESSION data (and POST data perhaps) which it's impossible to know it's value before concatenation.

Body:
A more concise workaround can be:

$_SESSION['message'] = ($_SESSION['message'] ?? ''). " string here";

Which is probably as good as it gets.


问:
how to add any flutter widget inside customscroll view?
I want to show a custom message or Text widget when the list is empty inside a custom scroll view . I have sliverapp bar and sliver list in which i am showing the list so when it is empty i want to show it Text but it is giving me errors .</p>

答:
Probably the best for you will be sliver SliverFillRemaining.
Do some logic in the slivers of CustomScrollView, if the list is empty place the SliverFillRemaining, when the list is not empty place the SliverList.

Here you have some of the available slivers in Flutter: https://docs.flutter.dev/development/ui/widgets/layout#Sliver%20widgets


问:
poetry install fails on macOS 11.6/Xcode 13: dyld: Library not loaded: @executable_path/../Python3
New poetry install fails on macOS 11.6/Xcode 13, using official installer:

```<code>u@s-MacBook-Pro ~ % curl -sSL https://install.python-poetry.org | python3 -
Retrieving Poetry metadata

# Welcome to Poetry!

This will download and install the latest version of Poetry,
a dependency and package manager for Python.

It will add the `poetry` command to Poetry's bin directory, located at:

/Users/u/Library/Python/3.8/bin

You can uninstall at any time by executing this script with the --uninstall option,
and these changes will be reverted.

Installing Poetry (1.1.12): An error occurred. Removing partial environment.
Poetry installation failed.
See /Users/u/poetry-installer-error-h3v75uw9.log for error logs.
u@s-MacBook-Pro ~ % more /Users/u/poetry-installer-error-h3v75uw9.log
dyld: Library not loaded: @executable_path/../Python3
  Referenced from: /Users/u/Library/Application Support/pypoetry/venv/bin/python3
  Reason: image not found

Traceback:

  File "<stdin>", line 877, in main
  File "<stdin>", line 514, in run
u@s-MacBook-Pro ~ %
</code>```

There is no previous poetry install or reference to poetry in caches or Application Support:

```<code>u@s-MacBook-Pro ~ % ls -al Library/Application\ Support/pypoetry
total 0
drwxr-xr-x   2 u  staff    64 26 Jan 16:58 .
drwx------+ 55 u  staff  1760 26 Jan 16:43 ..
u@s-MacBook-Pro ~ % ls -al Library/Caches/pypoetry
ls: Library/Caches/pypoetry: No such file or directory
</code>```

Python version 3.8.9:

```<code>u@s-MacBook-Pro ~ % python3 --version
Python 3.8.9
u@s-MacBook-Pro ~ %
</code>```

Xcode version:

```<code>u@s-MacBook-Pro ~ % xcodebuild -version
Xcode 13.2.1
Build version 13C100
u@s-MacBook-Pro ~ %
</code>```

答:
I worked through this by installing a non-system version of python3, then installing poetry.

brew install pyenv

pyenv install 3.8.12

pyenv local 3.8.12

curl -sSL https://install.python-poetry.org | python3 -

Body:
New poetry install fails on macOS 11.6/Xcode 13, using official installer:

u@s-MacBook-Pro ~ % curl -sSL https://install.python-poetry.org | python3 -
Retrieving Poetry metadata

# Welcome to Poetry!

This will download and install the latest version of Poetry,
a dependency and package manager for Python.

It will add the `poetry` command to Poetry's bin directory, located at:

/Users/u/Library/Python/3.8/bin

You can uninstall at any time by executing this script with the --uninstall option,
and these changes will be reverted.

Installing Poetry (1.1.12): An error occurred. Removing partial environment.
Poetry installation failed.
See /Users/u/poetry-installer-error-h3v75uw9.log for error logs.
u@s-MacBook-Pro ~ % more /Users/u/poetry-installer-error-h3v75uw9.log
dyld: Library not loaded: @executable_path/../Python3
  Referenced from: /Users/u/Library/Application Support/pypoetry/venv/bin/python3
  Reason: image not found

Traceback:

  File "<stdin>", line 877, in main
  File "<stdin>", line 514, in run
u@s-MacBook-Pro ~ %

There is no previous poetry install or reference to poetry in caches or Application Support:

u@s-MacBook-Pro ~ % ls -al Library/Application\ Support/pypoetry
total 0
drwxr-xr-x   2 u  staff    64 26 Jan 16:58 .
drwx------+ 55 u  staff  1760 26 Jan 16:43 ..
u@s-MacBook-Pro ~ % ls -al Library/Caches/pypoetry
ls: Library/Caches/pypoetry: No such file or directory

Python version 3.8.9:

u@s-MacBook-Pro ~ % python3 --version
Python 3.8.9
u@s-MacBook-Pro ~ %

Xcode version:

u@s-MacBook-Pro ~ % xcodebuild -version
Xcode 13.2.1
Build version 13C100
u@s-MacBook-Pro ~ %


问:
Angular ng build throws error write EPIPE
I tried to build an angular app with ng build but I got this error:

```<code>throw er; // Unhandled 'error' event
      ^

Error: write EPIPE
    at afterWriteDispatched (node:internal/stream_base_commons:164:15)
    at writeGeneric (node:internal/stream_base_commons:155:3)
    at Socket._writeGeneric (node:net:795:11)
    at Socket._write (node:net:807:8)
    at writeOrBuffer (node:internal/streams/writable:389:12)
    at _write (node:internal/streams/writable:330:10)
    at Socket.Writable.write (node:internal/streams/writable:334:10)
    at Object.writeToStdin (/home/[user]/example/node_modules/esbuild-wasm/lib/main.js:1864:19)
    at sendRequest (/home/[user]/example/node_modules/esbuild-wasm/lib/main.js:637:14)
    at start (/home/[user]/example/node_modules/esbuild-wasm/lib/main.js:1274:9)
Emitted 'error' event on Socket instance at:
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)
    at runNextTicks (node:internal/process/task_queues:65:3)
    at processImmediate (node:internal/timers:437:9) {
  errno: -32,
  code: 'EPIPE',
  syscall: 'write'
}

</code>```

I have checked many questions like this but didn't solve my problem. this error is a little different from others.

Angular version:

```<code>Angular CLI: 13.2.2
Node: 16.13.2
Package Manager: npm
OS: linux x64

Angular: 13.1.1
... animations, common, compiler, compiler-cli, core, forms
... localize, platform-browser, platform-browser-dynamic, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1301.2
@angular-devkit/build-angular   13.1.2
@angular-devkit/core            13.1.2
@angular-devkit/schematics      13.2.2
@angular/cli                    13.2.2
@schematics/angular             13.2.2
rxjs                            7.4.0
typescript                      4.5.4
</code>```

I would be grateful for any help

答:
Downgrading Angular and Node versions did the trick.

```<code>Angular CLI 13.2.2 -> 12.2.16
Node 16.13.2 -> 14.19.0
</code>```

Body:
I tried to build an angular app with ng build but I got this error:

throw er; // Unhandled 'error' event
      ^

Error: write EPIPE
    at afterWriteDispatched (node:internal/stream_base_commons:164:15)
    at writeGeneric (node:internal/stream_base_commons:155:3)
    at Socket._writeGeneric (node:net:795:11)
    at Socket._write (node:net:807:8)
    at writeOrBuffer (node:internal/streams/writable:389:12)
    at _write (node:internal/streams/writable:330:10)
    at Socket.Writable.write (node:internal/streams/writable:334:10)
    at Object.writeToStdin (/home/[user]/example/node_modules/esbuild-wasm/lib/main.js:1864:19)
    at sendRequest (/home/[user]/example/node_modules/esbuild-wasm/lib/main.js:637:14)
    at start (/home/[user]/example/node_modules/esbuild-wasm/lib/main.js:1274:9)
Emitted 'error' event on Socket instance at:
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)
    at runNextTicks (node:internal/process/task_queues:65:3)
    at processImmediate (node:internal/timers:437:9) {
  errno: -32,
  code: 'EPIPE',
  syscall: 'write'
}

I have checked many questions like this but didn't solve my problem. this error is a little different from others.

Angular version:

Angular CLI: 13.2.2
Node: 16.13.2
Package Manager: npm
OS: linux x64

Angular: 13.1.1
... animations, common, compiler, compiler-cli, core, forms
... localize, platform-browser, platform-browser-dynamic, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1301.2
@angular-devkit/build-angular   13.1.2
@angular-devkit/core            13.1.2
@angular-devkit/schematics      13.2.2
@angular/cli                    13.2.2
@schematics/angular             13.2.2
rxjs                            7.4.0
typescript                      4.5.4

I would be grateful for any help

Body:
Downgrading Angular and Node versions did the trick.

Angular CLI 13.2.2 -> 12.2.16
Node 16.13.2 -> 14.19.0


问:
script/command to add extra space before stating of selected/each line in a paragraph
I need to update my cpp source files header by adding extra one space before starting of the below lines in header information -

```<code>This file is an example header file.
There are 100 files are present with this formats.
Some files are with proper space before starting of each line in this paragraph.
How to move each line in this paragraph with single space at start using any script.
All above lines are fixed throughout all files.
</code>```

Present Header format:

```<code>/*++++++++++++++++++++++++++++++ FileHeaderBegin +++++++++++++++++++++++++++++++

 ALL INFORMATION ARE BELONGS TO ABCDEF
 Copyright 2015 - 2020 ABCDEF LTD
 All Rights Reserved

This file is an example header file.
There are 100 files are present with this formats.
Some files are with proper space before starting of each line in this paragraph.
How to move each line in this paragraph with single space at start using any script.
All above lines are fixed throughout all files.

 *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 *
 * FILENAME: test.cpp
 *
 * DESCRIPTION: Sample file for command test
 *
 *++++++++++++++++++++++++++++++ FileHeaderEnd +++++++++++++++++++++++++++++++*/
</code>```

Expected:

```<code>/*++++++++++++++++++++++++++++++ FileHeaderBegin +++++++++++++++++++++++++++++++

 ALL INFORMATION ARE BELONGS TO ABCDEF
 Copyright 2015 - 2020 ABCDEF LTD
 All Rights Reserved

 This file is an example header file.
 There are 100 files are present with this formats.
 Some files are with proper space before starting of each line in this paragraph.
 How to move each line in this paragraph with single space at start using any script.
 All above lines are fixed throughout all files.

 *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 *
 * FILENAME: test.cpp
 *
 * DESCRIPTION: Sample file for command test
 *
 *++++++++++++++++++++++++++++++ FileHeaderEnd +++++++++++++++++++++++++++++++*/
</code>```

Query:
Is there any command or script available to do that changes.
I have total 270 files with few files with proper space added and majority files with no space added.

答:
If your file header always looks like that you can do the following with GNU awk:

```<code>awk '(FNR==1){h=0}(!h && !/^ /){$0=" " $0}/*\//{h++}1' file
</code>```

You can now put this in a loop to process your files.

This awk script searches for the string "*/" which appears for the first time right after the header. Only until this string is found, we check for lines that mis the space at the beginning.

For inplace modifications with awk: see Save modifications in place with awk

Body:
I need to update my cpp source files header by adding extra one space before starting of the below lines in header information -

This file is an example header file.
There are 100 files are present with this formats.
Some files are with proper space before starting of each line in this paragraph.
How to move each line in this paragraph with single space at start using any script.
All above lines are fixed throughout all files.

Present Header format:

/*++++++++++++++++++++++++++++++ FileHeaderBegin +++++++++++++++++++++++++++++++

 ALL INFORMATION ARE BELONGS TO ABCDEF
 Copyright 2015 - 2020 ABCDEF LTD
 All Rights Reserved

This file is an example header file.
There are 100 files are present with this formats.
Some files are with proper space before starting of each line in this paragraph.
How to move each line in this paragraph with single space at start using any script.
All above lines are fixed throughout all files.

 *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 *
 * FILENAME: test.cpp
 *
 * DESCRIPTION: Sample file for command test
 *
 *++++++++++++++++++++++++++++++ FileHeaderEnd +++++++++++++++++++++++++++++++*/

Expected:

/*++++++++++++++++++++++++++++++ FileHeaderBegin +++++++++++++++++++++++++++++++

 ALL INFORMATION ARE BELONGS TO ABCDEF
 Copyright 2015 - 2020 ABCDEF LTD
 All Rights Reserved

 This file is an example header file.
 There are 100 files are present with this formats.
 Some files are with proper space before starting of each line in this paragraph.
 How to move each line in this paragraph with single space at start using any script.
 All above lines are fixed throughout all files.

 *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 *
 * FILENAME: test.cpp
 *
 * DESCRIPTION: Sample file for command test
 *
 *++++++++++++++++++++++++++++++ FileHeaderEnd +++++++++++++++++++++++++++++++*/

Query:
Is there any command or script available to do that changes.
I have total 270 files with few files with proper space added and majority files with no space added.

Body:
If your file header always looks like that you can do the following with GNU awk:

awk '(FNR==1){h=0}(!h && !/^ /){$0=" " $0}/*\//{h++}1' file

You can now put this in a loop to process your files.

This awk script searches for the string "*/" which appears for the first time right after the header. Only until this string is found, we check for lines that mis the space at the beginning.

For inplace modifications with awk: see Save modifications in place with awk


问:
App crashes on simulator but works fine in device after upgrading to lion
My app is working fine on simulator all the while until i upgraded to OS Lion & xcode Version 4.1.

Now I got the error below.

EXC_BAD_ACCESS
warning: Unable to restore previously selected frame.

But It's working fine on iPhone.
Appreciate for any suggestion ...

答: Try going into the keyboard settings on the simulator and turn everything off.</p>


问:
pandas: replace values in column with the last character in the column name
I have a dataframe as follows:

```<code>import pandas as pd
df = pd.DataFrame({'sent.1':[0,1,0,1],
                'sent.2':[0,1,1,0],
                'sent.3':[0,0,0,1],
                'sent.4':[1,1,0,1]
               })
</code>```

I am trying to replace the non-zero values with the 5th character in the column names (which is the numeric part of the column names), so the output should be,

```<code>   sent.1  sent.2  sent.3  sent.4
0       0       0       0       4
1       1       2       0       4
2       0       2       0       0
3       1       0       3       4
</code>```

I have tried the following but it does not work,

```<code>print(df.replace(1, pd.Series([i[5] for i in df.columns], [i[5] for i in df.columns])))
</code>```

However when I replace it with column name, the above code works, so I am not sure which part is wrong.

```<code>print(df.replace(1, pd.Series(df.columns,  df.columns)))
</code>```

答:
Since you're dealing with 1's and 0's, you can actually just use multiply the dataframe by a range:

```<code>df = df * range(1, df.shape[1] + 1)
</code>```

Output:

```<code>   sent.1  sent.2  sent.3  sent.4
0       0       0       0       4
1       1       2       0       4
2       0       2       0       0
3       1       0       3       4
</code>```

Or, if you want to take the numbers from the column names:

```<code>df = df * df.columns.str.split('.').str[-1].astype(int)
</code>```

Body:
I have a dataframe as follows:

import pandas as pd
df = pd.DataFrame({'sent.1':[0,1,0,1],
                'sent.2':[0,1,1,0],
                'sent.3':[0,0,0,1],
                'sent.4':[1,1,0,1]
               })

I am trying to replace the non-zero values with the 5th character in the column names (which is the numeric part of the column names), so the output should be,

   sent.1  sent.2  sent.3  sent.4
0       0       0       0       4
1       1       2       0       4
2       0       2       0       0
3       1       0       3       4

I have tried the following but it does not work,

print(df.replace(1, pd.Series([i[5] for i in df.columns], [i[5] for i in df.columns])))

However when I replace it with column name, the above code works, so I am not sure which part is wrong.

print(df.replace(1, pd.Series(df.columns,  df.columns)))

Body:
Since you're dealing with 1's and 0's, you can actually just use multiply the dataframe by a range:

df = df * range(1, df.shape[1] + 1)

Output:

   sent.1  sent.2  sent.3  sent.4
0       0       0       0       4
1       1       2       0       4
2       0       2       0       0
3       1       0       3       4

Or, if you want to take the numbers from the column names:

df = df * df.columns.str.split('.').str[-1].astype(int)


问:
padStart is not a function
```<code>let m = 5;
m = m.padStart(2, '0');
</code>```

Error:

```<code>m.padStart is not a function
</code>```

Expecting result: 05;

I'm on Chrome, last version.

Any help?

答:
Since padStart() is not compatible with Internet Explorer (IE) and other old browser versions and if you try using it with numbers you can get:

```<code>let m = 5;
m = m.padStart(2, '0');
alert(m);
</code>```

Uncaught TypeError: m.padStart is not a function
at :2:7

Here I am to provide you a function that I created, it works fine with Strings as well as Numbers in case that somebody need something like that padding a Number to 01, 02, .. 09:

```<code>let m = 5;
m = padValue(m);
alert(m);

// Sam pading value to start with 0. eg: 01, 02, .. 09, 10, ..
function padValue(value) {
    return (value < 10) ? "0" + value : value;
}
</code>```

As I mentioned you can replace assigned 5 value to 05:

```<code>let m = '5'; // The result will be 05
</code>```

If you pass a value greater than 9 as String or Number will display the value without adding the padding. e.g.:

```<code>let m = '10'; // The result will be 10
</code>```

Or

```<code>let m = 10; // The result will be 10
</code>```

Title: padStart is not a function

Body:
let m = 5;
m = m.padStart(2, '0');

Error:

m.padStart is not a function

Expecting result: 05;

I'm on Chrome, last version.

Any help?

Body:
Since padStart() is not compatible with Internet Explorer (IE) and other old browser versions and if you try using it with numbers you can get:

let m = 5;
m = m.padStart(2, '0');
alert(m);

Uncaught TypeError: m.padStart is not a function
at :2:7

Here I am to provide you a function that I created, it works fine with Strings as well as Numbers in case that somebody need something like that padding a Number to 01, 02, .. 09:

let m = 5;
m = padValue(m);
alert(m);

// Sam pading value to start with 0. eg: 01, 02, .. 09, 10, ..
function padValue(value) {
    return (value < 10) ? "0" + value : value;
}

As I mentioned you can replace assigned 5 value to 05:

let m = '5'; // The result will be 05

If you pass a value greater than 9 as String or Number will display the value without adding the padding. e.g.:

let m = '10'; // The result will be 10

Or

let m = 10; // The result will be 10


问:
How to read comma-delimited data with some values using commas between quotes
I have a data file that includes comma-delimited data that I am trying to read into Octave. Most of the data is fine, but some includes numbers between double quotes that use commas between the quotes. Here's a sample section of data:

```<code>.123,4.2,"4,123",700,12pie
.34,4.23,602,701,23dj
.4345,4.6,"3,623,234",700,134nfg
.951,68.5,45,699,4lkj
</code>```

I've been using textscan to read the data (since there's a mix of number and strings), specifying comma delimiters, and that works most of the time, but occasionally the file contains these bigger integers in quotes scattered through that column. I was able to get around one of these quoted numbers earlier in the data file because I knew where it would be, but it wasn't pretty:

```<code>sclose = textscan(fid, '%n %n', 1, 'delimiter', ',');
junk = fgetl(fid, 1);
junk = textscan(fid, '%s', 1, 'delimiter', '"');
junk = fgetl(fid, 1);
sopen = textscan(fid, '%n %s', 1, 'delimiter', ',');
</code>```

I don't care about the data in that column, but because it changes size and sometimes contains the quoted with extra commas that I want to ignore, I'm struggling with how to read/skip it. Any suggestions on how to handle it?

Here's my current (ugly) approach that reads the column as a string, then uses strfind to check for a " within the string. If it's present then it reads another comma-delimited string and repeats the check until the closing " is found and then resumes reading the data.

```<code>fid = fopen('sample.txt', 'r');
for k=1:4
  expdata1(k, :) = textscan(fid, '%n %n %s', 1, 'delimiter', ',');  #read first 3 data pts
  qcheck = char(expdata1(k,3));
  idx = strfind(qcheck, '"');  #look for "
  dloc = ftell(fid);
  for l=1:4
    if isempty(idx) #if no " present, continue reading data
      break
    endif
    dloc = ftell(fid);  #save location so can return to next data point
    expdata1(k, 3) = textscan(fid, '%s', 1, 'delimiter', ',');  #if " present, read next comma segment and check for "
    qcheck = char(expdata1(k,3));
    idx = strfind(qcheck, '"');
  endfor
  fseek(fid, dloc);
  expdata2(k, :) = textscan(fid, '%n %s', 1, 'delimiter', ',');
endfor
fclose(fid);
</code>```

There's gotta be a better way...

答:
I see this has a matlab tag on it, are you using matlab textscan or octave?

If in matlab, I would suggest using either readmatrix or readtable.

Also note, the format specifier for quoted string is %q. This should be applicable to both languages even for textscan.

Putting your sample data in data.csv, the following is possible:

>> readtable("data.csv", 'Format','%f%f%q%d%s');
ans =

  4×5 table

     Var1     Var2        Var3         Var4       Var5
    ______    ____    _____________    ____    __________

     0.123     4.2    {'4,123'    }    700     {'12pie' }
      0.34    4.23    {'602'      }    701     {'23dj'  }
    0.4345     4.6    {'3,623,234'}    700     {'134nfg'}
     0.951    68.5    {'45'       }    699     {'4lkj'  }
```

Body:
I have a data file that includes comma-delimited data that I am trying to read into Octave. Most of the data is fine, but some includes numbers between double quotes that use commas between the quotes. Here's a sample section of data:

.123,4.2,"4,123",700,12pie
.34,4.23,602,701,23dj
.4345,4.6,"3,623,234",700,134nfg
.951,68.5,45,699,4lkj

I've been using textscan to read the data (since there's a mix of number and strings), specifying comma delimiters, and that works most of the time, but occasionally the file contains these bigger integers in quotes scattered through that column. I was able to get around one of these quoted numbers earlier in the data file because I knew where it would be, but it wasn't pretty:

sclose = textscan(fid, '%n %n', 1, 'delimiter', ',');
junk = fgetl(fid, 1);
junk = textscan(fid, '%s', 1, 'delimiter', '"');
junk = fgetl(fid, 1);
sopen = textscan(fid, '%n %s', 1, 'delimiter', ',');

I don't care about the data in that column, but because it changes size and sometimes contains the quoted with extra commas that I want to ignore, I'm struggling with how to read/skip it. Any suggestions on how to handle it?

Here's my current (ugly) approach that reads the column as a string, then uses strfind to check for a " within the string. If it's present then it reads another comma-delimited string and repeats the check until the closing " is found and then resumes reading the data.

fid = fopen('sample.txt', 'r');
for k=1:4
  expdata1(k, :) = textscan(fid, '%n %n %s', 1, 'delimiter', ',');  #read first 3 data pts
  qcheck = char(expdata1(k,3));
  idx = strfind(qcheck, '"');  #look for "
  dloc = ftell(fid);
  for l=1:4
    if isempty(idx) #if no " present, continue reading data
      break
    endif
    dloc = ftell(fid);  #save location so can return to next data point
    expdata1(k, 3) = textscan(fid, '%s', 1, 'delimiter', ',');  #if " present, read next comma segment and check for "
    qcheck = char(expdata1(k,3));
    idx = strfind(qcheck, '"');
  endfor
  fseek(fid, dloc);
  expdata2(k, :) = textscan(fid, '%n %s', 1, 'delimiter', ',');
endfor
fclose(fid);

There's gotta be a better way...


答:
you could use string multiplication on a boolean array to place the strings based on the condition, and where to restore the zeros:

mask = df.ne(0)
(mask*df.columns.str[5]).where(mask, 0)
```
<p>To have integers:</p>
<pre class="lang-py prettyprint-override"><code>mask = df.ne(0)
(mask*df.columns.str[5].astype(int))
</code>```

output:

```<code>  sent.1 sent.2 sent.3 sent.4
0      0      0      0      4
1      1      2      0      4
2      0      2      0      0
3      1      0      3      4
</code>```

Title: pandas: replace values in column with the last character in the column name

Body:
you could use string multiplication on a boolean array to place the strings based on the condition, and where to restore the zeros:

mask = df.ne(0)
(mask*df.columns.str[5]).where(mask, 0)

To have integers:

mask = df.ne(0)
(mask*df.columns.str[5].astype(int))

output:

  sent.1 sent.2 sent.3 sent.4
0      0      0      0      4
1      1      2      0      4
2      0      2      0      0
3      1      0      3      4


问:
Android 12 APK throws invalid package upon install
I have an Azure build pipeline which is producing an APK which installs (via AppCenter) just fine on Android 10 but pops up the error:

App not installed as package appears to be invalid

on Android 12.

The AndroidManifest.xml in the solution looks like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app.myapplocal" android:installLocation="auto" android:versionCode="1" android:versionName="1.1">
    <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="31" />
    <uses-permission android:name="android.permission.FLASHLIGHT" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <application android:label="L MyApp" android:icon="@drawable/icon" android:largeHeap="true"></application>
</manifest>
</code>```

When I examine the manifest via Android Studio's APK Analyze option, I see this:

```<code><uses-sdk
    android:minSdkVersion="21"
    android:targetSdkVersion="31" />

<uses-permission
    android:name="android.permission.FLASHLIGHT" />

<uses-permission
    android:name="android.permission.INTERNET" />

<uses-permission
    android:name="android.permission.CAMERA" />

<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
    android:label="D MyApp"
    android:icon="@ref/0x7f07015e"
    android:name="crc646948444ac10504e5.MainApplication"
    android:debuggable="true"
    android:allowBackup="true"
    android:largeHeap="true"
    android:extractNativeLibs="true">

    <meta-data
        android:name="com.google.android.gms.vision.DEPENDENCIES"
        android:value="barcode" />

    <activity
        android:theme="@ref/0x7f0d0001"
        android:label="MyApp"
        android:icon="@ref/0x7f07015e"
        android:name="crc646948444ac10504e5.MainActivity"
        android:screenOrientation="1"
        android:configChanges="0x680" />

    <activity
        android:theme="@ref/0x7f0d0000"
        android:name="crc646948444ac10504e5.SplashActivity"
        android:exported="true"
        android:screenOrientation="1"
        android:noHistory="true">

        <intent-filter>

            <action
                android:name="android.intent.action.MAIN" />

            <category
                android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:label="Web Authenticator"
        android:name="crc641e66d166111bdf3e.FormAuthenticatorActivity" />

    <activity
        android:label="Web Authenticator"
        android:name="crc641e66d166111bdf3e.WebAuthenticatorActivity" />

    <activity
        android:label="Web Authenticator Native Browser"
        android:name="crc641e66d166111bdf3e.WebAuthenticatorNativeBrowserActivity"
        android:launchMode="1" />

    <activity
        android:name="com.microsoft.windowsazure.mobileservices.authentication.RedirectUrlActivity" />

    <service
        android:name="crc64a98abb514ffad9f1.KeepAliveService" />

    <receiver
        android:label="Essentials Connectivity Broadcast Receiver"
        android:name="crc64a0e0a82d0db9a07d.ConnectivityBroadcastReceiver"
        android:enabled="true"
        android:exported="false" />

    <receiver
        android:name="crc643f46942d9dd1fff9.PowerSaveModeBroadcastReceiver"
        android:enabled="true"
        android:exported="false" />

    <provider
        android:name="mono.android.MultiDexLoader"
        android:exported="false"
        android:authorities="com.app.myapp.mono.android.MultiDexLoader.__mono_init__"
        android:initOrder="1999999999" />

    <provider
        android:name="mono.MonoRuntimeProvider"
        android:exported="false"
        android:authorities="com.app.myapp.mono.MonoRuntimeProvider.__mono_init__"
        android:initOrder="1999999998" />

    <activity
        android:theme="@ref/0x01030010"
        android:name="com.google.android.gms.common.api.GoogleApiActivity"
        android:exported="false" />

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@ref/0x7f090008" />
</application>

<uses-permission
    android:name="android.permission.ACCESS_NETWORK_STATE" />
</code>```

I had previously thought that the problem with Android 12 was that the android:targetSdkVersion was set to 29 but changing this in the solution's manifest and changing the project file's TargetFrameworkVersion from v11.0 to v12.0 did not help either. (This was updated in Visual Studio using the project properties' Application > Compile using Android version value.)

What might I be missing in order to allow installing on recent Android devices? (I am not familiar with Xamarin or Android, I'm afraid.)

答:
It may be that it doesn't like the install location "auto", resulting in:

```<code>android:installLocation="0"
</code>```

Which should be one of:

```<code>android:installLocation=["auto" | "internalOnly" | "preferExternal"]
</code>```

Body:
I have an Azure build pipeline which is producing an APK which installs (via AppCenter) just fine on Android 10 but pops up the error:

App not installed as package appears to be invalid

on Android 12.

The AndroidManifest.xml in the solution looks like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app.myapplocal" android:installLocation="auto" android:versionCode="1" android:versionName="1.1">
    <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="31" />
    <uses-permission android:name="android.permission.FLASHLIGHT" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <application android:label="L MyApp" android:icon="@drawable/icon" android:largeHeap="true"></application>
</manifest>

When I examine the manifest via Android Studio's APK Analyze option, I see this:

<uses-sdk
    android:minSdkVersion="21"
    android:targetSdkVersion="31" />

<uses-permission
    android:name="android.permission.FLASHLIGHT" />

<uses-permission
    android:name="android.permission.INTERNET" />

<uses-permission
    android:name="android.permission.CAMERA" />

<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
    android:label="D MyApp"
    android:icon="@ref/0x7f07015e"
    android:name="crc646948444ac10504e5.MainApplication"
    android:debuggable="true"
    android:allowBackup="true"
    android:largeHeap="true"
    android:extractNativeLibs="true">

    <meta-data
        android:name="com.google.android.gms.vision.DEPENDENCIES"
        android:value="barcode" />

    <activity
        android:theme="@ref/0x7f0d0001"
        android:label="MyApp"
        android:icon="@ref/0x7f07015e"
        android:name="crc646948444ac10504e5.MainActivity"
        android:screenOrientation="1"
        android:configChanges="0x680" />

    <activity
        android:theme="@ref/0x7f0d0000"
        android:name="crc646948444ac10504e5.SplashActivity"
        android:exported="true"
        android:screenOrientation="1"
        android:noHistory="true">

        <intent-filter>

            <action
                android:name="android.intent.action.MAIN" />

            <category
                android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:label="Web Authenticator"
        android:name="crc641e66d166111bdf3e.FormAuthenticatorActivity" />

    <activity
        android:label="Web Authenticator"
        android:name="crc641e66d166111bdf3e.WebAuthenticatorActivity" />

    <activity
        android:label="Web Authenticator Native Browser"
        android:name="crc641e66d166111bdf3e.WebAuthenticatorNativeBrowserActivity"
        android:launchMode="1" />

    <activity
        android:name="com.microsoft.windowsazure.mobileservices.authentication.RedirectUrlActivity" />

    <service
        android:name="crc64a98abb514ffad9f1.KeepAliveService" />

    <receiver
        android:label="Essentials Connectivity Broadcast Receiver"
        android:name="crc64a0e0a82d0db9a07d.ConnectivityBroadcastReceiver"
        android:enabled="true"
        android:exported="false" />

    <receiver
        android:name="crc643f46942d9dd1fff9.PowerSaveModeBroadcastReceiver"
        android:enabled="true"
        android:exported="false" />

    <provider
        android:name="mono.android.MultiDexLoader"
        android:exported="false"
        android:authorities="com.app.myapp.mono.android.MultiDexLoader.__mono_init__"
        android:initOrder="1999999999" />

    <provider
        android:name="mono.MonoRuntimeProvider"
        android:exported="false"
        android:authorities="com.app.myapp.mono.MonoRuntimeProvider.__mono_init__"
        android:initOrder="1999999998" />

    <activity
        android:theme="@ref/0x01030010"
        android:name="com.google.android.gms.common.api.GoogleApiActivity"
        android:exported="false" />

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@ref/0x7f090008" />
</application>

<uses-permission
    android:name="android.permission.ACCESS_NETWORK_STATE" />

I had previously thought that the problem with Android 12 was that the android:targetSdkVersion was set to 29 but changing this in the solution's manifest and changing the project file's TargetFrameworkVersion from v11.0 to v12.0 did not help either. (This was updated in Visual Studio using the project properties' Application > Compile using Android version value.)

What might I be missing in order to allow installing on recent Android devices? (I am not familiar with Xamarin or Android, I'm afraid.)

Body:
It may be that it doesn't like the install location "auto", resulting in:

android:installLocation="0"

Which should be one of:

android:installLocation=["auto" | "internalOnly" | "preferExternal"]


问:
Pandas aggregate order for monthly/weekly changes
I am retrieving data from a SQL database using django, and then convert it to a pandas dataframe.
The goal is to calculate some metrics for each person well as metrics overall across all persons.

After calculating my metrics, I want to compare the values to the previous month and calculate the changes as percentage.

This works roughly like this:

member_frame = member_frame.truncate(before=(previous_start - timedelta(days=1)))
```
<p>which gives me all entries from the last month up to including the end of this month.</p>
<p>I then calculate the sum of some values:</p>
<pre class="lang-py prettyprint-override"><code>aggregate_avgs = member_frame.groupby(member_frame.index.month).mean().replace(np.inf, 1).fillna(0)
</code>```

And finally calculate the percentage changes:

avgs_change = aggregate_avgs.pct_change().replace(np.inf, 1).fillna(-1)
```
<p>Which, if we look at the changes from january to february, like that:</p>
```target_date
1           -1.000000 -1.000000 -1.000000           -1.0 -1.000000 -1.000000  -1.000000
2            0.142857  0.076923 -0.828571            0.0 -0.587774 -0.699994  -0.507199
```
<p>This works... fine? Since I am only interested in the changes from the first to the second date, I simply take the values from the second row.</p>
<p>But if I do the same for december and january, I get this:</p>
```target_date
1           -1.00000 -1.000000 -1.000000           -1.0 -1.000000 -1.000000  -1.000000
12           0.02682  0.273444  0.449811            0.0  0.259059  0.424178   0.223225
```

As you can see, this is somewhat reversed, and the changes are actually for the wrong month.
The target_date index is a datetime index.

I suspect that the same will happen if I do that with weekly changes, when crossing years.

What am I doing wrong?
I am quite new to pandas, so it might as well be a very easy mistake.

答:
IIUC, you might want to use resample instead, which is akin to grouping by month and year:

```<code>aggregate_avgs = member_frame.resample('m').mean().replace(np.inf, 1).fillna(0)
</code>```

Body:
I am retrieving data from a SQL database using django, and then convert it to a pandas dataframe.
The goal is to calculate some metrics for each person well as metrics overall across all persons.

After calculating my metrics, I want to compare the values to the previous month and calculate the changes as percentage.

This works roughly like this:

member_frame = member_frame.truncate(before=(previous_start - timedelta(days=1)))

which gives me all entries from the last month up to including the end of this month.

I then calculate the sum of some values:

aggregate_avgs = member_frame.groupby(member_frame.index.month).mean().replace(np.inf, 1).fillna(0)

And finally calculate the percentage changes:

avgs_change = aggregate_avgs.pct_change().replace(np.inf, 1).fillna(-1)

Which, if we look at the changes from january to february, like that:

target_date
1           -1.000000 -1.000000 -1.000000           -1.0 -1.000000 -1.000000  -1.000000
2            0.142857  0.076923 -0.828571            0.0 -0.587774 -0.699994  -0.507199

This works... fine? Since I am only interested in the changes from the first to the second date, I simply take the values from the second row.

But if I do the same for december and january, I get this:

target_date
1           -1.00000 -1.000000 -1.000000           -1.0 -1.000000 -1.000000  -1.000000
12           0.02682  0.273444  0.449811            0.0  0.259059  0.424178   0.223225

As you can see, this is somewhat reversed, and the changes are actually for the wrong month.
The target_date index is a datetime index.

I suspect that the same will happen if I do that with weekly changes, when crossing years.

What am I doing wrong?
I am quite new to pandas, so it might as well be a very easy mistake.

Body:
IIUC, you might want to use resample instead, which is akin to grouping by month and year:

aggregate_avgs = member_frame.resample('m').mean().replace(np.inf, 1).fillna(0)


问:
Sort number array using lodash/Javascript
I have a string array as below.

```<code>let arr = ["1", "1+", "1-","2", "2+", "3","3+", "2-", "3-", "4", "10"];
</code>```

I want the expected output as below.

```<code>["1+", "1", "1-", "2+", "2", "2-", "3+", "3", "3-", "4", "10"];
</code>```

I tried the below code but it is not giving me the correct result.

let arr = ["1", "1+", "1-","2", "2+", "3","3+", "2-", "3-", "4", "10"];
let result = arr.sort((a,b) => {
  return a.localeCompare(b, undefined, {
      numeric: true,
      sensitivity: 'base',
    });
  });

console.log(result);```

答:
Split each string using a regex word boundary. Use destructuring to get the number in string form (an, bn), and the sign (as, bs). If the sign is undefined use a comma as a fallback, since comma falls between + and - in the ascii table.

The return value should be an - bn (difference  of auto-casted numbers), and if that is 0 then use bs?.localeCompare(as) to sort by the sign.

const arr = ["1", "1+", "1-","2", "2+", "3","3+", "2-", "3-", "4", "10"];

const getNumAndSign = str => str.split(/\b/)

const sorted = arr.sort((a, b) => {
  const [an, as = ','] = getNumAndSign(a)
  const [bn, bs = ','] = getNumAndSign(b)

  return +an - +bn || bs?.localeCompare(as)
})

console.log(sorted);```

Body:
I have a string array as below.

let arr = ["1", "1+", "1-","2", "2+", "3","3+", "2-", "3-", "4", "10"];

I want the expected output as below.

["1+", "1", "1-", "2+", "2", "2-", "3+", "3", "3-", "4", "10"];

I tried the below code but it is not giving me the correct result.

let arr = ["1", "1+", "1-","2", "2+", "3","3+", "2-", "3-", "4", "10"];
let result = arr.sort((a,b) => {
  return a.localeCompare(b, undefined, {
      numeric: true,
      sensitivity: 'base',
    });
  });

console.log(result);