问:
edge policy IntranetFileLinksEnabled enabled does not open file
Last week Edge 95 was released bringing the new and long awaiting IntranetFileLinksEnabled policy.

Testing this I encounter a different behavior than expected.

Having the following test html file with links on a web-server e.g. http://demohost/ and having http://demohost/ added as "local-intranet" site.

Clicking the file links on e.g. http://demohost/test.html, I expect the file to be opened directly (e.g. docx in MS Word, pdf in Acrobat Reader, txt in Notepad ...):

```<code><a href="file://power/share/demo.txt">file://power/share/demo.txt</a><br/>
<a href="file://power/share/demo.docx">file://power/share/demo.docx</a><br/>
<a href="file://power/share/demo.pdf">file://power/share/demo.pdf</a><br/>
<a href="file://power/share/demo.html">file://power/share/demo.html</a><br/>
</code>```

But instead the share is opened in the explorer and the file is selected, but not opened.
e.g. demo.docx or demo.pdf:

Are there any additional policies I have to configure to establish a similar behavior as the Internet Explorer used to have? (actually opening the files)

Result of edge://policy/:

EDIT: I tried out a lot of different GPO settings in "Microsoft Edge" and "Internet Explorer" category, e.g. PopupsAllowedForUrls. Didn't find a solution.

EDIT2: Also file links to a drive e.g. file://D:/temp/demo.txt are blocked completely.

答:
This is by design and for sure because of security purposes.

If you read the policy documentation carefully, it is really good
documented what is going to happen:

This setting allows file URL links to intranet zone files from
intranet zone HTTPS websites to open Windows File Explorer for that
file or directory.

If you enable this policy, intranet zone file URL links originating
from intranet zone HTTPS pages will open Windows File Explorer to the
parent directory of the file and select the file. Intranet zone
directory URL links originating from intranet zone HTTPS pages will
open Windows File Explorer to the directory with no items in the
directory selected.

If you disable or don't configure this policy, file URL links will not
open.

Microsoft Edge uses the definition of intranet zone as configured for
Internet Explorer. Note that https://localhost/ is specifically
blocked as an exception of allowed intranet zone host, while loopback
addresses (127.0.0.*, [::1]) are considered internet zone by default.

Users may opt out of prompts on a per-protocol/per-site basis unless
the ExternalProtocolDialogShowAlwaysOpenCheckbox policy is disabled.

Body:
Last week Edge 95 was released bringing the new and long awaiting IntranetFileLinksEnabled policy.

Testing this I encounter a different behavior than expected.

Having the following test html file with links on a web-server e.g. http://demohost/ and having http://demohost/ added as "local-intranet" site.

Clicking the file links on e.g. http://demohost/test.html, I expect the file to be opened directly (e.g. docx in MS Word, pdf in Acrobat Reader, txt in Notepad ...):

file://power/share/demo.txt

file://power/share/demo.docx

file://power/share/demo.pdf

file://power/share/demo.html

But instead the share is opened in the explorer and the file is selected, but not opened.
e.g. demo.docx or demo.pdf:

Are there any additional policies I have to configure to establish a similar behavior as the Internet Explorer used to have? (actually opening the files)

Result of edge://policy/:

EDIT: I tried out a lot of different GPO settings in "Microsoft Edge" and "Internet Explorer" category, e.g. PopupsAllowedForUrls. Didn't find a solution.

EDIT2: Also file links to a drive e.g. file://D:/temp/demo.txt are blocked completely.


来源: stackexchange

问:
Recursively map an array with unlimited number of nested arrays in React
I have a huge set of data, basically a family tree ranging back to about 800 years old and have a lot of nested parent/child arrays.

I know .map method to loop over array/nested array to a limited size. However, how can thee code be minimalistic for mapping over nested arrays?

FYI: Its a react app.

Sample data:

```<code>const complete_date = [
    {
        "fullname": "some name",
        "dob": "",
        "children": [
          {
            "id": "someid",
            "fullname": "some name",
            "dob": "",
            "children": [
              {
                "id": "someid",
                "fullname": "some name",
                "dob": "",
                "children": [
                  {
                    "id": "someid",
                    "fullname": "some name",
                    "dob": "",
                    "children": [
                      {
                        "id": "someid",
                        "fullname": "some name",
                        "dob": "",
                        "children": [
                          {
                            "id": "someid",
                            "fullname": "some name",
                            "dob": ""
                          }
                        ]
                      }
                    ]
                  },
                  {
                    "id": "someid",
                    "fullname": "some name",
                    "dob": "",
                    "children": [
                      {
                        "id": "someid",
                        "fullname": "some name",
                        "dob": "",
                        "children": [
                          {
                            "id": "someid",
                            "fullname": "some name",
                            "dob": ""
                          }
                        ]
                      }
                    ]
                  },
                  {
                    "id": "someid",
                    "fullname": "some name",
                    "dob": "",
                    "children": [
                      {
                        "id": "someid",
                        "fullname": "some name",
                        "dob": "",
                        "children": [
                          {
                            "id": "someid",
                            "fullname": "some name",
                            "dob": "",
                            "children": [
                              {
                                "id": "someid",
                                "fullname": "some name",
                                "dob": "",
                                "children": [
                                  {
                                    "id": "someid",
                                    "fullname": "some name",
                                    "dob": "",
                                    "children": [
                                      {
                                        "id": "someid",
                                        "fullname": "some name",
                                        "dob": "",
                                        "children": [
                                          {
                                            "id": "someid",
                                            "fullname": "some name",
                                            "dob": ""
                                          }
                                        ]
                                      }
                                    ]
                                  },
                                  {
                                    "id": "someid",
                                    "fullname": "some name",
                                    "dob": "",
                                    "children": [
                                      {
                                        "id": "someid",
                                        "fullname": "some name",
                                        "dob": "",
                                        "children": [
                                          {
                                            "id": "someid",
                                            "fullname": "some name",
                                            "dob": ""
                                          }
                                        ]
                                      }
                                    ]
                                  },
                                  {
                                    "id": "someid",
                                    "fullname": "some name",
                                    "dob": "",
                                    "children": [
                                      {
                                        "id": "someid",
                                        "fullname": "some name",
                                        "dob": "",
                                        "children": [
                                          {
                                            "id": "someid",
                                            "fullname": "some name",
                                            "dob": ""
                                          }
                                        ]
                                      }
                                    ]
                                  }
                                ]
                              }
                            ]
                          }
                        ]
                      },
                      {
                        "id": "someid",
                        "fullname": "some name",
                        "dob": "",
                        "children": [
                          {
                            "id": "someid",
                            "fullname": "some name",
                            "dob": "",
                            "children": [
                              {
                                "id": "someid",
                                "fullname": "some name",
                                "dob": ""
                              }
                            ]
                          }
                        ]
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
    }
]
</code>```

Currently I know of writing .map method everytime.

Sample:
This is a snippet from the current implementation which is a real pain.

```<code>  {complete_data.map((data) => (
  <li>
    {data.fullname}
    <ul className="list-disc">
      {data.children.map((d) => (
        <li className="ml-10">
          {d.fullname}
          {d.children.length
            ? d.children.map((d2) => (
                <ul className="list-disc">
                  <li className="ml-10">
                    {d2.fullname}
                    <ul className="list-disc">
                      {d2.children.length
                        ? d2.children.map((d3) => (
                            <li className="ml-10">
                              {d3.fullname}
                              <ul className="list-disc">
                                {d3.children.length
                                  ? d3.children.map((d4) => (
                                      <li className="ml-10">
                                        {d4.fullname}
                                        <ul className="list-disc">
                                          {d4.children.length
                                            ? d4.children.map(
                                                (d5) => (
                                                  <li className="ml-10">
                                                    {d5.fullname}
                                                  </li>
                                                )
                                              )
                                            : null}
                                        </ul>
                                      </li>
                                    ))
                                  : null}
                              </ul>
                            </li>
                          ))
                        : null}
                    </ul>
                  </li>
                </ul>
              ))
            : null}
        </li>
      ))}
    </ul>
  </li>
))}
</code>```

Any ideas or help to simplify the process would be immensely appreciated.
Thanks.

答:
```<code>const List = ({complete_data})=> {
   return (
      <ul className="list-disc">
        {complete_data.map(x=> <Item key={x.id} data={x} />)}
      </ul>
   )
}

const Item = ({data})=> {
   return (
     <li className="ml-10">
         {data.fullname}
         {data.children.length > 0 && (
            <ul className="list-disc">
               {data.children.map((x)=> <Item key={x.id} data={x} />)}
            </ul>
         )}
     </li>
   )
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a huge set of data, basically a family tree ranging back to about 800 years old and have a lot of nested parent/child arrays.

I know .map method to loop over array/nested array to a limited size. However, how can thee code be minimalistic for mapping over nested arrays?

FYI: Its a react app.

Sample data:

const complete_date = [
    {
        "fullname": "some name",
        "dob": "",
        "children": [
          {
            "id": "someid",
            "fullname": "some name",
            "dob": "",
            "children": [
              {
                "id": "someid",
                "fullname": "some name",
                "dob": "",
                "children": [
                  {
                    "id": "someid",
                    "fullname": "some name",
                    "dob": "",
                    "children": [
                      {
                        "id": "someid",
                        "fullname": "some name",
                        "dob": "",
                        "children": [
                          {
                            "id": "someid",
                            "fullname": "some name",
                            "dob": ""
                          }
                        ]
                      }
                    ]
                  },
                  {
                    "id": "someid",
                    "fullname": "some name",
                    "dob": "",
                    "children": [
                      {
                        "id": "someid",
                        "fullname": "some name",
                        "dob": "",
                        "children": [
                          {
                            "id": "someid",
                            "fullname": "some name",
                            "dob": ""
                          }
                        ]
                      }
                    ]
                  },
                  {
                    "id": "someid",
                    "fullname": "some name",
                    "dob": "",
                    "children": [
                      {
                        "id": "someid",
                        "fullname": "some name",
                        "dob": "",
                        "children": [
                          {
                            "id": "someid",
                            "fullname": "some name",
                            "dob": "",
                            "children": [
                              {
                                "id": "someid",
                                "fullname": "some name",
                                "dob": "",
                                "children": [
                                  {
                                    "id": "someid",
                                    "fullname": "some name",
                                    "dob": "",
                                    "children": [
                                      {
                                        "id": "someid",
                                        "fullname": "some name",
                                        "dob": "",
                                        "children": [
                                          {
                                            "id": "someid",
                                            "fullname": "some name",
                                            "dob": ""
                                          }
                                        ]
                                      }
                                    ]
                                  },
                                  {
                                    "id": "someid",
                                    "fullname": "some name",
                                    "dob": "",
                                    "children": [
                                      {
                                        "id": "someid",
                                        "fullname": "some name",
                                        "dob": "",
                                        "children": [
                                          {
                                            "id": "someid",
                                            "fullname": "some name",
                                            "dob": ""
                                          }
                                        ]
                                      }
                                    ]
                                  },
                                  {
                                    "id": "someid",
                                    "fullname": "some name",
                                    "dob": "",
                                    "children": [
                                      {
                                        "id": "someid",
                                        "fullname": "some name",
                                        "dob": "",
                                        "children": [
                                          {
                                            "id": "someid",
                                            "fullname": "some name",
                                            "dob": ""
                                          }
                                        ]
                                      }
                                    ]
                                  }
                                ]
                              }
                            ]
                          }
                        ]
                      },
                      {
                        "id": "someid",
                        "fullname": "some name",
                        "dob": "",
                        "children": [
                          {
                            "id": "someid",
                            "fullname": "some name",
                            "dob": "",
                            "children": [
                              {
                                "id": "someid",
                                "fullname": "some name",
                                "dob": ""
                              }
                            ]
                          }
                        ]
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
    }
]

Currently I know of writing .map method everytime.

Sample:
This is a snippet from the current implementation which is a real pain.

  {complete_data.map((data) => (

    {data.fullname}

      {data.children.map((d) => (

          {d.fullname}
          {d.children.length
            ? d.children.map((d2) => (

                    {d2.fullname}

                      {d2.children.length
                        ? d2.children.map((d3) => (

                              {d3.fullname}

                                {d3.children.length
                                  ? d3.children.map((d4) => (

                                        {d4.fullname}

                                          {d4.children.length
                                            ? d4.children.map(
                                                (d5) => (

                                                    {d5.fullname}

                                                )
                                              )
                                            : null}

                                    ))
                                  : null}

                          ))
                        : null}

              ))
            : null}

      ))}

))}

Any ideas or help to simplify the process would be immensely appreciated.
Thanks.


问:
Rotate twice from two origin
I have a css div I want first to rotate at 180deg from the center origin and then rotate from -45deg from the "new" bottom left corner.
But I don't manage to apply two different rotations

https://imgur.com/a/9GSToEx -> So you can better understand

CSS

.player1{
    background-color: blueviolet;
    transform-origin: center;
    transform: rotate(180deg);
    transform-origin: bottom left;
    transform: rotate(45deg);
}

```
<h2>HTML</h2>
<pre class="lang-html prettyprint-override"><code><div class="player1">
            <div class="questionSpace"></div>
        </div>
</code>```

Thank you ^^

答:
This can be a bit tricky because of the need to move the origin and the rotations not being additive.

A fairly straightforward way of getting round the problem is to enclose the element in a parent whose sole purpose is to allow an independent 180deg rotation.

This snippet colors the player1 element with a linear-gradient so it can be seen that the 180deg rotation has taken place.

.player1container {
  display: inline-block;
  transform: rotate(180deg);
  margin: 20vmin;
  /* added just for demo */
}

.player1 {
  background-color: blueviolet;
  width: 20vmin;
  height: 10vmin;
  background-image: linear-gradient(red, blue);
  transform: rotate(-45deg);
  transform-origin: top right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="player1container">
  <div class="player1">
    <div class="questionSpace"></div>
  </div>
</div></code>```

Title: Rotate twice from two origin

Body:
I have a css div I want first to rotate at 180deg from the center origin and then rotate from -45deg from the "new" bottom left corner.
But I don't manage to apply two different rotations

https://imgur.com/a/9GSToEx -> So you can better understand

CSS

.player1{
    background-color: blueviolet;
    transform-origin: center;
    transform: rotate(180deg);
    transform-origin: bottom left;
    transform: rotate(45deg);
}

HTML

Thank you ^^

Body:
This can be a bit tricky because of the need to move the origin and the rotations not being additive.

A fairly straightforward way of getting round the problem is to enclose the element in a parent whose sole purpose is to allow an independent 180deg rotation.

This snippet colors the player1 element with a linear-gradient so it can be seen that the 180deg rotation has taken place.

.player1container {
  display: inline-block;
  transform: rotate(180deg);
  margin: 20vmin;
  /* added just for demo */
}

.player1 {
  background-color: blueviolet;
  width: 20vmin;
  height: 10vmin;
  background-image: linear-gradient(red, blue);
  transform: rotate(-45deg);
  transform-origin: top right;
}

<div class="player1container">
  <div class="player1">
    <div class="questionSpace"></div>
  </div>
</div>


问:
what happens to events after the object it references is disposed of?
what happens if i link a method of some object to a delegate, and then dispose of the object?

Like this:

```<code>class Hunter
{
    public event Action Shoot;

    public execute()
    {
        Form formBabySeal = new Form();

        Shoot += formBabySeal.Close;

        formBabySeal.Show();
        formBabySeal.Close(); //Dispose Form

        if (Shoot != null)
        {
             Shoot(); //event is null?
        }
    }
}
</code>```

答:
formBabySeal is not null just because you dispose it. So, formBabySeal.Close() will be called.

Your code is equivalent to this when looking at what methods are called:

```<code>Form formBabySeal = new Form();

formBabySeal.Show();
formBabySeal.Close(); //Dispose Form
formBabySeal.Close();
</code>```

This will close the form (first call to Close) and the second call won't do anything, because the form is already closed.

However, as Steve points out in the comment section, your code will introduce a memory leak, because Shoot still holds a reference to the Close method of formBabySeal and because of this formBabySeal will be kept alive as long as the instance of the class Hunter is alive.

ContentLicense: CC BY-SA 3.0

Body:
what happens if i link a method of some object to a delegate, and then dispose of the object?

Like this:

class Hunter
{
    public event Action Shoot;

    public execute()
    {
        Form formBabySeal = new Form();

        Shoot += formBabySeal.Close;

        formBabySeal.Show();
        formBabySeal.Close(); //Dispose Form

        if (Shoot != null)
        {
             Shoot(); //event is null?
        }
    }
}

Body:
formBabySeal is not null just because you dispose it. So, formBabySeal.Close() will be called.

Your code is equivalent to this when looking at what methods are called:

Form formBabySeal = new Form();

formBabySeal.Show();
formBabySeal.Close(); //Dispose Form
formBabySeal.Close();

This will close the form (first call to Close) and the second call won't do anything, because the form is already closed.

However, as Steve points out in the comment section, your code will introduce a memory leak, because Shoot still holds a reference to the Close method of formBabySeal and because of this formBabySeal will be kept alive as long as the instance of the class Hunter is alive.


问:
local time doesnt save in local storage after page refresh
Im quite a newbie with coding

So i got the code below, the local time is being set correctly on the webpage and in local storage. However, after refreshing the time sets again and i dont need that. I was looking through several topics and couldnt find anything that fits my problem.
Tried document.write() etc, but didnt work

What could be the solution to this problem or what are the issues in my code that the time sets new after refresh?

const date = new Date().toLocaleTimeString();
document.getElementById('entryTime').textContent = date

localStorage.setItem('time', JSON.stringify(date));

if (localStorage.getItem("time")) {
  entryTime = JSON.parse(localStorage.getItem("time"));
} else {
  // No data, start with an empty array
  entryTime = [];
}
console.log(date);
document.getElementById('entryTime').innerHTML = date```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row" style="margin-top: 10px !important; margin-bottom: 1px !important; font-size: 30px;" id="entryTime"></div></code>```

答:
Does this work for you?</p>
```<code>var entryTime;
if (localStorage.getItem("time")) {
    entryTime = JSON.parse(localStorage.getItem("time"));
} else {
    entryTime  = new Date().toLocaleTimeString();
    localStorage.setItem('time', JSON.stringify(entryTime ));
}
document.getElementById('entryTime').innerHTML = entryTime;
</code>```

Body:
Does this work for you?

var entryTime;
if (localStorage.getItem("time")) {
    entryTime = JSON.parse(localStorage.getItem("time"));
} else {
    entryTime  = new Date().toLocaleTimeString();
    localStorage.setItem('time', JSON.stringify(entryTime ));
}
document.getElementById('entryTime').innerHTML = entryTime;


问:
Adding user input to a string array with while-loop without overwriting the current element at the index C# "Ryggsäck"
So HI! I'm new to C# (started about 3 weeks ago) and have taken up some programming courses and have run in to a problem.

Here is the for loop that I'm using, and I understand that the if statement looks contrary from what I wanna achieve, but when 'if (ruckSack[i] != "")' I got the "assigned string".
Furthermore, with the current code, if I just "add" an empty string to the array the it's assigned and I understand that I give the array an empty sting as a value.

```<code>int i = container;
  while (i < 5)
  {
      if (ruckSack[i] == "")
  {
      Console.WriteLine("Assigned string");
      i++;
  }
  else
  {
      Console.WriteLine("Empty string");
  }
      ruckSack[i] = Console.ReadLine();
      i++;
  }
</code>```

So I have a display elements of array, and delete elements from array.
So I know that everything works except for the storage-func.
I would have used a list, but the assignment asks for a string array.
How would one do to solve this?

Thanks in advance!!
Best regards

EDIT: If any one wants the whole source code, tell me and i'll add it!

答:
If yout want to avoid that the user can type a input if there is already any string in the array, yout need to inclue the Console.ReadLine() into the else-Block.

Also, you will need to use another way to check if a string is assigned as ruckSack[i] == "" only return true if the array contains an emtpy string (""). You can use string.IsNullOrEmpty(ruckSack[i]) or string.IsNullOrWhitespace(ruckSack[i]) (last one returns also true if only space on other white-spaces are in the string).

Put together:

  int i = container;
  while (i < 5)
  {
      if (string.IsNullOrWhiteSpace(ruckSack[i]))
      {
          Console.WriteLine("Assigned string");
          i++;
      }
      else
      {
          Console.WriteLine("Empty string");
          ruckSack[i] = Console.ReadLine();
      }
      i++;
  }
```

Body:
So HI! I'm new to C# (started about 3 weeks ago) and have taken up some programming courses and have run in to a problem.

Here is the for loop that I'm using, and I understand that the if statement looks contrary from what I wanna achieve, but when 'if (ruckSack[i] != "")' I got the "assigned string".
Furthermore, with the current code, if I just "add" an empty string to the array the it's assigned and I understand that I give the array an empty sting as a value.

int i = container;
  while (i < 5)
  {
      if (ruckSack[i] == "")
  {
      Console.WriteLine("Assigned string");
      i++;
  }
  else
  {
      Console.WriteLine("Empty string");
  }
      ruckSack[i] = Console.ReadLine();
      i++;
  }

So I have a display elements of array, and delete elements from array.
So I know that everything works except for the storage-func.
I would have used a list, but the assignment asks for a string array.
How would one do to solve this?

Thanks in advance!!
Best regards

EDIT: If any one wants the whole source code, tell me and i'll add it!


问:
Django : "TypeError: unsupported operand type(s) for +: 'FloatField' and 'FloatField'"

I am trying to add 2 models.FloatField variables in Django before saving the model, and getting an error.

```<code>    from django.db import models
    class MyModel(models.Model):

        def __init__(self):
            self.value1 = models.FloatField(default=10.0)
            self.value2 = models.FloatField(default=20.0)

        def add_values(self):
            return self.value1 = self.value1 + self.value2
</code>```

When I create MyModel object and call add_values function, I get following error

```<code>    my_model = MyModel()
    my_model.add_values()
</code>```
```<code>   **Error Stack**
   line 8, in add_values
   self.value1 = self.value1 + self.value2
   TypeError: unsupported operand type(s) for +: 'FloatField' and 'FloatField'```
```

答:
You do not construct fields in the constructor, but at the model layer, so:

```<code>from django.db import models

class MyModel(models.Model):
    <strong>value1</strong> = models.FloatField(default=10.0)
    <strong>value2</strong> = models.FloatField(default=20.0)

    def add_values(self):
        return self.value1 = self.value1 + self.value2</code>```

It might also be better to turn the add_values into a property:

```<code>from django.db import models

class MyModel(models.Model):
    value1 = models.FloatField(default=10.0)
    value2 = models.FloatField(default=20.0)

    <strong>@property</strong>
    def sum_values(self):
        return self.value1 = self.value1 + self.value2</code>```

Body:
I am trying to add 2 models.FloatField variables in Django before saving the model, and getting an error.

    from django.db import models
    class MyModel(models.Model):

        def __init__(self):
            self.value1 = models.FloatField(default=10.0)
            self.value2 = models.FloatField(default=20.0)

        def add_values(self):
            return self.value1 = self.value1 + self.value2

When I create MyModel object and call add_values function, I get following error

    my_model = MyModel()
    my_model.add_values()

   **Error Stack**
   line 8, in add_values
   self.value1 = self.value1 + self.value2
   TypeError: unsupported operand type(s) for +: 'FloatField' and 'FloatField'```

Body:
You do not construct fields in the constructor, but at the model layer, so:

from django.db import models

class MyModel(models.Model):
    value1 = models.FloatField(default=10.0)
    value2 = models.FloatField(default=20.0)

    def add_values(self):
        return self.value1 = self.value1 + self.value2

It might also be better to turn the add_values into a property:

from django.db import models

class MyModel(models.Model):
    value1 = models.FloatField(default=10.0)
    value2 = models.FloatField(default=20.0)

    @property
    def sum_values(self):
        return self.value1 = self.value1 + self.value2


问:
How to insert a function in LLVM module
I am writing an LLVM pass, where I clone some functions by calling llvm::CloneFunction. Now I also want to insert those functions in the module. How can I do that?

答:
CloneFunction will automatically insert the new Function into the old Function's module. From the doxygen:

Return a copy of the specified function and add it to that function's module.

Title: How to insert a function in LLVM module


问:
SLF4J best practices
I'm writing a library and I use sfl4j to handle logging.

I think it's good idea as long as every body can provide it's own implementation and then, the log provided by my application will be handled correctly.

But I don't know if I have to provide an implementation as a transitive dependency or not.

Exemple:

If I only provide that:

```<code>    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.1</version>
        </dependency>
    </dependencies>
</code>```

The user of my lib can choose the implementation, but if he just add my lib without reading configuration, it will not work

Otherwise, if I provide that:

```<code>    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.1</version>
        </dependency>
    </dependencies>
</code>```

My lib will work correctly just when adding dependency to it, but If the user want to use an other slf4j, he will have to exclude mine.

What do you thing about that?

答: You never provide a log implementation. The client application has to do so. Otherwhise this would be a violation of separation of concerns. Don't do any assumptions about an unknown client.

Title: SLF4J best practices

Body:
I'm writing a library and I use sfl4j to handle logging.

I think it's good idea as long as every body can provide it's own implementation and then, the log provided by my application will be handled correctly.

But I don't know if I have to provide an implementation as a transitive dependency or not.

Exemple:

If I only provide that:

    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.1</version>
        </dependency>
    </dependencies>

The user of my lib can choose the implementation, but if he just add my lib without reading configuration, it will not work

Otherwise, if I provide that:

    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.1</version>
        </dependency>
    </dependencies>

My lib will work correctly just when adding dependency to it, but If the user want to use an other slf4j, he will have to exclude mine.

What do you thing about that?


问:
How to convert a @requestBody to a customized object?
I am using springboot controller with @RequestBody.  I have following json request body

```<code>{
  "abc":"xyz",
  "valid":"yes"
}
</code>```

I have a corresponding POJO

```<code>class MyObject{
  private String abc;
  private Boolean valid;
}
</code>```

I have controller like

```<code>@PostMapping(value = "somePath", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<MyResponse>  myMethod(@RequestBody MyObject request)  {
</code>```

Obviously it won't work because valid is a string in request whereas it is boolean in MyObject. I want it to have a logic so if valid=yes is in request it will be converted to boolean true in MyObject. Any mechanism does spring has to achieve that?

答:
It is possible if you annotate your MyObject with jackson annotations: in this case you can create an all args constructor with the JsonCreator annotation and define there your expected behaviour:

```<code>public class MyObject {

    private String abc;
    private Boolean valid;

    @JsonCreator
    public MyObject(String abc, String valid) {
        this.abc = abc;
        if (valid.equals("yes")) {
            //be aware valid will remain null
            //if valid is different from yes
            this.valid = true;
        }
    }

}
</code>```

Body:
I am using springboot controller with @RequestBody.  I have following json request body

{
  "abc":"xyz",
  "valid":"yes"
}

I have a corresponding POJO

class MyObject{
  private String abc;
  private Boolean valid;
}

I have controller like

@PostMapping(value = "somePath", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<MyResponse>  myMethod(@RequestBody MyObject request)  {

Obviously it won't work because valid is a string in request whereas it is boolean in MyObject. I want it to have a logic so if valid=yes is in request it will be converted to boolean true in MyObject. Any mechanism does spring has to achieve that?

Body:
It is possible if you annotate your MyObject with jackson annotations: in this case you can create an all args constructor with the JsonCreator annotation and define there your expected behaviour:

public class MyObject {

    private String abc;
    private Boolean valid;

    @JsonCreator
    public MyObject(String abc, String valid) {
        this.abc = abc;
        if (valid.equals("yes")) {
            //be aware valid will remain null
            //if valid is different from yes
            this.valid = true;
        }
    }

}


问:
How to verify the request is coming from Cypress?
We have a service which verifies user before it can access data. I need to know if the request is coming from Cypress. I understand I can look into user-agent or I can also set request header but I am trying to find any other way that normal user can't do from browser. Is there anything else Cypress sends with request that we can use?</p>

答:
All Cypress commands are executed in the browser. Like you mentioned you can set a custom request-header to identify Cypress requests. However these can in theory alway be set outside Cypress via Postman or an http interceptor.

Best option is to set the custom request header with a secret which gets validated in the application itself.


问:
Chrome: Save web.whatsapp.com as html - smileys missing
I would like to save my web.whatsapp.com chat history. With google chrome and right-click > Save as.. > Format: Webpage, Complete i can download the html file. That way pictures of the chat history are included but smileys are missing.

I do not really have a clue about html - what i figured out so far is that the smileys are stored in one big image file that is accessible via: blob:https%3A//web.whatsapp.com/233563d6-722b-483a-835c-c9907f1d9c42
when you have web.whatsapp.com open.

What i am struggling with is how to store this file in the html directory in order to get the smileys in the offline version. Any help and advice is appreciated!

答:
RandomDude's right. This does solve the problem! However, I had to change the regex because now the image tags are a bit different:

```<code><img crossorigin="anonymous" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" alt="" draggable="false" class="b38 emoji wa i0jNr selectable-text copyable-text" data-plain-text="" style="background-position: 0px -20px;">
</code>```

The new lazy regular expression is:

Find: ]*>

Replace: $1

I am also making sure, that we are handling an emoji just in case.

Body:
RandomDude's right. This does solve the problem! However, I had to change the regex because now the image tags are a bit different:

<img crossorigin="anonymous" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" alt="" draggable="false" class="b38 emoji wa i0jNr selectable-text copyable-text" data-plain-text="" style="background-position: 0px -20px;">

The new lazy regular expression is:

Find: <img[\w\d\s="-:;]+alt="([^"]*)"[\w\d\s="-:;]+emoji[^>]*>

Replace: $1

I am also making sure, that we are handling an emoji just in case.


问:
How to get a response without a endpoint in JavaScript?
Here is the code I wrote:

...
    await fetch('https://google.com', {
      method: "GET",
      mode: "no-cors"
    })
    .then((response) => {
      console.log(response.body);
      console.log(response.status);
      return response.text();
    })
    .then((responseText) => {
      console.log(responseText);
    })
    .catch((error) => {
      console.log(error.toString());
    });
...

```
```https://google.com (O)
https://google.com/test (X)
```

I want to get a response(HTML) from a URL with no endpoint. So I sent HTTP requests using the Fetch API, but it continues to return a null value.

Is there a way to solve this problem in the pure JS environment?

答:
I want to get a response(HTML) from a URL with no endpoint. So I sent HTTP requests using the Fetch API, but it continues to return a null value.

By using, mode: "no-cors" you get an opaque response and that can't be accessed with JavaScript.

So, as stated here, you should get a null value.

If a site, sends the Access-Control-Allow-Origin header in its responses, only then frontend JavaScript code can directly access responses from that site.

And, the site (google) you are trying to access does not send that.

Is there a way to solve this problem in the pure JS environment?

You can access responses from sites that allow it or configure your backend to send the Access-Control-Allow-Origin header.

For example this snippet works,

async function testResponse() {
    let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    let json = await response.json()
    console.log(json)
}

testResponse()
```
<p>However, if you want to access response from a site that does not allow it, <code>CORS proxy</code> might help.
Details available in this answer.</p>
<hr />
<p>Also, <code>fetch</code> uses promised-based API. That means you can use it like this,</p>
<pre class="lang-js prettyprint-override"><code>
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then( response => console.log(response) )

</code>```

or,

```<code>async function test() {
    let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    console.log(response)
}

test()
</code>```

No need to use both at the same time.

Body:
Here is the code I wrote:

...
    await fetch('https://google.com', {
      method: "GET",
      mode: "no-cors"
    })
    .then((response) => {
      console.log(response.body);
      console.log(response.status);
      return response.text();
    })
    .then((responseText) => {
      console.log(responseText);
    })
    .catch((error) => {
      console.log(error.toString());
    });
...

https://google.com (O)
https://google.com/test (X)

I want to get a response(HTML) from a URL with no endpoint. So I sent HTTP requests using the Fetch API, but it continues to return a null value.

Is there a way to solve this problem in the pure JS environment?

Body:
I want to get a response(HTML) from a URL with no endpoint. So I sent HTTP requests using the Fetch API, but it continues to return a null value.

By using, mode: "no-cors" you get an opaque response and that can't be accessed with JavaScript.

So, as stated here, you should get a null value.

If a site, sends the Access-Control-Allow-Origin header in its responses, only then frontend JavaScript code can directly access responses from that site.

And, the site (google) you are trying to access does not send that.

Is there a way to solve this problem in the pure JS environment?

You can access responses from sites that allow it or configure your backend to send the Access-Control-Allow-Origin header.

For example this snippet works,

async function testResponse() {
    let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    let json = await response.json()
    console.log(json)
}

testResponse()

However, if you want to access response from a site that does not allow it, CORS proxy might help.
Details available in this answer.

Also, fetch uses promised-based API. That means you can use it like this,

fetch('https://jsonplaceholder.typicode.com/todos/1')
.then( response => console.log(response) )

or,

async function test() {
    let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    console.log(response)
}

test()

No need to use both at the same time.


问:
Transportation problem on python using networkx when total node demand is not zero

There are 6 nodes with negative and positive demands. I need to calculate the best variant to satisfy as much consumers as I can. I'm trying to solve it using networkx python library:

```<code>import networkx as nx

G = nx.DiGraph()

G.add_node("1", demand=15)
G.add_node("2", demand=25)
G.add_node("3", demand=60)
G.add_node("4", demand=-55)
G.add_node("5", demand=-35)
G.add_node("6", demand=-40)

G.add_edge("1", "2", weight=2)
G.add_edge("1", "3", weight=1)
G.add_edge("1", "6", weight=3)

G.add_edge("2", "6", weight=4)
G.add_edge("2", "3", weight=5)

G.add_edge("3", "4", weight=3)

G.add_edge("4", "5", weight=6)

G.add_edge("5", "6", weight=2)

flowCost = nx.min_cost_flow_cost(G)
print(flowCost)
</code>```

But as I understand the problem is that summary of my negative and positive demands is not zero and I get error:

```<code>networkx.exception.NetworkXUnfeasible: total node demand is not zero
</code>```

So is there some solution for this problem? Maybe it's better to use some different library?

答:
To make the network feasible, the total demand must be zero.

Here is the correct code:

```<code>import networkx as nx

G = nx.DiGraph()

G.add_node("1", demand=15)
G.add_node("2", demand=25)
G.add_node("3", demand=60)
G.add_node("4", demand=-45)
G.add_node("5", demand=-25)
G.add_node("6", demand=-30)

G.add_edge("1", "2", weight=2)
G.add_edge("1", "3", weight=1)
G.add_edge("1", "6", weight=3)

G.add_edge("2", "6", weight=4)
G.add_edge("2", "3", weight=5)

G.add_edge("3", "4", weight=3)

G.add_edge("4", "5", weight=6)

G.add_edge("5", "6", weight=2)

flowCost = nx.min_cost_flow_cost(G)
print(flowCost)
</code>```

Body:
There are 6 nodes with negative and positive demands. I need to calculate the best variant to satisfy as much consumers as I can. I'm trying to solve it using networkx python library:

import networkx as nx

G = nx.DiGraph()

G.add_node("1", demand=15)
G.add_node("2", demand=25)
G.add_node("3", demand=60)
G.add_node("4", demand=-55)
G.add_node("5", demand=-35)
G.add_node("6", demand=-40)

G.add_edge("1", "2", weight=2)
G.add_edge("1", "3", weight=1)
G.add_edge("1", "6", weight=3)

G.add_edge("2", "6", weight=4)
G.add_edge("2", "3", weight=5)

G.add_edge("3", "4", weight=3)

G.add_edge("4", "5", weight=6)

G.add_edge("5", "6", weight=2)

flowCost = nx.min_cost_flow_cost(G)
print(flowCost)

But as I understand the problem is that summary of my negative and positive demands is not zero and I get error:

networkx.exception.NetworkXUnfeasible: total node demand is not zero

So is there some solution for this problem? Maybe it's better to use some different library?

Body:
To make the network feasible, the total demand must be zero.

Here is the correct code:

import networkx as nx

G = nx.DiGraph()

G.add_node("1", demand=15)
G.add_node("2", demand=25)
G.add_node("3", demand=60)
G.add_node("4", demand=-45)
G.add_node("5", demand=-25)
G.add_node("6", demand=-30)

G.add_edge("1", "2", weight=2)
G.add_edge("1", "3", weight=1)
G.add_edge("1", "6", weight=3)

G.add_edge("2", "6", weight=4)
G.add_edge("2", "3", weight=5)

G.add_edge("3", "4", weight=3)

G.add_edge("4", "5", weight=6)

G.add_edge("5", "6", weight=2)

flowCost = nx.min_cost_flow_cost(G)
print(flowCost)


问:
is there an excel function that turns the text color of a cell into a value?
I need to perform some averageif and sumif functions on a database whose criteria is defined by the colour of the text in each row.

Currently, I am manually assigning to each row a value based on the colour of the text (1 for red and 2 for black) in order to perform calculations. The problem is that my file if huge and it's not possible to keep assigning values manually.

I was wondering if there was some excel function that returns a value based on the colour of the text (or any other solution that saves time).

Thank you

答:
In case VBA is okay in your use case, you can write a function and place it in Module1. You may need to create the Module1 (Alt+F11, Locate your Project, right click and select Insert --> Module)

Text Color

```<code>Function getBackCol(Rng As Range) As Variant
    getBackCol = Rng.Interior.ColorIndex
End Function
</code>```

Background Color

```<code>Function getFontCol(Rng As Range) As Variant
    getFontCol = Rng.Font.ColorIndex
End Function
</code>```

You can then use the formula like below

```<code>=getBackCol(E5)
</code>```

or

```<code>=getFontCol(E5)
</code>```

Body:
In case VBA is okay in your use case, you can write a function and place it in Module1. You may need to create the Module1 (Alt+F11, Locate your Project, right click and select Insert --> Module)

Text Color

Function getBackCol(Rng As Range) As Variant
    getBackCol = Rng.Interior.ColorIndex
End Function

Background Color

Function getFontCol(Rng As Range) As Variant
    getFontCol = Rng.Font.ColorIndex
End Function

You can then use the formula like below

=getBackCol(E5)

or

=getFontCol(E5)


问:
UTM params for GA4 measurement protocol
How do I send UTM params or any campaign data to google analytics 4 using measurement protocol? Their GA4 documentation does not mention anything about this.</p>

答:
At the time of writing the Measurement Protocol (Google Analytics 4)  is still in beta.

There are limitations in what it supports and what it will support in the future.

UTM parameters are text strings that you can append to URLs that allow you track those URLs when they get clicked on. UTM parameters make Universal analytics Google Analytics pick up on the data in the code and log it with the pageview. The resulting data is visible in Universal analytics Google Analytics, meaning you can track traffic in terms of where it came from and how it got to you.

At the time of writing there is no mention of UTM support in Google analytics GA4

Title: UTM params for GA4 measurement protocol


问:
Extract Key from android keystore
From the Android Keystore Docs

Android Keystore system protects key material from unauthorized use. Firstly, Android Keystore mitigates unauthorized use of key material outside of the Android device by preventing extraction of the key material from application processes and from the Android device as a whole. Secondly, Android KeyStore mitigates unauthorized use of key material on the Android device by making apps specify authorized uses of their keys and then enforcing these restrictions outside of the apps' processes.

I am not able to understand it completely.

by preventing extraction of the key material from application processes

What does it mean? Any application process in the device can not extract the key from the store?

So once key is put in the store, there's no way to get it from the store (in case I want to use it somewhere else as well).
So if I want to do that, how do I implement my own custom keystore, which allows to extract the key for only my app's process and no-one else.

答:
I would also add that privateKey.getEncoded() method will return null if you  retrieve the privateKey from the AndroidKeyStore.

So considering the code below:

```<code>KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);

KeyStore.Entry keyStoreEntry = keyStore.getEntry(alias, null);
PrivateKey privateKey = ((KeyStore.PrivateKeyEntry)
keyStoreEntry).getPrivateKey();
byte[] privateKeyData = privateKey.getEncoded();
</code>```

privateKeyData will be null. This is what it means that

"Android Keystore system protects key material from unauthorized use"

Title: Extract Key from android keystore

Body:
I would also add that privateKey.getEncoded() method will return null if you  retrieve the privateKey from the AndroidKeyStore.

So considering the code below:

KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);

KeyStore.Entry keyStoreEntry = keyStore.getEntry(alias, null);
PrivateKey privateKey = ((KeyStore.PrivateKeyEntry)
keyStoreEntry).getPrivateKey();
byte[] privateKeyData = privateKey.getEncoded();

privateKeyData will be null. This is what it means that

"Android Keystore system protects key material from unauthorized use"


问:
next-i18next t(...).map is not a function
I just migrate my working app from react to nextjs.
I followed the tutorial provided by next and installed next-i18next but I'm not being able to map

I got this kind of object

```<code> "skills": {
    "title": "Skills",
    "items": [
      {
        "title": "Javascript",
        "additionalInfo": [
          "React",
          "Node"
         ]
      }
    ]
}
</code>```

and i need to parse the translation into this component

```<code> {t("skills.items", { returnObjects: true }).map(
            ({ title, additionalInfo }, index) => (
              <Fragment key={index}>
                <TitleRow>
                  <p>{title}</p>
                </TitleRow>
    ...
</code>```

Any ideas on what i missed in the migration?

答:
it may be t is not ready to be used in a first render...
If you're using the useTranslation hook, there should be a ready flag. => https://react.i18next.com/latest/usetranslation-hook#not-using-suspense
Or you can check for !!t("skills.items", { returnObjects: true }) before calling map

Body:
I just migrate my working app from react to nextjs.
I followed the tutorial provided by next and installed next-i18next but I'm not being able to map

I got this kind of object

 "skills": {
    "title": "Skills",
    "items": [
      {
        "title": "Javascript",
        "additionalInfo": [
          "React",
          "Node"
         ]
      }
    ]
}

and i need to parse the translation into this component

 {t("skills.items", { returnObjects: true }).map(
            ({ title, additionalInfo }, index) => (
              <Fragment key={index}>
                <TitleRow>

{title}

                </TitleRow>
    ...

Any ideas on what i missed in the migration?


问:
Integer out of range
I'm getting an integer out of range error when trying to migrate my database from SQLite to PostgreSQL.

I think I have pinpointed the problem: I have some huge integers in a IntegerField field in  my model.

Basically on the order of 52675215334.

When I change this value to a small number like 1 and then try to migrate my database, all is fine.

Is there some other data type I should be using other than IntegerField to store these large values?

答:
Do not forget to migrate the changes you did, otherwise it will not work

```<code>python manage.py migrate
</code>```

python manage.py makemigrations

Title: Integer out of range

Body:
Do not forget to migrate the changes you did, otherwise it will not work

python manage.py migrate

python manage.py makemigrations


问:
Compose Dialog closing on keyboard appearance when LazyColumn is in background
I have a layout where each item in a LazyColumn can display an item-specific dialog. The Dialogs showed and worked fine except for some of the larger ones where whenever I would try to edit text in one of the dialog's TextFields it would trigger the dialog to disappear.

I tried a lot of different approaches and the weirdest thing was that the dialog works fine and allows me do edit the textfields if I only scroll the LazyColumn by even 1 item before attempting to show the dialog.

It has proven hard to reproduce the issue in a simple setting as changing even basic elements of my code makes the bug disappear but I finally managed. The appearance of the bug seems to depend on the LazyColumn being Scrollable and on the KeyBoard to be of type text. Next a somewhat long code sample and a GIF showing the issue:

```<code>@Composable
fun JointCourseTemplate(courseTemplateDto: CourseTemplateDto) {
    LazyColumn(
        //state= LazyListState()
    ){
        for(i in 0..4){
            item { TestPart(i = i) }
            for (j in 0..8){
                item { TestItem(i = j) }
            }
        }

    }
}

@Composable
fun TestPart(i:Int) {
    var showDialog by remember {
        mutableStateOf(false)
    }
    Row(Modifier.padding(8.dp)) {
        Text("part"+i)
        Button(onClick = { showDialog=true }) {
            Text("show dialog")
        }
    }

    PartDialog(showDialog = showDialog, hideDialog = {showDialog=false})
}

@Composable
fun TestItem(i:Int) {
    Row(Modifier.padding(8.dp)) {
        Text("item"+i)
        Button(onClick = { /*TODO*/ }) {
            Text("show dialog")
        }
    }
}

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun PartDialog(showDialog:Boolean, hideDialog: () -> Unit) {
    var text by remember {
        mutableStateOf("")
    }
    if (showDialog) {
        Dialog(properties = DialogProperties(
            dismissOnClickOutside = false,
            usePlatformDefaultWidth = false
        ),
            onDismissRequest = { hideDialog() }) {
            Surface(
                modifier = Modifier
                    //.wrapContentHeight()
                    //.fillMaxWidth(0.9f)
                    .width(400.dp)
                    .height(600.dp),
                shape = RoundedCornerShape(10.dp)
            ) {
                Column {
                    Text(text = "Some Dialog")
                    OutlinedTextField(value = text, onValueChange = {text=it}, label = { Text(text = "TroubleMaker")})
                }
            }
        }
    }
}
</code>```

答:
This problem is due to the fact that you open the dialog from a lazy cell, which is located at the bottom of the screen. Therefore, when the keyboard appears, this cell becomes invisible and is removed from the view tree. I would say this is intended behavior.

I would suggest that you move the dialog from LazyColumn. Perhaps you need information about a particular item to be displayed inside the dialog, you can store the selected item instead of a boolean value:

val (selectedDialogItem, setSelectedItem) = remember { mutableStateOf<Int?>(null) }
LazyColumn {
    items(4) { i ->
        Row(Modifier.padding(8.dp)) {
            Text("part"+i)
            Button(onClick = {
                setSelectedItem(i)
            }) {
                Text("show dialog")
            }
        }
    }
}
if (selectedDialogItem != null) {
    Dialog(
        // ...
    )
}
```

p.s. I'm not using delegation here to allow selectedDialogItem smart cast inside if block

Body:
I have a layout where each item in a LazyColumn can display an item-specific dialog. The Dialogs showed and worked fine except for some of the larger ones where whenever I would try to edit text in one of the dialog's TextFields it would trigger the dialog to disappear.

I tried a lot of different approaches and the weirdest thing was that the dialog works fine and allows me do edit the textfields if I only scroll the LazyColumn by even 1 item before attempting to show the dialog.

It has proven hard to reproduce the issue in a simple setting as changing even basic elements of my code makes the bug disappear but I finally managed. The appearance of the bug seems to depend on the LazyColumn being Scrollable and on the KeyBoard to be of type text. Next a somewhat long code sample and a GIF showing the issue:

@Composable
fun JointCourseTemplate(courseTemplateDto: CourseTemplateDto) {
    LazyColumn(
        //state= LazyListState()
    ){
        for(i in 0..4){
            item { TestPart(i = i) }
            for (j in 0..8){
                item { TestItem(i = j) }
            }
        }

    }
}

@Composable
fun TestPart(i:Int) {
    var showDialog by remember {
        mutableStateOf(false)
    }
    Row(Modifier.padding(8.dp)) {
        Text("part"+i)
        Button(onClick = { showDialog=true }) {
            Text("show dialog")
        }
    }

    PartDialog(showDialog = showDialog, hideDialog = {showDialog=false})
}

@Composable
fun TestItem(i:Int) {
    Row(Modifier.padding(8.dp)) {
        Text("item"+i)
        Button(onClick = { /*TODO*/ }) {
            Text("show dialog")
        }
    }
}

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun PartDialog(showDialog:Boolean, hideDialog: () -> Unit) {
    var text by remember {
        mutableStateOf("")
    }
    if (showDialog) {
        Dialog(properties = DialogProperties(
            dismissOnClickOutside = false,
            usePlatformDefaultWidth = false
        ),
            onDismissRequest = { hideDialog() }) {
            Surface(
                modifier = Modifier
                    //.wrapContentHeight()
                    //.fillMaxWidth(0.9f)
                    .width(400.dp)
                    .height(600.dp),
                shape = RoundedCornerShape(10.dp)
            ) {
                Column {
                    Text(text = "Some Dialog")
                    OutlinedTextField(value = text, onValueChange = {text=it}, label = { Text(text = "TroubleMaker")})
                }
            }
        }
    }
}

Body:
This problem is due to the fact that you open the dialog from a lazy cell, which is located at the bottom of the screen. Therefore, when the keyboard appears, this cell becomes invisible and is removed from the view tree. I would say this is intended behavior.

I would suggest that you move the dialog from LazyColumn. Perhaps you need information about a particular item to be displayed inside the dialog, you can store the selected item instead of a boolean value:

val (selectedDialogItem, setSelectedItem) = remember { mutableStateOf<Int?>(null) }
LazyColumn {
    items(4) { i ->
        Row(Modifier.padding(8.dp)) {
            Text("part"+i)
            Button(onClick = {
                setSelectedItem(i)
            }) {
                Text("show dialog")
            }
        }
    }
}
if (selectedDialogItem != null) {
    Dialog(
        // ...
    )
}

p.s. I'm not using delegation here to allow selectedDialogItem smart cast inside if block


问:
Replace substring with another substring C++
How could I replace a substring in a string with another substring in C++, what functions could I use? </p>

```<code>eg: string test = "abc def abc def";
test.replace("abc", "hij").replace("def", "klm"); //replace occurrence of abc and def with other substring
</code>```

答:
```<code>    string & replace(string & subj, string old, string neu)
    {
        size_t uiui = subj.find(old);
        if (uiui != string::npos)
        {
           subj.erase(uiui, old.size());
           subj.insert(uiui, neu);
        }
        return subj;
    }
</code>```

I think this fits your requirement with few code!

Body:
How could I replace a substring in a string with another substring in C++, what functions could I use?

eg: string test = "abc def abc def";
test.replace("abc", "hij").replace("def", "klm"); //replace occurrence of abc and def with other substring

Body:
    string & replace(string & subj, string old, string neu)
    {
        size_t uiui = subj.find(old);
        if (uiui != string::npos)
        {
           subj.erase(uiui, old.size());
           subj.insert(uiui, neu);
        }
        return subj;
    }

I think this fits your requirement with few code!


问:
Vanilla Javascript use of bind() with REST parameter
Why bind() passes even the type of event with rest parameters. How to avoid passing the event 'click'?

```<code>function say(...numbers) {
  for (const number of numbers) {
    console.log(number);
  }
}

window.addEventListener('DOMContentLoaded', () => {
  const el = document.getElementById('input_10_5');
  el.addEventListener('click', say.bind(null, 1, 2, 3));
});
</code>```

Console.log result:

```<code>1
2
3
click { target: input#input_10_5.medium, buttons: 0, clientX: 1062, clientY: 732, layerX: 96, layerY: 24
</code>```

}

答:
You can't. The event handling system always passes the event.

The callback function itself has the same parameters and return value as the handleEvent() method; that is, the callback accepts a single parameter: an object based on Event describing the event that has occurred, and it returns nothing.

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#the_event_listener_callback

If your goal is to iterate the arguments and treat them all the same then how about:
function say(numbers, event)
say.bind(null, [1, 2, 3])

Body:
Why bind() passes even the type of event with rest parameters. How to avoid passing the event 'click'?

function say(...numbers) {
  for (const number of numbers) {
    console.log(number);
  }
}

window.addEventListener('DOMContentLoaded', () => {
  const el = document.getElementById('input_10_5');
  el.addEventListener('click', say.bind(null, 1, 2, 3));
});

Console.log result:

1
2
3
click { target: input#input_10_5.medium, buttons: 0, clientX: 1062, clientY: 732, layerX: 96, layerY: 24

}


问:
Can't access form data in PHP
I'm not a novice, but I'm not an expert either; I'm a keen learner.

Problem (minimalised) - I have a basic form which posts a name to another page which is supposed to receive name and print name. Code of both forms is below.

Form:

```<code><?php
    echo "Hello, World!";
    echo "
        <form action='CFAcomments.php' method='POST'>
            <table style='width: 50%;' border='0'>
                <tbody>
                    <tr>
                        <td><label for='name'>name: </label></td>
                        <td><input type='Text' name='name' value='anon' /></td>
                    </tr>
                    <tr>
                        <td><input type='submit' name='send' value='Send' /></td>
                    </tr>
                </tbody>
            </table>
        </form>
    ";
?>
</code>```

Form Process:

```<code><?php
    echo "Hello, World 1!";
    echo "<br/>";
    var_dump($_POST);
    $name = $_POST("name");
    echo "Hello $name!";
?>
</code>```

Result:

```<code>Hello, World 1!
array(2) { ["name"]=> string(11) "anon" ["send"]=> string(4) "Send" }
</code>```

Problem:

Even though var_dump($_POST) shows data being sent, echo $name print nothing. Changing echo $name to echo "test" prints nothing too. The code seems to stop executing at $name = $_post("name");. If I remove this line echo "anything" works.

I've used PHP and forms for the last two years and never come across this. Any help would be appreciated.

答:
```<code>$name = $_POST("name");
</code>```

is not the correct way. It should be:

```<code>$name = $_POST["name"];
</code>```

since $_POST is an array.

Title: Can't access form data in PHP

Body:
I'm not a novice, but I'm not an expert either; I'm a keen learner.

Problem (minimalised) - I have a basic form which posts a name to another page which is supposed to receive name and print name. Code of both forms is below.

Form:

<?php
    echo "Hello, World!";
    echo "
        <form action='CFAcomments.php' method='POST'>

                        name:
                        <input type='Text' name='name' value='anon' />

                        <input type='submit' name='send' value='Send' />

        </form>
    ";
?>

Form Process:

<?php
    echo "Hello, World 1!";
    echo "
";
    var_dump($_POST);
    $name = $_POST("name");
    echo "Hello $name!";
?>

Result:

Hello, World 1!
array(2) { ["name"]=> string(11) "anon" ["send"]=> string(4) "Send" }

Problem:

Even though var_dump($_POST) shows data being sent, echo $name print nothing. Changing echo $name to echo "test" prints nothing too. The code seems to stop executing at $name = $_post("name");. If I remove this line echo "anything" works.

I've used PHP and forms for the last two years and never come across this. Any help would be appreciated.

Body:
$name = $_POST("name");

is not the correct way. It should be:

$name = $_POST["name"];

since $_POST is an array.


问:
Finding the most frequent character in a string using binary search
Suppose you are given a string of length n and there are 26 ASCII characters that can constitute the string. Identical characters are grouped together in the string (e.g aaabbbcccddd). Find the most frequent character.

The brute force is to scan the entire string and iteratively count the number of characters which takes O(n) time with O(1) space. Is there a O(log n) solution for this? I was given a hint to binary search to find the partition that contains the most frequent character, but I am not sure how binary search would help me eliminating the half of the string.

答:
You can use binary search to find the last occurrence (or rightmost occurrence) of a character in a sub-range of a string to solve this problem.

You use it to hop across the input string, from character to character, no matter how often the same character is being repeated. While you hop, you remember the most frequent character so far and how often it was repeated.

middle( left : Integer, right : integer) : (mid : Integer, valid : Boolean)

let mid = left + floor(right - left, 2)

return (mid, left != mid)

find-rightmost(s : String, c : Char, left : Integer, right : Integer) : (lastIndex : Integer, found : Boolean)

if left >= right then return (left, false) ;; empty range case

if s[right] = c then return (right, true) ;; spans whole range case

let (mid, valid) = middle(left, right) ;; mid is invalid if left = middle

if valid AND s[mid] = c then find-rightmost(s, c, mid, right)

else if valid then find-rightmost(s, c, left, mid)

else return (left, s[left] = c)

find-rightmost is classic binary search in recursive form.

most-frequent-char(s : String) : (c : Char, frequency : Integer)?

let n = length(s)

let nm1 = n - 1

if n = 0 then return nil ;; or NULL of nullptr or whatever you prefer

else if n = 1 then return (s[0], 1) ;; trivial string of length 1

else

let mutable i = 0

let mutable maxf = 0

let mutable cmax = '-'

while i < nm1

let (ilast, found) = find-rightmost(s, s[i], i + 1, nm1)

~~~ update max, cmax when suitable

if found then

i := ilast + 1

else

i := i + 1

end while

return (cmax,maxf)

This yields a total complexity of about O(m*log(n)) where m is the number of disjoint characters.

Since pseudo code cannot easily be verified to actually "work", here the same in Common Lisp:

(defparameter *test-cases*
  '(""
    "a"
    "ab"
    "aabcd"
    "aaaaaaaaaa"
    "abbbbbbbcccdd"))

(defun middle (left right)
  (let ((mid (+ left (floor (- right left) 2))))
    (values mid (/= mid left))))

(defun find-rightmost (s c left right)
  (if (< left right)
      (multiple-value-bind (mid valid) (middle left right)
    (cond
      ((char-equal c (aref s right))
       (values right t))
      ((and valid (char-equal c (aref s mid)))
       (find-rightmost s c mid right))
      (valid
       (find-rightmost s c left mid))
      (t (values left (char-equal c (aref s left))))))
      (values left nil)))

(defun most-frequent-char (s)
  (let* ((n (length s))
     (n-1 (- n 1)))
    (cond
      ((= n 0)
       nil)
      ((= n 1)
       (list :char (aref s 0) :freq 1))
      (t ;; string length > 1 - we actually have to work...
       (loop
     with i = 0
     with cmaxf = nil
     with nmax = 0
     while ( freq nmax)
              (setf nmax freq)
              (setf cmaxf c))
            (setf i (+ ilast 1)))
          (progn
            (when (= 0 nmax)
              (setf nmax 1)
              (setf cmaxf c))
            (incf i))))
     finally (return (list :char cmaxf :freq nmax)))))))

(defun run-tests ()
  (mapcar #'(lambda (in)
          (list in (most-frequent-char in)))
      *test-cases*))
```

CL-USER> (format t "~{~S~%~}~%" (run-tests))

("" NIL)

("a" (:CHAR #\a :FREQ 1))

("ab" (:CHAR #\a :FREQ 1))

("aabcd" (:CHAR #\a :FREQ 2))

("aaaaaaaaaa" (:CHAR #\a :FREQ 10))

("abbbbbbbcccdd" (:CHAR #\b :FREQ 7))

Body:
You can use binary search to find the last occurrence (or rightmost occurrence) of a character in a sub-range of a string to solve this problem.

You use it to hop across the input string, from character to character, no matter how often the same character is being repeated. While you hop, you remember the most frequent character so far and how often it was repeated.

middle( left : Integer, right : integer) : (mid : Integer, valid : Boolean)

let mid = left + floor(right - left, 2)

return (mid, left != mid)

find-rightmost(s : String, c : Char, left : Integer, right : Integer) : (lastIndex : Integer, found : Boolean)

if left >= right then return (left, false) ;; empty range case

if s[right] = c then return (right, true) ;; spans whole range case

let (mid, valid) = middle(left, right) ;; mid is invalid if left = middle

if valid AND s[mid] = c then find-rightmost(s, c, mid, right)

else if valid then find-rightmost(s, c, left, mid)

else return (left, s[left] = c)

find-rightmost is classic binary search in recursive form.

most-frequent-char(s : String) : (c : Char, frequency : Integer)?

let n = length(s)

let nm1 = n - 1

if n = 0 then return nil ;; or NULL of nullptr or whatever you prefer

else if n = 1 then return (s[0], 1) ;; trivial string of length 1

else

let mutable i = 0

let mutable maxf = 0

let mutable cmax = '-'

while i < nm1

let (ilast, found) = find-rightmost(s, s[i], i + 1, nm1)

~~~ update max, cmax when suitable

if found then

i := ilast + 1

else

i := i + 1

end while

return (cmax,maxf)

This yields a total complexity of about O(m*log(n)) where m is the number of disjoint characters.

Since pseudo code cannot easily be verified to actually "work", here the same in Common Lisp:

(defparameter *test-cases*
  '(""
    "a"
    "ab"
    "aabcd"
    "aaaaaaaaaa"
    "abbbbbbbcccdd"))

(defun middle (left right)
  (let ((mid (+ left (floor (- right left) 2))))
    (values mid (/= mid left))))

(defun find-rightmost (s c left right)
  (if (< left right)
      (multiple-value-bind (mid valid) (middle left right)
    (cond
      ((char-equal c (aref s right))
       (values right t))
      ((and valid (char-equal c (aref s mid)))
       (find-rightmost s c mid right))
      (valid
       (find-rightmost s c left mid))
      (t (values left (char-equal c (aref s left))))))
      (values left nil)))

(defun most-frequent-char (s)
  (let* ((n (length s))
     (n-1 (- n 1)))
    (cond
      ((= n 0)
       nil)
      ((= n 1)
       (list :char (aref s 0) :freq 1))
      (t ;; string length > 1 - we actually have to work...
       (loop
     with i = 0
     with cmaxf = nil
     with nmax = 0
     while (< i n-1)
     for c = (aref s i)
     do (multiple-value-bind (ilast found)
        (find-rightmost s c (+ i 1) n-1)
          (if found
          (let ((freq (+ 1 (- ilast i))))
            (when (> freq nmax)
              (setf nmax freq)
              (setf cmaxf c))
            (setf i (+ ilast 1)))
          (progn
            (when (= 0 nmax)
              (setf nmax 1)
              (setf cmaxf c))
            (incf i))))
     finally (return (list :char cmaxf :freq nmax)))))))

(defun run-tests ()
  (mapcar #'(lambda (in)
          (list in (most-frequent-char in)))
      *test-cases*))

CL-USER> (format t "~{~S~%~}~%" (run-tests))

("" NIL)

("a" (:CHAR #\a :FREQ 1))

("ab" (:CHAR #\a :FREQ 1))

("aabcd" (:CHAR #\a :FREQ 2))

("aaaaaaaaaa" (:CHAR #\a :FREQ 10))

("abbbbbbbcccdd" (:CHAR #\b :FREQ 7))


问:
Set pupeteer window size when running not headless (not viewport)
Is it somehow possible to set the browsers (Chrome[ium]) window size like the viewport size?

Setting only the viewport results in a unhandy appearance when the browser is not running headfully and I want to visually see what's going on within the browser instance.

So I would like something like below:

```<code>const browser = await puppeteer.launch({
      headless: false, // The browser is visible
      ignoreHTTPSErrors: true
}),
page = await browser.newPage();

// This is well explained in the API
await page.setViewport({
    width: options.width,
    height: options.height
});

// But is there something like this (careful this is dummy code)
browser.setWindowSize({
    width: options.width,
    height: options.height
});
</code>```

Thanks for any help pointing me into the right direction

答:
```<code> const browser = await puppeteer.launch({
        headless: false,
        defaultViewport: null,
        args: ['--start-maximized'], // we can use '--start-fullscreen' || --start-maximized
    });
</code>```

Body:
Is it somehow possible to set the browsers (Chrome[ium]) window size like the viewport size?

Setting only the viewport results in a unhandy appearance when the browser is not running headfully and I want to visually see what's going on within the browser instance.

So I would like something like below:

const browser = await puppeteer.launch({
      headless: false, // The browser is visible
      ignoreHTTPSErrors: true
}),
page = await browser.newPage();

// This is well explained in the API
await page.setViewport({
    width: options.width,
    height: options.height
});

// But is there something like this (careful this is dummy code)
browser.setWindowSize({
    width: options.width,
    height: options.height
});

Thanks for any help pointing me into the right direction