问:
Why am I getting a "=" symbol at the pdf table of contents
If you notice, I get a the equal symbol before every reference the document have in the pdf.
Unable to find if this is of some optional setting which I should do!

And the below is my preamble and some part of the document.

```<code>% In the preamble:
% arara: lualatex: { synctex: on }
% arara: biber
% arara: makeglossaries
% arara: makeindex
% arara: lualatex: { synctex: on }
% arara: lualatex: { synctex: on }

% !TeX root = MasterThesis.tex
% !TeX encoding = utf8
% !TeX spellcheck = en_US
\documentclass[12pt, a4paper, oneside, openany]{scrbook}
%\pagestyle{headings}

\usepackage{fontspec}
\fontspec{Times New Roman}
\usepackage{url}
\usepackage[colorlinks=true,linkcolor=black]{hyperref}
\linespread{1.5}
\usepackage[toc, acronym]{glossaries}
\makeglossaries
\usepackage{graphicx}
\graphicspath{{images/}}
\usepackage[a4paper]{geometry}
\title{Seamless Firmware Update Over the Air}
\author{Vijay Bhargava B}
\date{February 2023}
\pdfstringdefDisableCommands{%
    \def\\{}%
    \def\texttt#1{<#1>}%
}
\setcounter{tocdepth}{3}
\renewcommand{\contentsname}{Table of Contents}
\usepackage{titletoc}
\newcommand{\setupname}[1][\chaptername]{
    \titlecontents{chapter}[0pt]{\vspace{1ex}}{\bfseries#1~\thecontentslabel:\quad}{\bfseries}{\bfseries\hfill\contentspage}[]
}

\begin{document}
\maketitle
%\pagenumbering{roman} %start roman page number
%\setcounter{page}{1}
\include{00_1_Declaration_honest}
\setlength{\parindent}{0pt}
\include{00_1_Abstract}
\setupname
\tableofcontents
%\pagenumbering{arabic}
%\setcounter{page}{1}
</code>```

The above part is the preamble and some part of the document.

Body:
If you notice, I get a the equal symbol before every reference the document have in the pdf.
Unable to find if this is of some optional setting which I should do!

And the below is my preamble and some part of the document.

% In the preamble:
% arara: lualatex: { synctex: on }
% arara: biber
% arara: makeglossaries
% arara: makeindex
% arara: lualatex: { synctex: on }
% arara: lualatex: { synctex: on }

% !TeX root = MasterThesis.tex
% !TeX encoding = utf8
% !TeX spellcheck = en_US
\documentclass[12pt, a4paper, oneside, openany]{scrbook}
%\pagestyle{headings}

\usepackage{fontspec}
\fontspec{Times New Roman}
\usepackage{url}
\usepackage[colorlinks=true,linkcolor=black]{hyperref}
\linespread{1.5}
\usepackage[toc, acronym]{glossaries}
\makeglossaries
\usepackage{graphicx}
\graphicspath{{images/}}
\usepackage[a4paper]{geometry}
\title{Seamless Firmware Update Over the Air}
\author{Vijay Bhargava B}
\date{February 2023}
\pdfstringdefDisableCommands{%
    \def\\{}%
    \def\texttt#1{<#1>}%
}
\setcounter{tocdepth}{3}
\renewcommand{\contentsname}{Table of Contents}
\usepackage{titletoc}
\newcommand{\setupname}[1][\chaptername]{
    \titlecontents{chapter}[0pt]{\vspace{1ex}}{\bfseries#1~\thecontentslabel:\quad}{\bfseries}{\bfseries\hfill\contentspage}[]
}

\begin{document}
\maketitle
%\pagenumbering{roman} %start roman page number
%\setcounter{page}{1}
\include{00_1_Declaration_honest}
\setlength{\parindent}{0pt}
\include{00_1_Abstract}
\setupname
\tableofcontents
%\pagenumbering{arabic}
%\setcounter{page}{1}

The above part is the preamble and some part of the document.


来源: stackexchange

问:
How can I pickle multiple objects in the same file, and load them by index in the file?
I want to run my program X times to generate a file that contains X pickled matrices. I then want to run my program Y times using a command line argument to print the pickled matrices depending on its position in the file.

Here is my attempt:

```<code>
if sys.argv[1] == '-continue':
    with open('testing123.txt', 'rb') as pickledFile:
        pickledFile.seek(1)                # index of matrix in file is changes by need
        inputMatrix = pickle.load(pickledFile)
    print(inputMatrix)

else:
    weights = np.random.rand(9+1, 8)
    for i in range(7):
        weights[9][i] = random.uniform(.5,1.5)
    print(weights)

    with open("testing123.txt", "ab") as pickledFile:
        pickle.dump(weights, pickledFile)

</code>```

I was expecting:

Adding 3 matrices to the file:

```<code>command line: >> python3 testing123.py
output: >> [<matrix1>]
command line: >> python3 testing123.py
output: >> [<matrix2>]
command line: >> python3 testing123.py
output: >> [<matrix3>]
</code>```

Printing those 3 matrices by seeking their appropriate positions in the file:

```<code>command line: >> python3 testing123.py -continue
output: >> [<matrix1>]
command line: >> python3 testing123.py -continue
output: >> [<matrix2>]
command line: >> python3 testing123.py -continue
output: >> [<matrix3>]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to run my program X times to generate a file that contains X pickled matrices. I then want to run my program Y times using a command line argument to print the pickled matrices depending on its position in the file.

Here is my attempt:

if sys.argv[1] == '-continue':
    with open('testing123.txt', 'rb') as pickledFile:
        pickledFile.seek(1)                # index of matrix in file is changes by need
        inputMatrix = pickle.load(pickledFile)
    print(inputMatrix)

else:
    weights = np.random.rand(9+1, 8)
    for i in range(7):
        weights[9][i] = random.uniform(.5,1.5)
    print(weights)

    with open("testing123.txt", "ab") as pickledFile:
        pickle.dump(weights, pickledFile)

I was expecting:

Adding 3 matrices to the file:

command line: >> python3 testing123.py
output: >> [<matrix1>]
command line: >> python3 testing123.py
output: >> [<matrix2>]
command line: >> python3 testing123.py
output: >> [<matrix3>]

Printing those 3 matrices by seeking their appropriate positions in the file:

command line: >> python3 testing123.py -continue
output: >> [<matrix1>]
command line: >> python3 testing123.py -continue
output: >> [<matrix2>]
command line: >> python3 testing123.py -continue
output: >> [<matrix3>]


问:
JPA CriteriaBuilder build with different table name
I have following code

```<code>CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<AppUsage> criteriaQuery = criteriaBuilder.createQuery(User.class);
Root<AppUsage> itemRoot = criteriaQuery.from(User.class);
</code>```

User entity class has tablename = "user"
Is it possible to change above code so that user can be loaded from different table such as below

```<code>String tableName = "generated by logic"
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<AppUsage> criteriaQuery = criteriaBuilder.createQuery(User.class, tableName);
Root<AppUsage> itemRoot = criteriaQuery.from(User.class,tableName);
</code>```

I am trying to build the same query so that it can be used to query from different table but with data in different time range.

Body:
I have following code

CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<AppUsage> criteriaQuery = criteriaBuilder.createQuery(User.class);
Root<AppUsage> itemRoot = criteriaQuery.from(User.class);

User entity class has tablename = "user"
Is it possible to change above code so that user can be loaded from different table such as below

String tableName = "generated by logic"
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<AppUsage> criteriaQuery = criteriaBuilder.createQuery(User.class, tableName);
Root<AppUsage> itemRoot = criteriaQuery.from(User.class,tableName);

I am trying to build the same query so that it can be used to query from different table but with data in different time range.


问:
How can I change the lines of the subgroups in R?
I'm trying to draw three lines per group using ggplot in R.
I'd like to change the second and third lines per group to dashed lines.
So, "Blacks" and "Whites" per gene will be dashed lines, only "All" group per gene  will have a solid line.
However, I have no idea on how to do this.

Please help me with this.

Here are the example codes. Please never mind the dots outside of the lines.
It was supposed to be beta and 95% CI. I just created dummy numbers for this issue.

```<code>beta <- runif(9)
lower <- runif(9)
upper <- runif(9)
gene <- rep(c(letters[1:3]), times=3)

sample.data <- data.frame(cbind(beta, lower, upper, gene))
sample.data$group<-rep(c("all", "blacks", "whites"), each=3)

cols <- colnames(sample.data)[1:3]
sample.data[cols] <- sapply(sample.data[cols], as.numeric)

p <- sample.data %>% mutate (group = as.factor(group)) %>%
  ggplot(aes(x=gene, y=beta, colour=group)) +
  geom_point(aes(x=gene, y=beta), size=2.2, position = position_dodge(width = 0.5)) +
  geom_errorbar(aes(x=gene, ymin=lower, ymax=upper), size=0.7, width=0.4, position = position_dodge(width = 0.5))+
  theme_bw() +
  theme(axis.text.x = element_text(size=10, angle = 45, vjust = 0.9, hjust=0.95)) +
  theme(axis.text.y = element_text(size=11)) +
  guides(color=guide_legend("Group")) + scale_color_hue(labels = c("ALL", "Blacks", "Whites"))
</code>```

Body:
I'm trying to draw three lines per group using ggplot in R.
I'd like to change the second and third lines per group to dashed lines.
So, "Blacks" and "Whites" per gene will be dashed lines, only "All" group per gene  will have a solid line.
However, I have no idea on how to do this.

Please help me with this.

Here are the example codes. Please never mind the dots outside of the lines.
It was supposed to be beta and 95% CI. I just created dummy numbers for this issue.

beta <- runif(9)
lower <- runif(9)
upper <- runif(9)
gene <- rep(c(letters[1:3]), times=3)

sample.data <- data.frame(cbind(beta, lower, upper, gene))
sample.data$group<-rep(c("all", "blacks", "whites"), each=3)

cols <- colnames(sample.data)[1:3]
sample.data[cols] <- sapply(sample.data[cols], as.numeric)

p <- sample.data %>% mutate (group = as.factor(group)) %>%
  ggplot(aes(x=gene, y=beta, colour=group)) +
  geom_point(aes(x=gene, y=beta), size=2.2, position = position_dodge(width = 0.5)) +
  geom_errorbar(aes(x=gene, ymin=lower, ymax=upper), size=0.7, width=0.4, position = position_dodge(width = 0.5))+
  theme_bw() +
  theme(axis.text.x = element_text(size=10, angle = 45, vjust = 0.9, hjust=0.95)) +
  theme(axis.text.y = element_text(size=11)) +
  guides(color=guide_legend("Group")) + scale_color_hue(labels = c("ALL", "Blacks", "Whites"))


问:
Text formula type not showing in OTBI subject area
I have a formula field that is not showing in OTBI subject area. Not sure if I could get any input on this.</p>


问:
Poetry/Meson: How to use meson as a build backend with Cython files to install a Python/Cython package
I have a Python package that contains Cython code, similar to scikit-learn. I am trying to use poetry to do package management, but meson to handle the build process for Cython and possible c++ code. Before, when I was using the deprecated setuptools and distutils, I was able to do the following in scikit-learn:

```<code>pip install -e .
</code>```

which built the Cython files and allowed them to be importable by sklearn's Python files. For example from _criterion import Criterion works, where _criterion.pxd/pyx is a Cython file that contains some variable named Criterion.

Now I am using poetry and meson and things do not work.

My Goals to Use Poetry and Meson

I would ideally like to be able to just do poetry install (or poetry build and poetry install), which should build and install things by using Meson to build local Cython/C++ files and then use poetry to handle other pip installable Python packages.

My Question

How do I correctly use poetry with meson to build my Cython files and install them along with other relevant Python dependencies to install my package?

My Attempt using just Meson incorrectly Cython files to the wrong environment

I instantiated my meson.build files such that running meson build in my repo's root directory works:

```<code>The Meson build system
Version: 0.63.2
Source dir: /Users/adam2392/Documents/scikit-tree
Build dir: /Users/adam2392/Documents/scikit-tree/build
Build type: native build
Project name: scikit-tree
Project version: 0.0.0.dev0
C compiler for the host machine: arm64-apple-darwin20.0.0-clang (clang 14.0.6 "clang version 14.0.6")
C linker for the host machine: arm64-apple-darwin20.0.0-clang ld64 609
C++ compiler for the host machine: arm64-apple-darwin20.0.0-clang++ (clang 14.0.6 "clang version 14.0.6")
C++ linker for the host machine: arm64-apple-darwin20.0.0-clang++ ld64 609
Host machine cpu family: aarch64
Host machine cpu: arm64
Library m found: YES
Program cython found: YES (/Users/adam2392/miniforge3/envs/sktree/bin/cython)
Program python3 found: YES (/Users/adam2392/miniforge3/envs/sktree/bin/python3)
Message: /Users/adam2392/miniforge3/envs/sktree/bin/python3
Message: /opt/homebrew/lib/python3.9/site-packages/
Found pkg-config: /opt/homebrew/bin/pkg-config (0.29.2)
Program _build_utils/cythoner.py found: YES (python /Users/adam2392/Documents/scikit-tree/sktree/_build_utils/cythoner.py)
Build targets in project: 1

scikit-tree 0.0.0.dev0

  User defined options
    backend: ninja

Found ninja-1.11.1 at /opt/homebrew/bin/ninja
</code>```

When I then run meson install within the build/ directory:

```<code>(sktree) adam2392@Adams-MacBook-Pro build % meson install
ninja: Entering directory `/Users/adam2392/Documents/scikit-tree/build'
[3/3] Linking target sktree/tree/_unsup_criterion.cpython-39-darwin.so
ld: warning: -pie being ignored. It is only used when linking a main executable
Installing sktree/tree/_unsup_criterion.cpython-39-darwin.so to /opt/homebrew/lib/python3.9/site-packages/sktree/tree
Installing /Users/adam2392/Documents/scikit-tree/sktree/__init__.py to /opt/homebrew/lib/python3.9/site-packages/sktree
Installing /Users/adam2392/Documents/scikit-tree/sktree/_forest.py to /opt/homebrew/lib/python3.9/site-packages/sktree
Installing /Users/adam2392/Documents/scikit-tree/sktree/tree/__init__.py to /opt/homebrew/lib/python3.9/site-packages/sktree/tree
Installing /Users/adam2392/Documents/scikit-tree/sktree/tree/_classes.py to /opt/homebrew/lib/python3.9/site-packages/sktree/tree
</code>```

which installs for example the Cython files into the incorrect Python environment (i.e. home-brew). I need it to be installed in my virtual environment.

My Attempt using Poetry doesn't work either

My pyproject.toml file has the following lines:

```<code>[build-system]
build-backend = "mesonpy"
requires = [
    "meson-python>=0.11.0",
    # `wheel` is needed for non-isolated builds, given that `meson-python`
    # doesn't list it as a runtime requirement (at least in 0.10.0)
    # See https://github.com/FFY00/meson-python/blob/main/pyproject.toml#L4
    "wheel",
    "setuptools<=65.5",
    "packaging",
    "Cython>=0.29.24",
    "scikit-learn",
]
</code>```

However, when I run poetry install, there are no errors, but:

```<code>python -c "from sktree import tree"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/adam2392/Documents/scikit-tree/sktree/__init__.py", line 37, in <module>
    from . import tree
  File "/Users/adam2392/Documents/scikit-tree/sktree/tree/__init__.py", line 1, in <module>
    from ._classes import UnsupervisedDecisionTree
  File "/Users/adam2392/Documents/scikit-tree/sktree/tree/_classes.py", line 3, in <module>
    from ._unsup_criterion import UnsupervisedCriterion
ModuleNotFoundError: No module named 'sktree.tree._unsup_criterion'
</code>```

Body:
I have a Python package that contains Cython code, similar to scikit-learn. I am trying to use poetry to do package management, but meson to handle the build process for Cython and possible c++ code. Before, when I was using the deprecated setuptools and distutils, I was able to do the following in scikit-learn:

pip install -e .

which built the Cython files and allowed them to be importable by sklearn's Python files. For example from _criterion import Criterion works, where _criterion.pxd/pyx is a Cython file that contains some variable named Criterion.

Now I am using poetry and meson and things do not work.

My Goals to Use Poetry and Meson

I would ideally like to be able to just do poetry install (or poetry build and poetry install), which should build and install things by using Meson to build local Cython/C++ files and then use poetry to handle other pip installable Python packages.

My Question

How do I correctly use poetry with meson to build my Cython files and install them along with other relevant Python dependencies to install my package?

My Attempt using just Meson incorrectly Cython files to the wrong environment

I instantiated my meson.build files such that running meson build in my repo's root directory works:

The Meson build system
Version: 0.63.2
Source dir: /Users/adam2392/Documents/scikit-tree
Build dir: /Users/adam2392/Documents/scikit-tree/build
Build type: native build
Project name: scikit-tree
Project version: 0.0.0.dev0
C compiler for the host machine: arm64-apple-darwin20.0.0-clang (clang 14.0.6 "clang version 14.0.6")
C linker for the host machine: arm64-apple-darwin20.0.0-clang ld64 609
C++ compiler for the host machine: arm64-apple-darwin20.0.0-clang++ (clang 14.0.6 "clang version 14.0.6")
C++ linker for the host machine: arm64-apple-darwin20.0.0-clang++ ld64 609
Host machine cpu family: aarch64
Host machine cpu: arm64
Library m found: YES
Program cython found: YES (/Users/adam2392/miniforge3/envs/sktree/bin/cython)
Program python3 found: YES (/Users/adam2392/miniforge3/envs/sktree/bin/python3)
Message: /Users/adam2392/miniforge3/envs/sktree/bin/python3
Message: /opt/homebrew/lib/python3.9/site-packages/
Found pkg-config: /opt/homebrew/bin/pkg-config (0.29.2)
Program _build_utils/cythoner.py found: YES (python /Users/adam2392/Documents/scikit-tree/sktree/_build_utils/cythoner.py)
Build targets in project: 1

scikit-tree 0.0.0.dev0

  User defined options
    backend: ninja

Found ninja-1.11.1 at /opt/homebrew/bin/ninja

When I then run meson install within the build/ directory:

(sktree) adam2392@Adams-MacBook-Pro build % meson install
ninja: Entering directory `/Users/adam2392/Documents/scikit-tree/build'
[3/3] Linking target sktree/tree/_unsup_criterion.cpython-39-darwin.so
ld: warning: -pie being ignored. It is only used when linking a main executable
Installing sktree/tree/_unsup_criterion.cpython-39-darwin.so to /opt/homebrew/lib/python3.9/site-packages/sktree/tree
Installing /Users/adam2392/Documents/scikit-tree/sktree/__init__.py to /opt/homebrew/lib/python3.9/site-packages/sktree
Installing /Users/adam2392/Documents/scikit-tree/sktree/_forest.py to /opt/homebrew/lib/python3.9/site-packages/sktree
Installing /Users/adam2392/Documents/scikit-tree/sktree/tree/__init__.py to /opt/homebrew/lib/python3.9/site-packages/sktree/tree
Installing /Users/adam2392/Documents/scikit-tree/sktree/tree/_classes.py to /opt/homebrew/lib/python3.9/site-packages/sktree/tree

which installs for example the Cython files into the incorrect Python environment (i.e. home-brew). I need it to be installed in my virtual environment.

My Attempt using Poetry doesn't work either

My pyproject.toml file has the following lines:

[build-system]
build-backend = "mesonpy"
requires = [
    "meson-python>=0.11.0",
    # `wheel` is needed for non-isolated builds, given that `meson-python`
    # doesn't list it as a runtime requirement (at least in 0.10.0)
    # See https://github.com/FFY00/meson-python/blob/main/pyproject.toml#L4
    "wheel",
    "setuptools<=65.5",
    "packaging",
    "Cython>=0.29.24",
    "scikit-learn",
]

However, when I run poetry install, there are no errors, but:

python -c "from sktree import tree"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/adam2392/Documents/scikit-tree/sktree/__init__.py", line 37, in <module>
    from . import tree
  File "/Users/adam2392/Documents/scikit-tree/sktree/tree/__init__.py", line 1, in <module>
    from ._classes import UnsupervisedDecisionTree
  File "/Users/adam2392/Documents/scikit-tree/sktree/tree/_classes.py", line 3, in <module>
    from ._unsup_criterion import UnsupervisedCriterion
ModuleNotFoundError: No module named 'sktree.tree._unsup_criterion'


问:
Joomla 4 redirect fails after logout
Just upgraded to Joomla 4 this week and everything seemed ok but a problem appeared in that once logged in you get an not found error page when logging out. It seems the site is redirecting to the home page adding in the subdirectory tohi which it should not include. It should redirect to torontohiking.com without the "tohi".

Errors noted by users:

“And I noticed that your homepage showing 404 error https://www.torontohiking.com/tohi/”

“I clicked the "Logout" link, the ToHi site redirected me to the following URL: "https://www.torontohiking.com/tohi/index.php” Deleting the tohi gave me the home page

The login link works and redirects properly but the logout link gives the not found error page. I've tried various menu links and internal urls. Removing tohi from the logout link
finally logs one out. Not sure what direction to go in.

I did a lot of Google searching on the topic but nothing relatable came up

I've tried various menu links and internal and external urls. Removing tohi from the logout link
finally logs one out. Not sure what direction to go in.
I'm thinking maybe installing a redirect extension could help

Title: Joomla 4 redirect fails after logout


问:
Firebase trouble when initializing CLI to deploy a react app
I keep getting the error below:

? Are you ready to proceed? Yes

? Which Firebase features do you want to set up for this directory? Press Space to select features, then Enter to confirm your choices. Hosting: Configure files for Firebase Hosting and (optionally) set up GitHub Action deploys

=== Project Setup

First, let's associate this project directory with a Firebase project.

You can create multiple project aliases by running firebase use --add,
but for now we'll just set up a default project.

? Please select an option: Use an existing project

Error: Failed to list Firebase projects. See firebase-debug.log for more info.

PS C:\Users\xxxxxlinked-in>

I have tried everything I can find on StackOverflow:

firebase login will log me in.
I have also done the firebase login --reauth one and also just reinstalling it npm install -g firebase-tools.

Its just when I go to use an existing project.

If it helps to know, I keep gettin another error when uing this command firebase projects:list.


问:
only show first result of youtube-dl channel request
I am trying to make a script that can view the latest video of a channel, my current method works but it keeps displaying all the videos.

Im wondering if it is possible to only get the first line of this youtube-dl channel request.

Input:

youtube-dl -i --get-filename -o "%(title)s, %(id)s" "youtube.com/user/pewdiepie/videos"

Current output:

WARNING: The url doesn't specify the protocol, trying with http

Saying goodbye is hard.., EOWP5Y7eErE

This illegal Swedish tradition is insane..., 8ch5LLc1z7s

My 12 Things I Can't LiveWithout., 7tB4jwvvuhQ

Lot of big changes lately.., https://www.youtube.com/watch?v=psHriqExm6U

Why I deleted the subreddit, https://www.youtube.com/watch?v=7yyjFudHYuw

Mr Beast passed me in subs.., https://www.youtube.com/watch?v=vHtqsuA8WJ4

Rating Liver Kings Apology, https://www.youtube.com/watch?v=tlNBB0jdL3w

'My mom fakes cancer', https://www.youtube.com/watch?v=wjPIcTU3AAM

Twitter Level Predator Exposed, https://www.youtube.com/watch?v=djr8j-4fS3A

Gordon Ramsey vs Fake Italian.., https://www.youtube.com/watch?v=X98VPQCE_WI

Twins wants to be Pregnant (At the same time...), https://www.youtube.com/watch?v=W27TjYZhytw

 I Spent 12 Hours at a Japanese Arcade, It was weird. (Collab w_ @PewDiePie ), https://www.youtube.com/watch?v=eIbqhi5Ikq8

Dr Phil destroys Gamer boy, https://www.youtube.com/watch?v=s0d-AFtXtkM

too big waves for me.., https://www.youtube.com/watch?v=8XR9OzAeDqQ

She fell for it!, https://www.youtube.com/watch?v=LzCA5zHayyk

Does this mean Im cursed now, https://www.youtube.com/watch?v=UhjjjqmGAkI

I took my car off road ... (Oops), https://www.youtube.com/watch?v=cLFJjMokld8

 ^C ERROR: Interrupted by user

^ Each line for every uploaded video.

Wanted output: Saying goodbye is hard.., https://www.youtube.com/watch?v=EOWP5Y7eErE, One line and exited program

(I usually would resolve this just by placing a |head -1 at the end of the command. but the command stays active and my script is paused.)

Version: 2021.12.17

OS: debian


问:
No suitable driver found for jdbc/OkStore2 in Netbeans and glassfish
Good day everyone, I have been watching this video series as a guide line for my own netbeans e commerce project but at 27:00 the teacher test the data source but when I try to run the file one I got this error message.

“jakarta.servlet.jsp.JspException: Unable to get connection,
DataSource invalid: "java.sql.SQLException: No suitable driver found
for jdbc/OkStore2"”

I’m on windows 11. The program versions I’m using are Apache Netbeans IDE 16, MySQL WorkBench 8.0 CE, Eclipse GlassFish 6.2.5 (build 6.x-b66-g0159b68 2022-02-12T17:39:59+0000). My driver is mysql-connector-j-8.0.31.
https://www.youtube.com/watch?v=JlLGrqHSSjk&list=PLWS58wV27xi5AFrSfru26h4KWNMv1h2XA&index=7&ab_channel=CS.Math.Educator

error message

Failed solution

putting the driver jar manually into WEB-INF/lib

putting the driver jar manually into
\glassfish\domains\domain1\lib\ext\


问:
How can I impute missing values according to a linear line connecting the nearest existing values on either side?
For individual columns within a data frame, I want to replace NA values with imputed values corresponding to the closest existing values on either side. These imputed values should represent a linear line between the existing values - for example, 5, NA, NA, NA, 6 would become 5, 5.25, 5.50, 5.75. 6.

So, this data frame -

```<code>reprex_df <- data.frame(
  ID    = seq(from=1, to=13, by=1),
  Value = c(2,NA,NA,NA,3,NA,NA,NA,9,NA,NA,NA,11)
)
reprex_df
    ID Value
1    1     2
2    2    NA
3    3    NA
4    4    NA
5    5     3
6    6    NA
7    7    NA
8    8    NA
9    9     9
10  10    NA
11  11    NA
12  12    NA
13  13    11
</code>```

would turn into this:

```<code>    ID  Value
1    1   2.00
2    2   2.25
3    3   2.50
4    4   2.75
5    5   3.00
6    6   4.50
7    7   6.00
8    8   7.50
9    9   9.00
10  10   9.50
11  11  10.00
12  12  10.50
13  13  11.00
</code>```

Is there any simple (hopefully tidy) way to do this? FWIW, this is similar to this question, but not quite the same as that deals with a simple mean of the two existing values on either side of the NA.

Body:
For individual columns within a data frame, I want to replace NA values with imputed values corresponding to the closest existing values on either side. These imputed values should represent a linear line between the existing values - for example, 5, NA, NA, NA, 6 would become 5, 5.25, 5.50, 5.75. 6.

So, this data frame -

reprex_df <- data.frame(
  ID    = seq(from=1, to=13, by=1),
  Value = c(2,NA,NA,NA,3,NA,NA,NA,9,NA,NA,NA,11)
)
reprex_df
    ID Value
1    1     2
2    2    NA
3    3    NA
4    4    NA
5    5     3
6    6    NA
7    7    NA
8    8    NA
9    9     9
10  10    NA
11  11    NA
12  12    NA
13  13    11

would turn into this:

    ID  Value
1    1   2.00
2    2   2.25
3    3   2.50
4    4   2.75
5    5   3.00
6    6   4.50
7    7   6.00
8    8   7.50
9    9   9.00
10  10   9.50
11  11  10.00
12  12  10.50
13  13  11.00

Is there any simple (hopefully tidy) way to do this? FWIW, this is similar to this question, but not quite the same as that deals with a simple mean of the two existing values on either side of the NA.


问:
Upload images fron python on Firebase
could you tell me if you can automatically upload images from Python that is hosted on Firebase

I haven't tried anything yet.
I'm not talking about storage, but about uploading a web page in firebase and loading images automatically on that web page ...

Title: Upload images fron python on Firebase


问:
The program that we made by cx-freeze does not run in other computers
I made a program with pyside6 and converted it to an executable Windows bundle with cx-freeze
This file runs on my computer, but it doesn't run on other computers and gives the following message


问:
In Angular 14, how do I find the value of"publicHost" (from angular.json) within my service?
I'm using Angular 14.  In my angular.json file I have

```<code>    "serve": {
      "builder": "ngx-build-plus:dev-server",
      "configurations": {
        "production": {
    ...
        "development": {
          "browserTarget": "my-app:build:development"
        }
      },
      "defaultConfiguration": "development",
      "options": {
        "port": 4204,
        "publicHost": "http://localhost:8005",
        "extraWebpackConfig": "webpack.config.js"
      }
    },
</code>```

I would like to know how I can get the value of the "publicHost" in an injectable service I have, for example

```<code>@Injectable({
  providedIn: 'root'
})
export class AppService {

    public getPublicHost() {
        ...
    }
}
</code>```

It is not an option to return "windnow.location.host" only because this particular application runs as a remote application within a larger shell application using Angular's module federation.  What I have learend is that in such a configuration, "windnow.location.host" only returns the URL of the parent (shell) application and not the remote.

Body:
I'm using Angular 14.  In my angular.json file I have

    "serve": {
      "builder": "ngx-build-plus:dev-server",
      "configurations": {
        "production": {
    ...
        "development": {
          "browserTarget": "my-app:build:development"
        }
      },
      "defaultConfiguration": "development",
      "options": {
        "port": 4204,
        "publicHost": "http://localhost:8005",
        "extraWebpackConfig": "webpack.config.js"
      }
    },

I would like to know how I can get the value of the "publicHost" in an injectable service I have, for example

@Injectable({
  providedIn: 'root'
})
export class AppService {

    public getPublicHost() {
        ...
    }
}

It is not an option to return "windnow.location.host" only because this particular application runs as a remote application within a larger shell application using Angular's module federation.  What I have learend is that in such a configuration, "windnow.location.host" only returns the URL of the parent (shell) application and not the remote.


Title: How does efficient_apriori package code itemsets?

Body:
Doing association rules mining using efficient_apriori package in python.Found a  very useful answer on how to convert the output to a dataframe

However, struggling with the Itemset output and hoping someone can help me parse that correctly. Guessing LHS is an index value, but struggling with the decimal values in RHS. Does anyone know how the encoding is done? I have tried the same with SKU descriptions, and get the same output.

Input dataframe looks like this:

   | SKU                                                                  | Count | Percent     |
    |----------------------------------------------------------------------|-------|-------------|
    | "('000000009100000749',)"                                            | 110   | 0.029633621 |
    | "('000000009100000749', '000000009100000776')"                       | 1     | 0.000269397 |
    | "('000000009100000749', '000000009100000776', '000000009100002260')" | 1     | 0.000269397 |
    | "('000000009100000749', '000000009100000777', '000000009100002260')" | 1     | 0.000269397 |
    | "('000000009100000749', '000000009100000777', '000000009100002530')" | 1     | 0.000269397 |

Output looks like this:

 |   | lhs                         | rhs                         | count_full | count_lhs | count_rhs | num_transactions | confidence | support     |
    |---|-----------------------------|-----------------------------|------------|-----------|-----------|------------------|------------|-------------|
    | 0 | "(1,)"                      | "(0.00026939655172413793,)" | 168        | 168       | 168       | 297              | 1          | 0.565656566 |
    | 1 | "(0.00026939655172413793,)" | "(1,)"                      | 168        | 168       | 168       | 297              | 1          | 0.565656566 |
    | 2 | "(2,)"                      | "(0.0005387931034482759,)"  | 36         | 36        | 36        | 297              | 1          | 0.121212121 |
    | 3 | "(0.0005387931034482759,)"  | "(2,)"                      | 36         | 36        | 36        | 297              | 1          | 0.121212121 |
    | 4 | "(3,)"                      | "(0.0008081896551724138,)"  | 21         | 21        | 21        | 297              | 1          | 0.070707071 |

Could someone help me understand what's outputting in the LHS and RHS columns, and how to join  that back to the 'SKU'? Ideally would like the output to have the 'SKU' instead of whatever is showing up.

I have looked at the documentation and it is quite sparse.


问:
I'm having prerendering errors deploying my project in vercel
I'm having trouble deploying my project in vercel, when I deploy I, get the following error message:

```<code>> Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
SyntaxError: Unexpected token A in JSON at position 0
    at JSON.parse (<anonymous>)
    at Response.json (node:internal/deps/undici/undici:6160:23)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async loadPosts (/vercel/path0/.next/server/chunks/226.js:24:18)
    at async getStaticProps (/vercel/path0/.next/server/pages/index.js:399:19)
    at async renderToHTML (/vercel/path0/node_modules/next/dist/server/render.js:385:20)
    at async /vercel/path0/node_modules/next/dist/export/worker.js:277:36
    at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:79:20)
> Build error occurred
info  - Generating static pages (7/7)
Error: Export encountered errors on following paths:
    /
    at /vercel/path0/node_modules/next/dist/export/index.js:409:19
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:79:20)
    at async /vercel/path0/node_modules/next/dist/build/index.js:1345:21
    at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:79:20)
    at async /vercel/path0/node_modules/next/dist/build/index.js:1205:17
    at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:79:20)
    at async Object.build [as default] (/vercel/path0/node_modules/next/dist/build/index.js:66:29)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Error: Command "yarn run build" exited with 1
</code>```

My folder structure

```<code>-pages
--index.tsx
--[tag]/[title].tsx
-components
--...All my components
-lib
--posts.ts
-utilities/index.ts

</code>```

My index.tsx

```<code>import Head from 'next/head'
import Image from 'next/image'
import { Inter } from '@next/font/google'
import styles from '../styles/Home.module.css'
import Box from '@mui/material/Box'
import FeaturedPostContainer from '../components/cards/FeaturedPostContainer'
import PostCategory from '../components/cards/PostCategory'
import { Post } from '../custom_types/Posts'
import PostCategoryContainer from '../components/cards/PostCategoryContainer'
import { url } from '../utilities'
import { loadFeaturedPosts, loadPosts } from '../lib/posts'

export default function Home({
    featuredPosts,
    posts,
}: {
    featuredPosts: Post[] | null
    posts: Post[] | null
}) {
    // console.log(featuredPosts, 'from now home component')
    return (
        <>
            <Head>
                <title>Blog | By Dev Louix</title>
                <meta
                    name="description"
                    content="Generated by create next app"
                />
                <meta
                    name="viewport"
                    content="width=device-width, initial-scale=1"
                />
                <link rel="icon" href="/favicon.ico" />
            </Head>
            <Box component="main" sx={{ p: 3 }}>
                {featuredPosts ? (
                    <>
                        <FeaturedPostContainer posts={featuredPosts} />
                        <PostCategoryContainer posts={posts} />
                    </>
                ) : (
                    <h1>No Posts</h1>
                )}
            </Box>
        </>
    )
}

export async function getStaticProps() {
    const posts = await loadPosts()
    const featuredPosts = await loadFeaturedPosts()

    // Pass data to the page via props
    return { props: { posts: posts, featuredPosts: featuredPosts } }
}

</code>```

[title].tsx

```<code>import { useRouter } from 'next/router'
import React, { useEffect, useState } from 'react'
import PostBody from '../../components/PostBody'
import { Post } from '../../custom_types/Posts'
import { loadPosts } from '../../lib/posts'
import { url } from '../../utilities'

function Postroute() {
    const router = useRouter()
    const { tag, title } = router.query
    const [post, setPost] = useState<Post>({})
    const [loading, setLoading] = useState(true)
    const TAGS = ['featured', 'tutorial', 'how-to', 'articles']
    let tagLength = TAGS.length - 1

    useEffect(() => {
        if (router.isReady) {
            console.log(tag, title)
            for (let tagIndex = 0; tagIndex < TAGS.length; tagIndex++) {
                console.log(tagIndex)

                const tagName = TAGS[tagIndex]
                if (tagName == tag) {
                    fetchPost(tagName)
                    setLoading(false)
                    break
                } else if (tagIndex == tagLength && tagName != tag) {
                    router.push('/')
                }
            }
        }
    }, [router.isReady])

    async function fetchPost(tagName: string) {
        const data = await loadPosts()

        const post = data.filter((post:Post) => {
            if (post.title == title) {
                return post
            }
        })
        setPost(post[0])
        console.log(post[0], 'posters')
    }

    return (
        <>
            {loading ? (
                <h1>Loading....</h1>
            ) : (
                <PostBody
                    title={post.title}
                    body={post.body}
                    thumbnail={post.thumbnail}
                />
            )}
        </>
    )
}

export default Postroute

</code>```

lib/posts.ts

```<code>import { url } from '../utilities'

export async function loadPosts() {
    // Call an external API endpoint to get posts
    const res = await fetch(`${url}/api/posts`)
    const data = await res.json()
    let posts = data.posts

    console.log(posts,"posts from lib..............................................................");

    return posts
}

export async function loadFeaturedPosts() {
    // Call an external API endpoint to get posts
    const res = await fetch(`${url}/api/posts`)
    const data = await res.json()

    let featuredPosts = data.featuredPosts
    console.log(featuredPosts,"from lib=========================================================");

    return featuredPosts
}

</code>```

utilities/index.ts

```<code>export const url: string | undefined = process.env.NEXT_PUBLIC_VERCEL_URL
    ? process.env.NEXT_PUBLIC_VERCEL_URL
    : process.env.NEXT_PUBLIC_BASE_FETCH_URL
</code>```

Where is the error coming from and how do I resolve it?

I have troubleshooted it with other similar problems and also stagged the .env url in vercel, but didn't seem to resolve it.

Body:
I'm having trouble deploying my project in vercel, when I deploy I, get the following error message:

> Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
SyntaxError: Unexpected token A in JSON at position 0
    at JSON.parse (<anonymous>)
    at Response.json (node:internal/deps/undici/undici:6160:23)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async loadPosts (/vercel/path0/.next/server/chunks/226.js:24:18)
    at async getStaticProps (/vercel/path0/.next/server/pages/index.js:399:19)
    at async renderToHTML (/vercel/path0/node_modules/next/dist/server/render.js:385:20)
    at async /vercel/path0/node_modules/next/dist/export/worker.js:277:36
    at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:79:20)
> Build error occurred
info  - Generating static pages (7/7)
Error: Export encountered errors on following paths:
    /
    at /vercel/path0/node_modules/next/dist/export/index.js:409:19
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:79:20)
    at async /vercel/path0/node_modules/next/dist/build/index.js:1345:21
    at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:79:20)
    at async /vercel/path0/node_modules/next/dist/build/index.js:1205:17
    at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:79:20)
    at async Object.build [as default] (/vercel/path0/node_modules/next/dist/build/index.js:66:29)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Error: Command "yarn run build" exited with 1

My folder structure

-pages
--index.tsx
--[tag]/[title].tsx
-components
--...All my components
-lib
--posts.ts
-utilities/index.ts

My index.tsx

import Head from 'next/head'
import Image from 'next/image'
import { Inter } from '@next/font/google'
import styles from '../styles/Home.module.css'
import Box from '@mui/material/Box'
import FeaturedPostContainer from '../components/cards/FeaturedPostContainer'
import PostCategory from '../components/cards/PostCategory'
import { Post } from '../custom_types/Posts'
import PostCategoryContainer from '../components/cards/PostCategoryContainer'
import { url } from '../utilities'
import { loadFeaturedPosts, loadPosts } from '../lib/posts'

export default function Home({
    featuredPosts,
    posts,
}: {
    featuredPosts: Post[] | null
    posts: Post[] | null
}) {
    // console.log(featuredPosts, 'from now home component')
    return (
        <>

                <title>Blog | By Dev Louix</title>
                <meta
                    name="description"
                    content="Generated by create next app"
                />
                <meta
                    name="viewport"
                    content="width=device-width, initial-scale=1"
                />
                <link rel="icon" href="/favicon.ico" />

            <Box component="main" sx={{ p: 3 }}>
                {featuredPosts ? (
                    <>
                        <FeaturedPostContainer posts={featuredPosts} />
                        <PostCategoryContainer posts={posts} />
                    </>
                ) : (

No Posts

                )}
            </Box>
        </>
    )
}

export async function getStaticProps() {
    const posts = await loadPosts()
    const featuredPosts = await loadFeaturedPosts()

    // Pass data to the page via props
    return { props: { posts: posts, featuredPosts: featuredPosts } }
}

[title].tsx

import { useRouter } from 'next/router'
import React, { useEffect, useState } from 'react'
import PostBody from '../../components/PostBody'
import { Post } from '../../custom_types/Posts'
import { loadPosts } from '../../lib/posts'
import { url } from '../../utilities'

function Postroute() {
    const router = useRouter()
    const { tag, title } = router.query
    const [post, setPost] = useState<Post>({})
    const [loading, setLoading] = useState(true)
    const TAGS = ['featured', 'tutorial', 'how-to', 'articles']
    let tagLength = TAGS.length - 1

    useEffect(() => {
        if (router.isReady) {
            console.log(tag, title)
            for (let tagIndex = 0; tagIndex < TAGS.length; tagIndex++) {
                console.log(tagIndex)

                const tagName = TAGS[tagIndex]
                if (tagName == tag) {
                    fetchPost(tagName)
                    setLoading(false)
                    break
                } else if (tagIndex == tagLength && tagName != tag) {
                    router.push('/')
                }
            }
        }
    }, [router.isReady])

    async function fetchPost(tagName: string) {
        const data = await loadPosts()

        const post = data.filter((post:Post) => {
            if (post.title == title) {
                return post
            }
        })
        setPost(post[0])
        console.log(post[0], 'posters')
    }

    return (
        <>
            {loading ? (

Loading....

            ) : (
                <PostBody
                    title={post.title}
                    body={post.body}
                    thumbnail={post.thumbnail}
                />
            )}
        </>
    )
}

export default Postroute

lib/posts.ts

import { url } from '../utilities'

export async function loadPosts() {
    // Call an external API endpoint to get posts
    const res = await fetch(`${url}/api/posts`)
    const data = await res.json()
    let posts = data.posts

    console.log(posts,"posts from lib..............................................................");

    return posts
}

export async function loadFeaturedPosts() {
    // Call an external API endpoint to get posts
    const res = await fetch(`${url}/api/posts`)
    const data = await res.json()

    let featuredPosts = data.featuredPosts
    console.log(featuredPosts,"from lib=========================================================");

    return featuredPosts
}

utilities/index.ts

export const url: string | undefined = process.env.NEXT_PUBLIC_VERCEL_URL
    ? process.env.NEXT_PUBLIC_VERCEL_URL
    : process.env.NEXT_PUBLIC_BASE_FETCH_URL

Where is the error coming from and how do I resolve it?

I have troubleshooted it with other similar problems and also stagged the .env url in vercel, but didn't seem to resolve it.


问:
C# Simulate the effect of throwing an exception without throwing an exception
I have a specific process I am running... there can be many errors during it as it uses player input, and the errors can be found in various classes because it's big. For clarification, I am building a parser(using antlr4), and many syntax and language errors can happen anywhere in the code because of that(Not actual exceptions, just them writing bad code in my language). I'd like it so that when such an "error" is detected, The entire parsing process would stop but without throwing an exception...

Ik that I can wrap a Try-Catch around the whole process easily and then just use that... but considering how big that is and knowing that it's not recommended to put a Try-Catch on really big stuff unless really necessary, I wonder if there's another way to force the entire callstack to back off.

So far, I have a static property IsRunning on a Diagnostic class, and whenever you use the Diagnostics.PrintError() method IsRunning is set to false. But for things to actually stop I need to throw ing if (!Diagnostics.IsRunning) return null; practically after every invoke to a method that might call Diagnostics.PrintError()... and not only is it quite dumb and hard to maintain... it's extremely easy to miss a check like that and never find out where it comes from...

Does anyone have a better solution or will I be forced to use C# Exceptions and a HUGE Try-Catch around the whole process?

as a reminder, what I want is to be able to completely force-stop the entire parsing process if a certain condition is met(in my case, !Diagnostics.IsRunning), but still, continue everything else, essentially popping the entire callstack up to the point that the Parse() method was called, and continue normally from there.


问:
STM32F407 Stucks on UART Interrupt
I got a problem with my STM32F407 and the UART.
I want to receive data with USART3 in interrupt mode.

my primary code is that:

```<code>UART_HandleTypeDef huart3;
uint8_t buffer[16];

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if(huart == &huart3)
    {
        if(HAL_UART_Receive_IT(&huart3, uartData, sizeof(uartData)) != HAL_OK)
        {
            uint32_t error = HAL_UART_GetError(&huart3);
        }
    }
}

void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
  uint32_t error = huart->ErrorCode;
}

int main(void)
{
  HAL_Init();
  SystemClock_Config();
  MX_GPIO_Init()
  MX_USART3_UART_Init();
  MX_NVIC_Init();
  HAL_UART_Receive_IT(&huart3, uartData, sizeof(uartData));
  while (1)
  {
    osDelay(1);
  }
}
</code>```

i send over my serial console the text 'test' until the buffer is full and interrupt is fired.
my interrupt is fired one time and then no more, HAL_UART_Receive_IT gives me HAL_OK back, but the

ErrorCallback is fired after the with HAL_UART_RxCpltCallback with error 0x8, this says that are a UART Overrun Error...

Okay.. i see no blocking function that can be overrun the UART, or is my function wrong?
it gives many examples with this code to use the UART, who is the problem?

Thank you!
Daniel

Title: STM32F407 Stucks on UART Interrupt

Body:
I got a problem with my STM32F407 and the UART.
I want to receive data with USART3 in interrupt mode.

my primary code is that:

UART_HandleTypeDef huart3;
uint8_t buffer[16];

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if(huart == &huart3)
    {
        if(HAL_UART_Receive_IT(&huart3, uartData, sizeof(uartData)) != HAL_OK)
        {
            uint32_t error = HAL_UART_GetError(&huart3);
        }
    }
}

void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
  uint32_t error = huart->ErrorCode;
}

int main(void)
{
  HAL_Init();
  SystemClock_Config();
  MX_GPIO_Init()
  MX_USART3_UART_Init();
  MX_NVIC_Init();
  HAL_UART_Receive_IT(&huart3, uartData, sizeof(uartData));
  while (1)
  {
    osDelay(1);
  }
}

i send over my serial console the text 'test' until the buffer is full and interrupt is fired.
my interrupt is fired one time and then no more, HAL_UART_Receive_IT gives me HAL_OK back, but the

ErrorCallback is fired after the with HAL_UART_RxCpltCallback with error 0x8, this says that are a UART Overrun Error...

Okay.. i see no blocking function that can be overrun the UART, or is my function wrong?
it gives many examples with this code to use the UART, who is the problem?

Thank you!
Daniel


问:
Edit Music metadata with Windows Runtime API with .net 6
After some research, I found out how to have my project access the Windows Runtime API.
Now I can happily read the Music properties of my file (Albums, Title etc):

```<code>StorageFile sf = await StorageFile.GetFileFromPathAsync(filename);
var props = await sf.Properties.GetMusicPropertiesAsync();
</code>```

I can read and edit them, but I didn't find a way to persist.
I tried like this:

```<code>props.Album = "TEST";
await sf.Properties.SavePropertiesAsync();
</code>```

Nothing breaks, but nothing changes, and my album is still what it was before.
Am I doing something silly and wrong?

Body:
After some research, I found out how to have my project access the Windows Runtime API.
Now I can happily read the Music properties of my file (Albums, Title etc):

StorageFile sf = await StorageFile.GetFileFromPathAsync(filename);
var props = await sf.Properties.GetMusicPropertiesAsync();

I can read and edit them, but I didn't find a way to persist.
I tried like this:

props.Album = "TEST";
await sf.Properties.SavePropertiesAsync();

Nothing breaks, but nothing changes, and my album is still what it was before.
Am I doing something silly and wrong?


问:
How can a simple std::cout << "---" << std::endl; alter how UB manifests?

Some background

Today I saw, in the body of a function kaboom, a local shared_ptr pointing to a *global object and, being captured by reference and its pointee returned by reference by a lambda, i.e. [&local]() -> auto& { return *local; }; this lambda was stored somehow for further use after the function kaboom returned.

As soon as I saw this, I thought the code was invoking undefined behavior. I tried to make a minimal example to support my claim, and came up with the following.

#include <iostream>
#include <memory>
#include <functional>
#include <vector>

struct Resource {
    const int i{3};
};

std::shared_ptr<Resource> global = std::make_unique<Resource>();

auto getSharedStuff() {
    return global;
}

std::vector<std::function<Resource&()>> actions{};

void kaboom() {
    std::shared_ptr<Resource> local = getSharedStuff();
    actions.push_back([&local]() -> auto& { return *local; });
}

int main() {
    kaboom();
    std::cout << global->i << std::endl;
    std::cout << actions[0]().i << std::endl;
}
```
<p>The simple fact that the 2 <code>cout</code>s give 3 and 0 respectively is proof for me that I'm observing UB (3 is correct, and 0 could have been anything, including 3, but I've been lucky that it was not 3, so the UB is well manifest).</p>
<p>Good.</p>
<h2>The code I'm curious about</h2>
<p>But before getting there, an intermediate version of the repro above was this:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <memory>
#include <functional>
#include <vector>

struct Resource {
    Resource(Resource const&) = delete;
    Resource(Resource&&) = delete;
    Resource() { std::cout << this << "'s ctor" << std::endl; }
    ~Resource() { std::cout << this << "'s dtor" << std::endl; }
    void operator()() { std::cout << this << "'s operator()" << std::endl; }
};

std::shared_ptr<Resource> global = std::make_unique<Resource>();

auto getSharedStuff() {
    return global;
}

std::vector<std::function<Resource&()>> actions{};

void kaboom() {
    std::shared_ptr<Resource> local = getSharedStuff();
    actions.push_back([&local]() -> auto& { return *local; });
}

int main() {
    kaboom();
    std::cout << "---" << std::endl;
    actions[0]()();
}
</code>```

which can result in this output

0xc602b0's ctor
---
0x7f0f48f7f4a0's operator()
0xc602b0's dtor
```
<p>I'm kind of ok with this, as <code>actions[0]()()</code> is dereferencing a destroyed <code>shared_ptr</code> and calling <code>operator()</code> on the screwed up result, so I accept that <code>this</code> can be screwup too.</p>
<p>What's funny, though, is that removing <code>std::cout << "---" << std::endl;</code> makes UB less manifest, as the output becomes something like this:</p>
<pre class="lang-none prettyprint-override"><code>0xce92b0's ctor
0xce92b0's operator()
0xce92b0's dtor
</code>```

So my question is: how can a "simple" line as std::cout << "---" << std::endl; affect this way the manifestation of UB?

Body:
Some background

Today I saw, in the body of a function kaboom, a local shared_ptr pointing to a *global object and, being captured by reference and its pointee returned by reference by a lambda, i.e. [&local]() -> auto& { return *local; }; this lambda was stored somehow for further use after the function kaboom returned.

As soon as I saw this, I thought the code was invoking undefined behavior. I tried to make a minimal example to support my claim, and came up with the following.

#include <iostream>
#include <memory>
#include <functional>
#include <vector>

struct Resource {
    const int i{3};
};

std::shared_ptr<Resource> global = std::make_unique<Resource>();

auto getSharedStuff() {
    return global;
}

std::vector<std::function<Resource&()>> actions{};

void kaboom() {
    std::shared_ptr<Resource> local = getSharedStuff();
    actions.push_back([&local]() -> auto& { return *local; });
}

int main() {
    kaboom();
    std::cout << global->i << std::endl;
    std::cout << actions[0]().i << std::endl;
}

The simple fact that the 2 couts give 3 and 0 respectively is proof for me that I'm observing UB (3 is correct, and 0 could have been anything, including 3, but I've been lucky that it was not 3, so the UB is well manifest).

Good.

The code I'm curious about

But before getting there, an intermediate version of the repro above was this:

#include <iostream>
#include <memory>
#include <functional>
#include <vector>

struct Resource {
    Resource(Resource const&) = delete;
    Resource(Resource&&) = delete;
    Resource() { std::cout << this << "'s ctor" << std::endl; }
    ~Resource() { std::cout << this << "'s dtor" << std::endl; }
    void operator()() { std::cout << this << "'s operator()" << std::endl; }
};

std::shared_ptr<Resource> global = std::make_unique<Resource>();

auto getSharedStuff() {
    return global;
}

std::vector<std::function<Resource&()>> actions{};

void kaboom() {
    std::shared_ptr<Resource> local = getSharedStuff();
    actions.push_back([&local]() -> auto& { return *local; });
}

int main() {
    kaboom();
    std::cout << "---" << std::endl;
    actions[0]()();
}

which can result in this output

0xc602b0's ctor
---
0x7f0f48f7f4a0's operator()
0xc602b0's dtor

I'm kind of ok with this, as actions[0]()() is dereferencing a destroyed shared_ptr and calling operator() on the screwed up result, so I accept that this can be screwup too.

What's funny, though, is that removing std::cout << "---" << std::endl; makes UB less manifest, as the output becomes something like this:

0xce92b0's ctor
0xce92b0's operator()
0xce92b0's dtor

So my question is: how can a "simple" line as std::cout << "---" << std::endl; affect this way the manifestation of UB?


问:
How Can I Submit Radio Input Values in Html Form in Flutter?
I want to answer surveys on a form on a website by making an html parser on Flutter.

The html output is as follows. For example, how can I select the value of the poll with the name poll_13 as 120.

```<code><div id="polls">
    <form id="polls_form_1" class="wp-polls-form" action="/index.php" method="post">
        <input type="radio" id="poll-answer-10" name="poll_13" value="117">
        <input type="radio" id="poll-answer-11" name="poll_13" value="118">
        <input type="radio" id="poll-answer-12" name="poll_13" value="119">
        <input type="radio" id="poll-answer-13" name="poll_13" value="120">
        <input type="button" name="vote" value="Vote" class="Buttons" onclick="poll_vote(13);">
    </form>
</div>
</code>```

I was able to select the poll-answer-13 element by importing the html and http packages, but I couldn't figure out how to click and submit the form.

```<code>  void submitForm() async {
    var response = await http.get(Uri.parse(
          "https://xxxx.com/poll"));
          var document = parse(response.body);
      var pollAnswer118 = document.querySelector("#poll-answer-13");
  }
</code>```

Body:
I want to answer surveys on a form on a website by making an html parser on Flutter.

The html output is as follows. For example, how can I select the value of the poll with the name poll_13 as 120.

    <form id="polls_form_1" class="wp-polls-form" action="/index.php" method="post">
        <input type="radio" id="poll-answer-10" name="poll_13" value="117">
        <input type="radio" id="poll-answer-11" name="poll_13" value="118">
        <input type="radio" id="poll-answer-12" name="poll_13" value="119">
        <input type="radio" id="poll-answer-13" name="poll_13" value="120">
        <input type="button" name="vote" value="Vote" class="Buttons" onclick="poll_vote(13);">
    </form>

I was able to select the poll-answer-13 element by importing the html and http packages, but I couldn't figure out how to click and submit the form.

  void submitForm() async {
    var response = await http.get(Uri.parse(
          "https://xxxx.com/poll"));
          var document = parse(response.body);
      var pollAnswer118 = document.querySelector("#poll-answer-13");
  }


问:
Cannot further process the result from useQuery in Vue Apollo (Vue 3, composition API)
I have a Vue 3 component that displays some data, fetched through a composable that talks to an API via Apollo. The useMyQuery function returns result and loading from the query, which works fine. It also does a transformation (transformData) on an array from the result object (arrayData). This is the part that doesn't work.

When I run the code as displayed, I get the error Uncaught (in promise) TypeError: data is undefined (I assume because when it first runs, useQuery hasn't returned anything yet. But if I wrap the content of the transformData-function like if (!data) {return null} else {...}, it never seems to update, it just returns null.

I wonder if this is because I am running the function only on the result.arrayData, which is not reactive? In that case, how can I make this work?

The composable:

// useMyQueries.js
import { useQuery } from '@vue/apollo-composable'
import gql from 'graphql-tag'

export function useMyQuery() {
    const variables = {
        'search': "hello",
        'limit': 0
    }
    const { result, loading } = useQuery(gql(QUERY), variables)

    function transformData(data) {
        return {
            labels: data.map(item => item.time),
            datasets: [{ data: data.map(item => item.count) }]
        };

    }
    return {
        result,
        loading,
        transformedData: transformData(result.arrayData),
    }
}
```
<p>The component:</p>
<pre class="lang-js prettyprint-override"><code>// MyComponent.vue
<template>
    <v-container>
        <v-card title="Title" :loading="loading">
            <v-card-text>
                {{ transformedData }}
            </v-card-text>
        </v-card>
    </v-container>
</template>

<script setup>
import { useMyQuery } from '@/useMyQueries.js'

const { result, loading, transformedData } = useMyQuery()

</script>
</code>```

Body:
I have a Vue 3 component that displays some data, fetched through a composable that talks to an API via Apollo. The useMyQuery function returns result and loading from the query, which works fine. It also does a transformation (transformData) on an array from the result object (arrayData). This is the part that doesn't work.

When I run the code as displayed, I get the error Uncaught (in promise) TypeError: data is undefined (I assume because when it first runs, useQuery hasn't returned anything yet. But if I wrap the content of the transformData-function like if (!data) {return null} else {...}, it never seems to update, it just returns null.

I wonder if this is because I am running the function only on the result.arrayData, which is not reactive? In that case, how can I make this work?

The composable:

// useMyQueries.js
import { useQuery } from '@vue/apollo-composable'
import gql from 'graphql-tag'

export function useMyQuery() {
    const variables = {
        'search': "hello",
        'limit': 0
    }
    const { result, loading } = useQuery(gql(QUERY), variables)

    function transformData(data) {
        return {
            labels: data.map(item => item.time),
            datasets: [{ data: data.map(item => item.count) }]
        };

    }
    return {
        result,
        loading,
        transformedData: transformData(result.arrayData),
    }
}

The component:

// MyComponent.vue
<template>
    <v-container>
        <v-card title="Title" :loading="loading">
            <v-card-text>
                {{ transformedData }}
            </v-card-text>
        </v-card>
    </v-container>
</template>


问:
OpenCV: passing an argument from a C main function to the OpenCV C++ API
I have an application that is written in C, and I would like to use a few OpenCV functions to do some image processing. I see where the C API has been deprecated, so I am currently trying to interface with the C++ API from C. I am running into some compilation issues.

Just to reproduce the example, let's say that I have this C main function in a file grouping_test_main.c:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <malloc.h>

extern "C"
{
        #include "opencv_grouping.h"
}
uint8_t **allocate_2D_array(uint32_t SizeY, uint32_t SizeX);
int free_2D_array(uint8_t **image_array, uint32_t SizeY);

int main()
{
        uint32_t SizeY=19;
        uint32_t SizeX=20;
        uint8_t **image_array;
        FILE* fimage_array = fopen("./test_array.txt", "r");
        double threshold_value=128;
        ConnectedComponentsResults results;
        int i;
        int j;

        image_array = allocate_2D_array(SizeY, SizeX);

        for (i=0; i<SizeY; i++)
        {
                for (j=0; j<SizeX; j++)
                {
                        fscanf(fimage_array, "%hhd", &image_array[i][j]);
                }
        }
        fclose(fimage_array);

        treshold_then_group(image_array, SizeY, SizeX, results);
        printf("Number of connected components: %d\n", results.num_components);
        free_2D_array(image_array, SizeY);
}

uint8_t **allocate_2D_array(uint32_t SizeY, uint32_t SizeX)

        /*
         * Allocates memory for a 2D image array.
         */
{
        int i;
        uint8_t **image_array;

        image_array = malloc(SizeY * sizeof(uint8_t *));
        for (i = 0; i < SizeY; i++)
        {
                image_array[i] = malloc(SizeX * sizeof(uint8_t ));
                if(image_array[i] == NULL)
                {
                        fprintf(stderr, "Memory allocation for image_array[%d] failed.\n", i);
                        exit(EXIT_FAILURE);
                }
        }
        return image_array;
}

int free_2D_array(image_array, SizeY)

        /*
         * Frees memory allocated for 2D image array.
         */

        uint8_t **image_array;
        uint32_t SizeY;
{
        int i;

        for (i = 0; i < SizeY; i++)
        {
                free(image_array[i]);
        }
        return(1);
}
</code>```

threshold_then_group() is the C++ function. test_array.txt is a text file with a 19X20 array:

```<code>0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 255 255 255 0 0 0 0 0 0 255 255 255 255 255 0 0 0
0 0 0 255 255 255 0 0 0 0 0 0 0 255 255 255 0 0 0 0
0 0 255 255 255 255 0 0 0 0 0 0 0 0 255 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 255 255 0 0 0 0 0 0 0 0 255 0 0 0 0 0
0 0 0 255 255 255 255 255 0 0 0 0 255 255 255 255 0 0 0 0
0 0 0 0 255 255 255 255 255 0 0 255 255 255 0 0 0 0 0 0
0 0 0 0 0 0 255 255 255 255 255 255 255 0 0 0 0 0 0 0
0 0 0 0 0 0 0 255 255 255 255 255 255 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 255 255 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
</code>```

opencv_grouping.h is the header file where I declare the C++ functions.

```<code>/* Header file for opencv_grouping.cpp.
 */

#ifndef CONNECTED_COMPONENTS_H
#define CONNECTED_COMPONENTS_H

#include <stdint.h>
#include <opencv2/opencv.hpp>

struct ConnectedComponentsResults
{
        int num_components;
        cv::Mat labels;
        cv::Mat stats;
        cv::Mat centroids;
};

void threshold_then_group(uint8_t **image_array, uint32_t SizeY, uint32_t SizeX, double threshold_value, ConnectedComponentsResults &results);

#endif
</code>```

Then, the C++ functions in opencv_grouping.cpp are:

```<code>/* Grouping and centroiding implementation using OpenCV's
 * connectedComponentsWithStats().
 */

#include <stdint.h>
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstdlib>

#include <opencv2/opencv.hpp>
#include "opencv_grouping.h"

void threshold_then_group(uint8_t **image_array, uint32_t SizeY, uint32_t SizeX, double threshold_value, ConnectedComponentsResults &results)
{
        uint8_t *image_data = new uint8_t[SizeY * SizeX];
        double max_value=255.0;
        int i;
        int j;

        for (i=0; i<SizeY; i++)
        {
                for (j=0; j<SizeX; j++)
                {
                        image_data[i * SizeX + j] = image_array[i][j];
                }
        }

        cv::Mat image(SizeY, SizeX, CV_8U, image_data);

        cv::Mat binary;
        threshold(image, binary, threshold_value, max_value, cv::THRESH_BINARY);

        cv::Mat labels, stats, centroids;

        int num_components = cv::connectedComponentsWithStats(binary, results.labels, results.stats, results.centroids, 8, CV_32S);

        results.num_components = results.stats.rows - 1;

        delete[] image_data;
}
</code>```

I am attempting to compile the code like this:

```<code>g++ `pkg-config --cflags opencv4` -c opencv_grouping.cpp
gcc `pkg-config --cflags opencv4` -c grouping_test_main.c
gcc opencv_test.o opencv_grouping.o -lstdc++ `pkg-config --libs opencv4` -o opencv_test2
</code>```

opencv_grouping.cpp compiles just fine, but grouping_test_main.c fails. This is because opencv_grouping.h includes opencv2/opencv.hpp, and the error messages indicate that the files included in opencv.hpp must be compiled using a C++ compiler. I haven't tried to compile the main function using g++, but even if this somehow works, this isn't really a solution. My actual main function is a lot more complicated than what I've shown here, and it uses a lot of C libraries that I don't think would compile with g++.

Body:
I have an application that is written in C, and I would like to use a few OpenCV functions to do some image processing. I see where the C API has been deprecated, so I am currently trying to interface with the C++ API from C. I am running into some compilation issues.

Just to reproduce the example, let's say that I have this C main function in a file grouping_test_main.c:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <malloc.h>

extern "C"
{
        #include "opencv_grouping.h"
}
uint8_t **allocate_2D_array(uint32_t SizeY, uint32_t SizeX);
int free_2D_array(uint8_t **image_array, uint32_t SizeY);

int main()
{
        uint32_t SizeY=19;
        uint32_t SizeX=20;
        uint8_t **image_array;
        FILE* fimage_array = fopen("./test_array.txt", "r");
        double threshold_value=128;
        ConnectedComponentsResults results;
        int i;
        int j;

        image_array = allocate_2D_array(SizeY, SizeX);

        for (i=0; i<SizeY; i++)
        {
                for (j=0; j<SizeX; j++)
                {
                        fscanf(fimage_array, "%hhd", &image_array[i][j]);
                }
        }
        fclose(fimage_array);

        treshold_then_group(image_array, SizeY, SizeX, results);
        printf("Number of connected components: %d\n", results.num_components);
        free_2D_array(image_array, SizeY);
}

uint8_t **allocate_2D_array(uint32_t SizeY, uint32_t SizeX)

        /*
         * Allocates memory for a 2D image array.
         */
{
        int i;
        uint8_t **image_array;

        image_array = malloc(SizeY * sizeof(uint8_t *));
        for (i = 0; i < SizeY; i++)
        {
                image_array[i] = malloc(SizeX * sizeof(uint8_t ));
                if(image_array[i] == NULL)
                {
                        fprintf(stderr, "Memory allocation for image_array[%d] failed.\n", i);
                        exit(EXIT_FAILURE);
                }
        }
        return image_array;
}

int free_2D_array(image_array, SizeY)

        /*
         * Frees memory allocated for 2D image array.
         */

        uint8_t **image_array;
        uint32_t SizeY;
{
        int i;

        for (i = 0; i < SizeY; i++)
        {
                free(image_array[i]);
        }
        return(1);
}

threshold_then_group() is the C++ function. test_array.txt is a text file with a 19X20 array:

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 255 255 255 0 0 0 0 0 0 255 255 255 255 255 0 0 0
0 0 0 255 255 255 0 0 0 0 0 0 0 255 255 255 0 0 0 0
0 0 255 255 255 255 0 0 0 0 0 0 0 0 255 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 255 255 0 0 0 0 0 0 0 0 255 0 0 0 0 0
0 0 0 255 255 255 255 255 0 0 0 0 255 255 255 255 0 0 0 0
0 0 0 0 255 255 255 255 255 0 0 255 255 255 0 0 0 0 0 0
0 0 0 0 0 0 255 255 255 255 255 255 255 0 0 0 0 0 0 0
0 0 0 0 0 0 0 255 255 255 255 255 255 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 255 255 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

opencv_grouping.h is the header file where I declare the C++ functions.

/* Header file for opencv_grouping.cpp.
 */

#ifndef CONNECTED_COMPONENTS_H
#define CONNECTED_COMPONENTS_H

#include <stdint.h>
#include <opencv2/opencv.hpp>

struct ConnectedComponentsResults
{
        int num_components;
        cv::Mat labels;
        cv::Mat stats;
        cv::Mat centroids;
};

void threshold_then_group(uint8_t **image_array, uint32_t SizeY, uint32_t SizeX, double threshold_value, ConnectedComponentsResults &results);

#endif

Then, the C++ functions in opencv_grouping.cpp are:

/* Grouping and centroiding implementation using OpenCV's
 * connectedComponentsWithStats().
 */

#include <stdint.h>
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstdlib>

#include <opencv2/opencv.hpp>
#include "opencv_grouping.h"

void threshold_then_group(uint8_t **image_array, uint32_t SizeY, uint32_t SizeX, double threshold_value, ConnectedComponentsResults &results)
{
        uint8_t *image_data = new uint8_t[SizeY * SizeX];
        double max_value=255.0;
        int i;
        int j;

        for (i=0; i<SizeY; i++)
        {
                for (j=0; j<SizeX; j++)
                {
                        image_data[i * SizeX + j] = image_array[i][j];
                }
        }

        cv::Mat image(SizeY, SizeX, CV_8U, image_data);

        cv::Mat binary;
        threshold(image, binary, threshold_value, max_value, cv::THRESH_BINARY);

        cv::Mat labels, stats, centroids;

        int num_components = cv::connectedComponentsWithStats(binary, results.labels, results.stats, results.centroids, 8, CV_32S);

        results.num_components = results.stats.rows - 1;

        delete[] image_data;
}

I am attempting to compile the code like this:

g++ `pkg-config --cflags opencv4` -c opencv_grouping.cpp
gcc `pkg-config --cflags opencv4` -c grouping_test_main.c
gcc opencv_test.o opencv_grouping.o -lstdc++ `pkg-config --libs opencv4` -o opencv_test2

opencv_grouping.cpp compiles just fine, but grouping_test_main.c fails. This is because opencv_grouping.h includes opencv2/opencv.hpp, and the error messages indicate that the files included in opencv.hpp must be compiled using a C++ compiler. I haven't tried to compile the main function using g++, but even if this somehow works, this isn't really a solution. My actual main function is a lot more complicated than what I've shown here, and it uses a lot of C libraries that I don't think would compile with g++.


问:
Need messages in single line from Slack Bot Webhook app
I'm using slackBot webhook curls to send messages to slack, but i see the message being spilled over to multiple lines.

Is there any way i can make them appear in single line.

Below one is the message coming from webhook but i am wishing to have it like the way its depicted in top message of the image.

I've already tired to use coded blocks as well but even that didnt help me much.


问:
playwright chrome extension opening in different browser
hey guys im using playwright to open chrome extension with chromium.
I'm launching the goto page as below and for some reason the url is opening in a different browser than where the chrome extension is loading. so basically in a new context.

any help would be appreciated.

```<code>browser_args = [
           ("--disable-extensions-except=" + extensionPath),
           ("--load-extension=" + extensionPath),
        ]
        browser = p.chromium.launch(
            headless=False,
            args=browser_args,
            executable_path="./chrome/chrome.exe",
            proxy=proxy
        )
        self.context = browser.new_context(
            user_agent=user_agent
        )
        self.context2 = browser.new_context()
        self.page2 = self.context2.new_page()
        self.page = self.context.new_page()
        self.page.set_default_timeout(timeout=6000000)
        try:
            self.page.goto('https://google.com')
</code>```

I tried launch_persistent_context but that didn't work for me either.

is there a way to force the chrome extension to load in the same browser context as in a new tab ?

thanks a lot !

Body:
hey guys im using playwright to open chrome extension with chromium.
I'm launching the goto page as below and for some reason the url is opening in a different browser than where the chrome extension is loading. so basically in a new context.

any help would be appreciated.

browser_args = [
           ("--disable-extensions-except=" + extensionPath),
           ("--load-extension=" + extensionPath),
        ]
        browser = p.chromium.launch(
            headless=False,
            args=browser_args,
            executable_path="./chrome/chrome.exe",
            proxy=proxy
        )
        self.context = browser.new_context(
            user_agent=user_agent
        )
        self.context2 = browser.new_context()
        self.page2 = self.context2.new_page()
        self.page = self.context.new_page()
        self.page.set_default_timeout(timeout=6000000)
        try:
            self.page.goto('https://google.com')

I tried launch_persistent_context but that didn't work for me either.

is there a way to force the chrome extension to load in the same browser context as in a new tab ?

thanks a lot !


问:
how to detect "go to" vs "back to" the fragment
My app use fragment to serve as pages.

I need to different things when i "go to" the page vs "back to" the page. But this both triggers onCreate life cycle for the fragment. How do I distinguish them?


问:
why "add" is ignored in plotting using "curve" function?
Sorry guys in advance if my question is trivial but I am new to R.
when I try to run the following chunk, the curves is plotted but I get the warning :'add' will be ignored as there is no existing plot.
and if I try to knit the whole document, it is interrupted with the following error: Error in plot.xy(xy.coords(x,y), type=type, ...) plot.new has not been called yet</p>
```<code>library(pwr)

occ <- function(type, conf.level=0.05) {
  n_levels <- c(2, 3, 4, 5, 10, 20, 50, 100)
  ty <- 0.8
  for (i in n_levels) {
    curve(1-pwr.t.test(i, x, type=type, sig.level=conf.level)$power, add=T,
        xlim=c(0,6),
        ylim=c(0,1),
        xlab="d",
        ylab="P(Tpe II error) or (1- Power)",
        main="Operative Characteristic curves for two samples T-test")

    tx <- pwr.t.test(i, power=1- ty, type=type, sig.level=conf.level)$d
    text(tx, ty, lab=i, col="red")
    ty <- ty - 0.1
  }
}

occ("two.sample", 0.01)
</code>```

Body:
Sorry guys in advance if my question is trivial but I am new to R.
when I try to run the following chunk, the curves is plotted but I get the warning :'add' will be ignored as there is no existing plot.
and if I try to knit the whole document, it is interrupted with the following error: Error in plot.xy(xy.coords(x,y), type=type, ...) plot.new has not been called yet

library(pwr)

occ <- function(type, conf.level=0.05) {
  n_levels <- c(2, 3, 4, 5, 10, 20, 50, 100)
  ty <- 0.8
  for (i in n_levels) {
    curve(1-pwr.t.test(i, x, type=type, sig.level=conf.level)$power, add=T,
        xlim=c(0,6),
        ylim=c(0,1),
        xlab="d",
        ylab="P(Tpe II error) or (1- Power)",
        main="Operative Characteristic curves for two samples T-test")

    tx <- pwr.t.test(i, power=1- ty, type=type, sig.level=conf.level)$d
    text(tx, ty, lab=i, col="red")
    ty <- ty - 0.1
  }
}

occ("two.sample", 0.01)


问:
Animate several properties of several views with Core Animation
I want to animate several properties of several subviews using Core Animations in Swift. I'm looking for a way to group the animations together and handle them as one, mainly to be able to synchronise them altogether and pause and resume all of them together, but also in order to avoid code duplication and make the code cleaner.

I tried to use other kind of animations, such as UIView.animate or UIViewPropertyAnimator, but neither of them fit my needs because they don't allow the customization needed for my case.

For now, I'm using CATransaction to ensure that the animation changes are committed to Core Animation at the same time:

CATransaction.begin()
CATransaction.setAnimationDuration(1.5)
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(controlPoints: 0.85, 0, 0.15, 1))

let opacityAnimation = CABasicAnimation(keyPath: "opacity")
opacityAnimation.fromValue = 0
opacityAnimation.toValue = 1.0
opacityAnimation.repeatCount = .infinity
opacityAnimation.autoreverses = true
self.lable.layer.add(beforeOpacityAnimation, forKey: "opacityAninmation")

let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
scaleAnimation.fromValue = 1.5
scaleAnimation.toValue = 1.0
scaleAnimation.repeatCount = .infinity
scaleAnimation.autoreverses = true
self.imageView.layer.add(targetImageScaleAnimation, forKey: "scaleAnimator")

CATransaction.commit()
```

So far so good. But now I want to be able to pause and resume all animations together. From what I see here, in order to achieve this one would need to iterate over all animated layers (e.g. self.lable.layer, self.imageView.layer) to modify their speed, timeOffset and beginTime properties (this is kinda dirty and nonatomic).

Is there a way to group these animations or refer to them as one in order to pause and resume them altogether?

If not, should I at least put these iterations over layers inside a CATransaction as well?

Body:
I want to animate several properties of several subviews using Core Animations in Swift. I'm looking for a way to group the animations together and handle them as one, mainly to be able to synchronise them altogether and pause and resume all of them together, but also in order to avoid code duplication and make the code cleaner.

I tried to use other kind of animations, such as UIView.animate or UIViewPropertyAnimator, but neither of them fit my needs because they don't allow the customization needed for my case.

For now, I'm using CATransaction to ensure that the animation changes are committed to Core Animation at the same time:

CATransaction.begin()
CATransaction.setAnimationDuration(1.5)
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(controlPoints: 0.85, 0, 0.15, 1))

let opacityAnimation = CABasicAnimation(keyPath: "opacity")
opacityAnimation.fromValue = 0
opacityAnimation.toValue = 1.0
opacityAnimation.repeatCount = .infinity
opacityAnimation.autoreverses = true
self.lable.layer.add(beforeOpacityAnimation, forKey: "opacityAninmation")

let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
scaleAnimation.fromValue = 1.5
scaleAnimation.toValue = 1.0
scaleAnimation.repeatCount = .infinity
scaleAnimation.autoreverses = true
self.imageView.layer.add(targetImageScaleAnimation, forKey: "scaleAnimator")

CATransaction.commit()

So far so good. But now I want to be able to pause and resume all animations together. From what I see here, in order to achieve this one would need to iterate over all animated layers (e.g. self.lable.layer, self.imageView.layer) to modify their speed, timeOffset and beginTime properties (this is kinda dirty and nonatomic).

Is there a way to group these animations or refer to them as one in order to pause and resume them altogether?

If not, should I at least put these iterations over layers inside a CATransaction as well?


问:
The system cannot find the file specified in sublime text
```<code>[WinError 2] The system cannot find the file specified
[cmd: ['py', '-u', 'C:\\Users\\Scorpion\\Desktop\\Facial Recognition Python\\program.py']]
[dir: C:\Users\Scorpion\Desktop\Facial Recognition Python]
[path: C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\dotnet\;C:\Program Files\Git\cmd;C:\Program Files\Go\bin;"C:\python35;";C:\Users\Scorpion\AppData\Local\Microsoft\WindowsApps;C:\Users\Scorpion\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\Scorpion\go\bin;C:\xampp\php;C:\Program Files\CMake\bin;]
[Finished]
</code>```

I am new to python and sublime text, I have written the whole program but it is not executed
Can somebody help!!

I am new to python and sublime text, I have written the whole program but it is not executed
Can somebody help!!

Body:
[WinError 2] The system cannot find the file specified
[cmd: ['py', '-u', 'C:\\Users\\Scorpion\\Desktop\\Facial Recognition Python\\program.py']]
[dir: C:\Users\Scorpion\Desktop\Facial Recognition Python]
[path: C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\dotnet\;C:\Program Files\Git\cmd;C:\Program Files\Go\bin;"C:\python35;";C:\Users\Scorpion\AppData\Local\Microsoft\WindowsApps;C:\Users\Scorpion\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\Scorpion\go\bin;C:\xampp\php;C:\Program Files\CMake\bin;]
[Finished]

I am new to python and sublime text, I have written the whole program but it is not executed
Can somebody help!!

I am new to python and sublime text, I have written the whole program but it is not executed
Can somebody help!!


问:
NextJS delete cookies and redirect from middleware
what I want to achieve is to delete 'accessToken' and 'refreshToken' cookies if both the accessToken and refreshToken are expired and then redirect to '/login' route.

This is my code now

// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { verifyAccessToken, verifyRefreshToken } from './utils/checkAuth';
import jwt_decode from "jwt-decode";
import { refreshAccessToken } from './utils/refreshToken';

interface JwtPayload {
  email: string
  sub: number
  iat: number
  exp: number
}

export async function middleware(req: NextRequest) {
    const accessToken = req.cookies.get('accessToken')?.value;
    const refreshToken = req.cookies.get('refreshToken')?.value;

    if(accessToken && refreshToken){
      const jwtPayload: JwtPayload = jwt_decode(accessToken);

      const validToken =
        accessToken &&
        (await verifyAccessToken(accessToken).catch((err) => {
          console.log(err);
        }));

      if(req.nextUrl.pathname.startsWith('/login') && !validToken){
        return
      }

      if((req.url.includes('/login') || req.url.includes('/register')) && validToken){
        return NextResponse.redirect(new URL('/login', req.url));
      }

      if(!validToken){
        try {
          const validRefreshToken =
            refreshToken &&
            (await verifyRefreshToken(refreshToken).catch((err) => {
              console.log(err);
            }));
          if(validRefreshToken){
            const newAccessToken = await refreshAccessToken(refreshToken, jwtPayload?.sub);
            console.log('GENERATED NEW ACCESS TOKEN', newAccessToken);
            // here I want to set accesToken cookie to newAccessToken
          } else {
            console.log('Refresh token expired');
            throw new Error('Refresh token expired')
          }
        } catch (error) {
          console.log('cookies should be deleted');
          return NextResponse.redirect(new URL('/login', req.url));
        }
      }
      console.log('TOKEN VALID', accessToken);
    } else {
      if(req.nextUrl.pathname.startsWith('/login')){
        return
      } else {
        return NextResponse.redirect(new URL('/login', req.url));
      }
    }
}

// See "Matching Paths" below to learn more
export const config = {
  matcher: ['/', '/login', '/register', '/jobs/:path*', '/profile'],
}```
</div>
</div>
</p>
<p>I found out that by doing this</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>const response = NextResponse.next()
response.cookies.delete('accessToken')
response.cookies.delete('refreshToken')</code>```

this will work but then for this to actually delete the cookies I need to return "response" from the middleware but I also want to redirect the user to "/login" and this does not happen if I return "response" instead of returning the "NextResponse.redirect(new URL('/login', req.url))"

How can I remove the cookies or set the cookies and then also redirect ?

Body:
what I want to achieve is to delete 'accessToken' and 'refreshToken' cookies if both the accessToken and refreshToken are expired and then redirect to '/login' route.

This is my code now

// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { verifyAccessToken, verifyRefreshToken } from './utils/checkAuth';
import jwt_decode from "jwt-decode";
import { refreshAccessToken } from './utils/refreshToken';

interface JwtPayload {
  email: string
  sub: number
  iat: number
  exp: number
}

export async function middleware(req: NextRequest) {
    const accessToken = req.cookies.get('accessToken')?.value;
    const refreshToken = req.cookies.get('refreshToken')?.value;

    if(accessToken && refreshToken){
      const jwtPayload: JwtPayload = jwt_decode(accessToken);

      const validToken =
        accessToken &&
        (await verifyAccessToken(accessToken).catch((err) => {
          console.log(err);
        }));

      if(req.nextUrl.pathname.startsWith('/login') && !validToken){
        return
      }

      if((req.url.includes('/login') || req.url.includes('/register')) && validToken){
        return NextResponse.redirect(new URL('/login', req.url));
      }

      if(!validToken){
        try {
          const validRefreshToken =
            refreshToken &&
            (await verifyRefreshToken(refreshToken).catch((err) => {
              console.log(err);
            }));
          if(validRefreshToken){
            const newAccessToken = await refreshAccessToken(refreshToken, jwtPayload?.sub);
            console.log('GENERATED NEW ACCESS TOKEN', newAccessToken);
            // here I want to set accesToken cookie to newAccessToken
          } else {
            console.log('Refresh token expired');
            throw new Error('Refresh token expired')
          }
        } catch (error) {
          console.log('cookies should be deleted');
          return NextResponse.redirect(new URL('/login', req.url));
        }
      }
      console.log('TOKEN VALID', accessToken);
    } else {
      if(req.nextUrl.pathname.startsWith('/login')){
        return
      } else {
        return NextResponse.redirect(new URL('/login', req.url));
      }
    }
}

// See "Matching Paths" below to learn more
export const config = {
  matcher: ['/', '/login', '/register', '/jobs/:path*', '/profile'],
}

I found out that by doing this

const response = NextResponse.next()
response.cookies.delete('accessToken')
response.cookies.delete('refreshToken')

this will work but then for this to actually delete the cookies I need to return "response" from the middleware but I also want to redirect the user to "/login" and this does not happen if I return "response" instead of returning the "NextResponse.redirect(new URL('/login', req.url))"

How can I remove the cookies or set the cookies and then also redirect ?


问:
AWS ec2Client socket timeout - can't connect through docker to aws services
I am trying to programmatically create a key pair with the AWS JS sdk. I am working within a docker container on an EC2 server. My aws credentials are correct as well as the region. After creating the client, I send keypair request with await client.send(command) with the client being the Ec2Client created the credentials, and the command being created by the CreateKeyPairCommand- after which i receive the following error Error [TimeoutError]: Socket timed out without establishing a connection within 1100 ms     at Timeout._onTimeout (/usr/src/app/node_modules/@aws-sdk/node-http-handler/dist-cjs/set-connection-timeout.js:12:38)     at listOnTimeout (node:internal/timers:564:17)     at process.processTimers (node:internal/timers:507:7) {   '$metadata': { attempts: 5, totalRetryDelay: 1029 } }

My hunch is that it is an issue with the ports and the way the sdk communicates with aws. Upon further research, I've come to see that aws communicates over ports 443 for HTTPS and 80 for HTTP, which are both exposed for my docker application both in the containers as well as the associated security group. I can ssh into the client and connect with the container, and run requests from postman through the container otherwise. It is only when the aws sdk tries to send a request that this networking error presents itself. If you have any ideas, let me know!


问:
Fetch different columns from different google sheets using Query
I am running into issues with a fairly simple QUERY statement in Google Spreadsheets. The goal is to get data (unique cells/values) from different sheets (same file). The example shows that I am using the cell reference from two sheets.

```<code>=QUERY({TeamScaled!I:I,TeamRx!M:M, TeamLeadScaled!I:I, TeamLeadScaled!M:M},)
</code>```

The result: data gets distributed in 4 (E,F, G, H) columns and not 2 (E & F). How can I bring everything to E and F? I tried separating sheets by a semi-column but that wipes off the data.

Sample Image

Body:
I am running into issues with a fairly simple QUERY statement in Google Spreadsheets. The goal is to get data (unique cells/values) from different sheets (same file). The example shows that I am using the cell reference from two sheets.

=QUERY({TeamScaled!I:I,TeamRx!M:M, TeamLeadScaled!I:I, TeamLeadScaled!M:M},)

The result: data gets distributed in 4 (E,F, G, H) columns and not 2 (E & F). How can I bring everything to E and F? I tried separating sheets by a semi-column but that wipes off the data.

Sample Image


问:
Err in $A.getCallback()[Err during LWC component connect phase:[Cannot read properties of undefined (reading 'name')]]Failing descriptor: ltng:outApp
ERRORS

•This page has an error. You might just need to refresh it. Error in $A.getCallback() [Error during LWC component connect phase: [Cannot read properties of undefined (reading 'name')]] Failing descriptor: {ltng:outApp}
•No component definition for c:b2bBuildToPar in the client registry - for best performance add <aura:dependency resource="c:b2bBuildToPar"/> to your extension of c:b2b_BuildToParApp.
o The error that it’s throwing doesn’t make sense because the <aura:dependency resource="c:b2bBuildToPar"/> is inside of the b2b_BuildToParApp.

<aura:application access="GLOBAL" extends="ltng:outApp" description="b2b_BuildToParApp">

-->

-->

```<code><aura:dependency resource="c:b2bBuildToPar"/>
</code>```

</aura:application>

•SecureElement does not allow access to charset

I'm trying to debug an issue we are having on our storefront in B2B commerce. We have a build to par page that you can add and remove products from. We have a CSR flow that Allows a user to access a contacts storefront with their user credentials. Then we have a User Experience flow that allows users to imitate contacts user and access the storefront as if they were that user. User Experience works fine, but when using the CSR flow and adding or deleting products from the build to par list in that instance we are given an error with the above logs/warnings. I'm not familiar with LWC and could use help breaking down what these errors mean and hopefully Identifying the issue.

Body:
ERRORS

•This page has an error. You might just need to refresh it. Error in $A.getCallback() [Error during LWC component connect phase: [Cannot read properties of undefined (reading 'name')]] Failing descriptor: {ltng:outApp}
•No component definition for c:b2bBuildToPar in the client registry - for best performance add <aura:dependency resource="c:b2bBuildToPar"/> to your extension of c:b2b_BuildToParApp.
o The error that it’s throwing doesn’t make sense because the <aura:dependency resource="c:b2bBuildToPar"/> is inside of the b2b_BuildToParApp.

<aura:application access="GLOBAL" extends="ltng:outApp" description="b2b_BuildToParApp">

-->

-->

<aura:dependency resource="c:b2bBuildToPar"/>

</aura:application>

•SecureElement does not allow access to charset

I'm trying to debug an issue we are having on our storefront in B2B commerce. We have a build to par page that you can add and remove products from. We have a CSR flow that Allows a user to access a contacts storefront with their user credentials. Then we have a User Experience flow that allows users to imitate contacts user and access the storefront as if they were that user. User Experience works fine, but when using the CSR flow and adding or deleting products from the build to par list in that instance we are given an error with the above logs/warnings. I'm not familiar with LWC and could use help breaking down what these errors mean and hopefully Identifying the issue.


问:
Github Actions fails in qa but passes in dev
Built a cloudformation stack and I want to deploy it using Github Actions. In the .yml, there are options to build in dev or qa. Running the script in dev passes. Running the script in qa fails and gives me this error

botocore.exceptions.ClientError: An error occurred (ValidationError) when calling the CreateStack operation: Parameters: [GroupId] must have values

I'm not sure why. Any ideas?

I tried adding GroupId to the script, but then different errors pop up stating that Region and Environment are not in the template, which is false.