问:
R: using namespace in server file in shiny?
In my shinyApp, I need to update some input (in UI) based on user's input (server).

If I don't use namespace in server file, the code does not work. When I introduced namespace, it works as expected.

Below is my minimum example:

The app allows users to delete or undo certain columns of their uploaded data. To make the example simpler, I used a default dataset here.

Note: I added line numbers in this piece of code to help explain the code.

You can copy another identical code without line number to run in your PC.

See line 18 and 33 where I added namespace in server file.

My question is that: Is it Ok to use namespace in server file? Is my way correct and if there are other suggested/correct way to do it?

1. choice_ui <- function(id) {
2.   ns <- NS(id)
3.   tagList(
4.     sidebarPanel(
5.     uiOutput(outputId = ns("selectColumn"), label = "Select Columns to delete"),
6.     actionButton(inputId = ns("removeCol"), label = "Remove"),
7.     actionButton(inputId = ns("undoCol"), label = "Undo")
8.     ),
9.     mainPanel(
10.     dataTableOutput(outputId = ns("rawView")),
11.     dataTableOutput(outputId = ns("processView")),
12.     textOutput(outputId = ns("count"))
13.     )
14.   )
15. }
16.
17. choice_server <- function(id, r) {
18.   ns <- NS(id) ## use namespace here
19.   moduleServer(id, function(input, output, session){
20.       inputData <- reactive({
21.         r$data <- head(mtcars)
22.         return(head(mtcars))
23.         })
24.
25.       output$rawView <- renderDataTable({inputData()})
26.       output$processView <- renderDataTable({r$data})
27.       output$count <- renderText(ncol(r$data))
28.
29.       # remove or undo
30.       removecolumn <- function(df, nameofthecolumn){dplyr::select(df, -all_of(nameofthecolumn))}
31.
32.       output$selectColumn <- renderUI({
33.         selectInput(inputId = ns("selectColumn"), ## namespace
34.                     label = "Select sample(s) to remove",
35.                     choices = colnames(r$data)
36.                     )
37.         })
38.       observeEvent(input$removeCol, {
39.         r$data <- removecolumn(r$data, input$selectColumn)
40.         })
41.       observeEvent(input$undoCol, {
42.         r$data <- inputData()
43.         })
44.     }
45.   )
46. }
47.
48.
49. # Application
50. library(shiny)
51. app_ui <- function() {
52.   fluidPage(
53.     choice_ui("choice_ui_1")
54.   )
55. }
56.
57. app_server <- function(input, output, session) {
58.   r <- reactiveValues()
59.   choice_server("choice_ui_1", r = r)
60. }
61.
62. shinyApp(app_ui, app_server)
```
<p>Please copy the following code if you want to test it in your PC.</p>
<pre class="lang-r prettyprint-override"><code>choice_ui <- function(id) {
  ns <- NS(id)
  tagList(
    sidebarPanel(
      uiOutput(outputId = ns("selectColumn"), label = "Select Columns to delete"),
      actionButton(inputId = ns("removeCol"), label = "Remove"),
      actionButton(inputId = ns("undoCol"), label = "Undo")
    ),
    mainPanel(
      dataTableOutput(outputId = ns("rawView")),
      dataTableOutput(outputId = ns("processView")),
      textOutput(outputId = ns("count"))
    )
  )
}

choice_server <- function(id, r) {
  ns <- NS(id) ## use namespace here
  moduleServer(id, function(input, output, session){
    inputData <- reactive({
      r$data <- head(mtcars)
      return(head(mtcars))
    })

    output$rawView <- renderDataTable({inputData()})
    output$processView <- renderDataTable({r$data})
    output$count <- renderText(ncol(r$data))

    # remove or undo
    removecolumn <- function(df, nameofthecolumn){dplyr::select(df, -all_of(nameofthecolumn))}

    output$selectColumn <- renderUI({
      selectInput(inputId = ns("selectColumn"), ## namespace
                  label = "Select sample(s) to remove",
                  choices = colnames(r$data)
      )
    })
    observeEvent(input$removeCol, {
      r$data <- removecolumn(r$data, input$selectColumn)
    })
    observeEvent(input$undoCol, {
      r$data <- inputData()
    })
  }
  )
}

# Application
library(shiny)
app_ui <- function() {
  fluidPage(
    choice_ui("choice_ui_1")
  )
}

app_server <- function(input, output, session) {
  r <- reactiveValues()
  choice_server("choice_ui_1", r = r)
}

shinyApp(app_ui, app_server)
</code>```

Body:
In my shinyApp, I need to update some input (in UI) based on user's input (server).

If I don't use namespace in server file, the code does not work. When I introduced namespace, it works as expected.

Below is my minimum example:

The app allows users to delete or undo certain columns of their uploaded data. To make the example simpler, I used a default dataset here.

Note: I added line numbers in this piece of code to help explain the code.

You can copy another identical code without line number to run in your PC.

See line 18 and 33 where I added namespace in server file.

My question is that: Is it Ok to use namespace in server file? Is my way correct and if there are other suggested/correct way to do it?

1. choice_ui <- function(id) {
2.   ns <- NS(id)
3.   tagList(
4.     sidebarPanel(
5.     uiOutput(outputId = ns("selectColumn"), label = "Select Columns to delete"),
6.     actionButton(inputId = ns("removeCol"), label = "Remove"),
7.     actionButton(inputId = ns("undoCol"), label = "Undo")
8.     ),
9.     mainPanel(
10.     dataTableOutput(outputId = ns("rawView")),
11.     dataTableOutput(outputId = ns("processView")),
12.     textOutput(outputId = ns("count"))
13.     )
14.   )
15. }
16.
17. choice_server <- function(id, r) {
18.   ns <- NS(id) ## use namespace here
19.   moduleServer(id, function(input, output, session){
20.       inputData <- reactive({
21.         r$data <- head(mtcars)
22.         return(head(mtcars))
23.         })
24.
25.       output$rawView <- renderDataTable({inputData()})
26.       output$processView <- renderDataTable({r$data})
27.       output$count <- renderText(ncol(r$data))
28.
29.       # remove or undo
30.       removecolumn <- function(df, nameofthecolumn){dplyr::select(df, -all_of(nameofthecolumn))}
31.
32.       output$selectColumn <- renderUI({
33.         selectInput(inputId = ns("selectColumn"), ## namespace
34.                     label = "Select sample(s) to remove",
35.                     choices = colnames(r$data)
36.                     )
37.         })
38.       observeEvent(input$removeCol, {
39.         r$data <- removecolumn(r$data, input$selectColumn)
40.         })
41.       observeEvent(input$undoCol, {
42.         r$data <- inputData()
43.         })
44.     }
45.   )
46. }
47.
48.
49. # Application
50. library(shiny)
51. app_ui <- function() {
52.   fluidPage(
53.     choice_ui("choice_ui_1")
54.   )
55. }
56.
57. app_server <- function(input, output, session) {
58.   r <- reactiveValues()
59.   choice_server("choice_ui_1", r = r)
60. }
61.
62. shinyApp(app_ui, app_server)

Please copy the following code if you want to test it in your PC.

choice_ui <- function(id) {
  ns <- NS(id)
  tagList(
    sidebarPanel(
      uiOutput(outputId = ns("selectColumn"), label = "Select Columns to delete"),
      actionButton(inputId = ns("removeCol"), label = "Remove"),
      actionButton(inputId = ns("undoCol"), label = "Undo")
    ),
    mainPanel(
      dataTableOutput(outputId = ns("rawView")),
      dataTableOutput(outputId = ns("processView")),
      textOutput(outputId = ns("count"))
    )
  )
}

choice_server <- function(id, r) {
  ns <- NS(id) ## use namespace here
  moduleServer(id, function(input, output, session){
    inputData <- reactive({
      r$data <- head(mtcars)
      return(head(mtcars))
    })

    output$rawView <- renderDataTable({inputData()})
    output$processView <- renderDataTable({r$data})
    output$count <- renderText(ncol(r$data))

    # remove or undo
    removecolumn <- function(df, nameofthecolumn){dplyr::select(df, -all_of(nameofthecolumn))}

    output$selectColumn <- renderUI({
      selectInput(inputId = ns("selectColumn"), ## namespace
                  label = "Select sample(s) to remove",
                  choices = colnames(r$data)
      )
    })
    observeEvent(input$removeCol, {
      r$data <- removecolumn(r$data, input$selectColumn)
    })
    observeEvent(input$undoCol, {
      r$data <- inputData()
    })
  }
  )
}

# Application
library(shiny)
app_ui <- function() {
  fluidPage(
    choice_ui("choice_ui_1")
  )
}

app_server <- function(input, output, session) {
  r <- reactiveValues()
  choice_server("choice_ui_1", r = r)
}

shinyApp(app_ui, app_server)


来源: stackexchange

问:
Github Action to check if file has changed
I would like to have a Github action that checks if a file has changed, being this way mandatory to change the content of one file (changelog in my case) to pass the CI in a PR.</p>

ContentLicense: CC BY-SA 4.0


问:
gprof symspec including C++ class functions
I'm trying to profile a particular portion of a large C++ program. I am using gprof and Gprof2Dot to generate nice graphs. However, I would like to exclude certain startup functions from the graph.

I thought I should be able to run gprof -Qclass::init to supress class::init and all its children, but that doesn't seem to be working. In fact, I can't get any "symspec" containing "::" to work. -Qmain works as I expect, however.

What magic tricks need to be done to get gprof to include/exclude function names with "::"?

ContentLicense: CC BY-SA 3.0


问:
PdfSharp pdf password protected
I'm facing strange issue.
My goal is to run query on the Oracle Database which give me an OracleBlob (where the pdf file is stored). Then I want to check if pdf stored in that blob is password protected - if it is return and do nothing else protect that file with a password.

So right now it is working only at the first time when the pdf file is not password protected. When i try to run it again with a password it takes hours to complete ...
Could You help me with that ?

How can i prepare an exception for it or maybe I did something wrong in the code?

```<code> public Stream encryptPdf(int idIn, string code)
        {

            string constr = "User Id=user;Password=pass;Data Source=database";
            OracleConnection con = new OracleConnection(constr);
            con.Open();

            // Get the ByteCodes for blob file
            string cmdstr = string.Format(@"select t.blob_file from table t where t.id = {0}", idIn);
            OracleCommand cmd = new OracleCommand(cmdstr, con);

            // Since we are going to update the OracleBlob object, we will
            //have to create a transaction
            OracleTransaction txn = con.BeginTransaction();

            // Get the reader
            OracleDataReader reader = cmd.ExecuteReader();

            // Declare the variables to retrieve the data in EmpInfo
            OracleBlob byteCodesBlob;

            // Read the first row

                reader.Read();
            if (!reader.IsDBNull(0))
            {
                byteCodesBlob = reader.GetOracleBlobForUpdate(0);

                try
                {

                    PdfSharp.Pdf.PdfDocument document = PdfSharp.Pdf.IO.PdfReader.Open(byteCodesBlob);
                    PdfSecuritySettings securitySettings = document.SecuritySettings;
                    securitySettings.UserPassword = "user";
                    securitySettings.OwnerPassword = code;
                    securitySettings.PermitAccessibilityExtractContent = false;
                    securitySettings.PermitAnnotations = false;
                    securitySettings.PermitAssembleDocument = false;
                    securitySettings.PermitExtractContent = false;
                    securitySettings.PermitFormsFill = true;
                    securitySettings.PermitFullQualityPrint = false;
                    securitySettings.PermitModifyDocument = true;
                    securitySettings.PermitPrint = false;

                    document.Save(byteCodesBlob);

                    // Close the reader
                    reader.Close();

                    // Update the ByteCodes object
                    BinaryReader binaryReader = new BinaryReader(byteCodesBlob);
                    byte[] data = binaryReader.ReadBytes((int)byteCodesBlob.Length);

                    byteCodesBlob.Append(data, 0, data.Length);

                    // Now commit the transaction
                    txn.Commit();
                    Console.WriteLine("Blob Column successfully updated");

                }
                catch (Exception ex)
                {
                    reader.Dispose();
                    con.Dispose();
                    //throw new Exception(ex.Message.ToString()); ?
                    return null;
                }
            }
                else
                    reader.Dispose();

                // Close the connection
                con.Dispose();
                return null;
        }
</code>```

Title: PdfSharp pdf password protected

Body:
I'm facing strange issue.
My goal is to run query on the Oracle Database which give me an OracleBlob (where the pdf file is stored). Then I want to check if pdf stored in that blob is password protected - if it is return and do nothing else protect that file with a password.

So right now it is working only at the first time when the pdf file is not password protected. When i try to run it again with a password it takes hours to complete ...
Could You help me with that ?

How can i prepare an exception for it or maybe I did something wrong in the code?

 public Stream encryptPdf(int idIn, string code)
        {

            string constr = "User Id=user;Password=pass;Data Source=database";
            OracleConnection con = new OracleConnection(constr);
            con.Open();

            // Get the ByteCodes for blob file
            string cmdstr = string.Format(@"select t.blob_file from table t where t.id = {0}", idIn);
            OracleCommand cmd = new OracleCommand(cmdstr, con);

            // Since we are going to update the OracleBlob object, we will
            //have to create a transaction
            OracleTransaction txn = con.BeginTransaction();

            // Get the reader
            OracleDataReader reader = cmd.ExecuteReader();

            // Declare the variables to retrieve the data in EmpInfo
            OracleBlob byteCodesBlob;

            // Read the first row

                reader.Read();
            if (!reader.IsDBNull(0))
            {
                byteCodesBlob = reader.GetOracleBlobForUpdate(0);

                try
                {

                    PdfSharp.Pdf.PdfDocument document = PdfSharp.Pdf.IO.PdfReader.Open(byteCodesBlob);
                    PdfSecuritySettings securitySettings = document.SecuritySettings;
                    securitySettings.UserPassword = "user";
                    securitySettings.OwnerPassword = code;
                    securitySettings.PermitAccessibilityExtractContent = false;
                    securitySettings.PermitAnnotations = false;
                    securitySettings.PermitAssembleDocument = false;
                    securitySettings.PermitExtractContent = false;
                    securitySettings.PermitFormsFill = true;
                    securitySettings.PermitFullQualityPrint = false;
                    securitySettings.PermitModifyDocument = true;
                    securitySettings.PermitPrint = false;

                    document.Save(byteCodesBlob);

                    // Close the reader
                    reader.Close();

                    // Update the ByteCodes object
                    BinaryReader binaryReader = new BinaryReader(byteCodesBlob);
                    byte[] data = binaryReader.ReadBytes((int)byteCodesBlob.Length);

                    byteCodesBlob.Append(data, 0, data.Length);

                    // Now commit the transaction
                    txn.Commit();
                    Console.WriteLine("Blob Column successfully updated");

                }
                catch (Exception ex)
                {
                    reader.Dispose();
                    con.Dispose();
                    //throw new Exception(ex.Message.ToString()); ?
                    return null;
                }
            }
                else
                    reader.Dispose();

                // Close the connection
                con.Dispose();
                return null;
        }


问:
opencore user. my google docs keeps glitching
I have the OpenCore Legacy Patcher on my 2010 MacBook Pro, and it's running great with all the patches applied.  Google Docs and Sheets (maybe Slides too idk) are not working properly in chrome and microsoft edge. There are many issues, but sometimes I can't see what I typed for example. as such it has made using the google docs offline feature problematic. how do i resolve this?

i tried using user agent switcher in firefox but it didn't work. i am mainly interested in using google docs offline feature. i can use it online with firefox and safari but i do not always have access to internet and this has become a challenge.

this the google docs tab before i start typing.

this is the tab when i start typing.

sometimes everything this appears except what I'm typing


问:
How to get names of devices in your local network using node js
I need to get HueBridge IP address in my app in node js, I would like to scan the whole network and then search for the name "Hue Bridge" or something similar, I found npm package named 'local-devices', but it doesn't return a device name for me for some reason.

```<code>const find = require('local-devices');

find().then(devices => {
    console.log(devices)
  })
</code>```

Output:

```<code>[
  { name: '?', ip: '192.168.1.72', mac: 'secret_mac'},
  { name: '?', ip: '192.168.1.116', mac: 'secret_mac'},
  { name: '?', ip: '192.168.1.117', mac: 'secret_mac'}
]
</code>```

Body:
I need to get HueBridge IP address in my app in node js, I would like to scan the whole network and then search for the name "Hue Bridge" or something similar, I found npm package named 'local-devices', but it doesn't return a device name for me for some reason.

const find = require('local-devices');

find().then(devices => {
    console.log(devices)
  })

Output:

[
  { name: '?', ip: '192.168.1.72', mac: 'secret_mac'},
  { name: '?', ip: '192.168.1.116', mac: 'secret_mac'},
  { name: '?', ip: '192.168.1.117', mac: 'secret_mac'}
]


问:
JavaFX TextField NuberFormatException
Have been sitting with this for over an hour, so I have a plain textField which is meant for entering Int numbers, and then I perform filtering based on the number.

My filter function

```<code>private void fillAllListsFiltered() {

        List<Trip> trips = tripHib.getAllTrips();
        trips.forEach(c -> { if(c.getTime() > gt(tripTextTime) && c.getLength() > gt(tripTextLength)) tripListView.getItems().add(c);});

    }
</code>```

And then my "function" for parsing Int from the textField. (I understand I could just parse it in the first function as Integer.parseInt(tripTextTime.getText()), but for some reason it does not work.

```<code>private static int gt(TextField textField) {
        System.out.println(textField.getText());
        String text = textField.getText().trim();
        return Integer.parseInt(text);
    }
</code>```

I have also added the trim as an extra, but it didn't really help.

the error is "NumberFormatException: For input string: "" "

Title: JavaFX TextField NuberFormatException

Body:
Have been sitting with this for over an hour, so I have a plain textField which is meant for entering Int numbers, and then I perform filtering based on the number.

My filter function

private void fillAllListsFiltered() {

        List<Trip> trips = tripHib.getAllTrips();
        trips.forEach(c -> { if(c.getTime() > gt(tripTextTime) && c.getLength() > gt(tripTextLength)) tripListView.getItems().add(c);});

    }

And then my "function" for parsing Int from the textField. (I understand I could just parse it in the first function as Integer.parseInt(tripTextTime.getText()), but for some reason it does not work.

private static int gt(TextField textField) {
        System.out.println(textField.getText());
        String text = textField.getText().trim();
        return Integer.parseInt(text);
    }

I have also added the trim as an extra, but it didn't really help.

the error is "NumberFormatException: For input string: "" "


问:
Regex: extracting multiple lines if they have the same ID
This is the text (from a Persian corpus):

```<code>1 Jaryane senID=39968
2 mosum senID=39968
3 be senID=39968
...
12 ast senID=39968

1 Magar senID=39969
2 nemishavad senID=39969
...
10 ؟ senID=39969
</code>```

I want to extract lines starting with anything and ending with "؟" (Persian question mark). Like this:

```<code>1 Magar senID=39969
2 nemishavad senID=39969
...
10 ؟ senID=39969
</code>```

Is there any way to extract multiple lines with the same ID (senID=...) and end with "؟"?

Body:
This is the text (from a Persian corpus):

1 Jaryane senID=39968
2 mosum senID=39968
3 be senID=39968
...
12 ast senID=39968

1 Magar senID=39969
2 nemishavad senID=39969
...
10 ؟ senID=39969

I want to extract lines starting with anything and ending with "؟" (Persian question mark). Like this:

1 Magar senID=39969
2 nemishavad senID=39969
...
10 ؟ senID=39969

Is there any way to extract multiple lines with the same ID (senID=...) and end with "؟"?


问:
Best practice to store and query likes/dislikes of a post in firestore
I am building an app where users can like and dislike posts. Now, in firestore, I am creating a liked_by and disliked_by collections inside each post document, where I add the userId of the users who liked/disliked a post as document IDs.

Now, when showing posts to a user in the app, I have to check if each post has been liked or disliked by the current user, so that I show them that they have already liked/dislike the post. This means I have to perform 3 queries for every post (one for the post contents, one to check if the user's ID is in the list of the liked_by collection, and another to check if the user's ID is in the list of the disliked_by collection). That seems like too many queries per post, especially considering that the likelihood of the user actually having liked/disliked a post that they're seeing is low.

Is there a more efficient way of doing this?

Other options I have thought about:

Keeping the liked/disliked list of user IDs in an array field within the post document. The downside here is that a post document will be too much text data when fetching, and also documents have a limit of 1MB so it's not fully scalable.

Creating a liked/disliked collections in each users document and keep a list of post IDs that a user has liked/disliked. The one downside here is that overtime this list of documents will grow and I'll have to always fetch all documents every time at first. So if the user has liked/disliked 300 posts overtime, then from that point forward, i'll always fetch all 300 documents to see if a post they are looking at is within the list. If they only ended up looking at 30 posts, then this wouldn't be worth it, I could've queried the likes/dislikes separately and only fetched 90 documents (3 queries for each post as mentioned in second paragraph), instead of the 300 plust the 30 posts.

Thanks


问:
how to use loop through all the dataframe and apply condition to it
I have 49 dataframes and one matrix file which has NA values initially and will be filled up based on a condition applied on the 49 dataframe.
The condition are's: First check if the respective gene is present in the dataframe. if yes, then check the rsid if that rsid is present for that particular gene then take it weight value and add to the matrix file otherwise it should be 0

This is how my dataframe look like: enter image description here

This is how my matrix look like:

enter image description here

I am able to fill the matrix for individual dataframe but not able to understand how to do it through loop so that I can analyse all the dataframe at one go.

```<code>y <- en_Adipose_Subcutaneous$gene==genes_union[1]
z <- which(y[y])
a <- en_Adipose_Subcutaneous[z,]
weightsval <- ifelse(rownames(models_df)[1:1657598]%in% a$rsid,a$weight,0)
models_df[1:1657598,1] <- weightsval

y <- en_Adipose_Visceral_omentum$gene==genes_union[1]
z <- which(y[y])
a <- en_Adipose_Visceral_omentum[z,]
weightsval <- ifelse(colnames(models_df)[1:1657598]%in% a$rsid,a$weight,0)
models_df[1:1657598,2] <- weightsval

My data:
en_Adipose_Visceral_omentum <- data.frame(gene=c("ENSG00000107937.18","ENSG00000107937.18"),rsid=c("rs7475652","rs7918643"),varID=c("chr10_295356_T_C_b38","chr10_301812_C_T_b38"),ref_allele=c("T","C"),eff_allele=c("C","T"),weight=c(0.004,-0.00735))

dput(mod1els_df)
structure(c(NA, NA, NA, NA, NA, NA, NA, NA, NA), .Dim = c(3L,
3L), .Dimnames = list(c("rs11252127", "rs11252546", "rs11591988"
), c("en_Adipose_Subcutaneous", "en_Adipose_Visceral_Omentum",
"en_Adrenal_Gland")))
</code>```

Body:
I have 49 dataframes and one matrix file which has NA values initially and will be filled up based on a condition applied on the 49 dataframe.
The condition are's: First check if the respective gene is present in the dataframe. if yes, then check the rsid if that rsid is present for that particular gene then take it weight value and add to the matrix file otherwise it should be 0

This is how my dataframe look like: enter image description here

This is how my matrix look like:

enter image description here

I am able to fill the matrix for individual dataframe but not able to understand how to do it through loop so that I can analyse all the dataframe at one go.

y <- en_Adipose_Subcutaneous$gene==genes_union[1]
z <- which(y[y])
a <- en_Adipose_Subcutaneous[z,]
weightsval <- ifelse(rownames(models_df)[1:1657598]%in% a$rsid,a$weight,0)
models_df[1:1657598,1] <- weightsval

y <- en_Adipose_Visceral_omentum$gene==genes_union[1]
z <- which(y[y])
a <- en_Adipose_Visceral_omentum[z,]
weightsval <- ifelse(colnames(models_df)[1:1657598]%in% a$rsid,a$weight,0)
models_df[1:1657598,2] <- weightsval

My data:
en_Adipose_Visceral_omentum <- data.frame(gene=c("ENSG00000107937.18","ENSG00000107937.18"),rsid=c("rs7475652","rs7918643"),varID=c("chr10_295356_T_C_b38","chr10_301812_C_T_b38"),ref_allele=c("T","C"),eff_allele=c("C","T"),weight=c(0.004,-0.00735))

dput(mod1els_df)
structure(c(NA, NA, NA, NA, NA, NA, NA, NA, NA), .Dim = c(3L,
3L), .Dimnames = list(c("rs11252127", "rs11252546", "rs11591988"
), c("en_Adipose_Subcutaneous", "en_Adipose_Visceral_Omentum",
"en_Adrenal_Gland")))


问:
sequelize How to join between 2 table that have 1 common column
I have 2 table , the first table hold tags that one user love them

and the second table shows tags of one post

I want to call a query that gets tags that this user loves them
and then return related posts to this tag without duplicate


问:
Boolean config in pytest.ini is being returned as string when it should be boolean
We're running into an issue where we try to pass a boolean configuration from pytest.ini:

```<code>enable = False
</code>```

To a instance of class "SerialClass":

```<code>def __init__(self, enable=False):
  self.enabled = enable
</code>```

This config is grabbed from the pytest.ini via a pytest fixture:

```<code>@pytest.fixture(scope="session")
def can_fixture(options, pytestconfig):
  can_manager = SerialClass(options.get('enable'))
</code>```

And used to send a can message as shown below:

```<code>def send(self, canID: int, data: list=None):
  **Code omitted for brevity**
  if self.enabled:
    msg = msg + 'H;
</code>```

The issue is this config is returned as a string instead of a boolean. The only workaround we've found is to json.loads to convert it to boolean:

```<code>def __init__(self, enable=False):
  self.enabled = json.loads(enable.lower())
</code>```

Other workarounds such as casting the options.get('enable') as a boolean in the fixture has not worked. What is the best way to handle boolean configurations from pytest.ini?

Body:
We're running into an issue where we try to pass a boolean configuration from pytest.ini:

enable = False

To a instance of class "SerialClass":

def __init__(self, enable=False):
  self.enabled = enable

This config is grabbed from the pytest.ini via a pytest fixture:

@pytest.fixture(scope="session")
def can_fixture(options, pytestconfig):
  can_manager = SerialClass(options.get('enable'))

And used to send a can message as shown below:

def send(self, canID: int, data: list=None):
  **Code omitted for brevity**
  if self.enabled:
    msg = msg + 'H;

The issue is this config is returned as a string instead of a boolean. The only workaround we've found is to json.loads to convert it to boolean:

def __init__(self, enable=False):
  self.enabled = json.loads(enable.lower())

Other workarounds such as casting the options.get('enable') as a boolean in the fixture has not worked. What is the best way to handle boolean configurations from pytest.ini?


问:
Ajax script will not load PHP read dir script?
I have a simple ajax script from javascriptkit.com that loads and external page into a div. When I stick my PHP read directory script in there it does not work. Is this something that can even be accomplished? Below is the ajax....

```<code><head>
<script type="text/javascript" src="ajaxpagefetcher.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>

<div id="demo" style="border: 1px dashed gray; width: 300px; height: 200px; padding: 3px;
background: none repeat scroll 0% 0% lightyellow;"></div>
<a href="javascript:ajaxpagefetcher.load('demo', 'PHP SCRIPT HERE', false)">Load Content 1</a>
</body>
</code>```

Here is the PHP that I am using.

```<code> <?php

  // These files will be ignored
  $excludedFiles = array (
'excludeMe.file',
'excludeMeAs.well'
  );

  // These file extensions will be ignored
  $excludedExtensions = array (
   'html',
'xslt',
    'htm',
'ahk',
'xsl',
'txt',
 'xml'
  );

// Make sure we ignore . and ..
$excludedFiles = array_merge($excludedFiles,array('.','..'));

// Convert to lower case so we are not case-sensitive
for ($i = 0; isset($excludedFiles[$i]); $i++) $excludedFiles[$i] =
strtolower(ltrim($excludedFiles[$i],'.'));
for ($i = 0; isset($excludedExtensions[$i]); $i++) $excludedExtensions[$i] =
strtolower($excludedExtensions[$i]);

// Loop through directory
$dir = 'dir/dir/';
if ($handle = opendir($dir)) {

while (false !== ($file = readdir($handle))) {
  $extn = explode('.',$file);
  $extn = array_pop($extn);
  // Only echo links for files that don't match our rules
  if (!in_array(strtolower($file),$excludedFiles) &&
  !in_array(strtolower($extn),$excludedExtensions)) {
    $count++;
    print("<a href=\"".$dir.$file."\">".$file."</a><br />\n");
  }
}
 echo '<br />';
closedir($handle);
 }

 ?>
</code>```

Body:
I have a simple ajax script from javascriptkit.com that loads and external page into a div. When I stick my PHP read directory script in there it does not work. Is this something that can even be accomplished? Below is the ajax....

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

Load Content 1

Here is the PHP that I am using.

 <?php

  // These files will be ignored
  $excludedFiles = array (
'excludeMe.file',
'excludeMeAs.well'
  );

  // These file extensions will be ignored
  $excludedExtensions = array (
   'html',
'xslt',
    'htm',
'ahk',
'xsl',
'txt',
 'xml'
  );

// Make sure we ignore . and ..
$excludedFiles = array_merge($excludedFiles,array('.','..'));

// Convert to lower case so we are not case-sensitive
for ($i = 0; isset($excludedFiles[$i]); $i++) $excludedFiles[$i] =
strtolower(ltrim($excludedFiles[$i],'.'));
for ($i = 0; isset($excludedExtensions[$i]); $i++) $excludedExtensions[$i] =
strtolower($excludedExtensions[$i]);

// Loop through directory
$dir = 'dir/dir/';
if ($handle = opendir($dir)) {

while (false !== ($file = readdir($handle))) {
  $extn = explode('.',$file);
  $extn = array_pop($extn);
  // Only echo links for files that don't match our rules
  if (!in_array(strtolower($file),$excludedFiles) &&
  !in_array(strtolower($extn),$excludedExtensions)) {
    $count++;
    print("".$file."
\n");
  }
}
 echo '
';
closedir($handle);
 }

 ?>


问:
Browser console shows CORS error regardless of the type of error that happens on the server side of a fastapi app
I have fastapi app that is running on the same server as a react app.

I make a simple, async request to the route, but regardless of the type of error that happens on the server (syntaxerror, valueerror, etc...), the browser console shows a CORS error

I am 100% positive it is not a cors error

How can I make it display more accurate errors on the frontend?


问:
datatype conversion from .net core 3.1 to .net framework 4.7
This is my class that is returning as a result from .net core 3.1 web api action method

```<code>public class DataSync
{
    public string FieldName { get; set; }
    public Type DataType { get; set; }
}
</code>```

Json Result

{  "FieldName": "LastName",  "DataType": "System.String,
System.Private.CoreLib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=7cec85d7bea7798e"  }

My client application is in .net framework 4.7 where I am desterilizing the above json in same model class using newtonsoft.json but it's throwing error because .net framework 4.7 frame work does not understand System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e its expecting datatype should be System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 in json result.

I know this is because of datatype returned from core, .net framework does not understand that, so may be direct desterilization not possible, I am looking for known and right way to handle this issue across the all datatypes so my .net framework client application can desterilize the result return from .net core api.

Body:
This is my class that is returning as a result from .net core 3.1 web api action method

public class DataSync
{
    public string FieldName { get; set; }
    public Type DataType { get; set; }
}

Json Result

{  "FieldName": "LastName",  "DataType": "System.String,
System.Private.CoreLib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=7cec85d7bea7798e"  }

My client application is in .net framework 4.7 where I am desterilizing the above json in same model class using newtonsoft.json but it's throwing error because .net framework 4.7 frame work does not understand System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e its expecting datatype should be System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 in json result.

I know this is because of datatype returned from core, .net framework does not understand that, so may be direct desterilization not possible, I am looking for known and right way to handle this issue across the all datatypes so my .net framework client application can desterilize the result return from .net core api.


问:
Add shadow to sticky element
I am new to css and html and I am trying to recreate the behavior  whereby a group is sticky and once it is sticky I add a bottom shadow. I manage to make the element sticky by applying this code:

```

but now I dont know where to start to add the shadow only when the group is stuck at the top. do you have an idea? thanks

Title: Add shadow to sticky element

Body:
I am new to css and html and I am trying to recreate the behavior  whereby a group is sticky and once it is sticky I add a bottom shadow. I manage to make the element sticky by applying this code:

but now I dont know where to start to add the shadow only when the group is stuck at the top. do you have an idea? thanks


问:
#Teradata error expected something like ')' between ';' and the end of the request
```<code>
REPLACE MACRO GEO_MATCHED (REGION INTEGER) AS (
INSERT INTO DLA_v.GEO_FULL_2019_MATCHED
              SELECT
                 Poly.Project_ID AS "Project_ID",
                             Poly.WIKIMAPIA_ID AS "POLY_ID_WIKIMAPIA",
                             Poly.NAME AS "POLY_NAME",

                             Fast.REVENUE_YTD,
                             Fast.JOB_VERTICAL,

                             Poly.geometry.ST_Contains(Fast.geometry)  AS "INSIDE"
              FROM
                            (SELECT * FROM  DLA_A_19143.geo_jobsite_input_data
                            WHERE region__c = :REGION)Fast, DLA_D_SLSMKT.GEO_POLYGONS Poly
              WHERE
                             (Poly.geometry.ST_Contains(Fast.geometry) = 1;);

 ----region with null values
</code>```

getting this error for this code :
[42000] [Teradata][ODBC Teradata Driver][Teradata Database] Syntax error, expected something like ')' between ';' and the end of the request.

Added the brackets as it has asked to add the bracted between semicolumns and end of request its not working, if any one could help .

Body:
REPLACE MACRO GEO_MATCHED (REGION INTEGER) AS (
INSERT INTO DLA_v.GEO_FULL_2019_MATCHED
              SELECT
                 Poly.Project_ID AS "Project_ID",
                             Poly.WIKIMAPIA_ID AS "POLY_ID_WIKIMAPIA",
                             Poly.NAME AS "POLY_NAME",

                             Fast.REVENUE_YTD,
                             Fast.JOB_VERTICAL,

                             Poly.geometry.ST_Contains(Fast.geometry)  AS "INSIDE"
              FROM
                            (SELECT * FROM  DLA_A_19143.geo_jobsite_input_data
                            WHERE region__c = :REGION)Fast, DLA_D_SLSMKT.GEO_POLYGONS Poly
              WHERE
                             (Poly.geometry.ST_Contains(Fast.geometry) = 1;);

 ----region with null values

getting this error for this code :
[42000] [Teradata][ODBC Teradata Driver][Teradata Database] Syntax error, expected something like ')' between ';' and the end of the request.

Added the brackets as it has asked to add the bracted between semicolumns and end of request its not working, if any one could help .


问:
Slow performance when working with multiple XML files
I'm trying to work with two XML files. I use the second highlighted answer in this thread [1] as a base script.

This is what I got:

```<code>jQuery.extend({
getValues: function(url) {
var result = null;
$.ajax({
    url: url,
    type: 'get',
    dataType: 'xml',
    async: false,
    success: function(data) {
        result = data;
    }
});
return result;
}
});

var party1 = $.getValues('http://data.riksdagen.se/voteringlista/?rm=2010%2F11&bet=&punkt=parti=M&valkrets=&rost=&iid=&sz=500&utformat=xml&gruppering=bet')
var party2 = $.getValues('http://data.riksdagen.se/voteringlista/?rm=2010%2F11&bet=&punkt=&parti=S&valkrets=&rost=&iid=&sz=500&utformat=xml&gruppering=bet')

$(party1).find('votering').each(function(){
var id = $(this).find("forslagspunkt").text()
partyTwo(id)
//-------------------------------------
//HERE I RUN A FEW SIMPLE IF STATEMENTS
//------------------------------------

})

function partyTwo(id) {
$(party2).find('votering').filter(function() {
    return $(this).find("forslagspunkt").text() == id;
    }).each(function () {

//-------------------------------------
// AGAIN, A FEW SIMPLE IF STATEMENTS
//------------------------------------

            return vote
})
}
</code>```

This leaves me with two problems:

1) partyTwo(id) returns 'undefined', but works fine if I manually insert an id outside.

2) The whole script runs very slow (+5 sec to load).

Any thoughts?

[1] JQuery - Storing ajax response into global variable

Body:
I'm trying to work with two XML files. I use the second highlighted answer in this thread [1] as a base script.

This is what I got:

jQuery.extend({
getValues: function(url) {
var result = null;
$.ajax({
    url: url,
    type: 'get',
    dataType: 'xml',
    async: false,
    success: function(data) {
        result = data;
    }
});
return result;
}
});

var party1 = $.getValues('http://data.riksdagen.se/voteringlista/?rm=2010%2F11&bet=&punkt=parti=M&valkrets=&rost=&iid=&sz=500&utformat=xml&gruppering=bet')
var party2 = $.getValues('http://data.riksdagen.se/voteringlista/?rm=2010%2F11&bet=&punkt=&parti=S&valkrets=&rost=&iid=&sz=500&utformat=xml&gruppering=bet')

$(party1).find('votering').each(function(){
var id = $(this).find("forslagspunkt").text()
partyTwo(id)
//-------------------------------------
//HERE I RUN A FEW SIMPLE IF STATEMENTS
//------------------------------------

})

function partyTwo(id) {
$(party2).find('votering').filter(function() {
    return $(this).find("forslagspunkt").text() == id;
    }).each(function () {

//-------------------------------------
// AGAIN, A FEW SIMPLE IF STATEMENTS
//------------------------------------

            return vote
})
}

This leaves me with two problems:

1) partyTwo(id) returns 'undefined', but works fine if I manually insert an id outside.

2) The whole script runs very slow (+5 sec to load).

Any thoughts?

[1] JQuery - Storing ajax response into global variable


问:
Elasticsearch returns 'long' field wrapped around double quotatons (as same as a string)
I have an index similar to the following mapping (please note the long field named identifier):

```<code>{
  "my_index" : {
    "mappings" : {
      "dynamic" : "strict",
      "properties" : {
        ...
        "identifier" : {
          "type" : "long"
        },
        ...
    }
  }
}
</code>```

I have indexed billions of documents in the index. The problem is that when I execute search queries I sometimes encounter documents that contain identifier fields wrapped around double quotations (as if it is an string). Therefore, my application interprets the JSON response of the search query by mistakenly inferring the type of identifier as string.

Sample response JSON:

```<code>[
    {
        ...
        "identifier": "893421315356545028",
        ...
    },
    {
        ...
        "identifier": 1053248278618427392,
        ...
    }
}
</code>```

This is an actual (but cleaned) result and you can see that one of the result documents is returned with its identifier field wrapped around double quotations. It is quite strange as the mapping is defined before indexing and the dynamic setting is set to 'strict'.

Elasticsearch version is 7.7.0.

Body:
I have an index similar to the following mapping (please note the long field named identifier):

{
  "my_index" : {
    "mappings" : {
      "dynamic" : "strict",
      "properties" : {
        ...
        "identifier" : {
          "type" : "long"
        },
        ...
    }
  }
}

I have indexed billions of documents in the index. The problem is that when I execute search queries I sometimes encounter documents that contain identifier fields wrapped around double quotations (as if it is an string). Therefore, my application interprets the JSON response of the search query by mistakenly inferring the type of identifier as string.

Sample response JSON:

[
    {
        ...
        "identifier": "893421315356545028",
        ...
    },
    {
        ...
        "identifier": 1053248278618427392,
        ...
    }
}

This is an actual (but cleaned) result and you can see that one of the result documents is returned with its identifier field wrapped around double quotations. It is quite strange as the mapping is defined before indexing and the dynamic setting is set to 'strict'.

Elasticsearch version is 7.7.0.


问:
React Native - Not able to add and delete data from array correctly
I am creating an App in which I have two screens -- One is Feed and Bookmark. Each Feed has bookmark icon from which we can add and delete bookmark. If I add bookmark from feed then It will be added to list and if I delete that then list will be updated with existing once but the issue is that sometime data added double at the time of addition and sometimes at time of deletion array did not get the index of selected item and stays there and sometimes my list got disturbed with showing half items.

Code to click bookmark button on feed

```<code> const selectBookmark = () => {
   item.bookmarked = !item.bookmarked;
   setBookMarkSelected(!item.bookmarked);
   setBookmarkClicked(true);

   setBookmarkLoader(true);
 };

</code>```

Call API each time at updating bookmark

```<code>  const bookmarkResponse = await addDeleteBookmark(
    email,
    userId,
    item.cardId,
    userSelectedChannel,
    token,
    item.bookmarked,
    item.createdAt,
    item.cardType,
  )
    .then(res => {
      setBookmarkLoader(false);
      if (res !== 'error') {
        console.log('not in else');
        updatebookMark();
      } else {
        console.log(' in else');
        item.bookmarked = !item.bookmarked;
      }

    })
    .catch(function (error) {

      setBookmarkLoader(false);

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

**when I get response from API I call updateBookmark function too update local database **

```<code> const updatebookMark = () => {

 // code to update feed Array locally
let newArray = [...feedArray];

let id = item.cardId;
const index = newArray.findIndex(object => {
  return object.cardId === id;
});

if (index !== -1) {
  newArray[index].bookmarked = item.bookmarked;

  addFeedsToLocalDB(newArray);
}

 // code to update bookmark Array locally
let bookmarks = [...bookmarkArray];

 // bookmark added then add new bookmark
if (item.bookmarked) {
  const index = bookmarkArray.findIndex(object => {
    return object.cardId === id;
  });
  if (index === -1) {
    bookmarks.push(item);
    addBookMarksTOLocalDB(bookmarks);
  }

} else {

    // if deletion then delete from bookmark
  const indexBookmark = bookmarks.findIndex(object => {
    return object.cardId === id;
  });

  console.log('bookmark card indexBookmark  image', indexBookmark);

  bookmarks.splice(indexBookmark, 1);

  // console.log('bookmarked after splicing image', bookmarks);

  addBookMarksTOLocalDB(bookmarks);

  // setBookmarksArray(bookmarks);
}

let homeArray = [...homeCards];

const indexHome = newArray.findIndex(object => {
  return object.cardId === id;
});

if (indexHome !== -1) {
  homeArray[indexHome].bookmarked = item.bookmarked;

  addHomeToLocalDB(homeArray);
}
</code>```

};

but the issue is that this addition and deletion bookmark is causing issue and I am not able to get that.

Body:
I am creating an App in which I have two screens -- One is Feed and Bookmark. Each Feed has bookmark icon from which we can add and delete bookmark. If I add bookmark from feed then It will be added to list and if I delete that then list will be updated with existing once but the issue is that sometime data added double at the time of addition and sometimes at time of deletion array did not get the index of selected item and stays there and sometimes my list got disturbed with showing half items.

Code to click bookmark button on feed

 const selectBookmark = () => {
   item.bookmarked = !item.bookmarked;
   setBookMarkSelected(!item.bookmarked);
   setBookmarkClicked(true);

   setBookmarkLoader(true);
 };

Call API each time at updating bookmark

  const bookmarkResponse = await addDeleteBookmark(
    email,
    userId,
    item.cardId,
    userSelectedChannel,
    token,
    item.bookmarked,
    item.createdAt,
    item.cardType,
  )
    .then(res => {
      setBookmarkLoader(false);
      if (res !== 'error') {
        console.log('not in else');
        updatebookMark();
      } else {
        console.log(' in else');
        item.bookmarked = !item.bookmarked;
      }

    })
    .catch(function (error) {

      setBookmarkLoader(false);

    });
};

**when I get response from API I call updateBookmark function too update local database **

 const updatebookMark = () => {

 // code to update feed Array locally
let newArray = [...feedArray];

let id = item.cardId;
const index = newArray.findIndex(object => {
  return object.cardId === id;
});

if (index !== -1) {
  newArray[index].bookmarked = item.bookmarked;

  addFeedsToLocalDB(newArray);
}

 // code to update bookmark Array locally
let bookmarks = [...bookmarkArray];

 // bookmark added then add new bookmark
if (item.bookmarked) {
  const index = bookmarkArray.findIndex(object => {
    return object.cardId === id;
  });
  if (index === -1) {
    bookmarks.push(item);
    addBookMarksTOLocalDB(bookmarks);
  }

} else {

    // if deletion then delete from bookmark
  const indexBookmark = bookmarks.findIndex(object => {
    return object.cardId === id;
  });

  console.log('bookmark card indexBookmark  image', indexBookmark);

  bookmarks.splice(indexBookmark, 1);

  // console.log('bookmarked after splicing image', bookmarks);

  addBookMarksTOLocalDB(bookmarks);

  // setBookmarksArray(bookmarks);
}

let homeArray = [...homeCards];

const indexHome = newArray.findIndex(object => {
  return object.cardId === id;
});

if (indexHome !== -1) {
  homeArray[indexHome].bookmarked = item.bookmarked;

  addHomeToLocalDB(homeArray);
}

};

but the issue is that this addition and deletion bookmark is causing issue and I am not able to get that.


问:
Selecting multiple lines with richtext format information in PyCharm Console
How can I select the last two or more lines in PyCharm Console?

In the following image, I tried to select the last two lines but couldn't; I was able to select only the last line. Currently, it either allows me to select multiple lines before the last line, or select only the last line. In the former case, format information is lost when copied and pasted to another text editor (no colors).

My aim is to select multiple lines including the last line with format information and paste them into another text editor. I tried both the latest PyCharm Professional and PyCharm CE editions.


问:
git fetch --dry-run still changes the local repo and transfer data
I'm trying to test if a remote repo has a given SHA.  ls-remote does not work for this unless it is a tag or a HEAD (which is not guaranteed for this case).

git fetch --dry-run $remote $rev SEEMS to fit the bill, except it changes local state.  For example:

```<code>$ git cat-file -t f80f1b23b4cab2a295a091c623bb4746d188bd4a
fatal: git cat-file: could not get object info

$ git rev-parse FETCH_HEAD
42d21cf12aab73ac8bc6245cc74ac9850bdf6989

$ git fetch --dry-run file:///tmp/e2e.2527526915/repo f80f1b23b4cab2a295a091c623bb4746d188bd4a
remote: Enumerating objects: 20, done.
remote: Counting objects: 100% (20/20), done.
remote: Compressing objects: 100% (9/9), done.
remote: Total 18 (delta 6), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (18/18), 415.91 KiB | 84.00 KiB/s, done.
From file:///tmp/e2e.2527526915/repo
 * branch            f80f1b23b4cab2a295a091c623bb4746d188bd4a -> FETCH_HEAD

$ git cat-file -t f80f1b23b4cab2a295a091c623bb4746d188bd4a
commit

$ git rev-parse FETCH_HEAD
42d21cf12aab73ac8bc6245cc74ac9850bdf6989
</code>```

FETCH_HEAD was not updated (good) but the rev is question is now present locally (bad), further tested by making a very large commit and watching the fetch be very slow.

Am I using --dry-run wrong?  Is there a different way to ask for what I want?

Body:
I'm trying to test if a remote repo has a given SHA.  ls-remote does not work for this unless it is a tag or a HEAD (which is not guaranteed for this case).

git fetch --dry-run $remote $rev SEEMS to fit the bill, except it changes local state.  For example:

$ git cat-file -t f80f1b23b4cab2a295a091c623bb4746d188bd4a
fatal: git cat-file: could not get object info

$ git rev-parse FETCH_HEAD
42d21cf12aab73ac8bc6245cc74ac9850bdf6989

$ git fetch --dry-run file:///tmp/e2e.2527526915/repo f80f1b23b4cab2a295a091c623bb4746d188bd4a
remote: Enumerating objects: 20, done.
remote: Counting objects: 100% (20/20), done.
remote: Compressing objects: 100% (9/9), done.
remote: Total 18 (delta 6), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (18/18), 415.91 KiB | 84.00 KiB/s, done.
From file:///tmp/e2e.2527526915/repo
 * branch            f80f1b23b4cab2a295a091c623bb4746d188bd4a -> FETCH_HEAD

$ git cat-file -t f80f1b23b4cab2a295a091c623bb4746d188bd4a
commit

$ git rev-parse FETCH_HEAD
42d21cf12aab73ac8bc6245cc74ac9850bdf6989

FETCH_HEAD was not updated (good) but the rev is question is now present locally (bad), further tested by making a very large commit and watching the fetch be very slow.

Am I using --dry-run wrong?  Is there a different way to ask for what I want?


问:
ASP.NET blazor WebAssembly: detect AOT at run time
In a Blazor WebAssembly project with AOT, is there a way to detect at runtime whether a function body is interpreted or runs natively as WASM instructions?

Background. I tried AOT in my Blazor WebAssembly project. I see that dotnet.wasm.xxx file got much bigger and the general performance has improved. However I have doubts about my code that is loaded and called dynamically. I suspect AOT compiler may not be able to discover that code at build time, and therefore it has to be interpreted at run time. Looking for a way to instrument that code to print at run time if it's being interpreted or runs natively.


问:
Which concept to use for Responsive design?
I recently studied responsive images article from MDN in which they had used tags like <srcset> and <picture> for art direction and resolution switching problem.
https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images

Previously, I had an exposure to media queries and bootstrap for responsive design.

So, currently confused between these things when to use which one....please help on this.


问:
Encountering an error while making an essay app with gpt 3
so i was making a essay app i am getting this error index.html:24

POST https://api.openai.com/v1/completions 429
This is my code
`

Essay Generator

Essay Generator

Topic:

Word Count:

Generate Essay

```<code><script>
 function sendTopicAndWordCount() {
  // Get the topic and word count from the form
  var topic = document.getElementById("topic").value;
  var wordCount = document.getElementById("wordCount").value;

  // Make the API request using a CORS proxy
  fetch("https://api.openai.com/v1/completions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Bearer key"
    },
    body: JSON.stringify({
      "model": "text-davinci-003",
      "prompt": "essay on" + topic,
     "max_tokens": wordCount,
      "temperature": 0.1
    })
  })
  .then(response => response.json())
  .then(response => {
    // Display the API's response in the div
    document.getElementById("response").innerHTML = response.text;
  });
  // https://cors-anywhere.herokuapp.com/https://api.openai.com/v1/completions
  //https://api.openai.com/v1/text-davinci/questions
}
     </script>
       </body>
    </html>
    `
</code>```

I am trying to build an essay generator

Body:
so i was making a essay app i am getting this error index.html:24

POST https://api.openai.com/v1/completions 429
This is my code
`

Essay Generator

Essay Generator

Topic:

Word Count:

Generate Essay

    `

I am trying to build an essay generator


问:
Pytest - Correctly use assert_called_with?
I need to test if a function send was called with specific key:

```<code>from unittest.mock import patch, MagicMock

def send(key=None):
    print('key is', key)

def do_smth():
    send(key='a')

@patch('pitest.decorat.send', return_value=MagicMock())
def test_do_smth(mo):
    do_smth()
    assert mo.assert_called_with(key='a')
</code>```

But I get error:

```<code>Launching pytest with arguments /Users/alber.aleksandrov/PycharmProjects/Playground/pitest/decorat.py --no-header --no-summary -q in /Users/alber.aleksandrov/PycharmProjects/Playground/pitest

============================= test session starts ==============================
collecting ... collected 1 item

decorat.py::test_do_smth FAILED                                          [100%]key is a

decorat.py:11 (test_do_smth)
mo = <MagicMock name='send' id='4551497888'>

    @patch('pitest.decorat.send', return_value=MagicMock())
    def test_do_smth(mo):
        do_smth()
>       assert mo.assert_called_with(key='a')

decorat.py:15:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <MagicMock name='send' id='4551497888'>, args = (), kwargs = {'key': 'a'}
expected = "send(key='a')", actual = 'not called.'
error_message = "expected call not found.\nExpected: send(key='a')\nActual: not called."

    def assert_called_with(self, /, *args, **kwargs):
        """assert that the last call was made with the specified arguments.

        Raises an AssertionError if the args and keyword args passed in are
        different to the last call to the mock."""
        if self.call_args is None:
            expected = self._format_mock_call_signature(args, kwargs)
            actual = 'not called.'
            error_message = ('expected call not found.\nExpected: %s\nActual: %s'
                    % (expected, actual))
>           raise AssertionError(error_message)
E           AssertionError: expected call not found.
E           Expected: send(key='a')
E           Actual: not called.
</code>```

Files:

How to write test properly?

Body:
I need to test if a function send was called with specific key:

from unittest.mock import patch, MagicMock

def send(key=None):
    print('key is', key)

def do_smth():
    send(key='a')

@patch('pitest.decorat.send', return_value=MagicMock())
def test_do_smth(mo):
    do_smth()
    assert mo.assert_called_with(key='a')

But I get error:

Launching pytest with arguments /Users/alber.aleksandrov/PycharmProjects/Playground/pitest/decorat.py --no-header --no-summary -q in /Users/alber.aleksandrov/PycharmProjects/Playground/pitest

============================= test session starts ==============================
collecting ... collected 1 item

decorat.py::test_do_smth FAILED                                          [100%]key is a

decorat.py:11 (test_do_smth)
mo = <MagicMock name='send' id='4551497888'>

    @patch('pitest.decorat.send', return_value=MagicMock())
    def test_do_smth(mo):
        do_smth()
>       assert mo.assert_called_with(key='a')

decorat.py:15:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <MagicMock name='send' id='4551497888'>, args = (), kwargs = {'key': 'a'}
expected = "send(key='a')", actual = 'not called.'
error_message = "expected call not found.\nExpected: send(key='a')\nActual: not called."

    def assert_called_with(self, /, *args, **kwargs):
        """assert that the last call was made with the specified arguments.

        Raises an AssertionError if the args and keyword args passed in are
        different to the last call to the mock."""
        if self.call_args is None:
            expected = self._format_mock_call_signature(args, kwargs)
            actual = 'not called.'
            error_message = ('expected call not found.\nExpected: %s\nActual: %s'
                    % (expected, actual))
>           raise AssertionError(error_message)
E           AssertionError: expected call not found.
E           Expected: send(key='a')
E           Actual: not called.

Files:

How to write test properly?


问:
send post request from react native
```<code>fetch('ADDRESS', {
  method: 'POST',
  headers: {
    'STW-Authorization': 'Basic YmFybmk6YmFybmkxNTY=',
  },
  body: `<?xml version='1.0' encoding='Windows-1250'?>
  <dat:dataPack>
  ...
  </dat:dataPack>`,
})
.then(response => response.text())
.then(data => {
  //var xml = new XMLParser().parseFromString(data);    // Assume xmlText contains the example XML
  console.log(data);
})
.catch(err => console.error(err));

`
</code>```

how can i send body with post method.
because this what i writed code it is not working.
and when i get the response how can i parse in react native

Title: send post request from react native

Body:
fetch('ADDRESS', {
  method: 'POST',
  headers: {
    'STW-Authorization': 'Basic YmFybmk6YmFybmkxNTY=',
  },
  body: `<?xml version='1.0' encoding='Windows-1250'?>
  <dat:dataPack>
  ...
  </dat:dataPack>`,
})
.then(response => response.text())
.then(data => {
  //var xml = new XMLParser().parseFromString(data);    // Assume xmlText contains the example XML
  console.log(data);
})
.catch(err => console.error(err));

`

how can i send body with post method.
because this what i writed code it is not working.
and when i get the response how can i parse in react native


问:
Aws lambda authorizer - cache inside lambda decorator
How can I prevent multiple lambda authorizers triggered at the same time by api gateway from the same user?
It is happening because I’m doing multiple calls from the UI at the same time.
The reason that I want to prevent the behavior is because I’m caching mechanism inside the lambda authorizer which I’m not really enjoying from because of that behavior

thanks everyone for a answer about this or any suggestions


问:
Google Cloud, without organization: How to give another user Billing Account Administrator role for a billing account
I'm migrating resources in Google Cloud from one individual account to another (no organization is set up for either of the accounts).

However I can't find a way to give new account a Billing Account Administrator role for existing billing account. Is it possible?


问:
Espresso Error performing 'single click - At Coordinates: 1693, 181 and precision: 16, 16' on view '
I read through question about same problem but the solutions suggested there did not work for me
I am seeing this only on API 25. I tried on 26 through 29, with same dimensions of the emulator and it all passed.

What I observed is, the click is already happening but somehow the espresso is still waiting. My layout is a custom tab layout. The click is to go to second tab. When the test is waiting, I can see that the second tab is already clicked. I tried to do a manual click on that tab and nothing happens. I can tap on first tab and then tap on second tab and then the test passes.
There is no softkepboard popping up. I tried with show surface updates and do not see any other Ui updates happening at that time.

Here is the stacktrace

```<code>at androidx.test.espresso.PerformException$Builder.build(PerformException.java:5)
at androidx.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:25)
at androidx.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:36)
at androidx.test.espresso.ViewInteraction.waitForAndHandleInteractionResults(ViewInteraction.java:106)
at androidx.test.espresso.ViewInteraction.desugaredPerform(ViewInteraction.java:43)
at androidx.test.espresso.ViewInteraction.perform(ViewInteraction.java:94)```

```

Body:
I read through question about same problem but the solutions suggested there did not work for me
I am seeing this only on API 25. I tried on 26 through 29, with same dimensions of the emulator and it all passed.

What I observed is, the click is already happening but somehow the espresso is still waiting. My layout is a custom tab layout. The click is to go to second tab. When the test is waiting, I can see that the second tab is already clicked. I tried to do a manual click on that tab and nothing happens. I can tap on first tab and then tap on second tab and then the test passes.
There is no softkepboard popping up. I tried with show surface updates and do not see any other Ui updates happening at that time.

Here is the stacktrace

at androidx.test.espresso.PerformException$Builder.build(PerformException.java:5)
at androidx.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:25)
at androidx.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:36)
at androidx.test.espresso.ViewInteraction.waitForAndHandleInteractionResults(ViewInteraction.java:106)
at androidx.test.espresso.ViewInteraction.desugaredPerform(ViewInteraction.java:43)
at androidx.test.espresso.ViewInteraction.perform(ViewInteraction.java:94)```


问:
How work Wangkanai Browser detection on Blazor Server
I'm trying to get the browser information from the user in a Blazor Server application. For this I use the Nuget Package Wangkanai.Detection 6.10. Apparently Blazor support has been added, but the user-agent-string is always used from the server and not from the client.

I have get the *user-agent* from the client

```<code>window.GetUserAgent = () => {
return navigator.userAgent;
}
</code>```

Is there a way to set the user agent string?

Body:
I'm trying to get the browser information from the user in a Blazor Server application. For this I use the Nuget Package Wangkanai.Detection 6.10. Apparently Blazor support has been added, but the user-agent-string is always used from the server and not from the client.

I have get the *user-agent* from the client

window.GetUserAgent = () => {
return navigator.userAgent;
}

Is there a way to set the user agent string?


问:
How to find if a location is part of another?
I am building an app where users can find events within a given location.

For example, if the given location is Europe, it should return all events with locations within Europe.

I have no idea how to go at it, if there is an API that I can use or anything.

Any suggestions?


问:
How to enable unlimited fine-grained ABAC in AWS for S3 objects?
I didn't find any way how to enable Attribute Based Access Control for S3 objects if I need to assign more tag values than one S3 Tag can support:

... tag values can be up to 256 Unicode characters in length. AWS Docs

For example, if I need very fine-grained ABAC to mark an S3 object with 1000 IDs in the Tag Value of the Tag Key IDs, then I will overreach the maximum 256 characters, e.g. IDs=1,2,3,4...999,1000

What can be a solution of that problem?


问:
Cannot retrieve data using PDO, returns empty result
Just to say that I am new to PDO and I am still learning.

I am trying to create a simple application, and connect to a database table that has 5 columns. What I am trying to do is to get all records as objects.

I have a file to create the connection as follow:

```<code>$servername = 'localhost';
$username = 'username';
$password = 'password';
$db = 'database';
try {
    //$conn = new PDO("mysql:host=$servername;dbname=".$db, $username, $password);
    $conn = new PDO("mysql:host=$servername;dbname=$db", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //echo 'Connected successfully';
}
catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
</code>```

If I uncomment the echo I can see "Connected successfully" printed on the screen, so I can see the connection is successful. Than, in my class file I have following:

```<code><?php

declare(strict_types = 1);

/**
 * \file        class/domains.class.php
 * \brief       This file is a CRUD class file for ff (Create/Read/Update/Delete)
 */
class domains
{

    public $id;
    public $label;
    public $website;
    public $ftp;
    public $data_base;

    public function __construct()
    {

        global $conn;

        $this->conn = $conn;
    }

    /**
     *
     * Load the info information in the object
     *
     * @param $id
     * @param $sortorder
     * @param $sortfield
     * @param $limit
     *
     * @return int
     */
    public function fetch($id = '', $sortorder = '', $sortfield = '', $limit = 0)
    {

        $this->conn->beginTransaction();

        if ($id) {
            $where = ' WHERE rowid = :id';
        } else {
            $where = ' WHERE 1 = 1';
        }
        if (!empty($sortfield)) {
            $sort = ' ORDER BY ' . $sortfield;
        }
        if (!empty($sortorder)) {
            $sort = ' DESC';
        }
        if (!empty($limit)) {
            $lim = ' LIMIT ' . $limit;
        }

        $sql = $this->conn->prepare('SELECT t.rowid as id, t.label, t.website, t.data_base, r.rowid as line_id, r.is_db, r.is_site, r.is_ftp, r.db_name, r.server, r.url, r.username, r.pass_crypted FROM domains as t INNER JOIN records as r ON r.fk_domain = t.rowid ' . $where . ' ' . $sort . ' ' . $lim . '');

        if ($id) {
            $sql->bindParam(':id', $this->id, PDO::PARAM_INT);
        }

        try {
            $result = $sql->fetchAll(PDO::FETCH_CLASS, "domains");
            if ($result) {
                return 1;
            } else {
                return -1;
            }
        }
        catch (Exception $e) {
            print $e->getMessage();

            return -2;
        }
    }

}
</code>```

Whatever I use as "$result = $sql->" the return is always -1 and in my log file I see 221225 22:20:03      14 Connect  user@localhost as database on passman

Am I doing something wrong with the prepared statement? The file that handles the connection is included before the object initialization and '$object->fetch()'

Body:
Just to say that I am new to PDO and I am still learning.

I am trying to create a simple application, and connect to a database table that has 5 columns. What I am trying to do is to get all records as objects.

I have a file to create the connection as follow:

$servername = 'localhost';
$username = 'username';
$password = 'password';
$db = 'database';
try {
    //$conn = new PDO("mysql:host=$servername;dbname=".$db, $username, $password);
    $conn = new PDO("mysql:host=$servername;dbname=$db", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //echo 'Connected successfully';
}
catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

If I uncomment the echo I can see "Connected successfully" printed on the screen, so I can see the connection is successful. Than, in my class file I have following:

<?php

declare(strict_types = 1);

/**
 * \file        class/domains.class.php
 * \brief       This file is a CRUD class file for ff (Create/Read/Update/Delete)
 */
class domains
{

    public $id;
    public $label;
    public $website;
    public $ftp;
    public $data_base;

    public function __construct()
    {

        global $conn;

        $this->conn = $conn;
    }

    /**
     *
     * Load the info information in the object
     *
     * @param $id
     * @param $sortorder
     * @param $sortfield
     * @param $limit
     *
     * @return int
     */
    public function fetch($id = '', $sortorder = '', $sortfield = '', $limit = 0)
    {

        $this->conn->beginTransaction();

        if ($id) {
            $where = ' WHERE rowid = :id';
        } else {
            $where = ' WHERE 1 = 1';
        }
        if (!empty($sortfield)) {
            $sort = ' ORDER BY ' . $sortfield;
        }
        if (!empty($sortorder)) {
            $sort = ' DESC';
        }
        if (!empty($limit)) {
            $lim = ' LIMIT ' . $limit;
        }

        $sql = $this->conn->prepare('SELECT t.rowid as id, t.label, t.website, t.data_base, r.rowid as line_id, r.is_db, r.is_site, r.is_ftp, r.db_name, r.server, r.url, r.username, r.pass_crypted FROM domains as t INNER JOIN records as r ON r.fk_domain = t.rowid ' . $where . ' ' . $sort . ' ' . $lim . '');

        if ($id) {
            $sql->bindParam(':id', $this->id, PDO::PARAM_INT);
        }

        try {
            $result = $sql->fetchAll(PDO::FETCH_CLASS, "domains");
            if ($result) {
                return 1;
            } else {
                return -1;
            }
        }
        catch (Exception $e) {
            print $e->getMessage();

            return -2;
        }
    }

}

Whatever I use as "$result = $sql->" the return is always -1 and in my log file I see 221225 22:20:03      14 Connect  user@localhost as database on passman

Am I doing something wrong with the prepared statement? The file that handles the connection is included before the object initialization and '$object->fetch()'


Title: helmholtz decomposition of a vector V(x,z)=[f(x,z),0,0]

Body:
i wrote the below program in python with the hope of conducting a Helmholtz decomposition on a vector V(x,z)=[f(x,z),0,0] where f(x,z) is a function defined earlier, the aim of this program is to get the solenoidal and harmonic parts of vector V as S(x,z)=[S1(x,z),S2(x,z),S3(x,z)] and H(x,z)=[H1(x,z),H2(x,z),H3(x,z)] with S and H satisfying the condition V=S+H which transllates to (S1+H1=f, S2+H2=0, S3+H3=0)

please help i cant get anywhere with this problem, the output of the above code isnt what i wanted , its the following:

Solenoidal:
[[-22.6179559436889 + 41.14742726254I, 33.243161684442 - 99.9416505604629I, -22.6179559436889 + 41.14742726254I], [0.000151144774536593 + 0.000222403457962539I, 0, -0.000151144774536593 - 0.000222403457962539I], [22.6210744289585 - 41.1540953247099I, -41.2442631673893 + 88.1909008014634I, 6.6295316668479 - 64.6849359328842I]]
Harmonic:
[[26.6155393446675 - 35.2651619174123I, -33.243161684442 + 99.9416505604629I, 18.6203725427103 - 47.0296926076676I], [-0.000151144774536593 - 0.000222403457962539I, 0, 0.000151144774536593 + 0.000222403457962539I], [-18.6231887384308 + 47.0368054767535I, 41.2442631673893 - 88.1909008014634I, -10.6274173573755 + 58.8022257808406I]]

`

import math
import numpy as np
from sympy import symbols, simplify, lambdify

# Define x and z as symbolic variables
x, z = symbols('x, z')

# Define the function f
def f(x, z):
  term1 = 171.05 * 10**(-18) * ((1.00 * x**4 + 2.00 * x**2 * z**2 + 1.00 * z**4) * math.atan(z*x) - 1.00 * x**3 * z - 1.00 * x * z**3)
  term2 = -3.17 * 10**6 * x**4 - 6.36 * 10**6 * x**2 * z**2 - 3.19 * 10**6 * z**4 + 1.00 * x**4 * z + 2.00 * x**2 * z**3 + 1.00 * z**5
  term3 = (z - 44.33 * 10**3)
  term4 = ((-2.00 * 10**3) / (576.30 * 10**3 + 13.00 * z))**2.69 * (x**2 + z**2)**7.00 / 2.00 * z
  return term1 * term2 * term3 / (term4 + 1e-15)  # Add a small value to term4 to avoid division by zero

# Define a 2D array with 3 elements
vector = np.array([[f(x, z) for x in range(-1, 2)] for z in range(-1, 2)])

def helmholtz_hodge_decomposition(vector):
  # Compute the gradient of the vector field
  gradient = np.gradient(vector)

  # Compute the curl of the vector field
  curl = np.cross(gradient[0], gradient[1])

  # Compute the divergence of the vector field
  divergence = np.sum(gradient, axis=0)

  # Compute the harmonic part of the vector field
  harmonic = -curl - divergence

  # Compute the solenoidal part of the vector field
  solenoidal = vector - harmonic

  return solenoidal, harmonic

# Print the solenoidal and harmonic parts as functions of x and z
solenoidal, harmonic = helmholtz_hodge_decomposition(vector)
print("Solenoidal:")
print(simplify(solenoidal))
print("Harmonic:")
print(simplify(harmonic))

# Create functions from the solenoidal and harmonic parts
solenoidal_part = lambdify((x, z), simplify(solenoidal), 'numpy')
harmonic_part = lambdify((x, z), simplify(harmonic), 'numpy')

`

expecting :Conducting a Helmholtz decomposition on a vector V(x,z)=[f(x,z),0,0] where f(x,z) is a function defined earlier, the aim of this program is to get the solenoidal and harmonic parts of vector V as S(x,z)=[S1(x,z),S2(x,z),S3(x,z)] and H(x,z)=[H1(x,z),H2(x,z),H3(x,z)] with S and H satisfying the condition V=S+H which transllates to (S1+H1=f, S2+H2=0, S3+H3=0)


问:
Why is a double tap required the child buttons ExpandableListView?
The first time you click on the child element button, nothing happens.
When I click the second time, the event is executed.

```<code>@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
                         View convertView, ViewGroup parent) {
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.child_view, null);
        fConvertView = convertView;
    }

    Button buttonRestart = (Button)convertView.findViewById(R.id.buttonRestart);
    buttonRestart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view){

        }
    });
</code>```

At the same time, in my code, the child group collapses and unfolds every second.

```<code>private void startTimer(final long finish, long tick, int posic) {
    mTimerRunning.set(posic, true);
    countDownTimers[posic] = new CountDownTimer(finish, tick) {
        @Override
        public void onTick(long millisUntilFinished) {

            mTimeLeftInMillis.set(posic, millisUntilFinished);
            long remainedSecs = millisUntilFinished / 1000;

            ArrayList<String> children = new ArrayList<String>();
            String minute = String.valueOf((remainedSecs / 60));
            if((remainedSecs / 60) < 10){
                minute = "0" + minute;
            }
            String sec = String.valueOf((remainedSecs % 60));
            if((remainedSecs % 60) < 10){
                sec = "0" + sec;
            }

            String time = "" + minute + ":" + sec;
            children.add(time + "@" + resStr);
            mGroups.set(posic,children);
            listView.collapseGroup(posic);
            listView.expandGroup(posic);

        }
        @Override
        public void onFinish() {
            mTimerRunning.set(posic, false);
            listView.collapseGroup(posic);
            cancel();
        }
    }.start();
}
</code>```

How can this be fixed? I need the button to be pressed the first time.

I tried adding

```<code>android:focusableInTouchMode="false"
</code>```
```<code>android:descendantFocusability="afterDescendants"
</code>```
```<code>listView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
</code>```

In Android Manifest

```<code>android:windowSoftInputMode="adjustPan"
</code>```

Body:
The first time you click on the child element button, nothing happens.
When I click the second time, the event is executed.

@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
                         View convertView, ViewGroup parent) {
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.child_view, null);
        fConvertView = convertView;
    }

    Button buttonRestart = (Button)convertView.findViewById(R.id.buttonRestart);
    buttonRestart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view){

        }
    });

At the same time, in my code, the child group collapses and unfolds every second.

private void startTimer(final long finish, long tick, int posic) {
    mTimerRunning.set(posic, true);
    countDownTimers[posic] = new CountDownTimer(finish, tick) {
        @Override
        public void onTick(long millisUntilFinished) {

            mTimeLeftInMillis.set(posic, millisUntilFinished);
            long remainedSecs = millisUntilFinished / 1000;

            ArrayList<String> children = new ArrayList<String>();
            String minute = String.valueOf((remainedSecs / 60));
            if((remainedSecs / 60) < 10){
                minute = "0" + minute;
            }
            String sec = String.valueOf((remainedSecs % 60));
            if((remainedSecs % 60) < 10){
                sec = "0" + sec;
            }

            String time = "" + minute + ":" + sec;
            children.add(time + "@" + resStr);
            mGroups.set(posic,children);
            listView.collapseGroup(posic);
            listView.expandGroup(posic);

        }
        @Override
        public void onFinish() {
            mTimerRunning.set(posic, false);
            listView.collapseGroup(posic);
            cancel();
        }
    }.start();
}

How can this be fixed? I need the button to be pressed the first time.

I tried adding

android:focusableInTouchMode="false"

android:descendantFocusability="afterDescendants"

listView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);

In Android Manifest

android:windowSoftInputMode="adjustPan"


问:
How do I configure ESLint to add line spacing between my path aliases?
Right now with my ESLint auto import sorter and ESLint configuration, everything works fine. But I want to add line spacing between my different aliases. Not sure how I can accomplish that.

Right now React imports go on top and all others are grouped together with a space between.

.eslintrc.js

```<code>module.exports = {
  root: true,
  extends: '@react-native-community',
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint', 'import'],
  overrides: [
    {
      files: ['*.ts', '*.tsx'],
      rules: {
        'no-undef': 'off',
        'no-shadow': 'off',
        'react/jsx-uses-react': 'off',
        'react/react-in-jsx-scope': 'off',
        '@typescript-eslint/no-shadow': ['error'],
        'sort-imports': [
          'error',
          { ignoreCase: true, ignoreDeclarationSort: true },
        ],
        'import/order': [
          'error',
          {
            groups: [
              ['external', 'builtin'],
              'internal',
              ['sibling', 'parent'],
              'index',
            ],
            pathGroups: [
              {
                pattern: '@(react|react-native)',
                group: 'external',
                position: 'before',
              },
              {
                pattern: '@tests/**',
                group: 'internal',
              },
              {
                pattern: '@assets/**',
                group: 'internal',
              },
              {
                pattern: '@components/**',
                group: 'internal',
              },
              {
                pattern: '@config/**',
                group: 'internal',
              },
              {
                pattern: '@constants/**',
                group: 'internal',
              },
              {
                pattern: '@hooks/**',
                group: 'internal',
              },
              {
                pattern: '@jotai/**',
                group: 'internal',
              },
              {
                pattern: '@navigation/**',
                group: 'internal',
              },
              {
                pattern: '@routes/**',
                group: 'internal',
              },
              {
                pattern: '@screens/**',
                group: 'internal',
              },
              {
                pattern: '@theme/**',
                group: 'internal',
              },
              {
                pattern: '@types/**',
                group: 'internal',
              },
              {
                pattern: '@utils/**',
                group: 'internal',
              },
            ],
            pathGroupsExcludedImportTypes: ['internal', 'react'],
            'newlines-between': 'always',
            alphabetize: {
              order: 'asc',
              caseInsensitive: true,
            },
          },
        ],
      },
    },
  ],
};
</code>```

tsconfig.json

```<code>{
  "extends": "@tsconfig/react-native/tsconfig.json",
  "compilerOptions": {
    "strict": true,
    "skipLibCheck": true,
    "baseUrl": ".",
    "paths": {
      "@tests/*": ["src/__tests__/*"],
      "@assets/*": ["src/assets/*"],
      "@components/*": ["src/components/*"],
      "@config/*": ["src/config/*"],
      "@constants/*": ["src/constants/*"],
      "@hooks/*": ["src/hooks/*"],
      "@jotai/*": ["src/jotai/*"],
      "@navigation/*": ["src/navigation/*"],
      "@routes/*": ["src/routes/*"],
      "@screens/*": ["src/screens/*"],
      "@theme/*": ["src/theme/*"],
      "@app/types/*": ["src/types/*"],
      "@app/utils/*": ["src/utils/*"]
    }
  }
}
</code>```

How it currently looks, but want more spacing between the different aliases.
Thank you and Merry Christmas!

Body:
Right now with my ESLint auto import sorter and ESLint configuration, everything works fine. But I want to add line spacing between my different aliases. Not sure how I can accomplish that.

Right now React imports go on top and all others are grouped together with a space between.

.eslintrc.js

module.exports = {
  root: true,
  extends: '@react-native-community',
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint', 'import'],
  overrides: [
    {
      files: ['*.ts', '*.tsx'],
      rules: {
        'no-undef': 'off',
        'no-shadow': 'off',
        'react/jsx-uses-react': 'off',
        'react/react-in-jsx-scope': 'off',
        '@typescript-eslint/no-shadow': ['error'],
        'sort-imports': [
          'error',
          { ignoreCase: true, ignoreDeclarationSort: true },
        ],
        'import/order': [
          'error',
          {
            groups: [
              ['external', 'builtin'],
              'internal',
              ['sibling', 'parent'],
              'index',
            ],
            pathGroups: [
              {
                pattern: '@(react|react-native)',
                group: 'external',
                position: 'before',
              },
              {
                pattern: '@tests/**',
                group: 'internal',
              },
              {
                pattern: '@assets/**',
                group: 'internal',
              },
              {
                pattern: '@components/**',
                group: 'internal',
              },
              {
                pattern: '@config/**',
                group: 'internal',
              },
              {
                pattern: '@constants/**',
                group: 'internal',
              },
              {
                pattern: '@hooks/**',
                group: 'internal',
              },
              {
                pattern: '@jotai/**',
                group: 'internal',
              },
              {
                pattern: '@navigation/**',
                group: 'internal',
              },
              {
                pattern: '@routes/**',
                group: 'internal',
              },
              {
                pattern: '@screens/**',
                group: 'internal',
              },
              {
                pattern: '@theme/**',
                group: 'internal',
              },
              {
                pattern: '@types/**',
                group: 'internal',
              },
              {
                pattern: '@utils/**',
                group: 'internal',
              },
            ],
            pathGroupsExcludedImportTypes: ['internal', 'react'],
            'newlines-between': 'always',
            alphabetize: {
              order: 'asc',
              caseInsensitive: true,
            },
          },
        ],
      },
    },
  ],
};

tsconfig.json

{
  "extends": "@tsconfig/react-native/tsconfig.json",
  "compilerOptions": {
    "strict": true,
    "skipLibCheck": true,
    "baseUrl": ".",
    "paths": {
      "@tests/*": ["src/__tests__/*"],
      "@assets/*": ["src/assets/*"],
      "@components/*": ["src/components/*"],
      "@config/*": ["src/config/*"],
      "@constants/*": ["src/constants/*"],
      "@hooks/*": ["src/hooks/*"],
      "@jotai/*": ["src/jotai/*"],
      "@navigation/*": ["src/navigation/*"],
      "@routes/*": ["src/routes/*"],
      "@screens/*": ["src/screens/*"],
      "@theme/*": ["src/theme/*"],
      "@app/types/*": ["src/types/*"],
      "@app/utils/*": ["src/utils/*"]
    }
  }
}

How it currently looks, but want more spacing between the different aliases.
Thank you and Merry Christmas!


问:
Which is better way to rotate logs of Django Application, logging Module of Python or Logrotate of linux?
I want to rotate my logs of Django application, I am able to rotate the logs (based on size) successfully with logging module of python but its causing issue because same log file is getting accessed by celery process and other processes and because of that sometimes application is writing logs in debug.log.1 instead of debug.log file (assume my log file name is debug.log). I suspect this is because my celery process and django server (uwsgi server) is running by different user and because of permission issue it is behaving like that.

I am thinking of using logrotate of linux to rotate my log instead of using python class

```<code>logging.handlers.RotatingFileHandler
</code>```

Can anyone help me in choosing the best way to rotate the log also if you can help me understand why my application is suddenly writing logs in debug.log.1 file instead of debug.log that would be great.

Body:
I want to rotate my logs of Django application, I am able to rotate the logs (based on size) successfully with logging module of python but its causing issue because same log file is getting accessed by celery process and other processes and because of that sometimes application is writing logs in debug.log.1 instead of debug.log file (assume my log file name is debug.log). I suspect this is because my celery process and django server (uwsgi server) is running by different user and because of permission issue it is behaving like that.

I am thinking of using logrotate of linux to rotate my log instead of using python class

logging.handlers.RotatingFileHandler

Can anyone help me in choosing the best way to rotate the log also if you can help me understand why my application is suddenly writing logs in debug.log.1 file instead of debug.log that would be great.


问:
How to structure a table when there is sensitive data in mongodb
goal:
restrict access to who can see an API key that is stored in a record in the channel collection.

issue:
I am not sure how to set the data structure for this,

context:
I am working on a platform where people can sell data to other people. This platform allows for data to be streamed by API calls.
example:
user 1 creates a 'stream' record.
the 'stream' record contains information about what the stream contains, such as information about flowers or chocolates.

user 2 purchases the rights to the stream.

user 2 should see an API key to which he will use to identify the data in his system.

when user 1 sends data, the data will first hit our system, then the data will be redirected to user 2 system, and that will be identified using this API key.

question:
I want to create a field on a collection's record that is only readable by users who purchased the record.
note: more than 1 user can purchase the stream

is this possible?

Approach 1:
create a separate collection that stores api keys in relation to any give channel

Approach 2:
store the api keys in the channel record itself

I know I can create another collection, where I can restrict who can access the whole record, then put the API key there.

But I wanted to see if I can restrict fields on a records field.


问:
Having problem with Next.js while adding additional script
Image

I'm working with next js for a digital agency website. There are several scripts that we should use in our next app. Firstly we tried to use script in _document.js file. Then we tried to create a component with those scripts and import it where it is needed. But unfortunately we failed in both cases. The scripts doesn't work. We also tried to use Script component from next. It’s also not working. But while we use those scripts directly to the component, as shown in the image, surprisingly it works. But we don’t want to use them every time with every components directly. We want to use it for one time but should work for every components that rendered. Is there any way to do this? I'm a new bee in this programing world. So I'm expecting help from my elders. Thanks in advance.

I'm trying to write those scripts for one time and expecting from them to do work for all the pages that rendered in the UI.


问:
I have an indicator need buy and sell trigger in a specific area
I need your help with this indicator, So I need a buy and sell signal in a particular condition; please see the attached pictureImage for alert understanding Here you will find the source code of my indicator, you can put it in your trading view account to see what I mean for alert creating... Please help me

```<code>enter code here
</code>```

//@version=5

indicator(title="The Sniper", shorttitle="The Sniper", format=format.price, precision=2, timeframe="", timeframe_gaps=true)

ma(source, length, type) =>
    switch type
        "SMA" => ta.sma(source, length)

ma27(source, length, type) =>
    switch type
        "SMA" => ta.ema(source, length)

ma27TypeInput = input.string("SMA", title="ma27 Type", options=["SMA"], group="MA Settings")

ma27LengthInput = input.int(27, title="ma27 Length", group="MA Settings")

ema21(source, length, type) =>
    switch type
        "EMA" => ta.ema(source, length)

ema21TypeInput = input.string("EMA", title="ema21 Type", options=["EMA"], group="EMA Settings")

ema21LengthInput = input.int(21, title="ema21 Length", group="EMA Settings")

rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="RSI Settings")
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
ma21TypeInput = input.string("SMA", title="MA Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA Settings")
maLengthInput = input.int(21, title="MA21 Length", group="MA21 Settings")

up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
rsiMA21 = ma(rsi, maLengthInput, ma21TypeInput)
rsima27 = ma27(rsi, ma27LengthInput, ma27TypeInput)

//rsiema21 = ema21(rsi, ema21LengthInput, ema21TypeInput)

isBB = ma21TypeInput == "Bollinger Bands"

rsima21 = plot(rsiMA21, "RSI-based MA21", color.orange, linewidth = 2, style = plot.style_stepline)
//rsiema211 = plot(rsiema21, "RSI-based ema21", color=color.red, linewidth = 2)
plot(rsima27, "RSI-based ma27", color=color.red, linewidth = 2)
plot(rsi, "RSI", color=#7E57C2, linewidth = 2)

rsiu = hline(70, "RSI Upper Band", color=#787B86)
Red = plot(55, color=color.new(color.red, 0), linewidth=2, title= 'RedLine')

rsil = hline(30, "RSI Lower Band", color=#787B86)
Green = plot(45, color=color.new(color.green, 0), linewidth=2, title= 'Green')

fill(rsiu, rsil, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")```

Body:
I need your help with this indicator, So I need a buy and sell signal in a particular condition; please see the attached pictureImage for alert understanding Here you will find the source code of my indicator, you can put it in your trading view account to see what I mean for alert creating... Please help me

enter code here

//@version=5

indicator(title="The Sniper", shorttitle="The Sniper", format=format.price, precision=2, timeframe="", timeframe_gaps=true)

ma(source, length, type) =>
    switch type
        "SMA" => ta.sma(source, length)

ma27(source, length, type) =>
    switch type
        "SMA" => ta.ema(source, length)

ma27TypeInput = input.string("SMA", title="ma27 Type", options=["SMA"], group="MA Settings")

ma27LengthInput = input.int(27, title="ma27 Length", group="MA Settings")

ema21(source, length, type) =>
    switch type
        "EMA" => ta.ema(source, length)

ema21TypeInput = input.string("EMA", title="ema21 Type", options=["EMA"], group="EMA Settings")

ema21LengthInput = input.int(21, title="ema21 Length", group="EMA Settings")

rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="RSI Settings")
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
ma21TypeInput = input.string("SMA", title="MA Type", options=["SMA", "Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group="MA Settings")
maLengthInput = input.int(21, title="MA21 Length", group="MA21 Settings")

up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
rsiMA21 = ma(rsi, maLengthInput, ma21TypeInput)
rsima27 = ma27(rsi, ma27LengthInput, ma27TypeInput)

//rsiema21 = ema21(rsi, ema21LengthInput, ema21TypeInput)

isBB = ma21TypeInput == "Bollinger Bands"

rsima21 = plot(rsiMA21, "RSI-based MA21", color.orange, linewidth = 2, style = plot.style_stepline)
//rsiema211 = plot(rsiema21, "RSI-based ema21", color=color.red, linewidth = 2)
plot(rsima27, "RSI-based ma27", color=color.red, linewidth = 2)
plot(rsi, "RSI", color=#7E57C2, linewidth = 2)

rsiu = hline(70, "RSI Upper Band", color=#787B86)
Red = plot(55, color=color.new(color.red, 0), linewidth=2, title= 'RedLine')

rsil = hline(30, "RSI Lower Band", color=#787B86)
Green = plot(45, color=color.new(color.green, 0), linewidth=2, title= 'Green')

fill(rsiu, rsil, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")