问:
Docker connection refused between containers after compose
We are using a docker compose file to release our .NET based microservice architecture. However since we introduced env files for the services, releases never go according to what they used to.

These env files only contain secrets/keys/connstrings no critical data, that is required for running.

The docker compose task, portainer and logs show no error or anything out of the ordinary, but the main entry point container can't reach a few of them, giving no timeout or unknown host, but a Connection Refused response immediately. We stop a "missing" container, wait 10 seconds, start the container and it magically works. Not all container communication is faulty, but usually the same ones after every release.

The containers are in a named stack and automatically added to the default network of the stack.

The machine in question is an on-premise linux system in Hyper-V, running Ubuntu 20.04 and Docker version is 20.10.17.

Docker compose file snippet, launched via command docker-compose -p demo up -d --build

```<code>services:
  service1:
    image: service1
    hostname: service1.hostname
    build:
      context: .
      dockerfile: ./service1.Dockerfile
    env_file:
      - service1.env

  service2:
    image: service2
    hostname: service2.hostname
    build:
      context: .
      dockerfile: ./service2.Dockerfile
    ports:
      - 15443:443
    env_file:
      - service2.env
</code>```

The services are assigned a hostname each in the compose file and they are communicating using that hostname. These are 2 of the service examples from the docker compose file, the containers use the https://service1.hostname pattern to communicate.

Azure is only marked in the labels, because it is deployed via an azure release pipeline, but with our self-hosted agent, so I'm not sure if it's relevant.

Body:
We are using a docker compose file to release our .NET based microservice architecture. However since we introduced env files for the services, releases never go according to what they used to.

These env files only contain secrets/keys/connstrings no critical data, that is required for running.

The docker compose task, portainer and logs show no error or anything out of the ordinary, but the main entry point container can't reach a few of them, giving no timeout or unknown host, but a Connection Refused response immediately. We stop a "missing" container, wait 10 seconds, start the container and it magically works. Not all container communication is faulty, but usually the same ones after every release.

The containers are in a named stack and automatically added to the default network of the stack.

The machine in question is an on-premise linux system in Hyper-V, running Ubuntu 20.04 and Docker version is 20.10.17.

Docker compose file snippet, launched via command docker-compose -p demo up -d --build

services:
  service1:
    image: service1
    hostname: service1.hostname
    build:
      context: .
      dockerfile: ./service1.Dockerfile
    env_file:
      - service1.env

  service2:
    image: service2
    hostname: service2.hostname
    build:
      context: .
      dockerfile: ./service2.Dockerfile
    ports:
      - 15443:443
    env_file:
      - service2.env

The services are assigned a hostname each in the compose file and they are communicating using that hostname. These are 2 of the service examples from the docker compose file, the containers use the https://service1.hostname pattern to communicate.

Azure is only marked in the labels, because it is deployed via an azure release pipeline, but with our self-hosted agent, so I'm not sure if it's relevant.


来源: stackexchange

问:
'WebDriver' object is not callable
I am trying to call webdriver from another but its showing me typeError with webdriver is not callable

fileName: "call_folder1"

```<code>import sys
sys.path.insert(1,"/Users/akru/Desktop/AKRU-Automation/automation-scripts/Staging/test_folder1/")

import Login_yopmail

obj1=Login_yopmail.setUpDriver()
obj1.initiate_driver()
driver=obj1.driver()

class login_yopmail:
    def access_url(self):
        url="https://avaxdev.akru.co"

    def entre_email():
        print("Login yopmail")
        pass

</code>```

here is file containing webriver

```<code>#import unittest
from selenium import webdriver
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service as ChromeService

class setUpDriver:
    def initiate_driver(self):
        WINDOW_SIZE = "1920,1080"
        chrome_options = Options()
        #chrome_options.add_argument("--headless")
        chrome_options.add_argument("--disable-gpu")
        chrome_options.add_argument("--disable-popup-blocking")
        chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
        chrome_options.add_argument('--no-sandbox')
        chrome_options.add_argument('--start-maximized')
        chrome_options.add_argument('--disable-setuid-sandbox')
        service = ChromeService(executable_path=ChromeDriverManager().install())
        self.driver = webdriver.Chrome(service=service , options=chrome_options)
        driver=self.driver
        return driver
</code>```

I am trying to call webdriver initiated in another python filer from another directory

ContentLicense: CC BY-SA 4.0

Title: 'WebDriver' object is not callable

Body:
I am trying to call webdriver from another but its showing me typeError with webdriver is not callable

fileName: "call_folder1"

import sys
sys.path.insert(1,"/Users/akru/Desktop/AKRU-Automation/automation-scripts/Staging/test_folder1/")

import Login_yopmail

obj1=Login_yopmail.setUpDriver()
obj1.initiate_driver()
driver=obj1.driver()

class login_yopmail:
    def access_url(self):
        url="https://avaxdev.akru.co"

    def entre_email():
        print("Login yopmail")
        pass

here is file containing webriver

#import unittest
from selenium import webdriver
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service as ChromeService

class setUpDriver:
    def initiate_driver(self):
        WINDOW_SIZE = "1920,1080"
        chrome_options = Options()
        #chrome_options.add_argument("--headless")
        chrome_options.add_argument("--disable-gpu")
        chrome_options.add_argument("--disable-popup-blocking")
        chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
        chrome_options.add_argument('--no-sandbox')
        chrome_options.add_argument('--start-maximized')
        chrome_options.add_argument('--disable-setuid-sandbox')
        service = ChromeService(executable_path=ChromeDriverManager().install())
        self.driver = webdriver.Chrome(service=service , options=chrome_options)
        driver=self.driver
        return driver

I am trying to call webdriver initiated in another python filer from another directory


问:
Passing arguments into an Assebly function
I'm trying to pass some arguments into a function but it doesn't get them correctly. I want to multiply some matrices and I want to pass: address of matrix 1, address of matrix 2, address of the matrix i want the result to be in, and the size of the matrix.

```<code>matrix_mult:
pushl %ebp
pushl %ebx
pushl %edi
pushl %esi
movl %esp, %ebp

movl 8(%ebp), %edi
movl 12(%ebp), %esi
movl 16(%ebp), %ebx
movl 20(%ebp), %ecx

*the rest of the algorithm*
</code>```

After those lines, the values in edi, esi, ebx, ecx are all wrong.

The function calling looks like this - trying to multiply matrix by itself and storing the result into matrix2. The matrix and msizze are stored correctly.

```<code>main:
*reading msize and matrix*

pushl msize
pushl $matrix2
pushl $matrix
pushl $matrix
call matrix_mult
addl $16, %esp

</code>```

In the debugger it shows me that:
edi = 2
esi = big negative value
ebx = big positive value
ecx = big positive value

Body:
I'm trying to pass some arguments into a function but it doesn't get them correctly. I want to multiply some matrices and I want to pass: address of matrix 1, address of matrix 2, address of the matrix i want the result to be in, and the size of the matrix.

matrix_mult:
pushl %ebp
pushl %ebx
pushl %edi
pushl %esi
movl %esp, %ebp

movl 8(%ebp), %edi
movl 12(%ebp), %esi
movl 16(%ebp), %ebx
movl 20(%ebp), %ecx

*the rest of the algorithm*

After those lines, the values in edi, esi, ebx, ecx are all wrong.

The function calling looks like this - trying to multiply matrix by itself and storing the result into matrix2. The matrix and msizze are stored correctly.

main:
*reading msize and matrix*

pushl msize
pushl $matrix2
pushl $matrix
pushl $matrix
call matrix_mult
addl $16, %esp

In the debugger it shows me that:
edi = 2
esi = big negative value
ebx = big positive value
ecx = big positive value


问:
Clustered Stack Bar chart in Google Data Studio
I have a requirement to create a clustered stacked bar chart with Google Data Studio.

Sample Data looks like,

owner_name
closing_price
open_price
won_price
won_count
total_count

Owner1
408000
500000
408000
4
5

Owner1
549000
550000
549000
3
6

Owner1
320000
350000
320000
2
7

Owner2
120000
120000
120000
4
8

Owner2
400000
500000
400000
5
9

Owner2
800000
900000
800000
7
8

Owner2
456000
460000
456000
8
9

Owner3
659000
660000
659000
9
10

Sample Dataset - https://docs.google.com/spreadsheets/d/1M8EcQC8rXSuyOP_SUYjgGISbLNEurEqo15rxHLlgrRk/edit?usp=sharing

Dimension -
owner_name

Metrics

SUM of won_price

On top of the SUM of won price bar there should be SUM(open_price + won_price) - This is a stacked bar

Next to that bar there should be SUM(won_price/100 * 75%)

On top of the point 3 bar there should be SUM(open_price)

(these dimension and metrics might be wrong as I've defined these)
Also the owner_name in X Axis label should looks like,

```<code>   Owner1
 2 Won Deals
 (4 Deals)
</code>```

It should looks like below image. Tried many things. But ended up with the following 2nd image result.

Expected Result

Result What I Got

Report I tried can be found here

Is there any possibility to achieve above type clustered stacked bar chart in google data studio?

Body:
I have a requirement to create a clustered stacked bar chart with Google Data Studio.

Sample Data looks like,

owner_name
closing_price
open_price
won_price
won_count
total_count

Owner1
408000
500000
408000
4
5

Owner1
549000
550000
549000
3
6

Owner1
320000
350000
320000
2
7

Owner2
120000
120000
120000
4
8

Owner2
400000
500000
400000
5
9

Owner2
800000
900000
800000
7
8

Owner2
456000
460000
456000
8
9

Owner3
659000
660000
659000
9
10

Sample Dataset - https://docs.google.com/spreadsheets/d/1M8EcQC8rXSuyOP_SUYjgGISbLNEurEqo15rxHLlgrRk/edit?usp=sharing

Dimension -
owner_name

Metrics

SUM of won_price

On top of the SUM of won price bar there should be SUM(open_price + won_price) - This is a stacked bar

Next to that bar there should be SUM(won_price/100 * 75%)

On top of the point 3 bar there should be SUM(open_price)

(these dimension and metrics might be wrong as I've defined these)
Also the owner_name in X Axis label should looks like,

   Owner1
 2 Won Deals
 (4 Deals)

It should looks like below image. Tried many things. But ended up with the following 2nd image result.

Expected Result

Result What I Got

Report I tried can be found here

Is there any possibility to achieve above type clustered stacked bar chart in google data studio?


问:
Cordova iOS single size icon support
Does Cordova support single-size icons for iOS and if so, how to add it to config.xml?

I removed all the different icon sizes and just left

<icon height="1024" src="src/resources/images/Icons/ios/Icon-App-1024x1024.png" width="1024" />

But either way, I only get the default Cordova icon to display.

If I set it to single size in Xcode it works as expected.

Deployment is through Azure Pipeline, so I can´t set it manually for release.

Title: Cordova iOS single size icon support


问:
Flutter type '(dynamic) => Search' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform'
I am trying to make a search function but I am getting the following error: type '(dynamic) => Search' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform', the function in which the error:

```<code> static Future<List<Search>> searchProducts(String search) async {
    var url =
        '${Constants.API_URL_DOMAIN}action=search&token=${Constants.USER_TOKEN}&q=$search';
    final response = await http.get(Uri.parse(url));
    final body = jsonDecode(response.body);
    print(url);
    return List.from(body['data'].map((e) => Search.fromJson(e)).toList());
  }

  late Future<List<Search>> searchFuture = Func.searchProducts(searchController.text);
  Widget buildSearch() => FutureBuilder<List<Search>>(
      future: searchFuture,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Column(
            children: [
              Text('test')
            ],
          );
        } else {
          print(snapshot.error);
          print('error');
          return const Text('error');
        }
      }
  );
</code>```

I can't figure out where this error comes from, I have similar functions in other parts of the code and they work fine.
My Search class :

```<code>class Search {
  Search({
    required this.products,
    required this.categories,
  });
  late final Products products;
  late final Categories categories;

  Search.fromJson(Map<String, dynamic> json){
    products = Products.fromJson(json['products']);
    categories = Categories.fromJson(json['categories']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['products'] = products.toJson();
    _data['categories'] = categories.toJson();
    return _data;
  }
}

class Products {
  Products({
    required this.total,
    required this.items,
  });
  late final int total;
  late final List<Items> items;

  Products.fromJson(Map<String, dynamic> json){
    total = json['total'];
    items = List.from(json['items']).map((e)=>Items.fromJson(e)).toList();
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['total'] = total;
    _data['items'] = items.map((e)=>e.toJson()).toList();
    return _data;
  }
}

class Items {
  Items({
    required this.id,
    required this.name,
    required this.isFavorite,
    required this.price,
    required this.link,
    this.media,
  });
  late final int id;
  late final String name;
  late final bool isFavorite;
  late final int price;
  late final String link;
  late final List<Media>? media;

  Items.fromJson(Map<String, dynamic> json){
    id = json['id'];
    name = json['name'];
    isFavorite = json['is_favorite'];
    price = json['price'];
    link = json['link'];
    media = null;
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['id'] = id;
    _data['name'] = name;
    _data['is_favorite'] = isFavorite;
    _data['price'] = price;
    _data['link'] = link;
    _data['media'] = media;
    return _data;
  }
}

class Media {
  Media({
    required this.id,
    required this.productId,
    required this.type,
    required this.links,
    this.position,
    required this.createdAt,
    required this.updatedAt,
  });
  late final int id;
  late final int productId;
  late final String type;
  late final Links links;
  late final Null position;
  late final String createdAt;
  late final String updatedAt;

  Media.fromJson(Map<String, dynamic> json){
    id = json['id'];
    productId = json['product_id'];
    type = json['type'];
    links = Links.fromJson(json['links']);
    position = null;
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['id'] = id;
    _data['product_id'] = productId;
    _data['type'] = type;
    _data['links'] = links.toJson();
    _data['position'] = position;
    _data['created_at'] = createdAt;
    _data['updated_at'] = updatedAt;
    return _data;
  }
}

class Links {
  Links({
    this.s3,
    this.cdn,
    required this.local,
  });
  late final Null s3;
  late final Null cdn;
  late final Local local;

  Links.fromJson(Map<String, dynamic> json){
    s3 = null;
    cdn = null;
    local = Local.fromJson(json['local']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['s3'] = s3;
    _data['cdn'] = cdn;
    _data['local'] = local.toJson();
    return _data;
  }
}

class Local {
  Local({
    required this.full,
    required this.thumbnails,
  });
  late final String full;
  late final Thumbnails thumbnails;

  Local.fromJson(Map<String, dynamic> json){
    full = json['full'];
    thumbnails = Thumbnails.fromJson(json['thumbnails']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['full'] = full;
    _data['thumbnails'] = thumbnails.toJson();
    return _data;
  }
}

class Thumbnails {
  Thumbnails({
  required this.s150,
  required this.s350,
  required this.s750,
});
late final String s150;
late final String s350;
late final String s750;

Thumbnails.fromJson(Map<String, dynamic> json){
s150 = json['150'];
s350 = json['350'];
s750 = json['750'];
}

Map<String, dynamic> toJson() {
  final _data = <String, dynamic>{};
  _data['150'] = 150;
  _data['350'] = 350;
  _data['750'] = 750;
  return _data;
}
}

class Categories {
  Categories({
    required this.total,
    required this.items,
  });
  late final int total;
  late final List<Items> items;

  Categories.fromJson(Map<String, dynamic> json){
    total = json['total'];
    items = List.from(json['items']).map((e)=>Items.fromJson(e)).toList();
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['total'] = total;
    _data['items'] = items.map((e)=>e.toJson()).toList();
    return _data;
  }
}
</code>```

Body:
I am trying to make a search function but I am getting the following error: type '(dynamic) => Search' is not a subtype of type '(String, dynamic) => MapEntry<dynamic, dynamic>' of 'transform', the function in which the error:

 static Future<List<Search>> searchProducts(String search) async {
    var url =
        '${Constants.API_URL_DOMAIN}action=search&token=${Constants.USER_TOKEN}&q=$search';
    final response = await http.get(Uri.parse(url));
    final body = jsonDecode(response.body);
    print(url);
    return List.from(body['data'].map((e) => Search.fromJson(e)).toList());
  }

  late Future<List<Search>> searchFuture = Func.searchProducts(searchController.text);
  Widget buildSearch() => FutureBuilder<List<Search>>(
      future: searchFuture,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Column(
            children: [
              Text('test')
            ],
          );
        } else {
          print(snapshot.error);
          print('error');
          return const Text('error');
        }
      }
  );

I can't figure out where this error comes from, I have similar functions in other parts of the code and they work fine.
My Search class :

class Search {
  Search({
    required this.products,
    required this.categories,
  });
  late final Products products;
  late final Categories categories;

  Search.fromJson(Map<String, dynamic> json){
    products = Products.fromJson(json['products']);
    categories = Categories.fromJson(json['categories']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['products'] = products.toJson();
    _data['categories'] = categories.toJson();
    return _data;
  }
}

class Products {
  Products({
    required this.total,
    required this.items,
  });
  late final int total;
  late final List<Items> items;

  Products.fromJson(Map<String, dynamic> json){
    total = json['total'];
    items = List.from(json['items']).map((e)=>Items.fromJson(e)).toList();
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['total'] = total;
    _data['items'] = items.map((e)=>e.toJson()).toList();
    return _data;
  }
}

class Items {
  Items({
    required this.id,
    required this.name,
    required this.isFavorite,
    required this.price,
    required this.link,
    this.media,
  });
  late final int id;
  late final String name;
  late final bool isFavorite;
  late final int price;
  late final String link;
  late final List<Media>? media;

  Items.fromJson(Map<String, dynamic> json){
    id = json['id'];
    name = json['name'];
    isFavorite = json['is_favorite'];
    price = json['price'];
    link = json['link'];
    media = null;
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['id'] = id;
    _data['name'] = name;
    _data['is_favorite'] = isFavorite;
    _data['price'] = price;
    _data['link'] = link;
    _data['media'] = media;
    return _data;
  }
}

class Media {
  Media({
    required this.id,
    required this.productId,
    required this.type,
    required this.links,
    this.position,
    required this.createdAt,
    required this.updatedAt,
  });
  late final int id;
  late final int productId;
  late final String type;
  late final Links links;
  late final Null position;
  late final String createdAt;
  late final String updatedAt;

  Media.fromJson(Map<String, dynamic> json){
    id = json['id'];
    productId = json['product_id'];
    type = json['type'];
    links = Links.fromJson(json['links']);
    position = null;
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['id'] = id;
    _data['product_id'] = productId;
    _data['type'] = type;
    _data['links'] = links.toJson();
    _data['position'] = position;
    _data['created_at'] = createdAt;
    _data['updated_at'] = updatedAt;
    return _data;
  }
}

class Links {
  Links({
    this.s3,
    this.cdn,
    required this.local,
  });
  late final Null s3;
  late final Null cdn;
  late final Local local;

  Links.fromJson(Map<String, dynamic> json){
    s3 = null;
    cdn = null;
    local = Local.fromJson(json['local']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['s3'] = s3;
    _data['cdn'] = cdn;
    _data['local'] = local.toJson();
    return _data;
  }
}

class Local {
  Local({
    required this.full,
    required this.thumbnails,
  });
  late final String full;
  late final Thumbnails thumbnails;

  Local.fromJson(Map<String, dynamic> json){
    full = json['full'];
    thumbnails = Thumbnails.fromJson(json['thumbnails']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['full'] = full;
    _data['thumbnails'] = thumbnails.toJson();
    return _data;
  }
}

class Thumbnails {
  Thumbnails({
  required this.s150,
  required this.s350,
  required this.s750,
});
late final String s150;
late final String s350;
late final String s750;

Thumbnails.fromJson(Map<String, dynamic> json){
s150 = json['150'];
s350 = json['350'];
s750 = json['750'];
}

Map<String, dynamic> toJson() {
  final _data = <String, dynamic>{};
  _data['150'] = 150;
  _data['350'] = 350;
  _data['750'] = 750;
  return _data;
}
}

class Categories {
  Categories({
    required this.total,
    required this.items,
  });
  late final int total;
  late final List<Items> items;

  Categories.fromJson(Map<String, dynamic> json){
    total = json['total'];
    items = List.from(json['items']).map((e)=>Items.fromJson(e)).toList();
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['total'] = total;
    _data['items'] = items.map((e)=>e.toJson()).toList();
    return _data;
  }
}


问:
How to set an icon for the toolbar using Tkinter
I tried to change the default icons of tkinter (I am actually using customTkinter, but it is suposed to work the same way) and I did change the app icon itself but the icon showing in the toolbar is not what it should be.

here what i've got

here what it shows

I tried using all kind of iconbitmap, wm_icon, etc...


问:
How can i get the value of the country code Selected
I am new to Js and i am able to get the phone number am passing but not able to get the country code i have selected how can i get it in my controller

```<code><!DOCTYPE html>
<html lang="en">
 <head>

   <meta name="viewport" content="width=device-width, initial-scale=1" />
   <link
     rel="stylesheet"
     href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.css"
   />
   <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/intlTelInput.min.js"></script>
 </head>
 <body>
   <input id="phone" type="tel" name="phone" />
 </body>
  <script>
   const phoneInputField = document.querySelector("#phone");
   const phoneInput = window.intlTelInput(phoneInputField, {
     utilsScript:
       "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js",
   });
 </script>
</html>
</code>```

this is my test.php view page

```<code>        public function send_mail() {

        $this->load->library('form_validation');
        $this->form_validation->set_rules('fname', 'First Name', 'required');
        $this->form_validation->set_rules('lname', 'Last Name', 'required');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
        $this->form_validation->set_rules('phone', 'Phone', 'required|regex_match[/^[0-9]{10}$/]');
        $this->form_validation->set_rules('esubject', 'Subject', 'required');
        $this->form_validation->set_rules('msg', 'Message', 'required');
        // $this->form_validation->set_rules('g-recaptcha-response', 'Capcha', 'required');

        if ($this->form_validation->run() == FALSE) {
          $this->load->view('contact');
          }
       else {

      $to = "";
        $cc = "";
        $fname = $this->input->post('fname');
        $lname = $this->input->post('lname');
        $email = $this->input->post('email');
        $phone = $this->input->post('phone');
        echo $phone; exit;
}
}
</code>```

This is my controller Main.php

I need to get the country code and phone number in this variable
$phone;

Body:
I am new to Js and i am able to get the phone number am passing but not able to get the country code i have selected how can i get it in my controller

<!DOCTYPE html>

   <meta name="viewport" content="width=device-width, initial-scale=1" />
   <link
     rel="stylesheet"
     href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.css"
   />

   <input id="phone" type="tel" name="phone" />

this is my test.php view page

        public function send_mail() {

        $this->load->library('form_validation');
        $this->form_validation->set_rules('fname', 'First Name', 'required');
        $this->form_validation->set_rules('lname', 'Last Name', 'required');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
        $this->form_validation->set_rules('phone', 'Phone', 'required|regex_match[/^[0-9]{10}$/]');
        $this->form_validation->set_rules('esubject', 'Subject', 'required');
        $this->form_validation->set_rules('msg', 'Message', 'required');
        // $this->form_validation->set_rules('g-recaptcha-response', 'Capcha', 'required');

        if ($this->form_validation->run() == FALSE) {
          $this->load->view('contact');
          }
       else {

      $to = "";
        $cc = "";
        $fname = $this->input->post('fname');
        $lname = $this->input->post('lname');
        $email = $this->input->post('email');
        $phone = $this->input->post('phone');
        echo $phone; exit;
}
}

This is my controller Main.php

I need to get the country code and phone number in this variable
$phone;


问:
Excel to Word VBA. Create Hover Texts for 25k Definitions

What is the BEST option to create Hover Texts for 25k Definitions?

(Excel to Word using VBA)

Screen Tips?

Tool Tips?

Foot Notes?

Glossary?

Book Marks?

Other Options?

Over 25K Definitions in Table

Based on feedback and countless HOURS, Im having a tough time figuring out the best option for a Text Hover Effect.

Ive tried Bookmarks and Screen Tips and ran into many issues.

Ive also attempted to tweak the below VBA code to work with Hyperlinks to no avail.

3 STEPS

Select the Term from Column:A

Find the Term in Word Document

ADD Definition From Column:B as a HOVER effect in Word

```<code>| Column A    | Column B                 |

| ----------- | ------------------------ |

| Example A   | Definition Example....   |

| Example B   | Definition Example....   |
</code>```

Column: A1:A25000 = Term

Column: B1:B25000 = Definition

*The below code works great for finding and highlighting the Terms, But I haven't figured out the Hover Effect.

Favor 2023

```<code>`'Version #1: Only loops through Word Document Content for text to Find and Replace.
'Leverage & Lean "Less Clicks, More Results"
Sub FindReplaceAcrossMultipleWordDocumentsFreeMacro()
    ' Means variable is in use
    Dim FindReplaceCounter As Integer '
    Dim FolderPath As String '
    Dim LastRow As Integer '
    Dim LastRowPath As Integer '
    Dim MyRange As Object '
    Dim oFile As Object '
    Dim oFolder As Object '
    Dim oFSO As Object '
    Dim WordApp As New Word.Application '
    Dim WordCounter As Integer '
    Dim WordDocument As Object '

    On Error GoTo LeverageLean

    Set WordApp = New Word.Application 'Forces a New Word Application each and every time.  (Prevents Error 462)

    If Cells(2, 3).Value <> "" Then 'If a path to Word Documents exist
        WordCounter = 2
        LastRowPath = Cells(Rows.Count, 3).End(xlUp).Row 'Identify Last Row in Column C
        Do Until WordCounter > LastRowPath 'Loop through any Word Documents in Column C
            Set WordDocument = WordApp.Documents.Open(Cells(WordCounter, 3).Value)
            WordApp.Visible = True
            FindReplaceCounter = 2
            LastRow = Cells(Rows.Count, 1).End(xlUp).Row 'Identify Last Row in Column A
            Do Until FindReplaceCounter > LastRow 'Complete the Find and Replace for all values in Column A & B
                Set MyRange = WordApp.ActiveDocument.Content
                With MyRange.Find
                    .Format = True
                    .MatchWholeWord = True
                    '.MatchWildcards = True 'Find and Replace Uppercase & Lowercase Text
                    .Wrap = wdFindContinue
                    .Forward = True
                    .Text = Cells(FindReplaceCounter, 1).Value
                    '.Replacement.Highlight = True 'Highlight the Replacement Text Found
                    .Replacement.Text = Cells(FindReplaceCounter, 2).Value
                    .Execute Replace:=wdReplaceAll
                End With
                FindReplaceCounter = FindReplaceCounter + 1
            Loop
            WordApp.ActiveDocument.Save
            WordApp.ActiveDocument.Close 'Close Active Word Document
            WordCounter = WordCounter + 1
        Loop
    ElseIf Cells(2, 3).Value = "" Then 'If NO paths to Word Documents exist
        FolderPath = Left(ActiveWorkbook.FullName, Len(ActiveWorkbook.FullName) - Len(ActiveWorkbook.Name)) 'Active Workbook File Path
        Set oFSO = CreateObject("Scripting.FileSystemObject")
        Set oFolder = oFSO.GetFolder(FolderPath)
        For Each oFile In oFolder.Files 'Loop through every File in Active Workbook's folder path
            If InStr(1, oFile.Type, "Microsoft Word") <> 0 And InStr(1, oFile.Name, "~") = 0 Then 'If the File Type contains the phrase Microsoft Word and is NOT Lock File
                Set WordDocument = WordApp.Documents.Open(FolderPath & oFile.Name)
                WordApp.Visible = True
                FindReplaceCounter = 2
                LastRow = Cells(Rows.Count, 1).End(xlUp).Row 'Identify Last Row in Column A
                Do Until FindReplaceCounter > LastRow 'Complete the Find and Replace for all values in Column A & B
                    Set MyRange = WordApp.ActiveDocument.Content
                    With MyRange.Find
                        .Format = True
                        .MatchWholeWord = True
                        .Wrap = wdFindContinue
                        .Forward = True
                        .Text = Cells(FindReplaceCounter, 1).Value
                        '.Replacement.Highlight = True 'Highlight the Replacement Text Found
                        .Replacement.Text = Cells(FindReplaceCounter, 2).Value
                        .Execute Replace:=wdReplaceAll
                    End With
                    FindReplaceCounter = FindReplaceCounter + 1
                Loop
                WordApp.ActiveDocument.Save
                WordApp.ActiveDocument.Close 'Close Active Word Document
            End If
        Next oFile
    End If

    WordApp.Quit

    MsgBox "The Find and Replace has been completed. Stay Awesome!"

    Set oFSO = Nothing
    Set oFolder = Nothing
    Set oFile = Nothing
    Set WordApp = Nothing
    Set WordDocument = Nothing

    Exit Sub

LeverageLean:
    MsgBox (Err.Number & " - " & Err.Description & vbNewLine & vbNewLine & "Don't hesitate to email me: brentschneider@leveragelean.com")

End Sub
'Stay Awesome`
</code>```

Body:
What is the BEST option to create Hover Texts for 25k Definitions?

(Excel to Word using VBA)

Screen Tips?

Tool Tips?

Foot Notes?

Glossary?

Book Marks?

Other Options?

Over 25K Definitions in Table

Based on feedback and countless HOURS, Im having a tough time figuring out the best option for a Text Hover Effect.

Ive tried Bookmarks and Screen Tips and ran into many issues.

Ive also attempted to tweak the below VBA code to work with Hyperlinks to no avail.

3 STEPS

Select the Term from Column:A

Find the Term in Word Document

ADD Definition From Column:B as a HOVER effect in Word

| Column A    | Column B                 |

| ----------- | ------------------------ |

| Example A   | Definition Example....   |

| Example B   | Definition Example....   |

Column: A1:A25000 = Term

Column: B1:B25000 = Definition

*The below code works great for finding and highlighting the Terms, But I haven't figured out the Hover Effect.

Favor 2023

`'Version #1: Only loops through Word Document Content for text to Find and Replace.
'Leverage & Lean "Less Clicks, More Results"
Sub FindReplaceAcrossMultipleWordDocumentsFreeMacro()
    ' Means variable is in use
    Dim FindReplaceCounter As Integer '
    Dim FolderPath As String '
    Dim LastRow As Integer '
    Dim LastRowPath As Integer '
    Dim MyRange As Object '
    Dim oFile As Object '
    Dim oFolder As Object '
    Dim oFSO As Object '
    Dim WordApp As New Word.Application '
    Dim WordCounter As Integer '
    Dim WordDocument As Object '

    On Error GoTo LeverageLean

    Set WordApp = New Word.Application 'Forces a New Word Application each and every time.  (Prevents Error 462)

    If Cells(2, 3).Value <> "" Then 'If a path to Word Documents exist
        WordCounter = 2
        LastRowPath = Cells(Rows.Count, 3).End(xlUp).Row 'Identify Last Row in Column C
        Do Until WordCounter > LastRowPath 'Loop through any Word Documents in Column C
            Set WordDocument = WordApp.Documents.Open(Cells(WordCounter, 3).Value)
            WordApp.Visible = True
            FindReplaceCounter = 2
            LastRow = Cells(Rows.Count, 1).End(xlUp).Row 'Identify Last Row in Column A
            Do Until FindReplaceCounter > LastRow 'Complete the Find and Replace for all values in Column A & B
                Set MyRange = WordApp.ActiveDocument.Content
                With MyRange.Find
                    .Format = True
                    .MatchWholeWord = True
                    '.MatchWildcards = True 'Find and Replace Uppercase & Lowercase Text
                    .Wrap = wdFindContinue
                    .Forward = True
                    .Text = Cells(FindReplaceCounter, 1).Value
                    '.Replacement.Highlight = True 'Highlight the Replacement Text Found
                    .Replacement.Text = Cells(FindReplaceCounter, 2).Value
                    .Execute Replace:=wdReplaceAll
                End With
                FindReplaceCounter = FindReplaceCounter + 1
            Loop
            WordApp.ActiveDocument.Save
            WordApp.ActiveDocument.Close 'Close Active Word Document
            WordCounter = WordCounter + 1
        Loop
    ElseIf Cells(2, 3).Value = "" Then 'If NO paths to Word Documents exist
        FolderPath = Left(ActiveWorkbook.FullName, Len(ActiveWorkbook.FullName) - Len(ActiveWorkbook.Name)) 'Active Workbook File Path
        Set oFSO = CreateObject("Scripting.FileSystemObject")
        Set oFolder = oFSO.GetFolder(FolderPath)
        For Each oFile In oFolder.Files 'Loop through every File in Active Workbook's folder path
            If InStr(1, oFile.Type, "Microsoft Word") <> 0 And InStr(1, oFile.Name, "~") = 0 Then 'If the File Type contains the phrase Microsoft Word and is NOT Lock File
                Set WordDocument = WordApp.Documents.Open(FolderPath & oFile.Name)
                WordApp.Visible = True
                FindReplaceCounter = 2
                LastRow = Cells(Rows.Count, 1).End(xlUp).Row 'Identify Last Row in Column A
                Do Until FindReplaceCounter > LastRow 'Complete the Find and Replace for all values in Column A & B
                    Set MyRange = WordApp.ActiveDocument.Content
                    With MyRange.Find
                        .Format = True
                        .MatchWholeWord = True
                        .Wrap = wdFindContinue
                        .Forward = True
                        .Text = Cells(FindReplaceCounter, 1).Value
                        '.Replacement.Highlight = True 'Highlight the Replacement Text Found
                        .Replacement.Text = Cells(FindReplaceCounter, 2).Value
                        .Execute Replace:=wdReplaceAll
                    End With
                    FindReplaceCounter = FindReplaceCounter + 1
                Loop
                WordApp.ActiveDocument.Save
                WordApp.ActiveDocument.Close 'Close Active Word Document
            End If
        Next oFile
    End If

    WordApp.Quit

    MsgBox "The Find and Replace has been completed. Stay Awesome!"

    Set oFSO = Nothing
    Set oFolder = Nothing
    Set oFile = Nothing
    Set WordApp = Nothing
    Set WordDocument = Nothing

    Exit Sub

LeverageLean:
    MsgBox (Err.Number & " - " & Err.Description & vbNewLine & vbNewLine & "Don't hesitate to email me: brentschneider@leveragelean.com")

End Sub
'Stay Awesome`


问:
Expand a variable inside a regular expression
in Typescript, I need to expand a variable inside a regular expression to build a filter for a MongoDB query; none of the following solutions seem to be valid; only the variable "code" is expanded, not the "subCode"; suppose we have:

```<code>let code = "code1";
let subCode = "CODE2.";
const regexExpression = {code: { $in: [`${code}`, /^`${subCode}`\..*/i] }};

const newRegexExpression = new RegExp(/code: { $in: [`${code}`, /^`${subCode}`\..*/i] }/i
);
</code>```

Desired result:

```<code>{ "code" : { $in : [ "code1", /^"CODE2\.".*/i ] } }
</code>```

Body:
in Typescript, I need to expand a variable inside a regular expression to build a filter for a MongoDB query; none of the following solutions seem to be valid; only the variable "code" is expanded, not the "subCode"; suppose we have:

let code = "code1";
let subCode = "CODE2.";
const regexExpression = {code: { $in: [`${code}`, /^`${subCode}`\..*/i] }};

const newRegexExpression = new RegExp(/code: { $in: [`${code}`, /^`${subCode}`\..*/i] }/i
);

Desired result:

{ "code" : { $in : [ "code1", /^"CODE2\.".*/i ] } }


问:
How do I get the path to the SQL script that is executed by Microsoft SQL Server 2016?
I am trying to install some application on Windows Server 2019. The application relies on a database, so I also have SQL Server 2016 (v 13.0.1601.5) on the server. But during installation, I get an error message, basically telling me some SQL script, say "abc.sql" has encountered a problem and cannot continue. When I open SQL Server's XEven Profiler, I surely see what the problem is; it fails to create a stored procedure because of some bug in the code, something like this:

```<code>CREATE PROCEDURE [dbo].[doSomethingNice] (**@problematicParameter** int, @nonProblematicParameter int)
AS
BEGIN
    SET NOCOUNT ON;

    update [dbo].[SomeTable]
        set SomeField =**@ProblematicParameter**
    where
        SomeOtherField= @nonProblematicParameter
END
</code>```

Of course, the problem is the casing.

XEvent Profiler kindly specifies which application runs the query, and in this case, it is Windows Installer.

```<code>client_app_name: Windows Installer - Unicode
</code>```

I believe (more likely hope), if I can somehow get hold of the original script file, abc.sql, I can fix it and run it from SQL Server Management Studio. This would work since the installer program provides the option of using an existing database instead of creating a new one.

I scoured the Temp directory but could not find the said script. I know it must be somewhere on the disk. How can I find where it is? Does XEvent Profiler provide that data?

Body:
I am trying to install some application on Windows Server 2019. The application relies on a database, so I also have SQL Server 2016 (v 13.0.1601.5) on the server. But during installation, I get an error message, basically telling me some SQL script, say "abc.sql" has encountered a problem and cannot continue. When I open SQL Server's XEven Profiler, I surely see what the problem is; it fails to create a stored procedure because of some bug in the code, something like this:

CREATE PROCEDURE [dbo].[doSomethingNice] (**@problematicParameter** int, @nonProblematicParameter int)
AS
BEGIN
    SET NOCOUNT ON;

    update [dbo].[SomeTable]
        set SomeField =**@ProblematicParameter**
    where
        SomeOtherField= @nonProblematicParameter
END

Of course, the problem is the casing.

XEvent Profiler kindly specifies which application runs the query, and in this case, it is Windows Installer.

client_app_name: Windows Installer - Unicode

I believe (more likely hope), if I can somehow get hold of the original script file, abc.sql, I can fix it and run it from SQL Server Management Studio. This would work since the installer program provides the option of using an existing database instead of creating a new one.

I scoured the Temp directory but could not find the said script. I know it must be somewhere on the disk. How can I find where it is? Does XEvent Profiler provide that data?


问:
How can I deal with the following : "error: the value of 'foo' is not usable in a constant expression."?
I am using Yaml-cpp and Eigen in my small project.

For example, in cfg_.yaml

```<code>foo:
 bar: 15
</code>```

In constants.h

```<code>#pragma once
#include "yaml-cpp/yaml.h"
#include <iostream>
#ifndef DO_FORWARD_GRADIENT_constexprANTS_H
#define DO_FORWARD_GRADIENT_constexprANTS_H
const std::string yaml_path = "${MYWORKSPACE}/cfg_.yaml";
YAML::Node cfg_ = YAML::LoadFile(yaml_path);
const int nq = cfg_["foo"]["bar"].as<int>();
#endif
</code>```

In main.cpp

```<code>#include <Eigen.h>
#include <constants.h>

int main(){

Eigen::Matrix<double,nq,1> matrix_test;
matrix_test.setZero();

return 0;
}
</code>```

But, the following error occurs:

error: the value of 'nq' is not usable in a constant expression.

I figured out that this happens because the variable is not defined at compile time.

I want to use the yaml file to reduce the build time when changing the variables.

For example, I want to call the value of variable in constants.h  from the cfg.yaml.

How can I solve the error?

Body:
I am using Yaml-cpp and Eigen in my small project.

For example, in cfg_.yaml

foo:
 bar: 15

In constants.h

#pragma once
#include "yaml-cpp/yaml.h"
#include <iostream>
#ifndef DO_FORWARD_GRADIENT_constexprANTS_H
#define DO_FORWARD_GRADIENT_constexprANTS_H
const std::string yaml_path = "${MYWORKSPACE}/cfg_.yaml";
YAML::Node cfg_ = YAML::LoadFile(yaml_path);
const int nq = cfg_["foo"]["bar"].as<int>();
#endif

In main.cpp

#include <Eigen.h>
#include <constants.h>

int main(){

Eigen::Matrix<double,nq,1> matrix_test;
matrix_test.setZero();

return 0;
}

But, the following error occurs:

error: the value of 'nq' is not usable in a constant expression.

I figured out that this happens because the variable is not defined at compile time.

I want to use the yaml file to reduce the build time when changing the variables.

For example, I want to call the value of variable in constants.h  from the cfg.yaml.

How can I solve the error?


问:
Cannot find package babel-preset-react
I need help, there was an error while building the application.
Cannot find package 'babel-preset-react' imported from Path\babel-virtual-resolve-base.js

Installed in devDependencies:

"@babel/cli": "^7.20.7",

"@babel/core": "^7.20.7",

"@babel/node": "^7.20.7",

"@babel/plugin-transform-async-to-generator": "^7.20.7",

"@babel/preset-env": "^7.20.2",

"@babel/preset-react": "^7.18.6",

"babel-eslint": "^10.1.0",

"babel-jest": "^24.9.0",

"babel-loader": "^8.2.2",

"babel-preset-react-app": "^10.0.1",

"babelify": "^10.0.0",

In dependencies:

"grunt-babel": "^8.0.0",

"@babel/polyfill": "^7.12.1",

.babelrc:

{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
]
}

Cannot find package 'babel-preset-react'.
babel-preset-react is babel 6 version, I don't need it. I am using babel version 7.

If I install babel-preset-react a new error occurs.
Plugin/Preset files are not allowed to export objects, only functions. In Path\node_modules\babel-preset-react\lib\index.js

Before that, I migrated from babel 6 to babel 7.
Deleted node_modules and package-lock.json and npm install again

Title: Cannot find package babel-preset-react


问:
Gatsby 5, TS and new Slice component
Not sure if we are missing something obvious here.The documentation for slices says that you're supposed to be able to use children as usual for a slice component.
But whenever I add a child of any type. Like fragment, custom component or just plain HTML i get this:

The error goes away if I remove child props.
The rendered slice component looks like this:

```<code>const Layout = ({
  children,
  data,
}: SliceComponentProps<LayoutProps>) => {
  const { meetingPlace, menuCards, menuItem } =
    data.contentfulMeetingPlacePageHome;

  return (
    <>
      {meetingPlace && (
        <TabBar
          menuGroups={menuItem}
          menuCards={menuCards}
          logo={meetingPlace?.logo}
          socialMediaLinks={meetingPlace?.socialMediaLinks}
          meetingPlace={meetingPlace}
        />
      )}
      <div className="relative lg:px-28 xl:container xl:px-28">
        {meetingPlace && (
          <Header meetingPlace={meetingPlace} logo={meetingPlace?.logo} />
        )}
        {children}
      </div>
    </>
  );
};

export default Layout;

export const query = graphql`
  ...
`;
</code>```

And

Inside gatsby-node I run the following code to create the slice:

```<code>actions.createSlice({
    id: 'layout',
    component: path.resolve('./src/components/layout/layout.tsx'),
  });
</code>```

I get same error even I make a simple dummy slice component with no data as long as it a child of any kind.
Have the following gatsby packages in the project:

```<code>"gatsby": "5.3.3",
    "gatsby-plugin-google-tagmanager": "^5.3.1",
    "gatsby-plugin-image": "^3.3.2",
    "gatsby-plugin-manifest": "^5.3.1",
    "gatsby-plugin-react-helmet": "^6.3.0",
    "gatsby-plugin-react-svg": "^3.3.0",
    "gatsby-plugin-robots-txt": "^1.8.0",
    "gatsby-plugin-sass": "^6.3.1",
    "gatsby-plugin-sharp": "^5.3.2",
    "gatsby-plugin-sitemap": "^6.3.1",
    "gatsby-source-contentful": "^8.3.1",
    "gatsby-source-filesystem": "^5.3.1",
    "gatsby-transformer-inline-svg": "^1.2.0",
    "gatsby-transformer-sharp": "^5.3.1",
     "gatsby-plugin-postcss": "^6.3.0",
</code>```

Title: Gatsby 5, TS and new Slice component

Body:
Not sure if we are missing something obvious here.The documentation for slices says that you're supposed to be able to use children as usual for a slice component.
But whenever I add a child of any type. Like fragment, custom component or just plain HTML i get this:

The error goes away if I remove child props.
The rendered slice component looks like this:

const Layout = ({
  children,
  data,
}: SliceComponentProps<LayoutProps>) => {
  const { meetingPlace, menuCards, menuItem } =
    data.contentfulMeetingPlacePageHome;

  return (
    <>
      {meetingPlace && (
        <TabBar
          menuGroups={menuItem}
          menuCards={menuCards}
          logo={meetingPlace?.logo}
          socialMediaLinks={meetingPlace?.socialMediaLinks}
          meetingPlace={meetingPlace}
        />
      )}

        {meetingPlace && (

        )}
        {children}

    </>
  );
};

export default Layout;

export const query = graphql`
  ...
`;

And

Inside gatsby-node I run the following code to create the slice:

actions.createSlice({
    id: 'layout',
    component: path.resolve('./src/components/layout/layout.tsx'),
  });

I get same error even I make a simple dummy slice component with no data as long as it a child of any kind.
Have the following gatsby packages in the project:

"gatsby": "5.3.3",
    "gatsby-plugin-google-tagmanager": "^5.3.1",
    "gatsby-plugin-image": "^3.3.2",
    "gatsby-plugin-manifest": "^5.3.1",
    "gatsby-plugin-react-helmet": "^6.3.0",
    "gatsby-plugin-react-svg": "^3.3.0",
    "gatsby-plugin-robots-txt": "^1.8.0",
    "gatsby-plugin-sass": "^6.3.1",
    "gatsby-plugin-sharp": "^5.3.2",
    "gatsby-plugin-sitemap": "^6.3.1",
    "gatsby-source-contentful": "^8.3.1",
    "gatsby-source-filesystem": "^5.3.1",
    "gatsby-transformer-inline-svg": "^1.2.0",
    "gatsby-transformer-sharp": "^5.3.1",
     "gatsby-plugin-postcss": "^6.3.0",


问:
JS HTMLElement.click() removes the URL part after the #
I have a Vue 3 app using Vue Router 4.

I have a button using the javascript HTMLElement.click() method to click on a hidden file input.

When I click it and the browser's file picker pops up, all the part of my URL after the hash gets cut out which changes my view.

I have no errors whatsoever so I really don't know what is causing this. Any idea ?


问:
Opening docx and pdf documents in react native
Faced a number of problems opening documents in a mobile application. We have 2 types of PDF and DOCX documents available.
There are no packages to open Docx for react native.
In order to open a pdf, you need to have the base64 of that document. The back-end does not give back, and in order for the mobile application to create it itself, you need to fasten a heavy package.

Two types of documents can be opened in webview, but only viewing without saving will be available there, and then, this will only work on ios, android immediately starts downloading documents without viewing.
You can use the google.docs service to view documents, but you won't be able to open the document without cookies. Our back-end doesn't let the google.docs robot (for obvious reasons) download the document and display it to us.


问:
Run Selenium directly on Pydroid3 on Android
my goal is to run a python script that uses Selenium to manipulate the chrome browser, directly with Pydroid 3 app on my android smartphone (without a pc connection).

I followed the instructions at the link https://chromedriver.chromium.org/getting-started/getting-started---android to download the appropriate webdriver and set it correctly for Android.

In detail the version of Chrome on my Smartphone (Samsung S10) is 108.0.5359.128 therefore, following what is indicated here:
https://chromedriver.chromium.org/downloads#h.p_ID_32
I downloaded webdriver "chromedriver_linux64.zip" present at the following link:
https://chromedriver.storage.googleapis.com/index.html?path=108.0.5359.71/

But following this example
https://chromedriver.chromium.org/getting-started/getting-started---android#h.p_ID_390 and running the following Python3 script:

```<code>from selenium import webdriver

path_to_chromedriver = os.path.dirname(__file__) + '/chromedriver'
print('path_to_chromedriver: ', path_to_chromedriver)
options = webdriver.ChromeOptions()
options.add_experimental_option('androidPackage', 'com.android.chrome')
driver = webdriver.Chrome(path_to_chromedriver, 0, options=options)
driver.get('https://google.com')
driver.quit()
</code>```

or this one:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.service import Service

path_to_chromedriver = os.path.dirname(__file__) + '/chromedriver'
print('path_to_chromedriver: ', path_to_chromedriver)
service = Service(path_to_chromedriver)
options = webdriver.ChromeOptions()
options.add_experimental_option('androidPackage', 'com.android.chrome')
driver = webdriver.Chrome(service=service, options=options)
driver.get('https://google.com')
</code>```

I get this error:

```<code>path_to_chromedriver:  /storage/emulated/0/Download/ke-ce-verimme-justwatch-scraper/ke-ce-verimme-justwatch-scraper/scrapers/chromedriver
Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
    start(fakepyfile,mainpyfile)
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
    exec(open(mainpyfile).read(),  __main__.__dict__)
  File "<string>", line 124, in <module>
  File "/storage/emulated/0/Download/ke-ce-verimme-justwatch-scraper/ke-ce-verimme-justwatch-scraper/scrapers/justwatchScraper.py", line 168, in start
    scrolledGenrePage = scrollGenrePageToTheEnd(genrePageURL)
  File "/storage/emulated/0/Download/ke-ce-verimme-justwatch-scraper/ke-ce-verimme-justwatch-scraper/scrapers/justwatchScraper.py", line 47, in scrollGenrePageToTheEnd
    driver = webdriver.Chrome(service=service, options=options)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/selenium/webdriver/chrome/webdriver.py", line 81, in __init__
    super().__init__(
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/selenium/webdriver/chromium/webdriver.py", line 103, in __init__
    self.service.start()
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/selenium/webdriver/common/service.py", line 106, in start
    self.assert_process_still_running()
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/selenium/webdriver/common/service.py", line 117, in assert_process_still_running
    return_code = self.process.poll()
AttributeError: 'Service' object has no attribute 'process'

[Program finished]
</code>```

Can anyone help me or suggest a workaround?

Body:
my goal is to run a python script that uses Selenium to manipulate the chrome browser, directly with Pydroid 3 app on my android smartphone (without a pc connection).

I followed the instructions at the link https://chromedriver.chromium.org/getting-started/getting-started---android to download the appropriate webdriver and set it correctly for Android.

In detail the version of Chrome on my Smartphone (Samsung S10) is 108.0.5359.128 therefore, following what is indicated here:
https://chromedriver.chromium.org/downloads#h.p_ID_32
I downloaded webdriver "chromedriver_linux64.zip" present at the following link:
https://chromedriver.storage.googleapis.com/index.html?path=108.0.5359.71/

But following this example
https://chromedriver.chromium.org/getting-started/getting-started---android#h.p_ID_390 and running the following Python3 script:

from selenium import webdriver

path_to_chromedriver = os.path.dirname(__file__) + '/chromedriver'
print('path_to_chromedriver: ', path_to_chromedriver)
options = webdriver.ChromeOptions()
options.add_experimental_option('androidPackage', 'com.android.chrome')
driver = webdriver.Chrome(path_to_chromedriver, 0, options=options)
driver.get('https://google.com')
driver.quit()

or this one:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

path_to_chromedriver = os.path.dirname(__file__) + '/chromedriver'
print('path_to_chromedriver: ', path_to_chromedriver)
service = Service(path_to_chromedriver)
options = webdriver.ChromeOptions()
options.add_experimental_option('androidPackage', 'com.android.chrome')
driver = webdriver.Chrome(service=service, options=options)
driver.get('https://google.com')

I get this error:

path_to_chromedriver:  /storage/emulated/0/Download/ke-ce-verimme-justwatch-scraper/ke-ce-verimme-justwatch-scraper/scrapers/chromedriver
Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
    start(fakepyfile,mainpyfile)
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
    exec(open(mainpyfile).read(),  __main__.__dict__)
  File "<string>", line 124, in <module>
  File "/storage/emulated/0/Download/ke-ce-verimme-justwatch-scraper/ke-ce-verimme-justwatch-scraper/scrapers/justwatchScraper.py", line 168, in start
    scrolledGenrePage = scrollGenrePageToTheEnd(genrePageURL)
  File "/storage/emulated/0/Download/ke-ce-verimme-justwatch-scraper/ke-ce-verimme-justwatch-scraper/scrapers/justwatchScraper.py", line 47, in scrollGenrePageToTheEnd
    driver = webdriver.Chrome(service=service, options=options)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/selenium/webdriver/chrome/webdriver.py", line 81, in __init__
    super().__init__(
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/selenium/webdriver/chromium/webdriver.py", line 103, in __init__
    self.service.start()
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/selenium/webdriver/common/service.py", line 106, in start
    self.assert_process_still_running()
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/selenium/webdriver/common/service.py", line 117, in assert_process_still_running
    return_code = self.process.poll()
AttributeError: 'Service' object has no attribute 'process'

[Program finished]

Can anyone help me or suggest a workaround?


问:
How do I make a POST request in Visual Basics code from Outlook
I'm a beginner in Visual Basics and would like to make a post request using Visual Basics from Outlook.

I looked up on HttpWebRequest but I haven't been successful.

Here's my cURL equivalent code:

```<code>curl -X POST --header "X-TrackerToken: token" --header "Content-Type: application/json" -d '{"text": "my-data"}' "https://www.url.com"
</code>```

Body:
I'm a beginner in Visual Basics and would like to make a post request using Visual Basics from Outlook.

I looked up on HttpWebRequest but I haven't been successful.

Here's my cURL equivalent code:

curl -X POST --header "X-TrackerToken: token" --header "Content-Type: application/json" -d '{"text": "my-data"}' "https://www.url.com"


问:
Can we call a big query stored procedure from Tableau?
I have a stored procedure routine in big query which I want to execute from Tableau. The idea is that the custom parameters from Tableau will be passed as input to the SP. But I don't see a way to use the SP from Tableau.

It doesn't show up in the list of available objects in the database.
I have tried using a custom SQL and use "CALL dataset.sp_name()" but it throws an error.

I have worked with stored procedures from other databases (like MySQL etc) in Tableau, but it's not working the same way for BQ.


问:
Extracting the largest rectangle like object from an image with any possible orientation using openCV?
I have pictures of cheques which were scanned and are on A4 sheets now.
I need to extract those cheques, which can be a bit tilted or rotated.
Now using an AI model would be my last preference. I tried the following script and it gave away every little and tiny rectangle from the image

```<code>import cv2
import numpy as np
from google.colab.patches import cv2_imshow

# Read the image into a NumPy array
image = cv2.imread('/content/img.jpg')

# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Use the Canny edge detector to find the edges of the objects in the image
edges = cv2.Canny(gray, 50, 150)

# Find the contours of the objects
contours, _ = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# Iterate through the contours
for contour in contours:
  # Approximate the shape of the contour as a polygon
  epsilon = 0.1 * cv2.arcLength(contour, True)
  approx = cv2.approxPolyDP(contour, epsilon, True)

  # If the approximated polygon has 4 sides, it is a rectangle
  if len(approx) == 4:
    # Extract the rectangle from the image
    x, y, w, h = cv2.boundingRect(contour)
    rectangle = image[y:y+h, x:x+w]

    # Do something with the rectangle (e.g., display it, save it to a file, etc.)
    cv2_imshow(rectangle)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
</code>```

and this is what my images look like
what would be the best non YoLo type of solution here

Body:
I have pictures of cheques which were scanned and are on A4 sheets now.
I need to extract those cheques, which can be a bit tilted or rotated.
Now using an AI model would be my last preference. I tried the following script and it gave away every little and tiny rectangle from the image

import cv2
import numpy as np
from google.colab.patches import cv2_imshow

# Read the image into a NumPy array
image = cv2.imread('/content/img.jpg')

# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Use the Canny edge detector to find the edges of the objects in the image
edges = cv2.Canny(gray, 50, 150)

# Find the contours of the objects
contours, _ = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# Iterate through the contours
for contour in contours:
  # Approximate the shape of the contour as a polygon
  epsilon = 0.1 * cv2.arcLength(contour, True)
  approx = cv2.approxPolyDP(contour, epsilon, True)

  # If the approximated polygon has 4 sides, it is a rectangle
  if len(approx) == 4:
    # Extract the rectangle from the image
    x, y, w, h = cv2.boundingRect(contour)
    rectangle = image[y:y+h, x:x+w]

    # Do something with the rectangle (e.g., display it, save it to a file, etc.)
    cv2_imshow(rectangle)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

and this is what my images look like
what would be the best non YoLo type of solution here


问:
How to map seperately dynamic number of query parameters and pageable information in rest call?
I am having a rest call where the front end sends me page and size and also a dynamic number of query parameters in the url. I map them all using this piece of code:

From postman:

```<code>http://localhost:8080/something/search?page=0&size=10&sort=applicationId,asc&applicationId=name1&applicationId=name2&reference=12345
</code>```

The way I map them:

```<code>public ResponseEntity<Page<ObjectToReturn>> getObjectWithDynamicCriteria(Pageable pageable, @RequestParam MultiValueMap<String, String> params)
</code>```

My problem with this approach is that both pageable and multivalue map contains the same information about the pageable object.

```<code>  Page request [number: 0, size 10, sort: applicationId: ASC]
  params {page=[0], size=[10], sort=[applicationId,asc], applicationId=[name1, name2], reference=[12345]}
</code>```

I process the multivalue map values for example the application id and the reference but before I remove the page and size from the map because they already exist in the pageable object.

Is there any way to have lets say pageable object and multivalue map but the multivalue map to not have the -->  page=[0], size=[10], sort=[applicationId,asc]?

Body:
I am having a rest call where the front end sends me page and size and also a dynamic number of query parameters in the url. I map them all using this piece of code:

From postman:

http://localhost:8080/something/search?page=0&size=10&sort=applicationId,asc&applicationId=name1&applicationId=name2&reference=12345

The way I map them:

public ResponseEntity<Page<ObjectToReturn>> getObjectWithDynamicCriteria(Pageable pageable, @RequestParam MultiValueMap<String, String> params)

My problem with this approach is that both pageable and multivalue map contains the same information about the pageable object.

  Page request [number: 0, size 10, sort: applicationId: ASC]
  params {page=[0], size=[10], sort=[applicationId,asc], applicationId=[name1, name2], reference=[12345]}

I process the multivalue map values for example the application id and the reference but before I remove the page and size from the map because they already exist in the pageable object.

Is there any way to have lets say pageable object and multivalue map but the multivalue map to not have the -->  page=[0], size=[10], sort=[applicationId,asc]?


问:
How can I make web-ports visible/accessible on host from docker-container (docker-compose, docker, Ubuntu)?
My C++ application runs on an Ubuntu Focal server and communicates with another service on a different server via secure web-socket. I test the functionality with a set of local python3 scripts and that all works fine.
Now I want to create a docker-image for my service and expose the socket.
The container I built runs fine and communicates with a MariaDB container over the docker-network.

My Dockerfile is this:

```<code>FROM ubuntu:focal

ENV DEBIAN_FRONTEND noninteractive
ENV TZ=Europe/London
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ \> /etc/timezone

RUN mkdir -p /app

# Updating/upgrading the base image

RUN apt-get -y update
RUN apt-get -y upgrade

# Installing some useful tools

RUN apt-get install -y net-tools
RUN apt-get install -y iproute2
RUN apt-get install -y iputils-ping
RUN apt-get install -y dbus
RUN apt-get install -y firewalld

RUN apt-get install -y openssh-server
RUN apt-get install -y rsync
RUN apt-get install -y mariadb-client
RUN apt-get install -y libmariadb-dev

# Setting up an SSH daemon

RUN sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
RUN sed 's@session\\s*required\\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" \>\> /etc/profile && echo "Port 1022" \>\> /etc/ssh/sshd_config
RUN ssh-keygen -b 1024 -t rsa -f /etc/ssh/ssh_host_key -q -N ""
RUN ssh-keygen -b 1024 -t dsa -f /etc/ssh/ssh_host_dsa_key -q -N ""

# Set shell to bash

SHELL \["/bin/bash", "--login", "-c"\]

# Create directories in this container

RUN mkdir -p /app/deploy/bin
COPY content2copy/deploy/bin/myserv /app/deploy/bin
COPY content2copy/run_AES.sh /app/deploy
EXPOSE 5000

WORKDIR /app/deploy
</code>```

My docker-compose.yml is the following:

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

  myserv_run:
    build:
      context: .
      dockerfile: Dockerfile
      args:
        progress: plain
    depends_on:
      - mariadb
    command: bash -c /app/deploy/run_MY.sh
    stdin_open: true
    tty: true
    hostname: myserv_servicehost
    image: myserv_run_ubuntu20:latest
    networks:
      - myserv_network
    ports:
      - ${WEBAPI_PORT}:${WEBAPI_PORT}
    volumes:
      - ${MY_LOG_DIR}:/app/log:rw
      - ${MY_CONFIG_DIR}:/app/deploy/config:rw
    cap_add:
      - ALL

  mariadb:
    image: mariadb:10.7
    ports:
      - 3306:${MARIADB_PORT}
    hostname: myserv_dbhost
    command: --init-file /app/deploy/create_myserv_db.sql
    volumes:
      - ${MARIADB_DIR}:/var/lib/mysql:rw
      - ${APPLICATION_FILES_DIR}/create_myserv__db.sql:/app/deploy/create_myserv_db.sql:rw
    networks:
      - myserv_network
    environment:
      MYSQL_ROOT_PASSWORD: somesecret
      MYSQL_DATABASE: myserv_db
      MYSQL_USER: ${MY_DB_USER}
      MYSQL_PASSWORD: ${MY_DB_PASSWORD}

networks:
  myserv_network: {}
</code>```

When I issue the docker-compose up command, both mariadb and myserv stay up and myserv is writing to the database.

However, a python3 test program that sends json strings via web-port wss://localhost:5000 fails with error

```<code>websocket version=0.59.0
[20221230-10:36:27.085823] ERROR: TLS/SSL connection has been closed (EOF) (_ssl.c:997)[20221230-10:36:27.086067] closed ()
</code>```

However, port 5000 is being listened on

```<code>[vm.ubuntu: ~]> ss -tunlp4 | tr -s ' ' ' ' | grep 5000
tcp LISTEN 0 4096 0.0.0.0:5000 0.0.0.0:*
</code>```

Odd thing is when I try to investigate the port with lsof I only can see it when using root privileges:

```<code>[vm.ubuntu: ~]> lsof -i :5000
## no output!
[vm.ubuntu: ~]> sudo lsof -i :5000
COMMAND      PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
docker-pr 193674 root    4u  IPv4 687684      0t0  TCP *:5000 (LISTEN)
docker-pr 193686 root    4u  IPv6 686599      0t0  TCP *:5000 (LISTEN)
</code>```

When I run the service on a virtual machine (where it works) I use the command:
firewall-cmd --add-port 5000
to open the port through the firewall. I've done the same inside the container (and outside) and a combination of those but the result is the same.

```<code>netstat -a -l -n | grep 5000
tcp        0      0 0.0.0.0:5000            0.0.0.0:*               LISTEN
tcp6       0      0 :::5000                 :::*                    LISTEN
</code>```

docker ps also shows that port 5000 is exposed by the container.

I also tried to run the python3 scripts in interactive mode within the running container but still I had no luck.

So question really is:
Am I missing some docker security feature here? Do I need to make extra configuration changes for web-ports to work with docker?

EDIT:

Reproduce behaviour:

file websockserver:

```<code>#!/usr/bin/env python3

# WSS (WS over TLS) server example, with a self-signed certificate

import asyncio
import ssl
import websockets

async def hello(websocket):
    name = await websocket.recv()
    print(f"< {name}")

    greeting = f"Hello {name}!"

    await websocket.send(greeting)
    print(f"> {greeting}")

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain("./rootCA.crt", "./rootCA.key")

start_server = websockets.serve(
    hello, '127.0.0.1', 5000, ssl=ssl_context)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
</code>```

file websockclient:

```<code>#!/usr/bin/env python3

# WSS (WS over TLS) client example, with a self-signed certificate

import asyncio
import ssl
import websockets

#ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ssl_context = ssl._create_unverified_context()
ssl_context.load_cert_chain("./rootCA.crt", "./rootCA.key")

async def hello():
    async with websockets.connect(
            'wss://localhost:5000', ssl=ssl_context) as websocket:
        name = input("What's your name? ")

        await websocket.send(name)
        print(f"> {name}")

        greeting = await websocket.recv()
        print(f"< {greeting}")

asyncio.get_event_loop().run_until_complete(hello())
</code>```

file docker-compose:

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

  py_server:
    build:
      context: .
      dockerfile: Dockerfile.server
      args:
        progress: plain
    command: bash -c /usr/src/app/websockserver
    stdin_open: true
    tty: true
    hostname: server_host
    image: py_server:latest
    networks:
      - py_network
    ports:
       # HOST:CONTAINER)
      - "5000:5000"

networks:
  py_network: {}
</code>```

file Dockerfile.server:
NOTE: Commented out part used to create certificates

```<code>FROM python:3

WORKDIR /usr/src/app

# RUN openssl genpkey -algorithm RSA -out rootCA.key -pkeyopt rsa_keygen_bits:4096 -pkeyopt rsa_keygen_pubexp:3
# RUN openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 5000 -out rootCA.crt -config rootCA.cnf
# RUN openssl req -new -sha256 -nodes -out webapi.csr -newkey rsa:4096 -keyout webapi.key -config webapi.cnf -extensions v3_req
# RUN openssl x509 -req -in webapi.csr -CA rootCA.crt -CAkey rootCA.key -CAcreateserial -days 5000 -extfile webapi.cnf -extensions v3_req -out webapi.crt
COPY ./rootCA.crt /usr/src/app
COPY ./webapi.crt /usr/src/app
COPY ./rootCA.key /usr/src/app
COPY ./webapi.key /usr/src/app
RUN cp /usr/src/app/rootCA.crt /usr/local/share/ca-certificates/PRMrootCA.crt
RUN cp /usr/src/app/webapi.crt /usr/local/share/ca-certificates/webapi.crt
RUN update-ca-certificates

RUN pip3 install websockets
RUN pip3 install websocket

WORKDIR /usr/src/app

COPY ./websockserver /usr/src/app
</code>```

When starting websockserver in one terminal and websockclient in another then server and client communicate.
When the server is dockerised then the client cannot connect.

lsof -i :5000 only shows a result when run with sudo privileges.

Body:
My C++ application runs on an Ubuntu Focal server and communicates with another service on a different server via secure web-socket. I test the functionality with a set of local python3 scripts and that all works fine.
Now I want to create a docker-image for my service and expose the socket.
The container I built runs fine and communicates with a MariaDB container over the docker-network.

My Dockerfile is this:

FROM ubuntu:focal

ENV DEBIAN_FRONTEND noninteractive
ENV TZ=Europe/London
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ \> /etc/timezone

RUN mkdir -p /app

# Updating/upgrading the base image

RUN apt-get -y update
RUN apt-get -y upgrade

# Installing some useful tools

RUN apt-get install -y net-tools
RUN apt-get install -y iproute2
RUN apt-get install -y iputils-ping
RUN apt-get install -y dbus
RUN apt-get install -y firewalld

RUN apt-get install -y openssh-server
RUN apt-get install -y rsync
RUN apt-get install -y mariadb-client
RUN apt-get install -y libmariadb-dev

# Setting up an SSH daemon

RUN sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
RUN sed 's@session\\s*required\\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" \>\> /etc/profile && echo "Port 1022" \>\> /etc/ssh/sshd_config
RUN ssh-keygen -b 1024 -t rsa -f /etc/ssh/ssh_host_key -q -N ""
RUN ssh-keygen -b 1024 -t dsa -f /etc/ssh/ssh_host_dsa_key -q -N ""

# Set shell to bash

SHELL \["/bin/bash", "--login", "-c"\]

# Create directories in this container

RUN mkdir -p /app/deploy/bin
COPY content2copy/deploy/bin/myserv /app/deploy/bin
COPY content2copy/run_AES.sh /app/deploy
EXPOSE 5000

WORKDIR /app/deploy

My docker-compose.yml is the following:

version: "3.3"
services:

  myserv_run:
    build:
      context: .
      dockerfile: Dockerfile
      args:
        progress: plain
    depends_on:
      - mariadb
    command: bash -c /app/deploy/run_MY.sh
    stdin_open: true
    tty: true
    hostname: myserv_servicehost
    image: myserv_run_ubuntu20:latest
    networks:
      - myserv_network
    ports:
      - ${WEBAPI_PORT}:${WEBAPI_PORT}
    volumes:
      - ${MY_LOG_DIR}:/app/log:rw
      - ${MY_CONFIG_DIR}:/app/deploy/config:rw
    cap_add:
      - ALL

  mariadb:
    image: mariadb:10.7
    ports:
      - 3306:${MARIADB_PORT}
    hostname: myserv_dbhost
    command: --init-file /app/deploy/create_myserv_db.sql
    volumes:
      - ${MARIADB_DIR}:/var/lib/mysql:rw
      - ${APPLICATION_FILES_DIR}/create_myserv__db.sql:/app/deploy/create_myserv_db.sql:rw
    networks:
      - myserv_network
    environment:
      MYSQL_ROOT_PASSWORD: somesecret
      MYSQL_DATABASE: myserv_db
      MYSQL_USER: ${MY_DB_USER}
      MYSQL_PASSWORD: ${MY_DB_PASSWORD}

networks:
  myserv_network: {}

When I issue the docker-compose up command, both mariadb and myserv stay up and myserv is writing to the database.

However, a python3 test program that sends json strings via web-port wss://localhost:5000 fails with error

websocket version=0.59.0
[20221230-10:36:27.085823] ERROR: TLS/SSL connection has been closed (EOF) (_ssl.c:997)[20221230-10:36:27.086067] closed ()

However, port 5000 is being listened on

[vm.ubuntu: ~]> ss -tunlp4 | tr -s ' ' ' ' | grep 5000
tcp LISTEN 0 4096 0.0.0.0:5000 0.0.0.0:*

Odd thing is when I try to investigate the port with lsof I only can see it when using root privileges:

[vm.ubuntu: ~]> lsof -i :5000
## no output!
[vm.ubuntu: ~]> sudo lsof -i :5000
COMMAND      PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
docker-pr 193674 root    4u  IPv4 687684      0t0  TCP *:5000 (LISTEN)
docker-pr 193686 root    4u  IPv6 686599      0t0  TCP *:5000 (LISTEN)

When I run the service on a virtual machine (where it works) I use the command:
firewall-cmd --add-port 5000
to open the port through the firewall. I've done the same inside the container (and outside) and a combination of those but the result is the same.

netstat -a -l -n | grep 5000
tcp        0      0 0.0.0.0:5000            0.0.0.0:*               LISTEN
tcp6       0      0 :::5000                 :::*                    LISTEN

docker ps also shows that port 5000 is exposed by the container.

I also tried to run the python3 scripts in interactive mode within the running container but still I had no luck.

So question really is:
Am I missing some docker security feature here? Do I need to make extra configuration changes for web-ports to work with docker?

EDIT:

Reproduce behaviour:

file websockserver:

#!/usr/bin/env python3

# WSS (WS over TLS) server example, with a self-signed certificate

import asyncio
import ssl
import websockets

async def hello(websocket):
    name = await websocket.recv()
    print(f"< {name}")

    greeting = f"Hello {name}!"

    await websocket.send(greeting)
    print(f"> {greeting}")

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain("./rootCA.crt", "./rootCA.key")

start_server = websockets.serve(
    hello, '127.0.0.1', 5000, ssl=ssl_context)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

file websockclient:

#!/usr/bin/env python3

# WSS (WS over TLS) client example, with a self-signed certificate

import asyncio
import ssl
import websockets

#ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ssl_context = ssl._create_unverified_context()
ssl_context.load_cert_chain("./rootCA.crt", "./rootCA.key")

async def hello():
    async with websockets.connect(
            'wss://localhost:5000', ssl=ssl_context) as websocket:
        name = input("What's your name? ")

        await websocket.send(name)
        print(f"> {name}")

        greeting = await websocket.recv()
        print(f"< {greeting}")

asyncio.get_event_loop().run_until_complete(hello())

file docker-compose:

version: "3.3"
services:

  py_server:
    build:
      context: .
      dockerfile: Dockerfile.server
      args:
        progress: plain
    command: bash -c /usr/src/app/websockserver
    stdin_open: true
    tty: true
    hostname: server_host
    image: py_server:latest
    networks:
      - py_network
    ports:
       # HOST:CONTAINER)
      - "5000:5000"

networks:
  py_network: {}

file Dockerfile.server:
NOTE: Commented out part used to create certificates

FROM python:3

WORKDIR /usr/src/app

# RUN openssl genpkey -algorithm RSA -out rootCA.key -pkeyopt rsa_keygen_bits:4096 -pkeyopt rsa_keygen_pubexp:3
# RUN openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 5000 -out rootCA.crt -config rootCA.cnf
# RUN openssl req -new -sha256 -nodes -out webapi.csr -newkey rsa:4096 -keyout webapi.key -config webapi.cnf -extensions v3_req
# RUN openssl x509 -req -in webapi.csr -CA rootCA.crt -CAkey rootCA.key -CAcreateserial -days 5000 -extfile webapi.cnf -extensions v3_req -out webapi.crt
COPY ./rootCA.crt /usr/src/app
COPY ./webapi.crt /usr/src/app
COPY ./rootCA.key /usr/src/app
COPY ./webapi.key /usr/src/app
RUN cp /usr/src/app/rootCA.crt /usr/local/share/ca-certificates/PRMrootCA.crt
RUN cp /usr/src/app/webapi.crt /usr/local/share/ca-certificates/webapi.crt
RUN update-ca-certificates

RUN pip3 install websockets
RUN pip3 install websocket

WORKDIR /usr/src/app

COPY ./websockserver /usr/src/app

When starting websockserver in one terminal and websockclient in another then server and client communicate.
When the server is dockerised then the client cannot connect.

lsof -i :5000 only shows a result when run with sudo privileges.


问:
How apply a customized css to an Rmarkdown document with selected a theme?
For instance, I am using the flatly theme from Rmarkdown to generate a HTML file.

I want to apply some customize css to this theme, but nothing has change. It seems that my css file does not work on the predefined Markdown theme.

Below is the YAML file of my Rmarkdown document.

```<code>---
title: "Test"
author: "Test"
output:
  html_document:
    theme: flatly
    toc: true
    toc_float: true
    number_sections: true
    css: style.css
---
</code>```

Here is my style.css file

```<code>/* Whole document: */
body{
  font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
  font-size: 15px;
  text-align: justify;
}

/* Quoted text  */
blockquote{
  font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
  background: white;
  border-left: 0.2em solid #76D7C4;
  font-size: 14px;
}

/* Code text  */

code {
  background: #ffcccc.
  word-wrap: break-word;
}
</code>```

Body:
For instance, I am using the flatly theme from Rmarkdown to generate a HTML file.

I want to apply some customize css to this theme, but nothing has change. It seems that my css file does not work on the predefined Markdown theme.

Below is the YAML file of my Rmarkdown document.

---
title: "Test"
author: "Test"
output:
  html_document:
    theme: flatly
    toc: true
    toc_float: true
    number_sections: true
    css: style.css
---

Here is my style.css file

/* Whole document: */
body{
  font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
  font-size: 15px;
  text-align: justify;
}

/* Quoted text  */
blockquote{
  font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
  background: white;
  border-left: 0.2em solid #76D7C4;
  font-size: 14px;
}

/* Code text  */

code {
  background: #ffcccc.
  word-wrap: break-word;
}


问:
MODX SimpleSearch uses always the default container
I am using SimpleSearch with the default containerTpl setting (=SearchResults).

It seems that SimpleSearch uses the chunk from core/components/simplesearch/elements/chunks and not my SearchResults chunk which has been saved in the database. So no matter how I edit the chunk on the manager, SimpleSearch always uses the default version of the chunk. I even deleted the cache folder but the problem continues.

I am using MODX3.0.2 with SimpleSearch 3.0.0.

I made also a test snippet with the command:

```<code>$modx->getChunk("SearchResults")
</code>```

and that returns the correct chunk from the database. But in SimpleSearch snippet, the default version is always returned.

Body:
I am using SimpleSearch with the default containerTpl setting (=SearchResults).

It seems that SimpleSearch uses the chunk from core/components/simplesearch/elements/chunks and not my SearchResults chunk which has been saved in the database. So no matter how I edit the chunk on the manager, SimpleSearch always uses the default version of the chunk. I even deleted the cache folder but the problem continues.

I am using MODX3.0.2 with SimpleSearch 3.0.0.

I made also a test snippet with the command:

$modx->getChunk("SearchResults")

and that returns the correct chunk from the database. But in SimpleSearch snippet, the default version is always returned.


问:
Best way to query a mongoDB database
I have a database containing ngram information of loads of documents. The database contains 8 collections, each for an ngram length (unigram - bigram - trigram etc). For each ngram, I also saved the lemma of the word and the POS-tag. So, the collection of trigrams contains the following fields: (Item1, Lemma1, POS1, Item2, Lemma2, POS2, Item3, Lemma3, POS3). There is also some other information stored, like the count for each of these, but that information is never used for querying purposes.

Now, I'm not a data engineer of any kind so I don't know a lot about indexing databases. The way the database is accessed is as follows: a rule in a specific syntax is the input, which is then converted to a query. A query can ask for, for example, any ngrams where:

```<code>{Item1 = Walk
    or
POS1 = VERB},
{POS2: IN},
{Lemma3: be}
</code>```

So, any combination can be used. A user can ask for any ngram of length three where the second item has a postag "VERB", but it can also ask for ngrams where the Xth item is an exact word etc.

Does anyone have any recommendations on which indexing strategy makes the most sense? Do I make a compound index for each possible combinations? Or do you index each individual field seperately? Anything that could provide more insight in how this works, is useful. This is a hobby project, so we're not talking about multiple users trying to access the same database and expecting the fastest possible result, I simply want to optimize the database slightly because currently querying it takes very long.

Thanks in advance. If more information is needed to provide an answer, please ask me!

Title: Best way to query a mongoDB database

Body:
I have a database containing ngram information of loads of documents. The database contains 8 collections, each for an ngram length (unigram - bigram - trigram etc). For each ngram, I also saved the lemma of the word and the POS-tag. So, the collection of trigrams contains the following fields: (Item1, Lemma1, POS1, Item2, Lemma2, POS2, Item3, Lemma3, POS3). There is also some other information stored, like the count for each of these, but that information is never used for querying purposes.

Now, I'm not a data engineer of any kind so I don't know a lot about indexing databases. The way the database is accessed is as follows: a rule in a specific syntax is the input, which is then converted to a query. A query can ask for, for example, any ngrams where:

{Item1 = Walk
    or
POS1 = VERB},
{POS2: IN},
{Lemma3: be}

So, any combination can be used. A user can ask for any ngram of length three where the second item has a postag "VERB", but it can also ask for ngrams where the Xth item is an exact word etc.

Does anyone have any recommendations on which indexing strategy makes the most sense? Do I make a compound index for each possible combinations? Or do you index each individual field seperately? Anything that could provide more insight in how this works, is useful. This is a hobby project, so we're not talking about multiple users trying to access the same database and expecting the fastest possible result, I simply want to optimize the database slightly because currently querying it takes very long.

Thanks in advance. If more information is needed to provide an answer, please ask me!


问:
Display unused factor levels in bar plot
I have the following sample data. The variable "y" has 4 factor levels. However, only 3 of them appear in the data.

How can I add the missing category "C" to the legend (and not necessarily to the plot)?

library(tidyverse)

# Sample data
n <- 100
df <- data.frame(x = sample(c("grp1","grp2", "grp3", "grp4"), size = n, replace = TRUE),
                 y = sample(c("A", "B", "D", "E"), size = n, replace = TRUE)) %>%
  mutate(x = as.factor(x),
         y = factor(y, levels = c("A", "B", "C", "D", "E")))

# Stacked barplot
df %>%
  group_by(x) %>%
  count(y) %>%
  mutate(percent = 1 / sum(n) * n) %>%

  ggplot(aes(x = x, y = percent, fill = y)) + geom_col()
```


问:
Multer mkdirSync not working when creating child folders in non-existing parent folder
So, when the user uploads a file to the message, it puts the file to:
CDN/attachments/ chatid / userid / date / the file

The mkdirSync function works if i use it like this: testfolder.

My guess, its not working, because the folders named attachments, userid etc. doesn't exist.

Is there any way to make it work? Thanks!

Heres my code:

```<code>  @Post("uploadImg")
  @UseInterceptors(
    AnyFilesInterceptor({
      storage: diskStorage({
        destination: function (req: any, file, cb) {
          console.log(req.body , file, cb)
          if (existsSync(`CDN/attachments/${req.body.dest}`)) {
            console.log('Directory exists!')
          } else {
            console.log("CREATE")
            mkdirSync(`CDN/attachments/${req.body.dest}`)
          }

          // var newAbsoluteDir = `CDN/attachments/${req.body.dest}`;
          // console.log(req.body)
          // cb(null, newAbsoluteDir);
        },
        filename: function (req, file, cb) {
          cb(null, file.originalname + '-' + Date.now() + ".png");
        },
      }),
    })
  )
  async uploadedFile(@UploadedFiles() file) {
    console.log(file)
    // console.log(file)
    // return file;
  }
</code>```

The error:

```<code>Error: ENOENT: no such file or directory, mkdir 'CDN/attachments/63aea8c5e37c6b1242a6973f/63aea86fe37c6b1242a6970a/20230105/'
    at mkdirSync (node:fs:1381:3)
    at DiskStorage.destination [as getDestination] (C:\Users\alms\Desktop\Chatenium2\chatenium-server\src\chat\message\dm\dm.controller.ts:52:22)
    at DiskStorage._handleFile (C:\Users\alms\Desktop\Chatenium2\chatenium-server\node_modules\multer\storage\disk.js:31:8)
    at C:\Users\alms\Desktop\Chatenium2\chatenium-server\node_modules\multer\lib\make-middleware.js:137:17
    at allowAll (C:\Users\alms\Desktop\Chatenium2\chatenium-server\node_modules\multer\index.js:8:3)
    at Multipart.<anonymous> (C:\Users\alms\Desktop\Chatenium2\chatenium-server\node_modules\multer\lib\make-middleware.js:107:7)
    at Multipart.emit (node:events:513:28)
    at HeaderParser.cb (C:\Users\alms\Desktop\Chatenium2\chatenium-server\node_modules\busboy\lib\types\multipart.js:358:14)
    at HeaderParser.push (C:\Users\alms\Desktop\Chatenium2\chatenium-server\node_modules\busboy\lib\types\multipart.js:162:20)
    at SBMH.ssCb [as _cb] (C:\Users\alms\Desktop\Chatenium2\chatenium-server\node_modules\busboy\lib\types\multipart.js:394:37)

</code>```

Body:
So, when the user uploads a file to the message, it puts the file to:
CDN/attachments/ chatid / userid / date / the file

The mkdirSync function works if i use it like this: testfolder.

My guess, its not working, because the folders named attachments, userid etc. doesn't exist.

Is there any way to make it work? Thanks!

Heres my code:

  @Post("uploadImg")
  @UseInterceptors(
    AnyFilesInterceptor({
      storage: diskStorage({
        destination: function (req: any, file, cb) {
          console.log(req.body , file, cb)
          if (existsSync(`CDN/attachments/${req.body.dest}`)) {
            console.log('Directory exists!')
          } else {
            console.log("CREATE")
            mkdirSync(`CDN/attachments/${req.body.dest}`)
          }

          // var newAbsoluteDir = `CDN/attachments/${req.body.dest}`;
          // console.log(req.body)
          // cb(null, newAbsoluteDir);
        },
        filename: function (req, file, cb) {
          cb(null, file.originalname + '-' + Date.now() + ".png");
        },
      }),
    })
  )
  async uploadedFile(@UploadedFiles() file) {
    console.log(file)
    // console.log(file)
    // return file;
  }

The error:

Error: ENOENT: no such file or directory, mkdir 'CDN/attachments/63aea8c5e37c6b1242a6973f/63aea86fe37c6b1242a6970a/20230105/'
    at mkdirSync (node:fs:1381:3)
    at DiskStorage.destination [as getDestination] (C:\Users\alms\Desktop\Chatenium2\chatenium-server\src\chat\message\dm\dm.controller.ts:52:22)
    at DiskStorage._handleFile (C:\Users\alms\Desktop\Chatenium2\chatenium-server\node_modules\multer\storage\disk.js:31:8)
    at C:\Users\alms\Desktop\Chatenium2\chatenium-server\node_modules\multer\lib\make-middleware.js:137:17
    at allowAll (C:\Users\alms\Desktop\Chatenium2\chatenium-server\node_modules\multer\index.js:8:3)
    at Multipart.<anonymous> (C:\Users\alms\Desktop\Chatenium2\chatenium-server\node_modules\multer\lib\make-middleware.js:107:7)
    at Multipart.emit (node:events:513:28)
    at HeaderParser.cb (C:\Users\alms\Desktop\Chatenium2\chatenium-server\node_modules\busboy\lib\types\multipart.js:358:14)
    at HeaderParser.push (C:\Users\alms\Desktop\Chatenium2\chatenium-server\node_modules\busboy\lib\types\multipart.js:162:20)
    at SBMH.ssCb [as _cb] (C:\Users\alms\Desktop\Chatenium2\chatenium-server\node_modules\busboy\lib\types\multipart.js:394:37)


问:
Fill color to adjacent cells in Excel add-in in React js
I am working on Excel add-in in React js. I have current cell address, for example "B3", know I want to fill color on adjacent cells and itself (left cell, current cell, right cell) with dynamic range. How to achieve this thing? I have searched a lot but nothing helped out.

```<code>let range = worksheet.getRange(address);
range.format.fill.color = "red";
</code>```

In above code, only current cell is getting red.

Body:
I am working on Excel add-in in React js. I have current cell address, for example "B3", know I want to fill color on adjacent cells and itself (left cell, current cell, right cell) with dynamic range. How to achieve this thing? I have searched a lot but nothing helped out.

let range = worksheet.getRange(address);
range.format.fill.color = "red";

In above code, only current cell is getting red.


问:
SwiftUI - Localization: What is the difference between locale versions
I want to make my app show different view for the Japanese people.
There are so many different ways to get SwiftUI's locale, what is the difference between them?

```<code>    @Environment(\.locale) var locale

    locale == Locale(identifier: "ja_JP")
    locale.identifier == "ja"
    locale.identifier == "ja_JP"
    locale.language.languageCode == "ja"
    locale.language.languageCode == Locale.LanguageCode.japanese
    locale.language.languageCode?.identifier == "ja"
</code>```

For example:

```<code>struct LocalizedView: View {
    @Environment(\.locale) var locale

    var isJapaneseLocale: Bool {
        locale == Locale(identifier: "ja_JP") ||
        locale.identifier == "ja" ||
        locale.identifier == "ja_JP" ||
        locale.language.languageCode == "ja" ||
        locale.language.languageCode == Locale.LanguageCode.japanese ||
        locale.language.languageCode?.identifier == "ja"
    }

    var body: some View {
        if isJapaneseLocale {
            Rectangle()
        } else {
            Circle()
        }
    }
}
</code>```

Body:
I want to make my app show different view for the Japanese people.
There are so many different ways to get SwiftUI's locale, what is the difference between them?

    @Environment(\.locale) var locale

    locale == Locale(identifier: "ja_JP")
    locale.identifier == "ja"
    locale.identifier == "ja_JP"
    locale.language.languageCode == "ja"
    locale.language.languageCode == Locale.LanguageCode.japanese
    locale.language.languageCode?.identifier == "ja"

For example:

struct LocalizedView: View {
    @Environment(\.locale) var locale

    var isJapaneseLocale: Bool {
        locale == Locale(identifier: "ja_JP") ||
        locale.identifier == "ja" ||
        locale.identifier == "ja_JP" ||
        locale.language.languageCode == "ja" ||
        locale.language.languageCode == Locale.LanguageCode.japanese ||
        locale.language.languageCode?.identifier == "ja"
    }

    var body: some View {
        if isJapaneseLocale {
            Rectangle()
        } else {
            Circle()
        }
    }
}