问:
PHP Session doesn't get, header don't redirect, blank page
i can't connect to my site, when i put this code in login.php page i obtain a blank page when i submit the form with correct informations on the index.php page,
but when I enter a false e-mail address or a bad password I have the errors but I am not redirected.
And the session does not register because even if I have a blank page (header that does not redirect), I have no information to retrieve from my session during calls such as an echo of a first name linked to one of the tables sql, earlier my code was working fine but I had to touch a few things and since then I can't connect anymore

Thank's you, Sincerely.

```<code> <?php
    // Connexion à la base de données
    require 'database.php';

    // Démarrage de la session
    session_start();

    // Récupération des données du formulaire
    $email = htmlspecialchars($_POST['email'], ENT_QUOTES);
    $password = htmlspecialchars($_POST['password'], ENT_QUOTES);

    // Vérification de l'existance de l'utilisateur
    $sql = "SELECT * FROM utilisateurs WHERE email='$email'";
    $result = mysqli_query($conn, $sql);
    if (mysqli_num_rows($result) == 0) {
      // Affichage d'un message d'erreur
      echo '<div class="alert alert-danger" role="alert">Erreur : utilisateur inexistant.</div>';
      echo "<meta http-equiv='refresh' content='5;url=index.php?modal=loginModal'>";
    } else {
      // Récupération du mot de passe hashé de l'utilisateur
      $utilisateur = mysqli_fetch_assoc($result);
      $password_hashed = $utilisateur['password'];

      // Vérification du mot de passe
      if (password_verify($password, $password_hashed)) {

        // Enregistrement de l'utilisateur dans la session
        $_SESSION['utilisateur'] = $utilisateur;

        // Redirection vers la page d'accueil
        header("Location: index.php");
      } else {
        // Affichage d'un message d'erreur
        echo '<div class="alert alert-danger" role="alert">Erreur : mot de passe incorrect.</div>';
        echo "<meta http-equiv='refresh' content='5;url=index.php?modal=loginModal'>";
      }
    }

    // Fermeture de la connexion à la base de données
    mysqli_close($conn);
    ?>
</code>```

Body:
i can't connect to my site, when i put this code in login.php page i obtain a blank page when i submit the form with correct informations on the index.php page,
but when I enter a false e-mail address or a bad password I have the errors but I am not redirected.
And the session does not register because even if I have a blank page (header that does not redirect), I have no information to retrieve from my session during calls such as an echo of a first name linked to one of the tables sql, earlier my code was working fine but I had to touch a few things and since then I can't connect anymore

Thank's you, Sincerely.

 <?php
    // Connexion à la base de données
    require 'database.php';

    // Démarrage de la session
    session_start();

    // Récupération des données du formulaire
    $email = htmlspecialchars($_POST['email'], ENT_QUOTES);
    $password = htmlspecialchars($_POST['password'], ENT_QUOTES);

    // Vérification de l'existance de l'utilisateur
    $sql = "SELECT * FROM utilisateurs WHERE email='$email'";
    $result = mysqli_query($conn, $sql);
    if (mysqli_num_rows($result) == 0) {
      // Affichage d'un message d'erreur
      echo '
Erreur : utilisateur inexistant.
';
      echo "<meta http-equiv='refresh' content='5;url=index.php?modal=loginModal'>";
    } else {
      // Récupération du mot de passe hashé de l'utilisateur
      $utilisateur = mysqli_fetch_assoc($result);
      $password_hashed = $utilisateur['password'];

      // Vérification du mot de passe
      if (password_verify($password, $password_hashed)) {

        // Enregistrement de l'utilisateur dans la session
        $_SESSION['utilisateur'] = $utilisateur;

        // Redirection vers la page d'accueil
        header("Location: index.php");
      } else {
        // Affichage d'un message d'erreur
        echo '
Erreur : mot de passe incorrect.
';
        echo "<meta http-equiv='refresh' content='5;url=index.php?modal=loginModal'>";
      }
    }

    // Fermeture de la connexion à la base de données
    mysqli_close($conn);
    ?>


来源: stackexchange

问:
Menu Submenu with PHP Classes and Objects
I need to make a menu with a submenu. Menu 'id' => 'parent1' = submenu 'parent' => 'parent1'.
If parent has no child echo only parent. If parent has childrens insert all children inside parent. Maybe try with a for loop, or some other solution?

If a child exists, each submenu child should be inserted in its parent by id. How?

The code example should echo:

```<code><div class="menu" href="myurl">Parent 1
     <div class="submenu" href="myurl">Child 1</div>
     <div class="submenu" href="myurl">Child 2</div>
</div>
<div class="menu" href="myurl">Parent 2
     <div class="submenu" href="myurl">Child 3</div>
</div>
</code>```
```<code>class menu  {
    public $id;
    public $parent;
    public $name;
    public $url;

    public function add_node($args) {
    echo '
     <div class="menu" href="' . $args['url'] . '">' . $args['name'] . '

         <div class="submenu" href="' . $args['url'] . '">' . $args['name'] . '</div>

     </div>';
    }
}

if (class_exists('menu')){
     global $menu;
     $menu = new menu();
}

function menu_parent_child(){
    $args = array(
    'id' => 'parent1',
    'name' => 'Parent 1',
    'url' => 'myurl'
    );

    $args = array(
    'parent' => 'parent1',
    'name' => 'Child 1',
    'url' => 'myurl'
    );

    $args = array(
    'parent' => 'parent1',
    'name' => 'Child 2',
    'url' => 'myurl'
    );

    $args = array(
    'id' => 'parent2',
    'name' => 'Parent 2',
    'url' => 'myurl'
    );

    $args = array(
    'parent' => 'parent2',
    'name' => 'Child 3',
    'url' => 'myurl'
    );
}

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to make a menu with a submenu. Menu 'id' => 'parent1' = submenu 'parent' => 'parent1'.
If parent has no child echo only parent. If parent has childrens insert all children inside parent. Maybe try with a for loop, or some other solution?

If a child exists, each submenu child should be inserted in its parent by id. How?

The code example should echo:

Parent 1

Child 1

Child 2

Parent 2

Child 3

class menu  {
    public $id;
    public $parent;
    public $name;
    public $url;

    public function add_node($args) {
    echo '

' . $args['name'] . '

' . $args['name'] . '

';
    }
}

if (class_exists('menu')){
     global $menu;
     $menu = new menu();
}

function menu_parent_child(){
    $args = array(
    'id' => 'parent1',
    'name' => 'Parent 1',
    'url' => 'myurl'
    );

    $args = array(
    'parent' => 'parent1',
    'name' => 'Child 1',
    'url' => 'myurl'
    );

    $args = array(
    'parent' => 'parent1',
    'name' => 'Child 2',
    'url' => 'myurl'
    );

    $args = array(
    'id' => 'parent2',
    'name' => 'Parent 2',
    'url' => 'myurl'
    );

    $args = array(
    'parent' => 'parent2',
    'name' => 'Child 3',
    'url' => 'myurl'
    );
}


问:
XML Schema "maxOccurs"
I have a question about using "minOccurs" and "maxOccurs". when I insert "unbounded" in "maxOccurs", in which constructor element should be inserted "sequence"? In the root?
Thanks

I put "sequence" in the reference element.Is it wrong?

Title: XML Schema "maxOccurs"


问:
ipyleaflet does not render layers on jupyter lab
I've installed ipyleaflet in jupyter lab using based on the following guide: https://ipyleaflet.readthedocs.io/en/latest/installation/index.html#jupyterlab-extension

The following code executes, the map is shown correctly but the layers (in this case one Marker) are not showing up.

```<code>from ipyleaflet import Map, Marker
center = [21.501558, 39.184964]
m = Map(center=center, zoom=15)
marker = Marker(location=center, draggable=True)
m.add_layer(marker)
display(m)
</code>```

The browser console shows the following warnings:

```<code>Failed to fetch ipywidgets through the "jupyter.widget.control" comm channel, fallback to fetching individual model state. Reason: Control comm was closed too early
_loadFromKernel
Could not create a view for model id ...
</code>```

Followed by an error:

```<code>Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '_layerAdd')
    at e.addLayer (leaflet-src.js:6889:16)
    at 138.69ef2a39232f5de9d78a.js?v=69ef2a39232f5de9d78a:1:39625
    at async Promise.all (index 1)
</code>```

What could be the reason for layers not showing up on the correctly rendered map?

Body:
I've installed ipyleaflet in jupyter lab using based on the following guide: https://ipyleaflet.readthedocs.io/en/latest/installation/index.html#jupyterlab-extension

The following code executes, the map is shown correctly but the layers (in this case one Marker) are not showing up.

from ipyleaflet import Map, Marker
center = [21.501558, 39.184964]
m = Map(center=center, zoom=15)
marker = Marker(location=center, draggable=True)
m.add_layer(marker)
display(m)

The browser console shows the following warnings:

Failed to fetch ipywidgets through the "jupyter.widget.control" comm channel, fallback to fetching individual model state. Reason: Control comm was closed too early
_loadFromKernel
Could not create a view for model id ...

Followed by an error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '_layerAdd')
    at e.addLayer (leaflet-src.js:6889:16)
    at 138.69ef2a39232f5de9d78a.js?v=69ef2a39232f5de9d78a:1:39625
    at async Promise.all (index 1)

What could be the reason for layers not showing up on the correctly rendered map?


问:
Can inflect.engine() be used to change simple verbs into their singular form, e.g. have to has?
I am using the inflect module in Python to change across plurals to singular and vice versa. This works great for nouns (houses->house). However, I am having some trouble to change a simple "have" into "has".

For example,

```<code>import inflect
pdi = inflect.engine()
print(pdi.singular_noun("have"))
>>have
pdi.gender("neuter")
print(pdi.singular_noun("have"))
>>have
</code>```

However, other functions seem to be okay, e.g.

```<code>pdi.present_participle("have")
>>having
</code>```

I'd be surprised if inflect cannont change a simple have into has. I scanned the documentation of it but I can't find the reference to do this.

Either I am missing an argument or parameter or it could be a problem with the version. I am using inflect 5.3.0 but the documentation is for 6.0.2. Strangely, when I type pip install inflect==6.0.2 it shows no matching distribution and that the latest distribution is 5.3.0. NLTK seems to have something similar like inflect, but I don't want to install another big library in my slim app. I wonder what am I missing here?

Body:
I am using the inflect module in Python to change across plurals to singular and vice versa. This works great for nouns (houses->house). However, I am having some trouble to change a simple "have" into "has".

For example,

import inflect
pdi = inflect.engine()
print(pdi.singular_noun("have"))
>>have
pdi.gender("neuter")
print(pdi.singular_noun("have"))
>>have

However, other functions seem to be okay, e.g.

pdi.present_participle("have")
>>having

I'd be surprised if inflect cannont change a simple have into has. I scanned the documentation of it but I can't find the reference to do this.

Either I am missing an argument or parameter or it could be a problem with the version. I am using inflect 5.3.0 but the documentation is for 6.0.2. Strangely, when I type pip install inflect==6.0.2 it shows no matching distribution and that the latest distribution is 5.3.0. NLTK seems to have something similar like inflect, but I don't want to install another big library in my slim app. I wonder what am I missing here?


问:
Change logo for certain Docker hub repository
It should be a simple thing, but I found no possibility to change the logo of a certain docker hub repository.
(I don't mean the docker id logo of the account - this can be bound to gravatar.)

I found only very rare information about this. One of them says, that a verified publisher account is required, but in the hub, there are several OSS repositories which have also a logo.

(I have a Sponsored OSS project, but even there I found no option)

Did I oversee something at all?


问:
Error message for matplotlib: ModuleNotFoundError: No module named 'matplotlib.colorbar'
I get the following error when I try to from matplotlib import pyplot as plt

```<code>" import matplotlib.colorbar as cbar ModuleNotFoundError: No module named 'matplotlib.colorbar'"
</code>```

Happens with a file holding just the one line of code, as well as in code which ran
yesterday.

I have tried an alternate import form: import matplotlib.pypot as plt.
Tried to think of ways to avoid trying to import colorbar, which I don't need

Body:
I get the following error when I try to from matplotlib import pyplot as plt

" import matplotlib.colorbar as cbar ModuleNotFoundError: No module named 'matplotlib.colorbar'"

Happens with a file holding just the one line of code, as well as in code which ran
yesterday.

I have tried an alternate import form: import matplotlib.pypot as plt.
Tried to think of ways to avoid trying to import colorbar, which I don't need


问:
Uncaught ReferenceError: validateProduct is not defined at HTMLFormElement.onsubmit
I wrote a JS script for a form in a jsp Page.
When I submit the form, console show this: Uncaught ReferenceError: validateProduct is not defined at HTMLFormElement.onsubmit

JS File has others functions which works, only validateProduct() function doesn't work.

I show you the .js file and just the interested part of .jsp file.

    function css(errore){
    errore.style.textAlign="center";
    errore.style.padding="4% 0 0 2%";
    errore.style.backgroundColor="#fcdde8";
    errore.style.fontFamily="Roboto";
    errore.style.height="35px";
    errore.style.outlineWidth="3px";
    errore.style.outlineColor="#663344";
    errore.style.outlineStyle="solid";
    errore.style.fontSize="15px";
}

$(function(){
    $('#insert').click(
        function(){
        $('#ins').slideToggle('slow');
        });
})

$(function(){
    $('#remove').click(
        function(){
        $('#rem').slideToggle('slow');
        });
})

$(function(){
    $('#modifica').click(
        function(){
        $('#mod').slideToggle('slow');
        });
})

$(function(){
    $('#ordini').click(
        function(){
        $('#scegli1').slideToggle('slow');
        $('#scegli2').slideToggle('slow');
        });
})

$(function(){
    $('#scegli1').click(
        function(){
        $('#oUt').slideToggle('slow');
        });
})

$(function(){
    $('#scegli2').click(
        function(){
        $('#oDate').slideToggle('slow');
        });
})

function validateProduct(){
    var nome=document.getElementById("nome");
    var descrizione=document.getElementById("descrizione");
    var prezzo=document.getElementById("prezzo");
    var errore=document.getElementById("error");

    if(nome.value.length<1 || nome.value.length>100){
        css(errore);
        errore.innerHTML="ERRORE:Inserisci nome correttamente!";
        console.log("Sono caduto in errore nome");
        return false;
    }

    if(descrizione.value.length>300){
        css(errore);
        errore.innerHTML="ERRORE:Inserisci descrizione correttamente!";
        console.log("Sono caduto in errore descrizione");
        return false;
    }

    if(prezzo.value < 0.01){
        css(errore);
        errore.innerHTML="ERRORE:Inserisci prezzo correttamente!";
        console.log("Sono caduto in errore prezzo");
        return false;
    }
    return true;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <body>
    <script src="${pageContext.request.contextPath}/gestione/gestione.js"></script>
//...
<form action="InserisciProdotto" class=ins id="ins" onSubmit="return validateProduct();">
//...
    </form></code>```

Body:
I wrote a JS script for a form in a jsp Page.
When I submit the form, console show this: Uncaught ReferenceError: validateProduct is not defined at HTMLFormElement.onsubmit

JS File has others functions which works, only validateProduct() function doesn't work.

I show you the .js file and just the interested part of .jsp file.

    function css(errore){
    errore.style.textAlign="center";
    errore.style.padding="4% 0 0 2%";
    errore.style.backgroundColor="#fcdde8";
    errore.style.fontFamily="Roboto";
    errore.style.height="35px";
    errore.style.outlineWidth="3px";
    errore.style.outlineColor="#663344";
    errore.style.outlineStyle="solid";
    errore.style.fontSize="15px";
}

$(function(){
    $('#insert').click(
        function(){
        $('#ins').slideToggle('slow');
        });
})

$(function(){
    $('#remove').click(
        function(){
        $('#rem').slideToggle('slow');
        });
})

$(function(){
    $('#modifica').click(
        function(){
        $('#mod').slideToggle('slow');
        });
})

$(function(){
    $('#ordini').click(
        function(){
        $('#scegli1').slideToggle('slow');
        $('#scegli2').slideToggle('slow');
        });
})

$(function(){
    $('#scegli1').click(
        function(){
        $('#oUt').slideToggle('slow');
        });
})

$(function(){
    $('#scegli2').click(
        function(){
        $('#oDate').slideToggle('slow');
        });
})

function validateProduct(){
    var nome=document.getElementById("nome");
    var descrizione=document.getElementById("descrizione");
    var prezzo=document.getElementById("prezzo");
    var errore=document.getElementById("error");

    if(nome.value.length<1 || nome.value.length>100){
        css(errore);
        errore.innerHTML="ERRORE:Inserisci nome correttamente!";
        console.log("Sono caduto in errore nome");
        return false;
    }

    if(descrizione.value.length>300){
        css(errore);
        errore.innerHTML="ERRORE:Inserisci descrizione correttamente!";
        console.log("Sono caduto in errore descrizione");
        return false;
    }

    if(prezzo.value < 0.01){
        css(errore);
        errore.innerHTML="ERRORE:Inserisci prezzo correttamente!";
        console.log("Sono caduto in errore prezzo");
        return false;
    }
    return true;
}

//...
<form action="InserisciProdotto" class=ins id="ins" onSubmit="return validateProduct();">
//...
    </form>


问:
Drag and drop detection on a UI rect
found a script on Github which implements a drag and drop feature in Unity. There, I adapted the code "ImageExample.cs" to my project. It happens that I can't make the drop point detection system work with my UI. The drop point is composed of a empty UI object (only a rect transform and the adapted code), with the actual UI visual elements as it's children.

Already google a bunch of stuff trying to figure out what's the problem, without success. Tested some RectTransformUtility's methods, checked answers like this one or this one(top 2 answers) and etc..

The following method is my adapted version to receive and load the image:

```<code>protected void LoadImage()
{
    if (dropInfo == null)
    {
        Debug.LogError("Information is null!!");
        return;
    }
    Debug.LogError("Rect pos is " + dropRect.position);
    Debug.LogError("Rect transform pos is "+rectTransform.position);
    Debug.LogError("aInfo is " + dropInfo.pos);
    if (dropRect.Contains(dropInfo.pos))
    {
        var data = System.IO.File.ReadAllBytes(dropInfo.file);
        receivedImage = new Texture2D(1, 1);
        receivedImage.LoadImage(data);
        onTextureUpdate(receivedImage);
        onDropInfoUpdate(dropInfo.file);
    }
}
</code>```

Where:

"aInfo" it's assigned as the author's example, just with a single texture instead of array.

"rectTransform" represents the empty UI container, meaning the valid area to receive images.

"dropRect" stands for the "rect" variable inside of "rectTransform"

If I drop the image in the correct zone, nothing happens and this values are presented:

After some testing, I could find a place where the image is received by the application, but the position is totally wrong (top left corner of the window), this values are show in this case:

Anyway, it shouldn't be something hard, but my grap of UI x screen coordinates and stuff like that is bad apparently. Hopefully somebody will have an answer to my dobut.

Title: Drag and drop detection on a UI rect

Body:
found a script on Github which implements a drag and drop feature in Unity. There, I adapted the code "ImageExample.cs" to my project. It happens that I can't make the drop point detection system work with my UI. The drop point is composed of a empty UI object (only a rect transform and the adapted code), with the actual UI visual elements as it's children.

Already google a bunch of stuff trying to figure out what's the problem, without success. Tested some RectTransformUtility's methods, checked answers like this one or this one(top 2 answers) and etc..

The following method is my adapted version to receive and load the image:

protected void LoadImage()
{
    if (dropInfo == null)
    {
        Debug.LogError("Information is null!!");
        return;
    }
    Debug.LogError("Rect pos is " + dropRect.position);
    Debug.LogError("Rect transform pos is "+rectTransform.position);
    Debug.LogError("aInfo is " + dropInfo.pos);
    if (dropRect.Contains(dropInfo.pos))
    {
        var data = System.IO.File.ReadAllBytes(dropInfo.file);
        receivedImage = new Texture2D(1, 1);
        receivedImage.LoadImage(data);
        onTextureUpdate(receivedImage);
        onDropInfoUpdate(dropInfo.file);
    }
}

Where:

"aInfo" it's assigned as the author's example, just with a single texture instead of array.

"rectTransform" represents the empty UI container, meaning the valid area to receive images.

"dropRect" stands for the "rect" variable inside of "rectTransform"

If I drop the image in the correct zone, nothing happens and this values are presented:

After some testing, I could find a place where the image is received by the application, but the position is totally wrong (top left corner of the window), this values are show in this case:

Anyway, it shouldn't be something hard, but my grap of UI x screen coordinates and stuff like that is bad apparently. Hopefully somebody will have an answer to my dobut.


问:
Can't use OpenCV and pyplot in the same python file
Every time I try to use pyplot while CV is imported in the same file, I get the following error

```<code>QObject::moveToThread: Current thread (0x56408e7ad250) is not the object's thread (0x56408e4dc1a0).
Cannot move to target thread (0x56408e7ad250)

qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in ".../python3.10/site-packages/cv2/qt/plugins" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Available platform plugins are: xcb, eglfs, linuxfb, minimal, minimalegl, offscreen, vnc, wayland-egl, wayland, wayland-xcomposite-egl, wayland-xcomposite-glx, webgl.
</code>```

I first thought this was a general problem with pyplot but now realized that it only occurs when i also import OpenCV. Is there a way to make both things work or do I have to split my code into multiple files? I use pycharm on linux.

Body:
Every time I try to use pyplot while CV is imported in the same file, I get the following error

QObject::moveToThread: Current thread (0x56408e7ad250) is not the object's thread (0x56408e4dc1a0).
Cannot move to target thread (0x56408e7ad250)

qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in ".../python3.10/site-packages/cv2/qt/plugins" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

Available platform plugins are: xcb, eglfs, linuxfb, minimal, minimalegl, offscreen, vnc, wayland-egl, wayland, wayland-xcomposite-egl, wayland-xcomposite-glx, webgl.

I first thought this was a general problem with pyplot but now realized that it only occurs when i also import OpenCV. Is there a way to make both things work or do I have to split my code into multiple files? I use pycharm on linux.


问:
how to change a dataframes certain columns to 3 decimal points? - I need to do it for the whole column, not just one set of data
I need to change stock data from values such as [337.510009765625] to [337.510] for the Open High Low and Close, but not the volume

I don't want to round, I just want to knock off the extra digits

I've looked everywhere and tried a few methods but I cant find a way to do it to my whole DataFrame

Looking to knock off the decimal points - not round


问:
Exporting constant macros as constexpr values in C++20 module
I am currently playing with C++20 modules, in order to modernize our company code base.

Suppose you want to write a C++ module to export the content of a C library that uses #define to declare numerical or string constants. For example, imagine you want to create a Windows module with all the content of <Windows.h>.

So assume we have an existing third-party library header SuperLib.h that contains this:

```<code>#pragma once
struct super_lib_type {int field;};
extern void super_lib_function(int a);
#define SUPER_LIB_CONSTANT 42
</code>```

Now we write a C++ module like that:

```<code>export module SuperLib;
export
{
#include <SuperLib.h>
}
</code>```

The super_lib_function function and super_lib_type type will be successfully exported in the module. But obviously not SUPER_LIB_CONSTANT constant, since macros are by design never exported to C++20 modules.

To fix this, it will be great if we could have the equivalent of that code:

```<code>export module SuperLib;
export
{
#include <SuperLib.h>
}
#undef SUPER_LIB_CONSTANT
export constexpr auto SUPER_LIB_CONSTANT = 42;
</code>```

But without having to hard code the value 42 in the module file.
I tried to write a macro to do that. This one kind of works:

```<code>#define EXPORT(name) export constexpr auto SL_##name = name;
EXPORT(SUPER_LIB_CONSTANT)
</code>```

It will export a constant SL_SUPER_LIB_CONSTANT. But this approach has the inconvenience to require a prefix, or a suffix, in the symbol name. For compatibility with existing code, it would be great if the exported name is the same as the original macro.

I thought I could solve the problem by splitting the original macro name into 2 pieces.
Something like that:

```<code>#define CONCAT(prefix,suffix) prefix##suffix
#define EXPORT(prefix,suffix) export constexpr auto CONCAT(prefix,suffix) = prefix##suffix;
EXPORT(SUPER_LIB_,CONSTANT)
</code>```

But this generates the invalid code export auto constexpr 42 = 42; after preprocessing.

Still, I have the impression that it is possible to write a two arguments macro to fulfill the need. And maybe even a single argument macro.

Body:
I am currently playing with C++20 modules, in order to modernize our company code base.

Suppose you want to write a C++ module to export the content of a C library that uses #define to declare numerical or string constants. For example, imagine you want to create a Windows module with all the content of <Windows.h>.

So assume we have an existing third-party library header SuperLib.h that contains this:

#pragma once
struct super_lib_type {int field;};
extern void super_lib_function(int a);
#define SUPER_LIB_CONSTANT 42

Now we write a C++ module like that:

export module SuperLib;
export
{
#include <SuperLib.h>
}

The super_lib_function function and super_lib_type type will be successfully exported in the module. But obviously not SUPER_LIB_CONSTANT constant, since macros are by design never exported to C++20 modules.

To fix this, it will be great if we could have the equivalent of that code:

export module SuperLib;
export
{
#include <SuperLib.h>
}
#undef SUPER_LIB_CONSTANT
export constexpr auto SUPER_LIB_CONSTANT = 42;

But without having to hard code the value 42 in the module file.
I tried to write a macro to do that. This one kind of works:

#define EXPORT(name) export constexpr auto SL_##name = name;
EXPORT(SUPER_LIB_CONSTANT)

It will export a constant SL_SUPER_LIB_CONSTANT. But this approach has the inconvenience to require a prefix, or a suffix, in the symbol name. For compatibility with existing code, it would be great if the exported name is the same as the original macro.

I thought I could solve the problem by splitting the original macro name into 2 pieces.
Something like that:

#define CONCAT(prefix,suffix) prefix##suffix
#define EXPORT(prefix,suffix) export constexpr auto CONCAT(prefix,suffix) = prefix##suffix;
EXPORT(SUPER_LIB_,CONSTANT)

But this generates the invalid code export auto constexpr 42 = 42; after preprocessing.

Still, I have the impression that it is possible to write a two arguments macro to fulfill the need. And maybe even a single argument macro.


问:
Custom hot keys/commands in jupyter
Is there a way to create custom hotkeys/commands in jupiter?

For example, lets say I press Ctrl+1 and jupiter automatically pastes this code:

```<code>import pandas as pd
import util as x
asdasd
adsasd
asasdasd
</code>```

Title: Custom hot keys/commands in jupyter

Body:
Is there a way to create custom hotkeys/commands in jupiter?

For example, lets say I press Ctrl+1 and jupiter automatically pastes this code:

import pandas as pd
import util as x
asdasd
adsasd
asasdasd


问:
Intercept JavaScript function call in Blazor WebAssembly
I'm trying to create a Blazor WebAssembly PWA app which should use the JavaScript framework Framework7.io to provide a native-like UI style.

As I'm no JavaScript developer I'm currently struggling to implement a page where a list of data should be displayed and which should be updated by a pull-to-refresh gesture.

In Framework7 samples code like this is used:

```<code>`...
<div class="page-content ptr-content" data-ptr-mousewheel="true" @ptr:refresh=${loadMore}>
  <div class="ptr-preloader">
    <div class="preloader"></div>
    <div class="ptr-arrow"></div>
  </div>
  <div class=" list media-list">
    <ul>
      ${items.map((item) => $h`
      <li class="item-content">
...
const loadMore = (e, done) => {
  setTimeout(() => {
    // Add new item
    items.push({
      picURL: 'https://cdn.framework7.io/placeholder/abstract-88x88-' + (Math.floor(Math.random() * 10) + 1) + '.jpg',
      song: songs[Math.floor(Math.random() * songs.length)],
      author: authors[Math.floor(Math.random() * authors.length)],
    })

    // Update state to rerender
    $update();

    // Done
    done();
  }, 1000);
}
...`
</code>```

But I have absolutely no clue if and how this can be ported somehow to .net...

As far as I understand I need a way to specify a function for "@ptr:refresh" but I can't define a .net function here directly !?
Maybe I can somehow define an event listener somewhere that then uses JSInterop and call some .net code?

Body:
I'm trying to create a Blazor WebAssembly PWA app which should use the JavaScript framework Framework7.io to provide a native-like UI style.

As I'm no JavaScript developer I'm currently struggling to implement a page where a list of data should be displayed and which should be updated by a pull-to-refresh gesture.

In Framework7 samples code like this is used:

`...

      ${items.map((item) => $h`

...
const loadMore = (e, done) => {
  setTimeout(() => {
    // Add new item
    items.push({
      picURL: 'https://cdn.framework7.io/placeholder/abstract-88x88-' + (Math.floor(Math.random() * 10) + 1) + '.jpg',
      song: songs[Math.floor(Math.random() * songs.length)],
      author: authors[Math.floor(Math.random() * authors.length)],
    })

    // Update state to rerender
    $update();

    // Done
    done();
  }, 1000);
}
...`

But I have absolutely no clue if and how this can be ported somehow to .net...

As far as I understand I need a way to specify a function for "@ptr:refresh" but I can't define a .net function here directly !?
Maybe I can somehow define an event listener somewhere that then uses JSInterop and call some .net code?


问:
Problems with conversion between mktime and gmtime_r
If I define a broken-down time using  struct tm, then convert it to time_t using mktime and the result try to get back again as an struct tm I thought I was going to get the same result.

OK, maybe the first time something change because I define tm_isdst = -1 so mktime maybe affect that value, but not the second time.

The following code does that:

```<code>void print(const tm& t)
{
    std::cout   << t.tm_mday << '/'
        << t.tm_mon << '/'
        << t.tm_year << ' '
        << t.tm_hour << ':'
        << t.tm_min << ':'
        << t.tm_sec << ";  "
        << t.tm_wday << '|'
        << t.tm_isdst << '\n';
}

int main(){
    tm t;
    t.tm_sec = 32;
    t.tm_min = 22;
    t.tm_hour = 0;

    t.tm_mday = 6;
    t.tm_mon = 0;
    t.tm_year = 2023 - 1900;

    t.tm_wday = 5;
    t.tm_isdst = -1;

    print(t);

    time_t timet0 = mktime(&t);
    std::cout << "time_t0 = " << timet0 << '\n';
    gmtime_r(&timet0, &t);

    print(t);

    time_t timet1 = mktime(&t);
    std::cout << "time_t1 - time_t0 =  " << (timet1 - timet0) << '\n';
    std::cout << "time_t1 = " << timet1 << '\n';
    gmtime_r(&timet1, &t);
    print(t);

    timet1 = mktime(&t);
    std::cout << "time_t = " << timet1 << '\n';
    gmtime_r(&timet1, &t);
    print(t);

}
</code>```

And the result of executing it is

```<code>6/0/123 0:22:32;  5|-1
time_t0 = 1672960952
5/0/123 23:22:32;  4|0
time_t1 - time_t0 =  -3600
time_t1 = 1672957352
5/0/123 22:22:32;  4|0
time_t = 1672953752
5/0/123 21:22:32;  4|0
</code>```

Why am I losing an hour every time I call the pair mktime/gmtime_r?

Body:
If I define a broken-down time using  struct tm, then convert it to time_t using mktime and the result try to get back again as an struct tm I thought I was going to get the same result.

OK, maybe the first time something change because I define tm_isdst = -1 so mktime maybe affect that value, but not the second time.

The following code does that:

void print(const tm& t)
{
    std::cout   << t.tm_mday << '/'
        << t.tm_mon << '/'
        << t.tm_year << ' '
        << t.tm_hour << ':'
        << t.tm_min << ':'
        << t.tm_sec << ";  "
        << t.tm_wday << '|'
        << t.tm_isdst << '\n';
}

int main(){
    tm t;
    t.tm_sec = 32;
    t.tm_min = 22;
    t.tm_hour = 0;

    t.tm_mday = 6;
    t.tm_mon = 0;
    t.tm_year = 2023 - 1900;

    t.tm_wday = 5;
    t.tm_isdst = -1;

    print(t);

    time_t timet0 = mktime(&t);
    std::cout << "time_t0 = " << timet0 << '\n';
    gmtime_r(&timet0, &t);

    print(t);

    time_t timet1 = mktime(&t);
    std::cout << "time_t1 - time_t0 =  " << (timet1 - timet0) << '\n';
    std::cout << "time_t1 = " << timet1 << '\n';
    gmtime_r(&timet1, &t);
    print(t);

    timet1 = mktime(&t);
    std::cout << "time_t = " << timet1 << '\n';
    gmtime_r(&timet1, &t);
    print(t);

}

And the result of executing it is

6/0/123 0:22:32;  5|-1
time_t0 = 1672960952
5/0/123 23:22:32;  4|0
time_t1 - time_t0 =  -3600
time_t1 = 1672957352
5/0/123 22:22:32;  4|0
time_t = 1672953752
5/0/123 21:22:32;  4|0

Why am I losing an hour every time I call the pair mktime/gmtime_r?


问:
How to add multiple items into Excel file in single column using XLSX library in NodeJs
I have a JSON data which also contains an array field I want to convert that JSON data in Excel format for that I am using XLSX library.

Below is my code:

```<code>const XLSX = require('xlsx');
const path = require('path');

const workSheetColumnNames = ['name','hobbies'];

const sheetName = 'Reports';

const filePath = './final_report.xlsx';

const exportSheetToExcel = (data,workSheetColumnNames,sheetName,filePath) => {

 const data = [
              {
              name:'Paul',
              hobbies: ['Football','Reading']
              },
              {
              name:'Riya',
              hobbies: ['Singing','Dancing']
              },
              {
              name:'Jack',
              hobbies: ['Gaming']
              },
              ...
             ]

 const lists = data.map((res) => {
    return [res.name,res.hobbies];
 })

 const workSheetData = [workSheetColumnNames,...lists];
 const workBook = XLSX.utils.book_new();
 const workSheet = XLSX.utils.aoa_to_sheet(workSheetData);
 XLSX.utils.book_append_sheet(workBook,workSheet,sheetName);
 XLSX.writeFile(workBook,path.resolve(filePath));

 return true;

}

exportSheetToExcel(data,workSheetColumnNames,sheetName,filePath);
</code>```

Now the problem is its creating the Excel file but for hobbies column wherever there is more than 1 items in array its showing ERR:509 in Excel file hobbies column.

Is there any way so that I can enter multiple items in same column in Excel file?

Body:
I have a JSON data which also contains an array field I want to convert that JSON data in Excel format for that I am using XLSX library.

Below is my code:

const XLSX = require('xlsx');
const path = require('path');

const workSheetColumnNames = ['name','hobbies'];

const sheetName = 'Reports';

const filePath = './final_report.xlsx';

const exportSheetToExcel = (data,workSheetColumnNames,sheetName,filePath) => {

 const data = [
              {
              name:'Paul',
              hobbies: ['Football','Reading']
              },
              {
              name:'Riya',
              hobbies: ['Singing','Dancing']
              },
              {
              name:'Jack',
              hobbies: ['Gaming']
              },
              ...
             ]

 const lists = data.map((res) => {
    return [res.name,res.hobbies];
 })

 const workSheetData = [workSheetColumnNames,...lists];
 const workBook = XLSX.utils.book_new();
 const workSheet = XLSX.utils.aoa_to_sheet(workSheetData);
 XLSX.utils.book_append_sheet(workBook,workSheet,sheetName);
 XLSX.writeFile(workBook,path.resolve(filePath));

 return true;

}

exportSheetToExcel(data,workSheetColumnNames,sheetName,filePath);

Now the problem is its creating the Excel file but for hobbies column wherever there is more than 1 items in array its showing ERR:509 in Excel file hobbies column.

Is there any way so that I can enter multiple items in same column in Excel file?


问:
Timeout due to parsing Nuxt Content documents every cold start in Vercel server
I've a web built with Nuxt 2 deployed in Vercel where I'm using the @nuxt/content module for rendering some articles. It's using SSR and target: server, and everytime the server hibernates due to lack of activity, the first load takes +10 seconds or directly returns a timeout.

It's caused because when the server does the cold start, it is parsing the documents again reaching the time limit. I'm not sure why is this happening and how can I fix it. I guess moving to ssr: false can maybe help but I'm afraid my SEO can be affected. I believe a better solution should exist just to avoid re-parsing the documents everytime it does a cold start.

```<code>Nuxt version: 2.15.7
@nuxt/content version: 1.14.0
@nuxtjs/vercel-builder version: 0.22.1
Running on Node 16
</code>```

Parsing documents at cold start

nuxt.config.js

export default {
  ssr: true,

  target: "server",

  plugins: [
    "@/plugins/articleManager.ts",
    "@/plugins/leaflet.client.js",
    "@/plugins/device.server.js",
  ],

  components: true,

  buildModules: [
    "@nuxt/typescript-build",
    "@nuxtjs/vuetify",
    "vue-ssr-carousel/nuxt",
  ],

  modules: [
    "@nuxtjs/pwa",
    "@nuxt/content",
    "@nuxtjs/sitemap",
    "@nuxtjs/robots",
    "@nuxt/image",
  ],

  content: {
    fullTextSearchFields: ["title", "description"],
  },

  build: {
    build: {
      extend(config, { isClient }) {
        if (isClient) {
          config.devtool = "source-map";
        }
      },
    },
  },

  srcDir: "src/",
};

```
<p>vercel.json</p>
<pre class="lang-js prettyprint-override"><code>{
  "version": 2,
  "builds": [
    {
      "src": "package.json",
      "use": "@vercel/node"
    },
    {
      "src": "nuxt.config.js",
      "use": "@nuxtjs/vercel-builder",
      "config": {
        "serverFiles": [
          ".nuxt/content/**",
          "src/content/**",
          "server/**",
          ".nuxt/dist/sitemap-routes.json"
        ]
      }
    }
  ]
}

</code>```

I've tried many configurations to avoid the server parsing the documents every cold start but didn't succed. I also tried keep ssr: true with target: static but didn't managed to make it work. And even if it worked, I doubt that would solve the problem.

Thanks!

Body:
I've a web built with Nuxt 2 deployed in Vercel where I'm using the @nuxt/content module for rendering some articles. It's using SSR and target: server, and everytime the server hibernates due to lack of activity, the first load takes +10 seconds or directly returns a timeout.

It's caused because when the server does the cold start, it is parsing the documents again reaching the time limit. I'm not sure why is this happening and how can I fix it. I guess moving to ssr: false can maybe help but I'm afraid my SEO can be affected. I believe a better solution should exist just to avoid re-parsing the documents everytime it does a cold start.

Nuxt version: 2.15.7
@nuxt/content version: 1.14.0
@nuxtjs/vercel-builder version: 0.22.1
Running on Node 16

Parsing documents at cold start

nuxt.config.js

export default {
  ssr: true,

  target: "server",

  plugins: [
    "@/plugins/articleManager.ts",
    "@/plugins/leaflet.client.js",
    "@/plugins/device.server.js",
  ],

  components: true,

  buildModules: [
    "@nuxt/typescript-build",
    "@nuxtjs/vuetify",
    "vue-ssr-carousel/nuxt",
  ],

  modules: [
    "@nuxtjs/pwa",
    "@nuxt/content",
    "@nuxtjs/sitemap",
    "@nuxtjs/robots",
    "@nuxt/image",
  ],

  content: {
    fullTextSearchFields: ["title", "description"],
  },

  build: {
    build: {
      extend(config, { isClient }) {
        if (isClient) {
          config.devtool = "source-map";
        }
      },
    },
  },

  srcDir: "src/",
};

vercel.json

{
  "version": 2,
  "builds": [
    {
      "src": "package.json",
      "use": "@vercel/node"
    },
    {
      "src": "nuxt.config.js",
      "use": "@nuxtjs/vercel-builder",
      "config": {
        "serverFiles": [
          ".nuxt/content/**",
          "src/content/**",
          "server/**",
          ".nuxt/dist/sitemap-routes.json"
        ]
      }
    }
  ]
}

I've tried many configurations to avoid the server parsing the documents every cold start but didn't succed. I also tried keep ssr: true with target: static but didn't managed to make it work. And even if it worked, I doubt that would solve the problem.

Thanks!


问:
Redirect user in django after form submission using JavaScript
Using JS to add some interactivity to the form and now would like to redirect the user to a different url and be able to do it dynamically. Using plain JS as of now, need ideas. Adding sample code below.

```<code>book.addEventListener('submit', (e) => {
    e.preventDefault();
    const submitButton = document.getElementById('book');
    submitButton.disabled = true;
    submitButton.innerHTML = 'Booking...';
    setTimeout(() => {
        submitButton.innerHTML = `<i class="fa-solid fa-check" style="color: white; text-align: center;"></i>`;
    }, 1000);
    // return user to profile page
});
</code>```

Not really sure what to try as I am new to using JavaScript.

Body:
Using JS to add some interactivity to the form and now would like to redirect the user to a different url and be able to do it dynamically. Using plain JS as of now, need ideas. Adding sample code below.

book.addEventListener('submit', (e) => {
    e.preventDefault();
    const submitButton = document.getElementById('book');
    submitButton.disabled = true;
    submitButton.innerHTML = 'Booking...';
    setTimeout(() => {
        submitButton.innerHTML = `<i class="fa-solid fa-check" style="color: white; text-align: center;"></i>`;
    }, 1000);
    // return user to profile page
});

Not really sure what to try as I am new to using JavaScript.


问:
Dataset properties for acceptable confirmatory factor analysis
I don't exactly figure out the data requirement for confirmatory factor analysis. what kind of dataset gives acceptable performance metrics for the confirmatory factor analysis? For example: if there are three factors, all the items that belong the same factor has high covariance is enough for good results? Thanks.</p>


问:
Unable to open xcode. Shows error "Required content for platform tvOS Simulator is missing."
I'm unable to open my Xcode after accidentally deleting my Xcode from the applications folder to the trash and putting it back in my applications. Every time I try to open Xcode it shows the following error.

I tried googling this error and found this post on the Apple's forum page which asks me to just re-install from the official mac app store which I feel is a lazy answer and I do have enough storage for doing that on my old MacBook air with just 256GB.

I did find another post on SO that shows deleting a folder for a similar issue fixed the problem. Is there a similar solution or any other solution which doesn't require me to re-install Xcode once again?

My versions:-

MacBook Air (Intel)

macOS - 12.6.2

Xcode - 13.2.1


问:
C#, Visual Studio 2022 update, error after publishing - provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified
There are a lot of similar questions here and I think I read all of them, but still haven't found the cause of this error:

provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.

provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

The code:

```<code>string connection = Properties.Settings.Default.SqlConnection;

SqlConnectionStringBuilder builder = new()
        {
            ["Server"] = connection,
            ["Database"] = "myDatabase",
            ["Trusted_Connection"] = true
        };

using SqlConnection conn = new(builder.ConnectionString);

try
{
    conn.Open();
}
catch (Exception ex)
{
    throw;
}
finally
{
    conn.Close();
}
</code>```

I store myServerName\myInstanceName in the settings:

```<code><add name="TestSQLConnection.Properties.Settings.SqlConnection"
     connectionString="Servername\SQL2012" />
</code>```

This works on my local machine, but when I publish the application, the user will get the above mentioned error. If I log in and run the published application on the server, it works (but I am admin, so that is not a surprise) and strangely enough, after I run it, other users will be able to run it without error, but only temporarily (How is this possible?). I am having this issue since the latest update of VS2022, before that it worked and if I publish an older project now, the user gets the same error. All the applications I published earlier with the same connection string work just fine (which rules out most of the possible causes discussed here in earlier questions).

Things that I tried:

Make sure there is no typo in the connection string

Make sure that the server is reachable

Replace server name with IP in the connection string

Check if SQL Server Browser is running

Enable port 1433 in Server Configuration Manager

Add port 1433 to the connection string

Test applications published earlier with similar code (same connection string) and the same user.

Repair Visual Studio 2022

Any idea where should I try to look for the root cause would be highly appreciated. Can this be an issue with VS (I also tried to repair VS out of desperation, with no avail) or am I missing something trivial?

UPDATE

It is definitely an issue with the access rights. If I publish the application to a folder that is already in use for an application deployed before, it works. The funny thing is that there is no difference in security settings between the old and new folders. (same users/groups have the same access rights to the folders)

Body:
There are a lot of similar questions here and I think I read all of them, but still haven't found the cause of this error:

provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.

provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

The code:

string connection = Properties.Settings.Default.SqlConnection;

SqlConnectionStringBuilder builder = new()
        {
            ["Server"] = connection,
            ["Database"] = "myDatabase",
            ["Trusted_Connection"] = true
        };

using SqlConnection conn = new(builder.ConnectionString);

try
{
    conn.Open();
}
catch (Exception ex)
{
    throw;
}
finally
{
    conn.Close();
}

I store myServerName\myInstanceName in the settings:

<add name="TestSQLConnection.Properties.Settings.SqlConnection"
     connectionString="Servername\SQL2012" />

This works on my local machine, but when I publish the application, the user will get the above mentioned error. If I log in and run the published application on the server, it works (but I am admin, so that is not a surprise) and strangely enough, after I run it, other users will be able to run it without error, but only temporarily (How is this possible?). I am having this issue since the latest update of VS2022, before that it worked and if I publish an older project now, the user gets the same error. All the applications I published earlier with the same connection string work just fine (which rules out most of the possible causes discussed here in earlier questions).

Things that I tried:

Make sure there is no typo in the connection string

Make sure that the server is reachable

Replace server name with IP in the connection string

Check if SQL Server Browser is running

Enable port 1433 in Server Configuration Manager

Add port 1433 to the connection string

Test applications published earlier with similar code (same connection string) and the same user.

Repair Visual Studio 2022

Any idea where should I try to look for the root cause would be highly appreciated. Can this be an issue with VS (I also tried to repair VS out of desperation, with no avail) or am I missing something trivial?

UPDATE

It is definitely an issue with the access rights. If I publish the application to a folder that is already in use for an application deployed before, it works. The funny thing is that there is no difference in security settings between the old and new folders. (same users/groups have the same access rights to the folders)


问:
How to get notification from a custom UITextField
I have a Swiftui textfield button with the body like below, and a subclass of UITextField called MyTextField. What change should I make in order to successfully down cast obj.object to MyTextField

var body: some View {
        Button {
            onTap()
        } label: {
            TextField(" ", text: $buttonContent)
                .onReceive(NotificationCenter.default.publisher(for: UITextField.textDidBeginEditingNotification)) { obj in
                        if let textField = obj.object as? MyTextField {
                            // How to have it reach here?
                        }
                }
        }
    }
```
<pre class="lang-swift prettyprint-override"><code>class MyTextField: UITextField {
    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override public func deleteBackward() {
        if text == "" {
             // do something when backspace is tapped/entered in an empty text field
            print("delete on empty field")
        }
        // do something for every backspace
        super.deleteBackward()
    }

    override func becomeFirstResponder() -> Bool {
        let result = super.becomeFirstResponder()
        if result {
            NotificationCenter.default.post(name: UITextField.textDidBeginEditingNotification, object: self)
        }
        return result
    }
}
</code>```

Body:
I have a Swiftui textfield button with the body like below, and a subclass of UITextField called MyTextField. What change should I make in order to successfully down cast obj.object to MyTextField

var body: some View {
        Button {
            onTap()
        } label: {
            TextField(" ", text: $buttonContent)
                .onReceive(NotificationCenter.default.publisher(for: UITextField.textDidBeginEditingNotification)) { obj in
                        if let textField = obj.object as? MyTextField {
                            // How to have it reach here?
                        }
                }
        }
    }

class MyTextField: UITextField {
    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override public func deleteBackward() {
        if text == "" {
             // do something when backspace is tapped/entered in an empty text field
            print("delete on empty field")
        }
        // do something for every backspace
        super.deleteBackward()
    }

    override func becomeFirstResponder() -> Bool {
        let result = super.becomeFirstResponder()
        if result {
            NotificationCenter.default.post(name: UITextField.textDidBeginEditingNotification, object: self)
        }
        return result
    }
}


问:
Replace values in dataframe from text-input as variable
I am trying to replace all values selected in a multiselect and replace them by information given in a text_input.
Unfortunately, only the last value is amended and I do not know why.

```<code>`import streamlit as st
import pandas as pd
import openpyxl
from st_aggrid import AgGrid, GridUpdateMode, JsCode
from st_aggrid.grid_options_builder import GridOptionsBuilder
from datetime import datetime as dt
import calendar

uploaded_file = st.file_uploader(‘Please select the file’)
df = pd.read_excel(
io = uploaded_file,
engine = ‘openpyxl’,
sheet_name=‘Sheet1’,
)

df1 = pd.DataFrame(df, columns=[‘A’,‘B’,‘C’,‘D’,‘E’] )

st.write(df1)

#create a list removing all duplicates
dflist1 = pd.DataFrame(df1, columns=[‘B’])
dflist1 = dflist1[‘B’].unique().tolist()

#remove the empty value from the list
dflist1 = list(filter(None, dflist1))
replacedvalue = st.multiselect(
‘Select value replaced’,
dflist1, default=None)

list0=(dflist1)
list1=

for i in replacedvalue:
for k in list0:
if k==i:
test_radio=st.text_input('ticker ‘+ k + ’ to be replace by:’,‘Ticker only’,key=‘testlist’+k)
list1.append(test_radio)

df1 = df1.replace(to_replace=k, value= test_radio, regex=False)
AgGrid(df1)`
</code>```

Expected behavior:

I would like all variable selected being replaced in the dataframe from their respective value inserted in the inputbox.
Thanks in advance for your help

Actual behavior:

I expected all elements selected in the multiselect being replaced by the values entered on the different text_input.
By testing the code, you will realize that only the last one selected i the multiselect widget is replaced on the dataframe

Debug info
Streamlit version: v1.10.0
Python version: Python 3.6.15
Using Jupiterlab
OS version: windows 11
Browser version: chome

Body:
I am trying to replace all values selected in a multiselect and replace them by information given in a text_input.
Unfortunately, only the last value is amended and I do not know why.

`import streamlit as st
import pandas as pd
import openpyxl
from st_aggrid import AgGrid, GridUpdateMode, JsCode
from st_aggrid.grid_options_builder import GridOptionsBuilder
from datetime import datetime as dt
import calendar

uploaded_file = st.file_uploader(‘Please select the file’)
df = pd.read_excel(
io = uploaded_file,
engine = ‘openpyxl’,
sheet_name=‘Sheet1’,
)

df1 = pd.DataFrame(df, columns=[‘A’,‘B’,‘C’,‘D’,‘E’] )

st.write(df1)

#create a list removing all duplicates
dflist1 = pd.DataFrame(df1, columns=[‘B’])
dflist1 = dflist1[‘B’].unique().tolist()

#remove the empty value from the list
dflist1 = list(filter(None, dflist1))
replacedvalue = st.multiselect(
‘Select value replaced’,
dflist1, default=None)

list0=(dflist1)
list1=

for i in replacedvalue:
for k in list0:
if k==i:
test_radio=st.text_input('ticker ‘+ k + ’ to be replace by:’,‘Ticker only’,key=‘testlist’+k)
list1.append(test_radio)

df1 = df1.replace(to_replace=k, value= test_radio, regex=False)
AgGrid(df1)`

Expected behavior:

I would like all variable selected being replaced in the dataframe from their respective value inserted in the inputbox.
Thanks in advance for your help

Actual behavior:

I expected all elements selected in the multiselect being replaced by the values entered on the different text_input.
By testing the code, you will realize that only the last one selected i the multiselect widget is replaced on the dataframe

Debug info
Streamlit version: v1.10.0
Python version: Python 3.6.15
Using Jupiterlab
OS version: windows 11
Browser version: chome


问:
Copy latitude and longitude information for a number of events into another frame containing individuals location
I have data in two different datasets. The default dataset is in the .dta format and is cross-section of a sample in year X. The event dataset is imported through an excel file and is a series of events in the same year. I am just interested in the location information of the events.

```<code>set obs 10
gen iid = _n
gen latitude_i = runiform()
gen longitude_i = runiform()

frame create events
frame change events
set obs 5
gen eventid = _n
gen latitude = runiform()
gen longitude = runiform()
</code>```

For each event in the events frame I want to create a two new variables for the location variables (latitudeevent1, longitudeevent1, latitudevent2, longitutdeevent2, etc.) in my default frame. Because the list of events is long, I would like to automate this and not do it manually.
The ultimate goal is to compute the distance for each event from the location of the person.

```<code>frame change default
gen latitude1 = latitude from eventid = 1 in frame events
gen longitude1 = longitutde from eventid = 1  in frame events
gen latitude2 = latitude from eventid = 2 in frame events
gen longitude2 = longitude from eventid = 2 in frame events
</code>```

My general idea is to reshape the events data from long to wide leaving me with just one row. The problem is that reshape needs a unique identifier i which leaves me with a table with more than one row. The second problem is accessing the data in the events frame from the default frame. This is problematic because frval needs a linked dataframe which is not possible and frame put [varlist] in [if], into(*newframename*) only works if you put the data into a new frame.

Body:
I have data in two different datasets. The default dataset is in the .dta format and is cross-section of a sample in year X. The event dataset is imported through an excel file and is a series of events in the same year. I am just interested in the location information of the events.

set obs 10
gen iid = _n
gen latitude_i = runiform()
gen longitude_i = runiform()

frame create events
frame change events
set obs 5
gen eventid = _n
gen latitude = runiform()
gen longitude = runiform()

For each event in the events frame I want to create a two new variables for the location variables (latitudeevent1, longitudeevent1, latitudevent2, longitutdeevent2, etc.) in my default frame. Because the list of events is long, I would like to automate this and not do it manually.
The ultimate goal is to compute the distance for each event from the location of the person.

frame change default
gen latitude1 = latitude from eventid = 1 in frame events
gen longitude1 = longitutde from eventid = 1  in frame events
gen latitude2 = latitude from eventid = 2 in frame events
gen longitude2 = longitude from eventid = 2 in frame events

My general idea is to reshape the events data from long to wide leaving me with just one row. The problem is that reshape needs a unique identifier i which leaves me with a table with more than one row. The second problem is accessing the data in the events frame from the default frame. This is problematic because frval needs a linked dataframe which is not possible and frame put [varlist] in [if], into(*newframename*) only works if you put the data into a new frame.


问:
Python Proxy Requests by using Session not working, works without session
I am trying to forward my requests through my proxy (Charles/Fiddler) for the purpose of my task and I noticed some weird behavior between requests.get and session.get.

When I use proxies=proxies in requests.get it works as intended, but when I use session.proxies = proxies I get a time out every single time. Here is my code:

```<code>proxies = {
    "http": "127.0.0.1:1080",
}
proxies["https"] = proxies["http"]

session = requests.Session()
session.proxies = proxies

print(requests.get("https://google.com", timeout=2, proxies=proxies)) # Ok [200]
print(session.get("https://google.com", timeout=20,)) # ProxyError timeout
</code>```

I tried looking at other stack overflow questions and they either have a different error or their solution was different.
I also tried both http:// and https:// in the values of my proxies dict and it was still the same.
Any idea what's going on?

Body:
I am trying to forward my requests through my proxy (Charles/Fiddler) for the purpose of my task and I noticed some weird behavior between requests.get and session.get.

When I use proxies=proxies in requests.get it works as intended, but when I use session.proxies = proxies I get a time out every single time. Here is my code:

proxies = {
    "http": "127.0.0.1:1080",
}
proxies["https"] = proxies["http"]

session = requests.Session()
session.proxies = proxies

print(requests.get("https://google.com", timeout=2, proxies=proxies)) # Ok [200]
print(session.get("https://google.com", timeout=20,)) # ProxyError timeout

I tried looking at other stack overflow questions and they either have a different error or their solution was different.
I also tried both http:// and https:// in the values of my proxies dict and it was still the same.
Any idea what's going on?


问:
built_value ColorSerializerPlugin Issue
I'm trying to build a custom Color serializer plugin to convert the flutter Color objects to Hex strings when saving to the backend.

I've written the below plugin

```<code>class ColorSerializerPlugin implements SerializerPlugin {
  @override
  Object? beforeSerialize(Object? object, FullType specifiedType) {
    if (object is Color && specifiedType.root == Color) {
      // print(
      //     'beforeSerialize : Object value: ${object.value.toRadixString(16)}');
      return '#FF${object.value.toRadixString(16).substring(2, 8)}';
    }
    return object;
  }

  @override
  Object? afterSerialize(Object? object, FullType specifiedType) {
    if (specifiedType.root == Color) {
      print(
          'afterSerialize : Object value: $object, Runtime: ${object.runtimeType}');
    }
    return object;
  }

  @override
  Object? beforeDeserialize(Object? object, FullType specifiedType) {
    if (object is String && specifiedType.root == Color) {
      return hexStringToColor(object);
    }
    return object;
  }

  @override
  Object? afterDeserialize(Object? object, FullType specifiedType) {
    return object;
  }
}

hexStringToColor(String hexColor) {
  hexColor = hexColor.toUpperCase().replaceAll("#", "");
  if (hexColor.length == 6) {
    hexColor = "FF" + hexColor;
  }
  return Color(int.parse(hexColor, radix: 16));
}
</code>```

the code is working well for the beforeSerialize, but the afterSerialize prints the following, and my final serialized object also shows the below value

afterSerialize : Object value: {$: String, : #FF922d2d}, Runtime: _InternalLinkedHashMap<String, Object?>

I'm unable to figure where the HashMap is being added. How can I just return the Hex value?

Thanks,
Elvis

Title: built_value ColorSerializerPlugin Issue

Body:
I'm trying to build a custom Color serializer plugin to convert the flutter Color objects to Hex strings when saving to the backend.

I've written the below plugin

class ColorSerializerPlugin implements SerializerPlugin {
  @override
  Object? beforeSerialize(Object? object, FullType specifiedType) {
    if (object is Color && specifiedType.root == Color) {
      // print(
      //     'beforeSerialize : Object value: ${object.value.toRadixString(16)}');
      return '#FF${object.value.toRadixString(16).substring(2, 8)}';
    }
    return object;
  }

  @override
  Object? afterSerialize(Object? object, FullType specifiedType) {
    if (specifiedType.root == Color) {
      print(
          'afterSerialize : Object value: $object, Runtime: ${object.runtimeType}');
    }
    return object;
  }

  @override
  Object? beforeDeserialize(Object? object, FullType specifiedType) {
    if (object is String && specifiedType.root == Color) {
      return hexStringToColor(object);
    }
    return object;
  }

  @override
  Object? afterDeserialize(Object? object, FullType specifiedType) {
    return object;
  }
}

hexStringToColor(String hexColor) {
  hexColor = hexColor.toUpperCase().replaceAll("#", "");
  if (hexColor.length == 6) {
    hexColor = "FF" + hexColor;
  }
  return Color(int.parse(hexColor, radix: 16));
}

the code is working well for the beforeSerialize, but the afterSerialize prints the following, and my final serialized object also shows the below value

afterSerialize : Object value: {$: String, : #FF922d2d}, Runtime: _InternalLinkedHashMap<String, Object?>

I'm unable to figure where the HashMap is being added. How can I just return the Hex value?

Thanks,
Elvis


问:
Combine Treeview Mui 5 and Datagrid to display but error as follows
I have 2 components:
1 is the treeview created as follows:

```<code>const renderTree = (nodes) => (
        <TreeItem key={nodes.id} nodeId={nodes.id ? nodes.id : "defaultNodeId"} label={nodes.name ? nodes.name : "defaultNodeName"}
        >
            {Array.isArray(nodes.children)
                ? nodes.children.map((node) => renderTree(node))
                : null}
        </TreeItem>
    );
</code>```
```<code><TreeView
                                aria-label="gmail"
                                defaultCollapseIcon={<ArrowDropDownIcon />}
                                defaultExpandIcon={<ArrowRightIcon />}
                                defaultEndIcon={<div style={{ width: 18 }} />}
                                defaultExpanded={['72']}
                                sx={{ height: 'auto', flexGrow: 1, maxWidth: 250, overflowY: 'auto' }}
                                onNodeSelect={handleSelectedItems}
                            >
                                {renderTree(data)}
                            </TreeView>
</code>```

2 is the datagrid created as follows:

```<code><DataGrid
                                    rows={gridrows}
                                    columns={columns}
                                    pageSize={10}
                                    rowsPerPageOptions={[10]}
                                    {/*//checkboxSelection*/}
                                    {/*//disableRowSelectionOnClick*/}
                                />
</code>```

When I click on the node on the TreeView, the below function will be executed:

```<code>const handleSelectedItems = (event, nodeId) => {
        console.log('ON fetchGridData', nodeId);
        event.preventDefault();
        event.stopPropagation();
        fetchGridData(nodeId);
        event.preventDefault();
        event.stopPropagation();
    }
</code>```

I have selected the data, but Treenode does not expand. Does anyone know what the error is? Please help me

I was able to select data and fill in datagrid, but every time I fill the treeview doesn't open node expand

Body:
I have 2 components:
1 is the treeview created as follows:

const renderTree = (nodes) => (
        <TreeItem key={nodes.id} nodeId={nodes.id ? nodes.id : "defaultNodeId"} label={nodes.name ? nodes.name : "defaultNodeName"}
        >
            {Array.isArray(nodes.children)
                ? nodes.children.map((node) => renderTree(node))
                : null}
        </TreeItem>
    );

<TreeView
                                aria-label="gmail"
                                defaultCollapseIcon={<ArrowDropDownIcon />}
                                defaultExpandIcon={<ArrowRightIcon />}
                                defaultEndIcon={
}
                                defaultExpanded={['72']}
                                sx={{ height: 'auto', flexGrow: 1, maxWidth: 250, overflowY: 'auto' }}
                                onNodeSelect={handleSelectedItems}
                            >
                                {renderTree(data)}
                            </TreeView>

2 is the datagrid created as follows:

<DataGrid
                                    rows={gridrows}
                                    columns={columns}
                                    pageSize={10}
                                    rowsPerPageOptions={[10]}
                                    {/*//checkboxSelection*/}
                                    {/*//disableRowSelectionOnClick*/}
                                />

When I click on the node on the TreeView, the below function will be executed:

const handleSelectedItems = (event, nodeId) => {
        console.log('ON fetchGridData', nodeId);
        event.preventDefault();
        event.stopPropagation();
        fetchGridData(nodeId);
        event.preventDefault();
        event.stopPropagation();
    }

I have selected the data, but Treenode does not expand. Does anyone know what the error is? Please help me

I was able to select data and fill in datagrid, but every time I fill the treeview doesn't open node expand


问:
Firebase realtime database: can't determine database rules for verifying google oauth email
I can't figure out realtime database: firebase rules for verifying google oauth email.

In the rules, the only thing I have been able to use to see if the user is authenticated with google oauth is this:

{
  "rules": {
    ".read": " auth.token.firebase.identities['google.com'][0] != '' "
  }
}
```
<p>And I want to also check if email is verified and is equal to "marcglassman@gmail.com"</p>
<p>I've tried to use:</p>
<pre class="lang-js prettyprint-override"><code>auth.token.email
auth.token.firebase.identities[0].email
auth.token.authFields.email
</code>```

and here is the reference doc I tried to use:
https://firebase.google.com/docs/reference/security/database/#authtoken

and here is the info I have avail:

const firebaseConsoleRealtimeDatabaseRulesPlaygroundAuthenticationPayload = {
  "uid": "NUMBER_I_DONT_SHOW",
  "token": {
    "sub": "NUMBER_I_DONT_SHOW",
    "authFields": {
      "email": "marcglassman@gmail.com",
      "email_verified": true,
      "phone_number": "NUMBER_I_DONT_SHOW",
      "name": "Marc Glassman"
    },
    "firebase": {
      "sign_in_provider": "google.com"
    }
  }
};

const userInfoAfterFirebaseAuthJSClientAuthenticateUserWithGoogleLoginResult = {
  "id":"NUMBER_I_DONT_SHOW",
  "name":"Marc Glassman",
  "provider":{
     "displayName":"Marc Glassman",
     "email":"marcglassman@gmail.com",
     "phoneNumber":null,
"photoURL":"https://lh3.googleusercontent.com/a/AEdFTp7PL8PnsNNquMywC5DtEVa3ZxtAeznkfousQ_HZqHo=s96-c",
     "providerId":"google.com",
     "uid":"NUMBER_I_DONT_SHOW"
  },
  "providerName":"(google+)",
  "uid":"NUMBER_I_DONT_SHOW"
}
```

Body:
I can't figure out realtime database: firebase rules for verifying google oauth email.

In the rules, the only thing I have been able to use to see if the user is authenticated with google oauth is this:

{
  "rules": {
    ".read": " auth.token.firebase.identities['google.com'][0] != '' "
  }
}

And I want to also check if email is verified and is equal to "marcglassman@gmail.com"

I've tried to use:

auth.token.email
auth.token.firebase.identities[0].email
auth.token.authFields.email

and here is the reference doc I tried to use:
https://firebase.google.com/docs/reference/security/database/#authtoken

and here is the info I have avail:

const firebaseConsoleRealtimeDatabaseRulesPlaygroundAuthenticationPayload = {
  "uid": "NUMBER_I_DONT_SHOW",
  "token": {
    "sub": "NUMBER_I_DONT_SHOW",
    "authFields": {
      "email": "marcglassman@gmail.com",
      "email_verified": true,
      "phone_number": "NUMBER_I_DONT_SHOW",
      "name": "Marc Glassman"
    },
    "firebase": {
      "sign_in_provider": "google.com"
    }
  }
};

const userInfoAfterFirebaseAuthJSClientAuthenticateUserWithGoogleLoginResult = {
  "id":"NUMBER_I_DONT_SHOW",
  "name":"Marc Glassman",
  "provider":{
     "displayName":"Marc Glassman",
     "email":"marcglassman@gmail.com",
     "phoneNumber":null,
"photoURL":"https://lh3.googleusercontent.com/a/AEdFTp7PL8PnsNNquMywC5DtEVa3ZxtAeznkfousQ_HZqHo=s96-c",
     "providerId":"google.com",
     "uid":"NUMBER_I_DONT_SHOW"
  },
  "providerName":"(google+)",
  "uid":"NUMBER_I_DONT_SHOW"
}


问:
Nuxt don't close webcan video when change the component
I was developed a WebRTC video page in Nuxt v2.15.8. When I change internal page, the cam, don't close automatic, I made a function that close the stream that is called when the user try to call another page, but something still happened

Someone had this problem with Nuxt?

```<code>async startMediaLocal() {

  this.localStream = await navigator.mediaDevices.getUserMedia({
    video: true,
    audio: true,
  })
  // this.localStream.setMirror(true)
  this.localStream.getTracks().forEach((track) => {
    this.pc.addTrack(track, this.localStream)
  })
  this.webcamVideo.srcObject = this.localStream
  this.remoteStream = new MediaStream()
  this.pc.ontrack = (event) => {
    event.streams[0].getTracks().forEach((track) => {
      this.remoteStream.addTrack(track)
    })
  }

  this.remoteVideo.srcObject = this.remoteStream
},

async stoptMediaLocal(){
    this.localStream.getVideoTracks()[0].stop()
    this.pc.getLocalStreams()[0].getVideoTracks()[0].stop()
    this.webcamVideo.srcObject.getVideoTracks()[0].stop()
    this.webcamVideo = ''
},
</code>```

Body:
I was developed a WebRTC video page in Nuxt v2.15.8. When I change internal page, the cam, don't close automatic, I made a function that close the stream that is called when the user try to call another page, but something still happened

Someone had this problem with Nuxt?

async startMediaLocal() {

  this.localStream = await navigator.mediaDevices.getUserMedia({
    video: true,
    audio: true,
  })
  // this.localStream.setMirror(true)
  this.localStream.getTracks().forEach((track) => {
    this.pc.addTrack(track, this.localStream)
  })
  this.webcamVideo.srcObject = this.localStream
  this.remoteStream = new MediaStream()
  this.pc.ontrack = (event) => {
    event.streams[0].getTracks().forEach((track) => {
      this.remoteStream.addTrack(track)
    })
  }

  this.remoteVideo.srcObject = this.remoteStream
},

async stoptMediaLocal(){
    this.localStream.getVideoTracks()[0].stop()
    this.pc.getLocalStreams()[0].getVideoTracks()[0].stop()
    this.webcamVideo.srcObject.getVideoTracks()[0].stop()
    this.webcamVideo = ''
},


问:
CamerApi2 Take images with lower resolution
i am using the Camera API 2 to capture Raw Images with an Android phone.
The following line of code gives the following possible resolutions for my phone:

```<code>Size[] largestRaw = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.RAW_SENSOR);

4080 3072
4080 2288
2032 1536
</code>```

If i am using the highest resolution everything is working fine. The raw image is saved in the external storage.
But if i choose one of the lower resolutions i get the following error:

```<code> android.hardware.camera2.CameraAccessException: CAMERA_ERROR (3): endConfigure:653: Camera 0: Error configuring streams: Broken pipe (-32)
</code>```

Am i missing somekind of configuration to get it working?

Thanks for any help/suggestions.

Body:
i am using the Camera API 2 to capture Raw Images with an Android phone.
The following line of code gives the following possible resolutions for my phone:

Size[] largestRaw = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.RAW_SENSOR);

4080 3072
4080 2288
2032 1536

If i am using the highest resolution everything is working fine. The raw image is saved in the external storage.
But if i choose one of the lower resolutions i get the following error:

 android.hardware.camera2.CameraAccessException: CAMERA_ERROR (3): endConfigure:653: Camera 0: Error configuring streams: Broken pipe (-32)

Am i missing somekind of configuration to get it working?

Thanks for any help/suggestions.


问:
How to assign value to hubspot form field
Below is my react component:

```<code>import React, { useEffect } from "react";

const HubspotContactForm = ({ pageContext, ...props }) => {

  useEffect(() => {

 document.getElementById("firstname-3478d953-3c8d-4bea-8501-af6ab93cac87").value = "test123"

      });
}

export default HubspotContactForm;
</code>```

If I inspect my firstname field you can see Id which is belong to hubspot:

Right now I am trying to assign just test value to my firstname field and I am unable to do so.
Can anyone assist me where I am wrong? I am new to reactjs.

Thanks in advance!

Body:
Below is my react component:

import React, { useEffect } from "react";

const HubspotContactForm = ({ pageContext, ...props }) => {

  useEffect(() => {

 document.getElementById("firstname-3478d953-3c8d-4bea-8501-af6ab93cac87").value = "test123"

      });
}

export default HubspotContactForm;

If I inspect my firstname field you can see Id which is belong to hubspot:

Right now I am trying to assign just test value to my firstname field and I am unable to do so.
Can anyone assist me where I am wrong? I am new to reactjs.

Thanks in advance!


问:
How can I proxy form data using http-proxy-middleware?
I created a proxy on firebase using http-proxy-middleware.
It works on GET requests but does not pass the data I send via body in POST requests. I did some research and added the "onProxyReq" method to the options. This way it works when I send json body, but not when I send form data.

const functions = require("firebase-functions");
const express = require("express");
var bodyParser = require("body-parser");

const {
  createProxyMiddleware,
  fixRequestBody,
} = require("http-proxy-middleware");
const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

var restream = function (proxyReq, req, res, options) {
  if (req.body) {
    let bodyData = JSON.stringify(req.body);

    proxyReq.setHeader("Content-Type", "application/json");
    proxyReq.setHeader("Content-Length", Buffer.byteLength(bodyData));
    proxyReq.write(bodyData);
  }
};

app.use(
  "/",
  createProxyMiddleware({
    target: "http://IPADDRESS:8080/api",
    changeOrigin: true,
    onProxyReq: restream,
    bodyParser: false,
  })
);

exports.api = functions.https.onRequest(app);
```

This code works with json body.

Changing "application/json" to "multipart/form-data" doesn't work.

All I want is to redirect the JWT token in the header and the FormData in the body.
What should be the best way for this?

Body:
I created a proxy on firebase using http-proxy-middleware.
It works on GET requests but does not pass the data I send via body in POST requests. I did some research and added the "onProxyReq" method to the options. This way it works when I send json body, but not when I send form data.

const functions = require("firebase-functions");
const express = require("express");
var bodyParser = require("body-parser");

const {
  createProxyMiddleware,
  fixRequestBody,
} = require("http-proxy-middleware");
const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

var restream = function (proxyReq, req, res, options) {
  if (req.body) {
    let bodyData = JSON.stringify(req.body);

    proxyReq.setHeader("Content-Type", "application/json");
    proxyReq.setHeader("Content-Length", Buffer.byteLength(bodyData));
    proxyReq.write(bodyData);
  }
};

app.use(
  "/",
  createProxyMiddleware({
    target: "http://IPADDRESS:8080/api",
    changeOrigin: true,
    onProxyReq: restream,
    bodyParser: false,
  })
);

exports.api = functions.https.onRequest(app);

This code works with json body.

Changing "application/json" to "multipart/form-data" doesn't work.

All I want is to redirect the JWT token in the header and the FormData in the body.
What should be the best way for this?


问:
image captioner generator method from single image to batch
i was following the tensorflow guide on image captioning linked here  and everything is working great but i wanted to to convert this method that generates captions for input image to take a batch of images instead of 1

for example this the current generator method

```<code>@Captioner.add_method
def simple_gen(self, image, temperature=1):
  initial = self.word_to_index([['[ٍSTART]']]) # (batch, sequence)
  img_features = self.feature_extractor(image[tf.newaxis, ...])

  tokens = initial # (batch, sequence)
  for n in range(50):
    preds = self((img_features, tokens)).numpy()  # (batch, sequence, vocab)
    preds = preds[:,-1, :]  #(batch, vocab)
    if temperature==0:
        next = tf.argmax(preds, axis=-1)[:, tf.newaxis]  # (batch, 1)
    else:
        next = tf.random.categorical(preds/temperature, num_samples=1)  # (batch, 1)
    tokens = tf.concat([tokens, next], axis=1) # (batch, sequence)

    if next[0] == self.word_to_index('[END]'):
      break
  words = idx_to_word(tokens[0, 1:-1])
  result = tf.strings.reduce_join(words, axis=-1, separator=' ')
  return result.numpy().decode()
</code>```

it takes one image output loaded by this function

```<code>def load_img(img_path):
    img = tf.io.read_file(img_path)
    img = tf.io.decode_jpeg(img,channels=3)
    img = tf.image.resize(img,IMAGE_SHAPE[:-1])
    return img

</code>```

and load_img function takes img_path and the generator function returns generated caption for this image

what i tried is i have a tf dataset that contains a list img paths and corresponding captions i tried the following code to load all images in the tf dataset and loop over them and call the simple_gen method but it's very slow and inefficient and i'm looking for a better way to optimize the method

```<code>for (img,capt) in test_raw.map(lambda img,capt: (load_img(img),capt)):
        preds = []
        for t in [0.0,0.5,1.0]:
            result = model.simple_gen(img)
            preds.append(result)

</code>```

Body:
i was following the tensorflow guide on image captioning linked here  and everything is working great but i wanted to to convert this method that generates captions for input image to take a batch of images instead of 1

for example this the current generator method

@Captioner.add_method
def simple_gen(self, image, temperature=1):
  initial = self.word_to_index([['[ٍSTART]']]) # (batch, sequence)
  img_features = self.feature_extractor(image[tf.newaxis, ...])

  tokens = initial # (batch, sequence)
  for n in range(50):
    preds = self((img_features, tokens)).numpy()  # (batch, sequence, vocab)
    preds = preds[:,-1, :]  #(batch, vocab)
    if temperature==0:
        next = tf.argmax(preds, axis=-1)[:, tf.newaxis]  # (batch, 1)
    else:
        next = tf.random.categorical(preds/temperature, num_samples=1)  # (batch, 1)
    tokens = tf.concat([tokens, next], axis=1) # (batch, sequence)

    if next[0] == self.word_to_index('[END]'):
      break
  words = idx_to_word(tokens[0, 1:-1])
  result = tf.strings.reduce_join(words, axis=-1, separator=' ')
  return result.numpy().decode()

it takes one image output loaded by this function

def load_img(img_path):
    img = tf.io.read_file(img_path)
    img = tf.io.decode_jpeg(img,channels=3)
    img = tf.image.resize(img,IMAGE_SHAPE[:-1])
    return img

and load_img function takes img_path and the generator function returns generated caption for this image

what i tried is i have a tf dataset that contains a list img paths and corresponding captions i tried the following code to load all images in the tf dataset and loop over them and call the simple_gen method but it's very slow and inefficient and i'm looking for a better way to optimize the method

for (img,capt) in test_raw.map(lambda img,capt: (load_img(img),capt)):
        preds = []
        for t in [0.0,0.5,1.0]:
            result = model.simple_gen(img)
            preds.append(result)


问:
Read Google Drive file in Javascript on New Google Sites web page
I have a new Google Sites web page with some Google Maps javascript to display a load of places (post offices in Somerset).  I have an XML file with the data on my Google Drive file with public access via the URL.  How do I read the Google Drive file in my Google Sites web page javascript ?

It seems like a simple thing to do, the Google Drive web page is generally accessible via the URL
https://drive.google.com/file/d/18tCKlaTfgzU0JPB0q7xQHqdQuJviOW8z/view?usp=sharing - there is nothing secret about the contents but I get stopped by the security from linking from one bit of Google to another even though the Google Sites web page is on my Google Drive.

I tried going down the Google Drive OAuth route but got into a twisty maze of web pages that just took me back to where I started - it gets to the point of "generate key" and then gives me a link that doesn't go anywhere.

At the moment I've taken the easy way out and imbedded the XML data in my web page !

Help please - it seems like it ought to be so easy but it ain't !


问:
Multiple API calls using axios and saving it into a state
I am building a site where I want to show the pictures of different sites for a particular location. I am using an API to get the data the problem is I've to make multiple API calls to get the pictures
1st API call is to get the geo location of a city selected by the user
2nd API call is to get the sites in that city through the geo coordinates received from the 1st API. Data received is in an array with object for each site with its unique id
3rd API call is to iterate through the array and pass in the unique id to get the picture link and save it into a state. I am using array.map function and sending multiple api calls but the results I am getting  says promise is fulfilled but results are undefined

Also how can i delay each of the 3rd api call by 1 sec as the api calls are limited

Thanks in advance

```<code>async function getData (location) {
  await axios.get(`https://api.opentripmap.com/0.1/en/places/geoname?name=${location}&apikey=${API_KEY}`).then(async (response) => {return await axios.get(`https://api.opentripmap.com/0.1/en/places/radius?radius=1000&lon=${response.data.lon}&lat=${response.data.lat}&limit=8&apikey=${API_KEY}`)}).then(async (response)=>{return Promise.all(response.data.features.map(async (item) => {
    await axios.get(`https://api.opentripmap.com/0.1/en/places/xid/${item.properties.xid}?apikey=${API_KEY}`)
  }))}).then((response) => {
   setData([...data, response])
  })
}
</code>```

Body:
I am building a site where I want to show the pictures of different sites for a particular location. I am using an API to get the data the problem is I've to make multiple API calls to get the pictures
1st API call is to get the geo location of a city selected by the user
2nd API call is to get the sites in that city through the geo coordinates received from the 1st API. Data received is in an array with object for each site with its unique id
3rd API call is to iterate through the array and pass in the unique id to get the picture link and save it into a state. I am using array.map function and sending multiple api calls but the results I am getting  says promise is fulfilled but results are undefined

Also how can i delay each of the 3rd api call by 1 sec as the api calls are limited

Thanks in advance

async function getData (location) {
  await axios.get(`https://api.opentripmap.com/0.1/en/places/geoname?name=${location}&apikey=${API_KEY}`).then(async (response) => {return await axios.get(`https://api.opentripmap.com/0.1/en/places/radius?radius=1000&lon=${response.data.lon}&lat=${response.data.lat}&limit=8&apikey=${API_KEY}`)}).then(async (response)=>{return Promise.all(response.data.features.map(async (item) => {
    await axios.get(`https://api.opentripmap.com/0.1/en/places/xid/${item.properties.xid}?apikey=${API_KEY}`)
  }))}).then((response) => {
   setData([...data, response])
  })
}


问:
Why are my folium popup markers showing my entire dash?
I have created a Dash and inside that i am displaying a folium map along with some other figures. There a markers on the map indicating an earthquake of significance and when clicked there is a popup showing a plotly bar chart with information about earthquakes in the region. I save the map as a .html file and when i open it in the browser it works perfectly. The problem is that when i try to do the same thing through my Dash, the popups show my ENTIRE Dash instead of the popups i get when i just open the .html in my browser.

Its basically a dash-ception inside my folium map. Why is this happening?

Here is the html.Div that contains the iFrame:

```<code>    html.Div(html.Iframe(id='map', srcDoc=open ('earthquakes.html', 'r').read(), width = '100%', height = '600')),

</code>```

Example:

What it should look like:
What it looks like:

I tried changing the html.Div(html.IFrame()) back and forth but I honestly have no clue why this is happening, as it works perfectly outside dash, so its hard for me to get any further with it.

Body:
I have created a Dash and inside that i am displaying a folium map along with some other figures. There a markers on the map indicating an earthquake of significance and when clicked there is a popup showing a plotly bar chart with information about earthquakes in the region. I save the map as a .html file and when i open it in the browser it works perfectly. The problem is that when i try to do the same thing through my Dash, the popups show my ENTIRE Dash instead of the popups i get when i just open the .html in my browser.

Its basically a dash-ception inside my folium map. Why is this happening?

Here is the html.Div that contains the iFrame:

    html.Div(html.Iframe(id='map', srcDoc=open ('earthquakes.html', 'r').read(), width = '100%', height = '600')),

Example:

What it should look like:
What it looks like:

I tried changing the html.Div(html.IFrame()) back and forth but I honestly have no clue why this is happening, as it works perfectly outside dash, so its hard for me to get any further with it.


问:
Facebook - Kochava (MMP) integration issue with SKAdNetwork
I have an a flutter app integrated with Kochava, where Kochava is selected to receive SKAdNetwork data. The app is also setup in facebook so that install campaigns can be run. However, when I select it in campaign manager, I get "The Mobile Measurement Partner app used to configure events for this app doesn't currently support SKAdNetwork events. To run iOS 14+ campaigns for this app, choose a different app event connection for SKAdNetwork in Events Manager.".

In the Events Manager, Kochava is configured as the source of SKAdNetwork events (and the configuration screen is "all green"). Also, on the dashboard I can see "fb_auto_published" app install event from MMP and the app screen shows a date of "last mobile app install" (those are all likely originating from iOS14+ live testing).

I want to avoid integration with Facebook SDK and having Facebook as the recipient of SKAdNetwork data (mainly because it feels like a less clean setup with MMP getting some events and Facebook some - while other networks like Twitter are also integrated).

I have tried replicating this setup under clean ad manager and setting up new app in Facebook (no change - still doesn't work). The Kochava-side configuration has been reviewed by Kochava team and looks good to them. Facebook's business support directs me to developer support but only after "recommended" step of Facebook SDK is completed (which I am a bit reluctant to do).


问:
How can I get Bootstrap Modal to refresh in Angular?
The following modal contains bookmarks added by the user. The user can delete unwanted bookmarks. Upon delete, the underlying component data is refreshed accordingly but the modal still shows the same data. If one out of three rows is deleted by the user, for instance, the modal still shows three rows even though the refrehsed component now has two rows.

```<code><div class="col">
  <div class="modal fade" role="dialog" tabindex="-1" id="viewBookmarksModal">
<div class="modal-dialog modal-lg" role="document">
  <div class="modal-content">
    <div class="modal-header">
      <h4 class="modal-title">View Bookmarks</h4>
    </div>
    <div class="modal-body">
        <div class="row mb-2" *ngFor="let bookmark of site?.bookmarks">
          <div class="col-12 col-lg-3">
            <a>
              <span>{{bookmark.title}}</span>
            </a>
          </div>
          <div class="col-12 col-lg-5 blue">
            <a>
              <span>{{bookmark.link}}</span>
            </a>
          </div>
          <div class="col-2 col-lg-2">
            <a>
              <button class="btn" type="button"
                (click)="deleteBookmark(site?._id, bookmark?._id)">
                <i class="fa fa-remove red" ></i>
              </button>
            </a>
          </div>
        </div>
    </div>
  </div>
</div>
</code>```

The deleteBookmark function of the component. Here I set a flag, this.isRefreshViewBookmarksModal = true,  to indicate a subsequent refresh would be required.

```<code>public deleteBookmark = (siteId, bookmarkId) => {
   this.isRefreshViewBookmarksModal = true;
   this.categoriesService.deleteBookmark(this.category?._id, siteId, bookmarkId )
 }
</code>```

The component subscribes to redux and receives the new set of data after delete. Here I test if the isRefreshViewBookmarksModal is true and call refreshViewBookmarksModal method to refresh the modal.

```<code>private subscribeToReduxStores = () => {
  const categories$ = this.store.select((state) => {
   return state.categoriesState.categories
 })

 categories$.subscribe(categories => {
   this.categories = categories;
   this.setActiveCategory(this.processingCategory || categories[0]);

   if(this.isRefreshViewBookmarksModal) {
     this.refreshViewBookmarksModal();
     this.isRefreshViewBookmarksModal = false;
   }
 })
</code>```

}

My attempts in refreshViewBookmarksModal  to refresh the modal fail.

```<code>private refreshViewBookmarksModal = () => {
  this.viewBookmarksModal = new window.bootstrap.Modal(
  document.getElementById('viewBookmarksModal')
  );

  //Attempt 1
  // this.viewBookmarksModal.dispose();
  // this.viewBookmarksModal.show();

  //Attempt 2
  // window.location.reload()
}
</code>```

Body:
The following modal contains bookmarks added by the user. The user can delete unwanted bookmarks. Upon delete, the underlying component data is refreshed accordingly but the modal still shows the same data. If one out of three rows is deleted by the user, for instance, the modal still shows three rows even though the refrehsed component now has two rows.

View Bookmarks

              {{bookmark.title}}

              {{bookmark.link}}

              <button class="btn" type="button"
                (click)="deleteBookmark(site?._id, bookmark?._id)">

              </button>

The deleteBookmark function of the component. Here I set a flag, this.isRefreshViewBookmarksModal = true,  to indicate a subsequent refresh would be required.

public deleteBookmark = (siteId, bookmarkId) => {
   this.isRefreshViewBookmarksModal = true;
   this.categoriesService.deleteBookmark(this.category?._id, siteId, bookmarkId )
 }

The component subscribes to redux and receives the new set of data after delete. Here I test if the isRefreshViewBookmarksModal is true and call refreshViewBookmarksModal method to refresh the modal.

private subscribeToReduxStores = () => {
  const categories$ = this.store.select((state) => {
   return state.categoriesState.categories
 })

 categories$.subscribe(categories => {
   this.categories = categories;
   this.setActiveCategory(this.processingCategory || categories[0]);

   if(this.isRefreshViewBookmarksModal) {
     this.refreshViewBookmarksModal();
     this.isRefreshViewBookmarksModal = false;
   }
 })

}

My attempts in refreshViewBookmarksModal  to refresh the modal fail.

private refreshViewBookmarksModal = () => {
  this.viewBookmarksModal = new window.bootstrap.Modal(
  document.getElementById('viewBookmarksModal')
  );

  //Attempt 1
  // this.viewBookmarksModal.dispose();
  // this.viewBookmarksModal.show();

  //Attempt 2
  // window.location.reload()
}