问:
axios.post is not sending data in body
i am sending form data via axios.post from react frontend to nodejs backend but i am getting undefined in the req.body in the backend, my backend is working from postman

my frontend

```<code>import React,{useState} from "react";
import axios from "axios";

function Compose(){

    const [inputTitle, setInputTitle] = useState("");
    const [inputBody, setInputBody] = useState("");
    function handleSubmit(event){
        axios.post('http://localhost:5000/compose',{
            title:  inputTitle,
            content: inputBody
        })
        .then(function(response) {
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        });
        event.preventDefault();
    }

    return (
        <div className="container">
            <h1>Compose</h1>
            <form onSubmit={handleSubmit}>
                <div className="form-group">
                    <label htmlFor="postTitle" className="form-label">Title :</label>
                    <input type="text" name="postTitle" className="form-control" onChange={(event)=>{setInputTitle(event.target.value)}} />
                </div>
                <div className="form-group">
                    <label htmlFor="postBody" className="form-label">Post :</label>
                    <textarea  className="form-control" name="postBody" rows="4" onChange={(event)=>{setInputBody(event.target.value)}}></textarea>
                </div>
                <button className="btn btn-primary" type="submit">Publish</button>
            </form>
        </div>
    )
}

export default Compose;
</code>```

my backend

```<code>app.post("/compose", function(req,res){
  console.log(req.body.title);
  let newPost = new Post({
    title:req.body.title,
    content:req.body.content
  });

  newPost.save(function(err,result){
    if (err){
      console.log(err);
    }
    else{
      res.send(result);
    }
  });
})
</code>```

i tried sending axios.post in data like this

```<code>axios.post('http://localhost:5000/compose',{data:{
            title:  inputTitle,
            content: inputBody
        }})
</code>```

but it didn't work

Title: axios.post is not sending data in body

Body:
i am sending form data via axios.post from react frontend to nodejs backend but i am getting undefined in the req.body in the backend, my backend is working from postman

my frontend

import React,{useState} from "react";
import axios from "axios";

function Compose(){

    const [inputTitle, setInputTitle] = useState("");
    const [inputBody, setInputBody] = useState("");
    function handleSubmit(event){
        axios.post('http://localhost:5000/compose',{
            title:  inputTitle,
            content: inputBody
        })
        .then(function(response) {
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        });
        event.preventDefault();
    }

    return (

Compose

            <form onSubmit={handleSubmit}>

                    Title :
                    <input type="text" name="postTitle" className="form-control" onChange={(event)=>{setInputTitle(event.target.value)}} />

                    Post :
                    <textarea  className="form-control" name="postBody" rows="4" onChange={(event)=>{setInputBody(event.target.value)}}></textarea>

                <button className="btn btn-primary" type="submit">Publish</button>
            </form>

    )
}

export default Compose;

my backend

app.post("/compose", function(req,res){
  console.log(req.body.title);
  let newPost = new Post({
    title:req.body.title,
    content:req.body.content
  });

  newPost.save(function(err,result){
    if (err){
      console.log(err);
    }
    else{
      res.send(result);
    }
  });
})

i tried sending axios.post in data like this

axios.post('http://localhost:5000/compose',{data:{
            title:  inputTitle,
            content: inputBody
        }})

but it didn't work


来源: stackexchange

问:
Post Request Axios
I am getting this error:

```<code>Error: User validation failed: phone: Path `phone` is required., email: Path `email` is required., lname: Path `lname` is required., fname: Path `fname` is required.
    at ValidationError.inspect (C:\Users\hanzl\OneDrive\Desktop\CRUD\server\node_modules\mongoose\lib\error\validation.js:50:26)
</code>```

REACT CODE:

```<code>const[data,setData]=useState({
        fname:'',
        lname:'',
        email:'',
        phone:''
    })

    const inputValues=(e)=>{
      var name=e.target.name
      var value=e.target.value
      setData(({...data,[name]:value}))
    }

    console.log(data)

    const addData=async (e)=>{
      e.preventDefault()
      try{
        const user=JSON.stringify(data)
        const res= await axios.post("http://localhost:6100/user/new",{user}).then((res)=>{console.log(res)})
      }catch(err){
        console.log(err)
      }
    }
</code>```

SERVER CODE:

```<code>app.use(express.json())

app.use(cors())
app.use('/user',UserRoute)
</code>```
```<code>const UserSchema=mongoose.Schema({
    fname:{
        type:String,
        required:true
    },
    lname:{
        type:String,
        required:true
    },
    email:{
        type:String,
        required:true
    },
    phone:{
        type:String,
        required:true
    }
})
</code>```
```<code>router.post('/new',async (req,res)=>{
    try{
        const data= new User(req.body)
        await data.save()
        res.status(200).json(data)
    }catch(err){
        console.log("Data Not created ")
        console.log(err)
    }
})
</code>```

I get error every time i try to do post request through axios. Whenever i remove required:true from schema. Empty object is stored in database. What is the solution for this problem, Kindly guide me through

ContentLicense: CC BY-SA 4.0

Title: Post Request Axios

Body:
I am getting this error:

Error: User validation failed: phone: Path `phone` is required., email: Path `email` is required., lname: Path `lname` is required., fname: Path `fname` is required.
    at ValidationError.inspect (C:\Users\hanzl\OneDrive\Desktop\CRUD\server\node_modules\mongoose\lib\error\validation.js:50:26)

REACT CODE:

const[data,setData]=useState({
        fname:'',
        lname:'',
        email:'',
        phone:''
    })

    const inputValues=(e)=>{
      var name=e.target.name
      var value=e.target.value
      setData(({...data,[name]:value}))
    }

    console.log(data)

    const addData=async (e)=>{
      e.preventDefault()
      try{
        const user=JSON.stringify(data)
        const res= await axios.post("http://localhost:6100/user/new",{user}).then((res)=>{console.log(res)})
      }catch(err){
        console.log(err)
      }
    }

SERVER CODE:

app.use(express.json())

app.use(cors())
app.use('/user',UserRoute)

const UserSchema=mongoose.Schema({
    fname:{
        type:String,
        required:true
    },
    lname:{
        type:String,
        required:true
    },
    email:{
        type:String,
        required:true
    },
    phone:{
        type:String,
        required:true
    }
})

router.post('/new',async (req,res)=>{
    try{
        const data= new User(req.body)
        await data.save()
        res.status(200).json(data)
    }catch(err){
        console.log("Data Not created ")
        console.log(err)
    }
})

I get error every time i try to do post request through axios. Whenever i remove required:true from schema. Empty object is stored in database. What is the solution for this problem, Kindly guide me through


问:
Is there any way to find the categories in a catalog id through meta graph api?
I have a certain use case to find out the categories stored inside a Catalogue. I have the catalog_id as stored in commerce manager in Meta.
I have explored meta graph api
https://graph.facebook.com/v15.0/{catalog_id}/categories

However, I get the following error:
{   "error": {     "message": "(#100) For field 'categories': The parameter categorization_criteria is required",     "type": "OAuthException",     "code": 100, "   } }

After adding categorization_criteria, I get another error like so:

{   "error": {     "message": "(#100) For field 'categories': Param categorization_criteria must be one of {BRAND, CATEGORY, PRODUCT_TYPE}",     "type": "OAuthException",     "code": 100, "   } }

And finally, after adding CATEGORY to it:
{   "error": {     "message": "Unsupported get request. Object with ID '{catalog_id here}' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api",     "type": "GraphMethodException",     "code": 100,     "error_subcode": 33, "   } }


问:
how can i get the title, img and info when user click the product
how can i get the title, img and info when user click the product so i insert the title and img and info from clicked product to product page template

```<code>//when click view more get title of eo.target
const viewMore = document.getElementsByClassName("view-more")[0]
const getInfoFromClickedItem = () => {
    viewMore.addEventListener("click",(eo) => {
        const generateTitle = viewMore.parentElement.getElementsByClassName("card-title")[0]
        const insertTitle = document.getElementsByClassName("product-title")[0]
    })
}
</code>```

the issue is when i click the button view more and go to product page i dont have access to main page and cant target html elements

Body:
how can i get the title, img and info when user click the product so i insert the title and img and info from clicked product to product page template

//when click view more get title of eo.target
const viewMore = document.getElementsByClassName("view-more")[0]
const getInfoFromClickedItem = () => {
    viewMore.addEventListener("click",(eo) => {
        const generateTitle = viewMore.parentElement.getElementsByClassName("card-title")[0]
        const insertTitle = document.getElementsByClassName("product-title")[0]
    })
}

the issue is when i click the button view more and go to product page i dont have access to main page and cant target html elements


问:
Do I have to initialize every data type in a struct?
I am currently trying to build a simple calculator using a linked list in C. My idea is to have every node hold the data types: number, operator and parenthesis. Since I'm still new to structs I'm now wondering if it would cause issues to just initialize one data type and leave the other two uninitialized when when creating a node?</p>
```<code>struct node {
    int number;
    char operator;
    char parenthesis;
    struct node* next;
};

</code>```

Body:
I am currently trying to build a simple calculator using a linked list in C. My idea is to have every node hold the data types: number, operator and parenthesis. Since I'm still new to structs I'm now wondering if it would cause issues to just initialize one data type and leave the other two uninitialized when when creating a node?

struct node {
    int number;
    char operator;
    char parenthesis;
    struct node* next;
};


问:
Problem with installing pygame, python 3.11.1
When I try to run the following command in the folder of my project, in cmd:

py -m pip install pygame

It fails with the following details:

```<code>Collecting pygame
  Using cached pygame-2.1.2.tar.gz (10.1 MB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [77 lines of output]

      WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
      Using WINDOWS configuration...

      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "C:\Users\netan\AppData\Local\Temp\pip-install-yjshn064\pygame_8c807f777c7245d49c8e8229be7d7b98\setup.py", line 359, in <module>
          buildconfig.config.main(AUTO_CONFIG)
        File "C:\Users\netan\AppData\Local\Temp\pip-install-yjshn064\pygame_8c807f777c7245d49c8e8229be7d7b98\buildconfig\config.py", line 225, in main
          deps = CFG.main(**kwds)
                 ^^^^^^^^^^^^^^^^
        File "C:\Users\netan\AppData\Local\Temp\pip-install-yjshn064\pygame_8c807f777c7245d49c8e8229be7d7b98\buildconfig\config_win.py", line 511, in main
          return setup_prebuilt_sdl2(prebuilt_dir)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "C:\Users\netan\AppData\Local\Temp\pip-install-yjshn064\pygame_8c807f777c7245d49c8e8229be7d7b98\buildconfig\config_win.py", line 471, in setup_prebuilt_sdl2
          DEPS.configure()
        File "C:\Users\netan\AppData\Local\Temp\pip-install-yjshn064\pygame_8c807f777c7245d49c8e8229be7d7b98\buildconfig\config_win.py", line 336, in configure
          from . import vstools
        File "C:\Users\netan\AppData\Local\Temp\pip-install-yjshn064\pygame_8c807f777c7245d49c8e8229be7d7b98\buildconfig\vstools.py", line 11, in <module>
          compiler.initialize()
        File "C:\Users\netan\AppData\Local\Programs\Python\Python311\Lib\site-packages\setuptools\_distutils\msvc9compiler.py", line 403, in initialize
          vc_env = query_vcvarsall(VERSION, plat_spec)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "C:\Users\netan\AppData\Local\Programs\Python\Python311\Lib\site-packages\setuptools\_distutils\msvc9compiler.py", line 281, in query_vcvarsall
          raise DistutilsPlatformError("Unable to find vcvarsall.bat")
      distutils.errors.DistutilsPlatformError: Unable to find vcvarsall.bat
      Making dir :prebuilt_downloads:
      Downloading... https://www.libsdl.org/release/SDL2-devel-2.0.18-VC.zip ed561079ec622b0bab5a9e02976f5d540b0622da
      Unzipping :prebuilt_downloads\SDL2-devel-2.0.18-VC.zip:
      Downloading... https://www.libsdl.org/projects/SDL_image/release/SDL2_image-devel-2.0.5-VC.zip 137f86474691f4e12e76e07d58d5920c8d844d5b
      Unzipping :prebuilt_downloads\SDL2_image-devel-2.0.5-VC.zip:
      Downloading... https://www.libsdl.org/projects/SDL_ttf/release/SDL2_ttf-devel-2.0.15-VC.zip 1436df41ebc47ac36e02ec9bda5699e80ff9bd27
      Unzipping :prebuilt_downloads\SDL2_ttf-devel-2.0.15-VC.zip:
      Downloading... https://www.libsdl.org/projects/SDL_mixer/release/SDL2_mixer-devel-2.0.4-VC.zip 9097148f4529cf19f805ccd007618dec280f0ecc
      Unzipping :prebuilt_downloads\SDL2_mixer-devel-2.0.4-VC.zip:
      Downloading... https://www.pygame.org/ftp/jpegsr9d.zip ed10aa2b5a0fcfe74f8a6f7611aeb346b06a1f99
      Unzipping :prebuilt_downloads\jpegsr9d.zip:
      Downloading... https://pygame.org/ftp/prebuilt-x64-pygame-1.9.2-20150922.zip 3a5af3427b3aa13a0aaf5c4cb08daaed341613ed
      Unzipping :prebuilt_downloads\prebuilt-x64-pygame-1.9.2-20150922.zip:
      copying into .\prebuilt-x64
      Path for SDL: prebuilt-x64\SDL2-2.0.18
      ...Library directory for SDL: prebuilt-x64/SDL2-2.0.18/lib/x64
      ...Include directory for SDL: prebuilt-x64/SDL2-2.0.18/include
      Path for FONT: prebuilt-x64\SDL2_ttf-2.0.15
      ...Library directory for FONT: prebuilt-x64/SDL2_ttf-2.0.15/lib/x64
      ...Include directory for FONT: prebuilt-x64/SDL2_ttf-2.0.15/include
      Path for IMAGE: prebuilt-x64\SDL2_image-2.0.5
      ...Library directory for IMAGE: prebuilt-x64/SDL2_image-2.0.5/lib/x64
      ...Include directory for IMAGE: prebuilt-x64/SDL2_image-2.0.5/include
      Path for MIXER: prebuilt-x64\SDL2_mixer-2.0.4
      ...Library directory for MIXER: prebuilt-x64/SDL2_mixer-2.0.4/lib/x64
      ...Include directory for MIXER: prebuilt-x64/SDL2_mixer-2.0.4/include
      Path for PORTMIDI: prebuilt-x64
      ...Library directory for PORTMIDI: prebuilt-x64/lib
      ...Include directory for PORTMIDI: prebuilt-x64/include
      DLL for SDL2: prebuilt-x64/SDL2-2.0.18/lib/x64/SDL2.dll
      DLL for SDL2_ttf: prebuilt-x64/SDL2_ttf-2.0.15/lib/x64/SDL2_ttf.dll
      DLL for SDL2_image: prebuilt-x64/SDL2_image-2.0.5/lib/x64/SDL2_image.dll
      DLL for SDL2_mixer: prebuilt-x64/SDL2_mixer-2.0.4/lib/x64/SDL2_mixer.dll
      DLL for portmidi: prebuilt-x64/lib/portmidi.dll
      Path for FREETYPE not found.
      ...Found include dir but no library dir in prebuilt-x64.
      Path for PNG not found.
      ...Found include dir but no library dir in prebuilt-x64.
      Path for JPEG not found.
      ...Found include dir but no library dir in prebuilt-x64.
      DLL for freetype: prebuilt-x64/SDL2_ttf-2.0.15/lib/x64/libfreetype-6.dll

      ---
      For help with compilation see:
          https://www.pygame.org/wiki/CompileWindows
      To contribute to pygame development see:
          https://www.pygame.org/contribute.html
      ---

      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.
</code>```

No idea how to solve it. I saw articles saying to revert to older versions of python. But I want to use python 3.11.1, is pygame not yet available on python 3.11.1?
I worked fine for me on 3.10 like a month ago.

I should note - any other package (for example, flask, requests etc...) installs successfully.

Body:
When I try to run the following command in the folder of my project, in cmd:

py -m pip install pygame

It fails with the following details:

Collecting pygame
  Using cached pygame-2.1.2.tar.gz (10.1 MB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [77 lines of output]

      WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
      Using WINDOWS configuration...

      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "C:\Users\netan\AppData\Local\Temp\pip-install-yjshn064\pygame_8c807f777c7245d49c8e8229be7d7b98\setup.py", line 359, in <module>
          buildconfig.config.main(AUTO_CONFIG)
        File "C:\Users\netan\AppData\Local\Temp\pip-install-yjshn064\pygame_8c807f777c7245d49c8e8229be7d7b98\buildconfig\config.py", line 225, in main
          deps = CFG.main(**kwds)
                 ^^^^^^^^^^^^^^^^
        File "C:\Users\netan\AppData\Local\Temp\pip-install-yjshn064\pygame_8c807f777c7245d49c8e8229be7d7b98\buildconfig\config_win.py", line 511, in main
          return setup_prebuilt_sdl2(prebuilt_dir)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "C:\Users\netan\AppData\Local\Temp\pip-install-yjshn064\pygame_8c807f777c7245d49c8e8229be7d7b98\buildconfig\config_win.py", line 471, in setup_prebuilt_sdl2
          DEPS.configure()
        File "C:\Users\netan\AppData\Local\Temp\pip-install-yjshn064\pygame_8c807f777c7245d49c8e8229be7d7b98\buildconfig\config_win.py", line 336, in configure
          from . import vstools
        File "C:\Users\netan\AppData\Local\Temp\pip-install-yjshn064\pygame_8c807f777c7245d49c8e8229be7d7b98\buildconfig\vstools.py", line 11, in <module>
          compiler.initialize()
        File "C:\Users\netan\AppData\Local\Programs\Python\Python311\Lib\site-packages\setuptools\_distutils\msvc9compiler.py", line 403, in initialize
          vc_env = query_vcvarsall(VERSION, plat_spec)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "C:\Users\netan\AppData\Local\Programs\Python\Python311\Lib\site-packages\setuptools\_distutils\msvc9compiler.py", line 281, in query_vcvarsall
          raise DistutilsPlatformError("Unable to find vcvarsall.bat")
      distutils.errors.DistutilsPlatformError: Unable to find vcvarsall.bat
      Making dir :prebuilt_downloads:
      Downloading... https://www.libsdl.org/release/SDL2-devel-2.0.18-VC.zip ed561079ec622b0bab5a9e02976f5d540b0622da
      Unzipping :prebuilt_downloads\SDL2-devel-2.0.18-VC.zip:
      Downloading... https://www.libsdl.org/projects/SDL_image/release/SDL2_image-devel-2.0.5-VC.zip 137f86474691f4e12e76e07d58d5920c8d844d5b
      Unzipping :prebuilt_downloads\SDL2_image-devel-2.0.5-VC.zip:
      Downloading... https://www.libsdl.org/projects/SDL_ttf/release/SDL2_ttf-devel-2.0.15-VC.zip 1436df41ebc47ac36e02ec9bda5699e80ff9bd27
      Unzipping :prebuilt_downloads\SDL2_ttf-devel-2.0.15-VC.zip:
      Downloading... https://www.libsdl.org/projects/SDL_mixer/release/SDL2_mixer-devel-2.0.4-VC.zip 9097148f4529cf19f805ccd007618dec280f0ecc
      Unzipping :prebuilt_downloads\SDL2_mixer-devel-2.0.4-VC.zip:
      Downloading... https://www.pygame.org/ftp/jpegsr9d.zip ed10aa2b5a0fcfe74f8a6f7611aeb346b06a1f99
      Unzipping :prebuilt_downloads\jpegsr9d.zip:
      Downloading... https://pygame.org/ftp/prebuilt-x64-pygame-1.9.2-20150922.zip 3a5af3427b3aa13a0aaf5c4cb08daaed341613ed
      Unzipping :prebuilt_downloads\prebuilt-x64-pygame-1.9.2-20150922.zip:
      copying into .\prebuilt-x64
      Path for SDL: prebuilt-x64\SDL2-2.0.18
      ...Library directory for SDL: prebuilt-x64/SDL2-2.0.18/lib/x64
      ...Include directory for SDL: prebuilt-x64/SDL2-2.0.18/include
      Path for FONT: prebuilt-x64\SDL2_ttf-2.0.15
      ...Library directory for FONT: prebuilt-x64/SDL2_ttf-2.0.15/lib/x64
      ...Include directory for FONT: prebuilt-x64/SDL2_ttf-2.0.15/include
      Path for IMAGE: prebuilt-x64\SDL2_image-2.0.5
      ...Library directory for IMAGE: prebuilt-x64/SDL2_image-2.0.5/lib/x64
      ...Include directory for IMAGE: prebuilt-x64/SDL2_image-2.0.5/include
      Path for MIXER: prebuilt-x64\SDL2_mixer-2.0.4
      ...Library directory for MIXER: prebuilt-x64/SDL2_mixer-2.0.4/lib/x64
      ...Include directory for MIXER: prebuilt-x64/SDL2_mixer-2.0.4/include
      Path for PORTMIDI: prebuilt-x64
      ...Library directory for PORTMIDI: prebuilt-x64/lib
      ...Include directory for PORTMIDI: prebuilt-x64/include
      DLL for SDL2: prebuilt-x64/SDL2-2.0.18/lib/x64/SDL2.dll
      DLL for SDL2_ttf: prebuilt-x64/SDL2_ttf-2.0.15/lib/x64/SDL2_ttf.dll
      DLL for SDL2_image: prebuilt-x64/SDL2_image-2.0.5/lib/x64/SDL2_image.dll
      DLL for SDL2_mixer: prebuilt-x64/SDL2_mixer-2.0.4/lib/x64/SDL2_mixer.dll
      DLL for portmidi: prebuilt-x64/lib/portmidi.dll
      Path for FREETYPE not found.
      ...Found include dir but no library dir in prebuilt-x64.
      Path for PNG not found.
      ...Found include dir but no library dir in prebuilt-x64.
      Path for JPEG not found.
      ...Found include dir but no library dir in prebuilt-x64.
      DLL for freetype: prebuilt-x64/SDL2_ttf-2.0.15/lib/x64/libfreetype-6.dll

      ---
      For help with compilation see:
          https://www.pygame.org/wiki/CompileWindows
      To contribute to pygame development see:
          https://www.pygame.org/contribute.html
      ---

      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

No idea how to solve it. I saw articles saying to revert to older versions of python. But I want to use python 3.11.1, is pygame not yet available on python 3.11.1?
I worked fine for me on 3.10 like a month ago.

I should note - any other package (for example, flask, requests etc...) installs successfully.


问:
Why is the code giving MLE in linked lists
Code is to merge two linked lists in sorted order which is working fine but when pushed online it is giving MLE for all the testcases. For eg. the first ll has the size of 4 which is 17 19 23 25 and 2nd ll has the size 2 which is 4 6. So o/p should be 4 6 17 19 23 25. Once getting the lists and reversing them, merging of them is done through recursion.</p>
```<code>#include <iostream>
using namespace std ;

class node
{
    public:
        int data ;
        node *next ;
        node *prev ;

        node(int d)
        {
            data = d ;
            next = NULL ;
        }
};

void insert_at_head(node *&head, int data)
{
    // corner case
    if (head == NULL)
    {
        head = new node(data) ;
        return ;
    }

    node *n = new node(data) ;
    n -> next = head ;
    head = n ;
}

node *merge_lists(node *a, node *b)
{
    // solving through recursion
    // corner case
    if (a == NULL)
    {
        return b ;
    }

    else if (b == NULL)
    {
        return a ;
    }

    node *temp ;

    if (a -> data < b -> data)
    {
        temp = a ;
        temp -> next = merge_lists(a->next,b) ;
    }

    if (b -> data < a -> data)
    {
        temp = b ;
        temp -> next = merge_lists(a,b->next) ;
    }

    return temp ;
}

void print(node *head)
{
    while(head != NULL)
    {
        cout<<head->data<<" " ;
        head = head -> next ;
    }
}

void reverse_list(node *&head)
{
    // we will swap addresses of the nodes
    // instead of values, as it will be a very expensive operation
    // 1 -> 2 -> 3 -> 4 -> 5
    node *current = head ;
    node *prev = NULL ;
    node *temp ;

    while(current != NULL)
    {
        // save the address of the next node
        temp = current -> next ;

        // current node will point to the prev node
        current -> next = prev ;

        prev = current ;
        current = temp ;
    }
    head = prev ;
}

int main ()
{
    int test_case, a_size, b_size ;

    cin>>test_case ;

    while(test_case > 0)
    {
        int count = 0, data ;
        cin>>a_size ;
        node *a = NULL ;
        while(count < a_size)
        {
            cin>>data ;
            insert_at_head(a,data) ;
            count++ ;
        }

        reverse_list(a) ;

        cin>>b_size ;
        count = 0 ;
        node *b = NULL ;
        while(count < b_size)
        {
            cin>>data ;
            insert_at_head(b,data) ;
            count++ ;
        }

        reverse_list(b) ;

        node *dislpay = merge_lists(a,b) ;

        print(dislpay) ;
        cout<<endl ;

        test_case-- ;
    }

    return 0 ;
}
</code>```

Body:
Code is to merge two linked lists in sorted order which is working fine but when pushed online it is giving MLE for all the testcases. For eg. the first ll has the size of 4 which is 17 19 23 25 and 2nd ll has the size 2 which is 4 6. So o/p should be 4 6 17 19 23 25. Once getting the lists and reversing them, merging of them is done through recursion.

#include <iostream>
using namespace std ;

class node
{
    public:
        int data ;
        node *next ;
        node *prev ;

        node(int d)
        {
            data = d ;
            next = NULL ;
        }
};

void insert_at_head(node *&head, int data)
{
    // corner case
    if (head == NULL)
    {
        head = new node(data) ;
        return ;
    }

    node *n = new node(data) ;
    n -> next = head ;
    head = n ;
}

node *merge_lists(node *a, node *b)
{
    // solving through recursion
    // corner case
    if (a == NULL)
    {
        return b ;
    }

    else if (b == NULL)
    {
        return a ;
    }

    node *temp ;

    if (a -> data  data)
    {
        temp = a ;
        temp -> next = merge_lists(a->next,b) ;
    }

    if (b -> data  data)
    {
        temp = b ;
        temp -> next = merge_lists(a,b->next) ;
    }

    return temp ;
}

void print(node *head)
{
    while(head != NULL)
    {
        cout<data<<" " ;
        head = head -> next ;
    }
}

void reverse_list(node *&head)
{
    // we will swap addresses of the nodes
    // instead of values, as it will be a very expensive operation
    // 1 -> 2 -> 3 -> 4 -> 5
    node *current = head ;
    node *prev = NULL ;
    node *temp ;

    while(current != NULL)
    {
        // save the address of the next node
        temp = current -> next ;

        // current node will point to the prev node
        current -> next = prev ;

        prev = current ;
        current = temp ;
    }
    head = prev ;
}

int main ()
{
    int test_case, a_size, b_size ;

    cin>>test_case ;

    while(test_case > 0)
    {
        int count = 0, data ;
        cin>>a_size ;
        node *a = NULL ;
        while(count < a_size)
        {
            cin>>data ;
            insert_at_head(a,data) ;
            count++ ;
        }

        reverse_list(a) ;

        cin>>b_size ;
        count = 0 ;
        node *b = NULL ;
        while(count < b_size)
        {
            cin>>data ;
            insert_at_head(b,data) ;
            count++ ;
        }

        reverse_list(b) ;

        node *dislpay = merge_lists(a,b) ;

        print(dislpay) ;
        cout<<endl ;

        test_case-- ;
    }

    return 0 ;
}


问:
Using 3 threads to read with 1 scanner the content of a file.csv and adding the content in an ArrayList
I'm training with Java and this is the first time that I'm using threads with it. An exercise asked me to read from a .cvs file and as a bonus it's asking me to use 3 threads to read this file and save the information in the same ArrayList<CustomClass>. I should have some kind of problem because every thread must read an unique line from the file.

This file contains this:

Clienti
nome,cognome,tipoMezzo,tipoParcheggio,dataOperazione,Operazione
Paolo,Rossi,cabrio,coperto,07/12/2022 09:00,0
Chiara,Bianchi,moto,aperto,07/12/2022 09:01,0
Abbondazio,Addolorata,4x4,aperto,07/12/2022 09:10,0
Agamennone,Agatangelo,moto,coperto,07/12/2022 09:11,0
Aldebrando,Barachisio,berlina,coperto,07/12/2022 09:12,0
Aldighiero,Barbaziano,moto,aperto,07/12/2022 10:01,0
Aldobrando,Bardomiano,moto,coperto,07/12/2022 10:05,0
Angilberto,Barsanufio,cabrio,aperto,07/12/2022 10:06,0
```
<pre class="lang-java prettyprint-override"><code>public class CarParkingImpl implements CarParking {
    ArrayList<Cliente> lista;
    byte coperto;
    byte aperto;

    public CarParkingImpl(){
        coperto=30;
        aperto =50;
        lista = new ArrayList<Cliente>();
    }

//This function must work with 3 operating Threads that read the same .cvs file and are syncronize to read each one a different line and put the information readed in the ArrayList 'lista'

    @Override
    public void carParkingFromCSV(String filePath) throws FileNotFoundException {
        Scanner scan = new Scanner(new File(filePath));
        scan.next();
        scan.next();
        while(scan.hasNext()){
            String[] clientInfo1 = scan.next().split(",");
            String[] clientInfo2 = scan.next().split(",");
            String[] daySplit = clientInfo1[4].split("/");
            String[] timeSplit = clientInfo2[0].split(":");
            Calendar tempCalendar = Calendar.getInstance();
            tempCalendar.set(Integer.parseInt(daySplit[2]),Integer.parseInt(daySplit[1])-1,Integer.parseInt(daySplit[0]),Integer.parseInt(timeSplit[0]),Integer.parseInt(timeSplit[1]));
            Cliente tempClient = new Cliente(clientInfo1[0],clientInfo1[1],clientInfo1[2],clientInfo1[3],tempCalendar,Byte.parseByte(clientInfo2[1]));
            try {
                carParkingClient(tempClient);
            }catch (CarParkingIsFullException e){
                System.err.println(e.getMessage());
            }
        }
        scan.close();
    }
}
</code>```

public class Cliente {
    String name;
    String surname;
    String carType;
    String parkReq;
    Calendar dateOperation;
    Byte parkOperation;

    public Cliente(String name, String surname, String carType, String parkReq, Calendar dateOperation, Byte parkOperation) {
        this.name = name;
        this.surname = surname;
        this.carType = carType;
        this.parkReq = parkReq;
        this.dateOperation = dateOperation;
        this.parkOperation = parkOperation;
    }
}
```
<pre class="lang-java prettyprint-override"><code>public class Main {
    public static void main(String[] args) throws FileNotFoundException {
        String path = "Clienti.csv";
        String outPath = "Report.txt";

       CarParkingImpl carParking = new CarParkingImpl();
        try {
            carParking.carParkingFromCSV(path);
            carParking.printReport(outPath);
        }catch (FileNotFoundException e){
            System.err.println(e.getMessage());
        }catch (IOException e){
            System.err.println(e.getMessage());
        }
    }
}
</code>```

Body:
I'm training with Java and this is the first time that I'm using threads with it. An exercise asked me to read from a .cvs file and as a bonus it's asking me to use 3 threads to read this file and save the information in the same ArrayList<CustomClass>. I should have some kind of problem because every thread must read an unique line from the file.

This file contains this:

Clienti
nome,cognome,tipoMezzo,tipoParcheggio,dataOperazione,Operazione
Paolo,Rossi,cabrio,coperto,07/12/2022 09:00,0
Chiara,Bianchi,moto,aperto,07/12/2022 09:01,0
Abbondazio,Addolorata,4x4,aperto,07/12/2022 09:10,0
Agamennone,Agatangelo,moto,coperto,07/12/2022 09:11,0
Aldebrando,Barachisio,berlina,coperto,07/12/2022 09:12,0
Aldighiero,Barbaziano,moto,aperto,07/12/2022 10:01,0
Aldobrando,Bardomiano,moto,coperto,07/12/2022 10:05,0
Angilberto,Barsanufio,cabrio,aperto,07/12/2022 10:06,0

public class CarParkingImpl implements CarParking {
    ArrayList<Cliente> lista;
    byte coperto;
    byte aperto;

    public CarParkingImpl(){
        coperto=30;
        aperto =50;
        lista = new ArrayList<Cliente>();
    }

//This function must work with 3 operating Threads that read the same .cvs file and are syncronize to read each one a different line and put the information readed in the ArrayList 'lista'

    @Override
    public void carParkingFromCSV(String filePath) throws FileNotFoundException {
        Scanner scan = new Scanner(new File(filePath));
        scan.next();
        scan.next();
        while(scan.hasNext()){
            String[] clientInfo1 = scan.next().split(",");
            String[] clientInfo2 = scan.next().split(",");
            String[] daySplit = clientInfo1[4].split("/");
            String[] timeSplit = clientInfo2[0].split(":");
            Calendar tempCalendar = Calendar.getInstance();
            tempCalendar.set(Integer.parseInt(daySplit[2]),Integer.parseInt(daySplit[1])-1,Integer.parseInt(daySplit[0]),Integer.parseInt(timeSplit[0]),Integer.parseInt(timeSplit[1]));
            Cliente tempClient = new Cliente(clientInfo1[0],clientInfo1[1],clientInfo1[2],clientInfo1[3],tempCalendar,Byte.parseByte(clientInfo2[1]));
            try {
                carParkingClient(tempClient);
            }catch (CarParkingIsFullException e){
                System.err.println(e.getMessage());
            }
        }
        scan.close();
    }
}

public class Cliente {
    String name;
    String surname;
    String carType;
    String parkReq;
    Calendar dateOperation;
    Byte parkOperation;

    public Cliente(String name, String surname, String carType, String parkReq, Calendar dateOperation, Byte parkOperation) {
        this.name = name;
        this.surname = surname;
        this.carType = carType;
        this.parkReq = parkReq;
        this.dateOperation = dateOperation;
        this.parkOperation = parkOperation;
    }
}

public class Main {
    public static void main(String[] args) throws FileNotFoundException {
        String path = "Clienti.csv";
        String outPath = "Report.txt";

       CarParkingImpl carParking = new CarParkingImpl();
        try {
            carParking.carParkingFromCSV(path);
            carParking.printReport(outPath);
        }catch (FileNotFoundException e){
            System.err.println(e.getMessage());
        }catch (IOException e){
            System.err.println(e.getMessage());
        }
    }
}


问:
Why is the actual memory usage in task manager different from the theoretical memory usage for C?
```<code>#include <stdio.h>
#include <unistd.h>
typedef struct kk {
  char k[1000000];
} uuuu;
uuuu k[1000];
int main() {
  sleep(100);
  return 0;
}

</code>```

The theoretical memory usage for this program should be [sizeof char(1Byte)* 1000000*1000];

However, the actual memory usage is only 961KB!

And since the global variable should be initialize to 0, all of the space should be memory in use.

Who can explain that?

Body:
#include <stdio.h>
#include <unistd.h>
typedef struct kk {
  char k[1000000];
} uuuu;
uuuu k[1000];
int main() {
  sleep(100);
  return 0;
}

The theoretical memory usage for this program should be [sizeof char(1Byte)* 1000000*1000];

However, the actual memory usage is only 961KB!

And since the global variable should be initialize to 0, all of the space should be memory in use.

Who can explain that?


问:
How to find distinct connected node groups using Networking Graph[Python]
File has 2 columns Node1 and Node2, each row represents connection between Node1 & Node2.Node1 may connect to several different Node2 and vice-versa. Two Node1's  are said to be connected if there is a chain of Node 1– Node 2– …– Node 1 connecting them.

I'm trying to find out how many distinct Node1 groups that have more than 10 Node1

Table:-
Node1              Node2
1                  A
2                  B
3                  A
1                  C
5                  E
3                  C

I tried using DFS(network/graph) in Python. It would be a great help if someone share the working code for the question posted


问:
Choice between interpolation search and binary search
I have a static sorted integer array of size N.

There will be a lot of element search queries

(get index of an element if it exists or of the nearest lesser element if it doesn't),

and I have to choose whether to use interpolation search or to stay with old good binary search.

how large is N when there is significant benefit from interpolation search?

what test to use for a check that the array values are uniformly distributed?

are there any other heuristics that can help me with the choice?


问:
Update active settings when plug and unplug the external monitor to the laptop
I have settings for an external monitor and a laptop screen. They are in the ~/.xprofile file and look like this:
xrandr --output eDP-1 --primary --mode 1920x1200 --pos 760x1440 --output HDMI-1 --mode 3440x1440 --dpi 144
I use arco linux with awesome wm.
If I restart my laptop with the monitor connected, everything works fine. But if I just connect the monitor to an already turned on laptop, then the monitor positioning is wrong. The laptop is under my external monitor, but when I connect the system positions the monitor to the right of the laptop.
The question is how to make sure that the monitor positioning settings are applied when it is connected to the laptop and not when I reboot.
Also, when I disconnect the monitor, my laptop still thinks that the monitor is connected and allows me to move the mouse course away from the laptop screen.

I would like that the settings automatically applied when you connect and disconnect the external monitor. Please, advise how to do this?


问:
Create folder in google drive and upload file REACTJS
I am working on project using reactjs ,In that I want to access user's google drive and create my own folder
and upload file in it , Creating folder is not done by user ,it should be done automatically in backend ,I just ask to user for accessing google drive....

I am trying use of google drive API in reactjs but creating folder and uploading I am not getting
Can anyone help me out in this?
Thank you.....


问:
How I highlight same characters in the TextFormField text with flutter

I want to highlight same characters in the TextFormField text. How can I do this in flutter? Thanks a lot.


问:
How to build .Net MAUI app referencing a standard .Net 6 Class Library?
I have a standard C# class library that's used for a lot of different projects, and I'd like to use it as a project reference in .Net MAUI. I've put this class library in the same solution as .NET MAUI. When I run the GUI from the VS debugger the app works fine, however when I try to publish it I get the error:
Metadata file '..\bin\Release\net6.0\win10-x64\myclasslibrary.dll' could not be found

In fact, my class library is located at: '..\bin\Release\net6.0\win-x64\myclasslibrary.dll'

How do I tell the .Net MAUI publish to look within the "win-x64" folder instead of "win10-x64"? Or alternatively how do I tell my class library to also compile to the win10-x64 folder as well? I've tried adding additional frameworks such as .net6-windows however the class library still isn't generating the win10-x64 folder, only the win-x64 one.

Update:

Here are the .csproj files for both my normal .net6 class library, and the MAUI project -

Standard .NET6  Class Library Project .csproj file:

```<code><PropertyGroup>
    <RuntimeIdentifiers>win-x64;linux-x64;</RuntimeIdentifiers>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
  <PackageReference Include="Newtonsoft.Json" Version="13.0.2" />
  <PackageReference Include="NSec.Cryptography" Version="22.4.0" />
</ItemGroup>
</code>```

MAUI Project .csproj file:

```<code><PropertyGroup>
    <TargetFrameworks>net6.0-android;net6.0-ios;net6.0-maccatalyst</TargetFrameworks>
    <TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('windows'))">$(TargetFrameworks);net6.0-windows10.0.19041.0</TargetFrameworks>
    <!-- Uncomment to also build the tizen app. You will need to install tizen by following this: https://github.com/Samsung/Tizen.NET -->
    <!-- <TargetFrameworks>$(TargetFrameworks);net6.0-tizen</TargetFrameworks> -->
    <OutputType>Exe</OutputType>
    <RootNamespace>MyMAUIApp_GUI</RootNamespace>
    <UseMaui>true</UseMaui>
    <SingleProject>true</SingleProject>
    <ImplicitUsings>enable</ImplicitUsings>
    <EnableDefaultCssItems>false</EnableDefaultCssItems>

    <!-- Display name -->
    <ApplicationTitle>MyMAUIApp-GUI</ApplicationTitle>

    <!-- App Identifier -->
    <ApplicationId>com.companyname.MyMAUIApp_gui</ApplicationId>
    <ApplicationIdGuid>00A85426-C72C-48BC-A656-26F0DD2470E7</ApplicationIdGuid>

    <!-- Versions -->
    <ApplicationDisplayVersion>1.0</ApplicationDisplayVersion>
    <ApplicationVersion>1</ApplicationVersion>

    <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'ios'">14.2</SupportedOSPlatformVersion>
    <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'maccatalyst'">14.0</SupportedOSPlatformVersion>
    <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">24.0</SupportedOSPlatformVersion>
    <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.17763.0</SupportedOSPlatformVersion>
    <TargetPlatformMinVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.17763.0</TargetPlatformMinVersion>
    <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'tizen'">6.5</SupportedOSPlatformVersion>
    <DefaultLanguage>en</DefaultLanguage>
    <GenerateAppInstallerFile>False</GenerateAppInstallerFile>
    <AppxAutoIncrementPackageRevision>False</AppxAutoIncrementPackageRevision>
    <AppxSymbolPackageEnabled>False</AppxSymbolPackageEnabled>
    <GenerateTestArtifacts>True</GenerateTestArtifacts>
    <HoursBetweenUpdateChecks>0</HoursBetweenUpdateChecks>
    <AppxPackageSigningEnabled>True</AppxPackageSigningEnabled>
    <PackageCertificateKeyFile>MyMAUIApp-GUI_TemporaryKey.pfx</PackageCertificateKeyFile>
    <AppxPackageSigningTimestampDigestAlgorithm>SHA256</AppxPackageSigningTimestampDigestAlgorithm>
    <Nullable>enable</Nullable>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net6.0-android|AnyCPU'">
  <PublishTrimmed>False</PublishTrimmed>
  <RunAOTCompilation>False</RunAOTCompilation>
</PropertyGroup>

<ItemGroup>
    <!-- App Icon -->
    <MauiIcon Include="Resources\AppIcon\appicon.svg" ForegroundFile="Resources\AppIcon\appiconfg.svg" Color="#512BD4" />
    <MauiImage Include="wwwroot\images\negative.svg" />

    <!-- Splash Screen -->
    <MauiSplashScreen Include="Resources\Splash\splash.svg" Color="#512BD4" BaseSize="128,128" />

    <!-- Images -->
    <MauiImage Include="Resources\Images\*" />
    <MauiImage Update="Resources\Images\dotnet_bot.svg" BaseSize="168,208" />

    <!-- Custom Fonts -->
    <MauiFont Include="Resources\Fonts\*" />

    <!-- Raw Assets (also remove the "Resources\Raw" prefix) -->
    <MauiAsset Include="Resources\Raw\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)" />
</ItemGroup>

<ItemGroup>
  <RazorComponent Include="Components\TxAddressBlock.razor" />
</ItemGroup>

<ItemGroup>
  <None Remove="Properties\PublishProfiles\MSIX-win10-x642.pubxml" />
</ItemGroup>

<ItemGroup>
  <ProjectReference Include="..\MyMAUIApp\ClassLibrary.csproj" />
</ItemGroup>
</code>```

To confirm I added the class library to the MAUI project in VS2022 by right clicking the project, selecting Add > Project Reference, and selecting the .csproj file for the class library

Body:
I have a standard C# class library that's used for a lot of different projects, and I'd like to use it as a project reference in .Net MAUI. I've put this class library in the same solution as .NET MAUI. When I run the GUI from the VS debugger the app works fine, however when I try to publish it I get the error:
Metadata file '..\bin\Release\net6.0\win10-x64\myclasslibrary.dll' could not be found

In fact, my class library is located at: '..\bin\Release\net6.0\win-x64\myclasslibrary.dll'

How do I tell the .Net MAUI publish to look within the "win-x64" folder instead of "win10-x64"? Or alternatively how do I tell my class library to also compile to the win10-x64 folder as well? I've tried adding additional frameworks such as .net6-windows however the class library still isn't generating the win10-x64 folder, only the win-x64 one.

Update:

Here are the .csproj files for both my normal .net6 class library, and the MAUI project -

Standard .NET6  Class Library Project .csproj file:

<PropertyGroup>
    <RuntimeIdentifiers>win-x64;linux-x64;</RuntimeIdentifiers>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
  <PackageReference Include="Newtonsoft.Json" Version="13.0.2" />
  <PackageReference Include="NSec.Cryptography" Version="22.4.0" />
</ItemGroup>

MAUI Project .csproj file:

<PropertyGroup>
    <TargetFrameworks>net6.0-android;net6.0-ios;net6.0-maccatalyst</TargetFrameworks>
    <TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('windows'))">$(TargetFrameworks);net6.0-windows10.0.19041.0</TargetFrameworks>

    <OutputType>Exe</OutputType>
    <RootNamespace>MyMAUIApp_GUI</RootNamespace>
    <UseMaui>true</UseMaui>
    <SingleProject>true</SingleProject>
    <ImplicitUsings>enable</ImplicitUsings>
    <EnableDefaultCssItems>false</EnableDefaultCssItems>

    <ApplicationTitle>MyMAUIApp-GUI</ApplicationTitle>

    <ApplicationId>com.companyname.MyMAUIApp_gui</ApplicationId>
    <ApplicationIdGuid>00A85426-C72C-48BC-A656-26F0DD2470E7</ApplicationIdGuid>

    <ApplicationDisplayVersion>1.0</ApplicationDisplayVersion>
    <ApplicationVersion>1</ApplicationVersion>

    <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'ios'">14.2</SupportedOSPlatformVersion>
    <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'maccatalyst'">14.0</SupportedOSPlatformVersion>
    <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">24.0</SupportedOSPlatformVersion>
    <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.17763.0</SupportedOSPlatformVersion>
    <TargetPlatformMinVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">10.0.17763.0</TargetPlatformMinVersion>
    <SupportedOSPlatformVersion Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'tizen'">6.5</SupportedOSPlatformVersion>
    <DefaultLanguage>en</DefaultLanguage>
    <GenerateAppInstallerFile>False</GenerateAppInstallerFile>
    <AppxAutoIncrementPackageRevision>False</AppxAutoIncrementPackageRevision>
    <AppxSymbolPackageEnabled>False</AppxSymbolPackageEnabled>
    <GenerateTestArtifacts>True</GenerateTestArtifacts>
    <HoursBetweenUpdateChecks>0</HoursBetweenUpdateChecks>
    <AppxPackageSigningEnabled>True</AppxPackageSigningEnabled>
    <PackageCertificateKeyFile>MyMAUIApp-GUI_TemporaryKey.pfx</PackageCertificateKeyFile>
    <AppxPackageSigningTimestampDigestAlgorithm>SHA256</AppxPackageSigningTimestampDigestAlgorithm>
    <Nullable>enable</Nullable>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net6.0-android|AnyCPU'">
  <PublishTrimmed>False</PublishTrimmed>
  <RunAOTCompilation>False</RunAOTCompilation>
</PropertyGroup>

<ItemGroup>

    <MauiIcon Include="Resources\AppIcon\appicon.svg" ForegroundFile="Resources\AppIcon\appiconfg.svg" Color="#512BD4" />
    <MauiImage Include="wwwroot\images\negative.svg" />

    <MauiSplashScreen Include="Resources\Splash\splash.svg" Color="#512BD4" BaseSize="128,128" />

    <MauiImage Include="Resources\Images\*" />
    <MauiImage Update="Resources\Images\dotnet_bot.svg" BaseSize="168,208" />

    <MauiFont Include="Resources\Fonts\*" />

    <MauiAsset Include="Resources\Raw\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)" />
</ItemGroup>

<ItemGroup>
  <RazorComponent Include="Components\TxAddressBlock.razor" />
</ItemGroup>

<ItemGroup>
  <None Remove="Properties\PublishProfiles\MSIX-win10-x642.pubxml" />
</ItemGroup>

<ItemGroup>
  <ProjectReference Include="..\MyMAUIApp\ClassLibrary.csproj" />
</ItemGroup>

To confirm I added the class library to the MAUI project in VS2022 by right clicking the project, selecting Add > Project Reference, and selecting the .csproj file for the class library


问:
Why does all formatting disappear from an NSTextView when using NSViewRepresentable and SwiftUI?
I am making a small program using SwiftUI that allows users to create rich text "notes" in an NSTextView. I have enabled all of the formatting features from NSTextView, including the ability to work with images. The program is only for macOS and not for iOS/iPadOS.

The problem I am facing is that whenever the user types anything in the NSTextView, the caret moves to the end and all formatting and images disappear.

Since I am just using the standard formatting options provided by Apple, I have not subclassed NSTextStorage or anything like that. My use-case should be pretty simple.

The program is tiny so far and the entire source code is on GitHub (https://github.com/eiskalteschatten/ScratchPad), but I'll post the relevant code here.

This is my NSViewRepresentable class for the NSTextView:

import SwiftUI

struct RichTextEditor: NSViewRepresentable {
    @EnvironmentObject var noteModel: NoteModel

    func makeNSView(context: Context) -> NSScrollView {
        let scrollView = NSTextView.scrollableTextView()

        guard let textView = scrollView.documentView as? NSTextView else {
            return scrollView
        }

        textView.isRichText = true
        textView.allowsUndo = true
        textView.allowsImageEditing = true
        textView.allowsDocumentBackgroundColorChange = true
        textView.allowsCharacterPickerTouchBarItem = true
        textView.isAutomaticLinkDetectionEnabled = true
        textView.displaysLinkToolTips = true
        textView.isAutomaticDataDetectionEnabled = true
        textView.isAutomaticTextReplacementEnabled = true
        textView.isAutomaticDashSubstitutionEnabled = true
        textView.isAutomaticSpellingCorrectionEnabled = true
        textView.isAutomaticQuoteSubstitutionEnabled = true
        textView.isAutomaticTextCompletionEnabled = true
        textView.isContinuousSpellCheckingEnabled = true
        textView.usesAdaptiveColorMappingForDarkAppearance = true
        textView.usesInspectorBar = true
        textView.usesRuler = true
        textView.usesFindBar = true
        textView.usesFontPanel = true
        textView.importsGraphics = true

        textView.delegate = context.coordinator
        context.coordinator.textView = textView

        return scrollView
    }

    func updateNSView(_ nsView: NSScrollView, context: Context) {
        context.coordinator.textView?.textStorage?.setAttributedString(noteModel.noteContents)
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    class Coordinator: NSObject, NSTextViewDelegate {
        var parent: RichTextEditor
        var textView : NSTextView?

        init(_ parent: RichTextEditor) {
            self.parent = parent
        }

        func textDidChange(_ notification: Notification) {
            guard let _textView = notification.object as? NSTextView else {
                return
            }

            self.parent.noteModel.noteContents = _textView.attributedString()
        }
    }
}

```
<p>On GitHub: https://github.com/eiskalteschatten/ScratchPad/blob/main/ScratchPad/Notes/RichTextEditor.swift</p>
<p>And this is my <code>NoteModel</code> class responsible for managing the <code>NSTextView</code> content:</p>
<pre class="lang-swift prettyprint-override"><code>import SwiftUI
import Combine

final class NoteModel: ObservableObject {
    private var switchingPages = false

    @Published var pageNumber = UserDefaults.standard.value(forKey: "pageNumber") as? Int ?? 1 {
        didSet {
            UserDefaults.standard.set(pageNumber, forKey: "pageNumber")
            switchingPages = true
            noteContents = NSAttributedString(string: "")
            openNote()
            switchingPages = false
        }
    }

    @Published var noteContents = NSAttributedString(string: "") {
        didSet {
            if !switchingPages {
                saveNote()
            }
        }
    }

    private var noteName: String {
        return "\(NoteManager.NOTE_NAME_PREFIX)\(pageNumber).rtfd"
    }

    init() {
        openNote()
    }

    private func openNote() {
        // This is necessary, but macOS seems to recover the stale bookmark automatically, so don't handle it for now
        var isStale = false

        guard let bookmarkData = UserDefaults.standard.object(forKey: "storageLocationBookmarkData") as? Data,
              let storageLocation = try? URL(resolvingBookmarkData: bookmarkData, options: .withSecurityScope, relativeTo: nil, bookmarkDataIsStale: &isStale)
        else {
            ErrorHandling.showErrorToUser("No storage location for your notes could be found!", informativeText: "Please try re-selecting your storage location in the settings.")
            return
        }

        let fullURL = storageLocation.appendingPathComponent(noteName)
        let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtfd]

        do {
            guard storageLocation.startAccessingSecurityScopedResource() else {
                ErrorHandling.showErrorToUser("ScratchPad is not allowed to access the storage location for your notes!", informativeText: "Please try re-selecting your storage location in the settings.")
                return
            }

            if let _ = try? fullURL.checkResourceIsReachable() {
                let attributedString = try NSAttributedString(url: fullURL, options: options, documentAttributes: nil)
                noteContents = attributedString
            }

            fullURL.stopAccessingSecurityScopedResource()
        } catch {
            print(error)
            ErrorHandling.showErrorToUser(error.localizedDescription)
        }
    }

    private func saveNote() {
        // This is necessary, but macOS seems to recover the stale bookmark automatically, so don't handle it for now
        var isStale = false

        guard let bookmarkData = UserDefaults.standard.object(forKey: "storageLocationBookmarkData") as? Data,
              let storageLocation = try? URL(resolvingBookmarkData: bookmarkData, options: .withSecurityScope, relativeTo: nil, bookmarkDataIsStale: &isStale)
        else {
            ErrorHandling.showErrorToUser("No storage location for your notes could be found!", informativeText: "Please try re-selecting your storage location in the settings.")
            return
        }

        let fullURL = storageLocation.appendingPathComponent(noteName)

        do {
            guard storageLocation.startAccessingSecurityScopedResource() else {
                ErrorHandling.showErrorToUser("ScratchPad is not allowed to access the storage location for your notes!", informativeText: "Please try re-selecting your storage location in the settings.")
                return
            }

            let rtdf = noteContents.rtfdFileWrapper(from: .init(location: 0, length: noteContents.length))
            try rtdf?.write(to: fullURL, options: .atomic, originalContentsURL: nil)
            fullURL.stopAccessingSecurityScopedResource()
        } catch {
            print(error)
            ErrorHandling.showErrorToUser(error.localizedDescription)
        }
    }
}
</code>```

On GitHub: https://github.com/eiskalteschatten/ScratchPad/blob/main/ScratchPad/Notes/NoteModel.swift

Does anyone have any idea why this is happening and/or how to fix it?

I have found these similar issues, but they don't really help me much:

Replacing NSAttributedString in NSTextStorage Moves NSTextView Cursor - I don't have any custom syntax highlighting or anything like that.

Cursor always jumps to the end of the UIViewRepresentable TextView when a newline is started before the final line + after last character on the line - Only solves the caret issue and causes jerky scroll behavior in longer documents.

Edit: I forgot to mention that I'm using macOS Ventura, but am targeting 12.0 or higher.

Edit #2: I have significantly updated the question to reflect what I've found through more debugging.

Body:
I am making a small program using SwiftUI that allows users to create rich text "notes" in an NSTextView. I have enabled all of the formatting features from NSTextView, including the ability to work with images. The program is only for macOS and not for iOS/iPadOS.

The problem I am facing is that whenever the user types anything in the NSTextView, the caret moves to the end and all formatting and images disappear.

Since I am just using the standard formatting options provided by Apple, I have not subclassed NSTextStorage or anything like that. My use-case should be pretty simple.

The program is tiny so far and the entire source code is on GitHub (https://github.com/eiskalteschatten/ScratchPad), but I'll post the relevant code here.

This is my NSViewRepresentable class for the NSTextView:

import SwiftUI

struct RichTextEditor: NSViewRepresentable {
    @EnvironmentObject var noteModel: NoteModel

    func makeNSView(context: Context) -> NSScrollView {
        let scrollView = NSTextView.scrollableTextView()

        guard let textView = scrollView.documentView as? NSTextView else {
            return scrollView
        }

        textView.isRichText = true
        textView.allowsUndo = true
        textView.allowsImageEditing = true
        textView.allowsDocumentBackgroundColorChange = true
        textView.allowsCharacterPickerTouchBarItem = true
        textView.isAutomaticLinkDetectionEnabled = true
        textView.displaysLinkToolTips = true
        textView.isAutomaticDataDetectionEnabled = true
        textView.isAutomaticTextReplacementEnabled = true
        textView.isAutomaticDashSubstitutionEnabled = true
        textView.isAutomaticSpellingCorrectionEnabled = true
        textView.isAutomaticQuoteSubstitutionEnabled = true
        textView.isAutomaticTextCompletionEnabled = true
        textView.isContinuousSpellCheckingEnabled = true
        textView.usesAdaptiveColorMappingForDarkAppearance = true
        textView.usesInspectorBar = true
        textView.usesRuler = true
        textView.usesFindBar = true
        textView.usesFontPanel = true
        textView.importsGraphics = true

        textView.delegate = context.coordinator
        context.coordinator.textView = textView

        return scrollView
    }

    func updateNSView(_ nsView: NSScrollView, context: Context) {
        context.coordinator.textView?.textStorage?.setAttributedString(noteModel.noteContents)
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    class Coordinator: NSObject, NSTextViewDelegate {
        var parent: RichTextEditor
        var textView : NSTextView?

        init(_ parent: RichTextEditor) {
            self.parent = parent
        }

        func textDidChange(_ notification: Notification) {
            guard let _textView = notification.object as? NSTextView else {
                return
            }

            self.parent.noteModel.noteContents = _textView.attributedString()
        }
    }
}

On GitHub: https://github.com/eiskalteschatten/ScratchPad/blob/main/ScratchPad/Notes/RichTextEditor.swift

And this is my NoteModel class responsible for managing the NSTextView content:

import SwiftUI
import Combine

final class NoteModel: ObservableObject {
    private var switchingPages = false

    @Published var pageNumber = UserDefaults.standard.value(forKey: "pageNumber") as? Int ?? 1 {
        didSet {
            UserDefaults.standard.set(pageNumber, forKey: "pageNumber")
            switchingPages = true
            noteContents = NSAttributedString(string: "")
            openNote()
            switchingPages = false
        }
    }

    @Published var noteContents = NSAttributedString(string: "") {
        didSet {
            if !switchingPages {
                saveNote()
            }
        }
    }

    private var noteName: String {
        return "\(NoteManager.NOTE_NAME_PREFIX)\(pageNumber).rtfd"
    }

    init() {
        openNote()
    }

    private func openNote() {
        // This is necessary, but macOS seems to recover the stale bookmark automatically, so don't handle it for now
        var isStale = false

        guard let bookmarkData = UserDefaults.standard.object(forKey: "storageLocationBookmarkData") as? Data,
              let storageLocation = try? URL(resolvingBookmarkData: bookmarkData, options: .withSecurityScope, relativeTo: nil, bookmarkDataIsStale: &isStale)
        else {
            ErrorHandling.showErrorToUser("No storage location for your notes could be found!", informativeText: "Please try re-selecting your storage location in the settings.")
            return
        }

        let fullURL = storageLocation.appendingPathComponent(noteName)
        let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtfd]

        do {
            guard storageLocation.startAccessingSecurityScopedResource() else {
                ErrorHandling.showErrorToUser("ScratchPad is not allowed to access the storage location for your notes!", informativeText: "Please try re-selecting your storage location in the settings.")
                return
            }

            if let _ = try? fullURL.checkResourceIsReachable() {
                let attributedString = try NSAttributedString(url: fullURL, options: options, documentAttributes: nil)
                noteContents = attributedString
            }

            fullURL.stopAccessingSecurityScopedResource()
        } catch {
            print(error)
            ErrorHandling.showErrorToUser(error.localizedDescription)
        }
    }

    private func saveNote() {
        // This is necessary, but macOS seems to recover the stale bookmark automatically, so don't handle it for now
        var isStale = false

        guard let bookmarkData = UserDefaults.standard.object(forKey: "storageLocationBookmarkData") as? Data,
              let storageLocation = try? URL(resolvingBookmarkData: bookmarkData, options: .withSecurityScope, relativeTo: nil, bookmarkDataIsStale: &isStale)
        else {
            ErrorHandling.showErrorToUser("No storage location for your notes could be found!", informativeText: "Please try re-selecting your storage location in the settings.")
            return
        }

        let fullURL = storageLocation.appendingPathComponent(noteName)

        do {
            guard storageLocation.startAccessingSecurityScopedResource() else {
                ErrorHandling.showErrorToUser("ScratchPad is not allowed to access the storage location for your notes!", informativeText: "Please try re-selecting your storage location in the settings.")
                return
            }

            let rtdf = noteContents.rtfdFileWrapper(from: .init(location: 0, length: noteContents.length))
            try rtdf?.write(to: fullURL, options: .atomic, originalContentsURL: nil)
            fullURL.stopAccessingSecurityScopedResource()
        } catch {
            print(error)
            ErrorHandling.showErrorToUser(error.localizedDescription)
        }
    }
}

On GitHub: https://github.com/eiskalteschatten/ScratchPad/blob/main/ScratchPad/Notes/NoteModel.swift

Does anyone have any idea why this is happening and/or how to fix it?

I have found these similar issues, but they don't really help me much:

Replacing NSAttributedString in NSTextStorage Moves NSTextView Cursor - I don't have any custom syntax highlighting or anything like that.

Cursor always jumps to the end of the UIViewRepresentable TextView when a newline is started before the final line + after last character on the line - Only solves the caret issue and causes jerky scroll behavior in longer documents.

Edit: I forgot to mention that I'm using macOS Ventura, but am targeting 12.0 or higher.

Edit #2: I have significantly updated the question to reflect what I've found through more debugging.


问:
auto expand variables in Visual Studio Code when debug
enter image description here
how to auto expand this "next"？

I already enable this setting debug.autoExpandLazyVariables，BUT NO USE
from Default expanded variables in VSCode Java debugger


问:
Shiny DataTable - How to change filter size?
I've this Shiny app:

The filter size is too narrow so I can't see the whole words.
I want to make the filter box wider without changing the table/column size, just the filter box.

this is my code:

```<code>library(DT)
iris2 = iris[c(1:10, 51:60, 101:110), ]
# no clear buttons
datatable(iris2, options = list(autoWidth = TRUE), filter = list(
  position = 'top', clear = FALSE
))

</code>```

Is it possible?

Body:
I've this Shiny app:

The filter size is too narrow so I can't see the whole words.
I want to make the filter box wider without changing the table/column size, just the filter box.

this is my code:

library(DT)
iris2 = iris[c(1:10, 51:60, 101:110), ]
# no clear buttons
datatable(iris2, options = list(autoWidth = TRUE), filter = list(
  position = 'top', clear = FALSE
))

Is it possible?


问:
Why do I get "ModuleNotFoundError: No module named 'TAP'" when TAP is installed?
I am trying to use Rx to validate a YAML document against a schema, but python can't find the TAP module even though I've just installed it and I can see it's right there:

```<code>[:~/git/Rx/python] [my-venv] master* ± python3 rx-test.py
Traceback (most recent call last):
  File "/home/atsaloli/git/Rx/python/rx-test.py", line 1, in <module>
    from TAP.Simple import *
ModuleNotFoundError: No module named 'TAP'
[:~/git/Rx/python] [my-venv] master* 1 ± pip3 freeze | grep -i tap
tap==0.2
tap.py==3.1
[:~/git/Rx/python] [my-venv] master* ± ls /home/atsaloli/my-venv/lib/python3.10/site-packages/tap/
adapter.py    formatter.py  line.py    __main__.py  parser.py    rules.py   tests
directive.py  __init__.py   loader.py  main.py      __pycache__  runner.py  tracker.py
[:~/git/Rx/python] [my-venv] master* ±
</code>```

Rx is https://rjbs.manxome.org/rx/index.html

Similar questions (no accepted answer):

ModuleNotFoundError: No module named 'script' but script actually exist and directory precise

ModuleNotFoundError: No module named 'mysql' even when module is installed

Python error "ImportError: No module named"

P.S. I did install tap:

```<code>[:~/git/learn_python/yaml-validator] [my-venv] 1 $ pip install tap
Requirement already satisfied: tap in /home/atsaloli/my-venv/lib/python3.10/site-packages (0.2)
Requirement already satisfied: mc_bin_client in /home/atsaloli/my-venv/lib/python3.10/site-packages (from tap) (1.0.1)
[:~/git/learn_python/yaml-validator] [my-venv] $
</code>```

Body:
I am trying to use Rx to validate a YAML document against a schema, but python can't find the TAP module even though I've just installed it and I can see it's right there:

[:~/git/Rx/python] [my-venv] master* ± python3 rx-test.py
Traceback (most recent call last):
  File "/home/atsaloli/git/Rx/python/rx-test.py", line 1, in <module>
    from TAP.Simple import *
ModuleNotFoundError: No module named 'TAP'
[:~/git/Rx/python] [my-venv] master* 1 ± pip3 freeze | grep -i tap
tap==0.2
tap.py==3.1
[:~/git/Rx/python] [my-venv] master* ± ls /home/atsaloli/my-venv/lib/python3.10/site-packages/tap/
adapter.py    formatter.py  line.py    __main__.py  parser.py    rules.py   tests
directive.py  __init__.py   loader.py  main.py      __pycache__  runner.py  tracker.py
[:~/git/Rx/python] [my-venv] master* ±

Rx is https://rjbs.manxome.org/rx/index.html

Similar questions (no accepted answer):

ModuleNotFoundError: No module named 'script' but script actually exist and directory precise

ModuleNotFoundError: No module named 'mysql' even when module is installed

Python error "ImportError: No module named"

P.S. I did install tap:

[:~/git/learn_python/yaml-validator] [my-venv] 1 $ pip install tap
Requirement already satisfied: tap in /home/atsaloli/my-venv/lib/python3.10/site-packages (0.2)
Requirement already satisfied: mc_bin_client in /home/atsaloli/my-venv/lib/python3.10/site-packages (from tap) (1.0.1)
[:~/git/learn_python/yaml-validator] [my-venv] $


问:
how to find my city location with location search in React Redux with Leaflet with OpenStreetMap
I was assigned by my lecturer to add city search to my application using React(Redux) using Leaflet (OpenStreetMap) can anyone help me to solve this problem? and what are the dependencies needed?

Here My Code

```<code>import React from 'react'
import {MapContainer, TileLayer} from 'react-leaflet'
import {IoLogoDropbox} from 'react-icons/io5'
import 'leaflet/dist/leaflet.css'

function FormDashboardMap() {
  return (
    <div>
        <h1 className="title"><IoLogoDropbox/> Map</h1>
        <div className="card has-shadow">
            <div className="card-content">
                <div className="content">
                    <MapContainer style={{ height: "450px", width: "100%" }} center={[51.505, -0.09]} zoom={19}>
                    <TileLayer
                        attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"

                        />
                    </MapContainer>
                </div>
            </div>
        </div>
    </div>
  )
}

export default FormDashboardMap
</code>```

what to add to add city search feature to my code?

Body:
I was assigned by my lecturer to add city search to my application using React(Redux) using Leaflet (OpenStreetMap) can anyone help me to solve this problem? and what are the dependencies needed?

Here My Code

import React from 'react'
import {MapContainer, TileLayer} from 'react-leaflet'
import {IoLogoDropbox} from 'react-icons/io5'
import 'leaflet/dist/leaflet.css'

function FormDashboardMap() {
  return (

<IoLogoDropbox/> Map

                    <MapContainer style={{ height: "450px", width: "100%" }} center={[51.505, -0.09]} zoom={19}>
                    <TileLayer
                        attribution='© OpenStreetMap contributors'
                        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"

                        />
                    </MapContainer>

  )
}

export default FormDashboardMap

what to add to add city search feature to my code?


问:
Create secret "kubernetes.io/service-account-token" with kubectl
I am trying to create secret for my service account with kubectl, but cannot do this. Is it possible?

➤ kubectl create secret generic test --type=kubernetes.io/service-account-token -n dev
error: failed to create secret Secret "test" is invalid: metadata.annotations[kubernetes.io/service-account.name]: Required value
```

I understand the error, but I can't find an example anywhere on how to create these types of secrets from the command line. From a file, I create a secret of this type without any problems.

Body:
I am trying to create secret for my service account with kubectl, but cannot do this. Is it possible?

➤ kubectl create secret generic test --type=kubernetes.io/service-account-token -n dev
error: failed to create secret Secret "test" is invalid: metadata.annotations[kubernetes.io/service-account.name]: Required value

I understand the error, but I can't find an example anywhere on how to create these types of secrets from the command line. From a file, I create a secret of this type without any problems.


问:
Realloc FAILS with >= 27 chars
I've stumbled upon following problem: I wrote a program in C, which functions as a variation of Mergesort, just with forking. For this problem, I wrote a function which reads exactly one line from some input stream specified by a parameter, adds a '\0' at the end, and returns a boolean, indicating whether a newline character exists or not. The source code is below:

```<code>static bool getInputLine(FILE *f, char **input, int *size_in) {
    int size = 0;
    char todo;

    do {
        if((*input = realloc(*input, (size + 1) * sizeof(char))) == NULL) exitWithStatus(EXIT_FAILURE, "reallocing FAILED");
        todo = fgetc(f);
        if(todo == EOF) break;
        (*input)[size] = todo;
        if(todo == '\n' && size == 0){
            fprintf(stdout, "\n");
            break;
        }
        size++;
    } while(todo != '\n');

    if((*input = realloc(*input, (size+1) * sizeof(char))) == NULL) exitWithStatus(EXIT_FAILURE, "reallocing FAILED");

    (*input)[size] = '\0';
    *size_in = size;

    return size == 0 || todo != '\n';
}
</code>```

The code works for (almost) any input, at least so I thought. For some reason, if a line is greater than exactly 26 chars, I get:

realloc(): invalid next size Aborted (core dumped)

I'm relatively new to C, and this had me confused as ever. Any help is greatly appreciated, thanks in advance!

My OS is Linux Fedora, if that helps in any way. Should you need anything else, please let me know :)

And just fyi, the input String is malloc'd with sizeof(char) before calling the function! It is freed again at exiting the process.

EDIT: Despite help from various sides, I have not been able to solve this issue. I had to generally rethink my strategy to solve the problem as a whole. I suppose it had something to do with global variables being inherited by the forked child processes, and hence borking the heap structs in some way or another. Unfortunately, I lost track of what happened exactly, despite restructuring my code to make it more debug-friendly.
Thank you very much for your help regardless! :)

Title: Realloc FAILS with >= 27 chars

Body:
I've stumbled upon following problem: I wrote a program in C, which functions as a variation of Mergesort, just with forking. For this problem, I wrote a function which reads exactly one line from some input stream specified by a parameter, adds a '\0' at the end, and returns a boolean, indicating whether a newline character exists or not. The source code is below:

static bool getInputLine(FILE *f, char **input, int *size_in) {
    int size = 0;
    char todo;

    do {
        if((*input = realloc(*input, (size + 1) * sizeof(char))) == NULL) exitWithStatus(EXIT_FAILURE, "reallocing FAILED");
        todo = fgetc(f);
        if(todo == EOF) break;
        (*input)[size] = todo;
        if(todo == '\n' && size == 0){
            fprintf(stdout, "\n");
            break;
        }
        size++;
    } while(todo != '\n');

    if((*input = realloc(*input, (size+1) * sizeof(char))) == NULL) exitWithStatus(EXIT_FAILURE, "reallocing FAILED");

    (*input)[size] = '\0';
    *size_in = size;

    return size == 0 || todo != '\n';
}

The code works for (almost) any input, at least so I thought. For some reason, if a line is greater than exactly 26 chars, I get:

realloc(): invalid next size Aborted (core dumped)

I'm relatively new to C, and this had me confused as ever. Any help is greatly appreciated, thanks in advance!

My OS is Linux Fedora, if that helps in any way. Should you need anything else, please let me know :)

And just fyi, the input String is malloc'd with sizeof(char) before calling the function! It is freed again at exiting the process.

EDIT: Despite help from various sides, I have not been able to solve this issue. I had to generally rethink my strategy to solve the problem as a whole. I suppose it had something to do with global variables being inherited by the forked child processes, and hence borking the heap structs in some way or another. Unfortunately, I lost track of what happened exactly, despite restructuring my code to make it more debug-friendly.
Thank you very much for your help regardless! :)


问:
Associate file .PY with Spyder v.5+ in ubuntu 22.04
With the installation of spyder 5+ I've got a problem with the opening of .py files. In properties -> Open with-> ... no more spyder icon. Is everybody already faced with it?

I'm grateful for your help in advance.

PC: Omen HP
OS: Ubuntu 22.04

I tried to reinstall Spyder, but without success. The Spyder icon is anyway not in the list of associated programs.

However other one, for example atom, is there.


问:
How can i pass validated data to another custom validator class in DRF?
I Have this kind of serializer.py

```<code>class PostSerializer(serializers.ModelSerializer):
    title = serializers.CharField(validators=[TitleValidator()])
    slug = serializers.CharField(validators=[SlugsValidator()], max_length=100, required=False)
</code>```

and i have two class validators for this fields

```<code>class TitleValidator:

    MIN_TITLE_LENGTH = 20

    def __call__(self, title: str):
        if len(title) < self.MIN_TITLE_LENGTH:
            raise ValidationError(f"Min title length is {self.MIN_TITLE_LENGTH}")
        return title

class SlugsValidator:

    def __call__(self, slug):
        # Get title here
        return slug
</code>```

How can I pass the validated title into SlugValidator class?

I've tried to pass data directly to the TitleValidator instance, but the only thing I can get is the field itself, not an actual value.
Another way was to pass data inside validate() method, but seems like custom class validators are executed first, and i' getting an error that the title argument is not provided.
Is there any way I can achieve this?

It seems like it possible to get all fields if you define all class validators inside Meta class, but I'm wondering if it is possible without using Meta class

Body:
I Have this kind of serializer.py

class PostSerializer(serializers.ModelSerializer):
    title = serializers.CharField(validators=[TitleValidator()])
    slug = serializers.CharField(validators=[SlugsValidator()], max_length=100, required=False)

and i have two class validators for this fields

class TitleValidator:

    MIN_TITLE_LENGTH = 20

    def __call__(self, title: str):
        if len(title) < self.MIN_TITLE_LENGTH:
            raise ValidationError(f"Min title length is {self.MIN_TITLE_LENGTH}")
        return title

class SlugsValidator:

    def __call__(self, slug):
        # Get title here
        return slug

How can I pass the validated title into SlugValidator class?

I've tried to pass data directly to the TitleValidator instance, but the only thing I can get is the field itself, not an actual value.
Another way was to pass data inside validate() method, but seems like custom class validators are executed first, and i' getting an error that the title argument is not provided.
Is there any way I can achieve this?

It seems like it possible to get all fields if you define all class validators inside Meta class, but I'm wondering if it is possible without using Meta class


问:
How to prevent code duplication in Dart functions?
Minimal reproducible code:

bool _flag = true;
void main() {
  if (_flag) {
    apiFunction(a: 1, b: true, c: 'c');
  } else {
    apiFunction(a: 1, b: true);
  }
}

// Some function that I can neither change nor read its default values.
void apiFunction({
  int a = 0,
  bool b = false,
  String c = '',
}) {...}
```
<p>As you can see based on <code>flag</code>, I need to pass <code>c: 'c'</code>, and I'm currently duplicating <code>apiFunction(a: 1, b: true)</code> part. Is there any better way to write this?</p>
<p>Note: Please don't write this answer, because the default value is not given.</p>
<pre class="lang-dart prettyprint-override"><code>apiFunction(a: 1, b: true, c: _flag ? 'c' : '');
</code>```

Real world scenario (optional)

For those who want to see this example in real world. When using cloud_firestore_odm, the generated abstract method update() accepts non-nullable value (if the non nullable type was used for a field) and the method looks like this:

Future<void> update({
  int a,
  bool b,
  String c,
  // other fields ...
});
```
<p>Its implementation looks like:</p>
<pre class="lang-dart prettyprint-override"><code>Future<void> update({
  Object? a = _sentinel,
  Object? b = _sentinel,
  Object? c = _sentinel,
  // other fields ...
})
</code>```

Body:
Minimal reproducible code:

bool _flag = true;
void main() {
  if (_flag) {
    apiFunction(a: 1, b: true, c: 'c');
  } else {
    apiFunction(a: 1, b: true);
  }
}

// Some function that I can neither change nor read its default values.
void apiFunction({
  int a = 0,
  bool b = false,
  String c = '',
}) {...}

As you can see based on flag, I need to pass c: 'c', and I'm currently duplicating apiFunction(a: 1, b: true) part. Is there any better way to write this?

Note: Please don't write this answer, because the default value is not given.

apiFunction(a: 1, b: true, c: _flag ? 'c' : '');

Real world scenario (optional)

For those who want to see this example in real world. When using cloud_firestore_odm, the generated abstract method update() accepts non-nullable value (if the non nullable type was used for a field) and the method looks like this:

Future<void> update({
  int a,
  bool b,
  String c,
  // other fields ...
});

Its implementation looks like:

Future<void> update({
  Object? a = _sentinel,
  Object? b = _sentinel,
  Object? c = _sentinel,
  // other fields ...
})


问:
How to Override CreateModelMixin corrctly
I want to override CreateModelMixin with my own class which derived from ModelViewSet
this is the class i want to override
class CreateModelMixin:

```<code>    """
    Create a model instance.
    """
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        serializer.save()

    def get_success_headers(self, data):
        try:
            return {'Location': str(data[api_settings.URL_FIELD_NAME])}
        except (TypeError, KeyError):
            return {}
</code>```

in the first instinct, I want to override only the create function with a different serializer
but would it be more correct to override perform_create?
if someone can guide me how it is the most correct way to override that will be much of help
thank you

Body:
I want to override CreateModelMixin with my own class which derived from ModelViewSet
this is the class i want to override
class CreateModelMixin:

    """
    Create a model instance.
    """
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        serializer.save()

    def get_success_headers(self, data):
        try:
            return {'Location': str(data[api_settings.URL_FIELD_NAME])}
        except (TypeError, KeyError):
            return {}

in the first instinct, I want to override only the create function with a different serializer
but would it be more correct to override perform_create?
if someone can guide me how it is the most correct way to override that will be much of help
thank you


问:
Setting user fingerprint issue in zkteco device using php library
i need to get fingerprint of user exsits befor o, zkecko k40 machine
when i get it .. it looks as a string of different characters (a-z 0-9 §?...) and also as a binray file
now i need to set this string or this binray file to another user in another zkteco machine
i used setfingerprint() function but it didn't work
can anyone give me a good library of zkteco php

i need to get fingerprint of user exsits befor o, zkecko k40 machine
when i get it .. it looks as a string of different characters (a-z 0-9 §?...) and also as a binray file
now i need to set this string or this binray file to another user in another zkteco machine
i used setfingerprint() function but it didn't work
can anyone give me a good library of zkteco php


问:
Problem getting data from url not supporting SSL
How can I run a radio that does not support https like the one below, by adding a link to it?
Radio Link http://canliyayin.radyo7.com/;stream
Https provisioning link https://cros9.yayin.com.tr/http://canliyayin.radyo7.com/;stream

I searched a lot but I couldn't find another page like cros9.yayin.com.tr
Can you suggest an alternative link similar to this address?
Thank you very much in advance


问:
Client-side API requests not caching using fetch in Next JS
I am using Next JS to build an app that fetches data from an external API. Given that the data received from the API will be relatively static, I am using memory-cache to store the data for 24 hours and re-use when the user refreshes the page. This has been working great when called in getStaticProps() as shown below:

```<code>export async function getStaticProps() {
  const value = cache.get(urls);
  if (value) {
    return {
      props: {
        result: value,
      },
    }
  } else {
    const data = await Promise.all(urls.map(url =>
      fetch(url, options).then(resp => resp.json())
    ));
    cache.put(urls, data, 24 * 1000 * 60 * 60);
    return {
      props: {
        result: data,
      },
    }
  }
</code>```

However, as part of the urls that are called they require an &timezone= parameter. I am detecting the users timezone using the code Intl.DateTimeFormat().resolvedOptions().timeZone but given that getStaticProps() is server-side, it is not able to correctly include the script in the API call so the timezone parameter is being ignored.

I have tried to fix this by switching the API call to be client-side using the code below:

```<code>  const [results, setResults] = useState([]);

  async function getData() {
    const cached = cache.get(urls);
    if (cached) {
      setResults(cached);
    } else {
      const data = await Promise.all(urls.map(url =>
        fetch(url, options).then(resp => resp.json())
      ));
      cache.put(urls, data, 24 * 1000 * 60 * 60);

      setResults(data);
    }
  }

  useEffect(() => {
    getData();
  }, []);
</code>```

The timezone parameter is now calling correctly but the cache appears to have stopped working. Each time I refresh the page it re-fetches the data from the API rather than using the cached result.

Can cache be stored in this way using client-side data fetching or do I need to use a different approach?

Body:
I am using Next JS to build an app that fetches data from an external API. Given that the data received from the API will be relatively static, I am using memory-cache to store the data for 24 hours and re-use when the user refreshes the page. This has been working great when called in getStaticProps() as shown below:

export async function getStaticProps() {
  const value = cache.get(urls);
  if (value) {
    return {
      props: {
        result: value,
      },
    }
  } else {
    const data = await Promise.all(urls.map(url =>
      fetch(url, options).then(resp => resp.json())
    ));
    cache.put(urls, data, 24 * 1000 * 60 * 60);
    return {
      props: {
        result: data,
      },
    }
  }

However, as part of the urls that are called they require an &timezone= parameter. I am detecting the users timezone using the code Intl.DateTimeFormat().resolvedOptions().timeZone but given that getStaticProps() is server-side, it is not able to correctly include the script in the API call so the timezone parameter is being ignored.

I have tried to fix this by switching the API call to be client-side using the code below:

  const [results, setResults] = useState([]);

  async function getData() {
    const cached = cache.get(urls);
    if (cached) {
      setResults(cached);
    } else {
      const data = await Promise.all(urls.map(url =>
        fetch(url, options).then(resp => resp.json())
      ));
      cache.put(urls, data, 24 * 1000 * 60 * 60);

      setResults(data);
    }
  }

  useEffect(() => {
    getData();
  }, []);

The timezone parameter is now calling correctly but the cache appears to have stopped working. Each time I refresh the page it re-fetches the data from the API rather than using the cached result.

Can cache be stored in this way using client-side data fetching or do I need to use a different approach?


问:
Hiding the IP address and port of my Authorization Server
I consider building a web application and I want to use OAuth2 protocol for the authentication and authorization of users.

I know that Client Server redirects user to Authorization Server to enter username and password. Thus, user can see the URL of login page on browser. I do not want to show what is written on url actually to user due to security reasons. I do not want to expose my Authorization Server with an host name and port to public.

As a solution, I decided Client Server act on behalf of user(browser). That means, client server will send get login page request and return the response (html) coming from Authorization Server. This is simple and I am able to serve login page on Client Server, but I do not know how can I make a request model (client-id, client-secret, redirect-uri, username, password) and where I will send request to (for example "/oauth2/authorize" and then "/oauth2/token") manually. I should apply all the steps in the right order. Can you suggest me this approach? or do you have any idea to achieve hiding the Authorization Server from public? or that is not so important?


问:
How should I troubleshootiing 'strconv.ParseFloat: parsing "to": invalid syntax' in prometheus
As the titles. I scraped the metrics of pods,encountered the errors in the prometheus target as follow:

target: http://192.168.62.150:20200/metrics

error: strconv.ParseFloat: parsing "to": invalid syntax

How prometheus parse the metrics and where should I find the data with error.

@DazWilkin
The part of curl http://192.168.62.136:20200/metrics  as follow:20200 is the port of consult envoy，9090 is the port the productapi service exposed.

```<code>envoy_server_initialization_time_ms_bucket{local_cluster="product-api",consul_source_service="product-api",consul_source_namespace="default",consul_source_partition="default",consul_source_datacenter="dc1",le="300000"} 1
envoy_server_initialization_time_ms_bucket{local_cluster="product-api",consul_source_service="product-api",consul_source_namespace="default",consul_source_partition="default",consul_source_datacenter="dc1",le="600000"} 1
envoy_server_initialization_time_ms_bucket{local_cluster="product-api",consul_source_service="product-api",consul_source_namespace="default",consul_source_partition="default",consul_source_datacenter="dc1",le="1800000"} 1
envoy_server_initialization_time_ms_bucket{local_cluster="product-api",consul_source_service="product-api",consul_source_namespace="default",consul_source_partition="default",consul_source_datacenter="dc1",le="3600000"} 1
envoy_server_initialization_time_ms_bucket{local_cluster="product-api",consul_source_service="product-api",consul_source_namespace="default",consul_source_partition="default",consul_source_datacenter="dc1",le="+Inf"} 1
envoy_server_initialization_time_ms_sum{local_cluster="product-api",consul_source_service="product-api",consul_source_namespace="default",consul_source_partition="default",consul_source_datacenter="dc1"} 1350
envoy_server_initialization_time_ms_count{local_cluster="product-api",consul_source_service="product-api",consul_source_namespace="default",consul_source_partition="default",consul_source_datacenter="dc1"} 1
failed to scrape metrics at url "http://127.0.0.1:9090/metrics"
</code>```

Body:
As the titles. I scraped the metrics of pods,encountered the errors in the prometheus target as follow:

target: http://192.168.62.150:20200/metrics

error: strconv.ParseFloat: parsing "to": invalid syntax

How prometheus parse the metrics and where should I find the data with error.

@DazWilkin
The part of curl http://192.168.62.136:20200/metrics  as follow:20200 is the port of consult envoy，9090 is the port the productapi service exposed.

envoy_server_initialization_time_ms_bucket{local_cluster="product-api",consul_source_service="product-api",consul_source_namespace="default",consul_source_partition="default",consul_source_datacenter="dc1",le="300000"} 1
envoy_server_initialization_time_ms_bucket{local_cluster="product-api",consul_source_service="product-api",consul_source_namespace="default",consul_source_partition="default",consul_source_datacenter="dc1",le="600000"} 1
envoy_server_initialization_time_ms_bucket{local_cluster="product-api",consul_source_service="product-api",consul_source_namespace="default",consul_source_partition="default",consul_source_datacenter="dc1",le="1800000"} 1
envoy_server_initialization_time_ms_bucket{local_cluster="product-api",consul_source_service="product-api",consul_source_namespace="default",consul_source_partition="default",consul_source_datacenter="dc1",le="3600000"} 1
envoy_server_initialization_time_ms_bucket{local_cluster="product-api",consul_source_service="product-api",consul_source_namespace="default",consul_source_partition="default",consul_source_datacenter="dc1",le="+Inf"} 1
envoy_server_initialization_time_ms_sum{local_cluster="product-api",consul_source_service="product-api",consul_source_namespace="default",consul_source_partition="default",consul_source_datacenter="dc1"} 1350
envoy_server_initialization_time_ms_count{local_cluster="product-api",consul_source_service="product-api",consul_source_namespace="default",consul_source_partition="default",consul_source_datacenter="dc1"} 1
failed to scrape metrics at url "http://127.0.0.1:9090/metrics"


问:
Problems running Processing P2D and P3D in Linux
I’d like to run Processing in an old computer (Acer ES1) with Xubuntu , but while everything seems to work fine, when I run sketches that use P2D or P3D I get the following error:

InternalError: XXX0 profile[2]: GL2 -> profileImpl GL3bc !!! not mapped

This happens with Processing 4.1.1. (as well as 4.0 and 3.5.4). In my understandings the issues is about an old bug that has been solved in the recent version for most of the machines, but not for mine. I suppose the bug should be related to this:
P3D don’t work on AMD dynamic switchable graphics #5308

I tried to follow all the possible workarounds suggested in the previous link but nothing worked out. The only thing I didn’t try and that I would avoid is downgrading the version, since I need to work with the latests.


问:
I need HTML translation
I was researching on codepen about web animations and I cama across this html code. Please I need help tarnsaltion it into normal html code.

HERE IS THE LINK FOR FURTHER INTERPRETATION  https://codepen.io/noeldelgado/pen/BaogqYy

```<code>- w = 1240
- h = 874

.loader.df.aic.jcc
  %div
    %h1 Loading
    %h2.loader--text 0%

.demo-wrapper
  %header.df.aic.jcc
    %div
      %h1 ScrollTrigger
      %h2 demo

  %section.demo-text
    .wrapper.text
      ABCDEFGHIJKLMNOPQRSTUVWXYZ

  - (1..4).each do |i|
    %section.demo-gallery
      %ul.wrapper
        - (1..rand(3..4)).each do |i|
          %li
            %img{:src=>"https://source.unsplash.com/random/#{w}x#{h}?sig=#{rand(0..206)}", :width => w, :height => h}

  %section.demo-text
    .wrapper.text
      ABCDEFGHIJKLMNOPQRSTUVWXYZ

  %footer.df.aic.jcc
    %p Images from <a href="https://unsplash.com/">Unsplash</a>
</code>```

I understand most of it but this part is the most confusing (1..4).each do |i|

Title: I need HTML translation

Body:
I was researching on codepen about web animations and I cama across this html code. Please I need help tarnsaltion it into normal html code.

HERE IS THE LINK FOR FURTHER INTERPRETATION  https://codepen.io/noeldelgado/pen/BaogqYy

- w = 1240
- h = 874

.loader.df.aic.jcc
  %div
    %h1 Loading
    %h2.loader--text 0%

.demo-wrapper
  %header.df.aic.jcc
    %div
      %h1 ScrollTrigger
      %h2 demo

  %section.demo-text
    .wrapper.text
      ABCDEFGHIJKLMNOPQRSTUVWXYZ

  - (1..4).each do |i|
    %section.demo-gallery
      %ul.wrapper
        - (1..rand(3..4)).each do |i|
          %li
            %img{:src=>"https://source.unsplash.com/random/#{w}x#{h}?sig=#{rand(0..206)}", :width => w, :height => h}

  %section.demo-text
    .wrapper.text
      ABCDEFGHIJKLMNOPQRSTUVWXYZ

  %footer.df.aic.jcc
    %p Images from Unsplash

I understand most of it but this part is the most confusing (1..4).each do |i|