问:
Numba bytecode generation for generic x64 processors? Rather than 1st run compiling a SLOW @njit(cache=True) argument
I have a pretty large project converted to Numba, and after run #1 with @nb.njit(cache=True, parallel=True, nogil=True), well, it's slow on run #1 (like 15 seconds vs. 0.2-1 seconds after compiling).  I realize it's compiling byte code optimized for the specific PC I'm running it on, but since the code is distributed to a large audience, I don't want it to take forever compiling the first run after we deploy our model.  What is not covered in the documentation is a "generic x64" cache=True method.  I don't care if the code is a little slower on a PC that doesn't have my specific processor, I only care that the initial and subsequent runtimes are quick, and prefer that they don't differ by a huge margin if I distribute a cache file for the @njit functions at deployment.

Does anyone know if such a "generic" x64 implementation is possible using Numba?  Or are we stuck with a slow run #1 and fast ones thereafter?

Please comment if you want more details; basically it's around a 50 lines of code function that gets JIT compiled via Numba and afterwards runs quite fast in parallel with no GIL.  But I'm willing to give up some extreme optimization if the code can work in a generic form across multiple processors.  As where I work, the PCs can vary quite a bit in terms of how advanced they are.

I looked briefly at the AOT (ahead of time) compilation of Numba functions, but these functions, in this case, have so many variables being altered I think it would take me weeks to decorate properly the functions to be compiled without a Numba dependency.  I really don't have the time to do AOT, it would make more sense to just rewrite in Cython the whole algorithm, and that's more like C/C++ and more time consuming that I want to devote to this project.  Unfortunately there is not (to my knowledge) a Numba -> Cython compiler project out there already.  Maybe there will be in the future (which would be outstanding), but I don't know of such a project out there currently.

答:
Unfortunately, you mainly listed all the current available options. Numba functions can be cached and the signature can be specified so to perform an eager compilation (compilation at the time of the function definition) instead of a lazy one (compilation during the first execution). Note that the cache=True flag is only meant to skip the compilation when it as already been done on the same platform before and not to share the code between multiple machine. AFAIK, the internal JIT used by Numba (LLVM-Lite) does not support that. In fact, it is exactly the purpose of the AOT compilation to do that. That being said, the AOT compilation requires the signatures to be provided (this is mandatory whatever the approach/tool used as long as the function is compiled) and it has quite strong limitations (eg. currently there is no support for parallel codes and fastmath). Keep in mind that Numba’s main use case is Just-in-Time compilation and not the ahead-of-time compilation.

Regarding your use-case, using Cython appears to make much more sense: the functions are pre-compiled once for some generic platforms and the compiled binaries can directly be provided to users without the need for recompilation on the target machine.

I don't care if the code is a little slower on a PC that doesn't have my specific processor.

Well, regarding your code, using a "generic" x86-64 code can be much slower. The main reasons lie in the use of SIMD instructions. Indeed, x86-64 processors all supports the SSE2 instruction set which provide basic 128-bit SIMD registers working on integers and floating-point numbers. Since about a decade, x86-processors supports the 256-bit AVX instruction set which significantly speed up floating-point computations. Since at least 7 years, almost all mainstream x86-64 processors supports the AVX-2 instruction set which mainly speed up integer computations (although it also improves floating-point thanks to new features). Since nearly a decade, the FMA instruction set can speed up codes using fuse-multiply adds by a factor of 2. Recent Intel processors support the 512-bit AVX-512 instruction set which not only double the number of items that can be computed per instruction but also adds many useful features. In the end, SIMD-friendly codes can be up to an order of magnitude faster with the new instruction sets compared to the obsolete "generic" SSE2 instruction set. Compilers (eg. GCC, Clang, ICC) are meant to generate a portable code by default and thus they only use SSE2 by default. Note that Numpy already uses such "new" features to speed up a lot many functions (see sorts, argmin/argmax, log/exp, etc.).


来源: stackexchange

问:
bash - regex trim untill symbol
trying to trim untill and including symbol " - " .

for some reason, when i add ^(.*?) bash will not modify the varieble.

GNU bash, version 5.1.16(0)-release (amd64-portbld-freebsd12.2)

```<code>fname="text1 - text2.jpg"
outp="${fname//^(.*?)\s-\s/}"
echo $outp
</code>```

expected result: text2.jpg

any suggestions?

答:
You appear to be trying to use a regexp (specifically a PCRE or a BRE or ERE with undefined behavior) instead of a globbing pattern in your command. See https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html.

Is this what you're trying to do?

```<code>$ echo "${fname/* - }"
text2.jpg

$ echo "${fname#* - }"
text2.jpg

$ echo "${fname/*[[:space:]]-[[:space:]]}"
text2.jpg
</code>```

ContentLicense: CC BY-SA 4.0

Title: bash - regex trim untill symbol

Body:
trying to trim untill and including symbol " - " .

for some reason, when i add ^(.*?) bash will not modify the varieble.

GNU bash, version 5.1.16(0)-release (amd64-portbld-freebsd12.2)

fname="text1 - text2.jpg"
outp="${fname//^(.*?)\s-\s/}"
echo $outp

expected result: text2.jpg

any suggestions?

Body:
You appear to be trying to use a regexp (specifically a PCRE or a BRE or ERE with undefined behavior) instead of a globbing pattern in your command. See https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html.

Is this what you're trying to do?

$ echo "${fname/* - }"
text2.jpg

$ echo "${fname#* - }"
text2.jpg

$ echo "${fname/*[[:space:]]-[[:space:]]}"
text2.jpg


问:
I have a button in my react app that i only want it to be pressed once
I have implemented this onclick event in it and I want the functions inside the onclick event to run once</p>
```<code>    <button className='btn2' onClick={() => {

OpenForm();

      if (IsLoggedIn === true){
        Like();
    }else if(IsLoggedIn === false){
    return;
    }
      }}>
</code>```

答:
If you want users to be able to press the button only once and then disable it after it was pressed, you can try this:

import { useState } from 'react'

function MyComponent() {

    const [disabled, setDisabled] = useState(false);

    const handleClick = () => {
        IsLoggedIn && Like();
        IsLoggedIn && setDisabled(true);
    };

    return (
        <>
            ...
            <button disabled={disabled} onClick={handleClick}>Click me</button>
            ...
        </>
}

```

Body:
I have implemented this onclick event in it and I want the functions inside the onclick event to run once

    <button className='btn2' onClick={() => {

OpenForm();

      if (IsLoggedIn === true){
        Like();
    }else if(IsLoggedIn === false){
    return;
    }
      }}>


问:
Ansible - Copy command output to file for multiple hosts
I run a playbook with a single command against multiple Cisco Nexus hosts. For all hosts, I want to store the output of the commands in a single file on the controller.

---
- name: Nxos
  hosts:
    - sw1
    - sw2
  gather_facts: false
  tasks:
    - name: interface counters
      cisco.nxos.nxos_command:
        commands: show interface counters errors non-zero
      register: output
```
<p>However, with this method below, only 1 host's output is saved and not the others.</p>
<pre class="lang-yaml prettyprint-override"><code>  - name: copy output to file
    copy: content="{{ output.stdout[0] }}" dest="output.txt"
</code>```

Whereas, if I use the below method, sometimes the output is stored for all hosts while other times it only stores output for a random number of hosts

  - name: Copy output to file
    local_action:
      module: lineinfile
      path: output.txt
      line: "###{{ inventory_hostname }}### \n\n {{ output.stdout[0] }}"
      create: yes
```

Any idea what could be wrong or what the best way to store the output be?

Thanks

答:
Use delegate_to: localhost instead of local_action and run the task only once. In the content, iterate special variable ansible_play_hosts_all and select the registered output from the hostvars. For example, the playbook below

- hosts: sw1,sw2
  gather_facts: false
  tasks:
    - command: "echo {{ inventory_hostname }}"
      register: output
    - name: Copy output to file
      copy:
        dest: output.txt
        content: |-
          {% for host in ansible_play_hosts_all %}
          {{ '###' }}{{ host }}{{ '###' }}
          {{ hostvars[host]['output']['stdout'] }}
          {% endfor %}
      delegate_to: localhost
      run_once: true
```
<p>gives</p>
<pre class="lang-yaml prettyprint-override"><code>shell> cat output.txt
###sw1###
sw1
###sw2###
sw2
</code>```

Body:
I run a playbook with a single command against multiple Cisco Nexus hosts. For all hosts, I want to store the output of the commands in a single file on the controller.

---
- name: Nxos
  hosts:
    - sw1
    - sw2
  gather_facts: false
  tasks:
    - name: interface counters
      cisco.nxos.nxos_command:
        commands: show interface counters errors non-zero
      register: output

However, with this method below, only 1 host's output is saved and not the others.

  - name: copy output to file
    copy: content="{{ output.stdout[0] }}" dest="output.txt"

Whereas, if I use the below method, sometimes the output is stored for all hosts while other times it only stores output for a random number of hosts

  - name: Copy output to file
    local_action:
      module: lineinfile
      path: output.txt
      line: "###{{ inventory_hostname }}### \n\n {{ output.stdout[0] }}"
      create: yes

Any idea what could be wrong or what the best way to store the output be?

Thanks

Body:
Use delegate_to: localhost instead of local_action and run the task only once. In the content, iterate special variable ansible_play_hosts_all and select the registered output from the hostvars. For example, the playbook below

- hosts: sw1,sw2
  gather_facts: false
  tasks:
    - command: "echo {{ inventory_hostname }}"
      register: output
    - name: Copy output to file
      copy:
        dest: output.txt
        content: |-
          {% for host in ansible_play_hosts_all %}
          {{ '###' }}{{ host }}{{ '###' }}
          {{ hostvars[host]['output']['stdout'] }}
          {% endfor %}
      delegate_to: localhost
      run_once: true

gives

shell> cat output.txt
###sw1###
sw1
###sw2###
sw2


问:
Django Admin Model - Foreign key is showing email, not id
I have two models -
An Article Model.
A Reporter Model.

Just like the Django Documentation

```<code>from django.db import models

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()

def __str__(self):
    return str(self.email)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

def __str__(self):
    return str(self.headline)
</code>```

I also have registered this in my admin.py file

```<code>@admin.register(Reporter)
class ReporterAdmin(admin.ModelAdmin):
    pass

@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
    pass
</code>```

When I go to add an article in admin, the field for reporter shows me the reporters email, I want it to show me the reporters id (the id field that is created by default).

答:
Answering my own question.

```<code>class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()

def __str__(self):
    return str(self.email)
</code>```

Should be

```<code>class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()

def __str__(self):
    return str(self.id)
</code>```

Body:
I have two models -
An Article Model.
A Reporter Model.

Just like the Django Documentation

from django.db import models

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()

def __str__(self):
    return str(self.email)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

def __str__(self):
    return str(self.headline)

I also have registered this in my admin.py file

@admin.register(Reporter)
class ReporterAdmin(admin.ModelAdmin):
    pass

@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
    pass

When I go to add an article in admin, the field for reporter shows me the reporters email, I want it to show me the reporters id (the id field that is created by default).

Body:
Answering my own question.

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()

def __str__(self):
    return str(self.email)

Should be

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()

def __str__(self):
    return str(self.id)


问:
Query in Django template
I am trying to query inside a django template, but i am just not sure how to correctly phrase the query, i have two models 1-category 2-items and i am trying to get all the items of a specific category from it's ID {% for item in Category.objects.get(id=${this.id}).items.all%}{{item.name}}{%endfor%}

here is the complete template:

```<code><div class="inventory-content">
    <div class='category'>
        <div>Categories</div>
        <div class='category-checkbox'>
            {%for category in items%}
            <input type="checkbox" id="{{category.id}}" name="{{category.name}}" value="{{category.id}}">
            <label for="{{category.name}}"> {{category.name}}</label><br>
            {%endfor%}
        </div>
    </div>
    <div class='items'></div>

</div>

<script>
    $('.category-checkbox input[type="checkbox"]').on('click', function() {
        if ($(this).is(':checked')) {
          // Add the element to the div with an id identifier
          $('.items').append(`<div id="item_${this.id}">{% for item in Category.objects.get(id=${this.id}).items.all%}{{item.name}}{%endfor%}</div>`);
        } else {
          // Remove the element from the div targeted by the id identifier
          $(`#item_${this.id}`).remove();
        }
      });
</script>
</code>```

models.py:

```<code>class Category(models.Model):
    name = models.CharField(max_length=150)
    vessel = models.ForeignKey(Vessel,on_delete=models.CASCADE,related_name='category')
    def __str__(self):
        return self.name
class Item(models.Model):
    name = models.CharField(max_length=255)
    part_number = models.IntegerField(blank=True)
    ROB = models.IntegerField(default=0)
    category=models.ForeignKey(Category,related_name='items',on_delete=models.CASCADE)

    def __str__(self):
        return self.name
</code>```

views.py:

```<code>def index(request,pk):
    vessel_id = Vessel.objects.get(id=pk)
    categories = vessel_id.category.all()
    category = Category.objects.all()
    item = categories.prefetch_related(
        'items')
    context ={"vessel_id":vessel_id,'items':item,"category":category}
    return render(request,'inventory.html',context)

</code>```

also i have been told it's bad practice to write query inside the template, so if you can guide me what better way could i have achieved this ?which is querying for all items in a specific category when checked

答:
As vessel_id you have Vessel object, not its id. Be careful with that.
You should definitely get what you need in your views. You already know, how to pass and use context. Even for scripts, but it might be little more tricky. You can try:

```<code>script_insider = ''.join([item.name for item in Category.objects.get(id=id_you_want).items.all()])
</code>```

It should sum your Items names to that: 'name_1name_2name_3'. You can use ' ' instead of '', then whitespace will separate the names: 'name_1 name_2 name_3'.

In templates you cannot use freely the code. You will mostly use for loops and if conditionings. You can also read about Custom Tags that can sometimes be more precise with template values.

Title: Query in Django template

Body:
I am trying to query inside a django template, but i am just not sure how to correctly phrase the query, i have two models 1-category 2-items and i am trying to get all the items of a specific category from it's ID {% for item in Category.objects.get(id=${this.id}).items.all%}{{item.name}}{%endfor%}

here is the complete template:

Categories

            {%for category in items%}
            <input type="checkbox" id="{{category.id}}" name="{{category.name}}" value="{{category.id}}">
             {{category.name}}

            {%endfor%}

models.py:

class Category(models.Model):
    name = models.CharField(max_length=150)
    vessel = models.ForeignKey(Vessel,on_delete=models.CASCADE,related_name='category')
    def __str__(self):
        return self.name
class Item(models.Model):
    name = models.CharField(max_length=255)
    part_number = models.IntegerField(blank=True)
    ROB = models.IntegerField(default=0)
    category=models.ForeignKey(Category,related_name='items',on_delete=models.CASCADE)

    def __str__(self):
        return self.name

views.py:

def index(request,pk):
    vessel_id = Vessel.objects.get(id=pk)
    categories = vessel_id.category.all()
    category = Category.objects.all()
    item = categories.prefetch_related(
        'items')
    context ={"vessel_id":vessel_id,'items':item,"category":category}
    return render(request,'inventory.html',context)

also i have been told it's bad practice to write query inside the template, so if you can guide me what better way could i have achieved this ?which is querying for all items in a specific category when checked

Body:
As vessel_id you have Vessel object, not its id. Be careful with that.
You should definitely get what you need in your views. You already know, how to pass and use context. Even for scripts, but it might be little more tricky. You can try:

script_insider = ''.join([item.name for item in Category.objects.get(id=id_you_want).items.all()])

It should sum your Items names to that: 'name_1name_2name_3'. You can use ' ' instead of '', then whitespace will separate the names: 'name_1 name_2 name_3'.

In templates you cannot use freely the code. You will mostly use for loops and if conditionings. You can also read about Custom Tags that can sometimes be more precise with template values.


问:
Very slow join query on large table (machine = Xeon 2.4 GHz, 16 core, 64 GB RAM)
Here is my query :

```<code>SELECT  email_data.id, email_data.source_file, email_data.report_id,
        email_data.filePath, email_data.fileName, email_data.size,
        email_data.emailID, email_data.msgID, email_data.cus, email_data.subject,
        email_data.sentto, email_data.emailFrom, email_data.hdrs, email_data.cc,
        email_data.bcc, email_data.extracted, email_data.DateTime,
        email_data.TimeStamp, email_data.OriginalDateTime, email_data.ParentID,
        email_data.reply_to, email_data.MD5Hash, email_data.duplicated,
        email_data.TimeZone, email_data.AttachName, email_data.fqdn,
        attach_data.id, attach_data.source_file, attach_data.report_id,
        attach_data.filePath, attach_data.fileName, attach_data.size, attach_data.ext,
        attach_data.emailID, attach_data.cus, attach_data.extracted,
        attach_data.MD5Hash, attach_data.duplicated
FROM email_data
LEFT JOIN attach_data
ON (email_data.emailID = attach_data.emailID);
</code>```

Combination of both of the table has 50k + records (email_data have 22k records and other have 30K + records).

Above query takes over 90 mins and still not finished.

This one :

```<code>SELECT email_data.id, attach_data.id
FROM email_data
LEFT JOIN attach_data
ON (email_data.emailID = attach_data.emailID);
</code>```

takes 2 mins 22 sec:

What am I doing wrong? It seems that MySQL do not using enough memory to speed things up, and it only uses 1 core out of 16 cores.

How can I configure it to use all available resources?

Or should I query IDs (as in 2nd query) and loop + select each of them back in my code? Will it cause same result?

I needs all those fields and all the row, I am converting them into Custom CSV-Like format so it can be exported to other software.

Columns :

```<code>mysql> show columns from email_data;
+------------------+----------+------+-----+---------+----------------+
| Field            | Type     | Null | Key | Default | Extra          |
+------------------+----------+------+-----+---------+----------------+
| id               | int(11)  | NO   | PRI | NULL    | auto_increment |
| source_file      | longtext | YES  |     | NULL    |                |
| report_id        | int(11)  | YES  |     | NULL    |                |
| filePath         | longtext | YES  |     | NULL    |                |
| fileName         | longtext | YES  |     | NULL    |                |
| size             | int(11)  | YES  |     | NULL    |                |
| emailID          | longtext | YES  |     | NULL    |                |
| msgID            | longtext | YES  |     | NULL    |                |
| cus              | longtext | YES  |     | NULL    |                |
| subject          | longtext | YES  |     | NULL    |                |
| sentto           | longtext | YES  |     | NULL    |                |
| emailFrom        | longtext | YES  |     | NULL    |                |
| hdrs             | longtext | YES  |     | NULL    |                |
| cc               | longtext | YES  |     | NULL    |                |
| bcc              | longtext | YES  |     | NULL    |                |
| extracted        | longtext | YES  |     | NULL    |                |
| DateTime         | char(1)  | YES  |     | NULL    |                |
| TimeStamp        | int(11)  | YES  |     | NULL    |                |
| OriginalDateTime | char(1)  | YES  |     | NULL    |                |
| ParentID         | longtext | YES  |     | NULL    |                |
| reply_to         | longtext | YES  |     | NULL    |                |
| MD5Hash          | longtext | YES  |     | NULL    |                |
| duplicated       | char(1)  | YES  |     | NULL    |                |
| TimeZone         | char(1)  | YES  |     | NULL    |                |
| AttachName       | longtext | YES  |     | NULL    |                |
| fqdn             | longtext | YES  |     | NULL    |                |
+------------------+----------+------+-----+---------+----------------+
</code>```

Almost same for attach_data

答:
It is almost certain that attach_data.emailID is lacking an index.  Consider that the query engine must go through every single row of email data, and if the index is missing, it must walk every row of attach_data, even after finding a match.

You should run an EXPLAIN on your query to see what MySql is actually doing.  If the index is missing, you will be doin 22,000 x 30,000 comparisons, or about 660 million comparisons to build up your resulting dataset.  If your id's are strings, you are in for a long ride.

If you do index attach_data.emailId, you will reduce the number of comparisons to about 22,000 x log(30,000), or about 330 thousand comparisons.  Huge difference.  Using a HASH index will make this even quicker (the lower bound is 22,000 comparisons).  If the indexes are missing, you can attach them after the fact.

And honestly, you should consider LIMIT to skip over and take a window of results.  This will save you a lot of grief shuffling that data to and from the client.  You might find that this sort of traffic can cause timeouts on a slow connect (and I agree with another poster, it's strange that you aren't timing out)

UPDATE

Holy cow.  Seeing your update to the question, you should definitely pull back only the non-longtext fields, iterate through those and pull back the longtext fields one at a time.  But seeing as your need is to dump a mysql table to a csv, I would recommend looking into mysqldump.  It can back your database up to CSV files for you.

ContentLicense: CC BY-SA 3.0

Body:
Here is my query :

SELECT  email_data.id, email_data.source_file, email_data.report_id,
        email_data.filePath, email_data.fileName, email_data.size,
        email_data.emailID, email_data.msgID, email_data.cus, email_data.subject,
        email_data.sentto, email_data.emailFrom, email_data.hdrs, email_data.cc,
        email_data.bcc, email_data.extracted, email_data.DateTime,
        email_data.TimeStamp, email_data.OriginalDateTime, email_data.ParentID,
        email_data.reply_to, email_data.MD5Hash, email_data.duplicated,
        email_data.TimeZone, email_data.AttachName, email_data.fqdn,
        attach_data.id, attach_data.source_file, attach_data.report_id,
        attach_data.filePath, attach_data.fileName, attach_data.size, attach_data.ext,
        attach_data.emailID, attach_data.cus, attach_data.extracted,
        attach_data.MD5Hash, attach_data.duplicated
FROM email_data
LEFT JOIN attach_data
ON (email_data.emailID = attach_data.emailID);

Combination of both of the table has 50k + records (email_data have 22k records and other have 30K + records).

Above query takes over 90 mins and still not finished.

This one :

SELECT email_data.id, attach_data.id
FROM email_data
LEFT JOIN attach_data
ON (email_data.emailID = attach_data.emailID);

takes 2 mins 22 sec:

What am I doing wrong? It seems that MySQL do not using enough memory to speed things up, and it only uses 1 core out of 16 cores.

How can I configure it to use all available resources?

Or should I query IDs (as in 2nd query) and loop + select each of them back in my code? Will it cause same result?

I needs all those fields and all the row, I am converting them into Custom CSV-Like format so it can be exported to other software.

Columns :

mysql> show columns from email_data;
+------------------+----------+------+-----+---------+----------------+
| Field            | Type     | Null | Key | Default | Extra          |
+------------------+----------+------+-----+---------+----------------+
| id               | int(11)  | NO   | PRI | NULL    | auto_increment |
| source_file      | longtext | YES  |     | NULL    |                |
| report_id        | int(11)  | YES  |     | NULL    |                |
| filePath         | longtext | YES  |     | NULL    |                |
| fileName         | longtext | YES  |     | NULL    |                |
| size             | int(11)  | YES  |     | NULL    |                |
| emailID          | longtext | YES  |     | NULL    |                |
| msgID            | longtext | YES  |     | NULL    |                |
| cus              | longtext | YES  |     | NULL    |                |
| subject          | longtext | YES  |     | NULL    |                |
| sentto           | longtext | YES  |     | NULL    |                |
| emailFrom        | longtext | YES  |     | NULL    |                |
| hdrs             | longtext | YES  |     | NULL    |                |
| cc               | longtext | YES  |     | NULL    |                |
| bcc              | longtext | YES  |     | NULL    |                |
| extracted        | longtext | YES  |     | NULL    |                |
| DateTime         | char(1)  | YES  |     | NULL    |                |
| TimeStamp        | int(11)  | YES  |     | NULL    |                |
| OriginalDateTime | char(1)  | YES  |     | NULL    |                |
| ParentID         | longtext | YES  |     | NULL    |                |
| reply_to         | longtext | YES  |     | NULL    |                |
| MD5Hash          | longtext | YES  |     | NULL    |                |
| duplicated       | char(1)  | YES  |     | NULL    |                |
| TimeZone         | char(1)  | YES  |     | NULL    |                |
| AttachName       | longtext | YES  |     | NULL    |                |
| fqdn             | longtext | YES  |     | NULL    |                |
+------------------+----------+------+-----+---------+----------------+

Almost same for attach_data


问:
Any way to use CSS Variables in SASS functions for hsl() transparency?
I have defined a color in my root:

```<code>:root {
--purple: hsl(266, 35%, 70%);
}
</code>```

And I'm trying to use it in a SASS function to give it transparency:

```<code>.purple {
  background: transparentize(#{"var(--primary-color)"}, 0.7)
}
</code>```

Does anyone know of a way to get this to work? Or is it just not possible?

答: Unfortunately, this is impossible. CSS variables are subsituted in for their values at runtime. The SASS compiler is just that -- a compiler, making it unable to read the value of CSS variables, since CSS variables can be defined in other files.</p>

Body:
I have defined a color in my root:

:root {
--purple: hsl(266, 35%, 70%);
}

And I'm trying to use it in a SASS function to give it transparency:

.purple {
  background: transparentize(#{"var(--primary-color)"}, 0.7)
}

Does anyone know of a way to get this to work? Or is it just not possible?


问:
What is the best way to make a request from a node express app to a third party api that requires its own authentication?
I have a node express app that uses keycloak authentication to secure all API endpoints. Express middleware has been set up for authentication to make sure that each incoming request from the front end has the appropriate keycloak token. I need to make a post request from my node app to a third party backend API to subscribe users to an email service that uses a different authentication method which my middleware would not work with.

What would be the best practice for making a request from the third party API? I am considering creating a new express instance and use a separate middleware specific for that post request. Is this an ok thing to do or is there a better way?

Here is a simplified version of my node app. See the

index.js

```<code>import { authmware } from "./authmware";
import express from "express";
import { router } from "./router";

const app = express();
authmware(app);
router(app);

app.use((err, req, res, next) => {
  logger.error(err.message);
  const code = err.code ? err.code : 500;
  const message = err.message ? err.message : "Internal Server Error";

  res.status(code).json({ error: message, success: false });
});

export default app;
</code>```

router.js

```<code>import express from "express";
import createProfile from "../../controllers/createProfile";

const router = express.Router();

router.post("/", createProfile);

export const router = (app) => {
   app.use("/api/v1/createProfile", router);
};
</code>```

controllers/createProfile.js

```<code>const createProfile = async (req, res) => {

  // ... Do some stuff

  // ** make request to a different api here **
  await makeThirdPartyApiRequest();

}
</code>```

How would I make this third party api request that uses a different style of authentication?

答:
This is a very common use case. You can use 10 third party APIs in your node server and all having different authentication mechanisms irrespective of the auth you are using for your client requests.

```<code>await makeThirdPartyApiRequest();
  // http request to API
  // attach proper auth headers (API key / jwt / basic auth / oAuth token). This will be based on the authentication method the API is offering.
}
</code>```

Update based on your recent comment:

The API should have some documentation on how to authenticate using the user key and secret key. For example: Google APIs just require you to send API key with request https://cloud.google.com/api-keys/docs/overview

Body:
I have a node express app that uses keycloak authentication to secure all API endpoints. Express middleware has been set up for authentication to make sure that each incoming request from the front end has the appropriate keycloak token. I need to make a post request from my node app to a third party backend API to subscribe users to an email service that uses a different authentication method which my middleware would not work with.

What would be the best practice for making a request from the third party API? I am considering creating a new express instance and use a separate middleware specific for that post request. Is this an ok thing to do or is there a better way?

Here is a simplified version of my node app. See the

index.js

import { authmware } from "./authmware";
import express from "express";
import { router } from "./router";

const app = express();
authmware(app);
router(app);

app.use((err, req, res, next) => {
  logger.error(err.message);
  const code = err.code ? err.code : 500;
  const message = err.message ? err.message : "Internal Server Error";

  res.status(code).json({ error: message, success: false });
});

export default app;

router.js

import express from "express";
import createProfile from "../../controllers/createProfile";

const router = express.Router();

router.post("/", createProfile);

export const router = (app) => {
   app.use("/api/v1/createProfile", router);
};

controllers/createProfile.js

const createProfile = async (req, res) => {

  // ... Do some stuff

  // ** make request to a different api here **
  await makeThirdPartyApiRequest();

}

How would I make this third party api request that uses a different style of authentication?

Body:
This is a very common use case. You can use 10 third party APIs in your node server and all having different authentication mechanisms irrespective of the auth you are using for your client requests.

await makeThirdPartyApiRequest();
  // http request to API
  // attach proper auth headers (API key / jwt / basic auth / oAuth token). This will be based on the authentication method the API is offering.
}

Update based on your recent comment:

The API should have some documentation on how to authenticate using the user key and secret key. For example: Google APIs just require you to send API key with request https://cloud.google.com/api-keys/docs/overview


问:
Quickest Possible Wifi Access Point Switching
I am developing an audio communication application which requires that an android phone quickly switch from one WiFi network to another. Currently, my code takes anywhere from 7 to 15 seconds switching WiFi networks that it already knows exist in the environment and are pre-configured. Is it possible to accelerate this time to switch. Must I live with buffering 15+ seconds of audio so that when the user roams from one WiFi network to the next, they won't hear any pauses?</p>

```<code> private void SwitchWifi(){

    int myBestNetworkStrength = -60;
    int myBestNetworkID = -1;
    List<WifiConfiguration> currentConfig = myManager.getConfiguredNetworks();
    if(myManager.startScan()){
        if(myNetworks==null){
            Initialize();
        }
        List<ScanResult> wifiList = myManager.getScanResults();
        for(int i = 0; i < wifiList.size(); i++){
            for(int j = 0; j < myNetworks.size(); j++){
                if(wifiList.get(i).SSID.matches(myNetworks.get(j).mySSID)){
                    if(myBestNetworkStrength < wifiList.get(i).level){
                        for(int k = 0; k < currentConfig.size(); k++){
                            DebugScreen.AddLog("WIFIswitch", "k = " + currentConfig.get(k).SSID);
                            if(currentConfig.get(k).SSID.matches("\"" + wifiList.get(i).SSID+ "\"")){
                                myBestNetworkID = k;
                                myBestNetworkStrength = wifiList.get(i).level;
                            }
                        }
                    }
                }
            }
        }
    }//
    DebugScreen.AddLog("WIFIswitch", "Best network strength is " + Integer.toString(myBestNetworkStrength) + " with network #" + Integer.toString(myBestNetworkID) );
    if(myBestNetworkID != -1){
        MailService.is_Waiting_For_New_Connection = true;
        while(!MailService.has_Entered_Pause_Loop){
            if(!isAlive())
                return;
        }
        myManager.disconnect();
        myManager.enableNetwork(myBestNetworkID, true);
        myManager.reconnect();
        MailService.is_Waiting_For_New_Connection = false;
    }
}
</code>```

答:
Maybe you could have an object that extends Observable (or implements a custom listener) that checks regularly (in a thread ?) what's the best network. When you detect that the current network is not the best anymore, you just notify the observers (or fire up the listener) and actually enable/reconnect to the new network.

So detecting what's the best network will always last 7 to 15s, but as it is done in background, switching from a network to another will be almost immediatly effective.

Body:
I am developing an audio communication application which requires that an android phone quickly switch from one WiFi network to another. Currently, my code takes anywhere from 7 to 15 seconds switching WiFi networks that it already knows exist in the environment and are pre-configured. Is it possible to accelerate this time to switch. Must I live with buffering 15+ seconds of audio so that when the user roams from one WiFi network to the next, they won't hear any pauses?

 private void SwitchWifi(){

    int myBestNetworkStrength = -60;
    int myBestNetworkID = -1;
    List<WifiConfiguration> currentConfig = myManager.getConfiguredNetworks();
    if(myManager.startScan()){
        if(myNetworks==null){
            Initialize();
        }
        List<ScanResult> wifiList = myManager.getScanResults();
        for(int i = 0; i < wifiList.size(); i++){
            for(int j = 0; j < myNetworks.size(); j++){
                if(wifiList.get(i).SSID.matches(myNetworks.get(j).mySSID)){
                    if(myBestNetworkStrength < wifiList.get(i).level){
                        for(int k = 0; k < currentConfig.size(); k++){
                            DebugScreen.AddLog("WIFIswitch", "k = " + currentConfig.get(k).SSID);
                            if(currentConfig.get(k).SSID.matches("\"" + wifiList.get(i).SSID+ "\"")){
                                myBestNetworkID = k;
                                myBestNetworkStrength = wifiList.get(i).level;
                            }
                        }
                    }
                }
            }
        }
    }//
    DebugScreen.AddLog("WIFIswitch", "Best network strength is " + Integer.toString(myBestNetworkStrength) + " with network #" + Integer.toString(myBestNetworkID) );
    if(myBestNetworkID != -1){
        MailService.is_Waiting_For_New_Connection = true;
        while(!MailService.has_Entered_Pause_Loop){
            if(!isAlive())
                return;
        }
        myManager.disconnect();
        myManager.enableNetwork(myBestNetworkID, true);
        myManager.reconnect();
        MailService.is_Waiting_For_New_Connection = false;
    }
}


问:
Splash does not render the elements created by javascript
I know there are a couple of posts asking the same questions. I have tried them all but after a couple of sleepless nights, I had to ask the question and I will be very appreciative if someone can help me with the problem.

So I am trying to get the reviews from a yelp restaurants page using Python. The reviews are generated dynamically using javascript. I tried every possible way with scrapy, requests-html, scrapy_splash, beautifulSoup. Nothing worked. I realized that even when using Splash by itself through the browser using localhost:8050, I still get the same problem. I tried to disable the private mode and increase the wait time but that did not fix the problem. I also tried it on both firefox and chromium, still the same.

Here is the page I am testing
https://www.yelp.com/biz/brendas-french-soul-food-san-francisco-5

You will notice that the divs containing the reviews are missing.

Any help will be much appreciated.

答:
The reviews you are searching for are loaded by js requesting this endpoint

```<code>https://www.yelp.com/biz/lJAGnYzku5zSaLnQ_T6_GQ/review_feed?rl=en&q=&sort_by=relevance_desc&start={offset value}
</code>```

Which shows 10 comments and whole load of other data.

Body:
The reviews you are searching for are loaded by js requesting this endpoint

https://www.yelp.com/biz/lJAGnYzku5zSaLnQ_T6_GQ/review_feed?rl=en&q=&sort_by=relevance_desc&start={offset value}

Which shows 10 comments and whole load of other data.


问:
Adding A Data Array for redirect
My question of the day is this. After a successful login I want to to send the user_id in a data array to the control panel when it redirects. I have a lot of code here. 98% of it was code that was written from a authentication library and I'm afraid if I tinker too much with it now I'll end up breaking something else by trying to do one thing. Any help?

```<code>class Auth extends CI_Controller
{
function __construct()
{
    parent::__construct();

    $this->load->helper(array('form', 'url'));
    $this->load->library('form_validation');
    $this->load->library('security');
    $this->load->library('tank_auth');
    $this->lang->load('tank_auth');

    if ($this->tank_auth->is_logged_in()) {
        redirect('/cpanel/');
    } else {
        redirect('/auth/login/');
    }
}

function index()
{

}

/**
 * Login user on the site
 *
 * @return void
 */
function login()
{
    if ($this->tank_auth->is_logged_in()) {                                 // logged in
        redirect('/cpanel');

    } elseif ($this->tank_auth->is_logged_in(FALSE)) {                      // logged in, not activated
        redirect('/auth/send_again/');

    } else {
        $data['login_by_username'] = ($this->config->item('login_by_username', 'tank_auth') AND
                $this->config->item('use_username', 'tank_auth'));
        $data['login_by_email'] = $this->config->item('login_by_email', 'tank_auth');

        $this->form_validation->set_rules('login', 'Login', 'trim|required|xss_clean');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
        $this->form_validation->set_rules('remember', 'Remember me', 'integer');

        // Get login for counting attempts to login
        if ($this->config->item('login_count_attempts', 'tank_auth') AND
                ($login = $this->input->post('login'))) {
            $login = $this->security->xss_clean($login);
        } else {
            $login = '';
        }

        $data['errors'] = array();

        if ($this->form_validation->run()) {                                // validation ok
            if ($this->tank_auth->login(
                    $this->form_validation->set_value('login'),
                    $this->form_validation->set_value('password'),
                    $this->form_validation->set_value('remember'),
                    $data['login_by_username'],
                    $data['login_by_email'])) {                             // success
                redirect('/cpanel');

            } else {
                $errors = $this->tank_auth->get_error_message();
                if (isset($errors['banned'])) {                             // banned user
                    $this->_show_message($this->lang->line('auth_message_banned').' '.$errors['banned']);

                } elseif (isset($errors['not_activated'])) {                // not activated user
                    redirect('/auth/send_again/');

                } else {                                                    // fail
                    foreach ($errors as $k => $v)   $data['errors'][$k] = $this->lang->line($v);
                }
            }
        }
        $this->template->set_layout('default')->enable_parser(false);
        $this->template->build('auth/login_form', $data);
    }
}
</code>```

EDIT:

With the following code when I go to my kansasoutlawwrestling.com/kowmanager page I get a white screen but if I go my login page which is kansasoutlawwrestling.com/kowmanager/login and log in then I get A PHP Error was encountered

Severity: Notice

Message: Undefined variable: id

Filename: controllers/auth.php

Line Number: 63
A PHP Error was encountered

Severity: Warning

Message: Cannot modify header information - headers already sent by (output started at /home/xtremer/public_html/system/core/Exceptions.php:170)

Filename: helpers/url_helper.php

Line Number: 543

```<code>class Auth extends CI_Controller
{
function __construct()
{
    parent::__construct();

    $this->load->helper(array('form', 'url'));
    $this->load->library('form_validation');
    $this->load->library('security');
    $this->load->library('tank_auth');
    $this->lang->load('tank_auth');

    $id = $this->tank_auth->get_user_id();

}

function index()
{

}

/**
 * Login user on the site
 *
 * @return void
 */
function login()
{
    if ($this->tank_auth->is_logged_in()) {                                 // logged in
        redirect('/cpanel', $id);

    } elseif ($this->tank_auth->is_logged_in(FALSE)) {                      // logged in, not activated
        redirect('/auth/send_again/');

    } else {
        $data['login_by_username'] = ($this->config->item('login_by_username', 'tank_auth') AND
                $this->config->item('use_username', 'tank_auth'));
        $data['login_by_email'] = $this->config->item('login_by_email', 'tank_auth');

        $this->form_validation->set_rules('login', 'Login', 'trim|required|xss_clean');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
        $this->form_validation->set_rules('remember', 'Remember me', 'integer');

        // Get login for counting attempts to login
        if ($this->config->item('login_count_attempts', 'tank_auth') AND
                ($login = $this->input->post('login'))) {
            $login = $this->security->xss_clean($login);
        } else {
            $login = '';
        }

        $data['errors'] = array();

        if ($this->form_validation->run()) {                                // validation ok
            if ($this->tank_auth->login(
                    $this->form_validation->set_value('login'),
                    $this->form_validation->set_value('password'),
                    $this->form_validation->set_value('remember'),
                    $data['login_by_username'],
                    $data['login_by_email'])) {                             // success
                redirect('/cpanel', $id);

            } else {
                $errors = $this->tank_auth->get_error_message();
                if (isset($errors['banned'])) {                             // banned user
                    $this->_show_message($this->lang->line('auth_message_banned').' '.$errors['banned']);

                } elseif (isset($errors['not_activated'])) {                // not activated user
                    redirect('/auth/send_again/');

                } else {                                                    // fail
                    foreach ($errors as $k => $v)   $data['errors'][$k] = $this->lang->line($v);
                }
            }
        }
        $this->template->set_layout('default')->enable_parser(false);
        $this->template->build('auth/login_form', $data);
    }
}
</code>```

答:
Well actually @Pekka, tank_auth uses language libraries, so the sentence isn't there, but the reference to the english version of the sentence.  The line you're looking for is right after $data['login_by_email'])) { // success in the file controllers/auth.php

It uses the _show_message() function inside of the auth controller.  The function sets a message in the flash session data, then redirects you to the main auth view (which displays the message stored in flash).  You can replace this line with a simple redirect('myControlPanel'); And you'll be fine.  Or do what I did and return them to the page that redirected them to the login page.

Hope that helps,
Max

Title: Adding A Data Array for redirect

Body:
My question of the day is this. After a successful login I want to to send the user_id in a data array to the control panel when it redirects. I have a lot of code here. 98% of it was code that was written from a authentication library and I'm afraid if I tinker too much with it now I'll end up breaking something else by trying to do one thing. Any help?

class Auth extends CI_Controller
{
function __construct()
{
    parent::__construct();

    $this->load->helper(array('form', 'url'));
    $this->load->library('form_validation');
    $this->load->library('security');
    $this->load->library('tank_auth');
    $this->lang->load('tank_auth');

    if ($this->tank_auth->is_logged_in()) {
        redirect('/cpanel/');
    } else {
        redirect('/auth/login/');
    }
}

function index()
{

}

/**
 * Login user on the site
 *
 * @return void
 */
function login()
{
    if ($this->tank_auth->is_logged_in()) {                                 // logged in
        redirect('/cpanel');

    } elseif ($this->tank_auth->is_logged_in(FALSE)) {                      // logged in, not activated
        redirect('/auth/send_again/');

    } else {
        $data['login_by_username'] = ($this->config->item('login_by_username', 'tank_auth') AND
                $this->config->item('use_username', 'tank_auth'));
        $data['login_by_email'] = $this->config->item('login_by_email', 'tank_auth');

        $this->form_validation->set_rules('login', 'Login', 'trim|required|xss_clean');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
        $this->form_validation->set_rules('remember', 'Remember me', 'integer');

        // Get login for counting attempts to login
        if ($this->config->item('login_count_attempts', 'tank_auth') AND
                ($login = $this->input->post('login'))) {
            $login = $this->security->xss_clean($login);
        } else {
            $login = '';
        }

        $data['errors'] = array();

        if ($this->form_validation->run()) {                                // validation ok
            if ($this->tank_auth->login(
                    $this->form_validation->set_value('login'),
                    $this->form_validation->set_value('password'),
                    $this->form_validation->set_value('remember'),
                    $data['login_by_username'],
                    $data['login_by_email'])) {                             // success
                redirect('/cpanel');

            } else {
                $errors = $this->tank_auth->get_error_message();
                if (isset($errors['banned'])) {                             // banned user
                    $this->_show_message($this->lang->line('auth_message_banned').' '.$errors['banned']);

                } elseif (isset($errors['not_activated'])) {                // not activated user
                    redirect('/auth/send_again/');

                } else {                                                    // fail
                    foreach ($errors as $k => $v)   $data['errors'][$k] = $this->lang->line($v);
                }
            }
        }
        $this->template->set_layout('default')->enable_parser(false);
        $this->template->build('auth/login_form', $data);
    }
}

EDIT:

With the following code when I go to my kansasoutlawwrestling.com/kowmanager page I get a white screen but if I go my login page which is kansasoutlawwrestling.com/kowmanager/login and log in then I get A PHP Error was encountered

Severity: Notice

Message: Undefined variable: id

Filename: controllers/auth.php

Line Number: 63
A PHP Error was encountered

Severity: Warning

Message: Cannot modify header information - headers already sent by (output started at /home/xtremer/public_html/system/core/Exceptions.php:170)

Filename: helpers/url_helper.php

Line Number: 543

class Auth extends CI_Controller
{
function __construct()
{
    parent::__construct();

    $this->load->helper(array('form', 'url'));
    $this->load->library('form_validation');
    $this->load->library('security');
    $this->load->library('tank_auth');
    $this->lang->load('tank_auth');

    $id = $this->tank_auth->get_user_id();

}

function index()
{

}

/**
 * Login user on the site
 *
 * @return void
 */
function login()
{
    if ($this->tank_auth->is_logged_in()) {                                 // logged in
        redirect('/cpanel', $id);

    } elseif ($this->tank_auth->is_logged_in(FALSE)) {                      // logged in, not activated
        redirect('/auth/send_again/');

    } else {
        $data['login_by_username'] = ($this->config->item('login_by_username', 'tank_auth') AND
                $this->config->item('use_username', 'tank_auth'));
        $data['login_by_email'] = $this->config->item('login_by_email', 'tank_auth');

        $this->form_validation->set_rules('login', 'Login', 'trim|required|xss_clean');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
        $this->form_validation->set_rules('remember', 'Remember me', 'integer');

        // Get login for counting attempts to login
        if ($this->config->item('login_count_attempts', 'tank_auth') AND
                ($login = $this->input->post('login'))) {
            $login = $this->security->xss_clean($login);
        } else {
            $login = '';
        }

        $data['errors'] = array();

        if ($this->form_validation->run()) {                                // validation ok
            if ($this->tank_auth->login(
                    $this->form_validation->set_value('login'),
                    $this->form_validation->set_value('password'),
                    $this->form_validation->set_value('remember'),
                    $data['login_by_username'],
                    $data['login_by_email'])) {                             // success
                redirect('/cpanel', $id);

            } else {
                $errors = $this->tank_auth->get_error_message();
                if (isset($errors['banned'])) {                             // banned user
                    $this->_show_message($this->lang->line('auth_message_banned').' '.$errors['banned']);

                } elseif (isset($errors['not_activated'])) {                // not activated user
                    redirect('/auth/send_again/');

                } else {                                                    // fail
                    foreach ($errors as $k => $v)   $data['errors'][$k] = $this->lang->line($v);
                }
            }
        }
        $this->template->set_layout('default')->enable_parser(false);
        $this->template->build('auth/login_form', $data);
    }
}


问:
Unable to show data on Data Table at startsup the page while using Search filter but showing data after search something?
I trying to implement rows Search on Data Table on my flutter web app using TextEditingController. The data comes from The API as Json formte using Employee model.
I used FutureBuilder to get the data from the API. And i inserted Snapshot data into 'empList' as List. Also Created empsFiltered List to show search filtered data.

The issue is: Unable to show actual data in the datatable on startup. But the data is shown while searching and after clearing the searchtextfield.

I want to show the actual data on startup. And also the data should be shown as searched.

How to do this.

```<code>class EditorHome extends StatefulWidget {
  const EditorHome({Key? key}) : super(key: key);

  @override
  _EditorHomeState createState() => _EditorHomeState();
}

class _EditorHomeState extends State<EditorHome> {
  TextEditingController searchController = TextEditingController();
  String _searchResult = '';

  List empList = [];
  List empsFiltered = [];

  @override
  void initState() {
    super.initState();
    empsFiltered = empList;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Fetch Data Table Example with search'),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Card(
              child: ListTile(
                leading: const Icon(Icons.search),
                title: TextField(
                    controller: searchController,
                    decoration: const InputDecoration(
                        hintText: 'Search', border: InputBorder.none),
                    onChanged: (value) {
                      setState(() {
                        _searchResult = value;
                        empsFiltered = empList
                            .where((e) =>
                                e.name.contains(_searchResult.toLowerCase()) ||
                                e.email.contains(_searchResult.toLowerCase()))
                            .toList();
                      });
                    }),
                trailing: IconButton(
                  icon: const Icon(Icons.cancel),
                  onPressed: () {
                    setState(() {
                      searchController.clear();
                      _searchResult = '';
                      empsFiltered = empList;
                    });
                  },
                ),
              ),
            ),
            FutureBuilder<List<Employees>>(
              //initialData: const <Employees>[],
              future: fetchResults(),
              builder: (context, snapshot) {
                if (snapshot.hasError ||
                    snapshot.data == null ||
                    snapshot.connectionState == ConnectionState.waiting) {
                  return const CircularProgressIndicator();
                }
                empList = snapshot.data!;

                return DataTable(
                  headingTextStyle: const TextStyle(
                      fontWeight: FontWeight.bold, color: Colors.black),
                  headingRowHeight: 50,
                  showBottomBorder: true,
                  decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey, width: 1)),
                  columns: const [
                    DataColumn(label: SizedBox(width: 30, child: Text('ID'))),
                    DataColumn(
                        label: SizedBox(width: 100, child: Text('Name'))),
                    DataColumn(
                        label: SizedBox(width: 100, child: Text('Email'))),
                  ],
                  rows: List.generate(
                    empsFiltered.length,
                    (index) {
                      var emp = empsFiltered[index];
                      return DataRow(cells: [
                        DataCell(
                          Text(emp.id.toString()),
                        ),
                        DataCell(
                          Text(emp.name),
                        ),
                        DataCell(
                          Text(emp.email),
                        ),
                      ]);
                    },
                  ).toList(),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

Below is my API:

```<code>Future<List<Employees>> fetchResults() async {
  //List<Employees> _results = [];
  Uri url = Uri.parse(" http:link ");
  var response = await http.get(url);
  var resultsJson = json.decode(response.body).cast<Map<String, dynamic>>();
  List<Employees> emplist = await resultsJson
      .map<Employees>((json) => Employees.fromJson(json))
      .toList();
  return emplist;
}
</code>```

答:
Posting here to add the code snippet:

You should create a state variable to contain the result of fetchResults, call fetchResults/set that variable in your initState. Use that new variable as future of the futureBuilder instead of the function call directly

```<code>class _EditorHomeState extends State<EditorHome> {
  Future<List> futureList;

  @override
  void initState() {
    super.initState();
    futureList = fetchResults();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      ...
      FutureBuilder<List<Employees>>(
        future: futureList,
        builder: (context, snapshot) {
      ...
    );
  }
}
</code>```

Body:
I trying to implement rows Search on Data Table on my flutter web app using TextEditingController. The data comes from The API as Json formte using Employee model.
I used FutureBuilder to get the data from the API. And i inserted Snapshot data into 'empList' as List. Also Created empsFiltered List to show search filtered data.

The issue is: Unable to show actual data in the datatable on startup. But the data is shown while searching and after clearing the searchtextfield.

I want to show the actual data on startup. And also the data should be shown as searched.

How to do this.

class EditorHome extends StatefulWidget {
  const EditorHome({Key? key}) : super(key: key);

  @override
  _EditorHomeState createState() => _EditorHomeState();
}

class _EditorHomeState extends State<EditorHome> {
  TextEditingController searchController = TextEditingController();
  String _searchResult = '';

  List empList = [];
  List empsFiltered = [];

  @override
  void initState() {
    super.initState();
    empsFiltered = empList;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Fetch Data Table Example with search'),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Card(
              child: ListTile(
                leading: const Icon(Icons.search),
                title: TextField(
                    controller: searchController,
                    decoration: const InputDecoration(
                        hintText: 'Search', border: InputBorder.none),
                    onChanged: (value) {
                      setState(() {
                        _searchResult = value;
                        empsFiltered = empList
                            .where((e) =>
                                e.name.contains(_searchResult.toLowerCase()) ||
                                e.email.contains(_searchResult.toLowerCase()))
                            .toList();
                      });
                    }),
                trailing: IconButton(
                  icon: const Icon(Icons.cancel),
                  onPressed: () {
                    setState(() {
                      searchController.clear();
                      _searchResult = '';
                      empsFiltered = empList;
                    });
                  },
                ),
              ),
            ),
            FutureBuilder<List<Employees>>(
              //initialData: const <Employees>[],
              future: fetchResults(),
              builder: (context, snapshot) {
                if (snapshot.hasError ||
                    snapshot.data == null ||
                    snapshot.connectionState == ConnectionState.waiting) {
                  return const CircularProgressIndicator();
                }
                empList = snapshot.data!;

                return DataTable(
                  headingTextStyle: const TextStyle(
                      fontWeight: FontWeight.bold, color: Colors.black),
                  headingRowHeight: 50,
                  showBottomBorder: true,
                  decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey, width: 1)),
                  columns: const [
                    DataColumn(label: SizedBox(width: 30, child: Text('ID'))),
                    DataColumn(
                        label: SizedBox(width: 100, child: Text('Name'))),
                    DataColumn(
                        label: SizedBox(width: 100, child: Text('Email'))),
                  ],
                  rows: List.generate(
                    empsFiltered.length,
                    (index) {
                      var emp = empsFiltered[index];
                      return DataRow(cells: [
                        DataCell(
                          Text(emp.id.toString()),
                        ),
                        DataCell(
                          Text(emp.name),
                        ),
                        DataCell(
                          Text(emp.email),
                        ),
                      ]);
                    },
                  ).toList(),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

Below is my API:

Future<List<Employees>> fetchResults() async {
  //List<Employees> _results = [];
  Uri url = Uri.parse(" http:link ");
  var response = await http.get(url);
  var resultsJson = json.decode(response.body).cast<Map<String, dynamic>>();
  List<Employees> emplist = await resultsJson
      .map<Employees>((json) => Employees.fromJson(json))
      .toList();
  return emplist;
}

Body:
Posting here to add the code snippet:

You should create a state variable to contain the result of fetchResults, call fetchResults/set that variable in your initState. Use that new variable as future of the futureBuilder instead of the function call directly

class _EditorHomeState extends State<EditorHome> {
  Future<List> futureList;

  @override
  void initState() {
    super.initState();
    futureList = fetchResults();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      ...
      FutureBuilder<List<Employees>>(
        future: futureList,
        builder: (context, snapshot) {
      ...
    );
  }
}


问:
Joining a calendar table on date to a table of items returns all NULLS (adding missing dates to table by a group)
I am trying to join a table of dates to an existing table of items.  I want to add the missing dates for each item see items table:

original dataset

```<code>date    item    price
1/1/2018    toys    22.82
1/3/2018    toys    28.99
1/6/2018    toys    32.56
1/2/2018    shoes   41.23
1/4/2018    shoes   62.74
1/10/2018   shoes   35.16
</code>```

I need to fill in missing dates for each item with a NULL price so then I can estimate it
so I want this result:
result wanted

```<code>date    item    price
1/1/2018    toys    22.82
1/2/2018    toys    NULL
1/3/2018    toys    28.99
1/4/2018    toys    NULL
1/5/2018    toys    NULL
1/6/2018    toys    32.56
1/2/2018    shoes   41.23
1/3/2018    shoes   NULL
1/4/2018    shoes   62.74
1/5/2018    shoes   NULL
1/6/2018    shoes   NULL
1/7/2018    shoes   NULL
1/8/2018    shoes   NULL
1/9/2018    shoes   NULL
1/10/2018   shoes   35.16
</code>```

I have tried the following:

```<code>    select c.day, e.item, e.price
from db.days c cross join
     (select distinct item from db.items e)
     left join
     db.items e
     on c.day = e.date_added;
</code>```

It gives me the following:
result

```<code>date    item    price
1/1/2018    NULL    NULL
1/2/2018    NULL    NULL
1/3/2018    NULL    NULL
1/4/2018    NULL    NULL
1/5/2018    NULL    NULL
1/6/2018    NULL    NULL
1/2/2018    NULL    NULL
1/3/2018    NULL    NULL
1/4/2018    NULL    NULL
1/5/2018    NULL    NULL
1/6/2018    NULL    NULL
1/7/2018    NULL    NULL
1/8/2018    NULL    NULL
1/9/2018    NULL    NULL
1/10/2018   NULL    NULL
</code>```

How can I get rid of the NULLs and get my desired result above? I am using SQLite Studio

答:
You can use a recursive cte:

```<code>with recursive cte(d) as (
   select min(date) from toys
   union all
   select date(c.d, '+1 day') from cte c where c.d < (select max(date) from toys)
)
select c.d, t1.item, t4.price from cte c
cross join (select distinct t.item from toys t) t1
left join toys t4 on t4.date = c.d and t4.item = t1.item
where c.d <= (select max(t3.date) from toys t3 where t3.item = t1.item) and c.d >= (select min(t3.date) from toys t3 where t3.item = t1.item)
</code>```

Body:
I am trying to join a table of dates to an existing table of items.  I want to add the missing dates for each item see items table:

original dataset

date    item    price
1/1/2018    toys    22.82
1/3/2018    toys    28.99
1/6/2018    toys    32.56
1/2/2018    shoes   41.23
1/4/2018    shoes   62.74
1/10/2018   shoes   35.16

I need to fill in missing dates for each item with a NULL price so then I can estimate it
so I want this result:
result wanted

date    item    price
1/1/2018    toys    22.82
1/2/2018    toys    NULL
1/3/2018    toys    28.99
1/4/2018    toys    NULL
1/5/2018    toys    NULL
1/6/2018    toys    32.56
1/2/2018    shoes   41.23
1/3/2018    shoes   NULL
1/4/2018    shoes   62.74
1/5/2018    shoes   NULL
1/6/2018    shoes   NULL
1/7/2018    shoes   NULL
1/8/2018    shoes   NULL
1/9/2018    shoes   NULL
1/10/2018   shoes   35.16

I have tried the following:

    select c.day, e.item, e.price
from db.days c cross join
     (select distinct item from db.items e)
     left join
     db.items e
     on c.day = e.date_added;

It gives me the following:
result

date    item    price
1/1/2018    NULL    NULL
1/2/2018    NULL    NULL
1/3/2018    NULL    NULL
1/4/2018    NULL    NULL
1/5/2018    NULL    NULL
1/6/2018    NULL    NULL
1/2/2018    NULL    NULL
1/3/2018    NULL    NULL
1/4/2018    NULL    NULL
1/5/2018    NULL    NULL
1/6/2018    NULL    NULL
1/7/2018    NULL    NULL
1/8/2018    NULL    NULL
1/9/2018    NULL    NULL
1/10/2018   NULL    NULL

How can I get rid of the NULLs and get my desired result above? I am using SQLite Studio

Body:
You can use a recursive cte:

with recursive cte(d) as (
   select min(date) from toys
   union all
   select date(c.d, '+1 day') from cte c where c.d < (select max(date) from toys)
)
select c.d, t1.item, t4.price from cte c
cross join (select distinct t.item from toys t) t1
left join toys t4 on t4.date = c.d and t4.item = t1.item
where c.d <= (select max(t3.date) from toys t3 where t3.item = t1.item) and c.d >= (select min(t3.date) from toys t3 where t3.item = t1.item)


问:
Flutter: Scrolling to a widget in ListView
How can I scroll to a special widget in a ListView?
For instance I want to scroll automatically to some Container in the ListView if I press a specific button.

```<code>ListView(children: <Widget>[
  Container(...),
  Container(...), #scroll for example to this container
  Container(...)
]);
</code>```

答:
This solution improves upon other answers as it does not require hard-coding each elements' heights. Adding ScrollPosition.viewportDimension and ScrollPosition.maxScrollExtent yields the full content height. This can be used to estimate the position of an element at some index. If all elements are the same height, the estimation is perfect.

// Get the full content height.
final contentSize = controller.position.viewportDimension + controller.position.maxScrollExtent;
// Index to scroll to.
final index = 100;
// Estimate the target scroll position.
final target = contentSize * index / itemCount;
// Scroll to that position.
controller.position.animateTo(
  target,
  duration: const Duration(seconds: 2),
  curve: Curves.easeInOut,
);
```
<p>And a full example:</p>
<p><img src="https://i.stack.imgur.com/jdZPT.gif" alt="user clicks a button to scroll to the one hundredth element of a long list" /></p>
<pre class="lang-dart prettyprint-override"><code>import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Flutter Test",
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final controller = ScrollController();
    final itemCount = 1000;
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Test"),
      ),
      body: Column(
        children: [
          ElevatedButton(
            child: Text("Scroll to 100th element"),
            onPressed: () {
              final contentSize = controller.position.viewportDimension + controller.position.maxScrollExtent;
              final index = 100;
              final target = contentSize * index / itemCount;
              controller.position.animateTo(
                target,
                duration: const Duration(seconds: 2),
                curve: Curves.easeInOut,
              );
            },
          ),
          Expanded(
            child: ListView.builder(
              controller: controller,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text("Item at index $index."),
                );
              },
              itemCount: itemCount,
            ),
          )
        ],
      ),
    );
  }
}

</code>```

Body:
How can I scroll to a special widget in a ListView?
For instance I want to scroll automatically to some Container in the ListView if I press a specific button.

ListView(children: <Widget>[
  Container(...),
  Container(...), #scroll for example to this container
  Container(...)
]);

Body:
This solution improves upon other answers as it does not require hard-coding each elements' heights. Adding ScrollPosition.viewportDimension and ScrollPosition.maxScrollExtent yields the full content height. This can be used to estimate the position of an element at some index. If all elements are the same height, the estimation is perfect.

// Get the full content height.
final contentSize = controller.position.viewportDimension + controller.position.maxScrollExtent;
// Index to scroll to.
final index = 100;
// Estimate the target scroll position.
final target = contentSize * index / itemCount;
// Scroll to that position.
controller.position.animateTo(
  target,
  duration: const Duration(seconds: 2),
  curve: Curves.easeInOut,
);

And a full example:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Flutter Test",
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final controller = ScrollController();
    final itemCount = 1000;
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Test"),
      ),
      body: Column(
        children: [
          ElevatedButton(
            child: Text("Scroll to 100th element"),
            onPressed: () {
              final contentSize = controller.position.viewportDimension + controller.position.maxScrollExtent;
              final index = 100;
              final target = contentSize * index / itemCount;
              controller.position.animateTo(
                target,
                duration: const Duration(seconds: 2),
                curve: Curves.easeInOut,
              );
            },
          ),
          Expanded(
            child: ListView.builder(
              controller: controller,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text("Item at index $index."),
                );
              },
              itemCount: itemCount,
            ),
          )
        ],
      ),
    );
  }
}


问:
ASP.NET - Problem with authentication: Manually added claim is missing in the next request
I am currently experimenting with external login providers like Google Authentication in my ASP.NET application.

As you can see on my Program.cs i'am running .NET6.

After the Google-Login was successfull, the ClaimsPrincipal has exactly one ClaimsIdentity (IsAuthenticated == true). Now I want to add my own 'Custom-Claim' to this identity. The addition works without any problems, but the next request is missing the custom claim (all other claims by Google are there).

Here is the part of my Program.cs where I add the authentication:

```<code>builder.Services.AddAuthentication(x =>
{
    x.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogle(GoogleDefaults.AuthenticationScheme, o =>
{
    o.ClientId = builder.Configuration["Authentication:Google:ClientId"];
    o.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"];
    o.ClaimActions.MapJsonKey("urn:google:picture","picture","url");
});
</code>```

Here is the configuration of the middleware pipeline in Program.cs:

```<code>app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();

app.Use((httpContext, func) =>
{
    if (httpContext.Request.Path.StartsWithSegments("/api"))
        httpContext.Request.Headers[HeaderNames.XRequestedWith] = "XMLHttpRequest";

    return func();
});

app.UseRouting();
app.MapRazorPages();
app.MapControllers();
</code>```

Endpoint for Google Login:

```<code>[HttpGet]
[Route("GoogleSignIn")]
public async Task GoogleSignIn()
{
    await HttpContext.ChallengeAsync(GoogleDefaults.AuthenticationScheme,
        new AuthenticationProperties {RedirectUri =Url.Action("GoogleResponse")});
}
</code>```

In the "GoogleResponse" method i add the mentioned custom claim:

```<code>//this method gets called after the google login has finished
public async Task<IActionResult> GoogleResponse()
{
    var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);

    var identity = result.Principal.Identities.FirstOrDefault();
    var currentSidClaim = identity.FindFirst(x => x.Type == ClaimTypes.Sid);

    if (currentSidClaim != null)
        identity.RemoveClaim(currentSidClaim);

    identity.AddClaim(new Claim(ClaimTypes.Sid, "Hi i am some claim, but i'll miss on the next request :("));

    return Redirect("/");
}
</code>```

ClaimsIdentity after adding the claim:

[https://i.stack.imgur.com/INdGy.png]

ClaimsIdentity on the next request (in the same controller btw):

[https://i.stack.imgur.com/oft3e.png]

Whether I access the identity via "User.Identity" or "HttpContext.User..." makes no difference.

Really hope somebody can clear things up for me.

I hope I don't have to implement a large / elaborate ASP.NET Identity solution to solve the problem. I would be happy with a lightweight authentication.

UPDATE:

After some further tests it looks like it is not necessarily related to the specific Google login. Even if I create a second identity at login, it is gone at the next request.

I guess the authentication cookie is not updated.

Thanks in advance!

答: Try to add claims after callback from the external website. As described here</p>

Body:
I am currently experimenting with external login providers like Google Authentication in my ASP.NET application.

As you can see on my Program.cs i'am running .NET6.

After the Google-Login was successfull, the ClaimsPrincipal has exactly one ClaimsIdentity (IsAuthenticated == true). Now I want to add my own 'Custom-Claim' to this identity. The addition works without any problems, but the next request is missing the custom claim (all other claims by Google are there).

Here is the part of my Program.cs where I add the authentication:

builder.Services.AddAuthentication(x =>
{
    x.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogle(GoogleDefaults.AuthenticationScheme, o =>
{
    o.ClientId = builder.Configuration["Authentication:Google:ClientId"];
    o.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"];
    o.ClaimActions.MapJsonKey("urn:google:picture","picture","url");
});

Here is the configuration of the middleware pipeline in Program.cs:

app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();

app.Use((httpContext, func) =>
{
    if (httpContext.Request.Path.StartsWithSegments("/api"))
        httpContext.Request.Headers[HeaderNames.XRequestedWith] = "XMLHttpRequest";

    return func();
});

app.UseRouting();
app.MapRazorPages();
app.MapControllers();

Endpoint for Google Login:

[HttpGet]
[Route("GoogleSignIn")]
public async Task GoogleSignIn()
{
    await HttpContext.ChallengeAsync(GoogleDefaults.AuthenticationScheme,
        new AuthenticationProperties {RedirectUri =Url.Action("GoogleResponse")});
}

In the "GoogleResponse" method i add the mentioned custom claim:

//this method gets called after the google login has finished
public async Task<IActionResult> GoogleResponse()
{
    var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);

    var identity = result.Principal.Identities.FirstOrDefault();
    var currentSidClaim = identity.FindFirst(x => x.Type == ClaimTypes.Sid);

    if (currentSidClaim != null)
        identity.RemoveClaim(currentSidClaim);

    identity.AddClaim(new Claim(ClaimTypes.Sid, "Hi i am some claim, but i'll miss on the next request :("));

    return Redirect("/");
}

ClaimsIdentity after adding the claim:

[https://i.stack.imgur.com/INdGy.png]

ClaimsIdentity on the next request (in the same controller btw):

[https://i.stack.imgur.com/oft3e.png]

Whether I access the identity via "User.Identity" or "HttpContext.User..." makes no difference.

Really hope somebody can clear things up for me.

I hope I don't have to implement a large / elaborate ASP.NET Identity solution to solve the problem. I would be happy with a lightweight authentication.

UPDATE:

After some further tests it looks like it is not necessarily related to the specific Google login. Even if I create a second identity at login, it is gone at the next request.

I guess the authentication cookie is not updated.

Thanks in advance!


问:
List ALL Files on iPhone
in Objective C how would I get a list of ALL files on the iPhone?

is this even possible or can I only get files from a certain directory or known path?

答: Not without jail-breaking your phone. All apps live in a sandbox and can only see certain files.</p>

Title: List ALL Files on iPhone


问:
How to use client.on in a JavaScript function?
I am currently using discord.js to develop a discord bot. I wanted to create a function to send a message based on user input.

The code I have is as follows:

```<code>function myFunction(keyWord) {
   client.on("messageCreate", myMessage => {
   if (myMessage.content.bot) {
      return
   }
   myMessage.channel.send(keyWord)
   })
}
</code>```

When I run this function in my code, the code seems to stop at the client.on section. It does not throw an error, it simply does not send the message or run any code beyond the client.on.

I appreciate any help!

答:
myMessage.content returns a string; you are reading it as an object.

If you want to check if the author is a bot, you would read message.author.bot.

Try the following:

function myFunction(keyWord) {
  client.on('messageCreate', (myMessage) => {
    if (myMessage.author.bot)
      return;

    myMessage.channel.send(keyWord);
  });
}

```

Body:
I am currently using discord.js to develop a discord bot. I wanted to create a function to send a message based on user input.

The code I have is as follows:

function myFunction(keyWord) {
   client.on("messageCreate", myMessage => {
   if (myMessage.content.bot) {
      return
   }
   myMessage.channel.send(keyWord)
   })
}

When I run this function in my code, the code seems to stop at the client.on section. It does not throw an error, it simply does not send the message or run any code beyond the client.on.

I appreciate any help!


问:
The document \"<?xml version='1.0'?>\\n\" does not have a valid root
I am new to parsing the xml in the ruby and I am stuck with an issue. I'll try my best to explain.
I get the below response from an api

```<code>"PK\x03\x04\x14\x00\b\b\b\x00,\x18ET\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1D\x00\x00\x00"
</code>```

I believe it is .tds format.
I am trying to parse it into a valid xml so this is what I tried.

xml = Nokogiri::XML(response)
which gives me #<Nokogiri::XML::Document:0xf744 name="document">

Then I tried to do Hash.from_xml(xml.to_xml)

But this throws error The document \"<?xml version='1.0'?>\\n\" does not have a valid root

Any idea what am I missing here?

答:
This string starts with "PK", which are initials of Phil Katz, author of the ZIP format. Which means it's a ZIP file. There are certain formats that are ZIP files, but actually follow some further structure conventions, like Java JAR files, but also all OpenDocument formats like .ods, .odt and all MS Office Open XML formats.

Since you are probably expecting an .ods file... While you could unzip it and then use Nokogiri to parse the XML, there's a better way to proceed.

There's an interesting Gem called Roo, that supports all most common spreadsheet formats and produces a nice Ruby API to deal with them: https://github.com/roo-rb/roo

I would recommend you to save the string to a temporary file and then open it with Roo.

Body:
I am new to parsing the xml in the ruby and I am stuck with an issue. I'll try my best to explain.
I get the below response from an api

"PK\x03\x04\x14\x00\b\b\b\x00,\x18ET\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1D\x00\x00\x00"

I believe it is .tds format.
I am trying to parse it into a valid xml so this is what I tried.

xml = Nokogiri::XML(response)
which gives me #<Nokogiri::XML::Document:0xf744 name="document">

Then I tried to do Hash.from_xml(xml.to_xml)

But this throws error The document \"<?xml version='1.0'?>\\n\" does not have a valid root

Any idea what am I missing here?


问:
Can't hide modal within Layout (wrapper) component
I'm trying to hide the shopping cart modal of an e-commerce store that I'm trying to build on React. When I try to follow the code in the tutorial, the cart modal window does not hide from the display and just remains there in front of all the other components. There's no error that displays btw.  I'm using a wrapper component with the name of Layout here.

Karte.js - the main cart component

```<code>import { useState, React } from "react";
import Modal from "./Modal";

export default function Karte(props) {
  const [cartIsOpen, setCartIsOpen] = useState(false);

  function functionName() {
    setCartIsOpen(true);
  }

  const cartItems = (
    <ul>
      {[{ id: "i1", name: "Ralph Lauren", amount: 3, price: 14.99 }].map(
        (item) => (
          <li key={item.id}>
            {item.name}
            {item.price}
          </li>
        )
      )}
    </ul>
  );

  return (
    <Modal>
      {cartItems}
      <div>
        <span>Total Amount</span>
        <span>35.54</span>
      </div>
      <div>
        <button onClick={functionName}>Close</button>
        <button>Checkout</button>
      </div>
    </Modal>
  );
}
</code>```

This is the Modal component code

```<code>const Modal = (props) => {
  return <div className="modal">{props.children}</div>;
};

export default Modal;
</code>```

Lastly, this is the Wrapper component (that the modal is a child component of)

```<code>import { useState, React } from "react";
import NavBar from "../NavBar";
import Modal from "../Modal";
import Backdrop from "../Backdrop";

export default function Layout(props) {
  const [cartIsOpen, setCartIsOpen] = useState(false);

  function functionName() {
    setCartIsOpen(true);
  }
  return (
    <div>
      <NavBar />
      <main>{props.children}</main>
      {cartIsOpen && <Modal />}
      <Backdrop />
    </div>
  );
}
</code>```

If it means anything, this is the App component too

```<code>function App() {
  return (
    <Layout>
      <Karte />
      <Routes>
        <Route path="/" element={<HomePage />} exact />
        <Route path="/checkout" element={<CheckoutPage />} />
        <Route path="/cart" element={<CartPage />} />
        <Route path="/login" element={<LoginPage />} />
        <Route path="/sale" element={<SalePage />} />
        <Route path="/faqs" element={<FaqsPage />} />
      </Routes>
    </Layout>
  );
}

export default App;
</code>```

答:
The good news is there are multiple ways to solve this. The main 2 options I'd consider are:

1. You could move your useState into App, and pass a toggleCart callback to Layout

App.js:

function App() {
  const [cartVisible, setCardVisible] = useState(false)

  return (
    <Layout onToggleCart={() => setCartVisible(!cartVisible)}>
      {cartVisible ? <Karte /> : null}
      <Routes>
        ...
      </Routes>
    </Layout>
  );
}
```
<h2>2. You could render <code>Karte</code> from <code>Layout</code></h2>
<p>Layout.js:</p>
<pre class="lang-js prettyprint-override"><code>import { useState, React } from "react";
import NavBar from "../NavBar";
import Modal from "../Modal";
import Backdrop from "../Backdrop";

export default function Layout(props) {
  const [cartIsOpen, setCartIsOpen] = useState(false);

  function functionName() {
    setCartIsOpen(true);
  }
  return (
    <>
      <div>
        <NavBar />
        <main>{props.children}</main>
        {cartIsOpen && <Modal />}
        <Backdrop />
      </div>
      {cartIsOpen ? <Karte /> : null}
    </>
  );
}
</code>```

And remove <Karte /> from App.js

Body:
I'm trying to hide the shopping cart modal of an e-commerce store that I'm trying to build on React. When I try to follow the code in the tutorial, the cart modal window does not hide from the display and just remains there in front of all the other components. There's no error that displays btw.  I'm using a wrapper component with the name of Layout here.

Karte.js - the main cart component

import { useState, React } from "react";
import Modal from "./Modal";

export default function Karte(props) {
  const [cartIsOpen, setCartIsOpen] = useState(false);

  function functionName() {
    setCartIsOpen(true);
  }

  const cartItems = (

      {[{ id: "i1", name: "Ralph Lauren", amount: 3, price: 14.99 }].map(
        (item) => (

            {item.name}
            {item.price}

        )
      )}

  );

  return (
    <Modal>
      {cartItems}

        Total Amount
        35.54

        <button onClick={functionName}>Close</button>
        <button>Checkout</button>

    </Modal>
  );
}

This is the Modal component code

const Modal = (props) => {
  return
{props.children}
;
};

export default Modal;

Lastly, this is the Wrapper component (that the modal is a child component of)

import { useState, React } from "react";
import NavBar from "../NavBar";
import Modal from "../Modal";
import Backdrop from "../Backdrop";

export default function Layout(props) {
  const [cartIsOpen, setCartIsOpen] = useState(false);

  function functionName() {
    setCartIsOpen(true);
  }
  return (

      <NavBar />
      {props.children}
      {cartIsOpen && <Modal />}
      <Backdrop />

  );
}

If it means anything, this is the App component too

function App() {
  return (
    <Layout>
      <Karte />
      <Routes>
        <Route path="/" element={<HomePage />} exact />
        <Route path="/checkout" element={<CheckoutPage />} />
        <Route path="/cart" element={<CartPage />} />
        <Route path="/login" element={<LoginPage />} />
        <Route path="/sale" element={<SalePage />} />
        <Route path="/faqs" element={<FaqsPage />} />
      </Routes>
    </Layout>
  );
}

export default App;

Body:
The good news is there are multiple ways to solve this. The main 2 options I'd consider are:

1. You could move your useState into App, and pass a toggleCart callback to Layout

App.js:

function App() {
  const [cartVisible, setCardVisible] = useState(false)

  return (
    <Layout onToggleCart={() => setCartVisible(!cartVisible)}>
      {cartVisible ? <Karte /> : null}
      <Routes>
        ...
      </Routes>
    </Layout>
  );
}

2. You could render Karte from Layout

Layout.js:

import { useState, React } from "react";
import NavBar from "../NavBar";
import Modal from "../Modal";
import Backdrop from "../Backdrop";

export default function Layout(props) {
  const [cartIsOpen, setCartIsOpen] = useState(false);

  function functionName() {
    setCartIsOpen(true);
  }
  return (
    <>
      <div>
        <NavBar />
        <main>{props.children}</main>
        {cartIsOpen && <Modal />}
        <Backdrop />
      </div>
      {cartIsOpen ? <Karte /> : null}
    </>
  );
}

And remove <Karte /> from App.js


问:
How can Java remove leading whitespace?
I have been trying to figure out why this Java code won't delete any leading whitespace to my actual string, I have been trying to use stripLeading() method and the trim(); method, and various other methods with the same functionality but still haven't gotten a favorable outcome. Code:

```<code>public static String message(String logLine) {
         logLine = (String) logLine.subSequence(logLine.indexOf(" ") + 1, logLine.length());
         return logLine;
         }
public static void main(String[] args) {

        System.out.println(message("[WARNING]:   \tTimezone not set  \r\n"));
    }
</code>```

What results is what I wanted, just the words "Timezone not set" however I want this program to completely ignore leading whitespace, which for some reason it can't. Thank you for any help.

答:
Possible solutions

Use String::replaceFirst to keep only the part after a prefix ([WARNING]:) followed by whitespaces and the main part:

public static String message(String logLine) {
    return logLine.replaceFirst("^\\S*\\s+(\\S+(\\s+\\S+)*)\\s+$", "$1");
}
```
</li>
<li><p>As the prefix ends with <code>':'</code>, a solution offered in the comment using <code>String::substring</code> + <code>String::trim</code> works too:</p>
<pre class="lang-java prettyprint-override"><code>public static String message(String logLine) {
    return logLine.substring(logLine.indexOf(":") + 1).trim();
}
</code>```

Title: How can Java remove leading whitespace?

Body:
I have been trying to figure out why this Java code won't delete any leading whitespace to my actual string, I have been trying to use stripLeading() method and the trim(); method, and various other methods with the same functionality but still haven't gotten a favorable outcome. Code:

public static String message(String logLine) {
         logLine = (String) logLine.subSequence(logLine.indexOf(" ") + 1, logLine.length());
         return logLine;
         }
public static void main(String[] args) {

        System.out.println(message("[WARNING]:   \tTimezone not set  \r\n"));
    }

What results is what I wanted, just the words "Timezone not set" however I want this program to completely ignore leading whitespace, which for some reason it can't. Thank you for any help.

Body:
Possible solutions

Use String::replaceFirst to keep only the part after a prefix ([WARNING]:) followed by whitespaces and the main part:

public static String message(String logLine) {
    return logLine.replaceFirst("^\\S*\\s+(\\S+(\\s+\\S+)*)\\s+$", "$1");
}

As the prefix ends with ':', a solution offered in the comment using String::substring + String::trim works too:

public static String message(String logLine) {
    return logLine.substring(logLine.indexOf(":") + 1).trim();
}


问:
How to presist a cookie with universal-cookie
I used this to set a cookie in my react application. It expires with hte session though. How can I store this cookie so it lasts beyond the session so it remains if the browser is closed and reopened?</p>
```<code>export default function App() {

  const [classnameTr,setClassname] = useState<string>("checkbox-row1");
  const [classnameLabel, setClassnameLabel] = useState<string>("my-label-black");
  const cookies = new Cookies();

  function setCookie() {
    cookies.set('certDiscCookie', 'certDiscCookieSet', { path: '/' });
    console.log("Cookies: " + cookies.get('certDiscCookie'));
  }

  function getCookie() {
    if (cookies.get('certDiscCookie') === "certDiscCookieSet") {
      setColor();
    }
  }

  return (
    <div className="App">
      <header className="App-header">
        <div className="checkbox-div">
          <table className="checkbox-table">
            <tbody>
                <td className="tr2-td2"><button className="certDiscButtonSet" onClick={() => setCookie()}>Set Cookie</button></td>
                <td className="tr3-td3"><button className="certDiscButtonGet" onClick={() => getCookie()}>Get Cookie</button></td>
              </tr>
            </tbody>
          </table>
        </div>
      </header>
    </div>
  );
}
</code>```

答: If you don't set expires option it's gonna work similar to original cookies.set() option - it becomes session cookie. You have to set some time after which it expires. If you do that it will remain after you restart the browser. There is no way to make it live forever. You can just set the date far into the future.

Body:
I used this to set a cookie in my react application. It expires with hte session though. How can I store this cookie so it lasts beyond the session so it remains if the browser is closed and reopened?

export default function App() {

  const [classnameTr,setClassname] = useState<string>("checkbox-row1");
  const [classnameLabel, setClassnameLabel] = useState<string>("my-label-black");
  const cookies = new Cookies();

  function setCookie() {
    cookies.set('certDiscCookie', 'certDiscCookieSet', { path: '/' });
    console.log("Cookies: " + cookies.get('certDiscCookie'));
  }

  function getCookie() {
    if (cookies.get('certDiscCookie') === "certDiscCookieSet") {
      setColor();
    }
  }

  return (

                <button className="certDiscButtonSet" onClick={() => setCookie()}>Set Cookie</button>
                <button className="certDiscButtonGet" onClick={() => getCookie()}>Get Cookie</button>

  );
}