问:
Flutter Pagination in the ListView.builder
I want to integrate pagination in my flutter app and here is what I have done

```<code>class Tedd extends StatefulWidget {
  @override
  _TeddState createState() => _TeddState();
}

class _TeddState extends State<Tedd> {
  NewsArticleService _articleService = NewsArticleService();
  List<NewsModel> _newsList = [];
  bool isLoading = true;
  int currentPage = 1;
  bool hasReachedEnd = false;

  _getAllNews() async {
    if (hasReachedEnd) {
      return;
    }

    setState(() {
      isLoading = true;
    });

    var articles = await _articleService.getAllNews(page: currentPage);
    var result = json.decode(articles.body);
    result['data'].forEach((data) {
      var news = NewsModel();
      news.id = data["id"];
      news.articleTitle = data["name"];
      if (mounted) {
        setState(() {
          _newsList.add(news);
          isLoading = false;
        });
      }
    });

    if(result["meta"]['current_page'] == result["meta"]['last_page']){
      setState(() {
        hasReachedEnd = true;
      });
    } else {
      setState(() {
        currentPage++;
      });
    }
  }

  @override
  void initState() {
    _getAllNews();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemCount: _newsList.length + (isLoading ? 1 : 0),
        itemBuilder: (context, index) {
          if (index == _newsList.length) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
          return Container(
              height: 150, child: Text(_newsList[index].articleTitle!));
        },
      ),
    );
  }
}
</code>```

And Here is my Repository class

```<code>class Repository {
  String _baseUrl = "pkbhai.com";
  String _subUrl =  "myprojects/kids-stories/api";

  httpGet(String api) async {
    return await http.get(Uri.https(_baseUrl, "$_subUrl/$api"));
  }
}
class NewsArticleService {
  Repository? _repository;
  NewsArticleService() {
    _repository = Repository();
  }
  getAllNews({int? page = 1}) async {
    return await _repository?.httpGet('all-stories?page=$page');
  }
}
</code>```

I want to fetch more available data when I scroll more and more.

But I am not getting pagination data, where am I doing wrong please suggest to me,

here is my JSON data please take a look
https://pkbhai.com/myprojects/kids-stories/api/all-stories

Body:
I want to integrate pagination in my flutter app and here is what I have done

class Tedd extends StatefulWidget {
  @override
  _TeddState createState() => _TeddState();
}

class _TeddState extends State<Tedd> {
  NewsArticleService _articleService = NewsArticleService();
  List<NewsModel> _newsList = [];
  bool isLoading = true;
  int currentPage = 1;
  bool hasReachedEnd = false;

  _getAllNews() async {
    if (hasReachedEnd) {
      return;
    }

    setState(() {
      isLoading = true;
    });

    var articles = await _articleService.getAllNews(page: currentPage);
    var result = json.decode(articles.body);
    result['data'].forEach((data) {
      var news = NewsModel();
      news.id = data["id"];
      news.articleTitle = data["name"];
      if (mounted) {
        setState(() {
          _newsList.add(news);
          isLoading = false;
        });
      }
    });

    if(result["meta"]['current_page'] == result["meta"]['last_page']){
      setState(() {
        hasReachedEnd = true;
      });
    } else {
      setState(() {
        currentPage++;
      });
    }
  }

  @override
  void initState() {
    _getAllNews();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemCount: _newsList.length + (isLoading ? 1 : 0),
        itemBuilder: (context, index) {
          if (index == _newsList.length) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
          return Container(
              height: 150, child: Text(_newsList[index].articleTitle!));
        },
      ),
    );
  }
}

And Here is my Repository class

class Repository {
  String _baseUrl = "pkbhai.com";
  String _subUrl =  "myprojects/kids-stories/api";

  httpGet(String api) async {
    return await http.get(Uri.https(_baseUrl, "$_subUrl/$api"));
  }
}
class NewsArticleService {
  Repository? _repository;
  NewsArticleService() {
    _repository = Repository();
  }
  getAllNews({int? page = 1}) async {
    return await _repository?.httpGet('all-stories?page=$page');
  }
}

I want to fetch more available data when I scroll more and more.

But I am not getting pagination data, where am I doing wrong please suggest to me,

here is my JSON data please take a look
https://pkbhai.com/myprojects/kids-stories/api/all-stories


来源: stackexchange

问:
Decrypting Image Headers for WebP, JPEG XL, HEIF, AVIF image formats using Python
I want to decode and understand the structure of various latest image formats (namely WebP, JPEG XL, HEIF and AVIF) and compare header information with respect to image data to see which format is header information heavy with respect to image data. I was wondering how I can do this using Python.

Is there a simple way to decode various image file formats of the same image in either HEX or Binary and learn how much of the file contents is the image data and how much else is the header information? Better yet, is there a way to learn the breakdown of header information for various file formats??

So far I got to a point where I got a file to open in binary mode (Below is the sample code I have for the AVIF test image) but I'm not sure how I can decrypt, read and understand the structure. Googling around, I found some information for JPEG format (like the information shown on this page for JPEG https://yasoob.me/posts/understanding-and-writing-jpeg-decoder-in-python/) but none for WebP, HEIF, and AVIF on how I can read the binary format.

image = 'test.avif'

with open(image, 'rb') as image_file:

```<code>content = image_file.read()
</code>```

Content

I wish to know how exactly can we extract the header information from the images while compression.

ContentLicense: CC BY-SA 4.0

Body:
I want to decode and understand the structure of various latest image formats (namely WebP, JPEG XL, HEIF and AVIF) and compare header information with respect to image data to see which format is header information heavy with respect to image data. I was wondering how I can do this using Python.

Is there a simple way to decode various image file formats of the same image in either HEX or Binary and learn how much of the file contents is the image data and how much else is the header information? Better yet, is there a way to learn the breakdown of header information for various file formats??

So far I got to a point where I got a file to open in binary mode (Below is the sample code I have for the AVIF test image) but I'm not sure how I can decrypt, read and understand the structure. Googling around, I found some information for JPEG format (like the information shown on this page for JPEG https://yasoob.me/posts/understanding-and-writing-jpeg-decoder-in-python/) but none for WebP, HEIF, and AVIF on how I can read the binary format.

image = 'test.avif'

with open(image, 'rb') as image_file:

content = image_file.read()

Content

I wish to know how exactly can we extract the header information from the images while compression.


问:
React Native - Sending a PDF with fetch but it is empty
Hey guys I have a question regarding the fetch function from JavaScript and the Package Nodemailer.

NOTE: I am using Expo.

I have a PDF created on my Emulator which looks good (filled with data). Now I want to send this PDF to my Backend and therer I want to send the File out as a PDF and get it in my Mails.

Frontend fetch-Call for my Backend:

```<code>  async sendMonthReportMail(fileUri) {

    await fetch(`${connectionString}/api/mails/sendmonthreport`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        senderUser: "My Name",
        recieverMail: "myname@mymail.com",
        pathMonthLock: `${fileUri}`
      })
    })
    .then(res => res.json())
    .then(res => {
      console.log("Success SendMailMonthLock - " + res)
    })
    .catch(err => console.log("Error SendMailMonthLock - " + err))
  }
</code>```

I have also tried to use formData and change the Content-Type to "application/pdf" but this did not work.

Now my Backend Code looks like this:

```<code>  router.post("/sendmonthreport", async (req, res) => {
    const {recieverMail} = req.body;
    const {senderUser} = req.body;
    const {pathMonthLock} = req.body;

    let transport = nodemailer.createTransport({
      host: "mailserver",
      port: xx,
      secure: false,
      tls: {
        rejectUnauthorized: false
      }
    });

    var message = {
      from: "My Sendermail <sender@mail.com>",
      to: `${recieverMail}`,
      subject: `Mail comming from - ${senderUser}`,
      text: `EmailText `,
      attachments:[{
        filename: "MyFilename.pdf",
        content: __dirname + `./${pathMonthLock}`,
      }]
    }

    await transport.sendMail(message)
    .catch(err => console.log("Error Mail: " + err ))

    res.send("email send")
  })
</code>```

Now the way that I choose the file.uri is threw the DocumentPicker for Expo.

The Problem I am having now is, that the Mail gets send correctly and there is a PDF attached to it with the correct name. However when I look at the PDF Size it is only 500Bytes and it is completly empty. When trying to open the File that is send via Mail then it tells me that the File is corrupted or wrong format.

How can I send the actual content that is inside the PDF?

When I try to use formData:

```<code>  async sendMonthReportMail(file) {

    fdPost.append("file", file);
    fdPost.append("senderUser", "User Name");
    fdPost.append("recieverMail", "username@mail.com");

    console.log(fdPost);

    await fetch(`${connectionString}/api/mails/sendmonthreport`, {
      method: "POST",
      headers: {
        accept: "application/json"
        // "Content-Type": "multipart/form-data",
        // "Content-Type": "application/json",
        // "Content-Type" : "application/pdf"
        // "Content-Type": "application/x-www-form-urlencoded"
      },

      body: fdPost

    })
    .then(res => res.json())
    .then(res => {
      console.log("Success SendMailMonthLock - " + res)
    })
    .catch(err => console.log("Error SendMailMonthLock - " + err))
  }
</code>```

fdPost is defined at the top of my file, console.logging it gives me a valid FormData but the request ends with a Network Error!

```<code>Error SendMailMonthLock - TypeError: Network request failed
</code>```

Also my Backend does not react to that call.

I also tried to use RN Fetch Blob but it only works in React Native only Projects. I am using Expo so this is not a soultion for me!

Edit:

I tried the suggestion in the comments (using Multer):

Frontend:

```<code>  async sendMonthReportMail(file) {

    fdPost.append("file", file);
    fdPost.append("senderUser", "name");
    fdPost.append("recieverMail", "mail@mail.com");

    await fetch(`${connectionString}/api/mails/sendmonthreportTest`, {
      method: "POST",
      headers: {
        Accept: "application/json",
        'Content-Type': 'multipart/form-data'
        },
      body: fdPost

    })
    .catch(err => console.log("Error SendMailMonthLock - " + err))
  }
</code>```

Backend:

```<code>router.post("/sendmonthreportTest", upload.single("file"), (req, res) => {
  console.dir(req.file + req.body);
})
</code>```

Still I have the same issue! It gives me TypeError: Network Error.

Also when I try to call that point with Postman I am getting:

```<code>POST /api/mails/sendmonthreportTest 500 6.952 ms - 1221
TypeError: Cannot convert object to primitive value
</code>```

To confirm my POST Body when I console.log the fdPost before the fetch:

```<code>{"_parts":[["file",{"size":69496,"name":"Monatsbericht_User_Name_Dezember2022.pdf","type":"success","uri":"file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540yxxx%252Fxxx/DocumentPicker/2xx07e4-4136-4b6f-ad70-26xxac64064.pdf","mimeType":"application/pdf"}],["senderUser","User Name"],["recieverMail","user@mail.com"]]}
</code>```

Body:
Hey guys I have a question regarding the fetch function from JavaScript and the Package Nodemailer.

NOTE: I am using Expo.

I have a PDF created on my Emulator which looks good (filled with data). Now I want to send this PDF to my Backend and therer I want to send the File out as a PDF and get it in my Mails.

Frontend fetch-Call for my Backend:

  async sendMonthReportMail(fileUri) {

    await fetch(`${connectionString}/api/mails/sendmonthreport`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        senderUser: "My Name",
        recieverMail: "myname@mymail.com",
        pathMonthLock: `${fileUri}`
      })
    })
    .then(res => res.json())
    .then(res => {
      console.log("Success SendMailMonthLock - " + res)
    })
    .catch(err => console.log("Error SendMailMonthLock - " + err))
  }

I have also tried to use formData and change the Content-Type to "application/pdf" but this did not work.

Now my Backend Code looks like this:

  router.post("/sendmonthreport", async (req, res) => {
    const {recieverMail} = req.body;
    const {senderUser} = req.body;
    const {pathMonthLock} = req.body;

    let transport = nodemailer.createTransport({
      host: "mailserver",
      port: xx,
      secure: false,
      tls: {
        rejectUnauthorized: false
      }
    });

    var message = {
      from: "My Sendermail <sender@mail.com>",
      to: `${recieverMail}`,
      subject: `Mail comming from - ${senderUser}`,
      text: `EmailText `,
      attachments:[{
        filename: "MyFilename.pdf",
        content: __dirname + `./${pathMonthLock}`,
      }]
    }

    await transport.sendMail(message)
    .catch(err => console.log("Error Mail: " + err ))

    res.send("email send")
  })

Now the way that I choose the file.uri is threw the DocumentPicker for Expo.

The Problem I am having now is, that the Mail gets send correctly and there is a PDF attached to it with the correct name. However when I look at the PDF Size it is only 500Bytes and it is completly empty. When trying to open the File that is send via Mail then it tells me that the File is corrupted or wrong format.

How can I send the actual content that is inside the PDF?

When I try to use formData:

  async sendMonthReportMail(file) {

    fdPost.append("file", file);
    fdPost.append("senderUser", "User Name");
    fdPost.append("recieverMail", "username@mail.com");

    console.log(fdPost);

    await fetch(`${connectionString}/api/mails/sendmonthreport`, {
      method: "POST",
      headers: {
        accept: "application/json"
        // "Content-Type": "multipart/form-data",
        // "Content-Type": "application/json",
        // "Content-Type" : "application/pdf"
        // "Content-Type": "application/x-www-form-urlencoded"
      },

      body: fdPost

    })
    .then(res => res.json())
    .then(res => {
      console.log("Success SendMailMonthLock - " + res)
    })
    .catch(err => console.log("Error SendMailMonthLock - " + err))
  }

fdPost is defined at the top of my file, console.logging it gives me a valid FormData but the request ends with a Network Error!

Error SendMailMonthLock - TypeError: Network request failed

Also my Backend does not react to that call.

I also tried to use RN Fetch Blob but it only works in React Native only Projects. I am using Expo so this is not a soultion for me!

Edit:

I tried the suggestion in the comments (using Multer):

Frontend:

  async sendMonthReportMail(file) {

    fdPost.append("file", file);
    fdPost.append("senderUser", "name");
    fdPost.append("recieverMail", "mail@mail.com");

    await fetch(`${connectionString}/api/mails/sendmonthreportTest`, {
      method: "POST",
      headers: {
        Accept: "application/json",
        'Content-Type': 'multipart/form-data'
        },
      body: fdPost

    })
    .catch(err => console.log("Error SendMailMonthLock - " + err))
  }

Backend:

router.post("/sendmonthreportTest", upload.single("file"), (req, res) => {
  console.dir(req.file + req.body);
})

Still I have the same issue! It gives me TypeError: Network Error.

Also when I try to call that point with Postman I am getting:

POST /api/mails/sendmonthreportTest 500 6.952 ms - 1221
TypeError: Cannot convert object to primitive value

To confirm my POST Body when I console.log the fdPost before the fetch:

{"_parts":[["file",{"size":69496,"name":"Monatsbericht_User_Name_Dezember2022.pdf","type":"success","uri":"file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540yxxx%252Fxxx/DocumentPicker/2xx07e4-4136-4b6f-ad70-26xxac64064.pdf","mimeType":"application/pdf"}],["senderUser","User Name"],["recieverMail","user@mail.com"]]}


问:
Load Eland dataframe partially by query (ElasticSearch, Python)
I'm trying to fetch data from ElasticSearch into an Eland dataframe partially, because it takes too much time to load the entire index.

The following works, except for the _query_compiler. The official Eland docs contains the parameter, but no description about how it works. I'm not even sure if this is the right approach though.

```<code>username = '..'
password = '..'
ip = '..'

es = Elasticsearch(hosts='https://{}:{}@{}'.format(username, password, ip), request_timeout=300, ca_certs='./Security/cert.pem')

index_name = '..'
index = ed.DataFrame(es_client=es, es_index_pattern=index_name, _query_compiler=???).to_pandas()
</code>```

The following query seems to work, except for the part that it's not an Eland dataframe. (Also, the body parameter is deprecated but w/e.) There is a related question here, but it's not helping towards a solution.

```<code>search_body = {
            "query": {
                "match": {
                    "some_field": "true"
                }
              }
        }

results = es.search(index=index_name, body=search_body)
</code>```

Body:
I'm trying to fetch data from ElasticSearch into an Eland dataframe partially, because it takes too much time to load the entire index.

The following works, except for the _query_compiler. The official Eland docs contains the parameter, but no description about how it works. I'm not even sure if this is the right approach though.

username = '..'
password = '..'
ip = '..'

es = Elasticsearch(hosts='https://{}:{}@{}'.format(username, password, ip), request_timeout=300, ca_certs='./Security/cert.pem')

index_name = '..'
index = ed.DataFrame(es_client=es, es_index_pattern=index_name, _query_compiler=???).to_pandas()

The following query seems to work, except for the part that it's not an Eland dataframe. (Also, the body parameter is deprecated but w/e.) There is a related question here, but it's not helping towards a solution.

search_body = {
            "query": {
                "match": {
                    "some_field": "true"
                }
              }
        }

results = es.search(index=index_name, body=search_body)


问:
import packages in CoffeeScript
I'm trying to import a package inside an old coffe script file:

import Quill from 'quill/core'

But keep getting the error:

Uncaught SyntaxError: Cannot use import statement outside a module

I set type: module inside the package.json file too. The import also is working in Vue files.

Title: import packages in CoffeeScript


问:
Different websocket endpoints with Apache2 vs "manage.py runserver". Django Channels
I have different endpoints when i run Django in apache compare to when I run it in the terminal.

Can it be some configuration in apache?

I belive it can be this ?
Apache 2 conf
ProxyPass "/ws/" "ws://127.0.0.1:8000/"

What does this mean; "/ws/"?

Apache to work:
ws_urlpatterns = [path('some_url/', Andring.as_asgi()), ]

Run in terminal:
 ws_urlpatterns = [path('ws/some_url/', Andring.as_asgi()), ]

In JS:
const socket = new WebSocket("ws://" + window.location.host + "/ws/some_url/");


问:
How can I echo a php variable that's INSIDE a php string variable?
I've got a database full of text fields, all of which contain WITHIN them the characters $myvariable.
When I retrieve such text field and save it as a php variable, say as $myDBtext, I can definitely echo it, but I'm having really hard time echoing the variable WITHIN it (I got $myvariable's value already set). That is, I can't display the value of $myvariable. It just writes $myvariable but not its value...
How can I display $myvariable's value?

```<code><?php echo $myDBtext;?>
</code>```

just displays the entire text, writing $myvariable but not its value.

```<code><?php echo "<?php echo '".$myDBtext."' ?>";?>
</code>```

doesn't display anything.

Body:
I've got a database full of text fields, all of which contain WITHIN them the characters $myvariable.
When I retrieve such text field and save it as a php variable, say as $myDBtext, I can definitely echo it, but I'm having really hard time echoing the variable WITHIN it (I got $myvariable's value already set). That is, I can't display the value of $myvariable. It just writes $myvariable but not its value...
How can I display $myvariable's value?

<?php echo $myDBtext;?>

just displays the entire text, writing $myvariable but not its value.

<?php echo "<?php echo '".$myDBtext."' ?>";?>

doesn't display anything.


问:
Questions about cuda memory model: does causality order remain transitive across different scopes
we recently encountered some CUDA memory model related issues when doing cross-CTA communication.
We are seeking an authoritative answer from CUDA memory model experts.
Specifically, we want to know whether causality order remain transitive across different scopes.
The specific case is as follows:

```<code>__device__ unsigned int count = 0;
__shared__ bool isLastBlockDone;
__global__ void sum(const float* array, unsigned int N,
                    float* result)
{
    // Each block sums a subset of the input array.
    float partialSum = calculatePartialSum(array, N);

    if (threadIdx.x == 0) {

        // Thread 0 of each block stores the partial sum
        // to global memory.
        result[blockIdx.x] = partialSum;

        // Thread 0 makes sure that the incrementation
        // of the "count" variable is only performed after
        // the partial sum has been written to global memory.
        __threadfence();

        // Thread 0 signals that it is done.
        unsigned int value = atomicInc(&count, gridDim.x);

        // Thread 0 determines if its block is the last
        // block to be done.
        isLastBlockDone = (value == (gridDim.x - 1));
    }

    // Synchronize to make sure that each thread reads
    // the correct value of isLastBlockDone.
    __syncthreads();

    if (isLastBlockDone) {

        // The last block sums the partial sums
        // stored in result[0 .. gridDim.x-1]
        float totalSum = calculateTotalSum(result);

        if (threadIdx.x == 0) {

            // Thread 0 of last block stores the total sum
            // to global memory and resets the count
            // varialble, so that the next kernel call
            // works properly.
            result[0] = totalSum;
            count = 0;
        }
    }
}
</code>```

In the above case, the result array is not declared as volatile, so they may be cached incoherently in L1.

So we want to know, according to CUDA memory model, when the last block executes calculateTotalSum in line 36, will it read out other CTA’s partial sum safely?

We suspect this has something to do with causality order transitivity across different scopes:
With threadfence(line 18) and atomic operations(line 21), causality order is established  in gpu scope between other block's write to result array(line 13)and last block’s write to the isLastBlockDone flag(line 25):
write_result_array -> write_isLastBlockDone.
With __syncthreads(line 30), causality order is established  in cta scope between write isLastBlockDone(line 25) and read result array(line 36):
write_isLastBlockDone -> read_result_array.

Can the causality order maintain transitive across different scopes according to the cuda memory model?
For example, in our case, does the following causality order hold?:
write_result_array -> write_isLastBlockDone -> read_result_array.

Is this code correct according to cuda memory model?
Does causality order remain transitive across different scopes?

Body:
we recently encountered some CUDA memory model related issues when doing cross-CTA communication.
We are seeking an authoritative answer from CUDA memory model experts.
Specifically, we want to know whether causality order remain transitive across different scopes.
The specific case is as follows:

__device__ unsigned int count = 0;
__shared__ bool isLastBlockDone;
__global__ void sum(const float* array, unsigned int N,
                    float* result)
{
    // Each block sums a subset of the input array.
    float partialSum = calculatePartialSum(array, N);

    if (threadIdx.x == 0) {

        // Thread 0 of each block stores the partial sum
        // to global memory.
        result[blockIdx.x] = partialSum;

        // Thread 0 makes sure that the incrementation
        // of the "count" variable is only performed after
        // the partial sum has been written to global memory.
        __threadfence();

        // Thread 0 signals that it is done.
        unsigned int value = atomicInc(&count, gridDim.x);

        // Thread 0 determines if its block is the last
        // block to be done.
        isLastBlockDone = (value == (gridDim.x - 1));
    }

    // Synchronize to make sure that each thread reads
    // the correct value of isLastBlockDone.
    __syncthreads();

    if (isLastBlockDone) {

        // The last block sums the partial sums
        // stored in result[0 .. gridDim.x-1]
        float totalSum = calculateTotalSum(result);

        if (threadIdx.x == 0) {

            // Thread 0 of last block stores the total sum
            // to global memory and resets the count
            // varialble, so that the next kernel call
            // works properly.
            result[0] = totalSum;
            count = 0;
        }
    }
}

In the above case, the result array is not declared as volatile, so they may be cached incoherently in L1.

So we want to know, according to CUDA memory model, when the last block executes calculateTotalSum in line 36, will it read out other CTA’s partial sum safely?

We suspect this has something to do with causality order transitivity across different scopes:
With threadfence(line 18) and atomic operations(line 21), causality order is established  in gpu scope between other block's write to result array(line 13)and last block’s write to the isLastBlockDone flag(line 25):
write_result_array -> write_isLastBlockDone.
With __syncthreads(line 30), causality order is established  in cta scope between write isLastBlockDone(line 25) and read result array(line 36):
write_isLastBlockDone -> read_result_array.

Can the causality order maintain transitive across different scopes according to the cuda memory model?
For example, in our case, does the following causality order hold?:
write_result_array -> write_isLastBlockDone -> read_result_array.

Is this code correct according to cuda memory model?
Does causality order remain transitive across different scopes?


问:
Fixing data missing in Hadoop
I have a question, which according to my understanding, is more about theory.

I have a job run in Hadoop; basically, it pulls out all customer information from all applications to the company's database. The job is run on a daily basis. The result is a master table with over 200 columns.

customer_id
active_status
dayid

1
0
20221230

2
1
20230101

From Jan 01st to Jan 03rd, data in the column active_status was missing. One of my stakeholders needs the data on Jan 02nd for the reports. My boss said there were 2 options:

Copy the data of Jan 02 into a new table with values in column A being replaced with the data of Jan 04

Fix the master table. She said that in Hadoop, tables could not be updated in a way like in the SQL database, and I would need to remove the file in HDFS, add a new file, and load data into the master table.

This is not the first time I heard that tables could not be updated in Hadoop. I have read that Hadoop works in the Write-Once & Read-Many mechanism.

However, I also know there is the statement INSERT OVERWRITE, which is used to replace existing data with new rows.

So, how should I understand this? For the 2nd option recommended by my boss. Is only the file related to dayid 20230102 be removed from HDFS, or the whole file (all dayid) is removed?

I'm a BA and am quite new in big data, so I hope you can shed more light on this.

Title: Fixing data missing in Hadoop


问:
Symfony 6.0 After exit Impersonation, if i go back from browser , then i get that temporary user's session in my session
Symfony 6.0 After exit Impersonation, if I go back from the browser, then I get that temporary user's session in my session.
On clicking, Exit Impersonation, it redirects to my destination perfectly.

However, after one Impersonation, and after exit of it. If I try to switch users with another user, I get the earlier user's session only, the not current one.

For Exit Impersonation

```<code>{% if is_granted('IS_IMPERSONATOR') %}
    <a style="color:indigo;" href="{{ impersonation_exit_path(path('companylist') ) }}">Exit From Switch Account</a>
{% endif %}
</code>```

Security.yml

```<code>security:
    enable_authenticator_manager: true
    # https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords
    role_hierarchy:
        ROLE_ADMIN: ['ROLE_CUSTOMER_ADMIN', 'ROLE_USER_ADMIN', 'ROLE_ALLOWED_TO_SWITCH']
    firewalls:
        app_user_provider:
            switch_user: true
            login_link:
                check_route: login_check
                signature_properties: ['id']
                max_uses: 2
                default_target_path: dashboard
                lifetime: 300
            provider: app_user_provider

</code>```

Body:
Symfony 6.0 After exit Impersonation, if I go back from the browser, then I get that temporary user's session in my session.
On clicking, Exit Impersonation, it redirects to my destination perfectly.

However, after one Impersonation, and after exit of it. If I try to switch users with another user, I get the earlier user's session only, the not current one.

For Exit Impersonation

{% if is_granted('IS_IMPERSONATOR') %}
    Exit From Switch Account
{% endif %}

Security.yml

security:
    enable_authenticator_manager: true
    # https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords
    role_hierarchy:
        ROLE_ADMIN: ['ROLE_CUSTOMER_ADMIN', 'ROLE_USER_ADMIN', 'ROLE_ALLOWED_TO_SWITCH']
    firewalls:
        app_user_provider:
            switch_user: true
            login_link:
                check_route: login_check
                signature_properties: ['id']
                max_uses: 2
                default_target_path: dashboard
                lifetime: 300
            provider: app_user_provider


问:
railway deployemnt (taking too much time on page One Moment your app should be live soon)
i have deployed my node Js project on railway through Github and it deployed successfully also shows in production log
npm WARN config production Use --omit=dev instead.

apitwidleagent@1.0.0 start
node index.js
your server is running on port to 6499 finally
mongoDB is connected

but its taking too much time on page when its say wait one moment your app should be live soon,its been around 30 mins passed and it still on waiting

i have check log but there is no error its loging my running messages
npm WARN config production Use --omit=dev instead.

apitwidleagent@1.0.0 start
node index.js
your server is running on port to 6499 finally
mongoDB is connected


问:
Django fixing migrations order for unit testing
I'm working on a codebase which has a lot of migrations. We also have SQL views which are defined in the migrations and later updated in the migrations (whenever changes to the SQL views were required). We have a challenge where when running unit tests the migrations are not applied in the same appear as they currently appear in the django_migrations table. This causes unit tests to fail.

My thought is, I could probably write a script to the dependencies of all the migrations files to follow the same order of django_migrations thus ensuring that migrations are run in the correct order. Then I can look into squashing migrations.

But this is a lengthy process and I'm not sure if this will actually work.

Has anyone come across this issue before? If so, how did you overcome it?


问:
Is it possible to create un-skippable full screen alerts in windows?
I want to create a notification or an alert for the user to restart the PC if it hasn't been done so for 5 days.I used windows toast to do this but found out that toasts can be dismissed and there is no way to perform an action upon dismissal, this is not good as the user can just dismiss the toast without restart the pc for n number of days. I need to implement something similar to the "Low/Ciritical battery" or the "Low Disk Space" Notification (see pictures attached).

I have tried some searching on how to implement this alert but almost all the sources use toast notifications to display the alert. Any help would be appreciated. Thanks.


问:
how to constantly refresh WIFI rssi on windows?
I am trying to read all the WIFI connections around, refreshing constantly
sadly, while I'm connected to a network, all other networks stop refreshing

Im using node.js, and my code for reading is:

```<code>var netsh = spawn('netsh', ['wlan', 'show', 'networks', 'mode=bssid']);

netsh.stdout.on('data', function (data) {
    res += data;
});
</code>```

i do not have a code for refreshing (I tried to force refresh the network card, and it works, but its not a realistic option for me)

at first my readings are:

```<code>[{ssid:'name1', bssid: **:**:**:1e:f5:88, rssi: 82  },
{ssid: 'name2',bssid: **:**:**:**:f2:ab, rssi: 11 },
{ssid: 'name3',bssid: **:**:**:**:f3:26,  rssi: 7  },
{ssid: 'name4', bssid: **:**:**:**:b1:f8, rssi: 6 },
{ssid: 'name5', bssid: **:**:**:**:0c:39, rssi: 9 }]

[{ssid:'name1', bssid: **:**:**:1e:f5:88, rssi: 81  },
{ssid: 'name2',bssid: **:**:**:**:f2:ab, rssi: 13 },
{ssid: 'name3',bssid: **:**:**:**:f3:26,  rssi: 7  },
{ssid: 'name4', bssid: **:**:**:**:b1:f8, rssi: 6 },
{ssid: 'name5', bssid: **:**:**:**:0c:39, rssi: 6 }]
</code>```

then, after a while, they all read only 'name1':

```<code>[{ssid: 'name1', bssid: **:**:**:1e:f5:88, rssi: 82 } ]
[{ssid: 'name1', bssid: **:**:**:1e:f5:88, rssi: 81 } ]
[{ssid: 'name1', bssid: **:**:**:1e:f5:88, rssi: 82 } ]
[{ssid: 'name1', bssid: **:**:**:1e:f5:88, rssi: 82 } ]
[{ssid: 'name1', bssid: **:**:**:1e:f5:88, rssi: 81 } ]
</code>```

i would like to keep refreshing the rssi on all the networks, like in the first example

thank you.

Body:
I am trying to read all the WIFI connections around, refreshing constantly
sadly, while I'm connected to a network, all other networks stop refreshing

Im using node.js, and my code for reading is:

var netsh = spawn('netsh', ['wlan', 'show', 'networks', 'mode=bssid']);

netsh.stdout.on('data', function (data) {
    res += data;
});

i do not have a code for refreshing (I tried to force refresh the network card, and it works, but its not a realistic option for me)

at first my readings are:

[{ssid:'name1', bssid: **:**:**:1e:f5:88, rssi: 82  },
{ssid: 'name2',bssid: **:**:**:**:f2:ab, rssi: 11 },
{ssid: 'name3',bssid: **:**:**:**:f3:26,  rssi: 7  },
{ssid: 'name4', bssid: **:**:**:**:b1:f8, rssi: 6 },
{ssid: 'name5', bssid: **:**:**:**:0c:39, rssi: 9 }]

[{ssid:'name1', bssid: **:**:**:1e:f5:88, rssi: 81  },
{ssid: 'name2',bssid: **:**:**:**:f2:ab, rssi: 13 },
{ssid: 'name3',bssid: **:**:**:**:f3:26,  rssi: 7  },
{ssid: 'name4', bssid: **:**:**:**:b1:f8, rssi: 6 },
{ssid: 'name5', bssid: **:**:**:**:0c:39, rssi: 6 }]

then, after a while, they all read only 'name1':

[{ssid: 'name1', bssid: **:**:**:1e:f5:88, rssi: 82 } ]
[{ssid: 'name1', bssid: **:**:**:1e:f5:88, rssi: 81 } ]
[{ssid: 'name1', bssid: **:**:**:1e:f5:88, rssi: 82 } ]
[{ssid: 'name1', bssid: **:**:**:1e:f5:88, rssi: 82 } ]
[{ssid: 'name1', bssid: **:**:**:1e:f5:88, rssi: 81 } ]

i would like to keep refreshing the rssi on all the networks, like in the first example

thank you.


问:
Host a .NET Core web application in a folder of a WordPress website on a Windows server running IIS
I have a SaaS application where the front-end marketing website is developed using a WordPress website while the main SaaS product is developed in .NET Core technology. In our case, both of these websites had different domain names. (www.example.com and app.example.com).

Now recently we have got a couple of people who are interested in white-labeling our product. So for all of them, we want to host a WordPress website and in it, there is an "app" folder that runs the .net Saas Application. I want to know if it is possible. If yes, how?

I also tried the below steps but couldn't achieve it - don't know why. Any idea on this?

Install the IIS URL Rewrite module on your server if it is not already installed.

In IIS Manager, navigate to the WordPress website and select the
"app" folder. Click on the "URL Rewrite" icon in the IIS Manager to
open the URL Rewrite module. Click on "Add Rules" in the right-hand
pane, and then select "Blank rule" from the options.

In the "Name" field, enter a name for the rule (e.g., "app-rule").

In the "Pattern" field, enter the pattern for the URL that should be
redirected to your .NET application (e.g., "app/*").

In the "Conditions" section, add a condition that checks if the
requested URL is a file or a directory. This will ensure that the
rule only applies to requests for the "app" folder and not for other
parts of the WordPress website.

In the "Action" section, select "Rewrite" as the action type and
enter the URL of the .NET application in the "Rewrite URL" field.
Click "Apply" to save the rule.


问:
sending Video file mp4 via clickatel whatsapp api
I have a video file on a server that I would like to send via clickatell's whatsapp API, but I keep getting this error:

```<code>[statusCode] => 23
[status] => DELIVERY_FAILURE
</code>```
```<code>$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://platform.clickatell.com/v1/message');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"messages\": [{ \"channel\": \"whatsapp\", \"to\": \"27607876384\", \"media\": {
        \"fileId\": \"dcd97e173a484ed4bf3f22953103509a.mp4\",
        \"caption\": \"First Image File\"}}]}");

$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Accept: application/json';
$headers[] = 'Authorization: 9-QxGt35SM-CMm-060G5tA==';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    echo $result;
}
curl_close($ch);
</code>```

It would be great to do this inline, if possible.

Body:
I have a video file on a server that I would like to send via clickatell's whatsapp API, but I keep getting this error:

[statusCode] => 23
[status] => DELIVERY_FAILURE

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://platform.clickatell.com/v1/message');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"messages\": [{ \"channel\": \"whatsapp\", \"to\": \"27607876384\", \"media\": {
        \"fileId\": \"dcd97e173a484ed4bf3f22953103509a.mp4\",
        \"caption\": \"First Image File\"}}]}");

$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Accept: application/json';
$headers[] = 'Authorization: 9-QxGt35SM-CMm-060G5tA==';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    echo $result;
}
curl_close($ch);

It would be great to do this inline, if possible.


问:
How to get percentage of increment/decrement of two formula field values in saved search NetSuite
I am working on to populate the payroll expenses of last month and current month using saved search according to departments.
I got the last month payroll expenses and current month payroll expenses using formula field.
Now I am trying to get result in percentage of two amount Values which I have got through formula fields.
I am not being able to get the even subtraction of both of the formula fields.
So that I can divide and get the increment /decrement percentage.

Tried many ways using formulas (case, subtraction of two formulas), using summary type and its functions but not got required result.

Please suggest something for saved search result.

Thanks.


问:
github searching whith multiple organization
I'm using GitHub searching features with great appreciation
https://docs.github.com/en/search-github/searching-on-github/searching-for-repositories

As explained in the above document, I usually search for something like this.
"involves:Kim org:orgA is:open"

But I also want to search like this.
"involves:Kim org:orgA or orgB is:open" which means searching for all open issues throughout orgA and orgB which involves user Kim.

I want to manage my all issues which spreaded into multiple organizations.

But it wasn't working in Git Hub.
Is it impossible for searching like that?


问:
Easy Permissions Android - onPermissionGranted and Denied executes automaitcally
These 2 callback methods

onPermissionsGranted

onPermissionsDenied

Automatically exeucted in the MainActivity without any permission dialog apperaing or any such of activity.

These 2 are executed when the user allows or denies the permission. But in my case when the user comes to the main activity these 2 methods automatically executed. Also providing me the issue showing the permission dialog, to allow the permissions through the settings, however the all permissions are allowed. This type of behaviour is coming in the Android 10.


问:
Why does iOS obtain app thread startup time sometimes exceeds the actual startup time
I get app thread start time via sysctl. Then, when the app starts in the background (such as receiving an incoming call), I calculate the preMain duration of the app. Most of the time, the data is normal (hundreds of milliseconds). But occasionally a very large duration (such as tens of seconds) appears. It feels like restarting the mobile phone test has a higher probability.</p>
```<code>    // Code in main.swift
    let appStartLaunchTime: CFAbsoluteTime = CFAbsoluteTimeGetCurrent()

    // Calculate preMain time
    var preMain = appStartLaunchTime - appLaunchTime! + kCFAbsoluteTimeIntervalSince1970

    public var appLaunchTime: Double? = {
        var processInfo = kinfo_proc()
        var size = MemoryLayout<kinfo_proc>.stride
        var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]
        guard sysctl(&mib, u_int(mib.count), &processInfo, &size, nil, 0) == 0 else {
            return nil
        }
        let startTime = processInfo.kp_proc.p_starttime
        let time = (Int64(startTime.tv_sec) * 1000) + Int64(startTime.tv_usec / 1000)
        return Double(time) / 1000.0
    }()
</code>```

Body:
I get app thread start time via sysctl. Then, when the app starts in the background (such as receiving an incoming call), I calculate the preMain duration of the app. Most of the time, the data is normal (hundreds of milliseconds). But occasionally a very large duration (such as tens of seconds) appears. It feels like restarting the mobile phone test has a higher probability.

    // Code in main.swift
    let appStartLaunchTime: CFAbsoluteTime = CFAbsoluteTimeGetCurrent()

    // Calculate preMain time
    var preMain = appStartLaunchTime - appLaunchTime! + kCFAbsoluteTimeIntervalSince1970

    public var appLaunchTime: Double? = {
        var processInfo = kinfo_proc()
        var size = MemoryLayout<kinfo_proc>.stride
        var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]
        guard sysctl(&mib, u_int(mib.count), &processInfo, &size, nil, 0) == 0 else {
            return nil
        }
        let startTime = processInfo.kp_proc.p_starttime
        let time = (Int64(startTime.tv_sec) * 1000) + Int64(startTime.tv_usec / 1000)
        return Double(time) / 1000.0
    }()


问:
Not able to set data in guacamole clipboard
I am using Apache Guacamole library in our project for rendering Windows VM in web browser.
For Clipboard integration I need to transfer clipboard content from Local System to remote VM (guacamole Clipboard) and vice versa.
I am able to get the clipboard content of remote VM using the guacamole onclipboard event. But I am unable to send Local System clipboard content to remote VM (Guacamole clipboard).I am using createClipboardStream() API for setting data to guacamole clipboard but I am not getting any data in remote VM clipboard.

Please find the code snippet as below -

Guacamole API reference -
https://guacamole.apache.org/doc/0.9.2/guacamole-common-js/symbols/Guacamole.Client.html#createClipboardStream

```<code>// sending Local System Clipboard content to Remote VM (Guacamole Clipboard)
function setGuacamoleClipboard(data) {
    var stream = guac.createClipboardStream("text/plain");
    var writer = new Guacamole.StringWriter(stream);
    for (var i=0; i<data.length; i += 4096){
        writer.sendText(data.substring(i, i+4096));
    }
    writer.sendEnd();
}
</code>```

I have also tried below Java code for setting guacamole clipboard using writeInstruction().This approach also did not work for me

```<code>tunnel.getSocket().getWriter().writeInstruction(new GuacamoleInstruction("clipboard","text/plain","Welcome Guacamole clipboard"));
</code>```

Am I missing anything ?

Body:
I am using Apache Guacamole library in our project for rendering Windows VM in web browser.
For Clipboard integration I need to transfer clipboard content from Local System to remote VM (guacamole Clipboard) and vice versa.
I am able to get the clipboard content of remote VM using the guacamole onclipboard event. But I am unable to send Local System clipboard content to remote VM (Guacamole clipboard).I am using createClipboardStream() API for setting data to guacamole clipboard but I am not getting any data in remote VM clipboard.

Please find the code snippet as below -

Guacamole API reference -
https://guacamole.apache.org/doc/0.9.2/guacamole-common-js/symbols/Guacamole.Client.html#createClipboardStream

// sending Local System Clipboard content to Remote VM (Guacamole Clipboard)
function setGuacamoleClipboard(data) {
    var stream = guac.createClipboardStream("text/plain");
    var writer = new Guacamole.StringWriter(stream);
    for (var i=0; i<data.length; i += 4096){
        writer.sendText(data.substring(i, i+4096));
    }
    writer.sendEnd();
}

I have also tried below Java code for setting guacamole clipboard using writeInstruction().This approach also did not work for me

tunnel.getSocket().getWriter().writeInstruction(new GuacamoleInstruction("clipboard","text/plain","Welcome Guacamole clipboard"));

Am I missing anything ?


问:
Why setUserID not working in Yandex metrica
I use yandex metrica in SPA application with VueJs.
at first, I run setUserID after all components load, it didn't work.

so I call it after yandex script init:

```<code>(function(m, e, t, r, i, k, a) {
  m[i] = m[i] || function() {
    (m[i].a = m[i].a || []).push(arguments);
  };
  m[i].l = 1 * new Date();
  k = e.createElement(t), a = e.getElementsByTagName(t)[0], k.async = 1, k.src = r, a.parentNode.insertBefore(k, a);
})
(window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym");

ym(11111111, "init", {
  clickmap: true,
  trackLinks: true,
  accurateTrackBounce: true,
  webvisor: true
});
const _u = localStorage.getItem('userID');
if (_u)
    ym(11111111, "setUserID", _u);
</code>```

because this method works when the app wasn't SPA.
but now userID is not available in yandex dashboard anymore.

Has any one similar exprience?

Body:
I use yandex metrica in SPA application with VueJs.
at first, I run setUserID after all components load, it didn't work.

so I call it after yandex script init:

(function(m, e, t, r, i, k, a) {
  m[i] = m[i] || function() {
    (m[i].a = m[i].a || []).push(arguments);
  };
  m[i].l = 1 * new Date();
  k = e.createElement(t), a = e.getElementsByTagName(t)[0], k.async = 1, k.src = r, a.parentNode.insertBefore(k, a);
})
(window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym");

ym(11111111, "init", {
  clickmap: true,
  trackLinks: true,
  accurateTrackBounce: true,
  webvisor: true
});
const _u = localStorage.getItem('userID');
if (_u)
    ym(11111111, "setUserID", _u);

because this method works when the app wasn't SPA.
but now userID is not available in yandex dashboard anymore.

Has any one similar exprience?


问:
Hibernate generates unwanted aliases when using @Formula annotation
When I give to the @Formula annotation this piece of code :

```<code>@Formula("(SELECT SUM(commission.montant) FROM commission, affaire)")
private Double totalCommissionsMCourant;
</code>```

Hibernates executes this SQL request :

```<code>[...,(SELECT SUM(commission.montant) FROM commission, a1_0.affaire) ...]
</code>```

As you can see, the "FROM commission, affaire" turns into "FROM commission, a1_0.affaire", which makes the SQL request invalid.

Disclaimer : I know that having this type of calculated field here does not make sense but this is a simplified version of what I'd want to have.

Do you have any idea on how to prevent this problem from happening ?

Here is part of the Entity's code :

```<code>@Entity(name = "Apporteur")
@Table(name = "apporteur")
public class ApporteurEntity {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Formula("(SELECT SUM(commission.montant) FROM commission, affaire)")
  private Double totalCommissionsMCourant;

}
</code>```

Hibernate version : 6.0.0

Body:
When I give to the @Formula annotation this piece of code :

@Formula("(SELECT SUM(commission.montant) FROM commission, affaire)")
private Double totalCommissionsMCourant;

Hibernates executes this SQL request :

[...,(SELECT SUM(commission.montant) FROM commission, a1_0.affaire) ...]

As you can see, the "FROM commission, affaire" turns into "FROM commission, a1_0.affaire", which makes the SQL request invalid.

Disclaimer : I know that having this type of calculated field here does not make sense but this is a simplified version of what I'd want to have.

Do you have any idea on how to prevent this problem from happening ?

Here is part of the Entity's code :

@Entity(name = "Apporteur")
@Table(name = "apporteur")
public class ApporteurEntity {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Formula("(SELECT SUM(commission.montant) FROM commission, affaire)")
  private Double totalCommissionsMCourant;

}

Hibernate version : 6.0.0


问:
Flutter Expandable leaves empty area after being collapsed
I have a long text in a CustomScrollView that I have wrapped in an Expandable widget.

When the text is collapsed I show the first 7 rows, and when it's expanded I show the entire text which can be long.

After I expand the text and then collapse it again I get a long area of nothing under the collapsed view.

Here is a screenshot of the expanded and collapsed text:

as you can see the Feature text widget is no longer directly beneath the text widget.

Here is the widget:

```<code>import 'package:expandable/expandable.dart';
import 'package:flutter/material.dart';
import 'package:My_ui/My_ui.dart';
import 'package:listing_detail_page/generated/l10n.dart';
import 'package:listing_detail_page/network/models/listing_detail.dart';

import '../../../generic_components/bottom_fade.dart';

class DescriptionView extends StatelessWidget {
  const DescriptionView({
    Key? key,
    required this.details,
    required this.expandableController,
  }) : super(key: key);

  final ListingDetails details;
  final ExpandableController expandableController;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(
        left: Spacing.x2,
        right: Spacing.x2,
        top: Spacing.x3,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Text(
            S.of(context).descriptionView_title_description,
            style: Theme.of(context).textTheme.headlineMedium?.copyWith(
                  fontWeight: FontWeight.w600,
                  color: MyColors.grey25,
                ),
          ),
          const SizedBox(height: Spacing.x1),
          ExpandableNotifier(
            controller: expandableController,
            child: ScrollOnExpand(
              child: Expandable(
                collapsed: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    BottomFade(
                      height: 80,
                      child: Text(
                        details.description ?? '',
                        maxLines: 7,
                        overflow: TextOverflow.fade,
                        style: Theme.of(context)
                            .textTheme
                            .bodyLarge
                            ?.copyWith(height: 1.5),
                      ),
                    ),
                    const SizedBox(height: Spacing.x1),
                    ExpandableButton(
                      child: Row(
                        children: [
                          const Icon(
                            Icons.add,
                            color: MyColors.blue,
                            size: 22,
                          ),
                          const SizedBox(width: Spacing.x1),
                          Text(
                            S
                                .of(context)
                                .descriptionView_button_readTheFullDescription,
                            textAlign: TextAlign.start,
                            style:
                                Theme.of(context).textTheme.bodyLarge?.copyWith(
                                      color: MyColors.blue,
                                      height: 1.5,
                                    ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                expanded: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Text(
                      details.description ?? '',
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge
                          ?.copyWith(height: 1.5),
                    ),
                    const SizedBox(height: Spacing.x1),
                    ExpandableButton(
                      child: Row(
                        children: [
                          const Icon(
                            Icons.remove,
                            color: MyColors.blue,
                            size: 22,
                          ),
                          const SizedBox(width: Spacing.x1),
                          Text(
                            S.of(context).descriptionView_button_showLess,
                            textAlign: TextAlign.start,
                            style:
                                Theme.of(context).textTheme.bodyLarge?.copyWith(
                                      color: MyColors.blue,
                                      height: 1.5,
                                    ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

And here is how it is being used:

```<code>import 'package:expandable/expandable.dart';
import 'package:flutter/material.dart';
import 'package:My_ui/My_ui.dart';
import 'package:listing_detail_page/network/models/feature_section.dart';
import 'package:listing_detail_page/network/models/listing_detail.dart';
import 'package:listing_detail_page/ui/generic_components/My_sliver_app_bar.dart';
import 'package:listing_detail_page/ui/screens/listing_detail/components/address_section.dart';
import 'package:listing_detail_page/ui/screens/listing_detail/components/description_view.dart';
import 'package:listing_detail_page/ui/screens/listing_detail/components/price_tile.dart';

class ListingDetailBody extends StatefulWidget {
  const ListingDetailBody({
    Key? key,
    required this.details,
    required this.listingId,
    required this.sections,
  }) : super(key: key);

  final ListingDetails details;
  final String listingId;
  final List<FeatureSection> sections;

  @override
  State<ListingDetailBody> createState() => _ListingDetailBodyState();
}

class _ListingDetailBodyState extends State<ListingDetailBody> {
  final ExpandableController _descriptionExpandableController =
      ExpandableController();

  @override
  void dispose() {
    _descriptionExpandableController.dispose();
    super.dispose();
  }

  Widget? _buildDescriptionView(BuildContext context) {
    final description = widget.details.description;
    if (description != null && description.isNotEmpty) {
      return DescriptionView(
        details: widget.details,
        expandableController: _descriptionExpandableController,
      );
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      physics: const BouncingScrollPhysics(),
      slivers: [
        MySliverAppBar(
          details: widget.details,
          listingId: widget.listingId,
        ),
        SliverList(
          delegate: SliverChildListDelegate(
            [
              ...
              const SizedBox(height: Spacing.x3),
              AddressSection(details: widget.details),
              PriceTile(details: widget.details),
              _buildDescriptionView(context),
             ...
            ].whereType<Widget>().toList(),
          ),
        ),
      ],
    );
  }
}

</code>```

Body:
I have a long text in a CustomScrollView that I have wrapped in an Expandable widget.

When the text is collapsed I show the first 7 rows, and when it's expanded I show the entire text which can be long.

After I expand the text and then collapse it again I get a long area of nothing under the collapsed view.

Here is a screenshot of the expanded and collapsed text:

as you can see the Feature text widget is no longer directly beneath the text widget.

Here is the widget:

import 'package:expandable/expandable.dart';
import 'package:flutter/material.dart';
import 'package:My_ui/My_ui.dart';
import 'package:listing_detail_page/generated/l10n.dart';
import 'package:listing_detail_page/network/models/listing_detail.dart';

import '../../../generic_components/bottom_fade.dart';

class DescriptionView extends StatelessWidget {
  const DescriptionView({
    Key? key,
    required this.details,
    required this.expandableController,
  }) : super(key: key);

  final ListingDetails details;
  final ExpandableController expandableController;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(
        left: Spacing.x2,
        right: Spacing.x2,
        top: Spacing.x3,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Text(
            S.of(context).descriptionView_title_description,
            style: Theme.of(context).textTheme.headlineMedium?.copyWith(
                  fontWeight: FontWeight.w600,
                  color: MyColors.grey25,
                ),
          ),
          const SizedBox(height: Spacing.x1),
          ExpandableNotifier(
            controller: expandableController,
            child: ScrollOnExpand(
              child: Expandable(
                collapsed: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    BottomFade(
                      height: 80,
                      child: Text(
                        details.description ?? '',
                        maxLines: 7,
                        overflow: TextOverflow.fade,
                        style: Theme.of(context)
                            .textTheme
                            .bodyLarge
                            ?.copyWith(height: 1.5),
                      ),
                    ),
                    const SizedBox(height: Spacing.x1),
                    ExpandableButton(
                      child: Row(
                        children: [
                          const Icon(
                            Icons.add,
                            color: MyColors.blue,
                            size: 22,
                          ),
                          const SizedBox(width: Spacing.x1),
                          Text(
                            S
                                .of(context)
                                .descriptionView_button_readTheFullDescription,
                            textAlign: TextAlign.start,
                            style:
                                Theme.of(context).textTheme.bodyLarge?.copyWith(
                                      color: MyColors.blue,
                                      height: 1.5,
                                    ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                expanded: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Text(
                      details.description ?? '',
                      style: Theme.of(context)
                          .textTheme
                          .bodyLarge
                          ?.copyWith(height: 1.5),
                    ),
                    const SizedBox(height: Spacing.x1),
                    ExpandableButton(
                      child: Row(
                        children: [
                          const Icon(
                            Icons.remove,
                            color: MyColors.blue,
                            size: 22,
                          ),
                          const SizedBox(width: Spacing.x1),
                          Text(
                            S.of(context).descriptionView_button_showLess,
                            textAlign: TextAlign.start,
                            style:
                                Theme.of(context).textTheme.bodyLarge?.copyWith(
                                      color: MyColors.blue,
                                      height: 1.5,
                                    ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

And here is how it is being used:

import 'package:expandable/expandable.dart';
import 'package:flutter/material.dart';
import 'package:My_ui/My_ui.dart';
import 'package:listing_detail_page/network/models/feature_section.dart';
import 'package:listing_detail_page/network/models/listing_detail.dart';
import 'package:listing_detail_page/ui/generic_components/My_sliver_app_bar.dart';
import 'package:listing_detail_page/ui/screens/listing_detail/components/address_section.dart';
import 'package:listing_detail_page/ui/screens/listing_detail/components/description_view.dart';
import 'package:listing_detail_page/ui/screens/listing_detail/components/price_tile.dart';

class ListingDetailBody extends StatefulWidget {
  const ListingDetailBody({
    Key? key,
    required this.details,
    required this.listingId,
    required this.sections,
  }) : super(key: key);

  final ListingDetails details;
  final String listingId;
  final List<FeatureSection> sections;

  @override
  State<ListingDetailBody> createState() => _ListingDetailBodyState();
}

class _ListingDetailBodyState extends State<ListingDetailBody> {
  final ExpandableController _descriptionExpandableController =
      ExpandableController();

  @override
  void dispose() {
    _descriptionExpandableController.dispose();
    super.dispose();
  }

  Widget? _buildDescriptionView(BuildContext context) {
    final description = widget.details.description;
    if (description != null && description.isNotEmpty) {
      return DescriptionView(
        details: widget.details,
        expandableController: _descriptionExpandableController,
      );
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      physics: const BouncingScrollPhysics(),
      slivers: [
        MySliverAppBar(
          details: widget.details,
          listingId: widget.listingId,
        ),
        SliverList(
          delegate: SliverChildListDelegate(
            [
              ...
              const SizedBox(height: Spacing.x3),
              AddressSection(details: widget.details),
              PriceTile(details: widget.details),
              _buildDescriptionView(context),
             ...
            ].whereType<Widget>().toList(),
          ),
        ),
      ],
    );
  }
}


问:
GDB "cannot find bounds of current function" when stepping into trampoline function at a special address
When I try to debug XV6 (an OS), I find GDB can't reach the assembly code.

I want to find out how to trace the executing path in the assembly code.

The file kernel/trap.c refers to the assembly code kernel/trampoline.S by the extern keyword, so that the identifiers trampoline, uservec and the userrer are actually the labels in the assembly code kernel/trampoline.S:

extern char trampoline[], uservec[], userret[];
```
```    #
        # code to switch between user and kernel space.
        #
        # this code is mapped at the same virtual address
        # (TRAMPOLINE) in user and kernel space so that
        # it continues to work when it switches page tables.
    #
    # kernel.ld causes this to be aligned
        # to a page boundary.
        #
    .section trampsec
.globl trampoline
trampoline:
.align 4
.globl uservec
uservec:
    #
        # trap.c sets stvec to point here, so
        # traps from user space start here,
        # in supervisor mode, but with a
        # user page table.
        #
        # sscratch points to where the process's p->trapframe is
        # mapped into user space, at TRAPFRAME.
        #

    # swap a0 and sscratch
        # so that a0 is TRAPFRAME
        csrrw a0, sscratch, a0

        # save the user registers in TRAPFRAME
        sd ra, 40(a0)
        sd sp, 48(a0)
        sd gp, 56(a0)
        sd tp, 64(a0)
        sd t0, 72(a0)
        sd t1, 80(a0)
        sd t2, 88(a0)
        sd s0, 96(a0)
        sd s1, 104(a0)
        sd a1, 120(a0)
        sd a2, 128(a0)
        sd a3, 136(a0)
        sd a4, 144(a0)
        sd a5, 152(a0)
        sd a6, 160(a0)
        sd a7, 168(a0)
        sd s2, 176(a0)
        sd s3, 184(a0)
        sd s4, 192(a0)
        sd s5, 200(a0)
        sd s6, 208(a0)
        sd s7, 216(a0)
        sd s8, 224(a0)
        sd s9, 232(a0)
        sd s10, 240(a0)
        sd s11, 248(a0)
        sd t3, 256(a0)
        sd t4, 264(a0)
        sd t5, 272(a0)
        sd t6, 280(a0)

    # save the user a0 in p->trapframe->a0
        csrr t0, sscratch
        sd t0, 112(a0)

        # restore kernel stack pointer from p->trapframe->kernel_sp
        ld sp, 8(a0)

        # make tp hold the current hartid, from p->trapframe->kernel_hartid
        ld tp, 32(a0)

        # load the address of usertrap(), p->trapframe->kernel_trap
        ld t0, 16(a0)

        # restore kernel page table from p->trapframe->kernel_satp
        ld t1, 0(a0)
        csrw satp, t1
        sfence.vma zero, zero

        # a0 is no longer valid, since the kernel page
        # table does not specially map p->tf.

        # jump to usertrap(), which does not return
        jr t0

.globl userret
userret:
        # userret(TRAPFRAME, pagetable)
        # switch from kernel to user.
        # usertrapret() calls here.
        # a0: TRAPFRAME, in user page table.
        # a1: user page table, for satp.

        # switch to the user page table.
        csrw satp, a1
        sfence.vma zero, zero

        # put the saved user a0 in sscratch, so we
        # can swap it with our a0 (TRAPFRAME) in the last step.
        ld t0, 112(a0)
        csrw sscratch, t0

        # restore all but a0 from TRAPFRAME
        ld ra, 40(a0)
        ld sp, 48(a0)
        ld gp, 56(a0)
        ld tp, 64(a0)
        ld t0, 72(a0)
        ld t1, 80(a0)
        ld t2, 88(a0)
        ld s0, 96(a0)
        ld s1, 104(a0)
        ld a1, 120(a0)
        ld a2, 128(a0)
        ld a3, 136(a0)
        ld a4, 144(a0)
        ld a5, 152(a0)
        ld a6, 160(a0)
        ld a7, 168(a0)
        ld s2, 176(a0)
        ld s3, 184(a0)
        ld s4, 192(a0)
        ld s5, 200(a0)
        ld s6, 208(a0)
        ld s7, 216(a0)
        ld s8, 224(a0)
        ld s9, 232(a0)
        ld s10, 240(a0)
        ld s11, 248(a0)
        ld t3, 256(a0)
        ld t4, 264(a0)
        ld t5, 272(a0)
        ld t6, 280(a0)

    # restore user a0, and save TRAPFRAME in sscratch
        csrrw a0, sscratch, a0

        # return to user mode and user pc.
        # usertrapret() set up sstatus and sepc.
        sret

```
<p>And the function <code>usertrapret()</code> use the function pointer to skip to the assembly code in the <code>kernel/trampoline.S</code>. The skipping statement is in the end of the function <code>usertrapret()</code>.</p>
<pre class="lang-c prettyprint-override"><code>//
// return to user space
//
void usertrapret(void) {
  struct proc *p = myproc();

  // we're about to switch the destination of traps from
  // kerneltrap() to usertrap(), so turn off interrupts until
  // we're back in user space, where usertrap() is correct.
  intr_off();

  // send syscalls, interrupts, and exceptions to trampoline.S
  w_stvec(TRAMPOLINE + (uservec - trampoline));

  // set up trapframe values that uservec will need when
  // the process next re-enters the kernel.
  p->trapframe->kernel_satp = r_satp();         // kernel page table
  p->trapframe->kernel_sp = p->kstack + PGSIZE; // process's kernel stack
  p->trapframe->kernel_trap = (uint64)usertrap;
  p->trapframe->kernel_hartid = r_tp(); // hartid for cpuid()

  // set up the registers that trampoline.S's sret will use
  // to get to user space.

  // set S Previous Privilege mode to User.
  unsigned long x = r_sstatus();
  x &= ~SSTATUS_SPP; // clear SPP to 0 for user mode
  x |= SSTATUS_SPIE; // enable interrupts in user mode
  w_sstatus(x);

  // set S Exception Program Counter to the saved user pc.
  w_sepc(p->trapframe->epc);

  // tell trampoline.S the user page table to switch to.
  uint64 satp = MAKE_SATP(p->pagetable);

  // jump to trampoline.S at the top of memory, which
  // switches to the user page table, restores user registers,
  // and switches to user mode with sret.
  uint64 fn = TRAMPOLINE + (userret - trampoline);
  ((void (*)(uint64, uint64))fn)(TRAPFRAME, satp);
}
</code>```

When I use GDB command stepi to trace the executing path, and when I encouter the statement, the GDB can't go on tracing the assembly, and the GDB will report "Cannot find bounds of current function", so I can't keep on tracing the detailed execution of the assembly code.

((void (*)(uint64, uint64))fn)(TRAPFRAME, satp);
```

Body:
When I try to debug XV6 (an OS), I find GDB can't reach the assembly code.

I want to find out how to trace the executing path in the assembly code.

The file kernel/trap.c refers to the assembly code kernel/trampoline.S by the extern keyword, so that the identifiers trampoline, uservec and the userrer are actually the labels in the assembly code kernel/trampoline.S:

extern char trampoline[], uservec[], userret[];

    #
        # code to switch between user and kernel space.
        #
        # this code is mapped at the same virtual address
        # (TRAMPOLINE) in user and kernel space so that
        # it continues to work when it switches page tables.
    #
    # kernel.ld causes this to be aligned
        # to a page boundary.
        #
    .section trampsec
.globl trampoline
trampoline:
.align 4
.globl uservec
uservec:
    #
        # trap.c sets stvec to point here, so
        # traps from user space start here,
        # in supervisor mode, but with a
        # user page table.
        #
        # sscratch points to where the process's p->trapframe is
        # mapped into user space, at TRAPFRAME.
        #

    # swap a0 and sscratch
        # so that a0 is TRAPFRAME
        csrrw a0, sscratch, a0

        # save the user registers in TRAPFRAME
        sd ra, 40(a0)
        sd sp, 48(a0)
        sd gp, 56(a0)
        sd tp, 64(a0)
        sd t0, 72(a0)
        sd t1, 80(a0)
        sd t2, 88(a0)
        sd s0, 96(a0)
        sd s1, 104(a0)
        sd a1, 120(a0)
        sd a2, 128(a0)
        sd a3, 136(a0)
        sd a4, 144(a0)
        sd a5, 152(a0)
        sd a6, 160(a0)
        sd a7, 168(a0)
        sd s2, 176(a0)
        sd s3, 184(a0)
        sd s4, 192(a0)
        sd s5, 200(a0)
        sd s6, 208(a0)
        sd s7, 216(a0)
        sd s8, 224(a0)
        sd s9, 232(a0)
        sd s10, 240(a0)
        sd s11, 248(a0)
        sd t3, 256(a0)
        sd t4, 264(a0)
        sd t5, 272(a0)
        sd t6, 280(a0)

    # save the user a0 in p->trapframe->a0
        csrr t0, sscratch
        sd t0, 112(a0)

        # restore kernel stack pointer from p->trapframe->kernel_sp
        ld sp, 8(a0)

        # make tp hold the current hartid, from p->trapframe->kernel_hartid
        ld tp, 32(a0)

        # load the address of usertrap(), p->trapframe->kernel_trap
        ld t0, 16(a0)

        # restore kernel page table from p->trapframe->kernel_satp
        ld t1, 0(a0)
        csrw satp, t1
        sfence.vma zero, zero

        # a0 is no longer valid, since the kernel page
        # table does not specially map p->tf.

        # jump to usertrap(), which does not return
        jr t0

.globl userret
userret:
        # userret(TRAPFRAME, pagetable)
        # switch from kernel to user.
        # usertrapret() calls here.
        # a0: TRAPFRAME, in user page table.
        # a1: user page table, for satp.

        # switch to the user page table.
        csrw satp, a1
        sfence.vma zero, zero

        # put the saved user a0 in sscratch, so we
        # can swap it with our a0 (TRAPFRAME) in the last step.
        ld t0, 112(a0)
        csrw sscratch, t0

        # restore all but a0 from TRAPFRAME
        ld ra, 40(a0)
        ld sp, 48(a0)
        ld gp, 56(a0)
        ld tp, 64(a0)
        ld t0, 72(a0)
        ld t1, 80(a0)
        ld t2, 88(a0)
        ld s0, 96(a0)
        ld s1, 104(a0)
        ld a1, 120(a0)
        ld a2, 128(a0)
        ld a3, 136(a0)
        ld a4, 144(a0)
        ld a5, 152(a0)
        ld a6, 160(a0)
        ld a7, 168(a0)
        ld s2, 176(a0)
        ld s3, 184(a0)
        ld s4, 192(a0)
        ld s5, 200(a0)
        ld s6, 208(a0)
        ld s7, 216(a0)
        ld s8, 224(a0)
        ld s9, 232(a0)
        ld s10, 240(a0)
        ld s11, 248(a0)
        ld t3, 256(a0)
        ld t4, 264(a0)
        ld t5, 272(a0)
        ld t6, 280(a0)

    # restore user a0, and save TRAPFRAME in sscratch
        csrrw a0, sscratch, a0

        # return to user mode and user pc.
        # usertrapret() set up sstatus and sepc.
        sret

And the function usertrapret() use the function pointer to skip to the assembly code in the kernel/trampoline.S. The skipping statement is in the end of the function usertrapret().

//
// return to user space
//
void usertrapret(void) {
  struct proc *p = myproc();

  // we're about to switch the destination of traps from
  // kerneltrap() to usertrap(), so turn off interrupts until
  // we're back in user space, where usertrap() is correct.
  intr_off();

  // send syscalls, interrupts, and exceptions to trampoline.S
  w_stvec(TRAMPOLINE + (uservec - trampoline));

  // set up trapframe values that uservec will need when
  // the process next re-enters the kernel.
  p->trapframe->kernel_satp = r_satp();         // kernel page table
  p->trapframe->kernel_sp = p->kstack + PGSIZE; // process's kernel stack
  p->trapframe->kernel_trap = (uint64)usertrap;
  p->trapframe->kernel_hartid = r_tp(); // hartid for cpuid()

  // set up the registers that trampoline.S's sret will use
  // to get to user space.

  // set S Previous Privilege mode to User.
  unsigned long x = r_sstatus();
  x &= ~SSTATUS_SPP; // clear SPP to 0 for user mode
  x |= SSTATUS_SPIE; // enable interrupts in user mode
  w_sstatus(x);

  // set S Exception Program Counter to the saved user pc.
  w_sepc(p->trapframe->epc);

  // tell trampoline.S the user page table to switch to.
  uint64 satp = MAKE_SATP(p->pagetable);

  // jump to trampoline.S at the top of memory, which
  // switches to the user page table, restores user registers,
  // and switches to user mode with sret.
  uint64 fn = TRAMPOLINE + (userret - trampoline);
  ((void (*)(uint64, uint64))fn)(TRAPFRAME, satp);
}

When I use GDB command stepi to trace the executing path, and when I encouter the statement, the GDB can't go on tracing the assembly, and the GDB will report "Cannot find bounds of current function", so I can't keep on tracing the detailed execution of the assembly code.

((void (*)(uint64, uint64))fn)(TRAPFRAME, satp);


问:
How to increase Spring Cloud Gateway throughput without 502 errors
I am running a Spring Cloud Gateway(version 3.0.3) Project with reactor netty(version 2.5.7). My system is with 8 core processor and 16 GB RAM. I have a route which calls the HttpBin API. When i launch load testing with Constant throughput of 25 tps, i am getting around 0.75% 502 (Bad Gate way) errors.
What might be the issue.

I tried increasing the Netty's worker Thread count to 200, but no change in the throughput. still getting around 0.75% 502 errors.

Update:- After upgrading Spring Cloud Gateway version to 4.0.0, the 502 error count is reduced. It is now 0.15% 502 errors.


问:
How to use multi filter_complex in ffmpeg (python)
I have over 2k mp3 file and I want to convert them to mono-left.wav and mono-right.wav, convert them I use this code

```<code>os.system('ffmpeg -i "/content/46.mp4" -filter_complex "[0:a]channelsplit=channel_layout=stereo[left][right]" -map "[left]" -ar 44100 left.wav -map "[right]" -ar 44100 right.wav')
</code>```

then I used this code to create mono-left-stereo.wav and mono-right-stereo.wav from mono-left.wav and mono-right.wav

```<code>os.system('ffmpeg -i mono-left.wav -filter_complex "[0:a][0:a]amerge=inputs=2[a]" -map "[a]" mono-left-stereo.wav')
os.system('ffmpeg -i mono-right.wav -filter_complex "[0:a][0:a]amerge=inputs=2[a]" -map "[a]" mono-right-stereo.wav')
</code>```

is there any way to merge this together so I can run this once and make mono-left-stereo.wav and mono-right-stereo.wav from 46.mp4?

Body:
I have over 2k mp3 file and I want to convert them to mono-left.wav and mono-right.wav, convert them I use this code

os.system('ffmpeg -i "/content/46.mp4" -filter_complex "[0:a]channelsplit=channel_layout=stereo[left][right]" -map "[left]" -ar 44100 left.wav -map "[right]" -ar 44100 right.wav')

then I used this code to create mono-left-stereo.wav and mono-right-stereo.wav from mono-left.wav and mono-right.wav

os.system('ffmpeg -i mono-left.wav -filter_complex "[0:a][0:a]amerge=inputs=2[a]" -map "[a]" mono-left-stereo.wav')
os.system('ffmpeg -i mono-right.wav -filter_complex "[0:a][0:a]amerge=inputs=2[a]" -map "[a]" mono-right-stereo.wav')

is there any way to merge this together so I can run this once and make mono-left-stereo.wav and mono-right-stereo.wav from 46.mp4?


问:
class-transformer: throw if source object doesn't fit destination class
I'm trying to handle different types of plainToInstance conversions using class-validator.
I'd like to dynamically transform all responses based on the structure:
if KikGenericResponse matches, then try to transform the "data" property inside.
Otherwise just transform KikGenericResponse.
The problem is that plainToInstance doesn't throw, but even passing a string it returns an empty instance of the class.
Is there a way of preventing this behaviour? Maybe using class-validator before trying the parsing??

Thanks in advance

```<code>export class KikResponseMessage {
  @Expose()
  get subtitle(): string {
    return this._subtitle;
  }

  @Expose()
  get title(): string {
    return this._title;
  }

  @Expose()
  get type(): string {
    return this._type;
  }

  constructor(
    private _title: string,
    private _subtitle?: string,
    private _type: KikResponseMessageTypes = KikResponseMessageTypes.ERROR
  ) {}
}
export class KikGenericResponse<T = any> {
  set messages(newValue: KikResponseMessage[]) {
    this._messages = newValue;
  }

  @Transform(({ value }) => (value.length ? value : void 0))
  get messages(): KikResponseMessage[] {
    return this._messages;
  }

  constructor(
    public data?: T,
    protected _messages: KikResponseMessage[] = []
  ) {}
}

</code>```
```<code> private _foo: any = instanceToPlain(new KikFoo());
  private _message: KikResponseMessage = new KikResponseMessage('Attenzione');
  private _plainResponse: any = {
    data: {
      foo: 1,
    },
    messages: [instanceToPlain(this._message)],
  };

  constructor(){
      this._testClassTransformer();
  }

  private _testClassTransformer(): void {
    console.info('PLAIN', this._plainResponse);
    const parsed = plainToInstance(KikGenericResponse, this._plainResponse);
    console.info('PARSED GENERIC RESP', {
      whole: parsed,
      msgs: parsed.messages,
    });
    const parsedError = plainToInstance(KikGenericResponse, "this._foo", {
      enableImplicitConversion: !0,
      excludeExtraneousValues: !0
    });
    console.info('Foo to KikGenericResponse (expecting error)', parsedError);
  }
</code>```

Body:
I'm trying to handle different types of plainToInstance conversions using class-validator.
I'd like to dynamically transform all responses based on the structure:
if KikGenericResponse matches, then try to transform the "data" property inside.
Otherwise just transform KikGenericResponse.
The problem is that plainToInstance doesn't throw, but even passing a string it returns an empty instance of the class.
Is there a way of preventing this behaviour? Maybe using class-validator before trying the parsing??

Thanks in advance

export class KikResponseMessage {
  @Expose()
  get subtitle(): string {
    return this._subtitle;
  }

  @Expose()
  get title(): string {
    return this._title;
  }

  @Expose()
  get type(): string {
    return this._type;
  }

  constructor(
    private _title: string,
    private _subtitle?: string,
    private _type: KikResponseMessageTypes = KikResponseMessageTypes.ERROR
  ) {}
}
export class KikGenericResponse<T = any> {
  set messages(newValue: KikResponseMessage[]) {
    this._messages = newValue;
  }

  @Transform(({ value }) => (value.length ? value : void 0))
  get messages(): KikResponseMessage[] {
    return this._messages;
  }

  constructor(
    public data?: T,
    protected _messages: KikResponseMessage[] = []
  ) {}
}

 private _foo: any = instanceToPlain(new KikFoo());
  private _message: KikResponseMessage = new KikResponseMessage('Attenzione');
  private _plainResponse: any = {
    data: {
      foo: 1,
    },
    messages: [instanceToPlain(this._message)],
  };

  constructor(){
      this._testClassTransformer();
  }

  private _testClassTransformer(): void {
    console.info('PLAIN', this._plainResponse);
    const parsed = plainToInstance(KikGenericResponse, this._plainResponse);
    console.info('PARSED GENERIC RESP', {
      whole: parsed,
      msgs: parsed.messages,
    });
    const parsedError = plainToInstance(KikGenericResponse, "this._foo", {
      enableImplicitConversion: !0,
      excludeExtraneousValues: !0
    });
    console.info('Foo to KikGenericResponse (expecting error)', parsedError);
  }


问:
Kotlin Multiplatform use commons module code in javascript project
I have a Multiplatform project setup that represents an API.
This API currently only has a commons module with targets for JS and JVM. However, there is no platform-specific code yet, since all code currently in the commons module (an API model and KTOR client) is already consisting of purely Multiplatform modules.

Now I have a frontend project (which is written in Svelte, JavaScript) where I would like to use the Kotlin code in the commons module of my API project. But I am a total noob at JavaScript, and I don't fully understand what would be the best approach here.
Ideally, I think I would like one JavaScript file that contains all the code I need.

Now I read somewhere that having the following configuration in Gradle

    js(IR) {
        browser {
            binaries.executable()
        }
    }
```
<p>Allows me to run this task: <code>compileProductionExecutableKotlinJs</code> which should generate a single JavaScript file that I can then use. However, when I run this task it does produce code in <code>build/js/packages/api/</code> but the javascript file there <code>api.js</code> contains only this:</p>
<pre class="lang-js prettyprint-override"><code>(function (root, factory) {
  if (typeof define === 'function' && define.amd)
    define(['exports'], factory);
  else if (typeof exports === 'object')
    factory(module.exports);
  else
    root.api = factory(typeof api === 'undefined' ? {} : api);
}(this, function (_) {
  'use strict';
  //region block: pre-declaration
  //endregion
  return _;
}));

//# sourceMappingURL=api.js.map
</code>```

It doesn't contain any of my Kotlin classes.

I guess I have 2 main questions:

Do I need to write code in my jsMain module, even though all my code should already be platform independent, for them to actually appear in the generated JS files? Or should I do this by annotating my code in the commons module?

Is my idea of producing a single JS file the right way to go about it, or is there a better way to produce a kind of library, like a jar file, that I can then import into the front-end project?

My apologies for the messy questions, I am very new to JavaScript, and the Multiplatform setup can be a tad confusing.

Body:
I have a Multiplatform project setup that represents an API.
This API currently only has a commons module with targets for JS and JVM. However, there is no platform-specific code yet, since all code currently in the commons module (an API model and KTOR client) is already consisting of purely Multiplatform modules.

Now I have a frontend project (which is written in Svelte, JavaScript) where I would like to use the Kotlin code in the commons module of my API project. But I am a total noob at JavaScript, and I don't fully understand what would be the best approach here.
Ideally, I think I would like one JavaScript file that contains all the code I need.

Now I read somewhere that having the following configuration in Gradle

    js(IR) {
        browser {
            binaries.executable()
        }
    }

Allows me to run this task: compileProductionExecutableKotlinJs which should generate a single JavaScript file that I can then use. However, when I run this task it does produce code in build/js/packages/api/ but the javascript file there api.js contains only this:

(function (root, factory) {
  if (typeof define === 'function' && define.amd)
    define(['exports'], factory);
  else if (typeof exports === 'object')
    factory(module.exports);
  else
    root.api = factory(typeof api === 'undefined' ? {} : api);
}(this, function (_) {
  'use strict';
  //region block: pre-declaration
  //endregion
  return _;
}));

//# sourceMappingURL=api.js.map

It doesn't contain any of my Kotlin classes.

I guess I have 2 main questions:

Do I need to write code in my jsMain module, even though all my code should already be platform independent, for them to actually appear in the generated JS files? Or should I do this by annotating my code in the commons module?

Is my idea of producing a single JS file the right way to go about it, or is there a better way to produce a kind of library, like a jar file, that I can then import into the front-end project?

My apologies for the messy questions, I am very new to JavaScript, and the Multiplatform setup can be a tad confusing.


问:
How to dynamically save a video with ffmpeg without stopping recording?
I am trying to save a video using ffmpeg with image input from an http webservice. I was able to create the video with the command:
ffmpeg -i http://source -c:v libx264 -r 30 -preset ultrafast -updatefirst 1 -y output.mp4.

However, the video is only actually made available when I stop recording.
Is there a procedure that would allow me to have the video available while recording as is the case using OpenCv's VideoWriter


问:
requestmapping with Spring, automatically adding extension
I am trying to map a function to two URIs: api/members/editPreferences.xml and api/members/editPreferences.json

when i test it in the browser, api/members/editPreferences.xml works, and api/members/editPreferences works, automatically redirecting to api/members/editPreferences.xml

however, api/members/editPreferences.json does not work, because Spring automatically adds ".xml" to the end of the URI. specifically the error says:

HTTP ERROR 404

Problem accessing /api/members/editPreferences.json.xml. Reason:

```<code>NOT_FOUND
</code>```

how do i get spring to stop adding ".xml" to the end of the URI?

ContentLicense: CC BY-SA 3.0

Body:
I am trying to map a function to two URIs: api/members/editPreferences.xml and api/members/editPreferences.json

when i test it in the browser, api/members/editPreferences.xml works, and api/members/editPreferences works, automatically redirecting to api/members/editPreferences.xml

however, api/members/editPreferences.json does not work, because Spring automatically adds ".xml" to the end of the URI. specifically the error says:

HTTP ERROR 404

Problem accessing /api/members/editPreferences.json.xml. Reason:

NOT_FOUND

how do i get spring to stop adding ".xml" to the end of the URI?


问:
Unique constraint key for 3 fields
I need to create unique constraint key by 3 fields. The problem is that in the third field have to be unique only when field equals to 1. For example, we have fields:

```<code>ContentId - uniqueidentifier
MemberId - uniqueidentifier
Approved - bit
</code>```

If we have in table record:

```<code>
ContentId = 99999999-9999-9999-9999-999999999999
MemberId = 88888888-8888-8888-8888-888888888888
Approved = 1

</code>```

And we try to add the same record so we must recieve sql error because of unique key.
But if we try to add the same record with Approved = 0 so it will add without exception

Is it possible to create constraint key with this logic? If it is show me one example please

Title: Unique constraint key for 3 fields

Body:
I need to create unique constraint key by 3 fields. The problem is that in the third field have to be unique only when field equals to 1. For example, we have fields:

ContentId - uniqueidentifier
MemberId - uniqueidentifier
Approved - bit

If we have in table record:

ContentId = 99999999-9999-9999-9999-999999999999
MemberId = 88888888-8888-8888-8888-888888888888
Approved = 1

And we try to add the same record so we must recieve sql error because of unique key.
But if we try to add the same record with Approved = 0 so it will add without exception

Is it possible to create constraint key with this logic? If it is show me one example please


问:
How to launch browser in full screen (maximised)- playwright c#
Im attempting to launch a browser using playwright/C# with the browser maximised.

Ive successfully managed to use SetViewPortSizeAsync to set the size of the browser, however id like to have the browser to be set to the maximum size, irrespectiv of where the tests are run.

below is some basic code that I managed to set the browser size with

```<code>public async Task pageLaunchTest()
{
using var playwright = await Playwright.CreateAsync();

await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
{
//Args = new string[] { "--start-maximized" },
Headless = false,
});

var page = await browser.NewPageAsync();
await page.SetViewportSizeAsync(500, 500);

await page.GotoAsync("https://playwright.dev/");
var pageTitle = await page.TitleAsync();
Assert.Equal ("Fast and reliable end-to-end testing for modern web apps | Playwright",
pageTitle);
</code>```

Unfortunately I was not able to maximise the browser using the setviewportsize method.
Note that on line 3 I also tried passing an argument  '--start-maximised' which others seem to have been successful with but this did not work for me so have commented this out temporarily.
Would appreciate any advice on how to effectively maximise the window before page navigation

Body:
Im attempting to launch a browser using playwright/C# with the browser maximised.

Ive successfully managed to use SetViewPortSizeAsync to set the size of the browser, however id like to have the browser to be set to the maximum size, irrespectiv of where the tests are run.

below is some basic code that I managed to set the browser size with

public async Task pageLaunchTest()
{
using var playwright = await Playwright.CreateAsync();

await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
{
//Args = new string[] { "--start-maximized" },
Headless = false,
});

var page = await browser.NewPageAsync();
await page.SetViewportSizeAsync(500, 500);

await page.GotoAsync("https://playwright.dev/");
var pageTitle = await page.TitleAsync();
Assert.Equal ("Fast and reliable end-to-end testing for modern web apps | Playwright",
pageTitle);

Unfortunately I was not able to maximise the browser using the setviewportsize method.
Note that on line 3 I also tried passing an argument  '--start-maximised' which others seem to have been successful with but this did not work for me so have commented this out temporarily.
Would appreciate any advice on how to effectively maximise the window before page navigation


问:
Support multiple input data models (i.e. polyglot) while reusing the same policy in Open Policy Agent
Has the Rego community settled on some practices for reuse of policy rules while supporting different input data models?

Problem

Assume the same policy is to be enforced by two different PEP:s (Policy Enforcement Point). Let's assume one is an Envoy-OPA setup and the other is an API gateway (non Envoy based) with OPA integration. The data required for the rules is shipped from both setups, but the models will be different (i.e. the data structure that the rules operate on). Are there any standard solutions to this issue?

Potential solutions

(1) Keep separate policy implementations. One for each PEP-technology-stack.
While this solves the task, we end up with different implementations of the same policy.

Pros: Simple and quick on Day 1

Cons: It violates the DRY
principle and carries all the usual issues visiting that rabbit hole.
Different implementations will eventually turn into a security risk.

(2) Lock the input data model. Make sure the input data sent to OPA conforms to the same model. The rules within the policy will operate on the provided input data model as-is.

Pros: One policy implementation suffice. Stable implementation and test harness even if PEP-technology would change.

Cons: The source data models (e.g. from Envoy or our example API Gateway) must be mapped to the policy target model before hitting OPA. Perhaps a viable solution if the flow of data is under your control but for any standard OPA integration it will bring headaches.

(3) Polyglot input data model. Accept different input data models in the same policy. Add a transformation layer (in the policy code) mapping the polyglot input to a stable internal data model. The rules within the policy will operate on the stable internal data model.

Pros: Stable implementation of rules and test harness even if PEP-technology would change. Change of PEP technology will be limited to changes in the transformation layer.

Cons: The transformation logic might be complex given Rego handling of undefined data.

Questions

Other solutions, insights or proven practices?

I would be especially interested in example code of alternative (3) as I currently see this being the best way forward. The logic needs to deal with undefined data and perhaps even conflicting data while mapping to the internal data model. How did you solve the "transformation" part?


问:
java.lang.NumberFormatException: For input string - in github version and tag
I made a release in version v1.0.0-a1 on github and I launched the build on jenkins, until there all worked very well then I create a new tag v1.0.0-a2 on github and I relaunch a build. Since I have this error at the compilation: java.lang.NumberFormatException: For input string: "0-a2"

I then delete the tag v1.0.0-a2 and I create a new v1.0.1-a1 but I still have the same error java.lang.NumberFormatException: For input string: "0-a2"even after deleting the tag and the build on Jenkins

How can I fix this problem,
Thanks for everything