问:
Inserting image url in quill only displays the image icon and not the image itself
I am using quill in Next.js and I have ran into a problem. Instead of using the default base64 encoding for images, I have added a custom handler that creates an object url for the images and I later pass it to the quill.insertEmbed() method. However, once I go to the browser, quill only displays an image icon like the one displayed by alt. I have tried to use the blotFormatter module but it still does not work. Honestly I do not know how blotFormatter works. Please help.
Here is my code

```<code>`import React, { useEffect, useState, useRef } from 'react';
import dynamic from 'next/dynamic';
import { useQuill } from 'react-quilljs';

// const BlotFormatter =
//   typeof window === 'object'
//     ? require('quill-blot-formatter')
//     : () => false;

const BlotFormatter = dynamic(
  () => {
    import('quill-blot-formatter');
  },
  { ssr: false, loading: () => <p>Text Editor Loading...</p> }
);

const TOOLBAR_OPTIONS = [
  [{ header: [1, 2, 3, 4, 5, 6, false] }],
  [{ font: [] }],
  [{ list: 'ordered' }, { list: 'bullet' }],
  ['bold', 'italic', 'underline', 'strike'],
  [{ indent: '-1' }, { indent: '+1' }, { align: [] }],
  [{ color: [] }, { background: [] }],
  [{ script: 'sub' }, { script: 'super' }],
  [{ align: [] }],
  ['image', 'blockquote', 'code-block'],
  ['clean'],
];

const QuillEditor = () => {
  const { quill, quillRef, Quill } = useQuill({
    modules: {
      toolbar: {
        container: TOOLBAR_OPTIONS,
      },
    },
    blotFormatter: {},
    clipboard: {
      // toggle to add extra line breaks when pasting HTML:
      matchVisual: false,
    },
    theme: 'snow',
    placeholder: 'Describe your question',
  });
  const openInputImageRef = useRef();

  if (Quill && !quill) {
    Quill.register('modules/blotFormatter', BlotFormatter);
  }

  useEffect(() => {
    if (quill) {
      quill.getModule('toolbar').addHandler('image', imageHandler);
      quill.getModule('blotFormatter');
    }
  }, [quill, Quill]);

  const imageHandler = () => {
    openInputImageRef.current.click();
  };

  //   handle image insertions
  const quillImageCallback = (e) => {
    e.preventDefault();
    e.stopPropagation();

    if (
      e.currentTarget &&
      e.currentTarget.files &&
      e.currentTarget.files.length > 0
    ) {
      const file = e.currentTarget.files[0];
      let formData = new FormData();
      formData.append(file.name, file);
      // create an objectUrl for the file
      const url = URL.createObjectURL(file);
      console.log(url);

      //   display the image on quill
      quill.focus();
      let range = quill.getSelection();
      let position = range ? range.index : 0;
      console.log('position....', position);

      quill.insertEmbed(
        position,
        'image',
        url,
        Quill.sources.USER
      );
      quill.setSelection(position + 1);
    }
  };`

  return (
    <div>
      <div ref={quillRef} />
      <div>
        <input
          type="file"
          accept="image/*"
          ref={openInputImageRef}
          onChange={(e) => quillImageCallback(e)}
          className="hidden"
        />
      </div>
    </div>
  );
};

export default QuillEditor;

</code>```

I am currently working on a project that works like stack overflow. In the project people can ask questions which have titles, describe their questions including posting images and add tags for topical targeting. For the rich text editor, I chose Quill. Quill handles image uploads by converting images to base 64. I however, prefer to handle images as formData objects. I tried to handle image uploads independently so that I could store them separately in a file system. After searching throughout the internet, I found ways to use the imageHandler in next js. In my imageHandler, I create an objectUrl using the URL.createObjectUrl() method and then insertEmbed it to quill for display to the user. However, quill only displays an image icon. Registering the blotFormatter module does not also work. I also admit that I do not understand how blotFormatter works exactly. I have seen some code snippets where people use Class components but it does not seem to work for me. Please advise me on how to go about this problem.

Quill displays an image icon

Body:
I am using quill in Next.js and I have ran into a problem. Instead of using the default base64 encoding for images, I have added a custom handler that creates an object url for the images and I later pass it to the quill.insertEmbed() method. However, once I go to the browser, quill only displays an image icon like the one displayed by alt. I have tried to use the blotFormatter module but it still does not work. Honestly I do not know how blotFormatter works. Please help.
Here is my code

`import React, { useEffect, useState, useRef } from 'react';
import dynamic from 'next/dynamic';
import { useQuill } from 'react-quilljs';

// const BlotFormatter =
//   typeof window === 'object'
//     ? require('quill-blot-formatter')
//     : () => false;

const BlotFormatter = dynamic(
  () => {
    import('quill-blot-formatter');
  },
  { ssr: false, loading: () =>
Text Editor Loading...
 }
);

const TOOLBAR_OPTIONS = [
  [{ header: [1, 2, 3, 4, 5, 6, false] }],
  [{ font: [] }],
  [{ list: 'ordered' }, { list: 'bullet' }],
  ['bold', 'italic', 'underline', 'strike'],
  [{ indent: '-1' }, { indent: '+1' }, { align: [] }],
  [{ color: [] }, { background: [] }],
  [{ script: 'sub' }, { script: 'super' }],
  [{ align: [] }],
  ['image', 'blockquote', 'code-block'],
  ['clean'],
];

const QuillEditor = () => {
  const { quill, quillRef, Quill } = useQuill({
    modules: {
      toolbar: {
        container: TOOLBAR_OPTIONS,
      },
    },
    blotFormatter: {},
    clipboard: {
      // toggle to add extra line breaks when pasting HTML:
      matchVisual: false,
    },
    theme: 'snow',
    placeholder: 'Describe your question',
  });
  const openInputImageRef = useRef();

  if (Quill && !quill) {
    Quill.register('modules/blotFormatter', BlotFormatter);
  }

  useEffect(() => {
    if (quill) {
      quill.getModule('toolbar').addHandler('image', imageHandler);
      quill.getModule('blotFormatter');
    }
  }, [quill, Quill]);

  const imageHandler = () => {
    openInputImageRef.current.click();
  };

  //   handle image insertions
  const quillImageCallback = (e) => {
    e.preventDefault();
    e.stopPropagation();

    if (
      e.currentTarget &&
      e.currentTarget.files &&
      e.currentTarget.files.length > 0
    ) {
      const file = e.currentTarget.files[0];
      let formData = new FormData();
      formData.append(file.name, file);
      // create an objectUrl for the file
      const url = URL.createObjectURL(file);
      console.log(url);

      //   display the image on quill
      quill.focus();
      let range = quill.getSelection();
      let position = range ? range.index : 0;
      console.log('position....', position);

      quill.insertEmbed(
        position,
        'image',
        url,
        Quill.sources.USER
      );
      quill.setSelection(position + 1);
    }
  };`

  return (

        <input
          type="file"
          accept="image/*"
          ref={openInputImageRef}
          onChange={(e) => quillImageCallback(e)}
          className="hidden"
        />

  );
};

export default QuillEditor;

I am currently working on a project that works like stack overflow. In the project people can ask questions which have titles, describe their questions including posting images and add tags for topical targeting. For the rich text editor, I chose Quill. Quill handles image uploads by converting images to base 64. I however, prefer to handle images as formData objects. I tried to handle image uploads independently so that I could store them separately in a file system. After searching throughout the internet, I found ways to use the imageHandler in next js. In my imageHandler, I create an objectUrl using the URL.createObjectUrl() method and then insertEmbed it to quill for display to the user. However, quill only displays an image icon. Registering the blotFormatter module does not also work. I also admit that I do not understand how blotFormatter works exactly. I have seen some code snippets where people use Class components but it does not seem to work for me. Please advise me on how to go about this problem.

Quill displays an image icon


来源: stackexchange

问:
Could Google Colab display Traditional Chinese fonts except "TaipeiSansTCBeta" in Matplotlib plots?
To whom it may concern:

Thank you for your time.
Here are some codes about drawing a matplotlib plot with Traditional-Chinese labels and legends which can work well in Colab.

```<code>import matplotlib as mpl,matplotlib.font_manager as mf,matplotlib.pyplot as plt

!wget -O TaipeiSansTCBeta-Regular.ttf https://drive.google.com/uc?id=1eGAsTN1HBpJAkeVM57_C7ccp7hbgSz3_&export=download
mf.fontManager.addfont('TaipeiSansTCBeta-Regular.ttf')
mpl.rc('font',family='Taipei Sans TC Beta')

lg=("明度高","\n亮度高","頻率高","\n摩擦力小","密度大")
xt=("純墨條","高筋麵粉","在來米粉","鹽","洗碗精","小蘇打粉","酵母")

a=(-1.06166376,-2.56410256,-15.21126761,-19.04761905,35.2941176470)
b=(0,0,-9.15492958,-42.85714285714285714,29.4117647058)
c=(-6.67539267,-15.38461538,-45.49295775,-47.61904762,17.6470588235)
d=(-9.08958697,-20.5128205,15.21126761,9.52380952,11.7647058823)
e=(-7.86794648,-17.94871795,0,-17.94871795,11.7647058823)
f=(-3.25770797,-7.69230769,-6.05633803,-52.38095238,-5.882352941176)
x=(0,0,0,0,0)
yd=(x,a,b,c,d,e,f)

fig,ax=plt.subplots(figsize=(4,5),dpi=300)
for i in range(0,len(xt)):
    ax.plot(lg,yd[i],label=xt[i],marker="o")

ptxk=["x-large","k"]
ax.tick_params(axis="x",labelsize=ptxk[0],colors=ptxk[1])
ax.tick_params(axis="y",labelsize="small")

ptt=["『定期定額』vs『定期定額逢低加碼』","x-large","k"]
ptlyl=["各\n變\n因\n較\n無\n添\n加\n墨\n百\n分\n比\n變\n化\n率\n(%)","x-large","darkcyan"]
plt.title(ptt[0],fontsize=ptt[1],color=ptt[2],y=-0.25)
ax.set_ylabel(ptlyl[0],fontsize=ptlyl[1],color=ptlyl[2],rotation=0)

ax.set_yticks([*range(-50,71,10)])
ax.yaxis.set_label_coords(-0.17,0.05)
ax.legend(fontsize="large")
ax.set_axisbelow(True)

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

The words in labels and legends only work well with the font called "TaipeiSansTCBeta" like the following picture.
(https://i.stack.imgur.com/CJfas.png)

Could the font be changed to another one like "DFKai-SB", or it only supports "TaipeiSansTCBeta"?

Some information on the internet about this is to add the codes below to line 2, and delete the codes about !wget, font_manager,  and mpl.rc. But it doesn't work at all by displaying blank blocks.

```<code>mpl.rcParams['font.family'] = 'DFKai-SB'
</code>```

(https://i.stack.imgur.com/EmMdL.png)

Would you please inform some demonstrations about the problem, or giving some clues to figure out how it works?

So far haven't found any answer to change to another Chinese font in Colab with matplotlib. It's highly appreciate for your guidance.

Best wishes and great thanks,
wish you have a happy new year.

ContentLicense: CC BY-SA 4.0

Body:
To whom it may concern:

Thank you for your time.
Here are some codes about drawing a matplotlib plot with Traditional-Chinese labels and legends which can work well in Colab.

import matplotlib as mpl,matplotlib.font_manager as mf,matplotlib.pyplot as plt

!wget -O TaipeiSansTCBeta-Regular.ttf https://drive.google.com/uc?id=1eGAsTN1HBpJAkeVM57_C7ccp7hbgSz3_&export=download
mf.fontManager.addfont('TaipeiSansTCBeta-Regular.ttf')
mpl.rc('font',family='Taipei Sans TC Beta')

lg=("明度高","\n亮度高","頻率高","\n摩擦力小","密度大")
xt=("純墨條","高筋麵粉","在來米粉","鹽","洗碗精","小蘇打粉","酵母")

a=(-1.06166376,-2.56410256,-15.21126761,-19.04761905,35.2941176470)
b=(0,0,-9.15492958,-42.85714285714285714,29.4117647058)
c=(-6.67539267,-15.38461538,-45.49295775,-47.61904762,17.6470588235)
d=(-9.08958697,-20.5128205,15.21126761,9.52380952,11.7647058823)
e=(-7.86794648,-17.94871795,0,-17.94871795,11.7647058823)
f=(-3.25770797,-7.69230769,-6.05633803,-52.38095238,-5.882352941176)
x=(0,0,0,0,0)
yd=(x,a,b,c,d,e,f)

fig,ax=plt.subplots(figsize=(4,5),dpi=300)
for i in range(0,len(xt)):
    ax.plot(lg,yd[i],label=xt[i],marker="o")

ptxk=["x-large","k"]
ax.tick_params(axis="x",labelsize=ptxk[0],colors=ptxk[1])
ax.tick_params(axis="y",labelsize="small")

ptt=["『定期定額』vs『定期定額逢低加碼』","x-large","k"]
ptlyl=["各\n變\n因\n較\n無\n添\n加\n墨\n百\n分\n比\n變\n化\n率\n(%)","x-large","darkcyan"]
plt.title(ptt[0],fontsize=ptt[1],color=ptt[2],y=-0.25)
ax.set_ylabel(ptlyl[0],fontsize=ptlyl[1],color=ptlyl[2],rotation=0)

ax.set_yticks([*range(-50,71,10)])
ax.yaxis.set_label_coords(-0.17,0.05)
ax.legend(fontsize="large")
ax.set_axisbelow(True)

plt.grid()
plt.show()

The words in labels and legends only work well with the font called "TaipeiSansTCBeta" like the following picture.
(https://i.stack.imgur.com/CJfas.png)

Could the font be changed to another one like "DFKai-SB", or it only supports "TaipeiSansTCBeta"?

Some information on the internet about this is to add the codes below to line 2, and delete the codes about !wget, font_manager,  and mpl.rc. But it doesn't work at all by displaying blank blocks.

mpl.rcParams['font.family'] = 'DFKai-SB'

(https://i.stack.imgur.com/EmMdL.png)

Would you please inform some demonstrations about the problem, or giving some clues to figure out how it works?

So far haven't found any answer to change to another Chinese font in Colab with matplotlib. It's highly appreciate for your guidance.

Best wishes and great thanks,
wish you have a happy new year.


问:
Can I somehow know in Lua how many arguments a function has beforehand?
I didn't think so, but since accordingly to THIS other languages seem to have a way... Do you think it'd be possible to know how many arguments a function requires even before it is really run/called?

My intention is have the chance to run or not a certain function in base of its arguments count in order to make sure (or more sure at least) my scripts are not going to run the wrong function while parsing all of the possible function container tables in _G, in order to avoid possible error messages just in case another user has a namesake one (which can be more or less probable depending on the function's name).

P.S. Or, of course, another way to can differentiate one function from another before running it in base of its arguments (or not) that you could think?


问:
Return specific rows from an array
I have a masterdata, which I update often. From this masterdata, I paste region specific data on seperate excel sheets. I do this by copying and pasting the data with the help of filtering.

Here is a sample of the masterdata (1st picture), and final product in which i filter the data to:

Is there a way to automate this? I.e., can I start using some formula that allows me to only update the masterdata in such a way that all the region sheets also update?

Title: Return specific rows from an array


问:
Is there any way of extracting the xpath of an HTML element using a javascript code or any other tool?

I am trying to extract and store xpath of some components of an web application for example a comment component of an instagram post. Is there any way either by executing javascript at frontend or by automation through selenium python through which I can get the xpath of such elements?

I tried researching a way through which I can automate the method we use to get the xpath using copy full xpath using chrome developer tool


问:
Why do key presses sometimes work and sometimes not?
I have some code to check if "q" is pressed and then I make an instance of a class. The problem is that sometimes it recognizes a press of the button and sometimes it doesn't. For example if I press "q" 10 times, sometimes it will recognize the press 3 times, sometimes 6 times, sometimes 7 times. So how can I fix it so it will recognize the press every single time? Some people said that it's probably because I call pygame.event.get() multiple times. Because of that I have tried getting events once in the whole script, but it's still the same result.

Code:

```<code>pygame.init()

fpsClock = pygame.time.Clock()
screen = pygame.display.set_mode((1920, 1080)

while True:

  #Input
  self.events = self.pygame.event.get()
  for event in self.events:
    if event.type == self.QUIT:
      self.pygame.quit()
      self.sys.exit()

    if event.type == self.pygame.KEYDOWN:

      if event.key == self.pygame.K_q:
        #makes an instance

  pygame.display.flip()
  fpsClock.tick(60)
</code>```

Body:
I have some code to check if "q" is pressed and then I make an instance of a class. The problem is that sometimes it recognizes a press of the button and sometimes it doesn't. For example if I press "q" 10 times, sometimes it will recognize the press 3 times, sometimes 6 times, sometimes 7 times. So how can I fix it so it will recognize the press every single time? Some people said that it's probably because I call pygame.event.get() multiple times. Because of that I have tried getting events once in the whole script, but it's still the same result.

Code:

pygame.init()

fpsClock = pygame.time.Clock()
screen = pygame.display.set_mode((1920, 1080)

while True:

  #Input
  self.events = self.pygame.event.get()
  for event in self.events:
    if event.type == self.QUIT:
      self.pygame.quit()
      self.sys.exit()

    if event.type == self.pygame.KEYDOWN:

      if event.key == self.pygame.K_q:
        #makes an instance

  pygame.display.flip()
  fpsClock.tick(60)


问:
Beforeunload event is not working on mobile phone
I am using an beforeunload event, to notify user if he changed form without saving it, before closing the browser.
I am using it in Angular

Code exmaple:

```<code>  @HostListener('window:beforeunload', ['$event'])
  unloadNotification($event: BeforeUnloadEvent) {
    if (!this.hasFormChanged) return;
    $event.returnValue();
  }
</code>```

It works fine on PC/laptop, but doesn't work on mobile.

However, here it says that it doesn't work on mobile: https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event

I am a little bit lost with an alternative.. Do you have any suggestions?

Thanks to everyone for help.

Body:
I am using an beforeunload event, to notify user if he changed form without saving it, before closing the browser.
I am using it in Angular

Code exmaple:

  @HostListener('window:beforeunload', ['$event'])
  unloadNotification($event: BeforeUnloadEvent) {
    if (!this.hasFormChanged) return;
    $event.returnValue();
  }

It works fine on PC/laptop, but doesn't work on mobile.

However, here it says that it doesn't work on mobile: https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event

I am a little bit lost with an alternative.. Do you have any suggestions?

Thanks to everyone for help.


问:
Setup an empty YUM repo that will download and keep in local the RPM it is asked for
I'm trying to understand if its possible to setup the following :

A fresh CentOS 7.9 server (called A) that is configured as YUM repo but with 0 RPM to serve.

Setup this server as a YUM repo on another machine (called B) and when I do yum install XXX the server A will fetch the RPM asked from other more standard repo, store them locally and then send them to B.

The goal is to the end with a mirror that contains all the rpm and dependencies I need for offline installation.


问:
Replacing text in PDF file
I am struggling with the problem of replacement of text in PDF file. I found library from Apache: PDFBox. I try to run example code which is on GitHub: https://github.com/chadilukito/Apache-PdfBox-2-Examples/blob/master/ReplaceText.java

Could you tell me how can I run it in IntelliJ IDE ?

I have the project in Maven because I should use necessary dependencies. I tried to run in terminal typing "java org.example.ReplaceText Lorem ipsum input_dok output_dok" because I have input_dok file in PDF. I want to get output_dok file and replace text "Lorem" with "ipsum"

Title: Replacing text in PDF file


问:
Unexpected char printed in console
```<code>int main()
{
  char j[] = "abc";
  print(j);
}
</code>```

When I define print like this:

```<code>void print(const char *cp)
{
  if (cp)
  {
    while (*cp)
    {
      int i = *cp;
      cout << *cp;
      // cout << *cp << endl;
      cp++;
    }
  }
}
</code>```

The console is something like this (I can not copy the result property, so I use a screenshot)

The % like character is quite expected

However, when I put the endl the wired % character disappear

```<code>void print(const char *cp)
{
  if (cp)
  {
    while (*cp)
    {
      int i = *cp;
      // cout << *cp;
      cout << *cp << endl;
      cp++;
    }
  }
}
</code>```

Could anyone help explain what happen?

I do not think % is not part of the prompt

I change my prompt the a text 'a', and the % still present

Title: Unexpected char printed in console

Body:
int main()
{
  char j[] = "abc";
  print(j);
}

When I define print like this:

void print(const char *cp)
{
  if (cp)
  {
    while (*cp)
    {
      int i = *cp;
      cout << *cp;
      // cout << *cp << endl;
      cp++;
    }
  }
}

The console is something like this (I can not copy the result property, so I use a screenshot)

The % like character is quite expected

However, when I put the endl the wired % character disappear

void print(const char *cp)
{
  if (cp)
  {
    while (*cp)
    {
      int i = *cp;
      // cout << *cp;
      cout << *cp << endl;
      cp++;
    }
  }
}

Could anyone help explain what happen?

I do not think % is not part of the prompt

I change my prompt the a text 'a', and the % still present


问:
ADuCM360 Microcontroller Hard Fault
We are Producing a device based on ADuCM360 Microcontroller. We have bought 200 PCs of ADuCM360 from China distributors and mount all of them on PCBs. After programming them I discovered that none of the boards work. after debugging I found out that ADuCM360 stuck in Hardfault exception after reset.
We have been using ADuCM360 for a long time and we haven't had any issue with them until now. Last year we purchased 100 PCs of ADuCM360 and all of them are working correctly.

I will describe the problem in detail so you can give me a hint to solve this problem.

I use j-link debugger
Keil uVision
and ADuCM360 Evaluation board

I programmed the evaluation Board with simple blinker example code.
I start debugging mode and the program execution is stopped at hardfault Handler as shown in picture below.

enter image description here

when I searched for caller code of hartfault the device is stopped at address @0x0001FFFC as shown below

enter image description here

I discovered that on the healthy ADuCM360 this block of flash is not readable by debugger (Address from @ 0x00020000 to @0x00020800). But in the faulty ADuCM360 these addresses have access to write and read.

I hope that you can help me find out the reason and solution for this problem.
Thanks

Title: ADuCM360 Microcontroller Hard Fault


问:
Can´t generate a JAR file properly
I am generating a .JAR from an app. I can run the app from NetBeans with no problem, but when I generate the .JAR it's impossible to open it.

I've selected the right main class in the properties, so I don't really know why this happens.

When I try to execute the .JAR it just pops up, and then closes in a blink.

The main() selection:

Title: Can´t generate a JAR file properly


问:
POST to one-to-many relationship table raise ValidationError "Unknown field."
I am trying to implement hospital api with to one-to-many relationship table (Subject - is Parent table, RawData - child table), with flask-api, marshmellow and flask-sqlalchemy frameworks. After implementing schemes, models and resource, I make post method with raw json, through postman in endpoint /api/upload/subject:

```<code>{
    "first_name": "Johny",
    "last_name": "Silverhand",
    "raw_tomograms": [
        {
            "rawdata_id": 1,
            "raw_name": "subject_1",
            "path": "/srv/John_s_rawdata.zip",
            "subject_id": 1
        }
    ]
}
</code>```

But get an error marshmallow.exceptions.ValidationError: {'raw_tomograms': {0: {'rawdata_id': ['Unknown field.'], 'raw_name': ['Unknown field.'], 'path': ['Unknown field.']}}}

Models:

#./api/models/subject.py:

```<code>from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from api.database import db

class Subject(db.Model):

    __tablename__ = "subject"

    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(50), nullable=True)
    last_name = db.Column(db.String(50), nullable=True)
    raw_tomograms = db.relationship("RawData", backref="subject", lazy=True)
    create_date = db.Column(db.DateTime(timezone=True), default=datetime.now())
    update_date = db.Column(db.DateTime(timezone=True), onupdate=datetime.now())

    def __repr__(self):
        return "<Subject {self.id} {self.first_name>"
</code>```

#./api/models/rawdata.py:

```<code>from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from api.database import db

class RawData(db.Model):

    __tablename__ = "raw_data"

    id = db.Column(db.Integer, primary_key=True)
    raw_name = db.Column(db.String(120), nullable=False)
    path = db.Column(db.String(250))
    create_date = db.Column(db.DateTime(timezone=True), default=datetime.now)
    update_date = db.Column(db.DateTime(timezone=True), onupdate=datetime.now)

    subject_id = db.Column(db.Integer, db.ForeignKey("subject.id"))

    def __repr__(self):
        return f"<Raw_data {self.id}>"
</code>```

Schemas:
#./api/schemas/rawdata.py:

```<code>from marshmallow import Schema, fields, post_load, EXCLUDE
from api.models.rawdata import RawData
from api.models.subject import Subject
from api.database import db
from api.database import ma

class RawSchema(Schema):
    rawdata_id = fields.Integer(),
    raw_name = fields.String(),
    path = fields.String(),
    create_date = fields.DateTime(timezone=True)
    update_date = fields.DateTime(timezone=True)
    subject_id = fields.Integer()

    @post_load
    def make_rawdata(self, data, **kwargs):
        return RawData(**data)
</code>```

#./api/schemas/subjecta.py:

```<code>from marshmallow import Schema, fields, post_load
from epidetect_api.models.subject import Subject
from epidetect_api.database import db
#from epidetect_api.database import ma
from epidetect_api.schemas.rawdata_schema import RawSchema

class SubjectSchema(Schema):
    """
    Subject Marshmallow Schema

    Marshmallow schema used for loading/dumping Subject
    """
    #raw_tomograms = ma.Nested(RawSchema, many=True)
    class Meta:
        model = Subject
        #exclude =
    id = fields.Integer(load=True, partial=True)
    first_name = fields.String(allow_none=True)
    last_name = fields.String(allow_none=True)
    create_date = fields.DateTime(timezone=True)
    update_date = fields.DateTime(timezone=True)
    raw_tomograms = fields.Nested(RawSchema, many=True)

    @post_load
    def make_subject(self, data, **kwargs):
        return Subject(**data)
</code>```

Resource:
#./api/resources/subject_resource.py

```<code>import logging

from flask import request, jsonify, render_template
from flask_restful import Resource, abort
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm.exc import NoResultFound
import json

from api.database import db
from api.models.subject import Subject
from api.schemas.subject_schema import SubjectSchema

SUBJECTS_ENDPOINT = "/api/upload/subject"
logger = logging.getLogger(__name__)

class SubjectsResource(Resource):
    def post(self):
        """
        SubjectsResource POST method. Adds a new Subject to the database.

        :return: Subject.id, 201 HTTP status code.
        """
        subject = SubjectSchema().load(request.json)
        print(request.json, flush=True)
        try:
            db.session.add(subject)
            db.session.commit()
        except IntegrityError as e:
            logger.warning(
                f"Integrity Error, this subject is already in the database. Error: {e}"
            )
            abort(500, message="Unexpected Error!")
        else:
            return subject.id, 201
</code>```

Full error log:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2091, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2076, in wsgi_app
    response = self.handle_exception(e)
  File "/usr/local/lib/python3.7/site-packages/flask_restful/__init__.py", line 271, in error_router
    return original_handler(e)
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2073, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1518, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.7/site-packages/flask_restful/__init__.py", line 271, in error_router
    return original_handler(e)
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1516, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1502, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "/usr/local/lib/python3.7/site-packages/flask_restful/__init__.py", line 467, in wrapper
    resp = resource(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/flask/views.py", line 84, in view
    return current_app.ensure_sync(self.dispatch_request)(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/flask_restful/__init__.py", line 582, in dispatch_request
    resp = meth(*args, **kwargs)
  File "/srv/api/resources/subject_resource.py", line 48, in post
    subject = SubjectSchema().load(request.json)
  File "/usr/local/lib/python3.7/site-packages/marshmallow/schema.py", line 720, in load
    data, many=many, partial=partial, unknown=unknown, postprocess=True
  File "/usr/local/lib/python3.7/site-packages/marshmallow/schema.py", line 904, in _do_load
    raise exc
marshmallow.exceptions.ValidationError: {'raw_tomograms': {0: {'rawdata_id': ['Unknown field.'], 'raw_name': ['Unknown field.'], 'path': ['Unknown field.']}}}
</code>```

Body:
I am trying to implement hospital api with to one-to-many relationship table (Subject - is Parent table, RawData - child table), with flask-api, marshmellow and flask-sqlalchemy frameworks. After implementing schemes, models and resource, I make post method with raw json, through postman in endpoint /api/upload/subject:

{
    "first_name": "Johny",
    "last_name": "Silverhand",
    "raw_tomograms": [
        {
            "rawdata_id": 1,
            "raw_name": "subject_1",
            "path": "/srv/John_s_rawdata.zip",
            "subject_id": 1
        }
    ]
}

But get an error marshmallow.exceptions.ValidationError: {'raw_tomograms': {0: {'rawdata_id': ['Unknown field.'], 'raw_name': ['Unknown field.'], 'path': ['Unknown field.']}}}

Models:

#./api/models/subject.py:

from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from api.database import db

class Subject(db.Model):

    __tablename__ = "subject"

    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(50), nullable=True)
    last_name = db.Column(db.String(50), nullable=True)
    raw_tomograms = db.relationship("RawData", backref="subject", lazy=True)
    create_date = db.Column(db.DateTime(timezone=True), default=datetime.now())
    update_date = db.Column(db.DateTime(timezone=True), onupdate=datetime.now())

    def __repr__(self):
        return "<Subject {self.id} {self.first_name>"

#./api/models/rawdata.py:

from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from api.database import db

class RawData(db.Model):

    __tablename__ = "raw_data"

    id = db.Column(db.Integer, primary_key=True)
    raw_name = db.Column(db.String(120), nullable=False)
    path = db.Column(db.String(250))
    create_date = db.Column(db.DateTime(timezone=True), default=datetime.now)
    update_date = db.Column(db.DateTime(timezone=True), onupdate=datetime.now)

    subject_id = db.Column(db.Integer, db.ForeignKey("subject.id"))

    def __repr__(self):
        return f"<Raw_data {self.id}>"

Schemas:
#./api/schemas/rawdata.py:

from marshmallow import Schema, fields, post_load, EXCLUDE
from api.models.rawdata import RawData
from api.models.subject import Subject
from api.database import db
from api.database import ma

class RawSchema(Schema):
    rawdata_id = fields.Integer(),
    raw_name = fields.String(),
    path = fields.String(),
    create_date = fields.DateTime(timezone=True)
    update_date = fields.DateTime(timezone=True)
    subject_id = fields.Integer()

    @post_load
    def make_rawdata(self, data, **kwargs):
        return RawData(**data)

#./api/schemas/subjecta.py:

from marshmallow import Schema, fields, post_load
from epidetect_api.models.subject import Subject
from epidetect_api.database import db
#from epidetect_api.database import ma
from epidetect_api.schemas.rawdata_schema import RawSchema

class SubjectSchema(Schema):
    """
    Subject Marshmallow Schema

    Marshmallow schema used for loading/dumping Subject
    """
    #raw_tomograms = ma.Nested(RawSchema, many=True)
    class Meta:
        model = Subject
        #exclude =
    id = fields.Integer(load=True, partial=True)
    first_name = fields.String(allow_none=True)
    last_name = fields.String(allow_none=True)
    create_date = fields.DateTime(timezone=True)
    update_date = fields.DateTime(timezone=True)
    raw_tomograms = fields.Nested(RawSchema, many=True)

    @post_load
    def make_subject(self, data, **kwargs):
        return Subject(**data)

Resource:
#./api/resources/subject_resource.py

import logging

from flask import request, jsonify, render_template
from flask_restful import Resource, abort
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm.exc import NoResultFound
import json

from api.database import db
from api.models.subject import Subject
from api.schemas.subject_schema import SubjectSchema

SUBJECTS_ENDPOINT = "/api/upload/subject"
logger = logging.getLogger(__name__)

class SubjectsResource(Resource):
    def post(self):
        """
        SubjectsResource POST method. Adds a new Subject to the database.

        :return: Subject.id, 201 HTTP status code.
        """
        subject = SubjectSchema().load(request.json)
        print(request.json, flush=True)
        try:
            db.session.add(subject)
            db.session.commit()
        except IntegrityError as e:
            logger.warning(
                f"Integrity Error, this subject is already in the database. Error: {e}"
            )
            abort(500, message="Unexpected Error!")
        else:
            return subject.id, 201

Full error log:

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2091, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2076, in wsgi_app
    response = self.handle_exception(e)
  File "/usr/local/lib/python3.7/site-packages/flask_restful/__init__.py", line 271, in error_router
    return original_handler(e)
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2073, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1518, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.7/site-packages/flask_restful/__init__.py", line 271, in error_router
    return original_handler(e)
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1516, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1502, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "/usr/local/lib/python3.7/site-packages/flask_restful/__init__.py", line 467, in wrapper
    resp = resource(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/flask/views.py", line 84, in view
    return current_app.ensure_sync(self.dispatch_request)(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/flask_restful/__init__.py", line 582, in dispatch_request
    resp = meth(*args, **kwargs)
  File "/srv/api/resources/subject_resource.py", line 48, in post
    subject = SubjectSchema().load(request.json)
  File "/usr/local/lib/python3.7/site-packages/marshmallow/schema.py", line 720, in load
    data, many=many, partial=partial, unknown=unknown, postprocess=True
  File "/usr/local/lib/python3.7/site-packages/marshmallow/schema.py", line 904, in _do_load
    raise exc
marshmallow.exceptions.ValidationError: {'raw_tomograms': {0: {'rawdata_id': ['Unknown field.'], 'raw_name': ['Unknown field.'], 'path': ['Unknown field.']}}}


问:
Logstash Custom JSON Pattern from xml
I'm trying to add custom json field into my logstash xml . I'm do this because trying to parse this fields and expecting to see kibana dashboard. So you can see my xml files below , globalSessionId field is my custom field. I'm new at ELK and so confused. I'm loggin somewhere this globalsessionId into my project but the project didn't even build and throw error. It's make sense globalSessionId is not a valid word but how can I do this valid ?

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <shutdownHook class="ch.qos.logback.core.hook.DelayingShutdownHook"/>
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
    <springProperty scope="context" name="APP_NAME" source="spring.application.name"/>
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
            <providers>
                <timestamp/>
                <version/>
                <pattern>
                    <pattern>
                        {
                        "logtime": "%d{yyyy-MM-dd HH:mm:ss.SSS,${TZ}}",
                        "thread": "%thread",
                        "level": "%level",
                        "APP_NAME": "${APP_NAME}",
                        "msg": "%message",
                        "stackTrace": "%rEx{full}",
                        "globalSessionId" : "%globalSessionId"
                        }
                    </pattern>
                </pattern>
            </providers>
        </encoder>
    </appender>
    <root level="INFO">
        <appender-ref ref="CONSOLE"/>
    </root>
</configuration>
</code>```

Any suggestion would be appreaciated

Title: Logstash Custom JSON Pattern from xml

Body:
I'm trying to add custom json field into my logstash xml . I'm do this because trying to parse this fields and expecting to see kibana dashboard. So you can see my xml files below , globalSessionId field is my custom field. I'm new at ELK and so confused. I'm loggin somewhere this globalsessionId into my project but the project didn't even build and throw error. It's make sense globalSessionId is not a valid word but how can I do this valid ?

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <shutdownHook class="ch.qos.logback.core.hook.DelayingShutdownHook"/>
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
    <springProperty scope="context" name="APP_NAME" source="spring.application.name"/>
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
            <providers>
                <timestamp/>
                <version/>
                <pattern>
                    <pattern>
                        {
                        "logtime": "%d{yyyy-MM-dd HH:mm:ss.SSS,${TZ}}",
                        "thread": "%thread",
                        "level": "%level",
                        "APP_NAME": "${APP_NAME}",
                        "msg": "%message",
                        "stackTrace": "%rEx{full}",
                        "globalSessionId" : "%globalSessionId"
                        }
                    </pattern>
                </pattern>
            </providers>
        </encoder>
    </appender>
    <root level="INFO">
        <appender-ref ref="CONSOLE"/>
    </root>
</configuration>

Any suggestion would be appreaciated


问:
Multiple Routes in Swagger
I'm trying to make two different routes in swagger as but both APIs show me the same endpoints. What I understand from this is somehow different routes don't register. How can I make it so?

```<code>import swaggerJSDoc from 'swagger-jsdoc'

export const swaggerPublicSpec = swaggerJSDoc({
  definition: {
    //***
      }
    }
  },
  apis: ['./docs/**/*.yaml', './src/**/openapi-public.yaml']
})

export const swaggerPrivateSpec = swaggerJSDoc({
  definition: {
    //***
      }
    }
  },
  apis: ['./docs/**/*.yaml', './src/**/openapi.yaml']
})

</code>```

This is their express app

```<code>appInstance.use('/docs', swaggerUI.serve, swaggerUI.setup(swaggerPublicSpec, { explorer: true }))
appInstance.use('/private-docs', swaggerUI.serve, swaggerUI.setup(swaggerPrivateSpec, { explorer: true }))
</code>```

Title: Multiple Routes in Swagger

Body:
I'm trying to make two different routes in swagger as but both APIs show me the same endpoints. What I understand from this is somehow different routes don't register. How can I make it so?

import swaggerJSDoc from 'swagger-jsdoc'

export const swaggerPublicSpec = swaggerJSDoc({
  definition: {
    //***
      }
    }
  },
  apis: ['./docs/**/*.yaml', './src/**/openapi-public.yaml']
})

export const swaggerPrivateSpec = swaggerJSDoc({
  definition: {
    //***
      }
    }
  },
  apis: ['./docs/**/*.yaml', './src/**/openapi.yaml']
})

This is their express app

appInstance.use('/docs', swaggerUI.serve, swaggerUI.setup(swaggerPublicSpec, { explorer: true }))
appInstance.use('/private-docs', swaggerUI.serve, swaggerUI.setup(swaggerPrivateSpec, { explorer: true }))


问:
setState (array) entries are disappearing
In the following example, User2's messages are getting erased from the state as soon as the User1 sends a message.

User1 sends a message, it gets displayed on screen. As soon as User2 replies, User1's messages disappear.

I'm persuaded it's a React setState mistake but I've followed the react-native-chat-ui's docs as much as possible but somehow there is something going wrong and I cannot put my finger on it.

Here's a video of the bug in action: https://streamable.com/rxbx18

Thank you.

```<code>import React, { useEffect, useState } from 'react';
import { Chat, MessageType } from '@flyerhq/react-native-chat-ui'
import { SafeAreaProvider } from 'react-native-safe-area-context'

const uuidv4 = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = Math.floor(Math.random() * 16)
    const v = c === 'x' ? r : (r % 4) + 8
    return v.toString(16)
  })
};

const user    = { id: uuidv4(), firstName: 'User1' };
const chatbot = { id: uuidv4(), firstName: 'User2' };

const App = () => {
  const [messages, setMessages] = useState<MessageType.Any[]>([])

  const addMessage = (message: MessageType.Any) => {
    setMessages([message, ...messages]);
  };

  const handleSendPress = (message: MessageType.PartialText) => {
    // display user message
    const textMessage: MessageType.Text = {
      author   : user,
      createdAt: Date.now(),
      id       : uuidv4(),
      text     : message.text,
      type     : 'text',
    };
    addMessage(textMessage);

    // display bot message
    // NOTE: adding a timeout so that you can see user's message for a second...
    setTimeout(() => {
      const chatbotTextMessage: MessageType.Text = {
        author   : chatbot,
        createdAt: Date.now(),
        id       : uuidv4(),
        text     : `Response that will erase user's messages...`,
        type     : 'text',
      };
      addMessage(chatbotTextMessage);
    }, 1000);
  };

  return (
    <SafeAreaProvider>
    <Chat
      messages={messages}
      showUserNames={true}
      onSendPress={handleSendPress}
      user={user}
    />
  </SafeAreaProvider>
  );
}

export default App;
</code>```

Body:
In the following example, User2's messages are getting erased from the state as soon as the User1 sends a message.

User1 sends a message, it gets displayed on screen. As soon as User2 replies, User1's messages disappear.

I'm persuaded it's a React setState mistake but I've followed the react-native-chat-ui's docs as much as possible but somehow there is something going wrong and I cannot put my finger on it.

Here's a video of the bug in action: https://streamable.com/rxbx18

Thank you.

import React, { useEffect, useState } from 'react';
import { Chat, MessageType } from '@flyerhq/react-native-chat-ui'
import { SafeAreaProvider } from 'react-native-safe-area-context'

const uuidv4 = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = Math.floor(Math.random() * 16)
    const v = c === 'x' ? r : (r % 4) + 8
    return v.toString(16)
  })
};

const user    = { id: uuidv4(), firstName: 'User1' };
const chatbot = { id: uuidv4(), firstName: 'User2' };

const App = () => {
  const [messages, setMessages] = useState<MessageType.Any[]>([])

  const addMessage = (message: MessageType.Any) => {
    setMessages([message, ...messages]);
  };

  const handleSendPress = (message: MessageType.PartialText) => {
    // display user message
    const textMessage: MessageType.Text = {
      author   : user,
      createdAt: Date.now(),
      id       : uuidv4(),
      text     : message.text,
      type     : 'text',
    };
    addMessage(textMessage);

    // display bot message
    // NOTE: adding a timeout so that you can see user's message for a second...
    setTimeout(() => {
      const chatbotTextMessage: MessageType.Text = {
        author   : chatbot,
        createdAt: Date.now(),
        id       : uuidv4(),
        text     : `Response that will erase user's messages...`,
        type     : 'text',
      };
      addMessage(chatbotTextMessage);
    }, 1000);
  };

  return (
    <SafeAreaProvider>
    <Chat
      messages={messages}
      showUserNames={true}
      onSendPress={handleSendPress}
      user={user}
    />
  </SafeAreaProvider>
  );
}

export default App;


问:
Stubbing exported function with sinon, mocha, and swc fails
I am trying to stub the function exported from my ES module.

I used wildcard import(import * as) to stub it, and it works when ts-node is used for transpiling(mocha --require ts-node/register */**/*.spec.ts).

But when swc is used, it fails with the message below(mocha --require @swc/register */**/*.spec.ts).

```<code>TypeError: Descriptor for property validate is non-configurable and non-writable
</code>```

/* hash.ts */
import * as argon2 from 'argon2'

export async function encrypt(plain) {
  return await argon2.hash(plain)
}

export async function validate(hash, plain) {
  return await argon2.verify(hash, plain)
}
```
<pre class="lang-js prettyprint-override"><code>/* service.ts */
import { validate } from './hash'

export async function isValidUser(user: User, password: string) {
  if (!user || !(await validate(user.password, password))) {
    return false
  }
  return true
}
</code>```

/* service.spec.ts */
import * as hash from './hash'
import { isValidUser } from './service'
import { stub } from 'sinon'

describe('isValidUser', () => {
  stub(hash, 'validate').callsFake(
    async (passwordFormDB, passwordFromUserInput) =>
      passwordFromDB === passwordFromUserInput
  )

  it('...', async () => {
    /* test `isValidUser` function */
  })
})
```
<pre class="lang-json prettyprint-override"><code>// .swcrc
{
  "test": ".*.ts$",
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "decorators": true,
      "importMeta": true
    },
    "transform": {
      "legacyDecorator": true,
      "decoratorMetadata": true
    },
    "paths": {
      "src/*": ["./src/*"]
    }
  },
  "module": {
    "type": "commonjs",
    "noInterop": true
  }
}
</code>```

Body:
I am trying to stub the function exported from my ES module.

I used wildcard import(import * as) to stub it, and it works when ts-node is used for transpiling(mocha --require ts-node/register */**/*.spec.ts).

But when swc is used, it fails with the message below(mocha --require @swc/register */**/*.spec.ts).

TypeError: Descriptor for property validate is non-configurable and non-writable

/* hash.ts */
import * as argon2 from 'argon2'

export async function encrypt(plain) {
  return await argon2.hash(plain)
}

export async function validate(hash, plain) {
  return await argon2.verify(hash, plain)
}

/* service.ts */
import { validate } from './hash'

export async function isValidUser(user: User, password: string) {
  if (!user || !(await validate(user.password, password))) {
    return false
  }
  return true
}

/* service.spec.ts */
import * as hash from './hash'
import { isValidUser } from './service'
import { stub } from 'sinon'

describe('isValidUser', () => {
  stub(hash, 'validate').callsFake(
    async (passwordFormDB, passwordFromUserInput) =>
      passwordFromDB === passwordFromUserInput
  )

  it('...', async () => {
    /* test `isValidUser` function */
  })
})

// .swcrc
{
  "test": ".*.ts$",
  "jsc": {
    "parser": {
      "syntax": "typescript",
      "decorators": true,
      "importMeta": true
    },
    "transform": {
      "legacyDecorator": true,
      "decoratorMetadata": true
    },
    "paths": {
      "src/*": ["./src/*"]
    }
  },
  "module": {
    "type": "commonjs",
    "noInterop": true
  }
}


问:
Can't instantiate abstract class MnistModel with abstract methods federated_output_computation, report_local_outputs
I was running the Tensorflow Federated Learning for Image Classification with the given colab notebook, the error appears when running the cell below on the simulation of federated training with the new model.

```<code>training_process = tff.learning.algorithms.build_weighted_fed_avg(
MnistModel,
client_optimizer_fn=lambda:
tf.keras.optimizers.SGD(learning_rate=0.02))
</code>```

It seems there is a problem inside the tff.learning.Model instance created here.

Body:
I was running the Tensorflow Federated Learning for Image Classification with the given colab notebook, the error appears when running the cell below on the simulation of federated training with the new model.

training_process = tff.learning.algorithms.build_weighted_fed_avg(
MnistModel,
client_optimizer_fn=lambda:
tf.keras.optimizers.SGD(learning_rate=0.02))

It seems there is a problem inside the tff.learning.Model instance created here.


问:
How can I change a converter for testing purpose?
I am currently working on a project and have to deal with some test cases. We implementented cryptographie in our database to learn how it is build but now we have to update the tests. The crypto should be hidden or someway.

This is the converter we used and added @Convert in the entity classes like so

```<code>@Column(name ="name", nullable = false)
   @Convert(converter = DBEncryptedStringConverter.class)
   public EncryptedString getName() {
       return this.name;
   }

   public void setName(EncryptedString name) {
       this.name = name;
   }
</code>```
```<code>@Converter
@Slf4j
public class DBEncryptedStringConverter implements AttributeConverter<EncryptedString, String> {
    private static final String ENC = "ENC__##__", RAW = "RAW__##__";
    @Override
    public String convertToDatabaseColumn(EncryptedString attribute) {
        if(attribute == null) return null;
        return (attribute.isEncrypted() ? ENC : RAW) + attribute.getString();
    }

    @Override
    public EncryptedString convertToEntityAttribute(String dbData) {
        if(dbData == null) return null;
        if(dbData.startsWith(ENC)) {
            return new EncryptedString(dbData.substring(ENC.length()), true);
        } else if(dbData.startsWith(RAW)) {
            return new EncryptedString(dbData.substring(RAW.length()), false);
        } else {
            log.warn("DB Entry without prefix found");
            log.warn("Treating as RAW");
            return new EncryptedString(dbData, false);
        }
    }
}
</code>```

I would like to use this class for testing

```<code>@Converter
public class MockDBEncryptedStringConverter implements AttributeConverter<EncryptedString, String> {
    @Override
    public String convertToDatabaseColumn(EncryptedString attribute) {
        return attribute.getString();
    }

    @Override
    public EncryptedString convertToEntityAttribute(String dbData) {
        return new EncryptedString(dbData, false);
    }
}
</code>```

I think mokcing with mokito would be a way to go, but I dont quiet understand how to use it

Body:
I am currently working on a project and have to deal with some test cases. We implementented cryptographie in our database to learn how it is build but now we have to update the tests. The crypto should be hidden or someway.

This is the converter we used and added @Convert in the entity classes like so

@Column(name ="name", nullable = false)
   @Convert(converter = DBEncryptedStringConverter.class)
   public EncryptedString getName() {
       return this.name;
   }

   public void setName(EncryptedString name) {
       this.name = name;
   }

@Converter
@Slf4j
public class DBEncryptedStringConverter implements AttributeConverter<EncryptedString, String> {
    private static final String ENC = "ENC__##__", RAW = "RAW__##__";
    @Override
    public String convertToDatabaseColumn(EncryptedString attribute) {
        if(attribute == null) return null;
        return (attribute.isEncrypted() ? ENC : RAW) + attribute.getString();
    }

    @Override
    public EncryptedString convertToEntityAttribute(String dbData) {
        if(dbData == null) return null;
        if(dbData.startsWith(ENC)) {
            return new EncryptedString(dbData.substring(ENC.length()), true);
        } else if(dbData.startsWith(RAW)) {
            return new EncryptedString(dbData.substring(RAW.length()), false);
        } else {
            log.warn("DB Entry without prefix found");
            log.warn("Treating as RAW");
            return new EncryptedString(dbData, false);
        }
    }
}

I would like to use this class for testing

@Converter
public class MockDBEncryptedStringConverter implements AttributeConverter<EncryptedString, String> {
    @Override
    public String convertToDatabaseColumn(EncryptedString attribute) {
        return attribute.getString();
    }

    @Override
    public EncryptedString convertToEntityAttribute(String dbData) {
        return new EncryptedString(dbData, false);
    }
}

I think mokcing with mokito would be a way to go, but I dont quiet understand how to use it


问:
Ionic ion-modal text color is according to device's dark mode not the app's dark mode
I've changed the
@media (prefers-color-scheme: dark) in variables.css to a dark class and I'm checking to change to it with window.matchMedia('(prefers-color-scheme: dark)').matches in typescript. I also have a toggle to change it inside the app. Everything works fine, except some of ion-modal elements (which are inside ng-template), like this:

```<code><ion-modal>
  <ng-template>
      <ion-label>
        test
      </ion-label>
      <ion-text>
        test
      </ion-text>
  </ng-template>
</ion-modal>
</code>```

they are still obeying the device's dark mode, meaning that when I toggle to light mode inside a device that is set to dark mode, the text color stay white while the modal color turns white, make the text invisible. I don't understand if there is something I'm missing here.

I've tried to fix each of their colors manually as a temporary fix, but that might cause other problems and would make my code dirty. I'd appreciate it if anyone can point to me what I am missing here or what is the correct fix for having them follow my dark mode not the device's. here is my Ionic info:

```<code>Ionic:

   Ionic CLI                     : 6.17.1
   Ionic Framework               : @ionic/angular 6.1.9
   @angular-devkit/build-angular : 14.2.6
   @angular-devkit/schematics    : 13.2.6
   @angular/cli                  : 14.2.6
   @ionic/angular-toolkit        : 6.1.0

Capacitor:

   Capacitor CLI      : 3.5.1
   @capacitor/android : 3.5.1
   @capacitor/core    : 3.5.1
   @capacitor/ios     : 3.5.1

Utility:

   cordova-res : 0.15.4
   native-run  : 1.6.0

System:

   NodeJS : v16.15.1
   npm    : 8.12.1
   OS     : Windows 10

</code>```

Body:
I've changed the
@media (prefers-color-scheme: dark) in variables.css to a dark class and I'm checking to change to it with window.matchMedia('(prefers-color-scheme: dark)').matches in typescript. I also have a toggle to change it inside the app. Everything works fine, except some of ion-modal elements (which are inside ng-template), like this:

<ion-modal>
  <ng-template>
      <ion-label>
        test
      </ion-label>
      <ion-text>
        test
      </ion-text>
  </ng-template>
</ion-modal>

they are still obeying the device's dark mode, meaning that when I toggle to light mode inside a device that is set to dark mode, the text color stay white while the modal color turns white, make the text invisible. I don't understand if there is something I'm missing here.

I've tried to fix each of their colors manually as a temporary fix, but that might cause other problems and would make my code dirty. I'd appreciate it if anyone can point to me what I am missing here or what is the correct fix for having them follow my dark mode not the device's. here is my Ionic info:

Ionic:

   Ionic CLI                     : 6.17.1
   Ionic Framework               : @ionic/angular 6.1.9
   @angular-devkit/build-angular : 14.2.6
   @angular-devkit/schematics    : 13.2.6
   @angular/cli                  : 14.2.6
   @ionic/angular-toolkit        : 6.1.0

Capacitor:

   Capacitor CLI      : 3.5.1
   @capacitor/android : 3.5.1
   @capacitor/core    : 3.5.1
   @capacitor/ios     : 3.5.1

Utility:

   cordova-res : 0.15.4
   native-run  : 1.6.0

System:

   NodeJS : v16.15.1
   npm    : 8.12.1
   OS     : Windows 10


问:
How to change google sheets, when API changes using Zapier
Disclaimer, I'm new to API's.

I have an API key, that holds data for a bunch of different basketball games. I currently have all of the different games in a google sheets document, under which I have the column "scores". I want to update the google sheets column "scores" every time the API changes.

I want to do this using Zapier, but I have no idea how. I have a clue that I need to use Catch Hooks, but I can't seem to figure it out. I'm trying to follow this guide: https://help.zapier.com/hc/en-us/articles/8496288690317-Trigger-Zaps-from-webhooks#3-add-the-webhook-url-to-your-app-0-3

But I can't seem to figure out how to add a new Webhook or Callback Url.
Btw, my API is from API-Basketball (https://www.api-basketball.com) and is being handled in RapidAPI. Maybe that will help


问:
AWS Lambda pre-token generation not modyfying value of custom claims in Jenkins (python)
I'm trying to change/add user group for Jenkins.
I use cognito to log-in and then I Invoke lambda function to add another group for the users.

Here's my lambda function:

```<code>    # Read custom groups claim
        #groups_string = event['request']['userAttributes']['custom:groups']
        #custom_groups = json.loads(groups_string)

    # Overrive custom:groups claim
    event["response"]["claimsOverrideDetails"] = {
        "claimsToAddOrOverride": {
            'custom:groups': '["cognito-xxx-stg-dev"]'
            }
        }
    #raise Exception(str(event))
    return event
</code>```

When I uncomment exception I get error like this (request and response):

```<code>
  "error" : "PreTokenGeneration failed with error {'version': '1', 'triggerSource':
'TokenGeneration_HostedAuth', 'region': 'eu-central-1', 'userPoolId': 'eu-central-
1_xxxxx', 'userName': 'xxxxx', 'callerContext': {'awsSdkVersion': 'aws-sdk-unknown-
unknown', 'clientId': 'xxx'}, 'request': {'userAttributes': {'sub': 'xxx',
'cognito:user_status': 'EXTERNAL_PROVIDER', 'identities':
'[{\"userId\":\"xxx\",\"providerName\":\"xxx\",\"providerType\":\"OIDC\",\"issuer\":null
,\"primary\":true,\"dateCreated\":1668756777933}]', 'email_verified': 'false', 'name':
 'xxx', 'preferred_username': 'xxx', 'given_name': 'xxx', 'family_name': 'xxx',
'email': 'xxx', 'custom:groups': '[\"cognito-xxx-stg-admin\"]'}, 'groupConfiguration':
{'groupsToOverride': ['xxx'], 'iamRolesToOverride': [], 'preferredRole': None}},
'response': {'claimsOverrideDetails': {'claimsToAddOrOverride': {'custom:groups':
'[\"cognito-xxx-stg-dev\"]'}}}}. (Service: AWSCognitoIdentityProviderInternalService;
Status Code: 400; Error Code: UserLambdaValidationException; Request ID: 4f40047d-13c4-
4a6b-a434-2afaf283d418; Proxy: null)"

</code>```

I know try this point I trigger lambda function, but the groups stay the same, as Jenkins whoAmI does not change:

Any tips/tricks what to do/check next?

BTW some values in request/response were changed due to sensitive info.

Body:
I'm trying to change/add user group for Jenkins.
I use cognito to log-in and then I Invoke lambda function to add another group for the users.

Here's my lambda function:

    # Read custom groups claim
        #groups_string = event['request']['userAttributes']['custom:groups']
        #custom_groups = json.loads(groups_string)

    # Overrive custom:groups claim
    event["response"]["claimsOverrideDetails"] = {
        "claimsToAddOrOverride": {
            'custom:groups': '["cognito-xxx-stg-dev"]'
            }
        }
    #raise Exception(str(event))
    return event

When I uncomment exception I get error like this (request and response):

  "error" : "PreTokenGeneration failed with error {'version': '1', 'triggerSource':
'TokenGeneration_HostedAuth', 'region': 'eu-central-1', 'userPoolId': 'eu-central-
1_xxxxx', 'userName': 'xxxxx', 'callerContext': {'awsSdkVersion': 'aws-sdk-unknown-
unknown', 'clientId': 'xxx'}, 'request': {'userAttributes': {'sub': 'xxx',
'cognito:user_status': 'EXTERNAL_PROVIDER', 'identities':
'[{\"userId\":\"xxx\",\"providerName\":\"xxx\",\"providerType\":\"OIDC\",\"issuer\":null
,\"primary\":true,\"dateCreated\":1668756777933}]', 'email_verified': 'false', 'name':
 'xxx', 'preferred_username': 'xxx', 'given_name': 'xxx', 'family_name': 'xxx',
'email': 'xxx', 'custom:groups': '[\"cognito-xxx-stg-admin\"]'}, 'groupConfiguration':
{'groupsToOverride': ['xxx'], 'iamRolesToOverride': [], 'preferredRole': None}},
'response': {'claimsOverrideDetails': {'claimsToAddOrOverride': {'custom:groups':
'[\"cognito-xxx-stg-dev\"]'}}}}. (Service: AWSCognitoIdentityProviderInternalService;
Status Code: 400; Error Code: UserLambdaValidationException; Request ID: 4f40047d-13c4-
4a6b-a434-2afaf283d418; Proxy: null)"

I know try this point I trigger lambda function, but the groups stay the same, as Jenkins whoAmI does not change:

Any tips/tricks what to do/check next?

BTW some values in request/response were changed due to sensitive info.


问:
angualr ngx-editor text output full raw data including object properties
ngx-editor would sometimes output the completed raw object value of the text i put in like

What the current output looks like

This happened less after i updated angular and ngx-editor but it started happening again randomly for random fields. i can't find this issue anywhere so i ran out of luck looking.

For context, i added the ngx editor in a separate component i can use to call back anywhere in other components

The HTML File of the component i made

the TS file of the component i made

How i imported the component i made

I tried updating the entire project and the ngx-editor version to the latest i can. I was expected to just get back the text i needed with the html tags not the entire object output


问:
JsonPath filter IN Operator not working as expected for of Array<int>
I have this Json object as example which I tried to query using JsonPath expression.

```<code>{
"values": [
    {
        "attributes": null,
        "label": "Label1",
        "validFor": [
            1,2
        ],
        "value": "Value1"
    },
    {
        "attributes": null,
        "label": "Label2",
        "validFor": [
            1,3
        ],
        "value": "Value2"
    },
    {
        "attributes": null,
        "label": "Label3",
        "validFor": [
            8
        ],
        "value": "Value3"
    },
    {
        "attributes": null,
        "label": "Label4",
        "validFor": [
            1,2
        ],
        "value": "Value4"
    }
]
</code>```

}

I am trying to get values that having validFor == 1 inside it. Here are the JsonPath expression I have tried:

```<code>$.values[?(1 in @.validFor)]
$.values[?(@.validFor in 1)]
</code>```

None of this working as expected. First expression actually giving some result, but it seems to return all objects as validFor.Count > 1.

Forgive me if I question is not clear or my English sounds bad. Feel free to ask more question for better understanding the question.

Thank you!

Body:
I have this Json object as example which I tried to query using JsonPath expression.

{
"values": [
    {
        "attributes": null,
        "label": "Label1",
        "validFor": [
            1,2
        ],
        "value": "Value1"
    },
    {
        "attributes": null,
        "label": "Label2",
        "validFor": [
            1,3
        ],
        "value": "Value2"
    },
    {
        "attributes": null,
        "label": "Label3",
        "validFor": [
            8
        ],
        "value": "Value3"
    },
    {
        "attributes": null,
        "label": "Label4",
        "validFor": [
            1,2
        ],
        "value": "Value4"
    }
]

}

I am trying to get values that having validFor == 1 inside it. Here are the JsonPath expression I have tried:

$.values[?(1 in @.validFor)]
$.values[?(@.validFor in 1)]

None of this working as expected. First expression actually giving some result, but it seems to return all objects as validFor.Count > 1.

Forgive me if I question is not clear or my English sounds bad. Feel free to ask more question for better understanding the question.

Thank you!


问:
Im trying to make an astar algorithm for a school thing
Here is my code i've been working on. I've scraped off all the errors from the code. But i cant get the code to run correctly and the application either explodes or doesn't atleast visualise the astar.

```<code>#include <SFML/Graphics.hpp>
#include <queue>
#include <unordered_map>
#include <cmath>
#include <vector>

const int WIDTH = 10;
const int HEIGHT = 10;

struct Node
{
    int x;
    int y;
    mutable float gScore;
    mutable float fScore;
    mutable const Node* parent;

    Node(int _x, int _y) : x(_x), y(_y), gScore(0), fScore(0), parent(nullptr) {}

    bool operator==(const Node& other) const
    {
        return x == other.x && y == other.y;
    }
};

// Hash function for nodes, needed for storing them in an unordered_map
struct NodeHash
{
    std::size_t operator()(const Node& node) const
    {
        return std::hash<int>()(node.x) ^ std::hash<int>()(node.y);
    }
};

// Overload the ">" operator for nodes, needed for using them in a priority queue
struct NodeGreater
{
    bool operator()(const Node& left, const Node& right) const
    {
        return left.fScore > right.fScore;
    }
};

// Represents a 2D grid
class Grid
{
public:
    Grid()
    {
        // Initialize the grid with all nodes as walkable
        for (int x = 0; x < WIDTH; x++)
        {
            for (int y = 0; y < HEIGHT; y++)
            {
                nodes[x][y] = true;
            }
        }
    }

    // Set the walkability of a node
    void setNode(int x, int y, bool walkable)
    {
        nodes[x][y] = walkable;
    }

    // Check if a node is walkable
    bool isNodeWalkable(int x, int y)
    {
        return nodes[x][y];
    }

private:
    bool nodes[WIDTH][HEIGHT];
};

// Calculate the Euclidean distance between two nodes
float euclideanDistance(Node a, Node b)
{
    int xDist = b.x - a.x;
    int yDist = b.y - a.y;
    return std::sqrt(xDist * xDist + yDist * yDist);
}

// Estimate the cost of reaching the end node from a given node
float heuristicCostEstimate(Node start, Node end)
{
    return euclideanDistance(start, end);
}

// Get the neighbors of a given node
std::vector<Node> getNeighbors(Grid grid, Node node)
{
    std::vector<Node> neighbors;

    for (int x = -1; x <= 1; x++)
    {
        for (int y = -1; y <= 1; y++)
        {
            // Skip the current node
            if (x == 0 && y == 0)
            {
                continue;
            }

            int neighborX = node.x + x;
            int neighborY = node.y + y;

            // Make sure the neighbor is within the bounds of the grid
            if (neighborX >= 0 && neighborX < WIDTH && neighborY >= 0 && neighborY < HEIGHT)
            {
                // Make sure the neighbor is walkable
                if (grid.isNodeWalkable(neighborX, neighborY))
                {
                    Node neighbor = { neighborX, neighborY };
                    neighbors.push_back(neighbor);
                }
            }
        }
    }

    return neighbors;
}

// Reconstruct the path from the end node to the start node
std::vector<Node> reconstructPath(Node end)
{
    std::vector<Node> path;
    Node current = end;

    while (current.parent != nullptr)
    {
        path.push_back(current);
        current = *current.parent;
    }

    path.push_back(current);
    std::reverse(path.begin(), path.end());

    return path;
}

// Run the A* algorithm to find the shortest path from the start to the end node
std::vector<Node> aStar(Grid grid, Node start, Node end)
{
    // Initialize the open and closed sets
    std::priority_queue<Node, std::vector<Node>, NodeGreater> openSet;
    std::unordered_map<Node, bool, NodeHash> closedSet;

    // Add the start node to the open set
    openSet.push(start);

    // Set the starting node's gScore to 0 and fScore to the estimated cost to the end node
    start.gScore = 0;
    start.fScore = heuristicCostEstimate(start, end);

    // Keep searching until the open set is empty
    while (!openSet.empty())
    {

        // Get the node in the open set with the lowest fScore
        Node current = openSet.top();
        openSet.pop();

        // If the current node is the end node, we have found the shortest path
        if (current == end)
        {
            return reconstructPath(current);
        }

        // Add the current node to the closed set
        closedSet[current] = true;

        // Get the neighbors of the current node
        std::vector<Node> neighbors = getNeighbors(grid, current);

        // Iterate through the neighbors
        for (const Node& neighbor : neighbors)
        {
            // Skip the neighbor if it is already in the closed set
            if (closedSet.count(neighbor) > 0)
            {
                continue;
            }

            // Calculate the tentative gScore for the neighbor
            float tentativeGScore = current.gScore + euclideanDistance(current, neighbor);

            bool neighborIsBetter = false;
            bool neighborInOpenSet = false;
            // Check if the neighbor is already in the open set
            std::priority_queue<Node, std::vector<Node>, NodeGreater> tempOpenSet = openSet;
            while (!tempOpenSet.empty())
            {
                Node tempNeighbor = tempOpenSet.top();
                tempOpenSet.pop();
                if (tempNeighbor == neighbor)
                {
                    neighborInOpenSet = true;
                    break;
                }
            }

            // Update the neighbor's scores and parent if the tentative gScore is lower than
            if (tentativeGScore < neighbor.gScore)
            {
                neighborIsBetter = true;
                neighbor.gScore = tentativeGScore;
                neighbor.fScore = tentativeGScore + heuristicCostEstimate(neighbor, end);
            }

            if (!neighborInOpenSet || neighborIsBetter)
            {
                // Update the neighbor's parent to the current node
                neighbor.parent = &current;

                // Add the neighbor to the open set if it is not already there
                if (!neighborInOpenSet)
                {
                    openSet.push(neighbor);
                }
            }
        }
    }

    // If we reach here, it means that we have not found a path to the end node
    return std::vector<Node>();
}

int main()
{
    // Create the window and grid
    sf::RenderWindow window(sf::VideoMode(500, 500), "A*");
    Grid grid;

    // Set some nodes as unwalkable
    grid.setNode(3, 3, false);
    grid.setNode(3, 4, false);
    grid.setNode(3, 5, false);
    grid.setNode(4, 3, false);
    // Set the start and end nodes
    Node start = { 1, 1 };
    Node end = { 8, 8 };

    // Run the A* algorithm and get the path
    std::vector<Node> path = aStar(grid, start, end);

    // Main loop
    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();

        // Draw the grid
        for (int x = 0; x < WIDTH; x++)
        {
            for (int y = 0; y < HEIGHT; y++)
            {
                sf::RectangleShape rect(sf::Vector2f(50, 50));
                rect.setPosition(x * 50, y * 50);
                if (grid.isNodeWalkable(x, y))
                {
                    rect.setFillColor(sf::Color::White);
                }
                else
                {
                    rect.setFillColor(sf::Color::Black);
                }
                window.draw(rect);
            }
        }

        // Draw the path
        for (Node node : path)
        {
            sf::RectangleShape rect(sf::Vector2f(50, 50));
            rect.setPosition(node.x * 50, node.y * 50);
            rect.setFillColor(sf::Color::Green);
            window.draw(rect);
        }

        // Draw the start and end nodes
        sf::RectangleShape startRect(sf::Vector2f(50, 50));
        startRect.setPosition(start.x * 50, start.y * 50);
        startRect.setFillColor(sf::Color::Red);
        window.draw(startRect);

        sf::RectangleShape endRect(sf::Vector2f(50, 50));
        endRect.setPosition(end.x * 50, end.y * 50);
        endRect.setFillColor(sf::Color::Blue);
        window.draw(endRect);

        window.display();
    }

    return 0;
}

</code>```

any idea why its doing this?

I've tried to debug the code and i cant seem to find the problem. Either the code doesn't run or it just shows the same thing

Body:
Here is my code i've been working on. I've scraped off all the errors from the code. But i cant get the code to run correctly and the application either explodes or doesn't atleast visualise the astar.

#include <SFML/Graphics.hpp>
#include <queue>
#include <unordered_map>
#include <cmath>
#include <vector>

const int WIDTH = 10;
const int HEIGHT = 10;

struct Node
{
    int x;
    int y;
    mutable float gScore;
    mutable float fScore;
    mutable const Node* parent;

    Node(int _x, int _y) : x(_x), y(_y), gScore(0), fScore(0), parent(nullptr) {}

    bool operator==(const Node& other) const
    {
        return x == other.x && y == other.y;
    }
};

// Hash function for nodes, needed for storing them in an unordered_map
struct NodeHash
{
    std::size_t operator()(const Node& node) const
    {
        return std::hash<int>()(node.x) ^ std::hash<int>()(node.y);
    }
};

// Overload the ">" operator for nodes, needed for using them in a priority queue
struct NodeGreater
{
    bool operator()(const Node& left, const Node& right) const
    {
        return left.fScore > right.fScore;
    }
};

// Represents a 2D grid
class Grid
{
public:
    Grid()
    {
        // Initialize the grid with all nodes as walkable
        for (int x = 0; x < WIDTH; x++)
        {
            for (int y = 0; y < HEIGHT; y++)
            {
                nodes[x][y] = true;
            }
        }
    }

    // Set the walkability of a node
    void setNode(int x, int y, bool walkable)
    {
        nodes[x][y] = walkable;
    }

    // Check if a node is walkable
    bool isNodeWalkable(int x, int y)
    {
        return nodes[x][y];
    }

private:
    bool nodes[WIDTH][HEIGHT];
};

// Calculate the Euclidean distance between two nodes
float euclideanDistance(Node a, Node b)
{
    int xDist = b.x - a.x;
    int yDist = b.y - a.y;
    return std::sqrt(xDist * xDist + yDist * yDist);
}

// Estimate the cost of reaching the end node from a given node
float heuristicCostEstimate(Node start, Node end)
{
    return euclideanDistance(start, end);
}

// Get the neighbors of a given node
std::vector<Node> getNeighbors(Grid grid, Node node)
{
    std::vector<Node> neighbors;

    for (int x = -1; x <= 1; x++)
    {
        for (int y = -1; y <= 1; y++)
        {
            // Skip the current node
            if (x == 0 && y == 0)
            {
                continue;
            }

            int neighborX = node.x + x;
            int neighborY = node.y + y;

            // Make sure the neighbor is within the bounds of the grid
            if (neighborX >= 0 && neighborX < WIDTH && neighborY >= 0 && neighborY < HEIGHT)
            {
                // Make sure the neighbor is walkable
                if (grid.isNodeWalkable(neighborX, neighborY))
                {
                    Node neighbor = { neighborX, neighborY };
                    neighbors.push_back(neighbor);
                }
            }
        }
    }

    return neighbors;
}

// Reconstruct the path from the end node to the start node
std::vector<Node> reconstructPath(Node end)
{
    std::vector<Node> path;
    Node current = end;

    while (current.parent != nullptr)
    {
        path.push_back(current);
        current = *current.parent;
    }

    path.push_back(current);
    std::reverse(path.begin(), path.end());

    return path;
}

// Run the A* algorithm to find the shortest path from the start to the end node
std::vector<Node> aStar(Grid grid, Node start, Node end)
{
    // Initialize the open and closed sets
    std::priority_queue<Node, std::vector<Node>, NodeGreater> openSet;
    std::unordered_map<Node, bool, NodeHash> closedSet;

    // Add the start node to the open set
    openSet.push(start);

    // Set the starting node's gScore to 0 and fScore to the estimated cost to the end node
    start.gScore = 0;
    start.fScore = heuristicCostEstimate(start, end);

    // Keep searching until the open set is empty
    while (!openSet.empty())
    {

        // Get the node in the open set with the lowest fScore
        Node current = openSet.top();
        openSet.pop();

        // If the current node is the end node, we have found the shortest path
        if (current == end)
        {
            return reconstructPath(current);
        }

        // Add the current node to the closed set
        closedSet[current] = true;

        // Get the neighbors of the current node
        std::vector<Node> neighbors = getNeighbors(grid, current);

        // Iterate through the neighbors
        for (const Node& neighbor : neighbors)
        {
            // Skip the neighbor if it is already in the closed set
            if (closedSet.count(neighbor) > 0)
            {
                continue;
            }

            // Calculate the tentative gScore for the neighbor
            float tentativeGScore = current.gScore + euclideanDistance(current, neighbor);

            bool neighborIsBetter = false;
            bool neighborInOpenSet = false;
            // Check if the neighbor is already in the open set
            std::priority_queue<Node, std::vector<Node>, NodeGreater> tempOpenSet = openSet;
            while (!tempOpenSet.empty())
            {
                Node tempNeighbor = tempOpenSet.top();
                tempOpenSet.pop();
                if (tempNeighbor == neighbor)
                {
                    neighborInOpenSet = true;
                    break;
                }
            }

            // Update the neighbor's scores and parent if the tentative gScore is lower than
            if (tentativeGScore < neighbor.gScore)
            {
                neighborIsBetter = true;
                neighbor.gScore = tentativeGScore;
                neighbor.fScore = tentativeGScore + heuristicCostEstimate(neighbor, end);
            }

            if (!neighborInOpenSet || neighborIsBetter)
            {
                // Update the neighbor's parent to the current node
                neighbor.parent = &current;

                // Add the neighbor to the open set if it is not already there
                if (!neighborInOpenSet)
                {
                    openSet.push(neighbor);
                }
            }
        }
    }

    // If we reach here, it means that we have not found a path to the end node
    return std::vector<Node>();
}

int main()
{
    // Create the window and grid
    sf::RenderWindow window(sf::VideoMode(500, 500), "A*");
    Grid grid;

    // Set some nodes as unwalkable
    grid.setNode(3, 3, false);
    grid.setNode(3, 4, false);
    grid.setNode(3, 5, false);
    grid.setNode(4, 3, false);
    // Set the start and end nodes
    Node start = { 1, 1 };
    Node end = { 8, 8 };

    // Run the A* algorithm and get the path
    std::vector<Node> path = aStar(grid, start, end);

    // Main loop
    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();

        // Draw the grid
        for (int x = 0; x < WIDTH; x++)
        {
            for (int y = 0; y < HEIGHT; y++)
            {
                sf::RectangleShape rect(sf::Vector2f(50, 50));
                rect.setPosition(x * 50, y * 50);
                if (grid.isNodeWalkable(x, y))
                {
                    rect.setFillColor(sf::Color::White);
                }
                else
                {
                    rect.setFillColor(sf::Color::Black);
                }
                window.draw(rect);
            }
        }

        // Draw the path
        for (Node node : path)
        {
            sf::RectangleShape rect(sf::Vector2f(50, 50));
            rect.setPosition(node.x * 50, node.y * 50);
            rect.setFillColor(sf::Color::Green);
            window.draw(rect);
        }

        // Draw the start and end nodes
        sf::RectangleShape startRect(sf::Vector2f(50, 50));
        startRect.setPosition(start.x * 50, start.y * 50);
        startRect.setFillColor(sf::Color::Red);
        window.draw(startRect);

        sf::RectangleShape endRect(sf::Vector2f(50, 50));
        endRect.setPosition(end.x * 50, end.y * 50);
        endRect.setFillColor(sf::Color::Blue);
        window.draw(endRect);

        window.display();
    }

    return 0;
}

any idea why its doing this?

I've tried to debug the code and i cant seem to find the problem. Either the code doesn't run or it just shows the same thing


问:
Map a local file to a remote URL for debugging
I have written a CLI app that helps me to deploy code from code.html to a specified URL address by clicking F5 (it's configured in launch.json thorugh Powershell extension)

That command deploys my code, then opens a Chromium instance with the target page on which the code starts to run.

I want to debug this code (it's simply JavaScript embedded in HTML) in my local code.html file (setting breakpoints etc).

To do that, I have configured the described task as a prelaunchTask and then added a configuration that attaches a debugger to my running Chromium when it's ready (See below).

Everything is super cool, the browser attaches fine, but I simply can't map my local code.html to a code file(s) automatically generated at the specified URL location, because my code is not running in the same page I wrote in, but it's embedded into a remote page, which is autogenerated, i.e. I only know the URL address where it runs.

Is there a way to map the code.html file to a remote URL, so I could debug that code while running?

launch.json

```<code>{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "attach",
            "name": "Attach to Chrome",
            "port": 1234,
            "urlFilter": "https://somewebsite.com*",
            "webRoot": "${workspaceFolder}",
            "preLaunchTask": "deployment"
        }
    ],
}
</code>```

tasks.json

```<code>{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "deployment",
            "type": "shell",
            "command": "C:\\Something.exe",
            "args": [ someargs ]
        }
    ]
}
</code>```

Body:
I have written a CLI app that helps me to deploy code from code.html to a specified URL address by clicking F5 (it's configured in launch.json thorugh Powershell extension)

That command deploys my code, then opens a Chromium instance with the target page on which the code starts to run.

I want to debug this code (it's simply JavaScript embedded in HTML) in my local code.html file (setting breakpoints etc).

To do that, I have configured the described task as a prelaunchTask and then added a configuration that attaches a debugger to my running Chromium when it's ready (See below).

Everything is super cool, the browser attaches fine, but I simply can't map my local code.html to a code file(s) automatically generated at the specified URL location, because my code is not running in the same page I wrote in, but it's embedded into a remote page, which is autogenerated, i.e. I only know the URL address where it runs.

Is there a way to map the code.html file to a remote URL, so I could debug that code while running?

launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "attach",
            "name": "Attach to Chrome",
            "port": 1234,
            "urlFilter": "https://somewebsite.com*",
            "webRoot": "${workspaceFolder}",
            "preLaunchTask": "deployment"
        }
    ],
}

tasks.json

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "deployment",
            "type": "shell",
            "command": "C:\\Something.exe",
            "args": [ someargs ]
        }
    ]
}


问:
Handle categories and sub-categories in react select hook form
I am trying to handle categories and sub-categories in react select hook form field. Currently we pass an array to options and it renders it.

Now I have data in arrays and nested arrays.

like this

```<code>Category: [
 {
   Sub-Category: []
 },
 {
   Sub-Category: []
 }
]
</code>```

Currently, I am handling it like this

```<code><option value="">Select</option>
              {medicalCategory?.response?.data?.map((value, index) => (
                <optgroup label={value?.cpt_category}>
                  {value?.sub_categories?.map((subCategory, index) => (
                    <option value={subCategory?.id}>
                      {subCategory?.cpt_category}
                    </option>
                  ))}
                </optgroup>
              ))}
</code>```

But I want to this in react select hook form. And when select a value, i should also get the value of category. Like this value: {category { Sub-Category: [] }}

I tried using onClick, onChange. But onChange only provide the value of the selected sub-category. Like only name or id. I want whole parent-Category and sub-category And as we know onClick doesn't work on onClick.

Body:
I am trying to handle categories and sub-categories in react select hook form field. Currently we pass an array to options and it renders it.

Now I have data in arrays and nested arrays.

like this

Category: [
 {
   Sub-Category: []
 },
 {
   Sub-Category: []
 }
]

Currently, I am handling it like this

<option value="">Select</option>
              {medicalCategory?.response?.data?.map((value, index) => (
                <optgroup label={value?.cpt_category}>
                  {value?.sub_categories?.map((subCategory, index) => (
                    <option value={subCategory?.id}>
                      {subCategory?.cpt_category}
                    </option>
                  ))}
                </optgroup>
              ))}

But I want to this in react select hook form. And when select a value, i should also get the value of category. Like this value: {category { Sub-Category: [] }}

I tried using onClick, onChange. But onChange only provide the value of the selected sub-category. Like only name or id. I want whole parent-Category and sub-category And as we know onClick doesn't work on onClick.


问:
How do I read a text file that is actively adding new content in Node.JS?
I am currently working on a for fun project which requires me to read output data from a (file.json). This file is constantly getting new data added to it and has multiple lines added per second, and I have no control over the file’s generation.

As of right now I have a listener running for changes in the file. Then it goes and grabs the most recent line. But it is not grabbing all lines if multiple lines are added in quick succession.


问:
Node.js: Custom MySQL connector - Cannot read properties of undefined (reading 'query')
I have created a custom connection module to connect to my MySQL DB. This module will be used by multiple lambda functions. But I am getting the following error:

'Cannot read properties of undefined (reading 'query')'

Here is the module:

```<code>const MyApplicationNameSecrets = require('../secrets/MyApplicationNameSecrets');
const mysql = require("mysql");

module.exports = class MySqlConnect {

    databaseCredObject;
    pool;

    constructor() {
        this.initPool();
    }

    async initPool() {
        if (!this.databaseCredObject) {
            await this.fetchSecret();
        }

        const connection_settings = {
            host: this.databaseCredObject.host,
            user: this.databaseCredObject.username,
            password: this.databaseCredObject.password,
            database: 'mydbname',
            connectionLimit: 10 // specify the maximum number of connections in the pool
        };

        this.pool = mysql.createPool(connection_settings);
    }

    async queryDb(sql, args) {
        return new Promise((resolve, reject) => {
            this.pool.query(sql, args, function (err, result) {
                console.log('Connected');
                if (err) {
                    console.log('error when connecting to db:', err);
                    return reject(err);
                }
                return resolve(result);
            });
        });
    }

    async fetchSecret() {
        const databaseCredString = await MyApplicationNameSecrets.getSecret('MyApplicationName', 'eu-west-2');
        this.databaseCredObject = JSON.parse(databaseCredString);
    }
}

</code>```

Wondering if anyone can help please:

thanks

Body:
I have created a custom connection module to connect to my MySQL DB. This module will be used by multiple lambda functions. But I am getting the following error:

'Cannot read properties of undefined (reading 'query')'

Here is the module:

const MyApplicationNameSecrets = require('../secrets/MyApplicationNameSecrets');
const mysql = require("mysql");

module.exports = class MySqlConnect {

    databaseCredObject;
    pool;

    constructor() {
        this.initPool();
    }

    async initPool() {
        if (!this.databaseCredObject) {
            await this.fetchSecret();
        }

        const connection_settings = {
            host: this.databaseCredObject.host,
            user: this.databaseCredObject.username,
            password: this.databaseCredObject.password,
            database: 'mydbname',
            connectionLimit: 10 // specify the maximum number of connections in the pool
        };

        this.pool = mysql.createPool(connection_settings);
    }

    async queryDb(sql, args) {
        return new Promise((resolve, reject) => {
            this.pool.query(sql, args, function (err, result) {
                console.log('Connected');
                if (err) {
                    console.log('error when connecting to db:', err);
                    return reject(err);
                }
                return resolve(result);
            });
        });
    }

    async fetchSecret() {
        const databaseCredString = await MyApplicationNameSecrets.getSecret('MyApplicationName', 'eu-west-2');
        this.databaseCredObject = JSON.parse(databaseCredString);
    }
}

Wondering if anyone can help please:

thanks


问:
How to create a PowerShell Remoting 7 remoting session to Remote computer
Morning Guys,

I'm probably missing something simple, but I'm trying to see how can I create a PS7 to PS7 remoting session to a remote computer so I can run PS7 cmdlets on the remote computer.

I have the latest PS7 version installed on both and selected enable remoting during the install. I've also ran Enable-PSRemoting on both systems as well

I've tried running Get-PSSessionConfiguration to get the configuration name and pass the -ConfigurationName parameter that is part of New-PSSession but it doesn't return anything.

Am I missing something?


问:
Bug in forking and running processes
So I've been trying to fork a process two times, first fork is to let the main process continue working and the second is to let the child capture the output of the execution of the grand child process. The code is as follow:

void execute_run(char **parameters) {
    task_t* task = create_task();
    tasks[task_number] = *task;

    int pipe_stdout[2];
    ASSERT_SYS_OK(pipe(pipe_stdout)); // creating a pipe for stdout

    pid_t pid = fork();
    ASSERT_SYS_OK(pid);

    if (pid == 0) {
        // child process
        char buffer[MAXLENGTH_OUTPUT];
        pid = fork();
        ASSERT_SYS_OK(pid);

        if (pid == 0) {
            // this process will redirect stdout to buffer
            const char* program_name = parameters[0];
            char** program_args = &parameters[1];

            ASSERT_SYS_OK(close(pipe_stdout[0]));
            ASSERT_SYS_OK(dup2(pipe_stdout[1], STDOUT_FILENO));
            // redirecting stdout to pipe
            ASSERT_SYS_OK(close(pipe_stdout[1]));

            ASSERT_SYS_OK(execvp(program_name, program_args));
        }
        else {
            ASSERT_SYS_OK(close(pipe_stdout[1]));
            int status;
            do
            {
              // this loop runs forever
            } while (waitpid(pid, &status, WNOHANG) == 0);

            ASSERT_SYS_OK(close(pipe_stdout[0]));
              // this is never printed
            fprintf(stderr, "Child process finished with status %d\n", status);
        }
    } else {
        // parent process won't use any of the pipe ends

        ASSERT_SYS_OK(close(pipe_stdout[0]));
        ASSERT_SYS_OK(close(pipe_stdout[1]));
    }

}
```

char** parameters are ['cat', 'in.txt'] in the example i'm trying to run (and file exists).
Thanks in advance!

I've tried debugging it and running with different commands like 'ls' for which it works fine, nevertheless I can't figure out why with 'cat' it doesn't work

Title: Bug in forking and running processes

Body:
So I've been trying to fork a process two times, first fork is to let the main process continue working and the second is to let the child capture the output of the execution of the grand child process. The code is as follow:

void execute_run(char **parameters) {
    task_t* task = create_task();
    tasks[task_number] = *task;

    int pipe_stdout[2];
    ASSERT_SYS_OK(pipe(pipe_stdout)); // creating a pipe for stdout

    pid_t pid = fork();
    ASSERT_SYS_OK(pid);

    if (pid == 0) {
        // child process
        char buffer[MAXLENGTH_OUTPUT];
        pid = fork();
        ASSERT_SYS_OK(pid);

        if (pid == 0) {
            // this process will redirect stdout to buffer
            const char* program_name = parameters[0];
            char** program_args = &parameters[1];

            ASSERT_SYS_OK(close(pipe_stdout[0]));
            ASSERT_SYS_OK(dup2(pipe_stdout[1], STDOUT_FILENO));
            // redirecting stdout to pipe
            ASSERT_SYS_OK(close(pipe_stdout[1]));

            ASSERT_SYS_OK(execvp(program_name, program_args));
        }
        else {
            ASSERT_SYS_OK(close(pipe_stdout[1]));
            int status;
            do
            {
              // this loop runs forever
            } while (waitpid(pid, &status, WNOHANG) == 0);

            ASSERT_SYS_OK(close(pipe_stdout[0]));
              // this is never printed
            fprintf(stderr, "Child process finished with status %d\n", status);
        }
    } else {
        // parent process won't use any of the pipe ends

        ASSERT_SYS_OK(close(pipe_stdout[0]));
        ASSERT_SYS_OK(close(pipe_stdout[1]));
    }

}

char** parameters are ['cat', 'in.txt'] in the example i'm trying to run (and file exists).
Thanks in advance!

I've tried debugging it and running with different commands like 'ls' for which it works fine, nevertheless I can't figure out why with 'cat' it doesn't work