答:
Will an implicit stack switch occur when switching from compatibility mode to 64-bit mode at the same privilege level?

No implicit stack switch will occur when switching from compatibility mode to 64-bit mode at the same privilege level; unless it's done by an interrupt using the IST mechanism.

However, if the BASE field is ignored, the stack base address will become 0x0 implicitly, which means an implicit stack switch will be raised, am I right?

For 80x86; in general a linear address is calculated by adding an offset within a segment to the base of a segment, where the base of the segment is stored in a "hidden" part of the segment register. For example, in 32-bit code, if you do mov eax,[esp] then the CPU calculates "linear_address = SS.base + ESP".

Because most operating systems use a "flat memory model" where segments are effectively disabled (by setting all segments bases to zero and all segment limits to "max"); CPUs optimized this specific case such that if segment bases are known to be zero the addition is skipped (e.g. for that mov eax,[esp] CPU may cheat and do "linear_address = ESP" if it already knows SS.base is zero).

For 64-bit code, excluding FS and GS segment registers, the value in the "hidden" part of the segment register (used for segment base) is assumed to be zero regardless of whether it is or not; and the CPU knows the segment base is always "assumed to be zero" and always optimizes the address calculation (by not adding segment base).

When switching from compatibility mode to 64-bit mode at the same privilege level; there are 2 possibilities:

a) The segment base for SS was zero in compatibility mode, and becomes "assumed zero" in 64-bit, and therefore the address of the stack doesn't change (see note).

b) The segment base for SS was non-zero in compatibility mode, and becomes "assumed zero" in 64-bit, and therefore the address of the stack does change.

The latter possibility (non-zero SS segment base in compatibility mode) would be something I'd strongly avoid; as it's horribly confusing for programmers, and has a "higher than normal" risk of quirks/errata (e.g. a future CPU doing things in a slightly different order and storing return information at "ss.base + esp" instead of at "0 + esp").

Note: In 64-bit code, anything that only updates the lower half of a register causes the upper half of the 64-bit register to be zeroed (e.g. loading the value 0x9ABCDEF0 into ESP will cause RSP to be set to 0x000000009ABCDEF0). I don't think this happens in compatibility mode (or at least, I don't think it's guaranteed to happen). This may potentially create a situation where "junk" left in the higher half of RSP before switching to compatibility mode is still present when you switch back to 64-bit (e.g. possibly causing the address of the stack to change from 0x9ABCDEF0 to 0x123456789ABCDEF0).

Body:
When switching from compatibility mode to 64-bit mode at the same privilege level by a far call, fields such as BASE or LIMIT in segment registers are ignored, and 64-bit pointer registers are all available. However, if the BASE field is ignored, the stack base address will become 0x0 implicitly, which means an implicit stack switch will be raised, am I right?
And if my understanding is correct, how does the CPU switch back to the original stack when returning via the ret instruction?


来源: stackexchange

问:
No response from uut in testbench
I am not getting any response from the uut in the testbench. The module exp2_up_down_counter works ok without testbench, but gives output as xxxx when instantiated in the testbench.

Here is the main module of the up-down counter:

```<code>`timescale 1ns/1ps
module exp2_up_down_counter (input clk, reset, mode, output reg [3:0] count);

  always @(posedge clk)

    if (reset == 1)
      count <= 0;   // reset the counter if reset is high
    else if (mode == 1)
      count <= count + 1; // works as up counter if mode pin is high
    else
      count <= count - 1; // works as down counter if mode pin is low

endmodule
</code>```

Simulation without testbench:

Testbench for up-down counter

```<code>`timescale 1ns/1ps

module exp2_up_down_counter_tb;
  reg clk, reset, mode;
  wire [3:0] count;

  exp2_up_down_counter uut(.clk(clk), .reset(reset), .mode(mode), .count(count));
  initial begin
    clk = 1'b0;
  end

    always  @(*) #5 clk <= ~clk;
  initial begin
    // initializing the inputs
    reset = 1;
    mode = 0;

    #5;
    reset = 0;
    #10
    mode = 1;
    #5000 $finish;
  end
endmodule
</code>```

Simulation with testbench:

答:
In exp2_up_down_counter, count is declared as a reg.  This means that its default value is X at time 0.  Since the reset signal is synchronous to the clock, you need to wait for the 1st posedge of clock before you release the reset.  Currently, the reset is released at the 1st posedge of clock in the testbench, which is a race condition.  Therefore, count does not get assigned the value of 0, and it retains the value of X for the whole simulation.

You need to delay the reset release.  For example, change:

```<code>#5;
reset = 0;
</code>```

to:

```<code>#15;
reset = 0;
</code>```

However, it is better to drive your synchronous inputs in the testbench the same way you drive your signals in the design: using @(posedge clk) and using nonblocking assignments (<=):

```<code>  initial begin
    reset = 1;
    mode  = 0;

    repeat (2) @(posedge clk);
    reset <= 0;
    repeat (1) @(posedge clk);
    mode <= 1;

    #5000 $finish;
  end
</code>```

Also, this is a more standard way to drive the clock in the testbench:

```<code>always #5 clk = ~clk;
</code>```

ContentLicense: CC BY-SA 4.0

Title: No response from uut in testbench

Body:
I am not getting any response from the uut in the testbench. The module exp2_up_down_counter works ok without testbench, but gives output as xxxx when instantiated in the testbench.

Here is the main module of the up-down counter:

`timescale 1ns/1ps
module exp2_up_down_counter (input clk, reset, mode, output reg [3:0] count);

  always @(posedge clk)

    if (reset == 1)
      count <= 0;   // reset the counter if reset is high
    else if (mode == 1)
      count <= count + 1; // works as up counter if mode pin is high
    else
      count <= count - 1; // works as down counter if mode pin is low

endmodule

Simulation without testbench:

Testbench for up-down counter

`timescale 1ns/1ps

module exp2_up_down_counter_tb;
  reg clk, reset, mode;
  wire [3:0] count;

  exp2_up_down_counter uut(.clk(clk), .reset(reset), .mode(mode), .count(count));
  initial begin
    clk = 1'b0;
  end

    always  @(*) #5 clk <= ~clk;
  initial begin
    // initializing the inputs
    reset = 1;
    mode = 0;

    #5;
    reset = 0;
    #10
    mode = 1;
    #5000 $finish;
  end
endmodule

Simulation with testbench:

Body:
In exp2_up_down_counter, count is declared as a reg.  This means that its default value is X at time 0.  Since the reset signal is synchronous to the clock, you need to wait for the 1st posedge of clock before you release the reset.  Currently, the reset is released at the 1st posedge of clock in the testbench, which is a race condition.  Therefore, count does not get assigned the value of 0, and it retains the value of X for the whole simulation.

You need to delay the reset release.  For example, change:

#5;
reset = 0;

to:

#15;
reset = 0;

However, it is better to drive your synchronous inputs in the testbench the same way you drive your signals in the design: using @(posedge clk) and using nonblocking assignments (<=):

  initial begin
    reset = 1;
    mode  = 0;

    repeat (2) @(posedge clk);
    reset <= 0;
    repeat (1) @(posedge clk);
    mode <= 1;

    #5000 $finish;
  end

Also, this is a more standard way to drive the clock in the testbench:

always #5 clk = ~clk;


问:
How to embed AcquireTokenInteractive prompt in a WPF UserControl
I have a Windows Desktop WPF application that is using the MSAL libraries to authorize a user against Azure Active Directory. It is all working, except the prompt where the user selects their account sometimes ends up behind the application (I assume when a user selects a different application in the taskbar prior completing the MSAL prompt).

I have added the WithParentActivityOrWindow option and pointed it to the main window of the application, but that doesn't attach the prompt to anything or force it in front of the application.

Is is possible to do one of the following, and if so, how?

Force the prompt to receive focus whenever the application is the 'active' Windows application

Embed the prompt within a WPF UserControl

For reference, the example code here is almost identical to what I'm using:
https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-desktop-acquire-token-interactive?tabs=dotnet

Edit: I noticed today that Visual Studio blocks until the OAuth prompt is completed, but I'm not sure how this is accomplished or if Visual Studio is using the MSAL libraries at all.

答: As the documentation states, AcquireTokenInteractive should be ran on the UI thread. My application is embedded within another application, so once I changed the call to run on the main application's UI thread it started working as expected.</p>


问:
Is there a performance benefit to narrowing the scope of a `querySelector()` search first?
(If it makes any difference, I'm working on a web component.)

If I have the following:

<form>
   <input type="hidden" id="foo" name="foo" value="bar" />
</form>

```
<p>…and I want to select the hidden field, which is faster/better?</p>
<p>A)</p>
<pre class="lang-js prettyprint-override"><code>let field = document.querySelector('#foo');
</code>```

B)

let field = myForm.querySelector('#foo');
```

答:
In the case of an ID selector, I think A is likely to be faster.

IDs are supposed to be unique, so the browser almost certainly has an index of all the IDs. Looking up an ID in document will use this index to find the element as quickly as possible.

But if you query for the ID nested in another element, it will assume that you're violating this expectation, and it will have to do an actual search within that element. This is difficult to optimize, and there's little incentive to do so since it's not a valid DOM.

It's possible that the browser will keep track of which IDs have been duplicated. If foo is not duplicated, B could be optimized to be equivalent to A.

So B is at best equivalent to A, but it could be worse.

Body:
(If it makes any difference, I'm working on a web component.)

If I have the following:

<form>
   <input type="hidden" id="foo" name="foo" value="bar" />
</form>

…and I want to select the hidden field, which is faster/better?

A)

let field = document.querySelector('#foo');

B)

let field = myForm.querySelector('#foo');


问:
Javascript switch, case, break doesn't work
I'm new at JS

I'm making a drum kit website and i create a switch section but it's not working.

```<code>var numberOfDrumButtons = document.querySelectorAll(".drum").length;

for (var i = 0; i < numberOfDrumButtons; i++) {

  document.querySelectorAll(".drum")[i].addEventListener("click", function() {

    var buttonInnerHtml = this.innerHTML;

    switch (buttonInnerHtml) {
      case "w":
        var tom1 = new Audio('songs/oni-chan.mp3');
        tom1.play();
        break;

      case "a":
        var tom2 = new Audio('songs/oni-chan2.mp3');
        tom2.play();
        break;

      case "s":
        var tom3 = new Audio('songs/oni-chan3.mp3');
        tom3.play();
        break;
      default:
        break;
    }

  })
}

</code>```

HTML:

```<code>  <div class="set">
    <button class="w drum"><span>w</span></button>
    <button class="a drum"><span>a</span></button>
    <button class="s drum"><span>s</span></button>
    <button class="d drum"><span>d</span></button>
    <button class="j drum"><span>j</span></button>
    <button class="k drum"><span>k</span></button>
    <button class="l drum"><span>L</span></button>
  </div>

  <script src="index.js" href="UTF-8"></script>
</code>```

答:
From the Audio docs(https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement/Audio#determining_when_playback_can_begin):

There are three ways you can tell when enough of the audio file has loaded to allow playback to begin:

Check the value of the readyState property. If it's HTMLMediaElement.HAVE_FUTURE_DATA, there's enough data available to begin playback and play for at least a short time. If it's HTMLMediaElement.HAVE_ENOUGH_DATA, then there's enough data available that, given the current download rate, you should be able to play the audio through to the end without interruption.

Listen for the canplay event. It is sent to the  element when there's enough audio available to begin playback, although interruptions may occur.

Listen for the canplaythrough event. It is sent when it's estimated that the audio should be able to play to the end without interruption.
The event-based approach is best:

```<code>myAudioElement.addEventListener("canplaythrough", event => {
  /* the audio is now playable; play it if permissions allow */
  myAudioElement.play();
});
</code>```

Body:
I'm new at JS

I'm making a drum kit website and i create a switch section but it's not working.

var numberOfDrumButtons = document.querySelectorAll(".drum").length;

for (var i = 0; i < numberOfDrumButtons; i++) {

  document.querySelectorAll(".drum")[i].addEventListener("click", function() {

    var buttonInnerHtml = this.innerHTML;

    switch (buttonInnerHtml) {
      case "w":
        var tom1 = new Audio('songs/oni-chan.mp3');
        tom1.play();
        break;

      case "a":
        var tom2 = new Audio('songs/oni-chan2.mp3');
        tom2.play();
        break;

      case "s":
        var tom3 = new Audio('songs/oni-chan3.mp3');
        tom3.play();
        break;
      default:
        break;
    }

  })
}

HTML:

    <button class="w drum">w</button>
    <button class="a drum">a</button>
    <button class="s drum">s</button>
    <button class="d drum">d</button>
    <button class="j drum">j</button>
    <button class="k drum">k</button>
    <button class="l drum">L</button>

Body:
From the Audio docs(https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement/Audio#determining_when_playback_can_begin):

There are three ways you can tell when enough of the audio file has loaded to allow playback to begin:

Check the value of the readyState property. If it's HTMLMediaElement.HAVE_FUTURE_DATA, there's enough data available to begin playback and play for at least a short time. If it's HTMLMediaElement.HAVE_ENOUGH_DATA, then there's enough data available that, given the current download rate, you should be able to play the audio through to the end without interruption.

Listen for the canplay event. It is sent to the  element when there's enough audio available to begin playback, although interruptions may occur.

Listen for the canplaythrough event. It is sent when it's estimated that the audio should be able to play to the end without interruption.
The event-based approach is best:

myAudioElement.addEventListener("canplaythrough", event => {
  /* the audio is now playable; play it if permissions allow */
  myAudioElement.play();
});


问:
How retrieves ASN.1 encoded information from PEM encoded key in iOS
Currently using Apple CommonCrypto, to make some encryptions. We have web application that use cryptography to keep zero knowledge principle, now we want to move this approach to iOS application.
I read about ASN.1, when try to parse using tool that is there I receive error -  not valid characters, but to be able to decrypt I need to remove some extra symbols. So to decrypt password, I need to pass several steps, one of it - to get salt, that is encrypted inside private key. private key looks like this:

```<code>"-----BEGIN ENCRYPTED PRIVATE KEY-----\r\nMIIFMjBcBgkqhkiG9w0BBQ0wTzAyBgkqhkiG9w0BBQwwJQQQsViPrFXr42CML5Ze\r\nYwQqCgIDAPoAMAwGCCqGSIb3DQIJBQAwGQYJYIZIAWUDBAEuBAwuBIjgFPCE/ESd\r\nqckEggTQjnq/Jv+J+OZUyTn+7plQJxrXHo375RYGNuUFlwkpzDmQAduU1ngrBh2D\r\nLwlBaiZQd+jU+7s5TVcIqJ3dNVdruN2du1v1TN/49NmQeWMc9IW9gH84vbAE5spu\r\naCx0RONt7UdJ1TENM4sRMvIUKky2jmTa/HaTnvBHb4/5TWIPBktj0B5QCqgQPVVB\r\nCmG/cK0JeZ0wPNTkEiP/Exst1smY/x3vqxO+/G8cjVZMi/uzjZgf/jbpJ0qbdQSR\r\nJ6xwVLID8Dc3O43KL3qmnkbu81iAWi4PuKiq3gvONOH/Ud2ENsNRVrLRUT/jYSyY\r\nnIuDccrW+YoTJ1qJLOIPXB/m1dUqS0aUo2VZCHwIPCqeuGEBrGX+U7MLXnXWMYY7\r\n0AIpS8Xq15Z+3OrnJFuQoQ+JZWOk+Ngqfq2rCasgZKZaCnqcUw09TDBhWWxyJUQE\r\nbcTpUX4hi1eJ5vFRNpLS0q7hI2wfAjkn8jnhKo2aH40/a9USjDJWjrW5RfKHkL/N\r\nrO5YKVin2iadoFkxXyv10WyZiYGinBUnr1GNl3fiC9JC6VCb4f4euyH9xvPMn9MU\r\nUw7EGufxcGo5thbyctHY0koBqvnaoQNCdf1IWhU8CCQLiMGKO4ND+cCZv5FGVoOn\r\ny3J6lBIon/g2MoLO8t6cqTK2N8xJbGmiYFayb1FTpvc6sZ7soiqmJ/EQmIxH8/jk\r\nzYGZVaMg3LbT4YkgtVkak0NrgHurk6Cp+Zf1KLM+rUTRRWf354Me6zMXhHiEbALw\r\nw9ubBrZDC5ftW7E0lwCp8y1vs9aUx+zyj7pTorNQYX8eC/A/ZdUj4EasfvqXj0Ke\r\nVLHdLlSPVsPyLY7loDwIQ1PQEU6rTELP/e4agPMda9zTRuJYelbp/oAA0YtHDD8f\r\nKs3OmLofzoWLG29wXi6KzjY09jIXh9sJ2qBHC1dyoJmHbDcIuN0n/sVI23BikdIZ\r\n3yJYfGP+MLq5c/YfiGGXOo1DxChSg+oUtWO0i30GWL4ze/alv3bjaZo6e+ahNatW\r\nqXbqDGAMQtcsaoeZfEJwtsMaQ1GVGOc5N5u7jaaelQ3/nClOwSDmAZ77/FXBaWNy\r\nSnpLfUfI9Hej6GTXDR5CEP0Wlac+n4uXdy801r4bayDKx8wlUNy93wfoHmYDrIlo\r\nyV7dKBZioAJtUA5NDVJj8KZPYI1Na6nIL8hxs44fSOqESZGHI9ir1RgrKk7k1G6F\r\nve6zlj7CENDl3UO4fNbRWI5lObCX4OWlKgYXlPN3SyrT0IzUXuw1QPHlqdl/j2VD\r\n+x6Ve2NFBSN9j8Gi90ZD159Oc+rdjXykGwT8p5ame60lB2qou72dgLUZn6U7GnG0\r\nWip27S4C2o90bwKnNKTX2o1rQRob101k7pkJEu3yJCKCnjIlR7Zwma3ZFXvhB1Ep\r\nikKhtP3zUiyQzzK1j8W98dKmSgTBYxpkJGfyGx8iqPZR5lGuD+Zrz+PzljSYD02l\r\nkiiV+uljWHGNFxo3DrTiJ4O2hSK0VEss5mRebiNWJv11egxL8nKsd0anWvdkajjd\r\nock5U77TGLV7nGks7OU6wGhuTqlB+2O6KYrl7HBoKS7QG75k1r96OFwZcXtlfErP\r\ntObwa4cNvekoknk4jhXyjbySJUB6E8TJal67gkyPCE/xACYniPY=\r\n-----END ENCRYPTED PRIVATE KEY-----"
</code>```

I need to retrieves ASN.1 encoded information from PEM encoded key. Web developers use library that does all these decryption, and as a decrypted value they receive:

```<code>const res = {
    salt: this.hexStringToArrayBuffer(opt.salt),
    iv: this.hexStringToArrayBuffer(opt.iv),
    cipher: opt.cipher,
    length: opt.length,
    hash: opt.hash,
    iter: opt.iter,
    encryptedData: this.hexStringToArrayBuffer(opt.encryptedData),
  };
</code>```

I need to use the same approach and be able decrypt these private keys. I searched a lot and haven't yet found any proper solution for swift. I will be very thankful for any advice.

Thanks a lot for any help!

答:
You need to decrypt -----BEGIN ENCRYPTED PRIVATE KEY-----

In openssl that would be

openssl rsa -in enc.key -out dec.key

if you are using rsa you would been to provide the passphrase for the encrypted key:

In you case:

Base64 decode the private key

decrypt the private key using the passphrase

base64 the result (or use it as the source for your ASN.1 decode

Body:
Currently using Apple CommonCrypto, to make some encryptions. We have web application that use cryptography to keep zero knowledge principle, now we want to move this approach to iOS application.
I read about ASN.1, when try to parse using tool that is there I receive error -  not valid characters, but to be able to decrypt I need to remove some extra symbols. So to decrypt password, I need to pass several steps, one of it - to get salt, that is encrypted inside private key. private key looks like this:

"-----BEGIN ENCRYPTED PRIVATE KEY-----\r\nMIIFMjBcBgkqhkiG9w0BBQ0wTzAyBgkqhkiG9w0BBQwwJQQQsViPrFXr42CML5Ze\r\nYwQqCgIDAPoAMAwGCCqGSIb3DQIJBQAwGQYJYIZIAWUDBAEuBAwuBIjgFPCE/ESd\r\nqckEggTQjnq/Jv+J+OZUyTn+7plQJxrXHo375RYGNuUFlwkpzDmQAduU1ngrBh2D\r\nLwlBaiZQd+jU+7s5TVcIqJ3dNVdruN2du1v1TN/49NmQeWMc9IW9gH84vbAE5spu\r\naCx0RONt7UdJ1TENM4sRMvIUKky2jmTa/HaTnvBHb4/5TWIPBktj0B5QCqgQPVVB\r\nCmG/cK0JeZ0wPNTkEiP/Exst1smY/x3vqxO+/G8cjVZMi/uzjZgf/jbpJ0qbdQSR\r\nJ6xwVLID8Dc3O43KL3qmnkbu81iAWi4PuKiq3gvONOH/Ud2ENsNRVrLRUT/jYSyY\r\nnIuDccrW+YoTJ1qJLOIPXB/m1dUqS0aUo2VZCHwIPCqeuGEBrGX+U7MLXnXWMYY7\r\n0AIpS8Xq15Z+3OrnJFuQoQ+JZWOk+Ngqfq2rCasgZKZaCnqcUw09TDBhWWxyJUQE\r\nbcTpUX4hi1eJ5vFRNpLS0q7hI2wfAjkn8jnhKo2aH40/a9USjDJWjrW5RfKHkL/N\r\nrO5YKVin2iadoFkxXyv10WyZiYGinBUnr1GNl3fiC9JC6VCb4f4euyH9xvPMn9MU\r\nUw7EGufxcGo5thbyctHY0koBqvnaoQNCdf1IWhU8CCQLiMGKO4ND+cCZv5FGVoOn\r\ny3J6lBIon/g2MoLO8t6cqTK2N8xJbGmiYFayb1FTpvc6sZ7soiqmJ/EQmIxH8/jk\r\nzYGZVaMg3LbT4YkgtVkak0NrgHurk6Cp+Zf1KLM+rUTRRWf354Me6zMXhHiEbALw\r\nw9ubBrZDC5ftW7E0lwCp8y1vs9aUx+zyj7pTorNQYX8eC/A/ZdUj4EasfvqXj0Ke\r\nVLHdLlSPVsPyLY7loDwIQ1PQEU6rTELP/e4agPMda9zTRuJYelbp/oAA0YtHDD8f\r\nKs3OmLofzoWLG29wXi6KzjY09jIXh9sJ2qBHC1dyoJmHbDcIuN0n/sVI23BikdIZ\r\n3yJYfGP+MLq5c/YfiGGXOo1DxChSg+oUtWO0i30GWL4ze/alv3bjaZo6e+ahNatW\r\nqXbqDGAMQtcsaoeZfEJwtsMaQ1GVGOc5N5u7jaaelQ3/nClOwSDmAZ77/FXBaWNy\r\nSnpLfUfI9Hej6GTXDR5CEP0Wlac+n4uXdy801r4bayDKx8wlUNy93wfoHmYDrIlo\r\nyV7dKBZioAJtUA5NDVJj8KZPYI1Na6nIL8hxs44fSOqESZGHI9ir1RgrKk7k1G6F\r\nve6zlj7CENDl3UO4fNbRWI5lObCX4OWlKgYXlPN3SyrT0IzUXuw1QPHlqdl/j2VD\r\n+x6Ve2NFBSN9j8Gi90ZD159Oc+rdjXykGwT8p5ame60lB2qou72dgLUZn6U7GnG0\r\nWip27S4C2o90bwKnNKTX2o1rQRob101k7pkJEu3yJCKCnjIlR7Zwma3ZFXvhB1Ep\r\nikKhtP3zUiyQzzK1j8W98dKmSgTBYxpkJGfyGx8iqPZR5lGuD+Zrz+PzljSYD02l\r\nkiiV+uljWHGNFxo3DrTiJ4O2hSK0VEss5mRebiNWJv11egxL8nKsd0anWvdkajjd\r\nock5U77TGLV7nGks7OU6wGhuTqlB+2O6KYrl7HBoKS7QG75k1r96OFwZcXtlfErP\r\ntObwa4cNvekoknk4jhXyjbySJUB6E8TJal67gkyPCE/xACYniPY=\r\n-----END ENCRYPTED PRIVATE KEY-----"

I need to retrieves ASN.1 encoded information from PEM encoded key. Web developers use library that does all these decryption, and as a decrypted value they receive:

const res = {
    salt: this.hexStringToArrayBuffer(opt.salt),
    iv: this.hexStringToArrayBuffer(opt.iv),
    cipher: opt.cipher,
    length: opt.length,
    hash: opt.hash,
    iter: opt.iter,
    encryptedData: this.hexStringToArrayBuffer(opt.encryptedData),
  };

I need to use the same approach and be able decrypt these private keys. I searched a lot and haven't yet found any proper solution for swift. I will be very thankful for any advice.

Thanks a lot for any help!


问:
(long) i + (int) j * k What is the type of the expression?
```<code>int i;
long j;
unsigned int k;
</code>```

I'm new to learning C, and can't figure this out. I've tried looking online many times for similar expressions. I honestly don't need the answer I really just want to understand how to figure it out. This has to do with mixing data types and I've only come across little information about what they are, but nothing clear to understand. Any help would be appreciated to understand how to figure out the data type for the following expression (long) i + (int) j * k

I appreciate any answers! Thank you!

答:
Other answers are telling you how to figure out the type using the C standard, but if you just want to know what the answer is for your particular compiler and compiler settings, then try compiling this invalid code:

int i;
long j;
unsigned int k;

void foo()
{
  char * x = (long) i + (int) j * k;
}
```

You will get a warning that says something like:

warning: initialization of 'char *' from 'long int' makes pointer from integer without a cast [-Wint-conversion]

This error message reveals to us that the compiler has decided that the type on the right-hand side of the assignment is a long int.

Body:
int i;
long j;
unsigned int k;

I'm new to learning C, and can't figure this out. I've tried looking online many times for similar expressions. I honestly don't need the answer I really just want to understand how to figure it out. This has to do with mixing data types and I've only come across little information about what they are, but nothing clear to understand. Any help would be appreciated to understand how to figure out the data type for the following expression (long) i + (int) j * k

I appreciate any answers! Thank you!

Body:
Other answers are telling you how to figure out the type using the C standard, but if you just want to know what the answer is for your particular compiler and compiler settings, then try compiling this invalid code:

int i;
long j;
unsigned int k;

void foo()
{
  char * x = (long) i + (int) j * k;
}

You will get a warning that says something like:

warning: initialization of 'char *' from 'long int' makes pointer from integer without a cast [-Wint-conversion]

This error message reveals to us that the compiler has decided that the type on the right-hand side of the assignment is a long int.


问:
Moving a file from host with docker-compose volume before Dockerfile is built
I have a few Dockerfiles that are dependant on a "pat" (Personal Access Token) file to be able to access a private nuget feed. I have taken some inspiration from somakdas to get this working.

To run my single Dockerfile I first create a "pat" file containing my token and build with docker build -f Services/User.API/Dockerfile -t userapi:dev --secret id=pat,src=pat .

This works as intended, but my issue is getting this to work using a docker-compose.yml file.

First I took a look at using docker-compose secrets, but it came to my attention that docker-compose secrets are access at runtime, not build-time. https://github.com/docker/compose/issues/6358

So now I'm trying to create a volume containing my pat file but I get cat: /pat: No such file or directory when the command RUN --mount=type=secret... is running. This may not be secure but it will only be running locally.

My Dockerfile

```<code>FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
RUN wget -qO- https://raw.githubusercontent.com/Microsoft/artifacts-credprovider/master/helpers/installcredprovider.sh | bash

WORKDIR /src
COPY ["User.API.csproj", "/Services/User.API"]

RUN --mount=type=secret,id=pat,dst=/pat export ENV VSS_NUGET_EXTERNAL_FEED_ENDPOINTS="{\"endpointCredentials\": [{\"endpoint\":\"<feed>\", \"username\":\"<user>\", \"password\":\"`cat /pat`\"}]}" \
&& dotnet restore "User.API.csproj" \
&& unset VSS_NUGET_EXTERNAL_FEED_ENDPOINTS

...
</code>```

My docker-compose.yml

```<code>services:
  user.api:
    container_name: User.API
    image: ${DOCKER_REGISTRY-}userapi
    build:
      context: .
      dockerfile: Services/User.API/Dockerfile
    networks:
      - app_network
    volumes:
      - ./pat:/app/src/pat
</code>```

Am I only able to access docker-compose volumes after the Dockerfile is built?

答:
I solved this by attacking the problem in a different way. As the main goal was to get this working locally I created Dockerfile.Local and docker-compose.local.yml. Together with this I created an .env file containing the "pat".

The docker-compose.local.yml passes the "pat" as an argument to the Dockerfile.Local where it's used. I also discarded --mount=type=secret and set the value to VSS_NUGET_EXTERNAL_FEED_ENDPOINTS directly.

.env file:

```<code>PAT_TOKEN=<personal access token>
</code>```

docker-compose.local.yml:

```<code>services:
  user.api:
    container_name: User.API
    image: ${DOCKER_REGISTRY-}userapi
    build:
      context: .
      dockerfile: Services/User.API/Dockerfile
    args:
      - PAT=${PAT_TOKEN}
    networks:
      - app_network
    volumes:
      - ./pat:/app/src/pat
</code>```

Dockerfile.Local:

```<code>FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
RUN wget -qO- https://raw.githubusercontent.com/Microsoft/artifacts-credprovider/master/helpers/installcredprovider.sh | bash

WORKDIR /src
COPY ["User.API.csproj", "/Services/User.API"]

ARG PAT
ENV VSS_NUGET_EXTERNAL_FEED_ENDPOINTS="{\"endpointCredentials\": [{\"endpoint\":\"<feed>\", \"username\":\"<user>\", \"password\":\"${PAT}\"}]}" \
&& dotnet restore "User.API.csproj" \
&& unset VSS_NUGET_EXTERNAL_FEED_ENDPOINTS

...
</code>```

Note: The .env file was added to .gitignore because it is containing sensitive information. We don't want that in our repository.

Body:
I have a few Dockerfiles that are dependant on a "pat" (Personal Access Token) file to be able to access a private nuget feed. I have taken some inspiration from somakdas to get this working.

To run my single Dockerfile I first create a "pat" file containing my token and build with docker build -f Services/User.API/Dockerfile -t userapi:dev --secret id=pat,src=pat .

This works as intended, but my issue is getting this to work using a docker-compose.yml file.

First I took a look at using docker-compose secrets, but it came to my attention that docker-compose secrets are access at runtime, not build-time. https://github.com/docker/compose/issues/6358

So now I'm trying to create a volume containing my pat file but I get cat: /pat: No such file or directory when the command RUN --mount=type=secret... is running. This may not be secure but it will only be running locally.

My Dockerfile

FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
RUN wget -qO- https://raw.githubusercontent.com/Microsoft/artifacts-credprovider/master/helpers/installcredprovider.sh | bash

WORKDIR /src
COPY ["User.API.csproj", "/Services/User.API"]

RUN --mount=type=secret,id=pat,dst=/pat export ENV VSS_NUGET_EXTERNAL_FEED_ENDPOINTS="{\"endpointCredentials\": [{\"endpoint\":\"<feed>\", \"username\":\"<user>\", \"password\":\"`cat /pat`\"}]}" \
&& dotnet restore "User.API.csproj" \
&& unset VSS_NUGET_EXTERNAL_FEED_ENDPOINTS

...

My docker-compose.yml

services:
  user.api:
    container_name: User.API
    image: ${DOCKER_REGISTRY-}userapi
    build:
      context: .
      dockerfile: Services/User.API/Dockerfile
    networks:
      - app_network
    volumes:
      - ./pat:/app/src/pat

Am I only able to access docker-compose volumes after the Dockerfile is built?

Body:
I solved this by attacking the problem in a different way. As the main goal was to get this working locally I created Dockerfile.Local and docker-compose.local.yml. Together with this I created an .env file containing the "pat".

The docker-compose.local.yml passes the "pat" as an argument to the Dockerfile.Local where it's used. I also discarded --mount=type=secret and set the value to VSS_NUGET_EXTERNAL_FEED_ENDPOINTS directly.

.env file:

PAT_TOKEN=<personal access token>

docker-compose.local.yml:

services:
  user.api:
    container_name: User.API
    image: ${DOCKER_REGISTRY-}userapi
    build:
      context: .
      dockerfile: Services/User.API/Dockerfile
    args:
      - PAT=${PAT_TOKEN}
    networks:
      - app_network
    volumes:
      - ./pat:/app/src/pat

Dockerfile.Local:

FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
RUN wget -qO- https://raw.githubusercontent.com/Microsoft/artifacts-credprovider/master/helpers/installcredprovider.sh | bash

WORKDIR /src
COPY ["User.API.csproj", "/Services/User.API"]

ARG PAT
ENV VSS_NUGET_EXTERNAL_FEED_ENDPOINTS="{\"endpointCredentials\": [{\"endpoint\":\"<feed>\", \"username\":\"<user>\", \"password\":\"${PAT}\"}]}" \
&& dotnet restore "User.API.csproj" \
&& unset VSS_NUGET_EXTERNAL_FEED_ENDPOINTS

...

Note: The .env file was added to .gitignore because it is containing sensitive information. We don't want that in our repository.


问:
How To Detect A Empty Column python
I Use Openpyxl Module

What I try to make:

Please tell how to make it and explain the detail.

I already try to make it but its just a forever loop :

```<code>sdp = mywbname[mysheetname]
perk = True
rows = "G"
column = 5
cell = rows+str(column)

print(cell)

while (perk == True):
    print(sdp[cell].value)
    column+=1
    if sdp[cell].value == "None":
        perk = False
    else:
        perk = True
</code>```

答:
You can use the worksheet.calculate_dimension() method which gives you the minimum bounding box of not-empty data as a range.

Then you can use one of the attributes of the range like cell_range.min_row or cell_range.bottom depending on exactly what you are looking for

Documentation about worksheet:
https://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.worksheet.html?highlight=worksheet

Documentation about cell_range:
https://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.worksheet.html?highlight=worksheet

Title: How To Detect A Empty Column python

Body:
I Use Openpyxl Module

What I try to make:

Please tell how to make it and explain the detail.

I already try to make it but its just a forever loop :

sdp = mywbname[mysheetname]
perk = True
rows = "G"
column = 5
cell = rows+str(column)

print(cell)

while (perk == True):
    print(sdp[cell].value)
    column+=1
    if sdp[cell].value == "None":
        perk = False
    else:
        perk = True


问:
How to change variables in the .env file dynamically in Laravel?
I want to create a Laravel web app that allows an admin user to change some variables(such as database credentials) in the .env file using the web backend system. But how do I save the changes?</p>

答:
A simple way to update the .env key value in laravel is to add the below code in the controller function where you want to change .env values.

```<code>$key = 'VARIABLE_NAME';
$value = 'NEW VALUE';
file_put_contents(app()->environmentFilePath(),
str_replace($key . '='. env($key),
$key . '=' . $value,file_get_contents(app()->environmentFilePath())));
</code>```

The above lines of code will change the required key-value in the .env file. The next step is to clear the cache because the updated env value is not loaded; therefore, you need to reload configurations after successful change redirects to route with commands below.

```<code>Artisan::call('cache:clear');
Artisan::call('config:clear');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
A simple way to update the .env key value in laravel is to add the below code in the controller function where you want to change .env values.

$key = 'VARIABLE_NAME';
$value = 'NEW VALUE';
file_put_contents(app()->environmentFilePath(),
str_replace($key . '='. env($key),
$key . '=' . $value,file_get_contents(app()->environmentFilePath())));

The above lines of code will change the required key-value in the .env file. The next step is to clear the cache because the updated env value is not loaded; therefore, you need to reload configurations after successful change redirects to route with commands below.

Artisan::call('cache:clear');
Artisan::call('config:clear');


问:
How to pass useState value to getServerSideProps in Nextjs?
Hi guys so I have been on this for 4 hrs trying to filter a product.
I have setState upon onClick event.
I can think of or find info on changing the query. THis is my code:

```<code>export async function getServerSideProps() {
    await db.connect();
    const products = await Product.find({}).lean();
    const categories = await Category.find({}).lean();
    await db.disconnect();
    return {
        props: {
            products: products.map(db.convertDocToObj),
            categories: categories.map(db.convertDocToObj),
        },
    };
}
</code>```

I have passing the state value but nothing. I think it is to provide an variable for the state and slap it in where 'meat' is, but should i dont know if i am to make serverside request that way

```<code>const products = await Product.find({ category: 'meat' }).lean();
</code>```

答:
Your getServerSideProps usage is correct. I would bet there is something incorrect with your data fetching.

Make sure products and categories are what you think they are before returning them in props here. I am unfamiliar with convertDocToObj method but if that returns a promise you will have to resolve that before returning from getServerSideProps.

Once products and categories are valid they will be available as props in your component:

function Page({ products, categories }) {
  // Render data...
}
```

Body:
Hi guys so I have been on this for 4 hrs trying to filter a product.
I have setState upon onClick event.
I can think of or find info on changing the query. THis is my code:

export async function getServerSideProps() {
    await db.connect();
    const products = await Product.find({}).lean();
    const categories = await Category.find({}).lean();
    await db.disconnect();
    return {
        props: {
            products: products.map(db.convertDocToObj),
            categories: categories.map(db.convertDocToObj),
        },
    };
}

I have passing the state value but nothing. I think it is to provide an variable for the state and slap it in where 'meat' is, but should i dont know if i am to make serverside request that way

const products = await Product.find({ category: 'meat' }).lean();


问:
React and Tailwind CSS: dynamically generated classes are not being applied
I'm just learning React and Tailwind CSS and had a strange experience with CSS grid using Tailwind classes. I've made the buttons for a calculator, with the last Button spanning two columns:

App.js:

```<code>export default function App() {
  return (
    <div className="flex min-h-screen items-center justify-center bg-blue-400">
      <Calculator />
    </div>
  );
}
</code>```

Calculator.js

```<code>import { IoBackspaceOutline } from "react-icons/io5";

export const Calculator = () => {
  return (
    <div className="grid grid-cols-4 grid-rows-5 gap-2">
      <Button>AC</Button>
      <Button>
        <IoBackspaceOutline size={26} />
      </Button>
      <Button>%</Button>
      <Button>÷</Button>
      <Button>7</Button>
      <Button>8</Button>
      <Button>9</Button>
      <Button>x</Button>
      <Button>4</Button>
      <Button>5</Button>
      <Button>6</Button>
      <Button>-</Button>
      <Button>1</Button>
      <Button>2</Button>
      <Button>3</Button>
      <Button>+</Button>
      <Button>0</Button>
      <Button>.</Button>
      <Button colSpan={2}>=</Button>
    </div>
  );
};

const Button = ({ colSpan = 1, rowSpan = 1, children }) => {
  return (
    <div
      className={`col-span-${colSpan} row-span-${rowSpan} bg-white p-3 rounded`}
    >
      <div className="flex items-center justify-center">{children}</div>
    </div>
  );
};
</code>```

This doesn't work (tested in Chrome):

Now here comes the weird part. I replaced the returned JSX from the App component with HTML from a Tailwind tutorial and deleted it again.

```<code><div className="bg-blue-400 text-blue-400 min-h-screen flex items-center justify-center">
  <div className="grid grid-cols-3 gap-2">
    <div className="col-span-2 bg-white p-10 rounded">1</div>
    <div className="bg-white p-10 rounded">2</div>
    <div className="row-span-3 bg-white p-10 rounded">3</div>
    <div className="bg-white p-10 rounded">4</div>
    <div className="bg-white p-10 rounded">5</div>
    <div className="bg-white p-10 rounded">6</div>
    <div className="col-span-2 bg-white p-10 rounded">7</div>
    <div className="bg-white p-10 rounded">8</div>
    <div className="bg-white p-10 rounded">9</div>
  </div>
</div>
</code>```

After I Ctrl-Z'd a bunch of times, so I had only the previous code, my button suddenly spans two columns as intended:

I checked to make sure that there were no changes in the code:

My friend even cloned my repo, followed the same steps and got the same result.
He suspects that it has something to do with the variable classNames in my Button component with regards to Tailwind's JIT compiler, but none of us can pinpoint the error.

Am I using variable CSS classes wrong?

This has been a WTF moment. What could be the reason for this?

答:
The CSS file generated by Tailwind will only include classes that it recognizes when it scans your code, which means that dynamically generated classes (e.g. col-span-${colSpan}) will not be included.

If you only need to span 2 columns, you could pass boolean values which will trigger the addition of a full col-span-2 or row-span-2 utility class to be added:

```<code>const Button = ({ colSpan = false, rowSpan = false, children }) => {
  return (
    <div
      className={`${colSpan ? 'col-span-2' : ''} ${rowSpan ? 'row-span-2' : ''} bg-white p-3 rounded`}
    >
      <div className="flex items-center justify-center">{children}</div>
    </div>
  );
};
</code>```

Otherwise, you could pass the values as classes to the Button component:

```<code><Button className='col-span-2 row-span-1'>=</Button>

const Button = ({ className, children }) => {
  return (
    <div
      className={`${className} bg-white p-3 rounded`}
    >
      <div className="flex items-center justify-center">{children}</div>
    </div>
  );
};
</code>```

More information: https://tailwindcss.com/docs/content-configuration#dynamic-class-names

Body:
I'm just learning React and Tailwind CSS and had a strange experience with CSS grid using Tailwind classes. I've made the buttons for a calculator, with the last Button spanning two columns:

App.js:

export default function App() {
  return (

      <Calculator />

  );
}

Calculator.js

import { IoBackspaceOutline } from "react-icons/io5";

export const Calculator = () => {
  return (

      <Button>AC</Button>
      <Button>
        <IoBackspaceOutline size={26} />
      </Button>
      <Button>%</Button>
      <Button>÷</Button>
      <Button>7</Button>
      <Button>8</Button>
      <Button>9</Button>
      <Button>x</Button>
      <Button>4</Button>
      <Button>5</Button>
      <Button>6</Button>
      <Button>-</Button>
      <Button>1</Button>
      <Button>2</Button>
      <Button>3</Button>
      <Button>+</Button>
      <Button>0</Button>
      <Button>.</Button>
      <Button colSpan={2}>=</Button>

  );
};

const Button = ({ colSpan = 1, rowSpan = 1, children }) => {
  return (
    <div
      className={`col-span-${colSpan} row-span-${rowSpan} bg-white p-3 rounded`}
    >

{children}

  );
};

This doesn't work (tested in Chrome):

Now here comes the weird part. I replaced the returned JSX from the App component with HTML from a Tailwind tutorial and deleted it again.

1

2

3

4

5

6

7

8

9

After I Ctrl-Z'd a bunch of times, so I had only the previous code, my button suddenly spans two columns as intended:

I checked to make sure that there were no changes in the code:

My friend even cloned my repo, followed the same steps and got the same result.
He suspects that it has something to do with the variable classNames in my Button component with regards to Tailwind's JIT compiler, but none of us can pinpoint the error.

Am I using variable CSS classes wrong?

This has been a WTF moment. What could be the reason for this?

Body:
The CSS file generated by Tailwind will only include classes that it recognizes when it scans your code, which means that dynamically generated classes (e.g. col-span-${colSpan}) will not be included.

If you only need to span 2 columns, you could pass boolean values which will trigger the addition of a full col-span-2 or row-span-2 utility class to be added:

const Button = ({ colSpan = false, rowSpan = false, children }) => {
  return (
    <div
      className={`${colSpan ? 'col-span-2' : ''} ${rowSpan ? 'row-span-2' : ''} bg-white p-3 rounded`}
    >
      <div className="flex items-center justify-center">{children}</div>
    </div>
  );
};

Otherwise, you could pass the values as classes to the Button component:

<Button className='col-span-2 row-span-1'>=</Button>

const Button = ({ className, children }) => {
  return (
    <div
      className={`${className} bg-white p-3 rounded`}
    >
      <div className="flex items-center justify-center">{children}</div>
    </div>
  );
};

More information: https://tailwindcss.com/docs/content-configuration#dynamic-class-names


问:
How to prevent React / React Native from automatically attaching a stacktrace to my console warnings in the React Native Debugger
I like to use the console to debug my React-Native (0.63.4) application.
For some time now, React seems to automatically add a stack trace to my console.warn and console.error logs.
For example, the logs look like this in the Chrome debugger:

As you can see in the screenshot, the log message is actually collapsed (see small arrow in the upper left). So I assume that the stacktrace is added via some function in React in addition to the "normal" stacktrace. When I expand the message, the "normal" stacktrace of the Chrome debugger appears below, e.g.

:

I'm sure this feature might be quite helpful, but the logs become completely illegible and confusing if they contain a few warnings. Therefore My question, does anyone know how to disable this feature?

答:
Actually, The Debuggers are mainly used to debug the app or trace the issue if we are facing anything in code.

So If there is an issue then we can get the proper stack of the issue to know from where the exact mistake is with which we can solve the problems in our code.

For this reason, we can accept that there will be no way to manage it manually.

Also, there is no manual documentation to manage the logs from React Native.


问:
Schema-validation: missing table [game]
I think it may be possible dupplicate of this: Schema-validation: missing table [hibernate_sequences] but I can't figure it out.

So in my application.properties file I have this option: spring.jpa.hibernate.ddl-auto=validate and I receive this error:

Schema-validation: missing table [game]

Why I am receiving this?

Here is my Game class and User class:

Game:

```<code>@Entity
public class Game {
    @Id
    @Column(name = "GAME_NUMBER")
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long gameNumber;

    private int playerScore;
    private int NPCScore;
    private Date datetime;

    @ManyToOne
    @JoinColumn(name="USER_ID")
    private User user;

    public Game() {}

    public Game(int playerScore, int nPCScore, Date datetime) {
        super();
        this.playerScore = playerScore;
        this.NPCScore = nPCScore;
        this.datetime = datetime;
    }

    public User getUser() {
        return user;
    }
} + getters & setters
</code>```

User:

```<code>@Entity
public class User {
    @Id
    @Column(name = "USER_ID")
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long userId;

    private String username;
    private String password;

    @OneToMany(mappedBy="user",cascade=CascadeType.ALL)
    private List<Game> games;

    @ElementCollection
    private List<Date> startSessions;

    public User() {}

    public User(String username, String password, List<Game> games, List<Date> startSessions) {
        super();
        this.username = username;
        this.password = password;
        this.games = games;
        this.startSessions = startSessions;
    }
}
</code>```

答:
Add this in application.yml:</p>
```<code>spring:
  jpa:
    properties:
      hibernate:
        default_schema: game
</code>```

Title: Schema-validation: missing table [game]

Body:
I think it may be possible dupplicate of this: Schema-validation: missing table [hibernate_sequences] but I can't figure it out.

So in my application.properties file I have this option: spring.jpa.hibernate.ddl-auto=validate and I receive this error:

Schema-validation: missing table [game]

Why I am receiving this?

Here is my Game class and User class:

Game:

@Entity
public class Game {
    @Id
    @Column(name = "GAME_NUMBER")
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long gameNumber;

    private int playerScore;
    private int NPCScore;
    private Date datetime;

    @ManyToOne
    @JoinColumn(name="USER_ID")
    private User user;

    public Game() {}

    public Game(int playerScore, int nPCScore, Date datetime) {
        super();
        this.playerScore = playerScore;
        this.NPCScore = nPCScore;
        this.datetime = datetime;
    }

    public User getUser() {
        return user;
    }
} + getters & setters

User:

@Entity
public class User {
    @Id
    @Column(name = "USER_ID")
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long userId;

    private String username;
    private String password;

    @OneToMany(mappedBy="user",cascade=CascadeType.ALL)
    private List<Game> games;

    @ElementCollection
    private List<Date> startSessions;

    public User() {}

    public User(String username, String password, List<Game> games, List<Date> startSessions) {
        super();
        this.username = username;
        this.password = password;
        this.games = games;
        this.startSessions = startSessions;
    }
}

Body:
Add this in application.yml:

spring:
  jpa:
    properties:
      hibernate:
        default_schema: game


问:
Caller does not have permission for DOCUMENT AI
I am trying to parse documents through Document AI batchprocess and while sending get request to document AI to get the response I get the error Caller does not have permission.Any solution there for this.Here I am attaching the picture for reference.

答:
Quoted from this doc:

Google Cloud APIs use the OAuth 2.0 protocol for authenticating both user accounts and service accounts. The OAuth 2.0 authentication process determines both the principal and the application.

Most Google Cloud APIs also support anonymous access to public data using API keys. However, API keys only identify the application, not the principal. When using API keys, the principal must be authenticated by other means.

I can see that you are using an API key to try and authorize the call from the URL. If you are using the API key, it only identifies the application, not the principal. So you should have to authenticate the principal(User or Service Account) using OAuth 2.0. Refer to this doc for more information.

Try setting the following in the headers as mentioned in the "Try this API -> credentials -> click on (?)":

```<code>GET https://documentai.googleapis.com/v1/%5BNAME%5D?key=[YOUR_API_KEY] HTTP/1.1

Authorization: Bearer [YOUR_ACCESS_TOKEN]

Accept: application/json
</code>```

Where YOUR_ACCESS_TOKEN can be found using the Cloud SDK and using the following command:

gcloud auth application-default print-access-token - This command is used for to print an access token for your current Application Default Credentials.

Body:
Quoted from this doc:

Google Cloud APIs use the OAuth 2.0 protocol for authenticating both user accounts and service accounts. The OAuth 2.0 authentication process determines both the principal and the application.

Most Google Cloud APIs also support anonymous access to public data using API keys. However, API keys only identify the application, not the principal. When using API keys, the principal must be authenticated by other means.

I can see that you are using an API key to try and authorize the call from the URL. If you are using the API key, it only identifies the application, not the principal. So you should have to authenticate the principal(User or Service Account) using OAuth 2.0. Refer to this doc for more information.

Try setting the following in the headers as mentioned in the "Try this API -> credentials -> click on (?)":

GET https://documentai.googleapis.com/v1/%5BNAME%5D?key=[YOUR_API_KEY] HTTP/1.1

Authorization: Bearer [YOUR_ACCESS_TOKEN]

Accept: application/json

Where YOUR_ACCESS_TOKEN can be found using the Cloud SDK and using the following command:

gcloud auth application-default print-access-token - This command is used for to print an access token for your current Application Default Credentials.


问:
memory loss in the following C code
I am getting memory loss of 16 byte in the following code for queuing. Could you please let me know how can get rid of this problem? The code is:

```<code>      void enqueue( enqueuenode * queueNode1 ,bplus *bplusNew){
      [98] -> enqueue *queue=NULL;
              queue = malloc(sizeof(enqueue_node));
              queue->bplus = bplusNew;
              queue->next= NULL;
                if(queueNode1->headNode == NULL){
                   queueNode1->headNode=queueNode1->tailNode = queue ;
                   }
                 else{
                 queueNode1->tailNode->next = queue;
                 queueNode1->tailNode = queue;
                 }
            }
</code>```

Following are two strucutres

```<code>         typedef struct enqueue_help{
           bplus bplusNode;
           struct enqueue_help * next;
         }*enqueue,enqueue_node;

        typedef struct enqueuenode_help{
          enqueue  headNode;
          enqueue  tailNode;
        }*enqueuenode,enqueuenode_node;
</code>```

And for the above code following is the valgrind output:

```<code>             =23800== 272 (16 direct, 256 indirect) bytes in 1 blocks are definitely lost in loss record 8 of 12
             ==23800==    at 0x4C2260E: malloc (vg_replace_malloc.c:207)
             ==23800==    by 0x4024BD:  enqueue(bplus.c:98)
             ==23800==    by 0x40260A:  PrintBplus (bplus.c:202)
             ==23800==    by 0x40286F: main (bplus.c:1251)
             ==23800==
</code>```

Here enqueuenode is the pointer for the structure which holds two enqueue as a head node and tail node. This is for traversal of queue during dequeuing. Each queue is a pointer for the structure which holds some node address which needs to be queued.

答:
This is where you allocated the lost memory.

Valgrind cannot report where you lost it, it only can keep track of allocations and deallocations.

Maybe you lose some nodes in one of your algorithms, which should be easy to test since the number of nodes decreases, but it's also possible that there is a bug in the code that frees the data structure.

Title: memory loss in the following C code

Body:
I am getting memory loss of 16 byte in the following code for queuing. Could you please let me know how can get rid of this problem? The code is:

      void enqueue( enqueuenode * queueNode1 ,bplus *bplusNew){
      [98] -> enqueue *queue=NULL;
              queue = malloc(sizeof(enqueue_node));
              queue->bplus = bplusNew;
              queue->next= NULL;
                if(queueNode1->headNode == NULL){
                   queueNode1->headNode=queueNode1->tailNode = queue ;
                   }
                 else{
                 queueNode1->tailNode->next = queue;
                 queueNode1->tailNode = queue;
                 }
            }

Following are two strucutres

         typedef struct enqueue_help{
           bplus bplusNode;
           struct enqueue_help * next;
         }*enqueue,enqueue_node;

        typedef struct enqueuenode_help{
          enqueue  headNode;
          enqueue  tailNode;
        }*enqueuenode,enqueuenode_node;

And for the above code following is the valgrind output:

             =23800== 272 (16 direct, 256 indirect) bytes in 1 blocks are definitely lost in loss record 8 of 12
             ==23800==    at 0x4C2260E: malloc (vg_replace_malloc.c:207)
             ==23800==    by 0x4024BD:  enqueue(bplus.c:98)
             ==23800==    by 0x40260A:  PrintBplus (bplus.c:202)
             ==23800==    by 0x40286F: main (bplus.c:1251)
             ==23800==

Here enqueuenode is the pointer for the structure which holds two enqueue as a head node and tail node. This is for traversal of queue during dequeuing. Each queue is a pointer for the structure which holds some node address which needs to be queued.


问:
Changing display property for a hidden text area element with Playwright in Python
I am trying to paste some text from the clipboard into a hidden textarea input element on a website with Playwright, but I keep getting issues because the element has attribute:

```<code>style="visibility:hidden, display:none;"
</code>```

I am trying to resolve that with page.evaluate command in Playwright, but can't seem to change the element visibility status. Here is the returned error:

```<code>page.evaluate("[id=txbLongDescription] => document.querySelector('[id=txbLongDescription]')", style='visibility:visible')
TypeError: Page.evaluate() got an unexpected keyword argument 'style'
</code>```

Here is my code so far:

```<code>def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context(accept_downloads=True)
page = context.new_page()

# Click in description input field

#paste description from clipboard
paste = pc.paste()

page.evaluate("[id=txbLongDescription] => document.querySelector('[id=txbLongDescription]')", style='visibility:visible')

page.fill('textarea[id=\"txbLongDescription\"]', f'{paste}')

#---------------------
context.close()
browser.close()

with sync_playwright() as playwright:
    run(playwright)
print('Done')
</code>```

答:
Here is my solution:

page.eval_on_selector(
  selector="textarea", # Modify the selector to fit yours.
  expression="(el) => el.style.display = 'inline-block'",
)
```

Here is the document of eval_on_selector().

Body:
I am trying to paste some text from the clipboard into a hidden textarea input element on a website with Playwright, but I keep getting issues because the element has attribute:

style="visibility:hidden, display:none;"

I am trying to resolve that with page.evaluate command in Playwright, but can't seem to change the element visibility status. Here is the returned error:

page.evaluate("[id=txbLongDescription] => document.querySelector('[id=txbLongDescription]')", style='visibility:visible')
TypeError: Page.evaluate() got an unexpected keyword argument 'style'

Here is my code so far:

def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context(accept_downloads=True)
page = context.new_page()

# Click in description input field

#paste description from clipboard
paste = pc.paste()

page.evaluate("[id=txbLongDescription] => document.querySelector('[id=txbLongDescription]')", style='visibility:visible')

page.fill('textarea[id=\"txbLongDescription\"]', f'{paste}')

#---------------------
context.close()
browser.close()

with sync_playwright() as playwright:
    run(playwright)
print('Done')

Body:
Here is my solution:

page.eval_on_selector(
  selector="textarea", # Modify the selector to fit yours.
  expression="(el) => el.style.display = 'inline-block'",
)

Here is the document of eval_on_selector().


问:
SwiftUI MVVM With ObservedObject
UPDATE (2/10/22 @ 11:30am CST):

I rewrote the workflow so that my viewModel conforms to the ObservableObject protocol and no longer conforms to the CreateUser class. Now my variables are updating properly (tested via print("\(viewModel.loadingStatus)") both before and after the loadingState value is set.

However, my view that uses a switch statement to show the current state of the view (i.e. switches on loadingState) does not update, even though the value of loadingState in the viewModel is being set correctly and I'm able to use that print statement to show that it's being set, in the view itself.

I even tried setting changing the viewModel's @Published var loadingState to read as:

```<code>@Published var loadingState: LoadingState = .loading {
    willSet {
        objectwillchange.send()
    }
}
</code>```

Of course, according to Apple's docs, that's exactly the same behavior as @Published by itself, and it did nothing to solve the issue.

It seems as though everything else is working properly, except for the view switch case not updating when loadingState changes in the viewModel.

Original Post:

I have a multi-page form where all of the views of the form share the same ObservableObject(s). What I would like to do is split up each individual view into an MVVM workflow so that the UI stuff is in the view and the data stuff is in the viewModel.

The issue is that since all of these views share the same ObservableObject(s), and the functions in each of the views make heavy use of these ObservableObjects (storing variables, using other functions, etc.), the viewModel can't just be an ObservableObject of its own, because I would need to write a custom intializer for everything (and there are a lot of variables). This also means that in my NavigationLink as well as the view's preview, I would have to call to every single one of those individually initialized vars.

CreateUser (the shared ObservableObject that has all of the form variables as @Published vars) is where I am setting all of the form variables as the user moves through the pages. The best I came up with was to conform my viewModel to CreateUser instead of simply ObservableObject. That seemed to work and after quite a bit of recoding, there were no more errors and my app built. That being said, as it's not working, I have a feeling that this is not the correct way to do it.

Unfortunately, it seems that the viewModel is not updating any of the CreateUser variables, nor is it accurately referencing the CreateUser variables that are being set. I tested this by using page 3 of the form (where the username is entered) as the test for the MVVM architecture, and asked it to print the variable from page 2. It returned the default value instead of what was actually set.

This means my data is not being passed through properly and my variables are not being referenced the way they should, so page 3 (the MVVM view) is stuck showing the loading state, even though it should show the loaded state once the json fetch is finished.

What is the proper procedure for instituting an MVVM workflow when you have multiple other ObservedObjects being utilized in each view? This is for the latest SwiftUI/XCode for iOS 15+.

Here's a bit of code to further explain (obviously very stripped down for this post, but you get the idea if you read my explanation above):

Main View:

```<code>import Combine
import SwiftUI

struct UsernameView: View {

@StateObject var viewModel: ViewModel

    var body: some View {
        VStack {
            List {
                switch viewModel.loadingState {
                    case .loading:
                        Section {
                            Text("I am loading")
                        }

                    case .loaded:
                        Section {
                            Text("I am loaded")
                        }

                    case .failed:
                        Section {
                            Text("Something went wrong")
                        }
                }
            }
        }
        .task {
            viewModel.userActivity = Date.now
            jsonFetch.sink (receiveCompletion: { completion in
                switch completion {
                    case .failure:
                        viewModel.loadingState = .failed
                    case .finished:
                        viewModel.loadingState = .loaded
                    }
                },
                receiveValue: { loadedData in
                    viewModel.userData = loadedData
                }).store(in: &viewModel.dataTransfer.requests)
        }
    }
}
</code>```

View Model:

```<code>import Combine
import SwiftUI

extension UsernameView {
    class ViewModel: CreateUser {

        @ObservedObject var textBindingManager = TextBindingManager(limit: 15)

        @Published var loadingState: LoadingState = .loading
        @Published var userData: [Usernames] = []
        @Published var usernameExists: [UsernameExists] = []

        func editingChanged(_ value: String) {
            username = String(value.prefix(textBindingManager.characterLimit))

            let jsonFetchUserExistsURL = URL(string: "https://api.foo.com/userselect?user=\(user)")
            let jsonFetchUserExistsTask = dataTransfer.jsonFetch(jsonFetchUserExistsURL, defaultValue: [UsernameExists]())

            if username.count >= 8 {
                guard network.isNetworkActive else { loadingAlert = true; return }
                Task {
                    status = .loading
                    usernameExists.removeAll()
                    jsonFetchUserExistsTask.sink (receiveCompletion: { completion in
                        switch completion {
                        case .failure:
                            self.loadingState = .failed
                        case .finished:
                            return
                        }
                    },
                    receiveValue: { loadedUserExists in
                        self.usernameExists = loadedUserExists
                    }).store(in: &dataTransfer.requests)
                }
            }
        }

extension UsernameView.ViewModel {
    enum LoadingState {
        case loading, loaded, failed
    }
}
</code>```

CreateUser:

```<code>import Combine
import SwiftUI

class CreateUser: ObservableObject {

    @ObservedObject var dataTransfer = NetworkTransfer()
    let network: NetworkMonitor

    init(network: NetworkMonitor) {
        self.network = network
    }

    @Published var userActivity = Date.now
    @Published var userActivityAlert = false
    @Published var birthday = Date()
    @Published var username = ""
}
</code>```

答:
I think it would be important to take a look at your NavigationLinks and way you are passing down the view model to the multiple pages of the form from a parent view. I don't see how this is done in your post, however, so my answer will be a guess.

My assumption is that UsernameView is one of the multiple pages of your form, and all of the pages in your form all use @StateObject var viewModel: ViewModel. This would be a red flag, if you want to share the same view model across all of them. @StateObject signifies that the view owns that object, and will hold onto it  for the lifetime of the view. @ObservedObject on the other hand is a reference to an ObservableObject that should be passed into the view. If the multiple pages of your form all use @StateObject, then it's possible that the way you've constructed things, you're getting distinct instantiations of your view model, which is why you're seeing default values in other pages for a previous page's input.

Here is a simple, high-level overview of how I might go about it.

struct ParentView: View {
    @StateObject var viewModel = ViewModel()
    @State var page = 1
    var body: some View {
        switch page {
        case 1:
            ChildView1(viewModel: self.viewModel)
        case 2:
            ChildView2(viewModel: self.viewModel)
        }
    }
}
```
<pre class="lang-swift prettyprint-override"><code>struct ChildView1: View {
    @ObservedObject var viewModel: ViewModel
    var body: some View {
        Text(viewModel.username)
    }
}
</code>```

struct ChildView2: View {
    @ObservedObject var viewModel: ViewModel
    var body: some View {
        Text(viewModel.username)
    }
}
```

The example would show the same username in both child views. The parent did a single instantiation of the view model via the @StateObject, and passed it down to the children without re-instantiating the model into the @ObservedObjects. This way, you will have the same object in memory correctly shared among the views.

Title: SwiftUI MVVM With ObservedObject

Body:
UPDATE (2/10/22 @ 11:30am CST):

I rewrote the workflow so that my viewModel conforms to the ObservableObject protocol and no longer conforms to the CreateUser class. Now my variables are updating properly (tested via print("\(viewModel.loadingStatus)") both before and after the loadingState value is set.

However, my view that uses a switch statement to show the current state of the view (i.e. switches on loadingState) does not update, even though the value of loadingState in the viewModel is being set correctly and I'm able to use that print statement to show that it's being set, in the view itself.

I even tried setting changing the viewModel's @Published var loadingState to read as:

@Published var loadingState: LoadingState = .loading {
    willSet {
        objectwillchange.send()
    }
}

Of course, according to Apple's docs, that's exactly the same behavior as @Published by itself, and it did nothing to solve the issue.

It seems as though everything else is working properly, except for the view switch case not updating when loadingState changes in the viewModel.

Original Post:

I have a multi-page form where all of the views of the form share the same ObservableObject(s). What I would like to do is split up each individual view into an MVVM workflow so that the UI stuff is in the view and the data stuff is in the viewModel.

The issue is that since all of these views share the same ObservableObject(s), and the functions in each of the views make heavy use of these ObservableObjects (storing variables, using other functions, etc.), the viewModel can't just be an ObservableObject of its own, because I would need to write a custom intializer for everything (and there are a lot of variables). This also means that in my NavigationLink as well as the view's preview, I would have to call to every single one of those individually initialized vars.

CreateUser (the shared ObservableObject that has all of the form variables as @Published vars) is where I am setting all of the form variables as the user moves through the pages. The best I came up with was to conform my viewModel to CreateUser instead of simply ObservableObject. That seemed to work and after quite a bit of recoding, there were no more errors and my app built. That being said, as it's not working, I have a feeling that this is not the correct way to do it.

Unfortunately, it seems that the viewModel is not updating any of the CreateUser variables, nor is it accurately referencing the CreateUser variables that are being set. I tested this by using page 3 of the form (where the username is entered) as the test for the MVVM architecture, and asked it to print the variable from page 2. It returned the default value instead of what was actually set.

This means my data is not being passed through properly and my variables are not being referenced the way they should, so page 3 (the MVVM view) is stuck showing the loading state, even though it should show the loaded state once the json fetch is finished.

What is the proper procedure for instituting an MVVM workflow when you have multiple other ObservedObjects being utilized in each view? This is for the latest SwiftUI/XCode for iOS 15+.

Here's a bit of code to further explain (obviously very stripped down for this post, but you get the idea if you read my explanation above):

Main View:

import Combine
import SwiftUI

struct UsernameView: View {

@StateObject var viewModel: ViewModel

    var body: some View {
        VStack {
            List {
                switch viewModel.loadingState {
                    case .loading:
                        Section {
                            Text("I am loading")
                        }

                    case .loaded:
                        Section {
                            Text("I am loaded")
                        }

                    case .failed:
                        Section {
                            Text("Something went wrong")
                        }
                }
            }
        }
        .task {
            viewModel.userActivity = Date.now
            jsonFetch.sink (receiveCompletion: { completion in
                switch completion {
                    case .failure:
                        viewModel.loadingState = .failed
                    case .finished:
                        viewModel.loadingState = .loaded
                    }
                },
                receiveValue: { loadedData in
                    viewModel.userData = loadedData
                }).store(in: &viewModel.dataTransfer.requests)
        }
    }
}

View Model:

import Combine
import SwiftUI

extension UsernameView {
    class ViewModel: CreateUser {

        @ObservedObject var textBindingManager = TextBindingManager(limit: 15)

        @Published var loadingState: LoadingState = .loading
        @Published var userData: [Usernames] = []
        @Published var usernameExists: [UsernameExists] = []

        func editingChanged(_ value: String) {
            username = String(value.prefix(textBindingManager.characterLimit))

            let jsonFetchUserExistsURL = URL(string: "https://api.foo.com/userselect?user=\(user)")
            let jsonFetchUserExistsTask = dataTransfer.jsonFetch(jsonFetchUserExistsURL, defaultValue: [UsernameExists]())

            if username.count >= 8 {
                guard network.isNetworkActive else { loadingAlert = true; return }
                Task {
                    status = .loading
                    usernameExists.removeAll()
                    jsonFetchUserExistsTask.sink (receiveCompletion: { completion in
                        switch completion {
                        case .failure:
                            self.loadingState = .failed
                        case .finished:
                            return
                        }
                    },
                    receiveValue: { loadedUserExists in
                        self.usernameExists = loadedUserExists
                    }).store(in: &dataTransfer.requests)
                }
            }
        }

extension UsernameView.ViewModel {
    enum LoadingState {
        case loading, loaded, failed
    }
}

CreateUser:

import Combine
import SwiftUI

class CreateUser: ObservableObject {

    @ObservedObject var dataTransfer = NetworkTransfer()
    let network: NetworkMonitor

    init(network: NetworkMonitor) {
        self.network = network
    }

    @Published var userActivity = Date.now
    @Published var userActivityAlert = false
    @Published var birthday = Date()
    @Published var username = ""
}

Body:
I think it would be important to take a look at your NavigationLinks and way you are passing down the view model to the multiple pages of the form from a parent view. I don't see how this is done in your post, however, so my answer will be a guess.

My assumption is that UsernameView is one of the multiple pages of your form, and all of the pages in your form all use @StateObject var viewModel: ViewModel. This would be a red flag, if you want to share the same view model across all of them. @StateObject signifies that the view owns that object, and will hold onto it  for the lifetime of the view. @ObservedObject on the other hand is a reference to an ObservableObject that should be passed into the view. If the multiple pages of your form all use @StateObject, then it's possible that the way you've constructed things, you're getting distinct instantiations of your view model, which is why you're seeing default values in other pages for a previous page's input.

Here is a simple, high-level overview of how I might go about it.

struct ParentView: View {
    @StateObject var viewModel = ViewModel()
    @State var page = 1
    var body: some View {
        switch page {
        case 1:
            ChildView1(viewModel: self.viewModel)
        case 2:
            ChildView2(viewModel: self.viewModel)
        }
    }
}

struct ChildView1: View {
    @ObservedObject var viewModel: ViewModel
    var body: some View {
        Text(viewModel.username)
    }
}

struct ChildView2: View {
    @ObservedObject var viewModel: ViewModel
    var body: some View {
        Text(viewModel.username)
    }
}

The example would show the same username in both child views. The parent did a single instantiation of the view model via the @StateObject, and passed it down to the children without re-instantiating the model into the @ObservedObjects. This way, you will have the same object in memory correctly shared among the views.


问:
How can I return only what's inside my
 tag if someone makes a cURL or wget request to my link?
I have a simple "hello world" python script here

print("Hello World")

I uploaded it to my site (similar to Pastebin or GitHub gist)

https://www.bunlongheng.com/raw/YWFjOGMxYTktM2Y5Mi00ZDdlLWI1NWQtOTg0Y2EwYjVlMDM5

When I shared the link, I can see the icon, and the title field as the actual text, it's nice. Tested in iPhone below

When I curl the link, I got <title> & <link> tags come with it like this:

```<code><title>print("Hello World")</title><link rel="shortcut icon" href="https://i.imgur.com/yRk5mqb.png" />```print("Hello World")```
</code>```

Which of course will break if I remotely executed my codes like this

```<code>curl https://www.bunlongheng.com/raw/YWFjOGMxYTktM2Y5Mi00ZDdlLWI1NWQtOTg0Y2EwYjVlMDM5 | python

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   153    0   153    0     0    354      0 --:--:-- --:--:-- --:--:--   353
  File "<stdin>", line 1
    <title>print("Hello World")</title><link rel="shortcut icon" href="https://i.imgur.com/yRk5mqb.png" />```print("Hello World")```
    ^
SyntaxError: invalid syntax
</code>```

How can I return only what's inside my ``` tag if someone makes a cURL or wget to my link?

答:
similar to Quentin, i would check if the Accept-header contains the string "html", and serve the html if it does. but if it does not explicitly mention html, serve the python directly. because all web-browsers say some version of Accept: ...html... (like Chrome says Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 )

while wget/curl/libcurl just says Accept: */*

Title: How can I return only what's inside my <pre> tag if someone makes a cURL or wget request to my link?

Body:
I have a simple "hello world" python script here

print("Hello World")

I uploaded it to my site (similar to Pastebin or GitHub gist)

https://www.bunlongheng.com/raw/YWFjOGMxYTktM2Y5Mi00ZDdlLWI1NWQtOTg0Y2EwYjVlMDM5

When I shared the link, I can see the icon, and the title field as the actual text, it's nice. Tested in iPhone below

When I curl the link, I got <title> & <link> tags come with it like this:

<title>print("Hello World")</title><link rel="shortcut icon" href="https://i.imgur.com/yRk5mqb.png" />
print("Hello World")

Which of course will break if I remotely executed my codes like this

curl https://www.bunlongheng.com/raw/YWFjOGMxYTktM2Y5Mi00ZDdlLWI1NWQtOTg0Y2EwYjVlMDM5 | python

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   153    0   153    0     0    354      0 --:--:-- --:--:-- --:--:--   353
  File "<stdin>", line 1
    <title>print("Hello World")</title><link rel="shortcut icon" href="https://i.imgur.com/yRk5mqb.png" />
print("Hello World")

    ^
SyntaxError: invalid syntax

How can I return only what's inside my
 tag if someone makes a cURL or wget to my link?


问:
Non suspend function is not executed after suspend function
I have a suspend function userRepo.updateUserWithNewPersonalDetails(details) and after executing this function I want to execute success() function which is a call back.

but the issue is success() is not getting executed.

any suggestions on how to get this to work.

this sequence does not work

```<code>  SUCCESS -> {
                        progress.postValue(GONE)
                        userRepo.updateUserWithNewPersonalDetails(details) // EXECUTED
                        success() // NOT EXECUTED
                    }
</code>```

if I change it to call success() first then save to repo, it works fine. but this is not the right way of doing it I think.

could you suggest please

```<code>  SUCCESS -> {
                        progress.postValue(GONE)
                        success() // EXECUTED
                        userRepo.updateUserWithNewPersonalDetails(details) // EXECUTED
                    }
</code>```

Fragment call

```<code>viewModel.save(personalDetails) { activity?.onBackPressed() }
</code>```

ViewModel

```<code>fun save(details: PersonalDetails, success: () -> Unit) {
    viewModelScope.launch {
        userRepo.savePersonalDetails(details).collect {
            when (it.status) {
                LOADING -> {
                    progress.postValue(VISIBLE)
                }
                SUCCESS -> {
                    progress.postValue(GONE)
                    userRepo.updateUserWithNewPersonalDetails(details)
                    success() // THIS IS NOT EXECUTED
                }
                ERROR -> {
                    progress.postValue(GONE)
                    error.postValue(ErrorResult(errorCode = SNACKBAR_ID_USER_DETAILS_SAVE_FAIL))
                }
            }
        }
    }
}
</code>```

userRepository

```<code>suspend fun updateUserWithNewPersonalDetails(details: PersonalDetails) {
        userDao.get().collect { cachedUser ->
            val updatedCachedUser = UserDB(cachedUser.id, etc..)
            userDao.save(updatedCachedUser)
        }
    }
</code>```

答:
success() method isn't called because you collect Flow in updateUserWithNewPersonalDetails method:

```<code>userDao.get().collect {...}
</code>```

It suspends a coroutine execution. My guess is that it is an infinite Flow, which doesn't complete until coroutine is completed. That's why userDao.get().collect suspends execution.

I don't quite understand what you are trying to achieve in the updateUserWithNewPersonalDetails method, but it seems it doesn't update the DB. If you want to update user details in the DB, you don't need to collect Flow. You should have something like this:

```<code>suspend fun updateUserWithNewPersonalDetails(details: PersonalDetails) {
    userDao.update(details)
}
</code>```

where userDao.update(details) is a suspend method, which updates DB:

```<code>suspend fun update(details: PersonalDetails)
</code>```

Body:
I have a suspend function userRepo.updateUserWithNewPersonalDetails(details) and after executing this function I want to execute success() function which is a call back.

but the issue is success() is not getting executed.

any suggestions on how to get this to work.

this sequence does not work

  SUCCESS -> {
                        progress.postValue(GONE)
                        userRepo.updateUserWithNewPersonalDetails(details) // EXECUTED
                        success() // NOT EXECUTED
                    }

if I change it to call success() first then save to repo, it works fine. but this is not the right way of doing it I think.

could you suggest please

  SUCCESS -> {
                        progress.postValue(GONE)
                        success() // EXECUTED
                        userRepo.updateUserWithNewPersonalDetails(details) // EXECUTED
                    }

Fragment call

viewModel.save(personalDetails) { activity?.onBackPressed() }

ViewModel

fun save(details: PersonalDetails, success: () -> Unit) {
    viewModelScope.launch {
        userRepo.savePersonalDetails(details).collect {
            when (it.status) {
                LOADING -> {
                    progress.postValue(VISIBLE)
                }
                SUCCESS -> {
                    progress.postValue(GONE)
                    userRepo.updateUserWithNewPersonalDetails(details)
                    success() // THIS IS NOT EXECUTED
                }
                ERROR -> {
                    progress.postValue(GONE)
                    error.postValue(ErrorResult(errorCode = SNACKBAR_ID_USER_DETAILS_SAVE_FAIL))
                }
            }
        }
    }
}

userRepository

suspend fun updateUserWithNewPersonalDetails(details: PersonalDetails) {
        userDao.get().collect { cachedUser ->
            val updatedCachedUser = UserDB(cachedUser.id, etc..)
            userDao.save(updatedCachedUser)
        }
    }

Body:
success() method isn't called because you collect Flow in updateUserWithNewPersonalDetails method:

userDao.get().collect {...}

It suspends a coroutine execution. My guess is that it is an infinite Flow, which doesn't complete until coroutine is completed. That's why userDao.get().collect suspends execution.

I don't quite understand what you are trying to achieve in the updateUserWithNewPersonalDetails method, but it seems it doesn't update the DB. If you want to update user details in the DB, you don't need to collect Flow. You should have something like this:

suspend fun updateUserWithNewPersonalDetails(details: PersonalDetails) {
    userDao.update(details)
}

where userDao.update(details) is a suspend method, which updates DB:

suspend fun update(details: PersonalDetails)


问:
Why closes my keyboard after every keystroke?
I'am working on an App for some algorithms. Something like "Question" if yes, then x and if no then y. Some I created a Component, for a single algorithm step.

Some of the answers are not only yes or no, so i added a optional text input to my component. If as possible answer in the algorithm "TextInput" there should be a TextInput Element and a Button with ok. After clicking Ok the TextInput should become a fixed Text. But after every keystroke the keyboard closes.

I found out, that this beahvior starts, after adding value and onTextChanged to the TextInput. But in other projects i got this exactly the same way working. Why? Can anyone help?

Here is my code for the component:

```<code>import { AutoSizeText, ResizeTextMode } from 'react-native-auto-size-text';
import { Dimensions, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { useState } from 'react';

export default function SingleAlgorithmStep(props) {
    const step = props.step;     //Inhalt des akutell auszuführenden Schritts
    const stepsDone = props.stepsDone;          //Array mit bereits erledigten Schritten
    const clickedButtons = props.clickedButtons;            //Array mit den bereits ausgewählten Buttons
    const currentAlgorithmJson = props.algorithmJson;           //Aktuellen Algorithmus von den Props auslesen

    const [textInputValue, changeTextInput] = useState('');

    let buttons = [];      //Array, was die Texte und die Anzahl der Buttons für diesen Step beinhaltet
    var buttonWidth = (Dimensions.get('window').width - 20);      //Breite eines Buttons entspricht der Bildschirmbreite abzüglich Rand
    if (Object.keys(step["Action"]).length > 1) {
        buttonWidth = (buttonWidth - (Object.keys(step["Action"]).length - 1) * 10) / Object.keys(step["Action"]).length;
    }     //Falls mehrere Buttons vorhanden sind, soll zwischen den Buttons etwas Platz sein und trotzdem sollen alle gleich groß sein

    for (const buttonText in step["Action"]) {
        const id = step["Question"] + " : " + buttonText;      //Einmalige ID erzeugen

        buttons = buttons.concat(
            <TouchableOpacity key={id} style={[styles.button, { width: buttonWidth, backgroundColor: clickedButtons.includes(id) ? "limegreen" : "dodgerblue" }]} onPress={() => {
                if (clickedButtons.filter(oldId => oldId.includes(step["Question"])).length > 0) {
                    //Falls auf einen bereits erledigten Schritt zurückgegangen wird...

                    props.actualizeButtons(clickedButtons.splice(0, stepsDone.indexOf(step)).concat(id));      //Gewählte Buttons werden bis zum Index des Schrittes beibehalten und der neue Button wird ergänzt
                    props.actualizeSteps(stepsDone.splice(0, stepsDone.indexOf(step) + 1).concat(currentAlgorithmJson[step["Action"][buttonText]]));     //Schritte werden bis zum Index des aktuellen Steps beibehalten und der nächste Schritt ergänzt
                }
                else {
                    props.actualizeButtons(clickedButtons.concat(id));     //ID zum Array hinzufüge, um angeklickte Buttons zu markieren
                    props.actualizeSteps(stepsDone.concat(currentAlgorithmJson[step["Action"][buttonText]]));      //Nächsten Schritt einfügen
                }
            }}>
                <AutoSizeText style={[styles.buttonText, { width: buttonWidth }]} fontSize={18} minFontSize={18} numberOfLines={3} mode={ResizeTextMode.min_font_size}>{buttonText === "TextInput" ? "Ok" : buttonText}</AutoSizeText>
            </TouchableOpacity>
        );
    }     //Jeden Button aus dem JSON als Element zur Liste hinzufügen, um so dynamisch die Anzahl der Button und den Button Text zu regulieren

    return (
        <View style={{ marginBottom: 15 }}>
            <AutoSizeText style={styles.Question} fontSize={24} minFontSize={21} numberOfLines={5} mode={ResizeTextMode.min_font_size}>{step["Question"]}</AutoSizeText>
            {Object.keys(step["Action"]).includes("TextInput") ?  !clickedButtons.includes(step["Question"] + " : " + "TextInput") ? <TextInput key={Math.random()} style={styles.input} value={textInputValue} onChangeText={(textInputValue) => changeTextInput(textInputValue)} placeholder={step["Question"]}></TextInput> : <Text>{textInputValue}</Text> : null}
            <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}>
                {buttons}
            </View>
        </View>
    )
}

const styles = StyleSheet.create({
    Question: {
        width: Dimensions.get('window').width - 20,
        minHeight: 40,
        borderColor: 'black',
        borderWidth: 2,
        textAlign: 'center',
    },
    input: {
        borderWidth: 1,
        borderColor: 'black',
        width: '100%',
        fontSize: 18,
        padding: 5,
        marginTop: 5,
    },
    button: {
        marginTop: 10,
        minHeight: 30,
        justifyContent: 'space-around'
    },
    buttonText: {
        textAlign: 'center',
        color: 'white',
        minHeight: 30,
        textAlignVertical: 'center'
    }
});
</code>```

答:
This is the default behavior when  TextInput is a child component to scrollable components, ScrollView, FlatList OR SectionList.

Make always keyboard persist tap  as below:

<FlatList
keyboardShouldPersistTaps="always"

//...otherProps
 />

```
<p>Then remove the <code>key</code> prop which is set to <code>Math.random()</code>. The random number value is dynamic for each rerender and doesn't provide any performance benefit.</p>
<pre class="lang-js prettyprint-override"><code><TextInput
  //key={Math.random()}  - Key should not be random number
  style={styles.input}
  value={textInputValue}
  onChangeText={(textInputValue) => changeTextInput(textInputValue)}
  placeholder={step["Question"]}
/>;

</code>```

Here working snack - https://snack.expo.dev/@emmbyiringiro/1920d6

Body:
I'am working on an App for some algorithms. Something like "Question" if yes, then x and if no then y. Some I created a Component, for a single algorithm step.

Some of the answers are not only yes or no, so i added a optional text input to my component. If as possible answer in the algorithm "TextInput" there should be a TextInput Element and a Button with ok. After clicking Ok the TextInput should become a fixed Text. But after every keystroke the keyboard closes.

I found out, that this beahvior starts, after adding value and onTextChanged to the TextInput. But in other projects i got this exactly the same way working. Why? Can anyone help?

Here is my code for the component:

import { AutoSizeText, ResizeTextMode } from 'react-native-auto-size-text';
import { Dimensions, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { useState } from 'react';

export default function SingleAlgorithmStep(props) {
    const step = props.step;     //Inhalt des akutell auszuführenden Schritts
    const stepsDone = props.stepsDone;          //Array mit bereits erledigten Schritten
    const clickedButtons = props.clickedButtons;            //Array mit den bereits ausgewählten Buttons
    const currentAlgorithmJson = props.algorithmJson;           //Aktuellen Algorithmus von den Props auslesen

    const [textInputValue, changeTextInput] = useState('');

    let buttons = [];      //Array, was die Texte und die Anzahl der Buttons für diesen Step beinhaltet
    var buttonWidth = (Dimensions.get('window').width - 20);      //Breite eines Buttons entspricht der Bildschirmbreite abzüglich Rand
    if (Object.keys(step["Action"]).length > 1) {
        buttonWidth = (buttonWidth - (Object.keys(step["Action"]).length - 1) * 10) / Object.keys(step["Action"]).length;
    }     //Falls mehrere Buttons vorhanden sind, soll zwischen den Buttons etwas Platz sein und trotzdem sollen alle gleich groß sein

    for (const buttonText in step["Action"]) {
        const id = step["Question"] + " : " + buttonText;      //Einmalige ID erzeugen

        buttons = buttons.concat(
            <TouchableOpacity key={id} style={[styles.button, { width: buttonWidth, backgroundColor: clickedButtons.includes(id) ? "limegreen" : "dodgerblue" }]} onPress={() => {
                if (clickedButtons.filter(oldId => oldId.includes(step["Question"])).length > 0) {
                    //Falls auf einen bereits erledigten Schritt zurückgegangen wird...

                    props.actualizeButtons(clickedButtons.splice(0, stepsDone.indexOf(step)).concat(id));      //Gewählte Buttons werden bis zum Index des Schrittes beibehalten und der neue Button wird ergänzt
                    props.actualizeSteps(stepsDone.splice(0, stepsDone.indexOf(step) + 1).concat(currentAlgorithmJson[step["Action"][buttonText]]));     //Schritte werden bis zum Index des aktuellen Steps beibehalten und der nächste Schritt ergänzt
                }
                else {
                    props.actualizeButtons(clickedButtons.concat(id));     //ID zum Array hinzufüge, um angeklickte Buttons zu markieren
                    props.actualizeSteps(stepsDone.concat(currentAlgorithmJson[step["Action"][buttonText]]));      //Nächsten Schritt einfügen
                }
            }}>
                <AutoSizeText style={[styles.buttonText, { width: buttonWidth }]} fontSize={18} minFontSize={18} numberOfLines={3} mode={ResizeTextMode.min_font_size}>{buttonText === "TextInput" ? "Ok" : buttonText}</AutoSizeText>
            </TouchableOpacity>
        );
    }     //Jeden Button aus dem JSON als Element zur Liste hinzufügen, um so dynamisch die Anzahl der Button und den Button Text zu regulieren

    return (
        <View style={{ marginBottom: 15 }}>
            <AutoSizeText style={styles.Question} fontSize={24} minFontSize={21} numberOfLines={5} mode={ResizeTextMode.min_font_size}>{step["Question"]}</AutoSizeText>
            {Object.keys(step["Action"]).includes("TextInput") ?  !clickedButtons.includes(step["Question"] + " : " + "TextInput") ? <TextInput key={Math.random()} style={styles.input} value={textInputValue} onChangeText={(textInputValue) => changeTextInput(textInputValue)} placeholder={step["Question"]}></TextInput> : <Text>{textInputValue}</Text> : null}
            <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-between' }}>
                {buttons}
            </View>
        </View>
    )
}

const styles = StyleSheet.create({
    Question: {
        width: Dimensions.get('window').width - 20,
        minHeight: 40,
        borderColor: 'black',
        borderWidth: 2,
        textAlign: 'center',
    },
    input: {
        borderWidth: 1,
        borderColor: 'black',
        width: '100%',
        fontSize: 18,
        padding: 5,
        marginTop: 5,
    },
    button: {
        marginTop: 10,
        minHeight: 30,
        justifyContent: 'space-around'
    },
    buttonText: {
        textAlign: 'center',
        color: 'white',
        minHeight: 30,
        textAlignVertical: 'center'
    }
});

Body:
This is the default behavior when  TextInput is a child component to scrollable components, ScrollView, FlatList OR SectionList.

Make always keyboard persist tap  as below:

<FlatList
keyboardShouldPersistTaps="always"

//...otherProps
 />

Then remove the key prop which is set to Math.random(). The random number value is dynamic for each rerender and doesn't provide any performance benefit.

<TextInput
  //key={Math.random()}  - Key should not be random number
  style={styles.input}
  value={textInputValue}
  onChangeText={(textInputValue) => changeTextInput(textInputValue)}
  placeholder={step["Question"]}
/>;

Here working snack - https://snack.expo.dev/@emmbyiringiro/1920d6


问:
How to get the length of a string field in Mongoose?
I am new to MongoDB and Mongoose.

I am practicing some of the queries with the following Schema and Model:

```<code>const articleSchema = mongoose.Schema({
  title: String,
  content: String,
});

const Article = mongoose.model('article', articleSchema);

</code>```

Let's say I added the following two documents:

```<code>{title: "One", content: "Content One"}
{title: "LongerTitleThanOne", content: "Content Two"}
</code>```

Which query can I use to find all documents where the "title" length is greater than 3?

I tried the following query but it only works with numbers:

```<code>Article.find({title:{$gt:3}}, (err,foundItems)=>{});
</code>```

Many thanks in advance for your help here.

答:
you can use $strLenCP and $expr:

mongo playground

```<code>Article.find({
  "$expr": {
    "$gt": [
      {
        "$strLenCP": "$title"
      },
      3
    ]
  }
})
</code>```

Body:
I am new to MongoDB and Mongoose.

I am practicing some of the queries with the following Schema and Model:

const articleSchema = mongoose.Schema({
  title: String,
  content: String,
});

const Article = mongoose.model('article', articleSchema);

Let's say I added the following two documents:

{title: "One", content: "Content One"}
{title: "LongerTitleThanOne", content: "Content Two"}

Which query can I use to find all documents where the "title" length is greater than 3?

I tried the following query but it only works with numbers:

Article.find({title:{$gt:3}}, (err,foundItems)=>{});

Many thanks in advance for your help here.

Body:
you can use $strLenCP and $expr:

mongo playground

Article.find({
  "$expr": {
    "$gt": [
      {
        "$strLenCP": "$title"
      },
      3
    ]
  }
})