问:
R rename multiple columns with wildcard with rename_with()
library(tidyverse)

I am looking to rename bunch columns and I tried to use rename_at() or rename_with() in R but not much success, can someone help? Thank you very much for your help.

Original data frame column names

```<code>tibble(
AAA_BBB1_P1_Elev = as.double(),
AAA_BBB2_P2_Elev = as.double(),
AAA_BBB2_P3_Elev = as.double()
)
</code>```

Want to change the column names to

```<code>tibble(
`BBB1-P1E` = as.double(),
`BBB1-P2E` = as.double(),
`BBB1-P3E` = as.double()
)

</code>```

答:
I had a similar problem. Data on people tested on two occasions was given as

```<code>Data %>%
  select(Identifier, contains('eq5d'),-EQ5D3L_Combined) %>%
  names()
</code>```

which gave this list of names.

"Identifier"      "EQ5D3L_Item_1"   "EQ5D3L_Item_2"

"EQ5D3L_Item_3"   "EQ5D3L_Item_4"   "EQ5D3L_Item_5"

"EQ5D3L_VAS"      "EQ5D3L_Item_1_2" "EQ5D3L_Item_2_2"
"EQ5D3L_Item_3_2" "EQ5D3L_Item_4_2" "EQ5D3L_Item_5_2"
"EQ5D3L_VAS_2"

The '_2' was the second measurement occasion, and I needed to put '_1' at the end of the variable from the first occasion.

To fix this I used rename_with as follows

```<code>Data %>%
   select(Identifier, contains('eq5d'),-EQ5D3L_Combined) %>%
   rename_with(~ifelse(!str_ends(.x,'[0-9]'),
                       str_c(.x,'_1'),
                       .x)) %>%
    names()
</code>```

The !str_end picks out variable names which did not end with a number, as a logical vector. The ifelse applies the rename_with only to those which did not end in a number, and the str_c adds '_1' to those - so I now have my variable named correctly for an easy pivot_longer.

Body:
library(tidyverse)

I am looking to rename bunch columns and I tried to use rename_at() or rename_with() in R but not much success, can someone help? Thank you very much for your help.

Original data frame column names

tibble(
AAA_BBB1_P1_Elev = as.double(),
AAA_BBB2_P2_Elev = as.double(),
AAA_BBB2_P3_Elev = as.double()
)

Want to change the column names to

tibble(
`BBB1-P1E` = as.double(),
`BBB1-P2E` = as.double(),
`BBB1-P3E` = as.double()
)

Body:
I had a similar problem. Data on people tested on two occasions was given as

Data %>%
  select(Identifier, contains('eq5d'),-EQ5D3L_Combined) %>%
  names()

which gave this list of names.

"Identifier"      "EQ5D3L_Item_1"   "EQ5D3L_Item_2"

"EQ5D3L_Item_3"   "EQ5D3L_Item_4"   "EQ5D3L_Item_5"

"EQ5D3L_VAS"      "EQ5D3L_Item_1_2" "EQ5D3L_Item_2_2"
"EQ5D3L_Item_3_2" "EQ5D3L_Item_4_2" "EQ5D3L_Item_5_2"
"EQ5D3L_VAS_2"

The '_2' was the second measurement occasion, and I needed to put '_1' at the end of the variable from the first occasion.

To fix this I used rename_with as follows

Data %>%
   select(Identifier, contains('eq5d'),-EQ5D3L_Combined) %>%
   rename_with(~ifelse(!str_ends(.x,'[0-9]'),
                       str_c(.x,'_1'),
                       .x)) %>%
    names()

The !str_end picks out variable names which did not end with a number, as a logical vector. The ifelse applies the rename_with only to those which did not end in a number, and the str_c adds '_1' to those - so I now have my variable named correctly for an easy pivot_longer.


来源: stackexchange

问:
Checking a Python module version at runtime
Many third-party Python modules have an attribute which holds the version information for the module (usually something like module.VERSION or module.__version__), however some do not.

Particular examples of such modules are libxslt and libxml2.

I need to check that the correct version of these modules are being used at runtime. Is there a way to do this?

A potential solution wold be to read in the source at runtime, hash it, and then compare it to the hash of the known version, but that's nasty.

Is there a better solutions?

答:
I'd stay away from hashing.  The version of libxslt being used might contain some type of patch that doesn't effect your use of it.

As an alternative, I'd like to suggest that you don't check at run time (don't know if that's a hard requirement or not).  For the python stuff I write that has external dependencies (3rd party libraries), I write a script that users can run to check their python install to see if the appropriate versions of modules are installed.

For the modules that don't have a defined 'version' attribute, you can inspect the interfaces it contains (classes and methods) and see if they match the interface they expect.  Then in the actual code that you're working on, assume that the 3rd party modules have the interface you expect.

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Mark Roddy


问:
Snap-confine has elevated permissions and is not confined but should be. Refusing to continue to avoid permission escalation attacks
I have been using snap for some time but after a recent upgrade, I get this error when I try opening any application

```<code>Snap-confine has elevated permissions and is not confined but should be.
Refusing to continue to avoid permission escalation attacks
</code>```

I have tried various fixes but it keeps getting worse. Any idea on what I should do?

I also tried sudo apt purge snapd snap-confine && sudo apt install -y snapd but when I try opening pycharm-community, it doesn't do anything.

答:
```<code>sudo apparmor_parser -r /etc/apparmor.d/*snap-confine*
sudo apparmor_parser -r /var/lib/snapd/apparmor/profiles/snap-confine*
</code>```

Fixes it. No restart required.

ContentLicense: CC BY-SA 4.0

Body:
I have been using snap for some time but after a recent upgrade, I get this error when I try opening any application

Snap-confine has elevated permissions and is not confined but should be.
Refusing to continue to avoid permission escalation attacks

I have tried various fixes but it keeps getting worse. Any idea on what I should do?

I also tried sudo apt purge snapd snap-confine && sudo apt install -y snapd but when I try opening pycharm-community, it doesn't do anything.

Body:
sudo apparmor_parser -r /etc/apparmor.d/*snap-confine*
sudo apparmor_parser -r /var/lib/snapd/apparmor/profiles/snap-confine*

Fixes it. No restart required.


问:
GCS catch error if file not found in bucket while streaming download
I am trying to fetch images from google cloud storage bucket from browser and serving the files using API in express. Following code breaks when the Image path is invalid. The try catch doesn't catch the file not found error. Am I missing something here? This code works if an image file exists.

From the Express side, I am using wildcard route (i.e. /*) as the API can accept any image path coming in and try to serve it.

const express = require('express')
const {Storage} = require('@google-cloud/storage');
let server = express()
const storage = new Storage();
const bucketName = '<some-bucket-name>'

server.get('/*', async (req, res) => {
  const widthString = req.query.width
  const heightString = req.query.height
  const format = req.query.format
  const fileName = req.path.substring(1);
  console.log("url: ", req.path)
  let width, height
  if (widthString) {
    width = parseInt(widthString)
  }
  if (heightString) {
    height = parseInt(heightString)
  }
  res.type(`image/${format || 'png'}`)

  try{
      await storage.bucket(bucketName).file(fileName).createReadStream().pipe(res)
  } catch (err) {
     console.error(err);
  }
})
```
<p>Error:</p>
<pre class="lang-js prettyprint-override"><code>url:  /media/artist/banner_image/16118/screenshot_2019_12_16_at_10.35.24_am.png
events.js:377
      throw er; // Unhandled 'error' event
      ^

ApiError: No such object: assets/media/artist/banner_image/16118/screenshot_2019_12_16_at_10.35.24_am.png
    at new ApiError (/home/ubuntu/imageoptimizer/node_modules/@google-cloud/common/build/src/util.js:73:15)
    at Util.parseHttpRespMessage (/home/ubuntu/imageoptimizer/node_modules/@google-cloud/common/build/src/util.js:175:41)
    at Util.handleResp (/home/ubuntu/imageoptimizer/node_modules/@google-cloud/common/build/src/util.js:149:76)
    at Duplexify.<anonymous> (/home/ubuntu/imageoptimizer/node_modules/@google-cloud/storage/build/src/file.js:888:31)
    at Duplexify.emit (events.js:400:28)
    at PassThrough.emit (events.js:400:28)
    at onResponse (/home/ubuntu/imageoptimizer/node_modules/retry-request/index.js:222:19)
    at PassThrough.<anonymous> (/home/ubuntu/imageoptimizer/node_modules/retry-request/index.js:163:11)
    at PassThrough.emit (events.js:412:35)
    at /home/ubuntu/imageoptimizer/node_modules/teeny-request/build/src/index.js:191:27
Emitted 'error' event on PassThrough instance at:
    at emitErrorNT (internal/streams/destroy.js:106:8)
    at emitErrorCloseNT (internal/streams/destroy.js:74:3)
    at processTicksAndRejections (internal/process/task_queues.js:82:21) {
  code: 404,
</code>```

答:
Posting my previous comment as an answer for visibility

You have to handle this exception by yourself. GCP won't throw the error directly. It only returns 404 as an output, and you have to handle it manually rather than expecting try{} catch () {} to catch this exception. Or you can request it as a new feature in issue tracker, however I am not sure how long it will take for the Google to implement this feature.

Body:
I am trying to fetch images from google cloud storage bucket from browser and serving the files using API in express. Following code breaks when the Image path is invalid. The try catch doesn't catch the file not found error. Am I missing something here? This code works if an image file exists.

From the Express side, I am using wildcard route (i.e. /*) as the API can accept any image path coming in and try to serve it.

const express = require('express')
const {Storage} = require('@google-cloud/storage');
let server = express()
const storage = new Storage();
const bucketName = '<some-bucket-name>'

server.get('/*', async (req, res) => {
  const widthString = req.query.width
  const heightString = req.query.height
  const format = req.query.format
  const fileName = req.path.substring(1);
  console.log("url: ", req.path)
  let width, height
  if (widthString) {
    width = parseInt(widthString)
  }
  if (heightString) {
    height = parseInt(heightString)
  }
  res.type(`image/${format || 'png'}`)

  try{
      await storage.bucket(bucketName).file(fileName).createReadStream().pipe(res)
  } catch (err) {
     console.error(err);
  }
})

Error:

url:  /media/artist/banner_image/16118/screenshot_2019_12_16_at_10.35.24_am.png
events.js:377
      throw er; // Unhandled 'error' event
      ^

ApiError: No such object: assets/media/artist/banner_image/16118/screenshot_2019_12_16_at_10.35.24_am.png
    at new ApiError (/home/ubuntu/imageoptimizer/node_modules/@google-cloud/common/build/src/util.js:73:15)
    at Util.parseHttpRespMessage (/home/ubuntu/imageoptimizer/node_modules/@google-cloud/common/build/src/util.js:175:41)
    at Util.handleResp (/home/ubuntu/imageoptimizer/node_modules/@google-cloud/common/build/src/util.js:149:76)
    at Duplexify.<anonymous> (/home/ubuntu/imageoptimizer/node_modules/@google-cloud/storage/build/src/file.js:888:31)
    at Duplexify.emit (events.js:400:28)
    at PassThrough.emit (events.js:400:28)
    at onResponse (/home/ubuntu/imageoptimizer/node_modules/retry-request/index.js:222:19)
    at PassThrough.<anonymous> (/home/ubuntu/imageoptimizer/node_modules/retry-request/index.js:163:11)
    at PassThrough.emit (events.js:412:35)
    at /home/ubuntu/imageoptimizer/node_modules/teeny-request/build/src/index.js:191:27
Emitted 'error' event on PassThrough instance at:
    at emitErrorNT (internal/streams/destroy.js:106:8)
    at emitErrorCloseNT (internal/streams/destroy.js:74:3)
    at processTicksAndRejections (internal/process/task_queues.js:82:21) {
  code: 404,


问:
NullPointerException Mock when use RestTemplate
I am new to using mockito and I have a problem. I wrote a controller test and it uses restTemplate to get data from another api, but when I run the test, the variable of this type is null. In result NullPointerException.

What could be the problem?

Controlle:

 @GetMapping(value = "api/cstat", produces = "application/json")
    public ResponseEntity<List<String>> cstat() {
               ResponseEntity<DTO> response =                  // <=====NPE
                            restTemplate.exchange(uri, HttpMethod.GET, entity, DTO.class);

                    if (response.getBody() != null).     //<==== AND HERE NPE(on future))
                    {
                       ...
                    } else {
                        ...
                    }
}
```
<p><strong>Test:</strong></p>
```
            Dto expected = new Dto();

            String actual = mockMvc.perform(MockMvcRequestBuilders
                                .get("/api/cstat").with(roleLmsRead()))
                        .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
```

答:
This is because you don't have restTemplate, so restTemplate is null.

To initialise this, in the test:

You need to declare restTemplate. E.g.

```<code>@Mock
private RestTemplate restTemplate;
</code>```

Then you need to inject this to your mockMvc. E.g.

```<code>@Inject
private Mvc mockMvc;
</code>```

In case of you're not writing test using the annotation style like this. You can do:

```<code>@Before
public void setUp() {
    restTemplate = Mockito.mock(RestTemplate.class);
    mockMvc = new MockMvc(restTemplate);
}
</code>```

P/S: If mockMvc is the one you're gonna test, so don't name it as prefix mock, it's confused.

Body:
I am new to using mockito and I have a problem. I wrote a controller test and it uses restTemplate to get data from another api, but when I run the test, the variable of this type is null. In result NullPointerException.

What could be the problem?

Controlle:

 @GetMapping(value = "api/cstat", produces = "application/json")
    public ResponseEntity<List<String>> cstat() {
               ResponseEntity<DTO> response =                  // <=====NPE
                            restTemplate.exchange(uri, HttpMethod.GET, entity, DTO.class);

                    if (response.getBody() != null).     //<==== AND HERE NPE(on future))
                    {
                       ...
                    } else {
                        ...
                    }
}

Test:

            Dto expected = new Dto();

            String actual = mockMvc.perform(MockMvcRequestBuilders
                                .get("/api/cstat").with(roleLmsRead()))
                        .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();

Body:
This is because you don't have restTemplate, so restTemplate is null.

To initialise this, in the test:

You need to declare restTemplate. E.g.

@Mock
private RestTemplate restTemplate;

Then you need to inject this to your mockMvc. E.g.

@Inject
private Mvc mockMvc;

In case of you're not writing test using the annotation style like this. You can do:

@Before
public void setUp() {
    restTemplate = Mockito.mock(RestTemplate.class);
    mockMvc = new MockMvc(restTemplate);
}

P/S: If mockMvc is the one you're gonna test, so don't name it as prefix mock, it's confused.


问:
Extract mail address from HTML-like string in Python
Using the GMail API it is possible to recover the sender of an email with:

```<code>email = service.users().messages().get(userId='me', id=msg['id']).execute()
payload = email['payload']
headers = payload['headers']
for hdr in headers:
if hdr['name'] == 'From':
   sender = hdr['value']
</code>```

This returns the variable sender as a string with the format:

```<code>"Name Surname" <name.surname@gmail.com>
</code>```

I would like to recover separately the name and email address from this string.
So that I end up with 2 (str) variables:

```<code>sender_name = "Name Surname"
sender_email_address = "name.surname@gmail.com"
</code>```

Is there a library that can assist with this?

答:
Here is an option:

```<code>mys = '"Name Surname" <name.surname@gmail.com>'
name_email = mys.split("<")
sender_name = name_email[0].strip().strip('"')
sender_email_address = name_email[1].strip(">")
print(f"sender_name: {sender_name}")
print(f"sender_email_address: {sender_email_address}")
</code>```

returns

```<code>Name Surname
name.surname@gmail.com
</code>```

Body:
Using the GMail API it is possible to recover the sender of an email with:

email = service.users().messages().get(userId='me', id=msg['id']).execute()
payload = email['payload']
headers = payload['headers']
for hdr in headers:
if hdr['name'] == 'From':
   sender = hdr['value']

This returns the variable sender as a string with the format:

"Name Surname" <name.surname@gmail.com>

I would like to recover separately the name and email address from this string.
So that I end up with 2 (str) variables:

sender_name = "Name Surname"
sender_email_address = "name.surname@gmail.com"

Is there a library that can assist with this?

Body:
Here is an option:

mys = '"Name Surname" <name.surname@gmail.com>'
name_email = mys.split("<")
sender_name = name_email[0].strip().strip('"')
sender_email_address = name_email[1].strip(">")
print(f"sender_name: {sender_name}")
print(f"sender_email_address: {sender_email_address}")

returns

Name Surname
name.surname@gmail.com


问:
How to change PHP version used by composer
I want to use another php version on my machine than the one already installed using WAMP (2 PHP version installed).

The composer installed uses PHP 5.6

A new project requires PHP7.0.

Whenever I choose PHP 7 from the control panel of WAMP and then run php -v it still printing PHP5.6 (CLI)... instead of PHP7.

How can I use PHP7 without reinstalling the composer again?

答:
This is what happens in my case. I hope this may help to someone have same situation. I'm using macOS Monterey with MAMP.

I linked the php 7.4 using ~/.profile file. So the terminal it says I'm using php 7.4. However, still my composer giving an error saying i'm using php 7.3.

So I check the php path using

```<code>which php
</code>```

This gives me the /usr/local/bin/php as my php cli location. So I remove the file and made a symlink to my php7.4 and now working perfectly.

```<code>sudo rm -rf /usr/local/bin/php
sudo ln -s /Applications/MAMP/bin/php/php7.4.21/bin/php /usr/local/bin/php
</code>```

Body:
This is what happens in my case. I hope this may help to someone have same situation. I'm using macOS Monterey with MAMP.

I linked the php 7.4 using ~/.profile file. So the terminal it says I'm using php 7.4. However, still my composer giving an error saying i'm using php 7.3.

So I check the php path using

which php

This gives me the /usr/local/bin/php as my php cli location. So I remove the file and made a symlink to my php7.4 and now working perfectly.

sudo rm -rf /usr/local/bin/php
sudo ln -s /Applications/MAMP/bin/php/php7.4.21/bin/php /usr/local/bin/php


问:
nginx fall back to default server_name on multiple sites conf
I'm not strong at nginx, but trying to setup nginx prod server (host) redirect to dockerized app as my-site.com and subdomain.my-site.com to another dockerized app. Both apps have different ports open.
Host is running on ubuntu: 18.04, nginx version: nginx/1.18.0.
My host server nginx.conf is:

```<code>user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
#
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}
</code>```

I have added /etc/nginx/sites-available/my-site.com.conf:

```<code>server {
    listen 80;
    listen [::]:80;
    server_name my-site.com www.my-site.com;
    root /var/www/my-site;

    location / {
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_redirect off;
    }
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/venckus-software.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/venckus-software.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

</code>```

And the subdomain /etc/nginx/sites-available/subdomain.my-site.com.conf:

```<code>server {
    listen 80;
    listen [::]:80;
    server_name subdomain.my-site.com www.subdomain.my-site.com;
    root /var/www/subdomain;

    location / {
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:8081/;
        proxy_set_header X-Real-IP $remote_addr;
        # proxy_ssl_server_name on;
        proxy_redirect off;
    }
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my-site.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/my-site.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

</code>```

Symlinks are created at /etc/nginx/sites-enabled for both my-site.com.conf and subdomain.my-site.com.conf, Docker containers are up and running without problems.

The issue is nginx is loading default index.html located at /var/www/html when trying to access my-site.com or subdomain.my-site.com. What am I missing, what is wrong?

UPDATE:
here is nginx -T output:

```<code>nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
# configuration file /etc/nginx/nginx.conf:
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip on;

        # gzip_vary on;
        # gzip_proxied any;
        # gzip_comp_level 6;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}

#mail {
#       # See sample authentication script at:
#       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#       # auth_http localhost/auth.php;
#       # pop3_capabilities "TOP" "USER";
#       # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#       server {
#               listen     localhost:110;
#               protocol   pop3;
#               proxy      on;
#       }
#
#       server {
#               listen     localhost:143;
#               protocol   imap;
#               proxy      on;
#       }
#}

# configuration file /etc/nginx/modules-enabled/50-mod-http-geoip.conf:
load_module modules/ngx_http_geoip_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-image-filter.conf:
load_module modules/ngx_http_image_filter_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-xslt-filter.conf:
load_module modules/ngx_http_xslt_filter_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-mail.conf:
load_module modules/ngx_mail_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-stream.conf:
load_module modules/ngx_stream_module.so;

# configuration file /etc/nginx/modules-enabled/70-mod-stream-geoip.conf:
load_module modules/ngx_stream_geoip_module.so;

# configuration file /etc/nginx/mime.types:

types {
    text/html                             html htm shtml;
    text/css                              css;
    text/xml                              xml;
    image/gif                             gif;
    image/jpeg                            jpeg jpg;
    application/javascript                js;
    application/atom+xml                  atom;
    application/rss+xml                   rss;

    text/mathml                           mml;
    text/plain                            txt;
    text/vnd.sun.j2me.app-descriptor      jad;
    text/vnd.wap.wml                      wml;
    text/x-component                      htc;

    image/png                             png;
    image/tiff                            tif tiff;
    image/vnd.wap.wbmp                    wbmp;
    image/x-icon                          ico;
    image/x-jng                           jng;
    image/x-ms-bmp                        bmp;
    image/svg+xml                         svg svgz;
    image/webp                            webp;

    application/font-woff                 woff;
    application/java-archive              jar war ear;
    application/json                      json;
    application/mac-binhex40              hqx;
    application/msword                    doc;
    application/pdf                       pdf;
    application/postscript                ps eps ai;
    application/rtf                       rtf;
    application/vnd.apple.mpegurl         m3u8;
    application/vnd.ms-excel              xls;
    application/vnd.ms-fontobject         eot;
    application/vnd.ms-powerpoint         ppt;
    application/vnd.wap.wmlc              wmlc;
    application/vnd.google-earth.kml+xml  kml;
    application/vnd.google-earth.kmz      kmz;
    application/x-7z-compressed           7z;
    application/x-cocoa                   cco;
    application/x-java-archive-diff       jardiff;
    application/x-java-jnlp-file          jnlp;
    application/x-makeself                run;
    application/x-perl                    pl pm;
    application/x-pilot                   prc pdb;
    application/x-rar-compressed          rar;
    application/x-redhat-package-manager  rpm;
    application/x-sea                     sea;
    application/x-shockwave-flash         swf;
    application/x-stuffit                 sit;
    application/x-tcl                     tcl tk;
    application/x-x509-ca-cert            der pem crt;
    application/x-xpinstall               xpi;
    application/xhtml+xml                 xhtml;
    application/xspf+xml                  xspf;
    application/zip                       zip;

    application/octet-stream              bin exe dll;
    application/octet-stream              deb;
    application/octet-stream              dmg;
    application/octet-stream              iso img;
    application/octet-stream              msi msp msm;

    application/vnd.openxmlformats-officedocument.wordprocessingml.document    docx;
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet          xlsx;
    application/vnd.openxmlformats-officedocument.presentationml.presentation  pptx;

    audio/midi                            mid midi kar;
    audio/mpeg                            mp3;
    audio/ogg                             ogg;
    audio/x-m4a                           m4a;
    audio/x-realaudio                     ra;

    video/3gpp                            3gpp 3gp;
    video/mp2t                            ts;
    video/mp4                             mp4;
    video/mpeg                            mpeg mpg;
    video/quicktime                       mov;
    video/webm                            webm;
    video/x-flv                           flv;
    video/x-m4v                           m4v;
    video/x-mng                           mng;
    video/x-ms-asf                        asx asf;
    video/x-ms-wmv                        wmv;
    video/x-msvideo                       avi;
}

# configuration file /etc/nginx/sites-enabled/sms:
server {
    listen 80;
    root /var/www/sms;
    server_name sms.my-site.com www.sms.my-site.com;

    location / {
       include proxy_params;
       proxy_pass http://unix:/var/www/sms/sms.sock;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my-site.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/my-site.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

# configuration file /etc/nginx/proxy_params:
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

# configuration file /etc/letsencrypt/options-ssl-nginx.conf:
# This file contains important security parameters. If you modify this file
# manually, Certbot will be unable to automatically provide future security
# updates. Instead, Certbot will print and log an error message with a path to
# the up-to-date file that you will need to refer to when manually updating
# this file.

ssl_session_cache shared:le_nginx_SSL:1m;
ssl_session_timeout 1440m;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;

ssl_ciphers "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS";

# configuration file /etc/nginx/sites-enabled/subdomain.my-site.com.conf:
# Subdomain routing
server {
        listen 80;
        listen [::]:80;
        server_name subdomain.my-site.com www.subdomain.my-site.com;
        root /var/www/subdomain;

        location / {
                proxy_set_header Host $host;
                proxy_pass http://127.0.0.1:8081/;
                proxy_set_header X-Real-IP $remote_addr;
                # proxy_ssl_server_name on;
                proxy_redirect off;
        }
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my-site.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/my-site.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

# configuration file /etc/nginx/sites-enabled/default:
##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# https://www.nginx.com/resources/wiki/start/
# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
# https://wiki.debian.org/Nginx/DirectoryStructure
#
# In most cases, administrators will remove this file from sites-enabled/ and
# leave it as reference inside of sites-available where it will continue to be
# updated by the nginx packaging team.
#
# This file will automatically load configuration files provided by other
# applications, such as Drupal or Wordpress. These applications will be made
# available underneath a path with that package name, such as /drupal8.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
        listen 80 default_server;
        listen [::]:80 default_server;

        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
        #
        # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/snakeoil.conf;

        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        # pass PHP scripts to FastCGI server
        #
        #location ~ \.php$ {
        #       include snippets/fastcgi-php.conf;
        #
        #       # With php-fpm (or other unix sockets):
        #       fastcgi_pass unix:/run/php/php7.4-fpm.sock;
        #       # With php-cgi (or other tcp sockets):
        #       fastcgi_pass 127.0.0.1:9000;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #       deny all;
        #}
}

# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#       listen 80;
#       listen [::]:80;
#
#       server_name example.com;
#
#       root /var/www/example.com;
#       index index.html;
#
#       location / {
#               try_files $uri $uri/ =404;
#       }
#}

# configuration file /etc/nginx/sites-enabled/my-site.com.conf:
# domain routing
server {
        listen 80;
        listen [::]:80;
        server_name my-site.com www.my-site.com;
        root /var/www/my-site;

        location / {
                proxy_set_header Host $host;
                proxy_pass http://127.0.0.1:8000;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_redirect off;
        }
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my-site.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/my-site.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
</code>```

Update 2:
as @IvanShatsky suggested - the curl -v -I localhost:8000 give this response:

```<code>* Rebuilt URL to: localhost:8000/
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8000 (#0)
> HEAD / HTTP/1.1
> Host: localhost:8000
> User-Agent: curl/7.58.0
> Accept: */*
>
< HTTP/1.1 400 Bad Request
HTTP/1.1 400 Bad Request
< Date: Tue, 08 Feb 2022 15:52:12 GMT
Date: Tue, 08 Feb 2022 15:52:12 GMT
< Server: WSGIServer/0.2 CPython/3.10.2
Server: WSGIServer/0.2 CPython/3.10.2
< Content-Type: text/html
Content-Type: text/html
< X-Content-Type-Options: nosniff
X-Content-Type-Options: nosniff
< Referrer-Policy: same-origin
Referrer-Policy: same-origin
< Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin
< Connection: close
Connection: close
<
* Excess found in a non pipelined read: excess = 143 url = / (zero-length body)
* Closing connection 0
</code>```

答: This was related to django settings.py running inside container and causing 'bad request' responses. The problem was values in settings.py ALLOWED_HOSTS list. I was using domain names with 'https://' prefix like 'https://my-site.com'. Removing prefixes to values like 'my-site.com' fixed the problem.

Body:
I'm not strong at nginx, but trying to setup nginx prod server (host) redirect to dockerized app as my-site.com and subdomain.my-site.com to another dockerized app. Both apps have different ports open.
Host is running on ubuntu: 18.04, nginx version: nginx/1.18.0.
My host server nginx.conf is:

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
#
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}

I have added /etc/nginx/sites-available/my-site.com.conf:

server {
    listen 80;
    listen [::]:80;
    server_name my-site.com www.my-site.com;
    root /var/www/my-site;

    location / {
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_redirect off;
    }
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/venckus-software.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/venckus-software.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

And the subdomain /etc/nginx/sites-available/subdomain.my-site.com.conf:

server {
    listen 80;
    listen [::]:80;
    server_name subdomain.my-site.com www.subdomain.my-site.com;
    root /var/www/subdomain;

    location / {
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:8081/;
        proxy_set_header X-Real-IP $remote_addr;
        # proxy_ssl_server_name on;
        proxy_redirect off;
    }
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my-site.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/my-site.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

Symlinks are created at /etc/nginx/sites-enabled for both my-site.com.conf and subdomain.my-site.com.conf, Docker containers are up and running without problems.

The issue is nginx is loading default index.html located at /var/www/html when trying to access my-site.com or subdomain.my-site.com. What am I missing, what is wrong?

UPDATE:
here is nginx -T output:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
# configuration file /etc/nginx/nginx.conf:
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        types_hash_max_size 2048;
        # server_tokens off;

        # server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # SSL Settings
        ##

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
        ssl_prefer_server_ciphers on;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip on;

        # gzip_vary on;
        # gzip_proxied any;
        # gzip_comp_level 6;
        # gzip_buffers 16 8k;
        # gzip_http_version 1.1;
        # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

        ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}

#mail {
#       # See sample authentication script at:
#       # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#       # auth_http localhost/auth.php;
#       # pop3_capabilities "TOP" "USER";
#       # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#       server {
#               listen     localhost:110;
#               protocol   pop3;
#               proxy      on;
#       }
#
#       server {
#               listen     localhost:143;
#               protocol   imap;
#               proxy      on;
#       }
#}

# configuration file /etc/nginx/modules-enabled/50-mod-http-geoip.conf:
load_module modules/ngx_http_geoip_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-image-filter.conf:
load_module modules/ngx_http_image_filter_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-http-xslt-filter.conf:
load_module modules/ngx_http_xslt_filter_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-mail.conf:
load_module modules/ngx_mail_module.so;

# configuration file /etc/nginx/modules-enabled/50-mod-stream.conf:
load_module modules/ngx_stream_module.so;

# configuration file /etc/nginx/modules-enabled/70-mod-stream-geoip.conf:
load_module modules/ngx_stream_geoip_module.so;

# configuration file /etc/nginx/mime.types:

types {
    text/html                             html htm shtml;
    text/css                              css;
    text/xml                              xml;
    image/gif                             gif;
    image/jpeg                            jpeg jpg;
    application/javascript                js;
    application/atom+xml                  atom;
    application/rss+xml                   rss;

    text/mathml                           mml;
    text/plain                            txt;
    text/vnd.sun.j2me.app-descriptor      jad;
    text/vnd.wap.wml                      wml;
    text/x-component                      htc;

    image/png                             png;
    image/tiff                            tif tiff;
    image/vnd.wap.wbmp                    wbmp;
    image/x-icon                          ico;
    image/x-jng                           jng;
    image/x-ms-bmp                        bmp;
    image/svg+xml                         svg svgz;
    image/webp                            webp;

    application/font-woff                 woff;
    application/java-archive              jar war ear;
    application/json                      json;
    application/mac-binhex40              hqx;
    application/msword                    doc;
    application/pdf                       pdf;
    application/postscript                ps eps ai;
    application/rtf                       rtf;
    application/vnd.apple.mpegurl         m3u8;
    application/vnd.ms-excel              xls;
    application/vnd.ms-fontobject         eot;
    application/vnd.ms-powerpoint         ppt;
    application/vnd.wap.wmlc              wmlc;
    application/vnd.google-earth.kml+xml  kml;
    application/vnd.google-earth.kmz      kmz;
    application/x-7z-compressed           7z;
    application/x-cocoa                   cco;
    application/x-java-archive-diff       jardiff;
    application/x-java-jnlp-file          jnlp;
    application/x-makeself                run;
    application/x-perl                    pl pm;
    application/x-pilot                   prc pdb;
    application/x-rar-compressed          rar;
    application/x-redhat-package-manager  rpm;
    application/x-sea                     sea;
    application/x-shockwave-flash         swf;
    application/x-stuffit                 sit;
    application/x-tcl                     tcl tk;
    application/x-x509-ca-cert            der pem crt;
    application/x-xpinstall               xpi;
    application/xhtml+xml                 xhtml;
    application/xspf+xml                  xspf;
    application/zip                       zip;

    application/octet-stream              bin exe dll;
    application/octet-stream              deb;
    application/octet-stream              dmg;
    application/octet-stream              iso img;
    application/octet-stream              msi msp msm;

    application/vnd.openxmlformats-officedocument.wordprocessingml.document    docx;
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet          xlsx;
    application/vnd.openxmlformats-officedocument.presentationml.presentation  pptx;

    audio/midi                            mid midi kar;
    audio/mpeg                            mp3;
    audio/ogg                             ogg;
    audio/x-m4a                           m4a;
    audio/x-realaudio                     ra;

    video/3gpp                            3gpp 3gp;
    video/mp2t                            ts;
    video/mp4                             mp4;
    video/mpeg                            mpeg mpg;
    video/quicktime                       mov;
    video/webm                            webm;
    video/x-flv                           flv;
    video/x-m4v                           m4v;
    video/x-mng                           mng;
    video/x-ms-asf                        asx asf;
    video/x-ms-wmv                        wmv;
    video/x-msvideo                       avi;
}

# configuration file /etc/nginx/sites-enabled/sms:
server {
    listen 80;
    root /var/www/sms;
    server_name sms.my-site.com www.sms.my-site.com;

    location / {
       include proxy_params;
       proxy_pass http://unix:/var/www/sms/sms.sock;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my-site.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/my-site.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

# configuration file /etc/nginx/proxy_params:
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

# configuration file /etc/letsencrypt/options-ssl-nginx.conf:
# This file contains important security parameters. If you modify this file
# manually, Certbot will be unable to automatically provide future security
# updates. Instead, Certbot will print and log an error message with a path to
# the up-to-date file that you will need to refer to when manually updating
# this file.

ssl_session_cache shared:le_nginx_SSL:1m;
ssl_session_timeout 1440m;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;

ssl_ciphers "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS";

# configuration file /etc/nginx/sites-enabled/subdomain.my-site.com.conf:
# Subdomain routing
server {
        listen 80;
        listen [::]:80;
        server_name subdomain.my-site.com www.subdomain.my-site.com;
        root /var/www/subdomain;

        location / {
                proxy_set_header Host $host;
                proxy_pass http://127.0.0.1:8081/;
                proxy_set_header X-Real-IP $remote_addr;
                # proxy_ssl_server_name on;
                proxy_redirect off;
        }
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my-site.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/my-site.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

# configuration file /etc/nginx/sites-enabled/default:
##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# https://www.nginx.com/resources/wiki/start/
# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
# https://wiki.debian.org/Nginx/DirectoryStructure
#
# In most cases, administrators will remove this file from sites-enabled/ and
# leave it as reference inside of sites-available where it will continue to be
# updated by the nginx packaging team.
#
# This file will automatically load configuration files provided by other
# applications, such as Drupal or Wordpress. These applications will be made
# available underneath a path with that package name, such as /drupal8.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
        listen 80 default_server;
        listen [::]:80 default_server;

        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
        #
        # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/snakeoil.conf;

        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        # pass PHP scripts to FastCGI server
        #
        #location ~ \.php$ {
        #       include snippets/fastcgi-php.conf;
        #
        #       # With php-fpm (or other unix sockets):
        #       fastcgi_pass unix:/run/php/php7.4-fpm.sock;
        #       # With php-cgi (or other tcp sockets):
        #       fastcgi_pass 127.0.0.1:9000;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #       deny all;
        #}
}

# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#       listen 80;
#       listen [::]:80;
#
#       server_name example.com;
#
#       root /var/www/example.com;
#       index index.html;
#
#       location / {
#               try_files $uri $uri/ =404;
#       }
#}

# configuration file /etc/nginx/sites-enabled/my-site.com.conf:
# domain routing
server {
        listen 80;
        listen [::]:80;
        server_name my-site.com www.my-site.com;
        root /var/www/my-site;

        location / {
                proxy_set_header Host $host;
                proxy_pass http://127.0.0.1:8000;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_redirect off;
        }
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/my-site.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/my-site.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

Update 2:
as @IvanShatsky suggested - the curl -v -I localhost:8000 give this response:

* Rebuilt URL to: localhost:8000/
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8000 (#0)
> HEAD / HTTP/1.1
> Host: localhost:8000
> User-Agent: curl/7.58.0
> Accept: */*
>
< HTTP/1.1 400 Bad Request
HTTP/1.1 400 Bad Request
< Date: Tue, 08 Feb 2022 15:52:12 GMT
Date: Tue, 08 Feb 2022 15:52:12 GMT
< Server: WSGIServer/0.2 CPython/3.10.2
Server: WSGIServer/0.2 CPython/3.10.2
< Content-Type: text/html
Content-Type: text/html
< X-Content-Type-Options: nosniff
X-Content-Type-Options: nosniff
< Referrer-Policy: same-origin
Referrer-Policy: same-origin
< Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin
< Connection: close
Connection: close
<
* Excess found in a non pipelined read: excess = 143 url = / (zero-length body)
* Closing connection 0


问:
Get Context in a Jetpack Compose Noncomposable function
I want to insert some data into Firebase. for that, I have a non-composable function and in that function, I'd like to call Toast.makeText . . in the .addOnSuccessListener part.
However, there's no way for me to get the context that should be in the Toast.makeText statement

```<code>fun saveActivityToFB(
    answer: String,
    question: String,
    id: String
) {

    var db: DatabaseReference = Firebase.database.reference
    val ques = Question(answer, question)

    db.child("activity").child("test").child(id).setValue(ques)
        .addOnSuccessListener {
            Log.d("FB", "OK")

           //problems with context here!!
            Toast.makeText(context, "Successfully Added to FB", Toast.LENGTH_SHORT).show()

        }
        .addOnFailureListener {
            Log.d("FB", "Not inserted into FB")
        }
}

</code>```

I know that in order to display Toast from composable function, I should get context as:

val context = LocalContext.current

But have no idea how to get the context in this case.

答:
```<code>@Composable
fun Test(){
    val context = LocalContext.current // here no problem getting context
    var db: DatabaseReference = Firebase.database.reference
    db.child("activity").child("test").child(id).setValue(ques)
    .addOnSuccessListener {
        Log.d("FB", "OK")

       //use context from outside of the scope here
        Toast.makeText(context, "Successfully Added to FB", Toast.LENGTH_SHORT).show()

    }
    .addOnFailureListener {
        Log.d("FB", "Not inserted into FB")
    }

}
</code>```

Body:
I want to insert some data into Firebase. for that, I have a non-composable function and in that function, I'd like to call Toast.makeText . . in the .addOnSuccessListener part.
However, there's no way for me to get the context that should be in the Toast.makeText statement

fun saveActivityToFB(
    answer: String,
    question: String,
    id: String
) {

    var db: DatabaseReference = Firebase.database.reference
    val ques = Question(answer, question)

    db.child("activity").child("test").child(id).setValue(ques)
        .addOnSuccessListener {
            Log.d("FB", "OK")

           //problems with context here!!
            Toast.makeText(context, "Successfully Added to FB", Toast.LENGTH_SHORT).show()

        }
        .addOnFailureListener {
            Log.d("FB", "Not inserted into FB")
        }
}

I know that in order to display Toast from composable function, I should get context as:

val context = LocalContext.current

But have no idea how to get the context in this case.


问:
Rails/HTML mount three buttons alongside
I've got 3 buttons that are next to each other and in my Macbook 13'' everything looks like it should:

But it turns out on a Zenbook 14 (which has a bigger screen?!) things get weird:

I'm using bootstrap, how to prevent such situation? Code below:

```<code>Status: <%= UserAuthorization.statuses[authorization.status].upcase %>
</br>
<% unless authorization.approved? %>
  <button class="modal-trigger btn btn-bh btn-xs btn-lng",
          data-toggle="modal",
          data-target="#confirm-caregiver-approve",
          data-modal-confirm-url="<%= approve_caregiver_authorization_path(authorization, registrant_page: true) %>">
          APPROVE
  </button>
<% end %>
<% unless authorization.declined? %>
  <button class="modal-trigger btn btn-bh btn-xs btn-lng",
          data-toggle="modal",
          data-target="#confirm-caregiver-decline",
          data-modal-confirm-url="<%= decline_caregiver_authorization_path(authorization, registrant_page: true) %>">
          DECLINE
  </button>
<% end %>
<% if authorization.pending? %>
  <button class="modal-trigger btn btn-bh btn-xs btn-lng",
          data-toggle="modal",
          data-target="#confirm-caregiver-in_review",
          data-modal-confirm-url="<%= in_review_caregiver_authorization_path(authorization, registrant_page: true) %>">
          IN REVIEW
  </button>
<% end %>
</code>```

[Edit]

This file is a partial so the file that renders it looks like this:

```<code><div class="row">
  <div class="col-md-12">
    <%= render partial: 'user_authorizations/user_authorization_review',
               locals: { authorization: registrant.user_authorizations.last } %>
  </div>
</div>
</code>```

When I'm trying to add grid like below:

```<code><div class="container">
  <div class="row">
    <div class="col-md-4">
      button here
    </div>
    <div class="col-md-4">
      button here
    </div>
    <div class="col-md-4">
      button here
    </div>
  </div>
</div>
</code>```

It's even worst:

答:
As you're using Bootstrap I would suggest you to use the Grid layout and wrap your buttons into a row.

Here is something that might match:

      button here

      button here

      button here

```

Body:
I've got 3 buttons that are next to each other and in my Macbook 13'' everything looks like it should:

But it turns out on a Zenbook 14 (which has a bigger screen?!) things get weird:

I'm using bootstrap, how to prevent such situation? Code below:

Status: <%= UserAuthorization.statuses[authorization.status].upcase %>

<% unless authorization.approved? %>
  <button class="modal-trigger btn btn-bh btn-xs btn-lng",
          data-toggle="modal",
          data-target="#confirm-caregiver-approve",
          data-modal-confirm-url="<%= approve_caregiver_authorization_path(authorization, registrant_page: true) %>">
          APPROVE
  </button>
<% end %>
<% unless authorization.declined? %>
  <button class="modal-trigger btn btn-bh btn-xs btn-lng",
          data-toggle="modal",
          data-target="#confirm-caregiver-decline",
          data-modal-confirm-url="<%= decline_caregiver_authorization_path(authorization, registrant_page: true) %>">
          DECLINE
  </button>
<% end %>
<% if authorization.pending? %>
  <button class="modal-trigger btn btn-bh btn-xs btn-lng",
          data-toggle="modal",
          data-target="#confirm-caregiver-in_review",
          data-modal-confirm-url="<%= in_review_caregiver_authorization_path(authorization, registrant_page: true) %>">
          IN REVIEW
  </button>
<% end %>

[Edit]

This file is a partial so the file that renders it looks like this:

    <%= render partial: 'user_authorizations/user_authorization_review',
               locals: { authorization: registrant.user_authorizations.last } %>

When I'm trying to add grid like below:

      button here

      button here

      button here

It's even worst:

Body:
As you're using Bootstrap I would suggest you to use the Grid layout and wrap your buttons into a row.

Here is something that might match:

<div class="container">
  <div class="row">
    <div class="col-md-2">
      button here
    </div>
    <div class="col-md-2">
      button here
    </div>
    <div class="col-md-2">
      button here
    </div>
  </div>
</div>


问:
Flutter Cloud Firestore: error: The argument type 'Object? Function()' can't be assigned to the parameter type 'Map<String, dynamic>'
I am trying to update some code which used an old Firestore version which is version 0.9.13 and I am updating it to the latest version. This code should pull data and populate a graph.

I have tried downgrading and upgrading to find a version that works, I can't seem to find a working version. There is a suggestion of adding a new argument to the model however I am unsure if this is the correct method.

Error Message:

```<code>error: The argument type 'Object? Function()' can't be assigned to the parameter type 'Map<String, dynamic>'. (argument_type_not_assignable at [firebase] lib\code\moodhomepage.dart:47)
</code>```

Code:

```<code>Widget _buildBody(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
  stream: FirebaseFirestore.instance.collection('moods').snapshots(),
  builder: (context, snapshot) {
    if (!snapshot.hasData) {
      return LinearProgressIndicator();
    } else {
      List<Mood> mood = snapshot.data!.docs
          .map((documentSnapshot) => Mood.fromMap(documentSnapshot.data))
          .toList();
      return _buildChart(context, mood);
    }
  },
);
</code>```

}

答:
Add the type of the returned data:

Change this:

```<code>return StreamBuilder<QuerySnapshot>(
</code>```

into this:

```<code>return StreamBuilder<QuerySnapshot<Map<String,dynamic>>(
</code>```

Body:
I am trying to update some code which used an old Firestore version which is version 0.9.13 and I am updating it to the latest version. This code should pull data and populate a graph.

I have tried downgrading and upgrading to find a version that works, I can't seem to find a working version. There is a suggestion of adding a new argument to the model however I am unsure if this is the correct method.

Error Message:

error: The argument type 'Object? Function()' can't be assigned to the parameter type 'Map<String, dynamic>'. (argument_type_not_assignable at [firebase] lib\code\moodhomepage.dart:47)

Code:

Widget _buildBody(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
  stream: FirebaseFirestore.instance.collection('moods').snapshots(),
  builder: (context, snapshot) {
    if (!snapshot.hasData) {
      return LinearProgressIndicator();
    } else {
      List<Mood> mood = snapshot.data!.docs
          .map((documentSnapshot) => Mood.fromMap(documentSnapshot.data))
          .toList();
      return _buildChart(context, mood);
    }
  },
);

}

Body:
Add the type of the returned data:

Change this:

return StreamBuilder<QuerySnapshot>(

into this:

return StreamBuilder<QuerySnapshot<Map<String,dynamic>>(


问:
How to add item to an array in Mongodb?
I am having trouble in appending data into an array in mongodb.
This is my schema:

const userSchema=mongoose.Schema({
    name: String,
    email: String,
    password: String,
    blog: [{
        date: Date,
        post: String
    }],
    week: [{
        weekday: String,
        tasks:[String]
    }],
    todo: [String]
});

const User= mongoose.model("User", userSchema);```
</div>
</div>
</p>
<p>I want to add data to todo but it is not working. Here is the code for that:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>app.post("/list", (req,res) =>{
    console.log(req.body);
    const user = req.body.userid;
    const item = req.body.data;

    console.log(user);
    console.log(item);
    User.findOne({_id: user}, function(err, foundUser){
        if(err){
            console.log(err);
        } else{
            foundUser.todo.push(item);
            foundUser.save();
            res.send("ToDo Updated");
        }
    });
});</code>```

I am getting user and item from the frontend. When I am console logging foundUser then I am getting the user but I am not able to add item to it.

答:
```<code>app.post("/list", (req,res) =>{
    console.log(req.body);
    const user = req.body.userid;
    const item = req.body.data;

    console.log(user);
    console.log(item);
    User.findOne({_id: user}, function(err, foundUser){
        if(err){
            console.log(err);
        } else{
            foundUser.todo.push(item);
            await User.updateOne({ _id: foundUser._id }, { $set: foundUser });
            res.send("ToDo Updated");
        }
    });
});
</code>```

Another approach

Title: How to add item to an array in Mongodb?

Body:
I am having trouble in appending data into an array in mongodb.
This is my schema:

const userSchema=mongoose.Schema({
    name: String,
    email: String,
    password: String,
    blog: [{
        date: Date,
        post: String
    }],
    week: [{
        weekday: String,
        tasks:[String]
    }],
    todo: [String]
});

const User= mongoose.model("User", userSchema);

I want to add data to todo but it is not working. Here is the code for that:

app.post("/list", (req,res) =>{
    console.log(req.body);
    const user = req.body.userid;
    const item = req.body.data;

    console.log(user);
    console.log(item);
    User.findOne({_id: user}, function(err, foundUser){
        if(err){
            console.log(err);
        } else{
            foundUser.todo.push(item);
            foundUser.save();
            res.send("ToDo Updated");
        }
    });
});

I am getting user and item from the frontend. When I am console logging foundUser then I am getting the user but I am not able to add item to it.

Body:
app.post("/list", (req,res) =>{
    console.log(req.body);
    const user = req.body.userid;
    const item = req.body.data;

    console.log(user);
    console.log(item);
    User.findOne({_id: user}, function(err, foundUser){
        if(err){
            console.log(err);
        } else{
            foundUser.todo.push(item);
            await User.updateOne({ _id: foundUser._id }, { $set: foundUser });
            res.send("ToDo Updated");
        }
    });
});

Another approach


问:
iframe Fits complete webpage as on Full HD Screen in to a small Window

In first Picture I have 6 iframes being loaded and each having its own HTML page. All pages in those iframes are responsive so they got adjust as per the size.

But I want to make it look like exactly the same those HTML pages would look in 1920x1080 resolution screen (shown in image 2)

Image 2 is the HTML page being loaded in the second row first iframe of Image 1

答:
You probably forgot to set the size to iframes. The code below helped me without any problems:

CSS Code:

```<code>div {
  width: 31%;
  height: 294px;
  margin: 0 auto;
}
iframe {
  width: -webkit-fill-available;
  height: -webkit-fill-available;
  overflow: hidden;
  border: 0;
}
</code>```

Body:
You probably forgot to set the size to iframes. The code below helped me without any problems:

CSS Code:

div {
  width: 31%;
  height: 294px;
  margin: 0 auto;
}
iframe {
  width: -webkit-fill-available;
  height: -webkit-fill-available;
  overflow: hidden;
  border: 0;
}


问:
Retrieve azure service bus messages using google functions
So the scenario is that there is a ML model running in google cloud and the input to that needs to be send in form of an azure service bus message. Is this even possible?

I need to implement a handler (google cloud function) to retrieve messages from azure service bus.

答:
You can use Azure service bus’ SDK and write your own code to retrieve it. You can go through these Azure Service Bus Client library for python samples, which may help you in writing your code.

You will need to trigger the function whenever you want to retrieve the messages from the service bus, to do that either you can use Cloud Scheduler to set a trigger timer or have Azure side trigger the HTTP URL of Cloud Functions.


问:
vue js import from node_modules
I am new to vue js and currently trying to import any vue plugin/component into other sfc .vue files for usage.

Currently I am using VS code with vue create project cli setup and in my main App.vue file I am trying to import plugin after installation via npm.

I have came across this code at many places but not sure from where this has been imported. Also not sure how this path system works?

```<code>import SomePlugin from 'some-plugin';
</code>```

My guess is that this comes inside node_modules folder after npm install cli part. Do we need to include full path of node_modules folder or vue-cli handles this automatically as full path looks weird.

```<code>import SomePlugin from '../node_modules/some-plugin';
</code>```

答: Importing using only the package name will always look in the node_modules folder, regardless of whether the node_modules is in the current directory, the parent directory, or the global directory. Unless if the path is preceded by ./, ../, etc.

Title: vue js import from node_modules

Body:
I am new to vue js and currently trying to import any vue plugin/component into other sfc .vue files for usage.

Currently I am using VS code with vue create project cli setup and in my main App.vue file I am trying to import plugin after installation via npm.

I have came across this code at many places but not sure from where this has been imported. Also not sure how this path system works?

import SomePlugin from 'some-plugin';

My guess is that this comes inside node_modules folder after npm install cli part. Do we need to include full path of node_modules folder or vue-cli handles this automatically as full path looks weird.

import SomePlugin from '../node_modules/some-plugin';