问:
Getting a RuntimeError while running chatbot using Pytorch and NLTK library (python engineer tutorial code)
I have written this line "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')" still getting the following errror. I have provided my all code that i written till now please with this.

RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking argument for argument mat1 in method wrapper_addmm)

Train.py File

```<code>import json
from nltk_utils import tokenize, stem, bag_of_words
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from model import NeuralNet

with open('intents.json', 'r') as f:
    intents = json.load(f)

all_words = []
tags = []
xy = []

for intent in intents['intents']:
    tag = intent['tag']
    tags.append(tag)
    for pattern in intent['patterns']:
        w = tokenize(pattern)
        all_words.extend(w)
        xy.append((w, tag))

ignore_words = ['?', '!', '.', ',']
all_words = [stem(w) for w in all_words if w not in ignore_words]
all_words = sorted(set(all_words))
tags = sorted(set(tags))

x_train = []
y_train = []

for (pattern_sentence, tag) in xy:
    bag = bag_of_words(pattern_sentence, all_words)
    x_train.append(bag)

    label = tags.index(tag)
    y_train.append(label) # CrossEntropyLoss

x_train = np.array(x_train)
y_train = np.array(y_train)

class ChatDataset(Dataset):
    def __init__(self):
        self.n_samples = len(x_train)
        self.x_data = x_train
        self.y_data = y_train

    # dataset[idx]
    def __getitem__(self, index):
        return self.x_data[index], self.y_data[index]

    def __len__(self):
        return self.n_samples

batch_size = 8
hidden_size = 8
output_size = len(tags)
input_size = len(x_train[0])
learning_rate = 0.001
num_epochs = 1000

print(input_size, len(all_words))
print(output_size, tags)

dataset = ChatDataset()
train_loader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=True)

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

model = NeuralNet(input_size, hidden_size, output_size).to(device)

criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

for epoch in range(num_epochs):
    for(words, labels) in train_loader:
        words =  words.to(device)
        labels = labels.type(torch.LongTensor) # <----- Here (Casting)
        labels = labels.to(device)

        # forward
        outputs = model(words)
        loss = criterion(outputs, labels)

        # backward and optimizer step
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

    if (epoch + 1) % 100 == 0:
        print(f'epoch {epoch + 1}/{num_epochs}, loss={loss.item():.4f}')

print(f'final loss: {loss.item():.4f}')

data = {
    "model_state" : model.state_dict(),
    "input_size" : input_size,
    "output_size" : output_size,
    "hidden_size" : hidden_size,
    "all_words" : all_words,
    "tags" : tags,
}

FILE = "data.pth"
torch.save(data, FILE)

print(f'training complete , file saved to {FILE}')

</code>```

chat.py file

```<code>import random
import json
import torch
from model import NeuralNet
from nltk_utils import bag_of_words, tokenize

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# device = torch.device('cuda')

with open('intents.json', 'r') as f:
    intents = json.load(f)

FILE = 'data.pth'
data = torch.load(FILE)
input_size = data["input_size"]
hidden_size = data["hidden_size"]
output_size = data["output_size"]
all_words = data["all_words"]
tags = data["tags"]
model_state = data["model_state"]

model = NeuralNet(input_size, hidden_size, output_size).to(device)
model.load_state_dict(model_state)
model.eval()

bot_name = 'Sam'
print("Let's chat: type 'quit' to exit")
while True:
    sentence = input('You: ')
    if sentence == "Quit":
        break

    sentence = tokenize(sentence)
    X = bag_of_words(sentence, all_words)
    X = X.reshape(1, X.shape[0])
    X = torch.from_numpy(X)

    output = model(X)
    _, predicted = torch.max(output, dim=1)
    tag = tags[predicted.item()]

    probs = torch.softmax(output, dim=1)
    prob = probs[0][predicted.item()]

    if prob.item() > 0.75:
        for intent in intents["intents"]:
            if tag == intent["tag"]:
                print(f"{bot_name}: {random.choice(intent['responses'])}")
    else:
        print(f"{bot_name}: I do not understand...:(")

</code>```

After running the chat.py. while chatbot is trying to send their response then it giving the runtime error.
I should get the response from chatbot. but getting the following error

Error Image

Body:
I have written this line "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')" still getting the following errror. I have provided my all code that i written till now please with this.

RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking argument for argument mat1 in method wrapper_addmm)

Train.py File

import json
from nltk_utils import tokenize, stem, bag_of_words
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from model import NeuralNet

with open('intents.json', 'r') as f:
    intents = json.load(f)

all_words = []
tags = []
xy = []

for intent in intents['intents']:
    tag = intent['tag']
    tags.append(tag)
    for pattern in intent['patterns']:
        w = tokenize(pattern)
        all_words.extend(w)
        xy.append((w, tag))

ignore_words = ['?', '!', '.', ',']
all_words = [stem(w) for w in all_words if w not in ignore_words]
all_words = sorted(set(all_words))
tags = sorted(set(tags))

x_train = []
y_train = []

for (pattern_sentence, tag) in xy:
    bag = bag_of_words(pattern_sentence, all_words)
    x_train.append(bag)

    label = tags.index(tag)
    y_train.append(label) # CrossEntropyLoss

x_train = np.array(x_train)
y_train = np.array(y_train)

class ChatDataset(Dataset):
    def __init__(self):
        self.n_samples = len(x_train)
        self.x_data = x_train
        self.y_data = y_train

    # dataset[idx]
    def __getitem__(self, index):
        return self.x_data[index], self.y_data[index]

    def __len__(self):
        return self.n_samples

batch_size = 8
hidden_size = 8
output_size = len(tags)
input_size = len(x_train[0])
learning_rate = 0.001
num_epochs = 1000

print(input_size, len(all_words))
print(output_size, tags)

dataset = ChatDataset()
train_loader = DataLoader(dataset=dataset, batch_size=batch_size, shuffle=True)

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

model = NeuralNet(input_size, hidden_size, output_size).to(device)

criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

for epoch in range(num_epochs):
    for(words, labels) in train_loader:
        words =  words.to(device)
        labels = labels.type(torch.LongTensor) # <----- Here (Casting)
        labels = labels.to(device)

        # forward
        outputs = model(words)
        loss = criterion(outputs, labels)

        # backward and optimizer step
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

    if (epoch + 1) % 100 == 0:
        print(f'epoch {epoch + 1}/{num_epochs}, loss={loss.item():.4f}')

print(f'final loss: {loss.item():.4f}')

data = {
    "model_state" : model.state_dict(),
    "input_size" : input_size,
    "output_size" : output_size,
    "hidden_size" : hidden_size,
    "all_words" : all_words,
    "tags" : tags,
}

FILE = "data.pth"
torch.save(data, FILE)

print(f'training complete , file saved to {FILE}')

chat.py file

import random
import json
import torch
from model import NeuralNet
from nltk_utils import bag_of_words, tokenize

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# device = torch.device('cuda')

with open('intents.json', 'r') as f:
    intents = json.load(f)

FILE = 'data.pth'
data = torch.load(FILE)
input_size = data["input_size"]
hidden_size = data["hidden_size"]
output_size = data["output_size"]
all_words = data["all_words"]
tags = data["tags"]
model_state = data["model_state"]

model = NeuralNet(input_size, hidden_size, output_size).to(device)
model.load_state_dict(model_state)
model.eval()

bot_name = 'Sam'
print("Let's chat: type 'quit' to exit")
while True:
    sentence = input('You: ')
    if sentence == "Quit":
        break

    sentence = tokenize(sentence)
    X = bag_of_words(sentence, all_words)
    X = X.reshape(1, X.shape[0])
    X = torch.from_numpy(X)

    output = model(X)
    _, predicted = torch.max(output, dim=1)
    tag = tags[predicted.item()]

    probs = torch.softmax(output, dim=1)
    prob = probs[0][predicted.item()]

    if prob.item() > 0.75:
        for intent in intents["intents"]:
            if tag == intent["tag"]:
                print(f"{bot_name}: {random.choice(intent['responses'])}")
    else:
        print(f"{bot_name}: I do not understand...:(")

After running the chat.py. while chatbot is trying to send their response then it giving the runtime error.
I should get the response from chatbot. but getting the following error

Error Image


来源: stackexchange

问:
How to use a django template variable in django-crispy bootstrap AppendedText or PrependedText?
I saw that a similar question was asked 10 years ago about buttons and that it was resolved. I was naive enough to think that maybe it was possible for other fields ^^
Have I missed something ?

As said in the Title, I'm trying to use a django template variable {{ tetra }}
in a Layout Fieldset AppendedText or PrependedText value, like this

```<code>class AddObjectForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Fieldset(
                'Some Text as Legend',
                AppendedText('userref', {{tetra}} ),
</code>```

but it won't work :-(
no more with

```<code>                AppendedText('userref', '{{tetra}}' ),
</code>```

or

```<code>                AppendedText('userref', '{{tetra|safe}}' ),
</code>```

I also tried with HTML tag like :

```<code>                PrependedText('userref', HTML("""{{tetra}}""") ),
</code>```

but in this case I also obtain : <crispy_forms.layout.HTML object at 0x7fb1997f8c70>

Can anyone enlighten me, direct me or confirm that this is not possible?

ContentLicense: CC BY-SA 4.0

Body:
I saw that a similar question was asked 10 years ago about buttons and that it was resolved. I was naive enough to think that maybe it was possible for other fields ^^
Have I missed something ?

As said in the Title, I'm trying to use a django template variable {{ tetra }}
in a Layout Fieldset AppendedText or PrependedText value, like this

class AddObjectForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Fieldset(
                'Some Text as Legend',
                AppendedText('userref', {{tetra}} ),

but it won't work :-(
no more with

                AppendedText('userref', '{{tetra}}' ),

or

                AppendedText('userref', '{{tetra|safe}}' ),

I also tried with HTML tag like :

                PrependedText('userref', HTML("""{{tetra}}""") ),

but in this case I also obtain : <crispy_forms.layout.HTML object at 0x7fb1997f8c70>

Can anyone enlighten me, direct me or confirm that this is not possible?


问:
Why does 'whereis python' give another location of python than which 'which python' when using python virtual environment?
I am using Python3.9 and MacOS.

I created a virtual environment using python3 -m venv venv command.

Inside the virtual environemt I want to check which python binary I am using.

I tried to use which and whereis bash commands and I was surprised because they give different results.

which python gives me the correct output: {path_to_venv}/bin/python.

whereis python gives me the system python instead: /usr/bin/python.

Why is it like that?


问:
How to detect StatusbarNotification large icon possition?
I have the following code to get the large icon of a statusbarNotification (sbn):

```<code>val extras = sbn.notification.extras
val extraPrsnIcn = if (extras.containsKey(Notification.EXTRA_LARGE_ICON)) extras.get(Notification.EXTRA_LARGE_ICON) else null
</code>```

It works great, but sometimes this image shown on the left of the statusbarNotification itself such as a Contact icon, or on the right like a weather icon.
How can I check this position (right or left)?

Body:
I have the following code to get the large icon of a statusbarNotification (sbn):

val extras = sbn.notification.extras
val extraPrsnIcn = if (extras.containsKey(Notification.EXTRA_LARGE_ICON)) extras.get(Notification.EXTRA_LARGE_ICON) else null

It works great, but sometimes this image shown on the left of the statusbarNotification itself such as a Contact icon, or on the right like a weather icon.
How can I check this position (right or left)?


问:
Code: Unable to access opcode bytes at RIP 0x
While working on kernel modules, I have been facing this issue when passing an array from kernel space to user space.

I am using IOCTL call in userspace to get the array from the kernel space

ret_val = ioctl(filedes, IOCTL_PRINT, localarray);
```
<p>And copy_to_user to pass it from kernel to user space.</p>
<pre class="lang-c prettyprint-override"><code>ret = copy_to_user((int *)ioctl_param, kernel_array, 15 * sizeof(int));
</code>```

This is my error

[  461.909674] Data value in index 0 : 21
[  461.909678] Data value in index 1 : 20
[  461.909678] Data value in index 2 : 19
[  461.909679] Data value in index 3 : 18
[  461.909680] Data value in index 4 : 17
[  461.909681] Data value in index 5 : 16
[  461.909681] Data value in index 6 : 15
[  461.909682] Data value in index 7 : 14
[  461.909683] Data value in index 8 : 13
[  461.909683] Data value in index 9 : 12
[  461.909684] Data value in index 10 : 11
[  461.909737] Data value in index 11 : 10
[  461.909738] Data value in index 12 : 9
[  461.909739] Data value in index 13 : 8
[  461.909740] Data value in index 14 : 7
[  461.910279] io[1799]: segfault at c0000000d ip 0000000c0000000d sp 00007fffaa57cd40 error 14 in         io[556f58436000+1000]
[  461.910288] Code: Unable to access opcode bytes at RIP 0xbffffffe3.
```

When I run it I could get the Kernel log but I cannot pass my array in the userspace. Is there a problem in pointer dereferencing?

Body:
While working on kernel modules, I have been facing this issue when passing an array from kernel space to user space.

I am using IOCTL call in userspace to get the array from the kernel space

ret_val = ioctl(filedes, IOCTL_PRINT, localarray);

And copy_to_user to pass it from kernel to user space.

ret = copy_to_user((int *)ioctl_param, kernel_array, 15 * sizeof(int));

This is my error

[  461.909674] Data value in index 0 : 21
[  461.909678] Data value in index 1 : 20
[  461.909678] Data value in index 2 : 19
[  461.909679] Data value in index 3 : 18
[  461.909680] Data value in index 4 : 17
[  461.909681] Data value in index 5 : 16
[  461.909681] Data value in index 6 : 15
[  461.909682] Data value in index 7 : 14
[  461.909683] Data value in index 8 : 13
[  461.909683] Data value in index 9 : 12
[  461.909684] Data value in index 10 : 11
[  461.909737] Data value in index 11 : 10
[  461.909738] Data value in index 12 : 9
[  461.909739] Data value in index 13 : 8
[  461.909740] Data value in index 14 : 7
[  461.910279] io[1799]: segfault at c0000000d ip 0000000c0000000d sp 00007fffaa57cd40 error 14 in         io[556f58436000+1000]
[  461.910288] Code: Unable to access opcode bytes at RIP 0xbffffffe3.

When I run it I could get the Kernel log but I cannot pass my array in the userspace. Is there a problem in pointer dereferencing?


问:
Dash add element to dropdown options on callback
So, I tried to to add options to a dcc.Dropdown in Dash on callback but it doesn't update the list. Here is my code :

List of options in dropDown :

```<code>l_parameters=[{"label_name":"Loth","hostname":"loth.telecomste.net","port":"22111","username":"grudu","password":"111-TgBT-2479"},
{"label_name":"Anna","hostname":"anna.telecomste.net","port":"22112","username":"grudu","password":"112-TgBT-5491"}]
</code>```

Html dropdown :

```<code>dcc.Dropdown(
                            id="metric-select-dropdown",
                            options=list(
                                {"label": param["label_name"], "value": param["label_name"]} for param in l_parameters[:]
                            ),
                            value=None,
                        ),
</code>```

Callback of dropdown trying to update options :

```<code>@app.callback(
output=[
        Output("metric-select-dropdown","options")
        ],
inputs=[Input("value-setter-set-btn", "n_clicks")

        ],
state=[
    State("metric-select-dropdown", "value"),
    State("value-setter-store", "data"),
    State("ud_nm_input", "value"),
    State("ud_usl_input", "value"),
    State("ud_lsl_input", "value"),
    State("ud_ucl_input", "value"),
    State("ud_lcl_input", "value"),
],)def set_value_setter_store(n_clicks, param, data,nm, usl, lsl, ucl, lcl):
if n_clicks is not None:
    usl1 = usl
    lsl1 = lsl
    ucl1 = ucl
    lcl1 = lcl

    l_parameters.append({"label_name":nm if nm is not None else "","hostname":usl1 if usl1 is not None else ""
    ,"port":lsl1 if lsl1 is not None else "","username":ucl1 if ucl1 is not None else ""
    ,"password":lcl1 if lcl1 is not None else ""})
    options=list({"label": param["label_name"], "value": param["label_name"]} for param in l_parameters[:])

    return options
</code>```

The UI:

The error message i got:

Body:
So, I tried to to add options to a dcc.Dropdown in Dash on callback but it doesn't update the list. Here is my code :

List of options in dropDown :

l_parameters=[{"label_name":"Loth","hostname":"loth.telecomste.net","port":"22111","username":"grudu","password":"111-TgBT-2479"},
{"label_name":"Anna","hostname":"anna.telecomste.net","port":"22112","username":"grudu","password":"112-TgBT-5491"}]

Html dropdown :

dcc.Dropdown(
                            id="metric-select-dropdown",
                            options=list(
                                {"label": param["label_name"], "value": param["label_name"]} for param in l_parameters[:]
                            ),
                            value=None,
                        ),

Callback of dropdown trying to update options :

@app.callback(
output=[
        Output("metric-select-dropdown","options")
        ],
inputs=[Input("value-setter-set-btn", "n_clicks")

        ],
state=[
    State("metric-select-dropdown", "value"),
    State("value-setter-store", "data"),
    State("ud_nm_input", "value"),
    State("ud_usl_input", "value"),
    State("ud_lsl_input", "value"),
    State("ud_ucl_input", "value"),
    State("ud_lcl_input", "value"),
],)def set_value_setter_store(n_clicks, param, data,nm, usl, lsl, ucl, lcl):
if n_clicks is not None:
    usl1 = usl
    lsl1 = lsl
    ucl1 = ucl
    lcl1 = lcl

    l_parameters.append({"label_name":nm if nm is not None else "","hostname":usl1 if usl1 is not None else ""
    ,"port":lsl1 if lsl1 is not None else "","username":ucl1 if ucl1 is not None else ""
    ,"password":lcl1 if lcl1 is not None else ""})
    options=list({"label": param["label_name"], "value": param["label_name"]} for param in l_parameters[:])

    return options

The UI:

The error message i got:


问:
During call iPhone alarm rings and call audio disconnected (voip call)
Steps are as-

set an alarm in your iPhone for example lets take 8:00 AM

suppose you call user B at 7:58AM

during your ongoing call with user B Alarm will rang up at 8:00AM till the alarm is ringing you can't hear User B and User B can't hear.

Expected result:-  During alarm both user will hear each others


问:
How the best use Multilanguage in views
I have a table with translated string. There are value for every language and languageId own rows.

I haven't problem with procedure or function because I can use parameter @LanguageId.

But I have a problem with views!

For example:

```<code>SELECT
  a.ID,
b.Text as TypeText,
b.TranslateId as TypeTranslateId,
c.Text as CategoryText,
c.TranslateId CategoryTranslateId,
d.Text as SourceText,
d.TranslateId as SourceTranslateId
FROM base a
LEFT JOIN enumB b a.TypeId = b.Id
LEFT JOIN enumC c a.CategoryId = c.Id
LEFT JOIN enumD d a.SourceId = d.Id
</code>```

I Can join all languages but I'm not sure this is good way.

If I refined each language in the view, the rows in the output would multiply according to the number of language sets.

If I pull only the key, it will then be hard to perform in the application condition on the like.

Title: How the best use Multilanguage in views

Body:
I have a table with translated string. There are value for every language and languageId own rows.

I haven't problem with procedure or function because I can use parameter @LanguageId.

But I have a problem with views!

For example:

SELECT
  a.ID,
b.Text as TypeText,
b.TranslateId as TypeTranslateId,
c.Text as CategoryText,
c.TranslateId CategoryTranslateId,
d.Text as SourceText,
d.TranslateId as SourceTranslateId
FROM base a
LEFT JOIN enumB b a.TypeId = b.Id
LEFT JOIN enumC c a.CategoryId = c.Id
LEFT JOIN enumD d a.SourceId = d.Id

I Can join all languages but I'm not sure this is good way.

If I refined each language in the view, the rows in the output would multiply according to the number of language sets.

If I pull only the key, it will then be hard to perform in the application condition on the like.


问:
Implementing IAP for a WebApp (pwa) on ios/Apple
I am having a hard time finding an answer whether it is possible to implement in-app-purchases for a web-based application on ios.

Apple's guidelines, similar to Google's pretty much say, "If you publish your app on our store, and offer the purchase of digital goods, you need to use our IAP implementation".

So my simple question is: HOW or can I implement IAP for a non-native but web based app for IOS, or is it just simply not possible?

For the Play Store there seems to be no issue, I found this explaining exactly how to iplement Play Billing.

Everything else I can find on this topic, is either not specific to Apple or just simply ignored (which I hope won't happen to my question ;P)

If there is no possible option, what alternatives are there? Can I alternatively to a PWA, maybe use something like capacitor to access the native payment API on ios?

Edit:
Capacitor definetly seems to be an option, but still, I am curious about PWA support on Apple's side.


问:
"Failed during: git fetch --force origin refs/heads/master:refs/remotes/origin/master "
while installing homebrew this error comes after 60% download..

```<code> * [new tag]             3.6.5                   -> 3.6.5
 * [new tag]             3.6.6                   -> 3.6.6
 * [new tag]             3.6.7                   -> 3.6.7
 * [new tag]             3.6.8                   -> 3.6.8
 * [new tag]             3.6.9                   -> 3.6.9
HEAD is now at 106af0355 Merge pull request #14337 from Red54/patch-2
==> Tapping homebrew/core
remote: Enumerating objects: 1391130, done.
remote: Counting objects: 100% (411/411), done.
remote: Compressing objects: 100% (218/218), done.
error: RPC failed; curl 56 GnuTLS recv error (-9): Error decoding the received TLS packet.
error: 4802 bytes of body are still expected
fetch-pack: unexpected disconnect while reading sideband packet
fatal: early EOF
fatal: fetch-pack: invalid index-pack output
Failed during: git fetch --force origin refs/heads/master:refs/remotes/origin/master
</code>```

How to fix this error??

Body:
while installing homebrew this error comes after 60% download..

 * [new tag]             3.6.5                   -> 3.6.5
 * [new tag]             3.6.6                   -> 3.6.6
 * [new tag]             3.6.7                   -> 3.6.7
 * [new tag]             3.6.8                   -> 3.6.8
 * [new tag]             3.6.9                   -> 3.6.9
HEAD is now at 106af0355 Merge pull request #14337 from Red54/patch-2
==> Tapping homebrew/core
remote: Enumerating objects: 1391130, done.
remote: Counting objects: 100% (411/411), done.
remote: Compressing objects: 100% (218/218), done.
error: RPC failed; curl 56 GnuTLS recv error (-9): Error decoding the received TLS packet.
error: 4802 bytes of body are still expected
fetch-pack: unexpected disconnect while reading sideband packet
fatal: early EOF
fatal: fetch-pack: invalid index-pack output
Failed during: git fetch --force origin refs/heads/master:refs/remotes/origin/master

How to fix this error??


问:
Querying loki logs using python
I am using the following script to query logs from loki which is running on some vm.I want to get the logs on multiple boxes and do some operation on them. so i am using loki as a source to get all the logs collectively.

```<code>import requests
import time
import requests
import urllib3
import ssl
import urllib.parse

class CustomHttpAdapter (requests.adapters.HTTPAdapter):
    # "Transport adapter" that allows us to use custom ssl_context.

    def __init__(self, ssl_context=None, **kwargs):
        self.ssl_context = ssl_context
        super().__init__(**kwargs)

    def init_poolmanager(self, connections, maxsize, block=False):
        self.poolmanager = urllib3.poolmanager.PoolManager(
            num_pools=connections, maxsize=maxsize,
            block=block, ssl_context=self.ssl_context)

def get_legacy_session():
    ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
    ctx.options |= 0x4  # OP_LEGACY_SERVER_CONNECT
    session = requests.session()
    session.mount('https://', CustomHttpAdapter(ctx))
    return session

loki_url = "https://url-for-loki"

query = '{instance="some-instance"}'
# query = urllib.parse.quote(query)
# print(query)
range_seconds = 60

limit = 10000

step = 60

headers = {
    "Content-Type": "application/json",
    "X-Scope-OrgID": "tenant-id",
}

while True:

    payload = {
        "query": query,
        "range": {
            "from": f"now-{range_seconds}s",
            "to": "now"
        },
        "limit": limit,
        "step": step,
    }

    print(payload)
    response = get_legacy_session().get(
        f"{loki_url}/loki/api/v1/query", json=payload, headers=headers)

    # print(response.json())
    print("text:-", response.text)

    if response.status_code != 200:
        print(f"Error: {response.status_code}")
        exit()

    for log in response.json()["data"]["result"]:
        print(log["values"][0][1])

    time.sleep(60)
</code>```

But i get a syntax error.
text:- parse error : syntax error: unexpected $end
Error: 400

what am i doing wrong here?

Title: Querying loki logs using python

Body:
I am using the following script to query logs from loki which is running on some vm.I want to get the logs on multiple boxes and do some operation on them. so i am using loki as a source to get all the logs collectively.

import requests
import time
import requests
import urllib3
import ssl
import urllib.parse

class CustomHttpAdapter (requests.adapters.HTTPAdapter):
    # "Transport adapter" that allows us to use custom ssl_context.

    def __init__(self, ssl_context=None, **kwargs):
        self.ssl_context = ssl_context
        super().__init__(**kwargs)

    def init_poolmanager(self, connections, maxsize, block=False):
        self.poolmanager = urllib3.poolmanager.PoolManager(
            num_pools=connections, maxsize=maxsize,
            block=block, ssl_context=self.ssl_context)

def get_legacy_session():
    ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
    ctx.options |= 0x4  # OP_LEGACY_SERVER_CONNECT
    session = requests.session()
    session.mount('https://', CustomHttpAdapter(ctx))
    return session

loki_url = "https://url-for-loki"

query = '{instance="some-instance"}'
# query = urllib.parse.quote(query)
# print(query)
range_seconds = 60

limit = 10000

step = 60

headers = {
    "Content-Type": "application/json",
    "X-Scope-OrgID": "tenant-id",
}

while True:

    payload = {
        "query": query,
        "range": {
            "from": f"now-{range_seconds}s",
            "to": "now"
        },
        "limit": limit,
        "step": step,
    }

    print(payload)
    response = get_legacy_session().get(
        f"{loki_url}/loki/api/v1/query", json=payload, headers=headers)

    # print(response.json())
    print("text:-", response.text)

    if response.status_code != 200:
        print(f"Error: {response.status_code}")
        exit()

    for log in response.json()["data"]["result"]:
        print(log["values"][0][1])

    time.sleep(60)

But i get a syntax error.
text:- parse error : syntax error: unexpected $end
Error: 400

what am i doing wrong here?


问:
Have multiple fields from another model linked by a foreign key
I have multiple models :

```<code>class Circuit(models.Model):
    name = models.CharField('Circuit', max_length=120)
    country = models.CharField('Pays', max_length=120, choices=country_choices)
    version = models.CharField('Version circuit', default='Grand-Prix', max_length=120, choices=circuit_version_choices)
    image = models.ImageField('Image noir/blanc', blank=True, upload_to='circuit_pics', default='circuit_pics/a2*1ùp6*ù.png')
    image_details = models.ImageField('Image détaillée', blank=True, upload_to='circuit_details', default='circuit_details/a2*1ùp6*ù.png')

class Event(models.Model):
    game = models.ForeignKey(Game, verbose_name='Nom du jeu', null=True, on_delete=models.SET_NULL)
    event_type = models.CharField(verbose_name="Type d'événement", max_length=50, choices=type_course)
    league = models.ForeignKey(League, verbose_name='Ligue', null=True, on_delete=models.SET_NULL)
    circuit = models.ForeignKey(Circuit, verbose_name='Circuit', null=True, on_delete=models.SET_NULL)
    event_date = models.DateTimeField(verbose_name="Date de la course")
</code>```

A race event takes place in a circuit. This circuit can have multiple versions (the version field in the Circuit model gives "Version1", "Version2", as possible choices).

How can I have this choice also in the Event model, so that, in the admin section, I also have the choice to pick the circuit version it will take place in.

More generally, how do I add multiple fields in a model from another model linked with a foreign key ?

Body:
I have multiple models :

class Circuit(models.Model):
    name = models.CharField('Circuit', max_length=120)
    country = models.CharField('Pays', max_length=120, choices=country_choices)
    version = models.CharField('Version circuit', default='Grand-Prix', max_length=120, choices=circuit_version_choices)
    image = models.ImageField('Image noir/blanc', blank=True, upload_to='circuit_pics', default='circuit_pics/a2*1ùp6*ù.png')
    image_details = models.ImageField('Image détaillée', blank=True, upload_to='circuit_details', default='circuit_details/a2*1ùp6*ù.png')

class Event(models.Model):
    game = models.ForeignKey(Game, verbose_name='Nom du jeu', null=True, on_delete=models.SET_NULL)
    event_type = models.CharField(verbose_name="Type d'événement", max_length=50, choices=type_course)
    league = models.ForeignKey(League, verbose_name='Ligue', null=True, on_delete=models.SET_NULL)
    circuit = models.ForeignKey(Circuit, verbose_name='Circuit', null=True, on_delete=models.SET_NULL)
    event_date = models.DateTimeField(verbose_name="Date de la course")

A race event takes place in a circuit. This circuit can have multiple versions (the version field in the Circuit model gives "Version1", "Version2", as possible choices).

How can I have this choice also in the Event model, so that, in the admin section, I also have the choice to pick the circuit version it will take place in.

More generally, how do I add multiple fields in a model from another model linked with a foreign key ?


问:
How do I delete a key in a dictionary array by condition in SQL Server?
The Value column of the Test table stores JSON like:

```<code>{
  "type": "classic",
  "columnState": [
         {"colId": "a", "sort": "asc"},
         {"colId": "b", "sort": "asc"},
         {"colId": "c", "sort": "asc"}
      ]
}
</code>```

How do I remove the "sort" key where "colId": "c" to get result like:

```<code>{
  "type": "classic",
  "columnState": [
         {"colId": "a", "sort": "asc"},
         {"colId": "b", "sort": "asc"},
         {"colId": "c"}
      ]
}
</code>```

The number and order of values in columnState can change.

Data example:

```<code>DECLARE @Test table
    (
        id int,
        Value VARCHAR(1000)
    )
INSERT INTO @Test VALUES
        (1, '{"type": "classic", "columnState": [ {"colId": "a", "sort": "asc"}, {"colId": "b", "sort": "asc"}, {"colId": "c", "sort": "asc"}]'),
        (2, '{"type": "classic", "columnState": [ {"colId": "a", "sort": "asc"}, {"colId": "c", "sort": "asc"}, {"colId": "b", "sort": "asc"}]'),
        (3, '{"type": "classic", "columnState": [ {"colId": "a", "sort": "asc"}, {"colId": "b", "sort": "asc"}, {"colId": "c"}]')

SELECT * FROM @Test
</code>```

Body:
The Value column of the Test table stores JSON like:

{
  "type": "classic",
  "columnState": [
         {"colId": "a", "sort": "asc"},
         {"colId": "b", "sort": "asc"},
         {"colId": "c", "sort": "asc"}
      ]
}

How do I remove the "sort" key where "colId": "c" to get result like:

{
  "type": "classic",
  "columnState": [
         {"colId": "a", "sort": "asc"},
         {"colId": "b", "sort": "asc"},
         {"colId": "c"}
      ]
}

The number and order of values in columnState can change.

Data example:

DECLARE @Test table
    (
        id int,
        Value VARCHAR(1000)
    )
INSERT INTO @Test VALUES
        (1, '{"type": "classic", "columnState": [ {"colId": "a", "sort": "asc"}, {"colId": "b", "sort": "asc"}, {"colId": "c", "sort": "asc"}]'),
        (2, '{"type": "classic", "columnState": [ {"colId": "a", "sort": "asc"}, {"colId": "c", "sort": "asc"}, {"colId": "b", "sort": "asc"}]'),
        (3, '{"type": "classic", "columnState": [ {"colId": "a", "sort": "asc"}, {"colId": "b", "sort": "asc"}, {"colId": "c"}]')

SELECT * FROM @Test


问:
Strange timeout behaviour with an ASP.NET Core MVC API
I am experiencing some strange behaviour with a timeout when using an API that I have written.
The API is very simple: just a controller that will call a service. The service run essentially is

```<code>public async Task<PerformWorkResponse> PerformWork()
{
  var result = await doSomeWork();
  return result;
}
</code>```

The doSomeWork function is primarilly I/O and API calls to external services, and it can take some time for it to finish, up to 6 minutes. I am finding a timeout of 3 minutes when running this API.
I have set the NGINX timeout to 15 minutes.

When trying to find the source of the timeout I also implemented a load test that calculates prime numbers larger than the input number.

```<code>public int GetPrimeNumber([FromQuery] int n)
{
  int result = FindPrimeNumber(n);
  return result;
}
</code>```

When running this, I don't get this timeout, only the timeout set by NGINX.

The only possible explanation that I have for this is that the doSomeWork function is async, while the prime number function is not. But when searching, but I have been unable to find any information about a timeout that only applies to async functions.

Body:
I am experiencing some strange behaviour with a timeout when using an API that I have written.
The API is very simple: just a controller that will call a service. The service run essentially is

public async Task<PerformWorkResponse> PerformWork()
{
  var result = await doSomeWork();
  return result;
}

The doSomeWork function is primarilly I/O and API calls to external services, and it can take some time for it to finish, up to 6 minutes. I am finding a timeout of 3 minutes when running this API.
I have set the NGINX timeout to 15 minutes.

When trying to find the source of the timeout I also implemented a load test that calculates prime numbers larger than the input number.

public int GetPrimeNumber([FromQuery] int n)
{
  int result = FindPrimeNumber(n);
  return result;
}

When running this, I don't get this timeout, only the timeout set by NGINX.

The only possible explanation that I have for this is that the doSomeWork function is async, while the prime number function is not. But when searching, but I have been unable to find any information about a timeout that only applies to async functions.


问:
Image Hashing is not happening on static image when serving from AWS S3 in Next.js
I want to serve all static resources like fonts and images from the CDN server. So currently static images and fonts lie under /public/images and /public/fonts. On build, Next.js will hash every image and font under .next/static/media. As shown in the image below.

Now as per the Asset Prefix document, I have also added a CDN path in the next.config.js

```<code>const getCDN = () => {
  if (process.env.NEXT_PUBLIC_APP_ENV === 'staging') {
    return 'https://cdn.staging.mydomain.com.au/';
  }

   if (process.env.NEXT_PUBLIC_APP_ENV === 'production') {
    return 'https://cdn.mydomain.com/';
  }
};

module.exports = {
  // Use the CDN in production and localhost for development.
  assetPrefix: getCDN(),
}
</code>```

Also, I have copied all .next/static folder content and uploaded it to S3 under mydomain/_next/static. S3 Path looks like below

```<code>s3://mydomain/_next/static/logo.68a3dfc9.png
</code>```

Now the logo image code looks like

```<code> <Image
      layout="fixed"
      width={90}
      height={34}
      src={'images/logo.png'}
      alt="realestateview.com.au logo"
      />
</code>```

But after building it nothing had changed

```<code><img alt="mydomain.com logo" src="/images/logo.png" decoding="async" data-nimg="intrinsic" style="position:absolute;top:0;left:0;bottom:0;right:0;box-sizing:border-box;padding:0;border:none;margin:auto;display:block;width:0;height:0;min-width:100%;max-width:100%;min-height:100%;max-height:100%">
</code>```

Am I missing something ? What do I need to do to serve that logo image from CDN and that hash? The desired image tag should be as shown below.

```<code><img alt="mydomain.com logo" src="https://cdn.mydomain.com/_next/static/media/logo.68a3dfc9.png" decoding="async" data-nimg="intrinsic" style="position:absolute;top:0;left:0;bottom:0;right:0;box-sizing:border-box;padding:0;border:none;margin:auto;display:block;width:0;height:0;min-width:100%;max-width:100%;min-height:100%;max-height:100%">
</code>```

Body:
I want to serve all static resources like fonts and images from the CDN server. So currently static images and fonts lie under /public/images and /public/fonts. On build, Next.js will hash every image and font under .next/static/media. As shown in the image below.

Now as per the Asset Prefix document, I have also added a CDN path in the next.config.js

const getCDN = () => {
  if (process.env.NEXT_PUBLIC_APP_ENV === 'staging') {
    return 'https://cdn.staging.mydomain.com.au/';
  }

   if (process.env.NEXT_PUBLIC_APP_ENV === 'production') {
    return 'https://cdn.mydomain.com/';
  }
};

module.exports = {
  // Use the CDN in production and localhost for development.
  assetPrefix: getCDN(),
}

Also, I have copied all .next/static folder content and uploaded it to S3 under mydomain/_next/static. S3 Path looks like below

s3://mydomain/_next/static/logo.68a3dfc9.png

Now the logo image code looks like

 <Image
      layout="fixed"
      width={90}
      height={34}
      src={'images/logo.png'}
      alt="realestateview.com.au logo"
      />

But after building it nothing had changed

Am I missing something ? What do I need to do to serve that logo image from CDN and that hash? The desired image tag should be as shown below.


问:
How can I read email (gmail account) in R
I would like to read email received on my google account.

I've tried ‘mRpostman’ package, setting a third party psw for the purpose, as it follows:

install.packages("mRpostman")
library(mRpostman)

con <- configure_imap(url="imaps://imap.gmail.com",
username="xxx@gmail.com",
password="***")

con$list_mail_folders()

then I get this error:

Error in list_mail_folders_int(self, retries) :
Request error: the server returned an error.

Is there a specific setting for gmail that has to be set? I don't find any indication on the documentation page (https://cran.r-project.org/web/packages/mRpostman/mRpostman.pdf), that has been updated on October 27, 2022, so I guess the package is still actively maintained.

Eventually does anyone know another package that I could use for this purpose?

Thanks in advance


问:
When I call an API on My First Page I want to fire Second Page API at the same time how can I achieve it! | React Native
I am working on react native from 3 months means I am still a beginner ,Help me with this Functionality : What I want is that when I add a product to my shopping cart the cart number on my bottom tab should increase at the same time . How can I achieve it?

This is my add to cart screen Here I am adding my products to the cart

```<code>import {
    View, Text, StyleSheet, ScrollView, TouchableOpacity, Alert, Image, ActivityIndicator, Dimensions
} from 'react-native'
import React, { useEffect, useState } from 'react'
import Ionicons from 'react-native-vector-icons/Ionicons'
import Octicons from 'react-native-vector-icons/Octicons'
import AsyncStorage from '@react-native-async-storage/async-storage'
import AntDesign from 'react-native-vector-icons/AntDesign';
import ImageZoom from 'react-native-image-pan-zoom';
import { UserProvider } from './UserContext'

const AddProduct = ({ route, navigation }) => {

    const [count, setCount] = useState(1)
    console.log("this is item quantity=>", count);

    const prodId = route.params.prodId
    console.log('data is coming from route', prodId);

    const [prodImg, setProdImg] = useState("")
    console.log("this is product image from use state=>", prodImg);
    const [productName, setProductName] = useState("")
    const [productDesc, setProductDesc] = useState("")
    // const [in_stock, setIn_stock] = useState("")
    const [availableQty, setAvailableQty] = useState("")
    const [basePrice, setBasePrice] = useState("")
    const [variations, setVariations] = useState([])
    console.log("this is variation data", variations);
    const [changePrice, setChangePrice] = useState("")
    const [variationid, setVariationid] = useState("")
    console.log('this is variation id=>', variationid);

    const [selectedVar, setselectedVar] = useState(0)
    const [customerId, setCustomerId] = useState("")
    console.log("This is customer id ", customerId);
    const baseUrl = "https://team.flymingotech.in/azamDeals/public/"
    const [loader, setLoader] = useState(false)
    const GetProductById = () => {
        setLoader(true)
        var requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };

        fetch(`https://team.flymingotech.in/azamDeals/public/api/readByID/${route.params.prodId}/read`, requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log(result)
                setProdImg(result[0].data.product_images)
                setProductName(result[0].data.product_name)
                setProductDesc(result[0].data.product_desc)
                setAvailableQty(result[0].data.available_qty)
                setBasePrice(result[0].data.base_price)
                // setProductData(result.data)
                setVariations(result[0].data?.variations)
                // if (result && result.data) {
                //     setVariations(result.data.variations);
                //   } else {
                //     console.log('Could not retrieve data');
                //   }
                setLoader(false)

            })
            .catch(error => {
                console.log('error in getProductbyId api', error)
                setLoader(false)
            });
    }
    const getId = async () => {
        try {
            const customer_id = JSON.parse(await AsyncStorage.getItem("Customer_id"))
            console.log("this is getting async storage data", customer_id);
            setCustomerId(customer_id)
        } catch (error) {
            console.log(error);
        }
    };

    useEffect(() => {
        getId()
        GetProductById()
    }, [route.params.prodId])
    function increment() {
        //setCount(prevCount => prevCount+=1);
        setCount(function (prevCount) {
            return (prevCount += 1);
        });
    }
    function decrement() {
        setCount(function (prevCount) {
            if (prevCount > 0) {
                return (prevCount -= 1);
            } else {
                return (prevCount = 0);
            }
        });
    }

    const AddCart = async () => {
        if (variationid == 0) {
            Alert.alert("Please select the product variation")
            return false;
        } else if (count == 0) {
            Alert.alert("Qty cannot be 0")
        }
        else {
            var myHeaders = new Headers();
            myHeaders.append("Content-Type", "application/json");

            var raw = JSON.stringify({
                "product_id": prodId,
                "item_qty": count,
                "item_price": changePrice,
                "total_price": "",
                "c_id": customerId,
                "variation_id": variationid
            });

            var requestOptions = {
                method: 'POST',
                headers: myHeaders,
                body: raw,
                redirect: 'follow'
            };

            await fetch("https://team.flymingotech.in/azamDeals/public/api/new_cart", requestOptions)
                .then(response => response.json())
                .then(result => {
                    console.log(result)
                    if (result.status == 1) {
                        Alert.alert('Added to cart')
                    }

                })
                .catch(error => console.log('error', error));
        }
    }
    const onSelect = (id) => {
        setselectedVar(id)
        console.log(id);
    }
    const images = [
        {
            url:
                'https://raw.githubusercontent.com/AboutReact/sampleresource/master/sample_img.png',
        },
        {
            url:
                'https://raw.githubusercontent.com/AboutReact/sampleresource/master/old_logo.png',
        },
    ];

    return (
        <View style={styles.mainContainer}>
            <View style={{ height: 80, backgroundColor: '#006C32', flexDirection: 'row', paddingTop: 25 }}>
                <TouchableOpacity onPress={() => navigation.goBack()}>
                    <AntDesign style={{ paddingLeft: 20 }} name='arrowleft' size={30} color="white" />
                </TouchableOpacity>
                <Text style={{ paddingLeft: 20, fontSize: 20, color: 'white' }}>Product Detail</Text>
            </View>
            {/* <SearchHeader /> */}
            {loader ?
                <View style={{
                    alignItems: "center",
                    justifyContent: "center",
                    height: "90%"
                }}>
                    <ActivityIndicator size={50} color="green" />
                </View>
                :

                <ScrollView>
                    <View style={{ marginLeft: 15, marginRight: 15 }}>
                        <View>

                            {/* <Image style={{ height: 300, width: '100%', borderRadius: 10, marginTop: 10 }}
                                source={{ uri: prodImg }} /> */}
                            <ImageZoom
                                cropWidth={350}
                                cropHeight={300}
                                imageWidth={200}
                                imageHeight={200}>
                                <Image style={{ width: 200, height: 200 }}
                                    source={{ uri: prodImg }} />
                            </ImageZoom>
                            <Text style={{ color: 'black', fontWeight: 'bold', marginTop: 10 }}>{productName}</Text>
                            <Text style={{ color: 'black', backgroundColor: 'white' }}>{productDesc}</Text>
                            <Text style={{ color: 'black', backgroundColor: 'white' }}  >Stock:{availableQty}</Text>
                            <Text style={{ color: 'black', backgroundColor: 'white' }}  >Base Price:₹{basePrice}</Text>
                            <Text style={{ color: 'black', backgroundColor: 'white' }}  >Variation Price:₹{changePrice}</Text>
                            {/* <Text style={{ color: 'black', backgroundColor: 'white' }}  >Variationid:{variationid}</Text>  */}

                            <View style={{ marginTop: 14 }}>
                                <Text style={{ color: 'black', fontSize: 18, }}>Size</Text>
                                <View style={{
                                    flexDirection: 'row',
                                    justifyContent: 'space-around', height: 25
                                }}>
                                    {/* {console.log("type", productData.variations.length)} */}
                                    <View >
                                        {variations?.length > 0 && variations.map((item, i) => (
                                            <View key={i}>
                                                <TouchableOpacity onPress={() => setChangePrice(item.variation_price,) | setVariationid(item.id) |onSelect(item.id)} style={{
                                                    height: 70, width: 120,
                                                    borderWidth: 0.5, borderColor: 'grey', borderRadius: 10,
                                                    justifyContent: 'center', alignItems: 'center',
                                                    backgroundColor: selectedVar === item.id ? "lightgrey" : "#fff"
                                                }}>
                                                    <Text style={{ color: 'black',  }}>{item.variation_label}</Text>
                                                    <Text style={{ color: 'black',  }}>{item.variation_weight}</Text>
                                                </TouchableOpacity>
                                            </View>
                                        ))}
                                    </View>
                                    {/* <FlatList horizontal
                                    data={productData}
                                    renderItem={(item)=>renderItem(item)}
                                    /> */}

                                    {/* <Pressable onPress={() => getSize('s')} style={[styles.variable, { backgroundColor: size === 's' ? '#D1D1D1' : '#FFF' }]}><Text style={styles.variableValue}>S</Text></Pressable>
                                <Pressable onPress={() => getSize('m')} style={[styles.variable, { backgroundColor: size === 'm' ? '#D1D1D1' : '#FFF' }]}><Text style={styles.variableValue}>M</Text></Pressable>
                                <Pressable onPress={() => getSize('l')} style={[styles.variable, { backgroundColor: size === 'l' ? '#D1D1D1' : '#FFF' }]}><Text style={styles.variableValue}>L</Text></Pressable> */}

                                </View>
                            </View>
                            <View style={{ flexDirection: "row", marginTop: 50, justifyContent: 'space-between', paddingBottom: 10 }}>
                                <View style={styles.countButton}>
                                    <TouchableOpacity onPress={decrement} style={{ alignSelf: 'center', marginLeft: 5 }}>
                                        <Octicons name="dash" size={28} color="black" />
                                    </TouchableOpacity>
                                    <Text style={{ alignSelf: 'center', fontSize: 17, marginLeft: 4, color: 'black' }}>{count}</Text>
                                    <TouchableOpacity onPress={increment} style={{ alignSelf: 'center' }}>
                                        <Ionicons name="add" size={28} color="black" />
                                    </TouchableOpacity>
                                </View>
                                <TouchableOpacity onPress={AddCart} style={{
                                    backgroundColor: '#006C32', height: 40
                                    , justifyContent: 'center', alignItems: 'center', width: 150, borderRadius: 5,
                                }}>
                                    <Text style={{ color: 'white', fontWeight: 'bold' }}>Add to Cart</Text>
                                </TouchableOpacity>
                            </View>

                            {/* <View>
                            <TouchableOpacity style={{
                                width: 300, marginTop: 20, backgroundColor: 'darkgreen', height: 50
                                , borderRadius: 10, justifyContent: 'center', alignItems: 'center', alignSelf: 'center'
                            }}>
                                <Text style={{ color: 'white', fontWeight: 'bold' }}>Buy Now</Text>
                            </TouchableOpacity>
                        </View> */}
                        </View>
                    </View>
                </ScrollView>
            }
        </View>
    )
}
const styles = StyleSheet.create({
    mainContainer: {
        flex: 1,
        backgroundColor: 'white'
    },
    image: {
        height: 300, width: '100%',
    },
    countButton: {
        backgroundColor: 'white', height: 40, borderWidth: 0.5, borderColor: 'grey'
        , width: 100, flexDirection: 'row', borderRadius: 10, justifyContent: 'space-between',

    },
    variable: {
        padding: 5,
        color: 'black',
        borderWidth: 1,
        borderColor: '#999999',
        borderRadius: 4,
    },
    variableValue: {

        fontWeight: '700',
    },
})

export default AddProduct
</code>```

And this is my screen where I am showing the count of the products as a badge using an API it is working it is showing the data but when I refresh the app that time only it shows the count

```<code>import { View, Text, StyleSheet } from 'react-native'
import React, { useEffect, useState } from 'react'
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { getFocusedRouteNameFromRoute } from '@react-navigation/native';
import Ionicons from 'react-native-vector-icons/Ionicons'
import User from 'react-native-vector-icons/FontAwesome'

// screens
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack'
import Home from '../screens/HomeScreen/Home';
import { CustomerStack, Cart, Profile } from './CustomerStack';
import { Badge } from 'react-native-elements';
import AsyncStorage from '@react-native-async-storage/async-storage';

// Screen Names

const Stack = createNativeStackNavigator();
const Tab = createBottomTabNavigator();

const BottomTabNav = ({ route, navigation }) => {
    const [Count, setCount] = useState("")
    console.log("this is Count of cart=>",Count);
    useEffect(() => {
        getCartCount()
    }, [])
    const getCartCount = async () => {
        const customer_id = JSON.parse(await AsyncStorage.getItem("Customer_id"))
        var requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };

        fetch(`https://team.flymingotech.in/azamDeals/public/api/countCartItems/${customer_id}`, requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log(result)
                setCount(result.data)
            })
            .catch(error => console.log('error', error));
    }
    <Tab.Screen
        name="CustomerStack"
        component={CustomerStack}
        options={({ route }) => ({ tabBarStyle: getTabBarStyle(route) })} />

    const getTabBarStyle = (route) => {
        const routeName = getFocusedRouteNameFromRoute(route) ?? 'CustomerStack';
        let display = (routeName === 'Player') ? 'none' : 'flex';
        return { display }
    }
    return (

        <Tab.Navigator initialRouteName='CustomerStack'
            tabBarOptions={{
                // activeTintColor: 'red',
                inactiveTintColor: 'white',

            }}
            screenOptions={({ route, }) => ({
                tabBarStyle: {
                    backgroundColor: '#006C32',
                },

                tabBarIcon: ({ focused, color, size }) => {
                    let iconName;
                    let rn = route.name;
                    if (rn === "CustomDrawer") {
                        iconName = focused ? 'home' : 'home'
                    }
                    else if (rn === "CustomerStack") {
                        iconName = focused ? 'home' : 'home'
                    }

                    else if (rn === "Cart") {
                        <View style={styles.unreadBadge}>
                            <Text style={styles.unreadBadgeText}>11</Text>
                        </View>
                        iconName = focused ? 'shopping-cart' : 'shopping-cart'

                    } else if (rn === "Account") {
                        iconName = focused ? 'user' : 'user'
                    }
                    return <User name={iconName} size={size} color={color} />
                },
            })}>
            <Tab.Screen options={{ headerShown: false, tabBarActiveTintColor: 'white', }} name="CustomerStack" component={CustomerStack} />

            <Tab.Screen options={{
                headerShown: false, tabBarActiveTintColor: 'white',
                tabBarBadge: Count
            }} name="Cart" component={Cart} />
            <Tab.Screen options={{ headerShown: false, tabBarActiveTintColor: 'white', }} name="Account" component={Profile} />

        </Tab.Navigator>

    )

}
const styles = StyleSheet.create({
    unreadBadge: {
        backgroundColor: '#FF3250',
        position: 'absolute',
        left: 20,
        bottom: 18,
        width: 25,
        height: 18,
        borderradius: 25,
        alignItems: 'center',
        justifyContent: 'center',
        zIndex: 100,    // this one is used to put message notify on top of icon
    },
    unreadBadgeText: {
        color: 'white',
        fontWeight: '600',
    },
})

export default BottomTabNav

</code>```

What I was going to try is that keep calling that API every 5 seconds then after calling the API So many times it will give Too many request error .

Whether I should use UseContext or Pass data through both the screen and call API I don't get it!

Body:
I am working on react native from 3 months means I am still a beginner ,Help me with this Functionality : What I want is that when I add a product to my shopping cart the cart number on my bottom tab should increase at the same time . How can I achieve it?

This is my add to cart screen Here I am adding my products to the cart

import {
    View, Text, StyleSheet, ScrollView, TouchableOpacity, Alert, Image, ActivityIndicator, Dimensions
} from 'react-native'
import React, { useEffect, useState } from 'react'
import Ionicons from 'react-native-vector-icons/Ionicons'
import Octicons from 'react-native-vector-icons/Octicons'
import AsyncStorage from '@react-native-async-storage/async-storage'
import AntDesign from 'react-native-vector-icons/AntDesign';
import ImageZoom from 'react-native-image-pan-zoom';
import { UserProvider } from './UserContext'

const AddProduct = ({ route, navigation }) => {

    const [count, setCount] = useState(1)
    console.log("this is item quantity=>", count);

    const prodId = route.params.prodId
    console.log('data is coming from route', prodId);

    const [prodImg, setProdImg] = useState("")
    console.log("this is product image from use state=>", prodImg);
    const [productName, setProductName] = useState("")
    const [productDesc, setProductDesc] = useState("")
    // const [in_stock, setIn_stock] = useState("")
    const [availableQty, setAvailableQty] = useState("")
    const [basePrice, setBasePrice] = useState("")
    const [variations, setVariations] = useState([])
    console.log("this is variation data", variations);
    const [changePrice, setChangePrice] = useState("")
    const [variationid, setVariationid] = useState("")
    console.log('this is variation id=>', variationid);

    const [selectedVar, setselectedVar] = useState(0)
    const [customerId, setCustomerId] = useState("")
    console.log("This is customer id ", customerId);
    const baseUrl = "https://team.flymingotech.in/azamDeals/public/"
    const [loader, setLoader] = useState(false)
    const GetProductById = () => {
        setLoader(true)
        var requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };

        fetch(`https://team.flymingotech.in/azamDeals/public/api/readByID/${route.params.prodId}/read`, requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log(result)
                setProdImg(result[0].data.product_images)
                setProductName(result[0].data.product_name)
                setProductDesc(result[0].data.product_desc)
                setAvailableQty(result[0].data.available_qty)
                setBasePrice(result[0].data.base_price)
                // setProductData(result.data)
                setVariations(result[0].data?.variations)
                // if (result && result.data) {
                //     setVariations(result.data.variations);
                //   } else {
                //     console.log('Could not retrieve data');
                //   }
                setLoader(false)

            })
            .catch(error => {
                console.log('error in getProductbyId api', error)
                setLoader(false)
            });
    }
    const getId = async () => {
        try {
            const customer_id = JSON.parse(await AsyncStorage.getItem("Customer_id"))
            console.log("this is getting async storage data", customer_id);
            setCustomerId(customer_id)
        } catch (error) {
            console.log(error);
        }
    };

    useEffect(() => {
        getId()
        GetProductById()
    }, [route.params.prodId])
    function increment() {
        //setCount(prevCount => prevCount+=1);
        setCount(function (prevCount) {
            return (prevCount += 1);
        });
    }
    function decrement() {
        setCount(function (prevCount) {
            if (prevCount > 0) {
                return (prevCount -= 1);
            } else {
                return (prevCount = 0);
            }
        });
    }

    const AddCart = async () => {
        if (variationid == 0) {
            Alert.alert("Please select the product variation")
            return false;
        } else if (count == 0) {
            Alert.alert("Qty cannot be 0")
        }
        else {
            var myHeaders = new Headers();
            myHeaders.append("Content-Type", "application/json");

            var raw = JSON.stringify({
                "product_id": prodId,
                "item_qty": count,
                "item_price": changePrice,
                "total_price": "",
                "c_id": customerId,
                "variation_id": variationid
            });

            var requestOptions = {
                method: 'POST',
                headers: myHeaders,
                body: raw,
                redirect: 'follow'
            };

            await fetch("https://team.flymingotech.in/azamDeals/public/api/new_cart", requestOptions)
                .then(response => response.json())
                .then(result => {
                    console.log(result)
                    if (result.status == 1) {
                        Alert.alert('Added to cart')
                    }

                })
                .catch(error => console.log('error', error));
        }
    }
    const onSelect = (id) => {
        setselectedVar(id)
        console.log(id);
    }
    const images = [
        {
            url:
                'https://raw.githubusercontent.com/AboutReact/sampleresource/master/sample_img.png',
        },
        {
            url:
                'https://raw.githubusercontent.com/AboutReact/sampleresource/master/old_logo.png',
        },
    ];

    return (
        <View style={styles.mainContainer}>
            <View style={{ height: 80, backgroundColor: '#006C32', flexDirection: 'row', paddingTop: 25 }}>
                <TouchableOpacity onPress={() => navigation.goBack()}>
                    <AntDesign style={{ paddingLeft: 20 }} name='arrowleft' size={30} color="white" />
                </TouchableOpacity>
                <Text style={{ paddingLeft: 20, fontSize: 20, color: 'white' }}>Product Detail</Text>
            </View>
            {/* <SearchHeader /> */}
            {loader ?
                <View style={{
                    alignItems: "center",
                    justifyContent: "center",
                    height: "90%"
                }}>
                    <ActivityIndicator size={50} color="green" />
                </View>
                :

                <ScrollView>
                    <View style={{ marginLeft: 15, marginRight: 15 }}>
                        <View>

                            {/* <Image style={{ height: 300, width: '100%', borderRadius: 10, marginTop: 10 }}
                                source={{ uri: prodImg }} /> */}
                            <ImageZoom
                                cropWidth={350}
                                cropHeight={300}
                                imageWidth={200}
                                imageHeight={200}>
                                <Image style={{ width: 200, height: 200 }}
                                    source={{ uri: prodImg }} />
                            </ImageZoom>
                            <Text style={{ color: 'black', fontWeight: 'bold', marginTop: 10 }}>{productName}</Text>
                            <Text style={{ color: 'black', backgroundColor: 'white' }}>{productDesc}</Text>
                            <Text style={{ color: 'black', backgroundColor: 'white' }}  >Stock:{availableQty}</Text>
                            <Text style={{ color: 'black', backgroundColor: 'white' }}  >Base Price:₹{basePrice}</Text>
                            <Text style={{ color: 'black', backgroundColor: 'white' }}  >Variation Price:₹{changePrice}</Text>
                            {/* <Text style={{ color: 'black', backgroundColor: 'white' }}  >Variationid:{variationid}</Text>  */}

                            <View style={{ marginTop: 14 }}>
                                <Text style={{ color: 'black', fontSize: 18, }}>Size</Text>
                                <View style={{
                                    flexDirection: 'row',
                                    justifyContent: 'space-around', height: 25
                                }}>
                                    {/* {console.log("type", productData.variations.length)} */}
                                    <View >
                                        {variations?.length > 0 && variations.map((item, i) => (
                                            <View key={i}>
                                                <TouchableOpacity onPress={() => setChangePrice(item.variation_price,) | setVariationid(item.id) |onSelect(item.id)} style={{
                                                    height: 70, width: 120,
                                                    borderWidth: 0.5, borderColor: 'grey', borderRadius: 10,
                                                    justifyContent: 'center', alignItems: 'center',
                                                    backgroundColor: selectedVar === item.id ? "lightgrey" : "#fff"
                                                }}>
                                                    <Text style={{ color: 'black',  }}>{item.variation_label}</Text>
                                                    <Text style={{ color: 'black',  }}>{item.variation_weight}</Text>
                                                </TouchableOpacity>
                                            </View>
                                        ))}
                                    </View>
                                    {/* <FlatList horizontal
                                    data={productData}
                                    renderItem={(item)=>renderItem(item)}
                                    /> */}

                                    {/* <Pressable onPress={() => getSize('s')} style={[styles.variable, { backgroundColor: size === 's' ? '#D1D1D1' : '#FFF' }]}><Text style={styles.variableValue}>S</Text></Pressable>
                                <Pressable onPress={() => getSize('m')} style={[styles.variable, { backgroundColor: size === 'm' ? '#D1D1D1' : '#FFF' }]}><Text style={styles.variableValue}>M</Text></Pressable>
                                <Pressable onPress={() => getSize('l')} style={[styles.variable, { backgroundColor: size === 'l' ? '#D1D1D1' : '#FFF' }]}><Text style={styles.variableValue}>L</Text></Pressable> */}

                                </View>
                            </View>
                            <View style={{ flexDirection: "row", marginTop: 50, justifyContent: 'space-between', paddingBottom: 10 }}>
                                <View style={styles.countButton}>
                                    <TouchableOpacity onPress={decrement} style={{ alignSelf: 'center', marginLeft: 5 }}>
                                        <Octicons name="dash" size={28} color="black" />
                                    </TouchableOpacity>
                                    <Text style={{ alignSelf: 'center', fontSize: 17, marginLeft: 4, color: 'black' }}>{count}</Text>
                                    <TouchableOpacity onPress={increment} style={{ alignSelf: 'center' }}>
                                        <Ionicons name="add" size={28} color="black" />
                                    </TouchableOpacity>
                                </View>
                                <TouchableOpacity onPress={AddCart} style={{
                                    backgroundColor: '#006C32', height: 40
                                    , justifyContent: 'center', alignItems: 'center', width: 150, borderRadius: 5,
                                }}>
                                    <Text style={{ color: 'white', fontWeight: 'bold' }}>Add to Cart</Text>
                                </TouchableOpacity>
                            </View>

                            {/* <View>
                            <TouchableOpacity style={{
                                width: 300, marginTop: 20, backgroundColor: 'darkgreen', height: 50
                                , borderRadius: 10, justifyContent: 'center', alignItems: 'center', alignSelf: 'center'
                            }}>
                                <Text style={{ color: 'white', fontWeight: 'bold' }}>Buy Now</Text>
                            </TouchableOpacity>
                        </View> */}
                        </View>
                    </View>
                </ScrollView>
            }
        </View>
    )
}
const styles = StyleSheet.create({
    mainContainer: {
        flex: 1,
        backgroundColor: 'white'
    },
    image: {
        height: 300, width: '100%',
    },
    countButton: {
        backgroundColor: 'white', height: 40, borderWidth: 0.5, borderColor: 'grey'
        , width: 100, flexDirection: 'row', borderRadius: 10, justifyContent: 'space-between',

    },
    variable: {
        padding: 5,
        color: 'black',
        borderWidth: 1,
        borderColor: '#999999',
        borderRadius: 4,
    },
    variableValue: {

        fontWeight: '700',
    },
})

export default AddProduct

And this is my screen where I am showing the count of the products as a badge using an API it is working it is showing the data but when I refresh the app that time only it shows the count

import { View, Text, StyleSheet } from 'react-native'
import React, { useEffect, useState } from 'react'
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { getFocusedRouteNameFromRoute } from '@react-navigation/native';
import Ionicons from 'react-native-vector-icons/Ionicons'
import User from 'react-native-vector-icons/FontAwesome'

// screens
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack'
import Home from '../screens/HomeScreen/Home';
import { CustomerStack, Cart, Profile } from './CustomerStack';
import { Badge } from 'react-native-elements';
import AsyncStorage from '@react-native-async-storage/async-storage';

// Screen Names

const Stack = createNativeStackNavigator();
const Tab = createBottomTabNavigator();

const BottomTabNav = ({ route, navigation }) => {
    const [Count, setCount] = useState("")
    console.log("this is Count of cart=>",Count);
    useEffect(() => {
        getCartCount()
    }, [])
    const getCartCount = async () => {
        const customer_id = JSON.parse(await AsyncStorage.getItem("Customer_id"))
        var requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };

        fetch(`https://team.flymingotech.in/azamDeals/public/api/countCartItems/${customer_id}`, requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log(result)
                setCount(result.data)
            })
            .catch(error => console.log('error', error));
    }
    <Tab.Screen
        name="CustomerStack"
        component={CustomerStack}
        options={({ route }) => ({ tabBarStyle: getTabBarStyle(route) })} />

    const getTabBarStyle = (route) => {
        const routeName = getFocusedRouteNameFromRoute(route) ?? 'CustomerStack';
        let display = (routeName === 'Player') ? 'none' : 'flex';
        return { display }
    }
    return (

        <Tab.Navigator initialRouteName='CustomerStack'
            tabBarOptions={{
                // activeTintColor: 'red',
                inactiveTintColor: 'white',

            }}
            screenOptions={({ route, }) => ({
                tabBarStyle: {
                    backgroundColor: '#006C32',
                },

                tabBarIcon: ({ focused, color, size }) => {
                    let iconName;
                    let rn = route.name;
                    if (rn === "CustomDrawer") {
                        iconName = focused ? 'home' : 'home'
                    }
                    else if (rn === "CustomerStack") {
                        iconName = focused ? 'home' : 'home'
                    }

                    else if (rn === "Cart") {
                        <View style={styles.unreadBadge}>
                            <Text style={styles.unreadBadgeText}>11</Text>
                        </View>
                        iconName = focused ? 'shopping-cart' : 'shopping-cart'

                    } else if (rn === "Account") {
                        iconName = focused ? 'user' : 'user'
                    }
                    return <User name={iconName} size={size} color={color} />
                },
            })}>
            <Tab.Screen options={{ headerShown: false, tabBarActiveTintColor: 'white', }} name="CustomerStack" component={CustomerStack} />

            <Tab.Screen options={{
                headerShown: false, tabBarActiveTintColor: 'white',
                tabBarBadge: Count
            }} name="Cart" component={Cart} />
            <Tab.Screen options={{ headerShown: false, tabBarActiveTintColor: 'white', }} name="Account" component={Profile} />

        </Tab.Navigator>

    )

}
const styles = StyleSheet.create({
    unreadBadge: {
        backgroundColor: '#FF3250',
        position: 'absolute',
        left: 20,
        bottom: 18,
        width: 25,
        height: 18,
        borderradius: 25,
        alignItems: 'center',
        justifyContent: 'center',
        zIndex: 100,    // this one is used to put message notify on top of icon
    },
    unreadBadgeText: {
        color: 'white',
        fontWeight: '600',
    },
})

export default BottomTabNav

What I was going to try is that keep calling that API every 5 seconds then after calling the API So many times it will give Too many request error .

Whether I should use UseContext or Pass data through both the screen and call API I don't get it!


问:
Explicit form activation not working with startmenu when using the WS_EX_NOACTIVATE flag
Have enabled the WS_EX_NOACTIVATE flag in CreateParams() in my application to prevent the application from stealing focus during startup (not actually needed in this small example, but needed in the much bigger real application with multiple forms).

When the form is clicked, Activate() is called.

```<code>public partial class MyForm : Form
{
   public MyForm()
   {
      InitializeComponent();
   }

   protected override CreateParams CreateParams
   {
      get
      {
         int WS_EX_NOACTIVATE = 0x08000000;
         CreateParams cp = base.CreateParams;
         cp.ExStyle |= WS_EX_NOACTIVATE;
         return cp;
      }
   }

   private void MyForm_Click(object sender, EventArgs e)
   {
      label1.Text = "Clicked";
      Activate();
   }
}
</code>```

This works fine in most cases, but when the Windows startmenu is opened and the form is clicked, the startmenu doesn't close (like it does when any other window is clicked).

The call to Activate() doesn't seem to fully activate the form when using NOACTIVATE in CreateParams().

Note 1: It actually works when running the application from Visual Studio, but not when starting the application using the .exe outside of VS.

Note 2: The application icon down in the taskbar starts to blink when the form is clicked.

Have tried to call SetActiveWindow, SetForegroundWindow with the window handle too, but that didn't help.

Is using .NET Framework 4.7.2 and Windows 10 Pro

Body:
Have enabled the WS_EX_NOACTIVATE flag in CreateParams() in my application to prevent the application from stealing focus during startup (not actually needed in this small example, but needed in the much bigger real application with multiple forms).

When the form is clicked, Activate() is called.

public partial class MyForm : Form
{
   public MyForm()
   {
      InitializeComponent();
   }

   protected override CreateParams CreateParams
   {
      get
      {
         int WS_EX_NOACTIVATE = 0x08000000;
         CreateParams cp = base.CreateParams;
         cp.ExStyle |= WS_EX_NOACTIVATE;
         return cp;
      }
   }

   private void MyForm_Click(object sender, EventArgs e)
   {
      label1.Text = "Clicked";
      Activate();
   }
}

This works fine in most cases, but when the Windows startmenu is opened and the form is clicked, the startmenu doesn't close (like it does when any other window is clicked).

The call to Activate() doesn't seem to fully activate the form when using NOACTIVATE in CreateParams().

Note 1: It actually works when running the application from Visual Studio, but not when starting the application using the .exe outside of VS.

Note 2: The application icon down in the taskbar starts to blink when the form is clicked.

Have tried to call SetActiveWindow, SetForegroundWindow with the window handle too, but that didn't help.

Is using .NET Framework 4.7.2 and Windows 10 Pro


问:
Wrong output using python strip() function
So I am having a weird issue here
When I am stripping a certain string which have parenthesis, its removing the first word after the parenthesis
Ex:

```<code>c = 'PurchaseOrderItem(d330d1adf0)'
print (c.strip("PurchaseOrderItem("+")"))
</code>```

OUTPUT : 330d1adf0

the above output should have the char 'd', but its removing it

Body:
So I am having a weird issue here
When I am stripping a certain string which have parenthesis, its removing the first word after the parenthesis
Ex:

c = 'PurchaseOrderItem(d330d1adf0)'
print (c.strip("PurchaseOrderItem("+")"))

OUTPUT : 330d1adf0

the above output should have the char 'd', but its removing it


问:
Getting Levenshtein distance from `diifflib.ndiff`
The levenshtein distance algorithm in Python is too slow as I am comparing many strings.

So I want to use difflib.ndiff to do it.

I tried parsing the output by interpreting "+", "-", " " from the result of ndiff, but failed.

Here is what I tried:

```<code>import difflib
edit_dist = sum(op[0] == "-" for op in difflib.ndiff("split", "sitting"))
</code>```

But the returned result is incorrect.

I want to use solutions from stdlib. Any advice / solutions?

P.S. I need to get the nunber edit distance, not ratio so SequenceMatcher.ratio doesn't work

Body:
The levenshtein distance algorithm in Python is too slow as I am comparing many strings.

So I want to use difflib.ndiff to do it.

I tried parsing the output by interpreting "+", "-", " " from the result of ndiff, but failed.

Here is what I tried:

import difflib
edit_dist = sum(op[0] == "-" for op in difflib.ndiff("split", "sitting"))

But the returned result is incorrect.

I want to use solutions from stdlib. Any advice / solutions?

P.S. I need to get the nunber edit distance, not ratio so SequenceMatcher.ratio doesn't work


问:
How to make executable file for Linux from python program via Pyinstaller
I have wroted a python app using tkinter and now I'm trying to make it executable for my Ubuntu. I've tried to instal Pyinstaller with pip install pip install pyinstaller and then run pyinstaller --onefile main.py. After the proces have ended I've decided to test my file and run ./dist/main but got this error:

```<code>Traceback (most recent call last):
  File "main.py", line 23, in <module>
  File "connection_tab.py", line 20, in __init__
  File "connection_tab.py", line 72, in get_params
FileNotFoundError: [Errno 2] No such file or directory: 'info.json'
[12398] Failed to execute script 'main' due to unhandled exception!
</code>```

'info.json' is a file I use to store the data, and it seems  pyinstaller have missed it.

What shoud I do to make it visible for app?

Body:
I have wroted a python app using tkinter and now I'm trying to make it executable for my Ubuntu. I've tried to instal Pyinstaller with pip install pip install pyinstaller and then run pyinstaller --onefile main.py. After the proces have ended I've decided to test my file and run ./dist/main but got this error:

Traceback (most recent call last):
  File "main.py", line 23, in <module>
  File "connection_tab.py", line 20, in __init__
  File "connection_tab.py", line 72, in get_params
FileNotFoundError: [Errno 2] No such file or directory: 'info.json'
[12398] Failed to execute script 'main' due to unhandled exception!

'info.json' is a file I use to store the data, and it seems  pyinstaller have missed it.

What shoud I do to make it visible for app?


问:
Datapower/MQ unknown 0 Byte Reply
I am creating a Datapower MPGW which will send a SOAP/MQ Request.  I have created a stub backend which will hold and not return any response in order to try simulate a timeout for testing purposes.

The issue I'm facing is the following, all with the same timestamp eg. 11:14:28

"Issuing a request to URL: dpmq://xxx/?RequestQueue=yyy, with a size of 100 bytes"

"No reply for URL: dpmq://xxx/?RequestQueue=yyy will be processed."

"Received a reply from URL: dpmq://xxx/?RequestQueue=yyy, with a size of 0 bytes"

To my knowledge my stub does not reply (one way i am ensuring this is by keeping the debugger on my IIB Stub holding the process preventing the response)

Perhaps as i am new i am not understanding, but i was expecting my Servers timeout to eventually kick in and my response/error flow to start.  However due to this instant 0byte reply, it does not seem to happen.

What could be causing this 0-Byte Response?

How can i stop this from happening?

Thanks

Title: Datapower/MQ unknown 0 Byte Reply


问:
SOAP Curl PHP request
I tried try to get Token, but answer always blank. What i doing wrong?

```<code>        $post_string = '
    <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:tem="http://tempuri.org/">
       <soap:Header/>
       <soap:Body>
          <tem:GetToken>
             <tem:WebChanelID>8</tem:WebChanelID>
             <tem:AccessCode>444555</tem:AccessCode>
          </tem:GetToken>
       </soap:Body>
    </soap:Envelope>
    ';
    $soap_do = curl_init();
    curl_setopt($soap_do, CURLOPT_URL,            "https://hma.ecvi.ru/service/webform.wsdl.php" );
    curl_setopt($soap_do, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($soap_do, CURLOPT_TIMEOUT,        10);
    curl_setopt($soap_do, CURLOPT_RETURNTRANSFER, true );
    curl_setopt($soap_do, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($soap_do, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($soap_do, CURLOPT_POST,           true );
    curl_setopt($soap_do, CURLOPT_POSTFIELDS,    $post_string);
    curl_setopt($soap_do, CURLOPT_HTTPHEADER,     array('Content-Type: text/xml; charset=utf-8', 'Content-Length: '.strlen($post_string) ));

    $result = curl_exec($soap_do);
    $err = curl_error($soap_do);
</code>```

I need to get an answer, but it's always blank.

Title: SOAP Curl PHP request

Body:
I tried try to get Token, but answer always blank. What i doing wrong?

        $post_string = '
    <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:tem="http://tempuri.org/">
       <soap:Header/>
       <soap:Body>
          <tem:GetToken>
             <tem:WebChanelID>8</tem:WebChanelID>
             <tem:AccessCode>444555</tem:AccessCode>
          </tem:GetToken>
       </soap:Body>
    </soap:Envelope>
    ';
    $soap_do = curl_init();
    curl_setopt($soap_do, CURLOPT_URL,            "https://hma.ecvi.ru/service/webform.wsdl.php" );
    curl_setopt($soap_do, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($soap_do, CURLOPT_TIMEOUT,        10);
    curl_setopt($soap_do, CURLOPT_RETURNTRANSFER, true );
    curl_setopt($soap_do, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($soap_do, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($soap_do, CURLOPT_POST,           true );
    curl_setopt($soap_do, CURLOPT_POSTFIELDS,    $post_string);
    curl_setopt($soap_do, CURLOPT_HTTPHEADER,     array('Content-Type: text/xml; charset=utf-8', 'Content-Length: '.strlen($post_string) ));

    $result = curl_exec($soap_do);
    $err = curl_error($soap_do);

I need to get an answer, but it's always blank.


问:
Storing a gRPC object with a oneof field in MongoDB in C# does not work
I have a message defined in a .proto file, that looks like this -

```<code>message Identifier {
    oneof id {
        uint64 id_number = 1;
        string id_string = 2;
    }
}

</code>```

Now, I created a mongo db collection that contains documents that have Identifier stored as a field.

The things, even though reading the database with a Mongo viewer such as Studio 3T works, reading the document using C# MongoDB shows id_number = 0, even when the field is populated on insertion and in the database. Has any one experienced something like this?

Body:
I have a message defined in a .proto file, that looks like this -

message Identifier {
    oneof id {
        uint64 id_number = 1;
        string id_string = 2;
    }
}

Now, I created a mongo db collection that contains documents that have Identifier stored as a field.

The things, even though reading the database with a Mongo viewer such as Studio 3T works, reading the document using C# MongoDB shows id_number = 0, even when the field is populated on insertion and in the database. Has any one experienced something like this?


问:
How can I recover the use of a Bitbucket account if the 2FA device and recovery keys have been lost?
We use Bitbucket for our source code repository. One of our colleagues has unfortunately lost their 2FA device and has also lost their recovery keys. Because Bitbucket is self administered this means that they can no longer log into that account.

This is a work account, so there is no personal repositories. All repositories are accessed via invitations to company work spaces. So I'm wondering would it be possible to somehow delete the account and then recreate it (with the email) and then invite the new account into the relevant work spaces?

So the questions are:

Is this possible?

If possible, what are the downsides of this approach?


问:
Switch from "Featured Image by URL" plugin to FIFU
I have been using "Featured Image by URL" plugin for years but it is now abandoned.

I want to change to FIFU, is there a way to seamlessly switch it automatically?

Thank you.

All the URL settings of featured image by URL will be kept when switching to FIFU (Featured Image From URL)


问:
Allowlist URL pattern in firebase flutter
I was trying to generate short dynamic link in the app using this function here (and long dynamic link gives me the same error)

```<code>FirebaseDynamicLinks dynamicLinks = FirebaseDynamicLinks.instance;

  Future<String> builDynamicLinks(String? id, {bool isFamily = false}) async {

    final DynamicLinkParameters parameters = DynamicLinkParameters(
      // The Dynamic Link URI domain. You can view created URIs on your Firebase console
      uriPrefix: 'https://links.nanny-finder.app/links/',

      // The deep Link passed to your application which you can use to affect change
      link: Uri.parse(
          'https://links.nanny-finder.app/links/${isFamily ? "families" : "nannies"}?id=$id'),

      // Android application details needed for opening correct app on device/Play Store
      androidParameters: AndroidParameters(
          packageName: 'com.mickaelrobin.nannyfinderuae',
          fallbackUrl: playStore),

      // iOS application details needed for opening correct app on device/App Store
      iosParameters: IOSParameters(
          bundleId: 'com.mickaelrobin.nannyfinderuae', fallbackUrl: appStore),
    );

    final ShortDynamicLink shortDynamicLink =
        await dynamicLinks.buildShortLink(parameters);
    print(shortDynamicLink);

    return shortDynamicLink.shortUrl.toString();
  }
</code>```

But I got this error:

```<code>FirebaseException ([firebase_dynamic_links/unknown] com.google.android.gms.common.api.ApiException: 400: We could not match param 'https://links.nanny-finder.app/links/nannies?id=GarmRWdyEgTRbFMfE3fnCp3Z7jY2' with whitelisted URL patterns in this Google project. [https://support.google.com/firebase/answer/9021429] [https://support.google.com/firebase/answer/9021429])
</code>```

And this is my domain in dynamic links https://links.nanny-finder.app/links
So I have to allow other patterns here right?
What pattern should it be?

Body:
I was trying to generate short dynamic link in the app using this function here (and long dynamic link gives me the same error)

FirebaseDynamicLinks dynamicLinks = FirebaseDynamicLinks.instance;

  Future<String> builDynamicLinks(String? id, {bool isFamily = false}) async {

    final DynamicLinkParameters parameters = DynamicLinkParameters(
      // The Dynamic Link URI domain. You can view created URIs on your Firebase console
      uriPrefix: 'https://links.nanny-finder.app/links/',

      // The deep Link passed to your application which you can use to affect change
      link: Uri.parse(
          'https://links.nanny-finder.app/links/${isFamily ? "families" : "nannies"}?id=$id'),

      // Android application details needed for opening correct app on device/Play Store
      androidParameters: AndroidParameters(
          packageName: 'com.mickaelrobin.nannyfinderuae',
          fallbackUrl: playStore),

      // iOS application details needed for opening correct app on device/App Store
      iosParameters: IOSParameters(
          bundleId: 'com.mickaelrobin.nannyfinderuae', fallbackUrl: appStore),
    );

    final ShortDynamicLink shortDynamicLink =
        await dynamicLinks.buildShortLink(parameters);
    print(shortDynamicLink);

    return shortDynamicLink.shortUrl.toString();
  }

But I got this error:

FirebaseException ([firebase_dynamic_links/unknown] com.google.android.gms.common.api.ApiException: 400: We could not match param 'https://links.nanny-finder.app/links/nannies?id=GarmRWdyEgTRbFMfE3fnCp3Z7jY2' with whitelisted URL patterns in this Google project. [https://support.google.com/firebase/answer/9021429] [https://support.google.com/firebase/answer/9021429])

And this is my domain in dynamic links https://links.nanny-finder.app/links
So I have to allow other patterns here right?
What pattern should it be?


问:
Contribution of samples to each principal component in python
I have performed a PCA over a dataset with 12 features (columns) and 304 samples (rows) and have obtained 12 PCs of which the first 3-4 ones explain most of the variance. I need to know the importance of each sample for the first PCs, since my objective is to obtain a subset of the original dataframe containing only the samples that contributed the most.

The PCA is currently in this state:

```<code>import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import scale

data = pd.read_excel(route)
pca_pipe = make_pipeline(StandardScaler(), PCA())
pca_pipe.fit(data)

pca_model = pca_pipe.named_steps['pca']

pca_model.explained_variance_ratio_
array([0.67916285, 0.08388413, 0.07940955, 0.06278752, 0.02876627,
       0.02004363, 0.01342659, 0.0118064 , 0.00720231, 0.0060033 ,
       0.0043399 , 0.00316755])
</code>```

As it shows, the first 3-4 PC explain most of the variance, I need to know which samples contributed more to those PC

Body:
I have performed a PCA over a dataset with 12 features (columns) and 304 samples (rows) and have obtained 12 PCs of which the first 3-4 ones explain most of the variance. I need to know the importance of each sample for the first PCs, since my objective is to obtain a subset of the original dataframe containing only the samples that contributed the most.

The PCA is currently in this state:

import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import scale

data = pd.read_excel(route)
pca_pipe = make_pipeline(StandardScaler(), PCA())
pca_pipe.fit(data)

pca_model = pca_pipe.named_steps['pca']

pca_model.explained_variance_ratio_
array([0.67916285, 0.08388413, 0.07940955, 0.06278752, 0.02876627,
       0.02004363, 0.01342659, 0.0118064 , 0.00720231, 0.0060033 ,
       0.0043399 , 0.00316755])

As it shows, the first 3-4 PC explain most of the variance, I need to know which samples contributed more to those PC