问:
Problem with loading a json file for geo_data in python
I am currently trying to use folium library in python to create webmaps. I have a file world.json which contains geo_data. I have provided a link to the file at the end of this post. I tried the following code:

data = [json.loads(line) for line in open('world.json', 'r')]
```

<p>and received the following error:</p>

```Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
  File "C:\Users\name\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Users\name\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\name\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
```

How can I load this file?

What I want to achieve is essentially obtain the population data and create a Choropleth and overlay it on my webmap.

Edit: Forgot the link:

https://1drv.ms/u/s!Army95vqcKXpaooVAZU_g-VCAVw?e=vwTknq

Edit: Previous link to skydrive stopped working due to "high traffic". Below is link to dropbox, hopefully this works:

https://www.dropbox.com/s/gmm8db0g03rc7cv/world.json?dl=0

答:
Good news/bad news:
It turns out that this file was encoded in a locale that we are not accustomed to, and json/ascii cannot make sense of some of the character encoding.  I tried this, and it seems to be working for me -- with a major caveat:

```<code>with open("world.json", "r") as fh:
    contents = fh.read()
asciiContents = contents.encode("ascii", errors="ignore")
data = json.loads(asciiContents)
</code>```

The major caveat is that only 3 countries come through with no encoding errors:

```<code>>>> len(data["features"])
3
</code>```

Maybe there another source for this data that is closer to a native english locale, or maybe someone else can provide wisdom in encoding foreign data in a more friendly way...

Body:
I am currently trying to use folium library in python to create webmaps. I have a file world.json which contains geo_data. I have provided a link to the file at the end of this post. I tried the following code:

data = [json.loads(line) for line in open('world.json', 'r')]

and received the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
  File "C:\Users\name\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Users\name\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\name\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

How can I load this file?

What I want to achieve is essentially obtain the population data and create a Choropleth and overlay it on my webmap.

Edit: Forgot the link:

https://1drv.ms/u/s!Army95vqcKXpaooVAZU_g-VCAVw?e=vwTknq

Edit: Previous link to skydrive stopped working due to "high traffic". Below is link to dropbox, hopefully this works:

https://www.dropbox.com/s/gmm8db0g03rc7cv/world.json?dl=0

Body:
Good news/bad news:
It turns out that this file was encoded in a locale that we are not accustomed to, and json/ascii cannot make sense of some of the character encoding.  I tried this, and it seems to be working for me -- with a major caveat:

with open("world.json", "r") as fh:
    contents = fh.read()
asciiContents = contents.encode("ascii", errors="ignore")
data = json.loads(asciiContents)

The major caveat is that only 3 countries come through with no encoding errors:

>>> len(data["features"])
3

Maybe there another source for this data that is closer to a native english locale, or maybe someone else can provide wisdom in encoding foreign data in a more friendly way...


来源: stackexchange

问:
How to implement a python script in a Django web app using parameters from a view
My question about implementing a script into a view in a django web app.

I have a .py script that I want to run inside this django web app using the user-supplied data, the configfile, the modelfile and the choice as command line arguments. The output is then a list with different scores which will then be displayed inside the html (not the part I need help with yet).

So I have 2 forms, one that uploads a ML model and another one (the one I need help with) that uses user-supplied data to run a uploaded model:

```<code>    class Meta:
        model = MlModel
        fields = [
            'modelname',
            'configfile',
            'modelfile',
            'choice',
        ]

class TestForm(forms.Form):
    testdata = forms.FileField()
    model = forms.ModelChoiceField(queryset=MlModel.objects.all())
</code>```

My views are as follow, where the test view is where the testing happens:

```<code>    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)

        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/mltesting/')
    else:
        form = UploadForm()
    context = {'form':form}
    return render(request,'mltesting/upload.html', context=context)
def test_model(request):
    submitbutton = request.POST.get("submit")
    testdata = ''
    modfile = ''
    confile = ''
    choice = ''
    form = TestForm(request.POST, request.FILES)
    if form.is_valid():
        testdata = request.FILES['testdata']
        model = form.cleaned_data.get('model')
        model = MlModel.objects.get(modelname=model)
        modfile = model.modelfile.path
        confile = model.configfile.path
        choice = model.choice
    else:
        form = TestForm()
    context = {'form': form, 'testdata': testdata, 'submitbutton': submitbutton, 'modelfile':modfile, 'configfile': confile,'choice': choice}
    return render(request,'mltesting/test.html', context=context)
</code>```

And this is the HTML template where the output of the testing is supposed to be:

```<code>
{% block content %}
<p>Compound Protein Interaction Tool</p>

<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_table }}
<input type="Submit" name="submit" value="Submit"/>
</form>

{% if submitbutton == "Submit" %}
{% endif %}
{% endblock %}
</code>```

I am fairly new to Django in general so I apologise for the (probable) bad formulation of my question, but all help is greatly appreciated.

答:
You can follow the answer from this solution

Make a folder in the same directory, add the py file there and then import the module you want in the view.py.

call the function as you would call any custom module.

** EDIT **
Call the script as stated in this answer

```<code>def test_model(request):

    if form.is_valid():
        testdata = request.FILES['testdata']
        model = form.cleaned_data.get('model')
        model = MlModel.objects.get(modelname=model)
        modfile = model.modelfile.path
        confile = model.configfile.path
        choice = model.choice
    else:
        form = TestForm()

    #########################################
    ###########Here you run your script
    ###########Any variable from the script will be loaded here
    exec(open("./path/toYour/script.py").read(), globals())

    #Add the information you want from the script to the context
    context = {'someVariableFromTheScript':someVariableFromTheScript, 'form': form, 'testdata': testdata, 'submitbutton': submitbutton, 'modelfile':modfile, 'configfile': confile,'choice': choice}
    return render(request,'mltesting/test.html', context=context)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My question about implementing a script into a view in a django web app.

I have a .py script that I want to run inside this django web app using the user-supplied data, the configfile, the modelfile and the choice as command line arguments. The output is then a list with different scores which will then be displayed inside the html (not the part I need help with yet).

So I have 2 forms, one that uploads a ML model and another one (the one I need help with) that uses user-supplied data to run a uploaded model:

    class Meta:
        model = MlModel
        fields = [
            'modelname',
            'configfile',
            'modelfile',
            'choice',
        ]

class TestForm(forms.Form):
    testdata = forms.FileField()
    model = forms.ModelChoiceField(queryset=MlModel.objects.all())

My views are as follow, where the test view is where the testing happens:

    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)

        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/mltesting/')
    else:
        form = UploadForm()
    context = {'form':form}
    return render(request,'mltesting/upload.html', context=context)
def test_model(request):
    submitbutton = request.POST.get("submit")
    testdata = ''
    modfile = ''
    confile = ''
    choice = ''
    form = TestForm(request.POST, request.FILES)
    if form.is_valid():
        testdata = request.FILES['testdata']
        model = form.cleaned_data.get('model')
        model = MlModel.objects.get(modelname=model)
        modfile = model.modelfile.path
        confile = model.configfile.path
        choice = model.choice
    else:
        form = TestForm()
    context = {'form': form, 'testdata': testdata, 'submitbutton': submitbutton, 'modelfile':modfile, 'configfile': confile,'choice': choice}
    return render(request,'mltesting/test.html', context=context)

And this is the HTML template where the output of the testing is supposed to be:

{% block content %}

Compound Protein Interaction Tool

<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_table }}
<input type="Submit" name="submit" value="Submit"/>
</form>

{% if submitbutton == "Submit" %}
{% endif %}
{% endblock %}

I am fairly new to Django in general so I apologise for the (probable) bad formulation of my question, but all help is greatly appreciated.

Body:
You can follow the answer from this solution

Make a folder in the same directory, add the py file there and then import the module you want in the view.py.

call the function as you would call any custom module.

** EDIT **
Call the script as stated in this answer

def test_model(request):

    if form.is_valid():
        testdata = request.FILES['testdata']
        model = form.cleaned_data.get('model')
        model = MlModel.objects.get(modelname=model)
        modfile = model.modelfile.path
        confile = model.configfile.path
        choice = model.choice
    else:
        form = TestForm()

    #########################################
    ###########Here you run your script
    ###########Any variable from the script will be loaded here
    exec(open("./path/toYour/script.py").read(), globals())

    #Add the information you want from the script to the context
    context = {'someVariableFromTheScript':someVariableFromTheScript, 'form': form, 'testdata': testdata, 'submitbutton': submitbutton, 'modelfile':modfile, 'configfile': confile,'choice': choice}
    return render(request,'mltesting/test.html', context=context)


问:
how to force sleep or any other type of timer to execute at particular time in c++?
I am doing socket programming in C and I want to do the following thing:

```<code>pid = fork();
if(pid == 0){
    //child process
    for(int m=0;m<2;m++){
        j=0;
        for(i=0;i<len_neighbors;i++){
            socket_des1[i] = get_socket_connection_client(hostname1, neighbor_socket[i],(char *) "udp");
            //sending data to other routers
            cout<<"\nMessage: Sending routing table to neighbor, "<<neighbors[i];
            if (send(socket_des1[i], &message1[0], message1.length(), 0) < 0){
                perror("\nError:Message sending failed\n");
                exit(1);
            }
            j++;
        }
        for(i=0;i<len_neighbors;i++){
            close(socket_des1[i]);
        }
        sleep(30);
        cout<<"Hello";
    }
}else{
    // code for parent process
}
</code>```

So basically the process will send data to all the neighbors and the goto sleep. What is happening here is the process sends data to first neighbor and then sleeps for 30secs. How do I force the process to finish sending and then execute sleep(30) statement.

I am using forking for the process. And the code above is part of child process.

答:
You are printing messages to buffered standard output stream. Maybe your messages are in the buffer untill you print \n after 30 s delay?
Try to use cerr instead of cout. Or do flush.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am doing socket programming in C and I want to do the following thing:

pid = fork();
if(pid == 0){
    //child process
    for(int m=0;m<2;m++){
        j=0;
        for(i=0;i<len_neighbors;i++){
            socket_des1[i] = get_socket_connection_client(hostname1, neighbor_socket[i],(char *) "udp");
            //sending data to other routers
            cout<<"\nMessage: Sending routing table to neighbor, "<<neighbors[i];
            if (send(socket_des1[i], &message1[0], message1.length(), 0) < 0){
                perror("\nError:Message sending failed\n");
                exit(1);
            }
            j++;
        }
        for(i=0;i<len_neighbors;i++){
            close(socket_des1[i]);
        }
        sleep(30);
        cout<<"Hello";
    }
}else{
    // code for parent process
}

So basically the process will send data to all the neighbors and the goto sleep. What is happening here is the process sends data to first neighbor and then sleeps for 30secs. How do I force the process to finish sending and then execute sleep(30) statement.

I am using forking for the process. And the code above is part of child process.


问:
Sub menu in side menu
I did a menu in the left side of the screen that it's rotated but when I try to add a sub menu it appears in the top side of the menu and not in the bottom could someone help me?

ul li{
 display:inline;
 padding: 0.4vw 0.7vw;
}
nav {
  grid-area: menu;
  font-family: Karla;
  display: block;
  writing-mode: vertical-lr;
  transform: rotate(-180deg);
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
}

.dropdown:hover .dropdown-content {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <ul>
    <li>Home</li>
    <li>Sobre</li>
    <div class="dropdown">
      <li>Portfólio</li>
      <div class="dropdown-content">
        <li> Link1</li>
      </div>
    </div>
    <li>Website</li>
  </ul>
</nav></code>```

答:
Check this

 the top side of the menu and not in the bottom could someone help me?

ul li{
 display:inline;
 padding: 0.4vw 0.7vw;
}
nav {
  grid-area: menu;
  font-family: Karla;
  display: block;
  writing-mode: vertical-lr;
  transform: rotate(-180deg);
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: relative;
}

.dropdown:hover .dropdown-content {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <ul>
    <li>Home</li>
    <li>Sobre</li>
    <div class="dropdown">
      <div class="dropdown-content">
        <li> Link1</li>
      </div>
      <li>Portfólio      </li>
    </div>
    <li>Website</li>
  </ul>
</nav></code>```

Title: Sub menu in side menu

Body:
I did a menu in the left side of the screen that it's rotated but when I try to add a sub menu it appears in the top side of the menu and not in the bottom could someone help me?

ul li{
 display:inline;
 padding: 0.4vw 0.7vw;
}
nav {
  grid-area: menu;
  font-family: Karla;
  display: block;
  writing-mode: vertical-lr;
  transform: rotate(-180deg);
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
}

.dropdown:hover .dropdown-content {
  display: block;
}

Home

Sobre

Portfólio

 Link1

Website

Body:
Check this

 the top side of the menu and not in the bottom could someone help me?

ul li{
 display:inline;
 padding: 0.4vw 0.7vw;
}
nav {
  grid-area: menu;
  font-family: Karla;
  display: block;
  writing-mode: vertical-lr;
  transform: rotate(-180deg);
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: relative;
}

.dropdown:hover .dropdown-content {
  display: block;
}

<nav>
  <ul>
    <li><a href="index.html">Home</a></li>
    <li><a href="sobre.html">Sobre</a></li>
    <div class="dropdown">
      <div class="dropdown-content">
        <li><a href="#"> Link1</a></li>
      </div>
      <li><a href="portfolio.html">Portfólio</a>      </li>
    </div>
    <li><a href="website.html">Website</a></li>
  </ul>
</nav>


问:
This app could not be installed at this time Xcode 11
I know there are lot of similar questions But I have similar problem like This But there is no solution provided it that question.

I have tried other questions' solution like:

1) Deleted Drive data

2) Erased contents from simulator

3) Restart simulator and Xcode

4) Deleted existing project and created new project

5) I have not included any pods

6) Its just a new project fresh I didn't code anything yet.

But still getting same alert : "This app coul not be installed at this time"

I am using macOS Catalina 10.15 beta and Xcode 11

I am getting this error

Details of error is explained in pic

答: If you have multiple user accounts on your Mac, log them all off I sometimes get a similar error when they are all logged on my Mac</p>


问:
Markdown in JS without enclosing
?
How can I convert a piece of markdown text to HTML using any JS library like markdown-js or marked without enclosing it in paragraph tag?

For example I like to convert this *italic* text to this italic text without enclosing it in

.

Edit:

- My question is not how to remove p tags from output after conversion, my question is how to ask the library not to enclose output in p tags.

- markdown-js and marked enclose output inside

 by default.

答:
Here's what worked for me (many years later). It assumes that you know what elements you don't want to wrap in paragraph tags.

const marked = require("marked");

// Every new line in markdown is considered a new paragraph, this prevents
// img tags from being wrapped in
 tags which is helpful for resizing img's,
// centering captions, etc.
marked.Renderer.prototype.paragraph = (text) => {
  if (text.startsWith("<img")) {
    return text + "\n";
  }
  return "
" + text + "
";
};

html = marked(markdownFile.body)
```

Title: Markdown in JS without enclosing <p>?

Body:
Here's what worked for me (many years later). It assumes that you know what elements you don't want to wrap in paragraph tags.

const marked = require("marked");

// Every new line in markdown is considered a new paragraph, this prevents
// img tags from being wrapped in <p> tags which is helpful for resizing img's,
// centering captions, etc.
marked.Renderer.prototype.paragraph = (text) => {
  if (text.startsWith("<img")) {
    return text + "\n";
  }
  return "<p>" + text + "</p>";
};

html = marked(markdownFile.body)


问:
Calcute mean for same time on different dates
I have data that shows a numeric amount of something measured at a few seconds after every minute of every day over a period of several days. Here is an example for two minutes on three days:

```<code>dat <- read.table(textConnection('
date_and_time amount
"2020-05-01 13:23:02" 8
"2020-05-01 13:24:06" 26
"2020-05-02 13:23:01" 5
"2020-05-02 13:24:01" 30
"2020-05-03 13:23:03" 6
"2020-05-03 13:24:02" 27
'), header = TRUE, colClasses=c("POSIXct", "numeric"))
</code>```

For that data, I want to calculate the mean amount for each minute over all days. For the above sample data, the result would look like this:

```<code>time_of_day mean_amount
13:23:00 6.333333
13:24:00 27.66667
</code>```

To get that result, I have converted the datetime objects to character strings, stripped the dates and the seconds from the strings, converted the strings to a factor, and calculated the means for each factor.

Is there a way to achieve that result with the datetime objects? That is, is there a function to calculate means over the same time of different dates?

答:
in Base-R

```<code>sapply(split(dat$amount,format(dat$date_and_time, format='%H:%M')), mean)

    13:23     13:24
 6.333333 27.666667
</code>```

I used the format function to strip the days and seconds. You could use other ways of calculating the mean from that as well.

Body:
I have data that shows a numeric amount of something measured at a few seconds after every minute of every day over a period of several days. Here is an example for two minutes on three days:

dat <- read.table(textConnection('
date_and_time amount
"2020-05-01 13:23:02" 8
"2020-05-01 13:24:06" 26
"2020-05-02 13:23:01" 5
"2020-05-02 13:24:01" 30
"2020-05-03 13:23:03" 6
"2020-05-03 13:24:02" 27
'), header = TRUE, colClasses=c("POSIXct", "numeric"))

For that data, I want to calculate the mean amount for each minute over all days. For the above sample data, the result would look like this:

time_of_day mean_amount
13:23:00 6.333333
13:24:00 27.66667

To get that result, I have converted the datetime objects to character strings, stripped the dates and the seconds from the strings, converted the strings to a factor, and calculated the means for each factor.

Is there a way to achieve that result with the datetime objects? That is, is there a function to calculate means over the same time of different dates?

Body:
in Base-R

sapply(split(dat$amount,format(dat$date_and_time, format='%H:%M')), mean)

    13:23     13:24
 6.333333 27.666667

I used the format function to strip the days and seconds. You could use other ways of calculating the mean from that as well.


问:
ModuleNotFoundError when importing from a ROS package
I have use a robot simulator which only works on ROS Indigo. I also have to use Tensorflow and Jupyter Notebook so I have created a virtual environment with Python3.6.

I want to import a file from the simulator package in a notebook. So after I source bin/activate for the virtualenv, I source devel/setup.bash from my catkin workspace. But even after doing this I get the following error

```<code>ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-8-8370e76446ee> in <module>
----> 1 import herbpy

~/my_workspace/devel/lib/python2.7/dist-packages/herbpy/__init__.py in <module>
     33 for __execfile in __execfiles:
     34     with open(__execfile, 'r') as __fh:
---> 35         exec(__fh.read())
     36     del __fh
     37     del __execfile

~/my_workspace/devel/lib/python2.7/dist-packages/herbpy/__init__.py in <module>

ModuleNotFoundError: No module named 'herb'
</code>```

I tried running a python file importing this module (while in the environment). It only ran with python2. But with python2, I can't use Tensorflow.

How do I import this file in my notebook?

答:
There's a few things. Remember that you can specify the version of python to run via the shebang in your script:

```<code>#!/usr/bin/env python  # For "both" versions, not recommended for ros
#!/usr/bin/env python2 # For ros, to access the python/pip packages only installed for py2
#!/usr/bin/env python3 # For python3 code, to avoid that 'python' usually selects py2
</code>```

You can call different python executables from launch files this way:

```<code><?xml version="1.0"?>
<launch>
  <!-- py3_ex.launch -->
    <node name="call_py3" pkg="my_new_pkg" type="call_py3.py" output="screen">
    </node>
</launch>
</code>```

```<code>#!/usr/bin/env python3
# call_py3.py
# Try to print out the python version
import sys
import platform
#import rospy

#rospy.init_node("call_py3");
print("\n\nPython Version:\n")
print(sys.version)
print(platform.python_version())
print("\n\n")
#rospy.spin()
</code>```

The above script will run python3 code (printing the version number), including tensorflow. The issue is that it, on trying to import rospy on py3 instead of py2, it won't find some of it's dependencies (such as rospkg) and give a fatal error.

To get around this, (assuming you don't switch to Ubuntu 20 + ROS Noetic, with native py3 support, or just use py2), you can call py3 scripts from your py2 ros node, such as with subprocess and piping. Or better yet, socket udp send over localhost your data/images/results/inputs, that might be the simplest way. To go this way, (and it works!) make a import socket udp connection to a localhost (127.0.0.1) random port (ex 5050), on both sides. Launch both scripts. Your py3 script can't import rospy but it can import ros msgs: from sensor_msgs.msg import Image. You can find a means to serialize it (there's multiple ways to turn a py obj into string and back).

A more painful way to setup python3 (but should be easier to use after) is to somehow replace the python2 packages to use ros with python3. There are a bunch of guides out there, and plenty of people who've ran into issues posted on SO.

Body:
I have use a robot simulator which only works on ROS Indigo. I also have to use Tensorflow and Jupyter Notebook so I have created a virtual environment with Python3.6.

I want to import a file from the simulator package in a notebook. So after I source bin/activate for the virtualenv, I source devel/setup.bash from my catkin workspace. But even after doing this I get the following error

ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-8-8370e76446ee> in <module>
----> 1 import herbpy

~/my_workspace/devel/lib/python2.7/dist-packages/herbpy/__init__.py in <module>
     33 for __execfile in __execfiles:
     34     with open(__execfile, 'r') as __fh:
---> 35         exec(__fh.read())
     36     del __fh
     37     del __execfile

~/my_workspace/devel/lib/python2.7/dist-packages/herbpy/__init__.py in <module>

ModuleNotFoundError: No module named 'herb'

I tried running a python file importing this module (while in the environment). It only ran with python2. But with python2, I can't use Tensorflow.

How do I import this file in my notebook?

Body:
There's a few things. Remember that you can specify the version of python to run via the shebang in your script:

#!/usr/bin/env python  # For "both" versions, not recommended for ros
#!/usr/bin/env python2 # For ros, to access the python/pip packages only installed for py2
#!/usr/bin/env python3 # For python3 code, to avoid that 'python' usually selects py2

You can call different python executables from launch files this way:

<?xml version="1.0"?>
<launch>
  <!-- py3_ex.launch -->
    <node name="call_py3" pkg="my_new_pkg" type="call_py3.py" output="screen">
    </node>
</launch>

#!/usr/bin/env python3
# call_py3.py
# Try to print out the python version
import sys
import platform
#import rospy

#rospy.init_node("call_py3");
print("\n\nPython Version:\n")
print(sys.version)
print(platform.python_version())
print("\n\n")
#rospy.spin()

The above script will run python3 code (printing the version number), including tensorflow. The issue is that it, on trying to import rospy on py3 instead of py2, it won't find some of it's dependencies (such as rospkg) and give a fatal error.

To get around this, (assuming you don't switch to Ubuntu 20 + ROS Noetic, with native py3 support, or just use py2), you can call py3 scripts from your py2 ros node, such as with subprocess and piping. Or better yet, socket udp send over localhost your data/images/results/inputs, that might be the simplest way. To go this way, (and it works!) make a import socket udp connection to a localhost (127.0.0.1) random port (ex 5050), on both sides. Launch both scripts. Your py3 script can't import rospy but it can import ros msgs: from sensor_msgs.msg import Image. You can find a means to serialize it (there's multiple ways to turn a py obj into string and back).

A more painful way to setup python3 (but should be easier to use after) is to somehow replace the python2 packages to use ros with python3. There are a bunch of guides out there, and plenty of people who've ran into issues posted on SO.


问:
Vuex: Add Dynamic Property to Object without triggering Watchers on existing Properties
I have a Vuex store with an object:

```<code> state: {
    contents: {},
 }
</code>```

where I dynamically store contents by key:

```<code>mutations: {
   updateContent: (state, { id, a, b }) => {
       Vue.set(state.contents, id, { a, b });
   },
}
</code>```

and get them using:

```<code>getters: {
    content: (state) => (id) => {
        if (id in state.contents) return state.contents[id];
        return [];
    }
},
</code>```

Let's say I have a component like this:

```<code>export default {
    props: ["id"],
    computed: {
       myContent() {
          return this.$store.getters.content(this.id)
       }
    },
    // ...
}
</code>```

How can I add dynamic properties using the mutation without triggering changes in components watching unchanged, already existant properties of state.contents?

Also see this fiddle.

答:
It seems like Vue(x) can't do this out-of-the-box. But by adding an empty Observer (yes, this is a hack) you can make Vue-components temporarily nonreactive (based on this blogpost).

Basically - we have an Observer on the object itself and an Observer on each of the properties. We will destroy the Observer on the object. When doing so, we have to make sure, that when the getter is first called by a component it returns a reactive value rather then {}, because the getter can't observe adding a new property to the object anymore. Therefore, we add a touch-mutation initializing the object. This function needs the original Observer of the object to create Observers on its properties, causing one, but only one, unnecessary update of the component:

```<code>mutations: {
    updateContent: (state, { id, a, b }) => {
        Vue.set(state.contents, id, { a, b });
    },
    touch: (state, { id }) => {
            if(id in state.contents) return
        if (myObserver === null)
            myObserver = state.contents.__ob__
        state.contents.__ob__ = myObserver
        Vue.set(state.contents, id, {});
        state.contents.__ob__ = new Observer({});
    }
},
</code>```

The constructor can be obtained using:

```<code> const Observer = (new Vue()).$data.__ob__.constructor;
</code>```

Our component has to call touch whenever the id changes:

```<code>props: ["id"],
watch: {
    i: {
        immediate: true,
        handler() {
            this.$store.commit("touch", { id: this.id })
        }
    }
},
computed: {
    myContent() {
        return this.$store.getters.content(this.id)
    }
},
</code>```

As you can see in this fiddle, adding new properties to the object doesn't trigger unnecessary updates anymore.

Body:
I have a Vuex store with an object:

 state: {
    contents: {},
 }

where I dynamically store contents by key:

mutations: {
   updateContent: (state, { id, a, b }) => {
       Vue.set(state.contents, id, { a, b });
   },
}

and get them using:

getters: {
    content: (state) => (id) => {
        if (id in state.contents) return state.contents[id];
        return [];
    }
},

Let's say I have a component like this:

export default {
    props: ["id"],
    computed: {
       myContent() {
          return this.$store.getters.content(this.id)
       }
    },
    // ...
}

How can I add dynamic properties using the mutation without triggering changes in components watching unchanged, already existant properties of state.contents?

Also see this fiddle.

Body:
It seems like Vue(x) can't do this out-of-the-box. But by adding an empty Observer (yes, this is a hack) you can make Vue-components temporarily nonreactive (based on this blogpost).

Basically - we have an Observer on the object itself and an Observer on each of the properties. We will destroy the Observer on the object. When doing so, we have to make sure, that when the getter is first called by a component it returns a reactive value rather then {}, because the getter can't observe adding a new property to the object anymore. Therefore, we add a touch-mutation initializing the object. This function needs the original Observer of the object to create Observers on its properties, causing one, but only one, unnecessary update of the component:

mutations: {
    updateContent: (state, { id, a, b }) => {
        Vue.set(state.contents, id, { a, b });
    },
    touch: (state, { id }) => {
            if(id in state.contents) return
        if (myObserver === null)
            myObserver = state.contents.__ob__
        state.contents.__ob__ = myObserver
        Vue.set(state.contents, id, {});
        state.contents.__ob__ = new Observer({});
    }
},

The constructor can be obtained using:

 const Observer = (new Vue()).$data.__ob__.constructor;

Our component has to call touch whenever the id changes:

props: ["id"],
watch: {
    i: {
        immediate: true,
        handler() {
            this.$store.commit("touch", { id: this.id })
        }
    }
},
computed: {
    myContent() {
        return this.$store.getters.content(this.id)
    }
},

As you can see in this fiddle, adding new properties to the object doesn't trigger unnecessary updates anymore.


问:
Visual Studio 2019 Installer doesn't start
I'm using Windows 10 ver. 1909.    Installer hangs or does nothing.   No feedback.</p>

答: I had exactly this problem.   Same version of Windows 10.  I tried both vs_community.exe and vs_professional.exe.  On a Microsoft Surface Pro 4.  The installer launches, a brief unpacking screen appears, that vanishes, and you're left with the task manager showing the installer but no user interface. I tried numerous different suggestions from Googling as well as the Collect.exe tool.  None of that helped.  Someone had a similar problem that hinted that a display could cause the problem.   My Surface had Duet installed, which allows you to use an iPad as a second monitor.   Uninstalling that allowed Visual Studio to install normally.  Apparently the Visual Studio installer is finicky about displays so if you have any unusual display drivers, or screen sharing utilities, they should be removed to allow installing.   I suspect that the driver or utility could be put back after installation.</p>


问:
Hide Button if not data in recyclerview
I had created a app in which i have multiple edittext and one buttonwith recyclerviuew and one button which are setvisibilty as Gone.On Button click it add all my data in my recyclerview list with by chnaging visibality of my recycelr view and my button.In my Custom Adapter i am using a image view to delete the item from postion now i want that if it delete all data from list then it should automatically hide my Button and recyclerview.

//Recycler_view Adapter

```<code> public class Myviewholder extends RecyclerView.ViewHolder {
        public TextView  land_Detail, area_detail, s_no1;
        public Button delete;

        public Myviewholder(View view) {
            super(view);

            land_Detail = view.findViewById(R.id.hint31);
            area_detail = view.findViewById(R.id.hint21);
            s_no1 = view.findViewById(R.id.hint11);
            delete = view.findViewById(R.id.hint41);

        }
    }

    public Land_adapters(List<Land_list> land_list, Context context) {
        this.laand_list = land_list;
        this.context = context;
    }

    @NonNull
    @Override
    public Land_adapters.Myviewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.land_list, parent, false);

        return new Myviewholder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull Myviewholder holder, final int position) {
        final Land_list current_year = laand_list.get(position);

        holder.area_detail.setText("District :" + current_year.getDistrict_name() + "\n" + "Village :" + current_year.getVillage_name());

        holder.s_no1.setText(String.valueOf(position + 1));
        holder.land_Detail.setText("Acre :" + current_year.getAcre() + "\n" + "Kanal :" + current_year.getKanal() + "\n" + "Marla :" + current_year.getMarla());
        holder.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(context, "", Toast.LENGTH_SHORT).show();
                Land_list theRemovedItem = laand_list.get(position);
                // remove your item from data base
                laand_list.remove(position);  // remove the item from list
                notifyItemRemoved(position); // notify the adapter about the removed item

            }
        });
    }

    @Override
    public int getItemCount() {
        return laand_list.size();
    }
</code>```

//how i am using my recycler in mainactivity class

```<code>   public void final_step() {
        // marla_edit.setError(null);
        recyclerView = findViewById(R.id.recycler_view_last1);

        mAdapter1 = new Land_Adapter(last_Year1);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setAdapter(mAdapter1);

        Land_list last_year1 = new Land_list(land_acre, land_kanal, village_selected1, land_marla, district_selected1, teshil_selected1, block_selected1, block_code, teshil_code1, village_code1, district_code);
        last_Year1.add(last_year1);
        mAdapter1.notifyDataSetChanged();
if (!(last_Year1.size() == 0)) {
    RelativeLayout linearLayout = findViewById(R.id.linear123);

    recyclerView.setVisibility(View.VISIBLE);
    next_button.setVisibility(View.VISIBLE);

}
else
{
    next_button.setVisibility(View.INVISIBLE);

}
</code>```

// i just want that when it press delete image in recycelr view it should hide my button automatically.

答:
you can use an interface to inform the fragment/activity, the list is empty.
Adapter like as below:

```<code>public class CustomAdapter extends RecyclerView.Adapter<CustomViewHolder> {

        AdapterListener listener;

        public void setListener(AdapterListener listener) {
            this.listener = listener;
        }

        ...

        @Override
        public void onBindViewHolder(@NonNull Myviewholder holder, final int position) {
            ...
            holder.delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ...
                    // remove your item from data base
                    laand_list.remove(position);  // remove the item from list
                    notifyItemRemoved(position); // notify the adapter about the removed item
                    if (laand_list.size()==0)
                        listener.onDataListIsEmpty();

                }
            });
        }

        public interface AdapterListener {
            void onDataListIsEmpty();
        }

    }
</code>```

The Activity/Fragment like as below:

```<code>class MyActivity extends Activity implements CustomAdapter.AdapterListener {

        CustomAdapter adapter;

        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            ...
            adapter = new CustomAdapter();
            adapter.setListener(this);
            ...
        }

        @Override
        public void onDataListIsEmpty() {
            // set visible or gone views
        }
    }
</code>```

Title: Hide Button if not data in recyclerview

Body:
I had created a app in which i have multiple edittext and one buttonwith recyclerviuew and one button which are setvisibilty as Gone.On Button click it add all my data in my recyclerview list with by chnaging visibality of my recycelr view and my button.In my Custom Adapter i am using a image view to delete the item from postion now i want that if it delete all data from list then it should automatically hide my Button and recyclerview.

//Recycler_view Adapter

 public class Myviewholder extends RecyclerView.ViewHolder {
        public TextView  land_Detail, area_detail, s_no1;
        public Button delete;

        public Myviewholder(View view) {
            super(view);

            land_Detail = view.findViewById(R.id.hint31);
            area_detail = view.findViewById(R.id.hint21);
            s_no1 = view.findViewById(R.id.hint11);
            delete = view.findViewById(R.id.hint41);

        }
    }

    public Land_adapters(List<Land_list> land_list, Context context) {
        this.laand_list = land_list;
        this.context = context;
    }

    @NonNull
    @Override
    public Land_adapters.Myviewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.land_list, parent, false);

        return new Myviewholder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull Myviewholder holder, final int position) {
        final Land_list current_year = laand_list.get(position);

        holder.area_detail.setText("District :" + current_year.getDistrict_name() + "\n" + "Village :" + current_year.getVillage_name());

        holder.s_no1.setText(String.valueOf(position + 1));
        holder.land_Detail.setText("Acre :" + current_year.getAcre() + "\n" + "Kanal :" + current_year.getKanal() + "\n" + "Marla :" + current_year.getMarla());
        holder.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(context, "", Toast.LENGTH_SHORT).show();
                Land_list theRemovedItem = laand_list.get(position);
                // remove your item from data base
                laand_list.remove(position);  // remove the item from list
                notifyItemRemoved(position); // notify the adapter about the removed item

            }
        });
    }

    @Override
    public int getItemCount() {
        return laand_list.size();
    }

//how i am using my recycler in mainactivity class

   public void final_step() {
        // marla_edit.setError(null);
        recyclerView = findViewById(R.id.recycler_view_last1);

        mAdapter1 = new Land_Adapter(last_Year1);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setAdapter(mAdapter1);

        Land_list last_year1 = new Land_list(land_acre, land_kanal, village_selected1, land_marla, district_selected1, teshil_selected1, block_selected1, block_code, teshil_code1, village_code1, district_code);
        last_Year1.add(last_year1);
        mAdapter1.notifyDataSetChanged();
if (!(last_Year1.size() == 0)) {
    RelativeLayout linearLayout = findViewById(R.id.linear123);

    recyclerView.setVisibility(View.VISIBLE);
    next_button.setVisibility(View.VISIBLE);

}
else
{
    next_button.setVisibility(View.INVISIBLE);

}

// i just want that when it press delete image in recycelr view it should hide my button automatically.

Body:
you can use an interface to inform the fragment/activity, the list is empty.
Adapter like as below:

public class CustomAdapter extends RecyclerView.Adapter<CustomViewHolder> {

        AdapterListener listener;

        public void setListener(AdapterListener listener) {
            this.listener = listener;
        }

        ...

        @Override
        public void onBindViewHolder(@NonNull Myviewholder holder, final int position) {
            ...
            holder.delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ...
                    // remove your item from data base
                    laand_list.remove(position);  // remove the item from list
                    notifyItemRemoved(position); // notify the adapter about the removed item
                    if (laand_list.size()==0)
                        listener.onDataListIsEmpty();

                }
            });
        }

        public interface AdapterListener {
            void onDataListIsEmpty();
        }

    }

The Activity/Fragment like as below:

class MyActivity extends Activity implements CustomAdapter.AdapterListener {

        CustomAdapter adapter;

        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            ...
            adapter = new CustomAdapter();
            adapter.setListener(this);
            ...
        }

        @Override
        public void onDataListIsEmpty() {
            // set visible or gone views
        }
    }


问:
Is there a way of getting a number to increment by 1 each time when inside a while loop?
I have this function:

function newMessages() {
    global $connection;

    $userId = $_SESSION['userId'];
    $query = "SELECT * FROM messages WHERE toUserId = '$userId' && messageRead = 'No' ORDER BY date DESC, time DESC";
    $selectImageQuery = mysqli_query($connection, $query);
    confirmQuery($selectImageQuery);

    while ($row = mysqli_fetch_assoc($selectImageQuery)) {
        $messageId = escape($row['messageId']);
        $message =  escape($row['message']);
        $fromUsername = escape($row['fromUsername']);
        $username = escape($_SESSION['username']);
        $date = escape($row['date']);
        $time = escape($row['time']);

        $query = "SELECT messageCount FROM users WHERE userId = '$userId' ";
        $selectCountQuery = mysqli_query($connection, $query);
        confirmQuery($selectCountQuery);

        while ($row = mysqli_fetch_assoc($selectCountQuery)) {
            $messageCount = escape($row['messageCount']);

            for ($i = 1; $i<=$messageCount; $i++) {
                $messageCount = $i;
                echo $messageCount;

                echo "
          <button type='button' class='btn btn-success' data-toggle='collapse' data-target='#demo$messageCount'>$date / $time - 1 new message from $fromUsername</button>

            $message

";
            }
        }
    }
}
```

The first while loop checks for messages and echo's them out which it does. I then need to find a way where a user can click on each one and only see the info for that one. Currently when a user clicks on one they all open because the data-target (of course) is the same for each. So i am thinking if there is a way of having $messageCount change on each loop

Please help!!! I am going mad

If i change for($i = 1; $i<=$messageCount; $i++) for for($i = 1; $i<=10; $i++) then i get 10 of the 1st message, then 10 of the 2nd message and so on. However only all the 1's open so it's a start i guess.

It would be nice if the number (down the left) went from 1 - 4

答:
I reckon I have managed to solve your problem. The problem lies in the last for-loop:

$messageCount = escape($row['messageCount']);

            for ($i = 1; $i<=$messageCount; $i++) {
                $messageCount = $i;
                echo $messageCount;
                ...
}
```

<p>Here you first get <code>$messageCount</code>. For this example it becomes <code>4</code>. Then in the loop, <code>$i</code> becomes <code>1</code>. Inside the loop you set <code>$messageCount</code> equal to <code>$i</code>, which was <code>1</code>. In the next "loop round" you check whether <code>$i</code> is lower or equal to <code>$messageCount</code>. Because both are now <code>1</code>. The loop continues.</p>

<p>You can solve this by replacing the above for-loop with the one below.</p>

<pre class="lang-php prettyprint-override"><code>for ($i = 1; $i<=$messageCount; $i++) {
                $displayMessageCount = $i;
                echo $displayMessageCount;

                echo "
          <button type='button' class='btn btn-success' data-toggle='collapse' data-target='#demo$displayMessageCount'>$date / $time - 1 new message from $fromUsername</button>
          <div id='demo$displayMessageCount' class='collapse'>
            $message
          </div><br><br>";
            }

</code>```

Now you have a separated variable that displays the count. $messageCount will now stay the same over every loop.
Hope this helps! If not, please comment.

Body:
I have this function:

function newMessages() {
    global $connection;

    $userId = $_SESSION['userId'];
    $query = "SELECT * FROM messages WHERE toUserId = '$userId' && messageRead = 'No' ORDER BY date DESC, time DESC";
    $selectImageQuery = mysqli_query($connection, $query);
    confirmQuery($selectImageQuery);

    while ($row = mysqli_fetch_assoc($selectImageQuery)) {
        $messageId = escape($row['messageId']);
        $message =  escape($row['message']);
        $fromUsername = escape($row['fromUsername']);
        $username = escape($_SESSION['username']);
        $date = escape($row['date']);
        $time = escape($row['time']);

        $query = "SELECT messageCount FROM users WHERE userId = '$userId' ";
        $selectCountQuery = mysqli_query($connection, $query);
        confirmQuery($selectCountQuery);

        while ($row = mysqli_fetch_assoc($selectCountQuery)) {
            $messageCount = escape($row['messageCount']);

            for ($i = 1; $i<=$messageCount; $i++) {
                $messageCount = $i;
                echo $messageCount;

                echo "
          <button type='button' class='btn btn-success' data-toggle='collapse' data-target='#demo$messageCount'>$date / $time - 1 new message from $fromUsername</button>

            $message

";
            }
        }
    }
}

The first while loop checks for messages and echo's them out which it does. I then need to find a way where a user can click on each one and only see the info for that one. Currently when a user clicks on one they all open because the data-target (of course) is the same for each. So i am thinking if there is a way of having $messageCount change on each loop

Please help!!! I am going mad

If i change for($i = 1; $i<=$messageCount; $i++) for for($i = 1; $i<=10; $i++) then i get 10 of the 1st message, then 10 of the 2nd message and so on. However only all the 1's open so it's a start i guess.

It would be nice if the number (down the left) went from 1 - 4

Body:
I reckon I have managed to solve your problem. The problem lies in the last for-loop:

$messageCount = escape($row['messageCount']);

            for ($i = 1; $i<=$messageCount; $i++) {
                $messageCount = $i;
                echo $messageCount;
                ...
}

Here you first get $messageCount. For this example it becomes 4. Then in the loop, $i becomes 1. Inside the loop you set $messageCount equal to $i, which was 1. In the next "loop round" you check whether $i is lower or equal to $messageCount. Because both are now 1. The loop continues.

You can solve this by replacing the above for-loop with the one below.

for ($i = 1; $i<=$messageCount; $i++) {
                $displayMessageCount = $i;
                echo $displayMessageCount;

                echo "
          <button type='button' class='btn btn-success' data-toggle='collapse' data-target='#demo$displayMessageCount'>$date / $time - 1 new message from $fromUsername</button>
          <div id='demo$displayMessageCount' class='collapse'>
            $message
          </div><br><br>";
            }

Now you have a separated variable that displays the count. $messageCount will now stay the same over every loop.
Hope this helps! If not, please comment.


问:
field in mongoose model is required : true but it is being created in postman
i am trying to give only name in the body and want error in the postman ...but for the status response in postman is 201 created but it is throwing error in console as

UnhandledPromiseRejectionWarning: ValidationError: User validation failed: password: Path password is required., email: Path email is required.
    at model.Document.invalidate (C:\projects\MERN\backend\node_modules\mongoose\lib\document.js:2564:32)
    at C:\projects\MERN\backend\node_modules\mongoose\lib\document.js:2386:17
    at C:\projects\MERN\backend\node_modules\mongoose\lib\schematype.js:1181:9
    at processTicksAndRejections (internal/process/task_queues.js:79:11)
(node:6524) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:6524) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

why there is no error in postman???????????

```<code>const mongoose = require('mongoose')

const userSchema = new mongoose.Schema({
name:{
    type : String,
    required : true
},
email:{
    type : String,
    required : true,
    unique:true,
},
password:{
    type : String,
    required : true,
    minlength: 7
},
date:{
    type :Date,
    default: Date.now
}
</code>```

})

```<code> const User = mongoose.model('User',userSchema)

 module.exports = User

router.post("/", async (req, res) => {
try {
const user = await new User(req.body);
user.save();
res.status(201).send({user});
} catch (e) {
res.status(500).send(e);
}
</code>```

});

答:
consider that your node application throws some error right and crashes as you describe well above. Because your node app is interfacing with the internet you need to devise a way to interpret the error from you app into to an error that is known by the internet also, that way postman will be able to tell that an error has occured...So how do we achieve this, the answer is error handling...

We will use your User model as you have described, and consider the code below it...

```<code>router.post("/", async (req, res) => {
  try {
    const user = await new User(req.body);

    // One important thing to note is that the return of this function call below is
    // a Promise object which means that it executes asynchrounously and from the error
    // log you have above, it is the reason your app is crashing...
    user.save();
    res.status(201).send({user});
  } catch (e) {
    res.status(500).send(e);
  }
});
</code>```

So then lets fix it...

```<code>router.post("/", async (req, res) => {
  const user = await new User(req.body);
  return user.save()

  // the then call simply accepts a callback that is executed after the async is complete
  .then((result) => res.status(201).send({user}))

  // this catch will be called in case the call encounters an error during execution
  .catch((error) => res.status(500).send(error));
});
</code>```

Note now we handle the error in the catch by responding to the HTTP request as you have with a 500 code...and also sending the error along with the response

Body:
i am trying to give only name in the body and want error in the postman ...but for the status response in postman is 201 created but it is throwing error in console as

UnhandledPromiseRejectionWarning: ValidationError: User validation failed: password: Path password is required., email: Path email is required.
    at model.Document.invalidate (C:\projects\MERN\backend\node_modules\mongoose\lib\document.js:2564:32)
    at C:\projects\MERN\backend\node_modules\mongoose\lib\document.js:2386:17
    at C:\projects\MERN\backend\node_modules\mongoose\lib\schematype.js:1181:9
    at processTicksAndRejections (internal/process/task_queues.js:79:11)
(node:6524) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:6524) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

why there is no error in postman???????????

const mongoose = require('mongoose')

const userSchema = new mongoose.Schema({
name:{
    type : String,
    required : true
},
email:{
    type : String,
    required : true,
    unique:true,
},
password:{
    type : String,
    required : true,
    minlength: 7
},
date:{
    type :Date,
    default: Date.now
}

})

 const User = mongoose.model('User',userSchema)

 module.exports = User

router.post("/", async (req, res) => {
try {
const user = await new User(req.body);
user.save();
res.status(201).send({user});
} catch (e) {
res.status(500).send(e);
}

});

Body:
consider that your node application throws some error right and crashes as you describe well above. Because your node app is interfacing with the internet you need to devise a way to interpret the error from you app into to an error that is known by the internet also, that way postman will be able to tell that an error has occured...So how do we achieve this, the answer is error handling...

We will use your User model as you have described, and consider the code below it...

router.post("/", async (req, res) => {
  try {
    const user = await new User(req.body);

    // One important thing to note is that the return of this function call below is
    // a Promise object which means that it executes asynchrounously and from the error
    // log you have above, it is the reason your app is crashing...
    user.save();
    res.status(201).send({user});
  } catch (e) {
    res.status(500).send(e);
  }
});

So then lets fix it...

router.post("/", async (req, res) => {
  const user = await new User(req.body);
  return user.save()

  // the then call simply accepts a callback that is executed after the async is complete
  .then((result) => res.status(201).send({user}))

  // this catch will be called in case the call encounters an error during execution
  .catch((error) => res.status(500).send(error));
});

Note now we handle the error in the catch by responding to the HTTP request as you have with a 500 code...and also sending the error along with the response


问:
wxpython problems with binding windows toast notification handler
i am trying to make a windows 10 toast notification that will run code if its clicked but my code only shows the notification and gives me an error when i click it

```<code>import os
import wx
import wx.adv

class MyApp(wx.App):
    def OnInit(self):
        sTitle = 'test'
        sMsg = 'test'
        nmsg = wx.adv.NotificationMessage(title=sTitle, message=sMsg)
        nmsg.SetFlags(wx.ICON_INFORMATION)
        nmsg.Show(timeout=wx.adv.NotificationMessage.Timeout_Auto)
        self.Bind(wx.EVT_NOTIFICATION_MESSAGE_CLICK, self.notifclicked)
        return True
    def _notifclicked(self, evt):
        print("notification has been clicked")
app = MyApp()
app.MainLoop()
</code>```

error code : AttributeError: module 'wx' has no attribute 'EVT_NOTIFICATION_MESSAGE_CLICK'

答:
Without wishing to say definitely that NotificationMessage is unfinished business, I'm going to suggest it.

I suspect that it is based on notify and notify2 which purport to support action callbacks but don't.

They should be relying on Dbus sending stuff back but it doesn't look like it does or you have to jump through hoops to make it happen. (Dbus MainLoop setup for example)

I have decided to adapt your code slightly, just to show how to add action buttons, although they are nothing more than eye candy and to show how I think the event callbacks should work, if it ever comes to reality.

Of course, if it currently does work and I haven't worked out how to do it, I'll happily eat these words. I code exclusively on Linux, so there's that as a caveat.

```<code>import wx
import wx.adv

Act_Id_1 = wx.NewIdRef()
Act_Id_2 = wx.NewIdRef()

class MyFrame(wx.Frame):
    def __init__(self, parent=None, id=wx.ID_ANY, title="", size=(360,100)):
        super(MyFrame, self).__init__(parent, id, title, size)
        self.m_no = 0
        self.panel = wx.Panel(self)
        self.Mbutton = wx.Button(self.panel, wx.ID_ANY, label="Fire off a message", pos=(10,10))
        self.Bind(wx.EVT_BUTTON, self.OnFire, self.Mbutton)
        #self.Bind(wx.adv.EVT_NOTIFICATION_MESSAGE_CLICK, self._notifclicked)
        #self.Bind(wx.adv.EVT_NOTIFICATION_MESSAGE_DISMISSED, self._notifdismissed)
        #self.Bind(wx.adv.EVT_NOTIFICATION_MESSAGE_ACTION, self._notifaction, id=Act_Id_1)
        self.Show()

    def OnFire(self, event):
        self.m_no +=1
        sTitle = 'Test heading'
        sMsg = 'Test message No '
        nmsg = wx.adv.NotificationMessage(title=sTitle, message=sMsg+str(self.m_no))
        nmsg.SetFlags(wx.ICON_INFORMATION)
        nmsg.AddAction(Act_Id_1, "Cancel")
        nmsg.AddAction(Act_Id_2, "Hold")
        nmsg.Show(timeout=10)

    def _notifclicked(self, event):
        print("notification has been clicked")
    def _notifdismissed(self, event):
        print("notification dismissed")
    def _notifaction(self, event):
        print("Action")
app = wx.App()
frame = MyFrame()
app.MainLoop()
</code>```

Body:
i am trying to make a windows 10 toast notification that will run code if its clicked but my code only shows the notification and gives me an error when i click it

import os
import wx
import wx.adv

class MyApp(wx.App):
    def OnInit(self):
        sTitle = 'test'
        sMsg = 'test'
        nmsg = wx.adv.NotificationMessage(title=sTitle, message=sMsg)
        nmsg.SetFlags(wx.ICON_INFORMATION)
        nmsg.Show(timeout=wx.adv.NotificationMessage.Timeout_Auto)
        self.Bind(wx.EVT_NOTIFICATION_MESSAGE_CLICK, self.notifclicked)
        return True
    def _notifclicked(self, evt):
        print("notification has been clicked")
app = MyApp()
app.MainLoop()

error code : AttributeError: module 'wx' has no attribute 'EVT_NOTIFICATION_MESSAGE_CLICK'

Body:
Without wishing to say definitely that NotificationMessage is unfinished business, I'm going to suggest it.

I suspect that it is based on notify and notify2 which purport to support action callbacks but don't.

They should be relying on Dbus sending stuff back but it doesn't look like it does or you have to jump through hoops to make it happen. (Dbus MainLoop setup for example)

I have decided to adapt your code slightly, just to show how to add action buttons, although they are nothing more than eye candy and to show how I think the event callbacks should work, if it ever comes to reality.

Of course, if it currently does work and I haven't worked out how to do it, I'll happily eat these words. I code exclusively on Linux, so there's that as a caveat.

import wx
import wx.adv

Act_Id_1 = wx.NewIdRef()
Act_Id_2 = wx.NewIdRef()

class MyFrame(wx.Frame):
    def __init__(self, parent=None, id=wx.ID_ANY, title="", size=(360,100)):
        super(MyFrame, self).__init__(parent, id, title, size)
        self.m_no = 0
        self.panel = wx.Panel(self)
        self.Mbutton = wx.Button(self.panel, wx.ID_ANY, label="Fire off a message", pos=(10,10))
        self.Bind(wx.EVT_BUTTON, self.OnFire, self.Mbutton)
        #self.Bind(wx.adv.EVT_NOTIFICATION_MESSAGE_CLICK, self._notifclicked)
        #self.Bind(wx.adv.EVT_NOTIFICATION_MESSAGE_DISMISSED, self._notifdismissed)
        #self.Bind(wx.adv.EVT_NOTIFICATION_MESSAGE_ACTION, self._notifaction, id=Act_Id_1)
        self.Show()

    def OnFire(self, event):
        self.m_no +=1
        sTitle = 'Test heading'
        sMsg = 'Test message No '
        nmsg = wx.adv.NotificationMessage(title=sTitle, message=sMsg+str(self.m_no))
        nmsg.SetFlags(wx.ICON_INFORMATION)
        nmsg.AddAction(Act_Id_1, "Cancel")
        nmsg.AddAction(Act_Id_2, "Hold")
        nmsg.Show(timeout=10)

    def _notifclicked(self, event):
        print("notification has been clicked")
    def _notifdismissed(self, event):
        print("notification dismissed")
    def _notifaction(self, event):
        print("Action")
app = wx.App()
frame = MyFrame()
app.MainLoop()


问:
Docker in MacOs is very slow
I have this docker-compose.yml:

```<code>version: "3.1"
services:

    memcached:
      image: memcached:alpine
      container_name: universal-memcached2

    redis:
      image: redis:alpine
      container_name: universal-redis2

    mariadb:
      image: mariadb:10.4
      container_name: universal-mariadb2
      working_dir: /application
      volumes:
        - .:/application
        - "../data/db:/var/lib/mysql" # skasowac
      environment:
        - MYSQL_ROOT_PASSWORD=Haslo
        - MYSQL_DATABASE=sample
        - MYSQL_USER=user
        - MYSQL_PASSWORD=Haslo
      ports:
        - "8083:3306"

    webserver:
      image: nginx:alpine
      container_name: universal-webserver2
      working_dir: /application
      volumes:
          - .:/application
          - ./phpdocker/nginx/nginx.conf:/etc/nginx/conf.d/default.conf
      ports:
       - "8080:80"

    php-fpm:
      build: phpdocker/php-fpm
      container_name: universal-php-fpm2
      working_dir: /application
      volumes:
        - .:/application
        - ./phpdocker/php-fpm/php-ini-overrides.ini:/etc/php/7.3/fpm/conf.d/99-overrides.ini

    volumes:
        generated:
        var:
        static:

    phpmyadmin:
      image: phpmyadmin/phpmyadmin
      links:
        - mariadb
      environment:
        PMA_HOST: mariadb
        PMA_PORT: 3306
      ports:
        - '8081:80'
</code>```

When I run my newest project in symfony 4 on it, it works very slowly... :(

I have new MacOs and Docker Desktop.
I'm currently learning the Symfony and Laravel framework, but this is very slow for Docker. It is not even working on it.

How can I repair it?

答:
Use Mutagen to sync volumes

It's a known issue that Docker for Mac is slow when using shared volumes containing a big amount of files, see https://github.com/docker/for-mac/issues/77.

So, some workarounds came like :cached and docker-sync. However it's not totally satisfactory because it's still slow compared to native (Linux) and docker-sync consumes a lot of resources when syncing.

That being said, there is a good alternative, not to say perfect, which is Mutagen. It's almost as fast as native shared volumes with Linux!

A benchmark is available:

Source: article on Medium

I created a full example for a Symfony project to show how to use it, but it can be used for any type of project in any language.

Title: Docker in MacOs is very slow

Body:
I have this docker-compose.yml:

version: "3.1"
services:

    memcached:
      image: memcached:alpine
      container_name: universal-memcached2

    redis:
      image: redis:alpine
      container_name: universal-redis2

    mariadb:
      image: mariadb:10.4
      container_name: universal-mariadb2
      working_dir: /application
      volumes:
        - .:/application
        - "../data/db:/var/lib/mysql" # skasowac
      environment:
        - MYSQL_ROOT_PASSWORD=Haslo
        - MYSQL_DATABASE=sample
        - MYSQL_USER=user
        - MYSQL_PASSWORD=Haslo
      ports:
        - "8083:3306"

    webserver:
      image: nginx:alpine
      container_name: universal-webserver2
      working_dir: /application
      volumes:
          - .:/application
          - ./phpdocker/nginx/nginx.conf:/etc/nginx/conf.d/default.conf
      ports:
       - "8080:80"

    php-fpm:
      build: phpdocker/php-fpm
      container_name: universal-php-fpm2
      working_dir: /application
      volumes:
        - .:/application
        - ./phpdocker/php-fpm/php-ini-overrides.ini:/etc/php/7.3/fpm/conf.d/99-overrides.ini

    volumes:
        generated:
        var:
        static:

    phpmyadmin:
      image: phpmyadmin/phpmyadmin
      links:
        - mariadb
      environment:
        PMA_HOST: mariadb
        PMA_PORT: 3306
      ports:
        - '8081:80'

When I run my newest project in symfony 4 on it, it works very slowly... :(

I have new MacOs and Docker Desktop.
I'm currently learning the Symfony and Laravel framework, but this is very slow for Docker. It is not even working on it.

How can I repair it?


问:
Safe area not working in custom TabBarController's ViewController
In the didFinishLaunchingWithOptions of my app's AppDelegate, after initializing my UIWindow property, I set the root controller to a subclass of UITabBarController, in which I set the view controllers (and some other custom behaviour).

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = TabBarController() // a subclass of UITabBarController
    self.window?.makeKeyAndVisible()

    return true
}
</code>```

The issue I have is that the safe areas in the TabBarController's view controllers does not seem to work properly.

eg: sticking a view to the bottom of a view controller's view, using it's safeAreaLayoutGuide, goes behind the tab bar.

```<code>self.bottomView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor)
</code>```

The custom behaviour (such as set tint colors, set the viewControllers and their tab bar items, or set the tabBarController's delegate - nothing crazy here) setup is made in it's viewDidLoad.

NB: I work in code only, I do not use interface builder.

答:
Can't reproduce. Here's the complete code for a view controller in a project that does what you seem to describe:

```<code>class FirstViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let v = UIView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .red
        self.view.addSubview(v)
        v.widthAnchor.constraint(equalToConstant: 100).isActive = true
        v.heightAnchor.constraint(equalToConstant: 100).isActive = true
        v.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        v.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor).isActive = true
    }
}
</code>```

And here's the result; the red square appears exactly where we expect to see it, pinned to the top of the tab bar:

Body:
In the didFinishLaunchingWithOptions of my app's AppDelegate, after initializing my UIWindow property, I set the root controller to a subclass of UITabBarController, in which I set the view controllers (and some other custom behaviour).

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = TabBarController() // a subclass of UITabBarController
    self.window?.makeKeyAndVisible()

    return true
}

The issue I have is that the safe areas in the TabBarController's view controllers does not seem to work properly.

eg: sticking a view to the bottom of a view controller's view, using it's safeAreaLayoutGuide, goes behind the tab bar.

self.bottomView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor)

The custom behaviour (such as set tint colors, set the viewControllers and their tab bar items, or set the tabBarController's delegate - nothing crazy here) setup is made in it's viewDidLoad.

NB: I work in code only, I do not use interface builder.

Body:
Can't reproduce. Here's the complete code for a view controller in a project that does what you seem to describe:

class FirstViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let v = UIView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .red
        self.view.addSubview(v)
        v.widthAnchor.constraint(equalToConstant: 100).isActive = true
        v.heightAnchor.constraint(equalToConstant: 100).isActive = true
        v.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        v.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor).isActive = true
    }
}

And here's the result; the red square appears exactly where we expect to see it, pinned to the top of the tab bar:


问:
VBA: add a row in excel only if there's a value in a cell
I'm currently using the macro below so when I make a change in cells from column B, it adds a Line. I'd like to know how to change the code so it only adds a line when there's content in the cell and not when I make a change (like erasing content from that same cell).
Thanks!</p>

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

    'Test if change is in column B and only one cell changed
    If Not Intersect(Target, Me.Columns("B")) Is Nothing And _
            Target.Cells.Count = 1 Then

        Target.Offset(1, 0).EntireRow.Insert Shift:=xlDown      'Insert row below data entry

        'Target.EntireRow.Insert Shift:=xlDown       'Insert row above data entry

    End If
End Sub
</code>```

答:
One simple way to check the if the target value is empty is to use Target.Value

```<code>If Target.Value <> "" Then
  Target.Offset(1, 0).EntireRow.Insert Shift:=xlDown
End If
</code>```

Body:
I'm currently using the macro below so when I make a change in cells from column B, it adds a Line. I'd like to know how to change the code so it only adds a line when there's content in the cell and not when I make a change (like erasing content from that same cell).
Thanks!

Private Sub Worksheet_Change(ByVal Target As Range)

    'Test if change is in column B and only one cell changed
    If Not Intersect(Target, Me.Columns("B")) Is Nothing And _
            Target.Cells.Count = 1 Then

        Target.Offset(1, 0).EntireRow.Insert Shift:=xlDown      'Insert row below data entry

        'Target.EntireRow.Insert Shift:=xlDown       'Insert row above data entry

    End If
End Sub

Body:
One simple way to check the if the target value is empty is to use Target.Value

If Target.Value <> "" Then
  Target.Offset(1, 0).EntireRow.Insert Shift:=xlDown
End If


问:
In a JSON array, how to search for a certain record returned by ConvertFrom-Json?
With Powershell 6 I am able to download a file in JSON format with:

```<code>PS C:\> Invoke-WebRequest https://login.microsoftonline.com/common/discovery/v2.0/keys |
>> ConvertFrom-Json |
>> Select-Object -expand keys

kty    : RSA
use    : sig
kid    : CtTuhMJmD5M7DLdzD2v2x3QKSRY
x5t    : CtTuhMJmD5M7DLdzD2v2x3QKSRY
n      : 18uZ3P3IgOySlnOsxeIN5WUKzvlm6evPDMFbmXPtTF0GMe7tD2JPfai2UGn74s7AFwqxWO5DQZRu6VfQUux8uMR4J7nxm1Kf__7pVEVJJyDuL5a8PARRYQtH68w-0IZxcFOkgsSdhtIzPQ2jj4mmRzWXIwh8M_8pJ6qiOjvjF9bhEq0CC_f27BnljPaFn8hxY69pCoxenWWqFcsUhFZvCMthhRubAbBilDr74KaXS5xCgySBhPzwekD9_NdCUu
         Csdqavd4T-VWnbplbB8YsC-R00FptBFKuTyT9zoGZjWZilQVmj7v3k8jXqYB2nWKgTAfwjmiyKz78FHkaE-nCIDw
e      : AQAB
x5c    : {MIIDBTCCAe2gAwIBAgIQXVogj9BAf49IpuOSIvztNDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTIwMDMxNzAwMDAwMFoXDTI1MDMxNzAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBB
         QADggEPADCCAQoCggEBANfLmdz9yIDskpZzrMXiDeVlCs75ZunrzwzBW5lz7UxdBjHu7Q9iT32otlBp++LOwBcKsVjuQ0GUbulX0FLsfLjEeCe58ZtSn//+6VRFSScg7i+WvDwEUWELR+vMPtCGcXBTpILEnYbSMz0No4+Jpkc1lyMIfDP/KSeqojo74xfW4RKtAgv39uwZ5Yz2hZ/IcWOvaQqMXp1lqhXLFIRWbwjLYYUbmwGwYpQ6++Cml0u
         cQoMkgYT88HpA/fzXQlLgrHamr3eE/lVp26ZWwfGLAvkdNBabQRSrk8k/c6BmY1mYpUFZo+795PI16mAdp1ioEwH8I5osis+/BR5GhPpwiA8CAwEAAaMhMB8wHQYDVR0OBBYEFF8MDGklOGhGNVJvsHHRCaqtzexcMA0GCSqGSIb3DQEBCwUAA4IBAQCKkegw/mdpCVl1lOpgU4G9RT+1gtcPqZK9kpimuDggSJju6KUQlOCi5/lIH5DCzpjFd
         mG17TjWVBNve5kowmrhLzovY0Ykk7+6hYTBK8dNNSmd4SK7zY++0aDIuOzHP2Cur+kgFC0gez50tPzotLDtMmp40gknXuzltwJfezNSw3gLgljDsGGcDIXK3qLSYh44qSuRGwulcN2EJUZBI9tIxoODpaWHIN8+z2uZvf8JBYFjA3+n9FRQn51X16CTcjq4QRTbNVpgVuQuyaYnEtx0ZnDvguB3RjGSPIXTRBkLl2x7e8/6uAZ6tchw8rhcOtP
         sFgJuoJokGjvcUSR/6Eqd}
issuer : https://login.microsoftonline.com/{tenantid}/v2.0

kty    : RSA
use    : sig
kid    : SsZsBNhZcF3Q9S4trpQBTByNRRI
x5t    : SsZsBNhZcF3Q9S4trpQBTByNRRI
n      : uHPewhg4WC3eLVPkEFlj7RDtaKYWXCI5G-LPVzsMKOuIu7qQQbeytIA6P6HT9_iIRt8zNQvuw4P9vbNjgUCpI6vfZGsjk3XuCVoB_bAIhvuBcQh9ePH2yEwS5reR-NrG1PsqzobnZZuigKCoDmuOb_UDx1DiVyNCbMBlEG7UzTQwLf5NP6HaRHx027URJeZvPAWY7zjHlSOuKoS_d1yUveaBFIgZqPWLCg44ck4gvik45HsNVWT9zYfT74dvUS
         SrMSR-SHFT7Hy1XjbVXpHJHNNAXpPoGoWXTuc0BxMsB4cqjfJqoftFGOG4x32vEzakArLPxAKwGvkvu0jToAyvSQ
e      : AQAB
x5c    : {MIIDBTCCAe2gAwIBAgIQWHw7h/Ysh6hPcXpnrJ0N8DANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTIwMDQyNzAwMDAwMFoXDTI1MDQyNzAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBB
         QADggEPADCCAQoCggEBALhz3sIYOFgt3i1T5BBZY+0Q7WimFlwiORviz1c7DCjriLu6kEG3srSAOj+h0/f4iEbfMzUL7sOD/b2zY4FAqSOr32RrI5N17glaAf2wCIb7gXEIfXjx9shMEua3kfjaxtT7Ks6G52WbooCgqA5rjm/1A8dQ4lcjQmzAZRBu1M00MC3+TT+h2kR8dNu1ESXmbzwFmO84x5UjriqEv3dclL3mgRSIGaj1iwoOOHJOIL4
         pOOR7DVVk/c2H0++Hb1EkqzEkfkhxU+x8tV421V6RyRzTQF6T6BqFl07nNAcTLAeHKo3yaqH7RRjhuMd9rxM2pAKyz8QCsBr5L7tI06AMr0kCAwEAAaMhMB8wHQYDVR0OBBYEFOI7M+DDFMlP7Ac3aomPnWo1QL1SMA0GCSqGSIb3DQEBCwUAA4IBAQBv+8rBiDY8sZDBoUDYwFQM74QjqCmgNQfv5B0Vjwg20HinERjQeH24uAWzyhWN9++Fm
         eY4zcRXDY5UNmB0nJz7UGlprA9s7voQ0Lkyiud0DO072RPBg38LmmrqoBsLb3MB9MZ2CGBaHftUHfpdTvrgmXSP0IJn7mCUq27g+hFk7n/MLbN1k8JswEODIgdMRvGqN+mnrPKkviWmcVAZccsWfcmS1pKwXqICTKzd6WmVdz+cL7ZSd9I2X0pY4oRwauoE2bS95vrXljCYgLArI3XB2QcnglDDBRYu3Z3aIJb26PTIyhkVKT7xaXhXl4Ogrbm
         Qon9/O61G2dzpjzzBPqNP}
issuer : https://login.microsoftonline.com/{tenantid}/v2.0
</code>```

(and there are more records in the keys array...)

How could I please search for the record with kid = "SsZsBNhZcF3Q9S4trpQBTByNRRI" and then return its x5c property?

Is the following a good way to find the record (I am confused by -expand, does it strip the outside JSON object and return just the keys array?) and then how to access its x5c property please?

```<code>PS C:\> Invoke-WebRequest https://login.microsoftonline.com/common/discovery/v2.0/keys |
>> ConvertFrom-Json |
>> Select-Object -expand keys |
>> Where-Object -Property kid -Eq SsZsBNhZcF3Q9S4trpQBTByNRRI

kty    : RSA
use    : sig
kid    : SsZsBNhZcF3Q9S4trpQBTByNRRI
x5t    : SsZsBNhZcF3Q9S4trpQBTByNRRI
n      : uHPewhg4WC3eLVPkEFlj7RDtaKYWXCI5G-LPVzsMKOuIu7qQQbeytIA6P6HT9_iIRt8zNQvuw4P9vbNjgUCpI6vfZGsjk3XuCVoB_bAIhvuBcQh9ePH2yEwS5reR-NrG1PsqzobnZZuigKCoDmuOb_UDx1DiVyNCbMBlEG7UzTQwLf5NP6HaRHx027URJeZvPAWY7zjHlSOuKoS_d1yUveaBFIgZqPWLCg44ck4gvik45HsNVWT9zYfT74dvUS
         SrMSR-SHFT7Hy1XjbVXpHJHNNAXpPoGoWXTuc0BxMsB4cqjfJqoftFGOG4x32vEzakArLPxAKwGvkvu0jToAyvSQ
e      : AQAB
x5c    : {MIIDBTCCAe2gAwIBAgIQWHw7h/Ysh6hPcXpnrJ0N8DANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTIwMDQyNzAwMDAwMFoXDTI1MDQyNzAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBB
         QADggEPADCCAQoCggEBALhz3sIYOFgt3i1T5BBZY+0Q7WimFlwiORviz1c7DCjriLu6kEG3srSAOj+h0/f4iEbfMzUL7sOD/b2zY4FAqSOr32RrI5N17glaAf2wCIb7gXEIfXjx9shMEua3kfjaxtT7Ks6G52WbooCgqA5rjm/1A8dQ4lcjQmzAZRBu1M00MC3+TT+h2kR8dNu1ESXmbzwFmO84x5UjriqEv3dclL3mgRSIGaj1iwoOOHJOIL4
         pOOR7DVVk/c2H0++Hb1EkqzEkfkhxU+x8tV421V6RyRzTQF6T6BqFl07nNAcTLAeHKo3yaqH7RRjhuMd9rxM2pAKyz8QCsBr5L7tI06AMr0kCAwEAAaMhMB8wHQYDVR0OBBYEFOI7M+DDFMlP7Ac3aomPnWo1QL1SMA0GCSqGSIb3DQEBCwUAA4IBAQBv+8rBiDY8sZDBoUDYwFQM74QjqCmgNQfv5B0Vjwg20HinERjQeH24uAWzyhWN9++Fm
         eY4zcRXDY5UNmB0nJz7UGlprA9s7voQ0Lkyiud0DO072RPBg38LmmrqoBsLb3MB9MZ2CGBaHftUHfpdTvrgmXSP0IJn7mCUq27g+hFk7n/MLbN1k8JswEODIgdMRvGqN+mnrPKkviWmcVAZccsWfcmS1pKwXqICTKzd6WmVdz+cL7ZSd9I2X0pY4oRwauoE2bS95vrXljCYgLArI3XB2QcnglDDBRYu3Z3aIJb26PTIyhkVKT7xaXhXl4Ogrbm
         Qon9/O61G2dzpjzzBPqNP}
issuer : https://login.microsoftonline.com/{tenantid}/v2.0
</code>```

答:
This is everyday powershell.  Pipe to that.  It looks like x5c is an array too.</p>

```<code>| select -expand x5c
</code>```

Body:
With Powershell 6 I am able to download a file in JSON format with:

PS C:\> Invoke-WebRequest https://login.microsoftonline.com/common/discovery/v2.0/keys |
>> ConvertFrom-Json |
>> Select-Object -expand keys

kty    : RSA
use    : sig
kid    : CtTuhMJmD5M7DLdzD2v2x3QKSRY
x5t    : CtTuhMJmD5M7DLdzD2v2x3QKSRY
n      : 18uZ3P3IgOySlnOsxeIN5WUKzvlm6evPDMFbmXPtTF0GMe7tD2JPfai2UGn74s7AFwqxWO5DQZRu6VfQUux8uMR4J7nxm1Kf__7pVEVJJyDuL5a8PARRYQtH68w-0IZxcFOkgsSdhtIzPQ2jj4mmRzWXIwh8M_8pJ6qiOjvjF9bhEq0CC_f27BnljPaFn8hxY69pCoxenWWqFcsUhFZvCMthhRubAbBilDr74KaXS5xCgySBhPzwekD9_NdCUu
         Csdqavd4T-VWnbplbB8YsC-R00FptBFKuTyT9zoGZjWZilQVmj7v3k8jXqYB2nWKgTAfwjmiyKz78FHkaE-nCIDw
e      : AQAB
x5c    : {MIIDBTCCAe2gAwIBAgIQXVogj9BAf49IpuOSIvztNDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTIwMDMxNzAwMDAwMFoXDTI1MDMxNzAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBB
         QADggEPADCCAQoCggEBANfLmdz9yIDskpZzrMXiDeVlCs75ZunrzwzBW5lz7UxdBjHu7Q9iT32otlBp++LOwBcKsVjuQ0GUbulX0FLsfLjEeCe58ZtSn//+6VRFSScg7i+WvDwEUWELR+vMPtCGcXBTpILEnYbSMz0No4+Jpkc1lyMIfDP/KSeqojo74xfW4RKtAgv39uwZ5Yz2hZ/IcWOvaQqMXp1lqhXLFIRWbwjLYYUbmwGwYpQ6++Cml0u
         cQoMkgYT88HpA/fzXQlLgrHamr3eE/lVp26ZWwfGLAvkdNBabQRSrk8k/c6BmY1mYpUFZo+795PI16mAdp1ioEwH8I5osis+/BR5GhPpwiA8CAwEAAaMhMB8wHQYDVR0OBBYEFF8MDGklOGhGNVJvsHHRCaqtzexcMA0GCSqGSIb3DQEBCwUAA4IBAQCKkegw/mdpCVl1lOpgU4G9RT+1gtcPqZK9kpimuDggSJju6KUQlOCi5/lIH5DCzpjFd
         mG17TjWVBNve5kowmrhLzovY0Ykk7+6hYTBK8dNNSmd4SK7zY++0aDIuOzHP2Cur+kgFC0gez50tPzotLDtMmp40gknXuzltwJfezNSw3gLgljDsGGcDIXK3qLSYh44qSuRGwulcN2EJUZBI9tIxoODpaWHIN8+z2uZvf8JBYFjA3+n9FRQn51X16CTcjq4QRTbNVpgVuQuyaYnEtx0ZnDvguB3RjGSPIXTRBkLl2x7e8/6uAZ6tchw8rhcOtP
         sFgJuoJokGjvcUSR/6Eqd}
issuer : https://login.microsoftonline.com/{tenantid}/v2.0

kty    : RSA
use    : sig
kid    : SsZsBNhZcF3Q9S4trpQBTByNRRI
x5t    : SsZsBNhZcF3Q9S4trpQBTByNRRI
n      : uHPewhg4WC3eLVPkEFlj7RDtaKYWXCI5G-LPVzsMKOuIu7qQQbeytIA6P6HT9_iIRt8zNQvuw4P9vbNjgUCpI6vfZGsjk3XuCVoB_bAIhvuBcQh9ePH2yEwS5reR-NrG1PsqzobnZZuigKCoDmuOb_UDx1DiVyNCbMBlEG7UzTQwLf5NP6HaRHx027URJeZvPAWY7zjHlSOuKoS_d1yUveaBFIgZqPWLCg44ck4gvik45HsNVWT9zYfT74dvUS
         SrMSR-SHFT7Hy1XjbVXpHJHNNAXpPoGoWXTuc0BxMsB4cqjfJqoftFGOG4x32vEzakArLPxAKwGvkvu0jToAyvSQ
e      : AQAB
x5c    : {MIIDBTCCAe2gAwIBAgIQWHw7h/Ysh6hPcXpnrJ0N8DANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTIwMDQyNzAwMDAwMFoXDTI1MDQyNzAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBB
         QADggEPADCCAQoCggEBALhz3sIYOFgt3i1T5BBZY+0Q7WimFlwiORviz1c7DCjriLu6kEG3srSAOj+h0/f4iEbfMzUL7sOD/b2zY4FAqSOr32RrI5N17glaAf2wCIb7gXEIfXjx9shMEua3kfjaxtT7Ks6G52WbooCgqA5rjm/1A8dQ4lcjQmzAZRBu1M00MC3+TT+h2kR8dNu1ESXmbzwFmO84x5UjriqEv3dclL3mgRSIGaj1iwoOOHJOIL4
         pOOR7DVVk/c2H0++Hb1EkqzEkfkhxU+x8tV421V6RyRzTQF6T6BqFl07nNAcTLAeHKo3yaqH7RRjhuMd9rxM2pAKyz8QCsBr5L7tI06AMr0kCAwEAAaMhMB8wHQYDVR0OBBYEFOI7M+DDFMlP7Ac3aomPnWo1QL1SMA0GCSqGSIb3DQEBCwUAA4IBAQBv+8rBiDY8sZDBoUDYwFQM74QjqCmgNQfv5B0Vjwg20HinERjQeH24uAWzyhWN9++Fm
         eY4zcRXDY5UNmB0nJz7UGlprA9s7voQ0Lkyiud0DO072RPBg38LmmrqoBsLb3MB9MZ2CGBaHftUHfpdTvrgmXSP0IJn7mCUq27g+hFk7n/MLbN1k8JswEODIgdMRvGqN+mnrPKkviWmcVAZccsWfcmS1pKwXqICTKzd6WmVdz+cL7ZSd9I2X0pY4oRwauoE2bS95vrXljCYgLArI3XB2QcnglDDBRYu3Z3aIJb26PTIyhkVKT7xaXhXl4Ogrbm
         Qon9/O61G2dzpjzzBPqNP}
issuer : https://login.microsoftonline.com/{tenantid}/v2.0

(and there are more records in the keys array...)

How could I please search for the record with kid = "SsZsBNhZcF3Q9S4trpQBTByNRRI" and then return its x5c property?

Is the following a good way to find the record (I am confused by -expand, does it strip the outside JSON object and return just the keys array?) and then how to access its x5c property please?

PS C:\> Invoke-WebRequest https://login.microsoftonline.com/common/discovery/v2.0/keys |
>> ConvertFrom-Json |
>> Select-Object -expand keys |
>> Where-Object -Property kid -Eq SsZsBNhZcF3Q9S4trpQBTByNRRI

kty    : RSA
use    : sig
kid    : SsZsBNhZcF3Q9S4trpQBTByNRRI
x5t    : SsZsBNhZcF3Q9S4trpQBTByNRRI
n      : uHPewhg4WC3eLVPkEFlj7RDtaKYWXCI5G-LPVzsMKOuIu7qQQbeytIA6P6HT9_iIRt8zNQvuw4P9vbNjgUCpI6vfZGsjk3XuCVoB_bAIhvuBcQh9ePH2yEwS5reR-NrG1PsqzobnZZuigKCoDmuOb_UDx1DiVyNCbMBlEG7UzTQwLf5NP6HaRHx027URJeZvPAWY7zjHlSOuKoS_d1yUveaBFIgZqPWLCg44ck4gvik45HsNVWT9zYfT74dvUS
         SrMSR-SHFT7Hy1XjbVXpHJHNNAXpPoGoWXTuc0BxMsB4cqjfJqoftFGOG4x32vEzakArLPxAKwGvkvu0jToAyvSQ
e      : AQAB
x5c    : {MIIDBTCCAe2gAwIBAgIQWHw7h/Ysh6hPcXpnrJ0N8DANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTIwMDQyNzAwMDAwMFoXDTI1MDQyNzAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBB
         QADggEPADCCAQoCggEBALhz3sIYOFgt3i1T5BBZY+0Q7WimFlwiORviz1c7DCjriLu6kEG3srSAOj+h0/f4iEbfMzUL7sOD/b2zY4FAqSOr32RrI5N17glaAf2wCIb7gXEIfXjx9shMEua3kfjaxtT7Ks6G52WbooCgqA5rjm/1A8dQ4lcjQmzAZRBu1M00MC3+TT+h2kR8dNu1ESXmbzwFmO84x5UjriqEv3dclL3mgRSIGaj1iwoOOHJOIL4
         pOOR7DVVk/c2H0++Hb1EkqzEkfkhxU+x8tV421V6RyRzTQF6T6BqFl07nNAcTLAeHKo3yaqH7RRjhuMd9rxM2pAKyz8QCsBr5L7tI06AMr0kCAwEAAaMhMB8wHQYDVR0OBBYEFOI7M+DDFMlP7Ac3aomPnWo1QL1SMA0GCSqGSIb3DQEBCwUAA4IBAQBv+8rBiDY8sZDBoUDYwFQM74QjqCmgNQfv5B0Vjwg20HinERjQeH24uAWzyhWN9++Fm
         eY4zcRXDY5UNmB0nJz7UGlprA9s7voQ0Lkyiud0DO072RPBg38LmmrqoBsLb3MB9MZ2CGBaHftUHfpdTvrgmXSP0IJn7mCUq27g+hFk7n/MLbN1k8JswEODIgdMRvGqN+mnrPKkviWmcVAZccsWfcmS1pKwXqICTKzd6WmVdz+cL7ZSd9I2X0pY4oRwauoE2bS95vrXljCYgLArI3XB2QcnglDDBRYu3Z3aIJb26PTIyhkVKT7xaXhXl4Ogrbm
         Qon9/O61G2dzpjzzBPqNP}
issuer : https://login.microsoftonline.com/{tenantid}/v2.0

Body:
This is everyday powershell.  Pipe to that.  It looks like x5c is an array too.

| select -expand x5c


问:
Javascript how to make text 10% larger
I am making a website and it is nearly finished and while testing someone mentioned a setting for text size. Now I know I can just go through and make the font to a set value that is set by something else. But I want to see if I can do it with Javascript.

On my settings page I have a range input from 80% to 120%, but how it will work is it will make the text size bigger depending on the current value it is. For example, the size setting was set to 100%, then I increased it to 110% I want all text to get 10% bigger than before, but I don't have a clue on how to do it, even if it's possible. If anyone has a different method to changing font size based on a setting that would be useful.

Or can I do this:

```<code>font-size: {{setting}};
</code>```

for the whole document after I have loaded the rest of the CSS, meaning would this set all text to this size or make it bigger/smaller depending on if its over 100%?

答:
The "right" way to set font sizes on elements is with 'rem' or 'em' units, never with fixed 'px' units.

If your document uses this method, then simply changing the body's font-size will change all the other element sizes.

function resize (factor) {
  let sizeStr = document.body.style.fontSize;
  let size = Number(sizeStr.replace('rem', '')) || 1;
  let bigger = (size * factor).toFixed(1) + 'rem';
  document.body.style.fontSize = bigger;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0.2rem;
}</code>```

<button onclick="resize(1.2)">Bigger</button>
<button onclick="resize(0.8)">Smaller</button>

H2

H3

H2

Paragraph

```

Title: Javascript how to make text 10% larger

Body:
I am making a website and it is nearly finished and while testing someone mentioned a setting for text size. Now I know I can just go through and make the font to a set value that is set by something else. But I want to see if I can do it with Javascript.

On my settings page I have a range input from 80% to 120%, but how it will work is it will make the text size bigger depending on the current value it is. For example, the size setting was set to 100%, then I increased it to 110% I want all text to get 10% bigger than before, but I don't have a clue on how to do it, even if it's possible. If anyone has a different method to changing font size based on a setting that would be useful.

Or can I do this:

font-size: {{setting}};

for the whole document after I have loaded the rest of the CSS, meaning would this set all text to this size or make it bigger/smaller depending on if its over 100%?

Body:
The "right" way to set font sizes on elements is with 'rem' or 'em' units, never with fixed 'px' units.

If your document uses this method, then simply changing the body's font-size will change all the other element sizes.

function resize (factor) {
  let sizeStr = document.body.style.fontSize;
  let size = Number(sizeStr.replace('rem', '')) || 1;
  let bigger = (size * factor).toFixed(1) + 'rem';
  document.body.style.fontSize = bigger;
}

* {
  margin: 0.2rem;
}

<body>
<button onclick="resize(1.2)">Bigger</button>
<button onclick="resize(0.8)">Smaller</button>

<h2>H2</h2>
<h3>H3</h3>
<h4>H2</h4>
<p>Paragraph</p>
</body>


问:
On printing webpage , it prints all the images of image slider
I have got a jquery image slider on my webpage , when i try to print that page all the  images of that slider are printed , I want to print the current slide image , how can i acheive that , Below is the website :
Duxbury Caravans</p>

答:
Use CSS rules for printing.

Try adding this to your CSS file:

```<code>@media print
{
    #slideshow { display: none }
}
</code>```

Here we added a rule to hide the "slideshow" div. This rule will be applied exclusively for "print" media.

Your problem is bigger than a quick / simple solution can handle.

You have learned an important lesson, which is to consider the print view of the website since the beginning.

Here is an example of how to handle this issue the right way: http://www.sathyasai.org.br/mensagem/ Try seeing a print preview, and look how the website screen view differs from the print view. Both were carefully considered from the start. At the print view,all stuff like background, navigation menus, breadcrumbs, etc., are removed.

It is not a good idea to develop the whole website design without thinking about the print output. QAs you are experiencing, you will have a lot of work to get the print output as you want. You have to "redesign" it to the printer now...

Good luck!

Body:
Use CSS rules for printing.

Try adding this to your CSS file:

@media print
{
    #slideshow { display: none }
}

Here we added a rule to hide the "slideshow" div. This rule will be applied exclusively for "print" media.

Your problem is bigger than a quick / simple solution can handle.

You have learned an important lesson, which is to consider the print view of the website since the beginning.

Here is an example of how to handle this issue the right way: http://www.sathyasai.org.br/mensagem/ Try seeing a print preview, and look how the website screen view differs from the print view. Both were carefully considered from the start. At the print view,all stuff like background, navigation menus, breadcrumbs, etc., are removed.

It is not a good idea to develop the whole website design without thinking about the print output. QAs you are experiencing, you will have a lot of work to get the print output as you want. You have to "redesign" it to the printer now...

Good luck!


问:
name 'Sequential' is not defined Python3 Keras
```<code>import numpy
import keras.models
import tensorflow
seed = 7

numpy.random.seed(seed)
dataset = numpy.genfromtxt("student-por.csv",delimiter=";")
X = dataset[:,0:33]
Y = dataset[:,8]
model = Sequential()
model.add(Dense(12, input_dim=8, init='uniform', activation='relu'))
model.add(Dense(8, init='uniform', activation='relu'))
model.add(Dense(1, init='uniform', activation='sigmoid'))
# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # Fit the model

scores = model.evaluate(X,Y)
print("%s: %s" % (model.metrics_names[1], scores[1]*100))
</code>```

Error :

#Exception 错误:
      #Using TensorFlow backend.
      #Traceback (most recent call last):
      #  File "test.py", line 11, in
      #    model = Sequential()
      #NameError: name 'Sequential' is not defined
      #很奇怪 他居然显示Sequential()有问题 我确认好多次我没打错了 引用库也不知道有什么问题

It is strange that he actually showed that there is a problem with Sequential (). I confirmed many times that I did not type the reference library incorrectly and did not know what was wrong.

答:
You should import it.</p>

```<code>from keras.models import Sequential
</code>```

Body:
import numpy
import keras.models
import tensorflow
seed = 7

numpy.random.seed(seed)
dataset = numpy.genfromtxt("student-por.csv",delimiter=";")
X = dataset[:,0:33]
Y = dataset[:,8]
model = Sequential()
model.add(Dense(12, input_dim=8, init='uniform', activation='relu'))
model.add(Dense(8, init='uniform', activation='relu'))
model.add(Dense(1, init='uniform', activation='sigmoid'))
# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # Fit the model

scores = model.evaluate(X,Y)
print("%s: %s" % (model.metrics_names[1], scores[1]*100))

Error :

#Exception 错误:
      #Using TensorFlow backend.
      #Traceback (most recent call last):
      #  File "test.py", line 11, in
      #    model = Sequential()
      #NameError: name 'Sequential' is not defined
      #很奇怪 他居然显示Sequential()有问题 我确认好多次我没打错了 引用库也不知道有什么问题

It is strange that he actually showed that there is a problem with Sequential (). I confirmed many times that I did not type the reference library incorrectly and did not know what was wrong.

Body:
You should import it.

from keras.models import Sequential


问:
I'm working creating a rental car billing calculator. I keep getting an error message saying that mileCharge is undefined. What am i missing?
```<code>mileCharge = totalMiles * 0.25
print(format(mileCharge, "%.2f"))
# This is the line that it kicking back the error message
</code>```

<p>I watched a youtube video which gave step by step instructions on this particular project and my code matches his exactly as far as I can tell.  His goes through fine while mine has an error message, </p>

```<code>    Traceback (most recent call last):
      File "rental_car.py", line 36, in <module>
        format(mileCharge, "%.2f")
    NameError: name 'mileCharge' is not defined
</code>```

答:
Are you sure if you have processed your first line in the console?

Your second line has an issue, but it is not name of the variable

check out this standalone code:

```<code>totalMiles = 5
mileCharge = totalMiles * 0.25
print(format(mileCharge, "2f"))
</code>```

notice that the format is changed, yours throws an error

Body:
mileCharge = totalMiles * 0.25
print(format(mileCharge, "%.2f"))
# This is the line that it kicking back the error message

I watched a youtube video which gave step by step instructions on this particular project and my code matches his exactly as far as I can tell.  His goes through fine while mine has an error message,

    Traceback (most recent call last):
      File "rental_car.py", line 36, in <module>
        format(mileCharge, "%.2f")
    NameError: name 'mileCharge' is not defined

Body:
Are you sure if you have processed your first line in the console?

Your second line has an issue, but it is not name of the variable

check out this standalone code:

totalMiles = 5
mileCharge = totalMiles * 0.25
print(format(mileCharge, "2f"))

notice that the format is changed, yours throws an error


问:
I'm getting a java.lang.StackOverflowError in my quicksort
This is basicly a simple quicksort whiche uses arraylists but I can't find the reason why I get stuck in an endless recursion. In the end the only reslut I get is a stack overflow error.</p>

```<code> List<Integer> quicksort(List<Integer> toSort){

        if(toSort.size() > 1){
            List<Integer> left = new ArrayList<>();
            List<Integer> right = new ArrayList<>();
            for(int i=0;i<toSort.size();i++){
                if(toSort.get(i) < toSort.get(toSort.size()/2))
                    left.add(toSort.get(i));
                else
                    right.add(toSort.get(i));
            }

            toSort = quicksort(left);
            toSort.addAll(quicksort(right));
            return toSort;

        }else
            return toSort;
    }
</code>```

答:
Consider you have 2 elements in your toSort List (when it's first called), [2, 1].

First, you create two Lists, left and right.

You then populate these based on the 'pivot'.  You use toSort.get(toSort.size() / 2); as the pivot.  toSort.size() = 2, so toSort.get(1) = 1 (from the List above) in this case.

You then add the elements to different Lists based on whether they are LESS THAN this value.  So that means you end up with (after the for loop has completed):

left = [], right = [2, 1].

You then call quickSort on both of these Lists again.  Second time round, when calling toSort.addAll(quicksort(right)); you're back in the exact state as your first call, and so the above just happens again.  Eventually this results in a stack overflow.

Your problem here is that you have mis-implemented the quicksort algorithm.  I'd recommend reviewing the pseudo-code for the quicksort algorithm that you based your implementation from, and working through smaller steps of it at a time (and then asking for help when you identify the smallest step that you're misunderstanding).

Body:
This is basicly a simple quicksort whiche uses arraylists but I can't find the reason why I get stuck in an endless recursion. In the end the only reslut I get is a stack overflow error.

 List<Integer> quicksort(List<Integer> toSort){

        if(toSort.size() > 1){
            List<Integer> left = new ArrayList<>();
            List<Integer> right = new ArrayList<>();
            for(int i=0;i<toSort.size();i++){
                if(toSort.get(i) < toSort.get(toSort.size()/2))
                    left.add(toSort.get(i));
                else
                    right.add(toSort.get(i));
            }

            toSort = quicksort(left);
            toSort.addAll(quicksort(right));
            return toSort;

        }else
            return toSort;
    }