问:
Function accesses global variable depending on useage in function
I only just came across this and it's managed to confuse me. I tried to use the same idea as Function2 but it didn't work, what confused me was it was managing to access other global variables even though I hadn't used global at all.
It seems it depends on how you use the variable which just doesn't seem right to me.
I understand all I need to do is global number in Function2 but why is it that this doesn't work?

```<code>number = 5

def Function1():
    temp = number
    print(temp)

def Function2():
    number += 1
    print(number)

def Function3():
    print(number)

Function1() # >>>  5

Function2() #      line 8, in Function2
            #      number += 1
            #      UnboundLocalError: local variable 'number' referenced before assignment

Function3() # >>>  5
</code>```

Function1 and Function3 work as I expect whereas Function2 does not.

I also tried replacing the number += 1 with number = number + 1 but same error occured.

Python version 3.9.13

Body:
I only just came across this and it's managed to confuse me. I tried to use the same idea as Function2 but it didn't work, what confused me was it was managing to access other global variables even though I hadn't used global at all.
It seems it depends on how you use the variable which just doesn't seem right to me.
I understand all I need to do is global number in Function2 but why is it that this doesn't work?

number = 5

def Function1():
    temp = number
    print(temp)

def Function2():
    number += 1
    print(number)

def Function3():
    print(number)

Function1() # >>>  5

Function2() #      line 8, in Function2
            #      number += 1
            #      UnboundLocalError: local variable 'number' referenced before assignment

Function3() # >>>  5

Function1 and Function3 work as I expect whereas Function2 does not.

I also tried replacing the number += 1 with number = number + 1 but same error occured.

Python version 3.9.13


来源: stackexchange

问:
No dSYMs were found for Version x.x.x
I am getting the Crashlytics detected a missing dSYM for version 1.2.1 error.
I got No dSYMs were found for Version 1.2.1 when I was trying to get the dsym file from xcode.

I was trying to get the dsym file from app store -> testflight -> Build Metadata -> includes symbols, but there have no download button just Yes there.

so I did some search and was trying to download the dysm file from xcode, Follow the link, and then got the Archive successfully, but when I try to download the debug symbols and get the error "No dSYMs were found for Version 1.2.1". Could someone give me some advice how to solve this problem? I didn't find someone with the same error as me.

Following is my build options setting:
xcode build option setting
This is the error I got:
error image

ContentLicense: CC BY-SA 4.0

Title: No dSYMs were found for Version x.x.x


问:
Is there a way to check if a custom event can be emitted in Android
From my Android native module I'm sending events to JavaScript. As suggested here I created a sendEvent method and everything is working properly.

I use it like this

```<code>...
sendEvent(reactContext, "MyEventName", params);
</code>```

However I would like to know if the event is available before emmit the event. Something like

```<code>...
if(reactContext.somethingElse.isEventAvailable("MyEventName"){
    sendEvent(reactContext, "MyEventName", params);
}
</code>```

or

```<code>...
if(reactContext.somethingElse.listenerCount() > 0){
    sendEvent(reactContext, "MyEventName", params);
}
</code>```

Body:
From my Android native module I'm sending events to JavaScript. As suggested here I created a sendEvent method and everything is working properly.

I use it like this

...
sendEvent(reactContext, "MyEventName", params);

However I would like to know if the event is available before emmit the event. Something like

...
if(reactContext.somethingElse.isEventAvailable("MyEventName"){
    sendEvent(reactContext, "MyEventName", params);
}

or

...
if(reactContext.somethingElse.listenerCount() > 0){
    sendEvent(reactContext, "MyEventName", params);
}


问:
postgres not releasing memory after big query
When I run a query in postgres it will load in memory all the data it needs for query execution but when the query finishes executing the memory consumed by postgres is not released.

I run postgres with the Timescaledb extension installed, which already stores 93 million records, the request to get all these 93 million records takes 13GB of RAM and 21mins. After the request, RAM is reduced to 9GB and holds it.

How can I release all this memory?

Here's my postgresql.conf memory section.

```<code>shared_buffers = 8GB
huge_pages = try
huge_page_size = 0
temp_buffers = 8MB
max_prepared_transactions = 0
work_mem = 5118kB
hash_mem_multiplier = 1.0
maintenance_work_mem = 2047MB
autovacuum_work_mem = -1
logical_decoding_work_mem = 64MB
max_stack_depth = 2MB
shared_memory_type = mmap
effective_cache_size = 4GB
</code>```

UPD 15.12.2022

@jjanes Yes, you were right. As a colleague and I found out, memory usage is not exactly what we thought about from the very beginning.

As we also understood from the free -m -h, when a request uses more memory than configured, the remaining data begins to be loaded into cache/buffer.

When we clean cache/buffer after big query, memory usage for this service drops to 8,53GB. This occupied memory +- coincides with the value of shared_buffers = 8GB, it practically does not decrease. For large requests, postgres still continues to use to request large chunks of memory from cache/buffer.

It turns out that we need to somehow clean the cache of postgres itself, since it does not release it itself?

Body:
When I run a query in postgres it will load in memory all the data it needs for query execution but when the query finishes executing the memory consumed by postgres is not released.

I run postgres with the Timescaledb extension installed, which already stores 93 million records, the request to get all these 93 million records takes 13GB of RAM and 21mins. After the request, RAM is reduced to 9GB and holds it.

How can I release all this memory?

Here's my postgresql.conf memory section.

shared_buffers = 8GB
huge_pages = try
huge_page_size = 0
temp_buffers = 8MB
max_prepared_transactions = 0
work_mem = 5118kB
hash_mem_multiplier = 1.0
maintenance_work_mem = 2047MB
autovacuum_work_mem = -1
logical_decoding_work_mem = 64MB
max_stack_depth = 2MB
shared_memory_type = mmap
effective_cache_size = 4GB

UPD 15.12.2022

@jjanes Yes, you were right. As a colleague and I found out, memory usage is not exactly what we thought about from the very beginning.

As we also understood from the free -m -h, when a request uses more memory than configured, the remaining data begins to be loaded into cache/buffer.

When we clean cache/buffer after big query, memory usage for this service drops to 8,53GB. This occupied memory +- coincides with the value of shared_buffers = 8GB, it practically does not decrease. For large requests, postgres still continues to use to request large chunks of memory from cache/buffer.

It turns out that we need to somehow clean the cache of postgres itself, since it does not release it itself?


问:
Is it possible to send a static file (image) from my Python Django backend to my NextJs front end (django rest framework)
as the title suggests I am using a Django BackEnd and a Next.js frontend, I have had no issues uploading an image from a NextJs form to django for static file storage. where I am running into issues is i cannot seem to send the image file back to the front end to take advantage of the nextjs  component.

basically everything I have attempted sends the path in the response which I can use as a src standard  tag but I would like to understand how to send a full image file


问:
Why keycloak public client doesn't have Authorization
I am not able to understand why public client doesn't have Authorization feature. How to achieve Authorization in frontend then?

One approach I understood is create two client one for frontend and one for resource server which is confidential client. And for resource server set the authz.and now in public client fetch backend authz info via api calls.

For authentication, I am passing tokens from frontend and validating jwt at backend. For Authorization also I can pass token which I retrieve from authz and validate jwt. So it means I am creating confidential client only for storing authz information, if I had public client with authz then I didn't had to create multiple client?


问:
How to write to existing excel file using SheetJS in JavaScript
There is a form that a user will use to upload an excel file to. From there, in JavaScript, I am able to pull the data (this includes if excel file has multiple sheets) and store it in arrays (columnA, columnB, etc.). However, I am not sure how to write to an existing excel file that is on the server with the data stored in the arrays. Any help would be appreciated.

The following is what I have so far:

```<code>    let selectedFile, fileName;

    document.getElementById('input-excel').addEventListener("change", (event) => {
        selectedFile = event.target.files[0];
        fileName = event.target.files[0].name;
    })

    let data=[{
        "name":"jayanth",
        "data":"scd",
        "abc":"sdef"
    }]

    document.getElementById('button').addEventListener("click", () => {
        XLSX.utils.json_to_sheet(data, selectedFile);
        if(fileName.includes("Excel FileName")){
            let fileReader = new FileReader();
            fileReader.readAsBinaryString(selectedFile);
            fileReader.onload = (event)=>{
                 let data = event.target.result;
                 let workbookInputted = XLSX.read(data,{type:"binary"}); //excel file
                 let residential_worksheet = workbookInputted.Sheets[workbookInputted.SheetNames[0]]; //test1 sheet
                 let non_residential_worksheet = workbookInputted.Sheets[workbookInputted.SheetNames[1]]; //test2 sheet
                 let peh_worksheet = workbookInputted.Sheets[workbookInputted.SheetNames[2]]; //test3 sheet
                 let educational_worksheet = workbookInputted.Sheets[workbookInputted.SheetNames[3]]; //test4 setting sheet
                 let correct_worksheet = workbookInputted.Sheets[workbookInputted.SheetNames[4]]; //test5 setting sheet

                 const sheetList = workbookInputted.SheetNames;

                 const res = WhichSheet(residential_worksheet,sheetList[0]);
                 const nonRes = WhichSheet(non_residential_worksheet,sheetList[1]);
                 const peh = WhichSheet(peh_worksheet,sheetList[2]);
                 const ed = WhichSheet(educational_worksheet,sheetList[3]);
                 const correct = WhichSheet(correct_worksheet,sheetList[4]);

                 //console.log(sheetList[3]);
            }
        }
    });

    function WhichSheet(worksheet, fileNme){
        if(fileName.localeCompare("test")){
            ReadColumntoJSData(worksheet, fileNme);
        } else if(fileName.includes("test2")){
            ReadColumntoJSData(worksheet, fileNme);
        } else if(fileName.includes("test3")){
            ReadColumntoJSData(worksheet, fileNme);
        } else if(fileName.includes("test4")){
            ReadColumntoJSData(worksheet, fileNme);
        } else if(fileName.includes("test5")){
            ReadColumntoJSData(worksheet, fileNme);
        }
    }

    /*==
    ====== Following method reads each column per sheet. ======
    ===*/
    function ReadColumntoJSData(worksheet, fileNme){
        var colA = [];
        var colB = [];
        var colC = [];
        var colD = [];
        var colE = [];
        var colF = [];

        for(let col in worksheet){
            if(col.toString()[0] === 'A'){
                if(col === "A1" || col === "A2" || col === "A3"){
                    //do nothing
                } else {
                    colA.push(worksheet[col].v);
                }
            }
            if(col.toString()[0] === 'B'){
                if(col === "B1" || col === "B2" || col === "B3"){
                    //do nothing
                } else {
                    colB.push(worksheet[col].v);
                }
            }
            if(col.toString()[0] === 'C'){
                if(col === "C1" || col === "C2" || col === "C3"){
                    //do nothing
                } else {
                    colC.push(worksheet[col].v);
                }
            }
            if(col.toString()[0] === 'D'){
                if(col === "D1" || col === "D2" || col === "D3"){
                    //do nothing
                } else {
                    colD.push(worksheet[col].v);
                }
            }
            if(col.toString()[0] === 'E'){
                if(col === "E1" || col === "E2" || col === "E3"){
                    //do nothing
                } else {
                    colE.push(worksheet[col].v);
                }
            }
            if(fileNme == "test2" || fileNme == "test5"){
                //do nothing
            } else{
                if(col.toString()[0] === 'F'){
                    if(col === "F1" || col === "F2" || col === "F3"){
                        //do nothing
                    } else {
                        colF.push(worksheet[col].v);
                    }
                }
            }
        }
        ExportToExcel(colA,colB,colC,colD,colE,colF);
    }

    function ExportToExcel(colA,colB,colC,colD,colE,colF,fileName){
        console.log(colA)
    }
</code>```

UPDATE: I tried the following to write to the existing excel sheet. However, I am getting the following error: Uncaught TypeError: Cannot read properties of undefined (reading 'A3').

```<code> var req = new XMLHttpRequest();
        req.open("GET", fileURL2, true);
        req.responseType = "arraybuffer";

        req.onload = function(e) {
          var data = new Uint8Array(req.response);
          const writeWorkBook = XLSX.read(data, {type:"array"});
          const writeWorkSheet = writeWorkBook.Sheets["TEST123"]
          console.log("Worksheet: " + JSON.stringify(writeWorkSheet));

          writeWorkSheet['A3'].v = colA[0];
        }

        req.send();
</code>```

Body:
There is a form that a user will use to upload an excel file to. From there, in JavaScript, I am able to pull the data (this includes if excel file has multiple sheets) and store it in arrays (columnA, columnB, etc.). However, I am not sure how to write to an existing excel file that is on the server with the data stored in the arrays. Any help would be appreciated.

The following is what I have so far:

    let selectedFile, fileName;

    document.getElementById('input-excel').addEventListener("change", (event) => {
        selectedFile = event.target.files[0];
        fileName = event.target.files[0].name;
    })

    let data=[{
        "name":"jayanth",
        "data":"scd",
        "abc":"sdef"
    }]

    document.getElementById('button').addEventListener("click", () => {
        XLSX.utils.json_to_sheet(data, selectedFile);
        if(fileName.includes("Excel FileName")){
            let fileReader = new FileReader();
            fileReader.readAsBinaryString(selectedFile);
            fileReader.onload = (event)=>{
                 let data = event.target.result;
                 let workbookInputted = XLSX.read(data,{type:"binary"}); //excel file
                 let residential_worksheet = workbookInputted.Sheets[workbookInputted.SheetNames[0]]; //test1 sheet
                 let non_residential_worksheet = workbookInputted.Sheets[workbookInputted.SheetNames[1]]; //test2 sheet
                 let peh_worksheet = workbookInputted.Sheets[workbookInputted.SheetNames[2]]; //test3 sheet
                 let educational_worksheet = workbookInputted.Sheets[workbookInputted.SheetNames[3]]; //test4 setting sheet
                 let correct_worksheet = workbookInputted.Sheets[workbookInputted.SheetNames[4]]; //test5 setting sheet

                 const sheetList = workbookInputted.SheetNames;

                 const res = WhichSheet(residential_worksheet,sheetList[0]);
                 const nonRes = WhichSheet(non_residential_worksheet,sheetList[1]);
                 const peh = WhichSheet(peh_worksheet,sheetList[2]);
                 const ed = WhichSheet(educational_worksheet,sheetList[3]);
                 const correct = WhichSheet(correct_worksheet,sheetList[4]);

                 //console.log(sheetList[3]);
            }
        }
    });

    function WhichSheet(worksheet, fileNme){
        if(fileName.localeCompare("test")){
            ReadColumntoJSData(worksheet, fileNme);
        } else if(fileName.includes("test2")){
            ReadColumntoJSData(worksheet, fileNme);
        } else if(fileName.includes("test3")){
            ReadColumntoJSData(worksheet, fileNme);
        } else if(fileName.includes("test4")){
            ReadColumntoJSData(worksheet, fileNme);
        } else if(fileName.includes("test5")){
            ReadColumntoJSData(worksheet, fileNme);
        }
    }

    /*==
    ====== Following method reads each column per sheet. ======
    ===*/
    function ReadColumntoJSData(worksheet, fileNme){
        var colA = [];
        var colB = [];
        var colC = [];
        var colD = [];
        var colE = [];
        var colF = [];

        for(let col in worksheet){
            if(col.toString()[0] === 'A'){
                if(col === "A1" || col === "A2" || col === "A3"){
                    //do nothing
                } else {
                    colA.push(worksheet[col].v);
                }
            }
            if(col.toString()[0] === 'B'){
                if(col === "B1" || col === "B2" || col === "B3"){
                    //do nothing
                } else {
                    colB.push(worksheet[col].v);
                }
            }
            if(col.toString()[0] === 'C'){
                if(col === "C1" || col === "C2" || col === "C3"){
                    //do nothing
                } else {
                    colC.push(worksheet[col].v);
                }
            }
            if(col.toString()[0] === 'D'){
                if(col === "D1" || col === "D2" || col === "D3"){
                    //do nothing
                } else {
                    colD.push(worksheet[col].v);
                }
            }
            if(col.toString()[0] === 'E'){
                if(col === "E1" || col === "E2" || col === "E3"){
                    //do nothing
                } else {
                    colE.push(worksheet[col].v);
                }
            }
            if(fileNme == "test2" || fileNme == "test5"){
                //do nothing
            } else{
                if(col.toString()[0] === 'F'){
                    if(col === "F1" || col === "F2" || col === "F3"){
                        //do nothing
                    } else {
                        colF.push(worksheet[col].v);
                    }
                }
            }
        }
        ExportToExcel(colA,colB,colC,colD,colE,colF);
    }

    function ExportToExcel(colA,colB,colC,colD,colE,colF,fileName){
        console.log(colA)
    }

UPDATE: I tried the following to write to the existing excel sheet. However, I am getting the following error: Uncaught TypeError: Cannot read properties of undefined (reading 'A3').

 var req = new XMLHttpRequest();
        req.open("GET", fileURL2, true);
        req.responseType = "arraybuffer";

        req.onload = function(e) {
          var data = new Uint8Array(req.response);
          const writeWorkBook = XLSX.read(data, {type:"array"});
          const writeWorkSheet = writeWorkBook.Sheets["TEST123"]
          console.log("Worksheet: " + JSON.stringify(writeWorkSheet));

          writeWorkSheet['A3'].v = colA[0];
        }

        req.send();


问:
How do I use a Navbar to search through Data from in Array and match the search in In Nextjs TypeScript?
```<code>
type Props = {
topic?: string;
}

function Header({topic}: Props) {
const [istopic, setTopic] = useState("");
const{loading, data, error} = !topic? useQuery(GET_POSTS): useQuery(GET_POSTS_BY_TOPIC,{
variables:{
     topic:topic,
}
});

const posts: Post[\] = !topic ? data?.getPostList : data?.getPostListByTopic
</code>```

//HERE IS THE METHOD I USED TO CREATE AN ARRAY FROM THE QUERY LIST

//HERE IS THE FORM INSIDE OF MY NAVBAR THAT I WANT TO USE TO SEARCH THE RESULTS

```<code><form
  onSubmit={handleSubmit}
  className="flex flex-1 items-center basis-1/3 space-x-2 rounded-md border-none border-gray-500 px-3 py-1"
>
  <input
    value={istopic}
    onChange={(e) => setTopic(e.target.value)}
    type="text"
    placeholder="Search"
    onSubmit={handleSubmit}
    className="flex-1 rounded-md border-gray-400 bg-transparent outline-none "
  />
  <SearchIcon className="h-7 w-7 text-gray-400" />
  <button disabled={!istopic} type="submit" hidden />
</form>;

{
  posts ? (
    posts
      ?.filter((post: any) => post.title.match(new RegExp(istopic, "i")))
      ?.map((post: any) => {
        <div>
          <a
            href={`/channel/${post.channels[0]?.topic}`}
            className=" absolute top-6 z-99  bg-blue-600 block py-2 pl-3 pr-4 text-gray-700 rounded"
            aria-current="page"
          >
            {post.title}
          </a>
        </div>;
        console.log(post.title);
      })
  ) : (
    <li>
      <a
        href="#"
        className=" absolute top-6 z-99  bg-blue-600   block py-2 pl-3 pr-4 text-gray-700 rounded hover:bg-gray-100"
        aria-current="page"
      >
        Nothing Found
      </a>
    </li>
  );
}

</code>```

I want to use the data from the array the to check if there is any that matches from the input field and display those matches

Body:
type Props = {
topic?: string;
}

function Header({topic}: Props) {
const [istopic, setTopic] = useState("");
const{loading, data, error} = !topic? useQuery(GET_POSTS): useQuery(GET_POSTS_BY_TOPIC,{
variables:{
     topic:topic,
}
});

const posts: Post[\] = !topic ? data?.getPostList : data?.getPostListByTopic

//HERE IS THE METHOD I USED TO CREATE AN ARRAY FROM THE QUERY LIST

//HERE IS THE FORM INSIDE OF MY NAVBAR THAT I WANT TO USE TO SEARCH THE RESULTS

<form
  onSubmit={handleSubmit}
  className="flex flex-1 items-center basis-1/3 space-x-2 rounded-md border-none border-gray-500 px-3 py-1"
>
  <input
    value={istopic}
    onChange={(e) => setTopic(e.target.value)}
    type="text"
    placeholder="Search"
    onSubmit={handleSubmit}
    className="flex-1 rounded-md border-gray-400 bg-transparent outline-none "
  />
  <SearchIcon className="h-7 w-7 text-gray-400" />
  <button disabled={!istopic} type="submit" hidden />
</form>;

{
  posts ? (
    posts
      ?.filter((post: any) => post.title.match(new RegExp(istopic, "i")))
      ?.map((post: any) => {

          <a
            href={`/channel/${post.channels[0]?.topic}`}
            className=" absolute top-6 z-99  bg-blue-600 block py-2 pl-3 pr-4 text-gray-700 rounded"
            aria-current="page"
          >
            {post.title}

;
        console.log(post.title);
      })
  ) : (

        Nothing Found

  );
}

I want to use the data from the array the to check if there is any that matches from the input field and display those matches


问:
Saving pdf from R-Shiny only generates a temporary pdf
I am writing an r-shiny app that takes user input and outputs it into a formatted pdf report. I can get the pdf to generate but its a temporary file (with a randomly generated temporary name) and I am not given an option to save it unless I save it from the pdf viewer itself. When the user pushes the 'Download Report' button I want them to be able to pick where the file is saved as I will eventually make this mobile compatible and it will need to work on laptops/phones/tablets etc. Not sure if it is related but any files that get copied to the temp directory (i.e rmarkdown files or images) need to be in the same folder as the Shiny App.

What do I need to change to make it save to the local computer? There are no errors or warnings produced when I execute the code just something like:
Output created: C:\Users\SGrass\AppData\Local\Temp\RtmpsrlxyW\file32a43867233b.pdf

Even when I try running the example from here I get the same issue (https://shiny.rstudio.com/articles/generating-reports.html)

```<code>#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
#    http://shiny.rstudio.com/
#

library(shiny)

# Define UI for application that draws a histogram
ui = fluidPage(
  sliderInput("slider", "Slider", 1, 100, 50),
  downloadButton("report", "Generate report")
)

# Define server logic required to draw a histogram
server = function(input, output) {
  output$report <- downloadHandler(
    # For PDF output, change this to "report.pdf"
    filename = "report.pdf",
    content = function(file) {
      # Copy the report file to a temporary directory before processing it, in
      # case we don't have write permissions to the current working dir (which
      # can happen when deployed).
      tempReport <- file.path(tempdir(), "report.Rmd")
      file.copy("report.Rmd", tempReport, overwrite = TRUE)

      # Set up parameters to pass to Rmd document
      params <- list(n = input$slider)

      # Knit the document, passing in the `params` list, and eval it in a
      # child of the global environment (this isolates the code in the document
      # from the code in this app).
      rmarkdown::render(tempReport,
                        output_file = file,
                        params = params,
                        envir = new.env(parent = globalenv())
      )
    }
  )
}

# Run the application
shinyApp(ui = ui, server = server)
</code>```
```<code>---
title: "Dynamic report"
output: pdf_document
params:
  n: NA
---

```{r}
# The `params` object is available in the document.
params$n
```

A plot of `params$n` random points.

```{r}
plot(rnorm(params$n), rnorm(params$n))
```
</code>```

Body:
I am writing an r-shiny app that takes user input and outputs it into a formatted pdf report. I can get the pdf to generate but its a temporary file (with a randomly generated temporary name) and I am not given an option to save it unless I save it from the pdf viewer itself. When the user pushes the 'Download Report' button I want them to be able to pick where the file is saved as I will eventually make this mobile compatible and it will need to work on laptops/phones/tablets etc. Not sure if it is related but any files that get copied to the temp directory (i.e rmarkdown files or images) need to be in the same folder as the Shiny App.

What do I need to change to make it save to the local computer? There are no errors or warnings produced when I execute the code just something like:
Output created: C:\Users\SGrass\AppData\Local\Temp\RtmpsrlxyW\file32a43867233b.pdf

Even when I try running the example from here I get the same issue (https://shiny.rstudio.com/articles/generating-reports.html)

#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
#    http://shiny.rstudio.com/
#

library(shiny)

# Define UI for application that draws a histogram
ui = fluidPage(
  sliderInput("slider", "Slider", 1, 100, 50),
  downloadButton("report", "Generate report")
)

# Define server logic required to draw a histogram
server = function(input, output) {
  output$report <- downloadHandler(
    # For PDF output, change this to "report.pdf"
    filename = "report.pdf",
    content = function(file) {
      # Copy the report file to a temporary directory before processing it, in
      # case we don't have write permissions to the current working dir (which
      # can happen when deployed).
      tempReport <- file.path(tempdir(), "report.Rmd")
      file.copy("report.Rmd", tempReport, overwrite = TRUE)

      # Set up parameters to pass to Rmd document
      params <- list(n = input$slider)

      # Knit the document, passing in the `params` list, and eval it in a
      # child of the global environment (this isolates the code in the document
      # from the code in this app).
      rmarkdown::render(tempReport,
                        output_file = file,
                        params = params,
                        envir = new.env(parent = globalenv())
      )
    }
  )
}

# Run the application
shinyApp(ui = ui, server = server)

---
title: "Dynamic report"
output: pdf_document
params:
  n: NA
---

```{r}
# The `params` object is available in the document.
params$n
```

A plot of `params$n` random points.

```{r}
plot(rnorm(params$n), rnorm(params$n))
```


问:
How to set an different grid cols for md and below screen?
I'm using tailwind to display grid. I want the grid to be grid-cols-3 for large screen and above,
and grid-cols-2 for medium screen and below.

Currently I'm using class="grid grid-cols-3 md:grid-cols-2" which is not working.

The md:grid-cols-2 is overriding for all screen size.
How can I set different grid size for different screen size


问:
why would memoizing a function cause it to have a different output
Is anyone able to explain a reason why these two functions would have different outputs? I'm trying to memoize my recursive function, but it output a different value when I do. Any ideas why? Wouldn't that mean it would have to enter into the same subproblem and find a different answer for this to be returning something different? I'm super confused, thanks for any help</p>
```<code>    public long maxAlternatingSumHelper(int[] nums,int index,boolean plus, long sum) {
        if (index == nums.length) {
            return sum;
        }

        int adder = nums[index];
        if (!plus) adder *= -1;
        long ans = Math.max(maxAlternatingSumHelper(nums,index+1,true, 0),
                Math.max(maxAlternatingSumHelper(nums,index+1,plus, sum),
                 maxAlternatingSumHelper(nums,index+1,!plus, sum + adder)));
        return ans;
    }
</code>```
```<code>    Hashtable<IndexPlus,Long> sumDp = new Hashtable<>();
    public long maxAlternatingSumHelper(int[] nums,int index,boolean plus, long sum) {
        if (index == nums.length) {
            return sum;
        }
        if (sumDp.containsKey(new IndexPlus(index,plus))){
            return sumDp.get(new IndexPlus(index,plus));
        }
        int adder = nums[index];
        if (!plus) adder *= -1;
        long ans = Math.max(maxAlternatingSumHelper(nums,index+1,true, 0),
                Math.max(maxAlternatingSumHelper(nums,index+1,plus, sum),
                 maxAlternatingSumHelper(nums,index+1,!plus, sum + adder)));
        sumDp.put(new IndexPlus(index,plus),ans);
        return ans;
    }
</code>```

Body:
Is anyone able to explain a reason why these two functions would have different outputs? I'm trying to memoize my recursive function, but it output a different value when I do. Any ideas why? Wouldn't that mean it would have to enter into the same subproblem and find a different answer for this to be returning something different? I'm super confused, thanks for any help

    public long maxAlternatingSumHelper(int[] nums,int index,boolean plus, long sum) {
        if (index == nums.length) {
            return sum;
        }

        int adder = nums[index];
        if (!plus) adder *= -1;
        long ans = Math.max(maxAlternatingSumHelper(nums,index+1,true, 0),
                Math.max(maxAlternatingSumHelper(nums,index+1,plus, sum),
                 maxAlternatingSumHelper(nums,index+1,!plus, sum + adder)));
        return ans;
    }

    Hashtable<IndexPlus,Long> sumDp = new Hashtable<>();
    public long maxAlternatingSumHelper(int[] nums,int index,boolean plus, long sum) {
        if (index == nums.length) {
            return sum;
        }
        if (sumDp.containsKey(new IndexPlus(index,plus))){
            return sumDp.get(new IndexPlus(index,plus));
        }
        int adder = nums[index];
        if (!plus) adder *= -1;
        long ans = Math.max(maxAlternatingSumHelper(nums,index+1,true, 0),
                Math.max(maxAlternatingSumHelper(nums,index+1,plus, sum),
                 maxAlternatingSumHelper(nums,index+1,!plus, sum + adder)));
        sumDp.put(new IndexPlus(index,plus),ans);
        return ans;
    }


问:
MUI grid not stacking side by side in dynamic form
This seems like a noob question, but for some reason, In my form, the grid is not stacking side by side when i set the prop to 6 IE md={6}. They all just set themselves to 6, and goto the next line. What i want, is for them to be side by side.</p>
```<code>            {fieldSet.map((item,index) => {
                if(item.domain === null){
                  if(item.alias == 'OBJECTID'){
                    return
                  };
                    return (
                        <Grid xs={12} md={6} lg={6} key={index}>
                            <FormControl variant="standard" fullWidth style={{marginBottom:'10px'}}>
                            <InputLabel shrink multiline htmlFor={item.alias} style={{color:'white'}}>{item.alias}</InputLabel>
                            <StyledInput id={item.alias} onChange={e => setFieldsData(fieldsData => ({...fieldsData, [e.target.id]: e.target.value}))} />
                            </FormControl>
                        </Grid>
                    )
                } else if(item.domain != null){
                    return (
                        <Grid xs={12} md={6} lg={6} key={index}>
                            <FormControl fullWidth size='small' style={{marginTop:'20px'}}>
                            <InputLabel id={item.alias}>{item.alias}</InputLabel>
                            <Select id={item.alias} labelId={item.alias} onChange={e => setFieldsData(fieldsData => ({...fieldsData, [item.alias]: e.target.value}))} style={{backgroundColor:'white'}}>
                              {item.domain.codedValues.map((values, index) => {
                                return (
                                  <MenuItem key={index} value={values.name}>{values.name}</MenuItem>
                                )
                              })}
                            </Select>
                            </FormControl>
                        </Grid>
                    )
                }
            })}
</code>```

Body:
This seems like a noob question, but for some reason, In my form, the grid is not stacking side by side when i set the prop to 6 IE md={6}. They all just set themselves to 6, and goto the next line. What i want, is for them to be side by side.

            {fieldSet.map((item,index) => {
                if(item.domain === null){
                  if(item.alias == 'OBJECTID'){
                    return
                  };
                    return (
                        <Grid xs={12} md={6} lg={6} key={index}>
                            <FormControl variant="standard" fullWidth style={{marginBottom:'10px'}}>
                            <InputLabel shrink multiline htmlFor={item.alias} style={{color:'white'}}>{item.alias}</InputLabel>


问:
is there a way to return the audio from javascript to html source tag
my project need to show the final audio processed to the user so i am using audio html tag and processed all the audio work in java script side the problem is how to give the processed audio to the html audio tag
i did it with button tag but can't do with audio tag (not working)ny help

java script mus.js

```<code>const mus = {
    A : new Audio("pA.mp3"),
    B : new Audio("pB.mp3")
}

let txt="";
function emc()
{
txt = document.getElementById("d1").value.toUpperCase()
console.log(txt);
for (const char of txt)
{
   mus[char].playbackRate = 2;
   char in mus ? mus[char].play() : char;

}
}
</code>```
```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>audio</title>

</head>
<body>

    <script src = "muss.js"></script>
    <br>
    <textarea id="d1" rows="13" cols="60"></textarea><br><br><br>
    <input type="button" value="playing" onClick="emc()"></input>
    <audio controls autoplay muted >
      <source src="x" type="audio/ogg">
    </audio>
    <br>
    <br><br><br>
    <button id="d0" onclick="playMusic()">work</button>
    <br>
    <br><br><br>
    <!--<div id="x"></div>-->
    <button id="x" onclick="emc()">Set Song</button>
    <audio controls onplay="playMusic()" autoplay muted> /// here this is not showing the playing  music instead only empty one
      <source src='${audio}' type="audio/mpeg"></source>
</audio>
</body>
</html>
</code>```

i tried every thing i know but not working help me

any suggestions or ideas ??

Body:
my project need to show the final audio processed to the user so i am using audio html tag and processed all the audio work in java script side the problem is how to give the processed audio to the html audio tag
i did it with button tag but can't do with audio tag (not working)ny help

java script mus.js

const mus = {
    A : new Audio("pA.mp3"),
    B : new Audio("pB.mp3")
}

let txt="";
function emc()
{
txt = document.getElementById("d1").value.toUpperCase()
console.log(txt);
for (const char of txt)
{
   mus[char].playbackRate = 2;
   char in mus ? mus[char].play() : char;

}
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>audio</title>

    <textarea id="d1" rows="13" cols="60"></textarea>

    <input type="button" value="playing" onClick="emc()"></input>
    <audio controls autoplay muted >
      <source src="x" type="audio/ogg">
    </audio>

    <button id="d0" onclick="playMusic()">work</button>

    <button id="x" onclick="emc()">Set Song</button>
    <audio controls onplay="playMusic()" autoplay muted> /// here this is not showing the playing  music instead only empty one
      <source src='${audio}' type="audio/mpeg"></source>
</audio>

i tried every thing i know but not working help me

any suggestions or ideas ??


问:
ag-grid-react masterdetail grid option different styles on master and detail grid
I'm using ag-grid-react masterdetail option to create a master grid with a detail grid. I'd the master grid to have a different theme from the detail grid.

For example, the master grid would have "ag-theme-alpine" and the detail grid would have "ag-theme-alphine-dark". Is this possible?

I tried looking through the docs for some options for the detailCellRendererParams but couldn't find anything obvious.


问:
Implementing SSR with React and ASP.NET core 5 with Razor pages
I am researching the best way to Implementing React with Razor pages in ASP.NET core with Razor pages.  I haven't really been able to find anything that applies to .NET 6 only .NET 5 and older.  The initial plan was to use something like InertiaJs, I was able to find a NuGet package for that unfortunately they stopped support after .NET 5. I started looking for other SSR implementations and found some packages that are out of date.

I am just putting this out here to see if anyone knows anything or has any leads on this. If I find anything I will make sure to put it in the comments.


问:
Using curl to download zip file but file is empty
I am trying to download dependency-check-7.4.1-release.zip using the below script in my GitLab Ci Pipeline:

```<code>script:
    - VERSION=$(curl https://jeremylong.github.io/DependencyCheck/current.txt)
    - curl "https://github.com/jeremylong/DependencyCheck/releases/download/v$VERSION/dependency-check-$VERSION-release.zip" --output dependency-check.zip
    - ls -al
    - unzip dependency-check-${VERSION}-release.zip
</code>```

The file is present in the build directory as show below:

```<code>total 40
drwxrwxrwx    9 root     root           250 Dec 13 18:27 .
drwxrwxrwx   18 root     root          4096 Dec 13 16:22 ..
-rw-rw-rw-    1 root     root         13347 Dec 13 13:18 .editorconfig
drwxrwxrwx    6 root     root           128 Dec 13 18:27 .git
-rw-rw-rw-    1 root     root          7471 Dec 13 13:18 .gitignore
-rw-rw-rw-    1 root     root          3397 Dec 13 18:27 .gitlab-ci.yml
drwxrwxrwx    6 root     root           326 Dec 13 13:18 xxxx
drwxrwxrwx    6 root     root            97 Dec 13 13:18 xxxx.Test
-rw-rw-rw-    1 root     root          1833 Dec 13 13:18 xxxx
drwxrwxrwx    2 root     root           197 Dec 13 13:18 PostMan
-rw-rw-rw-    1 root     root          1265 Dec 13 13:18 README.md
-rw-r--r--    1 root     root             0 Dec 13 18:27 dependency-check.zip
drwxrwxrwx    3 root     root           100 Dec 13 13:18 migration
drwxrwxrwx    2 root     root            32 Dec 13 16:14 templates
drwxrwxrwx    4 root     root           201 Dec 13 13:18 [MASKED]
</code>```

i am using this image: mcr.microsoft.com/dotnet/runtime:6.0-alpine3.14

I can not figure out what I did wrong.
Any help?

Body:
I am trying to download dependency-check-7.4.1-release.zip using the below script in my GitLab Ci Pipeline:

script:
    - VERSION=$(curl https://jeremylong.github.io/DependencyCheck/current.txt)
    - curl "https://github.com/jeremylong/DependencyCheck/releases/download/v$VERSION/dependency-check-$VERSION-release.zip" --output dependency-check.zip
    - ls -al
    - unzip dependency-check-${VERSION}-release.zip

The file is present in the build directory as show below:

total 40
drwxrwxrwx    9 root     root           250 Dec 13 18:27 .
drwxrwxrwx   18 root     root          4096 Dec 13 16:22 ..
-rw-rw-rw-    1 root     root         13347 Dec 13 13:18 .editorconfig
drwxrwxrwx    6 root     root           128 Dec 13 18:27 .git
-rw-rw-rw-    1 root     root          7471 Dec 13 13:18 .gitignore
-rw-rw-rw-    1 root     root          3397 Dec 13 18:27 .gitlab-ci.yml
drwxrwxrwx    6 root     root           326 Dec 13 13:18 xxxx
drwxrwxrwx    6 root     root            97 Dec 13 13:18 xxxx.Test
-rw-rw-rw-    1 root     root          1833 Dec 13 13:18 xxxx
drwxrwxrwx    2 root     root           197 Dec 13 13:18 PostMan
-rw-rw-rw-    1 root     root          1265 Dec 13 13:18 README.md
-rw-r--r--    1 root     root             0 Dec 13 18:27 dependency-check.zip
drwxrwxrwx    3 root     root           100 Dec 13 13:18 migration
drwxrwxrwx    2 root     root            32 Dec 13 16:14 templates
drwxrwxrwx    4 root     root           201 Dec 13 13:18 [MASKED]

i am using this image: mcr.microsoft.com/dotnet/runtime:6.0-alpine3.14

I can not figure out what I did wrong.
Any help?


问:
JAX-RS: How to return two-dimensional array
How can I return a two-dimensional array through JAX-RS? The following gets an error:

```<code>    @Produces(MediaType.APPLICATION_JSON)
    public Response getPicks(@PathParam("season") String season, @PathParam("week") int week)
...
    Pick[][] allPicks = Pick.Fetch(gameIds);
    return Response.status(200).entity(allPicks).build();
</code>```
```<code>SEVERE [http-nio-8079-exec-49]
org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo MessageBodyWriter not found for media type=application/json, type=class [[Lcom.lordbah.footballbeans.Pick;, genericType=class [[Lcom.lordbah.footballbeans.Pick;.
</code>```

while returning a one-dimensional array of the same object works fine:

```<code>    return Response.status(200).entity(allPicks[0]).build();
</code>```

The web client gets back a JSON array of Picks.

org.glassfish jaxb-core is back at 2.3.0.1, jersey-* at 2.31, in case it's a known add in later versions. I didn't see anything suggesting so.

It doesn't have any issue with the base object, or with an array of them, but the second dimension confuses it.

Body:
How can I return a two-dimensional array through JAX-RS? The following gets an error:

    @Produces(MediaType.APPLICATION_JSON)
    public Response getPicks(@PathParam("season") String season, @PathParam("week") int week)
...
    Pick[][] allPicks = Pick.Fetch(gameIds);
    return Response.status(200).entity(allPicks).build();

SEVERE [http-nio-8079-exec-49]
org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo MessageBodyWriter not found for media type=application/json, type=class [[Lcom.lordbah.footballbeans.Pick;, genericType=class [[Lcom.lordbah.footballbeans.Pick;.

while returning a one-dimensional array of the same object works fine:

    return Response.status(200).entity(allPicks[0]).build();

The web client gets back a JSON array of Picks.

org.glassfish jaxb-core is back at 2.3.0.1, jersey-* at 2.31, in case it's a known add in later versions. I didn't see anything suggesting so.

It doesn't have any issue with the base object, or with an array of them, but the second dimension confuses it.


问:
.NET Maui IOS Release build doesn't contain iTunesArtwork?
Just wondering about the white picture after deploying my app to itunesconnect.

After renaming the .ipa file to .zip and browsing through it it noticed that .net has not include an itunesartwork... file. Only the appicon and my icons for the tabbar included.

I created the .ipa with the terminal command:

dotnet publish -f:net7.0-ios -c:Release /p:ArchiveOnBuild=true

Did i miss something? Is there an optional parameter to force Visual Studio 2022 to create that 1024x1024 graphic?

If i look in the iossimulator folder for that app it includes all the graphics, and i think the file appiconItunesArtwork.png is the important one?


问:
OAuth2 and/or JWT: make sure users are authenticated
This question is not about the difference between Oauth2 and JWT.

I'm building an application using Go and the Gin framework. This application should be able to register users with Facebook SSO. Once a user is registered, I want to make sure that all my endpoints will require an authenticated user. So far I have implemented the Oauth flow, and it works. I'm using the goth/gothic libraries. It looks like this:

router.GET("/auth/:provider", func(c *gin.Context) {
    q := c.Request.URL.Query()
    q.Add("provider", c.Param("provider"))
    c.Request.URL.RawQuery = q.Encode()

    // try to get the user without re-authenticating
    if gothUser, err := gothic.CompleteUserAuth(c.Writer, c.Request); err == nil {
        logger.Debug("Re-using existing credentials", gothUser)
    } else {
        logger.Debug("Starting auth flow")
        gothic.BeginAuthHandler(c.Writer, c.Request)
    }
})

router.GET("/callback", func(c *gin.Context) {
    user, err := gothic.CompleteUserAuth(c.Writer, c.Request)
    l.Debug(user)

    if err != nil {
        c.AbortWithError(http.StatusInternalServerError, err)
    }
})
```

I'm a bit stuck regarding what to do next. All the articles I could find describe how to get the oauth token, but not how to use it. Should I use the info I get back from facebook (e.g: name, email) to build a JWT token to secure my endpoints? Or is there a way to securely/easily use the oauth token to do that?

I could use a pointer to be on the right track, as you know implementing the auth mechanism is quite important and I couldn't find a guide describing good practices.

Body:
This question is not about the difference between Oauth2 and JWT.

I'm building an application using Go and the Gin framework. This application should be able to register users with Facebook SSO. Once a user is registered, I want to make sure that all my endpoints will require an authenticated user. So far I have implemented the Oauth flow, and it works. I'm using the goth/gothic libraries. It looks like this:

router.GET("/auth/:provider", func(c *gin.Context) {
    q := c.Request.URL.Query()
    q.Add("provider", c.Param("provider"))
    c.Request.URL.RawQuery = q.Encode()

    // try to get the user without re-authenticating
    if gothUser, err := gothic.CompleteUserAuth(c.Writer, c.Request); err == nil {
        logger.Debug("Re-using existing credentials", gothUser)
    } else {
        logger.Debug("Starting auth flow")
        gothic.BeginAuthHandler(c.Writer, c.Request)
    }
})

router.GET("/callback", func(c *gin.Context) {
    user, err := gothic.CompleteUserAuth(c.Writer, c.Request)
    l.Debug(user)

    if err != nil {
        c.AbortWithError(http.StatusInternalServerError, err)
    }
})

I'm a bit stuck regarding what to do next. All the articles I could find describe how to get the oauth token, but not how to use it. Should I use the info I get back from facebook (e.g: name, email) to build a JWT token to secure my endpoints? Or is there a way to securely/easily use the oauth token to do that?

I could use a pointer to be on the right track, as you know implementing the auth mechanism is quite important and I couldn't find a guide describing good practices.


问:
argparse args.accumulate isn't being recognised as a valid attribute in Python
Context:
I am attempting to make a Youtube command line video downloader as a small project for myself to understand python better. I am using argparse to get the args from the command line.

Issue: When I ran it the error came up AttributeError: 'Namespace' object has no attribute 'accumulate' How can I fix this?

Python Version: 3.10

OS: Windows 11

```<code>...

parser = argparse.ArgumentParser(description='Download a Youtube video')
parser.add_argument('video_url', type=str, help='Type a URL for a YouTube video.')
parser.add_argument('save_dir', type=str, help='Type the directory you want the YouTube video to be saved to be saves.')
args = parser.parse_args()

if __name__ == '__main__':
    video_url = args.accumulate(args.video_url)
    save_dir = args.accumulate(args.save_dir)
    print(video_url, save_dir)
</code>```

I am doing this because it said this in the docs https://docs.python.org/3.10/library/argparse.html

Body:
Context:
I am attempting to make a Youtube command line video downloader as a small project for myself to understand python better. I am using argparse to get the args from the command line.

Issue: When I ran it the error came up AttributeError: 'Namespace' object has no attribute 'accumulate' How can I fix this?

Python Version: 3.10

OS: Windows 11

...

parser = argparse.ArgumentParser(description='Download a Youtube video')
parser.add_argument('video_url', type=str, help='Type a URL for a YouTube video.')
parser.add_argument('save_dir', type=str, help='Type the directory you want the YouTube video to be saved to be saves.')
args = parser.parse_args()

if __name__ == '__main__':
    video_url = args.accumulate(args.video_url)
    save_dir = args.accumulate(args.save_dir)
    print(video_url, save_dir)

I am doing this because it said this in the docs https://docs.python.org/3.10/library/argparse.html


问:
saving and loading a huggingface model in Tensorflow
I created a Huggingface model and a function to make predictions. Here is the prediction function I wrote (which is working fine)

```<code>def predict_proba(text_list, model, tokenizer):
    #tokenize the text
    encodings = tokenizer(text_list,
                          max_length=512,
                          truncation=True,
                          padding=True)
    #transform to tf.Dataset
    dataset = tf.data.Dataset.from_tensor_slices((dict(encodings)))
    #predict
    preds = model.predict(dataset.batch(1))['logits']

    #transform to array with probabilities
    res = tf.nn.softmax(preds, axis=1).numpy()

    return res
</code>```

Now If do

```<code>pred = predict_proba(x_test_list, model, tokenizer)
</code>```

Its working fine . But when I save the model

```<code>path = '/Shared/P1-Prediction/savedmodels'
model.save(path)
</code>```

And then I load it at a later point of time to make predictions

```<code>loadedmodel = keras.models.load_model(path)
</code>```

and now If I try to make predictions using this new loadedmodel

```<code>pred = predict_proba(x_test_list, loadedmodel , tokenizer)
</code>```

I am getting the below error. I dont understand why. this loadedmodel and model are exact same things . infact the model.summary() and loadedmodel.summary() look exactly the same. The error I get is as follows and I don't get this error with the original model.I am not able to understand this error and any help is highly highly appreciated.

```<code>ValueError: in user code:

    File "/databricks/python/lib/python3.8/site-packages/keras/engine/training.py", line 1801, in predict_function  *
        return step_function(self, iterator)
    File "/databricks/python/lib/python3.8/site-packages/keras/engine/training.py", line 1790, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "/databricks/python/lib/python3.8/site-packages/keras/engine/training.py", line 1783, in run_step  **
        outputs = model.predict_step(data)
    File "/databricks/python/lib/python3.8/site-packages/keras/engine/training.py", line 1751, in predict_step
        return self(x, training=False)
    File "/databricks/python/lib/python3.8/site-packages/keras/utils/traceback_utils.py", line 67, in error_handler
        raise e.with_traceback(filtered_tb) from None

    ValueError: Exception encountered when calling layer "tf_distil_bert_for_sequence_classification" (type TFDistilBertForSequenceClassification).

    Could not find matching concrete function to call loaded from the SavedModel. Got:
      Positional arguments (9 total):
        * {'attention_mask': <tf.Tensor 'input_ids:0' shape=(None, 512) dtype=int32>, 'input_ids': <tf.Tensor 'input_ids_1:0' shape=(None, 512) dtype=int32>}
        * None
        * None
        * None
        * None
        * None
        * None
        * None
        * False
      Keyword arguments: {}

     Expected these arguments to match one of the following 2 option(s):

    Option 1:
      Positional arguments (9 total):
        * {'input_ids': TensorSpec(shape=(None, 5), dtype=tf.int32, name='input_ids/input_ids')}
        * None
        * None
        * None
        * None
        * None
        * None
        * None
        * False
      Keyword arguments: {}

    Option 2:
      Positional arguments (9 total):
        * {'input_ids': TensorSpec(shape=(None, 5), dtype=tf.int32, name='input_ids/input_ids')}
        * None
        * None
        * None
        * None
        * None
        * None
        * None
        * True
      Keyword arguments: {}

    Call arguments received:
      • args=({'attention_mask': 'tf.Tensor(shape=(None, 512), dtype=int32)', 'input_ids': 'tf.Tensor(shape=(None, 512), dtype=int32)'},)
      • kwargs={'training': 'False'}
</code>```

I really wish I can make this issue more reproducible by sharing the code which I can but without the data it wont be reproducible. Any help is really appreciated.

Body:
I created a Huggingface model and a function to make predictions. Here is the prediction function I wrote (which is working fine)

def predict_proba(text_list, model, tokenizer):
    #tokenize the text
    encodings = tokenizer(text_list,
                          max_length=512,
                          truncation=True,
                          padding=True)
    #transform to tf.Dataset
    dataset = tf.data.Dataset.from_tensor_slices((dict(encodings)))
    #predict
    preds = model.predict(dataset.batch(1))['logits']

    #transform to array with probabilities
    res = tf.nn.softmax(preds, axis=1).numpy()

    return res

Now If do

pred = predict_proba(x_test_list, model, tokenizer)

Its working fine . But when I save the model

path = '/Shared/P1-Prediction/savedmodels'
model.save(path)

And then I load it at a later point of time to make predictions

loadedmodel = keras.models.load_model(path)

and now If I try to make predictions using this new loadedmodel

pred = predict_proba(x_test_list, loadedmodel , tokenizer)

I am getting the below error. I dont understand why. this loadedmodel and model are exact same things . infact the model.summary() and loadedmodel.summary() look exactly the same. The error I get is as follows and I don't get this error with the original model.I am not able to understand this error and any help is highly highly appreciated.

ValueError: in user code:

    File "/databricks/python/lib/python3.8/site-packages/keras/engine/training.py", line 1801, in predict_function  *
        return step_function(self, iterator)
    File "/databricks/python/lib/python3.8/site-packages/keras/engine/training.py", line 1790, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "/databricks/python/lib/python3.8/site-packages/keras/engine/training.py", line 1783, in run_step  **
        outputs = model.predict_step(data)
    File "/databricks/python/lib/python3.8/site-packages/keras/engine/training.py", line 1751, in predict_step
        return self(x, training=False)
    File "/databricks/python/lib/python3.8/site-packages/keras/utils/traceback_utils.py", line 67, in error_handler
        raise e.with_traceback(filtered_tb) from None

    ValueError: Exception encountered when calling layer "tf_distil_bert_for_sequence_classification" (type TFDistilBertForSequenceClassification).

    Could not find matching concrete function to call loaded from the SavedModel. Got:
      Positional arguments (9 total):
        * {'attention_mask': <tf.Tensor 'input_ids:0' shape=(None, 512) dtype=int32>, 'input_ids': <tf.Tensor 'input_ids_1:0' shape=(None, 512) dtype=int32>}
        * None
        * None
        * None
        * None
        * None
        * None
        * None
        * False
      Keyword arguments: {}

     Expected these arguments to match one of the following 2 option(s):

    Option 1:
      Positional arguments (9 total):
        * {'input_ids': TensorSpec(shape=(None, 5), dtype=tf.int32, name='input_ids/input_ids')}
        * None
        * None
        * None
        * None
        * None
        * None
        * None
        * False
      Keyword arguments: {}

    Option 2:
      Positional arguments (9 total):
        * {'input_ids': TensorSpec(shape=(None, 5), dtype=tf.int32, name='input_ids/input_ids')}
        * None
        * None
        * None
        * None
        * None
        * None
        * None
        * True
      Keyword arguments: {}

    Call arguments received:
      • args=({'attention_mask': 'tf.Tensor(shape=(None, 512), dtype=int32)', 'input_ids': 'tf.Tensor(shape=(None, 512), dtype=int32)'},)
      • kwargs={'training': 'False'}

I really wish I can make this issue more reproducible by sharing the code which I can but without the data it wont be reproducible. Any help is really appreciated.


问:
Permission denied when run docker
I recently moved docker files from /var/lib/docker to /home/username/.docker. After that, when running docker, an error began to occur:
WARNING: Error loading config file: /home/username/.docker/config.json: open /home/username/.docker/config.json: permission denied

The problem is solved as follows:

```<code>sudo chown "$USER":"$USER" /home/"$USER"/.docker -R
sudo chmod g+rwx "/home/$USER/.docker" -R
</code>```

But when restart the docker service or rebooting system, the rights to the .docker folder automatically changes to the root user and the error is repeated.

Title: Permission denied when run docker

Body:
I recently moved docker files from /var/lib/docker to /home/username/.docker. After that, when running docker, an error began to occur:
WARNING: Error loading config file: /home/username/.docker/config.json: open /home/username/.docker/config.json: permission denied

The problem is solved as follows:

sudo chown "$USER":"$USER" /home/"$USER"/.docker -R
sudo chmod g+rwx "/home/$USER/.docker" -R

But when restart the docker service or rebooting system, the rights to the .docker folder automatically changes to the root user and the error is repeated.


问:
Error using the module discord.py on fedora
hello i have this error when i use discord.py with python version 3.11:

```<code>  discord.client logging in using static token
Traceback (most recent call last):
  File "/home/adam/.local/lib/python3.11/site-packages/discord/http.py", line 801, in static_login
    data = await self.request(Route('GET', '/users/@me'))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/adam/.local/lib/python3.11/site-packages/discord/http.py", line 744, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/adam/Documents/programe/import discord.py", line 20, in <module>
    client.run('6KhBCVw8fSwljDww6aoo_hgFKl6Ij4Rl')
  File "/home/adam/.local/lib/python3.11/site-packages/discord/client.py", line 828, in run
    asyncio.run(runner())
  File "/usr/lib64/python3.11/asyncio/runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.11/asyncio/runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.11/asyncio/base_events.py", line 650, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "/home/adam/.local/lib/python3.11/site-packages/discord/client.py", line 817, in runner
    await self.start(token, reconnect=reconnect)
  File "/home/adam/.local/lib/python3.11/site-packages/discord/client.py", line 745, in start
    await self.login(token)
  File "/home/adam/.local/lib/python3.11/site-packages/discord/client.py", line 580, in login
    data = await self.http.static_login(token)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/adam/.local/lib/python3.11/site-packages/discord/http.py", line 805, in static_login
    raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
</code>```

the English language is not my native language I apologize for the language errors. Thank you in advance for your response.

I already tested the pip install -U yarl command and nothing works after

Body:
hello i have this error when i use discord.py with python version 3.11:

  discord.client logging in using static token
Traceback (most recent call last):
  File "/home/adam/.local/lib/python3.11/site-packages/discord/http.py", line 801, in static_login
    data = await self.request(Route('GET', '/users/@me'))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/adam/.local/lib/python3.11/site-packages/discord/http.py", line 744, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/adam/Documents/programe/import discord.py", line 20, in <module>
    client.run('6KhBCVw8fSwljDww6aoo_hgFKl6Ij4Rl')
  File "/home/adam/.local/lib/python3.11/site-packages/discord/client.py", line 828, in run
    asyncio.run(runner())
  File "/usr/lib64/python3.11/asyncio/runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.11/asyncio/runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.11/asyncio/base_events.py", line 650, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "/home/adam/.local/lib/python3.11/site-packages/discord/client.py", line 817, in runner
    await self.start(token, reconnect=reconnect)
  File "/home/adam/.local/lib/python3.11/site-packages/discord/client.py", line 745, in start
    await self.login(token)
  File "/home/adam/.local/lib/python3.11/site-packages/discord/client.py", line 580, in login
    data = await self.http.static_login(token)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/adam/.local/lib/python3.11/site-packages/discord/http.py", line 805, in static_login
    raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.

the English language is not my native language I apologize for the language errors. Thank you in advance for your response.

I already tested the pip install -U yarl command and nothing works after


问:
MapStruct DTO->Entity mapping with OneToMany as FK in DTO
Hi I'm pretty new to Java and Spring Boot. I have an API which uses 3 entities:

```<code>@Entity
public class Account {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(updatable = false, nullable = false)
    int id;

    // Other fields

    @Column(nullable = false)
    String accountId;

    @OneToMany(mappedBy = "account", cascade = CascadeType.ALL)
    @JsonBackReference
    List<StockMarketTransaction> transactions;

    @ManyToMany
    @JsonBackReference
    Set<StockMarketSubject> currentlyOwnedSubjects;

    public int getId() {
        return id;
    }

    public String getAccountId() {
        return accountId;
    }

    public void setAccountId(String accountId) {
        this.accountId = accountId;
    }

    public List<StockMarketTransaction> getTransactions() {
        return transactions;
    }

    public void setTransactions(List<StockMarketTransaction> transactions) {
        this.transactions = transactions;
    }

    public void addTransaction(StockMarketTransaction transaction){
        this.transactions.add(transaction);
    }

    public Set<StockMarketSubject> getCurrentlyOwnedSubjects() {
        return currentlyOwnedSubjects;
    }

    public void setCurrentlyOwnedSubjects(Set<StockMarketSubject> currentlyOwnedSubjects) {
        this.currentlyOwnedSubjects = currentlyOwnedSubjects;
    }
}
</code>```
```<code>@Entity
public class StockMarketSubject{

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

    // Other fields

    @OneToMany(mappedBy = "subject")
    @JsonBackReference
    List<StockMarketTransaction> transactions;

    @ManyToMany
    @JsonBackReference
    Set<Account> holdingAccounts;

    public int getId() {
        return id;
    }

    public List<StockMarketTransaction> getTransactions() {
        return transactions;
    }

    public void setTransactions(List<StockMarketTransaction> transactions) {
        this.transactions = transactions;
    }

    public void addTransaction(StockMarketTransaction transaction){
        this.transactions.add(transaction);
    }

    public Set<Account> getHoldingAccounts() {
        return holdingAccounts;
    }

    public void setHoldingAccounts(Set<Account> holdingAccounts) {
        this.holdingAccounts = holdingAccounts;
    }
}
</code>```
```<code>@Entity
public class StockMarketTransaction{

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

    // Other fields

    @ManyToOne
    @JsonManagedReference
    StockMarketSubject subject;

    @ManyToOne(cascade = CascadeType.ALL)
    @JsonManagedReference
    Account account;

    public Long getId() {
        return id;
    }

    public StockMarketSubject getSubject() {
        return subject;
    }

    public void setSubject(StockMarketSubject subject) {
        this.subject = subject;
    }

    public Account getAccount() {
        return account;
    }

    public void setAccount(Account account) {
        this.account = account;
    }
}
</code>```

I'm also using DTO to transfer data between service layer (fetch/create/update) and controllers. GET endpoints return DTO structure with data and POST endpoints use DTO as @RequestBody in order to capture user data sent via request.

For Transaction entity I use this DTO with MapStruct Mapper:

```<code>public class StockMarketTransactionDTO {
    @Schema(accessMode = Schema.AccessMode.READ_ONLY)
    Long id;

    // Other fields

    @NotEmpty
    @PositiveOrZero
    int subjectId;
    @NotEmpty
    @PositiveOrZero
    int accountId;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public int getSubjectId() {
        return subjectId;
    }

    public void setSubjectId(int subjectId) {
        this.subjectId = subjectId;
    }

    public int getAccountId() {
        return accountId;
    }

    public void setAccountId(int accountId) {
        this.accountId = accountId;
    }

    public StockMarketTransactionDTO(){}
}

@Mapper
public interface StockMarketTransactionMapper {

    StockMarketTransactionMapper INSTANCE = Mappers.getMapper(StockMarketTransactionMapper.class);

    @Mapping(source = "subject.id", target = "subjectId")
    @Mapping(source = "account.id", target = "accountId")
    StockMarketTransactionDTO stockMarketTransactionToStockMarketTransactionDTO(StockMarketTransaction transaction);

    @InheritInverseConfiguration
    StockMarketTransaction stockMarketTransactionDTOToStockMarketTransaction(StockMarketTransactionDTO dto);

}
</code>```

Insted of exchanging whole objects related to transaction I want to only attach their ID (PK) to DTO. Now when I use this mapper to create transaction DTO from entity and return it with response it works perfectly fine. It gives users a valid ID of related subject and account. But the issue I have is creating entity from DTO filled with user data. With this payload:

```<code>{
  "transactionDate": "2022-12-13T17:15:47.023Z",
  "pricePerOne": 20,
  "volume": 20,
  "operationType": "BUY",
  "description": {
    "advantages": "string",
    "disadvantages": "string",
    "reason": "string"
  },  // Other fields
  "subjectId": 1,
  "accountId": 1
}
</code>```

I get internal error:

```<code>org.hibernate.PropertyValueException: not-null property references a null or transient value : com.rcbg.afku.investmentdiary.brokeraccounts.entities.Account.accountId
</code>```

I tried find any efficient and proper way to map object like this with MapStruct but I failed.
Is there any possibility to handle this with @Mapping annotation, or should I create my own implementation of mapping method?

Body:
Hi I'm pretty new to Java and Spring Boot. I have an API which uses 3 entities:

@Entity
public class Account {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(updatable = false, nullable = false)
    int id;

    // Other fields

    @Column(nullable = false)
    String accountId;

    @OneToMany(mappedBy = "account", cascade = CascadeType.ALL)
    @JsonBackReference
    List<StockMarketTransaction> transactions;

    @ManyToMany
    @JsonBackReference
    Set<StockMarketSubject> currentlyOwnedSubjects;

    public int getId() {
        return id;
    }

    public String getAccountId() {
        return accountId;
    }

    public void setAccountId(String accountId) {
        this.accountId = accountId;
    }

    public List<StockMarketTransaction> getTransactions() {
        return transactions;
    }

    public void setTransactions(List<StockMarketTransaction> transactions) {
        this.transactions = transactions;
    }

    public void addTransaction(StockMarketTransaction transaction){
        this.transactions.add(transaction);
    }

    public Set<StockMarketSubject> getCurrentlyOwnedSubjects() {
        return currentlyOwnedSubjects;
    }

    public void setCurrentlyOwnedSubjects(Set<StockMarketSubject> currentlyOwnedSubjects) {
        this.currentlyOwnedSubjects = currentlyOwnedSubjects;
    }
}

@Entity
public class StockMarketSubject{

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

    // Other fields

    @OneToMany(mappedBy = "subject")
    @JsonBackReference
    List<StockMarketTransaction> transactions;

    @ManyToMany
    @JsonBackReference
    Set<Account> holdingAccounts;

    public int getId() {
        return id;
    }

    public List<StockMarketTransaction> getTransactions() {
        return transactions;
    }

    public void setTransactions(List<StockMarketTransaction> transactions) {
        this.transactions = transactions;
    }

    public void addTransaction(StockMarketTransaction transaction){
        this.transactions.add(transaction);
    }

    public Set<Account> getHoldingAccounts() {
        return holdingAccounts;
    }

    public void setHoldingAccounts(Set<Account> holdingAccounts) {
        this.holdingAccounts = holdingAccounts;
    }
}

@Entity
public class StockMarketTransaction{

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

    // Other fields

    @ManyToOne
    @JsonManagedReference
    StockMarketSubject subject;

    @ManyToOne(cascade = CascadeType.ALL)
    @JsonManagedReference
    Account account;

    public Long getId() {
        return id;
    }

    public StockMarketSubject getSubject() {
        return subject;
    }

    public void setSubject(StockMarketSubject subject) {
        this.subject = subject;
    }

    public Account getAccount() {
        return account;
    }

    public void setAccount(Account account) {
        this.account = account;
    }
}

I'm also using DTO to transfer data between service layer (fetch/create/update) and controllers. GET endpoints return DTO structure with data and POST endpoints use DTO as @RequestBody in order to capture user data sent via request.

For Transaction entity I use this DTO with MapStruct Mapper:

public class StockMarketTransactionDTO {
    @Schema(accessMode = Schema.AccessMode.READ_ONLY)
    Long id;

    // Other fields

    @NotEmpty
    @PositiveOrZero
    int subjectId;
    @NotEmpty
    @PositiveOrZero
    int accountId;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public int getSubjectId() {
        return subjectId;
    }

    public void setSubjectId(int subjectId) {
        this.subjectId = subjectId;
    }

    public int getAccountId() {
        return accountId;
    }

    public void setAccountId(int accountId) {
        this.accountId = accountId;
    }

    public StockMarketTransactionDTO(){}
}

@Mapper
public interface StockMarketTransactionMapper {

    StockMarketTransactionMapper INSTANCE = Mappers.getMapper(StockMarketTransactionMapper.class);

    @Mapping(source = "subject.id", target = "subjectId")
    @Mapping(source = "account.id", target = "accountId")
    StockMarketTransactionDTO stockMarketTransactionToStockMarketTransactionDTO(StockMarketTransaction transaction);

    @InheritInverseConfiguration
    StockMarketTransaction stockMarketTransactionDTOToStockMarketTransaction(StockMarketTransactionDTO dto);

}

Insted of exchanging whole objects related to transaction I want to only attach their ID (PK) to DTO. Now when I use this mapper to create transaction DTO from entity and return it with response it works perfectly fine. It gives users a valid ID of related subject and account. But the issue I have is creating entity from DTO filled with user data. With this payload:

{
  "transactionDate": "2022-12-13T17:15:47.023Z",
  "pricePerOne": 20,
  "volume": 20,
  "operationType": "BUY",
  "description": {
    "advantages": "string",
    "disadvantages": "string",
    "reason": "string"
  },  // Other fields
  "subjectId": 1,
  "accountId": 1
}

I get internal error:

org.hibernate.PropertyValueException: not-null property references a null or transient value : com.rcbg.afku.investmentdiary.brokeraccounts.entities.Account.accountId

I tried find any efficient and proper way to map object like this with MapStruct but I failed.
Is there any possibility to handle this with @Mapping annotation, or should I create my own implementation of mapping method?


问:
How do I leave a comment (phpdoc) at the end of a line when forming in PhpStorm?
Sometimes it is necessary to leave a link or other information at the end of a line, especially relevant in configuration arrays. But PhpStorm moves this comment to a new line.

I want to see like this

[
    'configFoo' => ['some' => true], /** @see Foo::some */
    'configBar' => ['baz' => true] /** @see Bar::baz */
]

//...
$a = 42; /** @link https://fakewikipedia.com/The_Answer_to_the_Ultimate_Question_of_Life */
$b = 1; /** @see ExternalDocumentation */
```
<p>But PhpStorm does as follows</p>
<pre class="lang-php prettyprint-override"><code>[
    'configFoo' => ['some' => true],
    /** @see Foo::some */
    'configBar' => ['baz' => true]
    /** @see Bar::baz */
]

//...
$a = 42;
/** @link https://fakewikipedia.com/The_Answer_to_the_Ultimate_Question_of_Life */
$b = 1;
/** @see ExternalDocumentation */
</code>```

I can't find an option to disable this formatting. Is it possible?

Body:
Sometimes it is necessary to leave a link or other information at the end of a line, especially relevant in configuration arrays. But PhpStorm moves this comment to a new line.

I want to see like this

[
    'configFoo' => ['some' => true], /** @see Foo::some */
    'configBar' => ['baz' => true] /** @see Bar::baz */
]

//...
$a = 42; /** @link https://fakewikipedia.com/The_Answer_to_the_Ultimate_Question_of_Life */
$b = 1; /** @see ExternalDocumentation */

But PhpStorm does as follows

[
    'configFoo' => ['some' => true],
    /** @see Foo::some */
    'configBar' => ['baz' => true]
    /** @see Bar::baz */
]

//...
$a = 42;
/** @link https://fakewikipedia.com/The_Answer_to_the_Ultimate_Question_of_Life */
$b = 1;
/** @see ExternalDocumentation */

I can't find an option to disable this formatting. Is it possible?


问:
Proper way to send JWT token via http client
I am looking for a way to send the JWT token in the header via the HTTP client but could not figure out the options, and below is the code in the startup file.

```<code>    public void ConfigureServices(IServiceCollection services)
    {
        ..........

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.Authority = $"{Configuration["ApiClientAuth:Authority"]}/v2.0";
            options.Audience = Configuration["ApiClientAuth:ClientId"];
            .....
            options.SaveToken = true;
        });

        //Using this middleware delegating handler to send the token but wondering whether this is the correct approach.
        services.AddTransient<TokenHandler>();

        var stitchingServices = new List<StitchingService>{ new (....), new (....)};

        stitchingServices.ForEach(x => services.AddHttpClient(x.Name, (sp, client) =>
        {
            client.BaseAddress = new Uri(x.GraphqlUrl);
        }).AddHttpMessageHandler<TokenHandler>());

         // For the above HTTP clients, I need to send a JWT token via the HTTP client header
        var hotChocolateServices = services
                                   .AddGraphQLServer()
                                   .AddAuthorization()
                                   .........

        if (WebHostEnvironment.IsDevelopment())
        {
            hotChocolateServices
                .AddInstrumentation()
                .AddApolloTracing();
        }
    }
</code>```

Below is the middleware delegating handler code

```<code>public class TokenHandler : DelegatingHandler
{
    private readonly IHttpContextAccessor accessor;
    public TokenHandler(IHttpContextAccessor accessor) => this.accessor = accessor;

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var accessToken = await accessor.HttpContext.GetTokenAsync("access_token");
        request.Headers.Authorization =
            new AuthenticationHeaderValue("Bearer", accessToken);
        return await base.SendAsync(request, cancellationToken);
    }
}
</code>```

Is this approach delicate, or is there any straightforward approach to sending the token via HTTP client? The access token is getting null when I debug this delegating handler.

Body:
I am looking for a way to send the JWT token in the header via the HTTP client but could not figure out the options, and below is the code in the startup file.

    public void ConfigureServices(IServiceCollection services)
    {
        ..........

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.Authority = $"{Configuration["ApiClientAuth:Authority"]}/v2.0";
            options.Audience = Configuration["ApiClientAuth:ClientId"];
            .....
            options.SaveToken = true;
        });

        //Using this middleware delegating handler to send the token but wondering whether this is the correct approach.
        services.AddTransient<TokenHandler>();

        var stitchingServices = new List<StitchingService>{ new (....), new (....)};

        stitchingServices.ForEach(x => services.AddHttpClient(x.Name, (sp, client) =>
        {
            client.BaseAddress = new Uri(x.GraphqlUrl);
        }).AddHttpMessageHandler<TokenHandler>());

         // For the above HTTP clients, I need to send a JWT token via the HTTP client header
        var hotChocolateServices = services
                                   .AddGraphQLServer()
                                   .AddAuthorization()
                                   .........

        if (WebHostEnvironment.IsDevelopment())
        {
            hotChocolateServices
                .AddInstrumentation()
                .AddApolloTracing();
        }
    }

Below is the middleware delegating handler code

public class TokenHandler : DelegatingHandler
{
    private readonly IHttpContextAccessor accessor;
    public TokenHandler(IHttpContextAccessor accessor) => this.accessor = accessor;

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var accessToken = await accessor.HttpContext.GetTokenAsync("access_token");
        request.Headers.Authorization =
            new AuthenticationHeaderValue("Bearer", accessToken);
        return await base.SendAsync(request, cancellationToken);
    }
}

Is this approach delicate, or is there any straightforward approach to sending the token via HTTP client? The access token is getting null when I debug this delegating handler.


问:
LSTM giving same prediction for every sample
I am trying to train an LSTM network on a music dataset to create a model that can identify pitches. There are 45 different labels (pitches) that I'm trying to classify a given sample with. However, every label has the same prediction value no matter the sample (i.e. all labels #1 have the same value, all labels #2, ...)

Our X_train_RNN is 16170x20x2688 (each of our 16170 samples has a sequence length of 20), and our y_train_RNN is a 16170x45 (each of our 16170 samples have a 45-dimensional vector containing real numbers). We then say that a negative real number corresponds to that pitch not being there, and a positive real number corresponds to that pitch being there.

Here's the LSTM in PyTorch:

```<code>class LSTM1(nn.Module):
    def __init__(self):
        super(LSTM1, self).__init__()
        self.num_classes = 45 #number of classes
        self.num_layers = 1 #number of layers
        self.input_size = 84*32 #input size
        self.hidden_size = 100 #hidden state
        self.seq_length = 20 #sequence length

        self.lstm = nn.LSTM(input_size=self.input_size, hidden_size=self.hidden_size,
                          num_layers=self.num_layers, batch_first=True) #lstm
        self.fc_1 =  nn.Linear(self.hidden_size, 128) #fully connected 1
        self.fc = nn.Linear(128, self.num_classes) #fully connected last layer
        self.relu = nn.ReLU()

    def forward(self,x):
        h_0 = Variable(torch.zeros(self.num_layers, x.size(0), self.hidden_size)) #hidden state
        c_0 = Variable(torch.zeros(self.num_layers, x.size(0), self.hidden_size)) #internal state
        # Propagate input through LSTM
        output, (hn, cn) = self.lstm(x, (h_0, c_0)) #lstm with input, hidden, and internal state
        hn = hn.view(-1, self.hidden_size) #reshaping the data for Dense layer next
        out = self.relu(hn)
        out = self.fc_1(out) #first Dense
        out = self.relu(out) #relu
        out = self.fc(out) #Final Output
        return out
</code>```

And here's how we use it:

```<code>from torch.nn.modules.loss import BCEWithLogitsLoss
epochs = 5
model = LSTM1()
criterion = BCEWithLogitsLoss()
optimizer = optim.Adam(model.parameters(), lr=1e-7)
train_loss = []
# training iteration
for epoch in range(epochs):
    running_loss = 0
    for itr, (image, label) in enumerate(trainloader):
        #print("image: " + str(image.shape))
        # zero gradient
        optimizer.zero_grad()
        # forward path
        y_predicted = model(image)
        #print("label: " + str(label.shape))
        #print("y_predicted: " + str(y_predicted.shape))
        loss = criterion(y_predicted, label)
        running_loss += loss.item()
        # backpropagating
        loss.backward()
        # optimizes the weights
        optimizer.step()
    with torch.no_grad():
      totalPos = 0
      for i in range(45):
        totalPos += np.count_nonzero(y_predicted.numpy()[:, i] > 0)
      print("num of positive: " + str(totalPos))
    train_loss.append(running_loss)
    print(f'epoch: {epoch+1}, loss: {running_loss:.4f}')
</code>```

But afterwards when we get our model and get our predictions...

```<code>with torch.no_grad():
  X = torch.tensor(X_test_RNN).float()
  testPreds = model2(X)
</code>```

testPreds has the same exact prediction for every value in a given column; no matter the sample. This even happens by the first or second epoch it seems. What could be going on?

Body:
I am trying to train an LSTM network on a music dataset to create a model that can identify pitches. There are 45 different labels (pitches) that I'm trying to classify a given sample with. However, every label has the same prediction value no matter the sample (i.e. all labels #1 have the same value, all labels #2, ...)

Our X_train_RNN is 16170x20x2688 (each of our 16170 samples has a sequence length of 20), and our y_train_RNN is a 16170x45 (each of our 16170 samples have a 45-dimensional vector containing real numbers). We then say that a negative real number corresponds to that pitch not being there, and a positive real number corresponds to that pitch being there.

Here's the LSTM in PyTorch:

class LSTM1(nn.Module):
    def __init__(self):
        super(LSTM1, self).__init__()
        self.num_classes = 45 #number of classes
        self.num_layers = 1 #number of layers
        self.input_size = 84*32 #input size
        self.hidden_size = 100 #hidden state
        self.seq_length = 20 #sequence length

        self.lstm = nn.LSTM(input_size=self.input_size, hidden_size=self.hidden_size,
                          num_layers=self.num_layers, batch_first=True) #lstm
        self.fc_1 =  nn.Linear(self.hidden_size, 128) #fully connected 1
        self.fc = nn.Linear(128, self.num_classes) #fully connected last layer
        self.relu = nn.ReLU()

    def forward(self,x):
        h_0 = Variable(torch.zeros(self.num_layers, x.size(0), self.hidden_size)) #hidden state
        c_0 = Variable(torch.zeros(self.num_layers, x.size(0), self.hidden_size)) #internal state
        # Propagate input through LSTM
        output, (hn, cn) = self.lstm(x, (h_0, c_0)) #lstm with input, hidden, and internal state
        hn = hn.view(-1, self.hidden_size) #reshaping the data for Dense layer next
        out = self.relu(hn)
        out = self.fc_1(out) #first Dense
        out = self.relu(out) #relu
        out = self.fc(out) #Final Output
        return out

And here's how we use it:

from torch.nn.modules.loss import BCEWithLogitsLoss
epochs = 5
model = LSTM1()
criterion = BCEWithLogitsLoss()
optimizer = optim.Adam(model.parameters(), lr=1e-7)
train_loss = []
# training iteration
for epoch in range(epochs):
    running_loss = 0
    for itr, (image, label) in enumerate(trainloader):
        #print("image: " + str(image.shape))
        # zero gradient
        optimizer.zero_grad()
        # forward path
        y_predicted = model(image)
        #print("label: " + str(label.shape))
        #print("y_predicted: " + str(y_predicted.shape))
        loss = criterion(y_predicted, label)
        running_loss += loss.item()
        # backpropagating
        loss.backward()
        # optimizes the weights
        optimizer.step()
    with torch.no_grad():
      totalPos = 0
      for i in range(45):
        totalPos += np.count_nonzero(y_predicted.numpy()[:, i] > 0)
      print("num of positive: " + str(totalPos))
    train_loss.append(running_loss)
    print(f'epoch: {epoch+1}, loss: {running_loss:.4f}')

But afterwards when we get our model and get our predictions...

with torch.no_grad():
  X = torch.tensor(X_test_RNN).float()
  testPreds = model2(X)

testPreds has the same exact prediction for every value in a given column; no matter the sample. This even happens by the first or second epoch it seems. What could be going on?


问:
How to get printThis.js to run a script after print or if print was cancelled
I'm trying to get PrintThis.js to run a script after printing, even if the print dialog is cancelled.
In my specific instance, I have to change the colspan on a TD before the print, and want to put it back when done.

Here is the code I've tried but it has no discernable effect at all.

```<code>$("#cInfoSpan").attr("colspan",4);
$(".printSpan").attr("colspan",2);

u=uniqueNumber();
$("#chemOrderWrapper").printThis({
    importCSS: false,
    loadCSS: "../css/printBlankChem.css?ver="+u,
    afterPrint:function(){
                $("#cInfoSpan").attr("colspan",5);
                $(".printSpan").attr("colspan",1);
    },
    beforePrintEvent:function(){
            console.log( "before pre");
    }
});
</code>```

Body:
I'm trying to get PrintThis.js to run a script after printing, even if the print dialog is cancelled.
In my specific instance, I have to change the colspan on a TD before the print, and want to put it back when done.

Here is the code I've tried but it has no discernable effect at all.

$("#cInfoSpan").attr("colspan",4);
$(".printSpan").attr("colspan",2);

u=uniqueNumber();
$("#chemOrderWrapper").printThis({
    importCSS: false,
    loadCSS: "../css/printBlankChem.css?ver="+u,
    afterPrint:function(){
                $("#cInfoSpan").attr("colspan",5);
                $(".printSpan").attr("colspan",1);
    },
    beforePrintEvent:function(){
            console.log( "before pre");
    }
});


问:
TypeError: Cannot read properties of undefined (reading '_ref')
I'm getting the following error  when trying to filter products by category. Not exactly sure what I am doing wrong...

// index.tsx

```<code>const Home = ({ categories, products }: Props) => {
  console.log(products);

  const showProducts = (category: number) => {
    return products
      .filter((product) => product.category._ref === categories[category]._id)
      .map((product) => <Product product={product} key={product._id} />); // filters products by category
  };

</code>```

Link to github repo https://github.com/angelDova/Apple

Any help would be appreciated, thank you!

Body:
I'm getting the following error  when trying to filter products by category. Not exactly sure what I am doing wrong...

// index.tsx

const Home = ({ categories, products }: Props) => {
  console.log(products);

  const showProducts = (category: number) => {
    return products
      .filter((product) => product.category._ref === categories[category]._id)
      .map((product) => <Product product={product} key={product._id} />); // filters products by category
  };

Link to github repo https://github.com/angelDova/Apple

Any help would be appreciated, thank you!