问:
Can I have mixed data types in a tkinter Combobox?
I'm trying to create a tkinter combobox with integers and strings as values. But it seems like whatever is selected from the combobox can only be assigned to either IntVar() or StringVar(). Is there a tkinter variable type that can take both integers and strings?</p>
```<code>root = Tk()
root.geometry('{}x{}'.format(1000,1000))
integer = IntVar()
string = StringVar()
dropDownList = Combobox(root, value=[1,2,3,'x','y'], textvariable = integer) #what do I need to do with the textvariable?
dropDownList.pack()
root.mainloop()
</code>```

答:
Is there a tkinter variable type that can take both integers and strings?

No, there is not. However, the value from a StringVar can easily be converted to an integer if it's in the proper format.

Body:
I'm trying to create a tkinter combobox with integers and strings as values. But it seems like whatever is selected from the combobox can only be assigned to either IntVar() or StringVar(). Is there a tkinter variable type that can take both integers and strings?

root = Tk()
root.geometry('{}x{}'.format(1000,1000))
integer = IntVar()
string = StringVar()
dropDownList = Combobox(root, value=[1,2,3,'x','y'], textvariable = integer) #what do I need to do with the textvariable?
dropDownList.pack()
root.mainloop()


来源: stackexchange

问:
How can I convert an array of characters to an integer (for 2 or more digits)
The array has to be entered by the user, and not specified in the app itself.

```<code>char coeff[20];
char expo[20];
for (int i = 0; i < Size; i++) {
    cin >> coeff[i];
    cin >> expo[i];
}
</code>```

When i enter a number in the cin >> coeff[i] , it doesn't let me enter more than one digit, is there a way to enter more than 1 digit and still be saved in it in the variable?

PS. I'm forced into using an array of characters here and not integers

答:
I think your professor wants you to read in text, and then convert that text to a number. This is a silly requirement.

The sensible program would >> into ints directly

```<code>int coeff;
int expo;
std::cin >> coeff >> expo;
</code>```

To read it into intermediate text safely you could

```<code>std::string coeff_s;
std::string expo_s;
std::cin >> coeff_s >> expo_s;
int coeff = std::stoi(coeff_s);
int expo = std::stoi(expo_s);
</code>```

However I predict that your professor will insist on using raw char[] and not std::string. You have to be more careful (prior to C++20) with that, specifying the length of the char[].

```<code>char coeff_s[20];
char expo_s[20];
std::cin >> std::setw(20) >> coeff_s >> std::setw(20) >> expo_s;
int coeff = std::atoi(coeff_s);
int expo = std::atoi(expo_s);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The array has to be entered by the user, and not specified in the app itself.

char coeff[20];
char expo[20];
for (int i = 0; i < Size; i++) {
    cin >> coeff[i];
    cin >> expo[i];
}

When i enter a number in the cin >> coeff[i] , it doesn't let me enter more than one digit, is there a way to enter more than 1 digit and still be saved in it in the variable?

PS. I'm forced into using an array of characters here and not integers

Body:
I think your professor wants you to read in text, and then convert that text to a number. This is a silly requirement.

The sensible program would >> into ints directly

int coeff;
int expo;
std::cin >> coeff >> expo;

To read it into intermediate text safely you could

std::string coeff_s;
std::string expo_s;
std::cin >> coeff_s >> expo_s;
int coeff = std::stoi(coeff_s);
int expo = std::stoi(expo_s);

However I predict that your professor will insist on using raw char[] and not std::string. You have to be more careful (prior to C++20) with that, specifying the length of the char[].

char coeff_s[20];
char expo_s[20];
std::cin >> std::setw(20) >> coeff_s >> std::setw(20) >> expo_s;
int coeff = std::atoi(coeff_s);
int expo = std::atoi(expo_s);


问:
Using testthat with more than one expected outcome
I wish to check an R function that may output one of two acceptable values using the "testthat" package.  Here's a simplified example:

Foo <- function () {
  if (uncontrolable_condition) {
    matrix(as.raw(0x0c))
  } else {
    matrix(as.raw(0x03))
  }
}
```
<p>The best solution I could come up with is</p>
```result <- Foo()
expect_true(identical(result, matrix(as.raw(0x0c))) ||
            identical(result, matrix(as.raw(0x03))))
```

But this loses the functionality of waldo::compare: if I fail the test,
I have to manually run waldo::compare(Foo(), matrix(as.raw(0x0c))) to see how the output differs from the expectation.

答:
I think you're going to need a custom expectation. Based on the testthat pkgdown site, it might look something like this:

expect_options <- function(object, options) {

  # 1. Capture object and label
  act <- quasi_label(rlang::enquo(object), arg = "object")

  # 2. Call expect()
  compResults <- purrr::map_lgl(options, ~identical(act$val, .x))
  expect(
    any(compResults),
    sprintf(
      "Input (%s) is not one of the accepted options: %s",
            toString(act$val),
            paste(purrr::map_chr(options, toString), collapse = ", ")
    )
  )

  # 3. Invisibly return the value
  invisible(act$val)

}

expect_options(result, list(matrix(as.raw(0x0c)), matrix(as.raw(0x03))))

```

Body:
I wish to check an R function that may output one of two acceptable values using the "testthat" package.  Here's a simplified example:

Foo <- function () {
  if (uncontrolable_condition) {
    matrix(as.raw(0x0c))
  } else {
    matrix(as.raw(0x03))
  }
}

The best solution I could come up with is

result <- Foo()
expect_true(identical(result, matrix(as.raw(0x0c))) ||
            identical(result, matrix(as.raw(0x03))))

But this loses the functionality of waldo::compare: if I fail the test,
I have to manually run waldo::compare(Foo(), matrix(as.raw(0x0c))) to see how the output differs from the expectation.


问:
How to check if an image path is valid in JavaScript
What I want to do:

I want to add all images within a specific folder into a List.
The number of images within may vary between 1-10, but they are all named as numbers. The current way I am doing it is by first making all 10 of them and then removing the ones that don't exist.

```<code>List = []
for(var i=0; i<10; i++){
List.push('Folder/' + i+1 + 'jpg')
}

List = ['Folder/1.jpg', 'Folder/2.jpg', 'Folder/3.jpg'..]
</code>```

Note:
I am not going to host this anywhere. This is something I am making just for me. When I want to use the site I am just gonna open the index.html from the project folder.

I did some research and this seemed to work, but only while using live server in Visual Studio. This doesn't work when simply opening the index.html file locally.

```<code>function checkImage(){
temp_list = []
  for(i=0; i<List.length; i++){
    var http = new XMLHttpRequest();

    http.open('HEAD', List[i], false);
    http.send();

    if(http.status != 404){
      temp_list.push(List[i])
    }
  }

  List= temp_list
</code>```

I've also tried this, but it deletes everything in the List.

```<code>function checkImage(){
  temp_list = []
  for(i=0; i<List.length; i++){
    checkImage2(List[i])
  }
  console.log(temp_list.length)
  List= temp_list
}

function checkImage2(path){
    var img = new Image();
    img.onload = temp_list.push(path)
    img.onerror = temp_list.splice(path,1)
    img.src = path
}
</code>```

My question: Is there a better way to check if a file(img) exists?

答:
You could use image.onerror to check if image load correctly.

let images = ["invalid.jpg", "invalid2.jpg", "https://upload.wikimedia.org/wikipedia/en/thumb/8/80/Wikipedia-logo-v2.svg/1200px-Wikipedia-logo-v2.svg.png"]
let workedimages = images.slice()
images.forEach((item, index) => {
  let img = new Image()
  img.src = item
  img.onerror = () => workedimages.splice(workedimages.indexOf(item), 1)
  if (index == images.length - 1) {
    img.onload = () =>
      console.log(workedimages)
  }
})```

Body:
What I want to do:

I want to add all images within a specific folder into a List.
The number of images within may vary between 1-10, but they are all named as numbers. The current way I am doing it is by first making all 10 of them and then removing the ones that don't exist.

List = []
for(var i=0; i<10; i++){
List.push('Folder/' + i+1 + 'jpg')
}

List = ['Folder/1.jpg', 'Folder/2.jpg', 'Folder/3.jpg'..]

Note:
I am not going to host this anywhere. This is something I am making just for me. When I want to use the site I am just gonna open the index.html from the project folder.

I did some research and this seemed to work, but only while using live server in Visual Studio. This doesn't work when simply opening the index.html file locally.

function checkImage(){
temp_list = []
  for(i=0; i<List.length; i++){
    var http = new XMLHttpRequest();

    http.open('HEAD', List[i], false);
    http.send();

    if(http.status != 404){
      temp_list.push(List[i])
    }
  }

  List= temp_list

I've also tried this, but it deletes everything in the List.

function checkImage(){
  temp_list = []
  for(i=0; i<List.length; i++){
    checkImage2(List[i])
  }
  console.log(temp_list.length)
  List= temp_list
}

function checkImage2(path){
    var img = new Image();
    img.onload = temp_list.push(path)
    img.onerror = temp_list.splice(path,1)
    img.src = path
}

My question: Is there a better way to check if a file(img) exists?


问:
How to limit Google Cloud Platform "BigQuery Metadata Viewer" permission?
I have 10 tables under my dataset. I need to create "BigQuery Metadata Viewer" permission but would like to neglect 2 tables under my dataset. So that BigQuery Metadata Viewer policy only will be able to access 8 tables.

I see that there is "condition" tab but could not figure out how to apply such a condition here.

答:
IAM condition is a nice way to solve that issue, but it's not available for BigQuery resources.

The solution here is to have 2 datasets

One with the 8 tables and the permission to view the metadata

one with the 2 other tables without the permission to view the metadata.


问:
esp32 arduino mqtt over websocket?
I'm working on something that needs MQTT over websocket (my server limitation on port 80)

I've looked everywhere for it, but either no one have ability to !ratain or (||) send over websocket packets. :D

I've somehow get to this include in arduino ---> its close src and low language (at least for me!)

```<code>#include "mqtt_client.h"
</code>```

and does this on my code:

```<code> esp_mqtt_client_config_t mqttConfig;
  mqttConfig.uri = "ws://test.mosquitto.org";
  mqttConfig.port = 8080;
  mqttConfig.transport = MQTT_TRANSPORT_OVER_WS;
  mqttConfig.event_handle(evt);
  esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqttConfig);
  //esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, client);
  esp_mqtt_client_start(client);
</code>```

ERROR:

```<code>cannot convert 'void (*)(esp_mqtt_event_handle_t) {aka void (*)(esp_mqtt_event_t*)}' to 'esp_mqtt_event_handle_t {aka esp_mqtt_event_t*}' in argument passing
</code>```

I'll send the header file below and some more:

arduino_H file

答:
Here:
esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqttConfig); you are not giving the function handle, but... assigning the result of invoked function...

This should be:
esp_mqtt_client_handle_t client = esp_mqtt_client_init;

Title: esp32 arduino mqtt over websocket?

Body:
I'm working on something that needs MQTT over websocket (my server limitation on port 80)

I've looked everywhere for it, but either no one have ability to !ratain or (||) send over websocket packets. :D

I've somehow get to this include in arduino ---> its close src and low language (at least for me!)

#include "mqtt_client.h"

and does this on my code:

 esp_mqtt_client_config_t mqttConfig;
  mqttConfig.uri = "ws://test.mosquitto.org";
  mqttConfig.port = 8080;
  mqttConfig.transport = MQTT_TRANSPORT_OVER_WS;
  mqttConfig.event_handle(evt);
  esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqttConfig);
  //esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, client);
  esp_mqtt_client_start(client);

ERROR:

cannot convert 'void (*)(esp_mqtt_event_handle_t) {aka void (*)(esp_mqtt_event_t*)}' to 'esp_mqtt_event_handle_t {aka esp_mqtt_event_t*}' in argument passing

I'll send the header file below and some more:

arduino_H file


问:
How to handle Refesh-Tokens with GoogleApis for NodeJS Client?
I'm looking at the following documentation:
https://github.com/googleapis/google-api-nodejs-client#handling-refresh-tokens

Especially this part:

```<code>oauth2Client.on('tokens', (tokens) => {
  if (tokens.refresh_token) {
    // store the refresh_token in my database!
    console.log(tokens.refresh_token);
  }
  console.log(tokens.access_token);
});
</code>```

What I don't understand is why I should store the refresh-token in a database.
Is it due to that the refresh-token is only provided to me on the first authorization?
But even so, shouldn't that mean that this part:

```<code>oauth2Client.setCredentials({
  refresh_token: `STORED_REFRESH_TOKEN`
});
</code>```

should replace the comment above (// store the refresh_token in my database!)?
A.K.A:

```<code>oauth2Client.on('tokens', (tokens) => {
  if (tokens.refresh_token) {
    oauth2Client.setCredentials({
  refresh_token: tokens.refresh_token
  });
});
</code>```

This due to Google's statement in the documentation:
"This library will automatically use a refresh token to obtain a new access token if it is about to expire".

What I want to build is an application where people login with their Google-account and then can use several analytics tools I build utilizing f.e Google-analytics API.

I've managed via the documentation to set a valid access-token, but I'm really interested in this topic and really want to learn the refresh-part but have a really hard time wrapping my head around it. If someone could help me understand, I would be really greatful. If not, could someone point me to a great explanation of this (for nodejs) elsewhere? :)

答:
Refresh tokens exist to keep a balance between security and user experience.
Access tokens should be short-lived (read more about access token lifetime), just in case a malicious attacker gets access to it. Without Refresh tokens, you will need to request user authorization each time.

Refresh tokens should be stored in a safe place

Save refresh tokens in secure long-term storage and continue to use them as long as they remain valid.

When you call oauth2Client.setCredentials you are initializing the SDK, so it can use the refresh token to fetch a new access token, but the SDK is not storing the refresh token in any long-term storage. That's your application responsibility.

Take into account, a Refresh token can be revoked too, in case it was leaked, or has not been used for six months (for Google APIs). Also, rotating a refresh token regularly is a good security practice.

It's your application responsibility to handle that part too, you can read more about Refresh token expiration here

Body:
I'm looking at the following documentation:
https://github.com/googleapis/google-api-nodejs-client#handling-refresh-tokens

Especially this part:

oauth2Client.on('tokens', (tokens) => {
  if (tokens.refresh_token) {
    // store the refresh_token in my database!
    console.log(tokens.refresh_token);
  }
  console.log(tokens.access_token);
});

What I don't understand is why I should store the refresh-token in a database.
Is it due to that the refresh-token is only provided to me on the first authorization?
But even so, shouldn't that mean that this part:

oauth2Client.setCredentials({
  refresh_token: `STORED_REFRESH_TOKEN`
});

should replace the comment above (// store the refresh_token in my database!)?
A.K.A:

oauth2Client.on('tokens', (tokens) => {
  if (tokens.refresh_token) {
    oauth2Client.setCredentials({
  refresh_token: tokens.refresh_token
  });
});

This due to Google's statement in the documentation:
"This library will automatically use a refresh token to obtain a new access token if it is about to expire".

What I want to build is an application where people login with their Google-account and then can use several analytics tools I build utilizing f.e Google-analytics API.

I've managed via the documentation to set a valid access-token, but I'm really interested in this topic and really want to learn the refresh-part but have a really hard time wrapping my head around it. If someone could help me understand, I would be really greatful. If not, could someone point me to a great explanation of this (for nodejs) elsewhere? :)


问:
How to print color in console using System.out.println?
How can I print color in console? I want to show data in colors when the processor sends data and in different colors when it receives data.</p>

答:
This kotlin code worked for me

import java.io.PrintStream

sealed class BackgroundColor(val value: Int) {
    object Default : BackgroundColor(0)

    // normal colors
    object Black : BackgroundColor(40)
    object Red : BackgroundColor(41)
    object Green : BackgroundColor(42)
    object Yellow : BackgroundColor(43)
    object Blue : BackgroundColor(44)
    object Magenta : BackgroundColor(45)
    object Cyan : BackgroundColor(46)
    object White : BackgroundColor(47)

    // colors with high contrast
    object BlackBright : BackgroundColor(100)
    object RedBright : BackgroundColor(101)
    object GreenBright : BackgroundColor(102)
    object YellowBright : BackgroundColor(103)
    object BlueBright : BackgroundColor(104)
    object MagentaBright : BackgroundColor(105)
    object CyanBright : BackgroundColor(106)
    object WhiteBright : BackgroundColor(107)
}

sealed class TextColor(val value: Int) {
    object Default : TextColor(0)

    // normal colors
    object Black : TextColor(30)
    object Red : TextColor(31)
    object Green : TextColor(32)
    object Yellow : TextColor(33)
    object Blue : TextColor(34)
    object Magenta : TextColor(35)
    object Cyan : TextColor(36)
    object White : TextColor(37)

    // colors with high contrast
    object BlackBright : TextColor(90)
    object RedBright : TextColor(91)
    object GreenBright : TextColor(92)
    object YellowBright : TextColor(93)
    object BlueBright : TextColor(94)
    object MagentaBright : TextColor(95)
    object CyanBright : TextColor(96)
    object WhiteBright : TextColor(97)
}

fun styleOutput(
    backgroundColor: BackgroundColor = BackgroundColor.Default,
    textColor: TextColor = TextColor.Default,
    boldText : Boolean = false,
    italicText : Boolean = false,
    underLineText : Boolean = false,
    action : PrintStream.() -> Unit
) {
    val styleFormat = StringBuilder("${27.toChar()}[${backgroundColor.value};${textColor.value}")

   if (boldText)
       styleFormat.append(";1")

    if (italicText)
        styleFormat.append(";3")

    if (underLineText)
        styleFormat.append(";4")

    styleFormat.append("m")

    print(styleFormat)
    System.out.action()
    print("${27.toChar()}[0m")
}
```
<p>and to use it</p>
<pre class="lang-kotlin prettyprint-override"><code>print("text without styling")
styleOutput(backgroundColor = BackgroundColor.Blue, textColor = TextColor.GreenBright, boldText = true) {
    print("text with styling")
}
print("text without styling")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This kotlin code worked for me

import java.io.PrintStream

sealed class BackgroundColor(val value: Int) {
    object Default : BackgroundColor(0)

    // normal colors
    object Black : BackgroundColor(40)
    object Red : BackgroundColor(41)
    object Green : BackgroundColor(42)
    object Yellow : BackgroundColor(43)
    object Blue : BackgroundColor(44)
    object Magenta : BackgroundColor(45)
    object Cyan : BackgroundColor(46)
    object White : BackgroundColor(47)

    // colors with high contrast
    object BlackBright : BackgroundColor(100)
    object RedBright : BackgroundColor(101)
    object GreenBright : BackgroundColor(102)
    object YellowBright : BackgroundColor(103)
    object BlueBright : BackgroundColor(104)
    object MagentaBright : BackgroundColor(105)
    object CyanBright : BackgroundColor(106)
    object WhiteBright : BackgroundColor(107)
}

sealed class TextColor(val value: Int) {
    object Default : TextColor(0)

    // normal colors
    object Black : TextColor(30)
    object Red : TextColor(31)
    object Green : TextColor(32)
    object Yellow : TextColor(33)
    object Blue : TextColor(34)
    object Magenta : TextColor(35)
    object Cyan : TextColor(36)
    object White : TextColor(37)

    // colors with high contrast
    object BlackBright : TextColor(90)
    object RedBright : TextColor(91)
    object GreenBright : TextColor(92)
    object YellowBright : TextColor(93)
    object BlueBright : TextColor(94)
    object MagentaBright : TextColor(95)
    object CyanBright : TextColor(96)
    object WhiteBright : TextColor(97)
}

fun styleOutput(
    backgroundColor: BackgroundColor = BackgroundColor.Default,
    textColor: TextColor = TextColor.Default,
    boldText : Boolean = false,
    italicText : Boolean = false,
    underLineText : Boolean = false,
    action : PrintStream.() -> Unit
) {
    val styleFormat = StringBuilder("${27.toChar()}[${backgroundColor.value};${textColor.value}")

   if (boldText)
       styleFormat.append(";1")

    if (italicText)
        styleFormat.append(";3")

    if (underLineText)
        styleFormat.append(";4")

    styleFormat.append("m")

    print(styleFormat)
    System.out.action()
    print("${27.toChar()}[0m")
}

and to use it

print("text without styling")
styleOutput(backgroundColor = BackgroundColor.Blue, textColor = TextColor.GreenBright, boldText = true) {
    print("text with styling")
}
print("text without styling")


问:
How to open a Finder at the "current dir" on Mac OS in Python?
I'm aiming for my Python app to work on Windows and Mac.  I'm looking to open a Finder window at the current directory (where the program is running).

The code I wrote below opens a Windows Explorer at .\  (current dir) but what is the equivalent on Mac ?

```<code>import os
import platform
#--------------

def MOpen_Explorer_Or_Finder(self,obj):

Msystem_info = platform.uname()
if(str(Msystem_info.system)=="Windows"):

    MExplorer_path = os.path.join(os.getenv('WINDIR'), 'explorer.exe')
    subprocess.run([MExplorer_path, ".\\"])

else:
    ### Or if "Darwin" (MacOS), then open Finder
    ...
</code>```

答:
It is simply:

```<code>subprocess.run(["/usr/bin/open","."])
</code>```

For more details, see the manpage for open.

Body:
I'm aiming for my Python app to work on Windows and Mac.  I'm looking to open a Finder window at the current directory (where the program is running).

The code I wrote below opens a Windows Explorer at .\  (current dir) but what is the equivalent on Mac ?

import os
import platform
#--------------

def MOpen_Explorer_Or_Finder(self,obj):

Msystem_info = platform.uname()
if(str(Msystem_info.system)=="Windows"):

    MExplorer_path = os.path.join(os.getenv('WINDIR'), 'explorer.exe')
    subprocess.run([MExplorer_path, ".\\"])

else:
    ### Or if "Darwin" (MacOS), then open Finder
    ...

Body:
It is simply:

subprocess.run(["/usr/bin/open","."])

For more details, see the manpage for open.


问:
Android : Update data on car audio
Sorry for my pore english.

I do a radio player. I can get curent name and title so every 15 seconds I read the new informations and display them on the main activity and in the notification. When I connect my phone to my car, the firdt artist is well displayed. When the second comes, name is correct on my phone but not updated on the car's screen. Eachtime the connection is stoped and restarted, name is correct but never updated when the next song comes.

My class implement AudioManager.

I use this code to update metadata :

mediaSession is a MediaSessionCompat

```<code>   mediaSession.setMetadata(new MediaMetadataCompat.Builder()
    .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, strArtist)
    .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, strAlbum)
    .putString(MediaMetadataCompat.METADATA_KEY_TITLE, strTitle)
    .build());
</code>```

I think the update of mediaSession is not sent to the bluetooth device.

Is there a command to force the sync ?

Thank you for any help.

JC

答:
I was facing this issue. And the problem was a bit. In My case, I was not setting the duration for the music. And always it was going to 0 only. After lots of research over google and stack overflow itself. I was not able to get the solution. But finally, I have found it and now it's working fine. If one of you also facing the same issue please go through with the below solution.

```<code>    private fun initMediaSessionMetadata(currentTrack: MusicModel?) {
    var duration =
        (currentTrack?.duration?.toLong() ?: mMediaPlayer?.duration?.toLong()) ?: 1000
    duration = if (duration <= 0) 1000 else duration
    val info = MediaMetadataCompat.Builder()
        .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, currentTrack?.id.toString())
        .putString(MediaMetadata.METADATA_KEY_TITLE, currentTrack?.name)
        .putString(MediaMetadata.METADATA_KEY_ARTIST, currentTrack?.artists)
        .putString(MediaMetadata.METADATA_KEY_ALBUM_ART_URI, currentTrack?.thumbnail)
        .putLong(MediaMetadata.METADATA_KEY_DURATION, duration)
    val metadata = info.build()
    mediaSession?.setMetadata(metadata)
}
</code>```

I hope you will able to crack it now. The following line is only the main problem for me

duration = if (duration <= 0) 1000 else duration

After this, My Code is working very well. If you have any query you can connect me via comment.

Title: Android : Update data on car audio

Body:
Sorry for my pore english.

I do a radio player. I can get curent name and title so every 15 seconds I read the new informations and display them on the main activity and in the notification. When I connect my phone to my car, the firdt artist is well displayed. When the second comes, name is correct on my phone but not updated on the car's screen. Eachtime the connection is stoped and restarted, name is correct but never updated when the next song comes.

My class implement AudioManager.

I use this code to update metadata :

mediaSession is a MediaSessionCompat

   mediaSession.setMetadata(new MediaMetadataCompat.Builder()
    .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, strArtist)
    .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, strAlbum)
    .putString(MediaMetadataCompat.METADATA_KEY_TITLE, strTitle)
    .build());

I think the update of mediaSession is not sent to the bluetooth device.

Is there a command to force the sync ?

Thank you for any help.

JC

Body:
I was facing this issue. And the problem was a bit. In My case, I was not setting the duration for the music. And always it was going to 0 only. After lots of research over google and stack overflow itself. I was not able to get the solution. But finally, I have found it and now it's working fine. If one of you also facing the same issue please go through with the below solution.

    private fun initMediaSessionMetadata(currentTrack: MusicModel?) {
    var duration =
        (currentTrack?.duration?.toLong() ?: mMediaPlayer?.duration?.toLong()) ?: 1000
    duration = if (duration <= 0) 1000 else duration
    val info = MediaMetadataCompat.Builder()
        .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, currentTrack?.id.toString())
        .putString(MediaMetadata.METADATA_KEY_TITLE, currentTrack?.name)
        .putString(MediaMetadata.METADATA_KEY_ARTIST, currentTrack?.artists)
        .putString(MediaMetadata.METADATA_KEY_ALBUM_ART_URI, currentTrack?.thumbnail)
        .putLong(MediaMetadata.METADATA_KEY_DURATION, duration)
    val metadata = info.build()
    mediaSession?.setMetadata(metadata)
}

I hope you will able to crack it now. The following line is only the main problem for me

duration = if (duration <= 0) 1000 else duration

After this, My Code is working very well. If you have any query you can connect me via comment.


问:
What is the difference between spring-boot-starter-oauth2-client, spring-cloud-starter-oauth2 and spring-security-oauth2
I am developing a client application for client_credentials grant type flow in OAUTH2.

I am not able to decide on which dependency to use in my project for this purpose among the following.

spring-boot-starter-oauth2-client

spring-cloud-starter-oauth2

spring-security-oauth2

I referred this documentation from spring-projects in which under client-support section it had a table describing the available options. But I am not able to understand which column is referring to which of the above dependencies.

I want to configure a WebClient or RestTemplate which retrieves the OAUTH2 token from the auth-server automatically before accessing a resource-server.

Please guide me in choosing the right artifact for my project.

答:
If you are using Spring Boot you should choose org.springframework.boot:spring-boot-starter-oauth2-client.

This includes Spring Security's OAuth 2.0 Client support and provides Spring Boot auto-configuration to set up OAuth2/Open ID Connect clients.

You can read about how to configure client in the Spring Boot reference documentation.

You can also find additional details in the Spring Security reference documentation.

If you are not using Spring Boot then you should choose org.springframework.security:spring-security-oauth2-client. This also provides Spring Security's latest OAuth 2.0 Client support, but does not include the Spring Boot auto-configuration.

The corresponding documentation is also the Spring Security reference documentation.

The third dependency you mentioned org.springframework.security.oauth:spring-security-oauth2 should not be used because it is part of the legacy Spring Security OAuth project, which is now deprecated.

The functionality that this library provided has now been moved into Spring Security.

That is what the Migration Guide describes, the migration from the legacy project to the latest Spring Security support.

You should not use the org.springframework.cloud:spring-cloud-starter-oauth2 at this time, because it relies on the legacy OAuth support.

This is likely to change in the future, as the Spring Cloud team updates to the latest Spring Security support.


问:
python - On my horizontal bar plot how do I assign specific color to certain index
this is my simplified code

```<code>import numpy as np
import pandas as pd
pd.DataFrame(np.random.randint(1,100,6),index=['1200 am', '1230 am', '0340 pm', '1200 pm', '1030 am', '0140 pm'],columns=['value']).plot(kind='barh')
</code>```

I want bars for "am" colored in red to distinguish between "am" and "pm", how do I do that?

答:
You can plot your data in two passes using a mask like so:

```<code>import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(1,100,6),
             index=['1200 am', '1230 am', '0340 pm', '1200 pm', '1030 am', '0140 pm'],
             columns=['value'])

m = df.index.str.contains('am')
ax = df.value.mask(m).plot(kind='barh', label='pm', legend=True)
df.value.mask(~m).plot(kind='barh', color='r', ax=ax, label='am', legend=True)
</code>```

Body:
this is my simplified code

import numpy as np
import pandas as pd
pd.DataFrame(np.random.randint(1,100,6),index=['1200 am', '1230 am', '0340 pm', '1200 pm', '1030 am', '0140 pm'],columns=['value']).plot(kind='barh')

I want bars for "am" colored in red to distinguish between "am" and "pm", how do I do that?

Body:
You can plot your data in two passes using a mask like so:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(1,100,6),
             index=['1200 am', '1230 am', '0340 pm', '1200 pm', '1030 am', '0140 pm'],
             columns=['value'])

m = df.index.str.contains('am')
ax = df.value.mask(m).plot(kind='barh', label='pm', legend=True)
df.value.mask(~m).plot(kind='barh', color='r', ax=ax, label='am', legend=True)


问:
How to parallely `map(...)` on a custom, single-threaded iterator in Rust?
I have a MyReader that implements Iterator and produces Buffers where Buffer : Send. MyReader produces a lot of Buffers very quickly, but I have a CPU-intensive job to perform on each Buffer (.map(|buf| ...)) that is my bottleneck, and then gather the results (ordered). I want to parallelize the CPU intense work - hopefully to N threads, that would use work stealing to perform them as fast as the number of cores allows.

Edit: To be more precise. I am working on rdedup. MyStruct is Chunker which reads io::Read (typically stdio), finds parts (chunks) of data and yields them. Then map() is supposed, for each chunk, to calculate sha256 digest of it, compress, encrypt, save and return the digest as the result of map(...). Digest of saved data is used to build index of the data. The order between chunks being processed by  map(...) does not matter, but digest returned from each map(...) needs to be collected in the same order that the chunks were found. The actual save to file step is offloaded to yet another thread (writter thread). actual code of PR in question

I hoped I can use rayon for this, but rayon expect an iterator that is already parallizable - eg. a Vec<...> or something like that. I have found no way to get a par_iter from MyReader - my reader is very single-threaded in nature.

There is simple_parallel but documentation says it's not recommended for general use. And I want to make sure everything will just work.

I could just take a spmc queue implementation and a custom thread_pool, but I was hopping for an existing solution that is optimized and tested.

There's also pipeliner but doesn't support ordered map yet.

答:
There is now a dpc-pariter crate. Simply replace iter.map(fn) with iter.parallel_map(fn), which will perform work in parallel while preserving result order.  From the docs:

* drop-in replacement for standard iterators(*)
  * preserves order
  * lazy, somewhat like single-threaded iterators
  * panic propagation
* support for iterating over borrowed values using scoped threads
* backpressure
* profiling methods (useful for analyzing pipelined processing bottlenecks)

```

Also, Rayon has an open issue with a great in-depth discussion of various implementation details and limitations.

Body:
There is now a dpc-pariter crate. Simply replace iter.map(fn) with iter.parallel_map(fn), which will perform work in parallel while preserving result order.  From the docs:

* drop-in replacement for standard iterators(*)
  * preserves order
  * lazy, somewhat like single-threaded iterators
  * panic propagation
* support for iterating over borrowed values using scoped threads
* backpressure
* profiling methods (useful for analyzing pipelined processing bottlenecks)

Also, Rayon has an open issue with a great in-depth discussion of various implementation details and limitations.


问:
Pass pagination arguments in Fauna Function
I'm trying to build fauna function which will accept before or after arguments in Paginate function, but when I run it I have error Array, Set, or Page expected, String provided
So this arguments are only provided as string.

This is my fauna function:

```<code>Query(
  Lambda(
    ["paginationAfter", "paginationBefore"],
    If(
      IsEmpty(Var("paginationAfter")),
      If(
        IsEmpty(Var("paginationBefore")),
        Map(
          Paginate(Match(Index("get_logs_by_date")), { size: 10 }),
          Lambda(["created", "ref"], Get(Var("ref")))
        ),
        Map(
          Paginate(Match(Index("get_logs_by_date")), {
            before: Var("paginationBefore"),
            size: 10
          }),
          Lambda(["created", "ref"], Get(Var("ref")))
        )
      ),
      Map(
        Paginate(Match(Index("get_logs_by_date")), {
          after: Var("paginationAfter"),
          size: 10
        }),
        Lambda(["created", "ref"], Get(Var("ref")))
      )
    )
  )
)
</code>```

Any help is appreaciated.
Note that I'm not using GRAPHQL
Thanks

答: You are using IsEmpty, which requires an array or set. Instead, try using IsNull instead.

Body:
I'm trying to build fauna function which will accept before or after arguments in Paginate function, but when I run it I have error Array, Set, or Page expected, String provided
So this arguments are only provided as string.

This is my fauna function:

Query(
  Lambda(
    ["paginationAfter", "paginationBefore"],
    If(
      IsEmpty(Var("paginationAfter")),
      If(
        IsEmpty(Var("paginationBefore")),
        Map(
          Paginate(Match(Index("get_logs_by_date")), { size: 10 }),
          Lambda(["created", "ref"], Get(Var("ref")))
        ),
        Map(
          Paginate(Match(Index("get_logs_by_date")), {
            before: Var("paginationBefore"),
            size: 10
          }),
          Lambda(["created", "ref"], Get(Var("ref")))
        )
      ),
      Map(
        Paginate(Match(Index("get_logs_by_date")), {
          after: Var("paginationAfter"),
          size: 10
        }),
        Lambda(["created", "ref"], Get(Var("ref")))
      )
    )
  )
)

Any help is appreaciated.
Note that I'm not using GRAPHQL
Thanks


问:
Scrolling 2 different elements in same time
If i have a textarea element and a div element how can i scroll them both in one time? ( when i scroll textarea i want the div to do the same )

I want to use pure javascript, as simple code as it is possible.

Ty.

答:
While the question asked about doing it in pure JavaScript, if you want to do this with jQuery, all you need to do is tie the scrollTop property of one element to the scrollTop of the other, using a function tied to the scroll event.

Something along the lines of:

```<code>$('.linked').scroll(function(){
    $('.linked').scrollTop($(this).scrollTop());
})
</code>```

With that function, all elements with a class of linked will scroll whenever you use the scrollbars of one of them. (I assumed vertical scrolling, if you wanted horizontal, do the same but with scrollLeft.)

See http://jsfiddle.net/g8Krz/ for a working example of the above.

Body:
While the question asked about doing it in pure JavaScript, if you want to do this with jQuery, all you need to do is tie the scrollTop property of one element to the scrollTop of the other, using a function tied to the scroll event.

Something along the lines of:

$('.linked').scroll(function(){
    $('.linked').scrollTop($(this).scrollTop());
})

With that function, all elements with a class of linked will scroll whenever you use the scrollbars of one of them. (I assumed vertical scrolling, if you wanted horizontal, do the same but with scrollLeft.)

See http://jsfiddle.net/g8Krz/ for a working example of the above.


问:
If I can have multiple factory methods in a creator class, why would I ever need the abstract factory pattern?
The abstract factory pattern is useful when we have families of related classes, and we want to instantiate them without relying on the implementation. However, what's wrong with using the factory method pattern in such a situation?

Let's say that we want to construct cross-platform UI elements, e.g. TextBox and Button for Windows and macOS and treat them abstractly. This is the typical situation in which we use the abstract factory pattern, and we can do so by defining the following:

AbstractUIElementsFactory interface

WindowsUIElementsFactory implements AbstractUIElementsFactory

MacUIElementsFactory implements AbstractUIElementsFactory

TextBox abstract class

MacTextBox extends TextBox

WindowsTextBox extends TextBox

Button abstract class

MacButton extends Button

WindowsButton extends Button

and the application would decide which concrete factory to create (based on some OS discovery mechanism) and pass it to a UIApplication class, which instantiates a TextBox and a Button, and calls display on them (which are abstract methods that simply return a String).

The code for this situation:

package abstractFactory;

abstract class Button {
    public abstract void display();
}

class MacButton extends Button {
    public void display() {
        System.out.println("macButton");
    }
}

class WindowsButton extends Button {

    @Override
    public void display() {
        System.out.println("winButton");
    }
}

abstract class TextBox {
    public abstract void display();
}

class MacTextBox extends TextBox {

    @Override
    public void display() {
        System.out.println("macTextBox");
    }
}

class WinTextBox extends TextBox {

    @Override
    public void display() {
        System.out.println("winTextBox");
    }
}

interface UICreatorAbstractFactory {
    Button getButton();
    TextBox getTextBox();
}

class MacFactory implements UICreatorAbstractFactory {

    @Override
    public Button getButton() {
        return new MacButton();
    }

    @Override
    public TextBox getTextBox() {
        return new MacTextBox();
    }
}

class WindowsFactory implements UICreatorAbstractFactory {

    @Override
    public Button getButton() {
        return new WindowsButton();
    }

    @Override
    public TextBox getTextBox() {
        return new WinTextBox();
    }
}

class UIApplication {
    private UICreatorAbstractFactory factory;

    UIApplication(UICreatorAbstractFactory _factory) {
        factory = _factory;
    }

    public void displayUI() {
        factory.getButton().display();
        factory.getTextBox().display();
    }
}

public class Main {
    public static void main(String[] args) {
        new UIApplication(new MacFactory()).displayUI();
    }
}
```
<p>This implementation allows us to get UI elements transparently from factory implementations and also UI elements implementations, which is largely why we would use the pattern.</p>
<p>Using the same <code>TextBox</code>, <code>Button</code>, and their derivatives, we can have a factory method implementation with two factory methods in the <em>creator</em>, <code>UICreator</code>, each of which returns an abstract UI element. And we derive the <em>creator</em> and make two specializations <code>WindowsUICreator</code>, and <code>MacUICreator</code>, and each of which returns the appropriate concrete UI element, as follows:</p>
<pre class="lang-java prettyprint-override"><code>abstract class UICreator {

    public void displayUI() {
        getButton().display();
        getTextBox().display();
    }

    protected abstract Button getButton();
    protected abstract TextBox getTextBox();

}

class WindowsUICreator extends UICreator {

    @Override
    protected Button getButton() {
        return new WindowsButton();
    }

    @Override
    protected TextBox getTextBox() {
        return new WinTextBox();
    }
}

class MacUICreator extends UICreator {

    @Override
    protected Button getButton() {
        return new MacButton();
    }

    @Override
    protected TextBox getTextBox() {
        return new MacTextBox();
    }
}

public class Main {

    public static void main(String[] args) {
        new MacUICreator().displayUI();
    }
}
</code>```

What are the downsides of this design? I believe it provides the needed decoupling by not having to deal with any concrete classes, and also provides the proper extensibility in the sense that we can introduce new UI elements and give them new factory methods, or newly supported OSs and implement concrete creators for them. And if we can use the factory method pattern in the exact situation the abstract factory pattern was designed for, I don't understand why do we have it at all?

答:
They are both about creating new objects but the factory method is used to create one product only while the Abstract Factory is about creating families of related or dependent products.
In the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition, whereas the Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation.</p>

Body:
The abstract factory pattern is useful when we have families of related classes, and we want to instantiate them without relying on the implementation. However, what's wrong with using the factory method pattern in such a situation?

Let's say that we want to construct cross-platform UI elements, e.g. TextBox and Button for Windows and macOS and treat them abstractly. This is the typical situation in which we use the abstract factory pattern, and we can do so by defining the following:

AbstractUIElementsFactory interface

WindowsUIElementsFactory implements AbstractUIElementsFactory

MacUIElementsFactory implements AbstractUIElementsFactory

TextBox abstract class

MacTextBox extends TextBox

WindowsTextBox extends TextBox

Button abstract class

MacButton extends Button

WindowsButton extends Button

and the application would decide which concrete factory to create (based on some OS discovery mechanism) and pass it to a UIApplication class, which instantiates a TextBox and a Button, and calls display on them (which are abstract methods that simply return a String).

The code for this situation:

package abstractFactory;

abstract class Button {
    public abstract void display();
}

class MacButton extends Button {
    public void display() {
        System.out.println("macButton");
    }
}

class WindowsButton extends Button {

    @Override
    public void display() {
        System.out.println("winButton");
    }
}

abstract class TextBox {
    public abstract void display();
}

class MacTextBox extends TextBox {

    @Override
    public void display() {
        System.out.println("macTextBox");
    }
}

class WinTextBox extends TextBox {

    @Override
    public void display() {
        System.out.println("winTextBox");
    }
}

interface UICreatorAbstractFactory {
    Button getButton();
    TextBox getTextBox();
}

class MacFactory implements UICreatorAbstractFactory {

    @Override
    public Button getButton() {
        return new MacButton();
    }

    @Override
    public TextBox getTextBox() {
        return new MacTextBox();
    }
}

class WindowsFactory implements UICreatorAbstractFactory {

    @Override
    public Button getButton() {
        return new WindowsButton();
    }

    @Override
    public TextBox getTextBox() {
        return new WinTextBox();
    }
}

class UIApplication {
    private UICreatorAbstractFactory factory;

    UIApplication(UICreatorAbstractFactory _factory) {
        factory = _factory;
    }

    public void displayUI() {
        factory.getButton().display();
        factory.getTextBox().display();
    }
}

public class Main {
    public static void main(String[] args) {
        new UIApplication(new MacFactory()).displayUI();
    }
}

This implementation allows us to get UI elements transparently from factory implementations and also UI elements implementations, which is largely why we would use the pattern.

Using the same TextBox, Button, and their derivatives, we can have a factory method implementation with two factory methods in the creator, UICreator, each of which returns an abstract UI element. And we derive the creator and make two specializations WindowsUICreator, and MacUICreator, and each of which returns the appropriate concrete UI element, as follows:

abstract class UICreator {

    public void displayUI() {
        getButton().display();
        getTextBox().display();
    }

    protected abstract Button getButton();
    protected abstract TextBox getTextBox();

}

class WindowsUICreator extends UICreator {

    @Override
    protected Button getButton() {
        return new WindowsButton();
    }

    @Override
    protected TextBox getTextBox() {
        return new WinTextBox();
    }
}

class MacUICreator extends UICreator {

    @Override
    protected Button getButton() {
        return new MacButton();
    }

    @Override
    protected TextBox getTextBox() {
        return new MacTextBox();
    }
}

public class Main {

    public static void main(String[] args) {
        new MacUICreator().displayUI();
    }
}

What are the downsides of this design? I believe it provides the needed decoupling by not having to deal with any concrete classes, and also provides the proper extensibility in the sense that we can introduce new UI elements and give them new factory methods, or newly supported OSs and implement concrete creators for them. And if we can use the factory method pattern in the exact situation the abstract factory pattern was designed for, I don't understand why do we have it at all?


问:
EF Core ToArray analog
Most of you know that ToList(), ToArray() use a lot of memory because they recreate the array after N element. I need to get all rows from table and I wrote smth like this

```<code>ToArray(_dbContext.MyTable.Count(), _dbContext.MyTable.Select(x => ...})

T[] ToArray<T>(int arraySize, IEnumerable<T> list)
    {
      var result = new T[arraySize];
      byte tempIndex = 0;
      foreach (var item in list)
      {
        result[tempIndex] = item;
        tempIndex++;
      }
      return result;
    }
</code>```

This code uses about 10% less memory than simple

```<code>_dbContext.MyTable.Select(x => ...}).ToList() \ ToArray()
</code>```

Does EF have something similar to my code?

答:
EF does not have this, but neither is the proposed method a good solution.

The proposed solution is not good because it runs two queries on the database, and that extra database call will tend to outweigh the extra RAM use. But let's say you know the size of the results (maybe because of pagination) and can skip the extra database query. Even then, this is still slower than it needs to be.

Instead, the way to optimize this is by recognizing that neither ToArray() or ToList() are necessary in the first place in most situations. Learn to work with the resulting IEnumerable, IQueryable, IAsyncEnumerable, etc directly. You can already use them for databinding or in a foreach loop to create whatever result you need; there's rarely a real need to call ToArray() at all.

Most of the time when you seem to need ToList() or ToArray(), it's because you're calling a method asking for an argument of that type. These methods should also be updated to instead ask for IEnumerable or IAsyncEnumerable. If you can push this all the way down the chain, the memory efficiency of your code can be increased dramatically, because the full result set is never loaded into memory; you only ever have one record in memory at a time.

Title: EF Core ToArray analog

Body:
Most of you know that ToList(), ToArray() use a lot of memory because they recreate the array after N element. I need to get all rows from table and I wrote smth like this

ToArray(_dbContext.MyTable.Count(), _dbContext.MyTable.Select(x => ...})

T[] ToArray<T>(int arraySize, IEnumerable<T> list)
    {
      var result = new T[arraySize];
      byte tempIndex = 0;
      foreach (var item in list)
      {
        result[tempIndex] = item;
        tempIndex++;
      }
      return result;
    }

This code uses about 10% less memory than simple

_dbContext.MyTable.Select(x => ...}).ToList() \ ToArray()

Does EF have something similar to my code?


问:
Excel formula to extract string between 2 specific character
I have a data table that looks like this:

And am using the following forumula:
=MID(LEFT(F2,FIND("D",F2)-1),FIND(" ",F2)+1,LEN(F2))

With the goal of extracting the numeric value after the "D" character in my Visit column. Some visits have 1 digit after the "D", some are 2, max will be 3 digits. However, the formula I've tried to use above is returning blanks and #VALUE! only. I figured the number character between the D and the space would work, but then I realize not all will have the space (see C2D16). Can someone explain what I am doing incorrectly?

TIA

答:
Your original approach would work as well, as long you handle the error. In order to investigate errors, like #value it's always a good idea to break down the formula into pieces to locate the issue.

=MID(F2,FIND("D",F2)+1,IFERROR(FIND(" ",F2)-FIND("D",F2)-1,LEN(F2)-FIND("D",F2)))


问:
Programmatic NSScrollView with layout anchors - how to fix the scrolling?
Quite a few SO posts on implementing a scroll view programmatically but I haven't found a solution for this case... here I am adding subviews to the document view (with everything laid out using layout anchors), which all works apart from the scrolling.

I think the issue here is that AppKit interprets the constraints in the example to mean there isn't anything to scroll, but I am not sure why...

```<code>import Cocoa

class ViewController: NSViewController {

    var scrollView = NSScrollView()
    var contentView = NSClipView()
    var documentView = ParentView()
    var generateButton = NSButton()

    @objc func generate(_ sender: NSObject) {

        let child = ChildView()
        child.translatesAutoresizingMaskIntoConstraints = false
        documentView.addSubview(child)
        documentView.setupChildViewLayout(sv: child)
    }

    override func viewDidLoad() {

        super.viewDidLoad()
        view.addSubview(generateButton)
        view.addSubview(scrollView)
        setupLayout()
    }

    func setupLayout() {

        scrollView.contentView = contentView
        scrollView.documentView = documentView

        scrollView.borderType = .lineBorder
        scrollView.hasHorizontalScroller = true
        scrollView.hasVerticalScroller = true

        scrollView.translatesAutoresizingMaskIntoConstraints = false
        contentView.translatesAutoresizingMaskIntoConstraints = false
        documentView.translatesAutoresizingMaskIntoConstraints = false

        view.addConstraints([
            scrollView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10),
            scrollView.trailingAnchor.constraint(lessThanOrEqualTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -150),
            scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 80),
            scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -100)
        ])

        NSLayoutConstraint.activate([
            scrollView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10),
            scrollView.trailingAnchor.constraint(lessThanOrEqualTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -150),
            scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 80),
            scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -100)
        ])

        scrollView.addConstraints([
            contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            contentView.trailingAnchor.constraint(greaterThanOrEqualTo: scrollView.trailingAnchor),
            contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
            contentView.bottomAnchor.constraint(greaterThanOrEqualTo: scrollView.bottomAnchor)
        ])

        NSLayoutConstraint.activate([
            contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            contentView.trailingAnchor.constraint(greaterThanOrEqualTo: scrollView.trailingAnchor),
            contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
            contentView.bottomAnchor.constraint(greaterThanOrEqualTo: scrollView.bottomAnchor)
        ])

        scrollView.addConstraints([
            documentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            documentView.trailingAnchor.constraint(greaterThanOrEqualTo: scrollView.trailingAnchor),
            documentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
            documentView.bottomAnchor.constraint(greaterThanOrEqualTo: scrollView.bottomAnchor)
        ])

        NSLayoutConstraint.activate([
            documentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            documentView.trailingAnchor.constraint(greaterThanOrEqualTo: scrollView.trailingAnchor),
            documentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
            documentView.bottomAnchor.constraint(greaterThanOrEqualTo: scrollView.bottomAnchor)
        ])

        // Setup anchor constraints for the button
        setupGenerateButton()
        generateButton.translatesAutoresizingMaskIntoConstraints = false

        view.addConstraints([
            generateButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10),
            generateButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -30),
            generateButton.heightAnchor.constraint(equalToConstant: 30),
            generateButton.widthAnchor.constraint(equalToConstant: 200)
        ])

        NSLayoutConstraint.activate([
            generateButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10),
            generateButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -30),
            generateButton.heightAnchor.constraint(equalToConstant: 30),
            generateButton.widthAnchor.constraint(equalToConstant: 200)
        ])
    }

    func setupGenerateButton() {
        generateButton.attributedTitle = NSMutableAttributedString(string: "GenerateChildView", attributes: [NSAttributedString.Key.strokeColor: (NSColor.white), NSAttributedString.Key.font: NSFont.systemFont(ofSize: (NSFont.systemFontSize))])
        generateButton.wantsLayer = true
        generateButton.bezelColor = NSColor(red: 0.2, green: 0.2, blue: 0.6, alpha: 1.0)
        generateButton.action  = #selector(self.generate(_:))
    }

}

class ParentView: NSView {

    override func draw(_ dirtyRect: NSRect) {

        super.draw(dirtyRect)
    }

    func setupChildViewLayout(sv: ChildView) {

        if (self.subviews.count < 2) {

            self.addConstraints([
                sv.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor),
                sv.topAnchor.constraint(equalTo: self.topAnchor)
            ])

            NSLayoutConstraint.activate([
                sv.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor),
                sv.topAnchor.constraint(equalTo: self.topAnchor)
            ])
        }

        else {

            let c = self.subviews.count - 2
            let lastView = self.subviews[c]

            self.addConstraints([
                sv.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor),
                sv.topAnchor.constraint(equalTo: lastView.bottomAnchor)
            ])

            NSLayoutConstraint.activate([
                sv.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor),
                sv.topAnchor.constraint(equalTo: lastView.bottomAnchor)
            ])
        }
    }
}

class ChildView: NSView {

    override var intrinsicContentSize: NSSize {

        return CGSize(width: 650, height: 200)
    }

    override func draw(_ dirtyRect: NSRect) {

        super.draw(dirtyRect)

        NSColor.gray.set()
        self.bounds.frame()

    }
}

</code>```

答:
You're still pinning the content view and the document view to the scroll view. Only add constraints to the outside of the scroll view and the inside of the document view. Don't add constraints between the content view, the document view and the scroll view. Add constraints between the parent view and its child views so the childs views will fit inside the parent view.</p>
```<code>class ViewController: NSViewController {

    var scrollView = NSScrollView()
    var documentView = ParentView()
    var generateButton = NSButton()

    @objc func generate(_ sender: NSObject) {
        let child = ChildView()
        child.translatesAutoresizingMaskIntoConstraints = false
        documentView.addSubview(child)
        documentView.setupChildViewLayout(sv: child)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(generateButton)
        view.addSubview(scrollView)
        setupLayout()
    }

    func setupLayout() {
        scrollView.documentView = documentView

        scrollView.borderType = .lineBorder
        scrollView.hasHorizontalScroller = true
        scrollView.hasVerticalScroller = true

        scrollView.translatesAutoresizingMaskIntoConstraints = false
        documentView.translatesAutoresizingMaskIntoConstraints = false

        view.addConstraints([
            scrollView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10),
            scrollView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -150),
            scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 80),
            scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -100)
        ])

        // Setup anchor constraints for the button
        setupGenerateButton()
        generateButton.translatesAutoresizingMaskIntoConstraints = false

        view.addConstraints([
            generateButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10),
            generateButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -30),
            generateButton.heightAnchor.constraint(equalToConstant: 30),
            generateButton.widthAnchor.constraint(equalToConstant: 200)
        ])
    }

    func setupGenerateButton() {
        generateButton.attributedTitle = NSMutableAttributedString(string: "GenerateChildView", attributes: [NSAttributedString.Key.strokeColor: (NSColor.white), NSAttributedString.Key.font: NSFont.systemFont(ofSize: (NSFont.systemFontSize))])
        generateButton.wantsLayer = true
        generateButton.bezelColor = NSColor(red: 0.2, green: 0.2, blue: 0.6, alpha: 1.0)
        generateButton.action  = #selector(self.generate(_:))
    }

}

class ParentView: NSView {

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
    }

    func setupChildViewLayout(sv: ChildView) {

        if (self.subviews.count == 1) {
            self.addConstraints([
                sv.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor),
                sv.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor),
                sv.topAnchor.constraint(equalTo: self.topAnchor),
                sv.bottomAnchor.constraint(equalTo: self.bottomAnchor)
            ])
        }

        else {

            let c = self.subviews.count - 2
            let lastView = self.subviews[c]

            self.addConstraints([
                sv.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor),
                sv.topAnchor.constraint(equalTo: lastView.bottomAnchor)
            ])

            let bottomConstraints = self.constraints.filter {
                $0.firstAttribute == NSLayoutConstraint.Attribute.bottom
            }
            self.removeConstraints(bottomConstraints)
            self.addConstraints([
                sv.bottomAnchor.constraint(equalTo: self.bottomAnchor)
            ])
        }
    }
}

class ChildView: NSView {

    override var intrinsicContentSize: NSSize {

        return CGSize(width: 650, height: 200)
    }

    override func draw(_ dirtyRect: NSRect) {

        super.draw(dirtyRect)

        NSColor.gray.set()
        self.bounds.frame()

    }
}
</code>```

Body:
Quite a few SO posts on implementing a scroll view programmatically but I haven't found a solution for this case... here I am adding subviews to the document view (with everything laid out using layout anchors), which all works apart from the scrolling.

I think the issue here is that AppKit interprets the constraints in the example to mean there isn't anything to scroll, but I am not sure why...

import Cocoa

class ViewController: NSViewController {

    var scrollView = NSScrollView()
    var contentView = NSClipView()
    var documentView = ParentView()
    var generateButton = NSButton()

    @objc func generate(_ sender: NSObject) {

        let child = ChildView()
        child.translatesAutoresizingMaskIntoConstraints = false
        documentView.addSubview(child)
        documentView.setupChildViewLayout(sv: child)
    }

    override func viewDidLoad() {

        super.viewDidLoad()
        view.addSubview(generateButton)
        view.addSubview(scrollView)
        setupLayout()
    }

    func setupLayout() {

        scrollView.contentView = contentView
        scrollView.documentView = documentView

        scrollView.borderType = .lineBorder
        scrollView.hasHorizontalScroller = true
        scrollView.hasVerticalScroller = true

        scrollView.translatesAutoresizingMaskIntoConstraints = false
        contentView.translatesAutoresizingMaskIntoConstraints = false
        documentView.translatesAutoresizingMaskIntoConstraints = false

        view.addConstraints([
            scrollView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10),
            scrollView.trailingAnchor.constraint(lessThanOrEqualTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -150),
            scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 80),
            scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -100)
        ])

        NSLayoutConstraint.activate([
            scrollView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10),
            scrollView.trailingAnchor.constraint(lessThanOrEqualTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -150),
            scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 80),
            scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -100)
        ])

        scrollView.addConstraints([
            contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            contentView.trailingAnchor.constraint(greaterThanOrEqualTo: scrollView.trailingAnchor),
            contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
            contentView.bottomAnchor.constraint(greaterThanOrEqualTo: scrollView.bottomAnchor)
        ])

        NSLayoutConstraint.activate([
            contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            contentView.trailingAnchor.constraint(greaterThanOrEqualTo: scrollView.trailingAnchor),
            contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
            contentView.bottomAnchor.constraint(greaterThanOrEqualTo: scrollView.bottomAnchor)
        ])

        scrollView.addConstraints([
            documentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            documentView.trailingAnchor.constraint(greaterThanOrEqualTo: scrollView.trailingAnchor),
            documentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
            documentView.bottomAnchor.constraint(greaterThanOrEqualTo: scrollView.bottomAnchor)
        ])

        NSLayoutConstraint.activate([
            documentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            documentView.trailingAnchor.constraint(greaterThanOrEqualTo: scrollView.trailingAnchor),
            documentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
            documentView.bottomAnchor.constraint(greaterThanOrEqualTo: scrollView.bottomAnchor)
        ])

        // Setup anchor constraints for the button
        setupGenerateButton()
        generateButton.translatesAutoresizingMaskIntoConstraints = false

        view.addConstraints([
            generateButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10),
            generateButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -30),
            generateButton.heightAnchor.constraint(equalToConstant: 30),
            generateButton.widthAnchor.constraint(equalToConstant: 200)
        ])

        NSLayoutConstraint.activate([
            generateButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10),
            generateButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -30),
            generateButton.heightAnchor.constraint(equalToConstant: 30),
            generateButton.widthAnchor.constraint(equalToConstant: 200)
        ])
    }

    func setupGenerateButton() {
        generateButton.attributedTitle = NSMutableAttributedString(string: "GenerateChildView", attributes: [NSAttributedString.Key.strokeColor: (NSColor.white), NSAttributedString.Key.font: NSFont.systemFont(ofSize: (NSFont.systemFontSize))])
        generateButton.wantsLayer = true
        generateButton.bezelColor = NSColor(red: 0.2, green: 0.2, blue: 0.6, alpha: 1.0)
        generateButton.action  = #selector(self.generate(_:))
    }

}

class ParentView: NSView {

    override func draw(_ dirtyRect: NSRect) {

        super.draw(dirtyRect)
    }

    func setupChildViewLayout(sv: ChildView) {

        if (self.subviews.count < 2) {

            self.addConstraints([
                sv.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor),
                sv.topAnchor.constraint(equalTo: self.topAnchor)
            ])

            NSLayoutConstraint.activate([
                sv.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor),
                sv.topAnchor.constraint(equalTo: self.topAnchor)
            ])
        }

        else {

            let c = self.subviews.count - 2
            let lastView = self.subviews[c]

            self.addConstraints([
                sv.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor),
                sv.topAnchor.constraint(equalTo: lastView.bottomAnchor)
            ])

            NSLayoutConstraint.activate([
                sv.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor),
                sv.topAnchor.constraint(equalTo: lastView.bottomAnchor)
            ])
        }
    }
}

class ChildView: NSView {

    override var intrinsicContentSize: NSSize {

        return CGSize(width: 650, height: 200)
    }

    override func draw(_ dirtyRect: NSRect) {

        super.draw(dirtyRect)

        NSColor.gray.set()
        self.bounds.frame()

    }
}

Body:
You're still pinning the content view and the document view to the scroll view. Only add constraints to the outside of the scroll view and the inside of the document view. Don't add constraints between the content view, the document view and the scroll view. Add constraints between the parent view and its child views so the childs views will fit inside the parent view.

class ViewController: NSViewController {

    var scrollView = NSScrollView()
    var documentView = ParentView()
    var generateButton = NSButton()

    @objc func generate(_ sender: NSObject) {
        let child = ChildView()
        child.translatesAutoresizingMaskIntoConstraints = false
        documentView.addSubview(child)
        documentView.setupChildViewLayout(sv: child)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(generateButton)
        view.addSubview(scrollView)
        setupLayout()
    }

    func setupLayout() {
        scrollView.documentView = documentView

        scrollView.borderType = .lineBorder
        scrollView.hasHorizontalScroller = true
        scrollView.hasVerticalScroller = true

        scrollView.translatesAutoresizingMaskIntoConstraints = false
        documentView.translatesAutoresizingMaskIntoConstraints = false

        view.addConstraints([
            scrollView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10),
            scrollView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -150),
            scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 80),
            scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -100)
        ])

        // Setup anchor constraints for the button
        setupGenerateButton()
        generateButton.translatesAutoresizingMaskIntoConstraints = false

        view.addConstraints([
            generateButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 10),
            generateButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -30),
            generateButton.heightAnchor.constraint(equalToConstant: 30),
            generateButton.widthAnchor.constraint(equalToConstant: 200)
        ])
    }

    func setupGenerateButton() {
        generateButton.attributedTitle = NSMutableAttributedString(string: "GenerateChildView", attributes: [NSAttributedString.Key.strokeColor: (NSColor.white), NSAttributedString.Key.font: NSFont.systemFont(ofSize: (NSFont.systemFontSize))])
        generateButton.wantsLayer = true
        generateButton.bezelColor = NSColor(red: 0.2, green: 0.2, blue: 0.6, alpha: 1.0)
        generateButton.action  = #selector(self.generate(_:))
    }

}

class ParentView: NSView {

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
    }

    func setupChildViewLayout(sv: ChildView) {

        if (self.subviews.count == 1) {
            self.addConstraints([
                sv.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor),
                sv.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor),
                sv.topAnchor.constraint(equalTo: self.topAnchor),
                sv.bottomAnchor.constraint(equalTo: self.bottomAnchor)
            ])
        }

        else {

            let c = self.subviews.count - 2
            let lastView = self.subviews[c]

            self.addConstraints([
                sv.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor),
                sv.topAnchor.constraint(equalTo: lastView.bottomAnchor)
            ])

            let bottomConstraints = self.constraints.filter {
                $0.firstAttribute == NSLayoutConstraint.Attribute.bottom
            }
            self.removeConstraints(bottomConstraints)
            self.addConstraints([
                sv.bottomAnchor.constraint(equalTo: self.bottomAnchor)
            ])
        }
    }
}

class ChildView: NSView {

    override var intrinsicContentSize: NSSize {

        return CGSize(width: 650, height: 200)
    }

    override func draw(_ dirtyRect: NSRect) {

        super.draw(dirtyRect)

        NSColor.gray.set()
        self.bounds.frame()

    }
}


问:
Where are playwright screenshots going - and how can I control this?
I have a really basic playwright (v1.18.1) test on Windows (11).

import { test, expect } from '@playwright/test';

test('test', async ({ page }) => {
    await page.goto('http://whatsmyuseragent.org/');
    // await page.screenshot(
    //  {path: `./tests/tmp/screenshots/whats.my.ua.${project:name}.png`});
    await page.screenshot();
});
```
<p>And when I run the test above - it says it worked.</p>
<pre class="lang-bash prettyprint-override"><code>Running :
     cd C:\playwright\tests
     && npx playwright test whats_my_user_agent.spec.ts --reporter=list

    Running 5 tests using 3 workers

       ok   [webkit] › whats_my_user_agent.spec.ts:3:1 › test   (3s)
       ok   [firefox] › whats_my_user_agent.spec.ts:3:1 › test   (4s)
       ok   [chromium] › whats_my_user_agent.spec.ts:3:1 › test   (5s)
       ok   [Mobile Chrome] › whats_my_user_agent.spec.ts:3:1 › test   (2s)
       ok   [Mobile Safari] › whats_my_user_agent.spec.ts:3:1 › test   (2s)

       5 passed   (8s)
</code>```

But I can find no sign of the screenshot file. There is no feedback giving any hints.

Where are the screenshots stored?

Is there a way to control the filename used?

Can the filename include the project name so that 5 png files are not written over each other?

答: The screenshot is always returned as a buffer by the screenshot function. If you don't pass a path the only way to get that screenshot is through the buffer.

Body:
I have a really basic playwright (v1.18.1) test on Windows (11).

import { test, expect } from '@playwright/test';

test('test', async ({ page }) => {
    await page.goto('http://whatsmyuseragent.org/');
    // await page.screenshot(
    //  {path: `./tests/tmp/screenshots/whats.my.ua.${project:name}.png`});
    await page.screenshot();
});

And when I run the test above - it says it worked.

Running :
     cd C:\playwright\tests
     && npx playwright test whats_my_user_agent.spec.ts --reporter=list

    Running 5 tests using 3 workers

       ok   [webkit] › whats_my_user_agent.spec.ts:3:1 › test   (3s)
       ok   [firefox] › whats_my_user_agent.spec.ts:3:1 › test   (4s)
       ok   [chromium] › whats_my_user_agent.spec.ts:3:1 › test   (5s)
       ok   [Mobile Chrome] › whats_my_user_agent.spec.ts:3:1 › test   (2s)
       ok   [Mobile Safari] › whats_my_user_agent.spec.ts:3:1 › test   (2s)

       5 passed   (8s)

But I can find no sign of the screenshot file. There is no feedback giving any hints.

Where are the screenshots stored?

Is there a way to control the filename used?

Can the filename include the project name so that 5 png files are not written over each other?


问:
UseState renders me the previous state
I have two inputs that change the text of a P tag at the same time, but the problem is that the render that shows me is always the previous value that was saved. I understand that I have to use a useEffect to render the component again and show the current value, but in the inputs handleChange if or if I need to send to the SetState that changes the text, the value that was saved in the initialValue. Until now I am learning React and I have already tried a lot of things, but nothing works for me, how could I implement the useEffect in this case? Thank you very much for the help.

```<code>const initialValue = {
  input1: 0,
  input2: 0,
};

const TestState = () => {
  const [obj, setObj] = useState(initialValue);
  const [textChange, setTextChange] = useState("-");

  useEffect(() => {}, [obj]);

  const handleChange = (e) => {
    setObj({ ...obj, [e.target.name]: e.target.value });
    //Basically I need to do this -> setTextChange(e.target.value), but with the value stored in the initialValue.
    setTextChange(e.target.name === "input1" ? obj.input1 : obj.input2);
  };

  return (
    <div>
      <form>
        <input type="text" name="input1" onChange={handleChange} />
        <input type="text" name="input2" onChange={handleChange} />
      </form>
      <p>{textChange}</p>
    </div>
  );
};
</code>```

https://codesandbox.io/s/practical-mahavira-pd94p?file=/src/TestState.js

答:
The setter you get from useState (i.e. setObj) does not immediately alter the value/state of the object under control. The update occurs before the next render(). That is why your obj object appears to be stale.

Note, you don't need to replace the obj object itself, you're just updating its contents. You could just do this:

```<code>const [obj] = useState(initialValue);
...

const handleChange = (e) => {
  //setObj({ ...obj, [e.target.name]: e.target.value });
  obj[e.target.name] = e.target.value;
  setTextChange(e.target.name === "input1" ? obj.input1 : obj.input2);
}
</code>```

Title: UseState renders me the previous state

Body:
I have two inputs that change the text of a P tag at the same time, but the problem is that the render that shows me is always the previous value that was saved. I understand that I have to use a useEffect to render the component again and show the current value, but in the inputs handleChange if or if I need to send to the SetState that changes the text, the value that was saved in the initialValue. Until now I am learning React and I have already tried a lot of things, but nothing works for me, how could I implement the useEffect in this case? Thank you very much for the help.

const initialValue = {
  input1: 0,
  input2: 0,
};

const TestState = () => {
  const [obj, setObj] = useState(initialValue);
  const [textChange, setTextChange] = useState("-");

  useEffect(() => {}, [obj]);

  const handleChange = (e) => {
    setObj({ ...obj, [e.target.name]: e.target.value });
    //Basically I need to do this -> setTextChange(e.target.value), but with the value stored in the initialValue.
    setTextChange(e.target.name === "input1" ? obj.input1 : obj.input2);
  };

  return (

      <form>
        <input type="text" name="input1" onChange={handleChange} />
        <input type="text" name="input2" onChange={handleChange} />
      </form>

{textChange}

  );
};

https://codesandbox.io/s/practical-mahavira-pd94p?file=/src/TestState.js

Body:
The setter you get from useState (i.e. setObj) does not immediately alter the value/state of the object under control. The update occurs before the next render(). That is why your obj object appears to be stale.

Note, you don't need to replace the obj object itself, you're just updating its contents. You could just do this:

const [obj] = useState(initialValue);
...

const handleChange = (e) => {
  //setObj({ ...obj, [e.target.name]: e.target.value });
  obj[e.target.name] = e.target.value;
  setTextChange(e.target.name === "input1" ? obj.input1 : obj.input2);
}


问:
How to measure HTTP-Session Size?
Is there some effective and accurate way to track the size of a particular session in a servlet based application?</p>

答:
Java doesn't have a sizeof() method like C (see this post for more information) so you generally can't get the size of anything in Java.  However, you can track what goes into and is removed from the session with a HttpSessionAttributeListener (link is JavaEE 8 and below).  This will give you some visibility into the number of attributes and, to an extent, the amount of memory being used.  Something like:

```<code>import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

@WebListener
public class MySessionAttributeListener implements HttpSessionAttributeListener {

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        System.out.println( "the attribute \"" + event.getName() + "\" with the value \"" + event.getValue() + "\" has been added" );
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        System.our.println( "the attribute \"" + event.getName() + "\" with the value \"" + event.getValue() + "\" has been removed" );
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        System.out.println( "the attribute \"" + event.getName() + "\" with the value \"" + event.getValue() + "\" has been replaced" );
    }
}
</code>```

Title: How to measure HTTP-Session Size?

Body:
Java doesn't have a sizeof() method like C (see this post for more information) so you generally can't get the size of anything in Java.  However, you can track what goes into and is removed from the session with a HttpSessionAttributeListener (link is JavaEE 8 and below).  This will give you some visibility into the number of attributes and, to an extent, the amount of memory being used.  Something like:

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

@WebListener
public class MySessionAttributeListener implements HttpSessionAttributeListener {

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        System.out.println( "the attribute \"" + event.getName() + "\" with the value \"" + event.getValue() + "\" has been added" );
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        System.our.println( "the attribute \"" + event.getName() + "\" with the value \"" + event.getValue() + "\" has been removed" );
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        System.out.println( "the attribute \"" + event.getName() + "\" with the value \"" + event.getValue() + "\" has been replaced" );
    }
}


问:
Creating all possible combinations of multiple lists to create survey routing logic
I currently script a lot of surveys that use XML where you can create routing logic, exec blocks etc. I know / use some very basic python and I am trying to learn more that I can apply to my surveys.

At the start of my surveys I gather customer segmentation info such as Age, Location, Social grade etc. These are then combined for quota purposes.

These are saved in autofills with the following categories (IL stands for interlock)

IL_Gender

r1: Male

r2: Female

r3: Other

IL_Age

r1: 18-34

r2: 35-54

r3: 55plus

IL_Region

r1: North

r2: South

r3: East
r4: West

IL_SEG

r1: ABC1

r2: C2DE

From these autofills I would like to create all of the possible combinations (in this case 72) of these using the following syntax:

```<code><row label="r1" autofill="(IL_Gender.r1) and (IL_Age.r1) and (IL_Region.r1) and (IL_SEG.r1)">1_Male_Age_1834_North_ABC1</row>
<row label="r2" autofill="(IL_Gender.r1) and (IL_Age.r1) and (IL_Region.r1) and (IL_SEG.r2)">2_Male_Age_1834_North_C2DE</row>
<row label="r3" autofill="(IL_Gender.r1) and (IL_Age.r1) and (IL_Region.r2) and (IL_SEG.r1)">3_Male_Age_1834_South_ABC1</row>
<row label="r4" autofill="(IL_Gender.r1) and (IL_Age.r1) and (IL_Region.r2) and (IL_SEG.r2)">4_Male_Age_1834_South_C2DE</row>
<row label="r5" autofill="(IL_Gender.r1) and (IL_Age.r1) and (IL_Region.r3) and (IL_SEG.r1)">5_Male_Age_1834_East_ABC1</row>
<row label="r6" autofill="(IL_Gender.r1) and (IL_Age.r1) and (IL_Region.r3) and (IL_SEG.r2)">6_Male_Age_1834_East_C2DE</row>
<row label="r7" autofill="(IL_Gender.r1) and (IL_Age.r1) and (IL_Region.r4) and (IL_SEG.r1)">7_Male_Age_1834_West_ABC1</row>
<row label="r8" autofill="(IL_Gender.r1) and (IL_Age.r1) and (IL_Region.r4) and (IL_SEG.r2)">8_Male_Age_1834_West_C2DE</row>
<row label="r9" autofill="(IL_Gender.r1) and (IL_Age.r2) and (IL_Region.r1) and (IL_SEG.r1)">9_Male_Age_3554_North_ABC1</row>
<row label="r10" autofill="(IL_Gender.r1) and (IL_Age.r2) and (IL_Region.r1) and (IL_SEG.r2)">10_Male_Age_3554_North_C2DE</row>
<row label="r11" autofill="(IL_Gender.r1) and (IL_Age.r2) and (IL_Region.r2) and (IL_SEG.r1)">11_Male_Age_3554_South_ABC1</row>
<row label="r12" autofill="(IL_Gender.r1) and (IL_Age.r2) and (IL_Region.r2) and (IL_SEG.r2)">12_Male_Age_3554_South_C2DE</row>
</code>```

And so on...

I'm not asking for people to do this for me I'm just wondering how difficult this would be and if anyone could point me in the right direction on what functions to use / steps I can take and any resources that might help me learn how to do this.

答:
Ultimately this really depends on how your customer segmentation info is stored. Let's assume it's in dictionary form. Then you can use the itertools.product function to get everything you want but you also need to do a bit of preprocessing and some postprocessing to store it all in the html in the desired form. If you have a template library that will do this for you (your web framework may have something that is preferable. Ultimately this really depends on how you want to use the output. Here's one way:

```<code>from itertools import product
from string import Template

oneDict = {"IL_Gender":{"r1": "Male", "r2": "Female", "r3": "Other"},
           "IL_Age": {"r1": "18-34", "r2": "35-54", "r3": "55plus"},
           "IL_Region": {"r1": "North", "r2": "South", "r3": "East", "r4": "West"},
           "IL_SEG": {"r1": "ABC1", "r2": "C2DE"}
          }

# create list of lists of outerkey.innerkey
arrays = []
for key in oneDict.keys():
    arrays.append([key + '.' + val for val in oneDict[key].keys()])

table_rows = []
t=Template('<row label=\"r$label\" autofill=\"($gender) and ($age) and ($region) \
            and ($seg)\">${label}_${gender}_${age}_${region}_${seg}</row>')

for idx, tup in enumerate(product(*arrays)):
    d = dict(label=idx, gender=tup[0], age=tup[1], region=tup[2], seg=tup[3])
    table_rows.append(t.safe_substitute(d))

# show first and last row
print(table_rows[0])
print(table_rows[71])
</code>```

Here I use Python's builtin Template strings which require the {}s around the use of the keys with trailing _ in the template string but are not required in the earlier instances in the templated string.

Body:
I currently script a lot of surveys that use XML where you can create routing logic, exec blocks etc. I know / use some very basic python and I am trying to learn more that I can apply to my surveys.

At the start of my surveys I gather customer segmentation info such as Age, Location, Social grade etc. These are then combined for quota purposes.

These are saved in autofills with the following categories (IL stands for interlock)

IL_Gender

r1: Male

r2: Female

r3: Other

IL_Age

r1: 18-34

r2: 35-54

r3: 55plus

IL_Region

r1: North

r2: South

r3: East
r4: West

IL_SEG

r1: ABC1

r2: C2DE

From these autofills I would like to create all of the possible combinations (in this case 72) of these using the following syntax:

<row label="r1" autofill="(IL_Gender.r1) and (IL_Age.r1) and (IL_Region.r1) and (IL_SEG.r1)">1_Male_Age_1834_North_ABC1</row>
<row label="r2" autofill="(IL_Gender.r1) and (IL_Age.r1) and (IL_Region.r1) and (IL_SEG.r2)">2_Male_Age_1834_North_C2DE</row>
<row label="r3" autofill="(IL_Gender.r1) and (IL_Age.r1) and (IL_Region.r2) and (IL_SEG.r1)">3_Male_Age_1834_South_ABC1</row>
<row label="r4" autofill="(IL_Gender.r1) and (IL_Age.r1) and (IL_Region.r2) and (IL_SEG.r2)">4_Male_Age_1834_South_C2DE</row>
<row label="r5" autofill="(IL_Gender.r1) and (IL_Age.r1) and (IL_Region.r3) and (IL_SEG.r1)">5_Male_Age_1834_East_ABC1</row>
<row label="r6" autofill="(IL_Gender.r1) and (IL_Age.r1) and (IL_Region.r3) and (IL_SEG.r2)">6_Male_Age_1834_East_C2DE</row>
<row label="r7" autofill="(IL_Gender.r1) and (IL_Age.r1) and (IL_Region.r4) and (IL_SEG.r1)">7_Male_Age_1834_West_ABC1</row>
<row label="r8" autofill="(IL_Gender.r1) and (IL_Age.r1) and (IL_Region.r4) and (IL_SEG.r2)">8_Male_Age_1834_West_C2DE</row>
<row label="r9" autofill="(IL_Gender.r1) and (IL_Age.r2) and (IL_Region.r1) and (IL_SEG.r1)">9_Male_Age_3554_North_ABC1</row>
<row label="r10" autofill="(IL_Gender.r1) and (IL_Age.r2) and (IL_Region.r1) and (IL_SEG.r2)">10_Male_Age_3554_North_C2DE</row>
<row label="r11" autofill="(IL_Gender.r1) and (IL_Age.r2) and (IL_Region.r2) and (IL_SEG.r1)">11_Male_Age_3554_South_ABC1</row>
<row label="r12" autofill="(IL_Gender.r1) and (IL_Age.r2) and (IL_Region.r2) and (IL_SEG.r2)">12_Male_Age_3554_South_C2DE</row>

And so on...

I'm not asking for people to do this for me I'm just wondering how difficult this would be and if anyone could point me in the right direction on what functions to use / steps I can take and any resources that might help me learn how to do this.

Body:
Ultimately this really depends on how your customer segmentation info is stored. Let's assume it's in dictionary form. Then you can use the itertools.product function to get everything you want but you also need to do a bit of preprocessing and some postprocessing to store it all in the html in the desired form. If you have a template library that will do this for you (your web framework may have something that is preferable. Ultimately this really depends on how you want to use the output. Here's one way:

from itertools import product
from string import Template

oneDict = {"IL_Gender":{"r1": "Male", "r2": "Female", "r3": "Other"},
           "IL_Age": {"r1": "18-34", "r2": "35-54", "r3": "55plus"},
           "IL_Region": {"r1": "North", "r2": "South", "r3": "East", "r4": "West"},
           "IL_SEG": {"r1": "ABC1", "r2": "C2DE"}
          }

# create list of lists of outerkey.innerkey
arrays = []
for key in oneDict.keys():
    arrays.append([key + '.' + val for val in oneDict[key].keys()])

table_rows = []
t=Template('<row label=\"r$label\" autofill=\"($gender) and ($age) and ($region) \
            and ($seg)\">${label}_${gender}_${age}_${region}_${seg}</row>')

for idx, tup in enumerate(product(*arrays)):
    d = dict(label=idx, gender=tup[0], age=tup[1], region=tup[2], seg=tup[3])
    table_rows.append(t.safe_substitute(d))

# show first and last row
print(table_rows[0])
print(table_rows[71])

Here I use Python's builtin Template strings which require the {}s around the use of the keys with trailing _ in the template string but are not required in the earlier instances in the templated string.


问:
error An unexpected error occurred: "EPERM: operation not permitted, unlink 'path_to_project\\node_modules\\prisma\\query_engine-windows.dll.node'
I installed Prisma and I run npx primsa db push it pushed all tables to database successfully, after that I run npx prisma generate it tried to install @prisma/client and it fails with this error message:

error An unexpected error occurred: "EPERM: operation not permitted, unlink 'path_to_project\node_modules\prisma\query_engine-windows.dll.node'

I tried to remove node_modules and re-install all modules but it not worked.

答: I had the same error but after installing Microsoft Visual C++ 2015 Redistributable it works fine now</p>


问:
Regex to get 00 if the string has less digits
I have a column that is giving me output like 'ABC2001' , 'ABC100145', 'ABC009282' ,' ABC1901'

I want to change this column value to have '00' in between literals and numbers if number is less than 6 digits. Something like -

```<code>COL_A
------------
ABC2001
ABC100145
ABC009282
ABC1901
</code>```

Expected output

```<code>COL_B
------------
ABC002001
ABC100145
ABC009282
ABC001901
</code>```

How to use regex for this ? Currently I am using

```<code>SELECT SUBSTR(COL_A,1,3)||LPAD(REGEXP_REPLACE(COL_A,'\D+'),6,'0') FROM TAB
</code>```

and it is giving me output like -

```<code>ABC210073
ABC210073
</code>```

答:
You do not need (slow) regular expressions and can use simple string functions:

SELECT col_a,
       SUBSTR(col_a, 1, 3) || LPAD(SUBSTR(col_a, 4), 6, '0') AS col_b
FROM   table_name;
```
<p>Which, for your sample data:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE table_name (col_a) AS
SELECT 'ABC2001'   FROM DUAL UNION ALL
SELECT 'ABC100145' FROM DUAL UNION ALL
SELECT 'ABC009282' FROM DUAL UNION ALL
SELECT 'ABC1901'   FROM DUAL;
</code>```

Outputs:

COL_A
COL_B

ABC2001
ABC002001

ABC100145
ABC100145

ABC009282
ABC009282

ABC1901
ABC001901

db<>fiddle here

Body:
I have a column that is giving me output like 'ABC2001' , 'ABC100145', 'ABC009282' ,' ABC1901'

I want to change this column value to have '00' in between literals and numbers if number is less than 6 digits. Something like -

COL_A
------------
ABC2001
ABC100145
ABC009282
ABC1901

Expected output

COL_B
------------
ABC002001
ABC100145
ABC009282
ABC001901

How to use regex for this ? Currently I am using

SELECT SUBSTR(COL_A,1,3)||LPAD(REGEXP_REPLACE(COL_A,'\D+'),6,'0') FROM TAB

and it is giving me output like -

ABC210073
ABC210073

Body:
You do not need (slow) regular expressions and can use simple string functions:

SELECT col_a,
       SUBSTR(col_a, 1, 3) || LPAD(SUBSTR(col_a, 4), 6, '0') AS col_b
FROM   table_name;

Which, for your sample data:

CREATE TABLE table_name (col_a) AS
SELECT 'ABC2001'   FROM DUAL UNION ALL
SELECT 'ABC100145' FROM DUAL UNION ALL
SELECT 'ABC009282' FROM DUAL UNION ALL
SELECT 'ABC1901'   FROM DUAL;

Outputs:

COL_A
COL_B

ABC2001
ABC002001

ABC100145
ABC100145

ABC009282
ABC009282

ABC1901
ABC001901

db<>fiddle here


问:
Colspan & rowspan of header for slickgrid
I am just wondering if there is a way to provide colspan/rowspan to header and have multiple header rows. </p>

答:
Here's an example of colspan:
http://6pac.github.io/SlickGrid/examples/example-colspan.html

As for rowspan, it's quite a bit more complicated, as you can see in the following Github issue:
https://github.com/6pac/SlickGrid/issues/381

***note that the active repository has changed from mleibman's to this one:
https://github.com/6pac/SlickGrid