问:
How to change tokenization (huggingface)?
In NER task we want to classification sentence tokens with using different approaches (BIO, for example). But we cant join any subtokens when tokenizer divides sentences stronger.

I would like to classificate 'weight 40.5 px' sentence with custom tokenization (by space in this example)
But after tokenization

```<code>tokenizer.convert_ids_to_tokens(tokenizer(['weight', '40.5', 'px'], is_split_into_words=True)['input_ids'])
</code>```

i had
['[CLS]', 'weight', '40', '.', '5', 'p', '##x', '[SEP]']
when '40.5' splitted into another tokens '40', '.', '5'. Its problem for me, because i want to classificate 3 tokens ('weight', '40.5', 'px'), but it not merge automaticaly, because '40', '.', '5' not looks like '40', '##.', '##5'.

What can i do to solve this problem?

Body:
In NER task we want to classification sentence tokens with using different approaches (BIO, for example). But we cant join any subtokens when tokenizer divides sentences stronger.

I would like to classificate 'weight 40.5 px' sentence with custom tokenization (by space in this example)
But after tokenization

tokenizer.convert_ids_to_tokens(tokenizer(['weight', '40.5', 'px'], is_split_into_words=True)['input_ids'])

i had
['[CLS]', 'weight', '40', '.', '5', 'p', '##x', '[SEP]']
when '40.5' splitted into another tokens '40', '.', '5'. Its problem for me, because i want to classificate 3 tokens ('weight', '40.5', 'px'), but it not merge automaticaly, because '40', '.', '5' not looks like '40', '##.', '##5'.

What can i do to solve this problem?


来源: stackexchange

问:
Auto increment loan counter in realtime firebase
I'm trying to build a REACT.JS Loan component that tracks down the payments of a loan from date A to date B.

I cannot figure out how to increment the counter automatically each month or every 30 days so I can show the users how many payments have been completed over the total payments.

so what can I base my counter on exactly ? or in other words how can I establish that the first month is the first payment, the second month is the second payment, the current payment is the current month payment etc...

This code below gets the start date and end date

then it calculates how many months there are in between, so I can later show the user that for example they have completed 1/6 payments ( 6 is the total number of payments which is also the total number of months )

```<code>const LoanItem = ({ item, index }) => {
  const per = (item.currentpayment * 100) / item.amount;

  const startDate = new Date(item.startdate);
  const endDate = new Date(item.enddate);

  const monthsTotal = endDate.getMonth() - startDate.getMonth() + 12 * (endDate.getFullYear() - startDate.getFullYear()) + 1;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to build a REACT.JS Loan component that tracks down the payments of a loan from date A to date B.

I cannot figure out how to increment the counter automatically each month or every 30 days so I can show the users how many payments have been completed over the total payments.

so what can I base my counter on exactly ? or in other words how can I establish that the first month is the first payment, the second month is the second payment, the current payment is the current month payment etc...

This code below gets the start date and end date

then it calculates how many months there are in between, so I can later show the user that for example they have completed 1/6 payments ( 6 is the total number of payments which is also the total number of months )

const LoanItem = ({ item, index }) => {
  const per = (item.currentpayment * 100) / item.amount;

  const startDate = new Date(item.startdate);
  const endDate = new Date(item.enddate);

  const monthsTotal = endDate.getMonth() - startDate.getMonth() + 12 * (endDate.getFullYear() - startDate.getFullYear()) + 1;


问:
Is it possible to make a 64 bit exe look like a 32 bit one?
I am trying to use a drm called truscont for my unity game and it currently only supports 32 bit exe so is it possible to make a 64 bit one look like 32 bit one.

Also I don't want to compile for 32 bit because of performance issues.

DRM Window

I haven't tried anything I don't even know where to start.


问:
Can Python be used to represent streamlines and equipotential lines graphically (Conformal mapping)
I found this problem on Schaum's Outline on Complex variables

Application of conformal mapping to fluid flow

I'm wondering if it is possible to do the graphical representation of the equipotential lines and streamlines using python.
I've done a bit of research and found that it can be done with matplotlib.

I've tried and this is what I've come up with so far mostly from help researching this site

```<code>import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm

#--- Constants ---#
nx = 5                         # nx: number of time steps in 'x'
ny = 5                         # ny: number of time steps in 'y'
dx = 1
dy = 0.5
U = 10.0

lower_x = 0.0
lower_y = 0.0

#-----------------#

XY = []

phi  = np.zeros((nx, ny))
psi  = np.zeros((nx, ny))

for j in range(0, ny):
    for i in range(0, nx):
        xi = i * dx + lower_x
        yi = j * dy + lower_y
        XY.append((xi, yi))
        #--  potential function  --#
        phi[i][j] = U * xi
        #--  stream function  --#
        psi[i][j] = U * yi

print("XY = ", XY, "\n\n")
print("Psi = ", psi)

#--- plotting part ---#
x = np.linspace(0.0, 10.0, nx)
y = np.linspace(0.0, 10.0, ny)
X, Y = np.meshgrid(x, y)

fig, ax = plt.subplots()
#cs = ax.contour(X, Y, phi, cmap=cm.hot)
#ax.clabel(cs, inline = 1, fontsize = 10)

cs_1 = ax.contour(X, Y, psi, cmap=cm.Blues)
ax.clabel(cs_1, inline = 1, fontsize = 10)

plt.show()
</code>```

I'm not very conversant with matplotlib but I would be glad if I could see how this is done so I could learn a thing or two. Thanks in advance.

Body:
I found this problem on Schaum's Outline on Complex variables

Application of conformal mapping to fluid flow

I'm wondering if it is possible to do the graphical representation of the equipotential lines and streamlines using python.
I've done a bit of research and found that it can be done with matplotlib.

I've tried and this is what I've come up with so far mostly from help researching this site

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm

#--- Constants ---#
nx = 5                         # nx: number of time steps in 'x'
ny = 5                         # ny: number of time steps in 'y'
dx = 1
dy = 0.5
U = 10.0

lower_x = 0.0
lower_y = 0.0

#-----------------#

XY = []

phi  = np.zeros((nx, ny))
psi  = np.zeros((nx, ny))

for j in range(0, ny):
    for i in range(0, nx):
        xi = i * dx + lower_x
        yi = j * dy + lower_y
        XY.append((xi, yi))
        #--  potential function  --#
        phi[i][j] = U * xi
        #--  stream function  --#
        psi[i][j] = U * yi

print("XY = ", XY, "\n\n")
print("Psi = ", psi)

#--- plotting part ---#
x = np.linspace(0.0, 10.0, nx)
y = np.linspace(0.0, 10.0, ny)
X, Y = np.meshgrid(x, y)

fig, ax = plt.subplots()
#cs = ax.contour(X, Y, phi, cmap=cm.hot)
#ax.clabel(cs, inline = 1, fontsize = 10)

cs_1 = ax.contour(X, Y, psi, cmap=cm.Blues)
ax.clabel(cs_1, inline = 1, fontsize = 10)

plt.show()

I'm not very conversant with matplotlib but I would be glad if I could see how this is done so I could learn a thing or two. Thanks in advance.


问:
How to handle many HTML links from one place (Pygal world map)
I am trying to make an interactable world map on Pygal, where if you click on a certain country you should be lead to a certain html site where there is information about the country. However, i do not wish to make a HTML site on each and every country as this would be very time consuming. Is there some other efficient way, where this would be possible?

My friend advised me to use an API, but I don't really know how to correctly use it and where to find it.


问:
Django, unable to filter all items under one or more categories attached to it using dynamic bootstrap 5 nav pills using many to many relationship
Given the files below am unable to filter all items relating to one category or more than one category.

Example:

let items = A, B, C, D

categories = 1, 2, 3, 4

items in category 1 = A and B

items in category 2 = C and D

category 3 and 4 are not having any items attached to them, they should return empty

Have a look at the files and kindly guide below

models.py

```<code>class Category(models.Model):
    name = models.CharField()

class Item(models.Model):
    name = models.CharField()
    category = models.ManyToManyField(Category)
</code>```

views.py

```<code>def filter_item(request):
    template = 'template.html'
    cat = Category.objects.all()
    context = {'cat': cat, }
    return render(request, template, context)
</code>```

template.html

```<code><ul class="nav nav-tabs" id="myTab" role="tablist">
    {% for c in cat %}
    <li class="nav-item" role="presentation">
        <button class="nav-link {% if  c.id == '{{ c.id }}' %} active {% endif %}" id="{{ c.name|slugify }}-tab" data-bs-toggle="tab" data-bs-target="#{{ c.name|slugify }}" type="button"
            role="tab" aria-controls="{{ c.name|slugify }}" aria-selected="true">{{ c.name }}</button>
    </li>
    {% endfor %}
</ul>
<div class="tab-content" id="myTabContent">
    {% for c in cat %}
    {% for i in c.item_set.all %}
    <div class="tab-pane fade {% if i.category.id == c.id %} show active {% endif %}" id="{{ i.name|slugify }}" role="tabpanel" aria-labelledby="{{ i.name|slugify }}-tab">{{ i.title }}</div>
    {% endfor %}
    {% endfor %}
</div>
</code>```

What i want to do

Allow users to add dynaminc categories ( would like to add dynamic sub categories too)

Allow users to add items and attach it to one or more than one category

Allow users to click between different categories and see related items in tabpanel using bootstrap nav pill

Allow the categories to be in a slide so that a user can slide through hidden categories

What have done and how it works

Have used {% if  c.id == '{{ c.id }} %}' to check is the id clicked is same had tried {% if  c.id == c.id %} only the tab not to work

The nav pill tabpanel only shows one item returned from each category being clicked despite having other items in it

I would like to develop something like this, make categories slide and have prev and next controls as shown here

plain bootstrap 5.html

```<code><ul class="nav nav-tabs" id="myTab" role="tablist">
  <li class="nav-item" role="presentation">
    <button class="nav-link active" id="home-tab" data-bs-toggle="tab" data-bs-target="#home" type="button" role="tab" aria-controls="home" aria-selected="true">Home</button>
  </li>
  <li class="nav-item" role="presentation">
    <button class="nav-link" id="profile-tab" data-bs-toggle="tab" data-bs-target="#profile" type="button" role="tab" aria-controls="profile" aria-selected="false">Profile</button>
  </li>
  <li class="nav-item" role="presentation">
    <button class="nav-link" id="contact-tab" data-bs-toggle="tab" data-bs-target="#contact" type="button" role="tab" aria-controls="contact" aria-selected="false">Contact</button>
  </li>
</ul>
<div class="tab-content" id="myTabContent">
  <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">...</div>
  <div class="tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">...</div>
  <div class="tab-pane fade" id="contact" role="tabpanel" aria-labelledby="contact-tab">...</div>
</div>
</code>```

Kindly note

How well can one add or remove active class in class="nav-link active"

Same to show and active in class="tab-pane fade show active"

Body:
Given the files below am unable to filter all items relating to one category or more than one category.

Example:

let items = A, B, C, D

categories = 1, 2, 3, 4

items in category 1 = A and B

items in category 2 = C and D

category 3 and 4 are not having any items attached to them, they should return empty

Have a look at the files and kindly guide below

models.py

class Category(models.Model):
    name = models.CharField()

class Item(models.Model):
    name = models.CharField()
    category = models.ManyToManyField(Category)

views.py

def filter_item(request):
    template = 'template.html'
    cat = Category.objects.all()
    context = {'cat': cat, }
    return render(request, template, context)

template.html

    {% for c in cat %}

        <button class="nav-link {% if  c.id == '{{ c.id }}' %} active {% endif %}" id="{{ c.name|slugify }}-tab" data-bs-toggle="tab" data-bs-target="#{{ c.name|slugify }}" type="button"
            role="tab" aria-controls="{{ c.name|slugify }}" aria-selected="true">{{ c.name }}</button>

    {% endfor %}

    {% for c in cat %}
    {% for i in c.item_set.all %}

{{ i.title }}

    {% endfor %}
    {% endfor %}

What i want to do

Allow users to add dynaminc categories ( would like to add dynamic sub categories too)

Allow users to add items and attach it to one or more than one category

Allow users to click between different categories and see related items in tabpanel using bootstrap nav pill

Allow the categories to be in a slide so that a user can slide through hidden categories

What have done and how it works

Have used {% if  c.id == '{{ c.id }} %}' to check is the id clicked is same had tried {% if  c.id == c.id %} only the tab not to work

The nav pill tabpanel only shows one item returned from each category being clicked despite having other items in it

I would like to develop something like this, make categories slide and have prev and next controls as shown here

plain bootstrap 5.html

    <button class="nav-link active" id="home-tab" data-bs-toggle="tab" data-bs-target="#home" type="button" role="tab" aria-controls="home" aria-selected="true">Home</button>

    <button class="nav-link" id="profile-tab" data-bs-toggle="tab" data-bs-target="#profile" type="button" role="tab" aria-controls="profile" aria-selected="false">Profile</button>

    <button class="nav-link" id="contact-tab" data-bs-toggle="tab" data-bs-target="#contact" type="button" role="tab" aria-controls="contact" aria-selected="false">Contact</button>

...

...

...

Kindly note

How well can one add or remove active class in class="nav-link active"

Same to show and active in class="tab-pane fade show active"


问:
C#/ExtJs SharpZilLib generate a corrupted zip
I'm using the library SharpzipLib to create a zip file from files in a memory stream.
The issue is that the generated zip seems to be corrupted and I can't open it.

```<code>        MemoryStream outputMemStream = new MemoryStream();
        ZipOutputStream zipStream = new ZipOutputStream(outputMemStream);

        zipStream.SetLevel(3); //0-9, 9 being the highest level of compression

        // loops through the PDFs I need to create
        foreach (var file in files)
        {
            var newEntry = new ZipEntry(file.FileName);
            newEntry.DateTime = DateTime.Now;

            zipStream.PutNextEntry(newEntry);

            byte[] bytes = file.Content;

            MemoryStream inStream = new MemoryStream(bytes);
            StreamUtils.Copy(inStream, zipStream, new byte[4096]);
            inStream.Close();
            zipStream.CloseEntry();
        }

        zipStream.IsStreamOwner = false;    // False stops the Close also Closing the underlying stream.
        zipStream.Close();          // Must finish the ZipOutputStream before using outputMemStream.

        outputMemStream.Position = 0;

        stream.Seek(0, SeekOrigin.Begin);
        var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StreamContent(stream)
        };

        httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
        httpResponseMessage.Content.Headers.ContentLength = stream.Length;
        httpResponseMessage.ContentDisposition =
                new ContentDispositionHeaderValue(asAttachment ? DownloadAttachment : InlineAttachment)
                {
                    FileName = fileName,
                    Name = fileCaption
                };
</code>```

Files contain a list of objects with a byte[] from a pdf and a name.
If I download the files individually they are fine.

TargetfileName looks like this: testFile-2023-01-02-18-02-23.zip

I tried with asAttachement as true and false.

Here's how the file is downloaded on the front end :

```<code>    var zipName = "TestFiles-" + new Date() + ".zip";
    let viewModel = this.getViewModel(),
        url = "localhost:10000/Documents/File?" + "ids=" + docIds.join(",") + "&fileName=" + zipName;
    Ext.Ajax.request({
        url: url,
        method: 'GET',
        useDefaultXhrHeader: false,
        withCredentials: true,

        success: function(response, options) {
            if(response.status == 200) {
                var a = document.createElement("a");
                document.body.appendChild(a);
                a.style = "display: none";
                var blob = new Blob([response.responseBytes || response.responseXml || response.responseText], {type: 'octet/stream'});
                var windowUrl = window.URL.createObjectURL(blob);
                a.href = windowUrl;
                a.download = zipName;
                a.click();
            }
        }
    });
</code>```

It's ExtJS but I did a simple ajax request.
I don't know if I did something wrong in the back-end or the front end.

Body:
I'm using the library SharpzipLib to create a zip file from files in a memory stream.
The issue is that the generated zip seems to be corrupted and I can't open it.

        MemoryStream outputMemStream = new MemoryStream();
        ZipOutputStream zipStream = new ZipOutputStream(outputMemStream);

        zipStream.SetLevel(3); //0-9, 9 being the highest level of compression

        // loops through the PDFs I need to create
        foreach (var file in files)
        {
            var newEntry = new ZipEntry(file.FileName);
            newEntry.DateTime = DateTime.Now;

            zipStream.PutNextEntry(newEntry);

            byte[] bytes = file.Content;

            MemoryStream inStream = new MemoryStream(bytes);
            StreamUtils.Copy(inStream, zipStream, new byte[4096]);
            inStream.Close();
            zipStream.CloseEntry();
        }

        zipStream.IsStreamOwner = false;    // False stops the Close also Closing the underlying stream.
        zipStream.Close();          // Must finish the ZipOutputStream before using outputMemStream.

        outputMemStream.Position = 0;

        stream.Seek(0, SeekOrigin.Begin);
        var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StreamContent(stream)
        };

        httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
        httpResponseMessage.Content.Headers.ContentLength = stream.Length;
        httpResponseMessage.ContentDisposition =
                new ContentDispositionHeaderValue(asAttachment ? DownloadAttachment : InlineAttachment)
                {
                    FileName = fileName,
                    Name = fileCaption
                };

Files contain a list of objects with a byte[] from a pdf and a name.
If I download the files individually they are fine.

TargetfileName looks like this: testFile-2023-01-02-18-02-23.zip

I tried with asAttachement as true and false.

Here's how the file is downloaded on the front end :

    var zipName = "TestFiles-" + new Date() + ".zip";
    let viewModel = this.getViewModel(),
        url = "localhost:10000/Documents/File?" + "ids=" + docIds.join(",") + "&fileName=" + zipName;
    Ext.Ajax.request({
        url: url,
        method: 'GET',
        useDefaultXhrHeader: false,
        withCredentials: true,

        success: function(response, options) {
            if(response.status == 200) {
                var a = document.createElement("a");
                document.body.appendChild(a);
                a.style = "display: none";
                var blob = new Blob([response.responseBytes || response.responseXml || response.responseText], {type: 'octet/stream'});
                var windowUrl = window.URL.createObjectURL(blob);
                a.href = windowUrl;
                a.download = zipName;
                a.click();
            }
        }
    });

It's ExtJS but I did a simple ajax request.
I don't know if I did something wrong in the back-end or the front end.


问:
Laravel 9 gradually slow down rate limiting for persistent attempts when limit reached
I'm working inside my Laravel 9 API. I've set up a new RateLimiter called "sending" which by default is limited to 20 requests per minute. What I'm trying to do, is if this rate limit is reached and additional requests continue to come in, I need to delay the rate limit  by the number of additional requests.

So if I hit the rate limit, I should be temporarily blocked for 1 minute, but if I hit the rate limit and make X number of requests, for example, 5 requests over the rate limit, I should now be temporarily blocked for 5 minutes.

My PHP:

/**
 * Configure the rate limiters for the application.
 *
 * @return void
 */
protected function configureRateLimiting()
{
    RateLimiter::for('api', function (Request $request) {
        return Limit::perMinute(150)->by($request->user()?->id ?: $request->ip());
    });

    RateLimiter::for('sending', function (Request $request) {
        return Limit::perMinute(20)->by($request->user()?->id ?: $request->ip());
    });
}
```


问:
VectorNav 100 trransfer data to another esp32
I have vn100 (VectorNav 100 IMU), 2 esp32 wroom with wifi/bt.
At the end, I want to get the data from vn100 and transfer it to esp32 that is not connected to the vn100.So what is needed:

Vn100 connected with wires to esp32 wroom with wifi/bt, lets name it esp1.

get the data from vn100 to esp1.

transfer the data from esp1 to another esp32 wroom with wifi/bt, lets name it esp2.
The connection between esp1 and esp2 is wireless. Using wifi(One esp as access point and the other connects to it, further in code).
I have connected the vn100 to esp1 and got the data correctly and all good.
Now im trying to transfer it to esp2 but its not working.

Each packet that comes from vn100 starts with byte 0xFA that indicates start of a packet from vn100.
when i make esp1 as a Access point station, the packets that come from vn100 stops coming to esp1 (no more bytee 0xFA so no more packets coming from vn100).As a result the data from vn100 stops its stream.
I need help with this part.

*I tried to connect esp1 and esp2 with wifi and transfer static data such as string/random numbers (without taking the data from vn100) and it worked fine.

Code for esp1:

```<code>#include <HardwareSerial.h>
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
const char *ssid = "ssid";
const char *password = "password";

// Function declarations
void read_imu_data(void);
void check_sync_byte(void);
unsigned short calculate_imu_crc(byte data[], unsigned int length);

// Union functions for byte to float conversions
// IMU sends data as bytes, the union functions are used to convert
// these data into other data types

//first 4 bytes are the header of the output binary message packets on the serial interface.
// next 36 bytes are the payload( the data we want )
// last 2 bytes are the crc for the checksum

// 1st byte is sync(page 35 in vn manual)
// 2nd byte is Groups(page 35 in vn manual), we choose group 01
//3rd and 4th byte is group fields (page 35 in vn manual)

// Attitude data // 12 bytes
union {float f; byte b[4];} yaw; // 4 bytes
union {float f; byte b[4];} pitch;// 4 bytes
union {float f; byte b[4];} roll;// 4 bytes

// Angular rates // 12 bytes
union {float f; byte b[4];} W_x;// 4 bytes
union {float f; byte b[4];} W_y;// 4 bytes
union {float f; byte b[4];} W_z;// 4 bytes

// Acceleration // 12 bytes
union {float f; byte b[4];} a_x;// 4 bytes
union {float f; byte b[4];} a_y;// 4 bytes
union {float f; byte b[4];} a_z;// 4 bytes

float prev_y = 0.0;
float prev_v_y = 0.0;
float y_acc = 0.0;
// new update
int distance_to_board = 50;//1m
int pos_y = 0.0;//in cm
int pos_z = 0.0;//in cm
// Checksum // 2 bytes
union {unsigned short s; byte b[2];} checksum;

// Parameters
bool imu_sync_detected = false;  // check if the sync byte (0xFA) is detected
byte in[100];  // array to save data sent from the IMU

HardwareSerial EspResevier(2);
AsyncWebServer server(80);

String readlocation() {

  return (String(pos_y) + "," + String(pos_z));
}

void setup() {

  // Start Serial for printing data to the Serial Monitor
  Serial.begin(115200);
  EspResevier.begin(115200, SERIAL_8N1, 21, 22 );//RX ,TX
  EspResevier.setRxBufferSize(1024);
  //delay(10);

  EspResevier.println("$VNASY,0*XX\r\n");//Pause Async Outputs
  EspResevier.print("$VNWRG,06,0*XX\r\n"); //write register command
  EspResevier.print("$VNWRG,75,2,8,01,0128*XX\r\n");
  EspResevier.print("$VNTAR*5F\r\n");
//  EspResevier.println("$VNCMD*XX\r\n"); //open cn cmd
//  EspResevier.println("system save\r\n");
//  EspResevier.println("exit\r\n");
  EspResevier.println("$VNASY,1*XX\r\n");// Resume Async Outputs

//  delay (1000);
    // Setting the ESP as an access point
   Serial.println("Setting AP (Access Point)…");
  WiFi.softAP(ssid,password);
  Serial.println(WiFi.softAP(ssid, password) ? "Ready" : "Failed!");
  IPAddress IP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(IP);

    server.on("/location", HTTP_GET, [](AsyncWebServerRequest *request){
   request->send_P(200, "text/plain", readlocation().c_str());
  });

    // Start server
  server.begin();
  delay (1000);
  Serial.println("FINISHED SETUP");

}

unsigned long timer = 0;

void loop() {
    imu_sync_detected = false;
   // Check if new IMU data is available
  if (EspResevier.available()){
    //Serial.println(" THERE IS AVAILABE!");
    check_sync_byte();
  }

  // If sync byte is detected, read the rest of the data
  if (imu_sync_detected) {
    //Serial.println(" READING!");
    read_imu_data();
  }
  delay(100);
}

// Check for the sync byte (0xFA)
void check_sync_byte(void) {
  for (int i = 0; i < 6; i++) {
    if (EspResevier.available()==0){
      break;
    }
    EspResevier.readBytes(in, 1); // reads 1 byte from EspResevier (IMU) and puts it in "in" array.
    if (in[0] == 0xFA) {
      //Serial.println("FOUND SYNC BYTE");
      imu_sync_detected = true;
      break;
    }
  }
}

// Read the IMU bytes
void read_imu_data(void) {
  if (EspResevier.available()>=41){
  EspResevier.readBytes(in, 41);
  checksum.b[0] = in[40];
  checksum.b[1] = in[39];

  if (calculate_imu_crc(in, 39) == checksum.s) {
    for (int i = 0; i < 4; i++) {
      yaw.b[i] = in[3 + i];
      pitch.b[i] = in[7 + i];
      roll.b[i] = in[11 + i];
      W_x.b[i] = in[15 + i];
      W_y.b[i] = in[19 + i];
      W_z.b[i] = in[23 + i];
      a_x.b[i] = in[27 + i];
      a_y.b[i] = in[31 + i];
      a_z.b[i] = in[35 + i];
    }

    // calculating y axe movement
    int delta_y = 0;
    delta_y = (tan(0.0174533*yaw.f) * distance_to_board) - pos_y;
    pos_y += delta_y;

    // calculating z axe movement
    int delta_z = 0;
    delta_z = (tan(0.0174533*pitch.f) * distance_to_board) - pos_z;
    pos_z += delta_z;
    Serial.println(String(pos_y) + "," + String(pos_z));//z
    }
  }
}

// Calculate the 16-bit CRC for the given ASCII or binary message.
unsigned short calculate_imu_crc(byte data[], unsigned int length)
{
  unsigned int i;
  unsigned short crc = 0;
  for(i=0; i<length; i++){
    crc = (byte)(crc >> 8) | (crc << 8);
    crc ^= data[i];
    crc ^= (byte)(crc & 0xff) >> 4;
    crc ^= crc << 12;
    crc ^= (crc & 0x00ff) << 5;
  }
//  Serial.print("crc : ");
//  Serial.println(crc);
  return crc;
}

</code>```

code for esp2:

```<code>#include <WiFi.h>
#include <HTTPClient.h>
const char *ssid = "ssid";
const char *password = "password";

//Your IP address or domain name with URL path
const char* serverNamePres = "http://192.168.4.1/location";

#include <Wire.h>

String location;

void setup() {
  Serial.begin(115200);

  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
     // Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED ){
      location = httpGETRequest(serverNamePres);
      Serial.println(" Location: " + location );
    }
    else {
      Serial.println("WiFi Disconnected");
    }
  delay(100);
}

String httpGETRequest(const char* serverName) {
  WiFiClient client;
  HTTPClient http;

  // Your Domain name with URL path or IP address with path
  http.begin(client, serverName);

  // Send HTTP POST request
  int httpResponseCode = http.GET();

  String payload = "--";

  if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    payload = http.getString();
  }
  else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }
  // Free resources
  http.end();

  return payload;
}

</code>```

in the code you can see 2 files :

File for esp1 which is connected with wires to the vn100. Esp1 receives the data and save it in 2 variables pos_y and pos_z which i want to send to esp2. Esp1 is set as a access point so that esp2 can connect to it.

File for esp2 which is connected wirelessly to esp1.

I need help with fixing this data transfer problem.Or if anyone can point to a problematic point in the connection between these 3 devices.
Thanks

Body:
I have vn100 (VectorNav 100 IMU), 2 esp32 wroom with wifi/bt.
At the end, I want to get the data from vn100 and transfer it to esp32 that is not connected to the vn100.So what is needed:

Vn100 connected with wires to esp32 wroom with wifi/bt, lets name it esp1.

get the data from vn100 to esp1.

transfer the data from esp1 to another esp32 wroom with wifi/bt, lets name it esp2.
The connection between esp1 and esp2 is wireless. Using wifi(One esp as access point and the other connects to it, further in code).
I have connected the vn100 to esp1 and got the data correctly and all good.
Now im trying to transfer it to esp2 but its not working.

Each packet that comes from vn100 starts with byte 0xFA that indicates start of a packet from vn100.
when i make esp1 as a Access point station, the packets that come from vn100 stops coming to esp1 (no more bytee 0xFA so no more packets coming from vn100).As a result the data from vn100 stops its stream.
I need help with this part.

*I tried to connect esp1 and esp2 with wifi and transfer static data such as string/random numbers (without taking the data from vn100) and it worked fine.

Code for esp1:

#include <HardwareSerial.h>
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
const char *ssid = "ssid";
const char *password = "password";

// Function declarations
void read_imu_data(void);
void check_sync_byte(void);
unsigned short calculate_imu_crc(byte data[], unsigned int length);

// Union functions for byte to float conversions
// IMU sends data as bytes, the union functions are used to convert
// these data into other data types

//first 4 bytes are the header of the output binary message packets on the serial interface.
// next 36 bytes are the payload( the data we want )
// last 2 bytes are the crc for the checksum

// 1st byte is sync(page 35 in vn manual)
// 2nd byte is Groups(page 35 in vn manual), we choose group 01
//3rd and 4th byte is group fields (page 35 in vn manual)

// Attitude data // 12 bytes
union {float f; byte b[4];} yaw; // 4 bytes
union {float f; byte b[4];} pitch;// 4 bytes
union {float f; byte b[4];} roll;// 4 bytes

// Angular rates // 12 bytes
union {float f; byte b[4];} W_x;// 4 bytes
union {float f; byte b[4];} W_y;// 4 bytes
union {float f; byte b[4];} W_z;// 4 bytes

// Acceleration // 12 bytes
union {float f; byte b[4];} a_x;// 4 bytes
union {float f; byte b[4];} a_y;// 4 bytes
union {float f; byte b[4];} a_z;// 4 bytes

float prev_y = 0.0;
float prev_v_y = 0.0;
float y_acc = 0.0;
// new update
int distance_to_board = 50;//1m
int pos_y = 0.0;//in cm
int pos_z = 0.0;//in cm
// Checksum // 2 bytes
union {unsigned short s; byte b[2];} checksum;

// Parameters
bool imu_sync_detected = false;  // check if the sync byte (0xFA) is detected
byte in[100];  // array to save data sent from the IMU

HardwareSerial EspResevier(2);
AsyncWebServer server(80);

String readlocation() {

  return (String(pos_y) + "," + String(pos_z));
}

void setup() {

  // Start Serial for printing data to the Serial Monitor
  Serial.begin(115200);
  EspResevier.begin(115200, SERIAL_8N1, 21, 22 );//RX ,TX
  EspResevier.setRxBufferSize(1024);
  //delay(10);

  EspResevier.println("$VNASY,0*XX\r\n");//Pause Async Outputs
  EspResevier.print("$VNWRG,06,0*XX\r\n"); //write register command
  EspResevier.print("$VNWRG,75,2,8,01,0128*XX\r\n");
  EspResevier.print("$VNTAR*5F\r\n");
//  EspResevier.println("$VNCMD*XX\r\n"); //open cn cmd
//  EspResevier.println("system save\r\n");
//  EspResevier.println("exit\r\n");
  EspResevier.println("$VNASY,1*XX\r\n");// Resume Async Outputs

//  delay (1000);
    // Setting the ESP as an access point
   Serial.println("Setting AP (Access Point)…");
  WiFi.softAP(ssid,password);
  Serial.println(WiFi.softAP(ssid, password) ? "Ready" : "Failed!");
  IPAddress IP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(IP);

    server.on("/location", HTTP_GET, [](AsyncWebServerRequest *request){
   request->send_P(200, "text/plain", readlocation().c_str());
  });

    // Start server
  server.begin();
  delay (1000);
  Serial.println("FINISHED SETUP");

}

unsigned long timer = 0;

void loop() {
    imu_sync_detected = false;
   // Check if new IMU data is available
  if (EspResevier.available()){
    //Serial.println(" THERE IS AVAILABE!");
    check_sync_byte();
  }

  // If sync byte is detected, read the rest of the data
  if (imu_sync_detected) {
    //Serial.println(" READING!");
    read_imu_data();
  }
  delay(100);
}

// Check for the sync byte (0xFA)
void check_sync_byte(void) {
  for (int i = 0; i < 6; i++) {
    if (EspResevier.available()==0){
      break;
    }
    EspResevier.readBytes(in, 1); // reads 1 byte from EspResevier (IMU) and puts it in "in" array.
    if (in[0] == 0xFA) {
      //Serial.println("FOUND SYNC BYTE");
      imu_sync_detected = true;
      break;
    }
  }
}

// Read the IMU bytes
void read_imu_data(void) {
  if (EspResevier.available()>=41){
  EspResevier.readBytes(in, 41);
  checksum.b[0] = in[40];
  checksum.b[1] = in[39];

  if (calculate_imu_crc(in, 39) == checksum.s) {
    for (int i = 0; i < 4; i++) {
      yaw.b[i] = in[3 + i];
      pitch.b[i] = in[7 + i];
      roll.b[i] = in[11 + i];
      W_x.b[i] = in[15 + i];
      W_y.b[i] = in[19 + i];
      W_z.b[i] = in[23 + i];
      a_x.b[i] = in[27 + i];
      a_y.b[i] = in[31 + i];
      a_z.b[i] = in[35 + i];
    }

    // calculating y axe movement
    int delta_y = 0;
    delta_y = (tan(0.0174533*yaw.f) * distance_to_board) - pos_y;
    pos_y += delta_y;

    // calculating z axe movement
    int delta_z = 0;
    delta_z = (tan(0.0174533*pitch.f) * distance_to_board) - pos_z;
    pos_z += delta_z;
    Serial.println(String(pos_y) + "," + String(pos_z));//z
    }
  }
}

// Calculate the 16-bit CRC for the given ASCII or binary message.
unsigned short calculate_imu_crc(byte data[], unsigned int length)
{
  unsigned int i;
  unsigned short crc = 0;
  for(i=0; i<length; i++){
    crc = (byte)(crc >> 8) | (crc << 8);
    crc ^= data[i];
    crc ^= (byte)(crc & 0xff) >> 4;
    crc ^= crc << 12;
    crc ^= (crc & 0x00ff) << 5;
  }
//  Serial.print("crc : ");
//  Serial.println(crc);
  return crc;
}

code for esp2:

#include <WiFi.h>
#include <HTTPClient.h>
const char *ssid = "ssid";
const char *password = "password";

//Your IP address or domain name with URL path
const char* serverNamePres = "http://192.168.4.1/location";

#include <Wire.h>

String location;

void setup() {
  Serial.begin(115200);

  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
     // Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED ){
      location = httpGETRequest(serverNamePres);
      Serial.println(" Location: " + location );
    }
    else {
      Serial.println("WiFi Disconnected");
    }
  delay(100);
}

String httpGETRequest(const char* serverName) {
  WiFiClient client;
  HTTPClient http;

  // Your Domain name with URL path or IP address with path
  http.begin(client, serverName);

  // Send HTTP POST request
  int httpResponseCode = http.GET();

  String payload = "--";

  if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    payload = http.getString();
  }
  else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }
  // Free resources
  http.end();

  return payload;
}

in the code you can see 2 files :

File for esp1 which is connected with wires to the vn100. Esp1 receives the data and save it in 2 variables pos_y and pos_z which i want to send to esp2. Esp1 is set as a access point so that esp2 can connect to it.

File for esp2 which is connected wirelessly to esp1.

I need help with fixing this data transfer problem.Or if anyone can point to a problematic point in the connection between these 3 devices.
Thanks


问:
How can I Convert 'pyspark.dbutils.DBUtils' to 'dbruntime.dbutils.DBUtils' in Databricks
I am working on a project where we have some helper functions that uses dbutils and they were initially used as notebook but now they got converted to python modules. Now I cannot access those methods as they cannot find dbutils.

I searched for ways of using dbutils in a way that I can call that from notebook as well as python module and I got some stack overflow answers that suggest using below methods:

```<code>def get_db_utils(spark):

      dbutils = None

      if spark.conf.get("spark.databricks.service.client.enabled") == "true":
        print("Inside IDE Dbutils")
        from pyspark.dbutils import DBUtils
        dbutils = DBUtils(spark)

      else:
        print("Inside Notebook Dbutils")
        import IPython
        dbutils = IPython.get_ipython().user_ns["dbutils"]

      return dbutils

def get_dbutils(spark):
  from pyspark.dbutils import DBUtils
  return DBUtils(spark)
</code>```

Whenever I check the type of the dbutils reference variable after calling these functions are as below:

```<code>dbutils1 = get_db_utils(spark)
dbutils2 = get_dbutils(spark)
print(type(dbutils1))
print(type(dbutils2))
</code>```

It gives the output as <class 'pyspark.dbutils.DBUtils'> but whereas when print the type of the actual dbutils I get the output as <class 'dbruntime.dbutils.DBUtils'>

Now when I try to read the secret value using actual dbutils it runs and works properly.
But whenever I used dbutils1 or dbutils2

```<code>secret_value = dbutils1.secrets.get(scope=SECRET_SCOPE, key="Key")
</code>```

it gives me below error:

```<code>IllegalArgumentException: Invalid URI host: null (authority: null)
</code>```

Is there any way I can get around this error?

Body:
I am working on a project where we have some helper functions that uses dbutils and they were initially used as notebook but now they got converted to python modules. Now I cannot access those methods as they cannot find dbutils.

I searched for ways of using dbutils in a way that I can call that from notebook as well as python module and I got some stack overflow answers that suggest using below methods:

def get_db_utils(spark):

      dbutils = None

      if spark.conf.get("spark.databricks.service.client.enabled") == "true":
        print("Inside IDE Dbutils")
        from pyspark.dbutils import DBUtils
        dbutils = DBUtils(spark)

      else:
        print("Inside Notebook Dbutils")
        import IPython
        dbutils = IPython.get_ipython().user_ns["dbutils"]

      return dbutils

def get_dbutils(spark):
  from pyspark.dbutils import DBUtils
  return DBUtils(spark)

Whenever I check the type of the dbutils reference variable after calling these functions are as below:

dbutils1 = get_db_utils(spark)
dbutils2 = get_dbutils(spark)
print(type(dbutils1))
print(type(dbutils2))

It gives the output as <class 'pyspark.dbutils.DBUtils'> but whereas when print the type of the actual dbutils I get the output as <class 'dbruntime.dbutils.DBUtils'>

Now when I try to read the secret value using actual dbutils it runs and works properly.
But whenever I used dbutils1 or dbutils2

secret_value = dbutils1.secrets.get(scope=SECRET_SCOPE, key="Key")

it gives me below error:

IllegalArgumentException: Invalid URI host: null (authority: null)

Is there any way I can get around this error?


问:
Multiple map functions and returning HTML
I'm running into issues with multiple map functions and displaying data.  I believe I'm missing some returns in the appropriate spots, but can't find a good example online.  Any help is appreciated. Thanks!</p>
```<code>Object.keys(patternData).map((pattern) => {
    if (patternData[pattern]['Matches'] && Object.keys(patternData[pattern] ['Matches']).length !== 0) {
        Object.keys(patternData[pattern]['Matches']).map((matchSymbol) =>
            <p> {matchSymbol} </p>
        )
    }
})
</code>```

Body:
I'm running into issues with multiple map functions and displaying data.  I believe I'm missing some returns in the appropriate spots, but can't find a good example online.  Any help is appreciated. Thanks!

Object.keys(patternData).map((pattern) => {
    if (patternData[pattern]['Matches'] && Object.keys(patternData[pattern] ['Matches']).length !== 0) {
        Object.keys(patternData[pattern]['Matches']).map((matchSymbol) =>

 {matchSymbol}

        )
    }
})


问:
Typescript baseUrl not resolving in build folder
I have a simple Typescript node app that works in dev mode but when I run a build, it doesn't seem to convert the baseUrl and paths correctly.

// index.ts

import config from "@/config"; // this lives in `src/config.ts`

console.log("config:", config)
```
<p>My tsconfig is as follows:</p>
<pre class="lang-json prettyprint-override"><code>{
  "compilerOptions": {
    "skipLibCheck": true,
    "target": "es2021",
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "module": "CommonJS",
    "moduleResolution": "node",
    "strict": false,
    "outDir": "dist",
    "baseUrl": "./src",
    "paths": {
      "@/*": ["*"]
    }
  },
  "include": ["src/**/*", "integration/**/*", "src/types.d.ts", "./global.d.ts"]
}
</code>```

I can then run a successful npm run build but then running npm run start throws an error: Error: Cannot find module '@/config'. When I check the build file, it is still showing the imports / requires with @ in them like so:

```<code>"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const config_1 = __importDefault(require("@/config")); // I believe this should be the relative path
console.log("config:", config_1.default);
</code>```

My NPM scripts are as follows:

{
  "scripts": {
    "build": "NODE_ENV=production && tsc --project tsconfig.build.json",
    "dev": "nodemon -r tsconfig-paths/register -r dotenv/config --watch 'src/**/*.ts' --exec 'ts-node' src/index.ts",
    "start": "NODE_ENV=production node dist/index.js"
  }
}
```

How do I configure Typescript to convert my imports to replace the baseUrl paths to the correct ones that Javascript will understand?

Body:
I have a simple Typescript node app that works in dev mode but when I run a build, it doesn't seem to convert the baseUrl and paths correctly.

// index.ts

import config from "@/config"; // this lives in `src/config.ts`

console.log("config:", config)

My tsconfig is as follows:

{
  "compilerOptions": {
    "skipLibCheck": true,
    "target": "es2021",
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "module": "CommonJS",
    "moduleResolution": "node",
    "strict": false,
    "outDir": "dist",
    "baseUrl": "./src",
    "paths": {
      "@/*": ["*"]
    }
  },
  "include": ["src/**/*", "integration/**/*", "src/types.d.ts", "./global.d.ts"]
}

I can then run a successful npm run build but then running npm run start throws an error: Error: Cannot find module '@/config'. When I check the build file, it is still showing the imports / requires with @ in them like so:

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const config_1 = __importDefault(require("@/config")); // I believe this should be the relative path
console.log("config:", config_1.default);

My NPM scripts are as follows:

{
  "scripts": {
    "build": "NODE_ENV=production && tsc --project tsconfig.build.json",
    "dev": "nodemon -r tsconfig-paths/register -r dotenv/config --watch 'src/**/*.ts' --exec 'ts-node' src/index.ts",
    "start": "NODE_ENV=production node dist/index.js"
  }
}

How do I configure Typescript to convert my imports to replace the baseUrl paths to the correct ones that Javascript will understand?


问:
best practice for changing GameObject behaviour between parents?
I have a game object that i need to move around in the scene.

Every time the game object is under a different parent it should behave differently in just one little aspect of its existance.

For example, let say i have a dog, when it is under a kid parent, the dog should play.

If the dog game object is move to be under the adult parent, it should bark.  etc...

My solution at first was to use if-else and check under which parent the dog is being used.

And by knowing the parent i can invoke the correct method of dog action.

But that approach is very ugly, and not very scalable.

I would like to maybe do something more polymorphic, and maybe create multiple dog classes, one for barking, one for playing, etc, and than somehow instantiate a new game object with different script every time the owner of the dog changes.

What is the best practice for such a thing?

No need to mention that i have many game objects that are switching their respective parents so i need a systematic solution.

Thank yous


问:
Undefined after console are homepage to see if we getting correct the data in inspect element [Solved]
The detail of the problem is that I'm not getting the data we expected within our code. We have set up the following to see within our project folder.

Within webpack.config.js we set up resolve.alias in the webpack configuration, so we can include it in the resolve object of the webpack config file.

This is the file:

```<code>module.exports = {
  // other webpack config options
  resolve: {
    alias: {
      // Create an alias for the queries folder
      queries: path.resolve(__dirname, 'src/queries'),
    },
  },
};

</code>```

This is what are path name will look like:

```<code>import { homeQuery } from "queries/navigation/homeLinks";
</code>```

Created a webpack.config.js.

Console.log are data of homeData and HomeData.homelink.

Tested the query within GraphQL Playground in Hygraph.

From there I checked the console in the browser.

I have found out we are not getting the query in our body that we want but we have tested the query within GraphQL Playground. We have found out that we correctly getting the correct query that we want to get into our data within console.log.

This is a query for the homepage:

```<code>import { gql } from "@apollo/client";

export const homeQuery = gql`
    query homeLinks {
        pages(
            where: {id: "clbzl7ovpe64d0ak5qh7o2p8f", slug: "Home"}
            stage: PUBLISHED
            locales: en
        ) {
            id
            slug
            title
        }
    }`
;
</code>```

This where we console are data for the homepage:

```<code> console.log(homeData && homeData?.homeLink?.pages);
 console.log(homeData)
</code>```
```<code>import React from 'react';
import '../assets/style/navigation.css';
import { useQuery } from '@apollo/client';
import { BrowserRouter as Router, Link } from 'react-router-dom';

import { homeQuery } from "../queries/navigation/homeLinks";

import { logoassetsQuery } from "../queries/navigation/logoLinks";

export default function App() {

  const { loading: logoAssetsLoading, error: logoassetsData } = useQuery(logoassetsQuery);

  //This is query for the pages.
  const { loading: homeLoading, error: homeError, data: homeData } = useQuery(homeQuery);

  //This is for front-end error message.
  if (logoAssetsLoading) return <p>Loading Logo Assets...</p>;
  if (homeLoading) return <p>Loading... this page links.</p>
  if (homeError) return <p>Error :( this page don't work.</p>;

  // Debugging step 1: Check the value of data.navigation
  console.log(homeData && homeData.homeLinks)
  console.log(homeData)

  // Debugging step 2: Check the value of data
  //console.log(data);

  return (
    <div className='navigation'>
      <div className='full_width_container'>
        <div className='wrapper'>
          <Router>
              <React.Fragment>
                  <nav>
                      <div className='nav_groups logo'>
                          {homeData && homeData?.homeLinks?.pages && homeData?.homeLinks?.page(link => (
                              <li key={link?.id}>
                                <Link to={`/${link?.slug}`}>
                                  <img src={logoassetsData?.logoAssets} alt='main logo'/>
                                </Link>
                              </li>
                          ))}
                      </div>
                  </nav>
              </React.Fragment>
          </Router>
      </div>
    </div>
  </div>
  );
}

</code>```

Body:
The detail of the problem is that I'm not getting the data we expected within our code. We have set up the following to see within our project folder.

Within webpack.config.js we set up resolve.alias in the webpack configuration, so we can include it in the resolve object of the webpack config file.

This is the file:

module.exports = {
  // other webpack config options
  resolve: {
    alias: {
      // Create an alias for the queries folder
      queries: path.resolve(__dirname, 'src/queries'),
    },
  },
};

This is what are path name will look like:

import { homeQuery } from "queries/navigation/homeLinks";

Created a webpack.config.js.

Console.log are data of homeData and HomeData.homelink.

Tested the query within GraphQL Playground in Hygraph.

From there I checked the console in the browser.

I have found out we are not getting the query in our body that we want but we have tested the query within GraphQL Playground. We have found out that we correctly getting the correct query that we want to get into our data within console.log.

This is a query for the homepage:

import { gql } from "@apollo/client";

export const homeQuery = gql`
    query homeLinks {
        pages(
            where: {id: "clbzl7ovpe64d0ak5qh7o2p8f", slug: "Home"}
            stage: PUBLISHED
            locales: en
        ) {
            id
            slug
            title
        }
    }`
;

This where we console are data for the homepage:

 console.log(homeData && homeData?.homeLink?.pages);
 console.log(homeData)

import React from 'react';
import '../assets/style/navigation.css';
import { useQuery } from '@apollo/client';
import { BrowserRouter as Router, Link } from 'react-router-dom';

import { homeQuery } from "../queries/navigation/homeLinks";

import { logoassetsQuery } from "../queries/navigation/logoLinks";

export default function App() {

  const { loading: logoAssetsLoading, error: logoassetsData } = useQuery(logoassetsQuery);

  //This is query for the pages.
  const { loading: homeLoading, error: homeError, data: homeData } = useQuery(homeQuery);

  //This is for front-end error message.
  if (logoAssetsLoading) return
Loading Logo Assets...
;
  if (homeLoading) return
Loading... this page links.

  if (homeError) return
Error :( this page don't work.
;

  // Debugging step 1: Check the value of data.navigation
  console.log(homeData && homeData.homeLinks)
  console.log(homeData)

  // Debugging step 2: Check the value of data
  //console.log(data);

  return (

          <Router>
              <React.Fragment>

                          {homeData && homeData?.homeLinks?.pages && homeData?.homeLinks?.page(link => (

                                <Link to={`/${link?.slug}`}>

                                </Link>

                          ))}

              </React.Fragment>
          </Router>

  );
}


问:
Angular Unit - testing (Jasmine karma) : Failed: Cannot read properties of undefined (reading 'getComplete)
I called getComplete method in component.spec.ts file which is defined in google.directive.ts file.
component.ts:-->

```<code> ngAfterViewInit(): void {
    ...
    this.googleComplete.getComplete(this.addresstext);
    console.log('address is:--' , this.addresstext);
</code>```

*googleComplete:--> ComponentPage.googleComplete: GoogleCompleteDirective

component.spec.ts:->

```<code>it('called getComplete method', waitForAsync(inject([GoogleCompleteDirective],
    ( googleCompleteDirective: GoogleCompleteDirective ) => {
    spyOn(component, 'ngAfterViewInit').and.callThrough();
    spyOn(googleCompleteDirective, 'getComplete').and.callThrough();
    component.ngAfterViewInit();
    expect(component.ngAfterViewInit).toHaveBeenCalled();
</code>```

google.directive.ts:->

```<code>getComplete(addresstext: ElementRef) {
//code here....
....
}

</code>```

directive.ts:-

```<code>getAutocomplete(addresstext: ElementRef) {
    const autocomplete = new google.maps.places.Autocomplete(addresstext.nativeElement,
      {
        componentRestrictions: { country: 'US' },
        fields: ['address_components', 'geometry'],
        types: ['address']
      });
</code>```

after testing this code, got Error:->
" Failed: google is not defined

ReferenceError: google is not defined"

I also used  providers:
[ GoogleCompleteDirective,{ provide: ElementRef, useValue: {} }, ]
in provider for elementref and imported getCompleteDirective

Please suggest me the ways to fix this?

It should pass test case but getting Error:->
" Failed: google is not defined

ReferenceError: google is not defined"

Body:
I called getComplete method in component.spec.ts file which is defined in google.directive.ts file.
component.ts:-->

 ngAfterViewInit(): void {
    ...
    this.googleComplete.getComplete(this.addresstext);
    console.log('address is:--' , this.addresstext);

*googleComplete:--> ComponentPage.googleComplete: GoogleCompleteDirective

component.spec.ts:->

it('called getComplete method', waitForAsync(inject([GoogleCompleteDirective],
    ( googleCompleteDirective: GoogleCompleteDirective ) => {
    spyOn(component, 'ngAfterViewInit').and.callThrough();
    spyOn(googleCompleteDirective, 'getComplete').and.callThrough();
    component.ngAfterViewInit();
    expect(component.ngAfterViewInit).toHaveBeenCalled();

google.directive.ts:->

getComplete(addresstext: ElementRef) {
//code here....
....
}

directive.ts:-

getAutocomplete(addresstext: ElementRef) {
    const autocomplete = new google.maps.places.Autocomplete(addresstext.nativeElement,
      {
        componentRestrictions: { country: 'US' },
        fields: ['address_components', 'geometry'],
        types: ['address']
      });

after testing this code, got Error:->
" Failed: google is not defined

ReferenceError: google is not defined"

I also used  providers:
[ GoogleCompleteDirective,{ provide: ElementRef, useValue: {} }, ]
in provider for elementref and imported getCompleteDirective

Please suggest me the ways to fix this?

It should pass test case but getting Error:->
" Failed: google is not defined

ReferenceError: google is not defined"


问:
How to combine Mixins and Protocols in Python
I'm trying to understand the correct way to use Protocols for ensuring the inheritor of a Mixin contains all the attributes needed by the Mixin to operate correctly. The Mixins are part of an existing codebase, so will be hard to change the design but I will do it if it makes the design "right".

This is a simplified example of how the code is currently implemented:

class A1Mixin(object):

    _needed_for_a1: str

    def a1(self):

        print(self._needed_for_a1)

class A1UserV1(
    A1Mixin,
    object
):

    def __init__(self, needed_for_a1: str):

        self._needed_for_a1: str = needed_for_a1
```
<p>But the issue with this is that type-checking on <code>A1UserV1</code> does not highlight if <code>self._needed_for_a1</code> is not defined in <code>__init__</code>.
So I thought this might work:</p>
<pre class="lang-py prettyprint-override"><code>class A1Protocol(Protocol):

    _needed_for_a1: str

class A1UserV2(
    A1Mixin,
    A1Protocol,
    object
):

    def __init__(self, needed_for_a1: str):

        self._needed_for_a1: str = needed_for_a1
</code>```

But still no flagging from PyCharm if I do not define self._needed_for_a1 in __init__. Is this even a proper use of Protocol?

Body:
I'm trying to understand the correct way to use Protocols for ensuring the inheritor of a Mixin contains all the attributes needed by the Mixin to operate correctly. The Mixins are part of an existing codebase, so will be hard to change the design but I will do it if it makes the design "right".

This is a simplified example of how the code is currently implemented:

class A1Mixin(object):

    _needed_for_a1: str

    def a1(self):

        print(self._needed_for_a1)

class A1UserV1(
    A1Mixin,
    object
):

    def __init__(self, needed_for_a1: str):

        self._needed_for_a1: str = needed_for_a1

But the issue with this is that type-checking on A1UserV1 does not highlight if self._needed_for_a1 is not defined in __init__.
So I thought this might work:

class A1Protocol(Protocol):

    _needed_for_a1: str

class A1UserV2(
    A1Mixin,
    A1Protocol,
    object
):

    def __init__(self, needed_for_a1: str):

        self._needed_for_a1: str = needed_for_a1

But still no flagging from PyCharm if I do not define self._needed_for_a1 in __init__. Is this even a proper use of Protocol?


问:
Cannot complete the kubernetes cluster authentication step with python client
I want to authenticate to a kubernetes cluster through python client library from here. The cluster information:

Kubernetes control plane is running at https://127.0.0.1:34823

CoreDNS is running at https://127.0.0.1:34823/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

I did all the steps with no problem. But in:

```<code>curl -s -k -XGET -H "Authorization: Bearer $KIND_TOKEN" -H "Accept: application/json, */*" -H "Content-Type: application/json" \
    -H "kubernetes/$Format" 'https://127.0.0.1:34823/api/v1/namespaces/default/pods/example' | jq .status.phase
</code>```

got error:

jq: error (at :12): Cannot index string with string "phase"

Also once I tried to test:

```<code>from kubernetes import client
import os

configuration = client.Configuration()
configuration.api_key_prefix["authorization"] = "Bearer"
configuration.host = "https://127.0.0.1:34823"
configuration.api_key["authorization"] = os.getenv("KIND_TOKEN", None)
configuration.verify_ssl = False  # Only for testing with KinD!
api_client = client.ApiClient(configuration)
v1 = client.CoreV1Api(api_client)

ret = v1.list_namespaced_pod(namespace="default", watch=False)
for pod in ret.items:
    print(f"Name: {pod.metadata.name}, Namespace: {pod.metadata.namespace} IP: {pod.status.pod_ip}")
</code>```

An other error:

MaxRetryError: HTTPConnectionPool(host=' https', port=80): Max retries exceeded with url: //127.0.0.1:34823/api/v1/namespaces/default/pods?watch=False (Caused by ProtocolError('Connection aborted.', InvalidURL("URL can't contain control characters. ' https' (found at least ' ')")))

The jq version is jq-1.6.

Body:
I want to authenticate to a kubernetes cluster through python client library from here. The cluster information:

Kubernetes control plane is running at https://127.0.0.1:34823

CoreDNS is running at https://127.0.0.1:34823/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

I did all the steps with no problem. But in:

curl -s -k -XGET -H "Authorization: Bearer $KIND_TOKEN" -H "Accept: application/json, */*" -H "Content-Type: application/json" \
    -H "kubernetes/$Format" 'https://127.0.0.1:34823/api/v1/namespaces/default/pods/example' | jq .status.phase

got error:

jq: error (at :12): Cannot index string with string "phase"

Also once I tried to test:

from kubernetes import client
import os

configuration = client.Configuration()
configuration.api_key_prefix["authorization"] = "Bearer"
configuration.host = "https://127.0.0.1:34823"
configuration.api_key["authorization"] = os.getenv("KIND_TOKEN", None)
configuration.verify_ssl = False  # Only for testing with KinD!
api_client = client.ApiClient(configuration)
v1 = client.CoreV1Api(api_client)

ret = v1.list_namespaced_pod(namespace="default", watch=False)
for pod in ret.items:
    print(f"Name: {pod.metadata.name}, Namespace: {pod.metadata.namespace} IP: {pod.status.pod_ip}")

An other error:

MaxRetryError: HTTPConnectionPool(host=' https', port=80): Max retries exceeded with url: //127.0.0.1:34823/api/v1/namespaces/default/pods?watch=False (Caused by ProtocolError('Connection aborted.', InvalidURL("URL can't contain control characters. ' https' (found at least ' ')")))

The jq version is jq-1.6.


问:
WebClient Integration Test with MockWebServer
I dont know if my configuration is wrong or something with mockwebserver.
I have method in one of my services

```<code>public UserResponse getUsername(String username) {
    return webClient.get()
            .uri("http://user-service/api/user",
                    uriBuilder -> uriBuilder.queryParam("username", username).build())
            .retrieve()
            .bodyToMono(UserResponse.class)
            .block();
}
</code>```

And I want to test this method by MockWebServer as below

```<code>public class CardWebClientTest {
private MockWebServer server;
private CardService service;

@BeforeEach
void setup() {
    server = new MockWebServer();
    WebClient webClient = WebClient.builder().baseUrl(server.url("").toString()).build();
    service = new CardService(webClient);
}

@Test
void test() {
    server.enqueue(new MockResponse().setBody("{\"id\": 12345}")
            .addHeader("Content-Type", "application/json")
            .setResponseCode(200));

    var result = service.getUsername("john");

    assertThat(result.getId()).isEqualTo(12345L);
}
</code>```

Am I missing something? It's propably something trivial but I can't find solution.
CardService which is calling UserService are communicating in EurekaServer with loadbalancer but Im assuming MockWebServer can handle this without any further configuration or not - idk. I will appreciate any help.

UserResponse dto looks like this

```<code>public class UserResponse
private Long id;
</code>```

I forgot to mention error message. It's always

Failed to resolve 'user-service' after 2 queries ; nested exception is java.net.UnknownHostException: Failed to resolve 'user-service' after 2 queries

Alright. Now I can see that mockwebserver has different hostname - it's calling http://kubernetes.docker.internal:52654/api/user and webclient is asking for http://user-service. But still I dont know how to configure mockwebserver to get response. I should set somehow hostname or maybe leave like that and just test webclient.get() to see if response is correct?

Body:
I dont know if my configuration is wrong or something with mockwebserver.
I have method in one of my services

public UserResponse getUsername(String username) {
    return webClient.get()
            .uri("http://user-service/api/user",
                    uriBuilder -> uriBuilder.queryParam("username", username).build())
            .retrieve()
            .bodyToMono(UserResponse.class)
            .block();
}

And I want to test this method by MockWebServer as below

public class CardWebClientTest {
private MockWebServer server;
private CardService service;

@BeforeEach
void setup() {
    server = new MockWebServer();
    WebClient webClient = WebClient.builder().baseUrl(server.url("").toString()).build();
    service = new CardService(webClient);
}

@Test
void test() {
    server.enqueue(new MockResponse().setBody("{\"id\": 12345}")
            .addHeader("Content-Type", "application/json")
            .setResponseCode(200));

    var result = service.getUsername("john");

    assertThat(result.getId()).isEqualTo(12345L);
}

Am I missing something? It's propably something trivial but I can't find solution.
CardService which is calling UserService are communicating in EurekaServer with loadbalancer but Im assuming MockWebServer can handle this without any further configuration or not - idk. I will appreciate any help.

UserResponse dto looks like this

public class UserResponse
private Long id;

I forgot to mention error message. It's always

Failed to resolve 'user-service' after 2 queries ; nested exception is java.net.UnknownHostException: Failed to resolve 'user-service' after 2 queries

Alright. Now I can see that mockwebserver has different hostname - it's calling http://kubernetes.docker.internal:52654/api/user and webclient is asking for http://user-service. But still I dont know how to configure mockwebserver to get response. I should set somehow hostname or maybe leave like that and just test webclient.get() to see if response is correct?


问:
Why do i get the Error cannot post /login using express and passportjs?
When i make a post request containing the user data to log in, i get the response: Cannot post /login.

What is really weird about this is that you can see trough logging that the request get processed.

I was using postman and a html form to test and both didnt worked.

When i have a failure in the passport.js file it gets logged.

.

Thats my server.js file (shortened):

const express = require("express");

const cors = require("cors");
const flash = require("express-flash");
const passport = require("passport");
const session = require("express-session");
//app configuration
const app = express();
require("dotenv").config();

const initializePassport = require("./config/passport-config");
initializePassport(
  passport,
  require('./models/User')
)

app.use(
  session({
    secret: "Janniks whatsapp Klon",
    resave: false,
    saveUninitialized: false,
  })
);

app.use(passport.initialize());
app.use(passport.session());

//For accepting post from data
const UserRouter = require("./api/User");

app.use(flash());
app.use(express.json());
app.use(bodyarser.urlencoded({ extended: true }));
app.use(
  cors() //{ origin: "http://localhost:3000", origin: "http://localhost:3000" }
);
app.use("/user", UserRouter);

app.post('/login', passport.authenticate('local', {
  sucessRedirect: 'http://localhost:3000/login',
  failureRedirect: 'http://localhost:3000/login',
  failureFlash: true
}),
)

```
<p>and thats my passport-config.js file</p>
<pre class="lang-js prettyprint-override"><code>const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')
//Password handle
function initialize(passport, User){
  const authenticateUser = async(emailORnumber, password, done)=>{
    //Find user with email or phone number
    let user;
    if(emailORnumber.includes('@')){
      user = await User.findOne({ email: emailORnumber})
    }else{
      user = await User.findOne({ number: emailORnumber })
    }
    if(!user){
      //User not found, error
      console.log('User not found')
      return done(null, false, { message: 'Falsches passwort oder falsche Handynummer' })
    }

    //Check if password is correct
    try{
    console.log('Checking password')
    const isMatch= await bcrypt.compare(password, user.password);
    if(!isMatch){
      return done(null, false, { message: 'Falsches passwort'})
    }else{
    //If credentials are correct, return the user object
    console.log('correct')        //gets logged
    return done(null, user)
    }
  }
  catch(err){
      console.log(err)
      return done(err)
    }

  }

   passport.use(new LocalStrategy({ usernameField: 'emailORnumber'}, authenticateUser)),
  //Serialize user to store
  passport.serializeUser((user, done)=>{
    console.log('Serializing user')              //gets logged
    done(null, user.id)
  })

  //Deserialize user from store
  passport.deserializeUser((id, done)=>{
    console.log('Serializing user')            //dont gets logged but there is no interaction
    User.findById(id, (err, user)=>{
      return done(err, user);
    });
  });

}

module.exports = initialize;
</code>```

Thanks for all awnsers that can be provided!

Body:
When i make a post request containing the user data to log in, i get the response: Cannot post /login.

What is really weird about this is that you can see trough logging that the request get processed.

I was using postman and a html form to test and both didnt worked.

When i have a failure in the passport.js file it gets logged.

.

Thats my server.js file (shortened):

const express = require("express");

const cors = require("cors");
const flash = require("express-flash");
const passport = require("passport");
const session = require("express-session");
//app configuration
const app = express();
require("dotenv").config();

const initializePassport = require("./config/passport-config");
initializePassport(
  passport,
  require('./models/User')
)

app.use(
  session({
    secret: "Janniks whatsapp Klon",
    resave: false,
    saveUninitialized: false,
  })
);

app.use(passport.initialize());
app.use(passport.session());

//For accepting post from data
const UserRouter = require("./api/User");

app.use(flash());
app.use(express.json());
app.use(bodyarser.urlencoded({ extended: true }));
app.use(
  cors() //{ origin: "http://localhost:3000", origin: "http://localhost:3000" }
);
app.use("/user", UserRouter);

app.post('/login', passport.authenticate('local', {
  sucessRedirect: 'http://localhost:3000/login',
  failureRedirect: 'http://localhost:3000/login',
  failureFlash: true
}),
)

and thats my passport-config.js file

const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')
//Password handle
function initialize(passport, User){
  const authenticateUser = async(emailORnumber, password, done)=>{
    //Find user with email or phone number
    let user;
    if(emailORnumber.includes('@')){
      user = await User.findOne({ email: emailORnumber})
    }else{
      user = await User.findOne({ number: emailORnumber })
    }
    if(!user){
      //User not found, error
      console.log('User not found')
      return done(null, false, { message: 'Falsches passwort oder falsche Handynummer' })
    }

    //Check if password is correct
    try{
    console.log('Checking password')
    const isMatch= await bcrypt.compare(password, user.password);
    if(!isMatch){
      return done(null, false, { message: 'Falsches passwort'})
    }else{
    //If credentials are correct, return the user object
    console.log('correct')        //gets logged
    return done(null, user)
    }
  }
  catch(err){
      console.log(err)
      return done(err)
    }

  }

   passport.use(new LocalStrategy({ usernameField: 'emailORnumber'}, authenticateUser)),
  //Serialize user to store
  passport.serializeUser((user, done)=>{
    console.log('Serializing user')              //gets logged
    done(null, user.id)
  })

  //Deserialize user from store
  passport.deserializeUser((id, done)=>{
    console.log('Serializing user')            //dont gets logged but there is no interaction
    User.findById(id, (err, user)=>{
      return done(err, user);
    });
  });

}

module.exports = initialize;

Thanks for all awnsers that can be provided!


问:
Error when installing package in Octave-online
I want to install the image package in Octave-online.net, but when I tried it, it gave me an error message. I am on a MacBook Air 2013 (if that's important), on macOS 11.7.2 .

I have tried to install Octave on my laptop and that didn't work, so I'm trying it with the online version.

I wrote

```<code>pkg install -forge image
</code>```

and expected it to install the package, but instead it gave me the following error message:

```<code>error: get_forge_pkg: could not read version number from package's page
error: called from
    get_forge_pkg at line 55 column 7
    get_forge_download at line 32 column 14
    pkg at line 538 column 31
</code>```

Does somebody know how to fix this or another way to install the package?

Thanks so much!

Body:
I want to install the image package in Octave-online.net, but when I tried it, it gave me an error message. I am on a MacBook Air 2013 (if that's important), on macOS 11.7.2 .

I have tried to install Octave on my laptop and that didn't work, so I'm trying it with the online version.

I wrote

pkg install -forge image

and expected it to install the package, but instead it gave me the following error message:

error: get_forge_pkg: could not read version number from package's page
error: called from
    get_forge_pkg at line 55 column 7
    get_forge_download at line 32 column 14
    pkg at line 538 column 31

Does somebody know how to fix this or another way to install the package?

Thanks so much!


问:
Angular Jasmine Karma Background Image Component Test
I am new to Angular JS and I would like to test if the background image that I have on my header component is loaded correctly. However, on the console log, it says that the image file is not found.

Here's the whole code for your reference:

HTML:

```<code>**<div class="flex-container" [ngStyle]="{'background-image' : 'url('+ bgImage +')'}">**
    <div class="text-container">
        <h1>{{ title }}</h1>
        <p>{{ description }}</p>
        <a [href]="buttonLink" target="_blank"><button>{{ buttonText }}</button></a>
    </div>
</div>
</code>```

Component.ts:

```<code>import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {

  @Input() title: string;
  @Input() description: string;
  @Input() buttonText: string;
  @Input() buttonLink: string;
  **@Input() bgImage: string;**

  constructor() { }

  ngOnInit(): void {
  }

}
</code>```

Component.spec.ts:

```<code>import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';

import { HeaderComponent } from './header.component';

describe('HeaderComponent', () => {
  let component: HeaderComponent;
  let fixture: ComponentFixture<HeaderComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ HeaderComponent ]
    })
    .compileComponents();

    fixture = TestBed.createComponent(HeaderComponent);
    component = fixture.componentInstance;
  });

  it('should create', () => {
    fixture.detectChanges();
    expect(component).toBeTruthy();
  });

  it('should render all inputs', () => {
    component.title = 'test'
    component.description = 'test-description'
    **component.bgImage = 'bgImageIllustrations.jpg'**
    fixture.detectChanges();
    const title = fixture.debugElement.query(By.css('h1')).nativeElement as HTMLElement
    const description = fixture.debugElement.query(By.css('p')).nativeElement as HTMLElement
    **const bgImage = fixture.debugElement.query(By.css('.flex-container')).nativeElement as HTMLElement;**
    expect(title.textContent).toBe('test');
    expect(description.textContent).toBe('test-description');
    **console.log(getComputedStyle(bgImage).backgroundImage);**
  });
});
</code>```

Hope you can help me to fix this issue. Thanks!

I would like to see if I am loading the right background image

Body:
I am new to Angular JS and I would like to test if the background image that I have on my header component is loaded correctly. However, on the console log, it says that the image file is not found.

Here's the whole code for your reference:

HTML:

**
**

{{ title }}

{{ description }}

        <button>{{ buttonText }}</button>

Component.ts:

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {

  @Input() title: string;
  @Input() description: string;
  @Input() buttonText: string;
  @Input() buttonLink: string;
  **@Input() bgImage: string;**

  constructor() { }

  ngOnInit(): void {
  }

}

Component.spec.ts:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';

import { HeaderComponent } from './header.component';

describe('HeaderComponent', () => {
  let component: HeaderComponent;
  let fixture: ComponentFixture<HeaderComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ HeaderComponent ]
    })
    .compileComponents();

    fixture = TestBed.createComponent(HeaderComponent);
    component = fixture.componentInstance;
  });

  it('should create', () => {
    fixture.detectChanges();
    expect(component).toBeTruthy();
  });

  it('should render all inputs', () => {
    component.title = 'test'
    component.description = 'test-description'
    **component.bgImage = 'bgImageIllustrations.jpg'**
    fixture.detectChanges();
    const title = fixture.debugElement.query(By.css('h1')).nativeElement as HTMLElement
    const description = fixture.debugElement.query(By.css('p')).nativeElement as HTMLElement
    **const bgImage = fixture.debugElement.query(By.css('.flex-container')).nativeElement as HTMLElement;**
    expect(title.textContent).toBe('test');
    expect(description.textContent).toBe('test-description');
    **console.log(getComputedStyle(bgImage).backgroundImage);**
  });
});

Hope you can help me to fix this issue. Thanks!

I would like to see if I am loading the right background image


问:
curl --proxy "http://user:pwd@127.0.0.1:1234" "http://httpbin.org/ip" return computer and proxy ip
I have on docker squid with proxy.
When I on my macbook put in terminal:

```<code>curl --proxy "http://user:pwd@proxy-ip:1234" "http://httpbin.org/ip" r
</code>```

I get:

```<code>{
  "origin": "my-macbook-ip, proxy-ip"
}
</code>```

Why I get two ip, not only from proxy?

Body:
I have on docker squid with proxy.
When I on my macbook put in terminal:

curl --proxy "http://user:pwd@proxy-ip:1234" "http://httpbin.org/ip" r

I get:

{
  "origin": "my-macbook-ip, proxy-ip"
}

Why I get two ip, not only from proxy?


问:
Stuck at django models get_absolute_url. NoReverseMatch
Its not redirecting and giving the error of NoReverseMatch. exception is: book_detail cannot be found... though i have the correct name and same name in urls.py and template. Even book_detail anchored to the book_list working completely fine. where am i doing the mistake kindly help me.
Details:

```<code>[Error]

NoReverseMatch at /catalog/book_create/
</code>```

Reverse for 'book_detail' not found. 'book_detail' is not a valid view function or pattern name.
Request Method: POST
Request URL:    http://127.0.0.1:8000/catalog/book_create/
Django Version: 4.1.3
Exception Type: NoReverseMatch
Exception Value:

Reverse for 'book_detail' not found. 'book_detail' is not a valid view function or pattern name.
Exception Location: C:\Users\Umar\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\urls\resolvers.py, line 828, in _reverse_with_prefix
Raised during:  catalog.views.BookCreateView
Python Executable:  C:\Users\Umar\AppData\Local\Programs\Python\Python311\python.exe
Python Version: 3.11.0
Python Path:

['C:\Users\Umar\Djano_learning\Django\my_site',
'C:\Users\Umar\AppData\Local\Programs\Python\Python311\python311.zip',
'C:\Users\Umar\AppData\Local\Programs\Python\Python311\Lib',
'C:\Users\Umar\AppData\Local\Programs\Python\Python311\DLLs',
'C:\Users\Umar\AppData\Local\Programs\Python\Python311',
'C:\Users\Umar\AppData\Local\Programs\Python\Python311\Lib\site-packages']
Server time:    Mon, 02 Jan 2023 17:02:23 +0000

Models:

```<code>class Book(models.Model):
title = models.CharField(max_length=100)
'''Linking Author class model to Book model'''
author = models.ForeignKey('Author',on_delete=models.SET_NULL,null=True)
summary = models.TextField(max_length=600)
isbn = models.CharField(max_length=13, unique=True)
  genre = models.ManyToManyField(Genre)
language =
models.ForeignKey('Language',on_delete=models.RESTRICT,null=True)

def __str__(self):
    return self.title

def get_absolute_url(self):
    return reverse('book_detail', kwargs={'pk' : self.pk})
[Book_detail.html]

<html lang="en">
<head>
</head>
<body>
<h2>Details of Books</h2>

<h2>{{book}}</h2>
<h2>{{author}}</h2>
</body>
</html>

   [Urls.py]

from django.urls import path,reverse_lazy,reverse
from .views import (HomeView,BookListView,
BookCreateView,BookDetailView,AuthorCreateView,AuthorListView,
AuthorDetailView)
from . import views

app_name='catalog'

# path is below
urlpatterns = [
path('',HomeView.as_view(),name='home'),
path('book_list/',BookListView.as_view(),name='book_list'),
path('book_create/',BookCreateView.as_view(),name='book_create'),
**path('book_detail/<int:pk>/',BookDetailView.as_view(),name='book_detail'),**
path('author_create/',AuthorCreateView.as_view(),name='author_create'),
path('author_list/',AuthorListView.as_view(),name='author_list'),   path('author_detail/<int:pk>/',AuthorDetailView.as_view(),name='people_detail')
,path('view/',views.auth_check,name='view')
]
</code>```

A simple Redirect should have to work.

Body:
Its not redirecting and giving the error of NoReverseMatch. exception is: book_detail cannot be found... though i have the correct name and same name in urls.py and template. Even book_detail anchored to the book_list working completely fine. where am i doing the mistake kindly help me.
Details:

[Error]

NoReverseMatch at /catalog/book_create/

Reverse for 'book_detail' not found. 'book_detail' is not a valid view function or pattern name.
Request Method: POST
Request URL:    http://127.0.0.1:8000/catalog/book_create/
Django Version: 4.1.3
Exception Type: NoReverseMatch
Exception Value:

Reverse for 'book_detail' not found. 'book_detail' is not a valid view function or pattern name.
Exception Location: C:\Users\Umar\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\urls\resolvers.py, line 828, in _reverse_with_prefix
Raised during:  catalog.views.BookCreateView
Python Executable:  C:\Users\Umar\AppData\Local\Programs\Python\Python311\python.exe
Python Version: 3.11.0
Python Path:

['C:\Users\Umar\Djano_learning\Django\my_site',
'C:\Users\Umar\AppData\Local\Programs\Python\Python311\python311.zip',
'C:\Users\Umar\AppData\Local\Programs\Python\Python311\Lib',
'C:\Users\Umar\AppData\Local\Programs\Python\Python311\DLLs',
'C:\Users\Umar\AppData\Local\Programs\Python\Python311',
'C:\Users\Umar\AppData\Local\Programs\Python\Python311\Lib\site-packages']
Server time:    Mon, 02 Jan 2023 17:02:23 +0000

Models:

class Book(models.Model):
title = models.CharField(max_length=100)
'''Linking Author class model to Book model'''
author = models.ForeignKey('Author',on_delete=models.SET_NULL,null=True)
summary = models.TextField(max_length=600)
isbn = models.CharField(max_length=13, unique=True)
  genre = models.ManyToManyField(Genre)
language =
models.ForeignKey('Language',on_delete=models.RESTRICT,null=True)

def __str__(self):
    return self.title

def get_absolute_url(self):
    return reverse('book_detail', kwargs={'pk' : self.pk})
[Book_detail.html]

Details of Books

{{book}}

{{author}}

   [Urls.py]

from django.urls import path,reverse_lazy,reverse
from .views import (HomeView,BookListView,
BookCreateView,BookDetailView,AuthorCreateView,AuthorListView,
AuthorDetailView)
from . import views

app_name='catalog'

# path is below
urlpatterns = [
path('',HomeView.as_view(),name='home'),
path('book_list/',BookListView.as_view(),name='book_list'),
path('book_create/',BookCreateView.as_view(),name='book_create'),
**path('book_detail/<int:pk>/',BookDetailView.as_view(),name='book_detail'),**
path('author_create/',AuthorCreateView.as_view(),name='author_create'),
path('author_list/',AuthorListView.as_view(),name='author_list'),   path('author_detail/<int:pk>/',AuthorDetailView.as_view(),name='people_detail')
,path('view/',views.auth_check,name='view')
]

A simple Redirect should have to work.


问:
No module named 'sklearn' in LabVIEW
I'm trying to run a python code that has an intelligent algorithm in LabVIEW using a python node, and I got the following error: Python returned the following error: <class 'ModuleNotFoundError'> No module named 'sklearn'. I tried with simpler code (without sklearn) and the code ran as expected. I've installed scikit-learn using pip, and if I try to run the python script from the command line, it works. But for the same python script, LabVIEW doesn't find the sklearn library. Do you know what I can do, or if there are some settings that maybe I configured wrongly?</p>

Title: No module named 'sklearn' in LabVIEW


问:
CSS transition timing function not working as expected
I have a nav-links class on which I want to have horizontal scroll effect based on changing translateX. I change translateX using CSS variable from JavaScript. Irrespective of any timing function the horizontal movement seems choppy from start point to final point. But scale operation and vertical movements is smooth. Computed values of css variables are also correctly passed.

```<code>
.nav-links {
  position: relative;
  left: 50vw;
  display: flex;
  gap: clamp(1rem, 2vw, 2rem);
  margin-top: clamp(2rem, 2vw, 3rem);
  padding: 0rem clamp(1rem, 2vw, 2rem);
  transition: all 500ms cubic-bezier(0.13, 0.53, 0.38, 0.97);
}

.nav-links[data-show-menu="false"] {
  transform: translate(var(--translateX), -70%) scale(0.9);
}
.nav-links[data-show-menu="true"] {
  transform: translate(var(--translateX), 0%) scale(1);
}
</code>```

translateX set in percentage terms as eg: --translateX :80%

Also tried to do same with animation, but it results in same issue.

Body:
I have a nav-links class on which I want to have horizontal scroll effect based on changing translateX. I change translateX using CSS variable from JavaScript. Irrespective of any timing function the horizontal movement seems choppy from start point to final point. But scale operation and vertical movements is smooth. Computed values of css variables are also correctly passed.

.nav-links {
  position: relative;
  left: 50vw;
  display: flex;
  gap: clamp(1rem, 2vw, 2rem);
  margin-top: clamp(2rem, 2vw, 3rem);
  padding: 0rem clamp(1rem, 2vw, 2rem);
  transition: all 500ms cubic-bezier(0.13, 0.53, 0.38, 0.97);
}

.nav-links[data-show-menu="false"] {
  transform: translate(var(--translateX), -70%) scale(0.9);
}
.nav-links[data-show-menu="true"] {
  transform: translate(var(--translateX), 0%) scale(1);
}

translateX set in percentage terms as eg: --translateX :80%

Also tried to do same with animation, but it results in same issue.


问:
Strange behavior in regards to memory leak between Dispatcher.BeginInvoke and await Dispatcher.InvokeAsync
I have observed a strange behavior in terms of memory leak between Dispatcher.BeginInvoke and Dispatcher.InovkeAsync(). A class object that gets passed to delegate inside InvokeAsync() (not as paramter) is not getting garbage collected after execution completion. But with BeginInvoke, this does not happen. Can somebody explain why that is so?

I have a WPF application that needs to display logs at runtime (say 500 logs per 1 min). I have an ObservableCollection<LogItem> object in viewmodel which is bound to Listbox as usual. Here SampleItem contains a large string value of length around 5000 (specifics of why this log is large will not explained here) and other smaller sized string properties. These SampleItem objects are injected into AddLog function via via event Handler from another Class.

```<code>
Class SampleItem
{
  string SampleData;  // around length  5000

  // few other properties which are of standard base types such as int, string of smaller size like 10
}

Class LogItem
{
  string log;
}

Class MyClass
{

 ObservableCollection<LogItem> _logs = new ObservableCollection<LogItem>();
 public ObservableCollection<LogItem> Logs
 {
   get{ return _logs;}
 }

 public async void AddLog(SampleItem item)
 {
    await Application.Current.Dispatcher.InovkeAsync(new Action(()=>{

    // Process the SampleItem object here and create LogItem object and add it to collection
       LogItem logitem = new LogItem()
       // object contents are set based on contents of SampleItem
       If(Logs.Count>500)
       {
          Logs.Clear()
        }
       Logs.Add(logitem );

    }));
 }

}
</code>```

With this implementation logs are displayed.
But the main issue here is memory is showing as increased in task manager. With Memory Profiling, it is observed that SampleItem objects are not getting garbage collected and is being held by AddLog await function which also is not released. I even commented out the region inside Dispatcher.InvokeAsync, same memory leak happens. Please note that SampleItem object is not used anywhere in the calling function where event handler is invoked. Memory leak will get reduced if I set the 'SampleData' property of SampleItem object as null at the end of delegate. But I don't think that is ideal.

When I tried with Dispatcher.BeginInvoke() method as shown below, this kind of memory leak never occured either in TaskManaer or Memory Profile.

```<code>public void AddLog(SampleItem item)
 {
    Application.Current.Dispatcher.BeginInvoke(new Action(()=>{

    // Process the SampleItem object here and create LogItem object and add it to collection
       LogItem logitem = new LogItem()
       // object contents are set based on contents of SampleItem
       If(Logs.Count>500)
       {
          Logs.Clear()
        }
       Logs.Add(logitem );

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

Does anybody know why this happening?

Body:
I have observed a strange behavior in terms of memory leak between Dispatcher.BeginInvoke and Dispatcher.InovkeAsync(). A class object that gets passed to delegate inside InvokeAsync() (not as paramter) is not getting garbage collected after execution completion. But with BeginInvoke, this does not happen. Can somebody explain why that is so?

I have a WPF application that needs to display logs at runtime (say 500 logs per 1 min). I have an ObservableCollection<LogItem> object in viewmodel which is bound to Listbox as usual. Here SampleItem contains a large string value of length around 5000 (specifics of why this log is large will not explained here) and other smaller sized string properties. These SampleItem objects are injected into AddLog function via via event Handler from another Class.

Class SampleItem
{
  string SampleData;  // around length  5000

  // few other properties which are of standard base types such as int, string of smaller size like 10
}

Class LogItem
{
  string log;
}

Class MyClass
{

 ObservableCollection<LogItem> _logs = new ObservableCollection<LogItem>();
 public ObservableCollection<LogItem> Logs
 {
   get{ return _logs;}
 }

 public async void AddLog(SampleItem item)
 {
    await Application.Current.Dispatcher.InovkeAsync(new Action(()=>{

    // Process the SampleItem object here and create LogItem object and add it to collection
       LogItem logitem = new LogItem()
       // object contents are set based on contents of SampleItem
       If(Logs.Count>500)
       {
          Logs.Clear()
        }
       Logs.Add(logitem );

    }));
 }

}

With this implementation logs are displayed.
But the main issue here is memory is showing as increased in task manager. With Memory Profiling, it is observed that SampleItem objects are not getting garbage collected and is being held by AddLog await function which also is not released. I even commented out the region inside Dispatcher.InvokeAsync, same memory leak happens. Please note that SampleItem object is not used anywhere in the calling function where event handler is invoked. Memory leak will get reduced if I set the 'SampleData' property of SampleItem object as null at the end of delegate. But I don't think that is ideal.

When I tried with Dispatcher.BeginInvoke() method as shown below, this kind of memory leak never occured either in TaskManaer or Memory Profile.

public void AddLog(SampleItem item)
 {
    Application.Current.Dispatcher.BeginInvoke(new Action(()=>{

    // Process the SampleItem object here and create LogItem object and add it to collection
       LogItem logitem = new LogItem()
       // object contents are set based on contents of SampleItem
       If(Logs.Count>500)
       {
          Logs.Clear()
        }
       Logs.Add(logitem );

    }));
 }

Does anybody know why this happening?


问:
stripe - embedded iframe height is off, cutting off zip code
I'm exploring using stripe and have started by using the "payments" layout w/the v3 javascript.  Problem is the "zip code" is always getting cut off as it looks like the iframe height is not adjusting properly.  Any suggestions as to what i may be doing wrong or how to adjust the iframe?
html:

```<code><form action="/" method="post" id="payment-form">
<div class="form-row">
    <div id="card-element"> <!-- a Stripe Element will be inserted here. --> </div>
    <!-- Used to display Element errors -->
    <div id="card-errors" role="alert"></div>
</div>
</code>```

js (angular/ionic):

```<code>this.card = this.stripeElements.create('payment');
this.card.mount('#card-element');
</code>```

screenshot

Thanks in advance.

Body:
I'm exploring using stripe and have started by using the "payments" layout w/the v3 javascript.  Problem is the "zip code" is always getting cut off as it looks like the iframe height is not adjusting properly.  Any suggestions as to what i may be doing wrong or how to adjust the iframe?
html:

<form action="/" method="post" id="payment-form">

js (angular/ionic):

this.card = this.stripeElements.create('payment');
this.card.mount('#card-element');

screenshot

Thanks in advance.


问:
How can I modify props values once the page has been refreshed in Vue?
My test code is the following, it's just an example to understand my question.

```<code><script setup lang="ts">
import { ref, onMounted } from 'vue'

const props = defineProps({
  account: Object,
})

const { account } = toRefs(props);

const accountDate = ref("")

const formatDate = (date) => {
    var d = new Date(date)
    var month = '' + (d.getMonth() + 1)
    var day = '' + d.getDate()
    var year = d.getFullYear()

    if (month.length < 2)
        month = '0' + month;
    if (day.length < 2)
        day = '0' + day;

    return [year, month, day].join('-');
}

onMounted(() => {
    accountDate.value = formatDate(account.value.date)
    console.log(account.value.date)
})

</script>

<template>
    <input type="text" v-model="accountDate"></input>
</template>
</code>```

So the "formatDate" function just transforms Date format to YYYY-MM-DD, it's not important in my question. So I v-model accountDate with the new Date format but the console.log shown just print "undefined". So props are not defined yet in onMounted lifecycle.
How can I do it?

Body:
My test code is the following, it's just an example to understand my question.

<template>
    <input type="text" v-model="accountDate"></input>
</template>

So the "formatDate" function just transforms Date format to YYYY-MM-DD, it's not important in my question. So I v-model accountDate with the new Date format but the console.log shown just print "undefined". So props are not defined yet in onMounted lifecycle.
How can I do it?