问:
Why isn't my train_images printing the numpy array out but instead the length?
What am I doing wrong? I'm putting the images in the train_test_split, and then I'm getting the length of it as result. I dont know what the problem is?

The result I'm getting


来源: stackexchange

问:
Google play console | Pre-launch report | Unable to start receiver com.google.android.finsky.instantapps.PhenotypeUpdateReceiver
I am developing a mobile application with ionic capacitor. 4 days a go we have uploaded our first testing version to google play console,
we had 3 Crashes reports in different devices, all with the same message

```<code>java.lang.RuntimeException: Unable to start receiver com.google.android.finsky.instantapps.PhenotypeUpdateReceiver:
        java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.gms.phenotype.UPDATE cmp=com.android.vending/com.google.android.finsky.instantapps.PhenotypeUpdateService }:
         app is in background uid UidRecord{b74db5c u0a192 TRNB bg:+1m35s296ms idle change:uncached procs:4 seq(0,0,0)}
</code>```

we have tried to reproduce the error using emulators with exactlly what is mentioned in the report with no luck.

Below is the fulls stack we have for the error

```<code> FATAL EXCEPTION: main
Process: com.android.vending:instant_app_installer, PID: 19791
java.lang.RuntimeException: Unable to start receiver com.google.android.finsky.instantapps.PhenotypeUpdateReceiver: java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.gms.phenotype.UPDATE cmp=com.android.vending/com.google.android.finsky.instantapps.PhenotypeUpdateService }: app is in background uid UidRecord{b74db5c u0a192 TRNB bg:+1m35s296ms idle change:uncached procs:4 seq(0,0,0)}
    at android.app.ActivityThread.handleReceiver(ActivityThread.java:4035)
    at android.app.ActivityThread.access$1400(ActivityThread.java:237)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1924)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:223)
    at android.app.ActivityThread.main(ActivityThread.java:7664)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.gms.phenotype.UPDATE cmp=com.android.vending/com.google.android.finsky.instantapps.PhenotypeUpdateService }: app is in background uid UidRecord{b74db5c u0a192 TRNB bg:+1m35s296ms idle change:uncached procs:4 seq(0,0,0)}
    at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1715)
    at android.app.ContextImpl.startService(ContextImpl.java:1670)
    at android.content.ContextWrapper.startService(ContextWrapper.java:720)
    at alj.a(PG:2)
    at alm.a(PG:3)
    at wnv.a(PG:2)
    at com.google.android.finsky.instantapps.PhenotypeUpdateReceiver.onReceive(PG:6)
    at android.app.ActivityThread.handleReceiver(ActivityThread.java:4026)
</code>```

this is our first try to publish a mobile application, and we are not sure if this crash report is why the application is not being approved or not

ContentLicense: CC BY-SA 4.0

Body:
I am developing a mobile application with ionic capacitor. 4 days a go we have uploaded our first testing version to google play console,
we had 3 Crashes reports in different devices, all with the same message

java.lang.RuntimeException: Unable to start receiver com.google.android.finsky.instantapps.PhenotypeUpdateReceiver:
        java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.gms.phenotype.UPDATE cmp=com.android.vending/com.google.android.finsky.instantapps.PhenotypeUpdateService }:
         app is in background uid UidRecord{b74db5c u0a192 TRNB bg:+1m35s296ms idle change:uncached procs:4 seq(0,0,0)}

we have tried to reproduce the error using emulators with exactlly what is mentioned in the report with no luck.

Below is the fulls stack we have for the error

 FATAL EXCEPTION: main
Process: com.android.vending:instant_app_installer, PID: 19791
java.lang.RuntimeException: Unable to start receiver com.google.android.finsky.instantapps.PhenotypeUpdateReceiver: java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.gms.phenotype.UPDATE cmp=com.android.vending/com.google.android.finsky.instantapps.PhenotypeUpdateService }: app is in background uid UidRecord{b74db5c u0a192 TRNB bg:+1m35s296ms idle change:uncached procs:4 seq(0,0,0)}
    at android.app.ActivityThread.handleReceiver(ActivityThread.java:4035)
    at android.app.ActivityThread.access$1400(ActivityThread.java:237)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1924)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:223)
    at android.app.ActivityThread.main(ActivityThread.java:7664)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { act=com.google.android.gms.phenotype.UPDATE cmp=com.android.vending/com.google.android.finsky.instantapps.PhenotypeUpdateService }: app is in background uid UidRecord{b74db5c u0a192 TRNB bg:+1m35s296ms idle change:uncached procs:4 seq(0,0,0)}
    at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1715)
    at android.app.ContextImpl.startService(ContextImpl.java:1670)
    at android.content.ContextWrapper.startService(ContextWrapper.java:720)
    at alj.a(PG:2)
    at alm.a(PG:3)
    at wnv.a(PG:2)
    at com.google.android.finsky.instantapps.PhenotypeUpdateReceiver.onReceive(PG:6)
    at android.app.ActivityThread.handleReceiver(ActivityThread.java:4026)

this is our first try to publish a mobile application, and we are not sure if this crash report is why the application is not being approved or not


问:
reCaptcha verification fails with uncaught promise error
I have encountered a problem when trying to implement reCAPTCHA v3 onto a website to prevent spam emails.

The problem I currently have is that the reCAPTCHA gives me an error that loos like this:

Uncaught (in promise) Ogiltigt åtgärdsnamn. Namnet får endast
innehålla bokstäverna A–Za–z eller _. Ta inte med användarspecifik
information.

Since I'm in Sweden the error code for some reason is not in English but a rough translation makes the error something like this:

Uncaught (in promise) Invalid action name. The name may only contain
the letters A–Za–z or _. Do not include user-specific information.

At recaptcha_sv.js:361 and at contact.html:1

I believe it has something to do with the email using a "@" symbol as well as a ".", example "this@gmail.com", or that the name uses a space or something like this. I have googled for hours but just cant simply find my answers or the root for the problem.

To give some more context to the problem I will show the code but not the keys for the recaptcha.

contact.html

```<code><body>
        <!-- Formuläret för att skicka ett E-Mail via sidan -->
        <div class="contact-container" id="contact">
            <div class="contact">
                <h1>Kontakta oss här!</h1>
                <form method="post" accept-charset="UTF-8" class="contact-form" id="contact-form">
                    <input type="hidden" value="recaptchaResponse" id="recaptchaResponse">
                    <input class="form-control" type="text" name="name" id="name" placeholder="Namn" required>
                    <input class="form-control" type="text" name="email" id="email" placeholder="E-Mail" required>
                    <input class="form-control" type="tel" name="tel" id="tel" placeholder="Telefonnummer" required>
                    <input class="form-control" type="text" name="reg" id="reg" placeholder="Regnummer" required>
                    <textarea name="msg" id="msg" cols="30" rows="10" placeholder="Medelande" required></textarea>

                    <button type="submit" value="Skicka Mail">Skicka Mail</button>
                </form>
            </div>
        </div>
    </div>

</body>
<script src="https://www.google.com/recaptcha/api.js?render=my-own-site-key"></script>
<script src="/js/init.js"></script>
</html>
</code>```

The init.js

```<code>window.addEventListener("load", function(){
    "use strict";
    const form = document.querySelector(".contact-form")
    form.addEventListener("submit", function(event){
        event.preventDefault()
        let fields = document.querySelectorAll(".contact-form .form-control")
        let valid = true;
        for (var i = 0; i < fields.length; i++){
            if(fields[i].value === ""){
                valid = false;
            }
        }
        if (valid){
            grecaptcha.ready(function(){
                grecaptcha
                    .execute("my-own-site-key", {
                        action: "contact-form"
                    })
                    .then(function(token){

                        let recaptchaResponse = document.getElementById("recaptchaResponse")
                        recaptchaResponse.value = token

                        fetch("/sendmail.php", {
                            method: "POST",
                            body: new FormData(form),
                        })
                        .then((response) => response.text())
                        .then((response) => {
                            console.log(response)
                        })
                    })
            })
        }
    })
})
</code>```

Lastly the sendmail.php

```<code><?php

    function isValid(){
        if(
            $_POST["name"] != "" &&
            $_POST["tel"] != "" &&
            $_POST["email"] != "" &&
            $_POST["msg"] != "" &&
            $_POST["reg"] != ""
        ) {
            return true;
        }
        return false;
    }

    // Declare variables
    $success_output = '';
    $error_output = '';

    if (isValid()){
        $recaptcha_url = "https://www.google.com/recaptcha/api/siteverify"; // URL to the reCAPTCHA servers
        $recaptcha_secret = "my-little-secret-key" // reCAPTCHA secret key
        $recaptcha_response = $_POST["recaptchaResponse"]; // reCAPTCHA response from the servers, added to form during runtime
        $recaptcha = file_get_contents($recaptcha_url."?secret=".$recaptcha_secret."&response=".$recaptcha_response); // send request to reCAPTCHA servers
        $recaptcha = json_decode($recaptcha); // decode the response
        if($recaptcha->success == true && $recaptcha->score >= 0.5 && $recaptcha->action == "contact-form"){
            // Send the email

            $Name = $_POST["name"];
            $Tel = $_POST["tel"];
            $MailFrom = $_POST["email"];
            $Message = UTF8_decode($_POST["msg"]);
            $Reg = $_POST["reg"];

            $MailTo  = "secret@mail.se";
            $Subject = "".$Name." | Thissite.se";

            $Headers = array(
                'From'         => $MailTo,
                'Reply-To'     => $MailTo,
                'MIME-Version' => '1.0',
                'Content-type' => 'text/html',
                'charset'      => 'UTF-8',
                'X-Mailer'     => 'PHP/' . phpversion()
            );

            $Msg = 'Namn: ' . $Name . '<br />Telefonnummer: ' . $Tel . '<br />E-mail: ' . $MailFrom . '<br />Regnummer: ' . $Reg . '<br /><br />Meddelande: ' . wordwrap($Message, 50);

            $test = mail($MailTo, $Subject, $Msg, $Headers);

            if ($test === true) {
                $success_output = "message was sent successfully!";
                header("Location: redirect.html");
            } else {
                $error_output = "mail error";
                echo "Meddelandet kunde inte skickas, vänligen kontakta oss på följande mail. (axel@brannhult.se)";
            }

        } else {
            // reCAPTCHA failed, dont send mail
            $error_output = "probably a robot";
            echo "Vi tror att du är en robot, är du inte en robot så vänligen kontakta oss på följande mail. (axel@brannhult.se) "
        }
    }

    // Output error or success message
    $output = [
        'error' => $error_output,
        'success' => $success_output
    ];

    echo json_encode($output);
?>
</code>```

Body:
I have encountered a problem when trying to implement reCAPTCHA v3 onto a website to prevent spam emails.

The problem I currently have is that the reCAPTCHA gives me an error that loos like this:

Uncaught (in promise) Ogiltigt åtgärdsnamn. Namnet får endast
innehålla bokstäverna A–Za–z eller _. Ta inte med användarspecifik
information.

Since I'm in Sweden the error code for some reason is not in English but a rough translation makes the error something like this:

Uncaught (in promise) Invalid action name. The name may only contain
the letters A–Za–z or _. Do not include user-specific information.

At recaptcha_sv.js:361 and at contact.html:1

I believe it has something to do with the email using a "@" symbol as well as a ".", example "this@gmail.com", or that the name uses a space or something like this. I have googled for hours but just cant simply find my answers or the root for the problem.

To give some more context to the problem I will show the code but not the keys for the recaptcha.

contact.html

Kontakta oss här!

                <form method="post" accept-charset="UTF-8" class="contact-form" id="contact-form">
                    <input type="hidden" value="recaptchaResponse" id="recaptchaResponse">
                    <input class="form-control" type="text" name="name" id="name" placeholder="Namn" required>
                    <input class="form-control" type="text" name="email" id="email" placeholder="E-Mail" required>
                    <input class="form-control" type="tel" name="tel" id="tel" placeholder="Telefonnummer" required>
                    <input class="form-control" type="text" name="reg" id="reg" placeholder="Regnummer" required>
                    <textarea name="msg" id="msg" cols="30" rows="10" placeholder="Medelande" required></textarea>

                    <button type="submit" value="Skicka Mail">Skicka Mail</button>
                </form>

The init.js

window.addEventListener("load", function(){
    "use strict";
    const form = document.querySelector(".contact-form")
    form.addEventListener("submit", function(event){
        event.preventDefault()
        let fields = document.querySelectorAll(".contact-form .form-control")
        let valid = true;
        for (var i = 0; i < fields.length; i++){
            if(fields[i].value === ""){
                valid = false;
            }
        }
        if (valid){
            grecaptcha.ready(function(){
                grecaptcha
                    .execute("my-own-site-key", {
                        action: "contact-form"
                    })
                    .then(function(token){

                        let recaptchaResponse = document.getElementById("recaptchaResponse")
                        recaptchaResponse.value = token

                        fetch("/sendmail.php", {
                            method: "POST",
                            body: new FormData(form),
                        })
                        .then((response) => response.text())
                        .then((response) => {
                            console.log(response)
                        })
                    })
            })
        }
    })
})

Lastly the sendmail.php

<?php

    function isValid(){
        if(
            $_POST["name"] != "" &&
            $_POST["tel"] != "" &&
            $_POST["email"] != "" &&
            $_POST["msg"] != "" &&
            $_POST["reg"] != ""
        ) {
            return true;
        }
        return false;
    }

    // Declare variables
    $success_output = '';
    $error_output = '';

    if (isValid()){
        $recaptcha_url = "https://www.google.com/recaptcha/api/siteverify"; // URL to the reCAPTCHA servers
        $recaptcha_secret = "my-little-secret-key" // reCAPTCHA secret key
        $recaptcha_response = $_POST["recaptchaResponse"]; // reCAPTCHA response from the servers, added to form during runtime
        $recaptcha = file_get_contents($recaptcha_url."?secret=".$recaptcha_secret."&response=".$recaptcha_response); // send request to reCAPTCHA servers
        $recaptcha = json_decode($recaptcha); // decode the response
        if($recaptcha->success == true && $recaptcha->score >= 0.5 && $recaptcha->action == "contact-form"){
            // Send the email

            $Name = $_POST["name"];
            $Tel = $_POST["tel"];
            $MailFrom = $_POST["email"];
            $Message = UTF8_decode($_POST["msg"]);
            $Reg = $_POST["reg"];

            $MailTo  = "secret@mail.se";
            $Subject = "".$Name." | Thissite.se";

            $Headers = array(
                'From'         => $MailTo,
                'Reply-To'     => $MailTo,
                'MIME-Version' => '1.0',
                'Content-type' => 'text/html',
                'charset'      => 'UTF-8',
                'X-Mailer'     => 'PHP/' . phpversion()
            );

            $Msg = 'Namn: ' . $Name . '
Telefonnummer: ' . $Tel . '
E-mail: ' . $MailFrom . '
Regnummer: ' . $Reg . '

Meddelande: ' . wordwrap($Message, 50);

            $test = mail($MailTo, $Subject, $Msg, $Headers);

            if ($test === true) {
                $success_output = "message was sent successfully!";
                header("Location: redirect.html");
            } else {
                $error_output = "mail error";
                echo "Meddelandet kunde inte skickas, vänligen kontakta oss på följande mail. (axel@brannhult.se)";
            }

        } else {
            // reCAPTCHA failed, dont send mail
            $error_output = "probably a robot";
            echo "Vi tror att du är en robot, är du inte en robot så vänligen kontakta oss på följande mail. (axel@brannhult.se) "
        }
    }

    // Output error or success message
    $output = [
        'error' => $error_output,
        'success' => $success_output
    ];

    echo json_encode($output);
?>


问:
pytest capture logging from function
For some reason I am unable to obtain the logs genereated in a tested function when using pytest. I've had a read around for all the usual solutions but am stumped, feel like am missing something obvious. Any advice would be much appreciated:

minimum reproducable example:

```<code>import logging

def function_to_test():
    message = "log me"

    logger = logging.getLogger("my-logger")
    logger.setLevel(logging.INFO)
    logger.propagate = True

    logger.info(message)

class Test():

    def test_function(self, caplog):
        with caplog.at_level(logging.INFO, logger="my-logger"):
            function_to_test()

        assert caplog.text != ""
</code>```

Title: pytest capture logging from function

Body:
For some reason I am unable to obtain the logs genereated in a tested function when using pytest. I've had a read around for all the usual solutions but am stumped, feel like am missing something obvious. Any advice would be much appreciated:

minimum reproducable example:

import logging

def function_to_test():
    message = "log me"

    logger = logging.getLogger("my-logger")
    logger.setLevel(logging.INFO)
    logger.propagate = True

    logger.info(message)

class Test():

    def test_function(self, caplog):
        with caplog.at_level(logging.INFO, logger="my-logger"):
            function_to_test()

        assert caplog.text != ""


问:
I don't understand why this function return None
```<code># Compute the sum of every single digits of variable.
def transform(variable):
    if variable < 10:
        return variable
    else:
        return variable % 10 + transform(variable // 10)

# Count the number of times executing transform method
# until final result of transform method is single digit.
# Then, return final result of transform method and the number of times.
def f(variable, c = 0):
    if variable < 10 and c == 0:
        return variable, c
    else:
        variable = transform(variable)
        c += 1
        if variable < 10:
            print(variable, c) # Before return, i'd like to check these output.
            return variable, c
        else:
            f(variable, c)

if __name__ == "__main__":
    x = int(input())
    x = f(x)
    print(x)
</code>```

Through 'print(variable, c)', I checked the function's output and
expected that I get variable, c which are both integers.
But, when i input integers like 1234567, i get None, the function's output even 1, 3 is printed as variable, c.
I don't understand this mismatch.

Body:
# Compute the sum of every single digits of variable.
def transform(variable):
    if variable < 10:
        return variable
    else:
        return variable % 10 + transform(variable // 10)

# Count the number of times executing transform method
# until final result of transform method is single digit.
# Then, return final result of transform method and the number of times.
def f(variable, c = 0):
    if variable < 10 and c == 0:
        return variable, c
    else:
        variable = transform(variable)
        c += 1
        if variable < 10:
            print(variable, c) # Before return, i'd like to check these output.
            return variable, c
        else:
            f(variable, c)

if __name__ == "__main__":
    x = int(input())
    x = f(x)
    print(x)

Through 'print(variable, c)', I checked the function's output and
expected that I get variable, c which are both integers.
But, when i input integers like 1234567, i get None, the function's output even 1, 3 is printed as variable, c.
I don't understand this mismatch.


问:
WinForms - Form with static property not being collected by GC
I am trying to find the reasons for the increase of memory usage over time in my app, specially when a user opens and closes a lot of forms. I am doing some tests trying to understand what are the things that I may be doing wrong, and I found a case I can't understand: if I instantiate a form with a static AutoCompleteStringCollection assigned to a ComboBox, the form finalizer is not called until I close the app. If I remove the static keyword, the finalizer is called in the next click and works as expected.

I was able to reproduce it in an empty project using .NET 6: every time I click the button, the memory keeps growing with every instance of the big Bitmap in Form2 and never gets released. Without the static keyword, only one Bitmap is kept in memory, the last one.

My question is: why a static variable not referenced anywhere else is keeping the instance of the Form2 from beeing collected by the GC?

```<code>public class Form1 : Form
    {
        public Form1()
        {
            var button = new Button() { Text = "Click Me" };
            button.Click += (s, e) =>
            {
                Form2 dummy = new Form2();
                dummy = null;

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();

            };
            this.Controls.Add(button);
        }
    }

    public class Form2 : Form
    {
        //Remove static keyword for the finalizer to be called
        private static AutoCompleteStringCollection SearchText = new AutoCompleteStringCollection();
        private Bitmap bigObject = new Bitmap(1000, 10000);

        public Form2()
        {
            var combo = new ComboBox();
            combo.AutoCompleteCustomSource = SearchText;
            this.Controls.Add(combo);
        }

        ~Form2()
        {
            //Not being called until I close the app
        }
    }
</code>```
```<code></code>```

Body:
I am trying to find the reasons for the increase of memory usage over time in my app, specially when a user opens and closes a lot of forms. I am doing some tests trying to understand what are the things that I may be doing wrong, and I found a case I can't understand: if I instantiate a form with a static AutoCompleteStringCollection assigned to a ComboBox, the form finalizer is not called until I close the app. If I remove the static keyword, the finalizer is called in the next click and works as expected.

I was able to reproduce it in an empty project using .NET 6: every time I click the button, the memory keeps growing with every instance of the big Bitmap in Form2 and never gets released. Without the static keyword, only one Bitmap is kept in memory, the last one.

My question is: why a static variable not referenced anywhere else is keeping the instance of the Form2 from beeing collected by the GC?

public class Form1 : Form
    {
        public Form1()
        {
            var button = new Button() { Text = "Click Me" };
            button.Click += (s, e) =>
            {
                Form2 dummy = new Form2();
                dummy = null;

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();

            };
            this.Controls.Add(button);
        }
    }

    public class Form2 : Form
    {
        //Remove static keyword for the finalizer to be called
        private static AutoCompleteStringCollection SearchText = new AutoCompleteStringCollection();
        private Bitmap bigObject = new Bitmap(1000, 10000);

        public Form2()
        {
            var combo = new ComboBox();
            combo.AutoCompleteCustomSource = SearchText;
            this.Controls.Add(combo);
        }

        ~Form2()
        {
            //Not being called until I close the app
        }
    }


问:
Inconsistency between decision_function and predict methods in OvO SVC in Scikit learn package
I have observed that there are differences in the implementation of the decision_function and the predict methods the one versus one multi class implementation of SVC in the sci-kit learn package. Is there a way to align this issue or is this indeed a bug in the implementation?

I was solving a multi classification problem with 11 classes with around 36 initial feature variables (160 features after some transformation e.g. scaling, missing value indicators etc.) and over 6,000 observations using the OvO linear SVC implemented in sci-kit learn. In cases where there are ties in votes for 2 or more of the 55 classifiers generated by the OvO SVC, the decision_function method uses confidences to break the ties in this case (see the source code from line 479 -521 here ). However, the predict method implements LIBSVM and a close look at the C++ code reveals that in the case of ties, the first runtime index in the loop is kept as the decision for the OvO linear SVC (see the source code from line 2865 to 2899 here).

For example, if there is a tie between class 5 and 7 with 17 votes each, class 5 will be taken to be the decision of the predict function since 5 is taken as the index before 7 in the for loop. I am not allowed to share the actual examples i have, but it is clear from the implementation that these cases my arise simply because this confidences are not implemented in LIBSVM.

I expected the decisions/predictions of both the decision_function method and the predict method to give the same results for the same parameters of the OvO SVC. In this particular multi classification case, whenever there are ties, there are some cases where the decision_function method give different results to those of the predict method. In my, actually the implementation of the decision function is more correct since it involves some quantified justification for making the decision in case of ties.

Is this really how the implementation should be or is this a bug in the implementation? Would it be possible to implement this confidence in LIBSVM package as part of the standard implementation ? What would these custom modifications look like? I mean somehow I don't think I am the first person to see this issue so I am quite sure there is something I am missing, but I have not found this case discussed anywhere in this forum or any other mains stream python forum. I would appreciate any help and clarification from the experts here.


问:
VTK module import error on Windows (ModuleNotFoundError: No module named 'vtkIOImagePython')
This is a follow-up to the question posted here

I am trying to run the following example (https://github.com/K3D-tools/K3D-jupyter/blob/3fef1ea419a84a51c8aed56cb285b9fcf0a18c9a/examples/volume_renderer.ipynb) in jupyter notebook.

```<code>import k3d
import math
import numpy as np
import nibabel as nib
from k3d.helpers import download
import ipywidgets as widgets
import vtk
from vtkmodules.util import numpy_support
basic_color_maps = [(attr, getattr(k3d.basic_color_maps, attr)) for attr in dir(k3d.basic_color_maps) if
                    not attr.startswith('__')]
paraview_color_maps = [(attr, getattr(k3d.paraview_color_maps, attr)) for attr in dir(k3d.paraview_color_maps) if
                       not attr.startswith('__')]
matplotlib_color_maps = [(attr, getattr(k3d.matplotlib_color_maps, attr)) for attr in dir(k3d.matplotlib_color_maps)
                         if not attr.startswith('__')]
colormaps = basic_color_maps + paraview_color_maps + matplotlib_color_maps

filename = download('https://vedo.embl.es/examples/data/embryo.slc')
reader = vtk.vtkSLCReader()
reader.SetFileName(filename)
reader.Update()
vti = reader.GetOutput()

bounds = vti.GetBounds()
x, y, z = vti.GetDimensions()
img = numpy_support.vtk_to_numpy(vti.GetPointData().GetArray(0)).reshape(-1, y, x)

tf_editor = k3d.transfer_function_editor()
volume = k3d.volume(img.astype(np.float16))

@widgets.interact(x=widgets.Dropdown(options=colormaps, description='ColorMap:'))
def g(x):
    tf_editor.color_map = np.array(x, dtype=np.float32)

plot = k3d.plot()
plot += volume
tf_editor.display()
plot.display()

a = widgets.jslink((tf_editor, 'color_map'), (volume, 'color_map'))
a = widgets.jslink((tf_editor, 'opacity_function'), (volume, 'opacity_function'))
</code>```

and I get the following error

```<code>
ImportError                               Traceback (most recent call last)
~\anaconda3\lib\site-packages\vtkmodules\vtkIOImage.py in <module>
      4     # use relative import for installed modules
----> 5     from .vtkIOImagePython import *
      6 except ImportError:

ImportError: DLL load failed: The specified module could not be found.

During handling of the above exception, another exception occurred:

ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-5-b5758b6de607> in <module>
      5 from k3d.helpers import download
      6 import ipywidgets as widgets
----> 7 import vtk
      8 from vtkmodules.util import numpy_support
      9 basic_color_maps = [(attr, getattr(k3d.basic_color_maps, attr)) for attr in dir(k3d.basic_color_maps) if

~\anaconda3\lib\site-packages\vtk.py in <module>
     30     all_spec = importlib.util.find_spec('vtkmodules.all')
     31     all_m = importlib.util.module_from_spec(all_spec)
---> 32     all_spec.loader.exec_module(all_m)
     33
     34     # import vtkmodules

~\anaconda3\lib\site-packages\vtkmodules\all.py in <module>
     54 from .vtkFiltersTopology import *
     55 from .vtkFiltersVerdict import *
---> 56 from .vtkIOImage import *
     57 from .vtkImagingHybrid import *
     58 from .vtkInfovisLayout import *

~\anaconda3\lib\site-packages\vtkmodules\vtkIOImage.py in <module>
      7     # during build and testing, the modules will be elsewhere,
      8     # e.g. in lib directory or Release/Debug config directories
----> 9     from vtkIOImagePython import *

ModuleNotFoundError: No module named 'vtkIOImagePython'
</code>```

I checked the files available in vtkmodules folder in the anaconda environment

and I could only find the vtkIOImagePython.pyd file and not vtkIOImagePython.py.

I am not sure how to solve this error. Suggestions will be really helpful.

Body:
This is a follow-up to the question posted here

I am trying to run the following example (https://github.com/K3D-tools/K3D-jupyter/blob/3fef1ea419a84a51c8aed56cb285b9fcf0a18c9a/examples/volume_renderer.ipynb) in jupyter notebook.

import k3d
import math
import numpy as np
import nibabel as nib
from k3d.helpers import download
import ipywidgets as widgets
import vtk
from vtkmodules.util import numpy_support
basic_color_maps = [(attr, getattr(k3d.basic_color_maps, attr)) for attr in dir(k3d.basic_color_maps) if
                    not attr.startswith('__')]
paraview_color_maps = [(attr, getattr(k3d.paraview_color_maps, attr)) for attr in dir(k3d.paraview_color_maps) if
                       not attr.startswith('__')]
matplotlib_color_maps = [(attr, getattr(k3d.matplotlib_color_maps, attr)) for attr in dir(k3d.matplotlib_color_maps)
                         if not attr.startswith('__')]
colormaps = basic_color_maps + paraview_color_maps + matplotlib_color_maps

filename = download('https://vedo.embl.es/examples/data/embryo.slc')
reader = vtk.vtkSLCReader()
reader.SetFileName(filename)
reader.Update()
vti = reader.GetOutput()

bounds = vti.GetBounds()
x, y, z = vti.GetDimensions()
img = numpy_support.vtk_to_numpy(vti.GetPointData().GetArray(0)).reshape(-1, y, x)

tf_editor = k3d.transfer_function_editor()
volume = k3d.volume(img.astype(np.float16))

@widgets.interact(x=widgets.Dropdown(options=colormaps, description='ColorMap:'))
def g(x):
    tf_editor.color_map = np.array(x, dtype=np.float32)

plot = k3d.plot()
plot += volume
tf_editor.display()
plot.display()

a = widgets.jslink((tf_editor, 'color_map'), (volume, 'color_map'))
a = widgets.jslink((tf_editor, 'opacity_function'), (volume, 'opacity_function'))

and I get the following error

ImportError                               Traceback (most recent call last)
~\anaconda3\lib\site-packages\vtkmodules\vtkIOImage.py in <module>
      4     # use relative import for installed modules
----> 5     from .vtkIOImagePython import *
      6 except ImportError:

ImportError: DLL load failed: The specified module could not be found.

During handling of the above exception, another exception occurred:

ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-5-b5758b6de607> in <module>
      5 from k3d.helpers import download
      6 import ipywidgets as widgets
----> 7 import vtk
      8 from vtkmodules.util import numpy_support
      9 basic_color_maps = [(attr, getattr(k3d.basic_color_maps, attr)) for attr in dir(k3d.basic_color_maps) if

~\anaconda3\lib\site-packages\vtk.py in <module>
     30     all_spec = importlib.util.find_spec('vtkmodules.all')
     31     all_m = importlib.util.module_from_spec(all_spec)
---> 32     all_spec.loader.exec_module(all_m)
     33
     34     # import vtkmodules

~\anaconda3\lib\site-packages\vtkmodules\all.py in <module>
     54 from .vtkFiltersTopology import *
     55 from .vtkFiltersVerdict import *
---> 56 from .vtkIOImage import *
     57 from .vtkImagingHybrid import *
     58 from .vtkInfovisLayout import *

~\anaconda3\lib\site-packages\vtkmodules\vtkIOImage.py in <module>
      7     # during build and testing, the modules will be elsewhere,
      8     # e.g. in lib directory or Release/Debug config directories
----> 9     from vtkIOImagePython import *

ModuleNotFoundError: No module named 'vtkIOImagePython'

I checked the files available in vtkmodules folder in the anaconda environment

and I could only find the vtkIOImagePython.pyd file and not vtkIOImagePython.py.

I am not sure how to solve this error. Suggestions will be really helpful.


问:
How to install exact specific redis version in Dockerfile Ubuntu 20.04
I need to install redis 7.0.5 version in Dockerfile.

Below commands installing 7.0.7 version

```<code>curl https://packages.redis.io/gpg | apt-key add - && echo "deb https://packages.redis.io/deb $(lsb_release -cs) main" | tee /etc/apt/sources.list.d/redis.list && apt-get update && apt-get install redis -y; \

</code>```

I have tried below commands but it is installing latest version

```<code>curl https://packages.redis.io/gpg | apt-key add - && echo "deb https://packages.redis.io/deb $(lsb_release -cs) main" | tee /etc/apt/sources.list.d/redis.list && apt-get update && apt-get install redis -y; \
</code>```

Body:
I need to install redis 7.0.5 version in Dockerfile.

Below commands installing 7.0.7 version

curl https://packages.redis.io/gpg | apt-key add - && echo "deb https://packages.redis.io/deb $(lsb_release -cs) main" | tee /etc/apt/sources.list.d/redis.list && apt-get update && apt-get install redis -y; \

I have tried below commands but it is installing latest version

curl https://packages.redis.io/gpg | apt-key add - && echo "deb https://packages.redis.io/deb $(lsb_release -cs) main" | tee /etc/apt/sources.list.d/redis.list && apt-get update && apt-get install redis -y; \


问:
Pointer to Pointer in Julia
I need to do allocate memory in a ccallable function determine_string(...) in Julia, see code below:

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

module ProductionCode
    import Printf

    Base.@ccallable function determine_string(msg_p_p::Ptr{Ptr{Cchar}})::Nothing
        println("determine_string(): msg_p_p ", msg_p_p)

        json_string::String = join([Printf.@sprintf("%15.7f", rand()) for i in 1:10])
        size_for_malloc::Csize_t = 1 + length(json_string)

        msg_p_p = @ccall malloc(size_for_malloc::Csize_t)::Ptr{Nothing}
        println("determine_string(): msg_p_p ", msg_p_p)

        println("determine_string(): json_string ", json_string)

        @ccall memcpy(msg_p_p::Ptr{Ptr{Cchar}}, json_string::Ptr{Cchar}, size_for_malloc::Csize_t)::Cvoid

        return nothing
    end

end # ProductionCode

function test()::Nothing
    msg_p::Ptr{Cchar} = C_NULL
    msg_p_p = <pointer to msg_p>

    println("test(): msg_p ", msg_p)
    ProductionCode.determine_string(msg_p_p)
    println("test(): msg_p ", msg_p)

    @ccall printf("printf: %s\n"::Ptr{Cchar}, msg_p::Ptr{Cchar})::Cint

    julia_string::String = Base.unsafe_string(Base.convert(Ptr{Cchar}, msg_p))

    @ccall free(msg_p::Ptr{Cchar})::Cvoid
    msg_p = C_NULL

    return nothing
end

test()
</code>```

Here determine_string(...) represents a function that determines a variable length string that has to be sent to the caller in C. The caller will use the string and free the memory. For unit test purposes, determine_string(...) has to be callable from Julia too.

Questions:

How to I get the pointer to pointer?

How do I do the malloc? How do I do the memcpy?

Title: Pointer to Pointer in Julia

Body:
I need to do allocate memory in a ccallable function determine_string(...) in Julia, see code below:

#!/usr/bin/env julia

module ProductionCode
    import Printf

    Base.@ccallable function determine_string(msg_p_p::Ptr{Ptr{Cchar}})::Nothing
        println("determine_string(): msg_p_p ", msg_p_p)

        json_string::String = join([Printf.@sprintf("%15.7f", rand()) for i in 1:10])
        size_for_malloc::Csize_t = 1 + length(json_string)

        msg_p_p = @ccall malloc(size_for_malloc::Csize_t)::Ptr{Nothing}
        println("determine_string(): msg_p_p ", msg_p_p)

        println("determine_string(): json_string ", json_string)

        @ccall memcpy(msg_p_p::Ptr{Ptr{Cchar}}, json_string::Ptr{Cchar}, size_for_malloc::Csize_t)::Cvoid

        return nothing
    end

end # ProductionCode

function test()::Nothing
    msg_p::Ptr{Cchar} = C_NULL
    msg_p_p = <pointer to msg_p>

    println("test(): msg_p ", msg_p)
    ProductionCode.determine_string(msg_p_p)
    println("test(): msg_p ", msg_p)

    @ccall printf("printf: %s\n"::Ptr{Cchar}, msg_p::Ptr{Cchar})::Cint

    julia_string::String = Base.unsafe_string(Base.convert(Ptr{Cchar}, msg_p))

    @ccall free(msg_p::Ptr{Cchar})::Cvoid
    msg_p = C_NULL

    return nothing
end

test()

Here determine_string(...) represents a function that determines a variable length string that has to be sent to the caller in C. The caller will use the string and free the memory. For unit test purposes, determine_string(...) has to be callable from Julia too.

Questions:

How to I get the pointer to pointer?

How do I do the malloc? How do I do the memcpy?


问:
condition in dict not push correctely
i have 2 type of questions in quiz plateforme, one choice with radiobutton and multichoice with checkbox,
when the checkbox is in begin of quiz it's work , if it's in second question or in the last i have an error , and in my consol log the rep in not an array

in my html i have data who contain questions ans reps and type of reps:

```<code> <div class="repsCol">

      {% for Question_reponse in Questions_reponses %}

         <div class = "Question {% if forloop.first %}active{% endif %}">

            <div class = "title_section_quiz">
               <h2 class="qst">{{Question_reponse.question}}</h2>

               <div class = "Reponses">

                     <div class = "img_quiz">
                        <img src="{% static 'img/sbg1.png' %}" width="300" height="300" alt="">
                     </div>

                     <div class = "reps_quiz">
                        {% for rep  in Question_reponse.reps %}
                           {% if Question_reponse.question_type == 'normal' %}
                              <label  class="container_radio" ><input type="radio" id = "chSub" class="subRep"  name = "rep" value="{{rep}}">{{rep}}<span class="checkmark_radio"></span></label>
                           {% elif Question_reponse.question_type == 'multiples' %}
                              <label ><input type="checkbox" id = "chSub" class="subRep"  name = "repCheck" value="{{rep}}">{{rep}}</label>

                           {% endif %}
                        {% endfor %}
                     </div>

               </div>

            </div>

         </div>
      {% endfor %}

         <div class = "ButtonNext containerButNxt">
            <input  id = "ButNxt" type="button" onclick="Next()" value = "Question suivate">
         </div>

      </div>
</code>```

and the function next() in jquery :

```<code>const allData = [];
      function Next(){

         //console.log(document.getElementsByClassName('Question active')[0].getElementsByTagName('p')[0].innerText);
         //console.log(document.querySelector('input[name="rep"]:checked').value);
         const resp = document.getElementsByClassName('Question');

         const data = [] ;
         var repcheck = [];
            if(document.querySelector('input[name="rep"]:checked')){
               data.push({
                  qst : document.getElementsByClassName('Question active')[0].getElementsByTagName('h2')[0].innerText,
                  rep : document.querySelector('input[name="rep"]:checked') .value
                  })
            }
            else if (document.querySelector('input[name="repCheck"]:checked')){

               $('input[name="repCheck"]:checked').each(function(){
                  repcheck.push(this.value);
               })
               data.push({
                  qst : document.getElementsByClassName('Question active')[0].getElementsByTagName('h2')[0].innerText,
                  rep : repcheck
                  })
            }

         //console.log(data)

         allData.push({...data});

         for (let i = 0; i < resp.length; i++) {

            let x = resp[i].className
            if (x.search('Question active') !== -1 ) {

               const reps = document.getElementsByClassName('subRep')

               if (i < resp.length -1) {

                  document.getElementsByClassName(resp[i].classList.remove('active'))
                  document.getElementsByClassName(resp[++i].classList.add('active'))

               }
               else if (i === resp.length -1){
                  console.log(allData)
                  console.log('Quiz Términé !');

                  //////////////////////////////////////////////
                  $.ajax({
                     type: 'POST',
                     url: "{% url 'SUBQUIZ' id_quiz %}",
                     data: JSON.stringify({allData}),
                     headers: {
                        "X-Requested-With": "XMLHttpRequest",
                        "X-CSRFToken": getCookie("csrftoken")},

                     success: function (response) {
                         alert(response)

                         $('.Question').hide();
                         $('.ButtonNext').hide();
                         //window.location = "{% url 'AllQuiz' %}"
                         //$('.EndQuiz').css('display','block');
                     },
                     error: function (response) {
                         // alert the error if any error occured
                         alert('Un probléme wowwwwwwwwwww');
                     }

                  })

                  /////////////////////////////////////////////
               }
            }
         }

      }

</code>```

Title: condition in dict not push correctely

Body:
i have 2 type of questions in quiz plateforme, one choice with radiobutton and multichoice with checkbox,
when the checkbox is in begin of quiz it's work , if it's in second question or in the last i have an error , and in my consol log the rep in not an array

in my html i have data who contain questions ans reps and type of reps:

      {% for Question_reponse in Questions_reponses %}

{{Question_reponse.question}}

                        {% for rep  in Question_reponse.reps %}
                           {% if Question_reponse.question_type == 'normal' %}
                              <input type="radio" id = "chSub" class="subRep"  name = "rep" value="{{rep}}">{{rep}}
                           {% elif Question_reponse.question_type == 'multiples' %}
                              <input type="checkbox" id = "chSub" class="subRep"  name = "repCheck" value="{{rep}}">{{rep}}

                           {% endif %}
                        {% endfor %}

      {% endfor %}

            <input  id = "ButNxt" type="button" onclick="Next()" value = "Question suivate">

and the function next() in jquery :

const allData = [];
      function Next(){

         //console.log(document.getElementsByClassName('Question active')[0].getElementsByTagName('p')[0].innerText);
         //console.log(document.querySelector('input[name="rep"]:checked').value);
         const resp = document.getElementsByClassName('Question');

         const data = [] ;
         var repcheck = [];
            if(document.querySelector('input[name="rep"]:checked')){
               data.push({
                  qst : document.getElementsByClassName('Question active')[0].getElementsByTagName('h2')[0].innerText,
                  rep : document.querySelector('input[name="rep"]:checked') .value
                  })
            }
            else if (document.querySelector('input[name="repCheck"]:checked')){

               $('input[name="repCheck"]:checked').each(function(){
                  repcheck.push(this.value);
               })
               data.push({
                  qst : document.getElementsByClassName('Question active')[0].getElementsByTagName('h2')[0].innerText,
                  rep : repcheck
                  })
            }

         //console.log(data)

         allData.push({...data});

         for (let i = 0; i < resp.length; i++) {

            let x = resp[i].className
            if (x.search('Question active') !== -1 ) {

               const reps = document.getElementsByClassName('subRep')

               if (i < resp.length -1) {

                  document.getElementsByClassName(resp[i].classList.remove('active'))
                  document.getElementsByClassName(resp[++i].classList.add('active'))

               }
               else if (i === resp.length -1){
                  console.log(allData)
                  console.log('Quiz Términé !');

                  //////////////////////////////////////////////
                  $.ajax({
                     type: 'POST',
                     url: "{% url 'SUBQUIZ' id_quiz %}",
                     data: JSON.stringify({allData}),
                     headers: {
                        "X-Requested-With": "XMLHttpRequest",
                        "X-CSRFToken": getCookie("csrftoken")},

                     success: function (response) {
                         alert(response)

                         $('.Question').hide();
                         $('.ButtonNext').hide();
                         //window.location = "{% url 'AllQuiz' %}"
                         //$('.EndQuiz').css('display','block');
                     },
                     error: function (response) {
                         // alert the error if any error occured
                         alert('Un probléme wowwwwwwwwwww');
                     }

                  })

                  /////////////////////////////////////////////
               }
            }
         }

      }


问:
django Test discovery Issues
i run ./manage.py test and i got this err

```<code>...

test_create_default_action_with_deadline (masoon.anomalies.tests.anomaly.AnomalyCreateDefaultAction) ... ok
masoon.actions.admin (unittest.loader._FailedTest) ... ERROR
masoon.actions.models (unittest.loader._FailedTest) ... ERROR
masoon.anomalies.models (unittest.loader._FailedTest) ... ERROR
...
======================================================================
ERROR: masoon.actions.admin (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: masoon.actions.admin
Traceback (most recent call last):
  File "/usr/lib/python3.10/unittest/loader.py", line 470, in _find_test_path
    package = self._get_module_from_name(name)
  File "/usr/lib/python3.10/unittest/loader.py", line 377, in _get_module_from_name
    __import__(name)
  File "/home/vahid/project/py/django/masoon/actions/admin/__init__.py", line 1, in <module>
    from .actions import ActionsAdmin
  File "/home/vahid/project/py/django/masoon/actions/admin/actions.py", line 8, in <module>
    class ActionsAdmin(AbstractBaseAdmin):
  File "/home/vahid/project/py/django/masoon/.venv/lib/python3.10/site-packages/django/contrib/admin/decorators.py", line 100, in _model_admin_wrapper
    admin_site.register(models, admin_class=admin_class)
  File "/home/vahid/project/py/django/masoon/.venv/lib/python3.10/site-packages/django/contrib/admin/sites.py", line 126, in register
    raise AlreadyRegistered(msg)
django.contrib.admin.sites.AlreadyRegistered: The model Action is already registered with 'actions.ActionsAdmin'.
</code>```

its not related to register admin. its relayed to discovery test file. unittest discover my admin fils as test and try to run it

filetree:

```<code>...
├── actions
│   ├── admin
│   │   ├── action_report.py
│   │   ├── actions.py
│   │   ├── answer.py
│   │   ├── __init__.py
│   ├── api
│   |   ├── ...
│   ├── tests
│   |   ├── actions.py
│   |   ├── answers.py
...
│   ├── apps.py
│   ├── __init__.py
│   ├── models
│   │   ├── action.py
│   │   ├── action_report.py
│   │   ├── answer.py
│   │   ├── __init__.py
├── infrastructure
│   ├── asgi.py
│   │       ...
│   ├── urls.py
│   └── wsgi.py
├──settings
...
│   ├── apps.py
│   ├── files.py
│   ├── __init__.py
│   ├── logging.py
│   ├── main.py
│   ├── middlewares.py
...
├── manage.py
...
</code>```

but when i run ./manage.py test modulname.tests
all test pass and django dont discover my models as test.

my setting modules __init__ like this :

```<code>...

from .apps import *
from .middlewares import *
from .drf import *

...

</code>```

__init__ of test or models or etc module somthing like this

```<code>from .anomaly import AnomalyCreateDefaultAction, AnomalyAPITest

</code>```

Why is it that unittest  discover my admins classes and my model classes

as a test to run it

Title: django Test discovery Issues

Body:
i run ./manage.py test and i got this err

...

test_create_default_action_with_deadline (masoon.anomalies.tests.anomaly.AnomalyCreateDefaultAction) ... ok
masoon.actions.admin (unittest.loader._FailedTest) ... ERROR
masoon.actions.models (unittest.loader._FailedTest) ... ERROR
masoon.anomalies.models (unittest.loader._FailedTest) ... ERROR
...
======================================================================
ERROR: masoon.actions.admin (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: masoon.actions.admin
Traceback (most recent call last):
  File "/usr/lib/python3.10/unittest/loader.py", line 470, in _find_test_path
    package = self._get_module_from_name(name)
  File "/usr/lib/python3.10/unittest/loader.py", line 377, in _get_module_from_name
    __import__(name)
  File "/home/vahid/project/py/django/masoon/actions/admin/__init__.py", line 1, in <module>
    from .actions import ActionsAdmin
  File "/home/vahid/project/py/django/masoon/actions/admin/actions.py", line 8, in <module>
    class ActionsAdmin(AbstractBaseAdmin):
  File "/home/vahid/project/py/django/masoon/.venv/lib/python3.10/site-packages/django/contrib/admin/decorators.py", line 100, in _model_admin_wrapper
    admin_site.register(models, admin_class=admin_class)
  File "/home/vahid/project/py/django/masoon/.venv/lib/python3.10/site-packages/django/contrib/admin/sites.py", line 126, in register
    raise AlreadyRegistered(msg)
django.contrib.admin.sites.AlreadyRegistered: The model Action is already registered with 'actions.ActionsAdmin'.

its not related to register admin. its relayed to discovery test file. unittest discover my admin fils as test and try to run it

filetree:

...
├── actions
│   ├── admin
│   │   ├── action_report.py
│   │   ├── actions.py
│   │   ├── answer.py
│   │   ├── __init__.py
│   ├── api
│   |   ├── ...
│   ├── tests
│   |   ├── actions.py
│   |   ├── answers.py
...
│   ├── apps.py
│   ├── __init__.py
│   ├── models
│   │   ├── action.py
│   │   ├── action_report.py
│   │   ├── answer.py
│   │   ├── __init__.py
├── infrastructure
│   ├── asgi.py
│   │       ...
│   ├── urls.py
│   └── wsgi.py
├──settings
...
│   ├── apps.py
│   ├── files.py
│   ├── __init__.py
│   ├── logging.py
│   ├── main.py
│   ├── middlewares.py
...
├── manage.py
...

but when i run ./manage.py test modulname.tests
all test pass and django dont discover my models as test.

my setting modules __init__ like this :

...

from .apps import *
from .middlewares import *
from .drf import *

...

__init__ of test or models or etc module somthing like this

from .anomaly import AnomalyCreateDefaultAction, AnomalyAPITest

Why is it that unittest  discover my admins classes and my model classes

as a test to run it


问:
Visual Studio 2022 - Debug .NET 6/7 Background Service with Runas a Different User
I need to execute a .NET 6 or 7 Background Service as a different account user.  Note I need to do this in Visual Studio 2022.  I have referenced "Start external program" functionality under the Debug section of a project's properties and reviewed How to debug a Visual Studio 2022 console application running as a service using a gMSA.

Has anyone figured out how to do this with 2022's new Debug settings?

I've tried different permutations on the following screen, with different arguments, with and without working directory, etc.:

When I debug the application, a console appears requesting the password (I do realize there is switch for caching this) which I provide.  It attempts to start a different console, yet closes extremely quick.  The original console then shows an exit code of 0:

VS's Output window shows the following:

```<code>08:12:35:002    The target process exited without raising a CoreCLR started event. Ensure that the target process is configured to use .NET Core. This may be expected if the target process did not run on .NET Core.
08:12:35:002    The program '[33484] runas.exe: Program Trace' has exited with code 0 (0x0).
08:12:35:002    The program '[33484] runas.exe' has exited with code 0 (0x0).
</code>```

My TargetFramework is "net6.0" and I have a number of runtimes and sdks on this box.

Has anyone been successful with 2022 and have some recommendations?

Body:
I need to execute a .NET 6 or 7 Background Service as a different account user.  Note I need to do this in Visual Studio 2022.  I have referenced "Start external program" functionality under the Debug section of a project's properties and reviewed How to debug a Visual Studio 2022 console application running as a service using a gMSA.

Has anyone figured out how to do this with 2022's new Debug settings?

I've tried different permutations on the following screen, with different arguments, with and without working directory, etc.:

When I debug the application, a console appears requesting the password (I do realize there is switch for caching this) which I provide.  It attempts to start a different console, yet closes extremely quick.  The original console then shows an exit code of 0:

VS's Output window shows the following:

08:12:35:002    The target process exited without raising a CoreCLR started event. Ensure that the target process is configured to use .NET Core. This may be expected if the target process did not run on .NET Core.
08:12:35:002    The program '[33484] runas.exe: Program Trace' has exited with code 0 (0x0).
08:12:35:002    The program '[33484] runas.exe' has exited with code 0 (0x0).

My TargetFramework is "net6.0" and I have a number of runtimes and sdks on this box.

Has anyone been successful with 2022 and have some recommendations?


问:
Your project's Realtime Database 'loginregister-cf438-default-rtdb' will start denying client requests unless you update your security rules
I can't read and write to my realtime database.</p>
```<code>{
  "rules": {
    ".read": "now < 1670947200000",  // 2022-12-14
    ".write": "now < 1670947200000",  // 2022-12-14
  }
}
</code>```

Body:
I can't read and write to my realtime database.

{
  "rules": {
    ".read": "now < 1670947200000",  // 2022-12-14
    ".write": "now < 1670947200000",  // 2022-12-14
  }
}


问:
Datetime does not match format
I am running unit tests in my local environment and docker on the remote build and I have a test that fails with the following error in the docker container:

ValueError: time data '16 Dec 2022 11:41:43 EST' does not match format '%d %b %Y %X %Z'

The strange thing is that it passes in my local environment when I run pytest. I have checked the format codes given here: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes and my datetime seems okay.

I don't know why the test is failing in the docker container with that error. It seems to be passing in my local env. Please help! Thanks!

EDIT:
I am trying to execute the following statement:
datetime_string = datetime.datetime.strptime(datetime_string_raw, "%d %b %Y %X %Z").strftime("%Y-%m-%dT%X")

where datetime_string_raw = "16 Dec 2022 11:41:43 EST"

Title: Datetime does not match format


问:
I can't find out how to fix my leaks in my own implementation of get_next_line function
I'm actually writing a function called get_next_line  that reads a file, line by line using a file descriptor.

It's a school project, and it is teaching me what a static variable is.

I think I did well with the logic part of the function, I tested my code with a .txt file and many different cases like an empty file, 1 character file, 1 line file and everything is working fine.

But the problem is, I have leaks in my code and I can't figure out how to fix them.

Here is my get_next_line program, it has two files, one named get_next_line_utils.c, containing handmade libc functions like ft_strdup, ft_substr, ft_strchr, ft_strjoin and ft_strlen . And the main file get_next_line.c containing the main functions and some static functions for GNL :

gnl_utils.c :

```<code>#include "get_next_line.h"

size_t  ft_strlen(const char *str)
{
    size_t  i;

    i = 0;
    while (str[i])
        i++;
    return (i);
}

/*
    ft_strjoin that works exactly like libft's ft_strjoin.
    It concatenates s2 to s1 in a new string (str).
    It is used in GNL to concatenate the stash and the buffer.
*/

char    *ft_strjoin(const char *s1, const char *s2)
{
    char    *str;
    size_t  size;
    int     i;
    int     j;

    size = ft_strlen(s1) + ft_strlen(s2);
    str = malloc(size * sizeof(char) + 1);
    if (!str)
        return (NULL);
    i = 0;
    j = 0;
    while (s1[i])
        str[j++] = s1[i++];
    i = 0;
    while (s2[i])
        str[j++] = s2[i++];
    str[j] = '\0';
    return (str);
}

/*
    ft_strchr is used to find the \n and is used only
    as a parameter for ft_substr. (it's size_t len)
*/

char    *ft_strchr(const char *s, int c)
{
    while (*s != '\0')
    {
        if ((unsigned char)*s == (unsigned char)c)
            return ((char *)s);
        s++;
    }
    if (c == 0)
        return ((char *)s);
    return (0);
}

/*
    ft_substr is used to get the line from the stash in GNL.
    In case 1 : Last line, it is doing a strdup of the stash.
    In case 2 : Not last line, it is strduping from start to \n.
*/

char    *ft_substr(const char *s, unsigned int start, size_t len)
{
    char    *str;
    int     i;
    int     y;

    if (start >= ft_strlen(s))
        start = ft_strlen(s);
    y = 0;
    while (start + y < start + len && s[start + y] != '\0')
        y++;
    i = 0;
    str = malloc((y) + 1);
    if (!str || start > ft_strlen(s))
        return (NULL);
    while (i < y)
    {
        str[i] = s[start];
        i++;
        start++;
    }
    str[i] = '\0';
    return (str);
}

/*
    ft_strdup is used to duplicate the buffer of read in stash
    in case of stash is NULL.
    stash become the content of the buffer and is \0 terminated.
*/

char    *ft_strdup(const char *s)
{
    char    *dup;
    int     i;

    i = 0;
    dup = malloc(ft_strlen(s) + 1);
    if (!dup)
        return (NULL);
    while (s[i])
    {
        dup[i] = s[i];
        i++;
    }
    dup[i] = '\0';
    return (dup);
}
</code>```

gnl.c :

```<code>#include "get_next_line.h"

/*
    check_line is juste a boolean that returns 1 if our string contains a \n.
    Else it returns -1.
*/

static int  check_line(char *str)
{
    int i;

    i = 0;
    if (!str)
        return (-1);
    while (str[i])
    {
        if (str[i] == '\n')
            return (1);
        i++;
    }
    return (-1);
}

/*
    ft_strcut is used in one case in GNL.
    When the stash contains a \n, we are cutting the string
    from the \n to the end of the string, so our new stash does not
    longer contain the \n ans the past line.
*/

static char *ft_strcut(char *str)
{
    char    *cutted_str;
    int     i;
    int     j;

    i = 0;
    j = 0;
    while (str[i] != '\n')
        i++;
    cutted_str = malloc(sizeof(char) * (ft_strlen(str) - i + 1));
    if (!cutted_str)
        return (NULL);
    i++;
    while (str[i])
        cutted_str[j++] = str[i++];
    cutted_str[j] = '\0';
    free(str);
    return (cutted_str);
}

char    *get_next_line(int fd)
{
    static char *stash; //Static variable that contains the result of concatenation of buffer and stash.
    char        *buff;  //Variable that contains the result of read in a buffer.
    char        *line;  //Variable that contains the line to return.
    int     readed; //Variable that contains the result of read.

    if (fd < 0 || BUFFER_SIZE <= 0) //Invalid inputs handling.
        return (NULL);

    //Init varaibles
    buff = malloc(sizeof(char) * (BUFFER_SIZE + 1));
    if (!buff)
        return (NULL);

    readed = read(fd, buff, BUFFER_SIZE);

    //If all the file readed OR error while reading AND stash is empty : return NULL.
    if (readed <= 0 && !stash)
        return (NULL);

    buff[readed] = '\0';
    if (!stash)
        stash = strdup(buff);
    else
        stash = ft_strjoin(stash, buff);
    free(buff);

    while (stash)
    {
        buff = malloc(sizeof(char) * (BUFFER_SIZE + 1));
        readed = read(fd, buff, BUFFER_SIZE);
        buff[readed] = '\0';
        stash = ft_strjoin(stash, buff);
        free(buff);

        //CASE 1 : Last line, no \n in stash. Read does not read BUFFER_SIZE but less.
        if (readed < BUFFER_SIZE && check_line(stash) == -1)
        {
            line = ft_strdup(stash);
            stash = NULL;
            free(stash);
            return (line);
        }
        //CASE 2 : Not the last line, \n in stash.
        else if (check_line(stash) != -1)
        {
            line = ft_substr(stash, 0, ft_strchr(stash, '\n') - stash + 1);
            stash = ft_strcut(stash);
            return (line);
        }
    }
    return (NULL);
}

int main(int argc, char **argv)
{
    char    *line;

    int i = 0;
    int fd = open("text.txt", O_RDONLY);
    if (argc == 2)
    {
        while (i < atoi(argv[1]))
        {
            line = get_next_line(fd);
            printf("Ligne %d : %s\n", i + 1, line);
            free(line);
            i++;
        }
    }
    return (0);
}
</code>```

Sorry for the indents, I have a norm to respect.

I tried debugging for a week now and I cant figure out how to fix the leaks.

I deleted all my code and restarted many times, trying to get new logics to solve this function but no results.

Valgrind is telling me this (when I use ./a.out 5 in a file with 4 lines of text)

➜  get_next_line git:(main) ✗ gwww -g -O0 -D BUFFER_SIZE=5 *.c && leaks ./a.out 5

==562032== Memcheck, a memory error detector

==562032== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.

==562032== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info

==562032== Command: ./a.out 5

==562032==

Ligne 1 : toto

Ligne 2 : toto but 2

Ligne 3 :

Ligne 4 : toto line 4

Ligne 5 : (null)

==562032==

==562032== HEAP SUMMARY:

==562032==     in use at exit: 76 bytes in 9 blocks

==562032==   total heap usage: 25 allocs, 16 frees, 1,222 bytes allocated

==562032==

==562032== 6 bytes in 1 blocks are definitely lost in loss record 1 of 5

==562032==    at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)

==562032==    by 0x10935F: get_next_line (get_next_line.c:85)

==562032==    by 0x109581: main (get_next_line.c:139)

==562032==

==562032== 6 bytes in 1 blocks are definitely lost in loss record 2 of 5

==562032==    at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)

==562032==    by 0x490738E: strdup (strdup.c:42)

==562032==    by 0x1093D1: get_next_line (get_next_line.c:97)

==562032==    by 0x109581: main (get_next_line.c:139)

==562032==

==562032== 12 bytes in 1 blocks are definitely lost in loss record 3 of 5

==562032==    at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)

==562032==    by 0x10964E: ft_strjoin (get_next_line_utils.c:39)

==562032==    by 0x109455: get_next_line (get_next_line.c:107)

==562032==    by 0x109581: main (get_next_line.c:139)

==562032==

==562032== 22 bytes in 3 blocks are definitely lost in loss record 4 of 5

==562032==    at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)

==562032==    by 0x1092BC: ft_strcut (get_next_line.c:53)

==562032==    by 0x109518: get_next_line (get_next_line.c:122)

==562032==    by 0x109581: main (get_next_line.c:139)

==562032==

==562032== 30 bytes in 3 blocks are definitely lost in loss record 5 of 5

==562032==    at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)

==562032==    by 0x10964E: ft_strjoin (get_next_line_utils.c:39)

==562032==    by 0x1093F0: get_next_line (get_next_line.c:99)

==562032==    by 0x109581: main (get_next_line.c:139)

==562032==

==562032== LEAK SUMMARY:

==562032==    definitely lost: 76 bytes in 9 blocks

==562032==    indirectly lost: 0 bytes in 0 blocks

==562032==      possibly lost: 0 bytes in 0 blocks

==562032==    still reachable: 0 bytes in 0 blocks

==562032==         suppressed: 0 bytes in 0 blocks

==562032==

==562032== For lists of detected and suppressed errors, rerun with: -s

==562032== ERROR SUMMARY: 5 errors from 5 contexts (suppressed: 0 from 0)

From what I understood, I have leaks from my stash but I can't free it because if I do so, GNL won't be able to write the lines remaining in the file. So the only free of stash in my program is when I return the last line.

I also understood that it's normal if I have still reachable leaks if I did not finish to read the file.

I'm pretty sure I free'd all my buffer that comes with the read() function.

But I don't understand that I still have leaks even when I returned the last line.

Any help is much appreciated !

Body:
I'm actually writing a function called get_next_line  that reads a file, line by line using a file descriptor.

It's a school project, and it is teaching me what a static variable is.

I think I did well with the logic part of the function, I tested my code with a .txt file and many different cases like an empty file, 1 character file, 1 line file and everything is working fine.

But the problem is, I have leaks in my code and I can't figure out how to fix them.

Here is my get_next_line program, it has two files, one named get_next_line_utils.c, containing handmade libc functions like ft_strdup, ft_substr, ft_strchr, ft_strjoin and ft_strlen . And the main file get_next_line.c containing the main functions and some static functions for GNL :

gnl_utils.c :

#include "get_next_line.h"

size_t  ft_strlen(const char *str)
{
    size_t  i;

    i = 0;
    while (str[i])
        i++;
    return (i);
}

/*
    ft_strjoin that works exactly like libft's ft_strjoin.
    It concatenates s2 to s1 in a new string (str).
    It is used in GNL to concatenate the stash and the buffer.
*/

char    *ft_strjoin(const char *s1, const char *s2)
{
    char    *str;
    size_t  size;
    int     i;
    int     j;

    size = ft_strlen(s1) + ft_strlen(s2);
    str = malloc(size * sizeof(char) + 1);
    if (!str)
        return (NULL);
    i = 0;
    j = 0;
    while (s1[i])
        str[j++] = s1[i++];
    i = 0;
    while (s2[i])
        str[j++] = s2[i++];
    str[j] = '\0';
    return (str);
}

/*
    ft_strchr is used to find the \n and is used only
    as a parameter for ft_substr. (it's size_t len)
*/

char    *ft_strchr(const char *s, int c)
{
    while (*s != '\0')
    {
        if ((unsigned char)*s == (unsigned char)c)
            return ((char *)s);
        s++;
    }
    if (c == 0)
        return ((char *)s);
    return (0);
}

/*
    ft_substr is used to get the line from the stash in GNL.
    In case 1 : Last line, it is doing a strdup of the stash.
    In case 2 : Not last line, it is strduping from start to \n.
*/

char    *ft_substr(const char *s, unsigned int start, size_t len)
{
    char    *str;
    int     i;
    int     y;

    if (start >= ft_strlen(s))
        start = ft_strlen(s);
    y = 0;
    while (start + y < start + len && s[start + y] != '\0')
        y++;
    i = 0;
    str = malloc((y) + 1);
    if (!str || start > ft_strlen(s))
        return (NULL);
    while (i < y)
    {
        str[i] = s[start];
        i++;
        start++;
    }
    str[i] = '\0';
    return (str);
}

/*
    ft_strdup is used to duplicate the buffer of read in stash
    in case of stash is NULL.
    stash become the content of the buffer and is \0 terminated.
*/

char    *ft_strdup(const char *s)
{
    char    *dup;
    int     i;

    i = 0;
    dup = malloc(ft_strlen(s) + 1);
    if (!dup)
        return (NULL);
    while (s[i])
    {
        dup[i] = s[i];
        i++;
    }
    dup[i] = '\0';
    return (dup);
}

gnl.c :

#include "get_next_line.h"

/*
    check_line is juste a boolean that returns 1 if our string contains a \n.
    Else it returns -1.
*/

static int  check_line(char *str)
{
    int i;

    i = 0;
    if (!str)
        return (-1);
    while (str[i])
    {
        if (str[i] == '\n')
            return (1);
        i++;
    }
    return (-1);
}

/*
    ft_strcut is used in one case in GNL.
    When the stash contains a \n, we are cutting the string
    from the \n to the end of the string, so our new stash does not
    longer contain the \n ans the past line.
*/

static char *ft_strcut(char *str)
{
    char    *cutted_str;
    int     i;
    int     j;

    i = 0;
    j = 0;
    while (str[i] != '\n')
        i++;
    cutted_str = malloc(sizeof(char) * (ft_strlen(str) - i + 1));
    if (!cutted_str)
        return (NULL);
    i++;
    while (str[i])
        cutted_str[j++] = str[i++];
    cutted_str[j] = '\0';
    free(str);
    return (cutted_str);
}

char    *get_next_line(int fd)
{
    static char *stash; //Static variable that contains the result of concatenation of buffer and stash.
    char        *buff;  //Variable that contains the result of read in a buffer.
    char        *line;  //Variable that contains the line to return.
    int     readed; //Variable that contains the result of read.

    if (fd < 0 || BUFFER_SIZE <= 0) //Invalid inputs handling.
        return (NULL);

    //Init varaibles
    buff = malloc(sizeof(char) * (BUFFER_SIZE + 1));
    if (!buff)
        return (NULL);

    readed = read(fd, buff, BUFFER_SIZE);

    //If all the file readed OR error while reading AND stash is empty : return NULL.
    if (readed <= 0 && !stash)
        return (NULL);

    buff[readed] = '\0';
    if (!stash)
        stash = strdup(buff);
    else
        stash = ft_strjoin(stash, buff);
    free(buff);

    while (stash)
    {
        buff = malloc(sizeof(char) * (BUFFER_SIZE + 1));
        readed = read(fd, buff, BUFFER_SIZE);
        buff[readed] = '\0';
        stash = ft_strjoin(stash, buff);
        free(buff);

        //CASE 1 : Last line, no \n in stash. Read does not read BUFFER_SIZE but less.
        if (readed < BUFFER_SIZE && check_line(stash) == -1)
        {
            line = ft_strdup(stash);
            stash = NULL;
            free(stash);
            return (line);
        }
        //CASE 2 : Not the last line, \n in stash.
        else if (check_line(stash) != -1)
        {
            line = ft_substr(stash, 0, ft_strchr(stash, '\n') - stash + 1);
            stash = ft_strcut(stash);
            return (line);
        }
    }
    return (NULL);
}

int main(int argc, char **argv)
{
    char    *line;

    int i = 0;
    int fd = open("text.txt", O_RDONLY);
    if (argc == 2)
    {
        while (i < atoi(argv[1]))
        {
            line = get_next_line(fd);
            printf("Ligne %d : %s\n", i + 1, line);
            free(line);
            i++;
        }
    }
    return (0);
}

Sorry for the indents, I have a norm to respect.

I tried debugging for a week now and I cant figure out how to fix the leaks.

I deleted all my code and restarted many times, trying to get new logics to solve this function but no results.

Valgrind is telling me this (when I use ./a.out 5 in a file with 4 lines of text)

➜  get_next_line git:(main) ✗ gwww -g -O0 -D BUFFER_SIZE=5 *.c && leaks ./a.out 5

==562032== Memcheck, a memory error detector

==562032== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.

==562032== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info

==562032== Command: ./a.out 5

==562032==

Ligne 1 : toto

Ligne 2 : toto but 2

Ligne 3 :

Ligne 4 : toto line 4

Ligne 5 : (null)

==562032==

==562032== HEAP SUMMARY:

==562032==     in use at exit: 76 bytes in 9 blocks

==562032==   total heap usage: 25 allocs, 16 frees, 1,222 bytes allocated

==562032==

==562032== 6 bytes in 1 blocks are definitely lost in loss record 1 of 5

==562032==    at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)

==562032==    by 0x10935F: get_next_line (get_next_line.c:85)

==562032==    by 0x109581: main (get_next_line.c:139)

==562032==

==562032== 6 bytes in 1 blocks are definitely lost in loss record 2 of 5

==562032==    at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)

==562032==    by 0x490738E: strdup (strdup.c:42)

==562032==    by 0x1093D1: get_next_line (get_next_line.c:97)

==562032==    by 0x109581: main (get_next_line.c:139)

==562032==

==562032== 12 bytes in 1 blocks are definitely lost in loss record 3 of 5

==562032==    at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)

==562032==    by 0x10964E: ft_strjoin (get_next_line_utils.c:39)

==562032==    by 0x109455: get_next_line (get_next_line.c:107)

==562032==    by 0x109581: main (get_next_line.c:139)

==562032==

==562032== 22 bytes in 3 blocks are definitely lost in loss record 4 of 5

==562032==    at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)

==562032==    by 0x1092BC: ft_strcut (get_next_line.c:53)

==562032==    by 0x109518: get_next_line (get_next_line.c:122)

==562032==    by 0x109581: main (get_next_line.c:139)

==562032==

==562032== 30 bytes in 3 blocks are definitely lost in loss record 5 of 5

==562032==    at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)

==562032==    by 0x10964E: ft_strjoin (get_next_line_utils.c:39)

==562032==    by 0x1093F0: get_next_line (get_next_line.c:99)

==562032==    by 0x109581: main (get_next_line.c:139)

==562032==

==562032== LEAK SUMMARY:

==562032==    definitely lost: 76 bytes in 9 blocks

==562032==    indirectly lost: 0 bytes in 0 blocks

==562032==      possibly lost: 0 bytes in 0 blocks

==562032==    still reachable: 0 bytes in 0 blocks

==562032==         suppressed: 0 bytes in 0 blocks

==562032==

==562032== For lists of detected and suppressed errors, rerun with: -s

==562032== ERROR SUMMARY: 5 errors from 5 contexts (suppressed: 0 from 0)

From what I understood, I have leaks from my stash but I can't free it because if I do so, GNL won't be able to write the lines remaining in the file. So the only free of stash in my program is when I return the last line.

I also understood that it's normal if I have still reachable leaks if I did not finish to read the file.

I'm pretty sure I free'd all my buffer that comes with the read() function.

But I don't understand that I still have leaks even when I returned the last line.

Any help is much appreciated !


问:
Type graphql query with radash
I have to type the orders in the try from radash tuple that is the result of a query made with graphql.
The call looks like that

const [error, orders] = await tryit(client.query)({
      query: GET_ORDER_BY_NUMBER,
      variables: {
        orderNumber: id,
      },
    })
```
<p>Currently, the default type for the orders is <code>ApolloQueryResult<unknown></code>. So to bypass that, I've tried to typed it like by creating an interface and assigning its value to it.</p>
<pre class="lang-js prettyprint-override"><code>interface ITryGetOrders {
      getOrders: IOrder[];
}

{..}

const [error, orders] : [Error, ApolloQueryResult<ITryGetOrders>] = await ...
</code>```

But I receive the following error and I don't know how to solve it:

Type '[Error, ApolloQueryResult]' is not assignable to type '[Error, ApolloQueryResult]'.

Title: Type graphql query with radash

Body:
I have to type the orders in the try from radash tuple that is the result of a query made with graphql.
The call looks like that

const [error, orders] = await tryit(client.query)({
      query: GET_ORDER_BY_NUMBER,
      variables: {
        orderNumber: id,
      },
    })

Currently, the default type for the orders is ApolloQueryResult<unknown>. So to bypass that, I've tried to typed it like by creating an interface and assigning its value to it.

interface ITryGetOrders {
      getOrders: IOrder[];
}

{..}

const [error, orders] : [Error, ApolloQueryResult<ITryGetOrders>] = await ...

But I receive the following error and I don't know how to solve it:

Type '[Error, ApolloQueryResult]' is not assignable to type '[Error, ApolloQueryResult]'.


问:
Component not maintaining input state after checkbox is checked within the table
I am trying to implement Table component what has text field, on submit it should validate the empty fields. If the checkbox is checked, then don't validate that row. But here on checkbox unchecked text field loses its previous value.

May be I am doing something wrong with my code, don't know why it is behaving like this.
For a reference I am attaching recorded evidence.

My code

```<code>interface InconsistenciesTableProps {
  inconsistencies: Inconsistency[] | null;
  onSubmit: (value: InconsistencyRequestData) => void;
}

const InconsistenciesTable = ({inconsistencies,onSubmit}: InconsistenciesTableProps) => {
  const [selectedRows, setSelectedRows] = useState<RowSelectionState>()
  const [showError, setShowError] = useState<boolean>(false)

  useEffect(() => {
    setShowError(false)

    if(selectedRows) {
      selectedRows?.forEach(row => {
        updateInconsistencies(row,'status','success')
      })

      const inconsistenciesIds = inconsistencies?.map(data => {return data.id})
      const unSelectedRows = inconsistenciesIds?.filter(id => !Array.from(selectedRows).includes(id))
      unSelectedRows?.forEach(row => {
        updateInconsistencies(row,'status','invalid')
      })
    }
  },[selectedRows])

  const updateInconsistencies = (id: string, key: string, value: string) => {
    const inconsistencyIndex = inconsistencies?.findIndex(data => data.id === id)
    inconsistencies[inconsistencyIndex] = {
      ...inconsistencies[inconsistencyIndex],
      [key]: value
    }
  }

  const explanation = (id: string, val: string) => {
    updateInconsistencies(id,'explanation',val)
  }

  const checkHasError = (inconsistency: Inconsistency) => {
    return showError && inconsistency.status === 'invalid' && inconsistency.explanation === ''
  }

  const tableBody = (inconsistencies: Inconsistency[]): TableRows[] => {
    return inconsistencies?.map(inconsistency => {
      const tableCells: TableCells[] = [
        {
          id: 'quantity_'+inconsistency.id,
          content: inconsistency.quantity
        },
        {
          id: 'explanation_'+inconsistency.id,
          content: <ExplanationForm
            isVisible={!selectedRows?.has(inconsistency.id)}
            value={inconsistency.explanation || ''}
            onChange={val => explanation(inconsistency.id,val)}
            hasError={checkHasError(inconsistency)}
          />
        }
      ]
      return {
        id: inconsistency.id,
        content: tableCells
      }
    })
  }

  const handleOnSubmit = () => {
    setShowError(true)
    const isInconsistency = validityComparison()

    if(!isInconsistency) {
      selectedRows?.forEach(row => {
        updateInconsistencies(row,'explanation','')
      })
      const requestData: InconsistencyRequestData = {
        inconsistencies: inconsistencies
      }
      onSubmit(requestData)
    }
  }

  return (
    <>
      {inconsistencies &&
        <Table
          content={tableBody(inconsistencies)}
          onRowSelectionChange={setSelectedRows}
          state={{rowSelection: selectedRows || new Set()}}
        />
      }
      <Button className="uppercase" text="CONFIRM AND SEND" onClick={handleOnSubmit} />
    </>
  )
}

export default InconsistenciesTable

</code>```

Update:
Sandbox code: https://codesandbox.io/s/cool-paper-0hpgff?file=/src/App.tsx

In a sandbox its working fine, but not working on my local machine.
If there is any area of improvements, then let me know.

Thanks in advance!

Update: I have re-written the code from scratch and now I understood where the problem is. It's in the form field where I am using inside the Table.

I have updated the sandbox code and it is giving another error now.
New sandbox link: https://codesandbox.io/s/sharp-ptolemy-1hqhm8

Body:
I am trying to implement Table component what has text field, on submit it should validate the empty fields. If the checkbox is checked, then don't validate that row. But here on checkbox unchecked text field loses its previous value.

May be I am doing something wrong with my code, don't know why it is behaving like this.
For a reference I am attaching recorded evidence.

My code

interface InconsistenciesTableProps {
  inconsistencies: Inconsistency[] | null;
  onSubmit: (value: InconsistencyRequestData) => void;
}

const InconsistenciesTable = ({inconsistencies,onSubmit}: InconsistenciesTableProps) => {
  const [selectedRows, setSelectedRows] = useState<RowSelectionState>()
  const [showError, setShowError] = useState<boolean>(false)

  useEffect(() => {
    setShowError(false)

    if(selectedRows) {
      selectedRows?.forEach(row => {
        updateInconsistencies(row,'status','success')
      })

      const inconsistenciesIds = inconsistencies?.map(data => {return data.id})
      const unSelectedRows = inconsistenciesIds?.filter(id => !Array.from(selectedRows).includes(id))
      unSelectedRows?.forEach(row => {
        updateInconsistencies(row,'status','invalid')
      })
    }
  },[selectedRows])

  const updateInconsistencies = (id: string, key: string, value: string) => {
    const inconsistencyIndex = inconsistencies?.findIndex(data => data.id === id)
    inconsistencies[inconsistencyIndex] = {
      ...inconsistencies[inconsistencyIndex],
      [key]: value
    }
  }

  const explanation = (id: string, val: string) => {
    updateInconsistencies(id,'explanation',val)
  }

  const checkHasError = (inconsistency: Inconsistency) => {
    return showError && inconsistency.status === 'invalid' && inconsistency.explanation === ''
  }

  const tableBody = (inconsistencies: Inconsistency[]): TableRows[] => {
    return inconsistencies?.map(inconsistency => {
      const tableCells: TableCells[] = [
        {
          id: 'quantity_'+inconsistency.id,
          content: inconsistency.quantity
        },
        {
          id: 'explanation_'+inconsistency.id,
          content: <ExplanationForm
            isVisible={!selectedRows?.has(inconsistency.id)}
            value={inconsistency.explanation || ''}
            onChange={val => explanation(inconsistency.id,val)}
            hasError={checkHasError(inconsistency)}
          />
        }
      ]
      return {
        id: inconsistency.id,
        content: tableCells
      }
    })
  }

  const handleOnSubmit = () => {
    setShowError(true)
    const isInconsistency = validityComparison()

    if(!isInconsistency) {
      selectedRows?.forEach(row => {
        updateInconsistencies(row,'explanation','')
      })
      const requestData: InconsistencyRequestData = {
        inconsistencies: inconsistencies
      }
      onSubmit(requestData)
    }
  }

  return (
    <>
      {inconsistencies &&

      }
      <Button className="uppercase" text="CONFIRM AND SEND" onClick={handleOnSubmit} />
    </>
  )
}

export default InconsistenciesTable

Update:
Sandbox code: https://codesandbox.io/s/cool-paper-0hpgff?file=/src/App.tsx

In a sandbox its working fine, but not working on my local machine.
If there is any area of improvements, then let me know.

Thanks in advance!

Update: I have re-written the code from scratch and now I understood where the problem is. It's in the form field where I am using inside the Table.

I have updated the sandbox code and it is giving another error now.
New sandbox link: https://codesandbox.io/s/sharp-ptolemy-1hqhm8


问:
Sorting results including null in Javascript
Im trying to sort some data in date order in JS. This code works apart from the 'null' data. (The null data is where the date field does not exits for that particular result.)  It sits at the top when I need it to sit at the bottom. I have tried various amends but none seem to work. Can anyone help?

Thanks in advance.

```<code> if (this.sortBy === "ending") {
            Results.sort((a, b) => {
              if (a.data.t == null || b.data.t == null) {
                return -1;
              }
              let aDate;
              let bDate;
              try {
                aDate = new Date(a.data.t);
              } catch (error) {
                aDate = 99999999;
              }
              try {
                bDate = new Date(b.data.t);
              } catch (error) {
                bDate = 99999999;
              }

              if (aDate > bDate) {
                return 1;
              }
              if (aDate < bDate) {
                return -1;
              }
              return 0;
            });
          }

          return Results;
        },
</code>```

Body:
Im trying to sort some data in date order in JS. This code works apart from the 'null' data. (The null data is where the date field does not exits for that particular result.)  It sits at the top when I need it to sit at the bottom. I have tried various amends but none seem to work. Can anyone help?

Thanks in advance.

 if (this.sortBy === "ending") {
            Results.sort((a, b) => {
              if (a.data.t == null || b.data.t == null) {
                return -1;
              }
              let aDate;
              let bDate;
              try {
                aDate = new Date(a.data.t);
              } catch (error) {
                aDate = 99999999;
              }
              try {
                bDate = new Date(b.data.t);
              } catch (error) {
                bDate = 99999999;
              }

              if (aDate > bDate) {
                return 1;
              }
              if (aDate < bDate) {
                return -1;
              }
              return 0;
            });
          }

          return Results;
        },


问:
Nuxt 3 + TipTap 2.0.0-beta.209 | SSG | Nuxt generate creates: ERROR StarterKit.configure is not a function
When creating a new project using Nuxt 3.0.0 + TipTap 2.0.0-beta.209, running nuxt generate creates the following error:

ERROR  StarterKit.configure is not a function

at setup (/D:/dev/nuxt-tiptap-issue/.nuxt/prerender/chunks/index.ac796611.mjs:56:20)
at _sfc_main.setup (/D:/dev/nuxt-tiptap-issue/.nuxt/prerender/chunks/index.ac796611.mjs:321:23)
at callWithErrorHandling (node_modules@vue\runtime-core\dist\runtime-core.cjs.prod.js:15:22)
at setupStatefulComponent (node_modules@vue\runtime-core\dist\runtime-core.cjs.prod.js:5762:29)
at setupComponent (node_modules@vue\runtime-core\dist\runtime-core.cjs.prod.js:5743:11)
at renderComponentVNode (node_modules@vue\server-renderer\dist\server-renderer.cjs.prod.js:169:17)
at renderVNode (node_modules@vue\server-renderer\dist\server-renderer.cjs.prod.js:296:22)
at renderComponentSubTree (node_modules@vue\server-renderer\dist\server-renderer.cjs.prod.js:260:13)
at renderComponentVNode (node_modules@vue\server-renderer\dist\server-renderer.cjs.prod.js:185:16)
at renderVNode (node_modules@vue\server-renderer\dist\server-renderer.cjs.prod.js:296:22)

The error references to this piece of code I wrote for the WYSIWYG editor (in pages/index.vue)

....
const editor = useEditor({
  extensions: [
    CustomDocument,
    StarterKit.configure({
      document: false,
      heading: {
        levels: [1, 2, 3, 4, 5, 6],
      }
    }),
....
```
<p>It works fine in SPA mode and <code>nuxt dev</code> also works fine.</p>
<p>I have created a reproduction repository here: https://github.com/CLFPosthumus/nuxt-tiptap-issue</p>
<p>Running <code>nuxt generate</code> also yields below warning:</p>
```WARN Using experimental payload extraction for full-static output. You can opt-out by setting experimental.payloadExtraction to false.
```

I tried toggling this setting, but it seems this warning is unrelated as it does not resolve the issue.

I think somehow Starterkit does not get imported correctly. But I struggle to debug/ fix this issue.

Body:
When creating a new project using Nuxt 3.0.0 + TipTap 2.0.0-beta.209, running nuxt generate creates the following error:

ERROR  StarterKit.configure is not a function

at setup (/D:/dev/nuxt-tiptap-issue/.nuxt/prerender/chunks/index.ac796611.mjs:56:20)
at _sfc_main.setup (/D:/dev/nuxt-tiptap-issue/.nuxt/prerender/chunks/index.ac796611.mjs:321:23)
at callWithErrorHandling (node_modules@vue\runtime-core\dist\runtime-core.cjs.prod.js:15:22)
at setupStatefulComponent (node_modules@vue\runtime-core\dist\runtime-core.cjs.prod.js:5762:29)
at setupComponent (node_modules@vue\runtime-core\dist\runtime-core.cjs.prod.js:5743:11)
at renderComponentVNode (node_modules@vue\server-renderer\dist\server-renderer.cjs.prod.js:169:17)
at renderVNode (node_modules@vue\server-renderer\dist\server-renderer.cjs.prod.js:296:22)
at renderComponentSubTree (node_modules@vue\server-renderer\dist\server-renderer.cjs.prod.js:260:13)
at renderComponentVNode (node_modules@vue\server-renderer\dist\server-renderer.cjs.prod.js:185:16)
at renderVNode (node_modules@vue\server-renderer\dist\server-renderer.cjs.prod.js:296:22)

The error references to this piece of code I wrote for the WYSIWYG editor (in pages/index.vue)

....
const editor = useEditor({
  extensions: [
    CustomDocument,
    StarterKit.configure({
      document: false,
      heading: {
        levels: [1, 2, 3, 4, 5, 6],
      }
    }),
....

It works fine in SPA mode and nuxt dev also works fine.

I have created a reproduction repository here: https://github.com/CLFPosthumus/nuxt-tiptap-issue

Running nuxt generate also yields below warning:

WARN Using experimental payload extraction for full-static output. You can opt-out by setting experimental.payloadExtraction to false.

I tried toggling this setting, but it seems this warning is unrelated as it does not resolve the issue.

I think somehow Starterkit does not get imported correctly. But I struggle to debug/ fix this issue.