问:
Why QThread: Destroyed while thread is still running?
My Code...

```<code>import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
from PyQt5.QtCore import *
import pyupbit
import datetime
from upbit1 import *
import multiprocessing as mp

from QThread1 import Thread1
from QThread2 import Thread2
from QThread3 import Thread3

form_class = uic.loadUiType("autotrading.ui")[0]
with open("pyupbit.txt", "r") as f:
            key0 = f.readline().strip()
            key1 = f.readline().strip()
now = datetime.datetime.now().strftime('%Y.%m.%d - %H:%M:%S')
upbit = pyupbit.Upbit(key0, key1)

class Login_Machine(QMainWindow, QWidget, form_class):
    class_attribute = pyqtSignal(str)
    def __init__(self, *args, **kwargs):

        super(Login_Machine, self).__init__(*args, **kwargs)
        form_class.__init__(self)
        self.setUI()

        self.login_event_loop = QEventLoop()

        self.k = Login()
        self.key0.setText(key0)
        self.key1.setText(key1)

        self.btn.setText("AutoTrading Start")
        self.btn2.setText("Login")

        self.btn.clicked.connect(self.auto)
        self.btn2.clicked.connect(self.login_slot)

        self.buying.setAlignment(Qt.AlignRight)
        self.buying.setDecimals(0)
        self.profit.setAlignment(Qt.AlignRight)
        self.profit.setDecimals(1)
        self.stop_loss.setAlignment(Qt.AlignRight)
        self.stop_loss.setDecimals(1)

        self.buying.setValue(5500)
        self.profit.setValue(2.5)
        self.stop_loss.setValue(0.5)

    def setUI(self):
        self.setupUi(self)

    def login_slot(self, errCode):
        balance = upbit.get_balance("USDT")
        if errCode == 0:

            self.log.append(f"{now} Login Success!")
            self.log.append(f"my balance: {balance}")

        self.login_event_loop.exit()

    def auto(self):

        a = Thread1(parent = self)
        b = Thread2(parent = self)
        c = Thread3(parent = self)

        if self.btn.text() == "AutoTrading Start":

            a.start()
            b.start()
            c.start()

            self.btn.setText("AutoTrading Stop")

        elif self.btn.text() == "AutoTrading Stop":

            a.end()
            b.end()
            c.end()

            self.log.append("AutoTrading Stop")
            self.btn.setText(""AutoTrading Start"")

if __name__ == "__main__":

    p = mp.Process(target = Login_Machine)
    p.start()
    p.join()

    app = QApplication(sys.argv)
    CH = Login_Machine()
    CH.show()
    app.exec_()

</code>```

When write this code, the error you saw in the title pops up and the window goes off.

I thought this was going to be fixed, but another problem arose.

How to use multiprocessing in QMainWindow?

If do this, the loop continues from the beginning, don't go to the end.

example, If it is from 1 to 100, proceed to 5, then go back to the beginning and start at 1.

Maybe it's because I'm stupid,'pool' and 'multithread' the result was the same.

If anyone can teach me, even one is fine, so please.

thanks for looking at my question.

Body:
My Code...

import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
from PyQt5.QtCore import *
import pyupbit
import datetime
from upbit1 import *
import multiprocessing as mp

from QThread1 import Thread1
from QThread2 import Thread2
from QThread3 import Thread3

form_class = uic.loadUiType("autotrading.ui")[0]
with open("pyupbit.txt", "r") as f:
            key0 = f.readline().strip()
            key1 = f.readline().strip()
now = datetime.datetime.now().strftime('%Y.%m.%d - %H:%M:%S')
upbit = pyupbit.Upbit(key0, key1)

class Login_Machine(QMainWindow, QWidget, form_class):
    class_attribute = pyqtSignal(str)
    def __init__(self, *args, **kwargs):

        super(Login_Machine, self).__init__(*args, **kwargs)
        form_class.__init__(self)
        self.setUI()

        self.login_event_loop = QEventLoop()

        self.k = Login()
        self.key0.setText(key0)
        self.key1.setText(key1)

        self.btn.setText("AutoTrading Start")
        self.btn2.setText("Login")

        self.btn.clicked.connect(self.auto)
        self.btn2.clicked.connect(self.login_slot)

        self.buying.setAlignment(Qt.AlignRight)
        self.buying.setDecimals(0)
        self.profit.setAlignment(Qt.AlignRight)
        self.profit.setDecimals(1)
        self.stop_loss.setAlignment(Qt.AlignRight)
        self.stop_loss.setDecimals(1)

        self.buying.setValue(5500)
        self.profit.setValue(2.5)
        self.stop_loss.setValue(0.5)

    def setUI(self):
        self.setupUi(self)

    def login_slot(self, errCode):
        balance = upbit.get_balance("USDT")
        if errCode == 0:

            self.log.append(f"{now} Login Success!")
            self.log.append(f"my balance: {balance}")

        self.login_event_loop.exit()

    def auto(self):

        a = Thread1(parent = self)
        b = Thread2(parent = self)
        c = Thread3(parent = self)

        if self.btn.text() == "AutoTrading Start":

            a.start()
            b.start()
            c.start()

            self.btn.setText("AutoTrading Stop")

        elif self.btn.text() == "AutoTrading Stop":

            a.end()
            b.end()
            c.end()

            self.log.append("AutoTrading Stop")
            self.btn.setText(""AutoTrading Start"")

if __name__ == "__main__":

    p = mp.Process(target = Login_Machine)
    p.start()
    p.join()

    app = QApplication(sys.argv)
    CH = Login_Machine()
    CH.show()
    app.exec_()

When write this code, the error you saw in the title pops up and the window goes off.

I thought this was going to be fixed, but another problem arose.

How to use multiprocessing in QMainWindow?

If do this, the loop continues from the beginning, don't go to the end.

example, If it is from 1 to 100, proceed to 5, then go back to the beginning and start at 1.

Maybe it's because I'm stupid,'pool' and 'multithread' the result was the same.

If anyone can teach me, even one is fine, so please.

thanks for looking at my question.


来源: stackexchange

问:
MQ MQHMDE throwing MQRC_HEADER_ERROR
I'm working one mq based application where i need to set JMS_IBM_Format as MQHMDE header, whenever i try to use this header i'm getting ('MQCC_FAILED') reason '2142' ('MQRC_HEADER_ERROR') error. Could you please help me how to place a message when using MQHMDE header

these are the info i'm using while sending

```<code>JMSDeliveryMode - Persistent
JMS_IBM_Format - MQConstants.MQFMT_MD_EXTENSION
JMS_IBM_Character_Set - 785
JMS_IBM_Encoding - 500
CamelJmsDestinationName - queue:///queueName?targetClient=0 (tried with target as 1 as well)
</code>```

I'm trying to send the msg through java based apache camel framework and the msg type is in string
below is the detailed error msg,

```<code>java.lang.RuntimeException: org.springframework.jms.IllegalStateException: JMSWMQ2007: Failed to send a message to destination 'queueName'.; nested exception is com.ibm.msg.client.jms.DetailedIllegalStateException: JMSWMQ2007: Failed to send a message to destination 'queueName'.  JMS attempted to perform an MQPUT or MQPUT1; however IBM MQ reported an error.  Use the linked exception to determine the cause of this error.; nested exception is com.ibm.mq.MQException: JMSCMQ0001: IBM MQ call failed with compcode '2' ('MQCC_FAILED') reason '2142' ('MQRC_HEADER_ERROR').
</code>```

ContentLicense: CC BY-SA 4.0

Title: MQ MQHMDE throwing MQRC_HEADER_ERROR

Body:
I'm working one mq based application where i need to set JMS_IBM_Format as MQHMDE header, whenever i try to use this header i'm getting ('MQCC_FAILED') reason '2142' ('MQRC_HEADER_ERROR') error. Could you please help me how to place a message when using MQHMDE header

these are the info i'm using while sending

JMSDeliveryMode - Persistent
JMS_IBM_Format - MQConstants.MQFMT_MD_EXTENSION
JMS_IBM_Character_Set - 785
JMS_IBM_Encoding - 500
CamelJmsDestinationName - queue:///queueName?targetClient=0 (tried with target as 1 as well)

I'm trying to send the msg through java based apache camel framework and the msg type is in string
below is the detailed error msg,

java.lang.RuntimeException: org.springframework.jms.IllegalStateException: JMSWMQ2007: Failed to send a message to destination 'queueName'.; nested exception is com.ibm.msg.client.jms.DetailedIllegalStateException: JMSWMQ2007: Failed to send a message to destination 'queueName'.  JMS attempted to perform an MQPUT or MQPUT1; however IBM MQ reported an error.  Use the linked exception to determine the cause of this error.; nested exception is com.ibm.mq.MQException: JMSCMQ0001: IBM MQ call failed with compcode '2' ('MQCC_FAILED') reason '2142' ('MQRC_HEADER_ERROR').


问:
How to concatenate multiple individual fasta files - and not doing it manually per sample
I received my paired end sequences with 4 files per sample, 2 files per read.
I want to concatenate the two files of each read and only have R1 and R2 for each sample.

Manually it works:

```<code>cat /media/Ea2/Ea2_FKDL220291524-1A_H22M7DSX5_L2_1.fq.gz /media/Ea2/Ea2_FKDL220291524-1A_HYVFNDSX3_L3_1.fq.gz > /media/Ea1/Ea1_concatenated_R1.fq.gz
</code>```

but I want to do it for multiple sequence files:

```<code>Ea1
Ea2
Ea3
etc...
</code>```

I tried doing it for multiple files for the R1 files first:

```<code>cat /media/Ea*/Ea*_*-1A_*_L*_1.fq.gz /media/Ea*/Ea*_*-1A_*_L*_1.fq.gz > /media/Ea*/Ea*_concatenated_R1.fq.gz
</code>```

it did not work.

I tried giving the command a list with the names of each samples like this:

```<code>for i in $(cat /media/list_for_con.txt) do cat /media/$i/$i_*-1A_*_L*_1.fq.gz /media//$i/$i_*-1A_*_L*_1.fq.gz > /media/$i/$i_concatenated_R1.fq.gz
</code>```

It did not work.
Even if it would work it would allot me to adress the R1 and then change it and do the R2 files.

Body:
I received my paired end sequences with 4 files per sample, 2 files per read.
I want to concatenate the two files of each read and only have R1 and R2 for each sample.

Manually it works:

cat /media/Ea2/Ea2_FKDL220291524-1A_H22M7DSX5_L2_1.fq.gz /media/Ea2/Ea2_FKDL220291524-1A_HYVFNDSX3_L3_1.fq.gz > /media/Ea1/Ea1_concatenated_R1.fq.gz

but I want to do it for multiple sequence files:

Ea1
Ea2
Ea3
etc...

I tried doing it for multiple files for the R1 files first:

cat /media/Ea*/Ea*_*-1A_*_L*_1.fq.gz /media/Ea*/Ea*_*-1A_*_L*_1.fq.gz > /media/Ea*/Ea*_concatenated_R1.fq.gz

it did not work.

I tried giving the command a list with the names of each samples like this:

for i in $(cat /media/list_for_con.txt) do cat /media/$i/$i_*-1A_*_L*_1.fq.gz /media//$i/$i_*-1A_*_L*_1.fq.gz > /media/$i/$i_concatenated_R1.fq.gz

It did not work.
Even if it would work it would allot me to adress the R1 and then change it and do the R2 files.


问:
How send purchase info to API in woocommerce
I want to whenever a product is sold, all products information sent to the API. Information like which products, products count, products ID. this is the API instruction :

```<code>{

SettleTypedID:1//payment method: 1 for cards 2 for credit

RRN:  ,

ApMerchantId:  ,

Products:

[{

ProductId:  ,

OrderCount:

},

{

ProductId:  ,
OrderCount:

}]}

</code>```

This is the Post request of API in js, but for one products and I don't know what variables should I use for them (where ever I put "?" in code). what are the correct variables and how should I say add all products where being purchased buy that user ? please help me.

```<code>    const options2 = {
        method: 'POST',
        headers: {
            "SettleTypeId": `${?}`,
            "RRN": `${?}`,
            "ApMerchantId:": `${?}`,
            "Products":
            [
                {
                    "ProductId":`${?}`,
                    "OrderCount":`${?}`
                }
            ]
        }
    };

    fetch('URL', options2)
        .then(response => response.json())
        .then(response => console.log(response))
        .catch(err => console.error(err));
</code>```

Thanks in advance.

Body:
I want to whenever a product is sold, all products information sent to the API. Information like which products, products count, products ID. this is the API instruction :

{

SettleTypedID:1//payment method: 1 for cards 2 for credit

RRN:  ,

ApMerchantId:  ,

Products:

[{

ProductId:  ,

OrderCount:

},

{

ProductId:  ,
OrderCount:

}]}

This is the Post request of API in js, but for one products and I don't know what variables should I use for them (where ever I put "?" in code). what are the correct variables and how should I say add all products where being purchased buy that user ? please help me.

    const options2 = {
        method: 'POST',
        headers: {
            "SettleTypeId": `${?}`,
            "RRN": `${?}`,
            "ApMerchantId:": `${?}`,
            "Products":
            [
                {
                    "ProductId":`${?}`,
                    "OrderCount":`${?}`
                }
            ]
        }
    };

    fetch('URL', options2)
        .then(response => response.json())
        .then(response => console.log(response))
        .catch(err => console.error(err));

Thanks in advance.


问:
problems with a git repo inside another git repo
I know we are not to supposed to create a git repo inside an existing repo, and I know about the submodules in git.
This is just out of curiosity:
Will it cause problems if I create a git repo inside an existing repo?
If yes, what are the side effects? (I want to know what happens?)</p>


问:
async function firebase notify variable onCodeSent
Hey I try to save the verification id outside from is function oncodesent in my code ,the problem is that variable is always null except from the binding of the function

this is my code

Registration.java

```<code> private PhoneAuthProvider.OnVerificationStateChangedCallbacks
            mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        @Override
        public void onVerificationCompleted(@NonNull PhoneAuthCredential credential)
        {
            final String code = credential.getSmsCode();
            if(code!=null)
            {
                verifycode(code);
            }
        }
        @Override
        public void onVerificationFailed(@NonNull FirebaseException e) {
            Toast.makeText(RegistrationActivity.this, "Verification Failed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCodeSent(@NonNull String verificationId,
                               @NonNull PhoneAuthProvider.ForceResendingToken token)
        {
            super.onCodeSent(verificationId, token);
            Intent intent = new Intent(RegistrationActivity.this, RegistrationActivity.class);
            intent.putExtra("verificationId", verificationId);
            Toast.makeText(RegistrationActivity.this, "Code sent", Toast.LENGTH_SHORT).show();
            btnJoinNl.setEnabled(true);
            flagVerification=true;
/*
            bar.setVisibility(View.INVISIBLE);
*/
        }};
</code>```

This is my oncreate method

```<code>        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        initializeViewParameters();

        handleListeners();
        buttonsend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                if(!isValidPhone(inputPhone.getText().toString())){
                    Toast.makeText(RegistrationActivity.this, "Enter Valid Phone No.", Toast.LENGTH_SHORT).show();
                }
                else {
                    String number = inputPhone.getText().toString();
/*
                    bar.setVisibility(View.VISIBLE);
*/
                    sendverificationcode(number);

            }
            }
        });
        verificationId = getIntent().getStringExtra("verificationId");

        autoOtpReceiver();
    }
</code>```

what I am trying to do is saving the verificationId globaly that I can use it whenever I want.
I didn't know how to notify this when the variable is changed

Body:
Hey I try to save the verification id outside from is function oncodesent in my code ,the problem is that variable is always null except from the binding of the function

this is my code

Registration.java

 private PhoneAuthProvider.OnVerificationStateChangedCallbacks
            mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        @Override
        public void onVerificationCompleted(@NonNull PhoneAuthCredential credential)
        {
            final String code = credential.getSmsCode();
            if(code!=null)
            {
                verifycode(code);
            }
        }
        @Override
        public void onVerificationFailed(@NonNull FirebaseException e) {
            Toast.makeText(RegistrationActivity.this, "Verification Failed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCodeSent(@NonNull String verificationId,
                               @NonNull PhoneAuthProvider.ForceResendingToken token)
        {
            super.onCodeSent(verificationId, token);
            Intent intent = new Intent(RegistrationActivity.this, RegistrationActivity.class);
            intent.putExtra("verificationId", verificationId);
            Toast.makeText(RegistrationActivity.this, "Code sent", Toast.LENGTH_SHORT).show();
            btnJoinNl.setEnabled(true);
            flagVerification=true;
/*
            bar.setVisibility(View.INVISIBLE);
*/
        }};

This is my oncreate method

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        initializeViewParameters();

        handleListeners();
        buttonsend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                if(!isValidPhone(inputPhone.getText().toString())){
                    Toast.makeText(RegistrationActivity.this, "Enter Valid Phone No.", Toast.LENGTH_SHORT).show();
                }
                else {
                    String number = inputPhone.getText().toString();
/*
                    bar.setVisibility(View.VISIBLE);
*/
                    sendverificationcode(number);

            }
            }
        });
        verificationId = getIntent().getStringExtra("verificationId");

        autoOtpReceiver();
    }

what I am trying to do is saving the verificationId globaly that I can use it whenever I want.
I didn't know how to notify this when the variable is changed


问:
Django forms: MultipleChoiceField set active options on init
I'm building a custom form using ul and li items for selecting options and I have a problem that is based on a logic I have in my forms. So I have some models in which I create my product attributes and a separate model which has those attributes values. So this is how I create my form

```<code>class PropertyAttributeForm(FormSpamDetect, forms.Form):
    adg = HoneypotField()

    def __init__(self, *args, **kwargs):
        super(PropertyAttributeForm, self).__init__(*args, **kwargs)

        # TODO add cache
        # Get custom attribute fields
        for attribute in PropertyAttribute.objects.filter(is_active=True):

            # TODO: add more types
            if attribute.type == PropertyAttribute.STRING:
                if choices := attribute.value_choices.all():
                    choices_tuple = ((choice.value_slugified, choice.value) for choice in choices)
                    self.fields[attribute.slugified_name] = forms.MultipleChoiceField()
                    self.fields[attribute.slugified_name].choices = choices_tuple

                    self.fields[attribute.slugified_name].required = False
                    self.fields[attribute.slugified_name].widget.attrs.update({"class": "hidden"})

    def save(self, commit=True):
        if self.is_valid():
            try:
                property = Property.objects.last() # TODO pass pk from session
                property.attrs = json.dumps(self.cleaned_data)

                property.save()
            except Property.DoesNotExist:
                return
</code>```

And this is my form in template:

```<code><form id="property-ajax-form" class="grid gap-12 mt-10 grid-flow-row grid-cols-1">
    {{ form.adg }}

    {% for field in form.attribute_fields %}
        <div class="text-lg text-center">
            <span class="text-left text-2xl font-medium text-primary">{{ attr_name_by_slugified_name[field]|safe }}</span>

            {{ form[field] }}
            <ul id="{{ field }}-options" class="grid grid-flow-row grid-cols-4 mt-5 gap-5 w-3/5 mx-auto">
                {% for attribute in form[field] %}
                    <li data-type="{{ attribute.data.value }}" class="flex flex-col m-auto items-center justify-center gap-3 h-40 w-full rounded-3xl shadow-sm transition ease-in-out border border-white border-3 cursor-pointer hover:scale-105 hover:border-blue [&.active]:font-medium [&.active]:border-blue [&.active]:text-blue {% if attribute.data.selected %}active{% endif %}">
                        <i class="text-3xl fa-{% if attribute.data.value == 'adapted_for_disabled' %}brands{% else %}light{% endif%}
                        {{ icon_by_attribute_slugified_name[attribute.data.value] }}"></i>
                        <span>{{ attribute.data.label }}</span>
                    </li>
                {% endfor %}
            </ul>
        </div>
    {% endfor %}

    {% include "property/create/control_buttons.html" %}
</form>
</code>```

The question is how can I set selected options in form init method? I'm not using a ModelForm due to my logic complexity, so there's no instance saved and I can't just pass it.

UI view

Body:
I'm building a custom form using ul and li items for selecting options and I have a problem that is based on a logic I have in my forms. So I have some models in which I create my product attributes and a separate model which has those attributes values. So this is how I create my form

class PropertyAttributeForm(FormSpamDetect, forms.Form):
    adg = HoneypotField()

    def __init__(self, *args, **kwargs):
        super(PropertyAttributeForm, self).__init__(*args, **kwargs)

        # TODO add cache
        # Get custom attribute fields
        for attribute in PropertyAttribute.objects.filter(is_active=True):

            # TODO: add more types
            if attribute.type == PropertyAttribute.STRING:
                if choices := attribute.value_choices.all():
                    choices_tuple = ((choice.value_slugified, choice.value) for choice in choices)
                    self.fields[attribute.slugified_name] = forms.MultipleChoiceField()
                    self.fields[attribute.slugified_name].choices = choices_tuple

                    self.fields[attribute.slugified_name].required = False
                    self.fields[attribute.slugified_name].widget.attrs.update({"class": "hidden"})

    def save(self, commit=True):
        if self.is_valid():
            try:
                property = Property.objects.last() # TODO pass pk from session
                property.attrs = json.dumps(self.cleaned_data)

                property.save()
            except Property.DoesNotExist:
                return

And this is my form in template:

<form id="property-ajax-form" class="grid gap-12 mt-10 grid-flow-row grid-cols-1">
    {{ form.adg }}

    {% for field in form.attribute_fields %}

            {{ attr_name_by_slugified_name[field]|safe }}

            {{ form[field] }}

                {% for attribute in form[field] %}

                        {{ attribute.data.label }}

                {% endfor %}

    {% endfor %}

    {% include "property/create/control_buttons.html" %}
</form>

The question is how can I set selected options in form init method? I'm not using a ModelForm due to my logic complexity, so there's no instance saved and I can't just pass it.

UI view


问:
Angular app not working when deploying to firebase hosting
Basically I'm just getting endless loading.

my firebase.json:

```<code>{
  "hosting": {
    "public": "dist/my-app",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}
</code>```

I built the project, and there is indeed index.html inside my-app folder.

I just don't know where the problem is, maybe routing? I'm using the same router config as I used is local host, didn't change anything when deployed

Body:
Basically I'm just getting endless loading.

my firebase.json:

{
  "hosting": {
    "public": "dist/my-app",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

I built the project, and there is indeed index.html inside my-app folder.

I just don't know where the problem is, maybe routing? I'm using the same router config as I used is local host, didn't change anything when deployed


问:
Ncurses in C, implement backspace
I'm working on a project to build wordle game with ncurses library. At this moment, I'm stuck because I try to implement backspace and it didn't work.

Here is my code:

```<code>#include <ncurses.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char **argv) {
    initscr();
    noecho();
    curs_set(0);
    int Y_Max, X_Max;
    getmaxyx(stdscr, Y_Max, X_Max);
    WINDOW *win = newwin(Y_Max / 2 + 1, X_Max / 4, Y_Max / 4, X_Max / 4);
    box(win, 0, 0);
    mvwprintw(win, 2, 25, "WORDLE");
    wgetch(win);
    char s[100];
    for (int j = 0; j < 6; j++) {
        WINDOW *chenar = newwin(1, 5, Y_Max / 4 + 4 + j, X_Max / 4 + 25);
        box(chenar, 0, 0);
        int i = 0;
        while (i < 5) {
            s[i] = wgetch(win);
            int coo = getparx(chenar), coo2 = getpary(chenar);
            if (s[i] != 127 && s[i] != KEY_BACKSPACE && s[i] != '\b') {
                wprintw(chenar, "%c", s[i]);
                wrefresh(chenar);
                i++;
            } else {
                wmove(chenar, coo2, coo);
                clrtoeol();
                wrefresh(chenar);
            }
        }
        wgetch(chenar);
    }
    cbreak();
    refresh();
    endwin();
    return 0;
}
</code>```

When I run, I type every character and when I pressed backspace it doesn't clear my line. I hope you can help me. Thanks!

Title: Ncurses in C, implement backspace

Body:
I'm working on a project to build wordle game with ncurses library. At this moment, I'm stuck because I try to implement backspace and it didn't work.

Here is my code:

#include <ncurses.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char **argv) {
    initscr();
    noecho();
    curs_set(0);
    int Y_Max, X_Max;
    getmaxyx(stdscr, Y_Max, X_Max);
    WINDOW *win = newwin(Y_Max / 2 + 1, X_Max / 4, Y_Max / 4, X_Max / 4);
    box(win, 0, 0);
    mvwprintw(win, 2, 25, "WORDLE");
    wgetch(win);
    char s[100];
    for (int j = 0; j < 6; j++) {
        WINDOW *chenar = newwin(1, 5, Y_Max / 4 + 4 + j, X_Max / 4 + 25);
        box(chenar, 0, 0);
        int i = 0;
        while (i < 5) {
            s[i] = wgetch(win);
            int coo = getparx(chenar), coo2 = getpary(chenar);
            if (s[i] != 127 && s[i] != KEY_BACKSPACE && s[i] != '\b') {
                wprintw(chenar, "%c", s[i]);
                wrefresh(chenar);
                i++;
            } else {
                wmove(chenar, coo2, coo);
                clrtoeol();
                wrefresh(chenar);
            }
        }
        wgetch(chenar);
    }
    cbreak();
    refresh();
    endwin();
    return 0;
}

When I run, I type every character and when I pressed backspace it doesn't clear my line. I hope you can help me. Thanks!


问:
How to deploy a trained model on a database with a different number of columns (features) than the training database?
I have a database with 50 columns and 100 rows.
The first column is the speed and the 49 remaining columns are the time.
This database shows the speed according to the time of 49 cars.
These 49 cars are classified in two: Slow and Fast.
I want to predict for a new car its class knowing some measures of its speed.
To do this I trained the Random forest on this basis, ie for each car I have 100 data.
Now I want to deploy this model for a new car.
In other words for this car I have only 10 data but I did not succeed because my model requires to fill the 90 remaining data which is not the goal of the study .

How to deploy a trained model on a database with a different number of columns (features) than the training database?


问:
Showing elements based on data attr in React
I have a nav (.navigation) which contains li's that have a data-panel assigned to them.

This is how I'm looking for it to work:

By default, the #screenOne panel is active (because it has the .active class)

User then clicks a .navigation__li, then it will get that elements data-panel attr and add the selected class to that li element

It will then also add the active class to the .panel that has the matching ID as the li the user clicks on.

With my current implementation, I'm running into Cannot read properties of undefined (reading 'getAttribute') errors.

Here is my current approach:

src/components/Navigation

import React from 'react';
import { Container, Row, Col } from 'react-bootstrap';
import changePanel from '../../utils/helpers';

class Navigation extends React.Component{

  render(){

    return(

        <Container>
          <Row>
            <Col>

                <Container>
                  <Row className="justify-content-center">
                    <Col>

Panel 1

Panel 2

                    </Col>
                  </Row>
                </Container>

            </Col>
          </Row>
        </Container>

    )
  }

}

export default Navigation;```
</div>
</div>
</p>
<p><code>src/components/Screen</code></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React from 'react';
import { Container, Row, Col } from 'react-bootstrap';

function Screen(props) {

  const sectionID = props.id;
  const tag = props.tag;
  const header = props.header;

  return(

    <div className="panel active" id={sectionID}>
      <Container>
        <Row className="justify-content-center align-items-center">

          <Col xs={12} md={6}>
            <div className="panel__left fadeIn">
              <h1 className="panel__left-title">
                <span className="d-block">{tag}</span>
                <span className="d-block">{header}</span>
              </h1>
            </div>
          </Col>

        </Row>
      </Container>
    </div>

  )

}

export default Screen;</code>```

src/utils/helpers

const changePanel = function() {

  // get data-panel attr from .navigation
  let panelID = this.getAttribute("data-panel");

  // remove active state from all .panel's
  let allPanels = Array.from(document.querySelectorAll('.panel'));
  for (let panel of allPanels) {
    panel.classList.remove('active');
  }

  // make the matching panel ID active
  document.querySelector("#"+ panelID).classList.add("active");

  // make the clicked nav item active
  let navItems = Array.from(document.querySelectorAll('.nagivation__li'));
  for (let navItem of navItems) {
    navItem.classList.remove('selected');
  }

  this.addClass("selected");

  // debugging
  console.log(panelID);

}

export default changePanel;```
</div>
</div>
</p>
<p><code>src/pages/Homepage</code></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React from "react";
import Screen from "../components/Screen/Screen";
import Navigation from "../components/Navigation/Navigation";

class Homepage extends React.Component {

  render(){

    return (
      <section id="project">
        <Screen id="screenOne" tag="Panel 1" header="Screen 1"/>
        <Screen id="screenTwo" tag="Panel 2" header="Screen 2"/>
        <Navigation />
      </section>
    );

  }

}

export default Homepage;</code>```

Body:
I have a nav (.navigation) which contains li's that have a data-panel assigned to them.

This is how I'm looking for it to work:

By default, the #screenOne panel is active (because it has the .active class)

User then clicks a .navigation__li, then it will get that elements data-panel attr and add the selected class to that li element

It will then also add the active class to the .panel that has the matching ID as the li the user clicks on.

With my current implementation, I'm running into Cannot read properties of undefined (reading 'getAttribute') errors.

Here is my current approach:

src/components/Navigation

import React from 'react';
import { Container, Row, Col } from 'react-bootstrap';
import changePanel from '../../utils/helpers';

class Navigation extends React.Component{

  render(){

    return(

        <Container>
          <Row>
            <Col>

                <Container>
                  <Row className="justify-content-center">
                    <Col>

Panel 1

Panel 2

                    </Col>
                  </Row>
                </Container>

            </Col>
          </Row>
        </Container>

    )
  }

}

export default Navigation;

src/components/Screen

import React from 'react';
import { Container, Row, Col } from 'react-bootstrap';

function Screen(props) {

  const sectionID = props.id;
  const tag = props.tag;
  const header = props.header;

  return(

      <Container>
        <Row className="justify-content-center align-items-center">

          <Col xs={12} md={6}>

                {tag}
                {header}

          </Col>

        </Row>
      </Container>

  )

}

export default Screen;

src/utils/helpers

const changePanel = function() {

  // get data-panel attr from .navigation
  let panelID = this.getAttribute("data-panel");

  // remove active state from all .panel's
  let allPanels = Array.from(document.querySelectorAll('.panel'));
  for (let panel of allPanels) {
    panel.classList.remove('active');
  }

  // make the matching panel ID active
  document.querySelector("#"+ panelID).classList.add("active");

  // make the clicked nav item active
  let navItems = Array.from(document.querySelectorAll('.nagivation__li'));
  for (let navItem of navItems) {
    navItem.classList.remove('selected');
  }

  this.addClass("selected");

  // debugging
  console.log(panelID);

}

export default changePanel;

src/pages/Homepage

import React from "react";
import Screen from "../components/Screen/Screen";
import Navigation from "../components/Navigation/Navigation";

class Homepage extends React.Component {

  render(){

    return (

        <Screen id="screenOne" tag="Panel 1" header="Screen 1"/>
        <Screen id="screenTwo" tag="Panel 2" header="Screen 2"/>
        <Navigation />

    );

  }

}

export default Homepage;


问:
How to identify server port for react deployment in firebase
My react application functions perfectly after deploying to firebase on port 3001.
enter image description here

When I try to fetch data using another from another system, however, the data fetch doesn't work.

How do I resolve this?

I understand I have to use environment port variables (i.e process.env.port) but I'm not sure how to approach this.

Is there an example I can follow. Thanks


问:
Java No line found after opening from project.jar
I have a problem after pressing the rebirth button, because the program turns off and on correctly, but when I turn it on again after a few minutes, I get an error:

```<code>Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
    at Clicker.Skarbiec.<init>(Skarbiec.java:23)
    at Clicker.Menu.<init>(Menu.java:9)
    at Clicker.EkranGlowny.<init>(EkranGlowny.java:12)
    at Clicker.Clicker.main(Clicker.java:5)
</code>```

To fix it I have to copy the data from the text file and create literally another one, what is wrong with it?

Method save:

```<code>public void zapisz() {
    try {
        BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\assai\\Desktop\\KlikerZdjecia\\progres.txt"));
        writer.write("Doświadczenie: " + doswiadczenie + " Pieniądze: " + pieniadze + " PieniądzeZaWciśnięcie: " + pieniadzeZaWcisniecie + " MnoznikZaRebirth: " + mnoznikZaRebirth + " PieniadzeLacznie: " + pieniadzeLacznie);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

Method load:

```<code>try (Scanner scanner = new Scanner(new File("C:\\Users\\assai\\Desktop\\KlikerZdjecia\\progres.txt"), StandardCharsets.UTF_8)) {
        String[] progress = scanner.nextLine().split("\\s+");
        doswiadczenie = BigDecimal.valueOf(Double.parseDouble(progress[1]));
        pieniadze = BigDecimal.valueOf(Double.parseDouble(progress[3]));
        pieniadzeZaWcisniecie = BigDecimal.valueOf(Double.parseDouble(progress[5]));
        mnoznikZaRebirth = BigDecimal.valueOf(Double.parseDouble(progress[7]));
        pieniadzeLacznie = BigDecimal.valueOf(Double.parseDouble(progress[9]));
    } catch(FileNotFoundException e){
        e.printStackTrace();
    } catch(IOException e){
        throw new RuntimeException(e);
    }
</code>```

rebirth actionPerformed:

```<code>if (e.getSource().equals(rebirth)) {
    BigDecimal odrodzenie;
    odrodzenie = skarbiec.getPieniadzeLacznie().multiply(BigDecimal.valueOf(0.0000001)).setScale(2, RoundingMode.HALF_UP);
    int confirm = JOptionPane.showConfirmDialog(ekran, "Czy na pewno chcesz zrobić rebirth? Dostaniesz za to: " + odrodzenie + "% Bonusu", "Potwierdzenie rebirth gry", JOptionPane.YES_NO_OPTION);
    if (confirm == JOptionPane.YES_OPTION) {
        skarbiec.setMnoznikZaRebirth(skarbiec.getMnoznikZaRebirth().add(odrodzenie));
        resetowanieGry();
        try {
            Process process = new ProcessBuilder("java", "-jar", "C:\\Users\\assai\\IdeaProjects\\ClickerGra\\out\\artifacts\\ClickerGra_jar\\ClickerGra.jar").start();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        System.exit(0);
    }
}
</code>```

Of course, the path is given correctly and the file after closing still has the same data that should work because without using the rebirth button the program works correctly.
Any ideas how Can I fix it?

It expects that the program, when enabled via jar, will run normally every time, not just the first time
I've already tried deleting the text file and creating a new one every time it shuts down, but the problem doesn't go away

Body:
I have a problem after pressing the rebirth button, because the program turns off and on correctly, but when I turn it on again after a few minutes, I get an error:

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
    at Clicker.Skarbiec.<init>(Skarbiec.java:23)
    at Clicker.Menu.<init>(Menu.java:9)
    at Clicker.EkranGlowny.<init>(EkranGlowny.java:12)
    at Clicker.Clicker.main(Clicker.java:5)

To fix it I have to copy the data from the text file and create literally another one, what is wrong with it?

Method save:

public void zapisz() {
    try {
        BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\assai\\Desktop\\KlikerZdjecia\\progres.txt"));
        writer.write("Doświadczenie: " + doswiadczenie + " Pieniądze: " + pieniadze + " PieniądzeZaWciśnięcie: " + pieniadzeZaWcisniecie + " MnoznikZaRebirth: " + mnoznikZaRebirth + " PieniadzeLacznie: " + pieniadzeLacznie);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Method load:

try (Scanner scanner = new Scanner(new File("C:\\Users\\assai\\Desktop\\KlikerZdjecia\\progres.txt"), StandardCharsets.UTF_8)) {
        String[] progress = scanner.nextLine().split("\\s+");
        doswiadczenie = BigDecimal.valueOf(Double.parseDouble(progress[1]));
        pieniadze = BigDecimal.valueOf(Double.parseDouble(progress[3]));
        pieniadzeZaWcisniecie = BigDecimal.valueOf(Double.parseDouble(progress[5]));
        mnoznikZaRebirth = BigDecimal.valueOf(Double.parseDouble(progress[7]));
        pieniadzeLacznie = BigDecimal.valueOf(Double.parseDouble(progress[9]));
    } catch(FileNotFoundException e){
        e.printStackTrace();
    } catch(IOException e){
        throw new RuntimeException(e);
    }

rebirth actionPerformed:

if (e.getSource().equals(rebirth)) {
    BigDecimal odrodzenie;
    odrodzenie = skarbiec.getPieniadzeLacznie().multiply(BigDecimal.valueOf(0.0000001)).setScale(2, RoundingMode.HALF_UP);
    int confirm = JOptionPane.showConfirmDialog(ekran, "Czy na pewno chcesz zrobić rebirth? Dostaniesz za to: " + odrodzenie + "% Bonusu", "Potwierdzenie rebirth gry", JOptionPane.YES_NO_OPTION);
    if (confirm == JOptionPane.YES_OPTION) {
        skarbiec.setMnoznikZaRebirth(skarbiec.getMnoznikZaRebirth().add(odrodzenie));
        resetowanieGry();
        try {
            Process process = new ProcessBuilder("java", "-jar", "C:\\Users\\assai\\IdeaProjects\\ClickerGra\\out\\artifacts\\ClickerGra_jar\\ClickerGra.jar").start();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        System.exit(0);
    }
}

Of course, the path is given correctly and the file after closing still has the same data that should work because without using the rebirth button the program works correctly.
Any ideas how Can I fix it?

It expects that the program, when enabled via jar, will run normally every time, not just the first time
I've already tried deleting the text file and creating a new one every time it shuts down, but the problem doesn't go away


问:
Error [ERR_REQUIRE_ESM]: require() of ES not supported
I want to use graphql upload package in nestjs. But I am facing some error-

Here is my code-

```<code>import { GraphqlUpload, FileUpload } from "graphql-upload/GraphQLUpload.mjs";
import { createWriteStream } from 'fs';

    @Mutation(() => SuccessInfo, { name: "updateProfile" })
    update(
        @Args("file", { type: () => GraphqlUpload }) {
            createReadStream,
            filename
        }: FileUpload
    ) {
        console.log(filename);
    }
</code>```

How can I solve this.

Body:
I want to use graphql upload package in nestjs. But I am facing some error-

Here is my code-

import { GraphqlUpload, FileUpload } from "graphql-upload/GraphQLUpload.mjs";
import { createWriteStream } from 'fs';

    @Mutation(() => SuccessInfo, { name: "updateProfile" })
    update(
        @Args("file", { type: () => GraphqlUpload }) {
            createReadStream,
            filename
        }: FileUpload
    ) {
        console.log(filename);
    }

How can I solve this.


问:
Why's an error being throw when trying to use MouseEvent
Anyone know what could be the issue here?  It's giving me an error that says:

Unexpected token, expected ",", it's pointing to the event: part but not sure what I'm supposed to do?  I've tried the obvious event, ... but that still didn't work

```<code>    const [anchorElNav, setAnchorElNav] = React.useState<null | HTMLElement>(null);
    const [anchorElUser, setAnchorElUser] = React.useState<null | HTMLElement>(null);

    const handleOpenNavMenu = (event: React.MouseEvent<HTMLElement>) => {
        setAnchorElNav(event.currentTarget);
    };

    const handleOpenUserMenu = (event: React.MouseEvent<HTMLElement>) => {
        setAnchorElUser(event.currentTarget);
    };
</code>```

how can I fix this?

Body:
Anyone know what could be the issue here?  It's giving me an error that says:

Unexpected token, expected ",", it's pointing to the event: part but not sure what I'm supposed to do?  I've tried the obvious event, ... but that still didn't work

    const [anchorElNav, setAnchorElNav] = React.useState<null | HTMLElement>(null);
    const [anchorElUser, setAnchorElUser] = React.useState<null | HTMLElement>(null);

    const handleOpenNavMenu = (event: React.MouseEvent<HTMLElement>) => {
        setAnchorElNav(event.currentTarget);
    };

    const handleOpenUserMenu = (event: React.MouseEvent<HTMLElement>) => {
        setAnchorElUser(event.currentTarget);
    };

how can I fix this?


问:
I am getting ValueError: The estimator Sequential should be a classifier. how can I solve it?
I am using VotingClassifier for 31 Pre-trained models, when I wanted to do voting using VotingClassifier. I got this error ValueError: The estimator Sequential should be a classifier. The code is as shown below:

```<code>estimators = [("EfficientNetB0_model",EfficientNetB0_model),("EfficientNetB1_model",EfficientNetB1_model),("DenseNet121_model",DenseNet121_model),
              ("DenseNet169_model",DenseNet169_model),("DenseNet201_model",DenseNet201_model),("EfficientNetB2_model",EfficientNetB2_model),
              ("EfficientNetB3_model",EfficientNetB3_model),("EfficientNetB4_model",EfficientNetB4_model),("EfficientNetB5_model",EfficientNetB5_model),
              ("EfficientNetB6_model",EfficientNetB6_model),("EfficientNetB7_model",EfficientNetB7_model),("EfficientNetV2B0_model",EfficientNetV2B0_model),
              ("EfficientNetV2B1_model",EfficientNetV2B1_model),("EfficientNetV2B2_model",EfficientNetV2B2_model),("EfficientNetV2B3_model",EfficientNetV2B3_model),
              ("EfficientNetV2L_model",EfficientNetV2L_model),("EfficientNetV2M_model",EfficientNetV2M_model),("EfficientNetV2S_model",EfficientNetV2S_model),
              ("InceptionResNetV2_model",InceptionResNetV2_model),("InceptionV3_model",InceptionV3_model),
              ("ResNet50_model",ResNet50_model),("ResNet50V2_model",ResNet50V2_model),("ResNet101_model",ResNet101_model),
              ("ResNet101V2_model",ResNet101V2_model),("ResNet152_model",ResNet152_model),("ResNet152V2_model",ResNet152V2_model),
              ("VGG16_model",VGG16_model),("VGG19_model",VGG19_model),("Xception_model",Xception_model),
              ("MobileNet_model",MobileNet_model),("MobileNetV2_model",MobileNetV2_model)]

weights = [0.2, 0.3, 0.0, 0.1, 0.0,
           0.3, 0.2, 0.1, 0.0, 0.3,
           0.1, 0.3, 0.3, 0.1, 0.0,
           0.1, 0.2, 0.1, 0.1, 0.1,
           0.4, 0.0, 0.2, 0.1, 0.4,
           0.0, 0.0, 0.1, 0.1, 0.0, 0.0
           ]

ensemble = VotingClassifier(estimators, weights=weights, voting= 'soft')
ensemble._estimator_type = "classifier"
ensemble = ensemble.fit(X_train, y_train)
print(ensemble.predict(X_test))
</code>```

Could you help me since I could not find any solution for that. Thank you
Is there any other ways to do voting ?

Body:
I am using VotingClassifier for 31 Pre-trained models, when I wanted to do voting using VotingClassifier. I got this error ValueError: The estimator Sequential should be a classifier. The code is as shown below:

estimators = [("EfficientNetB0_model",EfficientNetB0_model),("EfficientNetB1_model",EfficientNetB1_model),("DenseNet121_model",DenseNet121_model),
              ("DenseNet169_model",DenseNet169_model),("DenseNet201_model",DenseNet201_model),("EfficientNetB2_model",EfficientNetB2_model),
              ("EfficientNetB3_model",EfficientNetB3_model),("EfficientNetB4_model",EfficientNetB4_model),("EfficientNetB5_model",EfficientNetB5_model),
              ("EfficientNetB6_model",EfficientNetB6_model),("EfficientNetB7_model",EfficientNetB7_model),("EfficientNetV2B0_model",EfficientNetV2B0_model),
              ("EfficientNetV2B1_model",EfficientNetV2B1_model),("EfficientNetV2B2_model",EfficientNetV2B2_model),("EfficientNetV2B3_model",EfficientNetV2B3_model),
              ("EfficientNetV2L_model",EfficientNetV2L_model),("EfficientNetV2M_model",EfficientNetV2M_model),("EfficientNetV2S_model",EfficientNetV2S_model),
              ("InceptionResNetV2_model",InceptionResNetV2_model),("InceptionV3_model",InceptionV3_model),
              ("ResNet50_model",ResNet50_model),("ResNet50V2_model",ResNet50V2_model),("ResNet101_model",ResNet101_model),
              ("ResNet101V2_model",ResNet101V2_model),("ResNet152_model",ResNet152_model),("ResNet152V2_model",ResNet152V2_model),
              ("VGG16_model",VGG16_model),("VGG19_model",VGG19_model),("Xception_model",Xception_model),
              ("MobileNet_model",MobileNet_model),("MobileNetV2_model",MobileNetV2_model)]

weights = [0.2, 0.3, 0.0, 0.1, 0.0,
           0.3, 0.2, 0.1, 0.0, 0.3,
           0.1, 0.3, 0.3, 0.1, 0.0,
           0.1, 0.2, 0.1, 0.1, 0.1,
           0.4, 0.0, 0.2, 0.1, 0.4,
           0.0, 0.0, 0.1, 0.1, 0.0, 0.0
           ]

ensemble = VotingClassifier(estimators, weights=weights, voting= 'soft')
ensemble._estimator_type = "classifier"
ensemble = ensemble.fit(X_train, y_train)
print(ensemble.predict(X_test))

Could you help me since I could not find any solution for that. Thank you
Is there any other ways to do voting ?


问:
Eclipse IDE is not opening up
I am getting this error when end task from task manager.

I tried restarting pc but it didn't work.

Title: Eclipse IDE is not opening up


问:
Why objects in flask-sqlalchemy still show up as valid?
After setting up two tables with the following code

class User(db.Model):
    id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    email = db.Column(db.String(100), unique=True)
    password = db.Column(Password)
    name = db.Column(db.String(1000))
    studies = db.relationship('Study', backref='owner', lazy=True, cascade='save-update, merge, delete')

class Study(db.Model):
    id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    owner_id = db.Column(UUID(as_uuid=True), db.ForeignKey('user.id'), nullable=False)
```
<p>I am testing that the removal of studies happens when the user gets removed. So far, seems to be the case, but I need to get to the database to discover that:</p>
<pre class="lang-py prettyprint-override"><code>def test_studies_removed_with_user(app):
    user = User.query.filter_by(email=app.config['TESTUSER_EMAIL']).first()
    study = Study(owner=user)

    db.session.add(study)
    db.session.commit()

    assert study

    db.session.delete(user)
    db.session.commit()

    assert User.query.filter_by(email=app.config['TESTUSER_EMAIL']).first() is None
    assert not Study.query.filter_by(owner_id=user.id).all()
</code>```

if I break with the debugger in the prior to last assert, user variable is still populated, and so is study. I'd have expected these variables to be invalid now (because the asserts succeed, even the second which uses id from 'user', so the entries are removed on the database).

Is this expected behavior, or am I doing something wrong?

Body:
After setting up two tables with the following code

class User(db.Model):
    id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    email = db.Column(db.String(100), unique=True)
    password = db.Column(Password)
    name = db.Column(db.String(1000))
    studies = db.relationship('Study', backref='owner', lazy=True, cascade='save-update, merge, delete')

class Study(db.Model):
    id = db.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    owner_id = db.Column(UUID(as_uuid=True), db.ForeignKey('user.id'), nullable=False)

I am testing that the removal of studies happens when the user gets removed. So far, seems to be the case, but I need to get to the database to discover that:

def test_studies_removed_with_user(app):
    user = User.query.filter_by(email=app.config['TESTUSER_EMAIL']).first()
    study = Study(owner=user)

    db.session.add(study)
    db.session.commit()

    assert study

    db.session.delete(user)
    db.session.commit()

    assert User.query.filter_by(email=app.config['TESTUSER_EMAIL']).first() is None
    assert not Study.query.filter_by(owner_id=user.id).all()

if I break with the debugger in the prior to last assert, user variable is still populated, and so is study. I'd have expected these variables to be invalid now (because the asserts succeed, even the second which uses id from 'user', so the entries are removed on the database).

Is this expected behavior, or am I doing something wrong?


问:
How to render a custom GridView based on the JSON response from Server for Flutter(Android)?
I am designing a plant tracking app for which I need to render grids, the problem is the fields are uneven and so some grids are rectangular, some are square and some are uneven as well and I need to track each and every plant as a grid cell, and each plant has a different lifecycle and different set of rules for transplantation, germination, fruiting dates, plus each plant's most important rule is the spacing i.e some plants can be spaced at a distance of 60cm from each other but some require 400cm, so based on this data I want to render a cell wherein the size of the grid cell is determined by the plant's spacing and the color should be red after it is planted once, plus I can render the uneven Grids as well.

Is it possible to have such a GridView?

Here's the thing I am trying to achieve but the exception test cases are that it will not be limited to a square or a rectangle. Like in the image I have shown the red marked area, that's the different test cases I would like to cover.


问:
Owl carousel inside owl carousel using ngx-owl-carousel-o
Can anyone provide a code sample to create an owl carousel inside another owl carousel?

Help will be appreciated.

Need help


问:
buildozer android debug error when I tried to build apk
I am trying ro build a apk file from .py.
I am running a buildozer android debug deploy run command.
I have a openjdk version 1.8.0_352.
I am trying to run it on the VirtualBox.
Dont know why it doesn't work :(

Here are the logs:

first part of logs

second part of logs


问:
Why my bootstrap breakpoint width differs from the standard size?
I am trying to understand bootstrap classes. The doc contains following example:

```<code><div class="container">
  <div class="row">
    <div class="col-sm">
      One of three columns
    </div>
    <div class="col-sm">
      One of three columns
    </div>
    <div class="col-sm">
      One of three columns
    </div>
  </div>
</div>
</code>```

It gets rendered as follows in the jsfiddle as follows:

Given that class sm corresponds to size >=576px, I dont get why above gets rendered with breakpoint at 593px.

PS:

The CSS is as follows:

```<code>.row {
  background: #f8f9fa;
  margin-top: 20px;
  margin-left: 10px;
  margin-right: 10px;
}

.col {
  border: solid 1px #6c757d;
  padding: 10px;
}

.col-sm {
  border: solid 1px #6c757d;
}
</code>```

Body:
I am trying to understand bootstrap classes. The doc contains following example:

      One of three columns

      One of three columns

      One of three columns

It gets rendered as follows in the jsfiddle as follows:

Given that class sm corresponds to size >=576px, I dont get why above gets rendered with breakpoint at 593px.

PS:

The CSS is as follows:

.row {
  background: #f8f9fa;
  margin-top: 20px;
  margin-left: 10px;
  margin-right: 10px;
}

.col {
  border: solid 1px #6c757d;
  padding: 10px;
}

.col-sm {
  border: solid 1px #6c757d;
}


问:
App name wont update in Apple Pay menu after name change
I have changed the name of my app but it won't update in the Apple Pay screen when trying to purchase a subscription, it still shows the old name. I have a screenshot that shows in red where the name is that im trying to change.Screenshot of what im trying to change

I have changed name everywhere possible in react, revenuecat and app store connect. Unless I have missed some place? I have searched for the old app name in the react files atleast and can asure that the name isn't left there.


问:
How to send data from adapter class to mainClass in java
I know there are a lot of questions like this but not this. But i want kinda like on Change listener in my main class.

My problem (related to recyclerView)

I have an arrayList made in main class

The arrayList is then passed to adapter class

In my recyclerView i have a delete button, which successfull deletes from arrayList and recyclerView.

In my main class value of arrayList is added and the value is set to text View (the textView is not a part of recyclerView)

When i delete an item from array in adapter class. The sum of ArrayList changes but the changes don't apply to textView in mainClass.

My code

viewholder in adapterclass

```<code>    // ViewHolder class in Adapter class
    public class ViewHolder extends RecyclerView.ViewHolder{

        Button delButton;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            delButton = itemView.findViewById(R.id.deleteBtnTimberR);

            // Delete button is here
            delButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    arrayTimber.remove(getLayoutPosition());
                    notifyItemRemoved(getLayoutPosition());
                    notifyItemRangeChanged(getLayoutPosition(), arrayTimber.size());
                }
            });
        }
    }
</code>```

main class

```<code>        // here i get the final added answer.
        Float finalAnswer= 0.0F;
        for (int i=0; i<arrayList.size(); i++){
            finalAnswer += Float.parseFloat(arrayList.get(i).ansToBeAdded);
        }

        answerAdded.setText(String.valueof(finalAnswer));

        //Now i want something here when i change arrayList, the addition should happen again and the setText() should update.
</code>```

Body:
I know there are a lot of questions like this but not this. But i want kinda like on Change listener in my main class.

My problem (related to recyclerView)

I have an arrayList made in main class

The arrayList is then passed to adapter class

In my recyclerView i have a delete button, which successfull deletes from arrayList and recyclerView.

In my main class value of arrayList is added and the value is set to text View (the textView is not a part of recyclerView)

When i delete an item from array in adapter class. The sum of ArrayList changes but the changes don't apply to textView in mainClass.

My code

viewholder in adapterclass

    // ViewHolder class in Adapter class
    public class ViewHolder extends RecyclerView.ViewHolder{

        Button delButton;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            delButton = itemView.findViewById(R.id.deleteBtnTimberR);

            // Delete button is here
            delButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    arrayTimber.remove(getLayoutPosition());
                    notifyItemRemoved(getLayoutPosition());
                    notifyItemRangeChanged(getLayoutPosition(), arrayTimber.size());
                }
            });
        }
    }

main class

        // here i get the final added answer.
        Float finalAnswer= 0.0F;
        for (int i=0; i<arrayList.size(); i++){
            finalAnswer += Float.parseFloat(arrayList.get(i).ansToBeAdded);
        }

        answerAdded.setText(String.valueof(finalAnswer));

        //Now i want something here when i change arrayList, the addition should happen again and the setText() should update.


问:
updating plots with large points number in a cycle to visualize progress using matplotlib and python
I am using Python for processing large datasets.

Each part of the data in the dataset is processed step by step in a cycle.
I need to add some visualization during processing.

Now I do plotting using matplotlib for current portion of data.  For each step of the cycle I am executing function plot which plots new figure for each step..

The problem is I have a lot of data and plots... E.g. 1000000 plots, and if I will output it in Jupyter it just crashes. I want to use one figure and update data on it through a cycle and show it to see processing?

I want to create a ONE plot but the data on that figure will be changed on each step of processing - for current portion of data.

How to do that - to see that image during processing (e.g. using jupyter notebook)?

(So running through a cycle in one cell will show only one figure with one plot but the scatter on that plot will change cycle by cycle updating the existing figure)

something like:

```<code>update_plot(plot_name: str, datax: np.array, datay: np.array)
</code>```

that will CHANGE the existing plot (important - I need to see it on the screen on each step - to understand that there is progress and it works correctly) It's like animation where each step - is a frame that needs to be changed. E.g. I am adding a special point on a plot for each step.

Body:
I am using Python for processing large datasets.

Each part of the data in the dataset is processed step by step in a cycle.
I need to add some visualization during processing.

Now I do plotting using matplotlib for current portion of data.  For each step of the cycle I am executing function plot which plots new figure for each step..

The problem is I have a lot of data and plots... E.g. 1000000 plots, and if I will output it in Jupyter it just crashes. I want to use one figure and update data on it through a cycle and show it to see processing?

I want to create a ONE plot but the data on that figure will be changed on each step of processing - for current portion of data.

How to do that - to see that image during processing (e.g. using jupyter notebook)?

(So running through a cycle in one cell will show only one figure with one plot but the scatter on that plot will change cycle by cycle updating the existing figure)

something like:

update_plot(plot_name: str, datax: np.array, datay: np.array)

that will CHANGE the existing plot (important - I need to see it on the screen on each step - to understand that there is progress and it works correctly) It's like animation where each step - is a frame that needs to be changed. E.g. I am adding a special point on a plot for each step.


问:
Enable mbstring library for PHP Windows installation
Using php 8.20 X86 Win32 VS16 not thread safe

In PHP.ini I have

```<code>extension=mbstring
</code>```

(i.e. uncommented ";" in front)

and

```<code>extension_dir = "D:\webserve\php8X86Win32VS16NTS\ext"
</code>```

In file system I have:
file php_mbstring.dll
in:
directory D:\webserve\php8X86Win32VS16NTS\ext

...

PHPInfo()

states it is using the php.ini file I have edited.

extension direct is "ext" (which it is if if I use fully qualitfied
path in php.ini)

...

Yet I still get error in code:

Uncaught Error: Call to undefined function Stichoza\GoogleTranslate\Tokens\mb_strlen()

...

What is the next thing I should check in my configuration to get multibyte string support working in PHP?

Body:
Using php 8.20 X86 Win32 VS16 not thread safe

In PHP.ini I have

extension=mbstring

(i.e. uncommented ";" in front)

and

extension_dir = "D:\webserve\php8X86Win32VS16NTS\ext"

In file system I have:
file php_mbstring.dll
in:
directory D:\webserve\php8X86Win32VS16NTS\ext

...

PHPInfo()

states it is using the php.ini file I have edited.

extension direct is "ext" (which it is if if I use fully qualitfied
path in php.ini)

...

Yet I still get error in code:

Uncaught Error: Call to undefined function Stichoza\GoogleTranslate\Tokens\mb_strlen()

...

What is the next thing I should check in my configuration to get multibyte string support working in PHP?


问:
Veins -- Encapsulation of BSMs MAC frames and further MAC frames are encapsulated by AirFrame11p signals -- Omnet++
I am new to Veins and Omnet++ and currently working upon a simulation senario. I have successfully setup environment and run veins 5.2 demo application - Erlangen example.
I am trying to understand how the messages are encapsulated and flow of information. I have read certain Omnet++ documenation, veins exmaple and Stackoverflow post.

Despite reading and following many posts, visualization is still not clear and I would like to clearly in-depth understand, how encapsulation works/is happening in Veins.

I have gone through following post:
Which file to extend for customized messages in veins? What is the purpose of AirFrame11p.msg?

which says, "BSMs are packaged in MAC frames (80211Pkt), which in turn are encapsulated by AirFrame11p signals."
It would be nice, if anyone could please explain how exactly encapsulatin works down the hierarchy.


问:
How to know the real reason for Elastic Beanstalk deployment timeout and failure?
I'm trying to deploy a simple Ruby on Rails application (Ruby 2.7.7 and Rails ~> 6.1.7) using Elastic Beanstalk. Every time I deploy a new version or update the environment configuration, it takes some time, timeouts, and then fails with no changes applied.

Event details

I am SSH to my instance and I can't see any errors on eb-engine.log file. I restart my instance, terminate environment and create the new one too but that issue still happen.
I can't figure out why this happen. Please, help me!
Many thanks.


问:
How to animate adding/removing items in Compose LazyGrid?
I know there is the animateItemPlacement method for LazyColumn, but in LazyGrid it's marked with internal modifier. In any case, this is not exactly what I need, it doesn't animate the addition/removal of items. Are there ready-made solutions (for example, third-party libraries)?


问:
EINTR and epoll_ctl, should I check errno?
I am looking through code for FreeBSD. The code uses kevent programming interface. Now, I find the lines like below:

```<code>status = kevent(...)
if(status < 0){
 if(EINTR == errno){
  goto l_kevent;
 }
 /* ... */
}
</code>```

I need to port the code for Linux, and I wonder... Should I check for EINTR with Linux epoll calls. I know that epoll has epoll_pwait, and it is still should be checked for EINTR. But the documentation I have on hand tells me nothing about the epoll_ctl calls being interruptible.

I can look into source code for epoll. But, as humble, as I am, I do not know how signals are handled in kernel. So, if the code itself relies on some interrupt mechanics, I do not know where to look for return codes of interest.

Hope I explained problem. The question, once again: my documentation tell me nothing on epoll_ctl being interruptible, what should I do? Should I check for EINTR?

P.S
If someone will point me out for the source code for the epoll, that I can comprehend, I will gladly try to do my own research.

Body:
I am looking through code for FreeBSD. The code uses kevent programming interface. Now, I find the lines like below:

status = kevent(...)
if(status < 0){
 if(EINTR == errno){
  goto l_kevent;
 }
 /* ... */
}

I need to port the code for Linux, and I wonder... Should I check for EINTR with Linux epoll calls. I know that epoll has epoll_pwait, and it is still should be checked for EINTR. But the documentation I have on hand tells me nothing about the epoll_ctl calls being interruptible.

I can look into source code for epoll. But, as humble, as I am, I do not know how signals are handled in kernel. So, if the code itself relies on some interrupt mechanics, I do not know where to look for return codes of interest.

Hope I explained problem. The question, once again: my documentation tell me nothing on epoll_ctl being interruptible, what should I do? Should I check for EINTR?

P.S
If someone will point me out for the source code for the epoll, that I can comprehend, I will gladly try to do my own research.


问:
Typeorm get nested relations without intermediate table
I have Many-to-many relations with custom properties like here

I try to get a post with all category like

```<code>PostRepository.findOne({
      relations: ['postToCategories.category'],
      where: { id: 1},
})
</code>```

the results like this

```<code>{
  id: 1,
  name: 'post1',
  postToCategories: [{id: 1, category: {id: 1, name: "cate1"}}]
}
</code>```

But i don't want id of intermediate table. I need something like this

```<code>{
  id: 1,
  name: 'post1',
  postToCategories: [{category: {id: 1, name: "cate1"}}]
}
</code>```

or this

```<code>{
  id: 1,
  name: 'post1',
  postToCategories: [{id: 1, name: "cate1"}]
}
</code>```

I don't need id of postToCategories. How to do that thank.

Body:
I have Many-to-many relations with custom properties like here

I try to get a post with all category like

PostRepository.findOne({
      relations: ['postToCategories.category'],
      where: { id: 1},
})

the results like this

{
  id: 1,
  name: 'post1',
  postToCategories: [{id: 1, category: {id: 1, name: "cate1"}}]
}

But i don't want id of intermediate table. I need something like this

{
  id: 1,
  name: 'post1',
  postToCategories: [{category: {id: 1, name: "cate1"}}]
}

or this

{
  id: 1,
  name: 'post1',
  postToCategories: [{id: 1, name: "cate1"}]
}

I don't need id of postToCategories. How to do that thank.


问:
How to get all sub-Collection from firestore in react native?

I want to get list of all sub-Collection from firestore:

```<code>Chat (col):

     0NzkNYBCqrVsUfORWksdc8bMj7J2 (doc):

          Here, I want to get list of all sub collections
</code>```

I can access sub-Collection individually but i cant get list of collection.

Body:
I want to get list of all sub-Collection from firestore:

Chat (col):

     0NzkNYBCqrVsUfORWksdc8bMj7J2 (doc):

          Here, I want to get list of all sub collections

I can access sub-Collection individually but i cant get list of collection.


问:
Problem with using OpenCV library in Android Dynamic Shared library and Xamarin.Forms
I'm trying to use the OpenCV library for android (native C++) with Xamarin.Forms application. I created a Dynamic Shared Library and its wrapper in C# that works when there is no OpenCV in the project.

Next, I configured my library project to use OpenCV and built it (without actually using OpenCV in my code). The build is successful, but now when I run my Xamarin application and call functions from c++, this exception is thrown:

System.DllNotFoundException: 'libMathFuncs.so assembly: type: member:(null)'

I followed the instructions described here, successfully created a .so file, and used it in Xamarin.Forms application. I wrote the whole process in my blog.

Then I did the following changes to my Dynamic Shared Library project configuration (in Visual Studio):

In General -> Use of STL : LLVM libc++ static library (c++_static)   (also tried shared library)

In C++:

General -> Aditional Include Library: Add "PathToOpenCV\sdk\native\jni\include" (I also tried to add this

path to VC++ Directories -> External Include Directories)

set the Enable C++ Exceptions to Yes (-fexceptions)

set the Enable Run-Time Type Information to Yes (-frtti)

set the Precompile Header to Not Using Precompiled Headers

In Linker:

I tried two ways:

Way 1: I added "sdk\native\libs\arm64-v8a\libopencv_java4.so" to input -> Aditional Dependencies

Way 2:

Added "sdk\native\libs\arm64-v8a" to General -> Additional Library Directories and

Added "opencv_java4" to Input -> Library Dependencies

I didn't use any OpenCV in my code (Actually did at first, but remove them). The project is built successfully.
But now when the application calls the function from .so file, the above exception will be thrown.

I tried with or without changing the told flags, but the result was the same.

Note: For now I only intrested in ARM64

My environment:

Visual Studio 2022

Xamarin.Forms (Android Only)

Target API Level: Pie 9.0 (android-28)

Android NDK: R23C

Target: Nokia 8.1 - Android 11

There is code in GitHub that is similar to what I want to do. I compared the project configuration and code of this repo with my project but didn't find where I went wrong.


问:
Adding Email Authentication to a Login Service that uses React and Firebase
I currently have a file for authentication called AuthContext.js and a seperate file called Login.js for my login page. Firebase is only imported into the AuthContext file and it currently works, the method appears as follows

```<code>function signup(email, password) {
    return auth.createUserWithEmailAndPassword(email, password);
}
</code>```

And the method is called in the Login file inside of an async function.

```<code>async function handleSubmit(e) {
    e.preventDefault();

    if (passwordRef.current.value !== passwordConfirmRef.current.value) {
        return setError("Passwords do not match");
    }

    try {
        setError("");
        setLoading(true);
        await signup(emailRef.current.value, passwordRef.current.value);
        navigate("/");
    } catch (err) {
        setError("Failed to create an account");
    }
    setLoading(false);
}
</code>```

I am now attempting to integrate email authentication into the function. I would like to get it to where, if an account remains unverified for a elongated duration then it will delete the account, but I think that Is likely in the Firebase settings.

I found this article on geeksforgeeks that suggested calling the method in the following manner:

```<code>const signup = ()=>{
   auth.createUserWithEmailAndPassword(email , password)
   .then((userCredential)=>{
       // send verification mail.
     userCredential.user.sendEmailVerification();
     auth.signOut();
     alert("Email sent");
   })
   .catch(alert);
}
</code>```

However, when I attempted to return this function in the form

```<code>function signup(email, password) {
    return auth.createUserWithEmailAndPassword(email, password).then(
        (userCredentials) => {
            userCredentials.user.sendEmailVerification();
            auth.signOut();
            auth.alert("Please verify your email address before logging in.");
        }
    );
}
</code>```

It does not work properly, and I get error messages every time I try to sign up a new account. How do I properly implement this to where the promise returns properly and displays the correct message? Is there a way for me to link them to the /login page with an alert already on it that says "Please verify your email address before logging in."? Thanks in advance for any help!

Body:
I currently have a file for authentication called AuthContext.js and a seperate file called Login.js for my login page. Firebase is only imported into the AuthContext file and it currently works, the method appears as follows

function signup(email, password) {
    return auth.createUserWithEmailAndPassword(email, password);
}

And the method is called in the Login file inside of an async function.

async function handleSubmit(e) {
    e.preventDefault();

    if (passwordRef.current.value !== passwordConfirmRef.current.value) {
        return setError("Passwords do not match");
    }

    try {
        setError("");
        setLoading(true);
        await signup(emailRef.current.value, passwordRef.current.value);
        navigate("/");
    } catch (err) {
        setError("Failed to create an account");
    }
    setLoading(false);
}

I am now attempting to integrate email authentication into the function. I would like to get it to where, if an account remains unverified for a elongated duration then it will delete the account, but I think that Is likely in the Firebase settings.

I found this article on geeksforgeeks that suggested calling the method in the following manner:

const signup = ()=>{
   auth.createUserWithEmailAndPassword(email , password)
   .then((userCredential)=>{
       // send verification mail.
     userCredential.user.sendEmailVerification();
     auth.signOut();
     alert("Email sent");
   })
   .catch(alert);
}

However, when I attempted to return this function in the form

function signup(email, password) {
    return auth.createUserWithEmailAndPassword(email, password).then(
        (userCredentials) => {
            userCredentials.user.sendEmailVerification();
            auth.signOut();
            auth.alert("Please verify your email address before logging in.");
        }
    );
}

It does not work properly, and I get error messages every time I try to sign up a new account. How do I properly implement this to where the promise returns properly and displays the correct message? Is there a way for me to link them to the /login page with an alert already on it that says "Please verify your email address before logging in."? Thanks in advance for any help!


问:
How to change selectionSet from hook resolver in apollo
How can I use apollo to change selectionSet in field resolver through one resolver without using stitch and extend resolver?</p>


问:
Jest is not familiar with SubmitEvent, throws ReferenceError: SubmitEvent is not defined
I'm trying to create a unit test in StencilJS app for a submit event but it seems jest does not know what SubmitEvent is. I'm getting an error of ReferenceError: SubmitEvent is not defined. Anyone knows how to bypass this error, or how is it possible to mock this event so the form can emit this and the app can catch this event and run the relevant code?

```<code>  it('runs handleSubmit function on submit', async () => {
    const page = await newSpecPage({
      components: [Input],
      template: () => (
        <form id="form">
          <button type="submit" id="submit"></button>
          <my-input validator={validatorFunc}></my-input>
        </form>
      ),
    });

    // page.rootInstance is the reference to the component class and handleSubmit is the handler to the listener of the submit event
    const handleSubmitSpy = jest.spyOn(page.rootInstance, 'handleSubmit');
    const submit = page.body.querySelector('#submit') as HTMLButtonElement;
    const form = page.body.querySelector('#form') as HTMLFormElement;

    const e = new SubmitEvent('submit', { submitter: submit }); // throws ReferenceError: SubmitEvent is not defined
    await form.dispatchEvent(e);
    await page.waitForChanges();
    expect(handleSubmitSpy).toHaveBeenCalled();
  });
</code>```

The submit handler of the Stencil component:

```<code>  @Listen('submit', { target: 'document' })
  async handleSubmit() {
     ... do stuff related to submit event
  }
</code>```

Body:
I'm trying to create a unit test in StencilJS app for a submit event but it seems jest does not know what SubmitEvent is. I'm getting an error of ReferenceError: SubmitEvent is not defined. Anyone knows how to bypass this error, or how is it possible to mock this event so the form can emit this and the app can catch this event and run the relevant code?

  it('runs handleSubmit function on submit', async () => {
    const page = await newSpecPage({
      components: [Input],
      template: () => (
        <form id="form">
          <button type="submit" id="submit"></button>
          <my-input validator={validatorFunc}></my-input>
        </form>
      ),
    });

    // page.rootInstance is the reference to the component class and handleSubmit is the handler to the listener of the submit event
    const handleSubmitSpy = jest.spyOn(page.rootInstance, 'handleSubmit');
    const submit = page.body.querySelector('#submit') as HTMLButtonElement;
    const form = page.body.querySelector('#form') as HTMLFormElement;

    const e = new SubmitEvent('submit', { submitter: submit }); // throws ReferenceError: SubmitEvent is not defined
    await form.dispatchEvent(e);
    await page.waitForChanges();
    expect(handleSubmitSpy).toHaveBeenCalled();
  });

The submit handler of the Stencil component:

  @Listen('submit', { target: 'document' })
  async handleSubmit() {
     ... do stuff related to submit event
  }


问:
Why the (req, res, function() {...}) immediately after passport.authenticate('local') when registering a new user with passport-local-mongoose?
Following the The Complete 2023 Web Development Bootcamp-course by the App Brewery on Udemy, having progressed to lesson 386: Using Passport.js to Add Cookies and Sessions, I am wondering what the purpose is of (req, res, function() {...}) immediately after passport.authenticate('local') for registering a new user using passport-local-mongoose.

Source where the teacher has it from: https://mherman.org/blog/user-authentication-with-passport-dot-js/
(referenced in the documentation for passport-local-mongoose)

In context from the above link:

```<code>  app.post('/register', function(req, res) {
    Account.register(new Account({ username : req.body.username }), req.body.password, function(err, account) {
        if (err) {
            return res.render('register', { account : account });
        }

        passport.authenticate('local')(req, res, function () {
          res.redirect('/');
        });
    });
  });
</code>```

Why isn't it written as:

```<code>  ...
        passport.authenticate('local', function(req, res) {
          res.redirect('/');
        });
  ...
</code>```

with the callback included as an argument?

Trying approaches that adhere to what I've become familiar with thus far, found in the Passport.js documentation and the passport-local-mongoose documentation, the user gets registered, but the redirection to the secrets-page is not done, instead having the page's load-indicator run continuously without changing from the register-page.

The route for reference below.

```<code>app.route("/register").get(function (req, res) {
    res.render("register");
}).post(function (req, res) {
    User.register({username: req.body.username}, req.body.password, function (err, user) {
        if (err) {
            console.log(err);
            res.redirect("/register");
        }

        //WORKS: The App Brewery
        //Based on: https://mherman.org/blog/user-authentication-with-passport-dot-js/#add-registerjade, 2022-12-25
        passport.authenticate("local")(req, res, function () {
            res.redirect("/secrets");
        });

        //DOESN'T WORK: Passport documentation on authentication
        // passport.authenticate(
        //     "local",
        //     {failureRedirect: "/", failureMessage: true},
        //     function (req, res) {
        //         res.redirect("/secrets");
        //     });

        //DOESN'T WORK: passport-local-mongoose documentation
        // const authenticate = User.authenticate();
        // authenticate(req.body.username, req.body.password, function (err, result) {
        //     if (err) {
        //         console.log(err);
        //     } else {
        //         res.redirect("/secrets");
        //     }
        // });

    });
});
</code>```

Body:
Following the The Complete 2023 Web Development Bootcamp-course by the App Brewery on Udemy, having progressed to lesson 386: Using Passport.js to Add Cookies and Sessions, I am wondering what the purpose is of (req, res, function() {...}) immediately after passport.authenticate('local') for registering a new user using passport-local-mongoose.

Source where the teacher has it from: https://mherman.org/blog/user-authentication-with-passport-dot-js/
(referenced in the documentation for passport-local-mongoose)

In context from the above link:

  app.post('/register', function(req, res) {
    Account.register(new Account({ username : req.body.username }), req.body.password, function(err, account) {
        if (err) {
            return res.render('register', { account : account });
        }

        passport.authenticate('local')(req, res, function () {
          res.redirect('/');
        });
    });
  });

Why isn't it written as:

  ...
        passport.authenticate('local', function(req, res) {
          res.redirect('/');
        });
  ...

with the callback included as an argument?

Trying approaches that adhere to what I've become familiar with thus far, found in the Passport.js documentation and the passport-local-mongoose documentation, the user gets registered, but the redirection to the secrets-page is not done, instead having the page's load-indicator run continuously without changing from the register-page.

The route for reference below.

app.route("/register").get(function (req, res) {
    res.render("register");
}).post(function (req, res) {
    User.register({username: req.body.username}, req.body.password, function (err, user) {
        if (err) {
            console.log(err);
            res.redirect("/register");
        }

        //WORKS: The App Brewery
        //Based on: https://mherman.org/blog/user-authentication-with-passport-dot-js/#add-registerjade, 2022-12-25
        passport.authenticate("local")(req, res, function () {
            res.redirect("/secrets");
        });

        //DOESN'T WORK: Passport documentation on authentication
        // passport.authenticate(
        //     "local",
        //     {failureRedirect: "/", failureMessage: true},
        //     function (req, res) {
        //         res.redirect("/secrets");
        //     });

        //DOESN'T WORK: passport-local-mongoose documentation
        // const authenticate = User.authenticate();
        // authenticate(req.body.username, req.body.password, function (err, result) {
        //     if (err) {
        //         console.log(err);
        //     } else {
        //         res.redirect("/secrets");
        //     }
        // });

    });
});


问:
MSYS2 paths with \
I'm new to MSYS2 and have previously only used the Windows Command Prompt. Here I'm facing the problem, that a path copied from the Windows Explorer entered there with copy and paste can't be resolved. You must then manually  replace all the \ with / which is very tedious. Is there a better solution that saves a lot of time?</p>

Title: MSYS2 paths with \


问:
--base-href adds directory path instead of url path
I'm using gh page ng deploy --base-href=/some-app/, and inside the base in index.html I'm getting "c/program../some-app instead of the url, which prevents the GitHub pages from working correctly

How can I fix this?


问:
AWS EC2 using Wpguppy plugin for real time chat
I testing AWS EC2.
I am beginner.
I want to install wpguppy plugin for real time chat.
But wpguppy plugin need root access.
Hoo, i don't know how.
I need ubuntu,apache,mysql,php,phpmyadmin to install it.
Now i testing free at AWS EC2 free tier learning from youtube.
But it is not work for me.
it is too hard to learn.
So anyone can teach me how to do that.
this is the link of wpguppy plugin. It have free and premium.
https://wordpress.org/plugins/wpguppy-lite/
https://codecanyon.net/item/wpguppy-a-live-chat-plugin-for-wordpress/34619534
https://prnt.sc/Et5MBUXAFv65

And I link also youtube link how to do that.
They upload a video how to do that.
https://www.youtube.com/watch?v=oWA6RjOGcpY&t=3s
But i don't know how to do that start to end using AWS EC2,RDS,ubuntu,apache,mysql,php and phpmyadmin.
Please help me.

I tried and learn AWS EC2, RDS,ubuntu, apache,mysql,php,phpmyadmin from youtube.

Can you help me how to do that.


问:
Is it possible to return div element in React Custom hook?
I have an array of objects inside custom hook. I want to return JSX inside one of these objects, but I get Cannot find name 'div'.ts(2304) error. Is there any solution for this problem?

```<code>const columns: IColumn[] = useMemo(
    () => [
      {
        key: 'column2',
        onRender: (item: IDocumentItem) => {
          return <div style={{ fontWeight: 'normal' }}>{item.type}</div>;
        },
        data: 'string',
      },
...

    ],
    [setFieldName, setIndex, setItemSort]
  );
</code>```

Body:
I have an array of objects inside custom hook. I want to return JSX inside one of these objects, but I get Cannot find name 'div'.ts(2304) error. Is there any solution for this problem?

const columns: IColumn[] = useMemo(
    () => [
      {
        key: 'column2',
        onRender: (item: IDocumentItem) => {
          return
{item.type}
;
        },
        data: 'string',
      },
...

    ],
    [setFieldName, setIndex, setItemSort]
  );


问:
Python Model Deployment: Running locally on a users machine vs cloud server backend?
Im building a modelling tool and I am not sure how best to design a solution for rollout to a few hundred people, perhaps for a global team. The model is built in python, and depending on the specific modelling situation can take 30 seconds to run or a few hours for one projection.

Im looking to roll this out to the user team and am not sure of the best solution. Some users have slow machines and id like the flexibility of running the models each time a user requires on a cloud VM, but im not sure how best to go about this and handle situations where many users may queue large batched projections all at once.

Is deployment to cloud the best solution here? Can I on demand scale the compute to handle load spikes? Is spinning up new python processes the best approach? Or should I stick with local computation.

Would build some kind of API for cloud deployment.


Title: PySpark: How can I concatenate two different RDD with the same number of rows

Body:
I'm trying to concat 2 different dataframes but I was not able to do that at this moment.
I would like to do the following.

user_ids

+-------+
|user_id|
+-------+
|  96885|
|  58620|
|  56483|
|  65282|
|  61336|
|  63337|
|  56484|
|  36890|
|  57420|
|  54434|
| 101512|
|  58622|
|  67561|
|  55617|
|  58623|
|  54435|
| 230572|
|  58624|
|  30034|
|  55639|
+-------+

prediction

+----------+
|prediction|
+----------+
|         1|
|         1|
|         0|
|         0|
|         1|
|         0|
|         1|
|         1|
|         1|
|         1|
|         1|
|         1|
|         0|
|         0|
|         1|
|         1|
|         0|
|         1|
|         1|
|         1|
+----------+

What I would like to have is another RDD as following.

+-------++----------+
|user_id||prediction|
+-------++----------+
|  96885||         1|
|  58620||         1|
|  56483||         0|
|  65282||         0|
|  61336||         1|
|  63337||         0|
|  56484||         1|
|  36890||         1|
|  57420||         1|
|  54434||         1|
| 101512||         1|
|  58622||         1|
|  67561||         0|
|  55617||         0|
|  58623||         1|
|  54435||         1|
| 230572||         0|
|  58624||         1|
|  30034||         1|
|  55639||         1|
+-------++----------+

Using pandas I could do something like

user_ids['prediction'] = prediction.

But I need to do it in a distributed way using pyspark. How can I do that?


问:
How to send token by contract with python?
I want to send trc20 token by tronapi lib but my code doesn't work.

I don't have any error but it doesn't work :(

```<code>from tronapi import Tron
from tronapi import HttpProvider

full_node = HttpProvider('https://nile.trongrid.io')
solidity_node = HttpProvider('https://nile.trongrid.io')
event_server = HttpProvider('https://nile.trongrid.io')

tron = Tron(full_node=full_node,
            solidity_node=solidity_node,
            event_server=event_server)

tron.private_key = '59d4b72df50290d7f78e2c16fc27758d6e235f3959f2212f2497fc55da33e888'
tron.default_address = 'TRNDt7bjFoTq7p52iw5u2BLNhsff1ux7Fc'
Towallet = 'TFgmQmr31HxkiZ67KBjwZPseT1G5t4tWdT'
Amount = 11
usernum = 20
Tcontract='TXLAQ63Xg1NAzckPwKHvzw7CSEmLMEqcdj'
send = tron.transaction_builder.trigger_smart_contract(
    contract_address=tron.address.to_hex(Tcontract),
    function_selector='transfer(address, uint256)',
    fee_limit=30000000,
    call_value=0,
    parameters=[
        {'type': 'address', 'value': tron.address.to_hex(Towallet)},
        {'type': 'int256', 'value': int(float(Amount)*pow(10,6))}
    ]
)
print(send)
</code>```

the result:

```<code>{'result': {'result': True}, 'transaction': {'visible': False, 'txID': '2379e197670790c00c30b170e42c61e7f6040779e055790f8f41627170849ee2', 'raw_data': {'contract': [{'parameter': {'value': {'data': 'a9059cbb0000000000000000000000003eb4bca6f3d6791a6e044af18ae0889ea82307210000000000000000000000000000000000000000000000000000000000a7d8c0', 'owner_address': '41a8e4304def45a15814272a8738225b9edc42081b', 'contract_address': '41ea51342dabbb928ae1e576bd39eff8aaf070a8c6'}, 'type_url': 'type.googleapis.com/protocol.TriggerSmartContract'}, 'type': 'TriggerSmartContract'}], 'ref_block_bytes': 'a7ac', 'ref_block_hash': '50d0abab544c57c0', 'expiration': 1671983553000, 'fee_limit': 30000000, 'timestamp': 1671983495561}, 'raw_data_hex': '0a02a7ac220850d0abab544c57c040e8b3f1cfd4305aae01081f12a9010a31747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e54726967676572536d617274436f6e747261637412740a1541a8e4304def45a15814272a8738225b9edc42081b121541ea51342dabbb928ae1e576bd39eff8aaf070a8c62244a9059cbb0000000000000000000000003eb4bca6f3d6791a6e044af18ae0889ea82307210000000000000000000000000000000000000000000000000000000000a7d8c07089f3edcfd43090018087a70e'}}
</code>```

Body:
I want to send trc20 token by tronapi lib but my code doesn't work.

I don't have any error but it doesn't work :(

from tronapi import Tron
from tronapi import HttpProvider

full_node = HttpProvider('https://nile.trongrid.io')
solidity_node = HttpProvider('https://nile.trongrid.io')
event_server = HttpProvider('https://nile.trongrid.io')

tron = Tron(full_node=full_node,
            solidity_node=solidity_node,
            event_server=event_server)

tron.private_key = '59d4b72df50290d7f78e2c16fc27758d6e235f3959f2212f2497fc55da33e888'
tron.default_address = 'TRNDt7bjFoTq7p52iw5u2BLNhsff1ux7Fc'
Towallet = 'TFgmQmr31HxkiZ67KBjwZPseT1G5t4tWdT'
Amount = 11
usernum = 20
Tcontract='TXLAQ63Xg1NAzckPwKHvzw7CSEmLMEqcdj'
send = tron.transaction_builder.trigger_smart_contract(
    contract_address=tron.address.to_hex(Tcontract),
    function_selector='transfer(address, uint256)',
    fee_limit=30000000,
    call_value=0,
    parameters=[
        {'type': 'address', 'value': tron.address.to_hex(Towallet)},
        {'type': 'int256', 'value': int(float(Amount)*pow(10,6))}
    ]
)
print(send)

the result:

{'result': {'result': True}, 'transaction': {'visible': False, 'txID': '2379e197670790c00c30b170e42c61e7f6040779e055790f8f41627170849ee2', 'raw_data': {'contract': [{'parameter': {'value': {'data': 'a9059cbb0000000000000000000000003eb4bca6f3d6791a6e044af18ae0889ea82307210000000000000000000000000000000000000000000000000000000000a7d8c0', 'owner_address': '41a8e4304def45a15814272a8738225b9edc42081b', 'contract_address': '41ea51342dabbb928ae1e576bd39eff8aaf070a8c6'}, 'type_url': 'type.googleapis.com/protocol.TriggerSmartContract'}, 'type': 'TriggerSmartContract'}], 'ref_block_bytes': 'a7ac', 'ref_block_hash': '50d0abab544c57c0', 'expiration': 1671983553000, 'fee_limit': 30000000, 'timestamp': 1671983495561}, 'raw_data_hex': '0a02a7ac220850d0abab544c57c040e8b3f1cfd4305aae01081f12a9010a31747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e54726967676572536d617274436f6e747261637412740a1541a8e4304def45a15814272a8738225b9edc42081b121541ea51342dabbb928ae1e576bd39eff8aaf070a8c62244a9059cbb0000000000000000000000003eb4bca6f3d6791a6e044af18ae0889ea82307210000000000000000000000000000000000000000000000000000000000a7d8c07089f3edcfd43090018087a70e'}}


问:
How to fix typescript error for 'possibly null' prop in child component, which will render only when prop is defined?
Suppose the following:

```<code>type TDictionary = {
  MAIN_TITLE: string;
  COMPONENT_A_TITLE: string;
  COMPONENT_B_TITLE: string;
} | null;

const ComponentA: React.FC<{ dictionary: TDictionary }> = React.memo(
  ({ dictionary }) => {
    return <div>{dictionary.COMPONENT_A_TITLE}</div>;
  }
);

const ComponentB: React.FC<{ dictionary: TDictionary }> = React.memo(
  ({ dictionary }) => {
    return <div>{dictionary.COMPONENT_B_TITLE}</div>;
  }
);

const App = React.memo(() => {
  const [dictionary, setDictionary] = React.useState<TDictionary>(null);

  React.useEffect(() => {
    setTimeout(() => {
      setDictionary({
        MAIN_TITLE: "Hello world",
        COMPONENT_A_TITLE: "Hello from ComponentA",
        COMPONENT_B_TITLE: "Hello from ComponentB"
      });
    }, 1000);
  }, []);

  if (!dictionary) return <div>loading...</div>;

  return (
    <div className="App">
      <h1>{dictionary.MAIN_TITLE}</h1>
      <ComponentA dictionary={dictionary} />
      <ComponentB dictionary={dictionary} />
    </div>
  );
});
</code>```

Typescript keeps thinking that dictionary could be null at some point in the code, but clearly that's impossible. How can I fix this? The only way that I can think of is changing the interfaces for ComponentA and ComponentB to Exclude<TDictionary, null>, but that seems like an extra step?

Body:
Suppose the following:

type TDictionary = {
  MAIN_TITLE: string;
  COMPONENT_A_TITLE: string;
  COMPONENT_B_TITLE: string;
} | null;

const ComponentA: React.FC<{ dictionary: TDictionary }> = React.memo(
  ({ dictionary }) => {
    return
{dictionary.COMPONENT_A_TITLE}
;
  }
);

const ComponentB: React.FC<{ dictionary: TDictionary }> = React.memo(
  ({ dictionary }) => {
    return
{dictionary.COMPONENT_B_TITLE}
;
  }
);

const App = React.memo(() => {
  const [dictionary, setDictionary] = React.useState<TDictionary>(null);

  React.useEffect(() => {
    setTimeout(() => {
      setDictionary({
        MAIN_TITLE: "Hello world",
        COMPONENT_A_TITLE: "Hello from ComponentA",
        COMPONENT_B_TITLE: "Hello from ComponentB"
      });
    }, 1000);
  }, []);

  if (!dictionary) return
loading...
;

  return (

{dictionary.MAIN_TITLE}

      <ComponentA dictionary={dictionary} />
      <ComponentB dictionary={dictionary} />

  );
});

Typescript keeps thinking that dictionary could be null at some point in the code, but clearly that's impossible. How can I fix this? The only way that I can think of is changing the interfaces for ComponentA and ComponentB to Exclude<TDictionary, null>, but that seems like an extra step?


问:
ModuleNotFoundError: No module named 'seaborn' in spdyer
I recently installed spyder on my macbook (M1). I am getting module not found error when I tried to load seaborn.
Pl note

I am able to load the seaborn in jupyter notebook

Whey I change the python interpreter to the the one jupyter notebook is using (i.e. miniforge), I get following error

/Users/akbarboghani/miniforge3/bin/python: Error while finding module specification for 'spyder_kernels.console' (ModuleNotFoundError: No module named 'spyder_kernels')

Is there any setting I have missed? How do I resolve this

I tried changing preferences and restarted the spyder application. Checked for solution, did not find any.