问:
Palindrome problem - What am I doing wrong Here?
Problem statement:
You are given a binary string S and an integer K. In one operation, you can pick any bit and flip it, i.e turn 0 to 1 or 1 to 0. Can you make the string S a palindrome using exactly K operations?

Print YES if this is possible, and NO if it is not.

Input Format
The first line of input contains one integer T, denoting the number of test cases. The description of T test cases follows.
Each test case consists of two lines of input.
The first line of each test case contains two space-separated integers N and K, denoting the length of the binary string and the number of operations to be performed.
The second line contains the binary string S.
Output Format
For each test case, print the answer on a new line — YES if the S can be made a palindrome using exactly K operations, and NO otherwise.

You may print each character of YES and NO in either uppercase or lowercase (for example, yes, yEs, Yes will all be considered identical).

My solution:

```<code>T = int(input())
for i in range(T):
    N,K = map(int,input().split())
    S = input()
    counter = 0
    for i in range(int(len(S)/2)):
        if S[i] == S[-1-i]:
            continue
        else:
            counter = counter + 1
    if counter == K:
        print("Yes")
    else:
        print("No")
</code>```

But on submission, it shows the wrong answer, and upon custom input, it shows correct output, can someone point out what am I doing wrong?

答:
#include <bits/stdc++.h>
using namespace std;</p>
```<code>int main(){
    int t,n,k,i,j,c;
    cin>>t;
    while(t--){
        cin>>n>>k;
        char str[n];
        for( i=1;i<=n;i++){
            cin>>str[i];
        }
        str[0]=i;
        str[n-1]=j;
        while(i<=j){
            if(str[i++]!=str[j--]){
                c--;
            }

        }
        if(c=k){
            cout<<"YES"<<endl;
        }
        else{
            cout<<"NO"<<endl;
        }

    }
    return 0;
}
</code>```

Body:
Problem statement:
You are given a binary string S and an integer K. In one operation, you can pick any bit and flip it, i.e turn 0 to 1 or 1 to 0. Can you make the string S a palindrome using exactly K operations?

Print YES if this is possible, and NO if it is not.

Input Format
The first line of input contains one integer T, denoting the number of test cases. The description of T test cases follows.
Each test case consists of two lines of input.
The first line of each test case contains two space-separated integers N and K, denoting the length of the binary string and the number of operations to be performed.
The second line contains the binary string S.
Output Format
For each test case, print the answer on a new line — YES if the S can be made a palindrome using exactly K operations, and NO otherwise.

You may print each character of YES and NO in either uppercase or lowercase (for example, yes, yEs, Yes will all be considered identical).

My solution:

T = int(input())
for i in range(T):
    N,K = map(int,input().split())
    S = input()
    counter = 0
    for i in range(int(len(S)/2)):
        if S[i] == S[-1-i]:
            continue
        else:
            counter = counter + 1
    if counter == K:
        print("Yes")
    else:
        print("No")

But on submission, it shows the wrong answer, and upon custom input, it shows correct output, can someone point out what am I doing wrong?

Body:
#include <bits/stdc++.h>
using namespace std;

int main(){
    int t,n,k,i,j,c;
    cin>>t;
    while(t--){
        cin>>n>>k;
        char str[n];
        for( i=1;i<=n;i++){
            cin>>str[i];
        }
        str[0]=i;
        str[n-1]=j;
        while(i<=j){
            if(str[i++]!=str[j--]){
                c--;
            }

        }
        if(c=k){
            cout<<"YES"<<endl;
        }
        else{
            cout<<"NO"<<endl;
        }

    }
    return 0;
}


来源: stackexchange

问:
Generating downloadable reports with shiny in LAN
I shared an Rshiny app in LAN with my coworkers PCs, so I used shiny.host and shiny.port

So when my coworkers in theirs PCs tried to download reports when clicking in a report_button button, they received the last values that I chose on my PC

example:
On my PC I choose input$slider = 46 and I download the report file in HTML, then my coworker on his PC opens the link 192.168.5.140:8888 in his browser, chooses input$slider=73 and downloads the file, and then (!!!) he gets the same report that I got, i.e he gets input$slider = 46

here is the code :

```<code>library(shiny)
options(shiny.host = '192.168.5.140')
options(shiny.port = 8888)

ui = fluidPage(
  sliderInput("slider", "Slider", 1, 100, 50),
  downloadButton("report_button", "Generate report")
)

server = function(input, output) {

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

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

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

and the report.RMD file :

```<code>---
title: "Dynamic report"
output: html_document
params:
  n: NA
---

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

答:
You should be able to prevent this situation by using tempfile instead of tempdir to create the temporary Rmd file.

tempdir is constant as long as you are running the same R-session - which might end up in concurrent shiny sessions overwriting each others report results.

tempfile however, creates a unique file for each function call:

```<code>library(shiny)
options(shiny.host = '0.0.0.0')
options(shiny.port = 8888)

ui = fluidPage(
  sliderInput("slider", "Slider", 1, 100, 50),
  downloadButton("report_button", "Generate report")
)

server = function(input, output) {

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

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

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

ContentLicense: CC BY-SA 4.0

Body:
I shared an Rshiny app in LAN with my coworkers PCs, so I used shiny.host and shiny.port

So when my coworkers in theirs PCs tried to download reports when clicking in a report_button button, they received the last values that I chose on my PC

example:
On my PC I choose input$slider = 46 and I download the report file in HTML, then my coworker on his PC opens the link 192.168.5.140:8888 in his browser, chooses input$slider=73 and downloads the file, and then (!!!) he gets the same report that I got, i.e he gets input$slider = 46

here is the code :

library(shiny)
options(shiny.host = '192.168.5.140')
options(shiny.port = 8888)

ui = fluidPage(
  sliderInput("slider", "Slider", 1, 100, 50),
  downloadButton("report_button", "Generate report")
)

server = function(input, output) {

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

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

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

and the report.RMD file :

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

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

Body:
You should be able to prevent this situation by using tempfile instead of tempdir to create the temporary Rmd file.

tempdir is constant as long as you are running the same R-session - which might end up in concurrent shiny sessions overwriting each others report results.

tempfile however, creates a unique file for each function call:

library(shiny)
options(shiny.host = '0.0.0.0')
options(shiny.port = 8888)

ui = fluidPage(
  sliderInput("slider", "Slider", 1, 100, 50),
  downloadButton("report_button", "Generate report")
)

server = function(input, output) {

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

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

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


问:
cucumber cypress query > After configer with .feature file, why .js file not apper
I have configured my package.json & cypress.json & index.js as per cucumber requirement refer this link < https://github.com/TheBrainFamily/cypress-cucumber-preprocessor>

file stucture C:\Users\Ankit\CypressAutomation\cypress\integration\2-advanced-examples\BDD\ecommerce\ecommercestepdef.js & for feature file C:\Users\Ankit\CypressAutomation\cypress\integration\2-advanced-examples\BDD\ecommerce.feature

I have getting error in this:- node_modules/cypress-cucumber-preprocessor/lib/resolveStepDefinition.js:199:1

Step implementation missing for: I open ecommerce page

folder structure & feature file
data from fixture

stepdeintion1

stepdefination2

plugins>indexjs

packetjson

cypressjson

答: I guess there's a blank space before the step definition 1, at line 12, that could cause preprocessor not to recognize the implementation of the sentence in the feature


问:
Problem getting output of sp_executesql into a table column (SQL SERVER)
I have a table called QUERY_TABLE.
QUERY_TABLE contains queries of the following format (nothing dynamic, except the parameters in the WHERE clause):

```<code>  SELECT
     CASE
         WHEN COUNT(*) > 10 THEN 'Y'
         ELSE 'N'
     END check_ind
FROM
     DATA_TABLE
WHERE date_y = @DATE_Y AND date_m = @DATE_M
</code>```

I wrote the following script, to fetch each one of the above queries, run it, and put the result into another table - CONTROL_LOG_TABLE.

My problem is that the result column, STATUS_IND, should get either 'Y' or 'N' as values, but for some reason I have not figured out yet, it contains '0'.

Appreciate your help!

```<code>DECLARE
       @DATE_C DATE,
       @DATE_Y           INTEGER,
       @DATE_M           INTEGER,
       @CHECK_NUM        INTEGER,
       @CHECK_ID         INTEGER,
       @CTRLM_TREE       VARCHAR(50),
       @CTRLM_TREE_PARAM VARCHAR(50),
       @SQL_QUERY        NVARCHAR(MAX),
       @CHECK_DESC       NVARCHAR(MAX),
       @ACTION_DESC      NVARCHAR(MAX),
       @EXEC_SQL_QUERY   NVARCHAR(MAX),
       @RESULT_SQL       CHAR(1),
       @RowNo            INTEGER,
          @params NVARCHAR(100) = '@DATE_Y NVARCHAR(4), @DATE_M NVARCHAR(2)';

BEGIN

SET @RowNo = 0;
SET @DATE_C = GETDATE();
SET @DATE_Y = (SELECT YEAR (@DATE_C));
SET @DATE_M = (SELECT MONTH (@DATE_C));

DECLARE CURSOR_CHECK_ID CURSOR
FOR SELECT
       CHECK_ID,
       CTRLM_TREE,
       SQL_QUERY,
       CHECK_DESC,
       ACTION_DESC
    FROM
       QUERY_TABLE

OPEN CURSOR_CHECK_ID;
FETCH NEXT FROM CURSOR_CHECK_ID INTO
            @CHECK_ID,
            @CTRLM_TREE,
            @SQL_QUERY,
            @CHECK_DESC,
            @ACTION_DESC;
       WHILE @@FETCH_STATUS = 0
    BEGIN
           SET @RowNo = @RowNo+1
           SET @CHECK_NUM = @RowNo
           SET @EXEC_SQL_QUERY = @SQL_QUERY

                       EXECUTE @result_sql = sp_executesql @EXEC_SQL_QUERY, @params, @DATE_Y, @DATE_M

        INSERT INTO CONTROL_LOG_TABLE (UPDATE_DATE, DATE_C, CHECK_NUM, CHECK_ID, CTRLM_TREE, SQL_QUERY,
              CHECK_DESC, ACTION_DESC, STATUS_IND)
              values (GETDATE(), @DATE_C, @RowNo, @CHECK_ID, @CTRLM_TREE, @SQL_QUERY, @CHECK_DESC, @ACTION_DESC, @RESULT_SQL)

        FETCH NEXT FROM CURSOR_CHECK_ID INTO
            @CHECK_ID,
            @CTRLM_TREE,
            @SQL_QUERY,
            @CHECK_DESC,
            @ACTION_DESC;
    END;
CLOSE CURSOR_CHECK_ID;
DEALLOCATE CURSOR_CHECK_ID;
END;
</code>```

答:
One solution is to move the INSERT into the dynamic query.

You don't need to actually change those queries, you can just concatenate the INSERT around it.

SET @EXEC_SQL_QUERY = '
        INSERT INTO CONTROL_LOG_TABLE (UPDATE_DATE, DATE_C, CHECK_NUM, CHECK_ID, CTRLM_TREE, SQL_QUERY,
              CHECK_DESC, ACTION_DESC, STATUS_IND)
              values (GETDATE(), @DATE_C, @RowNo, @CHECK_ID, @CTRLM_TREE, @SQL_QUERY, @CHECK_DESC, @ACTION_DESC, (' + @SQL_QUERY + ')';
';
```
<p>Another way of doing it is to concatenate <code>SET @outputvariable</code> to it:</p>
```SET @EXEC_SQL_QUERY = 'SET @result = (' + @SQL_QUERY + ');
';

EXECUTE sp_executesql @EXEC_SQL_QUERY, @params, @DATE_Y, @DATE_M, @result_sql;

        INSERT INTO CONTROL_LOG_TABLE (UPDATE_DATE, DATE_C, CHECK_NUM, CHECK_ID, CTRLM_TREE, SQL_QUERY,
              CHECK_DESC, ACTION_DESC, STATUS_IND)
              values (GETDATE(), @DATE_C, @RowNo, @CHECK_ID, @CTRLM_TREE, @SQL_QUERY, @CHECK_DESC, @ACTION_DESC, @RESULT_SQL)
```

and you would need to add that output parameter to @params also.

I'm assuming you have all your bases covered with SQL injection here.

Body:
I have a table called QUERY_TABLE.
QUERY_TABLE contains queries of the following format (nothing dynamic, except the parameters in the WHERE clause):

  SELECT
     CASE
         WHEN COUNT(*) > 10 THEN 'Y'
         ELSE 'N'
     END check_ind
FROM
     DATA_TABLE
WHERE date_y = @DATE_Y AND date_m = @DATE_M

I wrote the following script, to fetch each one of the above queries, run it, and put the result into another table - CONTROL_LOG_TABLE.

My problem is that the result column, STATUS_IND, should get either 'Y' or 'N' as values, but for some reason I have not figured out yet, it contains '0'.

Appreciate your help!

DECLARE
       @DATE_C DATE,
       @DATE_Y           INTEGER,
       @DATE_M           INTEGER,
       @CHECK_NUM        INTEGER,
       @CHECK_ID         INTEGER,
       @CTRLM_TREE       VARCHAR(50),
       @CTRLM_TREE_PARAM VARCHAR(50),
       @SQL_QUERY        NVARCHAR(MAX),
       @CHECK_DESC       NVARCHAR(MAX),
       @ACTION_DESC      NVARCHAR(MAX),
       @EXEC_SQL_QUERY   NVARCHAR(MAX),
       @RESULT_SQL       CHAR(1),
       @RowNo            INTEGER,
          @params NVARCHAR(100) = '@DATE_Y NVARCHAR(4), @DATE_M NVARCHAR(2)';

BEGIN

SET @RowNo = 0;
SET @DATE_C = GETDATE();
SET @DATE_Y = (SELECT YEAR (@DATE_C));
SET @DATE_M = (SELECT MONTH (@DATE_C));

DECLARE CURSOR_CHECK_ID CURSOR
FOR SELECT
       CHECK_ID,
       CTRLM_TREE,
       SQL_QUERY,
       CHECK_DESC,
       ACTION_DESC
    FROM
       QUERY_TABLE

OPEN CURSOR_CHECK_ID;
FETCH NEXT FROM CURSOR_CHECK_ID INTO
            @CHECK_ID,
            @CTRLM_TREE,
            @SQL_QUERY,
            @CHECK_DESC,
            @ACTION_DESC;
       WHILE @@FETCH_STATUS = 0
    BEGIN
           SET @RowNo = @RowNo+1
           SET @CHECK_NUM = @RowNo
           SET @EXEC_SQL_QUERY = @SQL_QUERY

                       EXECUTE @result_sql = sp_executesql @EXEC_SQL_QUERY, @params, @DATE_Y, @DATE_M

        INSERT INTO CONTROL_LOG_TABLE (UPDATE_DATE, DATE_C, CHECK_NUM, CHECK_ID, CTRLM_TREE, SQL_QUERY,
              CHECK_DESC, ACTION_DESC, STATUS_IND)
              values (GETDATE(), @DATE_C, @RowNo, @CHECK_ID, @CTRLM_TREE, @SQL_QUERY, @CHECK_DESC, @ACTION_DESC, @RESULT_SQL)

        FETCH NEXT FROM CURSOR_CHECK_ID INTO
            @CHECK_ID,
            @CTRLM_TREE,
            @SQL_QUERY,
            @CHECK_DESC,
            @ACTION_DESC;
    END;
CLOSE CURSOR_CHECK_ID;
DEALLOCATE CURSOR_CHECK_ID;
END;

Body:
One solution is to move the INSERT into the dynamic query.

You don't need to actually change those queries, you can just concatenate the INSERT around it.

SET @EXEC_SQL_QUERY = '
        INSERT INTO CONTROL_LOG_TABLE (UPDATE_DATE, DATE_C, CHECK_NUM, CHECK_ID, CTRLM_TREE, SQL_QUERY,
              CHECK_DESC, ACTION_DESC, STATUS_IND)
              values (GETDATE(), @DATE_C, @RowNo, @CHECK_ID, @CTRLM_TREE, @SQL_QUERY, @CHECK_DESC, @ACTION_DESC, (' + @SQL_QUERY + ')';
';

Another way of doing it is to concatenate SET @outputvariable to it:

SET @EXEC_SQL_QUERY = 'SET @result = (' + @SQL_QUERY + ');
';

EXECUTE sp_executesql @EXEC_SQL_QUERY, @params, @DATE_Y, @DATE_M, @result_sql;

        INSERT INTO CONTROL_LOG_TABLE (UPDATE_DATE, DATE_C, CHECK_NUM, CHECK_ID, CTRLM_TREE, SQL_QUERY,
              CHECK_DESC, ACTION_DESC, STATUS_IND)
              values (GETDATE(), @DATE_C, @RowNo, @CHECK_ID, @CTRLM_TREE, @SQL_QUERY, @CHECK_DESC, @ACTION_DESC, @RESULT_SQL)

and you would need to add that output parameter to @params also.

I'm assuming you have all your bases covered with SQL injection here.


问:
Oracle SQL - How to return common date period from database (based on start/end dates)
I'm struggling with returning common period for start and end dates for specific Limit_ID.
My table looks like this:

Code
Start_Date
End_Date
Limit_ID

912
08/01/2022
14/01/2022
44

905
10/01/2022
12/01/2022
44

904
06/01/2022
09/01/2022
NULL

410
09/01/2022
20/01/2022
44

Base query looks like below, it's working but only when time periods have common part.

```<code>SELECT o.limit_id
      ,MAX(start_date) date_from
      ,MIN(end_date)   date_to
  FROM table1 e
  JOIN table2 o
    ON e.code= o.code
 WHERE o.limit_id = 44
 GROUP BY e.limit_id
</code>```

To make it easier to understand currently it's look like this (I'm getting correct period: 10/01 - 12/01)

But it doesn't work correctly for case when Code 904 will include Limit_ID = 44. Then I'll expect query to return 0 rows (as there is no common period). So my question is - is there a nice way to return results only if date ranges have common period?

Thanks

答:
You should check if max(start_date) is lower than min(end_date)</p>
```<code>SELECT o.limit_id
  ,MAX(start_date) date_from
  ,MIN(end_date)   date_to
  FROM table1 e
  JOIN table2 o
    ON e.code= o.code
 WHERE o.limit_id = 44
 GROUP BY e.limit_id
 HAVING MAX(start_date)<MIN(end_date)
</code>```

Body:
I'm struggling with returning common period for start and end dates for specific Limit_ID.
My table looks like this:

Code
Start_Date
End_Date
Limit_ID

912
08/01/2022
14/01/2022
44

905
10/01/2022
12/01/2022
44

904
06/01/2022
09/01/2022
NULL

410
09/01/2022
20/01/2022
44

Base query looks like below, it's working but only when time periods have common part.

SELECT o.limit_id
      ,MAX(start_date) date_from
      ,MIN(end_date)   date_to
  FROM table1 e
  JOIN table2 o
    ON e.code= o.code
 WHERE o.limit_id = 44
 GROUP BY e.limit_id

To make it easier to understand currently it's look like this (I'm getting correct period: 10/01 - 12/01)

But it doesn't work correctly for case when Code 904 will include Limit_ID = 44. Then I'll expect query to return 0 rows (as there is no common period). So my question is - is there a nice way to return results only if date ranges have common period?

Thanks

Body:
You should check if max(start_date) is lower than min(end_date)

SELECT o.limit_id
  ,MAX(start_date) date_from
  ,MIN(end_date)   date_to
  FROM table1 e
  JOIN table2 o
    ON e.code= o.code
 WHERE o.limit_id = 44
 GROUP BY e.limit_id
 HAVING MAX(start_date)<MIN(end_date)


问:
Query JOIN or not? (optimization)
i was wondering if to use 2 tables is better then using 1 single table .

Scenario:

i have a simple user table and a simple user_details table. i can JOIN tables and select both records.

But i was wondering if to merge 2 table into 1 single table.

what if i have 2milions users records in both tables?

in terms of speed and exec time is better to have a single table when selecting records?

答:
Denormalization will generally use-up more space while affording better query performance.

Be careful though - cache also matters and having more data effectively "shrinks" your cache! This may or may not wipe-out the theoretical performance benefit of merging two tables into one. As always, benchmark with representative data.

Of course, the more denormalized your data model is, the harder it will be to enforce data consistency. Performance does not matter if data is incorrect!

So, the answer to your question is: "it depends" ;)

ContentLicense: CC BY-SA 3.0

Title: Query JOIN or not? (optimization)


问:
Reference a sheet range dynamically inside formula by using a cell value
How can I reference a sheet range by using a cell value?

i.e

This is a working formula

```<code>=filter(dump!1:1000,dump!G:G = "Active")
</code>```

However, I need to reference the sheet's G:G range dynamically by using a cell value.
Let's assume my cell A1 contains "G:G" as the value inside it.

My formula would be something like

```<code>=filter(dump!1:1000,"dump!"&A2 = "Active")
</code>```

..but of course it doesn't work because I'm not using the syntax properly.

答:
Use INDIRECT:</p>
```<code>=filter(dump!1:1000,"dump!"&INDIRECT(A1) = "Active")
</code>```

Body:
How can I reference a sheet range by using a cell value?

i.e

This is a working formula

=filter(dump!1:1000,dump!G:G = "Active")

However, I need to reference the sheet's G:G range dynamically by using a cell value.
Let's assume my cell A1 contains "G:G" as the value inside it.

My formula would be something like

=filter(dump!1:1000,"dump!"&A2 = "Active")

..but of course it doesn't work because I'm not using the syntax properly.

Body:
Use INDIRECT:

=filter(dump!1:1000,"dump!"&INDIRECT(A1) = "Active")


问:
String replace returns unterminated character
I am trying to escape a string df['col'].str.replace('][', ']|[')
Anywhere where there are two closing and opening square bracket next to each other
There should be a '|' placed between them. My code returns the below error. I am pretty sure I do not
need escape characters here.

```<code> error: unterminated character set at position 1
</code>```

Body:
I am trying to escape a string df['col'].str.replace('][', ']|[')
Anywhere where there are two closing and opening square bracket next to each other
There should be a '|' placed between them. My code returns the below error. I am pretty sure I do not
need escape characters here.

 error: unterminated character set at position 1

Body:
import pandas as pd
df = pd.DataFrame({'A': ['[1,2,3][4,5,6][7,8,9][10,11,12]']})
df['A'] = df['A'].str.replace('\]\[', ']|[')
print(df)


问:
A new and (almost) effective way to update routes and allow external access
This is a procedure I tried to use to update all the routes of an already installed cluster to allow external access to it.

The procedure below seems very viable to me, but we have been having some problems so I would like your help to solve this big problem that has been consuming me for days... =|

PROCEDURES:

I found all namespaces that have routes...

```<code>[root@okd4-services okd_bare_metal]# oc get routes --all-namespaces
NAMESPACE                  NAME                HOST/PORT                                                   PATH   SERVICES            PORT    TERMINATION            WILDCARD
openshift-authentication   oauth-openshift     oauth-openshift.apps.mbr.okd.local                                 oauth-openshift     6443    passthrough/Redirect   None
openshift-console          console             console-openshift-console.apps.mbr.okd.local                       console             https   reencrypt/Redirect     None
openshift-console          downloads           downloads-openshift-console.apps.mbr.okd.local                     downloads           http    edge/Redirect          None
openshift-ingress-canary   canary              canary-openshift-ingress-canary.apps.mbr.okd.local                 ingress-canary      8080    edge/Redirect          None
openshift-monitoring       alertmanager-main   alertmanager-main-openshift-monitoring.apps.mbr.okd.local          alertmanager-main   web     reencrypt/Redirect     None
openshift-monitoring       grafana             grafana-openshift-monitoring.apps.mbr.okd.local                    grafana             https   reencrypt/Redirect     None
openshift-monitoring       prometheus-k8s      prometheus-k8s-openshift-monitoring.apps.mbr.okd.local             prometheus-k8s      web     reencrypt/Redirect     None
openshift-monitoring       thanos-querier      thanos-querier-openshift-monitoring.apps.mbr.okd.local             thanos-querier      web     reencrypt/Redirect     None
</code>```

I found all the resources related to each namespace and took note of the route configuration paths...

```<code>[root@okd4-services okd_bare_metal]# oc -n openshift-authentication get all
[...]
NAME                                       HOST/PORT                            PATH   SERVICES          PORT   TERMINATION            WILDCARD
route.route.openshift.io/oauth-openshift   oauth-openshift.apps.mbr.okd.local          oauth-openshift   6443   passthrough/Redirect   None
</code>```
```<code>[root@okd4-services okd_bare_metal]# oc -n openshift-console get all
[...]
NAME                                 HOST/PORT                                        PATH   SERVICES    PORT    TERMINATION          WILDCARD
route.route.openshift.io/console     console-openshift-console.apps.mbr.okd.local            console     https   reencrypt/Redirect   None
route.route.openshift.io/downloads   downloads-openshift-console.apps.mbr.okd.local          downloads   http    edge/Redirect        None
</code>```
```<code>[root@okd4-services okd_bare_metal]# oc -n openshift-ingress-canary get all
[...]
NAME                              HOST/PORT                                            PATH   SERVICES         PORT   TERMINATION     WILDCARD
route.route.openshift.io/canary   canary-openshift-ingress-canary.apps.mbr.okd.local          ingress-canary   8080   edge/Redirect   None
</code>```
```<code>[root@okd4-services okd_bare_metal]# oc -n openshift-monitoring get all
[...]
NAME                                         HOST/PORT                                                   PATH   SERVICES            PORT    TERMINATION          WILDCARD
route.route.openshift.io/alertmanager-main   alertmanager-main-openshift-monitoring.apps.mbr.okd.local          alertmanager-main   web     reencrypt/Redirect   None
route.route.openshift.io/grafana             grafana-openshift-monitoring.apps.mbr.okd.local                    grafana             https   reencrypt/Redirect   None
route.route.openshift.io/prometheus-k8s      prometheus-k8s-openshift-monitoring.apps.mbr.okd.local             prometheus-k8s      web     reencrypt/Redirect   None
route.route.openshift.io/thanos-querier      thanos-querier-openshift-monitoring.apps.mbr.okd.local             thanos-querier      web     reencrypt/Redirect   None
</code>```

In each route I updated the host property to a new domain...

```<code>oc edit -n openshift-console route.route.openshift.io/console
oc edit -n openshift-console route.route.openshift.io/downloads
oc edit -n openshift-ingress-canary route.route.openshift.io/canary
oc edit -n openshift-monitoring route.route.openshift.io/alertmanager-main
oc edit -n openshift-monitoring route.route.openshift.io/grafana
oc edit -n openshift-monitoring route.route.openshift.io/prometheus-k8s
oc edit -n openshift-monitoring route.route.openshift.io/thanos-querier
</code>```

In other words, I modified something like this...

```<code>apiVersion: route.openshift.io/v1
kind: Route
metadata:
[...]
spec:
  host: route-name.apps.mbr.okd.local
[...]
status:
[...]
    host: route-name.apps.mbr.okd.local
[...]
</code>```

... to something like this...

```<code>apiVersion: route.openshift.io/v1
kind: Route
metadata:
[...]
spec:
  host: route-name.apps.mbr.mydomain.net
[...]
status:
[...]
    host: route-name.apps.mbr.mydomain.net
[...]
</code>```

In the case of the route route.route.openshift.io/oauth-openshift I needed to modify the ingress...

```<code>oc edit ingress.config.openshift.io
</code>```

... modifing the domain property from something like this...

```<code>apiVersion: config.openshift.io/v1
kind: Ingress
metadata:
[...]
spec:
  domain: apps.mbr.okd.local
[...]
</code>```

... to something like this...

```<code>[root@okd4-services okd_bare_metal]# oc -n openshift-authentication get all
[...]
NAME                                       HOST/PORT                            PATH   SERVICES          PORT   TERMINATION            WILDCARD
route.route.openshift.io/oauth-openshift   oauth-openshift.apps.mbr.okd.local          oauth-openshift   6443   passthrough/Redirect   None
</code>```0

After doing the above procedures all my routes were updated to the new domain...

```<code>[root@okd4-services okd_bare_metal]# oc -n openshift-authentication get all
[...]
NAME                                       HOST/PORT                            PATH   SERVICES          PORT   TERMINATION            WILDCARD
route.route.openshift.io/oauth-openshift   oauth-openshift.apps.mbr.okd.local          oauth-openshift   6443   passthrough/Redirect   None
</code>```1

PROBLEMS:

However the following new problems arose...

I can access the new Web Console route...

https://console-openshift-console.apps.mbr.mydomain.net/

... and it redirects to the route below (old domain)...

https://oauth-openshift.apps.mbr.okd.local/oauth/authorize?client_id=console&redirect_uri=https%3A%2F%2Fconsole-openshift-console.apps.mbr.mydomain.net%2Fauth%2Fcallback&response_type=code&scope=user%3Afull&state=3ba1134a

... but we can use the new route...

https://oauth-openshift.apps.mbr.mydomain.net/oauth/authorize?client_id=console&redirect_uri=https%3A%2F%2Fconsole-openshift-console.apps.mbr.mydomain.net%2Fauth%2Fcallback&response_type=code&scope=user%3Afull&state=3ba1134a

...so great works...

... I enter the login, password, click on Log in and I'm redirected to this URL...

https://console-openshift-console.apps.mbr.mydomain.net/error?error=invalid_code&error_type=auth

... which in turn redirects to this (old domain)...

https://oauth-openshift.apps.mbr.okd.local/oauth/authorize?client_id=console&redirect_uri=https%3A%2F%2Fconsole-openshift-console.apps.mbr.mydomain.net%2Fauth%2Fcallback&response_type=code&scope=user%3Afull&state=da4a1dd0

CONCLUSION:

Even though we successfully updated the routes as exposed, we started to have problems with the login and the URLs of the Web Console that are not updated to the new domain.

QUESTION:

Does anyone have any idea how we can solve the mentioned problems?

IMPORTANT:

I - We've already tried this procedure Customizing the web console URL , but it doesn't update all routes and does not update URLs in the Web Console and also has the same login issues above;

II - I also tried this procedure Creating a route through an Ingress object , but equally it doesn't seem to me something that will solve the problems pointed out.

答:
The documentation is pretty clear: you cannot currently update the domain value of the ingress controller:

```<code>The domain value must be unique among all Ingress Controllers and cannot be updated.
</code>```

You can try to change your clusterConfig and adjust the domain, afterward try to delete and recreate the ingressController. There may be dragons

Body:
This is a procedure I tried to use to update all the routes of an already installed cluster to allow external access to it.

The procedure below seems very viable to me, but we have been having some problems so I would like your help to solve this big problem that has been consuming me for days... =|

PROCEDURES:

I found all namespaces that have routes...

[root@okd4-services okd_bare_metal]# oc get routes --all-namespaces
NAMESPACE                  NAME                HOST/PORT                                                   PATH   SERVICES            PORT    TERMINATION            WILDCARD
openshift-authentication   oauth-openshift     oauth-openshift.apps.mbr.okd.local                                 oauth-openshift     6443    passthrough/Redirect   None
openshift-console          console             console-openshift-console.apps.mbr.okd.local                       console             https   reencrypt/Redirect     None
openshift-console          downloads           downloads-openshift-console.apps.mbr.okd.local                     downloads           http    edge/Redirect          None
openshift-ingress-canary   canary              canary-openshift-ingress-canary.apps.mbr.okd.local                 ingress-canary      8080    edge/Redirect          None
openshift-monitoring       alertmanager-main   alertmanager-main-openshift-monitoring.apps.mbr.okd.local          alertmanager-main   web     reencrypt/Redirect     None
openshift-monitoring       grafana             grafana-openshift-monitoring.apps.mbr.okd.local                    grafana             https   reencrypt/Redirect     None
openshift-monitoring       prometheus-k8s      prometheus-k8s-openshift-monitoring.apps.mbr.okd.local             prometheus-k8s      web     reencrypt/Redirect     None
openshift-monitoring       thanos-querier      thanos-querier-openshift-monitoring.apps.mbr.okd.local             thanos-querier      web     reencrypt/Redirect     None

I found all the resources related to each namespace and took note of the route configuration paths...

[root@okd4-services okd_bare_metal]# oc -n openshift-authentication get all
[...]
NAME                                       HOST/PORT                            PATH   SERVICES          PORT   TERMINATION            WILDCARD
route.route.openshift.io/oauth-openshift   oauth-openshift.apps.mbr.okd.local          oauth-openshift   6443   passthrough/Redirect   None

[root@okd4-services okd_bare_metal]# oc -n openshift-console get all
[...]
NAME                                 HOST/PORT                                        PATH   SERVICES    PORT    TERMINATION          WILDCARD
route.route.openshift.io/console     console-openshift-console.apps.mbr.okd.local            console     https   reencrypt/Redirect   None
route.route.openshift.io/downloads   downloads-openshift-console.apps.mbr.okd.local          downloads   http    edge/Redirect        None

[root@okd4-services okd_bare_metal]# oc -n openshift-ingress-canary get all
[...]
NAME                              HOST/PORT                                            PATH   SERVICES         PORT   TERMINATION     WILDCARD
route.route.openshift.io/canary   canary-openshift-ingress-canary.apps.mbr.okd.local          ingress-canary   8080   edge/Redirect   None

[root@okd4-services okd_bare_metal]# oc -n openshift-monitoring get all
[...]
NAME                                         HOST/PORT                                                   PATH   SERVICES            PORT    TERMINATION          WILDCARD
route.route.openshift.io/alertmanager-main   alertmanager-main-openshift-monitoring.apps.mbr.okd.local          alertmanager-main   web     reencrypt/Redirect   None
route.route.openshift.io/grafana             grafana-openshift-monitoring.apps.mbr.okd.local                    grafana             https   reencrypt/Redirect   None
route.route.openshift.io/prometheus-k8s      prometheus-k8s-openshift-monitoring.apps.mbr.okd.local             prometheus-k8s      web     reencrypt/Redirect   None
route.route.openshift.io/thanos-querier      thanos-querier-openshift-monitoring.apps.mbr.okd.local             thanos-querier      web     reencrypt/Redirect   None

In each route I updated the host property to a new domain...

oc edit -n openshift-console route.route.openshift.io/console
oc edit -n openshift-console route.route.openshift.io/downloads
oc edit -n openshift-ingress-canary route.route.openshift.io/canary
oc edit -n openshift-monitoring route.route.openshift.io/alertmanager-main
oc edit -n openshift-monitoring route.route.openshift.io/grafana
oc edit -n openshift-monitoring route.route.openshift.io/prometheus-k8s
oc edit -n openshift-monitoring route.route.openshift.io/thanos-querier

In other words, I modified something like this...

apiVersion: route.openshift.io/v1
kind: Route
metadata:
[...]
spec:
  host: route-name.apps.mbr.okd.local
[...]
status:
[...]
    host: route-name.apps.mbr.okd.local
[...]

... to something like this...

apiVersion: route.openshift.io/v1
kind: Route
metadata:
[...]
spec:
  host: route-name.apps.mbr.mydomain.net
[...]
status:
[...]
    host: route-name.apps.mbr.mydomain.net
[...]

In the case of the route route.route.openshift.io/oauth-openshift I needed to modify the ingress...

oc edit ingress.config.openshift.io

... modifing the domain property from something like this...

apiVersion: config.openshift.io/v1
kind: Ingress
metadata:
[...]
spec:
  domain: apps.mbr.okd.local
[...]

... to something like this...

apiVersion: config.openshift.io/v1
kind: Ingress
metadata:
[...]
spec:
  domain: apps.mbr.mydomain.net
[...]

After doing the above procedures all my routes were updated to the new domain...

[root@okd4-services okd_bare_metal]# oc get routes --all-namespaces
NAMESPACE                  NAME                HOST/PORT                                                     PATH   SERVICES            PORT    TERMINATION            WILDCARD
openshift-authentication   oauth-openshift     oauth-openshift.apps.mbr.mydomain.net                                 oauth-openshift     6443    passthrough/Redirect   None
openshift-console          console             console-openshift-console.apps.mbr.mydomain.net                       console             https   reencrypt/Redirect     None
openshift-console          downloads           downloads-openshift-console.apps.mbr.mydomain.net                     downloads           http    edge/Redirect          None
openshift-ingress-canary   canary              canary-openshift-ingress-canary.apps.mbr.mydomain.net                 ingress-canary      8080    edge/Redirect          None
openshift-monitoring       alertmanager-main   alertmanager-main-openshift-monitoring.apps.mbr.mydomain.net          alertmanager-main   web     reencrypt/Redirect     None
openshift-monitoring       grafana             grafana-openshift-monitoring.apps.mbr.mydomain.net                    grafana             https   reencrypt/Redirect     None
openshift-monitoring       prometheus-k8s      prometheus-k8s-openshift-monitoring.apps.mbr.mydomain.net             prometheus-k8s      web     reencrypt/Redirect     None
openshift-monitoring       thanos-querier      thanos-querier-openshift-monitoring.apps.mbr.mydomain.net             thanos-querier      web     reencrypt/Redirect     None

PROBLEMS:

However the following new problems arose...

I can access the new Web Console route...

https://console-openshift-console.apps.mbr.mydomain.net/

... and it redirects to the route below (old domain)...

https://oauth-openshift.apps.mbr.okd.local/oauth/authorize?client_id=console&redirect_uri=https%3A%2F%2Fconsole-openshift-console.apps.mbr.mydomain.net%2Fauth%2Fcallback&response_type=code&scope=user%3Afull&state=3ba1134a

... but we can use the new route...

https://oauth-openshift.apps.mbr.mydomain.net/oauth/authorize?client_id=console&redirect_uri=https%3A%2F%2Fconsole-openshift-console.apps.mbr.mydomain.net%2Fauth%2Fcallback&response_type=code&scope=user%3Afull&state=3ba1134a

...so great works...

... I enter the login, password, click on Log in and I'm redirected to this URL...

https://console-openshift-console.apps.mbr.mydomain.net/error?error=invalid_code&error_type=auth

... which in turn redirects to this (old domain)...

https://oauth-openshift.apps.mbr.okd.local/oauth/authorize?client_id=console&redirect_uri=https%3A%2F%2Fconsole-openshift-console.apps.mbr.mydomain.net%2Fauth%2Fcallback&response_type=code&scope=user%3Afull&state=da4a1dd0

CONCLUSION:

Even though we successfully updated the routes as exposed, we started to have problems with the login and the URLs of the Web Console that are not updated to the new domain.

QUESTION:

Does anyone have any idea how we can solve the mentioned problems?

IMPORTANT:

I - We've already tried this procedure Customizing the web console URL , but it doesn't update all routes and does not update URLs in the Web Console and also has the same login issues above;

II - I also tried this procedure Creating a route through an Ingress object , but equally it doesn't seem to me something that will solve the problems pointed out.

Body:
The documentation is pretty clear: you cannot currently update the domain value of the ingress controller:

The domain value must be unique among all Ingress Controllers and cannot be updated.

You can try to change your clusterConfig and adjust the domain, afterward try to delete and recreate the ingressController. There may be dragons


问:
Is OutputDebugString thread safe?
In my code I call these methods at various places to send diagnostic output to DbgView:

```<code>inline void dbg_info(std::string s) {
    std::stringstream ss;
    ss << "INFO:" << std::this_thread::get_id() << ": " << s << std::endl;
    OutputDebugStringA(ss.str().c_str());
}

inline void dbg_err(std::string s) {
    std::stringstream ss;
    ss << "ERROR:" << std::this_thread::get_id() << ": " << s << std::endl;
    OutputDebugStringA(ss.str().c_str());
}
</code>```

Is the method OutputDebugStringA() thread safe or could it mix messages from multiple threads being output at the same time?

If not would it be sufficient and a good idea to create a static member variable of std::mutex and lock this in my two methods above?

答: Yes it is thread safe. It uses a mutex and events. Implementation details here.</p>

Title: Is OutputDebugString thread safe?

Body:
In my code I call these methods at various places to send diagnostic output to DbgView:

inline void dbg_info(std::string s) {
    std::stringstream ss;
    ss << "INFO:" << std::this_thread::get_id() << ": " << s << std::endl;
    OutputDebugStringA(ss.str().c_str());
}

inline void dbg_err(std::string s) {
    std::stringstream ss;
    ss << "ERROR:" << std::this_thread::get_id() << ": " << s << std::endl;
    OutputDebugStringA(ss.str().c_str());
}

Is the method OutputDebugStringA() thread safe or could it mix messages from multiple threads being output at the same time?

If not would it be sufficient and a good idea to create a static member variable of std::mutex and lock this in my two methods above?


问:
Request http in flutter web
I want to post data to the server with dio library but when I send data, I get XMLHttpRequest error. The server programmer checked twice his codes and made sure to enable CORS in the server. I think this error occurs because the server is not HTTPS and the browser blocks the request. I use this code to send my data to the server:

```<code>Response response = await client
        .post(theUrl,
            options: Options(
                validateStatus: (status) {
                  return status! < 500;
                },
                followRedirects: false,
                headers: {
                  HttpHeaders.contentTypeHeader: "application/json",
                  HttpHeaders.acceptHeader: "*/*",
                  HttpHeaders.accessControlAllowOriginHeader:
                      "Access-Control-Allow-Origin, Accept",
                }),
            data: convert.json.encode(data))
        .timeout(const Duration(seconds: 10));
</code>```

My log is just:

```<code>DioError [DioErrorType.RESPONSE]: XMLHttpRequest error.
</code>```

So, How can I ignore the certificate of the server host and send data to an HTTP URL in flutter web?

答:
I'm almost sure that the problem is because your server doesn't have an https certificate.
A workaround is run / debug your application with flutter desktop.

You can also take a look at: How to solve flutter web api cors error only with dart code?

Title: Request http in flutter web

Body:
I want to post data to the server with dio library but when I send data, I get XMLHttpRequest error. The server programmer checked twice his codes and made sure to enable CORS in the server. I think this error occurs because the server is not HTTPS and the browser blocks the request. I use this code to send my data to the server:

Response response = await client
        .post(theUrl,
            options: Options(
                validateStatus: (status) {
                  return status! < 500;
                },
                followRedirects: false,
                headers: {
                  HttpHeaders.contentTypeHeader: "application/json",
                  HttpHeaders.acceptHeader: "*/*",
                  HttpHeaders.accessControlAllowOriginHeader:
                      "Access-Control-Allow-Origin, Accept",
                }),
            data: convert.json.encode(data))
        .timeout(const Duration(seconds: 10));

My log is just:

DioError [DioErrorType.RESPONSE]: XMLHttpRequest error.

So, How can I ignore the certificate of the server host and send data to an HTTP URL in flutter web?


问:
Dynamically get difference between DateTime.Now and a model DateTime in Razor pages
I'm using c# .NET razor pages and trying to dynamically change the 'minutes ago' count.

Basically, I have this code:

```<code>@foreach(var comment in Model.Comments)
            {
                TimeSpan timeSpan = (DateTime.Now - comment.CommentDate);
                int minutesAgo = Convert.ToInt32(timeSpan.TotalMinutes);

                <div>
                    <p>@comment.Message</p>
                    <span>@minutesAgo minutes ago</span>
                </div>
            }
</code>```

The calculation works, but it stays static on the page.
I'm trying to get it updated as long the user stays on the page.

答:
One way of do this is use html data attribute and a js function to update the displayed text. Something like this:</p>
```<code>
<div class="text-center">
    <span class="dtu" data-datetime="@DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")"></span>
</div>

<script type="text/javascript">
    //recall the page every one minute.....
    function update_call() {
        var dtus = document.getElementsByClassName('dtu');
        Array.prototype.every.call(dtus, function(el) {
            const dtPost = new Date(el.dataset.datetime);
            el.innerHTML = timeAgo(dtPost);
        });
        window.setTimeout(update_call, 1000*5);
    }
    window.setTimeout(update_call, 500);

    const MONTH_NAMES = [
        'January', 'February', 'March', 'April', 'May', 'June',
        'July', 'August', 'September', 'October', 'November', 'December'
    ];

    function getFormattedDate(date, prefomattedDate = false, hideYear = false) {
    const day = date.getDate();
    const month = MONTH_NAMES[date.getMonth()];
    const year = date.getFullYear();
    const hours = date.getHours();
    let minutes = date.getMinutes();

    if (minutes < 10) {
        // Adding leading zero to minutes
        minutes = `0${ minutes }`;
    }

    if (prefomattedDate) {
        // Today at 10:20
        // Yesterday at 10:20
        return `${ prefomattedDate } at ${ hours }:${ minutes }`;
    }

    if (hideYear) {
        // 10. January at 10:20
        return `${ day }. ${ month } at ${ hours }:${ minutes }`;
    }

    // 10. January 2017. at 10:20
    return `${ day }. ${ month } ${ year }. at ${ hours }:${ minutes }`;
    }

    // --- Main function
    function timeAgo(dateParam) {
    if (!dateParam) {
        return null;
    }

    const date = typeof dateParam === 'object' ? dateParam : new Date(dateParam);
    const DAY_IN_MS = 86400000; // 24 * 60 * 60 * 1000

    var todayDate = new Date();
    var now_utc =  Date.UTC(todayDate.getUTCFullYear(), todayDate.getUTCMonth(), todayDate.getUTCDate(), todayDate.getUTCHours(), todayDate.getUTCMinutes(), todayDate.getUTCSeconds());
    const today = new Date(now_utc);
    const yesterday = new Date(today - DAY_IN_MS);
    const seconds = Math.round((today - date) / 1000);
    const minutes = Math.round(seconds / 60);
    const isToday = today.toDateString() === date.toDateString();
    const isYesterday = yesterday.toDateString() === date.toDateString();
    const isThisYear = today.getFullYear() === date.getFullYear();

    if (seconds < 5) {
        return 'now';
    } else if (seconds < 60) {
        return `${ seconds } seconds ago`;
    } else if (seconds < 90) {
        return 'about a minute ago';
    } else if (minutes < 60) {
        return `${ minutes } minutes ago`;
    } else if (isToday) {
        return getFormattedDate(date, 'Today'); // Today at 10:20
    } else if (isYesterday) {
        return getFormattedDate(date, 'Yesterday'); // Yesterday at 10:20
    } else if (isThisYear) {
        return getFormattedDate(date, false, true); // 10. January at 10:20
    }

    return getFormattedDate(date); // 10. January 2017. at 10:20
    }
</script>
</code>```

Body:
I'm using c# .NET razor pages and trying to dynamically change the 'minutes ago' count.

Basically, I have this code:

@foreach(var comment in Model.Comments)
            {
                TimeSpan timeSpan = (DateTime.Now - comment.CommentDate);
                int minutesAgo = Convert.ToInt32(timeSpan.TotalMinutes);

@comment.Message

                    @minutesAgo minutes ago

            }

The calculation works, but it stays static on the page.
I'm trying to get it updated as long the user stays on the page.

Body:
One way of do this is use html data attribute and a js function to update the displayed text. Something like this:

<div class="text-center">
    <span class="dtu" data-datetime="@DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")"></span>
</div>

<script type="text/javascript">
    //recall the page every one minute.....
    function update_call() {
        var dtus = document.getElementsByClassName('dtu');
        Array.prototype.every.call(dtus, function(el) {
            const dtPost = new Date(el.dataset.datetime);
            el.innerHTML = timeAgo(dtPost);
        });
        window.setTimeout(update_call, 1000*5);
    }
    window.setTimeout(update_call, 500);

    const MONTH_NAMES = [
        'January', 'February', 'March', 'April', 'May', 'June',
        'July', 'August', 'September', 'October', 'November', 'December'
    ];

    function getFormattedDate(date, prefomattedDate = false, hideYear = false) {
    const day = date.getDate();
    const month = MONTH_NAMES[date.getMonth()];
    const year = date.getFullYear();
    const hours = date.getHours();
    let minutes = date.getMinutes();

    if (minutes < 10) {
        // Adding leading zero to minutes
        minutes = `0${ minutes }`;
    }

    if (prefomattedDate) {
        // Today at 10:20
        // Yesterday at 10:20
        return `${ prefomattedDate } at ${ hours }:${ minutes }`;
    }

    if (hideYear) {
        // 10. January at 10:20
        return `${ day }. ${ month } at ${ hours }:${ minutes }`;
    }

    // 10. January 2017. at 10:20
    return `${ day }. ${ month } ${ year }. at ${ hours }:${ minutes }`;
    }

    // --- Main function
    function timeAgo(dateParam) {
    if (!dateParam) {
        return null;
    }

    const date = typeof dateParam === 'object' ? dateParam : new Date(dateParam);
    const DAY_IN_MS = 86400000; // 24 * 60 * 60 * 1000

    var todayDate = new Date();
    var now_utc =  Date.UTC(todayDate.getUTCFullYear(), todayDate.getUTCMonth(), todayDate.getUTCDate(), todayDate.getUTCHours(), todayDate.getUTCMinutes(), todayDate.getUTCSeconds());
    const today = new Date(now_utc);
    const yesterday = new Date(today - DAY_IN_MS);
    const seconds = Math.round((today - date) / 1000);
    const minutes = Math.round(seconds / 60);
    const isToday = today.toDateString() === date.toDateString();
    const isYesterday = yesterday.toDateString() === date.toDateString();
    const isThisYear = today.getFullYear() === date.getFullYear();

    if (seconds < 5) {
        return 'now';
    } else if (seconds < 60) {
        return `${ seconds } seconds ago`;
    } else if (seconds < 90) {
        return 'about a minute ago';
    } else if (minutes < 60) {
        return `${ minutes } minutes ago`;
    } else if (isToday) {
        return getFormattedDate(date, 'Today'); // Today at 10:20
    } else if (isYesterday) {
        return getFormattedDate(date, 'Yesterday'); // Yesterday at 10:20
    } else if (isThisYear) {
        return getFormattedDate(date, false, true); // 10. January at 10:20
    }

    return getFormattedDate(date); // 10. January 2017. at 10:20
    }
</script>


问:
AWK: Help on transforming data table
I have the following file called in.txt:

```<code>2020-01-01  fruit   banana  3.4
2020-03-02  alcohol smirnov 26.99
2020-03-10  fruit   orange  4.20
2020-04-03  fruit   orange  4.20
2021-09-01  alcohol beer    6.00
2021-08-03  fruit   mango   6.99
2022-01-01  fruit   orange  4.30
2022-03-04  alcohol beer    6.00
2022-03-03  alcohol beer    6.00
2022-04-01  fruit   mango   7.20
</code>```

I want to transform the file so it reads something like this:

```<code>                2020-01-01      2021-01-01      2022-01-01
                -2020-12-31     -2021-12-31     -2022-12-31
fruit   banana  3.40             0.00            0.00
        orange  8.40            0.00            4.30
        mango   0.00            6.99            7.20

Subt            11.80           6.99            11.50

alcohol beer    0.00            6.00            12.00
        smirnov 26.99           0.00            0.00

Subt            26.99           6.00            12.00

Total           38.59           12.99           23.50
</code>```

I have started writing the following script but am stuck on how to approach this. How can I display totals columns side by side. The other problem is that this is just dummy data. I have many different categories other than fruit and alcohol and it seems wrong to write if statements and for-loops for each one. Also how can I print fruit and alcohol out just once rather than for every iteration of column 3 and bring the date range to the top. Help is much appreciated.

```<code>#!/usr/bin/env bash

awk '

        BEGIN{
        FS=OFS="\t";
        }

        {
        if ($2 ~ fruit && $1 >= "2020-01-01" && $1 <= "2020-12-31") {
                        a[$3]+=$4;
                        sa+=$4;
                }
        }

        END {
        PROCINFO["sorted_in"]="@ind_str_asc";
        for (i in a) {
                        print "fruit", i, a[i]
                }
        }

' "${@:--}"
</code>```

答:
Using GNU awk for arrays of arrays:

```<code>$ cat tst.awk
BEGIN { OFS="\t" }
{
    sub(/-.*/,"",$1)
    minYear = ( NR==1 || $1 < minYear ? $1 : minYear )
    maxYear = ( NR==1 || $1 > maxYear ? $1 : maxYear )
    items[$2][$3]
    vals[$1][$2][$3] += $4
    typeTots[$1][$2] += $4
    yearTots[$1] += $4
}
END {
    printf "%s", OFS
    for ( year=minYear; year<=maxYear; year++ ) {
        printf "%s%s", OFS, year
    }
    print ""

    for ( type in items ) {
        itemCnt = 0
        for ( item in items[type] ) {
            printf "%s%s%s", (itemCnt++ ? "" : type), OFS, item
            for ( year=minYear; year<=maxYear; year++ ) {
                printf "%s%0.2f", OFS, vals[year][type][item]
            }
            print ""
        }
        printf "Subt%s", OFS
        for ( year=minYear; year<=maxYear; year++ ) {
            printf "%s%0.2f", OFS, typeTots[year][type]
        }
        print ORS
    }

    printf "Total%s", OFS
    for ( year=minYear; year<=maxYear; year++ ) {
        printf "%s%0.2f", OFS, yearTots[year]
    }
    print ""
}
</code>```

```<code>$ awk -f tst.awk in.txt
                2020    2021    2022
alcohol beer    0.00    6.00    12.00
        smirnov 26.99   0.00    0.00
Subt            26.99   6.00    12.00

fruit   orange  8.40    0.00    4.30
        mango   0.00    6.99    7.20
        banana  3.40    0.00    0.00
Subt            11.80   6.99    11.50

Total           38.79   12.99   23.50
</code>```

or if you really want specific date ranges instead of just the year in the header:

```<code>$ cat tst.awk
BEGIN { OFS="\t" }
{
    sub(/-.*/,"",$1)
    minYear = ( NR==1 || $1 < minYear ? $1 : minYear )
    maxYear = ( NR==1 || $1 > maxYear ? $1 : maxYear )
    items[$2][$3]
    vals[$1][$2][$3] += $4
    typeTots[$1][$2] += $4
    yearTots[$1] += $4
}
END {
    printf "%s", OFS
    for ( year=minYear; year<=maxYear; year++ ) {
        printf "%s%s-01-01", OFS, year
    }
    print ""

    printf "%s", OFS
    for ( year=minYear; year<=maxYear; year++ ) {
        printf "%s-%s-12-31", OFS, year
    }
    print ""

    for ( type in items ) {
        itemCnt = 0
        for ( item in items[type] ) {
            printf "%s%s%s", (itemCnt++ ? "" : type), OFS, item
            for ( year=minYear; year<=maxYear; year++ ) {
                printf "%s%0.2f", OFS, vals[year][type][item]
            }
            print ""
        }
        printf "Subt%s", OFS
        for ( year=minYear; year<=maxYear; year++ ) {
            printf "%s%0.2f", OFS, typeTots[year][type]
        }
        print ORS
    }

    printf "Total%s", OFS
    for ( year=minYear; year<=maxYear; year++ ) {
        printf "%s%0.2f", OFS, yearTots[year]
    }
    print ""
}
</code>```

```<code>$ awk -f tst.awk in.txt | column -s$'\t' -t
                  2020-01-01   2021-01-01   2022-01-01
                  -2020-12-31  -2021-12-31  -2022-12-31
alcohol  beer     0.00         6.00         12.00
         smirnov  26.99        0.00         0.00
Subt              26.99        6.00         12.00
fruit    orange   8.40         0.00         4.30
         mango    0.00         6.99         7.20
         banana   3.40         0.00         0.00
Subt              11.80        6.99         11.50
Total             38.79        12.99        23.50
</code>```

Title: AWK: Help on transforming data table

Body:
I have the following file called in.txt:

2020-01-01  fruit   banana  3.4
2020-03-02  alcohol smirnov 26.99
2020-03-10  fruit   orange  4.20
2020-04-03  fruit   orange  4.20
2021-09-01  alcohol beer    6.00
2021-08-03  fruit   mango   6.99
2022-01-01  fruit   orange  4.30
2022-03-04  alcohol beer    6.00
2022-03-03  alcohol beer    6.00
2022-04-01  fruit   mango   7.20

I want to transform the file so it reads something like this:

                2020-01-01      2021-01-01      2022-01-01
                -2020-12-31     -2021-12-31     -2022-12-31
fruit   banana  3.40             0.00            0.00
        orange  8.40            0.00            4.30
        mango   0.00            6.99            7.20

Subt            11.80           6.99            11.50

alcohol beer    0.00            6.00            12.00
        smirnov 26.99           0.00            0.00

Subt            26.99           6.00            12.00

Total           38.59           12.99           23.50

I have started writing the following script but am stuck on how to approach this. How can I display totals columns side by side. The other problem is that this is just dummy data. I have many different categories other than fruit and alcohol and it seems wrong to write if statements and for-loops for each one. Also how can I print fruit and alcohol out just once rather than for every iteration of column 3 and bring the date range to the top. Help is much appreciated.

#!/usr/bin/env bash

awk '

        BEGIN{
        FS=OFS="\t";
        }

        {
        if ($2 ~ fruit && $1 >= "2020-01-01" && $1 <= "2020-12-31") {
                        a[$3]+=$4;
                        sa+=$4;
                }
        }

        END {
        PROCINFO["sorted_in"]="@ind_str_asc";
        for (i in a) {
                        print "fruit", i, a[i]
                }
        }

' "${@:--}"

Body:
Using GNU awk for arrays of arrays:

$ cat tst.awk
BEGIN { OFS="\t" }
{
    sub(/-.*/,"",$1)
    minYear = ( NR==1 || $1 < minYear ? $1 : minYear )
    maxYear = ( NR==1 || $1 > maxYear ? $1 : maxYear )
    items[$2][$3]
    vals[$1][$2][$3] += $4
    typeTots[$1][$2] += $4
    yearTots[$1] += $4
}
END {
    printf "%s", OFS
    for ( year=minYear; year<=maxYear; year++ ) {
        printf "%s%s", OFS, year
    }
    print ""

    for ( type in items ) {
        itemCnt = 0
        for ( item in items[type] ) {
            printf "%s%s%s", (itemCnt++ ? "" : type), OFS, item
            for ( year=minYear; year<=maxYear; year++ ) {
                printf "%s%0.2f", OFS, vals[year][type][item]
            }
            print ""
        }
        printf "Subt%s", OFS
        for ( year=minYear; year<=maxYear; year++ ) {
            printf "%s%0.2f", OFS, typeTots[year][type]
        }
        print ORS
    }

    printf "Total%s", OFS
    for ( year=minYear; year<=maxYear; year++ ) {
        printf "%s%0.2f", OFS, yearTots[year]
    }
    print ""
}

$ awk -f tst.awk in.txt
                2020    2021    2022
alcohol beer    0.00    6.00    12.00
        smirnov 26.99   0.00    0.00
Subt            26.99   6.00    12.00

fruit   orange  8.40    0.00    4.30
        mango   0.00    6.99    7.20
        banana  3.40    0.00    0.00
Subt            11.80   6.99    11.50

Total           38.79   12.99   23.50

or if you really want specific date ranges instead of just the year in the header:

$ cat tst.awk
BEGIN { OFS="\t" }
{
    sub(/-.*/,"",$1)
    minYear = ( NR==1 || $1 < minYear ? $1 : minYear )
    maxYear = ( NR==1 || $1 > maxYear ? $1 : maxYear )
    items[$2][$3]
    vals[$1][$2][$3] += $4
    typeTots[$1][$2] += $4
    yearTots[$1] += $4
}
END {
    printf "%s", OFS
    for ( year=minYear; year<=maxYear; year++ ) {
        printf "%s%s-01-01", OFS, year
    }
    print ""

    printf "%s", OFS
    for ( year=minYear; year<=maxYear; year++ ) {
        printf "%s-%s-12-31", OFS, year
    }
    print ""

    for ( type in items ) {
        itemCnt = 0
        for ( item in items[type] ) {
            printf "%s%s%s", (itemCnt++ ? "" : type), OFS, item
            for ( year=minYear; year<=maxYear; year++ ) {
                printf "%s%0.2f", OFS, vals[year][type][item]
            }
            print ""
        }
        printf "Subt%s", OFS
        for ( year=minYear; year<=maxYear; year++ ) {
            printf "%s%0.2f", OFS, typeTots[year][type]
        }
        print ORS
    }

    printf "Total%s", OFS
    for ( year=minYear; year<=maxYear; year++ ) {
        printf "%s%0.2f", OFS, yearTots[year]
    }
    print ""
}

$ awk -f tst.awk in.txt | column -s$'\t' -t
                  2020-01-01   2021-01-01   2022-01-01
                  -2020-12-31  -2021-12-31  -2022-12-31
alcohol  beer     0.00         6.00         12.00
         smirnov  26.99        0.00         0.00
Subt              26.99        6.00         12.00
fruit    orange   8.40         0.00         4.30
         mango    0.00         6.99         7.20
         banana   3.40         0.00         0.00
Subt              11.80        6.99         11.50
Total             38.79        12.99        23.50


问:
Icon does not appear in iOS app (xcode assets configuration)
I'am trying put icon in my iOS app following xcode documentation, but the
the icon does not appear on my device or simulator.

My media assets file on xcode project navigator:

When selecting the assets file I can see my targets but I can't select my main one, I don't know why. As shown here:

In general settings of App I can see the AppIcon linked:

答: I solved this problem by adding the icons without using asset catalog. I took exam like this sample.</p>


问:
Using INDEX to pull periodic columns out of a separate sheet
I have a set of data that is WAY too big. I want to pull out every 18th column and put it into a new sheet that will be easier to manage. This is the code I have now, which is based on a similar question asking about pulling out cells from a row: Excel: Referencing a cell using a function

```<code>=INDEX(Sheet4!A+((COLUMN(A:A)-1)*18),Sheet4!1:1)
</code>```

I am currently getting a #NAME? error

Thank you for your help

答:
You can use a dynamic array to avoid requiring copying across and down:

```<code>=LET(data, Sheet4!$A$1:$ZZ$1000, lastrow, MAX((LEN(data)>0)*ROW(data)), arr, INDEX(data, SEQUENCE(lastrow), 1+(SEQUENCE(,5,0))*18), IF(arr=0,"",arr))
</code>```

where the three values (excluding 0 which is the sequence start value) in: 1+(SEQUENCE(,5,0))*18 control starting column, number of columns to spill and the column frequency in that order.

Body:
I have a set of data that is WAY too big. I want to pull out every 18th column and put it into a new sheet that will be easier to manage. This is the code I have now, which is based on a similar question asking about pulling out cells from a row: Excel: Referencing a cell using a function

=INDEX(Sheet4!A+((COLUMN(A:A)-1)*18),Sheet4!1:1)

I am currently getting a #NAME? error

Thank you for your help

Body:
You can use a dynamic array to avoid requiring copying across and down:

=LET(data, Sheet4!$A$1:$ZZ$1000, lastrow, MAX((LEN(data)>0)*ROW(data)), arr, INDEX(data, SEQUENCE(lastrow), 1+(SEQUENCE(,5,0))*18), IF(arr=0,"",arr))

where the three values (excluding 0 which is the sequence start value) in: 1+(SEQUENCE(,5,0))*18 control starting column, number of columns to spill and the column frequency in that order.


问:
How to compile QuasiQuoter during runtime?
I have a 'QuasiQuoter' which is useful in source code in Haskell, but also as a standalone application. So, I need to be able to run QuasiQuoter

During the compile time in Haskell - [myGrammar|someCommand|]

In runtime (runtime compilation) in shell - mygrammar 'someCommand'

The first part is easy but the second part might be a little clumsy if solved as calling the compiler with some generated code from the runtime.

I would like to solve a second part of the problem using some nice method in Haskell which doesn't accept only the source code, but accepts QuasyQuoter datatype instead so the code is less clumsy. But I can't find any compilation method like that.

Do you know any? Thanks.

Example of usage

Haskell

The function takes tuple [(a,b,c,d,e)] and returns a list of the strings with the products.

```<code>function = [lsql| {1..5}, r=[ a.* |> (*) ], "Product of a.1 * a.2 * ... * a.5 is &a.r"|]
</code>```

Bash

The command reads from stdin csv with at least 5 numerical columns and returns a list of their products (one per line).

```<code>lsql-csv '-, r=[ a.* |> (*) ], "Product of a.1 * a.2 * ... * a.5 is &a.r"'
</code>```

答:
I think the question is how to parse and process a string in a uniform way between a quasiquoter and some other chunk of code. If this interpretation is right, then you just... do that. For example:

```<code>-- implementation of these is left to the reader, but can use standard Haskell
-- programming techniques and libraries, like parsec and ADTs and stuff
command :: Parser Command
interpret :: Command -> IO ()
jit :: Command -> Exp -- or Q Exp
</code>```

Then, in your lsql-csv.hs, you would write something like

```<code>main = do
    [s] <- getArgs
    case parse command s of
        Left err -> die (show err)
        Right com -> interpret com
</code>```

and in your LSql/CSV/QQ.hs, you would write something like

```<code>lsql = QuasiQuoter { quoteExp = \s -> case parse command s of
    Left err -> qReport True (show err) >> fail ""
    Right com -> return (jit com) -- or just jit com if that's already a Q Exp
    }
</code>```

Body:
I have a 'QuasiQuoter' which is useful in source code in Haskell, but also as a standalone application. So, I need to be able to run QuasiQuoter

During the compile time in Haskell - [myGrammar|someCommand|]

In runtime (runtime compilation) in shell - mygrammar 'someCommand'

The first part is easy but the second part might be a little clumsy if solved as calling the compiler with some generated code from the runtime.

I would like to solve a second part of the problem using some nice method in Haskell which doesn't accept only the source code, but accepts QuasyQuoter datatype instead so the code is less clumsy. But I can't find any compilation method like that.

Do you know any? Thanks.

Example of usage

Haskell

The function takes tuple [(a,b,c,d,e)] and returns a list of the strings with the products.

function = [lsql| {1..5}, r=[ a.* |> (*) ], "Product of a.1 * a.2 * ... * a.5 is &a.r"|]

Bash

The command reads from stdin csv with at least 5 numerical columns and returns a list of their products (one per line).

lsql-csv '-, r=[ a.* |> (*) ], "Product of a.1 * a.2 * ... * a.5 is &a.r"'

Body:
I think the question is how to parse and process a string in a uniform way between a quasiquoter and some other chunk of code. If this interpretation is right, then you just... do that. For example:

-- implementation of these is left to the reader, but can use standard Haskell
-- programming techniques and libraries, like parsec and ADTs and stuff
command :: Parser Command
interpret :: Command -> IO ()
jit :: Command -> Exp -- or Q Exp

Then, in your lsql-csv.hs, you would write something like

main = do
    [s] <- getArgs
    case parse command s of
        Left err -> die (show err)
        Right com -> interpret com

and in your LSql/CSV/QQ.hs, you would write something like

lsql = QuasiQuoter { quoteExp = \s -> case parse command s of
    Left err -> qReport True (show err) >> fail ""
    Right com -> return (jit com) -- or just jit com if that's already a Q Exp
    }