问:
How do I take an user input from Scanner in one class and then apply it to another class in the same package?
For example

package testcircle1;

import java.util.Scanner;

public class TestCircle1 {

```<code>public static void main(String[] args) {
    System.out.println("Welcome!!!!");
    Circle c1 = new Circle( );
    Scanner in= new Scanner(System.in);

     System.out.println("Please enter a number");

    c1.setRadius() = in.nextDouble();

    System.out.println(c1.getRadius());

}
</code>```

}

package testcircle1;
public class Circle {

```<code>public Circle() {
}

public Circle(double radius) {

}

public void setRadius(double radius) {
    if (radius >= 0)
        this.radius = radius;
}

public double getRadius() {
    return radius;
}
</code>```

}

What am I doing wrong?

答:
You need to add below two.
1. Add 'private double radius;' in class Circle
2. In main method you need to use c1.setRadius(in.nextDouble())

providing code for the same

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Scanner;

public class TestCircle1 {

private static Logger logger = LoggerFactory.getLogger(TestCircle1.class);

public static void main(String[] args) {

```<code>System.out.println("Welcome!!!!");
Circle c1 = new Circle();

try {
  Scanner in = new Scanner(System.in);

  System.out.println("Please enter a number");

  if (!in.hasNextDouble()) {
    throw new IllegalArgumentException("Input is not a double value");
  }

  c1.setRadius(in.nextDouble());

  System.out.println(c1.getRadius());
} catch (IllegalArgumentException e) {
  logger.error(e.getMessage());
}
</code>```

}
}

```<code>public class Circle {
    private double radius;
    public Circle() {
    }

    public Circle(double radius) {

    }

    public void setRadius(double radius) {
        if (radius >= 0)
            this.radius = radius;
    }

    public double getRadius() {
        return radius;
    }

}
</code>```

Body:
For example

package testcircle1;

import java.util.Scanner;

public class TestCircle1 {

public static void main(String[] args) {
    System.out.println("Welcome!!!!");
    Circle c1 = new Circle( );
    Scanner in= new Scanner(System.in);

     System.out.println("Please enter a number");

    c1.setRadius() = in.nextDouble();

    System.out.println(c1.getRadius());

}

}

package testcircle1;
public class Circle {

public Circle() {
}

public Circle(double radius) {

}

public void setRadius(double radius) {
    if (radius >= 0)
        this.radius = radius;
}

public double getRadius() {
    return radius;
}

}

What am I doing wrong?

Body:
You need to add below two.
1. Add 'private double radius;' in class Circle
2. In main method you need to use c1.setRadius(in.nextDouble())

providing code for the same

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Scanner;

public class TestCircle1 {

private static Logger logger = LoggerFactory.getLogger(TestCircle1.class);

public static void main(String[] args) {

System.out.println("Welcome!!!!");
Circle c1 = new Circle();

try {
  Scanner in = new Scanner(System.in);

  System.out.println("Please enter a number");

  if (!in.hasNextDouble()) {
    throw new IllegalArgumentException("Input is not a double value");
  }

  c1.setRadius(in.nextDouble());

  System.out.println(c1.getRadius());
} catch (IllegalArgumentException e) {
  logger.error(e.getMessage());
}

}
}

public class Circle {
    private double radius;
    public Circle() {
    }

    public Circle(double radius) {

    }

    public void setRadius(double radius) {
        if (radius >= 0)
            this.radius = radius;
    }

    public double getRadius() {
        return radius;
    }

}


来源: stackexchange

问:
How to get Version from shadow element in Javers
I am trying to get version from shadows in the Javers.

Currently getting through this way. is this the correct implementation, I think this method can hamper performance a little bit. I am pasting the code here

```<code>    List<Shadow<Season>> shadows= javers.findShadows(QueryBuilder.byInstance(optionalSeason.get()).build());

    for (Shadow<Season> shadow : shadows) {
     List<CdoSnapshot> changes=javers.findSnapshots(QueryBuilder.byInstanceId(id,Season.class).withCommitId(shadow.getCommitId()).build());

     changes.get(0).getVersion()
                  }
</code>```

If there is any better way, please let me know, Thanks

答:
Good question, looks like you can't get it easily because this information is missing in Shadow class:

public class Shadow<T> {
    private final CommitMetadata commitMetadata;
    private final T it;
```

<p>Since each <code>Shadow</code> is created from one <code>CdoSnapshot</code>, <code>Shadow</code> class can be easily extended to:</p>

<pre class="lang-java prettyprint-override"><code>public class Shadow<T> {
    private final CdoSnapshot snapshot;
    private final T it;
</code>```

You can contribute this change to Javers if you want.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to get version from shadows in the Javers.

Currently getting through this way. is this the correct implementation, I think this method can hamper performance a little bit. I am pasting the code here

    List<Shadow<Season>> shadows= javers.findShadows(QueryBuilder.byInstance(optionalSeason.get()).build());

    for (Shadow<Season> shadow : shadows) {
     List<CdoSnapshot> changes=javers.findSnapshots(QueryBuilder.byInstanceId(id,Season.class).withCommitId(shadow.getCommitId()).build());

     changes.get(0).getVersion()
                  }

If there is any better way, please let me know, Thanks

Body:
Good question, looks like you can't get it easily because this information is missing in Shadow class:

public class Shadow<T> {
    private final CommitMetadata commitMetadata;
    private final T it;

Since each Shadow is created from one CdoSnapshot, Shadow class can be easily extended to:

public class Shadow<T> {
    private final CdoSnapshot snapshot;
    private final T it;

You can contribute this change to Javers if you want.


问:
How to send foreignkey data type in API by DRF
I have API written by Django Rest Framework:

models.py

```<code>STATUSES = (("F", "free"),
            ("R", "registered"),
            ("N", "not free")
            )
class Collector(models.Model):
    ip = models.TextField()

    class Meta:
        verbose_name = 'Коллектор'
        verbose_name_plural = 'Коллекторы'
        ordering = ('ip',)

    def __str__(self):
        return str(self.ip)

class Port(models.Model):
    port = models.CharField(max_length=1000)
    status = models.CharField(max_length=1, choices=STATUSES, default="F")
    collector_link = models.ForeignKey(Collector, on_delete=models.CASCADE)

    class Meta:
        verbose_name = 'Порт'
        verbose_name_plural = 'Порты'
        ordering = ('port',)

    def __str__(self):
        return str(self.port)
</code>```

serializers.py

```<code>class CollectorSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Collector
        fields = ("__all__")

class PortSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Port
        fields = ("__all__")
</code>```

views.py

```<code>class CollectorAPIView(APIView):
    serializer_class = serializers.CollectorSerializer
    allowed_methods = ["POST"]

    def post(self, request, *args, **kwargs):
        ip = request.POST['ip']
        obj = models.Collector(ip=request.POST['ip'])
        obj.save()
        return Response(status=status.HTTP_200_OK)

class PortAPIView(APIView):
    serializer_class = serializers.PortSerializer
    allowed_methods = ["POST"]

    def post(self, request, *args, **kwargs):
        port, status1, collector_link = request.POST["port"], request.POST["status"], request.POST["collector_link"]
        entry = models.Port(port=port, status=status1, collector_link=collector_link)
</code>```

entry.save()
            return Response(status=status.HTTP_201_CREATED)
In result, when I'm trying to send data to API in json format like {"port": "1", "status": "F", "collector_link": "10"} (collector_link=10 is id of collector instance in data base) I'm getting the next error:

ValueError at /sm/api/v1/port/ Cannot assign "'10'":
  "Port.collector_link" must be a "Collector" instance
  How I can to fix it?
  .

答:
Try collector_link_id key instead on collector_link

```<code>entry = models.Port(port=port, status=status1, collector_link_id=int(collector_link))

</code>```

Body:
I have API written by Django Rest Framework:

models.py

STATUSES = (("F", "free"),
            ("R", "registered"),
            ("N", "not free")
            )
class Collector(models.Model):
    ip = models.TextField()

    class Meta:
        verbose_name = 'Коллектор'
        verbose_name_plural = 'Коллекторы'
        ordering = ('ip',)

    def __str__(self):
        return str(self.ip)

class Port(models.Model):
    port = models.CharField(max_length=1000)
    status = models.CharField(max_length=1, choices=STATUSES, default="F")
    collector_link = models.ForeignKey(Collector, on_delete=models.CASCADE)

    class Meta:
        verbose_name = 'Порт'
        verbose_name_plural = 'Порты'
        ordering = ('port',)

    def __str__(self):
        return str(self.port)

serializers.py

class CollectorSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Collector
        fields = ("__all__")

class PortSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Port
        fields = ("__all__")

views.py

class CollectorAPIView(APIView):
    serializer_class = serializers.CollectorSerializer
    allowed_methods = ["POST"]

    def post(self, request, *args, **kwargs):
        ip = request.POST['ip']
        obj = models.Collector(ip=request.POST['ip'])
        obj.save()
        return Response(status=status.HTTP_200_OK)

class PortAPIView(APIView):
    serializer_class = serializers.PortSerializer
    allowed_methods = ["POST"]

    def post(self, request, *args, **kwargs):
        port, status1, collector_link = request.POST["port"], request.POST["status"], request.POST["collector_link"]
        entry = models.Port(port=port, status=status1, collector_link=collector_link)

entry.save()
            return Response(status=status.HTTP_201_CREATED)
In result, when I'm trying to send data to API in json format like {"port": "1", "status": "F", "collector_link": "10"} (collector_link=10 is id of collector instance in data base) I'm getting the next error:

ValueError at /sm/api/v1/port/ Cannot assign "'10'":
  "Port.collector_link" must be a "Collector" instance
  How I can to fix it?
  .

Body:
Try collector_link_id key instead on collector_link

entry = models.Port(port=port, status=status1, collector_link_id=int(collector_link))


问:
Problem returning double from a function in C++
I have a function like:

```<code>double foo(int a, int b)
{
    double r=a+b;
    return r/2.0;
}
</code>```

when a= 10000 and b= 10001 It works fine. Returns 10000.5

But when a= 100000 b= 100001 It returns 100000

I have tested with other numbers also. It only works when integers are less than 6 digits.(without using setprecision at output)

I also tried this, but it didn't help.

```<code>double r= double(a+b);
</code>```

Can anyone explain what's happening? If I use setprecision at the output, there's no probllem.

But, I have no control over when and how the output will be printed, I have to submit just this function. Is there anything I can do?

答:
C double or long double uses 6 digit precision in output by default. If you want to write 2000.007 it will give output 2000.01 which is rounded upto 6 digit. But in the memory it will have the correct value. So, the correct way of doing that will be

```<code>double foo(int a, int b)
{
    double r=a+b;
    cout<<setprecision(4)<<fixed;
    return r/2.0;
}
</code>```

And when you use setprecision() and fixed the outputs will be formatted from that point forward to all the outputs until any further changes are made.
So, if you don't want to change anything about the output style then I'm afraid you can't do anything about this.

EDIT: Working with doubles sometime seems to cause unexpected output. For example if you have something like

```<code>double c = 299792458;
double b = 299792450;
cout<<c<<" "<<b<<" "<<c-b;
</code>```

It will output

```<code>2.99792e+008 2.99792e+008 8
</code>```

Which is again rounded to 6 digits which is exactly how it should've happened. But as the 3rd output the result is correct.

Body:
I have a function like:

double foo(int a, int b)
{
    double r=a+b;
    return r/2.0;
}

when a= 10000 and b= 10001 It works fine. Returns 10000.5

But when a= 100000 b= 100001 It returns 100000

I have tested with other numbers also. It only works when integers are less than 6 digits.(without using setprecision at output)

I also tried this, but it didn't help.

double r= double(a+b);

Can anyone explain what's happening? If I use setprecision at the output, there's no probllem.

But, I have no control over when and how the output will be printed, I have to submit just this function. Is there anything I can do?

Body:
C double or long double uses 6 digit precision in output by default. If you want to write 2000.007 it will give output 2000.01 which is rounded upto 6 digit. But in the memory it will have the correct value. So, the correct way of doing that will be

double foo(int a, int b)
{
    double r=a+b;
    cout<<setprecision(4)<<fixed;
    return r/2.0;
}

And when you use setprecision() and fixed the outputs will be formatted from that point forward to all the outputs until any further changes are made.
So, if you don't want to change anything about the output style then I'm afraid you can't do anything about this.

EDIT: Working with doubles sometime seems to cause unexpected output. For example if you have something like

double c = 299792458;
double b = 299792450;
cout<<c<<" "<<b<<" "<<c-b;

It will output

2.99792e+008 2.99792e+008 8

Which is again rounded to 6 digits which is exactly how it should've happened. But as the 3rd output the result is correct.


问:
How do I determine the number of lines of text that will fit into a browser window
I want to display enough lines of text to fill the current size of the browser window.
Also, I'd like to update the value if the browser window changes size. Does javascript have the equivalent of SIGWINCH?

Thanks

答:
Create a dummy element, measure its height in pixels, then destroy it.

The number of lines you need is viewport height/height of line.

The equivalent of SIGWINCH in the browser is a resize event; you can set the handler as window.onresize = function(event){...}; (or use jQuery to set the 'resize' event handler).

ContentLicense: CC BY-SA 3.0


问:
Align 1 child left, the rest right in a div
Trying to align the 3 icons to the right while keeping the title positioned to the left:

Can't seem to get it to work.
Justify-self: flex-end produced no result.
Margin-right: auto produced this:

CODE:

```<code>    <div className="nav-header-container">
      <span className="nav-header">TITLE</span>
      <img
        className="nav-header-icon"
        src="http://localhost:8000/static/frontend/icons/bell.svg/"
      />
      <img
        className="nav-header-icon"
        src="http://localhost:8000/static/frontend/icons/chat.svg/"
      />
      <img
        className="nav-header-icon"
        src="http://localhost:8000/static/frontend/icons/settings.svg/"
      />
    </div>
</code>```

CSS:

```<code>.nav-header-container {
  display: flex;
  align-items: center;

  min-height: 4.26vh;
  width: 100%;

  padding-left: 1em;

  background-color: #435665;
}

.nav-header {
  font-family: open-sans, sans-serif;
  font-size: 20px;
  color: white;
}

.nav-header-icon {
  height: 20px;

  /* justify-self: flex-end; */
  margin-left: auto;
}
</code>```

答:
Wrap the icons in a div then go justify-content: space-between;

html

```<code> <div className="nav-header-container">
  <span className="nav-header">TITLE</span>
  <div class="nav-header-icons">
   <img
     className="nav-header-icon"
     src="http://localhost:8000/static/frontend/icons/bell.svg/"
   />
   <img
     className="nav-header-icon"
     src="http://localhost:8000/static/frontend/icons/chat.svg/"
   />
   <img
     className="nav-header-icon"
     src="http://localhost:8000/static/frontend/icons/settings.svg/"
   />
 </div>
</div>
</code>```

css

```<code>.nav-header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;

  min-height: 4.26vh;
  width: 100%;

  padding-left: 1em;

  background-color: #435665;
}

.nav-header-icons {
  padding-right: 1em;
}

.nav-header-icon {
  height: 20px;
  margin: 0 8px;
}
</code>```

Body:
Trying to align the 3 icons to the right while keeping the title positioned to the left:

Can't seem to get it to work.
Justify-self: flex-end produced no result.
Margin-right: auto produced this:

CODE:

      TITLE

CSS:

.nav-header-container {
  display: flex;
  align-items: center;

  min-height: 4.26vh;
  width: 100%;

  padding-left: 1em;

  background-color: #435665;
}

.nav-header {
  font-family: open-sans, sans-serif;
  font-size: 20px;
  color: white;
}

.nav-header-icon {
  height: 20px;

  /* justify-self: flex-end; */
  margin-left: auto;
}

Body:
Wrap the icons in a div then go justify-content: space-between;

html

 <div className="nav-header-container">
  <span className="nav-header">TITLE</span>
  <div class="nav-header-icons">
   <img
     className="nav-header-icon"
     src="http://localhost:8000/static/frontend/icons/bell.svg/"
   />
   <img
     className="nav-header-icon"
     src="http://localhost:8000/static/frontend/icons/chat.svg/"
   />
   <img
     className="nav-header-icon"
     src="http://localhost:8000/static/frontend/icons/settings.svg/"
   />
 </div>
</div>

css

.nav-header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;

  min-height: 4.26vh;
  width: 100%;

  padding-left: 1em;

  background-color: #435665;
}

.nav-header-icons {
  padding-right: 1em;
}

.nav-header-icon {
  height: 20px;
  margin: 0 8px;
}


问:
Convert Apache rewrite to Nginx
I have this htaccess code:

```<code>RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
</code>```

i wanna convert to nginx rewrite rules, i tried with

```<code>if (!-e $request_filename){
     rewrite ^(.+)$ /index.php?url=$1 break;
}
</code>```

But it doesn't work, any idea ?

答:
Convert your .htaccess for nginx. I just switched from Apache 2.4 to Nginx 1.18.0 and it works, but all rewrite lines should be inside your server block in nginx conf, otherwise it converts it all.

https://winginx.com/en/htaccess

Title: Convert Apache rewrite to Nginx

Body:
I have this htaccess code:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

i wanna convert to nginx rewrite rules, i tried with

if (!-e $request_filename){
     rewrite ^(.+)$ /index.php?url=$1 break;
}

But it doesn't work, any idea ?


问:
PHP Use foreach on a json string that has unicode emojis in it
I have a database and it stores discord guilds in it and the discord guilds can have emojis like   and • . I am having an issue though when I am trying to do a foreach on the data it just says

PHP Warning:  Invalid argument supplied for foreach() in /path/to/my/php/file

I just want to either entirely remove all emojis/unicodes or just be able to show them normally within the foreach statement without a ton of work.

Foreach im using

$stmt = $conn->prepare("SELECT guilds FROM users WHERE discord_id = :discord_id");
$stmt->bindParam(':discord_id', $userdata['discord_id']);
$guildData = $stmt->fecth(PDO::FETCH_ASSOC);
$guildData = json_decode($guildData, true);
var_dump($guildData);

foreach($guildData as $g) {
    echo $g;
}
```

<p>Sample of the data that is in the column guilds:</p>

```[{"id": 1, "guildname": "Server Name "}, {"id": 2, "guildname": "Server Name"}]
```

I want to either keep them and show all the emojis or just entirely remove all unicode emojis and symbols.

答:
```<code>$guildData = $stmt->fecth(PDO::FETCH_ASSOC);
</code>```

Assuming you fix the typo fecth to fetch, this line will return an array. For debugging purposes, when you write

```<code>var_dump($guildData);
</code>```

after that line, you will see something like this:

array(1) {
  ["guilds"]=>
  string(32) "[{"id": 1, "guildname": "Ser...."
}
```

<p>However, the <code>json_decode()</code> function expects a string, not an array.</p>

<p>To fix it you simply access the <code>guilds</code> field from the array:</p>

```$guildData = $stmt->fetch(PDO::FETCH_ASSOC); // returns an array
$jsonData = $guildData['guilds'];            // get the 'guilds' field
$extracted = json_decode($jsonData, true);   // JSON -> array
var_dump($extracted);                        // just for debugging
```

This will fix the "Invalid argument supplied for foreach()" error message. You also might have to take a look at UTF-8 all the way through to see if you have configured everything the right way to get the content in the correct format.

Body:
I have a database and it stores discord guilds in it and the discord guilds can have emojis like   and • . I am having an issue though when I am trying to do a foreach on the data it just says

PHP Warning:  Invalid argument supplied for foreach() in /path/to/my/php/file

I just want to either entirely remove all emojis/unicodes or just be able to show them normally within the foreach statement without a ton of work.

Foreach im using

$stmt = $conn->prepare("SELECT guilds FROM users WHERE discord_id = :discord_id");
$stmt->bindParam(':discord_id', $userdata['discord_id']);
$guildData = $stmt->fecth(PDO::FETCH_ASSOC);
$guildData = json_decode($guildData, true);
var_dump($guildData);

foreach($guildData as $g) {
    echo $g;
}

Sample of the data that is in the column guilds:

[{"id": 1, "guildname": "Server Name "}, {"id": 2, "guildname": "Server Name"}]

I want to either keep them and show all the emojis or just entirely remove all unicode emojis and symbols.

Body:
$guildData = $stmt->fecth(PDO::FETCH_ASSOC);

Assuming you fix the typo fecth to fetch, this line will return an array. For debugging purposes, when you write

var_dump($guildData);

after that line, you will see something like this:

array(1) {
  ["guilds"]=>
  string(32) "[{"id": 1, "guildname": "Ser...."
}

However, the json_decode() function expects a string, not an array.

To fix it you simply access the guilds field from the array:

$guildData = $stmt->fetch(PDO::FETCH_ASSOC); // returns an array
$jsonData = $guildData['guilds'];            // get the 'guilds' field
$extracted = json_decode($jsonData, true);   // JSON -> array
var_dump($extracted);                        // just for debugging

This will fix the "Invalid argument supplied for foreach()" error message. You also might have to take a look at UTF-8 all the way through to see if you have configured everything the right way to get the content in the correct format.


问:
Word wrap at only "Space" After break word into  class for each charactor
My Javascript text animation needs to break word into  class for each character, and after this word wrap is not working properly. Because words are breaking anywhere, I want them to only break at a "space". How can I do this from JS & CSS.

enter image description here

Here is complete code of my JS CSS & HTML

```<code>
<h1 class="rks1">A rose is a woody perennial flowering plant of the genus Rosa, in the family Rosaceae, or the flower it bears. There are over three hundred species and thousands of cultivars. They form a group of plants  </h1>

<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script>

<style>
.rks1 {
  font-weight: 900;
  font-size: 2.5em;
  font-family: rr;
}

.rks1 .letter {
  display: inline-block;
  line-height: 1em;
}
</style>

<script>

// Wrap every letter in a span
var textWrapper = document.querySelector('.rks1');
textWrapper.innerHTML = textWrapper.textContent.replace(/\S/g, "<span class='letter'>$&</span>");

anime.timeline({loop: true})
  .add({
    targets: '.rks1 .letter',
    scale: [3.5,1],
    opacity: [0,1],
    translateZ: 0,
    easing: "easeOutExpo",
    duration: 450,
    delay: (el, i) => 50*i
  }).add({
    targets: '.ml2',
    opacity: 0,
    duration: 1000,
    easing: "easeOutExpo",
    delay: 500
  });
</script>
</code>```

答:
For each "word" you find, wrap each word in a span as well and style that such that it does not wrap. E.g.

```<code>.word {
  white-space: nowrap;
}
</code>```

See: https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

Example:

// Wrap every letter in a span
var textWrapper = document.querySelector('.rks1');
textWrapper.innerHTML = textWrapper.textContent.replace(/(\S*)/g, function(m) {
  return `<span class="word">`
    + m.replace(/\S/g, "$&")
    + `</span>`;
});

anime.timeline({loop: false})
  .add({
    targets: '.rks1 .letter',
    scale: [3.5,1],
    opacity: [0,1],
    translateZ: 0,
    easing: "easeOutExpo",
    duration: 450,
    delay: (el, i) => 50*i
  }).add({
    targets: '.ml2',
    opacity: 0,
    duration: 1000,
    easing: "easeOutExpo",
    delay: 500
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.rks1 {
font-weight: 900;
font-size: 2.5em;
font-family: rr;
}

.rks1 .letter {
display: inline-block;
line-height: 1em;
}

.word {
background-color: #CFF;
white-space: nowrap;
}</code>```

A rose is a woody perennial flowering plant of the genus Rosa, in the family Rosaceae, or the flower it bears. There are over three hundred species and thousands of cultivars. They form a group of plants
```

Title: Word wrap at only "Space" After break word into <span> class for each charactor

Body:
My Javascript text animation needs to break word into  class for each character, and after this word wrap is not working properly. Because words are breaking anywhere, I want them to only break at a "space". How can I do this from JS & CSS.

enter image description here

Here is complete code of my JS CSS & HTML

A rose is a woody perennial flowering plant of the genus Rosa, in the family Rosaceae, or the flower it bears. There are over three hundred species and thousands of cultivars. They form a group of plants

Body:
For each "word" you find, wrap each word in a span as well and style that such that it does not wrap. E.g.

.word {
  white-space: nowrap;
}

See: https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

Example:

// Wrap every letter in a span
var textWrapper = document.querySelector('.rks1');
textWrapper.innerHTML = textWrapper.textContent.replace(/(\S*)/g, function(m) {
  return `<span class="word">`
    + m.replace(/\S/g, "<span class='letter'>$&</span>")
    + `</span>`;
});

anime.timeline({loop: false})
  .add({
    targets: '.rks1 .letter',
    scale: [3.5,1],
    opacity: [0,1],
    translateZ: 0,
    easing: "easeOutExpo",
    duration: 450,
    delay: (el, i) => 50*i
  }).add({
    targets: '.ml2',
    opacity: 0,
    duration: 1000,
    easing: "easeOutExpo",
    delay: 500
  });

.rks1 {
font-weight: 900;
font-size: 2.5em;
font-family: rr;
}

.rks1 .letter {
display: inline-block;
line-height: 1em;
}

.word {
background-color: #CFF;
white-space: nowrap;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script>

<h1 class="rks1">A rose is a woody perennial flowering plant of the genus Rosa, in the family Rosaceae, or the flower it bears. There are over three hundred species and thousands of cultivars. They form a group of plants  </h1>


问:
How to draw a closing view in pygame
I'm trying to make a simple game where, given some condition, the vision field of the character (always at the center of the screen) gets radially reduced until it totally closes and the game ends. The idea is to cover the view with a semi transparent mask around the character's vision field. The relevant part of the code with the solution I apply would be:

```<code>pg.init()
pg.display.init()
screensize = (width,height)=(600,600)
c=(int(width/2),int(height/2))
screen = pg.display.set_mode(screensize)
surface = pg.Surface((600,600), pg.SRCALPHA)

visionradius=20

run=True

while run:

    pg.time.delay(20)
    for event in pg.event.get():
        if event.type == pg.QUIT:
            run=False

    if CONDITION()==True:
        visionradius+=1
    else:
        pass

    pg.draw.circle(surface,(10,255,10,230),(c[0],c[1]),600,visionradius)
    screen.blit(surface, (0,0))

    if visionradius>599:
        run = False

    pg.display.update()
    screen.fill((255,255,255))
pg.quit()
</code>```

The problem with this solution is that it makes my game run slow as radius increases. I would appreciate any ideas for an alternative way for a semi transparent closing view, or for preventing the game running slow. I wonder if pygame draws tons of unitary tickness circles as visionradius increases, which would explain the problem I'm having... If that is so, I could reduce the circle's radius as tickness increases, and it would at least parcially reduce the problem!

答:
The problem with this solution is that it makes my game run slow.

Use pygame.time.Clock() / tick() rather than pygame.time.delay().

tick() the function will delay to keep the game running slower than the given ticks per second. The function ensures a constant frame rate:

clock = pg.time.Clock()
FPS = 50
run = True
while run:
    clock.tick(FPS)

    # [...]
```

Furthermore, the reduction seems to accelerate as the area of the circle decreases with the square of the radius. That is an optical illusion.

Title: How to draw a closing view in pygame

Body:
I'm trying to make a simple game where, given some condition, the vision field of the character (always at the center of the screen) gets radially reduced until it totally closes and the game ends. The idea is to cover the view with a semi transparent mask around the character's vision field. The relevant part of the code with the solution I apply would be:

pg.init()
pg.display.init()
screensize = (width,height)=(600,600)
c=(int(width/2),int(height/2))
screen = pg.display.set_mode(screensize)
surface = pg.Surface((600,600), pg.SRCALPHA)

visionradius=20

run=True

while run:

    pg.time.delay(20)
    for event in pg.event.get():
        if event.type == pg.QUIT:
            run=False

    if CONDITION()==True:
        visionradius+=1
    else:
        pass

    pg.draw.circle(surface,(10,255,10,230),(c[0],c[1]),600,visionradius)
    screen.blit(surface, (0,0))

    if visionradius>599:
        run = False

    pg.display.update()
    screen.fill((255,255,255))
pg.quit()

The problem with this solution is that it makes my game run slow as radius increases. I would appreciate any ideas for an alternative way for a semi transparent closing view, or for preventing the game running slow. I wonder if pygame draws tons of unitary tickness circles as visionradius increases, which would explain the problem I'm having... If that is so, I could reduce the circle's radius as tickness increases, and it would at least parcially reduce the problem!

Body:
The problem with this solution is that it makes my game run slow.

Use pygame.time.Clock() / tick() rather than pygame.time.delay().

tick() the function will delay to keep the game running slower than the given ticks per second. The function ensures a constant frame rate:

clock = pg.time.Clock()
FPS = 50
run = True
while run:
    clock.tick(FPS)

    # [...]

Furthermore, the reduction seems to accelerate as the area of the circle decreases with the square of the radius. That is an optical illusion.


问:
how to use XPath with XDocument?
There is a similar question, but it seems that the solution didn't work out in my case: Weirdness with XDocument, XPath and namespaces

Here is the XML I am working with:

```<code><?xml version="1.0" encoding="utf-8"?>
<Report Id="ID1" Type="Demo Report" Created="2011-01-01T01:01:01+11:00" Culture="en" xmlns="http://demo.com/2011/demo-schema">
    <ReportInfo>
        <Name>Demo Report</Name>
        <CreatedBy>Unit Test</CreatedBy>
    </ReportInfo>
</Report>
</code>```

And below is the code that I thought it should be working but it didn't...

```<code>XDocument xdoc = XDocument.Load(@"C:\SampleXML.xml");
XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable());
xnm.AddNamespace(String.Empty, "http://demo.com/2011/demo-schema");
Console.WriteLine(xdoc.XPathSelectElement("/Report/ReportInfo/Name", xnm) == null);
</code>```

Does anyone have any ideas?
Thanks.

答:
If you have XDocument it is easier to use LINQ-to-XML:

```<code>var document = XDocument.Load(fileName);
var name = document.Descendants(XName.Get("Name", @"http://demo.com/2011/demo-schema")).First().Value;
</code>```

If you are sure that XPath is the only solution you need:

```<code>using System.Xml.XPath;

var document = XDocument.Load(fileName);
var namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("empty", "http://demo.com/2011/demo-schema");
var name = document.XPathSelectElement("/empty:Report/empty:ReportInfo/empty:Name", namespaceManager).Value;
</code>```

Title: how to use XPath with XDocument?

Body:
There is a similar question, but it seems that the solution didn't work out in my case: Weirdness with XDocument, XPath and namespaces

Here is the XML I am working with:

<?xml version="1.0" encoding="utf-8"?>
<Report Id="ID1" Type="Demo Report" Created="2011-01-01T01:01:01+11:00" Culture="en" xmlns="http://demo.com/2011/demo-schema">
    <ReportInfo>
        <Name>Demo Report</Name>
        <CreatedBy>Unit Test</CreatedBy>
    </ReportInfo>
</Report>

And below is the code that I thought it should be working but it didn't...

XDocument xdoc = XDocument.Load(@"C:\SampleXML.xml");
XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable());
xnm.AddNamespace(String.Empty, "http://demo.com/2011/demo-schema");
Console.WriteLine(xdoc.XPathSelectElement("/Report/ReportInfo/Name", xnm) == null);

Does anyone have any ideas?
Thanks.

Body:
If you have XDocument it is easier to use LINQ-to-XML:

var document = XDocument.Load(fileName);
var name = document.Descendants(XName.Get("Name", @"http://demo.com/2011/demo-schema")).First().Value;

If you are sure that XPath is the only solution you need:

using System.Xml.XPath;

var document = XDocument.Load(fileName);
var namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("empty", "http://demo.com/2011/demo-schema");
var name = document.XPathSelectElement("/empty:Report/empty:ReportInfo/empty:Name", namespaceManager).Value;


问:
To use context manager or not?
I'm designing a relational database from scratch in Python, and operations on the DB involve a lot of file operations. What i'm currently doing is opening the files in r+ mode during initialisation and closing them during the shutdown like so-

```<code>class Table:
    def __init__(self,loc):
        self.file=open(loc,"r+")
    def insert(self,key,value):
        self.file.write((key,value))
        self.file.flush()
        os.fsync()
    def __close__(self):
        self.file.close()
</code>```

The alternative way of doing this would be to open the file in every call to insert using a context manager, but i presume that'd kill efficiency.
What would be the preferred way of doing things given the context?

答:
Use a with block for the instance, and then the user can have multiple calls happen while the underlying file is open, while still ensuring proper cleanup. You can do this by making the class a context manager. For convenience, you may also want to offer an explicit close method; follow convention and name it close, not __close__ (as there is not any special dunder method with that name).

Something like:

```<code>class Table:
    def __init__(self, loc):
        self.file = open(loc, "r+")
    def insert(self, key, value):
        self.file.write((key, value))
        self.file.flush()
        os.fsync(self.file.fileno())
    def close(self):
        self.file.close()
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_value, traceback):
        self.close()
</code>```

Now you can do something like:

```<code>with Table('foo/bar/baz.db') as t:
    for i, j in my_data:
        t.insert(i, j)

</code>```

Title: To use context manager or not?

Body:
I'm designing a relational database from scratch in Python, and operations on the DB involve a lot of file operations. What i'm currently doing is opening the files in r+ mode during initialisation and closing them during the shutdown like so-

class Table:
    def __init__(self,loc):
        self.file=open(loc,"r+")
    def insert(self,key,value):
        self.file.write((key,value))
        self.file.flush()
        os.fsync()
    def __close__(self):
        self.file.close()

The alternative way of doing this would be to open the file in every call to insert using a context manager, but i presume that'd kill efficiency.
What would be the preferred way of doing things given the context?

Body:
Use a with block for the instance, and then the user can have multiple calls happen while the underlying file is open, while still ensuring proper cleanup. You can do this by making the class a context manager. For convenience, you may also want to offer an explicit close method; follow convention and name it close, not __close__ (as there is not any special dunder method with that name).

Something like:

class Table:
    def __init__(self, loc):
        self.file = open(loc, "r+")
    def insert(self, key, value):
        self.file.write((key, value))
        self.file.flush()
        os.fsync(self.file.fileno())
    def close(self):
        self.file.close()
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_value, traceback):
        self.close()

Now you can do something like:

with Table('foo/bar/baz.db') as t:
    for i, j in my_data:
        t.insert(i, j)


问:
jquery function always skips form validation
I want to validate a form with the default html validation (required) if the form is valid, then it should execute this function

it always skips validation when i use the function
i also added the required parameter in the input tag, but still no validation

```<code>$(document).ready(function(){
    $('#send-form').click(function(e) {
      e.preventDefault();
      mail_url = 'mailto:office@test.at?Subject=' + 'Anfrage' + '&Body=' + $('#exampleFormControlTextarea1').val() + '%0D%0A' + '%0D%0A' +$('#inputVorname').val() + '%0D%0A' + $('#inputNachname').val() + '%0D%0A' + $('#inputAdresse').val() + '%0D%0A' + $('#inputPlz').val() + '%0D%0A' + $('#inputOrt').val() + '%0D%0A' + $('#inputTelefon').val() + '%0D%0A' + $('#email').val()
      window.location = mail_url
  });
});
</code>```

```<code>

HTML:

<form class="formular" id="kontakt">
    <div class="form-row">
        <div class="form-group col-md-6">
            <label for="inputVorname">*Vorname:</label>
            <input type="text" class="form-control" id="inputVorname" placeholder="Vorname" name="vorname" required>

        </div>
        <div class="form-group col-md-6">
            <label for="inputNachname">*Nachname:</label>
            <input type="text" class="form-control" id="inputNachname" placeholder="Nachname" required>
        </div>
    </div>

    <div class="form-row">
        <div class="form-group col-md-6">
            <label for="inputAdresse">*Adresse:</label>
            <input type="text" class="form-control" id="inputAdresse" placeholder="Adresse" required>
        </div>

        <div class="form-group col-md-2">
            <label for="inputPlz">*PLZ:</label>
            <input style="width: 80px;" type="text" class="form-control" id="inputPlz" placeholder="PLZ" required>
        </div>

        <div class="form-group col-md-4">
            <label for="inputOrt">*Ort:</label>
            <input type="text" class="form-control" id="inputOrt" placeholder="Ort" required>
        </div>
    </div>
    <div>

        <div class="form-group" id="head-textarea">
            <label for="exampleFormControlTextarea1">Fragen/Anmerkungen:</label>
            <textarea class="form-control" id="exampleFormControlTextarea1" rows="10"
                style="border:solid 2px black; border-radius: 0px;" maxlength="400"></textarea>
        </div>
        <p>blablablablablalblablablablablablabl</p>
        <div class="checkbox">
            <label class="checkbox-inline"><input type="checkbox" value="zustimmen" required>
                <p style="text-align: justify;">ksdjkfljksdfjklsdfjksdölflsdkfl</p>
            </label>
        </div>
    </div>
    <button id="send-form" value="Submit" type="submit"
        class="btn btn-primary btn-lg btn-block form-submit">ABSCHICKEN</button>
    </div>
    </div>
</form>

</code>```

答:
You need change event from click to submit as

```<code> $('#send-form').submit(function(e) {}
</code>```

$(document).ready(function(){
    $('#send-form').submit(function(e) {
      e.preventDefault();
      mail_url = 'mailto:office@test.at?Subject=' + 'Anfrage' + '&Body=' + $('#exampleFormControlTextarea1').val() + '%0D%0A' + '%0D%0A' +$('#inputVorname').val() + '%0D%0A' + $('#inputNachname').val() + '%0D%0A' + $('#inputAdresse').val() + '%0D%0A' + $('#inputPlz').val() + '%0D%0A' + $('#inputOrt').val() + '%0D%0A' + $('#inputTelefon').val() + '%0D%0A' + $('#email').val()
      window.location = mail_url
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="formular" id="kontakt">
    <div class="form-row">
        <div class="form-group col-md-6">
            <label for="inputVorname">*Vorname:</label>
            <input type="text" class="form-control" id="inputVorname" placeholder="Vorname" name="vorname" required>

        </div>
        <div class="form-group col-md-6">
            <label for="inputNachname">*Nachname:</label>
            <input type="text" class="form-control" id="inputNachname" placeholder="Nachname" required>
        </div>
    </div>

    <div class="form-row">
        <div class="form-group col-md-6">
            <label for="inputAdresse">*Adresse:</label>
            <input type="text" class="form-control" id="inputAdresse" placeholder="Adresse" required>
        </div>

        <div class="form-group col-md-2">
            <label for="inputPlz">*PLZ:</label>
            <input style="width: 80px;" type="text" class="form-control" id="inputPlz" placeholder="PLZ" required>
        </div>

        <div class="form-group col-md-4">
            <label for="inputOrt">*Ort:</label>
            <input type="text" class="form-control" id="inputOrt" placeholder="Ort" required>
        </div>
    </div>
    <div>

        <div class="form-group" id="head-textarea">
            <label for="exampleFormControlTextarea1">Fragen/Anmerkungen:</label>
            <textarea class="form-control" id="exampleFormControlTextarea1" rows="10"
                style="border:solid 2px black; border-radius: 0px;" maxlength="400"></textarea>
        </div>
        <p>blablablablablalblablablablablablabl</p>
        <div class="checkbox">
            <label class="checkbox-inline"><input type="checkbox" value="zustimmen" required>
                <p style="text-align: justify;">ksdjkfljksdfjklsdfjksdölflsdkfl</p>
            </label>
        </div>
    </div>
    <button id="send-form" value="Submit" type="submit"
        class="btn btn-primary btn-lg btn-block form-submit">ABSCHICKEN</button>
    </div>
    </div>
</form></code>```

Body:
I want to validate a form with the default html validation (required) if the form is valid, then it should execute this function

it always skips validation when i use the function
i also added the required parameter in the input tag, but still no validation

$(document).ready(function(){
    $('#send-form').click(function(e) {
      e.preventDefault();
      mail_url = 'mailto:office@test.at?Subject=' + 'Anfrage' + '&Body=' + $('#exampleFormControlTextarea1').val() + '%0D%0A' + '%0D%0A' +$('#inputVorname').val() + '%0D%0A' + $('#inputNachname').val() + '%0D%0A' + $('#inputAdresse').val() + '%0D%0A' + $('#inputPlz').val() + '%0D%0A' + $('#inputOrt').val() + '%0D%0A' + $('#inputTelefon').val() + '%0D%0A' + $('#email').val()
      window.location = mail_url
  });
});

HTML:

<form class="formular" id="kontakt">

            *Vorname:
            <input type="text" class="form-control" id="inputVorname" placeholder="Vorname" name="vorname" required>

            *Nachname:
            <input type="text" class="form-control" id="inputNachname" placeholder="Nachname" required>

            *Adresse:
            <input type="text" class="form-control" id="inputAdresse" placeholder="Adresse" required>

            *PLZ:
            <input style="width: 80px;" type="text" class="form-control" id="inputPlz" placeholder="PLZ" required>

            *Ort:
            <input type="text" class="form-control" id="inputOrt" placeholder="Ort" required>

            Fragen/Anmerkungen:
            <textarea class="form-control" id="exampleFormControlTextarea1" rows="10"
                style="border:solid 2px black; border-radius: 0px;" maxlength="400"></textarea>

blablablablablalblablablablablablabl

            <input type="checkbox" value="zustimmen" required>

ksdjkfljksdfjklsdfjksdölflsdkfl

    <button id="send-form" value="Submit" type="submit"
        class="btn btn-primary btn-lg btn-block form-submit">ABSCHICKEN</button>

</form>

Body:
You need change event from click to submit as

 $('#send-form').submit(function(e) {}

$(document).ready(function(){
    $('#send-form').submit(function(e) {
      e.preventDefault();
      mail_url = 'mailto:office@test.at?Subject=' + 'Anfrage' + '&Body=' + $('#exampleFormControlTextarea1').val() + '%0D%0A' + '%0D%0A' +$('#inputVorname').val() + '%0D%0A' + $('#inputNachname').val() + '%0D%0A' + $('#inputAdresse').val() + '%0D%0A' + $('#inputPlz').val() + '%0D%0A' + $('#inputOrt').val() + '%0D%0A' + $('#inputTelefon').val() + '%0D%0A' + $('#email').val()
      window.location = mail_url
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="formular" id="kontakt">
    <div class="form-row">
        <div class="form-group col-md-6">
            <label for="inputVorname">*Vorname:</label>
            <input type="text" class="form-control" id="inputVorname" placeholder="Vorname" name="vorname" required>

        </div>
        <div class="form-group col-md-6">
            <label for="inputNachname">*Nachname:</label>
            <input type="text" class="form-control" id="inputNachname" placeholder="Nachname" required>
        </div>
    </div>

    <div class="form-row">
        <div class="form-group col-md-6">
            <label for="inputAdresse">*Adresse:</label>
            <input type="text" class="form-control" id="inputAdresse" placeholder="Adresse" required>
        </div>

        <div class="form-group col-md-2">
            <label for="inputPlz">*PLZ:</label>
            <input style="width: 80px;" type="text" class="form-control" id="inputPlz" placeholder="PLZ" required>
        </div>

        <div class="form-group col-md-4">
            <label for="inputOrt">*Ort:</label>
            <input type="text" class="form-control" id="inputOrt" placeholder="Ort" required>
        </div>
    </div>
    <div>

        <div class="form-group" id="head-textarea">
            <label for="exampleFormControlTextarea1">Fragen/Anmerkungen:</label>
            <textarea class="form-control" id="exampleFormControlTextarea1" rows="10"
                style="border:solid 2px black; border-radius: 0px;" maxlength="400"></textarea>
        </div>
        <p>blablablablablalblablablablablablabl</p>
        <div class="checkbox">
            <label class="checkbox-inline"><input type="checkbox" value="zustimmen" required>
                <p style="text-align: justify;">ksdjkfljksdfjklsdfjksdölflsdkfl</p>
            </label>
        </div>
    </div>
    <button id="send-form" value="Submit" type="submit"
        class="btn btn-primary btn-lg btn-block form-submit">ABSCHICKEN</button>
    </div>
    </div>
</form>


问:
DatePicker on Mac not saving date until return key is pressed
I'm adapting my iPad app to Mac with Mac Catalyst and am having a problem with the datePicker (it has a datePickerMode of time). On iPad the datePicker is a wheel and whenever the user scrolls on the date picker the dateChanged action is fired. But on Mac the date picker is not a scroller and is instead a type of text input. I can type and change all the time values on Mac, but the dateChanged action won't be fired until I press the return key.

I would like to get the dateChange action fired whenever a user is entering in a time. How can I do this? I tried adding different targets to the datePicker but nothing work.

I actually prefer to have the date scroller on the Mac so if anyone knows how to do this instead I would greatly appreciate it (I looked all over the internet for this and found nothing)!

Here's my code:

```<code>class DateVC: UIViewController {
     @IBOutlet weak var datePicker: UIDatePicker!

     override func viewDidLoad() {
          super.viewDidLoad()

          //Just show the time
          datePicker.datePickerMode = .time
    }

     //Action connected to datePicker. This is not called until I press enter on Mac
     @IBAction func datePickerChanged(_ sender: Any) {
        //do actions
     }

}
</code>```

答:
Here is a SwiftUI solution that displays a date and time scroller picker on iPad, iPhone and Mac Catalyst. Works without pressing the return key. You can easily display just the HoursMinutesPicker if desired.</p>

```<code>import SwiftUI

struct ContentView: View {
@State var date = Date()
var body: some View {
    NavigationView {
        NavigationLink(destination: DateHMPicker(date: self.$date)) {
            VStack {
                Text("Show time")
                Text("\(self.date)")
            }
        }
    }.navigationViewStyle(StackNavigationViewStyle())
}
}

struct DateHMPicker: View {
var titleKey: LocalizedStringKey = ""
@Binding var date: Date

var body: some View {
    HStack {
        Spacer()
        DatePicker(titleKey, selection: self.$date, displayedComponents: .date).datePickerStyle(WheelDatePickerStyle())
        HoursMinutesPicker(date: self.$date)
        Spacer()
    }
}
}

struct HoursMinutesPicker: View {
@Binding var date: Date
@State var hours: Int = 0
@State var minutes: Int = 0

var body: some View {
    HStack {
        Spacer()
        Picker("", selection: Binding<Int>(
            get: { self.hours},
            set : {
                self.hours = $0
                self.update()
        })) {
            ForEach(0..<24, id: \.self) { i in
                Text("\(i) hours").tag(i)
            }
        }.pickerStyle(WheelPickerStyle()).frame(width: 90).clipped()
        Picker("", selection: Binding<Int>(
            get: { self.minutes},
            set : {
                self.minutes = $0
                self.update()
        })) {
            ForEach(0..<60, id: \.self) { i in
                Text("\(i) min").tag(i)
            }
        }.pickerStyle(WheelPickerStyle()).frame(width: 90).clipped()
        Spacer()
    }.onAppear(perform: loadData)
}

func loadData() {
    self.hours = Calendar.current.component(.hour, from: date)
    self.minutes = Calendar.current.component(.minute, from: date)
}

func update() {
    if let newDate = Calendar.current.date(bySettingHour: self.hours, minute: self.minutes, second: 0, of: date) {
        date = newDate
    }
}
}
</code>```

Body:
I'm adapting my iPad app to Mac with Mac Catalyst and am having a problem with the datePicker (it has a datePickerMode of time). On iPad the datePicker is a wheel and whenever the user scrolls on the date picker the dateChanged action is fired. But on Mac the date picker is not a scroller and is instead a type of text input. I can type and change all the time values on Mac, but the dateChanged action won't be fired until I press the return key.

I would like to get the dateChange action fired whenever a user is entering in a time. How can I do this? I tried adding different targets to the datePicker but nothing work.

I actually prefer to have the date scroller on the Mac so if anyone knows how to do this instead I would greatly appreciate it (I looked all over the internet for this and found nothing)!

Here's my code:

class DateVC: UIViewController {
     @IBOutlet weak var datePicker: UIDatePicker!

     override func viewDidLoad() {
          super.viewDidLoad()

          //Just show the time
          datePicker.datePickerMode = .time
    }

     //Action connected to datePicker. This is not called until I press enter on Mac
     @IBAction func datePickerChanged(_ sender: Any) {
        //do actions
     }

}

Body:
Here is a SwiftUI solution that displays a date and time scroller picker on iPad, iPhone and Mac Catalyst. Works without pressing the return key. You can easily display just the HoursMinutesPicker if desired.

import SwiftUI

struct ContentView: View {
@State var date = Date()
var body: some View {
    NavigationView {
        NavigationLink(destination: DateHMPicker(date: self.$date)) {
            VStack {
                Text("Show time")
                Text("\(self.date)")
            }
        }
    }.navigationViewStyle(StackNavigationViewStyle())
}
}

struct DateHMPicker: View {
var titleKey: LocalizedStringKey = ""
@Binding var date: Date

var body: some View {
    HStack {
        Spacer()
        DatePicker(titleKey, selection: self.$date, displayedComponents: .date).datePickerStyle(WheelDatePickerStyle())
        HoursMinutesPicker(date: self.$date)
        Spacer()
    }
}
}

struct HoursMinutesPicker: View {
@Binding var date: Date
@State var hours: Int = 0
@State var minutes: Int = 0

var body: some View {
    HStack {
        Spacer()
        Picker("", selection: Binding<Int>(
            get: { self.hours},
            set : {
                self.hours = $0
                self.update()
        })) {
            ForEach(0..<24, id: \.self) { i in
                Text("\(i) hours").tag(i)
            }
        }.pickerStyle(WheelPickerStyle()).frame(width: 90).clipped()
        Picker("", selection: Binding<Int>(
            get: { self.minutes},
            set : {
                self.minutes = $0
                self.update()
        })) {
            ForEach(0..<60, id: \.self) { i in
                Text("\(i) min").tag(i)
            }
        }.pickerStyle(WheelPickerStyle()).frame(width: 90).clipped()
        Spacer()
    }.onAppear(perform: loadData)
}

func loadData() {
    self.hours = Calendar.current.component(.hour, from: date)
    self.minutes = Calendar.current.component(.minute, from: date)
}

func update() {
    if let newDate = Calendar.current.date(bySettingHour: self.hours, minute: self.minutes, second: 0, of: date) {
        date = newDate
    }
}
}


问:
MySQL query slow querying table on primary key
So I have a table that's being used basically like a NoSQL setup. The structure is:

id bigint primary key
data mediumblob
modified timestamp

It has around 350k rows. The queries that run on it are all structured as follows:

select data from table where id=XXX;

The table engine is InnoDB. I'm noticing that sometimes queries run against this table are rather slow. Sometimes they take 3 seconds to run. The table is 3 GB on disk and I gave the innodb_buffer_pool_size 4G.

Is there anything I'm missing here? Are there any settings I can tweak to improve performance?

Edit: As requested explain output:

```<code>+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table    | type  | possible_keys | key     | key_len | ref   | rows | Extra |
+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+
|  1 | SIMPLE      | cache    | const | PRIMARY       | PRIMARY | 8       | const |    1 |       |
+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+
</code>```

create table:

```<code>CREATE TABLE `cache` (
  `id` bigint(20) unsigned NOT NULL DEFAULT '0',
  `data` mediumblob,
  `modified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
</code>```

答:
There are two issues that I see here initially.  First is that you have a query with a blob data type.  This will cause speed issues when it comes to data retrieval.  Second, you are using InnoDB, which is optimized for writing.  This means that while it is probably the best choice overall, in extreme read situations it might be less performant than MyISAM.  Neither of these issues are necessarily deal-killers but they do each add a performance hit.  Beyond this, however, I'm not sure I can give you a good answer as to what you can do to better optimize without first having you do profiling.  That is what I would recommend you do first.  Profile your query to figure out what the execution plan is and then identify why the execution plan is so slow.

Here is a good "Top 10" list of MySQL optimizations.  At least a couple apply in your situation directly:

http://20bits.com/articles/10-tips-for-optimizing-mysql-queries-that-dont-suck/

Here is another good optimization article that goes into server settings as well (for InnoDB specifically):

http://www.mysqlperformanceblog.com/2007/11/01/innodb-performance-optimization-basics/

Based on the CREATE TABLE statement you provided, I did think of another thing that you should address (again, not a query-killer but it is another performance hit).  Unless there is a business case for using a bigint for your ID field, choose an int instead.  An int will allow 2.1 billion rows so you shouldn't run out of numbers.  Making this switch will save you disk space and it will improve query performance.  Here is an article about it:

http://ronaldbradford.com/blog/bigint-v-int-is-there-a-big-deal-2008-07-18/

Body:
So I have a table that's being used basically like a NoSQL setup. The structure is:

id bigint primary key
data mediumblob
modified timestamp

It has around 350k rows. The queries that run on it are all structured as follows:

select data from table where id=XXX;

The table engine is InnoDB. I'm noticing that sometimes queries run against this table are rather slow. Sometimes they take 3 seconds to run. The table is 3 GB on disk and I gave the innodb_buffer_pool_size 4G.

Is there anything I'm missing here? Are there any settings I can tweak to improve performance?

Edit: As requested explain output:

+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table    | type  | possible_keys | key     | key_len | ref   | rows | Extra |
+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+
|  1 | SIMPLE      | cache    | const | PRIMARY       | PRIMARY | 8       | const |    1 |       |
+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+

create table:

CREATE TABLE `cache` (
  `id` bigint(20) unsigned NOT NULL DEFAULT '0',
  `data` mediumblob,
  `modified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8


问:
Pandas Detect Non-Numberic Data types
I need to detect and prevent any non-numeric data getting into my dataframe.

example:

```<code>     value       in       out     transf      inc        buy
0   208372  4206.84   4692.22     215976   725.41  105339.92
1      abs     0.00   1270.28      13602  1151.29       0.00
2   230172     0.00   1930.40      21539  1938.59       0.00
3   394391     0.00  11517.96     174320  1517.06  170032.09
4   382101     0.00   2962.82          0  3001.14   10000.00
</code>```

print(df.dtypes) gives me this:

```<code>value         object
in           float64
out          float64
transf         int64
inc          float64
buy          float64
dtype: object
</code>```

So how do I detect if there are any non-number (float64, int64) datatype?

Thank you.

答:
If you want to find the row number of the non numeric data you can use this:</p>

```<code>print('Following row indices contains the string type value')
for ind, row in df.iterrows():
    if any(isinstance(x,str) for x in row):
        print(ind+1)
</code>```

Title: Pandas Detect Non-Numberic Data types

Body:
I need to detect and prevent any non-numeric data getting into my dataframe.

example:

     value       in       out     transf      inc        buy
0   208372  4206.84   4692.22     215976   725.41  105339.92
1      abs     0.00   1270.28      13602  1151.29       0.00
2   230172     0.00   1930.40      21539  1938.59       0.00
3   394391     0.00  11517.96     174320  1517.06  170032.09
4   382101     0.00   2962.82          0  3001.14   10000.00

print(df.dtypes) gives me this:

value         object
in           float64
out          float64
transf         int64
inc          float64
buy          float64
dtype: object

So how do I detect if there are any non-number (float64, int64) datatype?

Thank you.

Body:
If you want to find the row number of the non numeric data you can use this:

print('Following row indices contains the string type value')
for ind, row in df.iterrows():
    if any(isinstance(x,str) for x in row):
        print(ind+1)


问:
Incrementation in Lua
I am playing a little bit with Lua.

I came across the following code snippet that have an unexpected behavior:

a = 3;
b = 5;
c = a-- * b++; // some computation
print(a, b, c);
```

Lua runs the program without any error but does not print 2  6  15 as expected. Why ?

答:
EDIT: Using SharpLua in C# incrementing/decrementing in lua can be done in shorthand like so:

```<code>a+=1 --increment by some value
a-=1 --decrement by some value
</code>```

In addition, multiplication/division can be done like so:

```<code>a*=2 --multiply by some value
a/=2 --divide by some value
</code>```

The same method can be used if adding, subtracting, multiplying or dividing one variable by another, like so:

```<code>a+=b
a-=b
a/=b
a*=b
</code>```

This is much simpler and tidier and I think a lot less complicated, but not everybody will share my view.

Hope this helps!

Title: Incrementation in Lua

Body:
I am playing a little bit with Lua.

I came across the following code snippet that have an unexpected behavior:

a = 3;
b = 5;
c = a-- * b++; // some computation
print(a, b, c);

Lua runs the program without any error but does not print 2  6  15 as expected. Why ?

Body:
EDIT: Using SharpLua in C# incrementing/decrementing in lua can be done in shorthand like so:

a+=1 --increment by some value
a-=1 --decrement by some value

In addition, multiplication/division can be done like so:

a*=2 --multiply by some value
a/=2 --divide by some value

The same method can be used if adding, subtracting, multiplying or dividing one variable by another, like so:

a+=b
a-=b
a/=b
a*=b

This is much simpler and tidier and I think a lot less complicated, but not everybody will share my view.

Hope this helps!


问:
Does using a prototype + definition instead of just a definition speed up the program?
Im very new to C programing, but have limited experience with Python, Java, and Perl. I was just wondering what the advantage is of having the prototype of a function above main() and the definition of that function below main() rather than just having the definition of said function above main(). From what I have read, the definition can act as a prototype as well.

Thanks in advance,

答:
There's no advantage in splitting a function into a standalone prototype and a definition. In fact, there's a clear and explicit disadvantage to that approach, since it requires extra maintenance efforts to keep the prototype and the definition in perfect sync. For this reason, a reasonable approach would be to provide a separate prototype only when you have to. For example, with external functions declared in header files you have no other choice but to keep the prototype and definition separate.

As for functions internal to a single translation unit (the ones that we'd normally declare static) there's absolutely no reason to create a standalone prototype, since the definition of the function itself includes a prototype. Just define your functions in the natural order: low level functions first, high level functions last, and that's it. If your program consists of a single translation unit, the main function will end up at the very bottom.

The only case you'd have to declare a standalone prototype in this approach would be if some form of recursion was involved.


问:
Android Studio -- Failed to apply plugin [id 'appengine']
When I sync my project with Gradle files, I get the following errors:

Caused by: org.gradle.api.internal.plugins.PluginApplicationException: Failed to apply plugin [id 'appengine']

and

Caused by: groovy.lang.MissingPropertyException: Could not get unknown property 'classesDir' for functional test classes of type org.gradle.api.internal.tasks.DefaultSourceSetOutput.

My gradle is on the latest version and I've tried previous solutions on Stack Overflow, but none of them seem to work.

Project Build.Gradle:

```<code>
buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
        google()
    }
    dependencies {

        classpath 'com.android.tools.build:gradle:3.6.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }

}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Backend build.gradle:

```<code>// https://github.com/GoogleCloudPlatform/gradle-appengine-plugin

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.google.appengine:gradle-appengine-plugin:1.9.59'
    }
}

repositories {
    jcenter();
}

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'appengine'

sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7

dependencies {
  appengineSdk 'com.google.appengine:appengine-java-sdk:1.9.59'
  compile 'com.google.appengine:appengine-endpoints:1.9.18'
  compile 'com.google.appengine:appengine-endpoints-deps:1.9.18'
  compile 'javax.servlet:servlet-api:2.5'
}

appengine {
  downloadSdk = true
  appcfg {
    oauth2 = true
  }
  endpoints {
    getClientLibsOnBuild = true
    getDiscoveryDocsOnBuild = true
  }
}
</code>```

It seems as the main issue is the App Engine plugin, but I'm not sure how to fix that. I believe the latest gradle files are being used, which was a solution other stack overflow solutions provided, but didn't work for me. If anyone has insight on this, it'd be great.

答: 'classesDir' is deprecated and removed in gradle 5.X onwards try replacing it by 'classesDirs'. Check this out for information here.</p>

Body:
When I sync my project with Gradle files, I get the following errors:

Caused by: org.gradle.api.internal.plugins.PluginApplicationException: Failed to apply plugin [id 'appengine']

and

Caused by: groovy.lang.MissingPropertyException: Could not get unknown property 'classesDir' for functional test classes of type org.gradle.api.internal.tasks.DefaultSourceSetOutput.

My gradle is on the latest version and I've tried previous solutions on Stack Overflow, but none of them seem to work.

Project Build.Gradle:

buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
        google()
    }
    dependencies {

        classpath 'com.android.tools.build:gradle:3.6.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }

}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Backend build.gradle:

// https://github.com/GoogleCloudPlatform/gradle-appengine-plugin

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.google.appengine:gradle-appengine-plugin:1.9.59'
    }
}

repositories {
    jcenter();
}

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'appengine'

sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7

dependencies {
  appengineSdk 'com.google.appengine:appengine-java-sdk:1.9.59'
  compile 'com.google.appengine:appengine-endpoints:1.9.18'
  compile 'com.google.appengine:appengine-endpoints-deps:1.9.18'
  compile 'javax.servlet:servlet-api:2.5'
}

appengine {
  downloadSdk = true
  appcfg {
    oauth2 = true
  }
  endpoints {
    getClientLibsOnBuild = true
    getDiscoveryDocsOnBuild = true
  }
}

It seems as the main issue is the App Engine plugin, but I'm not sure how to fix that. I believe the latest gradle files are being used, which was a solution other stack overflow solutions provided, but didn't work for me. If anyone has insight on this, it'd be great.


问:
Can't bind to 'aria-valuenow' since it isn't a known property of 'div'
What's wrong with the following code?
Hapenned to me when I tried to assign an expression to an element,

```<code><div class="progress-bar progress-bar-striped active" role="progressbar"
  aria-valuenow="{{MY_PREC}}" aria-valuemin="0" aria-valuemax="100" >
    {{MY_PREC}}
  </div>
</code>```

also tried as

```<code>[aria-valuenow]={{MY_PREC}}
</code>```

Seem like it happens since RC5

any ideas?

答:
In .ts file:

```<code>public MY_PREC = '55';
</code>```

In .html file:

```<code><div class="progress-bar progress-bar-striped active" role="progressbar"
     [attr.aria-valuenow]="MY_PREC" [style.width]="MY_PREC+'%'" aria-valuemin="0" aria-valuemax="100" >
     {{MY_PREC}}
</div>
</code>```

Body:
What's wrong with the following code?
Hapenned to me when I tried to assign an expression to an element,

    {{MY_PREC}}

also tried as

[aria-valuenow]={{MY_PREC}}

Seem like it happens since RC5

any ideas?

Body:
In .ts file:

public MY_PREC = '55';

In .html file:

<div class="progress-bar progress-bar-striped active" role="progressbar"
     [attr.aria-valuenow]="MY_PREC" [style.width]="MY_PREC+'%'" aria-valuemin="0" aria-valuemax="100" >
     {{MY_PREC}}
</div>


问:
Utilizing the <filesystem> library; visualStudios
I'll cut the the short of it. I'm attempting to understand the filesystem library but there's very little information I've been able to find. I managed to get it to compile and understand the filesystem::path type variable really well but don't seem to understand how to get filesystem::directory_iterator to work properly. I'm not sure if I'm using it for a purpose it wasn't design for. So here is what I'm attempting to do:

I wanted to create a program that opens every text file within a specified folder. For this I need to obtain the folder name and path but I want the program to be able to obtain this information on itself and dynamically so if I add or remove textFiles it'll have the logic to function.

I'm able to create a directory_iterator variable that it manages to hold the first file with me just giving it the directory like this:

```<code>const char address[]{ "C:\\Users\\c-jr8\\ProgramBranch\\PersonalPlatform\\log extruder\\logs" };

fs::directory_iterator myIterator(address);
</code>```

When testing the code in the folder I have four textFiles called "attempt 1" to "attempt 4". When reading the information on:

https://learn.microsoft.com/en-us/cpp/standard-library/directory-iterator-class?view=vs-2019#op_star

It mentions two functions to move the path object within the iterator to the next file. The first is increment(), which is the intendent method for iterating through the files, and operation++().

Now increment() hasn't been able to work for me cause it takes in a erro_code type variable and I haven't been able to find much information about how to implement this with the filesystem_errorcode variable or however it's meant to be used. The operation++() works beautifully and provides me with the path to every file but I was having issues with managing the code to detect when the operate++() functions leads to no other files. Once it iterates through every file it sorts of crashes when it keeps moving to the next. Here's that piece of code:

```<code>string tempString;
for (int i = 0; i < 5; i++) { //Here the limiting is 5 so it'll iterate onces more than the numbers of files unpurpose to see how it responses.
    tempString = myIterator.operator*().path().generic_string();
    ifstream tempFile(tempString);

    if (!tempFile.is_open()) {
        cout << "Looking at file: " << i + 1 << "; failed to open." << endl << endl;
        cin.get();
        return 0;
    }

    {
        //do things with file...
    }

    tempFile.close();
    myIterator.operator++();
}
</code>```

What I want if to find a way to stop the for loop once it the iterator goes off the final file.

whichever information about how the filesystem library works it would be very much appreciated.

答:
You should compare myIterator with a default constructed directory_iterator to check if the last file has been processed. You can also use a much simpler form to access the operators (shown in the code below):

```<code>string tempString;

// loop until myIterator == fs::directory_iterator{}
for(size_t i = 1; myIterator != fs::directory_iterator{}; ++i) {

    // access path() through the iterators operator->
    tempString = myIterator->path().generic_string();
    ifstream tempFile(tempString);

    if(!tempFile.is_open()) {
        cout << "Looking at file: " << i << "; failed to open." << endl << endl;
        cin.get();
        return 0;
    }
    {
        std::cout << tempString << " opened\n";
    }

    // tempFile.close(); // closes automatically when it goes out of scope

    // simpler form to use myIterator.operator++():
    ++myIterator;
}
</code>```

An even simpler approach would be to use a range-based for-loop:

```<code>for(const fs::directory_entry& dirent : fs::directory_iterator(address)) {
    const fs::path& path = dirent.path();
    ifstream tempFile(path);

    if(!tempFile) {
        cout << "Looking at file: " << path << "; failed to open.\n\n";
        cin.get();
        return 0;
    }
    std::cout << path << " opened\n";
}
</code>```

Body:
I'll cut the the short of it. I'm attempting to understand the filesystem library but there's very little information I've been able to find. I managed to get it to compile and understand the filesystem::path type variable really well but don't seem to understand how to get filesystem::directory_iterator to work properly. I'm not sure if I'm using it for a purpose it wasn't design for. So here is what I'm attempting to do:

I wanted to create a program that opens every text file within a specified folder. For this I need to obtain the folder name and path but I want the program to be able to obtain this information on itself and dynamically so if I add or remove textFiles it'll have the logic to function.

I'm able to create a directory_iterator variable that it manages to hold the first file with me just giving it the directory like this:

const char address[]{ "C:\\Users\\c-jr8\\ProgramBranch\\PersonalPlatform\\log extruder\\logs" };

fs::directory_iterator myIterator(address);

When testing the code in the folder I have four textFiles called "attempt 1" to "attempt 4". When reading the information on:

https://learn.microsoft.com/en-us/cpp/standard-library/directory-iterator-class?view=vs-2019#op_star

It mentions two functions to move the path object within the iterator to the next file. The first is increment(), which is the intendent method for iterating through the files, and operation++().

Now increment() hasn't been able to work for me cause it takes in a erro_code type variable and I haven't been able to find much information about how to implement this with the filesystem_errorcode variable or however it's meant to be used. The operation++() works beautifully and provides me with the path to every file but I was having issues with managing the code to detect when the operate++() functions leads to no other files. Once it iterates through every file it sorts of crashes when it keeps moving to the next. Here's that piece of code:

string tempString;
for (int i = 0; i < 5; i++) { //Here the limiting is 5 so it'll iterate onces more than the numbers of files unpurpose to see how it responses.
    tempString = myIterator.operator*().path().generic_string();
    ifstream tempFile(tempString);

    if (!tempFile.is_open()) {
        cout << "Looking at file: " << i + 1 << "; failed to open." << endl << endl;
        cin.get();
        return 0;
    }

    {
        //do things with file...
    }

    tempFile.close();
    myIterator.operator++();
}

What I want if to find a way to stop the for loop once it the iterator goes off the final file.

whichever information about how the filesystem library works it would be very much appreciated.

Body:
You should compare myIterator with a default constructed directory_iterator to check if the last file has been processed. You can also use a much simpler form to access the operators (shown in the code below):

string tempString;

// loop until myIterator == fs::directory_iterator{}
for(size_t i = 1; myIterator != fs::directory_iterator{}; ++i) {

    // access path() through the iterators operator->
    tempString = myIterator->path().generic_string();
    ifstream tempFile(tempString);

    if(!tempFile.is_open()) {
        cout << "Looking at file: " << i << "; failed to open." << endl << endl;
        cin.get();
        return 0;
    }
    {
        std::cout << tempString << " opened\n";
    }

    // tempFile.close(); // closes automatically when it goes out of scope

    // simpler form to use myIterator.operator++():
    ++myIterator;
}

An even simpler approach would be to use a range-based for-loop:

for(const fs::directory_entry& dirent : fs::directory_iterator(address)) {
    const fs::path& path = dirent.path();
    ifstream tempFile(path);

    if(!tempFile) {
        cout << "Looking at file: " << path << "; failed to open.\n\n";
        cin.get();
        return 0;
    }
    std::cout << path << " opened\n";
}


问:
Convert pandas column of type list to dict
Pandas column of length n is of type list.

```<code>df['size'][0] = [{'Name': 'Total', 'Value': 50, 'Unit': 'Units'}]

type(df['Size'][0])
list
</code>```

I'd like to convert the list to a dictionary. i.e type(df['Size'][0]) dict.

```<code>{'Name': 'Total',
 'Value': 50,
 'Unit': 'Units'}
</code>```

For context, I am trying to parse out the dictionary into multiple columns.

```<code>   # Unpack Size

   for i, row in df.iterrows():

       if type(row['Size'][i]) is dict:

           dict_obj = row['Size'][i]

           for key, val in dict_obj.items():

                if key == 'Name':
                   df.loc[index, 'Size_Name'] = val

                if key == 'Value':
                   df.loc[index, 'Size_Value'] = val

                if key == 'Unit':
                   df.loc[index, 'Size_Unit'] = val
</code>```

答:
If you have:

```<code>df['size'][0] = [{'Name': 'Total', 'Value': 50, 'Unit': 'Units'}]

type(df['Size'][0])
list
</code>```

you should use:

```<code>type(df['Size'][0][0])
dict
</code>```

And if you have several dictionaries in the list, increase the last index to get access to the rest of them.

Body:
Pandas column of length n is of type list.

df['size'][0] = [{'Name': 'Total', 'Value': 50, 'Unit': 'Units'}]

type(df['Size'][0])
list

I'd like to convert the list to a dictionary. i.e type(df['Size'][0]) dict.

{'Name': 'Total',
 'Value': 50,
 'Unit': 'Units'}

For context, I am trying to parse out the dictionary into multiple columns.

   # Unpack Size

   for i, row in df.iterrows():

       if type(row['Size'][i]) is dict:

           dict_obj = row['Size'][i]

           for key, val in dict_obj.items():

                if key == 'Name':
                   df.loc[index, 'Size_Name'] = val

                if key == 'Value':
                   df.loc[index, 'Size_Value'] = val

                if key == 'Unit':
                   df.loc[index, 'Size_Unit'] = val

Body:
If you have:

df['size'][0] = [{'Name': 'Total', 'Value': 50, 'Unit': 'Units'}]

type(df['Size'][0])
list

you should use:

type(df['Size'][0][0])
dict

And if you have several dictionaries in the list, increase the last index to get access to the rest of them.


问:
Java one liner to create a list of String, add contents of another List<String> and return a List
How to create a List of String then add all the contents of another List to it and then return that list??

Consider a function:

```<code>public List<String> foo() {
  return Arrays.asList("some", "list", "of", "strings", "from", "foo");
}
</code>```

A Class MyConstants:

```<code>public MyConstants {
  public static final String myConst = "String from Constant File";
}
</code>```

I am writing a function bar() and need a one liner to return a list:

```<code>public List<String> bar() {
    return new ArrayList<String>(Collections.singleTon(MyConstants.myConst)).addAll(foo());
}
</code>```

But addAll() returns boolean. Also, when I tried

```<code>Arrays.asList(return new ArrayList<String>(Collections.singleTon(MyConstants.myConst)).addAll(foo()));
</code>```

It is List<Boolean> for pretty obvious reasons.

How can I create a list, add another list to it and then return that combined list?

答:
Why on earth is there a constraint of one line?  Java collections are not great for fluent expressions. But you can abuse streams:

```<code>public List<String> bar() {
    return Stream.concat(Stream.of(MyConstants.myConst), foo().stream()).collect(toList());
}
</code>```

A less awful way is to use Guava libraries:

```<code>public List<String> bar() {
    return ImmutableList.<String>builder().add(MyConstants.myConst).addAll(foo()).build();
}
</code>```

Body:
How to create a List of String then add all the contents of another List to it and then return that list??

Consider a function:

public List<String> foo() {
  return Arrays.asList("some", "list", "of", "strings", "from", "foo");
}

A Class MyConstants:

public MyConstants {
  public static final String myConst = "String from Constant File";
}

I am writing a function bar() and need a one liner to return a list:

public List<String> bar() {
    return new ArrayList<String>(Collections.singleTon(MyConstants.myConst)).addAll(foo());
}

But addAll() returns boolean. Also, when I tried

Arrays.asList(return new ArrayList<String>(Collections.singleTon(MyConstants.myConst)).addAll(foo()));

It is List<Boolean> for pretty obvious reasons.

How can I create a list, add another list to it and then return that combined list?

Body:
Why on earth is there a constraint of one line?  Java collections are not great for fluent expressions. But you can abuse streams:

public List<String> bar() {
    return Stream.concat(Stream.of(MyConstants.myConst), foo().stream()).collect(toList());
}

A less awful way is to use Guava libraries:

public List<String> bar() {
    return ImmutableList.<String>builder().add(MyConstants.myConst).addAll(foo()).build();
}


问:
How can I track each "step" of a program in PHP?
For example, in my error_log, it says something like:

```<code>Error... require, include, a_function, another_function
</code>```

Basically it tracks each step of the program. I want to implement something like this for debugging purposes. How do I "track" the execution of the program in PHP?

答: You need debug_backtrace() and custom error handler</p>

Body:
For example, in my error_log, it says something like:

Error... require, include, a_function, another_function

Basically it tracks each step of the program. I want to implement something like this for debugging purposes. How do I "track" the execution of the program in PHP?


问:
how to use re.sub in python to remove a character by it's unicode
for example i want to do

```<code>new_data = t = re.sub('[ufd3e]'),' ',new_data)
</code>```

to replace the character uf3ef but it doesn't work

答:
you need to use \u to tell it it is unicode  (and you had a closing parenthesis in the wrong place)

```<code>new_data = t = re.sub(u'[\ufd3e]',' ',new_data)
</code>```

Body:
for example i want to do

new_data = t = re.sub('[ufd3e]'),' ',new_data)

to replace the character uf3ef but it doesn't work

Body:
you need to use \u to tell it it is unicode  (and you had a closing parenthesis in the wrong place)

new_data = t = re.sub(u'[\ufd3e]',' ',new_data)


问:
Role inheritance with shared groups
A self-hosted GitLab Instance (Community Edition 12.10.8) is considered.
Let's assume the following Group setup:

Group

Subgroup 1

Subgroup 1.1 (Admins)

Subgroup 1.2

Project A

Now, The Subgroup 1.1 is invited to Subgroup 1 with the role Owner.
The idea is that the user members in Subgroup 1.1 act as administrators for the Subgroup 1 and all further subgroups.

With this setup, the users from Subgroup 1.1 ("Admins") can access e.g the Subgroup 1.2 and its Project A. This was not the case before the group was added, i.e. the user have become members! However, I observe that:

The added users or the added group does not show up in the members list of Subgroup 1.2.

Even though the "Admins" should now be Owner of Subgroup 1.2 and Project A due to inheritance, they cannot delete Project A.

If I alternatively add a user as Owner to the Subgroup 1, he shows up as owner in Subgroup 1.2 and he can delete Project A.

Why does it make a difference if a user is directly added or added via a group?

In the Documentation it says:

Similarly to sharing a project with a group, you can share a group with another group to give direct group members access to the shared
  group. This is not valid for inherited members.

To share a given group, for example, ‘Frontend’ with another group,
  for example, ‘Engineering’:

Navigate to your ‘Frontend’ group page and use the left navigation menu to go to your group Members.

Select the Invite group tab.

Add ‘Engineering’ with the maximum access level of your choice.

Click Invite.

All the members of the ‘Engineering’ group will have been added to
  ‘Frontend’.

To me, this sounds like the added group members have identical function as directly added users.
Only the sentence "This is not valid for inherited members." might be the explanation, but I think I need further explanation on this.

Has anybody understood the logic behind this?
Thank you in advance for your help!

答:
After browsing the GitLab issues,  I come to the conclusion that both mentioned problems are (known) bugs and are discussed in issues at GitLab:

https://gitlab.com/gitlab-org/gitlab/-/issues/213546

https://gitlab.com/gitlab-org/gitlab/-/issues/219230

I guess this is as good as we come right now . Hopefully, both issues are solved soon.

Title: Role inheritance with shared groups


答:
there can be n number of dictionaries.

When you have arbitary number of dictionaries in list use df.explode

```<code>df = pd.DataFrame({'size':[[{'a':1},{'b':1}],[{'a':2}],[{'c':2},{'d':2},{'e':4}]]})

df
                             size
0            [{'a': 1}, {'b': 1}]
1                      [{'a': 2}]
2  [{'c': 2}, {'d': 2}, {'e': 4}]

df.explode('size')

       size
0  {'a': 1}
0  {'b': 1}
1  {'a': 2}
2  {'c': 2}
2  {'d': 2}
2  {'e': 4}
</code>```

If it's always list of one dictionary i.e df['size'][x] = [{...}] use itertools.chain.from_iterable

```<code>from itertools import chain

df['size'] = list(chain.from_iterable(df['size']))
</code>```

Title: Convert pandas column of type list to dict

Body:
there can be n number of dictionaries.

When you have arbitary number of dictionaries in list use df.explode

df = pd.DataFrame({'size':[[{'a':1},{'b':1}],[{'a':2}],[{'c':2},{'d':2},{'e':4}]]})

df
                             size
0            [{'a': 1}, {'b': 1}]
1                      [{'a': 2}]
2  [{'c': 2}, {'d': 2}, {'e': 4}]

df.explode('size')

       size
0  {'a': 1}
0  {'b': 1}
1  {'a': 2}
2  {'c': 2}
2  {'d': 2}
2  {'e': 4}

If it's always list of one dictionary i.e df['size'][x] = [{...}] use itertools.chain.from_iterable

from itertools import chain

df['size'] = list(chain.from_iterable(df['size']))


问:
Javers giving Duplicate key name 'jv_global_id_owner_id_fk_idx' when starting from Spring Boot with mySQL
I'm trying to integrate Javers 5.9.0 with my Spring Boot 2.1.13 application with mySQL.

As soon I run my application I'm getting

java.lang.RuntimeException: java.sql.SQLSyntaxErrorException:
  Duplicate key name 'jv_global_id_owner_id_fk_idx'

Please find the full error stack

org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'JaversFromStarter' defined in class path
  resource
  [org/javers/spring/boot/sql/JaversSqlAutoConfiguration.class]:
  Invocation of init method failed; nested exception is
  java.lang.RuntimeException: java.sql.SQLSyntaxErrorException:
  Duplicate key name 'jv_global_id_owner_id_fk_idx'     at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1771)
  ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]     at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593)
  ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]     at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
  ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]     at
  org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
  ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]     at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
  ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]     at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
  ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]     at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
  ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]     at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:847)
  ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]     at
  org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
  ~[spring-context-5.1.14.RELEASE.jar:5.1.14.RELEASE]   at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
  ~[spring-context-5.1.14.RELEASE.jar:5.1.14.RELEASE]   at
  org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
  ~[spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE]  at
  org.springframework.boot.SpringApplication.refresh(SpringApplication.java:744)
  [spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE]   at
  org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:391)
  [spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE]   at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:312)
  [spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE]   at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)
  [spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE]   at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1204)
  [spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE]   at
  [classes/:na] Caused by: java.lang.RuntimeException:
  java.sql.SQLSyntaxErrorException: Duplicate key name
  'jv_global_id_owner_id_fk_idx'    at
  org.javers.repository.sql.schema.JaversSchemaManager.executeSQL(JaversSchemaManager.java:165)
  ~[javers-persistence-sql-5.9.0.jar:na]    at
  org.javers.repository.sql.schema.JaversSchemaManager.addIndex(JaversSchemaManager.java:343)
  ~[javers-persistence-sql-5.9.0.jar:na]    at
  org.javers.repository.sql.schema.JaversSchemaManager.addDbIndexOnOwnerId(JaversSchemaManager.java:102)
  ~[javers-persistence-sql-5.9.0.jar:na]    at
  org.javers.repository.sql.schema.JaversSchemaManager.ensureSchema(JaversSchemaManager.java:61)
  ~[javers-persistence-sql-5.9.0.jar:na]    at
  org.javers.repository.sql.JaversSqlRepository.ensureSchema(JaversSqlRepository.java:186)
  ~[javers-persistence-sql-5.9.0.jar:na]    at
  org.javers.spring.jpa.JaversTransactionalDecorator$1.doInTransactionWithoutResult(JaversTransactionalDecorator.java:186)
  ~[javers-spring-jpa-5.9.0.jar:na]     at
  org.springframework.transaction.support.TransactionCallbackWithoutResult.doInTransaction(TransactionCallbackWithoutResult.java:36)
  ~[spring-tx-5.1.14.RELEASE.jar:5.1.14.RELEASE]    at
  org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140)
  ~[spring-tx-5.1.14.RELEASE.jar:5.1.14.RELEASE]    at
  org.javers.spring.jpa.JaversTransactionalDecorator.ensureSchema(JaversTransactionalDecorator.java:183)
  ~[javers-spring-jpa-5.9.0.jar:na]     at
  org.javers.spring.jpa.JaversTransactionalDecorator.afterPropertiesSet(JaversTransactionalDecorator.java:177)
  ~[javers-spring-jpa-5.9.0.jar:na]     at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1830)
  ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]     at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1767)
  ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]     ... 16 common
  frames omitted Caused by: java.sql.SQLSyntaxErrorException: Duplicate
  key name 'jv_global_id_owner_id_fk_idx'   at
  com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
  ~[mysql-connector-java-8.0.19.jar:8.0.19]     at
  com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
  ~[mysql-connector-java-8.0.19.jar:8.0.19]     at
  com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
  ~[mysql-connector-java-8.0.19.jar:8.0.19]     at
  com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:764)
  ~[mysql-connector-java-8.0.19.jar:8.0.19]     at
  com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:648)
  ~[mysql-connector-java-8.0.19.jar:8.0.19]     at
  com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:95)
  ~[HikariCP-3.2.0.jar:na]  at
  com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java)
  ~[HikariCP-3.2.0.jar:na]  at
  org.javers.repository.sql.schema.JaversSchemaManager.executeSQL(JaversSchemaManager.java:160)
  ~[javers-persistence-sql-5.9.0.jar:na]    ... 27 common frames omitted

答: Try to reproduce the issue int this test https://github.com/javers/javers/blob/master/javers-persistence-sql/src/test/groovy/org/javers/repository/sql/integration/docker/MySqlDockerIntegrationTest.groovy Then we will fix it</p>


问:
Align 1 child left, the rest right in a div
Trying to align the 3 icons to the right while keeping the title positioned to the left:

Can't seem to get it to work.
Justify-self: flex-end produced no result.
Margin-right: auto produced this:

CODE:

```<code>    <div className="nav-header-container">
      <span className="nav-header">TITLE</span>
      <img
        className="nav-header-icon"
        src="http://localhost:8000/static/frontend/icons/bell.svg/"
      />
      <img
        className="nav-header-icon"
        src="http://localhost:8000/static/frontend/icons/chat.svg/"
      />
      <img
        className="nav-header-icon"
        src="http://localhost:8000/static/frontend/icons/settings.svg/"
      />
    </div>
</code>```

CSS:

```<code>.nav-header-container {
  display: flex;
  align-items: center;

  min-height: 4.26vh;
  width: 100%;

  padding-left: 1em;

  background-color: #435665;
}

.nav-header {
  font-family: open-sans, sans-serif;
  font-size: 20px;
  color: white;
}

.nav-header-icon {
  height: 20px;

  /* justify-self: flex-end; */
  margin-left: auto;
}
</code>```

答:
You can add a div between title and icons (with class spacer on my example):

```<code><div className="nav-header-container">
  <span className="nav-header">TITLE</span>
  <div className="spacer"></div>
  <img className="nav-header-icon" src="http://localhost:8000/static/frontend/icons/bell.svg/" />
  <img className="nav-header-icon" src="http://localhost:8000/static/frontend/icons/chat.svg/" />
  <img className="nav-header-icon" src="http://localhost:8000/static/frontend/icons/settings.svg/" />
</div>
</code>```

And set it flex:1 on your css rule:

```<code>.spacer{
   flex: 1
}
</code>```

Body:
Trying to align the 3 icons to the right while keeping the title positioned to the left:

Can't seem to get it to work.
Justify-self: flex-end produced no result.
Margin-right: auto produced this:

CODE:

      TITLE

CSS:

.nav-header-container {
  display: flex;
  align-items: center;

  min-height: 4.26vh;
  width: 100%;

  padding-left: 1em;

  background-color: #435665;
}

.nav-header {
  font-family: open-sans, sans-serif;
  font-size: 20px;
  color: white;
}

.nav-header-icon {
  height: 20px;

  /* justify-self: flex-end; */
  margin-left: auto;
}

Body:
You can add a div between title and icons (with class spacer on my example):

<div className="nav-header-container">
  <span className="nav-header">TITLE</span>
  <div className="spacer"></div>
  <img className="nav-header-icon" src="http://localhost:8000/static/frontend/icons/bell.svg/" />
  <img className="nav-header-icon" src="http://localhost:8000/static/frontend/icons/chat.svg/" />
  <img className="nav-header-icon" src="http://localhost:8000/static/frontend/icons/settings.svg/" />
</div>

And set it flex:1 on your css rule:

.spacer{
   flex: 1
}