问:
Formtools does not display my formsets, only the forms
hi i am using formtools to submit a multistep form. The problem is that I haven't found many tutorials about it. And it is that I was able to create the form but the formset does not appear. What am I doing wrong or what am I missing?

if I stopped using formtools if the formset is seen but not with formtools, I think that I am not generating the view correctly so that it displays the formset and saves the data throughout the multi step form

views.py

```<code>class PresupuestoWizardView(SessionWizardView):
    file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'files'))
    form_list = [PresupuestosClientesForm, PresupuestosVehiculosForm,PresupuestosParteForm,PresupuestosManoObraForm,PresupuestosPagosForm,PresupuestosFotosForm]
    template_name = "Presupuestos/new-customer.html"

    def done(self, form_list, **kwargs):
        return render(self.request, "Presupuestos/new-customer.html", {
            'form_data': [form.cleaned_data for form in form_list],
         })

</code>```

forms.py

```<code>ParteFormSet = formset_factory(PresupuestosParteForm, extra=extra_forms, max_num=20)
ManoObraFormSet = formset_factory(PresupuestosManoObraForm, extra=extra_forms, max_num=20)
PagosFormSet = formset_factory(PresupuestosPagosForm, extra=extra_forms, max_num=20)

extra_forms = 1

DESCUENTO = (
    ('Quantity', 'Quantity'),
    ('Percentage', 'Percentage'),
)

DISCOUNT= (
    ('Quantity', 'Quantity'),
    ('Percentage', 'Percentage'),
)

class PresupuestosClientesForm(forms.ModelForm):
    class Meta:
        model = Clientes
        fields = '__all__'
        widgets = {
            'titulo': forms.Select(
                attrs={
                    'class': 'form-select'
                }
            ),
            'nombre': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),
            'apellido': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),
            'correo': forms.EmailInput(
                attrs={
                    'class': 'form-control'
                }
            ),
            'telefono': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),

            'tel': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),
            'notas': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),
        }

class PresupuestosVehiculosForm(forms.ModelForm):

    class Meta:
        model = Carro
        fields = '__all__'
        widgets = {
            'placas': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),
            'año': forms.NumberInput(
                attrs={
                    'class': 'form-control'
                }
            ),
            'modelo':forms.TextInput(
                attrs={
                    'class':'form-control'
                }
            ),
            'marca': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),
            'tipo': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),
            'motor': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),
            'vin': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),
            'color': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),

        }

class PresupuestosFotosForm(forms.ModelForm):
    class Meta:
        model = Foto
        fields = '__all__'
        widgets = {
            'imagenes': forms.FileInput(
                attrs={
                    'class': 'form-control',
                    'multiple': True
                }
            ),
        }

</code>```

答:
You need to pass your formsets into form_list not the individual forms

form_list = [PresupuestosClientesForm, PresupuestosVehiculosForm, ParteFormSet, ManoObraFormSet, PagosFormSet,PresupuestosFotosForm]

Body:
hi i am using formtools to submit a multistep form. The problem is that I haven't found many tutorials about it. And it is that I was able to create the form but the formset does not appear. What am I doing wrong or what am I missing?

if I stopped using formtools if the formset is seen but not with formtools, I think that I am not generating the view correctly so that it displays the formset and saves the data throughout the multi step form

views.py

class PresupuestoWizardView(SessionWizardView):
    file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'files'))
    form_list = [PresupuestosClientesForm, PresupuestosVehiculosForm,PresupuestosParteForm,PresupuestosManoObraForm,PresupuestosPagosForm,PresupuestosFotosForm]
    template_name = "Presupuestos/new-customer.html"

    def done(self, form_list, **kwargs):
        return render(self.request, "Presupuestos/new-customer.html", {
            'form_data': [form.cleaned_data for form in form_list],
         })

forms.py

ParteFormSet = formset_factory(PresupuestosParteForm, extra=extra_forms, max_num=20)
ManoObraFormSet = formset_factory(PresupuestosManoObraForm, extra=extra_forms, max_num=20)
PagosFormSet = formset_factory(PresupuestosPagosForm, extra=extra_forms, max_num=20)

extra_forms = 1

DESCUENTO = (
    ('Quantity', 'Quantity'),
    ('Percentage', 'Percentage'),
)

DISCOUNT= (
    ('Quantity', 'Quantity'),
    ('Percentage', 'Percentage'),
)

class PresupuestosClientesForm(forms.ModelForm):
    class Meta:
        model = Clientes
        fields = '__all__'
        widgets = {
            'titulo': forms.Select(
                attrs={
                    'class': 'form-select'
                }
            ),
            'nombre': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),
            'apellido': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),
            'correo': forms.EmailInput(
                attrs={
                    'class': 'form-control'
                }
            ),
            'telefono': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),

            'tel': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),
            'notas': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),
        }

class PresupuestosVehiculosForm(forms.ModelForm):

    class Meta:
        model = Carro
        fields = '__all__'
        widgets = {
            'placas': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),
            'año': forms.NumberInput(
                attrs={
                    'class': 'form-control'
                }
            ),
            'modelo':forms.TextInput(
                attrs={
                    'class':'form-control'
                }
            ),
            'marca': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),
            'tipo': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),
            'motor': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),
            'vin': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),
            'color': forms.TextInput(
                attrs={
                    'class': 'form-control'
                }
            ),

        }

class PresupuestosFotosForm(forms.ModelForm):
    class Meta:
        model = Foto
        fields = '__all__'
        widgets = {
            'imagenes': forms.FileInput(
                attrs={
                    'class': 'form-control',
                    'multiple': True
                }
            ),
        }


来源: stackexchange

问:
Equivalent to Docker Desktop's 'host.docker.internal' in Rancher Desktop
For Docker Desktop inside a container, the DNS name host.docker.internal resolves to an IP address allowing network access to the host. Is there something similar when using Rancher Desktop?

Assuming a running container (e.g the alpine image) in Docker Desktop it's possible to run

```<code>docker exec alpine-container ping -c 2 host.docker.internal
</code>```

Update: This has been resolved and released with v1.0.1 as it seems.

答:
When using the dockerd (moby) container runtime in Rancher Desktop, adding --add-host=host.docker.internal:host-gateway to your docker run command will achieve this behavior.

```<code>docker run -it --add-host=host.docker.internal:host-gateway alpine cat /etc/hosts
</code>```

Or for docker-compose:

```<code># docker-compose.yml
  my_app:
    image: ...
    extra_hosts:
      - "host.docker.internal:host-gateway"
</code>```

https://megamorf.gitlab.io/2020/09/19/access-native-services-on-docker-host-via-host-docker-internal/#implementation

However I don't believe this will work when using Rancher Desktop with containerd as the container runtime.

ContentLicense: CC BY-SA 4.0

Body:
For Docker Desktop inside a container, the DNS name host.docker.internal resolves to an IP address allowing network access to the host. Is there something similar when using Rancher Desktop?

Assuming a running container (e.g the alpine image) in Docker Desktop it's possible to run

docker exec alpine-container ping -c 2 host.docker.internal

Update: This has been resolved and released with v1.0.1 as it seems.

Body:
When using the dockerd (moby) container runtime in Rancher Desktop, adding --add-host=host.docker.internal:host-gateway to your docker run command will achieve this behavior.

docker run -it --add-host=host.docker.internal:host-gateway alpine cat /etc/hosts

Or for docker-compose:

# docker-compose.yml
  my_app:
    image: ...
    extra_hosts:
      - "host.docker.internal:host-gateway"

https://megamorf.gitlab.io/2020/09/19/access-native-services-on-docker-host-via-host-docker-internal/#implementation

However I don't believe this will work when using Rancher Desktop with containerd as the container runtime.


问:
Azure MS Team integration with Azure DevOps Taskboard only showing Issues, where are my work items?
Azure boards MS Team integration. Only showing Issues or Epics, where are my work items?

I added a tab into a Team channel, and I can see Issues, but there is not option for showing the Work Item field?
On the Azure Boards website I see both fields: Issues and Work items.

Here is no Work Item field

This is the website showing both types at once

答:
wow I can believe after almost a year nobody replied you. You can set it up in the Organization Settings > Boards > Settings then you can see the process selected. e.g Agile, Basic (what you mentioned) Scrum, etc.

I hope helped someone after this.


问:
Extract string between exact word and pattern using stringr
I have been wondering how to extract string in R using stringr or another package between the exact word "to the" (which is always lowercase) and the very second comma in a sentence.

For instance:

String: "This not what I want to the THIS IS WHAT I WANT, DO YOU SEE IT?, this is not what I want"

Desired output: "THIS IS WHAT I WANT, DO YOU SEE IT?"

I have this vector:

```<code>x<-c("This not what I want to the THIS IS WHAT I WANT, DO YOU SEE IT?, this is not what I want",
     "HYU_IO TO TO to the I WANT, THIS, this i dont, want", "uiui uiu to the xxxx,,this is not, what I want")
</code>```

and I am trying to use this code

```<code>str_extract(string = x, pattern = "(?<=to the ).*(?=\\,)")
</code>```

but I cant seem to get it to work to properly give me this:

```<code>"THIS IS WHAT I WANT, DO YOU SEE IT?"
"I WANT, THIS"
"xxxx,"
</code>```

Thank you guys so much for your time and help

答:
Alternative approach, by far not comparable with Gregor Thomas approach, but somehow an alternative:

vector to tibble

separate twice by first to the then by ,

paste together

pull for vector output.

```<code>library(tidyverse)

as_tibble(x) %>%
  separate(value, c("a", "b"), sep = 'to the ') %>%
  separate(b, c("a", "c"), sep =",") %>%
  mutate(x = paste0(a, ",", c), .keep="unused") %>%
  pull(x)
</code>```
```<code>[1] "THIS IS WHAT I WANT, DO YOU SEE IT?"
[2] "I WANT, THIS"
[3] "xxxx,"
</code>```

Body:
I have been wondering how to extract string in R using stringr or another package between the exact word "to the" (which is always lowercase) and the very second comma in a sentence.

For instance:

String: "This not what I want to the THIS IS WHAT I WANT, DO YOU SEE IT?, this is not what I want"

Desired output: "THIS IS WHAT I WANT, DO YOU SEE IT?"

I have this vector:

x<-c("This not what I want to the THIS IS WHAT I WANT, DO YOU SEE IT?, this is not what I want",
     "HYU_IO TO TO to the I WANT, THIS, this i dont, want", "uiui uiu to the xxxx,,this is not, what I want")

and I am trying to use this code

str_extract(string = x, pattern = "(?<=to the ).*(?=\\,)")

but I cant seem to get it to work to properly give me this:

"THIS IS WHAT I WANT, DO YOU SEE IT?"
"I WANT, THIS"
"xxxx,"

Thank you guys so much for your time and help

Body:
Alternative approach, by far not comparable with Gregor Thomas approach, but somehow an alternative:

vector to tibble

separate twice by first to the then by ,

paste together

pull for vector output.

library(tidyverse)

as_tibble(x) %>%
  separate(value, c("a", "b"), sep = 'to the ') %>%
  separate(b, c("a", "c"), sep =",") %>%
  mutate(x = paste0(a, ",", c), .keep="unused") %>%
  pull(x)

[1] "THIS IS WHAT I WANT, DO YOU SEE IT?"
[2] "I WANT, THIS"
[3] "xxxx,"


问:
Swift and Firebase - Receiving image from the user then uploading it to firebase
I want the user to upload an image from the photos library along with more input so I can write it to my database.
I made an object with the received data from the user and I uploaded it (using ".child()") to firebase realtime database, but then I had to add the photo to the object so I used the UIImagePicker to upload the photo then I got stuck.
my problem is that i don't know what type of info I should get from the image so I can add it to the object.
I'm not sure if using an object is the right choice but since the data I’m adding is related to a specific item I thought it would be suitable.

// The object

```<code> let object: [String : Any] = ["areaname": areaName! as Any ,"spotNo": spotNo, "loactionLat": areaLat, "locationLong": areaLong]
    database.child("Areas").child("Area_\(Int.random(in: 0..<100))" ).setValue(object)

@IBAction func chooseImageButton() {
    print("Add image button was pressed")
    let vc = UIImagePickerController()
    vc.sourceType = .photoLibrary
    vc.delegate = self
    vc.allowsEditing = true
    present(vc, animated: true)

}

extension AddAreaViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediawithInfo info: [UIImagePickerController.InfoKey : Any]) {
    print("\(info)")
    if let image = info[UIImagePickerController.InfoKey(rawValue: "UIImagePickerControllerEditedImage")] as? UIImage {
    }

    picker.dismiss(animated: true, completion: nil) }

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    picker.dismiss(animated: true, completion: nil)
}
</code>```

}

Firebase structure

答: My solution is saving the image using FirebaseStorage. And turn the image url to string write into database. When you need loading image. You can search by that urlstring.</p>

Body:
I want the user to upload an image from the photos library along with more input so I can write it to my database.
I made an object with the received data from the user and I uploaded it (using ".child()") to firebase realtime database, but then I had to add the photo to the object so I used the UIImagePicker to upload the photo then I got stuck.
my problem is that i don't know what type of info I should get from the image so I can add it to the object.
I'm not sure if using an object is the right choice but since the data I’m adding is related to a specific item I thought it would be suitable.

// The object

 let object: [String : Any] = ["areaname": areaName! as Any ,"spotNo": spotNo, "loactionLat": areaLat, "locationLong": areaLong]
    database.child("Areas").child("Area_\(Int.random(in: 0..<100))" ).setValue(object)

@IBAction func chooseImageButton() {
    print("Add image button was pressed")
    let vc = UIImagePickerController()
    vc.sourceType = .photoLibrary
    vc.delegate = self
    vc.allowsEditing = true
    present(vc, animated: true)

}

extension AddAreaViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediawithInfo info: [UIImagePickerController.InfoKey : Any]) {
    print("\(info)")
    if let image = info[UIImagePickerController.InfoKey(rawValue: "UIImagePickerControllerEditedImage")] as? UIImage {
    }

    picker.dismiss(animated: true, completion: nil) }

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    picker.dismiss(animated: true, completion: nil)
}

}

Firebase structure


问:
How can I fix this error: Uncaught SyntaxError: expected expression, got '<'?
I want to get the data from the JSON file, it works fine on my computer, but when I put it on my server, it shows this error.

Error: Uncaught SyntaxError: expected expression, got '<'

This is my code:

setInterval(function () {
    loadJSON(function (response) {
        jsonresponse = JSON.parse(response);
        document.getElementById('stats').innerHTML = jsonresponse[0].name;
    });
}, 1000);

function loadJSON(callback) {
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType('application/json');
    xobj.open('GET', 'data.json', true);
    xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == '200') {
            callback(xobj.responseText);
        }
    }
    xobj.send(null);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <link rel="stylesheet" href="/style.css">
    </head>
    <script src="./index.js"></script>
    <script src="./node.js"></script>
    <script src="./data.json"></script>
    </body>
</html></code>```

Any idea of how to fix this?

答:
Why have you added json file in script tag

Also are the files available on your server? Sometimes this error happens when the Javascript referenced file doesn't exist.

Body:
I want to get the data from the JSON file, it works fine on my computer, but when I put it on my server, it shows this error.

Error: Uncaught SyntaxError: expected expression, got '<'

This is my code:

setInterval(function () {
    loadJSON(function (response) {
        jsonresponse = JSON.parse(response);
        document.getElementById('stats').innerHTML = jsonresponse[0].name;
    });
}, 1000);

function loadJSON(callback) {
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType('application/json');
    xobj.open('GET', 'data.json', true);
    xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == '200') {
            callback(xobj.responseText);
        }
    }
    xobj.send(null);
}

<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <link rel="stylesheet" href="/style.css">

Any idea of how to fix this?

Body:
Why have you added json file in script tag <script src="./data.json"></script>

Also are the files available on your server? Sometimes this error happens when the Javascript referenced file doesn't exist.


问:
serve current directory from command line
could someone give me a hint, howto serve the current directory from command line with ruby? it would be great, if i can have some system wide configuration (e.g. mime-types) and simply launch it from every directory.</p>

答:
Simplest way possible (thanks Aaron Patterson/n0kada):

```<code>ruby -run -e httpd . -p 9090
</code>```

Alternate, more complex way:

```<code>ruby -r webrick -e "s = WEBrick::HTTPServer.new(:Port => 9090, :DocumentRoot => Dir.pwd); trap('INT') { s.shutdown }; s.start"
</code>```

Even the first command is hard to remember, so I just have this in my .bashrc:

```<code>function serve {
  port="${1:-3000}"
  ruby -run -e httpd . -p $port
}
</code>```

It serves the current directory on port 3000 by default, but you can also specify the port:

```<code>~ $ cd tmp
~/tmp $ serve      # ~/tmp served on port 3000
~/tmp $ cd ../www
~/www $ serve 5000   # ~/www served on port 5000
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Simplest way possible (thanks Aaron Patterson/n0kada):

ruby -run -e httpd . -p 9090

Alternate, more complex way:

ruby -r webrick -e "s = WEBrick::HTTPServer.new(:Port => 9090, :DocumentRoot => Dir.pwd); trap('INT') { s.shutdown }; s.start"

Even the first command is hard to remember, so I just have this in my .bashrc:

function serve {
  port="${1:-3000}"
  ruby -run -e httpd . -p $port
}

It serves the current directory on port 3000 by default, but you can also specify the port:

~ $ cd tmp
~/tmp $ serve      # ~/tmp served on port 3000
~/tmp $ cd ../www
~/www $ serve 5000   # ~/www served on port 5000

ContentLicense: CC BY-SA 3.0


问:
Kibana visualization for grouping and filter
I have my data in Elasticsearch like below

I'm trying to create a pie chart in kibana which shows the percentage of people who visited both UK and India and % of people who visited only India and % percentage of people who visited only UK.

 But I'm not able to find a way to group by person name and do filter on the country visited in the pie chart in kibana. Any way to do this?

答:
I believe you are looking for filterAggregation : Filter Aggregation
Effectively it enables aggregation on different filters.

Add this as a second aggregation(split slice) after the Persons Aggregation.

If you are just interested in count and Not counts per person, just leverage Filter Aggregation with respective filters which will give you the percentages per filter.


问:
How to make sure a line of code is run after another has completed?
I tried to make the last two lines of this code run after the ones before them but they have always run first! Please help.</p>
```<code>PostAPI.getPostById(postId: self.postId) { postResponse in
        let post = postResponse
        self.posts[indexPath.row] = post
        let cellNumber = IndexPath(row: indexPath.row, section: indexPath.section)
        self.postsTableView.reloadRows(at: [cellNumber], with: .none)
        likesButton?.tintColor = .systemPink
        likesButton?.setImage(UIImage(systemName: "heart.fill"), for: .normal)
    }
</code>```

答:
If DispatchQueue.main.async didnt work maybe you can try a function with completion</p>
```<code>PostAPI.getPostById(postId: self.postId) { postResponse in
    self.reloadThenLike {
        self.likesButton?.tintColor = .systemPink
        self.likesButton?.setImage(UIImage(systemName: "heart.fill"),
            for: .normal)
    }
}

func reloadThenLike(completion: @escaping () -> ()) {
    let post = postResponse
    self.posts[indexPath.row] = post
    let cellNumber = IndexPath(row: indexPath.row, section:
        indexPath.section)
    self.postsTableView.reloadRows(at: [cellNumber], with: .none)
    completion()
}
</code>```

Body:
I tried to make the last two lines of this code run after the ones before them but they have always run first! Please help.

PostAPI.getPostById(postId: self.postId) { postResponse in
        let post = postResponse
        self.posts[indexPath.row] = post
        let cellNumber = IndexPath(row: indexPath.row, section: indexPath.section)
        self.postsTableView.reloadRows(at: [cellNumber], with: .none)
        likesButton?.tintColor = .systemPink
        likesButton?.setImage(UIImage(systemName: "heart.fill"), for: .normal)
    }

Body:
If DispatchQueue.main.async didnt work maybe you can try a function with completion

PostAPI.getPostById(postId: self.postId) { postResponse in
    self.reloadThenLike {
        self.likesButton?.tintColor = .systemPink
        self.likesButton?.setImage(UIImage(systemName: "heart.fill"),
            for: .normal)
    }
}

func reloadThenLike(completion: @escaping () -> ()) {
    let post = postResponse
    self.posts[indexPath.row] = post
    let cellNumber = IndexPath(row: indexPath.row, section:
        indexPath.section)
    self.postsTableView.reloadRows(at: [cellNumber], with: .none)
    completion()
}


问:
How can I let the Debug Console print something 5 times instead of 1 time in Javascript, Visual Studio Code?
I am new to JavaScript. Is there a way to see the Hello 5 times instead see it showing that it was printed 5 times?

答:
Disable the setting:

Debug > Console: Collapse Identical Lines

Controls if the debug console should collapse identical lines and
show a number of occurrences with a badge.


问:
prometheus not starting (not loading prometheus.yml file)
while starting Prometheus I'm getting the following error:

```<code>level=error ts=2021-05-13T04:42:39.652Z caller=main.go:355 msg="Error loading config (--config.file=prometheus.yml)" err="parsing YAML file prometheus.yml: yaml: line 36: did not find expected key"
</code>```

I was trying to integrate Blackbox Exporter to Prometheus.

This is my prometheus.yml file:

# my global config
global:
  scrape_interval:     15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

# Alertmanager configuration
alerting:
  alertmanagers:
  - static_configs:
    - targets:
      # - alertmanager:9093

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "first_rules.yml"
  # - "second_rules.yml"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any time-series scraped from this config.
  - job_name: 'prometheus'

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    static_configs:
    - targets: ['localhost:9090']
  - job_name: 'node_exporter'
    static_configs:
    - targets: ['localhost:9100']

  - job_name: 'blackbox_exporter'
     metrics_path: /probe
     params:
       module: [http_2xx]
     static_configs:
       - targets:
           - https://www.google.in
     relabel_configs:
       - source_labels: [__address__]
         target_label: __param_target
       - source_labels: [__param_target]
         target_label: instance
       - target_label: __address__
         replacement: localhost:9115
```

答:
Try running

```<code>promtool check config your_config.yml
</code>```

For rules files use check rules instead.

For alertmanager config files use amtool check-config alertmanager.yml

Body:
while starting Prometheus I'm getting the following error:

level=error ts=2021-05-13T04:42:39.652Z caller=main.go:355 msg="Error loading config (--config.file=prometheus.yml)" err="parsing YAML file prometheus.yml: yaml: line 36: did not find expected key"

I was trying to integrate Blackbox Exporter to Prometheus.

This is my prometheus.yml file:

# my global config
global:
  scrape_interval:     15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

# Alertmanager configuration
alerting:
  alertmanagers:
  - static_configs:
    - targets:
      # - alertmanager:9093

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "first_rules.yml"
  # - "second_rules.yml"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any time-series scraped from this config.
  - job_name: 'prometheus'

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    static_configs:
    - targets: ['localhost:9090']
  - job_name: 'node_exporter'
    static_configs:
    - targets: ['localhost:9100']

  - job_name: 'blackbox_exporter'
     metrics_path: /probe
     params:
       module: [http_2xx]
     static_configs:
       - targets:
           - https://www.google.in
     relabel_configs:
       - source_labels: [__address__]
         target_label: __param_target
       - source_labels: [__param_target]
         target_label: instance
       - target_label: __address__
         replacement: localhost:9115

Body:
Try running

promtool check config your_config.yml

For rules files use check rules instead.

For alertmanager config files use amtool check-config alertmanager.yml


问:
When will most libraries be Python 3 compliant?
Does anyone have an idea how long it will take before "almost all" widely used Python libraries work with Python 3.0?

I am planning to stay on 2.X for a while because I don't want to start porting stuff over and then find that some library I already rely on or a new library I might start using doesn't work yet with py3k.

My understanding is that the py3k beta process was drawn out specifically to give library developers time to move their stuff over. Has this been happening?

Examples of the sorts of libraries I am talking about would be PIL, numpy/ scipy, SQLAlchemy, BeautifulSoup, CherryPy...

答:
The libraries you mention will be ported once someone puts some serious time into porting them.

In the specific case of NumPy/SciPy, a large part of the code is written as C extensions.  There is no 2to3 tool for C extensions and so it will take a large amount of man hours to port the code over to the format that cPython3 C extensions need to use.

OwnerDisplayName: indentation

LastEditorDisplayName: Adam Haile

OwnerDisplayName: David Locke


问:
How to fetch complex json data by specific names in flutter
https://api.covid19api.com/summary
This is the API I am using now I can fetch the global data by the below code I want to fetch data of a single Country(India) by the same method. If there is no method by which I can get the data then if I use "https://api.covid19api.com/total/dayone/country/India" then how to get the daily confirmed cases.?

```<code>class GlobalSummaryModel{
  final int newConfirmed;
  final int totalConfirmed;
  final int newDeaths;
  final int totalDeaths;
  final int newRecovered;
  final int totalRecovered;
  final DateTime date;

  GlobalSummaryModel(this.newConfirmed, this.totalConfirmed, this.newDeaths, this.totalDeaths, this.newRecovered, this.totalRecovered, this.date);

  factory GlobalSummaryModel.fromJson(Map<String, dynamic> json){
    return GlobalSummaryModel(
      json["Global"]["NewConfirmed"],
      json["Global"]["TotalConfirmed"],
      json["Global"]["NewDeaths"],
      json["Global"]["TotalDeaths"],
      json["Global"]["NewRecovered"],
      json["Global"]["TotalRecovered"],
      DateTime.parse(json["Date"]),
    );
  }
}
</code>```

Please provide me the code if you can that will be more helpful for me I am new in fetching data from the rest API.

答:
The API also returns a Countries field in the response, which contains data for India. You can extract that data like so:

```<code>final countries = json["Countries"];
final Map<String, dynamic> indiaSummaryData = countries.firstWhere((map) {
  return map["CountryCode"] == "IN";
});
</code>```

Body:
https://api.covid19api.com/summary
This is the API I am using now I can fetch the global data by the below code I want to fetch data of a single Country(India) by the same method. If there is no method by which I can get the data then if I use "https://api.covid19api.com/total/dayone/country/India" then how to get the daily confirmed cases.?

class GlobalSummaryModel{
  final int newConfirmed;
  final int totalConfirmed;
  final int newDeaths;
  final int totalDeaths;
  final int newRecovered;
  final int totalRecovered;
  final DateTime date;

  GlobalSummaryModel(this.newConfirmed, this.totalConfirmed, this.newDeaths, this.totalDeaths, this.newRecovered, this.totalRecovered, this.date);

  factory GlobalSummaryModel.fromJson(Map<String, dynamic> json){
    return GlobalSummaryModel(
      json["Global"]["NewConfirmed"],
      json["Global"]["TotalConfirmed"],
      json["Global"]["NewDeaths"],
      json["Global"]["TotalDeaths"],
      json["Global"]["NewRecovered"],
      json["Global"]["TotalRecovered"],
      DateTime.parse(json["Date"]),
    );
  }
}

Please provide me the code if you can that will be more helpful for me I am new in fetching data from the rest API.

Body:
The API also returns a Countries field in the response, which contains data for India. You can extract that data like so:

final countries = json["Countries"];
final Map<String, dynamic> indiaSummaryData = countries.firstWhere((map) {
  return map["CountryCode"] == "IN";
});


问:
Why can't I redirect to the file that grep uses for input?
```<code>File1:
foo
bar
baz

File2:
bar.patch

grep -f file1 file2 > file1
</code>```

Expected result, file1 contains bar.patch, instead it is empty.

How is grep processing the input file such that I cannot redirect to it?

答:
Redirection > happens before the command is executed, hence the grep sees empty file and returns nothing. If you really want to write to the same file you can use the sponge command (it is part of the moreutils). It buffers the input and writes to the output file only after the end of data. Example:

```<code>grep -f file1 file2 | sponge file1
</code>```

Check the bash manual for details about redirection:

Before a command is executed, its input and output may be redirected
using a special notation interpreted by the shell. Redirection allows
commands’ file handles to be duplicated, opened, closed, made to refer
to different files, and can change the files the command reads from
and writes to. Redirection may also be used to modify file handles in
the current shell execution environment. The following redirection
operators may precede or appear anywhere within a simple command or
may follow a command. Redirections are processed in the order they
appear, from left to right.

Or just redirect to a temporary file and then mv it over the file1.

```<code>grep -f file1 file2 > file3
mv -f file3 file1
</code>```

Body:
File1:
foo
bar
baz

File2:
bar.patch

grep -f file1 file2 > file1

Expected result, file1 contains bar.patch, instead it is empty.

How is grep processing the input file such that I cannot redirect to it?

Body:
Redirection > happens before the command is executed, hence the grep sees empty file and returns nothing. If you really want to write to the same file you can use the sponge command (it is part of the moreutils). It buffers the input and writes to the output file only after the end of data. Example:

grep -f file1 file2 | sponge file1

Check the bash manual for details about redirection:

Before a command is executed, its input and output may be redirected
using a special notation interpreted by the shell. Redirection allows
commands’ file handles to be duplicated, opened, closed, made to refer
to different files, and can change the files the command reads from
and writes to. Redirection may also be used to modify file handles in
the current shell execution environment. The following redirection
operators may precede or appear anywhere within a simple command or
may follow a command. Redirections are processed in the order they
appear, from left to right.

Or just redirect to a temporary file and then mv it over the file1.

grep -f file1 file2 > file3
mv -f file3 file1


问:
How to create a number of strings based of an array imported from a filetex?
I'm currently very new to python programming and encountered such problem
I have a textfile with strings separated by spaces and by new lines like this:

UR 11199 TPO 0625  APF 1371 ABS 1126 ABT 0475 ASL 0518

Im importing with numpy np.str and is printing out like this

```<code>`
[['UR' '11199']
 ['TPO' '0625']
 ['APF' '1371']
 ['ABS' '1126']
 ['ABT' '0475']
 ['ASL' '0518']]`
</code>```

My thing is that for each line I want to condense the letters with the numbers and make a single string so that the user might type anything beyond, complementing the string like this:

UR11199 OK

How should I do this? tried using hsplit but didnt worked out for me

##EDIT##
Maybe I wasnt clear enough, English isnt my first language.
I need to have different strings for each line, so that a user can input data for each line like

string a == UR11199 abcd

string b == TPO0625 EFGH

答:
What about that:

```<code>mys = "UR 11199 TPO 0625  APF 1371 ABS 1126 ABT 0475 ASL 0518"
for i, word in enumerate(mys.split()):
    print(word, end="" if i % 2 == 0 else "\n")
</code>```

output:

```<code>UR11199
TPO0625
APF1371
ABS1126
ABT0475
ASL0518
</code>```

Body:
I'm currently very new to python programming and encountered such problem
I have a textfile with strings separated by spaces and by new lines like this:

UR 11199 TPO 0625  APF 1371 ABS 1126 ABT 0475 ASL 0518

Im importing with numpy np.str and is printing out like this

`
[['UR' '11199']
 ['TPO' '0625']
 ['APF' '1371']
 ['ABS' '1126']
 ['ABT' '0475']
 ['ASL' '0518']]`

My thing is that for each line I want to condense the letters with the numbers and make a single string so that the user might type anything beyond, complementing the string like this:

UR11199 OK

How should I do this? tried using hsplit but didnt worked out for me

##EDIT##
Maybe I wasnt clear enough, English isnt my first language.
I need to have different strings for each line, so that a user can input data for each line like

string a == UR11199 abcd

string b == TPO0625 EFGH

Body:
What about that:

mys = "UR 11199 TPO 0625  APF 1371 ABS 1126 ABT 0475 ASL 0518"
for i, word in enumerate(mys.split()):
    print(word, end="" if i % 2 == 0 else "\n")

output:

UR11199
TPO0625
APF1371
ABS1126
ABT0475
ASL0518


问:
Count unique register in numpy array
I have a numpy array with letters "a", "b" or "c",

```<code>import numpy as np

my_array = np.array(["a", "a", "c", "c", "a"]) # In this example "b" is not present

</code>```

I want to fuild a function f that counts the unique records of each letter present in the array, for my example f should respond [3, 0, 2] meaning that "a" has appeared 3 times, "b" 0 times and "c" 2 times.

I'm looking for solution (if it possible) that use numpy functions and not explicit for loops over the array. Maybe a kind of group by

答:
Counter from the collections builtin will do that for you.

```<code>import numpy as np
my_array = np.array(["a", "a", "c", "c", "a"])
from collections import Counter
cnt = Counter(my_array)
cnt
#  Counter({'a': 3, 'c': 2})
</code>```

Note that it does not provide counts for items which did not appear until you ask for them. At that point the counter will return 0.

```<code>>>> cnt['b']
0
</code>```

If you want to wrap that in a function where you already have a list of keys (not all of which may be present in your array data), that will not populate the 0 counts with keys for you. If you want the 0s and the keys to be populated, something like this:

```<code>import numpy as np
from collections import Counter
from typing import Dict, Any

def counter_function(data, keys) -> Dict[Any, int]:
    cnt = Counter(data)
    for key in keys:
        cnt[key] = cnt[key]
    return cnt

my_array = np.array(["a", "a", "c", "c", "a"])
so_counter = counter_function(my_array, ["a", "b", "c"])
so_counter
# Counter({'a': 3, 'c': 2, 'b': 0})
</code>```

will do it for you.

Title: Count unique register in numpy array

Body:
I have a numpy array with letters "a", "b" or "c",

import numpy as np

my_array = np.array(["a", "a", "c", "c", "a"]) # In this example "b" is not present

I want to fuild a function f that counts the unique records of each letter present in the array, for my example f should respond [3, 0, 2] meaning that "a" has appeared 3 times, "b" 0 times and "c" 2 times.

I'm looking for solution (if it possible) that use numpy functions and not explicit for loops over the array. Maybe a kind of group by

Body:
Counter from the collections builtin will do that for you.

import numpy as np
my_array = np.array(["a", "a", "c", "c", "a"])
from collections import Counter
cnt = Counter(my_array)
cnt
#  Counter({'a': 3, 'c': 2})

Note that it does not provide counts for items which did not appear until you ask for them. At that point the counter will return 0.

>>> cnt['b']
0

If you want to wrap that in a function where you already have a list of keys (not all of which may be present in your array data), that will not populate the 0 counts with keys for you. If you want the 0s and the keys to be populated, something like this:

import numpy as np
from collections import Counter
from typing import Dict, Any

def counter_function(data, keys) -> Dict[Any, int]:
    cnt = Counter(data)
    for key in keys:
        cnt[key] = cnt[key]
    return cnt

my_array = np.array(["a", "a", "c", "c", "a"])
so_counter = counter_function(my_array, ["a", "b", "c"])
so_counter
# Counter({'a': 3, 'c': 2, 'b': 0})

will do it for you.


问:
How to zoom out on Firefox driver using Mac?
I try to figure out how to zoom in on Firefox driver using Selenium on a Mac. When I try to use the send_keys() method on the html element, nothing happens (no action). The action method gets no action neither.

When I try to use the pyautogui module instead, the code works on Windows but not on Mac. It actually zooms out to 120% on the Mac?

Which is the best way to solve this?

```<code># IMPORTS
from sys import platform
import os

import pyautogui
pyautogui.FAILSAFE = True

import time

import tkinter as tk

from selenium import webdriver
from selenium.webdriver import Firefox, FirefoxOptions
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
# import Action chains
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import Select
from selenium.webdriver.firefox.service import Service

class Driver():
    def __init__(self):
        ...
        self.driver = Firefox(service=self.service_path, options=self.opts)

        #open url
        self.driver.get("https://google.com/")

        #zoom out
        time.sleep(3)

        self.html = self.driver.find_element(By.TAG_NAME, "html")

        self.html.send_keys(Keys.COMMAND, Keys.SUBTRACT)

        # #create action chain object
        # self.action = ActionChains(self.driver)

        # self.action.send_keys(Keys.COMMAND, Keys.SUBTRACT)

        # # perform the operation
        # self.action.perform()

        # if platform == "win32":
        #     pyautogui.hotkey('ctrl', '-') #zoom out to 67%
        #     pyautogui.hotkey('ctrl', '-')
        #     pyautogui.hotkey('ctrl', '-')

        # if platform == "darwin":

        #     pyautogui.hotkey('command', '-') #this actually zoom in ro 120% ?!
        #     pyautogui.hotkey('command', '-')
        #     pyautogui.hotkey('command', '-')

Driver()
</code>```

答:
I finally found a way to zoom out after testing several methods. See below:</p>
```<code>    # 1
    # id_root = self.driver.find_element(By.ID, "root")
    #self.driver.execute_script("$('#root').css('zoom', 5);")

    # 2
    #self.driver.execute_script("document.body.style.MozTransform='scale(0.8)';")

    # 3
    #self.driver.execute_script("document.body.style.zoom='50%';")

    # 4
    #self.html = self.driver.find_element(By.TAG_NAME, "html")
    #self.html.send_keys(Keys.COMMAND, Keys.SUBTRACT)

    # 5
           # if platform == "win32":
    #     pyautogui.hotkey('ctrl', '-') #zoom out 3 times
    #     pyautogui.hotkey('ctrl', '-')
    #     pyautogui.hotkey('ctrl', '-')

    # if platform == "darwin":

    #     pyautogui.hotkey('COMMAND', '-') #zoom out
    #     pyautogui.hotkey('COMMAND', '-')
    #     pyautogui.hotkey('COMMAND', '-')

    #6 - This works!
    self.driver.set_context("chrome")
    win = self.driver.find_element(By.TAG_NAME, "html")
    win.send_keys(Keys.COMMAND + "-" + "-" + "-")
    self.driver.set_context("content")
</code>```

Body:
I try to figure out how to zoom in on Firefox driver using Selenium on a Mac. When I try to use the send_keys() method on the html element, nothing happens (no action). The action method gets no action neither.

When I try to use the pyautogui module instead, the code works on Windows but not on Mac. It actually zooms out to 120% on the Mac?

Which is the best way to solve this?

# IMPORTS
from sys import platform
import os

import pyautogui
pyautogui.FAILSAFE = True

import time

import tkinter as tk

from selenium import webdriver
from selenium.webdriver import Firefox, FirefoxOptions
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
# import Action chains
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import Select
from selenium.webdriver.firefox.service import Service

class Driver():
    def __init__(self):
        ...
        self.driver = Firefox(service=self.service_path, options=self.opts)

        #open url
        self.driver.get("https://google.com/")

        #zoom out
        time.sleep(3)

        self.html = self.driver.find_element(By.TAG_NAME, "html")

        self.html.send_keys(Keys.COMMAND, Keys.SUBTRACT)

        # #create action chain object
        # self.action = ActionChains(self.driver)

        # self.action.send_keys(Keys.COMMAND, Keys.SUBTRACT)

        # # perform the operation
        # self.action.perform()

        # if platform == "win32":
        #     pyautogui.hotkey('ctrl', '-') #zoom out to 67%
        #     pyautogui.hotkey('ctrl', '-')
        #     pyautogui.hotkey('ctrl', '-')

        # if platform == "darwin":

        #     pyautogui.hotkey('command', '-') #this actually zoom in ro 120% ?!
        #     pyautogui.hotkey('command', '-')
        #     pyautogui.hotkey('command', '-')

Driver()

Body:
I finally found a way to zoom out after testing several methods. See below:

    # 1
    # id_root = self.driver.find_element(By.ID, "root")
    #self.driver.execute_script("$('#root').css('zoom', 5);")

    # 2
    #self.driver.execute_script("document.body.style.MozTransform='scale(0.8)';")

    # 3
    #self.driver.execute_script("document.body.style.zoom='50%';")

    # 4
    #self.html = self.driver.find_element(By.TAG_NAME, "html")
    #self.html.send_keys(Keys.COMMAND, Keys.SUBTRACT)

    # 5
           # if platform == "win32":
    #     pyautogui.hotkey('ctrl', '-') #zoom out 3 times
    #     pyautogui.hotkey('ctrl', '-')
    #     pyautogui.hotkey('ctrl', '-')

    # if platform == "darwin":

    #     pyautogui.hotkey('COMMAND', '-') #zoom out
    #     pyautogui.hotkey('COMMAND', '-')
    #     pyautogui.hotkey('COMMAND', '-')

    #6 - This works!
    self.driver.set_context("chrome")
    win = self.driver.find_element(By.TAG_NAME, "html")
    win.send_keys(Keys.COMMAND + "-" + "-" + "-")
    self.driver.set_context("content")


问:
Jetpack Compose: Text remains black when the theme is dark despite using approved solution from analogous question
There is an analogous question to mine already on StackOverflow. It has a comprehensive, accepted answer that I thought would help me in what seems like a trivial problem.

I have a composable consisting of a Text composable. It is called PickerLabel as it is a part of a larger picker component:

@Composable
private fun PickerLabel(
    text: String,
    modifier: Modifier
) {
    Text(
        text = text,
        fontSize = 64.sp,
        modifier = modifier
            .pointerInput(Unit) {
                detectTapGestures { }
            }
    )
}
```
<p>It is used like this (it feels like nothing in its <code>modifier</code> can be impacting the text color):</p>
<pre class="lang-kotlin prettyprint-override"><code>PickerLabel(
    text = \* stringText *\,
    modifier = Modifier
        .align(Alignment.Center)
        .alpha(\* stringText *\)
)
</code>```

One last useful thing to see from my code would be the Theme.kt:

```<code>private val LightColorPalette = lightColors(
    primary = Jacarta,
    primaryVariant = BlueZodiac,
    secondary = ButterflyBush,
    secondaryVariant = Victoria,
    onPrimary = White,
    onSecondary = White,
    onSurface = White
)

private val DarkColorPalette = darkColors(
    primary = Jacarta,
    primaryVariant = BlueZodiac,
    secondary = ButterflyBush,
    secondaryVariant = Victoria,
    onPrimary = White,
    onSecondary = White,
    onSurface = White
)

@Composable
fun AppTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
    CompositionLocalProvider(LocalSpace provides Space()) {
        MaterialTheme(
            colors = if (darkTheme) DarkColorPalette else LightColorPalette,
            typography = Typography,
            shapes = Shapes,
            content = content
        )
    }
}
</code>```

With that setup in dark mode the PickerLabel is composed as such:

while it should look like this (it looks like this only in light mode):

Now, according to the answer to the previously mentioned question, I tried the following:

Adding a Surface as a parent container (the onSurface color was specified as White in Theme.kt):

setContent {
    AppTheme {
        Surface {
            ScreenContent()
        }
    }
}
```
<ol start="2">
<li>Using the <code>color</code> parameter in the <code>Text</code> composable:</li>
</ol>
<pre class="lang-kotlin prettyprint-override"><code>@Composable
private fun PickerLabel(
    text: String,
    modifier: Modifier
) {
    Text(
        text = text,
        color = White,
        fontSize = 64.sp,
        modifier = modifier
            .pointerInput(Unit) {
                detectTapGestures { }
            }
    )
}
</code>```

Using the style parameter in the Text composable:

@Composable
private fun PickerLabel(
    text: String,
    modifier: Modifier
) {
    Text(
        text = text,
        style = LocalTextStyle.current.copy(color = White),
        fontSize = 64.sp,
        modifier = modifier
            .pointerInput(Unit) {
                detectTapGestures { }
            }
    )
}
```
<ol start="4">
<li>Using a custom <code>LocalContentColor</code> to override the default <code>Black</code> color:</li>
</ol>
<pre class="lang-kotlin prettyprint-override"><code>setContent {
    AppTheme {
        CompositionLocalProvider(
            LocalContentColor provides White
        ) {
            ScreenContent()
        }
    }
}
</code>```

NONE of these solutions worked for me - each time I've tried them the Text color remained black no matter what.

Maybe there is a different factor deciding about the Text color that the mentioned answers didn't recognize. Or maybe I've made a mistake that can be spotted here in my code. Either way, if You have the slightest idea about what might be going on, please help.

Edit: changed the Theme.kt to include the check for system theme, to decide which color palette to use.

答:
I've managed to solve the issue. The solution is something I would've never thought would make sense.

No wrapping in Surface nor specifying some color parameters - the solution (at least in my, pretty specific, case) was to:

Unwrap the Text composable from the PickerLabel,

Set the fontSize to 63.8.sp (that's right - 63.9.sp was already too much and made the text black).

With those two (quite surprising and weird) steps the Text is composed in White color. No additional code was changed besides what I've said:

Text(
    text = /* stringText */,
    fontSize = 63.8.sp,
    modifier = modifier
        .align(Alignment.Center)
        .alpha(/* floatAlpha */)
        .pointerInput(Unit) {
            detectTapGestures { }
        }
)
```

Body:
There is an analogous question to mine already on StackOverflow. It has a comprehensive, accepted answer that I thought would help me in what seems like a trivial problem.

I have a composable consisting of a Text composable. It is called PickerLabel as it is a part of a larger picker component:

@Composable
private fun PickerLabel(
    text: String,
    modifier: Modifier
) {
    Text(
        text = text,
        fontSize = 64.sp,
        modifier = modifier
            .pointerInput(Unit) {
                detectTapGestures { }
            }
    )
}

It is used like this (it feels like nothing in its modifier can be impacting the text color):

PickerLabel(
    text = \* stringText *\,
    modifier = Modifier
        .align(Alignment.Center)
        .alpha(\* stringText *\)
)

One last useful thing to see from my code would be the Theme.kt:

private val LightColorPalette = lightColors(
    primary = Jacarta,
    primaryVariant = BlueZodiac,
    secondary = ButterflyBush,
    secondaryVariant = Victoria,
    onPrimary = White,
    onSecondary = White,
    onSurface = White
)

private val DarkColorPalette = darkColors(
    primary = Jacarta,
    primaryVariant = BlueZodiac,
    secondary = ButterflyBush,
    secondaryVariant = Victoria,
    onPrimary = White,
    onSecondary = White,
    onSurface = White
)

@Composable
fun AppTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
    CompositionLocalProvider(LocalSpace provides Space()) {
        MaterialTheme(
            colors = if (darkTheme) DarkColorPalette else LightColorPalette,
            typography = Typography,
            shapes = Shapes,
            content = content
        )
    }
}

With that setup in dark mode the PickerLabel is composed as such:

while it should look like this (it looks like this only in light mode):

Now, according to the answer to the previously mentioned question, I tried the following:

Adding a Surface as a parent container (the onSurface color was specified as White in Theme.kt):

setContent {
    AppTheme {
        Surface {
            ScreenContent()
        }
    }
}

Using the color parameter in the Text composable:

@Composable
private fun PickerLabel(
    text: String,
    modifier: Modifier
) {
    Text(
        text = text,
        color = White,
        fontSize = 64.sp,
        modifier = modifier
            .pointerInput(Unit) {
                detectTapGestures { }
            }
    )
}

Using the style parameter in the Text composable:

@Composable
private fun PickerLabel(
    text: String,
    modifier: Modifier
) {
    Text(
        text = text,
        style = LocalTextStyle.current.copy(color = White),
        fontSize = 64.sp,
        modifier = modifier
            .pointerInput(Unit) {
                detectTapGestures { }
            }
    )
}

Using a custom LocalContentColor to override the default Black color:

setContent {
    AppTheme {
        CompositionLocalProvider(
            LocalContentColor provides White
        ) {
            ScreenContent()
        }
    }
}

NONE of these solutions worked for me - each time I've tried them the Text color remained black no matter what.

Maybe there is a different factor deciding about the Text color that the mentioned answers didn't recognize. Or maybe I've made a mistake that can be spotted here in my code. Either way, if You have the slightest idea about what might be going on, please help.

Edit: changed the Theme.kt to include the check for system theme, to decide which color palette to use.


问:
how can the schema processor modify the instance document?
http://www.w3.org/TR/2004/REC-xmlschema-0-20041028/#Intro:

When an attribute is declared with a default value, the value of the
  attribute is whatever value appears as the attribute's value in an
  instance document; if the attribute does not appear in the instance
  document, the schema processor provides the attribute with a value
  equal to that of the default attribute.

Does anyone know what does it mean for the "schema processor to provide the attribute with a value" ?

isn't the schema just a validating mechanism with no output? if so how can the schema processor modify the instance document?

What does it mean for a schema to set a value when it is just a validating document with no output?

答:
When a schema processor validates a document, it collects information about elements and attributes into a post validation schema infoset (PSVI). The PSVI and the instance document are two different things, but of course closely related. PSVI can be used by applications to provide additional information on the document and its content model. For example, a DOM implementation can use the PSVI to return the default attribute value if one is missing, as well as reporting if that was the case, i.e.</p>

```<code>boolean Attr#getSpecified()
</code>```

Body:
When a schema processor validates a document, it collects information about elements and attributes into a post validation schema infoset (PSVI). The PSVI and the instance document are two different things, but of course closely related. PSVI can be used by applications to provide additional information on the document and its content model. For example, a DOM implementation can use the PSVI to return the default attribute value if one is missing, as well as reporting if that was the case, i.e.

boolean Attr#getSpecified()


问:
Cannot use ant layout slider collapsable with SSR with NextJs
I'm using antd within my NextJs app. I placed a Layout component at the top level of my app.

```<code>/* _app.tsx */
function MyApp({ Component, pageProps }: AppProps) {
  return (
    <Provider store={store}>
      <SideMenuLayout>
        <div>Patate</div>
      </SideMenuLayout>
    </Provider>
  );
}

/* sideMenuLayout.tsx */
const SideMenuLayout = ({ children }: SideMenuLayoutProps) => {
  const [collapsed, setCollapsed] = useState(false);
  const { Sider } = Layout;

  return (
    <Layout style={{ minHeight: "100vh" }}>
      <Sider collapsible collapsed={collapsed} onCollapse={setCollapsed}>
        <div className="logo" />
        <Menu theme="dark" defaultSelectedKeys={["1"]} mode="inline">
          <Menu.Item key="2" icon={<DesktopOutlined />}>
            Play
          </Menu.Item>
        </Menu>
      </Sider>
      <Layout className="site-layout">{children}</Layout>
    </Layout>
  );
};
</code>```

I get the error "Warning: useLayoutEffect does nothing on the server".

I understand <sider collapsible... use this useLayoutEffect. I don't understand why default mode is SSR in my case. I'm not sure how I should proceed if I wanna keep the sider collapsable.

Thanks!

答:
Replace component

Try to wrap antd Slider component with condition check, if it is browser pass antd slider otherwise a mocked one. Ideally, you should match the HTML structure of the Slider component with your fake slider.

import {Sider as AntSlider} = from 'antd'

export const Sider = props => (
  typeof window === `undefined`
    ?

    : <AntSlider {...props}/>
)
```

Body:
I'm using antd within my NextJs app. I placed a Layout component at the top level of my app.

/* _app.tsx */
function MyApp({ Component, pageProps }: AppProps) {
  return (
    <Provider store={store}>
      <SideMenuLayout>

Patate

      </SideMenuLayout>
    </Provider>
  );
}

/* sideMenuLayout.tsx */
const SideMenuLayout = ({ children }: SideMenuLayoutProps) => {
  const [collapsed, setCollapsed] = useState(false);
  const { Sider } = Layout;

  return (
    <Layout style={{ minHeight: "100vh" }}>
      <Sider collapsible collapsed={collapsed} onCollapse={setCollapsed}>

        <Menu theme="dark" defaultSelectedKeys={["1"]} mode="inline">
          <Menu.Item key="2" icon={<DesktopOutlined />}>
            Play
          </Menu.Item>
        </Menu>
      </Sider>
      <Layout className="site-layout">{children}</Layout>
    </Layout>
  );
};

I get the error "Warning: useLayoutEffect does nothing on the server".

I understand <sider collapsible... use this useLayoutEffect. I don't understand why default mode is SSR in my case. I'm not sure how I should proceed if I wanna keep the sider collapsable.

Thanks!

Body:
Replace component

Try to wrap antd Slider component with condition check, if it is browser pass antd slider otherwise a mocked one. Ideally, you should match the HTML structure of the Slider component with your fake slider.

import {Sider as AntSlider} = from 'antd'

export const Sider = props => (
  typeof window === `undefined`
    ? <div {...props}/>
    : <AntSlider {...props}/>
)


问:
json dynamic node parse in C#
I am receiving json with dynamic one node based on sector like "DEL-BOM", "NYC-BOM".
trying to parse but body getting null.
I just add Dictionary and key as node and class as value but still not getting values in DeserializeObject.

```<code>{
    "fareRule": {
        "DEL-BOM": {
            "fr": {
                "NO_SHOW": {
                    "DEFAULT": {
                        "policyInfo": "If Cancelled within 6 hrs of scheduled departure only statutory taxes will be Refunded."
                    }
                },
                "DATECHANGE": {
                    "DEFAULT": {
                        "amount": 3000.00,
                        "additionalFee": 50.00,
                        "policyInfo": "__nls__Changes permitted 06 Hrs before scheduled departure  __nls__ Within 06-96 hrs Rs 3,000 + Fare Difference __nls__ Before 96 hrs Rs 2,500 + Fare Difference",
                        "fcs": {
                            "CRFT": 9.00,
                            "ARF": 3000.00,
                            "ARFT": 150.00,
                            "CRF": 50.00
                        }
                    }
                },
                "CANCELLATION": {
                    "DEFAULT": {
                        "amount": 3500.00,
                        "additionalFee": 50.00,
                        "policyInfo": "__nls__Cancellation permitted 06 Hrs before scheduled departure __nls__ Within 06-96 hrs Rs 3,500 __nls__ Before 96 hrs Rs 3,000",
                        "fcs": {
                            "ACFT": 175.00,
                            "CCFT": 9.00,
                            "ACF": 3500.00,
                            "CCF": 50.00
                        }
                    }
                },
                "SEAT_CHARGEABLE": {
                    "DEFAULT": {
                        "policyInfo": "Paid Seat"
                    }
                }
            }
        }
    },
    "status": {
        "success": true,
        "httpStatus": 200
    }
}
</code>```

this is my class

```<code>public class Response
    {
        public Dictionary<string, Fr> fareRule { get; set; }
        public Status status { get; set; }
    }

    public class DEFAULT
    {
        public string policyInfo { get; set; }
        public double amount { get; set; }
        public double additionalFee { get; set; }
        public Fcs fcs { get; set; }
    }

    public class NOSHOW
    {
        public DEFAULT DEFAULT { get; set; }
    }

    public class Fcs
    {
        public double ARFT { get; set; }
        public double ARF { get; set; }
        public double CRFT { get; set; }
        public double CRF { get; set; }
        public double CCF { get; set; }
        public double ACF { get; set; }
        public double CCFT { get; set; }
        public double ACFT { get; set; }
    }

    public class DATECHANGE
    {
        public DEFAULT DEFAULT { get; set; }
    }

    public class CANCELLATION
    {
        public DEFAULT DEFAULT { get; set; }
    }

    public class SEATCHARGEABLE
    {
        public DEFAULT DEFAULT { get; set; }
    }

    public class Fr
    {
        public NOSHOW NO_SHOW { get; set; }
        public DATECHANGE DATECHANGE { get; set; }
        public CANCELLATION CANCELLATION { get; set; }
        public SEATCHARGEABLE SEAT_CHARGEABLE { get; set; }
    }

    public class Sector
    {
        public Fr fr { get; set; }
    }

    public class FareRule
    {

        public Sector sector { get; set; }
    }

    public class Status
    {
        public bool success { get; set; }
        public int httpStatus { get; set; }
    }
</code>```

I have tried based on Parse dynamic JSON

Key is converting but body or value is null.

答:
Use Newtonsoft.Json for deserialization
Your Correct Model is.

```<code>public class DATECHANGE
{
    public DEFAULT DEFAULT { get; set; }
}

public class CANCELLATION
{
    public DEFAULT DEFAULT { get; set; }
}

public class SEATCHARGEABLE
{
    public DEFAULT DEFAULT { get; set; }
}

public class Fr
{
    public NOSHOW NO_SHOW { get; set; }

    public DATECHANGE DATECHANGE { get; set; }

    public CANCELLATION CANCELLATION { get; set; }

    public SEATCHARGEABLE SEAT_CHARGEABLE { get; set; }
}

public class FareRule
{
    [JsonProperty(PropertyName = "DEL-BOM")]
    public DynamicBody DELBOM { get; set; }

    [JsonProperty(PropertyName = "NYC-BOM")]
    public DynamicBody NYCBOM { get; set; }
}

public class Status
{
    public bool Success { get; set; }

    public int HttpStatus { get; set; }
}

public class BaseResponseModel
{
    public FareRule FareRule { get; set; }

    public Status Status { get; set; }
}

public class DynamicBody
{
    public Fr Fr { get; set; }
}
</code>```

Then Deserialize like this code

```<code>var responseModel = JsonConvert.DeserializeObject<BaseResponseModel>(jsonStr);
</code>```

Title: json dynamic node parse in C#

Body:
I am receiving json with dynamic one node based on sector like "DEL-BOM", "NYC-BOM".
trying to parse but body getting null.
I just add Dictionary and key as node and class as value but still not getting values in DeserializeObject.

{
    "fareRule": {
        "DEL-BOM": {
            "fr": {
                "NO_SHOW": {
                    "DEFAULT": {
                        "policyInfo": "If Cancelled within 6 hrs of scheduled departure only statutory taxes will be Refunded."
                    }
                },
                "DATECHANGE": {
                    "DEFAULT": {
                        "amount": 3000.00,
                        "additionalFee": 50.00,
                        "policyInfo": "__nls__Changes permitted 06 Hrs before scheduled departure  __nls__ Within 06-96 hrs Rs 3,000 + Fare Difference __nls__ Before 96 hrs Rs 2,500 + Fare Difference",
                        "fcs": {
                            "CRFT": 9.00,
                            "ARF": 3000.00,
                            "ARFT": 150.00,
                            "CRF": 50.00
                        }
                    }
                },
                "CANCELLATION": {
                    "DEFAULT": {
                        "amount": 3500.00,
                        "additionalFee": 50.00,
                        "policyInfo": "__nls__Cancellation permitted 06 Hrs before scheduled departure __nls__ Within 06-96 hrs Rs 3,500 __nls__ Before 96 hrs Rs 3,000",
                        "fcs": {
                            "ACFT": 175.00,
                            "CCFT": 9.00,
                            "ACF": 3500.00,
                            "CCF": 50.00
                        }
                    }
                },
                "SEAT_CHARGEABLE": {
                    "DEFAULT": {
                        "policyInfo": "Paid Seat"
                    }
                }
            }
        }
    },
    "status": {
        "success": true,
        "httpStatus": 200
    }
}

this is my class

public class Response
    {
        public Dictionary<string, Fr> fareRule { get; set; }
        public Status status { get; set; }
    }

    public class DEFAULT
    {
        public string policyInfo { get; set; }
        public double amount { get; set; }
        public double additionalFee { get; set; }
        public Fcs fcs { get; set; }
    }

    public class NOSHOW
    {
        public DEFAULT DEFAULT { get; set; }
    }

    public class Fcs
    {
        public double ARFT { get; set; }
        public double ARF { get; set; }
        public double CRFT { get; set; }
        public double CRF { get; set; }
        public double CCF { get; set; }
        public double ACF { get; set; }
        public double CCFT { get; set; }
        public double ACFT { get; set; }
    }

    public class DATECHANGE
    {
        public DEFAULT DEFAULT { get; set; }
    }

    public class CANCELLATION
    {
        public DEFAULT DEFAULT { get; set; }
    }

    public class SEATCHARGEABLE
    {
        public DEFAULT DEFAULT { get; set; }
    }

    public class Fr
    {
        public NOSHOW NO_SHOW { get; set; }
        public DATECHANGE DATECHANGE { get; set; }
        public CANCELLATION CANCELLATION { get; set; }
        public SEATCHARGEABLE SEAT_CHARGEABLE { get; set; }
    }

    public class Sector
    {
        public Fr fr { get; set; }
    }

    public class FareRule
    {

        public Sector sector { get; set; }
    }

    public class Status
    {
        public bool success { get; set; }
        public int httpStatus { get; set; }
    }

I have tried based on Parse dynamic JSON

Key is converting but body or value is null.

Body:
Use Newtonsoft.Json for deserialization
Your Correct Model is.

public class DATECHANGE
{
    public DEFAULT DEFAULT { get; set; }
}

public class CANCELLATION
{
    public DEFAULT DEFAULT { get; set; }
}

public class SEATCHARGEABLE
{
    public DEFAULT DEFAULT { get; set; }
}

public class Fr
{
    public NOSHOW NO_SHOW { get; set; }

    public DATECHANGE DATECHANGE { get; set; }

    public CANCELLATION CANCELLATION { get; set; }

    public SEATCHARGEABLE SEAT_CHARGEABLE { get; set; }
}

public class FareRule
{
    [JsonProperty(PropertyName = "DEL-BOM")]
    public DynamicBody DELBOM { get; set; }

    [JsonProperty(PropertyName = "NYC-BOM")]
    public DynamicBody NYCBOM { get; set; }
}

public class Status
{
    public bool Success { get; set; }

    public int HttpStatus { get; set; }
}

public class BaseResponseModel
{
    public FareRule FareRule { get; set; }

    public Status Status { get; set; }
}

public class DynamicBody
{
    public Fr Fr { get; set; }
}

Then Deserialize like this code

var responseModel = JsonConvert.DeserializeObject<BaseResponseModel>(jsonStr);


问:
How to populate a list with text from website
I'm using this to populate a list(wordlist) from Amazon website product page hoping to get this text "Haz clic para obtener una vista ampliada" :

```<code>wordlist.append(WebDriverWait(robotel, 30).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span#canvasCaption"))).text)

</code>```

Problem is that when I do it in a loop, for multiple product pages sometimes for some products wordlist is empty, but then if I test again for the same product page wordlist gets populated.

I can't fiind the reason for this, so please help.

答:
Your line of code seems just perfect.

However, to avoid the empty wordlist you can additionally implement either/all of the following approaches:

As you are iterating through a loop some product pages and some products may take longer time to render, so you may need to increase the waiting time for 30 secs to 45 secs,

Beside considering the id attribute you can append some other attributes as well, e.g. class, aria-label, href, data-a-hires, alt, etc

Body:
I'm using this to populate a list(wordlist) from Amazon website product page hoping to get this text "Haz clic para obtener una vista ampliada" :

wordlist.append(WebDriverWait(robotel, 30).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span#canvasCaption"))).text)

Problem is that when I do it in a loop, for multiple product pages sometimes for some products wordlist is empty, but then if I test again for the same product page wordlist gets populated.

I can't fiind the reason for this, so please help.


问:
Symfony Doctrine query error
I have the following code:

```<code>$getmoney = Doctrine::getTable('Countries')->find(1);

$insertmoney = new Accounts();
$insertmoney->userid = $userid;
$insertmoney[$getmoney->getCurrency()] = $getmoney->getBaby();
$insertmoney->save();
</code>```

And the query generated by Doctrine is:

```<code>INSERT INTO accounts (1, userid, 2) VALUES ('0', '31', '15')
</code>```

But it seems to have a SQL error: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1, userid, 2) VALUES ('0', '31', '15')' at line 1

The correcy query would be:

```<code>INSERT INTO accounts (`1`, `userid`, `2`) VALUES ('0', '31', '15')
</code>```

Probably the wrong thing in this is the unfortunate names of the columns, numbers. I had to use numbers only because it make thing a lot easier.

What can I do to generate a query that has the columns' names between  " ` " ?

答:
Wow... that's quite unfortunate, indeed!
Anyway... you may configure identifier quoting so that you always use backticks.</p>

Title: Symfony Doctrine query error

Body:
I have the following code:

$getmoney = Doctrine::getTable('Countries')->find(1);

$insertmoney = new Accounts();
$insertmoney->userid = $userid;
$insertmoney[$getmoney->getCurrency()] = $getmoney->getBaby();
$insertmoney->save();

And the query generated by Doctrine is:

INSERT INTO accounts (1, userid, 2) VALUES ('0', '31', '15')

But it seems to have a SQL error: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1, userid, 2) VALUES ('0', '31', '15')' at line 1

The correcy query would be:

INSERT INTO accounts (`1`, `userid`, `2`) VALUES ('0', '31', '15')

Probably the wrong thing in this is the unfortunate names of the columns, numbers. I had to use numbers only because it make thing a lot easier.

What can I do to generate a query that has the columns' names between  " ` " ?


问:
Weighted empirical distribution function (ECDF) in python
I am trying to generate weighted empirical CDF in python. I know statsmodel.distributions.empirical_distribution provides an ECDF function, but it is unweighted. Is there a library that I can use or how can I go about extending this to write a function which calculates the weighted ECDF (EWCDF) like ewcdf {spatstat} in R.

答:
Seaborn library has ecdfplot function which implements a weighted version of ECDF. I looked into the code of how seaborn calculates it.

import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

sample = np.arange(100)
weights = np.random.randint(10, size=100)

estimator = sns.distributions.ECDF('proportion', complementary=True)
stat, vals = estimator(sample, weights=weights)
plt.plot(vals, stat)
```


问:
Is there any way to call base python function in r using reticulate?
I got a "generator object" from a python function. However, I tried many ways but failed to read the "generator object" in r using reticulate.  I know python base function list() can convert "generator object" to "json", which I can then read in r. I wonder how to use base python function in r? (I would not prefer to use py_run_file)

For example:

```<code>>library(reticulate)
>foo <- import("foo")
>res <- foo.func()
<generator object at 0x7fd4fe98ee40>
</code>```

答:
You could use iterate or iter_next.

As an example, consider a python generator firstn.py:

```<code>def firstn(n):
  num = 0
  while num < n:
    yield num
    num += 1
</code>```

You can traverse the generator either with iterate :

```<code>library(reticulate)
source_python('firstn.py')
gen <- firstn(10)
gen
#<generator object firstn at 0x0000020CE536AF10>

result <- iterate(gen)
result
# [1] 0 1 2 3 4 5 6 7 8 9
</code>```

or with iter_next:

```<code>iter_next(gen)
[1] 0
iter_next(gen)
[1] 1
iter_next(gen)
[1] 2
</code>```

Body:
I got a "generator object" from a python function. However, I tried many ways but failed to read the "generator object" in r using reticulate.  I know python base function list() can convert "generator object" to "json", which I can then read in r. I wonder how to use base python function in r? (I would not prefer to use py_run_file)

For example:

>library(reticulate)
>foo <- import("foo")
>res <- foo.func()
<generator object at 0x7fd4fe98ee40>

Body:
You could use iterate or iter_next.

As an example, consider a python generator firstn.py:

def firstn(n):
  num = 0
  while num < n:
    yield num
    num += 1

You can traverse the generator either with iterate :

library(reticulate)
source_python('firstn.py')
gen <- firstn(10)
gen
#<generator object firstn at 0x0000020CE536AF10>

result <- iterate(gen)
result
# [1] 0 1 2 3 4 5 6 7 8 9

or with iter_next:

iter_next(gen)
[1] 0
iter_next(gen)
[1] 1
iter_next(gen)
[1] 2


问:
How to return text with line break with Grape API?
I am trying to create an endpoint where the response body is just a string with line breaks, but the response keeps showing the \n character.

My endpoint code:

```<code>get '' do
  header('Content-Type', 'text/plain')
  body("Hello\nWorld")
end
</code>```

And this is the response I see in Postman:

What am I missing here?

Thank you

答:
I was able to make it work like I wanted with the following code:

```<code>get '' do
  env['api.format'] = :binary
  header('Content-Type', 'text/plain')
  body("Hello\nWorld")
end
</code>```

Body:
I am trying to create an endpoint where the response body is just a string with line breaks, but the response keeps showing the \n character.

My endpoint code:

get '' do
  header('Content-Type', 'text/plain')
  body("Hello\nWorld")
end

And this is the response I see in Postman:

What am I missing here?

Thank you

Body:
I was able to make it work like I wanted with the following code:

get '' do
  env['api.format'] = :binary
  header('Content-Type', 'text/plain')
  body("Hello\nWorld")
end


问:
how to do a subquery or filter in a condition met by a previous query correctly
Im using python, flask and sqlalchemy have the query below:

```<code>query = db.session.query(model.Foo1, model.Foo2).join(model.Foo1, model.Foo1.id == model.Foo2.name_id).first()
</code>```

Now let's assume that i want to search for the condition Foo1.id != 2 but still make sure that i meet the condition of the query above, what would be the best way to achieve that (i am trying to learn how to do subquery or filter in another query properly)

Thank for the help

答:
For Foo1.id != 2 You don't need a subquery. Filter is enough.

result = db.session.query(model.Foo1, model.Foo2)\
         .join(model.Foo1, model.Foo1.id == model.Foo2.name_id)\
         .filter(model.Foo1.id != 2).all()
```

This will return a list of all rows that have ids not equal to 2

Body:
Im using python, flask and sqlalchemy have the query below:

query = db.session.query(model.Foo1, model.Foo2).join(model.Foo1, model.Foo1.id == model.Foo2.name_id).first()

Now let's assume that i want to search for the condition Foo1.id != 2 but still make sure that i meet the condition of the query above, what would be the best way to achieve that (i am trying to learn how to do subquery or filter in another query properly)

Thank for the help

Body:
For Foo1.id != 2 You don't need a subquery. Filter is enough.

result = db.session.query(model.Foo1, model.Foo2)\
         .join(model.Foo1, model.Foo1.id == model.Foo2.name_id)\
         .filter(model.Foo1.id != 2).all()

This will return a list of all rows that have ids not equal to 2


问:
Optimizing/Reducing For-loops
I am learning C and I want to have an idea on how can I reduce the for-loops, to make it more presentable.

```<code>#include<stdio.h>

int main() {

char input[81];
int i;
char input2[9][9];
int col,row;
printf("Enter sudoku board:");
scanf("%s",&input);

for (i=0;i<9;i++) {
    for (col=0;col<9;col++)
        input2[0][col]=input[i];
    for (col=0;col<9;col++)
        input2[1][col]=input[i];
    for (col=0;col<9;col++)
        input2[2][col]=input[i];
    for (col=0;col<9;col++)
        input2[3][col]=input[i];
    for (col=0;col<9;col++)
        input2[4][col]=input[i];
    for (col=0;col<9;col++)
        input2[5][col]=input[i];
    for (col=0;col<9;col++)
        input2[6][col]=input[i];
    for (col=0;col<9;col++)
        input2[7][col]=input[i];
    for (col=0;col<9;col++)
        input2[8][col]=input[i];
}
</code>```

this shows that the user would enter 81 numbers in an array then the numbers entered will be transferred to a 9x9 array. thanks in advance!:)

答:
Your code is not doing what you expect it to do.

It sounds like you wanted something like :

```<code>for (row = 0; row < 9; ++row) {
    for (col = 0; col < 9; ++col) {
        input2[row][col] = input[(row * 9) + col];
    }
}
</code>```

EDIT : Btw, when letting the user enter a string, make sure that there is enough room in the buffer to hold the entire string, plus the terminating '\0' character ! Your input buffer needs to have room for at least 82 char's.

Title: Optimizing/Reducing For-loops

Body:
I am learning C and I want to have an idea on how can I reduce the for-loops, to make it more presentable.

#include<stdio.h>

int main() {

char input[81];
int i;
char input2[9][9];
int col,row;
printf("Enter sudoku board:");
scanf("%s",&input);

for (i=0;i<9;i++) {
    for (col=0;col<9;col++)
        input2[0][col]=input[i];
    for (col=0;col<9;col++)
        input2[1][col]=input[i];
    for (col=0;col<9;col++)
        input2[2][col]=input[i];
    for (col=0;col<9;col++)
        input2[3][col]=input[i];
    for (col=0;col<9;col++)
        input2[4][col]=input[i];
    for (col=0;col<9;col++)
        input2[5][col]=input[i];
    for (col=0;col<9;col++)
        input2[6][col]=input[i];
    for (col=0;col<9;col++)
        input2[7][col]=input[i];
    for (col=0;col<9;col++)
        input2[8][col]=input[i];
}

this shows that the user would enter 81 numbers in an array then the numbers entered will be transferred to a 9x9 array. thanks in advance!:)

Body:
Your code is not doing what you expect it to do.

It sounds like you wanted something like :

for (row = 0; row < 9; ++row) {
    for (col = 0; col < 9; ++col) {
        input2[row][col] = input[(row * 9) + col];
    }
}

EDIT : Btw, when letting the user enter a string, make sure that there is enough room in the buffer to hold the entire string, plus the terminating '\0' character ! Your input buffer needs to have room for at least 82 char's.


问:
Secure login with Jwt or oAuth?
I have a e eCommerce App and want to use a login/token that is Full secure. Is Jwt enough for 10k User or should I Use oAuth? Oauth ja expensive 1.5k dollar for 10k monthly active users</p>

答:
Yes Json web token(jwt) is enough! But be mindful of which data  you send through the token because it can be decoded.

The only thing that make jwt secure is the signature.

Also never expose your Secret key in your source code always use environment variable while in development

Title: Secure login with Jwt or oAuth?


问:
Merge rows which has same pattern
I have to combine rows into 1 which has same pattern. I am not sure how to acheive it.

I tried to merge with MAX but since its a string, not sure if there is way to combine.

```<code>SELECT ID,MAX(GRP1),MAX(GRP2),MAX(GRP3),MAX(GRP)
FROM GROUP_MAPPING
GROUP BY ID
</code>```

From table:

To Table

答:
Using the same principle as this answer:

SELECT DISTINCT
       id,
       grp1,
       grp2,
       grp3,
       grp
FROM   table_name
WHERE  CONNECT_BY_ISLEAF = 1
CONNECT BY NOCYCLE
       PRIOR id = id
AND    grp LIKE '%' || PRIOR grp1 || '%' || PRIOR grp2 || '%' || PRIOR grp3 || '%';
```
<p>or</p>
<pre class="lang-sql prettyprint-override"><code>SELECT DISTINCT
       id,
       grp1,
       grp2,
       grp3,
       grp
FROM   table_name
WHERE  CONNECT_BY_ISLEAF = 1
CONNECT BY NOCYCLE
       PRIOR id = id
AND    (PRIOR grp1 = grp1 OR PRIOR grp1 IS NULL)
AND    (PRIOR grp2 = grp2 OR PRIOR grp2 IS NULL)
AND    (PRIOR grp3 = grp3 OR PRIOR grp3 IS NULL)
</code>```

Which, for the sample data:

CREATE TABLE table_name (id, grp1, grp2, grp3, grp) AS
SELECT 'DEPT1', 10,   'AA', 'S1', '10AAAS1' FROM DUAL UNION ALL
SELECT 'DEPT1', NULL, 'AA', 'S1', 'AAS1'    FROM DUAL UNION ALL
SELECT 'DEPT1', 10,   NULL, NULL, '10'      FROM DUAL UNION ALL
SELECT 'DEPT1', 10,   'BB', NULL, '10BB'    FROM DUAL UNION ALL
SELECT 'DEPT1', NULL, 'BB', NULL, 'BB'      FROM DUAL;
```

Both output:

ID
GRP1
GRP2
GRP3
GRP

DEPT1
10
AA
S1
10AAAS1

DEPT1
10
BB
null
10BB

db<>fiddle here

Title: Merge rows which has same pattern

Body:
I have to combine rows into 1 which has same pattern. I am not sure how to acheive it.

I tried to merge with MAX but since its a string, not sure if there is way to combine.

SELECT ID,MAX(GRP1),MAX(GRP2),MAX(GRP3),MAX(GRP)
FROM GROUP_MAPPING
GROUP BY ID

From table:

To Table

Body:
Using the same principle as this answer:

SELECT DISTINCT
       id,
       grp1,
       grp2,
       grp3,
       grp
FROM   table_name
WHERE  CONNECT_BY_ISLEAF = 1
CONNECT BY NOCYCLE
       PRIOR id = id
AND    grp LIKE '%' || PRIOR grp1 || '%' || PRIOR grp2 || '%' || PRIOR grp3 || '%';

or

SELECT DISTINCT
       id,
       grp1,
       grp2,
       grp3,
       grp
FROM   table_name
WHERE  CONNECT_BY_ISLEAF = 1
CONNECT BY NOCYCLE
       PRIOR id = id
AND    (PRIOR grp1 = grp1 OR PRIOR grp1 IS NULL)
AND    (PRIOR grp2 = grp2 OR PRIOR grp2 IS NULL)
AND    (PRIOR grp3 = grp3 OR PRIOR grp3 IS NULL)

Which, for the sample data:

CREATE TABLE table_name (id, grp1, grp2, grp3, grp) AS
SELECT 'DEPT1', 10,   'AA', 'S1', '10AAAS1' FROM DUAL UNION ALL
SELECT 'DEPT1', NULL, 'AA', 'S1', 'AAS1'    FROM DUAL UNION ALL
SELECT 'DEPT1', 10,   NULL, NULL, '10'      FROM DUAL UNION ALL
SELECT 'DEPT1', 10,   'BB', NULL, '10BB'    FROM DUAL UNION ALL
SELECT 'DEPT1', NULL, 'BB', NULL, 'BB'      FROM DUAL;

Both output:

ID
GRP1
GRP2
GRP3
GRP

DEPT1
10
AA
S1
10AAAS1

DEPT1
10
BB
null
10BB

db<>fiddle here


答:
Since you want to allow the user to enter 81 digits ( as characters), the size of the char array to hold them must be 82 or more.

```<code>char input[82];
</code>```

Also your scanf should not have the &:

```<code>scanf("%s",input);
</code>```

Since you want to transform the 1D array entered by user to a 2D array you can do:

```<code>for (row=0;row<9;row++) {
   for (col=0;col<9;col++)
      input2[row][col] = input[row*9+col];
</code>```

Title: Optimizing/Reducing For-loops

Body:
Since you want to allow the user to enter 81 digits ( as characters), the size of the char array to hold them must be 82 or more.

char input[82];

Also your scanf should not have the &:

scanf("%s",input);

Since you want to transform the 1D array entered by user to a 2D array you can do:

for (row=0;row<9;row++) {
   for (col=0;col<9;col++)
      input2[row][col] = input[row*9+col];


问:
Insert XML with Namespace into source xml with using XSLT
I have scenario where I want to insert or append (insert.xml) into main xml (source.xml) using xslt.
Namespace is one of the key constrain here the source.xml contain all the namespace that insert.xml has.

My source file look like this (see below)

source.xml :

```<code><?xml version="1.0" encoding="UTF-8"?>
<tns:Requests xmlns:tns="http://mynamespace.com/request/wrapper/2022"
             xmlns:tns1="http://mynamespace.com/request/2022"
             xmlns:tns2="http://mynamespace.com/clientresponse/2022"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <tns:Request>
        <tns:Data>
            <tns:row1>Data1</tns:row1>
            <tns:row2>Data2</tns:row2>
        </tns:Data>
    </tns:Request>
</tns:Requests> ```
```
</blockquote>
<hr />
<p>my insert file looks like this (see below)</p>
<p><strong>Insert.xml</strong></p>
<blockquote>
```<?xml version="1.0" encoding="UTF-8"?>
<tns:ServiceResponse xmlns:tns="http://mynamespace.com/request/2022"
                    xmlns:tns1="http://mynamespace.com/clientresponse/2022"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <tns:ClientList>
       <tns1:Client>
           <tns1:name>John</tns1:name>
           <tns1:address>11 Wall street </tns1:address>
           <tns1:pin>7895</tns1:pin>
           <tns1:contact>78945615</tns1:contact>
       </tns1:Client>
   </tns:ClientList>
</tns:ServiceResponse>
```
</blockquote>
<p>I want the output like this (see below)</p>
<p><strong>Expected output:</strong></p>
<blockquote>
```
<?xml version="1.0" encoding="UTF-8"?>
<tns:Requests xmlns:tns="http://mynamespace.com/request/wrapper/2022"
             xmlns:tns1="http://mynamespace.com/request/2022"
             xmlns:tns2="http://mynamespace.com/clientresponse/2022"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <tns:Request>
        <tns:data>
            <tns:row1>Data1</tns:row1>
            <tns:row2>Data2</tns:row2>
        </tns:data>
        <tns1:ClientList>
            <tns2:Client>
                <tns2:name>John</tns2:name>
                <tns2:address>11 Wall street </tns2:address>
                <tns2:pin>7895</tns2:pin>
                <tns2:contact>78945615</tns2:contact>
            </tns2:Client>
        </tns1:ClientList>
    </tns:Request>
</tns:Requests>
```
</blockquote>
<p>my xsl file looks like this (see below)</p>
<p><strong>Xsl file:</strong></p>
<blockquote>
```<?xml version="1.0" encoding="UTF-8"?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
               xmlns:tns1="http://mynamespace.com/request/wrapper/2022"
               xmlns:tns="http://mynamespace.com/request/2022"
               version="2.0">

    <xsl:output method="xml" version="1.0" indent="yes"/>

    <xsl:template match="*">
        <xsl:element name="{local-name()}" namespace="{namespace-uri()}">
            <xsl:apply-templates select="@* | node()"/>
        </xsl:element>
    </xsl:template>
    <xsl:template match="tns1:Requests/tns1:Request/tns1:Data">
        <xsl:element name="{local-name()}" namespace="{namespace-uri()}">
            <xsl:apply-templates select="@* | node()"/>
        </xsl:element>
        <xsl:copy-of select="document('insert.xml')/tns:ServiceResponse/tns:ClientList"/>

    </xsl:template>
</xsl:transform>
```
</blockquote>
<p>i am getting the output as below
<strong>xslt output:</strong></p>
<blockquote>
```<?xml version="1.0" encoding="UTF-8"?>
<Requests xmlns="http://mynamespace.com/request/wrapper/2022">
    <Request>
        <Data xmlns="">
            <row1 xmlns="http://mynamespace.com/request/wrapper/2022">Data1</row1>
            <row2 xmlns="http://mynamespace.com/request/wrapper/2022">Data2</row2>
        </Data>
        <tns:ClientList xmlns:tns="http://mynamespace.com/request/2022"
                        xmlns:tns1="http://mynamespace.com/clientresponse/2022"
                        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <tns1:Client>
                <tns1:name>John</tns1:name>
                <tns1:address>11 Wall street </tns1:address>
                <tns1:pin>7895</tns1:pin>
                <tns1:contact>78945615</tns1:contact>
            </tns1:Client>
        </tns:ClientList>
    </Request>
</Requests>
```

答:
I think you want</p>
```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="2.0"
  xpath-default-namespace="http://mynamespace.com/request/wrapper/2022"
  xmlns:tns1="http://mynamespace.com/request/2022"
  xmlns:tns2="http://mynamespace.com/clientresponse/2022"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="xs">

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="Requests/Request/Data">
      <xsl:next-match/>
      <xsl:apply-templates select="document('insert.xml')/tns1:ServiceResponse/tns1:ClientList"/>
  </xsl:template>

  <xsl:template match="tns1:*">
    <xsl:element name="tns1:{local-name()}" namespace="{namespace-uri()}">
      <xsl:apply-templates/>
    </xsl:element>
  </xsl:template>

  <xsl:template match="tns2:*">
    <xsl:element name="tns2:{local-name()}" namespace="{namespace-uri()}">
      <xsl:apply-templates/>
    </xsl:element>
  </xsl:template>
</code>```

Body:
I have scenario where I want to insert or append (insert.xml) into main xml (source.xml) using xslt.
Namespace is one of the key constrain here the source.xml contain all the namespace that insert.xml has.

My source file look like this (see below)

source.xml :

<?xml version="1.0" encoding="UTF-8"?>
<tns:Requests xmlns:tns="http://mynamespace.com/request/wrapper/2022"
             xmlns:tns1="http://mynamespace.com/request/2022"
             xmlns:tns2="http://mynamespace.com/clientresponse/2022"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <tns:Request>
        <tns:Data>
            <tns:row1>Data1</tns:row1>
            <tns:row2>Data2</tns:row2>
        </tns:Data>
    </tns:Request>
</tns:Requests> ```

my insert file looks like this (see below)

Insert.xml

<?xml version="1.0" encoding="UTF-8"?>
<tns:ServiceResponse xmlns:tns="http://mynamespace.com/request/2022"
                    xmlns:tns1="http://mynamespace.com/clientresponse/2022"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <tns:ClientList>
       <tns1:Client>
           <tns1:name>John</tns1:name>
           <tns1:address>11 Wall street </tns1:address>
           <tns1:pin>7895</tns1:pin>
           <tns1:contact>78945615</tns1:contact>
       </tns1:Client>
   </tns:ClientList>
</tns:ServiceResponse>

I want the output like this (see below)

Expected output:

<?xml version="1.0" encoding="UTF-8"?>
<tns:Requests xmlns:tns="http://mynamespace.com/request/wrapper/2022"
             xmlns:tns1="http://mynamespace.com/request/2022"
             xmlns:tns2="http://mynamespace.com/clientresponse/2022"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <tns:Request>
        <tns:data>
            <tns:row1>Data1</tns:row1>
            <tns:row2>Data2</tns:row2>
        </tns:data>
        <tns1:ClientList>
            <tns2:Client>
                <tns2:name>John</tns2:name>
                <tns2:address>11 Wall street </tns2:address>
                <tns2:pin>7895</tns2:pin>
                <tns2:contact>78945615</tns2:contact>
            </tns2:Client>
        </tns1:ClientList>
    </tns:Request>
</tns:Requests>

my xsl file looks like this (see below)

Xsl file:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
               xmlns:tns1="http://mynamespace.com/request/wrapper/2022"
               xmlns:tns="http://mynamespace.com/request/2022"
               version="2.0">

    <xsl:output method="xml" version="1.0" indent="yes"/>

    <xsl:template match="*">
        <xsl:element name="{local-name()}" namespace="{namespace-uri()}">
            <xsl:apply-templates select="@* | node()"/>
        </xsl:element>
    </xsl:template>
    <xsl:template match="tns1:Requests/tns1:Request/tns1:Data">
        <xsl:element name="{local-name()}" namespace="{namespace-uri()}">
            <xsl:apply-templates select="@* | node()"/>
        </xsl:element>
        <xsl:copy-of select="document('insert.xml')/tns:ServiceResponse/tns:ClientList"/>

    </xsl:template>
</xsl:transform>

i am getting the output as below
xslt output:

<?xml version="1.0" encoding="UTF-8"?>
<Requests xmlns="http://mynamespace.com/request/wrapper/2022">
    <Request>
        <Data xmlns="">
            <row1 xmlns="http://mynamespace.com/request/wrapper/2022">Data1</row1>
            <row2 xmlns="http://mynamespace.com/request/wrapper/2022">Data2</row2>
        </Data>
        <tns:ClientList xmlns:tns="http://mynamespace.com/request/2022"
                        xmlns:tns1="http://mynamespace.com/clientresponse/2022"
                        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <tns1:Client>
                <tns1:name>John</tns1:name>
                <tns1:address>11 Wall street </tns1:address>
                <tns1:pin>7895</tns1:pin>
                <tns1:contact>78945615</tns1:contact>
            </tns1:Client>
        </tns:ClientList>
    </Request>
</Requests>

Body:
I think you want

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="2.0"
  xpath-default-namespace="http://mynamespace.com/request/wrapper/2022"
  xmlns:tns1="http://mynamespace.com/request/2022"
  xmlns:tns2="http://mynamespace.com/clientresponse/2022"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="xs">

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="Requests/Request/Data">
      <xsl:next-match/>
      <xsl:apply-templates select="document('insert.xml')/tns1:ServiceResponse/tns1:ClientList"/>
  </xsl:template>

  <xsl:template match="tns1:*">
    <xsl:element name="tns1:{local-name()}" namespace="{namespace-uri()}">
      <xsl:apply-templates/>
    </xsl:element>
  </xsl:template>

  <xsl:template match="tns2:*">
    <xsl:element name="tns2:{local-name()}" namespace="{namespace-uri()}">
      <xsl:apply-templates/>
    </xsl:element>
  </xsl:template>