问:
How to receive multipart files using Slim framework from android client?
I sent image file and content (text) using retrofit from android client and tried to get them in the server side but can not do that and the error is always : it is null.
Please how can I send image and receive it using #Retrofit and Slim framework?
If anyone can help, I will appreciate.

..............................................
Tried to send the image from android client like a multipart file and receive it with slim using method (getUploadedFiles) and it didn't work.

```<code> @Multipart
    @POST("createPostWithImage")
    Call<DefaultResponse> uploadTestPost(
            @Part("desc") RequestBody desc,
            @Part MultipartBody.Part image
    );
</code>```

```<code>$app-> post('/createPostWithImage', function(Request $request, Response $response) {

    $directory = __DIR__.'../photos/1';
    $uploadedFiles = $request->getUploadedFiles();
    $uploadedFile = $uploadedFiles['photo'];
    $uploadedFile->moveTo($directory);

});

</code>```

get the file which was sent from android client and save it into specific folder.

答:
```<code>$app->post('/file', function($request,$response) {
try{
     $directory = $this->get('upload_directory');
     $uploadedFiles = $request->getUploadedFiles();
     $uploadedFile = $uploadedFiles['example1'];
     $extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
    $basename =  mt_rand(10000000, 99999999);
    $uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $basename.'.'.$extension);
return $response->withJson(array('message' =>$uploadedFile),200);
}
catch(\Exception $ex){
       return $response->withJson(array('error' => $ex->getMessage()),422);
}
});

//minimal code to get started ...
</code>```

Body:
I sent image file and content (text) using retrofit from android client and tried to get them in the server side but can not do that and the error is always : it is null.
Please how can I send image and receive it using #Retrofit and Slim framework?
If anyone can help, I will appreciate.

..............................................
Tried to send the image from android client like a multipart file and receive it with slim using method (getUploadedFiles) and it didn't work.

 @Multipart
    @POST("createPostWithImage")
    Call<DefaultResponse> uploadTestPost(
            @Part("desc") RequestBody desc,
            @Part MultipartBody.Part image
    );

$app-> post('/createPostWithImage', function(Request $request, Response $response) {

    $directory = __DIR__.'../photos/1';
    $uploadedFiles = $request->getUploadedFiles();
    $uploadedFile = $uploadedFiles['photo'];
    $uploadedFile->moveTo($directory);

});

get the file which was sent from android client and save it into specific folder.


来源: stackexchange

问:
Add extra row to dataframe based on values of other rows
I have a dataframe with two rows of data. I would like to add a third row with values representing the difference between the previous two.

The data is in the following format:

```<code>Month   A   B   C   D   E   F
Jan     1   2   4   8   4   1
Feb     1   1   4   5   2   0
</code>```

I would like to add an extra row with a calculation to give the change across the two months:

```<code>Month   A   B   C   D   E   F
Jan     1   2   4   8   4   1
Feb     1   1   4   5   2   0
Change  0   1   0   3   2   1
</code>```

I've been looking at various functions to add additional rows including rbind and mutate but I'm struggling to perform the calculation in the newly created row.

答:
```<code>d1<-data.frame(Month = "Change" , df[1,-1] , df[2,-1])
newdf <- rbind(df,d1)
</code>```

This will create a new data-frame with what you require

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe with two rows of data. I would like to add a third row with values representing the difference between the previous two.

The data is in the following format:

Month   A   B   C   D   E   F
Jan     1   2   4   8   4   1
Feb     1   1   4   5   2   0

I would like to add an extra row with a calculation to give the change across the two months:

Month   A   B   C   D   E   F
Jan     1   2   4   8   4   1
Feb     1   1   4   5   2   0
Change  0   1   0   3   2   1

I've been looking at various functions to add additional rows including rbind and mutate but I'm struggling to perform the calculation in the newly created row.

Body:
d1<-data.frame(Month = "Change" , df[1,-1] , df[2,-1])
newdf <- rbind(df,d1)

This will create a new data-frame with what you require


问:
Pandas groupby scatter plot in a single plot
This is a followup question on this solution. There is automatic assignment of different colors when kind=line but for scatter plot that's not the case.

```<code>import pandas as pd
import matplotlib.pylab as plt
import numpy as np

# random df
df = pd.DataFrame(np.random.randint(0,10,size=(25, 3)), columns=['label','x','y'])

# plot groupby results on the same canvas
fig, ax = plt.subplots(figsize=(8,6))
df.groupby('label').plot(kind='scatter', x = "x", y = "y", ax=ax)
</code>```

There is a connected issue here. Is there any simple workaround for this?

Update:

When I try the solution recommended by @ImportanceOfBeingErnest for a label column with strings, its not working!

```<code>df = pd.DataFrame(np.random.randint(0,10,size=(5, 2)), columns=['x','y'])
df['label'] = ['yes','no','yes','yes','no']
fig, ax = plt.subplots(figsize=(8,6))
ax.scatter(x='x', y='y', c='label', data=df)
</code>```

It throws following error,

ValueError: Invalid RGBA argument: 'yes'

During handling of the above exception, another exception occurred:

答:
You can use sns:

```<code>df = pd.DataFrame(np.random.randint(0,10,size=(100, 2)), columns=['x','y'])
df['label'] = np.random.choice(['yes','no','yes','yes','no'], 100)
fig, ax = plt.subplots(figsize=(8,6))
sns.scatterplot(x='x', y='y', hue='label', data=df)
plt.show()
</code>```

Output:

Another option is as what suggested in the comment: Map value to number, by categorical type:

```<code>fig, ax = plt.subplots(figsize=(8,6))
ax.scatter(df.x, df.y, c = pd.Categorical(df.label).codes, cmap='tab20b')
plt.show()
</code>```

Output:

Body:
This is a followup question on this solution. There is automatic assignment of different colors when kind=line but for scatter plot that's not the case.

import pandas as pd
import matplotlib.pylab as plt
import numpy as np

# random df
df = pd.DataFrame(np.random.randint(0,10,size=(25, 3)), columns=['label','x','y'])

# plot groupby results on the same canvas
fig, ax = plt.subplots(figsize=(8,6))
df.groupby('label').plot(kind='scatter', x = "x", y = "y", ax=ax)

There is a connected issue here. Is there any simple workaround for this?

Update:

When I try the solution recommended by @ImportanceOfBeingErnest for a label column with strings, its not working!

df = pd.DataFrame(np.random.randint(0,10,size=(5, 2)), columns=['x','y'])
df['label'] = ['yes','no','yes','yes','no']
fig, ax = plt.subplots(figsize=(8,6))
ax.scatter(x='x', y='y', c='label', data=df)

It throws following error,

ValueError: Invalid RGBA argument: 'yes'

During handling of the above exception, another exception occurred:

Body:
You can use sns:

df = pd.DataFrame(np.random.randint(0,10,size=(100, 2)), columns=['x','y'])
df['label'] = np.random.choice(['yes','no','yes','yes','no'], 100)
fig, ax = plt.subplots(figsize=(8,6))
sns.scatterplot(x='x', y='y', hue='label', data=df)
plt.show()

Output:

Another option is as what suggested in the comment: Map value to number, by categorical type:

fig, ax = plt.subplots(figsize=(8,6))
ax.scatter(df.x, df.y, c = pd.Categorical(df.label).codes, cmap='tab20b')
plt.show()

Output:


问:
CSS media query looks good locally but not when hosted online
Locally my banner-home2.png looks as I need it.

However, when uploaded it's size gets bigger. (I'm hosting this on heroku, but the css file is on Amazon).

And I can see that in these Codepen, it also look wrong (bigger than it should be):

Online version:

stickersgallito.pe:

Local version (correct size):

Codepen: https://codepen.io/anon/pen/EzOONJ

These are my media queries on Amazon:

```<code><link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/home.css">
</code>```

home.css (media queries):

```<code>.my_header_bg_color {

    /*background-color: #4FB99F;*/
    /*background-color: #00ADB5;*/
    /*background-color: #6BB983;*/
    background-color: #00AD80;
}

/* standard media queries breakpoints */

@media (min-width: 320px) and (max-width: 480px) {
    /* smartphones, iPhone, portrait 480x320 phones */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .productos_finales_home img {

        padding-bottom: 15px;
    }

    .my_home_banner_image {
        bottom: 0;
        top: 0;
        position: relative;
        z-index: 0;
        width: 60%;
        display: block;
        margin-right: auto;
        margin-left: 165px;
    }

    /*.my_home_banner_image {*/
    /*display: none;*/
    /*}*/
    .my_home_banner_title {
        color: white;
        font-size: 36px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        text-decoration: none;
        background-color: #969696;
        display: inline-block;
        text-align: center;
        vertical-align: middle;
        cursor: pointer;
        color: #fff;
        font-weight: 700;
        font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
        text-shadow: 0 -1px 0 rgba(0, 0, 0, .25);
        letter-spacing: 0;
        line-height: 1.2;
        -webkit-font-smoothing: antialiased;
        -webkit-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -ms-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -moz-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -o-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        background-image: linear-gradient(to bottom, rgba(255, 255, 255, .09) 0%, rgba(0, 0, 0, .09) 100%);
        font-size: 1.4rem;
        padding: 22px 30px;
        border-radius: 6px;
        border: none;
    }

.my_home_banner_left {
    margin-left: 10px;
    z-index: 100;
}

.stickers_referenciales {
    margin-bottom: 5px;
}

}

@media (min-width: 481px) {
    /* portrait e-readers (Nook/Kindle), smaller tablets @ 600 or @ 640 wide. */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 40%;
        display: block;
        margin-right: auto;
        margin-left: 185px;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

}

@media (min-width: 641px) {
    /* portrait tablets, portrait iPad, landscape e-readers, landscape 800x480 or 854x480 phones */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 70%;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

    .my_home_banner_lef_text {
        margin-left: 10px;
        z-index: 100;
    }

}

@media (min-width: 961px) {
    /* tablet, landscape iPad, lo-res laptops ands desktops */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 60%;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

}

@media (min-width: 1025px) {
    /* big landscape tablets, laptops, and desktops */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 55%;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

    .subscribe_field {
        width: 350px;
    }

}

@media (min-width: 1281px) {
    /* hi-res laptops and desktops */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 70%;
    }

    /*.my_home_banner_image_left {*/
    /*display: none;*/
    /*}*/
    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

    .subscribe_field {
        width: 350px;
    }
}

.center-video {
    margin: 0 auto;
    width: 400px;
}
</code>```

答:
just modify this .my_home_banner_image class add top and reduce the width in your website it will works

```<code>@media (min-width: 1281px)
.my_home_banner_image {
    bottom: 0;
    position: absolute;
    right: -0px;
    bottom: 0;
    z-index: 0;
    width: 55%;
    top: 25px;
}
</code>```

Body:
Locally my banner-home2.png looks as I need it.

However, when uploaded it's size gets bigger. (I'm hosting this on heroku, but the css file is on Amazon).

And I can see that in these Codepen, it also look wrong (bigger than it should be):

Online version:

stickersgallito.pe:

Local version (correct size):

Codepen: https://codepen.io/anon/pen/EzOONJ

These are my media queries on Amazon:

<link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/home.css">

home.css (media queries):

.my_header_bg_color {

    /*background-color: #4FB99F;*/
    /*background-color: #00ADB5;*/
    /*background-color: #6BB983;*/
    background-color: #00AD80;
}

/* standard media queries breakpoints */

@media (min-width: 320px) and (max-width: 480px) {
    /* smartphones, iPhone, portrait 480x320 phones */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .productos_finales_home img {

        padding-bottom: 15px;
    }

    .my_home_banner_image {
        bottom: 0;
        top: 0;
        position: relative;
        z-index: 0;
        width: 60%;
        display: block;
        margin-right: auto;
        margin-left: 165px;
    }

    /*.my_home_banner_image {*/
    /*display: none;*/
    /*}*/
    .my_home_banner_title {
        color: white;
        font-size: 36px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        text-decoration: none;
        background-color: #969696;
        display: inline-block;
        text-align: center;
        vertical-align: middle;
        cursor: pointer;
        color: #fff;
        font-weight: 700;
        font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
        text-shadow: 0 -1px 0 rgba(0, 0, 0, .25);
        letter-spacing: 0;
        line-height: 1.2;
        -webkit-font-smoothing: antialiased;
        -webkit-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -ms-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -moz-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -o-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        background-image: linear-gradient(to bottom, rgba(255, 255, 255, .09) 0%, rgba(0, 0, 0, .09) 100%);
        font-size: 1.4rem;
        padding: 22px 30px;
        border-radius: 6px;
        border: none;
    }

.my_home_banner_left {
    margin-left: 10px;
    z-index: 100;
}

.stickers_referenciales {
    margin-bottom: 5px;
}

}

@media (min-width: 481px) {
    /* portrait e-readers (Nook/Kindle), smaller tablets @ 600 or @ 640 wide. */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 40%;
        display: block;
        margin-right: auto;
        margin-left: 185px;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

}

@media (min-width: 641px) {
    /* portrait tablets, portrait iPad, landscape e-readers, landscape 800x480 or 854x480 phones */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 70%;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

    .my_home_banner_lef_text {
        margin-left: 10px;
        z-index: 100;
    }

}

@media (min-width: 961px) {
    /* tablet, landscape iPad, lo-res laptops ands desktops */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 60%;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

}

@media (min-width: 1025px) {
    /* big landscape tablets, laptops, and desktops */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 55%;
    }

    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

    .subscribe_field {
        width: 350px;
    }

}

@media (min-width: 1281px) {
    /* hi-res laptops and desktops */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .my_home_banner_image {

        bottom: 0;
        position: absolute;
        right: -0px;
        bottom: 0;
        z-index: 0;
        width: 70%;
    }

    /*.my_home_banner_image_left {*/
    /*display: none;*/
    /*}*/
    .my_home_banner_title {
        color: white;
        font-size: 50px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        margin-bottom: 100px;
    }

    .my_home_banner_left {
        margin-left: 20px;
        z-index: 100;
    }

    .subscribe_field {
        width: 350px;
    }
}

.center-video {
    margin: 0 auto;
    width: 400px;
}

Body:
just modify this .my_home_banner_image class add top and reduce the width in your website it will works

@media (min-width: 1281px)
.my_home_banner_image {
    bottom: 0;
    position: absolute;
    right: -0px;
    bottom: 0;
    z-index: 0;
    width: 55%;
    top: 25px;
}


问:
MacOs zip file - different result when double click and running unzip command
The following folder is compressed using Compress-Archive on a Windows Server:

```
-folder
 |
 - folder1
 | - file1.txt
 |
 - folder2
 | - file2.txt
 |
 - file3.txt<br>
```

When folder is unzipped, the folder structure is correct on Windows and on Mac (while using unzip command in the terminal)

But on Mac when I go to finder, and double click on the file, I get the following folder structure:

```
-folder
 |
 - file1.txt
 - file2.txt
 - file3.txt
```

答:
The problem was when the file was created.
It was not related to MacOs issue but with certain path length known issue in windows

Body:
The following folder is compressed using Compress-Archive on a Windows Server:

-folder
 |
 - folder1
 | - file1.txt
 |
 - folder2
 | - file2.txt
 |
 - file3.txt

When folder is unzipped, the folder structure is correct on Windows and on Mac (while using unzip command in the terminal)

But on Mac when I go to finder, and double click on the file, I get the following folder structure:

-folder
 |
 - file1.txt
 - file2.txt
 - file3.txt


问:
How do I get the current time in milliseconds in Python?
How do I get the current time in milliseconds in Python?</p>

答:
For Python 3.7+, time.time_ns() gives the time passed in nanoseconds since the epoch.

This gives time in milliseconds as an integer:

```<code>import time

ms = time.time_ns() // 1_000_000
</code>```

Body:
For Python 3.7+, time.time_ns() gives the time passed in nanoseconds since the epoch.

This gives time in milliseconds as an integer:

import time

ms = time.time_ns() // 1_000_000


问:
Why push shows argument of type 'any[]' is not assignable to parameter of type 'never' error?
In this code i get the fallowing error:

Argument of type 'any[]' is not assignable to parameter of type
  'never'

```<code>var markers: [];
this.Getlapoints(this.map.getCenter(), 500000).then(data => {
  for (var key in data) {
    Leaflet.marker(data[key].location, //{ icon: greenIcon            }
    ).addTo(this.map).bindPopup(data[key].caption);
    // markers.push(data[key].location.lat,data[key].location.lng);
    // markers.push(data[key].location);

    var lat = data[key].location.lat;
    var lng = data[key].location.lng;
    markers.push([lat, lng]);
  }
  console.log(markers);
});
</code>```

答:
Change this :

```<code>const a = [];
</code>```

By this :

```<code>const a = Array();
</code>```

Body:
In this code i get the fallowing error:

Argument of type 'any[]' is not assignable to parameter of type
  'never'

var markers: [];
this.Getlapoints(this.map.getCenter(), 500000).then(data => {
  for (var key in data) {
    Leaflet.marker(data[key].location, //{ icon: greenIcon            }
    ).addTo(this.map).bindPopup(data[key].caption);
    // markers.push(data[key].location.lat,data[key].location.lng);
    // markers.push(data[key].location);

    var lat = data[key].location.lat;
    var lng = data[key].location.lng;
    markers.push([lat, lng]);
  }
  console.log(markers);
});

Body:
Change this :

const a = [];

By this :

const a = Array();


问:
How to change the position of the object when the window size is changed?
As in the title. I would like objects moving on the board to change position propositionally to change the size of the window. How to do it?</p>

答:
Let's assume that you are working with a JFrame.

You can get the dimensions of the JFrame as follows:

```<code>Dimension size = frame.getBounds().getSize()
double height = size.getHeight();
double width = size.getWidth();
</code>```

Then you can make your object move by a percentage of those values.

Whenever the window's size changes, an event is triggered.
You can update the dimensions whenever that event is triggered with a ComponentListener.

```<code>class ResizeListener implements ComponentListener {

    public void componentHidden(ComponentEvent e) {}
    public void componentMoved(ComponentEvent e) {}
    public void componentShown(ComponentEvent e) {}

    public void componentResized(ComponentEvent e) {
        Dimension newSize = e.getComponent().getBounds().getSize();
    }
}
</code>```

Do not forget to add the ComponentListener to your JFrame.

Sources: How to check current window size in java swing?

Body:
Let's assume that you are working with a JFrame.

You can get the dimensions of the JFrame as follows:

Dimension size = frame.getBounds().getSize()
double height = size.getHeight();
double width = size.getWidth();

Then you can make your object move by a percentage of those values.

Whenever the window's size changes, an event is triggered.
You can update the dimensions whenever that event is triggered with a ComponentListener.

class ResizeListener implements ComponentListener {

    public void componentHidden(ComponentEvent e) {}
    public void componentMoved(ComponentEvent e) {}
    public void componentShown(ComponentEvent e) {}

    public void componentResized(ComponentEvent e) {
        Dimension newSize = e.getComponent().getBounds().getSize();
    }
}

Do not forget to add the ComponentListener to your JFrame.

Sources: How to check current window size in java swing?


问:
How to sent id from one page to another when click on submit?
I have a database which consists of question_id, question, and options. Where I'll display the question and options. When the user clicked on submit I want to store the option they clicked and the question_id.
I am able to store the option they clicked but want to know how to store the question_id.

```<code>$user_email = $_SESSION['email'];
$query1="SELECT * FROM votes WHERE user_email='$user_email'";
$query2="SELECT * FROM poll_question WHERE status='1'";
$fetch2 = mysqli_query($con,$query2);
<html>
  <head>
    <body>
      <div class="container">
        <br />
        <br />
        <br />
        <div class="row">
          <div class="col-md-6">
          <?

            while( $row2 = mysqli_fetch_array($fetch2))
            {
             ?>
              <form method="post" class="poll_form">
                <h3><?echo $row2['question']?>?</h3>
                <br />
                <div class="radio">
                 <label><h4><input type="radio" name="poll_option" class="poll_option" value=<?echo $row2['option1']?> /><?echo $row2['option1']?></h4></label>
                </div>
                <div class="radio">
                 <label><h4><input type="radio" name="poll_option" class="poll_option" value=<?echo $row2['option1']?> /> <?echo $row2['option2']?></h4></label>
                </div>

                <br />
                <?php
                  if( $count >0)
                    {  ?>
                      <button disabled="disabled" alt="<?php echo $row2['question_id']; ?>" rel="<?php echo $user_email; ?>" class="btn btn-primary poll_option" title="<?php echo $ip; ?>">Submit</button>
                       <h>You selected : <? echo $row1['vote_option']; ?></h>
                       <br>
                       <p id="demo"></p>
                       <?php
                    }
                  else
                    { ?>
                        <button  alt="<?php echo $row2['question_id']; ?>" rel="<?php echo $user_email; ?>" class="btn btn-primary poll_option" title="<?php echo $ip; ?>">Submit</button>
                      <?
                    }
                    ?>
                </form>
           <? }
          } ?>
      <br />
  </div>
 </div>
   <br />
   <br />
   <br />
</div>
</body>
<script type="text/javascript">
    $(document).ready(function(){

        $(".poll_form").submit(function(event){
            event.preventDefault();   //prevents the form from submitting normally
                var poll_option = '';

                $('button.poll_option').each(function(){

                     if($(this).prop("checked"))
                         {
                             poll_option = $(this).val();

                             var option=poll_option;

                         }

                     var url = '<?php echo SITE_URL; ?>';
                     });
                $.post("poll_vote.php",$('.poll_form').serialize(),
                function(data)
                    {
                      if(data=="User Created Success"){

                           window.setTimeout(function () {
                                location.href ="<?php echo SITE_URL; ?>poll.php";
                            }, 100);
                      }
                      else{

                          $("#result").html(data);
                      }
                     }
                  );
             //to reset form data
        });
    });
    <? } ?>
    </script>

</html>
</code>```

Using th below function I am sending the poll_option to other where I kept the inset operation. Now I want to send the question_id also

答:
Create a hidden input field in your form.

```<code><input type="hidden" id="question_id" name="question_id" value="<?= $row2['question_id'] ?>">
</code>```

PHP solution:

In this case your question_id will be included in the POST.

You can then access it by calling $_POST['question_id'].

Jquery solution:

In Jquery you can also access it by:

```<code>$("#question_id").val();
</code>```

Body:
I have a database which consists of question_id, question, and options. Where I'll display the question and options. When the user clicked on submit I want to store the option they clicked and the question_id.
I am able to store the option they clicked but want to know how to store the question_id.

$user_email = $_SESSION['email'];
$query1="SELECT * FROM votes WHERE user_email='$user_email'";
$query2="SELECT * FROM poll_question WHERE status='1'";
$fetch2 = mysqli_query($con,$query2);

          <?

            while( $row2 = mysqli_fetch_array($fetch2))
            {
             ?>
              <form method="post" class="poll_form">

<?echo $row2['question']?>?

<input type="radio" name="poll_option" class="poll_option" value=<?echo $row2['option1']?> /><?echo $row2['option1']?>

<input type="radio" name="poll_option" class="poll_option" value=<?echo $row2['option1']?> /> <?echo $row2['option2']?>

                <?php
                  if( $count >0)
                    {  ?>
                      <button disabled="disabled" alt="<?php echo $row2['question_id']; ?>" rel="<?php echo $user_email; ?>" class="btn btn-primary poll_option" title="<?php echo $ip; ?>">Submit</button>
                       <h>You selected : <? echo $row1['vote_option']; ?></h>

                       <?php
                    }
                  else
                    { ?>
                        <button  alt="<?php echo $row2['question_id']; ?>" rel="<?php echo $user_email; ?>" class="btn btn-primary poll_option" title="<?php echo $ip; ?>">Submit</button>
                      <?
                    }
                    ?>
                </form>
           <? }
          } ?>

Using th below function I am sending the poll_option to other where I kept the inset operation. Now I want to send the question_id also

Body:
Create a hidden input field in your form.

<input type="hidden" id="question_id" name="question_id" value="<?= $row2['question_id'] ?>">

PHP solution:

In this case your question_id will be included in the POST.

You can then access it by calling $_POST['question_id'].

Jquery solution:

In Jquery you can also access it by:

$("#question_id").val();


问:
Effective stdin reading c programming
can anyone help me optimalize code for reading standard input. Here it is what I have now:</p>

```<code>unsigned char *msg;
size_t msgBytes = 0;
size_t inputMsgBuffLen = 1024;
if ( (msg = (unsigned char *) malloc(sizeof(unsigned char) * inputMsgBuffLen) ) == NULL ) {
    quitErr("Couldn't allocate memmory!", EXIT_FAILURE);
}
for (int c; (c = getchar()) != EOF; msgBytes++) {
    if (msgBytes >= (inputMsgBuffLen)) {
        inputMsgBuffLen <<= 1;
        if ( ( msg = (unsigned char *)realloc(msg, sizeof(unsigned char) * inputMsgBuffLen) ) == NULL) {
            free(msg);
            quitErr("Couldn't allocate more memmory!", EXIT_FAILURE);
        }
    }
    msg[msgBytes] = (unsigned char)c;
}
</code>```

答:
Question: are you reading binary or text data from stdin?  If text, why are you using unsigned char?

Some advice:

Drop all the casts on malloc and realloc; they aren't necessary and clutter up the code;

Instead of repeatedly calling getchar, use fread or fgets (depending on whether you're reading binary or text);

Remember that realloc can potentially return NULL, so you want to assign the result to a temporary value, otherwise you'll lose track of the original pointer and wind up leaking memory;

Use a statically allocated buffer for each chunk of input;

Use sizeof on objects, not types; it's a little cleaner, and it protects you in case the types change (e.g., T *p = malloc(sizeof *p * number_of_elements);.

Cleaned-up version assuming you intend to use unsigned chars:

```<code>#define inputBufSize 1024

unsigned char *msg = NULL;
size_t msgBytes = 0;
size_t inputMsgBufSize = 0;
unsigned char inputBuffer[inputBufSize];
size_t bytesRead = 0;

while ((bytesRead = fread(
    inputBuffer,            // target buffer
    sizeof inputBuffer,     // number of bytes in buffer
    1,                      // number of buffer-sized elements to read
    stdin)) > 0)
{
  unsigned char *tmp = realloc(msg, inputMsgBufSize + bytesRead));
  if (tmp)
  {
    msg = tmp;
    memmove(&msg[inputMsgBufSize], inputBuffer, bytesRead);
    inputMsgBufSize += bytesRead;
  }
  else
  {
    printf("Ran out of memory\n");
    free(msg);
    break;
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Effective stdin reading c programming

Body:
can anyone help me optimalize code for reading standard input. Here it is what I have now:

unsigned char *msg;
size_t msgBytes = 0;
size_t inputMsgBuffLen = 1024;
if ( (msg = (unsigned char *) malloc(sizeof(unsigned char) * inputMsgBuffLen) ) == NULL ) {
    quitErr("Couldn't allocate memmory!", EXIT_FAILURE);
}
for (int c; (c = getchar()) != EOF; msgBytes++) {
    if (msgBytes >= (inputMsgBuffLen)) {
        inputMsgBuffLen <<= 1;
        if ( ( msg = (unsigned char *)realloc(msg, sizeof(unsigned char) * inputMsgBuffLen) ) == NULL) {
            free(msg);
            quitErr("Couldn't allocate more memmory!", EXIT_FAILURE);
        }
    }
    msg[msgBytes] = (unsigned char)c;
}

Body:
Question: are you reading binary or text data from stdin?  If text, why are you using unsigned char?

Some advice:

Drop all the casts on malloc and realloc; they aren't necessary and clutter up the code;

Instead of repeatedly calling getchar, use fread or fgets (depending on whether you're reading binary or text);

Remember that realloc can potentially return NULL, so you want to assign the result to a temporary value, otherwise you'll lose track of the original pointer and wind up leaking memory;

Use a statically allocated buffer for each chunk of input;

Use sizeof on objects, not types; it's a little cleaner, and it protects you in case the types change (e.g., T *p = malloc(sizeof *p * number_of_elements);.

Cleaned-up version assuming you intend to use unsigned chars:

#define inputBufSize 1024

unsigned char *msg = NULL;
size_t msgBytes = 0;
size_t inputMsgBufSize = 0;
unsigned char inputBuffer[inputBufSize];
size_t bytesRead = 0;

while ((bytesRead = fread(
    inputBuffer,            // target buffer
    sizeof inputBuffer,     // number of bytes in buffer
    1,                      // number of buffer-sized elements to read
    stdin)) > 0)
{
  unsigned char *tmp = realloc(msg, inputMsgBufSize + bytesRead));
  if (tmp)
  {
    msg = tmp;
    memmove(&msg[inputMsgBufSize], inputBuffer, bytesRead);
    inputMsgBufSize += bytesRead;
  }
  else
  {
    printf("Ran out of memory\n");
    free(msg);
    break;
  }
}


问:
Numpy vectorization: Find intersection between list and list of lists
I am trying to find the intersection between a list and a list of lists. This is trivially solved with a simple for loop:

```<code>def find_intersec(x,y):
    result = []

    for i in range(len(y)):
        if set(x).intersection(set(y[i])):
            result.append(y[i])

    return(result)

x = [1,2,3,4,5,6]
y = [[1,2,3], [4,5,6], [9,10,11]]

find_intersec(x,y)
</code>```

How can I change the above into a numpy vectorization solution? I have tried numpy.intersect1d() with no success.

答:
As you mentioned, numpy.intersect1d() can be used:

```<code>import numpy as np

x = [1,2,3,4,5,6]
y = [[1,2,3], [4,5,6], [9,10,11]]

intersec = [np.intersect1d(i, x) for i in y if len(np.intersect1d(i, x)) > 0]
</code>```

result:

```<code>[array([1, 2, 3]), array([4, 5, 6])]
</code>```

Body:
I am trying to find the intersection between a list and a list of lists. This is trivially solved with a simple for loop:

def find_intersec(x,y):
    result = []

    for i in range(len(y)):
        if set(x).intersection(set(y[i])):
            result.append(y[i])

    return(result)

x = [1,2,3,4,5,6]
y = [[1,2,3], [4,5,6], [9,10,11]]

find_intersec(x,y)

How can I change the above into a numpy vectorization solution? I have tried numpy.intersect1d() with no success.

Body:
As you mentioned, numpy.intersect1d() can be used:

import numpy as np

x = [1,2,3,4,5,6]
y = [[1,2,3], [4,5,6], [9,10,11]]

intersec = [np.intersect1d(i, x) for i in y if len(np.intersect1d(i, x)) > 0]

result:

[array([1, 2, 3]), array([4, 5, 6])]


问:
Suppress external command error output from Powershell $error
In my profile, I've customised the prompt via the prompt function to embed git branch information:

```<code>function prompt
{
    $prefix = ""
    if ((test-path ".git") -or (test-path ".gitdir") -or ((git rev-parse --is-inside-work-tree 2> $null) -eq "true")) {
        $prefix = "[git:" + (& git symbolic-ref --short HEAD) + "]"
    }

    write-host "PS $prefix $(get-location) >" -nonewline -foregroundcolor DarkMagenta
    return " "
}
</code>```

The problem however is that when I'm outside of a git tree, the git rev-parse part of the check inserts an error into $error even though I'm redirecting errors to $null.

This means that $error gets polluted with the following error, as it is generated every time the prompt renders:

```<code>git : fatal: Not a git repository (or any of the parent directories): .git
At C:\temp\prompt.ps1:4 char:64
    + ... ".gitdir") -or ((git rev-parse --is-inside-work-tree 2> $null) -eq "t ...
    +                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (fatal: Not a gi...ectories): .git:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
</code>```

Running interactively I've noticed that the 2> $null does suppress the error to the console, but the error still appears in $error:

```<code>PS C:\temp> $error
PS C:\temp> git rev-parse --is-inside-work-tree 2> $null
PS C:\temp> $error
git : fatal: Not a git repository (or any of the parent directories): .git
At line:1 char:1
+ git rev-parse --is-inside-work-tree 2> $null
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (fatal: Not a gi...ectories): .git:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

PS C:\temp>
</code>```

I've tried wrapping the command in try {...} catch {}, and also using invoke-command with an erroraction of ignore, both with no luck:

```<code>PS c:\temp> $error.clear()
PS c:\temp> $error
PS c:\temp> invoke-command -scriptblock { git rev-parse --is-inside-work-tree 2> $null } -erroraction ignore
PS c:\temp> $error
git : fatal: Not a git repository (or any of the parent directories): .git
At line:1 char:31
+ ... d -scriptblock { git rev-parse --is-inside-work-tree 2> $null } -erro ...
+                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (fatal: Not a gi...ectories): .git:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

PS c:\temp> $error.clear()
PS c:\temp> $error
PS c:\temp> try { git rev-parse --is-inside-work-tree 2> $null } catch { }
PS c:\temp> $error
git : fatal: Not a git repository (or any of the parent directories): .git
At line:1 char:7
+ try { git rev-parse --is-inside-work-tree 2> $null } catch { }
+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (fatal: Not a gi...ectories): .git:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

PS c:\temp>
</code>```

How can I suppress this error from adding to $error so it stays clean?

答:
Unfortunately, as of PowerShell Core 6.2.1 / Windows PowerShell v5.1, using 2>$null to suppress stderr output from an external program unexpectedly still takes a detour via Powershell's error stream (stream  2), so the output is still recorded in $Error. This known problem is described in this GitHub issue.

As a workaround, you can call git via cmd /c (or sh -c on Unix) and let it do the redirection:

```<code># Windows
cmd /c 'git rev-parse --is-inside-work-tree 2>NUL'

# Linux, macOS
sh -c 'git rev-parse --is-inside-work-tree 2>/dev/null'
</code>```

As you state, this will correctly pass git's exit code through so you can determine success via $LASTEXITCODE afterwards.

Body:
In my profile, I've customised the prompt via the prompt function to embed git branch information:

function prompt
{
    $prefix = ""
    if ((test-path ".git") -or (test-path ".gitdir") -or ((git rev-parse --is-inside-work-tree 2> $null) -eq "true")) {
        $prefix = "[git:" + (& git symbolic-ref --short HEAD) + "]"
    }

    write-host "PS $prefix $(get-location) >" -nonewline -foregroundcolor DarkMagenta
    return " "
}

The problem however is that when I'm outside of a git tree, the git rev-parse part of the check inserts an error into $error even though I'm redirecting errors to $null.

This means that $error gets polluted with the following error, as it is generated every time the prompt renders:

git : fatal: Not a git repository (or any of the parent directories): .git
At C:\temp\prompt.ps1:4 char:64
    + ... ".gitdir") -or ((git rev-parse --is-inside-work-tree 2> $null) -eq "t ...
    +                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (fatal: Not a gi...ectories): .git:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Running interactively I've noticed that the 2> $null does suppress the error to the console, but the error still appears in $error:

PS C:\temp> $error
PS C:\temp> git rev-parse --is-inside-work-tree 2> $null
PS C:\temp> $error
git : fatal: Not a git repository (or any of the parent directories): .git
At line:1 char:1
+ git rev-parse --is-inside-work-tree 2> $null
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (fatal: Not a gi...ectories): .git:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

PS C:\temp>

I've tried wrapping the command in try {...} catch {}, and also using invoke-command with an erroraction of ignore, both with no luck:

PS c:\temp> $error.clear()
PS c:\temp> $error
PS c:\temp> invoke-command -scriptblock { git rev-parse --is-inside-work-tree 2> $null } -erroraction ignore
PS c:\temp> $error
git : fatal: Not a git repository (or any of the parent directories): .git
At line:1 char:31
+ ... d -scriptblock { git rev-parse --is-inside-work-tree 2> $null } -erro ...
+                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (fatal: Not a gi...ectories): .git:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

PS c:\temp> $error.clear()
PS c:\temp> $error
PS c:\temp> try { git rev-parse --is-inside-work-tree 2> $null } catch { }
PS c:\temp> $error
git : fatal: Not a git repository (or any of the parent directories): .git
At line:1 char:7
+ try { git rev-parse --is-inside-work-tree 2> $null } catch { }
+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (fatal: Not a gi...ectories): .git:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

PS c:\temp>

How can I suppress this error from adding to $error so it stays clean?

Body:
Unfortunately, as of PowerShell Core 6.2.1 / Windows PowerShell v5.1, using 2>$null to suppress stderr output from an external program unexpectedly still takes a detour via Powershell's error stream (stream  2), so the output is still recorded in $Error. This known problem is described in this GitHub issue.

As a workaround, you can call git via cmd /c (or sh -c on Unix) and let it do the redirection:

# Windows
cmd /c 'git rev-parse --is-inside-work-tree 2>NUL'

# Linux, macOS
sh -c 'git rev-parse --is-inside-work-tree 2>/dev/null'

As you state, this will correctly pass git's exit code through so you can determine success via $LASTEXITCODE afterwards.


问:
Node.js Auto Increment E11000 duplicate key error collection
I'm struggling with Error E11000 duplicate key error collection, I have a schema with another sub-schema array and when I try to insert my schema with the empty array I allways get this error. I tried to set it undefined on pre-save without sucesss...  I have deleted my schem from mongoDB and its indexes. The error appears after I insted **autoincrement **in Marker schema.

City Schema:

```<code>            let mongoose = require('mongoose');
            let autoIncrement = require('mongoose-auto-increment');
            let Marker = require('./marker');

            var MarkerSchema = require('mongoose').model('marker').schema;

            //City Schema
            //status : 1 Ok, 2 Hidden, 3 Deleted

            let citySchema = mongoose.Schema({
               id: {
                type: Number,
                required: true
              },
              name: {
                type: String,
                required: true
              },
              status: {
                type: Number,
                required: true
              },

              coordinates: {
                latitude: {
                  type: Number,
                  required: true
                },
                longitude: {
                  type: Number,
                  required: true
                }
              },
              markers: [MarkerSchema]

            });

            citySchema.pre('save', function (cb) {
              console.log('pre save');
              if (this.markers && this.markers.length === 0) {
              this.markers = undefined;
              }
              cb();
            });

            citySchema.plugin(autoIncrement.plugin, {
                model: 'city',
                field: 'id',
                startAt: 1,
                incrementBy: 1
            });

            let City = module.exports = mongoose.model('city', citySchema);
</code>```

marker schema

```<code>            let mongoose = require('mongoose');
            let autoIncrement = require('mongoose-auto-increment');

            let markerSchema = mongoose.Schema({
                status: {
                    type: Number,
                    required: true
                  },
                description: {
                  type: String,
                  required: true
                },
                coordinates: {
                    latitude: {
                      type: Number,
                      required: true
                    },
                    longitude: {
                      type: Number,
                      required: true
                    }
                }
            });

            markerSchema.plugin(autoIncrement.plugin, {
                model: 'marker',
                field: 'id',
                startAt: 1,
                incrementBy: 1
            });

            let Marker = module.exports = mongoose.model('marker', markerSchema);
</code>```

答:
Having the same issue ...
Rather sure this is caused by the mongoose-auto-increment module...</p>

Body:
I'm struggling with Error E11000 duplicate key error collection, I have a schema with another sub-schema array and when I try to insert my schema with the empty array I allways get this error. I tried to set it undefined on pre-save without sucesss...  I have deleted my schem from mongoDB and its indexes. The error appears after I insted **autoincrement **in Marker schema.

City Schema:

            let mongoose = require('mongoose');
            let autoIncrement = require('mongoose-auto-increment');
            let Marker = require('./marker');

            var MarkerSchema = require('mongoose').model('marker').schema;

            //City Schema
            //status : 1 Ok, 2 Hidden, 3 Deleted

            let citySchema = mongoose.Schema({
               id: {
                type: Number,
                required: true
              },
              name: {
                type: String,
                required: true
              },
              status: {
                type: Number,
                required: true
              },

              coordinates: {
                latitude: {
                  type: Number,
                  required: true
                },
                longitude: {
                  type: Number,
                  required: true
                }
              },
              markers: [MarkerSchema]

            });

            citySchema.pre('save', function (cb) {
              console.log('pre save');
              if (this.markers && this.markers.length === 0) {
              this.markers = undefined;
              }
              cb();
            });

            citySchema.plugin(autoIncrement.plugin, {
                model: 'city',
                field: 'id',
                startAt: 1,
                incrementBy: 1
            });

            let City = module.exports = mongoose.model('city', citySchema);

marker schema

            let mongoose = require('mongoose');
            let autoIncrement = require('mongoose-auto-increment');

            let markerSchema = mongoose.Schema({
                status: {
                    type: Number,
                    required: true
                  },
                description: {
                  type: String,
                  required: true
                },
                coordinates: {
                    latitude: {
                      type: Number,
                      required: true
                    },
                    longitude: {
                      type: Number,
                      required: true
                    }
                }
            });

            markerSchema.plugin(autoIncrement.plugin, {
                model: 'marker',
                field: 'id',
                startAt: 1,
                incrementBy: 1
            });

            let Marker = module.exports = mongoose.model('marker', markerSchema);


问:
VSCode pipenv run REPL program receives environment activation causing initial syntax error
The auto-sourcing/enable of Python environment is a great feature! But I don't know how to disable it for tasks. Pyenv for example automatically activates and runs commands in its virtualenv, so I end up having errors for my pipenv run commands.
I've made a little GIF with the behavior.

For reference, this is my .vscode/tasks.json file

```<code>{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [{
        "label": "Run IPython Shell",
        "problemMatcher": [],
        "type": "shell",
        "command": "pipenv run ipython",
        "presentation": {
            "echo": true,
            "reveal": "always",
            "focus": true,
            "panel": "shared",
            "showReuseMessage": true,
            "clear": false
        }
    }]
}
</code>```

And the output is the following:

```<code>> Executing task: pipenv run ipython <

source /Users/nahuel/.virtualenvs/pysrv-RjlHvHY5/bin/activate
Python 3.6.6 (default, Aug  6 2018, 12:14:58)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.1.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: source /Users/nahuel/.virtualenvs/pysrv-RjlHvHY5/bin/activate
  File "<ipython-input-1-944ce73c2717>", line 1
    source /Users/nahuel/.virtualenvs/pysrv-RjlHvHY5/bin/activate
                         ^
SyntaxError: invalid syntax

In [2]:
</code>```

答: This is not an issue in current versions of VSCode. The environment activation works for both pipenv and poetry, and can be customized from settings.</p>

Body:
The auto-sourcing/enable of Python environment is a great feature! But I don't know how to disable it for tasks. Pyenv for example automatically activates and runs commands in its virtualenv, so I end up having errors for my pipenv run commands.
I've made a little GIF with the behavior.

For reference, this is my .vscode/tasks.json file

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [{
        "label": "Run IPython Shell",
        "problemMatcher": [],
        "type": "shell",
        "command": "pipenv run ipython",
        "presentation": {
            "echo": true,
            "reveal": "always",
            "focus": true,
            "panel": "shared",
            "showReuseMessage": true,
            "clear": false
        }
    }]
}

And the output is the following:

> Executing task: pipenv run ipython <

source /Users/nahuel/.virtualenvs/pysrv-RjlHvHY5/bin/activate
Python 3.6.6 (default, Aug  6 2018, 12:14:58)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.1.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: source /Users/nahuel/.virtualenvs/pysrv-RjlHvHY5/bin/activate
  File "<ipython-input-1-944ce73c2717>", line 1
    source /Users/nahuel/.virtualenvs/pysrv-RjlHvHY5/bin/activate
                         ^
SyntaxError: invalid syntax

In [2]:


问:
mod-rewrite recursive loop
I want to change my website's dynamic urls to Search Engine Friendly URL's

Now the urls like this www.website.com/news.php?id=127591 ,
I want it became this www.website.com/news/127591/this-is-article-subject

I added this

```<code>RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT]
</code>```

in my .htaccess file. Everything from /news.php?id=123 change to /new/123/this-is-article-subject

The problem is, now I have two links refer to the same contents. Both /news.php?id=123 and /new/123/this-is-article-subject are the exactly duplicate content

It is said that search engine will punish this if they found duplicated contents.

I check the answers online and found this,

```<code>RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]
</code>```

HTTP 301 permanent redirect from the old URL to the new URL.

But this still have problem. When I put those three lines together, it not works.

```<code>RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]
</code>```

I guess the reason is the recursive loop. How could I solve this kind of problem?

Thanks!

Update

I changed to this

```<code>RewriteRule ^news/([0-9]+) /news.php?id=$1 [L]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]
</code>```

None of the two url work.

答:
If you're only concerned about search engines, you could create a robots.txt file containing:

```<code>User-agent: *
Disallow: /news.php
</code>```

This will make sure that search engines don't follow the news.php links.

To fix your rewrite rules, you might try adding L to the first RewriteRule to make sure that mod_rewrite doesn't continue:

```<code>RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT,L]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]
</code>```

Title: mod-rewrite recursive loop

Body:
I want to change my website's dynamic urls to Search Engine Friendly URL's

Now the urls like this www.website.com/news.php?id=127591 ,
I want it became this www.website.com/news/127591/this-is-article-subject

I added this

RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT]

in my .htaccess file. Everything from /news.php?id=123 change to /new/123/this-is-article-subject

The problem is, now I have two links refer to the same contents. Both /news.php?id=123 and /new/123/this-is-article-subject are the exactly duplicate content

It is said that search engine will punish this if they found duplicated contents.

I check the answers online and found this,

RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]

HTTP 301 permanent redirect from the old URL to the new URL.

But this still have problem. When I put those three lines together, it not works.

RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]

I guess the reason is the recursive loop. How could I solve this kind of problem?

Thanks!

Update

I changed to this

RewriteRule ^news/([0-9]+) /news.php?id=$1 [L]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]

None of the two url work.

Body:
If you're only concerned about search engines, you could create a robots.txt file containing:

User-agent: *
Disallow: /news.php

This will make sure that search engines don't follow the news.php links.

To fix your rewrite rules, you might try adding L to the first RewriteRule to make sure that mod_rewrite doesn't continue:

RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT,L]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]


问:
What is the SQL query to calculate average lease time?
I need to calculate an average lease time of my cars grouped by a brand.

For simplicity, I have the following LEASE table in my DB:

```<code>carMake | startDateTime | endDateTime
</code>```

My unfinished SQL query looks like:

```<code>SELECT lease.carMake
FROM lease
WHERE lease.startDateTime <= {?endDate} AND lease.endDateTime >= {?startDate}
SUM ... ???
GROUP BY lease.carMake ;
</code>```

Example:

```<code>carMake |   startDateTime   | endDateTime
MB        01.01.2018 00:00     01.01.2019 00:00
BMW       07.06.2018 21:00     01.01.2019 00:00
MB        06.06.2018 00:00     07.06.2018 00:00
</code>```

Result with query range between 06.06.2018 and 07.06.2018:

```<code>carMake | avgTime
MB        36 hours
BMW       3 hours
</code>```

Database is PostgreSQL

答:
```<code>SELECT carMake, AVG(endDateTime - startDateTime) AS avgTime WHERE startDateTime <= {?endDate} AND endDateTime >= {?startDate} FROM lease GROUP BY 1;
</code>```

Body:
I need to calculate an average lease time of my cars grouped by a brand.

For simplicity, I have the following LEASE table in my DB:

carMake | startDateTime | endDateTime

My unfinished SQL query looks like:

SELECT lease.carMake
FROM lease
WHERE lease.startDateTime <= {?endDate} AND lease.endDateTime >= {?startDate}
SUM ... ???
GROUP BY lease.carMake ;

Example:

carMake |   startDateTime   | endDateTime
MB        01.01.2018 00:00     01.01.2019 00:00
BMW       07.06.2018 21:00     01.01.2019 00:00
MB        06.06.2018 00:00     07.06.2018 00:00

Result with query range between 06.06.2018 and 07.06.2018:

carMake | avgTime
MB        36 hours
BMW       3 hours

Database is PostgreSQL


问:
Is there a way to handle/ignore inline xsd in received xml file in biztalk?
Client sends a file containing customer data in xml. The problem is that it also contains the xsd they use. Is there a way when setting up the source schema in biztalk to make it validate while ignoring the xsd?

I've tried including nodes for it, but it does not validate due to some namespace error, and it keeps looking for the first element node containing customer data

```<code><Root>
  <xsd:schema id="Root" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xsd:element name="Root" msdata:IsDataSet="true">
      <xsd:complexType>
        <xsd:choice maxOccurs="unbounded">
          <xsd:element name="Data" minOccurs="0" maxOccurs="unbounded">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="number" type="xsd:int"/>
                <xsd:element name="name">
                    <xsd:simpleType>
                      <xsd:restriction base="xsd:string">
                        <xsd:maxLength value="60"/>
                      </xsd:restriction>
                    </xsd:simpleType>
                </xsd:element>
                <xsd:element name="address">
                  <xsd:simpleType>
                    <xsd:restriction base="xsd:string">
                      <xsd:maxLength value="30"/>
                    </xsd:restriction>
                  </xsd:simpleType>
                </xsd:element>
                <xsd:element name="Zip">
                  <xsd:simpleType>
                    <xsd:restriction base="xsd:string">
                      <xsd:maxLength value="5"/>
                    </xsd:restriction>
                  </xsd:simpleType>
                </xsd:element>
                <xsd:element name="telephone">
                  <xsd:simpleType>
                    <xsd:restriction base="xsd:string">
                      <xsd:maxLength value="60"/>
                    </xsd:restriction>
                  </xsd:simpleType>
                </xsd:element>
                <xsd:element name="custNumber">
                  <xsd:simpleType>
                    <xsd:restriction base="xsd:string">
                      <xsd:maxLength value="11"/>
                    </xsd:restriction>
                  </xsd:simpleType>
                </xsd:element>
                <xsd:element name="branchnumber" type="xsd:int"/>
                </xsd:element>
              </xsd:sequence>
            </xsd:complexType>
          </xsd:element>
        </xsd:choice>
        <xsd:anyAttribute namespace="http://www.w3.org/XML/1998/namespace" processContents="lax"/>
      </xsd:complexType>
    </xsd:element>
  </xsd:schema>

    <Data>
        <number>12345</number>
        <name>Scrooge McDuck</name>
        <address>Address 1</adresse>
        <Zip>0000</Zip>
        <telephone>1234563290</telephone>
        <custNumber>123324</custNumber>
        <branchnumber>0</branchnumber>
    </Data>
    <Data>
        <number>23456</number>
        <name>Donald Duck</name>
        <address>Address 4</adresse>
        <Zip>4625</Zip>
        <telephone>1234567890</telephone>
        <custNumber>123321</custNumber>
        <branchnumber>0</branchnumber>
    </Data>
</Root>
</code>```

答:
I don't think this would actually cause a problem.

First, don't bother validating at runtime, no one ever does this and it's never mattered.

The schema should only contain the content nodes, this will work just fine in the Mapper, Properties etc.

Since you're not validating, provided the Schema is valid xml, it'll just go along for the ride and will be ignored.

To Validate in VS, just take the Schema nodes out.

Body:
Client sends a file containing customer data in xml. The problem is that it also contains the xsd they use. Is there a way when setting up the source schema in biztalk to make it validate while ignoring the xsd?

I've tried including nodes for it, but it does not validate due to some namespace error, and it keeps looking for the first element node containing customer data

<Root>
  <xsd:schema id="Root" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xsd:element name="Root" msdata:IsDataSet="true">
      <xsd:complexType>
        <xsd:choice maxOccurs="unbounded">
          <xsd:element name="Data" minOccurs="0" maxOccurs="unbounded">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="number" type="xsd:int"/>
                <xsd:element name="name">
                    <xsd:simpleType>
                      <xsd:restriction base="xsd:string">
                        <xsd:maxLength value="60"/>
                      </xsd:restriction>
                    </xsd:simpleType>
                </xsd:element>
                <xsd:element name="address">
                  <xsd:simpleType>
                    <xsd:restriction base="xsd:string">
                      <xsd:maxLength value="30"/>
                    </xsd:restriction>
                  </xsd:simpleType>
                </xsd:element>
                <xsd:element name="Zip">
                  <xsd:simpleType>
                    <xsd:restriction base="xsd:string">
                      <xsd:maxLength value="5"/>
                    </xsd:restriction>
                  </xsd:simpleType>
                </xsd:element>
                <xsd:element name="telephone">
                  <xsd:simpleType>
                    <xsd:restriction base="xsd:string">
                      <xsd:maxLength value="60"/>
                    </xsd:restriction>
                  </xsd:simpleType>
                </xsd:element>
                <xsd:element name="custNumber">
                  <xsd:simpleType>
                    <xsd:restriction base="xsd:string">
                      <xsd:maxLength value="11"/>
                    </xsd:restriction>
                  </xsd:simpleType>
                </xsd:element>
                <xsd:element name="branchnumber" type="xsd:int"/>
                </xsd:element>
              </xsd:sequence>
            </xsd:complexType>
          </xsd:element>
        </xsd:choice>
        <xsd:anyAttribute namespace="http://www.w3.org/XML/1998/namespace" processContents="lax"/>
      </xsd:complexType>
    </xsd:element>
  </xsd:schema>

    <Data>
        <number>12345</number>
        <name>Scrooge McDuck</name>
        <address>Address 1</adresse>
        <Zip>0000</Zip>
        <telephone>1234563290</telephone>
        <custNumber>123324</custNumber>
        <branchnumber>0</branchnumber>
    </Data>
    <Data>
        <number>23456</number>
        <name>Donald Duck</name>
        <address>Address 4</adresse>
        <Zip>4625</Zip>
        <telephone>1234567890</telephone>
        <custNumber>123321</custNumber>
        <branchnumber>0</branchnumber>
    </Data>
</Root>


问:
How to make the removal of the player’s result if he “took off” from the rating?
I need to make the player removed from the dictionary and from the file if he "flies" out of the rating (ie, takes the 6th place)
I have an idea to do it through Dictionary.Remove and then overwrite it in a file.

I made an algorithm of actions:
Read the file, delete the line in memory, and return the contents to the file (overwrite). If the file is large, you can read its line for the line and create a temporary file, replacing the original file later.

Here is the code for sorting them into places, maybe something will help:

```<code>private static Dictionary<string, int> AllNames()
    {
        return File
          .ReadLines(@"C:\Users\HP\Desktop\картинки\results.txt")
          .Where(line => !string.IsNullOrWhiteSpace(line))
          .Select(item => item.Split(' '))
          .ToDictionary(items => items[0],
                        items => int.Parse(items[1]));
    }

    private void updateRatingLabels()
    {
        var tops = AllNames()
          .OrderBy(pair => pair.Value)
          .ThenBy(pair => pair.Key, StringComparer.Ordinal)
          .Take(5)
          .ToArray();

        for (int i = 18; i <= 22; ++i)
            Controls.Find($"label{i}", true).First().Text = "";

        for (int i = 28; i <= 32; ++i)
            Controls.Find($"label{i}", true).First().Text = "";

        for (int i = 0; i < tops.Length; ++i)
        {
            Controls.Find($"label{i + 18}", true).First().Text = tops[i].Key;
            Controls.Find($"label{i + 28}", true).First().Text = $"{tops[i].Value / 60}:{tops[i].Value % 60:00}";
        }
    }
</code>```

答:
Let's put the question in a different way: we are going keep (not remove) at most 5 top players. We have to consider what we should do in case of tie (i.e. 2 or more players have the same score). I think it'll be honest to keep all such players (so that the actual dictionary can be longer than 5 records):

```<code>var newDictionary = AllNames()
  .GroupBy(pair => pair.Value)  // groups by scores
  .OrderBy(chunk => chunk.Key)  // less seconds the better
  .Take(5)                      // at most 5 groups (ties preserved)
  .SelectMany(chunk => chunk)   // flatten back ("ungroup")
  .ToDictionary(pair => pair.Key,
                pair => pair.Value);
</code>```

To save the data into the file, try File.WriteAllLines; let's use "Name Value" format

```<code> File.WriteAllLines(@"c:\TopPlayers.txt", newDictionary
   .Select(pair => $"{pair.Key} {pair.Value}"));
</code>```

Edit: If we have to add an user, with name and score we can do it in 2 ways:

Whatever score is remove 5th place and add new user:

```<code> var newDictionary = AllNames()
  .GroupBy(pair => pair.Value)  // groups by scores
  .OrderBy(chunk => chunk.Key)  // less seconds the better
  .Take(4)                      // at most 4 groups (ties preserved)
  .SelectMany(chunk => chunk)   // flatten back ("ungroup")
  .ToDictionary(pair => pair.Key,
                pair => pair.Value);

 newDictionary.Add(name, score);
</code>```

Add new user, then take top 5 (note, that new user can be excluded as a lower performer)

```<code> var newDictionary = AllNames()
  .Concat(new KeyValuePair<string, int>[] {
     new KeyValuePair<string, int>(name, score)} // All new users here
   )
  .GroupBy(pair => pair.Value)  // groups by scores
  .OrderBy(chunk => chunk.Key)  // less seconds the better
  .Take(5)                      // at most 5 groups (ties preserved)
  .SelectMany(chunk => chunk)   // flatten back ("ungroup")
  .ToDictionary(pair => pair.Key,
                pair => pair.Value);
</code>```

Edit 2: So you can implement a method like

```<code> private void SaveNewUser(string name, int score) {
   var newDictionary = AllNames()
     .GroupBy(pair => pair.Value)     // groups by scores
     .OrderBy(chunk => chunk.Key)     // less seconds the better
     .Take(4)                         // at most 4 groups (ties preserved)
     .SelectMany(chunk => chunk)      // flatten back ("ungroup")
     .ToDictionary(pair => pair.Key,
                  pair => pair.Value);

   newDictionary.Add(name, score);

   File.WriteAllLines(@"c:\TopPlayers.txt", newDictionary
     .Select(pair => $"{pair.Key} {pair.Value}"));
 }
</code>```

which you can call somewhere on, say, a button click:

```<code> private void saveButton_Click(object sender, EventArgs e) {
   SaveNewUser(textBoxWithName.Text, int.Parse(textBoxWithScore.Text));
 }
</code>```

Body:
I need to make the player removed from the dictionary and from the file if he "flies" out of the rating (ie, takes the 6th place)
I have an idea to do it through Dictionary.Remove and then overwrite it in a file.

I made an algorithm of actions:
Read the file, delete the line in memory, and return the contents to the file (overwrite). If the file is large, you can read its line for the line and create a temporary file, replacing the original file later.

Here is the code for sorting them into places, maybe something will help:

private static Dictionary<string, int> AllNames()
    {
        return File
          .ReadLines(@"C:\Users\HP\Desktop\картинки\results.txt")
          .Where(line => !string.IsNullOrWhiteSpace(line))
          .Select(item => item.Split(' '))
          .ToDictionary(items => items[0],
                        items => int.Parse(items[1]));
    }

    private void updateRatingLabels()
    {
        var tops = AllNames()
          .OrderBy(pair => pair.Value)
          .ThenBy(pair => pair.Key, StringComparer.Ordinal)
          .Take(5)
          .ToArray();

        for (int i = 18; i <= 22; ++i)
            Controls.Find($"label{i}", true).First().Text = "";

        for (int i = 28; i <= 32; ++i)
            Controls.Find($"label{i}", true).First().Text = "";

        for (int i = 0; i < tops.Length; ++i)
        {
            Controls.Find($"label{i + 18}", true).First().Text = tops[i].Key;
            Controls.Find($"label{i + 28}", true).First().Text = $"{tops[i].Value / 60}:{tops[i].Value % 60:00}";
        }
    }

Body:
Let's put the question in a different way: we are going keep (not remove) at most 5 top players. We have to consider what we should do in case of tie (i.e. 2 or more players have the same score). I think it'll be honest to keep all such players (so that the actual dictionary can be longer than 5 records):

var newDictionary = AllNames()
  .GroupBy(pair => pair.Value)  // groups by scores
  .OrderBy(chunk => chunk.Key)  // less seconds the better
  .Take(5)                      // at most 5 groups (ties preserved)
  .SelectMany(chunk => chunk)   // flatten back ("ungroup")
  .ToDictionary(pair => pair.Key,
                pair => pair.Value);

To save the data into the file, try File.WriteAllLines; let's use "Name Value" format

 File.WriteAllLines(@"c:\TopPlayers.txt", newDictionary
   .Select(pair => $"{pair.Key} {pair.Value}"));

Edit: If we have to add an user, with name and score we can do it in 2 ways:

Whatever score is remove 5th place and add new user:

 var newDictionary = AllNames()
  .GroupBy(pair => pair.Value)  // groups by scores
  .OrderBy(chunk => chunk.Key)  // less seconds the better
  .Take(4)                      // at most 4 groups (ties preserved)
  .SelectMany(chunk => chunk)   // flatten back ("ungroup")
  .ToDictionary(pair => pair.Key,
                pair => pair.Value);

 newDictionary.Add(name, score);

Add new user, then take top 5 (note, that new user can be excluded as a lower performer)

 var newDictionary = AllNames()
  .Concat(new KeyValuePair<string, int>[] {
     new KeyValuePair<string, int>(name, score)} // All new users here
   )
  .GroupBy(pair => pair.Value)  // groups by scores
  .OrderBy(chunk => chunk.Key)  // less seconds the better
  .Take(5)                      // at most 5 groups (ties preserved)
  .SelectMany(chunk => chunk)   // flatten back ("ungroup")
  .ToDictionary(pair => pair.Key,
                pair => pair.Value);

Edit 2: So you can implement a method like

 private void SaveNewUser(string name, int score) {
   var newDictionary = AllNames()
     .GroupBy(pair => pair.Value)     // groups by scores
     .OrderBy(chunk => chunk.Key)     // less seconds the better
     .Take(4)                         // at most 4 groups (ties preserved)
     .SelectMany(chunk => chunk)      // flatten back ("ungroup")
     .ToDictionary(pair => pair.Key,
                  pair => pair.Value);

   newDictionary.Add(name, score);

   File.WriteAllLines(@"c:\TopPlayers.txt", newDictionary
     .Select(pair => $"{pair.Key} {pair.Value}"));
 }

which you can call somewhere on, say, a button click:

 private void saveButton_Click(object sender, EventArgs e) {
   SaveNewUser(textBoxWithName.Text, int.Parse(textBoxWithScore.Text));
 }


问:
Modal dialog hide behind Main Frame after swich focus
I have a swing application, basically, a main frame that could pop up a modal dialog.
When the modal dialog is showing, if I switch to another window, like firefox. And then switch back to the swing application. The JDialog is not in front any more.

I don't want to set the dialog AlwaysOnTop to be true. because then the dialog will be on top of all windows include windows in other process.

So what should I do so that when I swich back, the modal dialog still on top?

BTW: it is a Applet, so the main frame is actually be set in this way:

```<code>private static Frame findParentFrame(Container owner){
    Container c = owner;
    while(c != null){
        if (c instanceof Frame)
            return (Frame)c;
        c = c.getParent();
    }
    return (Frame)null;
}
</code>```

答: Make sure that the JDialog is actually modal.  Also try setting the main frame as the owner.

Body:
I have a swing application, basically, a main frame that could pop up a modal dialog.
When the modal dialog is showing, if I switch to another window, like firefox. And then switch back to the swing application. The JDialog is not in front any more.

I don't want to set the dialog AlwaysOnTop to be true. because then the dialog will be on top of all windows include windows in other process.

So what should I do so that when I swich back, the modal dialog still on top?

BTW: it is a Applet, so the main frame is actually be set in this way:

private static Frame findParentFrame(Container owner){
    Container c = owner;
    while(c != null){
        if (c instanceof Frame)
            return (Frame)c;
        c = c.getParent();
    }
    return (Frame)null;
}


问:
RAML Max length of an item in a String array
I am defining a RAML spec. I have an attribute to hold an array of string. I want to make a rule that a string value in the array can have only maximum 3 charactors only (For example: regions: ["wes","nrh"] is valid. regions: ["lenghthyvalue", "anotherLenghthyvalue"]  invalid). How can I handle it in RAML. My current code is as following:

```<code>regions:
     type: string []
     required: true
</code>```

Available attributes are maxItems only. How to limit the character length of an item ?

I use raml 1.0

答:
First create a string type that has maxLength and minLength attributes. Then you can reference that type in your array type instead of just a string array. Example:

```<code>#%RAML 1.0
title: test
version: 1.0
types:
  region:
    type: string
    minLength: 3
    maxLength: 3
  regions:
     type: region []
     required: true

/test:
  get:
    queryParameters:
      regions: region
</code>```

Body:
I am defining a RAML spec. I have an attribute to hold an array of string. I want to make a rule that a string value in the array can have only maximum 3 charactors only (For example: regions: ["wes","nrh"] is valid. regions: ["lenghthyvalue", "anotherLenghthyvalue"]  invalid). How can I handle it in RAML. My current code is as following:

regions:
     type: string []
     required: true

Available attributes are maxItems only. How to limit the character length of an item ?

I use raml 1.0

Body:
First create a string type that has maxLength and minLength attributes. Then you can reference that type in your array type instead of just a string array. Example:

#%RAML 1.0
title: test
version: 1.0
types:
  region:
    type: string
    minLength: 3
    maxLength: 3
  regions:
     type: region []
     required: true

/test:
  get:
    queryParameters:
      regions: region


问:
i can't find any thing on my telegram bot API
I'm trying to get all the chat_id's in the telegram bot API

When I call

https://api.telegram.org/botmybot_token/getUpdates

I get this {"ok":true,"result":[]}

答:
You get empty updates because there were no messages (or other actions) from users.

To obtain user's chat_id follow these steps:

User must first find the bot and send it any message, because

Bots can't initiate conversations with users. A user must either add them to a group or send them a message first. People can use telegram.me/ links or username search to find your bot.

Get the following URL: https://api.telegram.org/botmybot_token/getUpdates?timeout=300. Note that you should use timeout= because this is a long polling method (i.e. you will receive response only when there is a new incoming update or timeout is reached):

(timeout is) Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only.

You can still receive updates without timeout setting, but that's not the right way to read user interaction. Instead you can you just run long-polling (i.e. with timeout setting) requests in a loop.

You can read more on getting infromation about user's chat_id here:

https://stackoverflow.com/a/56093268/2315573


问:
How to pass values from view.py to index.html in Django?
I have all these variables in my view.py on Django.
And I want to put in on the index.html

def current_database(request):
    contador = Post.objects.count()
    myclient = pymongo.MongoClient("mongodb://localhost:27017/")
    mydb = myclient["prueba2"]
    mycol = mydb["miapp_post"]
    template = loader.get_template('miapp/index.html')

    for x in mycol.find():
        dominio = x['dominio']
        porcentaje_movil = x['porcentaje_movil']
        orportunidades_movil = x['orportunidades_movil']
        diagnosticos_movil = x['diagnosticos_movil']
        porcentaje_ordenador = x['porcentaje_ordenador']
        oportunidades_ordenador = x['oportunidades_ordenador']
        diagnosticos_ordenador = x['diagnosticos_ordenador']
        return HttpResponse(template.render(dominio, porcentaje_movil, orportunidades_movil, diagnosticos_movil, porcentaje_ordenador, oportunidades_ordenador, diagnosticos_ordenador))
```

<p>When i go to my index.html all go fine the conecction its fine, no problem with that, but for exmple y put:</p>

<pre class="lang-py prettyprint-override"><code><p>Dominio: {{ dominio }}</p>
</code>```

or

Dominio: {% dominio %}

```

and I always get and error and i dont know how to pass these values to mi html.
Thanks.

答:
Just return the template like
return render(request,'miapp/index.html',{'data': dominio})
and access it in HTML using {{ data }}. Don't forget to import render function using from django.shortcuts import render

Body:
I have all these variables in my view.py on Django.
And I want to put in on the index.html

def current_database(request):
    contador = Post.objects.count()
    myclient = pymongo.MongoClient("mongodb://localhost:27017/")
    mydb = myclient["prueba2"]
    mycol = mydb["miapp_post"]
    template = loader.get_template('miapp/index.html')

    for x in mycol.find():
        dominio = x['dominio']
        porcentaje_movil = x['porcentaje_movil']
        orportunidades_movil = x['orportunidades_movil']
        diagnosticos_movil = x['diagnosticos_movil']
        porcentaje_ordenador = x['porcentaje_ordenador']
        oportunidades_ordenador = x['oportunidades_ordenador']
        diagnosticos_ordenador = x['diagnosticos_ordenador']
        return HttpResponse(template.render(dominio, porcentaje_movil, orportunidades_movil, diagnosticos_movil, porcentaje_ordenador, oportunidades_ordenador, diagnosticos_ordenador))

When i go to my index.html all go fine the conecction its fine, no problem with that, but for exmple y put:

Dominio: {{ dominio }}

or

Dominio: {% dominio %}

and I always get and error and i dont know how to pass these values to mi html.
Thanks.