问:
Optimizing/Reducing For-loops
I am learning C and I want to have an idea on how can I reduce the for-loops, to make it more presentable.

```<code>#include<stdio.h>

int main() {

char input[81];
int i;
char input2[9][9];
int col,row;
printf("Enter sudoku board:");
scanf("%s",&input);

for (i=0;i<9;i++) {
    for (col=0;col<9;col++)
        input2[0][col]=input[i];
    for (col=0;col<9;col++)
        input2[1][col]=input[i];
    for (col=0;col<9;col++)
        input2[2][col]=input[i];
    for (col=0;col<9;col++)
        input2[3][col]=input[i];
    for (col=0;col<9;col++)
        input2[4][col]=input[i];
    for (col=0;col<9;col++)
        input2[5][col]=input[i];
    for (col=0;col<9;col++)
        input2[6][col]=input[i];
    for (col=0;col<9;col++)
        input2[7][col]=input[i];
    for (col=0;col<9;col++)
        input2[8][col]=input[i];
}
</code>```

this shows that the user would enter 81 numbers in an array then the numbers entered will be transferred to a 9x9 array. thanks in advance!:)

答:
What you want is to fill in a 9 * 9 matrix based on 81 number of inputs. As is mentioned, you need allocate one more character for the terminating '\0'. That's what C-style array is famous for.

```<code>   int i = 0, row = 0, col = 0;
   // set matrix row by row
   for (row = 0; row < 9; row++)
   {
      // for each row, set from left to right
      for (col = 0; col < 9; col++)
      {
        input2[row][col] = input[i++];
      }
   }
</code>```

Improvement: you don't have to pre-allocate a string to hold that 81 characters. You can choose to directly set to the resulting array you want.

```<code>       int i = 0, row = 0, col = 0;
       // set matrix row by row
       for (row = 0; row < 9; row++)
       {
          // for each row, set from left to right
          for (col = 0; col < 9; col++)
          {
            scanf("%c", &input2[row][col]);
          }
       }
</code>```

Title: Optimizing/Reducing For-loops

Body:
I am learning C and I want to have an idea on how can I reduce the for-loops, to make it more presentable.

#include<stdio.h>

int main() {

char input[81];
int i;
char input2[9][9];
int col,row;
printf("Enter sudoku board:");
scanf("%s",&input);

for (i=0;i<9;i++) {
    for (col=0;col<9;col++)
        input2[0][col]=input[i];
    for (col=0;col<9;col++)
        input2[1][col]=input[i];
    for (col=0;col<9;col++)
        input2[2][col]=input[i];
    for (col=0;col<9;col++)
        input2[3][col]=input[i];
    for (col=0;col<9;col++)
        input2[4][col]=input[i];
    for (col=0;col<9;col++)
        input2[5][col]=input[i];
    for (col=0;col<9;col++)
        input2[6][col]=input[i];
    for (col=0;col<9;col++)
        input2[7][col]=input[i];
    for (col=0;col<9;col++)
        input2[8][col]=input[i];
}

this shows that the user would enter 81 numbers in an array then the numbers entered will be transferred to a 9x9 array. thanks in advance!:)

Body:
What you want is to fill in a 9 * 9 matrix based on 81 number of inputs. As is mentioned, you need allocate one more character for the terminating '\0'. That's what C-style array is famous for.

   int i = 0, row = 0, col = 0;
   // set matrix row by row
   for (row = 0; row < 9; row++)
   {
      // for each row, set from left to right
      for (col = 0; col < 9; col++)
      {
        input2[row][col] = input[i++];
      }
   }

Improvement: you don't have to pre-allocate a string to hold that 81 characters. You can choose to directly set to the resulting array you want.

       int i = 0, row = 0, col = 0;
       // set matrix row by row
       for (row = 0; row < 9; row++)
       {
          // for each row, set from left to right
          for (col = 0; col < 9; col++)
          {
            scanf("%c", &input2[row][col]);
          }
       }


来源: stackexchange

问:
Error 400 receieved when fetching from trovo API
I've been granted acces to an API that uses OAuth 2, I've tried it with different API's and my requests were working.
However with the trovo API I seem to get error 400 at every endpoint.
I also get a "blocked by CORS policy: o 'Access-Control-Allow-Origin' header is present on the requested resource."

```<code>function fetching() {
  fetch("https://open-api.trovo.live/openplatform/validate", {
    "method": "GET",
    "headers": {
        "Accept": "application/json",
        "Authorization": "myKey",
        "Client-Id": "myID"
    }
  })
  .then(response => {
    console.log(response.json());
  })
  .catch(err => {
    console.error(err);
  });
}
</code>```

I also recieved a Client Secret not sure what to do with that.
Here is the documentation from Trovo: https://developer.trovo.live/docs/APIs.html

Altogether I'm quite new to working with API's.

答:
The OAuth flow requires a server, and cannot be done entirely on the front-end. In this example, you would need a server running somewhere other than StreamElements that would keep track of the access and refresh token.

You would then have the front end connect to the server to get the access token instead of directly to Trovo. Reason for this: security. To get the access token you need the private key, and you don't want to be sending that to the front end, or else they can do stuff as if they were you.

Even though stream overlays don't seem like a front end, it's most often just a browser being rendered, as if you just had a website open in chrome.

https://www.digitalocean.com/community/tutorials/an-introduction-to-oauth-2

https://www.youtube.com/watch?v=3pZ3Nh8tgTE

ContentLicense: CC BY-SA 4.0

Body:
I've been granted acces to an API that uses OAuth 2, I've tried it with different API's and my requests were working.
However with the trovo API I seem to get error 400 at every endpoint.
I also get a "blocked by CORS policy: o 'Access-Control-Allow-Origin' header is present on the requested resource."

function fetching() {
  fetch("https://open-api.trovo.live/openplatform/validate", {
    "method": "GET",
    "headers": {
        "Accept": "application/json",
        "Authorization": "myKey",
        "Client-Id": "myID"
    }
  })
  .then(response => {
    console.log(response.json());
  })
  .catch(err => {
    console.error(err);
  });
}

I also recieved a Client Secret not sure what to do with that.
Here is the documentation from Trovo: https://developer.trovo.live/docs/APIs.html

Altogether I'm quite new to working with API's.


问:
why does my routing not working (/user/create)
This is how I set up the routing:
I'm trying to render create page when the user access the url domain.com/user/create
but when I try, it redirects to my original .get("/") instead (.get("/create"))

My routes:

[1]: https://i.stack.imgur.com/WrCn4.png

My view folder structure:
[2]: https://i.stack.imgur.com/W9ngF.png

My app.js
[3]: https://i.stack.imgur.com/cfXIr.png

Edited (With new finding and including codes instead of images)
I found out this was because I have the router with :email parameter.

```<code>router.get("/:email", userController.GetUserByParam, (req, res) => {

    console.log(req.data);
    res.render("user", { userList: req.data, date: req.date });
    //res.send(req.data);
    });
</code>```

I just don't understand why that interfere with my create routing?

```<code>router.get("/create", (req, res) => {
    //res.send("Test");
    res.render("Create");
    });
</code>```

答:
remove "/" before create and also add your controller after create.
if you want add data in database you need to use post</p>
```<code>router.post("create",controller.something(req,res)=>{
  res.render("created")
})
</code>```

Body:
This is how I set up the routing:
I'm trying to render create page when the user access the url domain.com/user/create
but when I try, it redirects to my original .get("/") instead (.get("/create"))

My routes:

[1]: https://i.stack.imgur.com/WrCn4.png

My view folder structure:
[2]: https://i.stack.imgur.com/W9ngF.png

My app.js
[3]: https://i.stack.imgur.com/cfXIr.png

Edited (With new finding and including codes instead of images)
I found out this was because I have the router with :email parameter.

router.get("/:email", userController.GetUserByParam, (req, res) => {

    console.log(req.data);
    res.render("user", { userList: req.data, date: req.date });
    //res.send(req.data);
    });

I just don't understand why that interfere with my create routing?

router.get("/create", (req, res) => {
    //res.send("Test");
    res.render("Create");
    });

Body:
remove "/" before create and also add your controller after create.
if you want add data in database you need to use post

router.post("create",controller.something(req,res)=>{
  res.render("created")
})


问:
How to test a NSDate with a wrong NSDateFormatter?
I'm working on iPhone application where the user can enter a date format as he want.
The problem is when he does not enter a valid format.
I don't know how to test it ?

For example, he enter :
Format = @"evlzuhbpùi égkjz $çà i,ùé'po";

I calculate my current date from this wrong format :

```<code>NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:Format];
NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", stringDate);
[dateFormatter release];
</code>```

My string date has a wrong value or hasn't a correct value.

Is anyone can tell me how to test my date format ?

Best regards

答:
Though you choose to validate the dateFormat with valid date format specifiers, it will be really hard to come up with a logic that validates the dateFormat with all the possible valid formats.

A simple but optimal solution would be to convert the converted date string back to NSDate with the same dateFormat. If the resultant date is nil, the definitely the dateFormat is an invalid one.

```<code>// Set the dateFormat to NSDateFormatter
[dateFormatter setDateFormat:Format];

// Get a string from NSDate using the date formatt
NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];

// Convert "stringDate" to NSDate with the same dateFormat
NSDate *date = [dateFormatter dateFromString:stringDate];

if (date == nil)  // The dateFormat is not a valid one
else // The dateFormat seems to be valid
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm working on iPhone application where the user can enter a date format as he want.
The problem is when he does not enter a valid format.
I don't know how to test it ?

For example, he enter :
Format = @"evlzuhbpùi égkjz $çà i,ùé'po";

I calculate my current date from this wrong format :

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:Format];
NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", stringDate);
[dateFormatter release];

My string date has a wrong value or hasn't a correct value.

Is anyone can tell me how to test my date format ?

Best regards

Body:
Though you choose to validate the dateFormat with valid date format specifiers, it will be really hard to come up with a logic that validates the dateFormat with all the possible valid formats.

A simple but optimal solution would be to convert the converted date string back to NSDate with the same dateFormat. If the resultant date is nil, the definitely the dateFormat is an invalid one.

// Set the dateFormat to NSDateFormatter
[dateFormatter setDateFormat:Format];

// Get a string from NSDate using the date formatt
NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];

// Convert "stringDate" to NSDate with the same dateFormat
NSDate *date = [dateFormatter dateFromString:stringDate];

if (date == nil)  // The dateFormat is not a valid one
else // The dateFormat seems to be valid


问:
Setting up reverse proxy Nginx + Gunicorn/Django REST - 404 Not Found
I have a setup with Nginx as web server and Gunicorn as application server serving a Django REST API.

Nginx is listening at port 80 and gunicorn at port 8000 (I launch gunicorn using this command):

```<code>gunicorn --bind 0.0.0.0:8000 cdm_api.wsgi -t 200 --workers=3
</code>```

and when I launch the petition to port 8000, I am able to access to the API running for instance:

```<code>curl -d "username=<user>&password=<pass>" -X POST http://127.0.0.1:8000/api/concept
</code>```

However, when I try to make the petition though Nginx acting as reverse proxy, I get 404 Not Found Error:

```<code>curl -d "username=<user>&password=<pass>" -X POST http://127.0.0.1:80/api/concept
</code>```

Here is my nginx conf file:

```<code>server {
    listen       80;
    listen  [::]:80;
    server_name  127.0.0.1;

    location  /api/ {
        proxy_pass http://127.0.0.1:8000/api/;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_connect_timeout 360s;
        proxy_read_timeout 360s;
    }

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
}
</code>```

Let me know if more information is needed. Thanks in advance!

答:
So

gunicorn will create a sock file and you will have to map your proxy_pass with the sock file created, for now you are mapping to your localhost:8000 for this you will have to run the django runserver command so that nginx can find a server running on port 8000.

something like -

```<code>    location / {
        include proxy_params;
        #proxy_pass http://unix:/home/abc/backend/social.sock;
        proxy_pass http://unix:/home/abc/backend/backend.sock;
    }
</code>```

gunicorn make it possible to serve django at production, you don't have to command runserver everytime. Make sure gunicorn restarts everytime when server reboots.

Body:
I have a setup with Nginx as web server and Gunicorn as application server serving a Django REST API.

Nginx is listening at port 80 and gunicorn at port 8000 (I launch gunicorn using this command):

gunicorn --bind 0.0.0.0:8000 cdm_api.wsgi -t 200 --workers=3

and when I launch the petition to port 8000, I am able to access to the API running for instance:

curl -d "username=<user>&password=<pass>" -X POST http://127.0.0.1:8000/api/concept

However, when I try to make the petition though Nginx acting as reverse proxy, I get 404 Not Found Error:

curl -d "username=<user>&password=<pass>" -X POST http://127.0.0.1:80/api/concept

Here is my nginx conf file:

server {
    listen       80;
    listen  [::]:80;
    server_name  127.0.0.1;

    location  /api/ {
        proxy_pass http://127.0.0.1:8000/api/;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_connect_timeout 360s;
        proxy_read_timeout 360s;
    }

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
}

Let me know if more information is needed. Thanks in advance!

Body:
So

gunicorn will create a sock file and you will have to map your proxy_pass with the sock file created, for now you are mapping to your localhost:8000 for this you will have to run the django runserver command so that nginx can find a server running on port 8000.

something like -

    location / {
        include proxy_params;
        #proxy_pass http://unix:/home/abc/backend/social.sock;
        proxy_pass http://unix:/home/abc/backend/backend.sock;
    }

gunicorn make it possible to serve django at production, you don't have to command runserver everytime. Make sure gunicorn restarts everytime when server reboots.


问:
Does Tuxedo XA transaction manager support ActiveMQ as resource manager for C++ applications?
I am looking for examples or resources to prove support for ActiveMQ as one of the resource managers with Tuxedo as the XA transaction manager. I am working on building a C++ Application to do the same. I am unable to find any documentation on Tuxedo community or Google for the same.</p>

答: No, it does not support it out of the box. There is a list of resource managers supported in $TUXDIR/udataobj/RM. To support ActiveMQ, you should add an entry in the RM file with the resource manager name, a symbol name that contains pointers to XA functions, and a list of libraries for linking the resource manager. After that, you should be able to build a transaction manager server, see the manual for buildtms command.</p>


问:
Remove empty cells and move content to the left Python
I have an Excel file which contains the following structure with no header or index - I've added just the column header from Excel without existing in my table:

A
B
C
D
E
...
J
K

ABC
XLS
1231341231
123123asdad1923
NaN
NaN
...
123123asdad1923

DEF
XLS
1231231231
1231823asda9123
NaN
askda213
...
123123asdad1923

XYZ
XLS
1231231233
2138820394832sd
NaN
NaN
...
asdasdq2ew12332

I would need that all the cells that contains NaN to be removed and while NaN, move the cells to the left.

Output should look like:

A
B
C
D
E
...
J
K

ABC
XLS
1231341231
123123asdad1923
123123asdad1923

DEF
XLS
1231231231
1231823asda9123
askda213
...
123123asdad1923

XYZ
XLS
1231231233
2138820394832sd
asdasdq2ew12332

I have found this similar question dropped on Stackoverflow, but the answer is not doing any change:

```<code>import pandas as pd

df = pd.read_excel('test.xlsx')
df = df.apply(lambda x: pd.Series(x.dropna().values))
df = df.fillna('')

df.to_excel("test_modified.xlsx", index=False, header=False)
</code>```

Any ideas how can achieve this?

Thank you.

答:
Ok, then I propose to transpose the dataset, process it, and transpose it back.

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame(
    {
        "A": ["ABC", "DEF", "XYZ"],
        "B": ["XLS", "XLS", "XLS"],
        "C": ["1231341231", "1231231231", "1231231233"],
        "D": ["123123asdad1923", "1231823asda9123", "2138820394832sd"],
        "E": [np.nan, np.nan, np.nan],
        "F": [np.nan, "askda213", np.nan],
        "I": ["blabla", "blabla", np.nan],
        "K": ["123123asdad1923", "123123asdad1923", "asdasdq2ew12332"],
    }
)

print(df)
# transpose
df_transposed = df.T
# move NaN at end of column
df_transposed = df_transposed.apply(lambda x: pd.Series(x.dropna().values))
# replace Nan by empty strings
df_transposed.replace(np.nan, "", inplace=True)
# transpose back
df = df_transposed.T
print()
print(df)
</code>```

will output:

```<code>     A    B           C                D   E         F       I                K
0  ABC  XLS  1231341231  123123asdad1923 NaN       NaN  blabla  123123asdad1923
1  DEF  XLS  1231231231  1231823asda9123 NaN  askda213  blabla  123123asdad1923
2  XYZ  XLS  1231231233  2138820394832sd NaN       NaN     NaN  asdasdq2ew12332

     0    1           2                3                4                5                6
0  ABC  XLS  1231341231  123123asdad1923           blabla  123123asdad1923
1  DEF  XLS  1231231231  1231823asda9123         askda213           blabla  123123asdad1923
2  XYZ  XLS  1231231233  2138820394832sd  asdasdq2ew12332

</code>```

Body:
I have an Excel file which contains the following structure with no header or index - I've added just the column header from Excel without existing in my table:

A
B
C
D
E
...
J
K

ABC
XLS
1231341231
123123asdad1923
NaN
NaN
...
123123asdad1923

DEF
XLS
1231231231
1231823asda9123
NaN
askda213
...
123123asdad1923

XYZ
XLS
1231231233
2138820394832sd
NaN
NaN
...
asdasdq2ew12332

I would need that all the cells that contains NaN to be removed and while NaN, move the cells to the left.

Output should look like:

A
B
C
D
E
...
J
K

ABC
XLS
1231341231
123123asdad1923
123123asdad1923

DEF
XLS
1231231231
1231823asda9123
askda213
...
123123asdad1923

XYZ
XLS
1231231233
2138820394832sd
asdasdq2ew12332

I have found this similar question dropped on Stackoverflow, but the answer is not doing any change:

import pandas as pd

df = pd.read_excel('test.xlsx')
df = df.apply(lambda x: pd.Series(x.dropna().values))
df = df.fillna('')

df.to_excel("test_modified.xlsx", index=False, header=False)

Any ideas how can achieve this?

Thank you.

Body:
Ok, then I propose to transpose the dataset, process it, and transpose it back.

import pandas as pd
import numpy as np

df = pd.DataFrame(
    {
        "A": ["ABC", "DEF", "XYZ"],
        "B": ["XLS", "XLS", "XLS"],
        "C": ["1231341231", "1231231231", "1231231233"],
        "D": ["123123asdad1923", "1231823asda9123", "2138820394832sd"],
        "E": [np.nan, np.nan, np.nan],
        "F": [np.nan, "askda213", np.nan],
        "I": ["blabla", "blabla", np.nan],
        "K": ["123123asdad1923", "123123asdad1923", "asdasdq2ew12332"],
    }
)

print(df)
# transpose
df_transposed = df.T
# move NaN at end of column
df_transposed = df_transposed.apply(lambda x: pd.Series(x.dropna().values))
# replace Nan by empty strings
df_transposed.replace(np.nan, "", inplace=True)
# transpose back
df = df_transposed.T
print()
print(df)

will output:

     A    B           C                D   E         F       I                K
0  ABC  XLS  1231341231  123123asdad1923 NaN       NaN  blabla  123123asdad1923
1  DEF  XLS  1231231231  1231823asda9123 NaN  askda213  blabla  123123asdad1923
2  XYZ  XLS  1231231233  2138820394832sd NaN       NaN     NaN  asdasdq2ew12332

     0    1           2                3                4                5                6
0  ABC  XLS  1231341231  123123asdad1923           blabla  123123asdad1923
1  DEF  XLS  1231231231  1231823asda9123         askda213           blabla  123123asdad1923
2  XYZ  XLS  1231231233  2138820394832sd  asdasdq2ew12332


问:
Why use traits?
What typical scenario would traits be used for in a Rust program? I have tried to wrap my head around them, but I still don't have a clear concept as to why one would decide to use them. I understand the syntax from reading about them from here.

How would one explain them to someone as if they were 5?

答:
From the docs:

A trait is a collection of methods defined for an unknown type: Self. They can access other methods declared in the same trait.

Traits are similar to interfaces in languages like Java, C++, etc.

It would really be helpful to go over examples, such as the ToString and the Display traits.

If you write this:

```<code>format!("x is {x}");
</code>```

the code will only work (and compile) if x implements the Display interface.

Similarly, this will only work if x implements the Debug interface:

```<code>format!("{x:?}");
</code>```

Leaving aside the "magic" associated with formatting strings, it should be clear x cannot be an instance of just any type. There needs to be a specific implementation that converts a given type to a string. Note that u16's implementation, for example, would be completely different from, say, IpAddr's implementation. However, both types have a common behavior. As a result, a string formatter doesn't even need to know which types implement the Display or Debug trait. It's not its concern. It only cares whether the type in question implements the given trait (and if it does not, the compiler simply won't accept that code).

Title: Why use traits?

Body:
From the docs:

A trait is a collection of methods defined for an unknown type: Self. They can access other methods declared in the same trait.

Traits are similar to interfaces in languages like Java, C++, etc.

It would really be helpful to go over examples, such as the ToString and the Display traits.

If you write this:

format!("x is {x}");

the code will only work (and compile) if x implements the Display interface.

Similarly, this will only work if x implements the Debug interface:

format!("{x:?}");

Leaving aside the "magic" associated with formatting strings, it should be clear x cannot be an instance of just any type. There needs to be a specific implementation that converts a given type to a string. Note that u16's implementation, for example, would be completely different from, say, IpAddr's implementation. However, both types have a common behavior. As a result, a string formatter doesn't even need to know which types implement the Display or Debug trait. It's not its concern. It only cares whether the type in question implements the given trait (and if it does not, the compiler simply won't accept that code).


问:
Row number in Dax
I have following DAX code. I need auto increment row number where FileNo and CI_No code are same. I tired with RANKX function but it return rank as 1 for all records. Any one have any idea how we can achieve this using DAX.

Thanks in advance.

Dax code:

```<code>DEFINE
VAR A = UNION(   ROW ("FileNo",  10, "CI_No", 101, "Amount" ,100)
                ,ROW ("FileNo",  10, "CI_No", 101, "Amount" ,100)
                ,ROW ("FileNo",  10, "CI_No", 101, "Amount" ,100)
                ,ROW ("FileNo",  20, "CI_No", 201, "Amount" ,200)
                ,ROW ("FileNo",  20, "CI_No", 201, "Amount" ,200)
                ,ROW ("FileNo",  20, "CI_No", 301, "Amount" ,300))

VAR B=  ADDCOLUMNS(A,
         "RowNo", RANKX(
        FILTER(A,
               [FileNo]=EARLIER([FileNo]) &&  [CI_No]=EARLIER([CI_No])
                ),
        [Amount], , DESC
        )        )

 EVALUATE B
</code>```

Expected Result

答:
You can try with mix of AddIndexColumn (from TransformData) and new Calculated column:

```<code>RowNo =
          RANKX(
        FILTER( ALLEXCEPT('sample','sample'[RowNo]) , [FileNo] = EARLIER('sample'[FileNo]) &&  [CL_No] = EARLIER('sample'[CL_No]) ),

        [DummySum], , DESC
        )
</code>```

DummySum = sum('sample'[Index])

EDIT:

```<code>Table = VAR A = ADDCOLUMNS(UNION(   ROW ("FileNo",  10, "CI_No", 101, "Amount" ,100)
                ,ROW ("FileNo",  10, "CI_No", 101, "Amount" ,100)
                ,ROW ("FileNo",  10, "CI_No", 101, "Amount" ,100)
                ,ROW ("FileNo",  20, "CI_No", 201, "Amount" ,200)
                ,ROW ("FileNo",  20, "CI_No", 201, "Amount" ,200)
                ,ROW ("FileNo",  20, "CI_No", 301, "Amount" ,300)), "Index", [Amount]+RAND())

VAR B=  ADDCOLUMNS(A,
         "RowNo", RANKX(
        FILTER(A,
               [FileNo]=EARLIER([FileNo]) &&  [CI_No]=EARLIER([CI_No])
                ),
        [Index], , DESC
        )        )

return B
</code>```

Title: Row number in Dax

Body:
I have following DAX code. I need auto increment row number where FileNo and CI_No code are same. I tired with RANKX function but it return rank as 1 for all records. Any one have any idea how we can achieve this using DAX.

Thanks in advance.

Dax code:

DEFINE
VAR A = UNION(   ROW ("FileNo",  10, "CI_No", 101, "Amount" ,100)
                ,ROW ("FileNo",  10, "CI_No", 101, "Amount" ,100)
                ,ROW ("FileNo",  10, "CI_No", 101, "Amount" ,100)
                ,ROW ("FileNo",  20, "CI_No", 201, "Amount" ,200)
                ,ROW ("FileNo",  20, "CI_No", 201, "Amount" ,200)
                ,ROW ("FileNo",  20, "CI_No", 301, "Amount" ,300))

VAR B=  ADDCOLUMNS(A,
         "RowNo", RANKX(
        FILTER(A,
               [FileNo]=EARLIER([FileNo]) &&  [CI_No]=EARLIER([CI_No])
                ),
        [Amount], , DESC
        )        )

 EVALUATE B

Expected Result

Body:
You can try with mix of AddIndexColumn (from TransformData) and new Calculated column:

RowNo =
          RANKX(
        FILTER( ALLEXCEPT('sample','sample'[RowNo]) , [FileNo] = EARLIER('sample'[FileNo]) &&  [CL_No] = EARLIER('sample'[CL_No]) ),

        [DummySum], , DESC
        )

DummySum = sum('sample'[Index])

EDIT:

Table = VAR A = ADDCOLUMNS(UNION(   ROW ("FileNo",  10, "CI_No", 101, "Amount" ,100)
                ,ROW ("FileNo",  10, "CI_No", 101, "Amount" ,100)
                ,ROW ("FileNo",  10, "CI_No", 101, "Amount" ,100)
                ,ROW ("FileNo",  20, "CI_No", 201, "Amount" ,200)
                ,ROW ("FileNo",  20, "CI_No", 201, "Amount" ,200)
                ,ROW ("FileNo",  20, "CI_No", 301, "Amount" ,300)), "Index", [Amount]+RAND())

VAR B=  ADDCOLUMNS(A,
         "RowNo", RANKX(
        FILTER(A,
               [FileNo]=EARLIER([FileNo]) &&  [CI_No]=EARLIER([CI_No])
                ),
        [Index], , DESC
        )        )

return B


问:
Why is this regression plot only plotting 2 of my regression coefficients?
```<code>#Plot voor price - carat
plot(training_diamanten$carat,training_diamanten$price, xlim=c(0,4.5),
+      ylim=c(0,20000), pch=1, las=1, bty='l', col='dark blue',
+      xlab = 'Hoeveelheid karaat in gewicht',
+      ylab='De prijs in US dollars',
+      main = 'Hoeveelheid karaat in gewicht vs de prijs in US dollars')
abline(model_carat, col='red', lwd=5)

Warning message:
In abline(model_carat, col = "red", lwd = 5) :
  only using the first two of 263 regression coefficients
</code>```

答:
Here is what I get when splitting the diamonds dataset 70:30:

Splitting in train and test dataset:

```<code>dt = sort(sample(nrow(diamonds), nrow(diamonds)*.7))

training_diamanten <- diamonds[dt,]
test_diamanten <- diamonds[dt,]
</code>```

Your provided code:

```<code>model_carat <- lm(price ~ carat, data = training_diamanten)

summary(model_carat)

plot(training_diamanten$carat,training_diamanten$price, xlim=c(0,4.5),
     ylim=c(0,20000), pch=1, las=1, bty='l', col='dark blue',
     xlab = 'Hoeveelheid karaat in gewicht',
     ylab='De prijs in US dollars',
     main = 'Hoeveelheid karaat in gewicht vs de prijs in US dollars')
abline(model_carat, col='red', lwd=5)
</code>```

Body:
Here is what I get when splitting the diamonds dataset 70:30:

Splitting in train and test dataset:

dt = sort(sample(nrow(diamonds), nrow(diamonds)*.7))

training_diamanten <- diamonds[dt,]
test_diamanten <- diamonds[dt,]

Your provided code:

model_carat <- lm(price ~ carat, data = training_diamanten)

summary(model_carat)

plot(training_diamanten$carat,training_diamanten$price, xlim=c(0,4.5),
     ylim=c(0,20000), pch=1, las=1, bty='l', col='dark blue',
     xlab = 'Hoeveelheid karaat in gewicht',
     ylab='De prijs in US dollars',
     main = 'Hoeveelheid karaat in gewicht vs de prijs in US dollars')
abline(model_carat, col='red', lwd=5)


问:
Why nine-patch image in RelativeLayour hides all inner elements?
When I set 9.PNG image as RelativeLayout's background, all elements inside it gets shrunken to the middle. Here is the XML and the snapshot.

```<code><RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@drawable/bg"
        >
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Just a simple white text which does not show up"
            android:textColor="#ffffff"
            />
</RelativeLayout>
</code>```

If I change background to a color or a normal image, I get the text.

```<code>android:background="@drawable/bg2" //normal image
</code>```

Can anyone explain why is this happening?

答:
Did you define the content area of your nine-patch? Because it looks like the content area is the little pixel in the middle.

The content area is defined by the bottom and right sides of your nine patch. You can for example make it as big as your patch.

Body:
When I set 9.PNG image as RelativeLayout's background, all elements inside it gets shrunken to the middle. Here is the XML and the snapshot.

<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@drawable/bg"
        >
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Just a simple white text which does not show up"
            android:textColor="#ffffff"
            />
</RelativeLayout>

If I change background to a color or a normal image, I get the text.

android:background="@drawable/bg2" //normal image

Can anyone explain why is this happening?


问:
best way to calculate available slots in JavaScript
I have an array of objects as below.

```<code>prepareTimeStamps = [
    {
        "date": "01/23",
        "name": "Jimmy",
        "startTime": "01/23/2022 5:00 pm",
        "endTime": "01/23/2022 7:00 pm",
        "slots": "05:00 PM,05:30 PM,06:00 PM,06:30 PM,07:00 PM"
    },
    {
        "date": "01/23",
        "name": "James",
        "startTime": "01/23/2022 5:00 pm",
        "endTime": "01/23/2022 6:00 pm",
        "slots": "05:00 PM,05:30 PM,06:00 PM"
    },
    {
        "date": "01/23",
        "name": "Jason",
        "startTime": "01/23/2022 5:00 pm",
        "endTime": "01/23/2022 7:00 pm",
        "slots": "05:00 PM,05:30 PM,06:00 PM,06:30 PM,07:00 PM"
    }
]
</code>```

Here James is available for 5 to 6 PM only however, Jimmy and Jason are available 5 to 7 PM. So I want results like 5 to 6 PM all 3 are available, but for 5 to 7 only 2 people are available.

I tried using calculating the string length of slots but it couldn't work for smaller strings.

Thanks in advance.

答:
One idea can be to calculate the hours between midnight the start/end of the slots. Then make the same calculation for request part and compare the numbers. The code down below should calculate, but I didn't run it. If it works, it will return

```<code>[9, 13.5]
// when the slots:
"09:00 PM,....01:30 AM"
</code>```

let slots = "05:00 PM,05:30 PM,06:00 PM,06:30 PM,07:00 PM"

let freeTime = slots.split(',').map(slot => freeTime(calculate(slot)));

let calculate = (slot) => {
  return slot.trim().split(' ').map(time => hoursFromMidnight(time));
}

let hoursFromMidnight = (time) => {
  let [h, m] = time[0].split(':');

  return  parsInt(h)
        + time[1].toLowerCase() == 'am' ? 12 : 0
        + parseInt(m) / 60;
}

const freeTime = (slots) => {
  return [slots[0], slots[slots.length - 1]]
}
```

Body:
I have an array of objects as below.

prepareTimeStamps = [
    {
        "date": "01/23",
        "name": "Jimmy",
        "startTime": "01/23/2022 5:00 pm",
        "endTime": "01/23/2022 7:00 pm",
        "slots": "05:00 PM,05:30 PM,06:00 PM,06:30 PM,07:00 PM"
    },
    {
        "date": "01/23",
        "name": "James",
        "startTime": "01/23/2022 5:00 pm",
        "endTime": "01/23/2022 6:00 pm",
        "slots": "05:00 PM,05:30 PM,06:00 PM"
    },
    {
        "date": "01/23",
        "name": "Jason",
        "startTime": "01/23/2022 5:00 pm",
        "endTime": "01/23/2022 7:00 pm",
        "slots": "05:00 PM,05:30 PM,06:00 PM,06:30 PM,07:00 PM"
    }
]

Here James is available for 5 to 6 PM only however, Jimmy and Jason are available 5 to 7 PM. So I want results like 5 to 6 PM all 3 are available, but for 5 to 7 only 2 people are available.

I tried using calculating the string length of slots but it couldn't work for smaller strings.

Thanks in advance.

Body:
One idea can be to calculate the hours between midnight the start/end of the slots. Then make the same calculation for request part and compare the numbers. The code down below should calculate, but I didn't run it. If it works, it will return

[9, 13.5]
// when the slots:
"09:00 PM,....01:30 AM"

let slots = "05:00 PM,05:30 PM,06:00 PM,06:30 PM,07:00 PM"

let freeTime = slots.split(',').map(slot => freeTime(calculate(slot)));

let calculate = (slot) => {
  return slot.trim().split(' ').map(time => hoursFromMidnight(time));
}

let hoursFromMidnight = (time) => {
  let [h, m] = time[0].split(':');

  return  parsInt(h)
        + time[1].toLowerCase() == 'am' ? 12 : 0
        + parseInt(m) / 60;
}

const freeTime = (slots) => {
  return [slots[0], slots[slots.length - 1]]
}


问:
-bash: yarn: command not found even after installing it globally
Mac OS  10.13.6

How did I install yarn

```<code>npm install --global yarn
</code>```

yarn installation path is /Users/useName/.config/yarn

Then ran below command

```<code>yarn create react-app app-name
</code>```

This worked well, but when I'm trying to run yarn add package_name, it's throwing error

```<code>bash: yarn: command not found
</code>```

The weird thing, after closing and opening terminal again under which I had globally ( ? ) installed yarn, the yarn command is not found.

答: Just re- install using "brew install yarn" and that should solve it.</p>

Body:
Mac OS  10.13.6

How did I install yarn

npm install --global yarn

yarn installation path is /Users/useName/.config/yarn

Then ran below command

yarn create react-app app-name

This worked well, but when I'm trying to run yarn add package_name, it's throwing error

bash: yarn: command not found

The weird thing, after closing and opening terminal again under which I had globally ( ? ) installed yarn, the yarn command is not found.


问:
Sort JSON response by date in laravel 5.5
So far I noticed, It is sorting with the first character of the date

My Code

```<code>$data = json_decode($json);
$collection = new Collection($data);
$collection->sortByDesc('CreationDate')
</code>```

My JSON

```<code>"[{"NumberCase":"CCS - 102957","CreationDate":"03/12/2019 16:59:19","ServiceName":"Televisión por Cable","ClientReport":"No ve algunos canales","StatusCode":"Activo"},{"NumberCase":"CCS - 107539","CreationDate":"23/12/2019 16:49:36","ServiceName":"Televisión por Cable","ClientReport":"No ve ningun canal","StatusCode":"Activo"},{"NumberCase":"CCS - 110407","CreationDate":"10/01/2020 16:58:42","ServiceName":"Televisión por Cable","ClientReport":"Baja calidad de imágen","StatusCode":"Activo"},{"NumberCase":"CCS - 115482","CreationDate":"04/02/2020 18:55:24","ServiceName":"Televisión por Cable","ClientReport":"No ve ningun canal","StatusCode":"Activo"},{"NumberCase":"CCS - 118120","CreationDate":"17/02/2020 13:36:58","ServiceName":"Televisión por Cable","ClientReport":"No ve ningun canal","StatusCode":"Activo"},{"NumberCase":"CCS - 189126","CreationDate":"18/08/2021 21:03:10","ServiceName":"Televisión por Cable","ClientReport":"No ve ningun canal","StatusCode":"Activo"},{"NumberCase":"CCS - 189870","CreationDate":"23/08/2021 16:41:50","ServiceName":"Televisión por Cable","ClientReport":"No ve algunos canales","StatusCode":"Resuelto"},{"NumberCase":"CCS - 82862","CreationDate":"09/09/2019 20:47:16","ServiceName":"Televisión por Cable","ClientReport":"No ve ningun canal","StatusCode":"Activo"},{"NumberCase":"CCS - 85805","CreationDate":"19/09/2019 20:35:24","ServiceName":"Televisión por Cable","ClientReport":"Se congela la imagén y salen cuadros en toda la pantalla","StatusCode":"Activo"}]"
</code>```

答:
I believe the issue you are facing is because of the non-standard datetime format. Try the following, it should work:

$collection->sortByDesc(function($item) {
    return DateTime::createFromFormat('d/m/Y H:i:s', $item->CreationDate);
});
```

Body:
So far I noticed, It is sorting with the first character of the date

My Code

$data = json_decode($json);
$collection = new Collection($data);
$collection->sortByDesc('CreationDate')

My JSON

"[{"NumberCase":"CCS - 102957","CreationDate":"03/12/2019 16:59:19","ServiceName":"Televisión por Cable","ClientReport":"No ve algunos canales","StatusCode":"Activo"},{"NumberCase":"CCS - 107539","CreationDate":"23/12/2019 16:49:36","ServiceName":"Televisión por Cable","ClientReport":"No ve ningun canal","StatusCode":"Activo"},{"NumberCase":"CCS - 110407","CreationDate":"10/01/2020 16:58:42","ServiceName":"Televisión por Cable","ClientReport":"Baja calidad de imágen","StatusCode":"Activo"},{"NumberCase":"CCS - 115482","CreationDate":"04/02/2020 18:55:24","ServiceName":"Televisión por Cable","ClientReport":"No ve ningun canal","StatusCode":"Activo"},{"NumberCase":"CCS - 118120","CreationDate":"17/02/2020 13:36:58","ServiceName":"Televisión por Cable","ClientReport":"No ve ningun canal","StatusCode":"Activo"},{"NumberCase":"CCS - 189126","CreationDate":"18/08/2021 21:03:10","ServiceName":"Televisión por Cable","ClientReport":"No ve ningun canal","StatusCode":"Activo"},{"NumberCase":"CCS - 189870","CreationDate":"23/08/2021 16:41:50","ServiceName":"Televisión por Cable","ClientReport":"No ve algunos canales","StatusCode":"Resuelto"},{"NumberCase":"CCS - 82862","CreationDate":"09/09/2019 20:47:16","ServiceName":"Televisión por Cable","ClientReport":"No ve ningun canal","StatusCode":"Activo"},{"NumberCase":"CCS - 85805","CreationDate":"19/09/2019 20:35:24","ServiceName":"Televisión por Cable","ClientReport":"Se congela la imagén y salen cuadros en toda la pantalla","StatusCode":"Activo"}]"


问:
Read and print file char by char
I am reading and then printing  this file char by char but now I would like to print 20 chars by 20 chars, incrementig the i value like i+=20 is not what i want.</p>
```<code>File fitxer = new File ("C:\\Users\\yuto\\IdeaProjects\\M6-DataAccess\\src\\UF1\\FluxesAndStreams\\A1.java");
            FileReader flux = new FileReader (fitxer);
            int i;
            while ((i = flux.read()) != -1) {

                System.out.println((char) i);
            }
            flux.close();
</code>```

答:
You can use aux variables like that:

```<code>File fitxer = new File ("C:\\Users\\yuto\\IdeaProjects\\M6-DataAccess\\src\\UF1\\FluxesAndStreams\\A1.java");
FileReader flux = new FileReader (fitxer);
int i;
byte aux = 0;
String s = "";
while ((i = flux.read()) != -1) {
    if (20 == aux){
        System.out.println(s);
        s = "";
        aux = 1
    }
    s+=i;
    aux++;
}
flux.close();
</code>```

or you can use the read overloaded method in FileReader who does exactly the same thing.

```<code>/* method signature
 * cbuf - Destination buffer
 * offset - Offset at which to start storing characters
 * length - Maximum number of characters to read
 */
public int read(char[] cbuf, int offset, int length) // return the number of bytes read
</code>```

example of read method mentioned above: https://www.tutorialspoint.com/java/io/inputstreamreader_read_char.htm

note the FileRead inherits read method from InputStreamReader.

Title: Read and print file char by char

Body:
I am reading and then printing  this file char by char but now I would like to print 20 chars by 20 chars, incrementig the i value like i+=20 is not what i want.

File fitxer = new File ("C:\\Users\\yuto\\IdeaProjects\\M6-DataAccess\\src\\UF1\\FluxesAndStreams\\A1.java");
            FileReader flux = new FileReader (fitxer);
            int i;
            while ((i = flux.read()) != -1) {

                System.out.println((char) i);
            }
            flux.close();

Body:
You can use aux variables like that:

File fitxer = new File ("C:\\Users\\yuto\\IdeaProjects\\M6-DataAccess\\src\\UF1\\FluxesAndStreams\\A1.java");
FileReader flux = new FileReader (fitxer);
int i;
byte aux = 0;
String s = "";
while ((i = flux.read()) != -1) {
    if (20 == aux){
        System.out.println(s);
        s = "";
        aux = 1
    }
    s+=i;
    aux++;
}
flux.close();

or you can use the read overloaded method in FileReader who does exactly the same thing.

/* method signature
 * cbuf - Destination buffer
 * offset - Offset at which to start storing characters
 * length - Maximum number of characters to read
 */
public int read(char[] cbuf, int offset, int length) // return the number of bytes read

example of read method mentioned above: https://www.tutorialspoint.com/java/io/inputstreamreader_read_char.htm

note the FileRead inherits read method from InputStreamReader.


问:
Async/Await in fetch() how to handle errors
I have stripe async code in my React app, and trying to add error handling in my code but have no idea how to handle it. i know how to do it with .then() but async/await is new to me

EDITED

added .catch() i got errors in network tab in response tab.
but i can log it to console?

```<code>    submit = async () => {
    const { email, price, name, phone, city, street, country } = this.state;
    let { token } = await this.props.stripe
      .createToken({
        name,
        address_city: city,
        address_line1: street,
        address_country: country
      })
      .catch(err => {
        console.log(err.response.data);
      });

    const data = {
      token: token.id,
      email,
      price,
      name,
      phone,
      city,
      street,
      country
    };

    let response = await fetch("/charge/pay", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    }).catch(err => {
      console.log(err.response.data);
    });
    console.log(response);
    if (response.ok)
      this.setState({
        complete: true
      });
  };
</code>```

thanks

答:
If response.ok is false you can throw an error then chain catch method after calling your function as follows</p>
```<code>async function fetchData(){
    const response = await fetch("/charge/pay", {
      method: "POST",
      headers: {
          "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    });

    if(!response.ok){
        const message = `An error occured: ${response.status}`;
        throw new Error(message);
    }

    const data = await response.json();
    return data;
}

fetchData()
    .catch(err => console.log(err.message));
</code>```

Body:
I have stripe async code in my React app, and trying to add error handling in my code but have no idea how to handle it. i know how to do it with .then() but async/await is new to me

EDITED

added .catch() i got errors in network tab in response tab.
but i can log it to console?

    submit = async () => {
    const { email, price, name, phone, city, street, country } = this.state;
    let { token } = await this.props.stripe
      .createToken({
        name,
        address_city: city,
        address_line1: street,
        address_country: country
      })
      .catch(err => {
        console.log(err.response.data);
      });

    const data = {
      token: token.id,
      email,
      price,
      name,
      phone,
      city,
      street,
      country
    };

    let response = await fetch("/charge/pay", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    }).catch(err => {
      console.log(err.response.data);
    });
    console.log(response);
    if (response.ok)
      this.setState({
        complete: true
      });
  };

thanks

Body:
If response.ok is false you can throw an error then chain catch method after calling your function as follows

async function fetchData(){
    const response = await fetch("/charge/pay", {
      method: "POST",
      headers: {
          "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    });

    if(!response.ok){
        const message = `An error occured: ${response.status}`;
        throw new Error(message);
    }

    const data = await response.json();
    return data;
}

fetchData()
    .catch(err => console.log(err.message));


问:
Easiest way to search column value, match with a set value, and assign to a variable in python
Aim: check if my bad_outcomes set includes df['Outcome'] pd dataframe column values. If the set does contain these values I want to assign them to a new variable landing_outcome with the value of 0. If not I assign landing_outcome a value of 1.

I am able to search a column df['Outcome'] and check if the values are in my set called 'bad_outcomes' using isin.

```<code>df[df['Outcome'].isin (bad_outcomes)]
</code>```

This works. Then I try to put this in an if statement

```<code>if df[df['Outcome'].isin (bad_outcomes)]:
    landing_outcome = 0
</code>```

This gives me a Value error:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Where I am going wrong?
Is using isin the best way to do this?

I checked python manual for if statements and could't find an obvious syntax issue, I searched this forum for the error message (there are many posts but I couldn't see one for my use case). I'm new, I hope this is ok to ask.

答:
I found this answer on condition statements on [codegrepper][1] which referenced this resource on stackoverflow

Which linked back to stackoverflow here: Pandas conditional creation of a series/dataframe column

Using this approach my solution was:

```<code>landing_class=[0 if outcome in bad_outcomes else 1 for outcome in df['Outcome']]
</code>```

Body:
Aim: check if my bad_outcomes set includes df['Outcome'] pd dataframe column values. If the set does contain these values I want to assign them to a new variable landing_outcome with the value of 0. If not I assign landing_outcome a value of 1.

I am able to search a column df['Outcome'] and check if the values are in my set called 'bad_outcomes' using isin.

df[df['Outcome'].isin (bad_outcomes)]

This works. Then I try to put this in an if statement

if df[df['Outcome'].isin (bad_outcomes)]:
    landing_outcome = 0

This gives me a Value error:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Where I am going wrong?
Is using isin the best way to do this?

I checked python manual for if statements and could't find an obvious syntax issue, I searched this forum for the error message (there are many posts but I couldn't see one for my use case). I'm new, I hope this is ok to ask.

Body:
I found this answer on condition statements on [codegrepper][1] which referenced this resource on stackoverflow

Which linked back to stackoverflow here: Pandas conditional creation of a series/dataframe column

Using this approach my solution was:

landing_class=[0 if outcome in bad_outcomes else 1 for outcome in df['Outcome']]


问:
Why is Visual Studio 2022 building my project in Release build when settings are set for Debug build?
I am trying to debug an assembly in a web project. The web project has a reference to the assembly. I have the code for the assembly. I have set the assembly project whose target framework is .Net Standatd 2.0 to Debug build as shown below.
I copied the generated .dll and .pdb files to the \bin\debug\net50 folder of the web project (targets .NET 5.0). During debugging the web project, I noticed in the modules window that Visual Studio loaded the assembly as Optimized and Skipped loading symbols. The dll and .pdb files have the same timestamps. I am not sure why the assembly's symbols are not being loaded.

Then I used this Assembly Information tool and it showed the dll as Release and optimized. So that explains why VS is loading it as such?

My question is why is it being built as Release and optimized?
My goal is getting VS to load it where I can set breakpoints and single step through the assembly code.

答: There was an Optimize property set to true in the csproj file. Changed it to false.</p>


答:
Try to parse the date into a DateTime object first, something like this

```<code>$data = json_decode($json);
$collection = new Collection($data);
$collection->sortByDesc(fn($item) => new \DateTime($item->CreationDate));
</code>```

Title: Sort JSON response by date in laravel 5.5

Body:
Try to parse the date into a DateTime object first, something like this

$data = json_decode($json);
$collection = new Collection($data);
$collection->sortByDesc(fn($item) => new \DateTime($item->CreationDate));


问:
List<Integer> to List<Long> conversion in Java 11 using Streams
I have a list of Integer and would like to convert into a list of Long (or any other type) by using Streams. I tried multiple options but all failed. How do I do that?</p>
```<code>List<Integer> arr = new ArrayList<Integer>();
    arr.add(1);
    arr.add(3);
    arr.add(5);
    arr.add(7);
    arr.add(9);
</code>```

答:
Use:

List<Long> longList = arr.stream()
    .map(Long::valueOf) //or map to any other type/objects with "e -> new..."
    .collect(Collectors.toList());
```

Body:
I have a list of Integer and would like to convert into a list of Long (or any other type) by using Streams. I tried multiple options but all failed. How do I do that?

List<Integer> arr = new ArrayList<Integer>();
    arr.add(1);
    arr.add(3);
    arr.add(5);
    arr.add(7);
    arr.add(9);


问:
for name in `ls` and filenames with spaces
next code doesnt work because of spaces in file names, How to fix?</p>

```<code>IFS = '\n'
for name in `ls `
do
    number=`echo "$name" | grep -o "[0-9]\{1,2\}"`
    if [[ ! -z "$number" ]]; then
        mv "$name" "./$number"
    fi
done
</code>```

答:
For me, I had to move to use find.

find /foo/path/ -maxdepth 1 -type f -name "*.txt" | while read name
do
    #do your stuff with $name
done
```

Body:
next code doesnt work because of spaces in file names, How to fix?

IFS = '\n'
for name in `ls `
do
    number=`echo "$name" | grep -o "[0-9]\{1,2\}"`
    if [[ ! -z "$number" ]]; then
        mv "$name" "./$number"
    fi
done


问:
Tiptap editor, how to paste multiple empty lines?
Using the basic version fo Tiptap editor:

```<code><template>
  <div v-if="editor">
    <editor-content :editor="editor" />
  </div>
</template>

<script>
import { Editor, EditorContent } from '@tiptap/vue-3'
import Document from '@tiptap/extension-document'
import Paragraph from '@tiptap/extension-paragraph'
import Text from '@tiptap/extension-text'

export default {
  components: {
    EditorContent,
  },

  data() {
    return {
      editor: null,
    }
  },

  mounted() {
    this.editor = new Editor({
      extensions: [
        Document,
        Paragraph,
        Text,
      ],
      content: `
        <p>The Paragraph extension is not required, but it’s very likely you want to use it. It’s needed to write paragraphs of text. </p>
      `,
    })
  },

  beforeUnmount() {
    this.editor.destroy()
  },
}
</script>
</code>```

(which is available to test at https://tiptap.dev/api/nodes/paragraph)

I noticed that when pasting a text with multiple lines, such as :

```<code>Hello

This is a test with two break lines at the above and three after this:

Thanks!
</code>```

The resulting is :

```<code><p>Hello</p>
<p>This is a test with two break lines at the above and three after this:</p>
<p>Thanks!</p>
</code>```

In this case, all the "multiple" break lines has been removed!

Is there a way to keep them, which means that once the paste is executed, the content should be:

```<code><p>Hello</p>
<p></p>
<p></p>
<p>This is a test with two break lines at the above and three after this:</p>
<p></p>
<p></p>
<p></p>
<p>Thanks!</p>
</code>```

(I'm ok with having

 instead of

 by enabling the Hardbreak extension too, but in either case, it doesn't work).

答:
I think you can use Paste Rules extension. You can look for empty lines with regex and replace them with
. Here is the example from TipTap docs:

```<code>// Check pasted content for the ~single tilde~ markdown syntax
import Strike from '@tiptap/extension-strike'
import { markPasteRule } from '@tiptap/core'

// Default:
// const pasteRegex = /(?:^|\s)((?:~~)((?:[^~]+))(?:~~))/g

// New:
const pasteRegex = /(?:^|\s)((?:~)((?:[^~]+))(?:~))/g

const CustomStrike = Strike.extend({
  addPasteRules() {
    return [
      markPasteRule({
        find: pasteRegex,
        type: this.type,
      }),
    ]
  },
})
</code>```

Alternatively, you can try disabling the paste rules altogether to see if that will solve your issue.

```<code>new Editor({
  content: `<p>Example Text</p>`,
  extensions: [
    StarterKit,
  ],
  enablePasteRules: false,
})
</code>```

Body:
Using the basic version fo Tiptap editor:

<template>

    <editor-content :editor="editor" />

</template>

(which is available to test at https://tiptap.dev/api/nodes/paragraph)

I noticed that when pasting a text with multiple lines, such as :

Hello

This is a test with two break lines at the above and three after this:

Thanks!

The resulting is :

Hello

This is a test with two break lines at the above and three after this:

Thanks!

In this case, all the "multiple" break lines has been removed!

Is there a way to keep them, which means that once the paste is executed, the content should be:

Hello

This is a test with two break lines at the above and three after this:

Thanks!

(I'm ok with having

 instead of

 by enabling the Hardbreak extension too, but in either case, it doesn't work).

Body:
I think you can use Paste Rules extension. You can look for empty lines with regex and replace them with <br>. Here is the example from TipTap docs:

// Check pasted content for the ~single tilde~ markdown syntax
import Strike from '@tiptap/extension-strike'
import { markPasteRule } from '@tiptap/core'

// Default:
// const pasteRegex = /(?:^|\s)((?:~~)((?:[^~]+))(?:~~))/g

// New:
const pasteRegex = /(?:^|\s)((?:~)((?:[^~]+))(?:~))/g

const CustomStrike = Strike.extend({
  addPasteRules() {
    return [
      markPasteRule({
        find: pasteRegex,
        type: this.type,
      }),
    ]
  },
})

Alternatively, you can try disabling the paste rules altogether to see if that will solve your issue.

new Editor({
  content: `<p>Example Text</p>`,
  extensions: [
    StarterKit,
  ],
  enablePasteRules: false,
})


问:
node.js create dynamic variables
I have a code where I want to generate manually using a function that creates variables and assign their values dynamically

an example code I want the function to generate :

```<code>  const browser1 = await puppeteer.launch();
  const browser2 = await puppeteer.launch();
  const browser3 = await puppeteer.launch();
  const browser4 = await puppeteer.launch();
  const browser5 = await puppeteer.launch();
  const browser6 = await puppeteer.launch();
  const context1 = await browser1.createIncognitoBrowserContext();
  const context2 = await browser2.createIncognitoBrowserContext();
  const context3 = await browser3.createIncognitoBrowserContext();
  const context4 = await browser4.createIncognitoBrowserContext();
  const context5 = await browser5.createIncognitoBrowserContext();
  const context6 = await browser6.createIncognitoBrowserContext();
  const page1 = await context1.newPage();
  const page2 = await context2.newPage();
  const page3 = await context3.newPage();
  const page4 = await context4.newPage();
  const page5 = await context5.newPage();
  const page6 = await context6.newPage();

</code>```

答:
Maybe something like this?</p>
```<code>const browsers = []
const contexts = []
const pages = []
const size = 6

for (let i = 0; i < size; i ++) {
  const browser = await puppeteer.launch()
  browsers.push(browser)
  const context = await browser.createIncognitoBrowserContext()
  contexts.push(context)
  const page = await context.newPage()
  pages.push(page)
}
</code>```

Title: node.js create dynamic variables

Body:
I have a code where I want to generate manually using a function that creates variables and assign their values dynamically

an example code I want the function to generate :

  const browser1 = await puppeteer.launch();
  const browser2 = await puppeteer.launch();
  const browser3 = await puppeteer.launch();
  const browser4 = await puppeteer.launch();
  const browser5 = await puppeteer.launch();
  const browser6 = await puppeteer.launch();
  const context1 = await browser1.createIncognitoBrowserContext();
  const context2 = await browser2.createIncognitoBrowserContext();
  const context3 = await browser3.createIncognitoBrowserContext();
  const context4 = await browser4.createIncognitoBrowserContext();
  const context5 = await browser5.createIncognitoBrowserContext();
  const context6 = await browser6.createIncognitoBrowserContext();
  const page1 = await context1.newPage();
  const page2 = await context2.newPage();
  const page3 = await context3.newPage();
  const page4 = await context4.newPage();
  const page5 = await context5.newPage();
  const page6 = await context6.newPage();

Body:
Maybe something like this?

const browsers = []
const contexts = []
const pages = []
const size = 6

for (let i = 0; i < size; i ++) {
  const browser = await puppeteer.launch()
  browsers.push(browser)
  const context = await browser.createIncognitoBrowserContext()
  contexts.push(context)
  const page = await context.newPage()
  pages.push(page)
}


问:
Averaging and Grouping In google Big Query
I have the table as shown in google big Query:

I just want to do the following:

Calculate Category wise total units sold

Calculate  Category wise average selling price

答:
consider below approach

```<code>select 'category' type, category name, count(1) units_sold, sum(sale_price) total_sale, round(avg(sale_price), 2) average_selling_price
from your_table group by category
union all
select * from (
  select 'product' type, product name, count(1) units_sold, sum(sale_price) total_sale, round(avg(sale_price), 2) average_selling_price
  from your_table group by product
  order by total_sale desc limit 10
)
union all
select * from (
  select 'order_date' type, '' || order_date name, count(1) units_sold, sum(sale_price) total_sale, round(avg(sale_price), 2) average_selling_price
  from your_table group by order_date
  order by total_sale desc limit 5
)
order by type
</code>```

if applied to sample/dummy data - output would be like below

Body:
consider below approach

select 'category' type, category name, count(1) units_sold, sum(sale_price) total_sale, round(avg(sale_price), 2) average_selling_price
from your_table group by category
union all
select * from (
  select 'product' type, product name, count(1) units_sold, sum(sale_price) total_sale, round(avg(sale_price), 2) average_selling_price
  from your_table group by product
  order by total_sale desc limit 10
)
union all
select * from (
  select 'order_date' type, '' || order_date name, count(1) units_sold, sum(sale_price) total_sale, round(avg(sale_price), 2) average_selling_price
  from your_table group by order_date
  order by total_sale desc limit 5
)
order by type

if applied to sample/dummy data - output would be like below


问:
Doesn't qsort() C library function work on linked lists?
I am trying to sort a singly linked list which has been created and all its items,pointers initialized. I am trying to use qsort() C library function as shown below. It doesn't seem to sort the list. It is giving me compiler error saying:
 left of 'item' specifies undefined struct/union 'LINKED_LIST_S' at line shown below in the code.

```<code>struct LINKED_LIST_S
{
         int item;
         struct LINKED_LIST_S * next;
 } ;

typedef int (*cmpfn)(const void *ptr1, const void *ptr2);

int mylistsort(my_list_t list, cmpfn f1)
{

    qsort ( list , 100, sizeof (struct LINKED_LIST_S), (fn) );
   return -1;
}

int sort_fn_ascend(const void *ptr1, const void *ptr2)
{
    int a = (*(LINKED_LIST_S *)ptr1).item; //Compiler error
   int b = (*(LINKED_LIST_S *)ptr2).item; //Compiler error

  return b - a;

}

int sort_fn_descend(const void *ptr1, const void *ptr2)
{
   int a = ((struct LINKED_LIST_S *)ptr1)->item; //Compiler error
   int b = ((struct LINKED_LIST_S *)ptr2)->item; //Compiler error

  return a - b;

}
</code>```

this is how the function mylistsort() is called at 2 places:

mylistsort(list, sort_fn_descend);//where list a properly initialized linked list pointer.

mylistsort(list, sort_fn_ascend);//where list a properly initialized linked list pointer.

1] Doesn't qsort() work on linked list if the head node poitner is passed as base array(first argument) to qsort.

2] How do I achieve the sorting of this linked list using qsort() in above code?

EDIT: Thanks for the answers. Now I have implemented a way to sort a list as mentioned by @muksie approach 1] he suggested, as code below. Still qsort() does not return a sorted array of ints.
First I want to sort an array of 100 elements, in descending order, but passed array is exact reverse, i.e. the elements are in ascending order of from 1,2,...100. What am I doing wrong? How can I fix it?

```<code>int linkedListSort(LINKED_LIST_T list, newCompareFunction fn, void *usr_info)
{
    LINKED_LIST_T tmpptr = list;
    int newitems[N_ITEMS];
    int i=0;

    //Logic to get all the items in the list in a array
    while(tmpptr != NULL)
    {
        newitems[i] = tmpptr->item;
        tmpptr = tmpptr->next;
        i++;
    }
    tmpptr = list;
    i = 0;
    //Sort that array
    //qsort ( list , 100, sizeof (struct LINKED_LIST_S), (fn) );
    qsort ( newitems , 100, sizeof(list->item), (fn) );

    //store the sorted items back into the list.
    while(tmpptr != NULL)
    {
        tmpptr->item = newitems[i];
        tmpptr = tmpptr->next;
        i++;
    }

   return -1;
}

int sort_fn_descend(void *ptr1,void *ptr2)
{
   int a = *((int*)(ptr1));
   int b = *((int*) (ptr2));

  return a - b;

}

int sort_fn_ascend(const void *ptr1, const void *ptr2)
{
    int a = *((int*)(ptr1));
   int b = *((int*) (ptr2));

  return b - a;

}
</code>```

答:
Since I was able to solve the problem, using approach 2] suggested by @muskie in his answer, I am posting the answer here.
A bug fix in functions sort_fn_descend/ascend, mentioned in the edited OP was needed , and the code is sorting the list jsut fine. Bug fix FYI - the descend function above should return b - a and ascend fn should return a - b. </p>

Body:
I am trying to sort a singly linked list which has been created and all its items,pointers initialized. I am trying to use qsort() C library function as shown below. It doesn't seem to sort the list. It is giving me compiler error saying:
 left of 'item' specifies undefined struct/union 'LINKED_LIST_S' at line shown below in the code.

struct LINKED_LIST_S
{
         int item;
         struct LINKED_LIST_S * next;
 } ;

typedef int (*cmpfn)(const void *ptr1, const void *ptr2);

int mylistsort(my_list_t list, cmpfn f1)
{

    qsort ( list , 100, sizeof (struct LINKED_LIST_S), (fn) );
   return -1;
}

int sort_fn_ascend(const void *ptr1, const void *ptr2)
{
    int a = (*(LINKED_LIST_S *)ptr1).item; //Compiler error
   int b = (*(LINKED_LIST_S *)ptr2).item; //Compiler error

  return b - a;

}

int sort_fn_descend(const void *ptr1, const void *ptr2)
{
   int a = ((struct LINKED_LIST_S *)ptr1)->item; //Compiler error
   int b = ((struct LINKED_LIST_S *)ptr2)->item; //Compiler error

  return a - b;

}

this is how the function mylistsort() is called at 2 places:

mylistsort(list, sort_fn_descend);//where list a properly initialized linked list pointer.

mylistsort(list, sort_fn_ascend);//where list a properly initialized linked list pointer.

1] Doesn't qsort() work on linked list if the head node poitner is passed as base array(first argument) to qsort.

2] How do I achieve the sorting of this linked list using qsort() in above code?

EDIT: Thanks for the answers. Now I have implemented a way to sort a list as mentioned by @muksie approach 1] he suggested, as code below. Still qsort() does not return a sorted array of ints.
First I want to sort an array of 100 elements, in descending order, but passed array is exact reverse, i.e. the elements are in ascending order of from 1,2,...100. What am I doing wrong? How can I fix it?

int linkedListSort(LINKED_LIST_T list, newCompareFunction fn, void *usr_info)
{
    LINKED_LIST_T tmpptr = list;
    int newitems[N_ITEMS];
    int i=0;

    //Logic to get all the items in the list in a array
    while(tmpptr != NULL)
    {
        newitems[i] = tmpptr->item;
        tmpptr = tmpptr->next;
        i++;
    }
    tmpptr = list;
    i = 0;
    //Sort that array
    //qsort ( list , 100, sizeof (struct LINKED_LIST_S), (fn) );
    qsort ( newitems , 100, sizeof(list->item), (fn) );

    //store the sorted items back into the list.
    while(tmpptr != NULL)
    {
        tmpptr->item = newitems[i];
        tmpptr = tmpptr->next;
        i++;
    }

   return -1;
}

int sort_fn_descend(void *ptr1,void *ptr2)
{
   int a = *((int*)(ptr1));
   int b = *((int*) (ptr2));

  return a - b;

}

int sort_fn_ascend(const void *ptr1, const void *ptr2)
{
    int a = *((int*)(ptr1));
   int b = *((int*) (ptr2));

  return b - a;

}


问:
Lenses, the State monad, and Maps with known keys
here is a puzzle that I keep on bumping into and that, I believe, no previous SO question has been addressing: How can I best use the lens library to set or get values within a State monad managing a nested data structure that involves Maps when I know for a fact that certain keys are present in the maps involved?

Here is the puzzle

{-# LANGUAGE TemplateHaskell, DerivingVia #-}

import Control.Monad.State
import Control.Monad.Except
import Control.Lens
import Data.Maybe
import Control.Monad
import Data.Map

type M = StateT World (ExceptT String Identity)

data World = World
  { _users      :: Map UserId User
  , _otherStuff :: Int
  }

type UserId = Int

data User = User
  { _balance     :: Balance
  , _moreStuff   :: Int
  }

newtype Balance = Balance Int
  deriving (Eq, Ord, Num) via Int

makeLenses 'World
makeLenses 'User

deleteUser :: UserId -> M ()
deleteUser uid = do
   user <- use $ users . at uid
   unless (isJust user) (throwError "unknown user")

   -- from here on we know the users exists.

   -- Question: how should the following lens look like?
   balance <- use $ users . ix uid . balance
   when (balance < 0) (throwError "you first have to settle your debt")
   when (balance > 0) (throwError "you first have to withdraw the remaining balance")

   users . at uid .= Nothing
```
<h1>Attempt 1: using <code>ix</code></h1>
<p>The snippet above is using <code>ix</code>.</p>
<pre class="lang-hs prettyprint-override"><code>   balance <- use $ users . ix uid . balance
</code>```

This yields a Traversal, so it may focus on multiple elements or none at all. In the context of use this means we need a Monoid and a Semigroup instance. In fact, this is what GHC has to say:

```<code>    • No instance for (Monoid Balance) arising from a use of ‘ix’
    • In the first argument of ‘(.)’, namely ‘ix uid’
      In the second argument of ‘(.)’, namely ‘ix uid . balance’
      In the second argument of ‘($)’, namely ‘users . ix uid . balance’
   |
45 |    balance <- use $ users . ix uid . balance
</code>```

There is no good way to implement <> for Balance. I could just implement addition, or use error, because, in fact, this function will never be called. But is this the cleanest way to do this?

Attempt 2: using at

Another option seems to be using at.

   balance <- use $ users . at uid . balance
```
<p>This yields a <code>Lens</code> that focuses on a <code>Maybe User</code>. This means, the follow-up lens <code>balance</code> has the wrong type.</p>
```    • Couldn't match type ‘User’
                     with ‘Maybe (IxValue (Map UserId User))’
      Expected type: (User -> Const Balance User)
                     -> Map UserId User -> Const Balance (Map UserId User)
        Actual type: (Maybe (IxValue (Map UserId User))
                      -> Const Balance (Maybe (IxValue (Map UserId User))))
                     -> Map UserId User -> Const Balance (Map UserId User)
    • In the first argument of ‘(.)’, namely ‘at uid’
      In the second argument of ‘(.)’, namely ‘at uid . balance’
      In the second argument of ‘($)’, namely ‘users . at uid . balance’
```
<h1>Attempt 3: working with <code>at</code>'s <code>Maybe</code></h1>
<p>Let's try to work with that <code>Maybe</code></p>
<pre class="lang-hs prettyprint-override"><code>   balance <- use $ users . at uid . _Just . balance
</code>```

This time, we have a Prism, which needs to deal with the situation when it has to work with Nothing. So we are back at requiring a Monoid.

```<code>    • No instance for (Monoid Balance) arising from a use of ‘_Just’
    • In the first argument of ‘(.)’, namely ‘_Just’
      In the second argument of ‘(.)’, namely ‘_Just . balance’
      In the second argument of ‘(.)’, namely ‘at uid . _Just . balance’
</code>```

Attempt 3b: working with at's Maybe

Let's try another way to work with that Maybe

   balance <- use $ users . at uid . non undefined . balance
```
<p>From the documentation:</p>
<blockquote>
<p>If v is an element of a type a, and a' is a sans the element v, then non v is an isomorphism from Maybe a' to a.</p>
</blockquote>
<p>We can use <code>undefined</code>, <code>error</code> or any "empty" <code>User</code> we want, it does not matter, since this case is never triggered, given the user id is present in the map.</p>
<p>For this to work we need <code>Eq</code> for <code>User</code>, which is fair enough. And it compiles and seems to work; that is, for reading. For writing, there is an, initially, unexpected twist:</p>
<pre class="lang-hs prettyprint-override"><code>topUp :: UserId -> Balance -> M ()
topUp uid b = do
   user <- use $ users . at uid
   unless (isJust user) (throwError "unknown user")

   users . at uid . non undefined . balance += b
</code>```

Running this blows up

```<code>experiment-exe: Prelude.undefined
CallStack (from HasCallStack):
  error, called at libraries/base/GHC/Err.hs:79:14 in base:GHC.Err
  undefined, called at app/Main.hs:55:25 in main:Main
</code>```

The explanation is that when writing, we use the optics "right-to-left", and in this direction non is injecting the User we provide as its parameter. Replacing undefined with a "empty" User obscures this mistake. It always replaces the existing user with the empty user, effectively loosing the user's initial balance when trying to top-up.

Conclusion

So, I have found options to make this work for reading, but none seems to be convincing. And I could not figure this out for writing.

What is your recommendation? How should that lens be constructed?

Edit: moved solution to self answer.

答:
The most direct facilities lens has for doing this are unsafe operations that treat a traversal that you "know" will target only one element as if it were a lens.  As you're probably aware, there's an operator for this that serves as a variation of ^. or ^?:

```<code>s <- get
let user = s ^?! users . at uid
</code>```

but for view (within a Reader) or use (within a State), there don't seem to be any built-in variations. You can write your own using the unsafeSingular function in Control.Lens.Traversal though:

```<code>use1 :: MonadState s m => Traversal' s a -> m a
use1 = use . unsafeSingular

view1 :: MonadReader s m => Traversal' s a -> m a
view1 = view . unsafeSingular
</code>```

after which:

```<code>balance <- use1 $ users . ix uid . balance
</code>```

should work.

If you would rather make the optic itself unsafe rather  using a safe optic unsafely, you can use unsafeSingular directly to modify the optic.  For example:

```<code>balance <- use $ users . unsafeSingular (ix uid) . balance
</code>```

Body:
here is a puzzle that I keep on bumping into and that, I believe, no previous SO question has been addressing: How can I best use the lens library to set or get values within a State monad managing a nested data structure that involves Maps when I know for a fact that certain keys are present in the maps involved?

Here is the puzzle

{-# LANGUAGE TemplateHaskell, DerivingVia #-}

import Control.Monad.State
import Control.Monad.Except
import Control.Lens
import Data.Maybe
import Control.Monad
import Data.Map

type M = StateT World (ExceptT String Identity)

data World = World
  { _users      :: Map UserId User
  , _otherStuff :: Int
  }

type UserId = Int

data User = User
  { _balance     :: Balance
  , _moreStuff   :: Int
  }

newtype Balance = Balance Int
  deriving (Eq, Ord, Num) via Int

makeLenses 'World
makeLenses 'User

deleteUser :: UserId -> M ()
deleteUser uid = do
   user <- use $ users . at uid
   unless (isJust user) (throwError "unknown user")

   -- from here on we know the users exists.

   -- Question: how should the following lens look like?
   balance <- use $ users . ix uid . balance
   when (balance < 0) (throwError "you first have to settle your debt")
   when (balance > 0) (throwError "you first have to withdraw the remaining balance")

   users . at uid .= Nothing

Attempt 1: using ix

The snippet above is using ix.

   balance <- use $ users . ix uid . balance

This yields a Traversal, so it may focus on multiple elements or none at all. In the context of use this means we need a Monoid and a Semigroup instance. In fact, this is what GHC has to say:

    • No instance for (Monoid Balance) arising from a use of ‘ix’
    • In the first argument of ‘(.)’, namely ‘ix uid’
      In the second argument of ‘(.)’, namely ‘ix uid . balance’
      In the second argument of ‘($)’, namely ‘users . ix uid . balance’
   |
45 |    balance <- use $ users . ix uid . balance

There is no good way to implement <> for Balance. I could just implement addition, or use error, because, in fact, this function will never be called. But is this the cleanest way to do this?

Attempt 2: using at

Another option seems to be using at.

   balance <- use $ users . at uid . balance

This yields a Lens that focuses on a Maybe User. This means, the follow-up lens balance has the wrong type.

    • Couldn't match type ‘User’
                     with ‘Maybe (IxValue (Map UserId User))’
      Expected type: (User -> Const Balance User)
                     -> Map UserId User -> Const Balance (Map UserId User)
        Actual type: (Maybe (IxValue (Map UserId User))
                      -> Const Balance (Maybe (IxValue (Map UserId User))))
                     -> Map UserId User -> Const Balance (Map UserId User)
    • In the first argument of ‘(.)’, namely ‘at uid’
      In the second argument of ‘(.)’, namely ‘at uid . balance’
      In the second argument of ‘($)’, namely ‘users . at uid . balance’

Attempt 3: working with at's Maybe

Let's try to work with that Maybe

   balance <- use $ users . at uid . _Just . balance

This time, we have a Prism, which needs to deal with the situation when it has to work with Nothing. So we are back at requiring a Monoid.

    • No instance for (Monoid Balance) arising from a use of ‘_Just’
    • In the first argument of ‘(.)’, namely ‘_Just’
      In the second argument of ‘(.)’, namely ‘_Just . balance’
      In the second argument of ‘(.)’, namely ‘at uid . _Just . balance’

Attempt 3b: working with at's Maybe

Let's try another way to work with that Maybe

   balance <- use $ users . at uid . non undefined . balance

From the documentation:

If v is an element of a type a, and a' is a sans the element v, then non v is an isomorphism from Maybe a' to a.

We can use undefined, error or any "empty" User we want, it does not matter, since this case is never triggered, given the user id is present in the map.

For this to work we need Eq for User, which is fair enough. And it compiles and seems to work; that is, for reading. For writing, there is an, initially, unexpected twist:

topUp :: UserId -> Balance -> M ()
topUp uid b = do
   user <- use $ users . at uid
   unless (isJust user) (throwError "unknown user")

   users . at uid . non undefined . balance += b

Running this blows up

experiment-exe: Prelude.undefined
CallStack (from HasCallStack):
  error, called at libraries/base/GHC/Err.hs:79:14 in base:GHC.Err
  undefined, called at app/Main.hs:55:25 in main:Main

The explanation is that when writing, we use the optics "right-to-left", and in this direction non is injecting the User we provide as its parameter. Replacing undefined with a "empty" User obscures this mistake. It always replaces the existing user with the empty user, effectively loosing the user's initial balance when trying to top-up.

Conclusion

So, I have found options to make this work for reading, but none seems to be convincing. And I could not figure this out for writing.

What is your recommendation? How should that lens be constructed?

Edit: moved solution to self answer.

Body:
The most direct facilities lens has for doing this are unsafe operations that treat a traversal that you "know" will target only one element as if it were a lens.  As you're probably aware, there's an operator for this that serves as a variation of ^. or ^?:

s <- get
let user = s ^?! users . at uid

but for view (within a Reader) or use (within a State), there don't seem to be any built-in variations. You can write your own using the unsafeSingular function in Control.Lens.Traversal though:

use1 :: MonadState s m => Traversal' s a -> m a
use1 = use . unsafeSingular

view1 :: MonadReader s m => Traversal' s a -> m a
view1 = view . unsafeSingular

after which:

balance <- use1 $ users . ix uid . balance

should work.

If you would rather make the optic itself unsafe rather  using a safe optic unsafely, you can use unsafeSingular directly to modify the optic.  For example:

balance <- use $ users . unsafeSingular (ix uid) . balance


问:
Javascript swap array elements
Is there any simpler way to swap two elements in an array?</p>

```<code>var a = list[x], b = list[y];
list[y] = a;
list[x] = b;
</code>```

答:
If you are not allowed to use in-place swap for some reason, here is a solution with map:

function swapElements(array, source, dest) {
  return source === dest
? array : array.map((item, index) => index === source
  ? array[dest] : index === dest
  ? array[source] : item);
}

const arr = ['a', 'b', 'c'];
const s1 = swapElements(arr, 0, 1);
console.log(s1[0] === 'b');
console.log(s1[1] === 'a');

const s2 = swapElements(arr, 2, 0);
console.log(s2[0] === 'c');
console.log(s2[2] === 'a');```
</div>
</div>
</p>
<p>Here is typescript code for quick copy-pasting:</p>
<pre class="lang-js prettyprint-override"><code>function swapElements(array: Array<any>, source: number, dest: number) {
  return source === dest
    ? array : array.map((item, index) => index === source
      ? array[dest] : index === dest
      ? array[source] : item);
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Javascript swap array elements

Body:
Is there any simpler way to swap two elements in an array?

var a = list[x], b = list[y];
list[y] = a;
list[x] = b;

Body:
If you are not allowed to use in-place swap for some reason, here is a solution with map:

function swapElements(array, source, dest) {
  return source === dest
? array : array.map((item, index) => index === source
  ? array[dest] : index === dest
  ? array[source] : item);
}

const arr = ['a', 'b', 'c'];
const s1 = swapElements(arr, 0, 1);
console.log(s1[0] === 'b');
console.log(s1[1] === 'a');

const s2 = swapElements(arr, 2, 0);
console.log(s2[0] === 'c');
console.log(s2[2] === 'a');

Here is typescript code for quick copy-pasting:

function swapElements(array: Array<any>, source: number, dest: number) {
  return source === dest
    ? array : array.map((item, index) => index === source
      ? array[dest] : index === dest
      ? array[source] : item);
}


问:
How to filter table by two columns
I have the following table:

ID
TEST_ID
Component
ComponentInfo

1
5
Test 1
Info

2
5
Test 1
AB 2

3
5
Test 1
XY

4
5
Test X
Info 2

5
5
Test X
Info 1

6
5
Test Y
Info 2

7
6
Test 1
Info 2

8
7
ABC
Info 1

9
8
XYZ
Info 2

9
9
XYZ
Info 2

I like to get the following output:

TEST_ID
Component

5
Test 1

5
Test X

5
Test Y

6
Test 1

7
ABC

8
XYZ

9
XYZ

I think it would be nice to realize it in the data transformation part. How can I do that?

答:
I don't see any filtering in your "question"; Rather, removing redundant columns and leaving unique values.

M language statement:

```<code>let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSUTIF4pDU4hIFEMczLy1fKVYnWskIXcbRScEILGOMLhMRCRY3QRaPgJoF1WOKVc4QLGeGLBeJqs8cyDVDdx9UzgLINQc7zBnVQEsg1wLsrihUHSAJSwyJWAA=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [ID = _t, TEST_ID = _t, Component = _t, ComponentInfo = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"ID", Int64.Type}, {"TEST_ID", Int64.Type}, {"Component", type text}, {"ComponentInfo", type text}}),
    #"Removed Columns" = Table.RemoveColumns(#"Changed Type",{"ID", "ComponentInfo"}),
    #"Removed Duplicates" = Table.Distinct(#"Removed Columns")
in
    #"Removed Duplicates"
</code>```

Title: How to filter table by two columns

Body:
I don't see any filtering in your "question"; Rather, removing redundant columns and leaving unique values.

M language statement:

let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSUTIF4pDU4hIFEMczLy1fKVYnWskIXcbRScEILGOMLhMRCRY3QRaPgJoF1WOKVc4QLGeGLBeJqs8cyDVDdx9UzgLINQc7zBnVQEsg1wLsrihUHSAJSwyJWAA=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [ID = _t, TEST_ID = _t, Component = _t, ComponentInfo = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"ID", Int64.Type}, {"TEST_ID", Int64.Type}, {"Component", type text}, {"ComponentInfo", type text}}),
    #"Removed Columns" = Table.RemoveColumns(#"Changed Type",{"ID", "ComponentInfo"}),
    #"Removed Duplicates" = Table.Distinct(#"Removed Columns")
in
    #"Removed Duplicates"


问:
Dynamic SQL in a Snowflake SQL Stored Procedure
I would like to run a select query in a Snowflake SQL Stored Procedures (not Javascript) using dynamic SQL.  Is this possible?

What I am looking to do is pass in a database name as a parameter.  I then want to select all schema names from INFORMATION_SCHEMA.SCHEMATA for that database.  I would like to use the input parameter value for the database name to fully qualify the table.  For example, DBNAME.INFORMATION_SCHEMA.SCHEMATA  where DBNAME is the name of my input parameter.

I would then like to loop through the results and for each schema do some code.

I find lots of Dynamic SQL examples for Javascript but I can't find one for a SQL stored procedure (language SQL) because it is so new.  Please let me know if this is possible and an example if possible.  Thanks!

答:
An example of commenting schemas in a specific database:

Preparing setup:

```<code>CREATE DATABASE TEST3;
CREATE SCHEMA TEST1;
CREATE SCHEMA TEST2;

SELECT CATALOG_NAME, SCHEMA_NAME, COMMENT
FROM TEST3.INFORMATION_SCHEMA.SCHEMATA;
</code>```

Procedure:

```<code>CREATE OR REPLACE PROCEDURE test_proc(DB_NAME STRING)
RETURNS STRING
LANGUAGE SQL
AS
$$
DECLARE
   TABLE_NAME   STRING;
   QUERY        STRING;
   OUTPUT       STRING DEFAULT '';
   c1           CURSOR FOR SELECT SCHEMA_NAME FROM TABLE(?)
                WHERE SCHEMA_NAME != 'INFORMATION_SCHEMA';
BEGIN
   TABLE_NAME := CONCAT(DB_NAME, '.INFORMATION_SCHEMA.SCHEMATA');
   OPEN c1 USING (TABLE_NAME);

   FOR rec IN c1 DO
       QUERY := 'COMMENT ON SCHEMA ' || DB_NAME || '.' || rec.SCHEMA_NAME
                 || ' IS ''test_comment'';';
       OUTPUT := OUTPUT || QUERY;
       EXECUTE IMMEDIATE :QUERY;
   END FOR;

   RETURN :OUTPUT;
END;
$$;
</code>```

Call:

```<code>CALL test_proc('TEST3');
</code>```

Output:

Body:
An example of commenting schemas in a specific database:

Preparing setup:

CREATE DATABASE TEST3;
CREATE SCHEMA TEST1;
CREATE SCHEMA TEST2;

SELECT CATALOG_NAME, SCHEMA_NAME, COMMENT
FROM TEST3.INFORMATION_SCHEMA.SCHEMATA;

Procedure:

CREATE OR REPLACE PROCEDURE test_proc(DB_NAME STRING)
RETURNS STRING
LANGUAGE SQL
AS
$$
DECLARE
   TABLE_NAME   STRING;
   QUERY        STRING;
   OUTPUT       STRING DEFAULT '';
   c1           CURSOR FOR SELECT SCHEMA_NAME FROM TABLE(?)
                WHERE SCHEMA_NAME != 'INFORMATION_SCHEMA';
BEGIN
   TABLE_NAME := CONCAT(DB_NAME, '.INFORMATION_SCHEMA.SCHEMATA');
   OPEN c1 USING (TABLE_NAME);

   FOR rec IN c1 DO
       QUERY := 'COMMENT ON SCHEMA ' || DB_NAME || '.' || rec.SCHEMA_NAME
                 || ' IS ''test_comment'';';
       OUTPUT := OUTPUT || QUERY;
       EXECUTE IMMEDIATE :QUERY;
   END FOR;

   RETURN :OUTPUT;
END;
$$;

Call:

CALL test_proc('TEST3');

Output:


问:
Redirect http to https AWS Application Load Balancer
Hey everyone so I configured my ELB to use an SSL certificate and it works great, however, I still have a problem where if a user comes to my website on port 80 under HTTP the website does not redirect them to an HTTPS secure connection. Heres a screenshot of my ELB configuration as seen in the Elastic Beanstalk configuration tab. Any help is appreciated thank you.
<img src="https://i.stack.imgur.com/Us9BP.png" alt="elb config"> </p>

答:
In fact, you cannot do it anynmore from the interface of elastic beanstalk
Don't do it from the app, bad solution for load.
You must now  go to the EC2 load balancer and change the listener for port 80 as described here : https://medium.com/@j_cunanan05/how-to-redirect-http-to-https-in-amazon-web-services-aws-elastic-beanstalk-67f309734e81</p>


问:
Stubbing a module, its methods, and inner classes with RSpec
I have a module like this that I'm trying to write unit tests for

module MyThing
  module Helpers
    def self.generate_archive
      # ...
      ::Configuration.export(arg)
    rescue ::Configuration::Error => error
      raise error
    end
  end
end
```
<p>The <code>::Configuration</code> module can't exist in my unit testing environment for reasons that are beyond my control, so I need to stub it out.  Here's what I've come up with so far.</p>
<pre class="lang-rb prettyprint-override"><code>RSpec.describe 'MyThing' do
  it 'generates an archive' do
    configuration_stub = stub_const("::Configuration", Module.new)
    configuration_error_stub = stub_const("::Configuration::Error", Class.new)

    expect_any_instance_of(configuration_stub).to receive(:export).with("arg")
    MyThing::Helpers.generate_archive
  end
end
</code>```

This gets me an error.

```<code>NoMethodError:
  Undefined method `export' for Configuration:Module
</code>```

If I put the configuration_stub definition inline with the expect_any_instance_of like this

RSpec.describe 'MyThing' do
  it 'generates an archive' do
    configuration_error_stub = stub_const("::Configuration::Error", Class.new)

    expect_any_instance_of(stub_const("::Configuration", Module.new)).to receive(:export).with("arg")
    MyThing::Helpers.generate_archive
  end
end
```
<p>I also get an error.</p>
```NameError:
  Uninitialized constant Configuration::Error
...
# --- Caused by: ---
# NoMethodError:
#   Undefined method `export' for Configuration:Module
```

答:
expect_any_instance_of works on instance methods. export is being called as a class method.

Instead, use a normal expect on the class.

```<code>expect(Configuration).to receive(:export).with("arg")
</code>```

Note: it is not necessary to write ::Configuration in the tests. The :: is to clarify between MyThing::Helpers::Configuration and Configuration.

Note: if you're calling methods directly on Configuration it should probably be a Class not a Module.

Note: instead of calling methods on a class, consider using a Configuration object. App.config.export where App.config returns the default Configuration object. This is more flexible.

The problem with that is RSpec will verify that Configuration.export exists. It doesn't. You could turn off verification, or you could make a real class to test with.

```<code>  before {
    stub_const(
      "Configuration",
      Class.new do
        def self.export(*args)
        end
      end
    )
  }

  it 'exports' do
    expect(Configuration).to receive(:export).with("arg")
    Configuration.export("arg")
  end
</code>```

You could write a stub Configuration module for testing only and put it into spec/support, but your tests are increasingly divorced from reality.

The real problem is your project should have a real Configuration class!

I'm going to guess the real Configuration contains production information which cannot be checked into the repository. This is a common anti-pattern. The Configuration module should hide the details of where the configuration values are coming from. There should be independent development, test, and production configurations. There are many ways of doing this, the most common are to use environment specific config files, or to store environment specific config values in environment variables.

While you could mock the Configuration::Error exception, there should be no reason Configuration::Error cannot exist in your test environment. Add it and simulate an error like so:

```<code>  context 'when Configuration.export raises an error'
    before {
      allow(Configuration).to receive(:export).and_raise(Configuration::Error)
    }

    it 'does whatever its supposed to do' do
    end
  end
</code>```

Body:
I have a module like this that I'm trying to write unit tests for

module MyThing
  module Helpers
    def self.generate_archive
      # ...
      ::Configuration.export(arg)
    rescue ::Configuration::Error => error
      raise error
    end
  end
end

The ::Configuration module can't exist in my unit testing environment for reasons that are beyond my control, so I need to stub it out.  Here's what I've come up with so far.

RSpec.describe 'MyThing' do
  it 'generates an archive' do
    configuration_stub = stub_const("::Configuration", Module.new)
    configuration_error_stub = stub_const("::Configuration::Error", Class.new)

    expect_any_instance_of(configuration_stub).to receive(:export).with("arg")
    MyThing::Helpers.generate_archive
  end
end

This gets me an error.

NoMethodError:
  Undefined method `export' for Configuration:Module

If I put the configuration_stub definition inline with the expect_any_instance_of like this

RSpec.describe 'MyThing' do
  it 'generates an archive' do
    configuration_error_stub = stub_const("::Configuration::Error", Class.new)

    expect_any_instance_of(stub_const("::Configuration", Module.new)).to receive(:export).with("arg")
    MyThing::Helpers.generate_archive
  end
end

I also get an error.

NameError:
  Uninitialized constant Configuration::Error
...
# --- Caused by: ---
# NoMethodError:
#   Undefined method `export' for Configuration:Module

Body:
expect_any_instance_of works on instance methods. export is being called as a class method.

Instead, use a normal expect on the class.

expect(Configuration).to receive(:export).with("arg")

Note: it is not necessary to write ::Configuration in the tests. The :: is to clarify between MyThing::Helpers::Configuration and Configuration.

Note: if you're calling methods directly on Configuration it should probably be a Class not a Module.

Note: instead of calling methods on a class, consider using a Configuration object. App.config.export where App.config returns the default Configuration object. This is more flexible.

The problem with that is RSpec will verify that Configuration.export exists. It doesn't. You could turn off verification, or you could make a real class to test with.

  before {
    stub_const(
      "Configuration",
      Class.new do
        def self.export(*args)
        end
      end
    )
  }

  it 'exports' do
    expect(Configuration).to receive(:export).with("arg")
    Configuration.export("arg")
  end

You could write a stub Configuration module for testing only and put it into spec/support, but your tests are increasingly divorced from reality.

The real problem is your project should have a real Configuration class!

I'm going to guess the real Configuration contains production information which cannot be checked into the repository. This is a common anti-pattern. The Configuration module should hide the details of where the configuration values are coming from. There should be independent development, test, and production configurations. There are many ways of doing this, the most common are to use environment specific config files, or to store environment specific config values in environment variables.

While you could mock the Configuration::Error exception, there should be no reason Configuration::Error cannot exist in your test environment. Add it and simulate an error like so:

  context 'when Configuration.export raises an error'
    before {
      allow(Configuration).to receive(:export).and_raise(Configuration::Error)
    }

    it 'does whatever its supposed to do' do
    end
  end


问:
Syntax coloring within diffs?
In emacs, when I diff code I lose the syntax highlighting. With my theme anyway all text is light gray. Added lines do have a green background, and removed lines do have a red background, etc. But the code keywords, etc are not colored like they are when I'm using that language's mode. Is there a way to turn on ruby syntax highlighting in diffs?

As an example of a tool that does this - if you look at diffs on github the code syntax highlighting is there, as well as highlighting for added/removed lines.

答: Syntax coloring in diffs is enabled by default in Emacs 27.</p>

Title: Syntax coloring within diffs?


问:
Finding Minimum For every group in ArrayList in Java
I have a class as below.

```<code>public class Employee{
int EmployeeDepartmentId;
int EmplyoyeeId;
int Salary;
}
</code>```

I an creating an ArrayList as Below.

```<code>ArrayList<Employee> arrEmployee = new ArrayList<Employee>;
</code>```

Now, I want to find out List of employees from every department with minimum salary.

How can this be achieved. I tried using Collections.Min(), but that will give me the minimum salary from whole list. I want it to be grouped by department.

Any suggestions?

答:
Do two runs. The first to group the employees by department, perhaps using a map:

```<code>Map<Integer,List<Employee>>
</code>```

Then loop over this map grabbing the minimum of each list.

Body:
I have a class as below.

public class Employee{
int EmployeeDepartmentId;
int EmplyoyeeId;
int Salary;
}

I an creating an ArrayList as Below.

ArrayList<Employee> arrEmployee = new ArrayList<Employee>;

Now, I want to find out List of employees from every department with minimum salary.

How can this be achieved. I tried using Collections.Min(), but that will give me the minimum salary from whole list. I want it to be grouped by department.

Any suggestions?

Body:
Do two runs. The first to group the employees by department, perhaps using a map:

Map<Integer,List<Employee>>

Then loop over this map grabbing the minimum of each list.


问:
How we can get response from google Calendar api
I am receiving calendar events on my server by calling the Google Calendar API,
while an event is changed or added to the calendar again I need to call Google calender api.
But I want that we don't need to call calendar api every time. If there is a change, I get a response from Google on my server
is there any solution for this?</p>

答:
You can request push notifications, you need to set up a notification channel for each resource you want to watch.

To use push notifications, you need to do two things:

Set up your receiving URL, or "Webhook" callback receiver.

Set up a notification channel for each resource endpoint you want to watch.

For more information you can refer here: https://developers.google.com/calendar/api/guides/push