问:
Get string from cotoutine
I'm confronted to a very simple issue, I'm trying to get a sid from a volley request, i've been able to implement a coroutine but i can't extract my data from the GlobalScope.launch() function, maybe it's not the great way to execute it I don't know, heres is my code I hope someone can help thanks.

```<code>GlobalScope.launch() {
    data = getData()
    println(data)
}
</code>```

And here's my coroutines and my getData function

```<code>suspend fun getData() = suspendCoroutine<String> { cont ->
    val queue = Volley.newRequestQueue(this)
    val url = "http://www.google.com/"

    val stringRequest = StringRequest(Request.Method.GET, url,
        { response ->
            cont.resume("Response is: ${response.substring(0, 500)}")
        },
        { cont.resume("Something went wrong!") })

    queue.add(stringRequest)
}
interface VolleyStringResponse {
    fun onSuccess(response: String?)
}
</code>```

答:
Simple answer is: you can't.

This is all about waiting for the result. There are several ways to wait for something, the most common are: thread blocking, suspending (coroutines), callbacks and futures/premises. You already converted waiting through callbacks to suspending - which is good, because suspending is usually easier to handle than callbacks.

But if you think about something like this:

fun onClick() {
    val data = getData()
    doSomething(data)
}
```
<p>Then this is impossible, at least not without blocking the thread which we should avoid. This is because non-suspending function can't wait in any other way than by blocking the thread.</p>
<p>Usually, we enclose a whole operation in a coroutine and inside it we execute operations sequentially, for example:</p>
<pre class="lang-kotlin prettyprint-override"><code>fun onClick() = lifecycleScope.launch {
    val data = getData()
    doSomething(data)
}
</code>```

So instead of extracting the data to outside of the launch(), we move the subsequent step also into launch().

Also, we should avoid using GlobalScope. On Android you could/should usually use lifecycleScope or viewModelScope instead.

Title: Get string from cotoutine

Body:
I'm confronted to a very simple issue, I'm trying to get a sid from a volley request, i've been able to implement a coroutine but i can't extract my data from the GlobalScope.launch() function, maybe it's not the great way to execute it I don't know, heres is my code I hope someone can help thanks.

GlobalScope.launch() {
    data = getData()
    println(data)
}

And here's my coroutines and my getData function

suspend fun getData() = suspendCoroutine<String> { cont ->
    val queue = Volley.newRequestQueue(this)
    val url = "http://www.google.com/"

    val stringRequest = StringRequest(Request.Method.GET, url,
        { response ->
            cont.resume("Response is: ${response.substring(0, 500)}")
        },
        { cont.resume("Something went wrong!") })

    queue.add(stringRequest)
}
interface VolleyStringResponse {
    fun onSuccess(response: String?)
}

Body:
Simple answer is: you can't.

This is all about waiting for the result. There are several ways to wait for something, the most common are: thread blocking, suspending (coroutines), callbacks and futures/premises. You already converted waiting through callbacks to suspending - which is good, because suspending is usually easier to handle than callbacks.

But if you think about something like this:

fun onClick() {
    val data = getData()
    doSomething(data)
}

Then this is impossible, at least not without blocking the thread which we should avoid. This is because non-suspending function can't wait in any other way than by blocking the thread.

Usually, we enclose a whole operation in a coroutine and inside it we execute operations sequentially, for example:

fun onClick() = lifecycleScope.launch {
    val data = getData()
    doSomething(data)
}

So instead of extracting the data to outside of the launch(), we move the subsequent step also into launch().

Also, we should avoid using GlobalScope. On Android you could/should usually use lifecycleScope or viewModelScope instead.


来源: stackexchange

问:
Conan + cmake + boost python
I have just started using conan from my cmake files to download and build dependencies - very convenient. I have tried using it also for Boost, but the default conanfile for boost does not seem to build boost python which I need. My current setup looks like:

```<code>conan_cmake_configure(REQUIRES
  fmt/8.0.1
  boost/1.75.0
  eigen/3.4.0
  GENERATORS cmake_find_package)

conan_cmake_autodetect(settings)

conan_cmake_install(PATH_OR_REFERENCE .
  BUILD missing
  REMOTE conancenter
  SETTINGS ${settings})

find_package(Eigen3 REQUIRED)
find_package(Boost COMPONENTS Python) // Approx syntax
...
</code>```

and this fails because the Boost python package is not available. I guess I can edit the conan_make_configures() command to make sure boost Python is built?

答:
you can use the OPTIONS variable of conan_cmake_configure:

```<code>conan_cmake_configure(REQUIRES
  fmt/8.0.1
  boost/1.75.0
  eigen/3.4.0
  GENERATORS cmake_find_package
  OPTIONS boost:without_python=False
)
</code>```

See: https://github.com/conan-io/conan_cmake_configure

You can find all available options for boost package at: boost C/C++ Package - JFrog ConanCenter

[Edit 1]: Use of a conanfile with cmake-conan

You can also create a conanfile.txt to manage your dependencies:

```<code>[requires]
fmt/8.0.1
boost/1.75.0
eigen/3.4.0

[options]
boost:without_python=False

[generators]
cmake_find_package
cmake_paths
</code>```

And call conan_cmake_run as follows:

```<code>conan_cmake_autodetect(settings)

conan_cmake_run(
        CONANFILE conanfile.txt
        BASIC_SETUP CMAKE_TARGETS
        BUILD missing
        SETTINGS ${settings}
)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Conan + cmake + boost python

Body:
I have just started using conan from my cmake files to download and build dependencies - very convenient. I have tried using it also for Boost, but the default conanfile for boost does not seem to build boost python which I need. My current setup looks like:

conan_cmake_configure(REQUIRES
  fmt/8.0.1
  boost/1.75.0
  eigen/3.4.0
  GENERATORS cmake_find_package)

conan_cmake_autodetect(settings)

conan_cmake_install(PATH_OR_REFERENCE .
  BUILD missing
  REMOTE conancenter
  SETTINGS ${settings})

find_package(Eigen3 REQUIRED)
find_package(Boost COMPONENTS Python) // Approx syntax
...

and this fails because the Boost python package is not available. I guess I can edit the conan_make_configures() command to make sure boost Python is built?

Body:
you can use the OPTIONS variable of conan_cmake_configure:

conan_cmake_configure(REQUIRES
  fmt/8.0.1
  boost/1.75.0
  eigen/3.4.0
  GENERATORS cmake_find_package
  OPTIONS boost:without_python=False
)

See: https://github.com/conan-io/conan_cmake_configure

You can find all available options for boost package at: boost C/C++ Package - JFrog ConanCenter

[Edit 1]: Use of a conanfile with cmake-conan

You can also create a conanfile.txt to manage your dependencies:

[requires]
fmt/8.0.1
boost/1.75.0
eigen/3.4.0

[options]
boost:without_python=False

[generators]
cmake_find_package
cmake_paths

And call conan_cmake_run as follows:

conan_cmake_autodetect(settings)

conan_cmake_run(
        CONANFILE conanfile.txt
        BASIC_SETUP CMAKE_TARGETS
        BUILD missing
        SETTINGS ${settings}
)


问:
Vue 3 and Vuetify 3 Alpha: ValidationError: progress plugin invalid options
After creating a Vue 3 project, adding Vuetify 3 Alpha, when I run "npm run serve", this is the error I get. I tried without adding Vuetify 3 Alpha and the Vue 3 project starts fine, it's just after adding the Vuetify that the error appears.</p>
```<code>INFO  Starting development server...
ERROR  ValidationError: Progress Plugin Invalid Options

    options should NOT have additional properties
    options should NOT have additional properties
    options should NOT have additional properties
    options should pass "instanceof" keyword validation
    options should match exactly one schema in oneOf

ValidationError: Progress Plugin Invalid Options

options should NOT have additional properties
options should NOT have additional properties
options should NOT have additional properties
options should pass "instanceof" keyword validation
options should match exactly one schema in oneOf

at validateOptions (c:\wamp64\www\vuetify-3\node_modules\webpack\node_modules\schema-utils\src\validateOptions.js:32:11)
at new ProgressPlugin (c:\wamp64\www\vuetify-3\node_modules\webpack\lib\ProgressPlugin.js:62:3)
at new Progress (c:\wamp64\www\vuetify-3\node_modules\progress-webpack-plugin\index.js:25:21)
at new progressPlugin (c:\wamp64\www\vuetify-3\node_modules\progress-webpack-plugin\index.js:127:10)
at c:\wamp64\www\vuetify-3\node_modules\webpack-chain\src\Plugin.js:14:18
at Object.toConfig (c:\wamp64\www\vuetify-3\node_modules\webpack-chain\src\Plugin.js:78:22)
at c:\wamp64\www\vuetify-3\node_modules\webpack-chain\src\Config.js:129:63
at Array.map (<anonymous>)
at module.exports.toConfig (c:\wamp64\www\vuetify-3\node_modules\webpack-chain\src\Config.js:129:40)
at Service.resolveWebpackConfig (c:\wamp64\www\vuetify-3\node_modules\@vue\cli-service\lib\Service.js:261:34)
</code>```

答: @Mishka's solution worked for me, but I did npm update --force to make it working.

Body:
After creating a Vue 3 project, adding Vuetify 3 Alpha, when I run "npm run serve", this is the error I get. I tried without adding Vuetify 3 Alpha and the Vue 3 project starts fine, it's just after adding the Vuetify that the error appears.

INFO  Starting development server...
ERROR  ValidationError: Progress Plugin Invalid Options

    options should NOT have additional properties
    options should NOT have additional properties
    options should NOT have additional properties
    options should pass "instanceof" keyword validation
    options should match exactly one schema in oneOf

ValidationError: Progress Plugin Invalid Options

options should NOT have additional properties
options should NOT have additional properties
options should NOT have additional properties
options should pass "instanceof" keyword validation
options should match exactly one schema in oneOf

at validateOptions (c:\wamp64\www\vuetify-3\node_modules\webpack\node_modules\schema-utils\src\validateOptions.js:32:11)
at new ProgressPlugin (c:\wamp64\www\vuetify-3\node_modules\webpack\lib\ProgressPlugin.js:62:3)
at new Progress (c:\wamp64\www\vuetify-3\node_modules\progress-webpack-plugin\index.js:25:21)
at new progressPlugin (c:\wamp64\www\vuetify-3\node_modules\progress-webpack-plugin\index.js:127:10)
at c:\wamp64\www\vuetify-3\node_modules\webpack-chain\src\Plugin.js:14:18
at Object.toConfig (c:\wamp64\www\vuetify-3\node_modules\webpack-chain\src\Plugin.js:78:22)
at c:\wamp64\www\vuetify-3\node_modules\webpack-chain\src\Config.js:129:63
at Array.map (<anonymous>)
at module.exports.toConfig (c:\wamp64\www\vuetify-3\node_modules\webpack-chain\src\Config.js:129:40)
at Service.resolveWebpackConfig (c:\wamp64\www\vuetify-3\node_modules\@vue\cli-service\lib\Service.js:261:34)


问:
Calling a Java program from a batch file with parameters containing Danish characters
I'm calling a java program from a batch file with parameters to send an email, works fine except that the program won't accept Danish charters like Æ, Ø, Å, (see fromCompanyName).

Batch file:

set host="smtp.xyz.com"
set username="foo@bar.dk"
set password="Password42"
set FromCompanyName="Testing æøå"
set from="foo@bar.dk"
```

So right now the 'From' in the email looks like this: Testing +å+ÿ+à

If I use echo æøå in batch file output: ├ª├©├Ñ

If I use echo æøå in a command prompt output: æøå

答:
Try to use a text editor which is able to create unicode files
and make sure to create your batch file using this editor.

I assume (set) you are using a Windows operating system?
You may check out Notepad++.

Open your Batch file and change the encoding using:

```<code>Encoding > Convert to UTF-8 (option without BOM)
</code>```

Body:
I'm calling a java program from a batch file with parameters to send an email, works fine except that the program won't accept Danish charters like Æ, Ø, Å, (see fromCompanyName).

Batch file:

set host="smtp.xyz.com"
set username="foo@bar.dk"
set password="Password42"
set FromCompanyName="Testing æøå"
set from="foo@bar.dk"

So right now the 'From' in the email looks like this: Testing +å+ÿ+à

If I use echo æøå in batch file output: ├ª├©├Ñ

If I use echo æøå in a command prompt output: æøå

Body:
Try to use a text editor which is able to create unicode files
and make sure to create your batch file using this editor.

I assume (set) you are using a Windows operating system?
You may check out Notepad++.

Open your Batch file and change the encoding using:

Encoding > Convert to UTF-8 (option without BOM)


问:
How to install VS Code in Alpine Linux
I have an operating environment that is Alpine linux only and I need to install VS Code. How can VS Code be run on Alpine Linux?</p>

答:
Dockerfile:

```<code>FROM node:14.19.0-alpine
RUN set -x \
    && sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories \
    && apk upgrade \
    && apk --no-cache add alpine-sdk bash libstdc++ libc6-compat \
    && npm config set python python3
RUN git clone --recursive https://github.com/cdr/code-server.git
RUN cd code-server
RUN yarn global add code-server

ENV PASSWORD=changeme
ENTRYPOINT code-server --bind-addr 0:8443

</code>```

Commands:

```<code>docker build . -t vscode
docker run -d -e PASSWORD=111111 -p8443:8443 vscode:latest
http://hostname:8443
</code>```

Title: How to install VS Code in Alpine Linux

Body:
Dockerfile:

FROM node:14.19.0-alpine
RUN set -x \
    && sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories \
    && apk upgrade \
    && apk --no-cache add alpine-sdk bash libstdc++ libc6-compat \
    && npm config set python python3
RUN git clone --recursive https://github.com/cdr/code-server.git
RUN cd code-server
RUN yarn global add code-server

ENV PASSWORD=changeme
ENTRYPOINT code-server --bind-addr 0:8443

Commands:

docker build . -t vscode
docker run -d -e PASSWORD=111111 -p8443:8443 vscode:latest
http://hostname:8443


问:
Does `git add -p` check one-to-one correspondence only MetaHead but not sentences after HunkHeader?
I'm digging into Git code, however, there is mystery.

When I look into https://github.com/git/git/blob/master/add-patch.c#L440-L455, I thought git add -p compares below input and output.

# input
git diff-files -p --no-color

# output
git diff-files -p --color | {something you defined in interactive.diffFilter}
```
<p>However, it seems they compare only MetaHead(before @@), and doesn't compare after HunkHeaders(@@ and after @@).</p>
<pre class="lang-sh prettyprint-override"><code># input
❯ git diff-files --no-color -p
diff --git a/src/options/set.rs b/src/options/set.rs
index a9ca6be..1a32706 100644
--- a/src/options/set.rs
+++ b/src/options/set.rs
@@ -196,7 +196,7 @@ pub fn set_options(
         opt.commit_style = "raw".to_string();
         opt.hunk_header_style = "raw".to_string();
         opt.hunk_header_decoration_style = "none".to_string();
-    }
+    } //aa
 }

# output
❯ git diff-files --color -p | delta --color-only
diff --git a/src/options/set.rs b/src/options/set.rs
index a9ca6be..1a32706 100644
--- a/src/options/set.rs
+++ b/src/options/set.rs
@@ -196,7 +196,7 @@ pub fn set_options( hogehogetest
196 ⋮196 │         opt.commit_style = "raw".to_string();
197 ⋮197 │         opt.hunk_header_style = "raw".to_string();
198 ⋮198 │         opt.hunk_header_decoration_style = "none".to_string();
199 ⋮    │-    }
    ⋮199 │+    } //aa
200 ⋮200 │ }
</code>```

As you see, it's completely different, however, git -c 'interactive.diffFilter=delta --color-only' add -p works.

If I edit output like,

diff --git a/src/options/set.rs b/src/options/set.rs
index a9ca6be..1a32706 100644
--- a/src/options/set.rs
+++ b/src/options/set.rs
   ### <- insert break line
@@ -196,7 +196,7 @@ pub fn set_options(
         opt.commit_style = "raw".to_string();
         opt.hunk_header_style = "raw".to_string();
         opt.hunk_header_decoration_style = "none".to_string();
-    }
+    } //aa
 }
```
<p><code>git add -p</code> now errors like below as expected.</p>
```fatal: mismatched output from interactive.diffFilter
hint: Your filter must maintain a one-to-one correspondence
hint: between its input and output lines.
```

I am really curious, why? The Git code I looked for is wrong...?

答:
Note that the code changed again for "git add -p"(man) (rewritten in C): it had regressed hunk splitting in some cases, which has been corrected with Git 2.36 (Q2 2022).

See commit 7008ddc, commit d16632f (11 Jan 2022) by Phillip Wood (phillipwood).

(Merged by Junio C Hamano -- gitster -- in commit ec4f70e, 09 Feb 2022)

builtin add -p: fix hunk splitting

Reproted-by: SZEDER Gábor

Signed-off-by: Phillip Wood

The C reimplementation of "add -p" fails to split the last hunk in a file if hunk ends with an addition or deletion without any post context line unless it is the last file to be processed.

To determine whether a hunk can be split a counter is incremented each time a context line follows an insertion or deletion.

If at the end of the hunk the value of this counter is greater than one then the hunk can be split into that number of smaller hunks.

If the last hunk in a file ends with an insertion or deletion then there is no following context line and the counter will not be incremented.

This case is already handled at the end of the loop where counter is incremented if the last hunk ended with an insertion or deletion.

Unfortunately there is no similar check between files (likely because the perl version only ever parses one diff at a time).

Fix this by checking if the last hunk ended with an insertion or deletion when we see the diff header of a new file and extend the existing regression test.

Body:
I'm digging into Git code, however, there is mystery.

When I look into https://github.com/git/git/blob/master/add-patch.c#L440-L455, I thought git add -p compares below input and output.

# input
git diff-files -p --no-color

# output
git diff-files -p --color | {something you defined in interactive.diffFilter}

However, it seems they compare only MetaHead(before @@), and doesn't compare after HunkHeaders(@@ and after @@).

# input
❯ git diff-files --no-color -p
diff --git a/src/options/set.rs b/src/options/set.rs
index a9ca6be..1a32706 100644
--- a/src/options/set.rs
+++ b/src/options/set.rs
@@ -196,7 +196,7 @@ pub fn set_options(
         opt.commit_style = "raw".to_string();
         opt.hunk_header_style = "raw".to_string();
         opt.hunk_header_decoration_style = "none".to_string();
-    }
+    } //aa
 }

# output
❯ git diff-files --color -p | delta --color-only
diff --git a/src/options/set.rs b/src/options/set.rs
index a9ca6be..1a32706 100644
--- a/src/options/set.rs
+++ b/src/options/set.rs
@@ -196,7 +196,7 @@ pub fn set_options( hogehogetest
196 ⋮196 │         opt.commit_style = "raw".to_string();
197 ⋮197 │         opt.hunk_header_style = "raw".to_string();
198 ⋮198 │         opt.hunk_header_decoration_style = "none".to_string();
199 ⋮    │-    }
    ⋮199 │+    } //aa
200 ⋮200 │ }

As you see, it's completely different, however, git -c 'interactive.diffFilter=delta --color-only' add -p works.

If I edit output like,

diff --git a/src/options/set.rs b/src/options/set.rs
index a9ca6be..1a32706 100644
--- a/src/options/set.rs
+++ b/src/options/set.rs
   ### <- insert break line
@@ -196,7 +196,7 @@ pub fn set_options(
         opt.commit_style = "raw".to_string();
         opt.hunk_header_style = "raw".to_string();
         opt.hunk_header_decoration_style = "none".to_string();
-    }
+    } //aa
 }

git add -p now errors like below as expected.

fatal: mismatched output from interactive.diffFilter
hint: Your filter must maintain a one-to-one correspondence
hint: between its input and output lines.

I am really curious, why? The Git code I looked for is wrong...?


问:
How can I check in my bashrc if an alias was already set
How can I check in my .bashrc if an alias was already set.

When I source a .bashrc file, which has a function name, say fun, and my current environment has an alias as fun also.

I tried unalias fun, but that will give me an error that fun not found when my environment wont have that alias already.

So in my .bashrc, in my fun function I want to check if alias was set, then unalias that.

答:
I use something similar to @noonex's proposal, but can handle empty aliases with :

```<code>[[ -v BASH_ALIASES[foo] ]] && unalias foo
</code>```

This will work even if foo alias exists but is empty :

```<code>alias foo=
[[ ${BASH_ALIASES[foo]} ]] && echo unalias1
[[ -v BASH_ALIASES[foo] ]] && echo unalias2
</code>```

Output :

```<code>unalias2
</code>```

Would you need a function like @codeforester's solution, you should change ${BASH_ALIASES[$alias_name]} accordingly.

Body:
I use something similar to @noonex's proposal, but can handle empty aliases with :

[[ -v BASH_ALIASES[foo] ]] && unalias foo

This will work even if foo alias exists but is empty :

alias foo=
[[ ${BASH_ALIASES[foo]} ]] && echo unalias1
[[ -v BASH_ALIASES[foo] ]] && echo unalias2

Output :

unalias2

Would you need a function like @codeforester's solution, you should change ${BASH_ALIASES[$alias_name]} accordingly.


问:
Can I override u-strings (u'example') in Python 2?
In debugging upgrading to Python 3, it would be useful to be able to override the u'' string prefix to call my own function or replace with a non-u string.

I've tried things like unichr = chr which is useful for my debugging but doesn't accomplish the above.

module.uprefix = str is the type of solution I'm looking for.

答:
You basically can't; as others have noted in the comments, the u-prefix is handled very early, well before anything where an in-code assignment would take effect.

About the best you could do is use ast.parse to read a module on disk (without importing it) and find all the u'' strings; it distinguishes the prefixes. That would help you find them in a Python-aware way, more reliably than just searching for u' and u", but the difference probably wouldn't be large, especially if you search with word boundaries (regex \bu['"]). Unless you somehow have a lot of u' and u" in your program that aren't the prefixes?

```<code>>>> ast.dump(ast.parse('"abc"', mode='eval'))
"Expression(body=Constant(value='abc', kind=None))"
>>> ast.dump(ast.parse('u"abc"', mode='eval'))
"Expression(body=Constant(value='abc', kind='u'))"
</code>```

Per the comments, what are you trying to do? I've migrated a lot of code from Python 2 to Python 3 and never needed this... There may be a different way to achieve the same goal?

Body:
You basically can't; as others have noted in the comments, the u-prefix is handled very early, well before anything where an in-code assignment would take effect.

About the best you could do is use ast.parse to read a module on disk (without importing it) and find all the u'' strings; it distinguishes the prefixes. That would help you find them in a Python-aware way, more reliably than just searching for u' and u", but the difference probably wouldn't be large, especially if you search with word boundaries (regex \bu['"]). Unless you somehow have a lot of u' and u" in your program that aren't the prefixes?

>>> ast.dump(ast.parse('"abc"', mode='eval'))
"Expression(body=Constant(value='abc', kind=None))"
>>> ast.dump(ast.parse('u"abc"', mode='eval'))
"Expression(body=Constant(value='abc', kind='u'))"

Per the comments, what are you trying to do? I've migrated a lot of code from Python 2 to Python 3 and never needed this... There may be a different way to achieve the same goal?


问:
Rails custom mail relay address
I am creating a rails app where I want to mask a customer's email address by providing them with a dummy one. Similar to Apples Private Relay. So for example, if a user is currently has an account whose email is johndoe@example.com, I would like to create an email similar to fakeemail123@example.com. However, I still want fakeemail123@example.com to be able to reach johndoe@example.com. How can I achieve this?

答:
Since rails 6 you can use Action Mailbox for this.

If your rails version is lower than 6 consider upgrading or otherwise you'll need to host a mail server on your own. Postfix is a good choice and somebody shared a sample configuration here.

Title: Rails custom mail relay address


问:
Perl: How to test if any value (even zero) has been assigned to a hash key
Is there a correct way of testing if a particular hash key has already been assigned any value, even if this value is zero? I have been working with a statement like this:

```<code>%hash=();
$hash{a}=1;
$hash{b}=0;
if($hash{$key}) { do something }
</code>```

but this gives the same result for keys that have neven been touched and those that have been assigned the value 0 (e.g. both $hash{b} and $hash{c} evaluate as 'false'). Is there a way of telling the difference between those two ?

答:
See perldoc -f defined and perldoc -f exists:

```<code>my %hash = (foo => 0, bar => undef);

print defined $hash{foo}; # true
print defined $hash{bar}; # false
print exists $hash{bar};  # true
print exists $hash{baz};  # false

delete $hash{bar};
print exists $hash{bar};  # false
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there a correct way of testing if a particular hash key has already been assigned any value, even if this value is zero? I have been working with a statement like this:

%hash=();
$hash{a}=1;
$hash{b}=0;
if($hash{$key}) { do something }

but this gives the same result for keys that have neven been touched and those that have been assigned the value 0 (e.g. both $hash{b} and $hash{c} evaluate as 'false'). Is there a way of telling the difference between those two ?

Body:
See perldoc -f defined and perldoc -f exists:

my %hash = (foo => 0, bar => undef);

print defined $hash{foo}; # true
print defined $hash{bar}; # false
print exists $hash{bar};  # true
print exists $hash{baz};  # false

delete $hash{bar};
print exists $hash{bar};  # false


问:
Builder.put can only be called from within the same library group (groupId=androidx.work)
When i am using WorkManager and I'm trying to pass some object to it

```<code>Data data = new Data.Builder().put("passstring",object).build();
</code>```

getting me Builder.put can only be called from within the same library group (groupId=androidx.work) error

答:
You can use workDataOf() method. Just make sure you pass Pairs of data
eg.</p>
```<code>workDataOf(Pair("param_name", "data"))
</code>```

Body:
When i am using WorkManager and I'm trying to pass some object to it

Data data = new Data.Builder().put("passstring",object).build();

getting me Builder.put can only be called from within the same library group (groupId=androidx.work) error

Body:
You can use workDataOf() method. Just make sure you pass Pairs of data
eg.

workDataOf(Pair("param_name", "data"))


问:
Python paste text copied to clipboard on Android
Is there any way to paste the copied text from clipboard on android using python?
Pyperclip and tkinter doesn't work, so is there maybe a way to do this with kivy or something?</p>

答:
I was able to solve this by using kivy (Kivy 2.0 only supports Python 2.7 to 3.9 at the moment, so make sure your Python version is compatible. Read more about installing kivy here: Installing Kivy). There is module for this, called Clipboard, and it can paste text from the users Clipboard.

```<code>#:import Clipboard kivy.core.clipboard.Clipboard

Button:
    on_release:
        self.text = Clipboard.paste()
        Clipboard.copy('Data')
</code>```

Body:
I was able to solve this by using kivy (Kivy 2.0 only supports Python 2.7 to 3.9 at the moment, so make sure your Python version is compatible. Read more about installing kivy here: Installing Kivy). There is module for this, called Clipboard, and it can paste text from the users Clipboard.

#:import Clipboard kivy.core.clipboard.Clipboard

Button:
    on_release:
        self.text = Clipboard.paste()
        Clipboard.copy('Data')


问:
Running Apache HOP generated jar file over remote Apache Flink (org.apache.beam.runners.core.construction.SerializablePipelineOptions)
My question is about running Apache HOP generated jar file over remote Apache Flink.

We are facing a problem with Java Serial version UID. We guess that configuration of Apache Beam serialized file’s serial version uid doesn’t match with the one at flink cluster.

How could we overcome this problem, we tried using same JDK implementations over the flink server and local machine (which generates the jar).

Recompiling the Beam Project, with specific serialversionuid’s , might be a solution, but we dont want to use this approach, because it might cause side-effects.

Could you please support us with an alternative solution

Thanks.

enter image description here

enter image description here

enter image description here

答:
We have received multiple issues around running things on Spark and Flink.
A step-by-step guide was created to run the samples.

In these samples we use Flink 1.13.5 (same as your version)

If the samples work on your cluster but your current pipeline does not it is also possible that one of the specific transforms you are using are causing the issue, if this is the case can you provide us with a sample pipeline to reproduce the issue so we can have a closer look.

Feel free to reach out to us using our mailinglists.

Cheers,

Hans


问:
Does anyone know nay fix for this error (TypeError: Cannot assign to read only property 'map' of object '#<QueryCursor>'
In local working fine but when i deployed on digital ocean Kubernetes server then showing error. please help....

答:
Downgrade node version to 17.4

nvm ls-remote

nvm install 17.4.*

nvm use 17.4


问:
Drawing outside content insets with drawGlyphsForGlyphRange
I'm trying to show some extra symbols next to lines in NSTextView, based on text attributes.

I have successfully subclassed NSLayoutManager, but it seems that layout manager can't draw outside the area set by textContainerInset.

Because my text view can potentially have a very long strings, I'm hoping to keep the drawing connected to displaying glyphs. Is there a way to trick the layout manager to be able to draw inside the content insets — or is there another method I use instead of drawGlyphsForGlyphRange?

I have tried calling super before and after drawing, as well as storing and not storing graphics state. I also attempted setDrawsOutsideLineFragment:YES for the glyphs, but with no luck.

Things like Xcode editor itself uses change markers, so I know that this is somehow doable, but it's very possible I'm looking from the wrong place.

My drawing method, simplified:

- (void)drawGlyphsForGlyphRange:(NSRange)glyphsToShow atPoint:(NSPoint)origin {
    [super drawGlyphsForGlyphRange:glyphsToShow atPoint:origin];

    NSTextStorage *textStorage = self.textStorage;
    NSTextContainer *textContainer = self.textContainers[0];

    NSRange glyphRange = glyphsToShow;
    NSSize offset = self.textContainers.firstObject.textView.textContainerInset;

    while (glyphRange.length > 0) {
        NSRange charRange = [self characterRangeForGlyphRange:glyphRange actualGlyphRange:NULL], attributeCharRange, attributeGlyphRange;

        id attribute = [textStorage attribute:@"Revision" atIndex:charRange.location longestEffectiveRange:&attributeCharRange inRange:charRange];
        attributeGlyphRange = [self glyphRangeForCharacterRange:attributeCharRange actualCharacterRange:NULL];
        attributeGlyphRange = NSIntersectionRange(attributeGlyphRange, glyphRange);

        if (attribute != nil) {
            [NSGraphicsContext saveGraphicsState];

            NSRect boundingRect = [self boundingRectForGlyphRange:attributeGlyphRange
                                                  inTextContainer:textContainer];

            // Find the top of the revision
            NSPoint point = NSMakePoint(offset.width - 20, offset.height + boundingRect.origin.y + 1.0);

            NSString *marker = @"*";

            [marker drawAtPoint:point withAttributes:@{
                NSForegroundColorAttributeName: NSColor.blackColor;
            }];

            [NSGraphicsContext restoreGraphicsState];
        }

        glyphRange.length = NSMaxRange(glyphRange) - NSMaxRange(attributeGlyphRange);
        glyphRange.location = NSMaxRange(attributeGlyphRange);
    }
}
```

答:
The answer was much more simple than I anticipated.

You can set lineFragmentPadding for the associated NSTextContainer to make more room for drawing in the margins. This has to be taken into account when setting insets for the text container.


问:
Creating your own header file in C
Can anyone explain how to create a header file in C with a simple example from beginning to end.</p>

答:
header files contain prototypes for functions you define in a .c or .cpp/.cxx file (depending if you're using c or c++). You want to place #ifndef/#defines around your .h code so that if you include the same .h twice in different parts of your programs, the prototypes are only included once.

client.h

```<code>#ifndef CLIENT_H
#define CLIENT_H

short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize);

#endif /** CLIENT_H */
</code>```

Then you'd implement the .h in a .c file like so:

client.c

```<code>#include "client.h"

short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize) {
 short ret = -1;
 //some implementation here
 return ret;
}
</code>```

Title: Creating your own header file in C

Body:
header files contain prototypes for functions you define in a .c or .cpp/.cxx file (depending if you're using c or c++). You want to place #ifndef/#defines around your .h code so that if you include the same .h twice in different parts of your programs, the prototypes are only included once.

client.h

#ifndef CLIENT_H
#define CLIENT_H

short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize);

#endif /** CLIENT_H */

Then you'd implement the .h in a .c file like so:

client.c

#include "client.h"

short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize) {
 short ret = -1;
 //some implementation here
 return ret;
}


问:
How to apply a constraint to a power law model so that it passes through a specific data point (Python)
I would like to develop a power law model using lmfit (or another library). Is there any way I can apply a constraint or bound to the model so that it has to pass through a specific data point (exp. the point (1, 2))</p>
```<code>plm = models.PowerLawModel()

params = plm.guess(y_data, x=x_data)
result = plm.fit(y_data, params, x=x_data, )
const = round(result.best_values['amplitude'], 3)
exp = round(result.best_values['exponent'], 3)
best = result.best_fit

</code>```

答:
For a Power Law model, which is just y = Amplitude * x**Exponent, it would be pretty easy to write a constraint to force the model to always go through a point (x0, y0).   You want Amplitude to be such that

```<code> y0 = Amplitude*x0**Exponent
</code>```

for any value of Exponent.  That is

```<code> Amplitude = y0*x0**(-Exponent)
</code>```

You can specify that in lmfit with something like

```<code>plm = models.PowerLawModel()
params = plm.guess(y_data, x=x_data)
params['amplitude'].expr = '{0:g}*{1:g}**(-exponent)'.format(y0, x0)
</code>```

This will make amplitude not vary independently from exponent in the fit, and always take values that depend on the value of exponent and this expression.

Body:
I would like to develop a power law model using lmfit (or another library). Is there any way I can apply a constraint or bound to the model so that it has to pass through a specific data point (exp. the point (1, 2))

plm = models.PowerLawModel()

params = plm.guess(y_data, x=x_data)
result = plm.fit(y_data, params, x=x_data, )
const = round(result.best_values['amplitude'], 3)
exp = round(result.best_values['exponent'], 3)
best = result.best_fit

Body:
For a Power Law model, which is just y = Amplitude * x**Exponent, it would be pretty easy to write a constraint to force the model to always go through a point (x0, y0).   You want Amplitude to be such that

 y0 = Amplitude*x0**Exponent

for any value of Exponent.  That is

 Amplitude = y0*x0**(-Exponent)

You can specify that in lmfit with something like

plm = models.PowerLawModel()
params = plm.guess(y_data, x=x_data)
params['amplitude'].expr = '{0:g}*{1:g}**(-exponent)'.format(y0, x0)

This will make amplitude not vary independently from exponent in the fit, and always take values that depend on the value of exponent and this expression.


问:
Compose android testing fails: Idling resource timed out
I'm trying to write the test for my composes. So I have a test class put in AndroidTest just like this:

```<code>@HiltAndroidTest
@UninstallModules(AuthenticationModule::class, AppModule::class)
class AuthenticationScreenTest {

    @get:Rule(order = 0)
    val hiltRule = HiltAndroidRule(this)

    @get:Rule(order = 1)
    val composeRule = createAndroidComposeRule<MainActivity>()

    @Inject
    lateinit var setting: Setting

    @Before
    fun setup() {
        hiltRule.inject()
        composeRule.setContent {
            val navController = rememberNavController()
            RefectoryTheme {
                NavHost(
                    navController = navController,
                    startDestination = AuthenticationNavGraph.AuthenticationScreen.route
                ) {
                    composable(AuthenticationNavGraph.AuthenticationScreen.route) {
                        AuthenticationScreen(navController = navController, setting = setting)
                    }
                }
            }
        }
    }

    @Test
    fun checkLoadingButtonExpantion() {
        composeRule.onNodeWithTag(testTag = AUTHENTICATION_SCREEN_LOGIN_BUTTON)
        .assertIsDisplayed()
    }
}
</code>```

but I keep getting the error:

```<code>androidx.compose.ui.test.junit4.android.ComposeNotIdleException: Idling resource timed out:
possibly due to compose being busy.
IdlingResourceRegistry has the following idling resources registered:
- [busy] androidx.compose.ui.test.junit4.ComposeIdlingResource@a005df5
All registered idling resources: Compose-Espresso link
</code>```

The android emulator is launched, test compiles successfully, but it seems it can't find the object.
I also have added a test tag to the modifier of the object:

```<code> LoadingButton(
                    buttonText = stringResource(id = R.string.login),
                    isExpanded = state.isLoginExpanded,
                    modifier = Modifier
                        .padding(MaterialTheme.spacing.medium)
                        .align(Alignment.CenterHorizontally)
                        .testTag(AUTHENTICATION_SCREEN_LOGIN_BUTTON)
                ) {
                    viewModel.onEvent(AuthenticationEvent.Login)
                }
</code>```

But after 28 seconds, I got the error as mentioned above.
What am I missing?

答:
I just realized what the problem was.
I am using Lottie on my screen, and the animation is infinity repeating.
So I don't know why but it seems that it doesn't allow testing to go through.
The tests ran without any problem when I commented the Lottie section.</p>

Body:
I'm trying to write the test for my composes. So I have a test class put in AndroidTest just like this:

@HiltAndroidTest
@UninstallModules(AuthenticationModule::class, AppModule::class)
class AuthenticationScreenTest {

    @get:Rule(order = 0)
    val hiltRule = HiltAndroidRule(this)

    @get:Rule(order = 1)
    val composeRule = createAndroidComposeRule<MainActivity>()

    @Inject
    lateinit var setting: Setting

    @Before
    fun setup() {
        hiltRule.inject()
        composeRule.setContent {
            val navController = rememberNavController()
            RefectoryTheme {
                NavHost(
                    navController = navController,
                    startDestination = AuthenticationNavGraph.AuthenticationScreen.route
                ) {
                    composable(AuthenticationNavGraph.AuthenticationScreen.route) {
                        AuthenticationScreen(navController = navController, setting = setting)
                    }
                }
            }
        }
    }

    @Test
    fun checkLoadingButtonExpantion() {
        composeRule.onNodeWithTag(testTag = AUTHENTICATION_SCREEN_LOGIN_BUTTON)
        .assertIsDisplayed()
    }
}

but I keep getting the error:

androidx.compose.ui.test.junit4.android.ComposeNotIdleException: Idling resource timed out:
possibly due to compose being busy.
IdlingResourceRegistry has the following idling resources registered:
- [busy] androidx.compose.ui.test.junit4.ComposeIdlingResource@a005df5
All registered idling resources: Compose-Espresso link

The android emulator is launched, test compiles successfully, but it seems it can't find the object.
I also have added a test tag to the modifier of the object:

 LoadingButton(
                    buttonText = stringResource(id = R.string.login),
                    isExpanded = state.isLoginExpanded,
                    modifier = Modifier
                        .padding(MaterialTheme.spacing.medium)
                        .align(Alignment.CenterHorizontally)
                        .testTag(AUTHENTICATION_SCREEN_LOGIN_BUTTON)
                ) {
                    viewModel.onEvent(AuthenticationEvent.Login)
                }

But after 28 seconds, I got the error as mentioned above.
What am I missing?


问:
Odoo Space Between Buttons on Top Tree View
I'm able to create a button when select multiple record by adding this header tag in tree view

```<code><tree create="false" delete="false">
    <header>
        <button name="action_cancel" type="object" string="Cancel" class="btn-danger"/>
    </header>
    ...
    ...
</tree>
</code>```

As you can see, there is no space button 8 selected button and cancel button. How can I add a space for that buttons?

答:
You can add ml4 class to action_cancel button

```<code><button name="action_cancel" type="object" string="Cancel" class="btn-danger ml4"/>
</code>```

Or alter the o_list_selection_box and define the right margin:

```<code>.o_list_selection_box {
    margin-right: 4px;
}
</code>```

Alter the web.assets_backend template to add the CSS file

Body:
I'm able to create a button when select multiple record by adding this header tag in tree view

<tree create="false" delete="false">

        <button name="action_cancel" type="object" string="Cancel" class="btn-danger"/>

    ...
    ...
</tree>

As you can see, there is no space button 8 selected button and cancel button. How can I add a space for that buttons?

Body:
You can add ml4 class to action_cancel button

<button name="action_cancel" type="object" string="Cancel" class="btn-danger ml4"/>

Or alter the o_list_selection_box and define the right margin:

.o_list_selection_box {
    margin-right: 4px;
}

Alter the web.assets_backend template to add the CSS file


问:
pandas DataFrame "no numeric data to plot" error
I have a small DataFrame that I want to plot using pandas.

```<code>    2   3
0   1300    1000
1   242751149   199446827
2   237712649   194704827
3   16.2    23.0
</code>```

I am still trying to learn plotting from within pandas . I want a plot In the above example when I say .

```<code>df.plot()
</code>```

I get the strangest error.

```<code>Library/Python/2.7/site-packages/pandas-0.16.2-py2.7-macosx-10.10-intel.egg/pandas/tools/plotting.pyc in _compute_plot_data(self)
   1015         if is_empty:
   1016             raise TypeError('Empty {0!r}: no numeric data to '
-> 1017                             'plot'.format(numeric_data.__class__.__name__))
   1018
   1019         self.data = numeric_data

TypeError: Empty 'DataFrame': no numeric data to plot
</code>```

While I understand that the DataFrame with its very lopsided values makes a very un-interesting plot. I am wondering why the error message complains of no numeric data to plot.

答:
Convert non numeric data into numeric using:</p>
```<code>DataFrame["Column_name"] = DataFrame["Column_name"].str.replace("[\$\,\.]", "")
</code>```

Body:
I have a small DataFrame that I want to plot using pandas.

    2   3
0   1300    1000
1   242751149   199446827
2   237712649   194704827
3   16.2    23.0

I am still trying to learn plotting from within pandas . I want a plot In the above example when I say .

df.plot()

I get the strangest error.

Library/Python/2.7/site-packages/pandas-0.16.2-py2.7-macosx-10.10-intel.egg/pandas/tools/plotting.pyc in _compute_plot_data(self)
   1015         if is_empty:
   1016             raise TypeError('Empty {0!r}: no numeric data to '
-> 1017                             'plot'.format(numeric_data.__class__.__name__))
   1018
   1019         self.data = numeric_data

TypeError: Empty 'DataFrame': no numeric data to plot

While I understand that the DataFrame with its very lopsided values makes a very un-interesting plot. I am wondering why the error message complains of no numeric data to plot.

Body:
Convert non numeric data into numeric using:

DataFrame["Column_name"] = DataFrame["Column_name"].str.replace("[\$\,\.]", "")


问:
Adding single value to speciifc dataframe column
I have a dataframe like:

```<code>principalDf =

    |   x   ||   y   ||   z   ||   values   |
    |  x0   ||  y0   ||  z0   ||   areal    |
    |  x1   ||  y1   ||  z1   ||   aimag    |
    |  x2   ||  y2   ||  z2   ||   breal    |
    |  x3   ||  y3   ||  z3   ||   bimag    |
</code>```

I want to produce:

```<code>frobprincipalDf =

|       x       ||       y       ||       z       ||   values   |
|sqrt(x0^2+x1^2)||sqrt(y0^2+y1^2)||sqrt(z0^2+z1^2)||     a      |
|sqrt(x2^2+x3^2)||sqrt(y2^2+y3^2)||sqrt(z2^2+z3^2)||     b      |
</code>```

I'm generating the required x, y and z data by:

```<code>frobprincipalDf = pd.DataFrame(columns=principalDf.columns)

for col in principalDf.columns[:-1]:
    for index in range(0,len(principalDf),2):
        frobnorm = np.sqrt(principalDf[col].iloc[index]**2+principalDf[col].iloc[index+1]**2)
        print(frobnorm)
</code>```

How can I add frobnorm to a specific col in the newly created frobprincipalDf?

Is there a better way to do this than nested for loops?

It should be generalisable for any value name, such that if another value begins with a, it will not 'group' them together.

It looks as though the below is a complete solution to the initial problem of even-index pairs of rows addition. This is slightly modified answer of quasi-human's answer. The secondary problem of adding a single value to a specific df column is still there though.

```<code>frobprincipalDf = np.sqrt(principalDf[['x', 'y', 'z']].shift() ** 2 + principalDf[['x', 'y', 'z']] ** 2)
frobprincipalDf = pd.concat([frobprincipalDf,principalDf['values'].str[:2]], axis=1)
frobprincipalDf = frobprincipalDf[frobprincipalDf.index % 2 == 1].reset_index(drop=True)
</code>```

答:
You can use shift method to pick out a pair of rows.

Code:

import numpy as np
import pandas as pd

# Create a sample dataframe
import io
s='''x,y,z,values
1,5,9,areal
2,6,10,aimag
3,7,11,breal
4,8,12,bimag'''
df = pd.read_csv(io.StringIO(s))

# Calculate values
df_calc = np.sqrt(df[['x', 'y', 'z']].shift() ** 2 + df[['x', 'y', 'z']] ** 2)

# Deal with strings
df_str = df['values'].str[:1]

# Concatenate the two dataframes
df_result = pd.concat([df_calc, df_str], axis=1)

# Pick out odd indice
df_result = df_result[df_result.index % 2 == 1].reset_index(drop=True)
```

Input:

x
y
z
values

1
5
9
areal

2
6
10
aimag

3
7
11
breal

4
8
12
bimag

Output:

x
y
z
values

2.23607
7.81025
13.4536
a

5
10.6301
16.2788
b

Body:
I have a dataframe like:

principalDf =

    |   x   ||   y   ||   z   ||   values   |
    |  x0   ||  y0   ||  z0   ||   areal    |
    |  x1   ||  y1   ||  z1   ||   aimag    |
    |  x2   ||  y2   ||  z2   ||   breal    |
    |  x3   ||  y3   ||  z3   ||   bimag    |

I want to produce:

frobprincipalDf =

|       x       ||       y       ||       z       ||   values   |
|sqrt(x0^2+x1^2)||sqrt(y0^2+y1^2)||sqrt(z0^2+z1^2)||     a      |
|sqrt(x2^2+x3^2)||sqrt(y2^2+y3^2)||sqrt(z2^2+z3^2)||     b      |

I'm generating the required x, y and z data by:

frobprincipalDf = pd.DataFrame(columns=principalDf.columns)

for col in principalDf.columns[:-1]:
    for index in range(0,len(principalDf),2):
        frobnorm = np.sqrt(principalDf[col].iloc[index]**2+principalDf[col].iloc[index+1]**2)
        print(frobnorm)

How can I add frobnorm to a specific col in the newly created frobprincipalDf?

Is there a better way to do this than nested for loops?

It should be generalisable for any value name, such that if another value begins with a, it will not 'group' them together.

It looks as though the below is a complete solution to the initial problem of even-index pairs of rows addition. This is slightly modified answer of quasi-human's answer. The secondary problem of adding a single value to a specific df column is still there though.

frobprincipalDf = np.sqrt(principalDf[['x', 'y', 'z']].shift() ** 2 + principalDf[['x', 'y', 'z']] ** 2)
frobprincipalDf = pd.concat([frobprincipalDf,principalDf['values'].str[:2]], axis=1)
frobprincipalDf = frobprincipalDf[frobprincipalDf.index % 2 == 1].reset_index(drop=True)

Body:
You can use shift method to pick out a pair of rows.

Code:

import numpy as np
import pandas as pd

# Create a sample dataframe
import io
s='''x,y,z,values
1,5,9,areal
2,6,10,aimag
3,7,11,breal
4,8,12,bimag'''
df = pd.read_csv(io.StringIO(s))

# Calculate values
df_calc = np.sqrt(df[['x', 'y', 'z']].shift() ** 2 + df[['x', 'y', 'z']] ** 2)

# Deal with strings
df_str = df['values'].str[:1]

# Concatenate the two dataframes
df_result = pd.concat([df_calc, df_str], axis=1)

# Pick out odd indice
df_result = df_result[df_result.index % 2 == 1].reset_index(drop=True)

Input:

x
y
z
values

1
5
9
areal

2
6
10
aimag

3
7
11
breal

4
8
12
bimag

Output:

x
y
z
values

2.23607
7.81025
13.4536
a

5
10.6301
16.2788
b


问:
Android: GATT 137 exception when read characteristic
I'm connecting bluetotooth device. I'm getting GATT 137 exception when I read characteristic of bluetooth device. Why I can't read characteristic ?
Code snippet:</p>
```<code>if (!mBluetoothGatt.readCharacteristic(mCharacteristic)) {
     Log.e(TAG, "read characteristic task is success")
    }else{
     Log.e(TAG, "read characteristic task is fail")
    }

</code>```

答: code 137 is AUTHORIZATION_FAILED. So you probably need to bond with your device first.</p>

Body:
I'm connecting bluetotooth device. I'm getting GATT 137 exception when I read characteristic of bluetooth device. Why I can't read characteristic ?
Code snippet:

if (!mBluetoothGatt.readCharacteristic(mCharacteristic)) {
     Log.e(TAG, "read characteristic task is success")
    }else{
     Log.e(TAG, "read characteristic task is fail")
    }


问:
Should constructor call init or vice versa?
In a case where I want to allow initializing a class directly in the construction, as well as allowing an empty instance (either default-constructed or that has had some kind of close() method called on it) to be initialized, is there any reason to prefer either of these two options for avoiding code duplication?

init/open calls constructor:

```<code>struct S {
  S(params...) : initlist... {
    ... init code ...
  }
  void init(params...) {
    *this = S(params...);
  }
  ...
};
</code>```

Constructor calls init/open:

```<code>struct S {
  S(params...) {
    init(params...);
  }
  void init(params...) {
    ... init code ...
  }
  ...
};
</code>```

Think for example a class representing a file, that can have the path passed to the constructor or  call an open() method later.

答:
I usually using just the init method because I tend to avoid exceptions, and constructors can't return status codes.

If you also want a non-default constructor, I think your second example is better. Your first version requires the class to be copyable or moveable. Depending on what's in your class, that requirement may complicate things. For instance, it's unnecessarily complicated to implement copies of file handles, you gonna need kernel calls like DuplicateHandle.

Body:
In a case where I want to allow initializing a class directly in the construction, as well as allowing an empty instance (either default-constructed or that has had some kind of close() method called on it) to be initialized, is there any reason to prefer either of these two options for avoiding code duplication?

init/open calls constructor:

struct S {
  S(params...) : initlist... {
    ... init code ...
  }
  void init(params...) {
    *this = S(params...);
  }
  ...
};

Constructor calls init/open:

struct S {
  S(params...) {
    init(params...);
  }
  void init(params...) {
    ... init code ...
  }
  ...
};

Think for example a class representing a file, that can have the path passed to the constructor or  call an open() method later.


问:
Vue 3: Rendering the object in descending order issue
I am trying to render the data in the desc order, but vue 3 always render it in the asc order

state: {
    entries: {
        2022: {
            10: {...},
            11: {...},
            12: {...},
            ...
        },
        2021: {
            10: {...},
            12: {...},
            ...
        },
        2020: {
            3: {...},
            8: {...},
            ...
        },
    },
}
```

But it always renders like this 2020, 2021, 2022 where as I require it to be 2022, 2021, 2020,

How to fix it

答:
integers are iterated first in the ascending order

Small Demo demonstrating above statement.

var jsonObj = {
  3: 'March',
  1: 'Jan',
  5: 'May'
};

console.log(jsonObj);```
</div>
</div>
</p>
<p>That's what a JavaScript engine recognizes as an integer and what humans recognize as a number are not same.</p>
<p>To achieve the order, we can convert that object into an array.</p>
<p><strong>Demo :</strong></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-js lang-js prettyprint-override"><code>const app = new Vue({
  el: '#app',
  data() {
    return {
      list: [{
      3: 'March' }, {
      1: 'Jan' }, {
      5: 'May' }]
    }
  }
})</code>```

        {{ item[Object.keys(item)[0]] }}

```

Body:
I am trying to render the data in the desc order, but vue 3 always render it in the asc order

state: {
    entries: {
        2022: {
            10: {...},
            11: {...},
            12: {...},
            ...
        },
        2021: {
            10: {...},
            12: {...},
            ...
        },
        2020: {
            3: {...},
            8: {...},
            ...
        },
    },
}

But it always renders like this 2020, 2021, 2022 where as I require it to be 2022, 2021, 2020,

How to fix it

Body:
integers are iterated first in the ascending order

Small Demo demonstrating above statement.

var jsonObj = {
  3: 'March',
  1: 'Jan',
  5: 'May'
};

console.log(jsonObj);

That's what a JavaScript engine recognizes as an integer and what humans recognize as a number are not same.

To achieve the order, we can convert that object into an array.

Demo :

const app = new Vue({
  el: '#app',
  data() {
    return {
      list: [{
      3: 'March' }, {
      1: 'Jan' }, {
      5: 'May' }]
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.0/vue.js"></script>

<body>
  <div id="app">
    <ul>
      <li v-for="(item, index) in list" :key="index">
        {{ item[Object.keys(item)[0]] }}
      </li>
    </ul>
  </div>
</body>


问:
Create a new columns based on keywords in YAKE
I'm trying to use YAKE to extract the keywords from a list of books' summaries.

```<code>df = {'Book': [1, 2], 'Summary': ['text definition includes the original words of something written, printed, or spoken', 'example of the Lorem ipsum placeholder text on a green and white webpage']}
df = pd.DataFrame(df)
</code>```

Then I tried to use a loop and extract 1 keyword from each summary:

```<code>for i in df['Summary']:
  language = "en"
  max_ngram_size = 1
  deduplication_threshold = 0.9
  numOfKeywords = 2
  custom_kw_extractor = yake.KeywordExtractor(lan=language, n=max_ngram_size, dedupLim=deduplication_threshold, top=numOfKeywords, features=None)
  keywords = custom_kw_extractor.extract_keywords(i)
  for kw, w in keywords:
    print(kw)
</code>```

Th output is:

```<code>printed
Lorem
</code>```

However, I'd like to add them as a new column in the same dataframe. The final output should be:

Book
Summary
Keywods

1
text definition includes the original words of something written, printed, or spoken
printed

2
example of the Lorem ipsum placeholder text on a green and white webpage
Lorem

I tried to make a new list

```<code>df['keywords'] = kw
</code>```

but it didn't work! It's been a while since I used Python and pandas and I don't seem to remember to do that!

Any help would be appreciated!

答:
Try df.Summary.apply:

```<code>import pandas as pd
import yake

language = "en"
max_ngram_size = 1
deduplication_threshold = 0.9
numOfKeywords = 1
custom_kw_extractor = yake.KeywordExtractor(lan=language, n=max_ngram_size, dedupLim=deduplication_threshold, top=numOfKeywords, features=None)

df = {'Book': [1, 2], 'Summary': ['text definition includes the original words of something written, printed, or spoken', 'example of the Lorem ipsum placeholder text on a green and white webpage']}
df = pd.DataFrame(df)

df['Keywords'] = df.Summary.apply(lambda x : custom_kw_extractor.extract_keywords(x)[0][0])
</code>```
```<code>|    |   Book | Summary                                                                              | Keywords   |
|---:|-------:|:-------------------------------------------------------------------------------------|:-----------|
|  0 |      1 | text definition includes the original words of something written, printed, or spoken | printed    |
|  1 |      2 | example of the Lorem ipsum placeholder text on a green and white webpage             | Lorem      |
</code>```

Or with to_numpy():

```<code>df['keywords'] = [custom_kw_extractor.extract_keywords(d)[0][0] for d in df.Summary.to_numpy()]
</code>```

Key words as lists using to_numpy(), since it is usually faster than df.apply:

```<code>df['Keywords']  = [[s[0] for s in custom_kw_extractor.extract_keywords(d)] for d in df.Summary.to_numpy()]
</code>```
```<code>|    |   Book | Summary                                                                              | Keywords                                               |
|---:|-------:|:-------------------------------------------------------------------------------------|:-------------------------------------------------------|
|  0 |      1 | text definition includes the original words of something written, printed, or spoken | ['printed', 'text', 'written', 'spoken', 'definition'] |
|  1 |      2 | example of the Lorem ipsum placeholder text on a green and white webpage             | ['Lorem', 'webpage', 'ipsum', 'placeholder', 'text']
</code>```

Or if you want comma separated strings:

```<code>df['Keywords']  = [','.join([s[0] for s in custom_kw_extractor.extract_keywords(d)]) for d in df.Summary.to_numpy()]
</code>```
```<code>|    |   Book | Summary                                                                              | Keywords                               |
|---:|-------:|:-------------------------------------------------------------------------------------|:---------------------------------------|
|  0 |      1 | text definition includes the original words of something written, printed, or spoken | printed,text,written,spoken,definition |
|  1 |      2 | example of the Lorem ipsum placeholder text on a green and white webpage             | Lorem,webpage,ipsum,placeholder,text   |
</code>```

Body:
I'm trying to use YAKE to extract the keywords from a list of books' summaries.

df = {'Book': [1, 2], 'Summary': ['text definition includes the original words of something written, printed, or spoken', 'example of the Lorem ipsum placeholder text on a green and white webpage']}
df = pd.DataFrame(df)

Then I tried to use a loop and extract 1 keyword from each summary:

for i in df['Summary']:
  language = "en"
  max_ngram_size = 1
  deduplication_threshold = 0.9
  numOfKeywords = 2
  custom_kw_extractor = yake.KeywordExtractor(lan=language, n=max_ngram_size, dedupLim=deduplication_threshold, top=numOfKeywords, features=None)
  keywords = custom_kw_extractor.extract_keywords(i)
  for kw, w in keywords:
    print(kw)

Th output is:

printed
Lorem

However, I'd like to add them as a new column in the same dataframe. The final output should be:

Book
Summary
Keywods

1
text definition includes the original words of something written, printed, or spoken
printed

2
example of the Lorem ipsum placeholder text on a green and white webpage
Lorem

I tried to make a new list

df['keywords'] = kw

but it didn't work! It's been a while since I used Python and pandas and I don't seem to remember to do that!

Any help would be appreciated!

Body:
Try df.Summary.apply:

import pandas as pd
import yake

language = "en"
max_ngram_size = 1
deduplication_threshold = 0.9
numOfKeywords = 1
custom_kw_extractor = yake.KeywordExtractor(lan=language, n=max_ngram_size, dedupLim=deduplication_threshold, top=numOfKeywords, features=None)

df = {'Book': [1, 2], 'Summary': ['text definition includes the original words of something written, printed, or spoken', 'example of the Lorem ipsum placeholder text on a green and white webpage']}
df = pd.DataFrame(df)

df['Keywords'] = df.Summary.apply(lambda x : custom_kw_extractor.extract_keywords(x)[0][0])

|    |   Book | Summary                                                                              | Keywords   |
|---:|-------:|:-------------------------------------------------------------------------------------|:-----------|
|  0 |      1 | text definition includes the original words of something written, printed, or spoken | printed    |
|  1 |      2 | example of the Lorem ipsum placeholder text on a green and white webpage             | Lorem      |

Or with to_numpy():

df['keywords'] = [custom_kw_extractor.extract_keywords(d)[0][0] for d in df.Summary.to_numpy()]

Key words as lists using to_numpy(), since it is usually faster than df.apply:

df['Keywords']  = [[s[0] for s in custom_kw_extractor.extract_keywords(d)] for d in df.Summary.to_numpy()]

|    |   Book | Summary                                                                              | Keywords                                               |
|---:|-------:|:-------------------------------------------------------------------------------------|:-------------------------------------------------------|
|  0 |      1 | text definition includes the original words of something written, printed, or spoken | ['printed', 'text', 'written', 'spoken', 'definition'] |
|  1 |      2 | example of the Lorem ipsum placeholder text on a green and white webpage             | ['Lorem', 'webpage', 'ipsum', 'placeholder', 'text']

Or if you want comma separated strings:

df['Keywords']  = [','.join([s[0] for s in custom_kw_extractor.extract_keywords(d)]) for d in df.Summary.to_numpy()]

|    |   Book | Summary                                                                              | Keywords                               |
|---:|-------:|:-------------------------------------------------------------------------------------|:---------------------------------------|
|  0 |      1 | text definition includes the original words of something written, printed, or spoken | printed,text,written,spoken,definition |
|  1 |      2 | example of the Lorem ipsum placeholder text on a green and white webpage             | Lorem,webpage,ipsum,placeholder,text   |


答:
Use the defined operator to check if something has value which is not undef

```<code>if ( defined $hash{ $key } ) {
  //do stuff
}
</code>```

Use the exists operator to check if a $key of a %hash has been written to

```<code>if ( exists $hash{ $key } ) {
  //do stuff
}
</code>```

The difference being that defined checks to see if a value is of anything other than undef and exists is used to verify if $key is a key of the hash despite its value.

Title: Perl: How to test if any value (even zero) has been assigned to a hash key

Body:
Is there a correct way of testing if a particular hash key has already been assigned any value, even if this value is zero? I have been working with a statement like this:

%hash=();
$hash{a}=1;
$hash{b}=0;
if($hash{$key}) { do something }

but this gives the same result for keys that have neven been touched and those that have been assigned the value 0 (e.g. both $hash{b} and $hash{c} evaluate as 'false'). Is there a way of telling the difference between those two ?

Body:
Use the defined operator to check if something has value which is not undef

if ( defined $hash{ $key } ) {
  //do stuff
}

Use the exists operator to check if a $key of a %hash has been written to

if ( exists $hash{ $key } ) {
  //do stuff
}

The difference being that defined checks to see if a value is of anything other than undef and exists is used to verify if $key is a key of the hash despite its value.


答:
Update

1 keyword was for simplicity but I'd love it if I can generalise it to multiple keywords

For multiple keywords, change numOfKeywords and lambda function:

```<code>language = 'en'
max_ngram_size = 1
deduplication_threshold = 0.9
numOfKeywords = 3  # <- Multiple keywords
custom_kw_extractor = yake.KeywordExtractor(lan=language, n=max_ngram_size,
                                            dedupLim=deduplication_threshold,
                                            top=numOfKeywords, features=None)

extract_keywords = lambda x: [k[0] for k in custom_kw_extractor.extract_keywords(x)]
df['TopKeyword'] = df['Summary'].apply(extract_keywords)
</code>```

Output:

Book
Summary
TopKeyword

1
text definition includes the original words of something written, printed, or spoken
['printed', 'text', 'written']

2
example of the Lorem ipsum placeholder text on a green and white webpage
['Lorem', 'webpage', 'ipsum']

To get a string instead of a list, update lambda function:

```<code>extract_keywords = lambda x: ','.join(k[0] for k in custom_kw_extractor.extract_keywords(x))
</code>```

Output:

Book
Summary
TopKeyword

1
text definition includes the original words of something written, printed, or spoken
printed,text,written

2
example of the Lorem ipsum placeholder text on a green and white webpage
Lorem,webpage,ipsum

Old answer

```<code>extract_keywords = lambda x: ','.join(k[0] for k in custom_kw_extractor.extract_keywords(x))
df['Keywords'] = df['Summary'].apply(extract_keywords)
</code>```

You don't need a loop here, apply can do it for you.

```<code>language = 'en'
max_ngram_size = 1
deduplication_threshold = 0.9
numOfKeywords = 1
custom_kw_extractor = yake.KeywordExtractor(lan=language, n=max_ngram_size,
                                            dedupLim=deduplication_threshold,
                                            top=numOfKeywords, features=None)

extract_keyword = lambda x: custom_kw_extractor.extract_keywords(x)[0][0]
df['TopKeyword'] = df['Summary'].apply(extract_keyword)
</code>```

Output:

Book
Summary
TopKeyword

1
text definition includes the original words of something written, printed, or spoken
printed

2
example of the Lorem ipsum placeholder text on a green and white webpage
Lorem

Title: Create a new columns based on keywords in YAKE

Body:
Update

1 keyword was for simplicity but I'd love it if I can generalise it to multiple keywords

For multiple keywords, change numOfKeywords and lambda function:

language = 'en'
max_ngram_size = 1
deduplication_threshold = 0.9
numOfKeywords = 3  # <- Multiple keywords
custom_kw_extractor = yake.KeywordExtractor(lan=language, n=max_ngram_size,
                                            dedupLim=deduplication_threshold,
                                            top=numOfKeywords, features=None)

extract_keywords = lambda x: [k[0] for k in custom_kw_extractor.extract_keywords(x)]
df['TopKeyword'] = df['Summary'].apply(extract_keywords)

Output:

Book
Summary
TopKeyword

1
text definition includes the original words of something written, printed, or spoken
['printed', 'text', 'written']

2
example of the Lorem ipsum placeholder text on a green and white webpage
['Lorem', 'webpage', 'ipsum']

To get a string instead of a list, update lambda function:

extract_keywords = lambda x: ','.join(k[0] for k in custom_kw_extractor.extract_keywords(x))

Output:

Book
Summary
TopKeyword

1
text definition includes the original words of something written, printed, or spoken
printed,text,written

2
example of the Lorem ipsum placeholder text on a green and white webpage
Lorem,webpage,ipsum

Old answer

extract_keywords = lambda x: ','.join(k[0] for k in custom_kw_extractor.extract_keywords(x))
df['Keywords'] = df['Summary'].apply(extract_keywords)

You don't need a loop here, apply can do it for you.

language = 'en'
max_ngram_size = 1
deduplication_threshold = 0.9
numOfKeywords = 1
custom_kw_extractor = yake.KeywordExtractor(lan=language, n=max_ngram_size,
                                            dedupLim=deduplication_threshold,
                                            top=numOfKeywords, features=None)

extract_keyword = lambda x: custom_kw_extractor.extract_keywords(x)[0][0]
df['TopKeyword'] = df['Summary'].apply(extract_keyword)

Output:

Book
Summary
TopKeyword

1
text definition includes the original words of something written, printed, or spoken
printed

2
example of the Lorem ipsum placeholder text on a green and white webpage
Lorem


问:
Django 4.0.2 | Python 3.9.7 | TypeError: __init__() missing 1 required positional argument: 'get_response'
I wrote a custom authentication and added a csrf check middleware in the authentication process.
I am calling the below function in the authentication function.

```<code>def enforce_csrf(self, request):
    """
    Enforce CSRF validation
    """
    check = CSRFCheck()
    check.process_request(request)
    reason = check.process_view(request, None, (), {})
    if reason:
        # CSRF failed, bail with explicit error message
        raise PermissionDenied('CSRF Failed: %s' % reason)
</code>```

The CSRFCheck() function is a custom middleware and it looks like this.

```<code>class CSRFCheck(CsrfViewMiddleware):
    def _reject(self, request, reason):
        return reason
</code>```

Now when I am trying to process the request, which requires authentication, I am getting the error:

TypeError: init() missing 1 required positional argument: 'get_response'

the same code is working perfectly in Django 3.2

Now, as far as I was able to debug, the CSRFCheck function is expecting a get_response method which I don't know where it is coming from.

答:
It would seem that the API for creating custom middleware is that you provide a get_response parameter upon initialization.

https://docs.djangoproject.com/en/4.0/topics/http/middleware/#writing-your-own-middleware

When you call CSRFCheck() you aren't providing it that parameter so when it runs, it fails.

You can try following the example in the link above and reformatting your custom middleware to match the example they provided.

Body:
I wrote a custom authentication and added a csrf check middleware in the authentication process.
I am calling the below function in the authentication function.

def enforce_csrf(self, request):
    """
    Enforce CSRF validation
    """
    check = CSRFCheck()
    check.process_request(request)
    reason = check.process_view(request, None, (), {})
    if reason:
        # CSRF failed, bail with explicit error message
        raise PermissionDenied('CSRF Failed: %s' % reason)

The CSRFCheck() function is a custom middleware and it looks like this.

class CSRFCheck(CsrfViewMiddleware):
    def _reject(self, request, reason):
        return reason

Now when I am trying to process the request, which requires authentication, I am getting the error:

TypeError: init() missing 1 required positional argument: 'get_response'

the same code is working perfectly in Django 3.2

Now, as far as I was able to debug, the CSRFCheck function is expecting a get_response method which I don't know where it is coming from.


问:
Binary Search tree time complexity
I am right now  working with a Binary Search tree. I wonder what is the Tim complexity for a Binary Search tree. More Specific what is the worst case Time complexity for the operation height, leaves and toString for a Binary Search tree and why?</p>

答:
All three operations have a  O(n) worst-case time complexity.

For height: all nodes will be visited when the tree is degenerate, and all nodes except one have exactly one child.

For leaves: each node will have to be visited in order to check whether they are a leave.

For toString: obviously all nodes need to be visited.

Title: Binary Search tree time complexity


问:
How do you set a relative path for a file-based package source with NuGet?
I'm using NuGet 2.1 with multiple solutions, each in a child directory under a single parent directory and a single packages directory which is shared by all the solutions (this became possible with NuGet 2.1).

I'd like to add a file-based package source which points to the packages directory in my working copy (I'm using Subversion).

This works:

```<code><configuration>
  <repositoryPath>_Packages</repositoryPath>
  <activePackageSource>
    <add key="Working copy package source" value="C:\AllMySolutions\_Packages" />
  </activePackageSource>
</configuration>
</code>```

This doesn't:

```<code><configuration>
  <repositoryPath>_Packages</repositoryPath>
  <activePackageSource>
    <add key="Working copy package source" value="_Packages" />
  </activePackageSource>
</configuration>
</code>```

I don't want to hard-code the absolute path but can't find a way of using a relative path in the value attribute inside activePackageSource.

答:
For .NETCore/.NET5 and newer, the config key repositoryPath doesn't work anymore, and it is now named globalPackagesFolder, so:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
    <config>
        <add key="globalPackagesFolder" value=".\packages\" />
    </config>
</configuration>
</code>```

Body:
I'm using NuGet 2.1 with multiple solutions, each in a child directory under a single parent directory and a single packages directory which is shared by all the solutions (this became possible with NuGet 2.1).

I'd like to add a file-based package source which points to the packages directory in my working copy (I'm using Subversion).

This works:

<configuration>
  <repositoryPath>_Packages</repositoryPath>
  <activePackageSource>
    <add key="Working copy package source" value="C:\AllMySolutions\_Packages" />
  </activePackageSource>
</configuration>

This doesn't:

<configuration>
  <repositoryPath>_Packages</repositoryPath>
  <activePackageSource>
    <add key="Working copy package source" value="_Packages" />
  </activePackageSource>
</configuration>

I don't want to hard-code the absolute path but can't find a way of using a relative path in the value attribute inside activePackageSource.

Body:
For .NETCore/.NET5 and newer, the config key repositoryPath doesn't work anymore, and it is now named globalPackagesFolder, so:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <config>
        <add key="globalPackagesFolder" value=".\packages\" />
    </config>
</configuration>


问:
Getting the Data in snapshot.val() but not able to treat it
I was making an app and had to fetch data from Realtime Database. I am getting the data in snapshot.val() like this

```<code>►{xz0ezxzrpkb:{…}}
▼xz0ezxzrpkb:{blood_group:"B+",cause:"Random Cause",created_on:"08-02-2022",email:"example@gmail.com",location:"Random Location",message:"Random Message",name:"Any_Name",phone_number:"+91 *********"}
</code>```

And Now I want to access this data. When I am trying snapshot.val()[0].email   and

snapshot.val().[0].email I am Getting

```<code>undefined (2)
</code>```

So, I am working in React Native and this is the code

```<code>db.ref('/requests/').on('value', (snapshot) => {
       console.log(snapshot.val())
       console.log(snapshot.val()[0].email)
       console.log(snapshot.val().[0].email)
});
</code>```

The nodes of database are as follows:

Please help me out.

答:
The snapshot value is not an object. Try refactoring the code using Object.keys() as shown below:

```<code>db.ref('/requests/').on('value', (snapshot) => {
  Object.keys(snapshot.val()).forEach((key) => {
    const request = snapshot.val()[key];
    console.log(key, request.email)
  })
});
</code>```

Body:
I was making an app and had to fetch data from Realtime Database. I am getting the data in snapshot.val() like this

►{xz0ezxzrpkb:{…}}
▼xz0ezxzrpkb:{blood_group:"B+",cause:"Random Cause",created_on:"08-02-2022",email:"example@gmail.com",location:"Random Location",message:"Random Message",name:"Any_Name",phone_number:"+91 *********"}

And Now I want to access this data. When I am trying snapshot.val()[0].email   and

snapshot.val().[0].email I am Getting

undefined (2)

So, I am working in React Native and this is the code

db.ref('/requests/').on('value', (snapshot) => {
       console.log(snapshot.val())
       console.log(snapshot.val()[0].email)
       console.log(snapshot.val().[0].email)
});

The nodes of database are as follows:

Please help me out.

Body:
The snapshot value is not an object. Try refactoring the code using Object.keys() as shown below:

db.ref('/requests/').on('value', (snapshot) => {
  Object.keys(snapshot.val()).forEach((key) => {
    const request = snapshot.val()[key];
    console.log(key, request.email)
  })
});


问:
BUG navigating from a view to another in SwiftUI
I have a problem and I really don't know how can i fix this. When I'm pressing the button, I want to navigate to the next view, but at the last view, it didn't work and it pushes me out to the MainView. So, in the CartView, if the onboardingState == 1, it will create an Order and the status will be changed to "pending", and will show the WaitingOrderView(), but is not working as expected.

I will put a view under the code that I will share right know.

```<code>struct CartView: View {
        @EnvironmentObject var syncViewModel : SyncViewModel
        @State var onboardingState: Int = 0
        @State var index = 0
        @State private var timer: AnyCancellable?

        var body: some View {
                ZStack {
                    switch onboardingState {
                    case 0 :
                        VStack {
                        welcomeSection
                        Spacer()
                        bottomButton
                            .padding(30)
                        }
                    case 1 :
                        VStack {
                        welcomeSection2
                        Spacer()
                        bottomButton
                            .padding(30)
                        }

                    case 2 :
                        VStack {
                        detailOrder
                        Spacer()
                        bottomButton
                            .padding(30)
                        }
                    default:
                        EmptyView()
                    }
                }
        }
    }
    extension CartView {
        private var bottomButton : some View {
            Text("Continue")
                .font(.headline)
                .foregroundColor(.white)
                .frame(height: 55)
                .frame(maxWidth: .infinity)
                .background(Color.onboardingColor)
                .cornerRadius(20)
                .onTapGesture {
                    handleNextButtonPressed()
                }
        }

        private var welcomeSection: some View {

            PaymentView()
        }

        private var welcomeSection2: some View {

            LivrareView()
        }
        @ViewBuilder
        private var detailOrder: some View {
            ZStack {
                if syncViewModel._order.status == syncViewModel.statusList.first(where: { status in
                    status.key == StatusKey.pending.rawValue
                })?.id
                {
                    WaitingOrderView()
                }
                else
                {
                    EmptyView()
                }
            }
        }
    }

    extension CartView {
        func handleNextButtonPressed() {
            if onboardingState == 1 {
                syncViewModel.createOrder()
                onboardingState += 1
            }
            else {
                withAnimation(.spring()) {
                    onboardingState += 1
                }
            }

        }
    }

</code>```
```<code>struct MainView: View {
    @EnvironmentObject var syncViewModel : SyncViewModel
    @Environment(\.managedObjectContext) private var viewContext
    @FetchRequest(sortDescriptors: [])
    private var menus : FetchedResults<LocalMenu>

    var body: some View {
        TabView{
            NavigationView{

             MeniuriView()
                    .toolbar {
                        ToolbarItem(placement: .navigationBarTrailing) {
                            ToolbarButtons(numberOfProducts: menus.count)
                    }
                        ToolbarItem(placement: .navigationBarLeading) {
                            Text(Texts.mainViewText1)
                                .font(.system(size: 24))
                                .fontWeight(.bold)
                                .padding()
                        }
                }
            }
            .tabItem {
                Text(Texts.mainViewText2)
                Image(systemName: "fork.knife")
            }
            NavigationView {
                AlteleView()
            }
            .tabItem {
                Text(Texts.mainViewText3)
                Image("altele", bundle: Bundle.main)
            }
        }
        .accentColor(Color.tabItemColor)
    }
}
</code>```
```<code>struct ToolbarButtons: View {
    @EnvironmentObject var syncViewModel : SyncViewModel
    @Environment(\.managedObjectContext) private var viewContext
    @FetchRequest(sortDescriptors: [])
    private var cartOrder : FetchedResults<CartOrders>
    var numberOfProducts : Int

    var body: some View {
        ZStack {
            Spacer()
            if syncViewModel._order.status == 0 && syncViewModel._order.id == 0{
                NavigationLink(destination: CartView()
                                .toolbar {
                    ToolbarItem(placement: .navigationBarLeading) {
                        Text(Texts.cartText)
                            .font(.system(size: 24))
                            .bold()
                    }
                }
                               , label: {
                    Image("otherIcon")
                        .padding(.top, 5)
                }
                )
            }
            else  if syncViewModel._order.id == cartOrder.first?.id  ?? Int32(syncViewModel._order.id) {
                NavigationLink  {
                    WaitingOrderView()
                } label: {
                    ZStack(alignment: .topTrailing) {
                        Image("cartIcon")
                            .padding(.top, 5)
                        if numberOfProducts > 0 {
                            Text("\(numberOfProducts)")
                                .font(.caption2).bold()
                                .foregroundColor(.white)
                                .frame(width: 15, height: 15)
                                .background(Color.tabItemColor)
                                .cornerRadius(50)
                                .offset(x: 10, y: -8)
                        }
                    }
                }
            }
        }
    }
}

</code>```
```<code>struct WaitingOrderView {
    @EnvironmentObject var syncViewModel : SyncViewModel
    let transition: AnyTransition = .asymmetric(
        insertion: .move(edge: .trailing),
        removal: .move(edge: .leading))
    var body: some View {
        ZStack {
            if syncViewModel._order.status == syncViewModel.statusList.first(where: { status in
                status.key == StatusKey.pending.rawValue
            })?.id {
                ChefView()
                    .environmentObject(syncViewModel)
            }
           else  if syncViewModel._order.status == syncViewModel.statusList.first(where: { status in
                status.key == StatusKey.accepted.rawValue
            })?.id
            {
                OrderConfirmedView()
            }
            else if syncViewModel._order.status == syncViewModel.statusList.first(where: { status in
                status.key == StatusKey.readyForDelivery.rawValue
            })?.id {
                OrderReadyForDeliveryView()
            }
            else if syncViewModel._order.status == syncViewModel.statusList.first(where: { status in
                status.key == StatusKey.onTheWay.rawValue
            })?.id {
                OrderOnTheWayView()
            } else if syncViewModel._order.status == syncViewModel.statusList.first(where: { status in
                status.key == StatusKey.completed.rawValue
            })?.id {
                OrderCompletedView()
            } else if syncViewModel._order.status == syncViewModel.statusList.first(where: { status in
                status.key == StatusKey.canceled.rawValue
            })?.id {
                OrderCanceledView()
            }
        }

    }
</code>```

答:
These might not be the reason for the exact bug but your use of SwiftUI is non-standard and will likely cause you problems. In browsing your code here is a list of issues I noticed:

We don't use view model objects in SwiftUI, we use @State and we can use a custom struct to make some logic more testable and the whole reason is to take advantage of Swift's value semantics - see Managing User Interface State. If you use objects instead of value types you will have major problems. Also worth watching Data Essentials in SwiftUI WWDC 2020 the first half is about view state and shows the use of custom structs, e.g. struct EditorConfig.

You are using computed vars e.g. private var detailOrder: some View instead of custom Views, e.g. DetailOrderView. This breaks SwiftUI's dependency tracking. You are supposed to break up your hierarchy into small views with only a few lets or states so body will be recomputed less often, which is called having tighter invalidation. A DetailOrderView could have let orderStatus so although it might be init many times, its body is only computed when orderStatus is different. In your current code your entire massive body is recomputed when orderStatus changes.

var numberOfProducts : Int should be let.

We try not to use if inside body which compiles to a _ConditionalView and breaks SwiftUI's structural identity. See Demystify SwiftUI WWDC 2021. You can avoid this with something like Text(orderStatus.complete ? "Complete" : "In-progress") so there is always a Text just with different params. We can also use modifiers conditionally by using the usual .automatic param in the else case.

Body:
I have a problem and I really don't know how can i fix this. When I'm pressing the button, I want to navigate to the next view, but at the last view, it didn't work and it pushes me out to the MainView. So, in the CartView, if the onboardingState == 1, it will create an Order and the status will be changed to "pending", and will show the WaitingOrderView(), but is not working as expected.

I will put a view under the code that I will share right know.

struct CartView: View {
        @EnvironmentObject var syncViewModel : SyncViewModel
        @State var onboardingState: Int = 0
        @State var index = 0
        @State private var timer: AnyCancellable?

        var body: some View {
                ZStack {
                    switch onboardingState {
                    case 0 :
                        VStack {
                        welcomeSection
                        Spacer()
                        bottomButton
                            .padding(30)
                        }
                    case 1 :
                        VStack {
                        welcomeSection2
                        Spacer()
                        bottomButton
                            .padding(30)
                        }

                    case 2 :
                        VStack {
                        detailOrder
                        Spacer()
                        bottomButton
                            .padding(30)
                        }
                    default:
                        EmptyView()
                    }
                }
        }
    }
    extension CartView {
        private var bottomButton : some View {
            Text("Continue")
                .font(.headline)
                .foregroundColor(.white)
                .frame(height: 55)
                .frame(maxWidth: .infinity)
                .background(Color.onboardingColor)
                .cornerRadius(20)
                .onTapGesture {
                    handleNextButtonPressed()
                }
        }

        private var welcomeSection: some View {

            PaymentView()
        }

        private var welcomeSection2: some View {

            LivrareView()
        }
        @ViewBuilder
        private var detailOrder: some View {
            ZStack {
                if syncViewModel._order.status == syncViewModel.statusList.first(where: { status in
                    status.key == StatusKey.pending.rawValue
                })?.id
                {
                    WaitingOrderView()
                }
                else
                {
                    EmptyView()
                }
            }
        }
    }

    extension CartView {
        func handleNextButtonPressed() {
            if onboardingState == 1 {
                syncViewModel.createOrder()
                onboardingState += 1
            }
            else {
                withAnimation(.spring()) {
                    onboardingState += 1
                }
            }

        }
    }

struct MainView: View {
    @EnvironmentObject var syncViewModel : SyncViewModel
    @Environment(\.managedObjectContext) private var viewContext
    @FetchRequest(sortDescriptors: [])
    private var menus : FetchedResults<LocalMenu>

    var body: some View {
        TabView{
            NavigationView{

             MeniuriView()
                    .toolbar {
                        ToolbarItem(placement: .navigationBarTrailing) {
                            ToolbarButtons(numberOfProducts: menus.count)
                    }
                        ToolbarItem(placement: .navigationBarLeading) {
                            Text(Texts.mainViewText1)
                                .font(.system(size: 24))
                                .fontWeight(.bold)
                                .padding()
                        }
                }
            }
            .tabItem {
                Text(Texts.mainViewText2)
                Image(systemName: "fork.knife")
            }
            NavigationView {
                AlteleView()
            }
            .tabItem {
                Text(Texts.mainViewText3)
                Image("altele", bundle: Bundle.main)
            }
        }
        .accentColor(Color.tabItemColor)
    }
}

struct ToolbarButtons: View {
    @EnvironmentObject var syncViewModel : SyncViewModel
    @Environment(\.managedObjectContext) private var viewContext
    @FetchRequest(sortDescriptors: [])
    private var cartOrder : FetchedResults<CartOrders>
    var numberOfProducts : Int

    var body: some View {
        ZStack {
            Spacer()
            if syncViewModel._order.status == 0 && syncViewModel._order.id == 0{
                NavigationLink(destination: CartView()
                                .toolbar {
                    ToolbarItem(placement: .navigationBarLeading) {
                        Text(Texts.cartText)
                            .font(.system(size: 24))
                            .bold()
                    }
                }
                               , label: {
                    Image("otherIcon")
                        .padding(.top, 5)
                }
                )
            }
            else  if syncViewModel._order.id == cartOrder.first?.id  ?? Int32(syncViewModel._order.id) {
                NavigationLink  {
                    WaitingOrderView()
                } label: {
                    ZStack(alignment: .topTrailing) {
                        Image("cartIcon")
                            .padding(.top, 5)
                        if numberOfProducts > 0 {
                            Text("\(numberOfProducts)")
                                .font(.caption2).bold()
                                .foregroundColor(.white)
                                .frame(width: 15, height: 15)
                                .background(Color.tabItemColor)
                                .cornerRadius(50)
                                .offset(x: 10, y: -8)
                        }
                    }
                }
            }
        }
    }
}

struct WaitingOrderView {
    @EnvironmentObject var syncViewModel : SyncViewModel
    let transition: AnyTransition = .asymmetric(
        insertion: .move(edge: .trailing),
        removal: .move(edge: .leading))
    var body: some View {
        ZStack {
            if syncViewModel._order.status == syncViewModel.statusList.first(where: { status in
                status.key == StatusKey.pending.rawValue
            })?.id {
                ChefView()
                    .environmentObject(syncViewModel)
            }
           else  if syncViewModel._order.status == syncViewModel.statusList.first(where: { status in
                status.key == StatusKey.accepted.rawValue
            })?.id
            {
                OrderConfirmedView()
            }
            else if syncViewModel._order.status == syncViewModel.statusList.first(where: { status in
                status.key == StatusKey.readyForDelivery.rawValue
            })?.id {
                OrderReadyForDeliveryView()
            }
            else if syncViewModel._order.status == syncViewModel.statusList.first(where: { status in
                status.key == StatusKey.onTheWay.rawValue
            })?.id {
                OrderOnTheWayView()
            } else if syncViewModel._order.status == syncViewModel.statusList.first(where: { status in
                status.key == StatusKey.completed.rawValue
            })?.id {
                OrderCompletedView()
            } else if syncViewModel._order.status == syncViewModel.statusList.first(where: { status in
                status.key == StatusKey.canceled.rawValue
            })?.id {
                OrderCanceledView()
            }
        }

    }