问:
MERN Stack App with NGINX: Timeout when react app tries to connect to server side API
I have a MERN stack app that I am trying to put into production.

I am able to get the client side running using NGINX as a reverse proxy to port 3000.

The issue I am having is when I am trying to get a response from my server running on port 5000. This is where I have my API to query against my database.

I believe the issue lies in my server block I have set up for my site. Below is an example for my signin endpoint that I am getting a TIMEOUT from. I have replaced my URL with example.com

```<code>server {

        root /var/www/example.com/html;
        index index.html index.htm index.nginx-debian.html;

        server_name example.com www.example.com;

        location / {
                proxy_pass http://localhost:3000;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }

        location /users/signin {
                proxy_pass http://localhost:5000/;
                proxy_buffering on;
        }

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = www.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

        listen 80;
        listen [::]:80;

        server_name example.com www.example.com;
    return 404; # managed by Certbot

}
</code>```

Any help would be appreciated. I believe I just need help trying to expose these endpoints properly.

Thanks!

Body:
I have a MERN stack app that I am trying to put into production.

I am able to get the client side running using NGINX as a reverse proxy to port 3000.

The issue I am having is when I am trying to get a response from my server running on port 5000. This is where I have my API to query against my database.

I believe the issue lies in my server block I have set up for my site. Below is an example for my signin endpoint that I am getting a TIMEOUT from. I have replaced my URL with example.com

server {

        root /var/www/example.com/html;
        index index.html index.htm index.nginx-debian.html;

        server_name example.com www.example.com;

        location / {
                proxy_pass http://localhost:3000;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }

        location /users/signin {
                proxy_pass http://localhost:5000/;
                proxy_buffering on;
        }

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = www.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

        listen 80;
        listen [::]:80;

        server_name example.com www.example.com;
    return 404; # managed by Certbot

}

Any help would be appreciated. I believe I just need help trying to expose these endpoints properly.

Thanks!


来源: stackexchange

问:
Can't save generated images in folders relevant to they width with Imagemin Webpack plugin
I am trying to use Webpack Imagemin plugin to generate images to different sizes and formats. Something like this:

<picture>
  <source
    media="(min-width: 576px)"
    srcset="./src/img/slide.jpg?width=540"
    type="image/jpg"
  />
  <source
    media="(min-width: 960px)"
    srcset="./src/img/slide.jpg?width=900"
    type="image/jpg"
  />
  <source
    media="(min-width: 576px)"
    srcset="./src/img/slide.jpg?as=webp&width=540"
    type="image/webp"
  />
  <source
    media="(min-width: 960px)"
    srcset="./src/img/slide.jpg?as=webp&width=900"
    type="image/webp"
  />

</picture>
```
<p>I want that images would saved in folders relevant to they width. E.g:</p>
<p><img src="https://i.imgur.com/llwr9tp.png" alt="" /></p>
<p>I try to use filename option in plugin settings</p>
<pre class="lang-js prettyprint-override"><code>const path = require("path");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");

module.exports = {
  entry: {
    index: "./src/index.ts",
  },
  mode: "development",
  output: {
    filename: "js/[name].js",
    path: path.resolve(__dirname, "dist"),
    clean: true,
    pathinfo: true,
  },
  module: {
    rules: [
      {
        test: /\.html$/i,
        use: "html-loader",
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        type: "asset/resource",
        parser: {
          dataUrlCondition: {
            maxSize: 10 * 1024, // 10kb
          },
        },
        // If i don't use this generator option, images saved in root (dist) folder -> dist/6gj86ddgt36jjy78.jpg
        generator: {
          filename: "example/[name]-[hash][ext]",
        },
      },
    ],
  },

  optimization: {
    minimize: true,
    minimizer: [
      new ImageMinimizerPlugin({
        minimizer: {
          // Using this option (with filename: in loader above) saves as -> dist/example/generated-slide-540-6gj86ddgt36jjy78.webp
          // --- images/[width] is ignored and folder name comes from loader options
          filename: "images/[width]/generated-[name]-[width][ext]",
          implementation: ImageMinimizerPlugin.sharpMinify,

          options: {
            encodeOptions: {
              // ....
            },
          },
        },
        generator: [
          {
            // Adding this option not worked too..
            // ---
            // filename: "images/[width]/generated-[name]-[width][ext]",
            preset: "webp",
            implementation: ImageMinimizerPlugin.sharpGenerate,
            options: {
              encodeOptions: {
                webp: {
                  // ....
                },
              },
            },
          },
        ],
      }),
    ],
  },
};
</code>```

What i am doing wrong?

P.S. I don't wont to use Imagemin plugin as Standalone loader because plugin docs

Loader optimizes or generates images using options, so inlined images via data URI (i.e. data:) will be optimized or generated too, not inlined images will be optimized too.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to use Webpack Imagemin plugin to generate images to different sizes and formats. Something like this:

<picture>
  <source
    media="(min-width: 576px)"
    srcset="./src/img/slide.jpg?width=540"
    type="image/jpg"
  />
  <source
    media="(min-width: 960px)"
    srcset="./src/img/slide.jpg?width=900"
    type="image/jpg"
  />
  <source
    media="(min-width: 576px)"
    srcset="./src/img/slide.jpg?as=webp&width=540"
    type="image/webp"
  />
  <source
    media="(min-width: 960px)"
    srcset="./src/img/slide.jpg?as=webp&width=900"
    type="image/webp"
  />

</picture>

I want that images would saved in folders relevant to they width. E.g:

I try to use filename option in plugin settings

const path = require("path");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");

module.exports = {
  entry: {
    index: "./src/index.ts",
  },
  mode: "development",
  output: {
    filename: "js/[name].js",
    path: path.resolve(__dirname, "dist"),
    clean: true,
    pathinfo: true,
  },
  module: {
    rules: [
      {
        test: /\.html$/i,
        use: "html-loader",
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        type: "asset/resource",
        parser: {
          dataUrlCondition: {
            maxSize: 10 * 1024, // 10kb
          },
        },
        // If i don't use this generator option, images saved in root (dist) folder -> dist/6gj86ddgt36jjy78.jpg
        generator: {
          filename: "example/[name]-[hash][ext]",
        },
      },
    ],
  },

  optimization: {
    minimize: true,
    minimizer: [
      new ImageMinimizerPlugin({
        minimizer: {
          // Using this option (with filename: in loader above) saves as -> dist/example/generated-slide-540-6gj86ddgt36jjy78.webp
          // --- images/[width] is ignored and folder name comes from loader options
          filename: "images/[width]/generated-[name]-[width][ext]",
          implementation: ImageMinimizerPlugin.sharpMinify,

          options: {
            encodeOptions: {
              // ....
            },
          },
        },
        generator: [
          {
            // Adding this option not worked too..
            // ---
            // filename: "images/[width]/generated-[name]-[width][ext]",
            preset: "webp",
            implementation: ImageMinimizerPlugin.sharpGenerate,
            options: {
              encodeOptions: {
                webp: {
                  // ....
                },
              },
            },
          },
        ],
      }),
    ],
  },
};

What i am doing wrong?

P.S. I don't wont to use Imagemin plugin as Standalone loader because plugin docs

Loader optimizes or generates images using options, so inlined images via data URI (i.e. data:) will be optimized or generated too, not inlined images will be optimized too.


问:
How to get count in same results including zero count values? (PostgreSQL)
Here is my problem...I have this query already giving me the results I am looking for except that I need to display rows that have zero values... in the column "station" I should be displaying numbers 4 and 7 too with zero values:

```<code>select
  sum("Ch1") AS "Ch1",
  sum("Ch2") AS "Ch2",
  sum("Ch3") AS "Ch3",
  sum("Ch4") AS "Ch4",
  CASE WHEN "FailCode" >= 10 and "FailCode" <= 13 THEN 1
       WHEN "FailCode" >= 14 and "FailCode" <= 17 THEN 2
       WHEN "FailCode" >= 18 and "FailCode" <= 21 THEN 3
       WHEN "FailCode" >= 23 and "FailCode" <= 26 THEN 4
       WHEN "FailCode" >= 27 and "FailCode" <= 30 THEN 5
       WHEN "FailCode" >= 35 and "FailCode" <= 38 THEN 6
       WHEN "FailCode" >= 40 and "FailCode" <= 43 THEN 7
   END AS station
from (
SELECT "FailCode",
count (*) FILTER (WHERE "FailCode" =10 or "FailCode"=14 or "FailCode"=18 or "FailCode"=23 or "FailCode"=27 or "FailCode"=35 or "FailCode"=40) as "Ch1",
count (*) FILTER (WHERE "FailCode" =11 or "FailCode"=15 or "FailCode"=19 or "FailCode"=24 or "FailCode"=28 or "FailCode"=36 or "FailCode"=41) as "Ch2",
count (*) FILTER (WHERE "FailCode" =12 or "FailCode"=16 or "FailCode"=20 or "FailCode"=25 or "FailCode"=29 or "FailCode"=37 or "FailCode"=42) as "Ch3",
count (*) FILTER (WHERE "FailCode" =13 or "FailCode"=17 or "FailCode"=21 or "FailCode"=26 or "FailCode"=30 or "FailCode"=38 or "FailCode"=43) as "Ch4"
FROM minical01
where ("FailCode" between 10 and 43) and not ("FailCode" between 31 and 34)
group by 1
) t
where t is not null
group by 5
order by 5
</code>```

This is what I am getting:

Ch1
Ch2
Ch3
Ch4
Station

61
487
117
57
1

6
13
5
7
2

0
29
17
21
3

283
807
113
510
5

2
0
0
0
6

This is what I am trying to get:

Ch1
Ch2
Ch3
Ch4
Station

61
487
117
57
1

6
13
5
7
2

0
29
17
21
3

0
0
0
0
4

283
807
113
510
5

2
0
0
0
6

0
0
0
0
7

The following is what I tried so far, but it's not changing my results. I still don't get any change:

```<code>select
  sum("Ch1") AS "Ch1",
  sum("Ch2") AS "Ch2",
  sum("Ch3") AS "Ch3",
  sum("Ch4") AS "Ch4",
  CASE WHEN "FailCode" >= 10 and "FailCode" <= 13 THEN 1
       WHEN "FailCode" >= 14 and "FailCode" <= 17 THEN 2
       WHEN "FailCode" >= 18 and "FailCode" <= 21 THEN 3
       WHEN "FailCode" >= 23 and "FailCode" <= 26 THEN 4
       WHEN "FailCode" >= 27 and "FailCode" <= 30 THEN 5
       WHEN "FailCode" >= 35 and "FailCode" <= 38 THEN 6
       WHEN "FailCode" >= 40 and "FailCode" <= 43 THEN 7
   END AS station
from (
SELECT "FailCode",
count (*) FILTER (WHERE "FailCode" =10 or "FailCode"=14 or "FailCode"=18 or "FailCode"=23 or "FailCode"=27 or "FailCode"=35 or "FailCode"=40) as "Ch1",
count (*) FILTER (WHERE "FailCode" =11 or "FailCode"=15 or "FailCode"=19 or "FailCode"=24 or "FailCode"=28 or "FailCode"=36 or "FailCode"=41) as "Ch2",
count (*) FILTER (WHERE "FailCode" =12 or "FailCode"=16 or "FailCode"=20 or "FailCode"=25 or "FailCode"=29 or "FailCode"=37 or "FailCode"=42) as "Ch3",
count (*) FILTER (WHERE "FailCode" =13 or "FailCode"=17 or "FailCode"=21 or "FailCode"=26 or "FailCode"=30 or "FailCode"=38 or "FailCode"=43) as "Ch4"
FROM minical01
where ("FailCode" between 10 and 43) and not ("FailCode" between 31 and 34)
group by 1
) t
LEFT JOIN generate_series(1, 7, 1) AS g(id)
ON g.id = t."FailCode"
where t is not null
group by 5
order by 5
</code>```

Body:
Here is my problem...I have this query already giving me the results I am looking for except that I need to display rows that have zero values... in the column "station" I should be displaying numbers 4 and 7 too with zero values:

select
  sum("Ch1") AS "Ch1",
  sum("Ch2") AS "Ch2",
  sum("Ch3") AS "Ch3",
  sum("Ch4") AS "Ch4",
  CASE WHEN "FailCode" >= 10 and "FailCode" <= 13 THEN 1
       WHEN "FailCode" >= 14 and "FailCode" <= 17 THEN 2
       WHEN "FailCode" >= 18 and "FailCode" <= 21 THEN 3
       WHEN "FailCode" >= 23 and "FailCode" <= 26 THEN 4
       WHEN "FailCode" >= 27 and "FailCode" <= 30 THEN 5
       WHEN "FailCode" >= 35 and "FailCode" <= 38 THEN 6
       WHEN "FailCode" >= 40 and "FailCode" <= 43 THEN 7
   END AS station
from (
SELECT "FailCode",
count (*) FILTER (WHERE "FailCode" =10 or "FailCode"=14 or "FailCode"=18 or "FailCode"=23 or "FailCode"=27 or "FailCode"=35 or "FailCode"=40) as "Ch1",
count (*) FILTER (WHERE "FailCode" =11 or "FailCode"=15 or "FailCode"=19 or "FailCode"=24 or "FailCode"=28 or "FailCode"=36 or "FailCode"=41) as "Ch2",
count (*) FILTER (WHERE "FailCode" =12 or "FailCode"=16 or "FailCode"=20 or "FailCode"=25 or "FailCode"=29 or "FailCode"=37 or "FailCode"=42) as "Ch3",
count (*) FILTER (WHERE "FailCode" =13 or "FailCode"=17 or "FailCode"=21 or "FailCode"=26 or "FailCode"=30 or "FailCode"=38 or "FailCode"=43) as "Ch4"
FROM minical01
where ("FailCode" between 10 and 43) and not ("FailCode" between 31 and 34)
group by 1
) t
where t is not null
group by 5
order by 5

This is what I am getting:

Ch1
Ch2
Ch3
Ch4
Station

61
487
117
57
1

6
13
5
7
2

0
29
17
21
3

283
807
113
510
5

2
0
0
0
6

This is what I am trying to get:

Ch1
Ch2
Ch3
Ch4
Station

61
487
117
57
1

6
13
5
7
2

0
29
17
21
3

0
0
0
0
4

283
807
113
510
5

2
0
0
0
6

0
0
0
0
7

The following is what I tried so far, but it's not changing my results. I still don't get any change:

select
  sum("Ch1") AS "Ch1",
  sum("Ch2") AS "Ch2",
  sum("Ch3") AS "Ch3",
  sum("Ch4") AS "Ch4",
  CASE WHEN "FailCode" >= 10 and "FailCode" <= 13 THEN 1
       WHEN "FailCode" >= 14 and "FailCode" <= 17 THEN 2
       WHEN "FailCode" >= 18 and "FailCode" <= 21 THEN 3
       WHEN "FailCode" >= 23 and "FailCode" <= 26 THEN 4
       WHEN "FailCode" >= 27 and "FailCode" <= 30 THEN 5
       WHEN "FailCode" >= 35 and "FailCode" <= 38 THEN 6
       WHEN "FailCode" >= 40 and "FailCode" <= 43 THEN 7
   END AS station
from (
SELECT "FailCode",
count (*) FILTER (WHERE "FailCode" =10 or "FailCode"=14 or "FailCode"=18 or "FailCode"=23 or "FailCode"=27 or "FailCode"=35 or "FailCode"=40) as "Ch1",
count (*) FILTER (WHERE "FailCode" =11 or "FailCode"=15 or "FailCode"=19 or "FailCode"=24 or "FailCode"=28 or "FailCode"=36 or "FailCode"=41) as "Ch2",
count (*) FILTER (WHERE "FailCode" =12 or "FailCode"=16 or "FailCode"=20 or "FailCode"=25 or "FailCode"=29 or "FailCode"=37 or "FailCode"=42) as "Ch3",
count (*) FILTER (WHERE "FailCode" =13 or "FailCode"=17 or "FailCode"=21 or "FailCode"=26 or "FailCode"=30 or "FailCode"=38 or "FailCode"=43) as "Ch4"
FROM minical01
where ("FailCode" between 10 and 43) and not ("FailCode" between 31 and 34)
group by 1
) t
LEFT JOIN generate_series(1, 7, 1) AS g(id)
ON g.id = t."FailCode"
where t is not null
group by 5
order by 5


问:
Training Dataset preparation for predicting customer Churn at a specific Month
I have dataset of customers from 2019-2022 . My goal is to predict customer Churn at a specific point in time , say exactly 3 months from the observation point using Logistic Regression.

So if I look at my customer base at Jan-2022(Say Month0) , i can tag churners as Customers who churned exactly at month3(April) and non churners as Customers who stayed Active at Month3(April).

The issue that I was thinking of was there could be a group of customers that churned at Month-1 or Month2 .

I  wouldn't be able to include them in the  training dataset because technically they did not churn at Month-3 but before(Feb or March) . Is excluding these customers the right approach to model this problem?

There are enough articles on modelling churn within a specific window(say within 3 months) using logistic Regression , but since I would be modelling churn at a specific point in time(Exactly at 3 months) , any guidance on the query is helpful. Thanks


问:
Temporarily prevent SwiftUI redraws
Is there any way to temporarily override SwiftUI's internal logic for when to redraw views?

Specifically, I have a rather complex view with a ForEach { ... } component. Everything works fine, but when the device is rotated, SwiftUI sees fit to re-render this entire view and all of its subviews 6 times throughout the animation of rotating to portrait/landscape mode, which causes the animation to hang.

None of the state variables actually change during that time, though the view is inside of a GeometryReader so geography will obviously update. Using an EquatableView won't help, because none of the state variables change.

I'm looking for a way to prevent all the redraws from happening, except for once after the device rotation is completed.

Title: Temporarily prevent SwiftUI redraws


问:
Query to find id missing from an item that otherwise uses at least one id from the same group
I am trying to come up with a query that shows me which "feeds" make only partial use of a "rule group" by returning a list of rules that are "missing" from a given feed that otherwise uses at least one rule from that group. Here is a simplified example:

Table A has a list of unique rule ids and the rule groups they belong to.

rulegroup
rule_id

450
3001

450
3002

450
3003

450
3011

573
7302

573
7303

573
7309

882
8145

882
8146

882
8148

882
8150

882
8151

Table B shows which rule ids are used by which feeds.
Some of the rule_id belong to a group above, and others don't.

feed
rule_id

A
1112

A
7302

A
7303

A
7309

A
4500

A
7992

B
7309

B
8146

B
8148

B
8150

B
7992

C
1112

C
4500

C
9930

D
3002

D
1800

D
2704

D
9055

What I want to find is only feeds that use at least one rule but not all the rules from any given group, along with the group id and the id of the rule that is missing from that feed. For this example, the results table should be:

feed
rulegroup
rule_id

B
882
8145

B
882
8151

D
450
3001

D
450
3003

D
450
3011

i.e.

Feed A gets no results because it has ALL the rules from group 573.

Feed B has 3 rules from group 882 but is missing 2 others from that group, so those 2 should appear in the results.

Feed C has no rules from any group, so it gets no results.

Feed D has one rule from group 450 but is missing 3 others from that group, so those 3 should appear in the results.

I have been fiddling with something like this:

```<code>SELECT B.feed, A.rulegroup, A.rule_id
FROM TableA AS A
JOIN TableB AS B ON A.rule_id = B.rule_id
GROUP BY B.feed, A.rulegroup
HAVING COUNT(B.rule_id) < (SELECT COUNT(*) FROM TableA WHERE rulegroup = A.rulegroup) AS total
LEFT JOIN TableA AS C ON A.rulegroup = C.rulegroup AND A.rule_id = C.rule_id
</code>```

I either get no results or I get "Every derived table must have its own alias". In real life, however, Tables A and B are each produced by queries with about 8 joins each, so it's complicating my thinking about this and it's possible that I've just made mistakes. Perhaps if I can confirm what works for the simpler example above, I'll be able to translate that to my more complex work use case. Can someone give me a query that would work for the above? Bonus points if you can accomplish this without using a correlated subquery.

Edited to add: I pasted an earlier attempted code above that mistakenly has a join after the HAVING clause, but I have also tried this arrangement:

```<code>FROM TableA AS A
JOIN TableB AS B ON A.rule_id = B.rule_id
LEFT JOIN TableA AS C ON A.rulegroup = C.rulegroup AND A.rule_id = C.rule_id
GROUP BY B.feed, A.rulegroup
HAVING COUNT(B.rule_id) < (SELECT COUNT(*) FROM TableA WHERE rulegroup = A.rulegroup)
</code>```

Body:
I am trying to come up with a query that shows me which "feeds" make only partial use of a "rule group" by returning a list of rules that are "missing" from a given feed that otherwise uses at least one rule from that group. Here is a simplified example:

Table A has a list of unique rule ids and the rule groups they belong to.

rulegroup
rule_id

450
3001

450
3002

450
3003

450
3011

573
7302

573
7303

573
7309

882
8145

882
8146

882
8148

882
8150

882
8151

Table B shows which rule ids are used by which feeds.
Some of the rule_id belong to a group above, and others don't.

feed
rule_id

A
1112

A
7302

A
7303

A
7309

A
4500

A
7992

B
7309

B
8146

B
8148

B
8150

B
7992

C
1112

C
4500

C
9930

D
3002

D
1800

D
2704

D
9055

What I want to find is only feeds that use at least one rule but not all the rules from any given group, along with the group id and the id of the rule that is missing from that feed. For this example, the results table should be:

feed
rulegroup
rule_id

B
882
8145

B
882
8151

D
450
3001

D
450
3003

D
450
3011

i.e.

Feed A gets no results because it has ALL the rules from group 573.

Feed B has 3 rules from group 882 but is missing 2 others from that group, so those 2 should appear in the results.

Feed C has no rules from any group, so it gets no results.

Feed D has one rule from group 450 but is missing 3 others from that group, so those 3 should appear in the results.

I have been fiddling with something like this:

SELECT B.feed, A.rulegroup, A.rule_id
FROM TableA AS A
JOIN TableB AS B ON A.rule_id = B.rule_id
GROUP BY B.feed, A.rulegroup
HAVING COUNT(B.rule_id) < (SELECT COUNT(*) FROM TableA WHERE rulegroup = A.rulegroup) AS total
LEFT JOIN TableA AS C ON A.rulegroup = C.rulegroup AND A.rule_id = C.rule_id

I either get no results or I get "Every derived table must have its own alias". In real life, however, Tables A and B are each produced by queries with about 8 joins each, so it's complicating my thinking about this and it's possible that I've just made mistakes. Perhaps if I can confirm what works for the simpler example above, I'll be able to translate that to my more complex work use case. Can someone give me a query that would work for the above? Bonus points if you can accomplish this without using a correlated subquery.

Edited to add: I pasted an earlier attempted code above that mistakenly has a join after the HAVING clause, but I have also tried this arrangement:

FROM TableA AS A
JOIN TableB AS B ON A.rule_id = B.rule_id
LEFT JOIN TableA AS C ON A.rulegroup = C.rulegroup AND A.rule_id = C.rule_id
GROUP BY B.feed, A.rulegroup
HAVING COUNT(B.rule_id) < (SELECT COUNT(*) FROM TableA WHERE rulegroup = A.rulegroup)


问:
Microsoft Graph issue - Filtering output
I'm exporting both custom and standard attributes of all users in Azure AD. I'm having difficulty wrapping my head around customizing the output when exporting.

For example, I'm seeking to export all users that are members, not Guests, with the below attributes:

```<code>$URI = "https://graph.microsoft.com/beta/users?`$select=displayName,userPrincipalName, mail, department, jobTitle, extension_1fe7973b28e74213b897d62528e614c7_extensionAttribute14, extension_1fe7973b28e74213b897d62528e614c7_extensionAttribute15, accountEnabled, signInActivity, UserType, id&`$expand=manager(`$select=displayName,userPrincipalName)&`$top=999"
</code>```

I've tried adding to the URI above to include $filter=userType eq 'Guest'

I've tried adjusting my report object to

```<code>$ReportLine  = [PSCustomObject] @{
UserType           = $filter=$User.UserType -eq "Member"}
</code>```

I've also tried modifying my write output code with no success:

```<code>Write-Host "All done. " $Report.Count "accounts processed - output available in c:\Temp\ReportUserSignin.csv."
$Report | Sort DisplayName | Out-GridView
$Report | ?{$_.UserType -eq "Guest"}| Sort {$_.LastSignIn -as [DateTime]} -Descending | Format-Table DisplayName, LastSignIn, Email | Export-CSV -NoTypeInformation c:\Temp\ReportUserSignin.csv
</code>```

The above two only results in True/False results of the user is a member or guest.

Can someone provide some insight as to what I'm missing here or even where the filter should be for the exported report? I greatly appreciate any and all advice! :)

Body:
I'm exporting both custom and standard attributes of all users in Azure AD. I'm having difficulty wrapping my head around customizing the output when exporting.

For example, I'm seeking to export all users that are members, not Guests, with the below attributes:

$URI = "https://graph.microsoft.com/beta/users?`$select=displayName,userPrincipalName, mail, department, jobTitle, extension_1fe7973b28e74213b897d62528e614c7_extensionAttribute14, extension_1fe7973b28e74213b897d62528e614c7_extensionAttribute15, accountEnabled, signInActivity, UserType, id&`$expand=manager(`$select=displayName,userPrincipalName)&`$top=999"

I've tried adding to the URI above to include $filter=userType eq 'Guest'

I've tried adjusting my report object to

$ReportLine  = [PSCustomObject] @{
UserType           = $filter=$User.UserType -eq "Member"}

I've also tried modifying my write output code with no success:

Write-Host "All done. " $Report.Count "accounts processed - output available in c:\Temp\ReportUserSignin.csv."
$Report | Sort DisplayName | Out-GridView
$Report | ?{$_.UserType -eq "Guest"}| Sort {$_.LastSignIn -as [DateTime]} -Descending | Format-Table DisplayName, LastSignIn, Email | Export-CSV -NoTypeInformation c:\Temp\ReportUserSignin.csv

The above two only results in True/False results of the user is a member or guest.

Can someone provide some insight as to what I'm missing here or even where the filter should be for the exported report? I greatly appreciate any and all advice! :)


问:
How can write this formula to Python code?

How can write this formula to Python code?

m and q - some static numbers.

It is normal distribution function.


问:
clang: error: linker command failed with exit code 1 (use -v to see invocation) in Visual Studio Code
I want to run a c++ code in Visual Studio Code but every time I get this error

```<code>Undefined symbols for architecture x86_64:
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

I tried several methods with editing the main function but non worked

Body:
I want to run a c++ code in Visual Studio Code but every time I get this error

Undefined symbols for architecture x86_64:
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I tried several methods with editing the main function but non worked


问:
How to apply CSS styling to modularized shiny code in Pagepiling
I am trying to stylize my UI in a shiny app that I am making. I had previously built a fairly comprehensive map that I now have to modularize to improve readability by setting the map background as a transparent layer. Unfortunately, I cannot seem to understand how to go about applying CSS styles while using modules.

```<code>mapUI <- function(id) {
  ns <- NS(id)
  leafletOutput(ns("map"),width =250 , height = 250))
}
</code>```
```<code>basin <-  rgdal::readOGR("data/basin.kml", "basin")

ui <- pagePiling(
  tags$head(
    tags$link(rel = "stylesheet", type = "text/css", href = "style.css")),
  sections.color = c('#f2f2f2', '#2C3E50', '#39C'),
  opts = options,
  menu = c("Start" = "start",
           "Station 1" = "station1",
           "Station 2" = "station2"
  ),
  pageSectionImage(
    center = TRUE,
    img = "image1.jpg",
    menu = "start",
    mapUI("map1")
  ),
  pageSectionImage(
    center = TRUE,
    img ="image2.jpg",
    menu = "station1",
    mapUI("map2")
  ),
pageSectionImage(
    center = TRUE,
    img ="image3.jpg",
    menu = "station2",
    mapUI("map3")
  )
)
</code>```
```<code>server <- function(input, output){

  mapServer <- function(id) {
    moduleServer(
      id,
      function(input, output, session) {
        output$map<-renderLeaflet({
          leaflet(options = leafletOptions(zoomControl = FALSE, minZoom = 5, maxZoom = 5))%>%
            addPolygons(data = basin,color = "white",weight = 2,opacity = 1,fillOpacity = 0.9 )
        })
      })
  }
  mapServer("map1")
  mapServer("map2")
}
</code>```

here is the style.css that doesn't work for me!

```<code>#bottommap-map{
 background: rgba(0,0,0,0.05);
}
</code>```

Body:
I am trying to stylize my UI in a shiny app that I am making. I had previously built a fairly comprehensive map that I now have to modularize to improve readability by setting the map background as a transparent layer. Unfortunately, I cannot seem to understand how to go about applying CSS styles while using modules.

mapUI <- function(id) {
  ns <- NS(id)
  leafletOutput(ns("map"),width =250 , height = 250))
}

basin <-  rgdal::readOGR("data/basin.kml", "basin")

ui <- pagePiling(
  tags$head(
    tags$link(rel = "stylesheet", type = "text/css", href = "style.css")),
  sections.color = c('#f2f2f2', '#2C3E50', '#39C'),
  opts = options,
  menu = c("Start" = "start",
           "Station 1" = "station1",
           "Station 2" = "station2"
  ),
  pageSectionImage(
    center = TRUE,
    img = "image1.jpg",
    menu = "start",
    mapUI("map1")
  ),
  pageSectionImage(
    center = TRUE,
    img ="image2.jpg",
    menu = "station1",
    mapUI("map2")
  ),
pageSectionImage(
    center = TRUE,
    img ="image3.jpg",
    menu = "station2",
    mapUI("map3")
  )
)

server <- function(input, output){

  mapServer <- function(id) {
    moduleServer(
      id,
      function(input, output, session) {
        output$map<-renderLeaflet({
          leaflet(options = leafletOptions(zoomControl = FALSE, minZoom = 5, maxZoom = 5))%>%
            addPolygons(data = basin,color = "white",weight = 2,opacity = 1,fillOpacity = 0.9 )
        })
      })
  }
  mapServer("map1")
  mapServer("map2")
}

here is the style.css that doesn't work for me!

#bottommap-map{
 background: rgba(0,0,0,0.05);
}


问:
Firebase Re-authentication error: Contextual closure type '(AuthDataResult?, Error?) -> Void' expects 2 arguments, but 1 was used in closure body
So, I tried to add a delete account function using Firebase Manage User service here, it's showing me error. Below is the code.

```<code>
@IBAction func deleteAccount() {
        let user = Auth.auth().currentUser
        var credential: AuthCredential

        user?.reauthenticate(with: credential) { error in
            if let error = error {
                self.redAlert(message: "Unable to authenticate. Please try again.")
            } else {
                Auth.auth().currentUser?.delete { error in
                  if let error = error {
                      self.redAlert(message: "An error happened. Please contact support to delete your account")
                  } else {
                      self.greenAlert(message: "Your account has been deleted")
                  }
              }
            }
        }
</code>```

Attached the screenshot as well.

It keeps showing "Contextual closure type '(AuthDataResult?, Error?) -> Void' expects 2 arguments, but 1 was used in closure body" which I really don't know how to fix it. Would you mind helping to pinpoint this?

Screenshot

EDIT: I actually found the solution. The right code should be:

```<code>@IBAction func deleteAccount(_send: Any) {
    let user = Auth.auth().currentUser
    let emailText: String = email.text!
    let passwordText: String = password.text!
    var credential: AuthCredential = EmailAuthProvider.credential(withEmail: emailText, password: passwordText)

    user?.reauthenticate(with: credential, completion: { (result, error) in
        if let error = error {
            self.redAlert(message: "Unable to authenticate. Please try again.")
        } else {
            Auth.auth().currentUser?.delete { error in
              if let error = error {
                  self.redAlert(message: "An error happened. Please contact support to delete your account")
              } else {
                  self.greenAlert(message: "Your account has been deleted")
                  self.stopLoading()
                  self.logout()
              }
          }
        }
    })

}
</code>```

Hope it helps anyone that is struggling!

Body:
So, I tried to add a delete account function using Firebase Manage User service here, it's showing me error. Below is the code.

@IBAction func deleteAccount() {
        let user = Auth.auth().currentUser
        var credential: AuthCredential

        user?.reauthenticate(with: credential) { error in
            if let error = error {
                self.redAlert(message: "Unable to authenticate. Please try again.")
            } else {
                Auth.auth().currentUser?.delete { error in
                  if let error = error {
                      self.redAlert(message: "An error happened. Please contact support to delete your account")
                  } else {
                      self.greenAlert(message: "Your account has been deleted")
                  }
              }
            }
        }

Attached the screenshot as well.

It keeps showing "Contextual closure type '(AuthDataResult?, Error?) -> Void' expects 2 arguments, but 1 was used in closure body" which I really don't know how to fix it. Would you mind helping to pinpoint this?

Screenshot

EDIT: I actually found the solution. The right code should be:

@IBAction func deleteAccount(_send: Any) {
    let user = Auth.auth().currentUser
    let emailText: String = email.text!
    let passwordText: String = password.text!
    var credential: AuthCredential = EmailAuthProvider.credential(withEmail: emailText, password: passwordText)

    user?.reauthenticate(with: credential, completion: { (result, error) in
        if let error = error {
            self.redAlert(message: "Unable to authenticate. Please try again.")
        } else {
            Auth.auth().currentUser?.delete { error in
              if let error = error {
                  self.redAlert(message: "An error happened. Please contact support to delete your account")
              } else {
                  self.greenAlert(message: "Your account has been deleted")
                  self.stopLoading()
                  self.logout()
              }
          }
        }
    })

}

Hope it helps anyone that is struggling!


问:
Changing partial effect lenght with keyframe
FULL CODE

```<code>import bpy
bpy.ops.mesh.primitive_plane_add(size=2, location=(0, 0, 0))
bpy.ops.transform.resize(value=(10, 10, 10))
bpy.ops.object.modifier_add(type='COLLISION')
bpy.ops.mesh.primitive_uv_sphere_add(segments=16, ring_count=8, radius=1,
location=(0, 0, 5))
bpy.ops.object.modifier_add(type='SUBSURF')
bpy.context.object.modifiers["Subdivision"].levels = 1
bpy.context.object.modifiers["Subdivision"].render_levels = 3
bpy.ops.object.shade_smooth()
bpy.ops.object.modifier_add(type='COLLISION')
bpy.ops.object.modifier_add(type='SOFT_BODY')
bpy.context.object.modifiers["Softbody"].settings.use_goal = False
bpy.context.object.modifiers["Softbody"].settings.bend = 5

# Particle physics for hair
mod = bpy.context.object.modifiers.new("ParticleSystem", type =
'PARTICLE_SYSTEM')
hair_stngs = mod.particle_system.settings
hair_stngs.type = 'HAIR'
hair_stngs.hair_length = 0
hair_stngs.use_advanced_hair = True
hair_stngs.count = 5000
hair_stngs.hair_step = 12
mod.particle_system.use_hair_dynamics = False

bpy.data.particles["ParticleSettings"].use_regrow_hair = True

bpy.context.object.keyframe_insert(data_path = "hair_length",frame = 0)
bpy.data.particles["ParticleSettings"].hair_length = 0

bpy.context.object.keyframe_insert(data_path = "hair_length",frame = 30)
bpy.data.particles["ParticleSettings"].hair_length = 2

bpy.context.object.keyframe_insert(data_path = "hair_length",frame = 60)
bpy.data.particles["ParticleSettings"].hair_length = 4

</code>```

When I want to change the data path  = hair_length, it does not accept the data path. How can i access the hair lenght?

bpy.context.object.keyframe_insert(data_path = "hair_length",frame = 0)
bpy.data.particles["ParticleSettings"].hair_length = 0

I tried right click and copy data path in partical settings hair lenght but data path didnt recognize by the blender

Body:
FULL CODE

import bpy
bpy.ops.mesh.primitive_plane_add(size=2, location=(0, 0, 0))
bpy.ops.transform.resize(value=(10, 10, 10))
bpy.ops.object.modifier_add(type='COLLISION')
bpy.ops.mesh.primitive_uv_sphere_add(segments=16, ring_count=8, radius=1,
location=(0, 0, 5))
bpy.ops.object.modifier_add(type='SUBSURF')
bpy.context.object.modifiers["Subdivision"].levels = 1
bpy.context.object.modifiers["Subdivision"].render_levels = 3
bpy.ops.object.shade_smooth()
bpy.ops.object.modifier_add(type='COLLISION')
bpy.ops.object.modifier_add(type='SOFT_BODY')
bpy.context.object.modifiers["Softbody"].settings.use_goal = False
bpy.context.object.modifiers["Softbody"].settings.bend = 5

# Particle physics for hair
mod = bpy.context.object.modifiers.new("ParticleSystem", type =
'PARTICLE_SYSTEM')
hair_stngs = mod.particle_system.settings
hair_stngs.type = 'HAIR'
hair_stngs.hair_length = 0
hair_stngs.use_advanced_hair = True
hair_stngs.count = 5000
hair_stngs.hair_step = 12
mod.particle_system.use_hair_dynamics = False

bpy.data.particles["ParticleSettings"].use_regrow_hair = True

bpy.context.object.keyframe_insert(data_path = "hair_length",frame = 0)
bpy.data.particles["ParticleSettings"].hair_length = 0

bpy.context.object.keyframe_insert(data_path = "hair_length",frame = 30)
bpy.data.particles["ParticleSettings"].hair_length = 2

bpy.context.object.keyframe_insert(data_path = "hair_length",frame = 60)
bpy.data.particles["ParticleSettings"].hair_length = 4

When I want to change the data path  = hair_length, it does not accept the data path. How can i access the hair lenght?

bpy.context.object.keyframe_insert(data_path = "hair_length",frame = 0)
bpy.data.particles["ParticleSettings"].hair_length = 0

I tried right click and copy data path in partical settings hair lenght but data path didnt recognize by the blender


问:
ArcadeDB integration with LiquidBase
Is there a any plan to be able to use Liquibase to maintain the structure and data inside ArcadeDB ?Thanks

I could not find any example on the net about this. Is it complex to do ?

Title: ArcadeDB integration with LiquidBase


问:
Get a token for the current logged in user, using MSAL.NET
I'm trying to get a token for the current logged in user, using MSAL.NET

I'm getting a reference to PublicClientApplication, using the following API:

```<code>_clientApp = PublicClientApplicationBuilder.Create(ClientId)
    .WithAuthority(AzureCloudInstance.AzurePublic, Tenant)
    .WithBroker()
    .WithDefaultRedirectUri()
    .Build();
</code>```

Then, later in the code, I'm trying to call AcquireTokenSilent with the following code:

```<code>var firstAccount = Microsoft.Identity.Client.PublicClientApplication.OperatingSystemAccount;
authResult = await _clientApp.AcquireTokenSilent(scopes, firstAccount)
</code>```

The call to AcquireTokenSilent thow an exception, with the following details:

```<code>Microsoft.Identity.Client.MsalServiceException
  HResult=0x80131500
  Message=WAM Error  Microsoft.Identity.Client.Platforms.Features.WamBroker.AadPlugin
 Error Code: WAM_aad_provider_error_3399614466
 Error Message:
 WAM Error Message: V2Error: invalid_request AADSTS90002: Tenant '75950cd6-4468-4918-b750-966c6b4fa3d1' not found. Check to make sure you have the correct tenant ID and are signing into the correct cloud. Check with your subscription administrator, this may happen if there are no active subscriptions for the tenant.
</code>```

Interestingly, the SID '75950cd6-4468-4918-b750-966c6b4fa3d1' is NOT my tenant ID, and actually, I do not have this string anywhere in my code.

In the application registration, I set up the redirect URI to:
ms-appx-web://microsoft.aad.brokerplugin/<my application SID>. The application is registered for domain only, and the my device is domain joined.

What am I doing wrong?

Update

Answer a comment from @Sridevi.
I'm following this demo almost to the letter: https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-windows-desktop

With the following changes:

As a redirect URI, I wrote: ms-appx-web://microsoft.aad.brokerplugin/<client SID>

When building the MSAL application, I added .WithBroker() as mentioned above

For firstAccount, I do not take the first account from the list of acounts as in the tutorial (it is empty the first time), but I'm using the enum OperatingSystemAccount, mentioned above as well.

I would appreciate a sample or tutorial for getting this token otherwise.

Body:
I'm trying to get a token for the current logged in user, using MSAL.NET

I'm getting a reference to PublicClientApplication, using the following API:

_clientApp = PublicClientApplicationBuilder.Create(ClientId)
    .WithAuthority(AzureCloudInstance.AzurePublic, Tenant)
    .WithBroker()
    .WithDefaultRedirectUri()
    .Build();

Then, later in the code, I'm trying to call AcquireTokenSilent with the following code:

var firstAccount = Microsoft.Identity.Client.PublicClientApplication.OperatingSystemAccount;
authResult = await _clientApp.AcquireTokenSilent(scopes, firstAccount)

The call to AcquireTokenSilent thow an exception, with the following details:

Microsoft.Identity.Client.MsalServiceException
  HResult=0x80131500
  Message=WAM Error  Microsoft.Identity.Client.Platforms.Features.WamBroker.AadPlugin
 Error Code: WAM_aad_provider_error_3399614466
 Error Message:
 WAM Error Message: V2Error: invalid_request AADSTS90002: Tenant '75950cd6-4468-4918-b750-966c6b4fa3d1' not found. Check to make sure you have the correct tenant ID and are signing into the correct cloud. Check with your subscription administrator, this may happen if there are no active subscriptions for the tenant.

Interestingly, the SID '75950cd6-4468-4918-b750-966c6b4fa3d1' is NOT my tenant ID, and actually, I do not have this string anywhere in my code.

In the application registration, I set up the redirect URI to:
ms-appx-web://microsoft.aad.brokerplugin/<my application SID>. The application is registered for domain only, and the my device is domain joined.

What am I doing wrong?

Update

Answer a comment from @Sridevi.
I'm following this demo almost to the letter: https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-windows-desktop

With the following changes:

As a redirect URI, I wrote: ms-appx-web://microsoft.aad.brokerplugin/<client SID>

When building the MSAL application, I added .WithBroker() as mentioned above

For firstAccount, I do not take the first account from the list of acounts as in the tutorial (it is empty the first time), but I'm using the enum OperatingSystemAccount, mentioned above as well.

I would appreciate a sample or tutorial for getting this token otherwise.


问:
copy paste error on function script from openAI
using open ai to generate code samples to see if they work however complie errors abound

```<code>function getPrice()
 // Function code goes here

// Call the function
getPrice()

var currentPrice = GetPrice()

// Calculate liquidation values
var liquidationValue25 = currentPrice * 0.25
var liquidationValue50 = currentPrice * 0.50
var liquidationValue75 = currentPrice * 0.75

// Plot liquidation values
PlotLine("Liquidation Value 25%", liquidationValue25, Color.DARK_GRAY)
PlotLine("Liquidation Value 50%", liquidationValue50, Color.MEDIUM_GRAY)
PlotLine("Liquidation Value 75%", liquidationValue75, Color.LIGHT_GRAY)

</code>```

doesnt work error is2:43:07 PM — Compilation error. Line 7: Syntax error at input 'function'

tried to run it to apply it to chart some guy did same process and it ran perfectly

Body:
using open ai to generate code samples to see if they work however complie errors abound

function getPrice()
 // Function code goes here

// Call the function
getPrice()

var currentPrice = GetPrice()

// Calculate liquidation values
var liquidationValue25 = currentPrice * 0.25
var liquidationValue50 = currentPrice * 0.50
var liquidationValue75 = currentPrice * 0.75

// Plot liquidation values
PlotLine("Liquidation Value 25%", liquidationValue25, Color.DARK_GRAY)
PlotLine("Liquidation Value 50%", liquidationValue50, Color.MEDIUM_GRAY)
PlotLine("Liquidation Value 75%", liquidationValue75, Color.LIGHT_GRAY)

doesnt work error is2:43:07 PM — Compilation error. Line 7: Syntax error at input 'function'

tried to run it to apply it to chart some guy did same process and it ran perfectly


问:
Asynchronous file reading to increase perf
Probleme : I'm working on a script to parse a bitcoin block (binary file).

My script is working fine, now I would like to increase the performance (I mean make it faster) and parse multiple blocks in the same time.
To do so I thought of using goroutines in order to read multiple files in parallel.

First question : Does using goroutines to to read / parse multiple files in parallel will reduce the execution time ?
Maybe goroutines are not the solution ?

Seconde question : If yes, what's wrong with the follow code which take the same time as the synchronious version to parse let's say 100 blocks ?

```<code>func getBlock(path string, ch chan s.Block) {
    f, err := os.Open(path)
    utils.Handle(err)
    defer f.Close()

    s.NewBlock(f, ch)
}

func main() {
    nbr_blk := len(os.Args) - 1
    files := os.Args[1:len(os.Args)]

    var t timer.Timer
    t.Start()

    ch := make(chan s.Block)

    for _, file := range files {
        go getBlock(file, ch)
    }

    for i := 0; i < nbr_blk; i++ {
        select {
        case blk := <-ch:
            fmt.Printf("Blk prev hash : %x\n", blk.Header.Hash_prev_block)
        }
    }

    time_spent := t.Stop()
    fmt.Printf("Time spent to parse %v blocks : %v\n", nbr_blk, time_spent)
}
</code>```

block.go :

```<code>func NewBlock(f *os.File, ch chan Block) {
    var blk Block
    blk.From(f)
    ch <- blk
}
</code>```

blk.From(f) is just reading the file and "populating" the struct Block with bytes

Body:
Probleme : I'm working on a script to parse a bitcoin block (binary file).

My script is working fine, now I would like to increase the performance (I mean make it faster) and parse multiple blocks in the same time.
To do so I thought of using goroutines in order to read multiple files in parallel.

First question : Does using goroutines to to read / parse multiple files in parallel will reduce the execution time ?
Maybe goroutines are not the solution ?

Seconde question : If yes, what's wrong with the follow code which take the same time as the synchronious version to parse let's say 100 blocks ?

func getBlock(path string, ch chan s.Block) {
    f, err := os.Open(path)
    utils.Handle(err)
    defer f.Close()

    s.NewBlock(f, ch)
}

func main() {
    nbr_blk := len(os.Args) - 1
    files := os.Args[1:len(os.Args)]

    var t timer.Timer
    t.Start()

    ch := make(chan s.Block)

    for _, file := range files {
        go getBlock(file, ch)
    }

    for i := 0; i < nbr_blk; i++ {
        select {
        case blk := <-ch:
            fmt.Printf("Blk prev hash : %x\n", blk.Header.Hash_prev_block)
        }
    }

    time_spent := t.Stop()
    fmt.Printf("Time spent to parse %v blocks : %v\n", nbr_blk, time_spent)
}

block.go :

func NewBlock(f *os.File, ch chan Block) {
    var blk Block
    blk.From(f)
    ch <- blk
}

blk.From(f) is just reading the file and "populating" the struct Block with bytes


问:
How to Translate a XML file to a French language in spring batch
We are processing an incoming  .txt file to an XML file through Spring Batch process, We also require to translate few XML's to french language, appreciate any code samples

We tried looking up and most of them have examples around Spring Boot but none specific to Spring Batch


问:
Jest-React hook Testing : How to call a setState inside a custom function using useEffect
I am trying to set mockPatient data and wanted to test if the 'sortByCaseFn ' function is called by the useEffect.

Here is my sourcecode:

Patient.tsx

```<code> const [patients, setPatients] = useState([]);
  const [sortBy, setSortBy] = useState('events');
  const [fetched, setFetched] = useState(false);

  const dispatch = useAppDispatch();
  const props = useAppSelector((state) => state.myPatientProps);

  const getPatientData = (): void => {
    dispatch(MyPatientActions.getMyPatientsData());
  };

  const sortByCaseFn = (sortBy, list) => {
    let patientsToSort = [...list];
    if (sortBy.includes('events'))
      patientsToSort.sort(
        sorter.byPropertiesOf(['-ActiveEventsCount', 'LastName'])
      );
    if (sortBy.includes('vae'))
      patientsToSort.sort(sorter.byPropertiesOf(['-VaeStatus']));

    console.log('patientsToSort---', patientsToSort);
    setPatients(patientsToSort);
  };

 useEffect(() => {
    if (!fetched) {
      getPatientData();
    }
  }, []);

  useEffect(() => {
    console.log('setpatients called .. ', patients);
  }, [patients]);

  useEffect(() => {
    const saved_sortby = localStorage.getItem('sortby');
    if (saved_sortby) {
      sortByCaseFn(saved_sortby, props.myPatientDetails);
    } else sortByCaseFn('events', props.myPatientDetails);
    setFetched(true);
  }, [props.myPatientDetails]);

  useEffect(() => {
    sortByCaseFn(sortBy, patients);
  }, [sortBy]);

return (
    <> Render Patient List  </> )

</code>```

My Test Code :
Patients.test.tsx

```<code>

jest.mock('react-redux', () => ({
  useSelector: jest.fn(),
  useDispatch: jest.fn()
}));

export const setHookTestState = (newState: any) => {
  const setStateMockFn = () => {};
  return Object.keys(newState).reduce((acc, val) => {
    acc = acc?.mockImplementationOnce(() => [newState[val], setStateMockFn]);
    return acc;
  }, jest.fn());
};

describe('My Patient Screen', () => {
  const useSelectorMock = reactRedux.useSelector as jest.Mock<any>;
  const useDispatchMock = reactRedux.useDispatch as jest.Mock<any>;

  beforeEach(() => {
     useSelectorMock.mockImplementation((selector) => selector(mockStore));
     useDispatchMock.mockImplementation(() => () => {});
  });
  afterEach(() => {
    useDispatchMock.mockClear();
    useSelectorMock.mockClear();
  });

  const mockInitialState = {
    myPatientDetails: vaeMock,
    fetching: false,
    failedMsg: '',
    requestPayload: {}
  };

  const mockStore = {
    counter: undefined,
    menu: undefined,
    selectPatientProps: undefined,
    myPatientProps: mockInitialState
  };

  test('validate sorting by events', async (done) => {

    React.useState = setHookTestState({
      patients: vaeMock,
      sortBy: 'vae',
      fetched: 'false'
    });

    const {
      getByText,
      getByRole,
      getByTestId,
      getAllByTestId,
      findAllByTestId,
      queryByText,
      container
    } = render(<Mypatient />);
    await waitFor(() => {
      expect(getByText('Ander, Sam')).toBeDefined();
    });
    const list = getAllByTestId('patientname');
    expect(within(list[0]).getByText('Sara, Jone')).toBeInTheDocument();  //Fails here as Sorting doesnt happen

    console.log('....list ', list);
  });
});
</code>```

My Observations:

The 'vaeMock' data that I set in redux state 'mockInitialState' is successfully sent as props

The 'vaeMock' data that I set in component state using setHookTestState is also set successfully.

The lifecycle events happens like this -
a. setPatients() is called using the component state data.
b. using props that is sent , sortByCaseFn is called but setPatients is not called.
c. again using the component state , sortByCaseFn is called but setPatients is not set.

Without setting the component state variables runs into a TypeError: Undefined is not iterable.

All Iam trying to do is - send a mockData to a component that uses useDispatch, useEffects
and sort the data on the component mount and initialize to local state variable.

Body:
I am trying to set mockPatient data and wanted to test if the 'sortByCaseFn ' function is called by the useEffect.

Here is my sourcecode:

Patient.tsx

 const [patients, setPatients] = useState([]);
  const [sortBy, setSortBy] = useState('events');
  const [fetched, setFetched] = useState(false);

  const dispatch = useAppDispatch();
  const props = useAppSelector((state) => state.myPatientProps);

  const getPatientData = (): void => {
    dispatch(MyPatientActions.getMyPatientsData());
  };

  const sortByCaseFn = (sortBy, list) => {
    let patientsToSort = [...list];
    if (sortBy.includes('events'))
      patientsToSort.sort(
        sorter.byPropertiesOf(['-ActiveEventsCount', 'LastName'])
      );
    if (sortBy.includes('vae'))
      patientsToSort.sort(sorter.byPropertiesOf(['-VaeStatus']));

    console.log('patientsToSort---', patientsToSort);
    setPatients(patientsToSort);
  };

 useEffect(() => {
    if (!fetched) {
      getPatientData();
    }
  }, []);

  useEffect(() => {
    console.log('setpatients called .. ', patients);
  }, [patients]);

  useEffect(() => {
    const saved_sortby = localStorage.getItem('sortby');
    if (saved_sortby) {
      sortByCaseFn(saved_sortby, props.myPatientDetails);
    } else sortByCaseFn('events', props.myPatientDetails);
    setFetched(true);
  }, [props.myPatientDetails]);

  useEffect(() => {
    sortByCaseFn(sortBy, patients);
  }, [sortBy]);

return (
    <> Render Patient List  </> )

My Test Code :
Patients.test.tsx

jest.mock('react-redux', () => ({
  useSelector: jest.fn(),
  useDispatch: jest.fn()
}));

export const setHookTestState = (newState: any) => {
  const setStateMockFn = () => {};
  return Object.keys(newState).reduce((acc, val) => {
    acc = acc?.mockImplementationOnce(() => [newState[val], setStateMockFn]);
    return acc;
  }, jest.fn());
};

describe('My Patient Screen', () => {
  const useSelectorMock = reactRedux.useSelector as jest.Mock<any>;
  const useDispatchMock = reactRedux.useDispatch as jest.Mock<any>;

  beforeEach(() => {
     useSelectorMock.mockImplementation((selector) => selector(mockStore));
     useDispatchMock.mockImplementation(() => () => {});
  });
  afterEach(() => {
    useDispatchMock.mockClear();
    useSelectorMock.mockClear();
  });

  const mockInitialState = {
    myPatientDetails: vaeMock,
    fetching: false,
    failedMsg: '',
    requestPayload: {}
  };

  const mockStore = {
    counter: undefined,
    menu: undefined,
    selectPatientProps: undefined,
    myPatientProps: mockInitialState
  };

  test('validate sorting by events', async (done) => {

    React.useState = setHookTestState({
      patients: vaeMock,
      sortBy: 'vae',
      fetched: 'false'
    });

    const {
      getByText,
      getByRole,
      getByTestId,
      getAllByTestId,
      findAllByTestId,
      queryByText,
      container
    } = render(<Mypatient />);
    await waitFor(() => {
      expect(getByText('Ander, Sam')).toBeDefined();
    });
    const list = getAllByTestId('patientname');
    expect(within(list[0]).getByText('Sara, Jone')).toBeInTheDocument();  //Fails here as Sorting doesnt happen

    console.log('....list ', list);
  });
});

My Observations:

The 'vaeMock' data that I set in redux state 'mockInitialState' is successfully sent as props

The 'vaeMock' data that I set in component state using setHookTestState is also set successfully.

The lifecycle events happens like this -
a. setPatients() is called using the component state data.
b. using props that is sent , sortByCaseFn is called but setPatients is not called.
c. again using the component state , sortByCaseFn is called but setPatients is not set.

Without setting the component state variables runs into a TypeError: Undefined is not iterable.

All Iam trying to do is - send a mockData to a component that uses useDispatch, useEffects
and sort the data on the component mount and initialize to local state variable.


问:
Creating a nested mongodb document using Apollo-graphql and mongoose
I am trying to create a restaurant mobile app using react native and for that I have used the following restaurant mongo model schema in the backend:

```<code>const restaurantSchema = mongoose.Schema({
    uid: {type: String, default:uuid.v4,required: true, unique: true},
    id: {type: String, unique: true},
    name: {type: String, required: true, unique: true},
    phone: {type: String, required: true, unique: true},
    owner: {type: String, required: true},
    address: {type: String, required: true, unique: true},
    menu: [{
        uid: {type: String, default:uuid.v4, unique: true},
        id: {type: String, unique: true},
        category_name: {type: String, unique: true},
        subcategory: [{
            uid: {type: String, default:uuid.v4, unique: true},
            id: {type: String, unique: true},
            subcategory_name: {type: String, unique: true},
            item: [{
                uid: {type: String, default:uuid.v4, unique:true},
                item_name: {type: String, unique: true},
                calories: {type: String},
                type: {type: String, enum: ['VEGAN', 'VEG', 'NON_VEG']},
                price: {type: String},
            }]
        }]
    }]
},
    {timestamps: true}
)
</code>```

I want to run a mutation such that, starting with the category_name array, it should check for each of the subarrays that whether the specified entry already exists or not in a single flow
If for the category already exists then the mutation should check whether the subcategory exists or not and if the category or the sub-category doesn't exist, the resolver should create new entries.

The mutation I wrote is working for some parts like when I try to mutate twice, it creates a category and subcategory entry but not in a single mutation operation

My resolver-

```<code>addMenuItems: async(_, {menuItemInput:{restaurant_name,name,calories,type,price,category,subcategory}},context) => {
            const user = await Auth.verifyToken(context,process.env.TOKEN_SECRET)
            //console.log(String(user.id))

            if (!user) {
                throw new ApolloError('Session expired')
            }
            const present_user = await User.findOne({uid:user.id})

            const valid_user = Rest.owner_checker(present_user.username,User)

            if (!valid_user) {
                throw new ApolloError('Only the owner is permitted to modify menu items!')
            }

            duplicate_item = Rest.duplicate_checker(name,restaurant_name,category,subcategory,Restaurant)

            if (duplicate_item !== null) {
                throw new UserInputError("This item already exists")
            }

            try {

                const newMenuItemStatus = await Rest.Item_adder(Restaurant, [name,restaurant_name,calories,type,price,category,subcategory])

                if (newMenuItemStatus === 'SUCCESS') {
                    console.log('New Item was added successfully')

                    const newMenuItem = await Restaurant.findOne(({name: restaurant_name},
                        {"menu":
                        {category_name: category,
                        "subcategory":
                        {"item": {
                            "$elemMatch": {"item_name": {"$in": name}}
                        }}

                        },
                    }))

                    return {
                        id: newMenuItem.id,
                        ...newMenuItem._doc
                    }
                }

            } catch (error) {

                throw new UserInputError('Item addition failed')
            }

        }
</code>```

The mutation code:

```<code>static Item_adder = async (Restaurant, Payload) => {
        const [name, restaurant_name,calories, type, price, category, subcategory] = Payload

        const Restaurant_category = await Restaurant.findOne({name: restaurant_name,
            "menu": {
                "$elemMatch": {"category_name": {"$in": category}}}}

        )
        console.log("Abefore: ",Restaurant_category)

        if (Restaurant_category == null) {
            await Restaurant.updateOne(
                {name: restaurant_name},
                {"$push": {"menu": {category_name: category}}},

            function (error, res) {
                if (error) {
                    console.log(error)
                }
                else {

                }

            }
            )
        }

            const Restaurant_subcategory = await Restaurant.findOne({name: restaurant_name,
                "menu.subcategory": {
                    "$elemMatch": {"subcategory_name": {"$in": subcategory}}}}

            )
            console.log("B: ",Restaurant_subcategory)

        if (Restaurant_subcategory == null) {
            await Restaurant.updateOne(
                {name: restaurant_name,
                 "menu": {category_name: category,
                           "$push": {"subcategory": {subcategory_name: subcategory}}}
                },

            function (error, res) {
                if (error) {
                    console.log(error)
                }
                else {
                    console.log(res)
                }

            })
        }

        await Restaurant.updateOne({name: restaurant_name,
            "menu":
            {category_name: category,
            "subcategory":
            {subcategory_name: subcategory,
             "$push": {"item": {item_name:name,
                                calories:calories,
                                type:type,
                                price:price}}}

            },
            function (error, res) {
                if (error) {
                    console.log(error)
                }
                else {
                    console.log(res)
                }

            }
        })

        return 'SUCCESS'

    }
</code>```

Where am I going wrong? I tried several combinations of resolvers and mongoose update queries but I've got no luck so far.

Body:
I am trying to create a restaurant mobile app using react native and for that I have used the following restaurant mongo model schema in the backend:

const restaurantSchema = mongoose.Schema({
    uid: {type: String, default:uuid.v4,required: true, unique: true},
    id: {type: String, unique: true},
    name: {type: String, required: true, unique: true},
    phone: {type: String, required: true, unique: true},
    owner: {type: String, required: true},
    address: {type: String, required: true, unique: true},
    menu: [{
        uid: {type: String, default:uuid.v4, unique: true},
        id: {type: String, unique: true},
        category_name: {type: String, unique: true},
        subcategory: [{
            uid: {type: String, default:uuid.v4, unique: true},
            id: {type: String, unique: true},
            subcategory_name: {type: String, unique: true},
            item: [{
                uid: {type: String, default:uuid.v4, unique:true},
                item_name: {type: String, unique: true},
                calories: {type: String},
                type: {type: String, enum: ['VEGAN', 'VEG', 'NON_VEG']},
                price: {type: String},
            }]
        }]
    }]
},
    {timestamps: true}
)

I want to run a mutation such that, starting with the category_name array, it should check for each of the subarrays that whether the specified entry already exists or not in a single flow
If for the category already exists then the mutation should check whether the subcategory exists or not and if the category or the sub-category doesn't exist, the resolver should create new entries.

The mutation I wrote is working for some parts like when I try to mutate twice, it creates a category and subcategory entry but not in a single mutation operation

My resolver-

addMenuItems: async(_, {menuItemInput:{restaurant_name,name,calories,type,price,category,subcategory}},context) => {
            const user = await Auth.verifyToken(context,process.env.TOKEN_SECRET)
            //console.log(String(user.id))

            if (!user) {
                throw new ApolloError('Session expired')
            }
            const present_user = await User.findOne({uid:user.id})

            const valid_user = Rest.owner_checker(present_user.username,User)

            if (!valid_user) {
                throw new ApolloError('Only the owner is permitted to modify menu items!')
            }

            duplicate_item = Rest.duplicate_checker(name,restaurant_name,category,subcategory,Restaurant)

            if (duplicate_item !== null) {
                throw new UserInputError("This item already exists")
            }

            try {

                const newMenuItemStatus = await Rest.Item_adder(Restaurant, [name,restaurant_name,calories,type,price,category,subcategory])

                if (newMenuItemStatus === 'SUCCESS') {
                    console.log('New Item was added successfully')

                    const newMenuItem = await Restaurant.findOne(({name: restaurant_name},
                        {"menu":
                        {category_name: category,
                        "subcategory":
                        {"item": {
                            "$elemMatch": {"item_name": {"$in": name}}
                        }}

                        },
                    }))

                    return {
                        id: newMenuItem.id,
                        ...newMenuItem._doc
                    }
                }

            } catch (error) {

                throw new UserInputError('Item addition failed')
            }

        }

The mutation code:

static Item_adder = async (Restaurant, Payload) => {
        const [name, restaurant_name,calories, type, price, category, subcategory] = Payload

        const Restaurant_category = await Restaurant.findOne({name: restaurant_name,
            "menu": {
                "$elemMatch": {"category_name": {"$in": category}}}}

        )
        console.log("Abefore: ",Restaurant_category)

        if (Restaurant_category == null) {
            await Restaurant.updateOne(
                {name: restaurant_name},
                {"$push": {"menu": {category_name: category}}},

            function (error, res) {
                if (error) {
                    console.log(error)
                }
                else {

                }

            }
            )
        }

            const Restaurant_subcategory = await Restaurant.findOne({name: restaurant_name,
                "menu.subcategory": {
                    "$elemMatch": {"subcategory_name": {"$in": subcategory}}}}

            )
            console.log("B: ",Restaurant_subcategory)

        if (Restaurant_subcategory == null) {
            await Restaurant.updateOne(
                {name: restaurant_name,
                 "menu": {category_name: category,
                           "$push": {"subcategory": {subcategory_name: subcategory}}}
                },

            function (error, res) {
                if (error) {
                    console.log(error)
                }
                else {
                    console.log(res)
                }

            })
        }

        await Restaurant.updateOne({name: restaurant_name,
            "menu":
            {category_name: category,
            "subcategory":
            {subcategory_name: subcategory,
             "$push": {"item": {item_name:name,
                                calories:calories,
                                type:type,
                                price:price}}}

            },
            function (error, res) {
                if (error) {
                    console.log(error)
                }
                else {
                    console.log(res)
                }

            }
        })

        return 'SUCCESS'

    }

Where am I going wrong? I tried several combinations of resolvers and mongoose update queries but I've got no luck so far.


问:
Using StartActivityForResult in non activity
I'm starting an Activity to pick a file and get the path from it. Therefore the "ActivivityResultLauncher" should be defined in onCreate() of MainActivity but I want it to define it in other non-activity classes, which I've already tried but I took null pointer exception error.

MainActivity Class

         public static ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if(result.getResultCode() == Activity.RESULT_OK) {
                    if (result.getData() != null) {
                        String path = "/" + result.getData().getData().getPath().substring(result.getData().getData().getPath().indexOf(":") + 1);
                        //animHandler.openAttach();
                    }
                }
            }
        });
    }
```
<p>PathHandler Class (a non-activity class)</p>
<pre class="lang-java prettyprint-override"><code>    public void pathReceiver() {

        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        Uri uri = Uri.parse(String.valueOf(Environment.getExternalStorageDirectory()));
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setDataAndType(uri, "text/plain");
        MainActivity.activityResultLauncher.launch(intent);

        /*
           I want to add the "public static ActivityResultLauncher..." definition into here.
        */
    }
</code>```

Body:
I'm starting an Activity to pick a file and get the path from it. Therefore the "ActivivityResultLauncher" should be defined in onCreate() of MainActivity but I want it to define it in other non-activity classes, which I've already tried but I took null pointer exception error.

MainActivity Class

         public static ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if(result.getResultCode() == Activity.RESULT_OK) {
                    if (result.getData() != null) {
                        String path = "/" + result.getData().getData().getPath().substring(result.getData().getData().getPath().indexOf(":") + 1);
                        //animHandler.openAttach();
                    }
                }
            }
        });
    }

PathHandler Class (a non-activity class)

    public void pathReceiver() {

        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        Uri uri = Uri.parse(String.valueOf(Environment.getExternalStorageDirectory()));
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setDataAndType(uri, "text/plain");
        MainActivity.activityResultLauncher.launch(intent);

        /*
           I want to add the "public static ActivityResultLauncher..." definition into here.
        */
    }


问:
Power Pivot Pivottable SUM is not working
My servers are grouped into Workloads.
These Workloads are migrating according to a schedule that is updated quarterly.
The servers are configured with two different types of storage.
What I need to show is, by quarter, what the total is for the two different types of storage.
Since this is a many-to-many relationship, I created a middle man table called Workloads.
When I do the Pivottable, it shows the grand total of all storage for each quarter (the exact same value, repeated).

Schedule:

Workloads:

Invoice:

My data model:

Thank you

Because Workload aaaaaa isn't in the Q3 update it's migrated and its servers shouldn't be included.

What I'm expecting:

The result I get:


问:
How to index a list of tf.keras.layers.Layer with a TensorFlow Tensor inside a tf.function?
I have a list of tf.keras.layers.Layer that I want to index based off of an index tensor inside a tf.function. Ideally like this:

```<code>import tensorflow as tf
from typing import List

@tf.function
def compute_single_output(heads: List[layers.Layer], index_tensor: tf.Tensor, input: tf.Tensor):
    logit = heads[index_tensor](input)
    return logit
</code>```

But I get this:

```<code>    TypeError: list indices must be integers or slices, not Tensor
</code>```

Is there any way to set this up so that I can do it? tf.gather won't work for a list of Layers. TF Lookup table wouldn't work either. I tried using a dict of heads instead of a list, also didn't work.

Only thing that works is to iterate over the list in a Python for loop, but this accumulates CPU RAM per iteration over the loop (because autograph can't convert heads into a tensor, it can't use tf.while_loop, see https://www.tensorflow.org/guide/function#loops for more info):

```<code>@tf.function
def compute_single_output(heads: List[layers.Layer], index_tensor: tf.Tensor, input: tf.Tensor):
    logit = tf.constant(-1, dtype=tf.float32)
    m = tf.constant(0)
    for head in heads:
        if m == index_tensor:
            logit = head(input)
        else:
            pass
        m += 1
    return logit
</code>```

I expect to be running this function for a long time, so I can't afford to accumulate memory indefinitely.

Body:
I have a list of tf.keras.layers.Layer that I want to index based off of an index tensor inside a tf.function. Ideally like this:

import tensorflow as tf
from typing import List

@tf.function
def compute_single_output(heads: List[layers.Layer], index_tensor: tf.Tensor, input: tf.Tensor):
    logit = heads[index_tensor](input)
    return logit

But I get this:

    TypeError: list indices must be integers or slices, not Tensor

Is there any way to set this up so that I can do it? tf.gather won't work for a list of Layers. TF Lookup table wouldn't work either. I tried using a dict of heads instead of a list, also didn't work.

Only thing that works is to iterate over the list in a Python for loop, but this accumulates CPU RAM per iteration over the loop (because autograph can't convert heads into a tensor, it can't use tf.while_loop, see https://www.tensorflow.org/guide/function#loops for more info):

@tf.function
def compute_single_output(heads: List[layers.Layer], index_tensor: tf.Tensor, input: tf.Tensor):
    logit = tf.constant(-1, dtype=tf.float32)
    m = tf.constant(0)
    for head in heads:
        if m == index_tensor:
            logit = head(input)
        else:
            pass
        m += 1
    return logit

I expect to be running this function for a long time, so I can't afford to accumulate memory indefinitely.


问:
React Chakra UI Modal bug
I'm developing in ReactTS in VS Code.
In the navbar there is a menu in which there is a logut button.
when clicked user logged out etc. but at the end the sign in modal appears and I cant figure out why.
The sign in button doesn't trigger neither does the variable turns true which controls the sign in modal.
I fixed it by setting isLogin to false but it never had turned to true anyway.

Menu Component:

```<code>export default function UserMenu() {

    const navigate = useNavigate();
    const user = useAppSelector(state => state.auth.user);
    const dispatch = useAppDispatch();
    const [isLogin, setIsLogin] = useState(false);

    if (user) return (
        <Menu>
            <MenuButton>
                Account
            </MenuButton>
            <MenuList>
                <MenuGroup title={user.name}>
                    <MenuItem onClick={() => {
                        dispatch(logout());
                        dispatch(setMovie(null));
                        navigate("/");
                        //Login bug
                        Had to set this here so it works but don't know why
                        setIsLogin(false);

                    }} >Logout</MenuItem>
                </MenuGroup>
            </MenuList >
        </Menu >
    )
    else return (
        <Fragment>
            <Button onClick={() => setIsLogin(true)}>Sign in</Button>

            THIS IS THE LOGIN MODAL THAT APPEARS RIGHT AFTER LOGOUT
            <Login isOpen={isLogin} onClose={() => setIsLogin(false)} />
            isLogin variable is never true.

        </Fragment>
    )
}
</code>```

(removed code for better readibility)
Login:

```<code>export default function Login({ isOpen = false, onClose, forwardto }:
{
isOpen: boolean,
onClose: () => void,
forwardto?: string
}) {

    return{(
        <Modal
            isOpen={isOpen}
            onClose={() => {
                onClose()
            }}
        >
            <ModalOverlay />
            <ModalContent>
                ...doesnt affect result
            </ModalContent>
        </Modal>
    )}
</code>```

Title: React Chakra UI Modal bug

Body:
I'm developing in ReactTS in VS Code.
In the navbar there is a menu in which there is a logut button.
when clicked user logged out etc. but at the end the sign in modal appears and I cant figure out why.
The sign in button doesn't trigger neither does the variable turns true which controls the sign in modal.
I fixed it by setting isLogin to false but it never had turned to true anyway.

Menu Component:

export default function UserMenu() {

    const navigate = useNavigate();
    const user = useAppSelector(state => state.auth.user);
    const dispatch = useAppDispatch();
    const [isLogin, setIsLogin] = useState(false);

    if (user) return (
        <Menu>
            <MenuButton>
                Account
            </MenuButton>
            <MenuList>
                <MenuGroup title={user.name}>
                    <MenuItem onClick={() => {
                        dispatch(logout());
                        dispatch(setMovie(null));
                        navigate("/");
                        //Login bug
                        Had to set this here so it works but don't know why
                        setIsLogin(false);

                    }} >Logout</MenuItem>
                </MenuGroup>
            </MenuList >
        </Menu >
    )
    else return (
        <Fragment>
            <Button onClick={() => setIsLogin(true)}>Sign in</Button>

            THIS IS THE LOGIN MODAL THAT APPEARS RIGHT AFTER LOGOUT
            <Login isOpen={isLogin} onClose={() => setIsLogin(false)} />
            isLogin variable is never true.

        </Fragment>
    )
}

(removed code for better readibility)
Login:

export default function Login({ isOpen = false, onClose, forwardto }:
{
isOpen: boolean,
onClose: () => void,
forwardto?: string
}) {

    return{(
        <Modal
            isOpen={isOpen}
            onClose={() => {
                onClose()
            }}
        >
            <ModalOverlay />
            <ModalContent>
                ...doesnt affect result
            </ModalContent>
        </Modal>
    )}


问:
How do I update a variable within string interpolation in JavaScript?
I have a global variable data_year in a file called energy-maps.globals.v0.js

```<code>/**
 * @type {number}
 * @description The year value to determine data loaded by the application.
 */
var data_year = 2012;
</code>```

data_year is used to modify a portion of an API url in order to switch the API endpoint to load data to the application. An example, from a file energy-maps.funcs.plants.v0.js:

```<code>let coal_plants = new PowerPlant('coal-plants', 'Coal plants', 1_092_000_000_000, 'electricity-generation', [{
  draw_layer: draw_coal_plants,
  src: [`${API_URL_PREFIX}/${data_year}/power_plants/coal`],
  d3_fetch: d3.json,
}], 'COAL', 'rgba(0, 0, 0, .5)', plant_stroke);
</code>```

API_URL_PREFIX is defined in energy-maps.globals.v0.js:

```<code>const API_URL_PREFIX = 'http://127.0.0.1:5000/api/v0.1.0/infrastructure'
</code>```

The src property of coal_plants is being called in a function called load_layer_data in a file energy-maps.init.builder.v1.js, where src is passed as an argument to d3.json():

```<code>/**
   * @description Call all draw methods for a given layer and render it
   * to its canvas element. Uses a recursive call in special cases.
   * @param {Object} lyr - An object from layers[].
   * @memberof Init
   */

    const load_layer_data = function load_layer_data(lyr) {
      for (let i = 0, num_draw_props = lyr.draw_props.length; i < num_draw_props; ++i) {
          start_loading_layer();
          Promise.all(lyr.draw_props[i].src.map(x => lyr.draw_props[i].d3_fetch(x)))
            .then(function(files) {
              lyr.context.restore();
              lyr.context.save();
              return files;
            }).then(files => {
              transform_layer(lyr.context, transform);
              return files
            }).then(files => {
              console.time('draw_layer')
              lyr.draw_props[i].draw_layer(lyr.context, files);
              console.timeEnd('draw_layer')
              console.log(lyr.draw_props[i].src)
            });

    }
  };
</code>```

data_year is modified in energy-maps.init.builder.v1.js when attached to a click handler for a button that should change its value.

```<code>let create_year_button = function create_year_button(btn_val, year_val) {
    let btn = document.createElement("button");
    btn.innerHTML = `${btn_val} Data`;
    document.getElementsByClassName('map-options-header')[0].appendChild(btn);
    btn.classList.add('btn-year');
    btn.addEventListener('click', function() {
      btn_val = btn_val;
      data_year = btn_val
      console.log(data_year)
      document.getElementById("value-year")
        .innerHTML = `out of ${year_val} in ${btn_val}`;
    })
  }

  create_year_button(2022, "$9.8T");
  create_year_button(2012, "$9.8T");
</code>```

When you click the button, the console will log the value of the button appropriately. When set to 2012, the API url is logged to the console as expected: ['http://127.0.0.1:5000/api/v0.1.0/infrastructure/2012/power_plants/coal']

But when data_year is changed to 2022, the API url remains unchanged: ['http://127.0.0.1:5000/api/v0.1.0/infrastructure/2012/power_plants/coal']

I read this post and tried to modify my code as follows in energy-maps.funcs.plants.v0.js, recognizing that string interpolation is not updated unless you declare it as a function:

```<code>const apiUrl = () => {
    `${API_URL_PREFIX}/${data_year}/power_plants/coal`
  }

const url = apiUrl()

let coal_plants = new PowerPlant('coal-plants', 'Coal plants', 681_740_400_000, 'electricity-generation', [{
  draw_layer: draw_coal_plants,
  src: [url],
  d3_fetch: d3.json,
}], 'coal', 'rgba(0, 0, 0, .5)', plant_stroke);
</code>```

And now when I load the data from the front end I get the following error:
GET http://127.0.0.1:3000/undefined 404 (NOT FOUND), with the application seemingly breaking at this line from energy-maps.init.builder.v1.js:

```<code>Promise.all(lyr.draw_props[i].src.map(x => lyr.draw_props[i].d3_fetch(x)))
</code>```

From here I can't really tell what's going on. Any advice on how to properly update data_year across these files and have it render appropriately in my string interpolation?

Body:
I have a global variable data_year in a file called energy-maps.globals.v0.js

/**
 * @type {number}
 * @description The year value to determine data loaded by the application.
 */
var data_year = 2012;

data_year is used to modify a portion of an API url in order to switch the API endpoint to load data to the application. An example, from a file energy-maps.funcs.plants.v0.js:

let coal_plants = new PowerPlant('coal-plants', 'Coal plants', 1_092_000_000_000, 'electricity-generation', [{
  draw_layer: draw_coal_plants,
  src: [`${API_URL_PREFIX}/${data_year}/power_plants/coal`],
  d3_fetch: d3.json,
}], 'COAL', 'rgba(0, 0, 0, .5)', plant_stroke);

API_URL_PREFIX is defined in energy-maps.globals.v0.js:

const API_URL_PREFIX = 'http://127.0.0.1:5000/api/v0.1.0/infrastructure'

The src property of coal_plants is being called in a function called load_layer_data in a file energy-maps.init.builder.v1.js, where src is passed as an argument to d3.json():

/**
   * @description Call all draw methods for a given layer and render it
   * to its canvas element. Uses a recursive call in special cases.
   * @param {Object} lyr - An object from layers[].
   * @memberof Init
   */

    const load_layer_data = function load_layer_data(lyr) {
      for (let i = 0, num_draw_props = lyr.draw_props.length; i < num_draw_props; ++i) {
          start_loading_layer();
          Promise.all(lyr.draw_props[i].src.map(x => lyr.draw_props[i].d3_fetch(x)))
            .then(function(files) {
              lyr.context.restore();
              lyr.context.save();
              return files;
            }).then(files => {
              transform_layer(lyr.context, transform);
              return files
            }).then(files => {
              console.time('draw_layer')
              lyr.draw_props[i].draw_layer(lyr.context, files);
              console.timeEnd('draw_layer')
              console.log(lyr.draw_props[i].src)
            });

    }
  };

data_year is modified in energy-maps.init.builder.v1.js when attached to a click handler for a button that should change its value.

let create_year_button = function create_year_button(btn_val, year_val) {
    let btn = document.createElement("button");
    btn.innerHTML = `${btn_val} Data`;
    document.getElementsByClassName('map-options-header')[0].appendChild(btn);
    btn.classList.add('btn-year');
    btn.addEventListener('click', function() {
      btn_val = btn_val;
      data_year = btn_val
      console.log(data_year)
      document.getElementById("value-year")
        .innerHTML = `out of ${year_val} in ${btn_val}`;
    })
  }

  create_year_button(2022, "$9.8T");
  create_year_button(2012, "$9.8T");

When you click the button, the console will log the value of the button appropriately. When set to 2012, the API url is logged to the console as expected: ['http://127.0.0.1:5000/api/v0.1.0/infrastructure/2012/power_plants/coal']

But when data_year is changed to 2022, the API url remains unchanged: ['http://127.0.0.1:5000/api/v0.1.0/infrastructure/2012/power_plants/coal']

I read this post and tried to modify my code as follows in energy-maps.funcs.plants.v0.js, recognizing that string interpolation is not updated unless you declare it as a function:

const apiUrl = () => {
    `${API_URL_PREFIX}/${data_year}/power_plants/coal`
  }

const url = apiUrl()

let coal_plants = new PowerPlant('coal-plants', 'Coal plants', 681_740_400_000, 'electricity-generation', [{
  draw_layer: draw_coal_plants,
  src: [url],
  d3_fetch: d3.json,
}], 'coal', 'rgba(0, 0, 0, .5)', plant_stroke);

And now when I load the data from the front end I get the following error:
GET http://127.0.0.1:3000/undefined 404 (NOT FOUND), with the application seemingly breaking at this line from energy-maps.init.builder.v1.js:

Promise.all(lyr.draw_props[i].src.map(x => lyr.draw_props[i].d3_fetch(x)))

From here I can't really tell what's going on. Any advice on how to properly update data_year across these files and have it render appropriately in my string interpolation?


问:
Plesk reports that updates were not installed for the following items
I received this message yesterday on email from Plesk and there are a lot of items listed.
It appears to be to do largely with Wordpress Toolkit on the server. Plesk is the interface I use on my Ionos Hosted Server.

Sites are working from the server ok but obviously updates will not happen whilst these errors are present.
Does anyone have a clue what could be causing this and how to fix it please.

Thanks

Website "eeeSafe Community Safety Sustainability and Skills" (https://eeesafe.com): PHP Fatal error: Uncaught TypeError: date(): Argument #2 ($timestamp) must be of type ?int, string given in /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/cron-command/src/Cron_Event_Command.php:418
Stack trace:
#0 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/cron-command/src/Cron_Event_Command.php(418): date()
#1 [internal function]: Cron_Event_Command::format_event()
#2 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/cron-command/src/Cron_Event_Command.php(460): array_map()
#3 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/cron-command/src/Cron_Event_Command.php(366): Cron_Event_Command::get_cron_events()
#4 [internal function]: Cron_Event_Command->delete()
#5 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/WP_CLI/Dispatcher/CommandFactory.php(100): call_user_func()
#6 [internal function]: WP_CLI\Dispatcher\CommandFactory::WP_CLI\Dispatcher{closure}()
#7 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/WP_CLI/Dispatcher/Subcommand.php(491): call_user_func()
#8 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/WP_CLI/Runner.php(419): WP_CLI\Dispatcher\Subcommand->invoke()
#9 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/class-wp-cli.php(1443): WP_CLI\Runner->run_command()
#10 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/plesk/wp-cli-toolkit-command/src/Wpt_Cron_Command.php(30): WP_CLI::run_command()
#11 [internal function]: Wpt_Cron_Command->reschedule()
#12 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/WP_CLI/Dispatcher/CommandFactory.php(100): call_user_func()
#13 [internal function]: WP_CLI\Dispatcher\CommandFactory::WP_CLI\Dispatcher{closure}()
#14 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/WP_CLI/Dispatcher/Subcommand.php(491): call_user_func()
#15 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/WP_CLI/Runner.php(419): WP_CLI\Dispatcher\Subcommand->invoke()
#16 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/WP_CLI/Runner.php(442): WP_CLI\Runner->run_command()
#17 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/WP_CLI/Runner.php(1276): WP_CLI\Runner->run_command_and_exit()
#18 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/LaunchRunner.php(28): WP_CLI\Runner->start()
#19 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/bootstrap.php(78): WP_CLI\Bootstrap\LaunchRunner->process()
#20 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/wp-cli.php(32): WP_CLI\bootstrap()
#21 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/boot-fs.php(17): require_once('...')
#22 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/wpt-wp-cli.php(31): require_once('...')
#23 {main}
thrown in /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/cron-command/src/Cron_Event_Command.php on line 418
Fatal error: Uncaught TypeError: date(): Argument #2 ($timestamp) must be of type ?int, string given in /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/cron-command/src/Cron_Event_Command.php:418
Stack trace:
#0 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/cron-command/src/Cron_Event_Command.php(418): date()
#1 [internal function]: Cron_Event_Command::format_event()
#2 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/cron-command/src/Cron_Event_Command.php(460): array_map()
#3 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/cron-command/src/Cron_Event_Command.php(366): Cron_Event_Command::get_cron_events()
#4 [internal function]: Cron_Event_Command->delete()
#5 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/WP_CLI/Dispatcher/CommandFactory.php(100): call_user_func()
#6 [internal function]: WP_CLI\Dispatcher\CommandFactory::WP_CLI\Dispatcher{closure}()
#7 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/WP_CLI/Dispatcher/Subcommand.php(491): call_user_func()
#8 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/WP_CLI/Runner.php(419): WP_CLI\Dispatcher\Subcommand->invoke()
#9 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/class-wp-cli.php(1443): WP_CLI\Runner->run_command()
#10 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/plesk/wp-cli-toolkit-command/src/Wpt_Cron_Command.php(30): WP_CLI::run_command()
#11 [internal function]: Wpt_Cron_Command->reschedule()
#12 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/WP_CLI/Dispatcher/CommandFactory.php(100): call_user_func()
#13 [internal function]: WP_CLI\Dispatcher\CommandFactory::WP_CLI\Dispatcher{closure}()
#14 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/WP_CLI/Dispatcher/Subcommand.php(491): call_user_func()
#15 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/WP_CLI/Runner.php(419): WP_CLI\Dispatcher\Subcommand->invoke()
#16 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/WP_CLI/Runner.php(442): WP_CLI\Runner->run_command()
#17 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/WP_CLI/Runner.php(1276): WP_CLI\Runner->run_command_and_exit()
#18 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/WP_CLI/Bootstrap/LaunchRunner.php(28): WP_CLI\Runner->start()
#19 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/bootstrap.php(78): WP_CLI\Bootstrap\LaunchRunner->process()
#20 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/wp-cli.php(32): WP_CLI\bootstrap()
#21 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/wp-cli/php/boot-fs.php(17): require_once('...')
#22 /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/wpt-wp-cli.php(31): require_once('...')
#23 {main}
thrown in /usr/local/psa/admin/plib/modules/wp-toolkit/vendor/wp-cli/vendor/wp-cli/cron-command/src/Cron_Event_Command.php on line 418
Error: There has been a critical error on this website.Learn more about troubleshooting WordPress. There has been a critical error on this website.

I thought it might be something to do with enablin mysqli on my server, where Plesk Web Pro is being used.
I can't find how to do that, but not convinced yet that this might be the answer.


问:
How to override request limit for AWS RDS Wait command?
I created a DB Cluster from snapshot and did wait command and got exceeded attempts

so I"m trying to create a script

```<code>DB_CLUSTER_IDENTIFIER=${1}
DB_CLUSTER_STATUS=$(aws rds describe-db-clusters --db-cluster-identifier "$DB_CLUSTER_IDENTIFIER" --query 'DBClusters[*].Status' --output text)

while [ "$DB_CLUSTER_STATUS" != "available" ]; do
  echo "DB cluster is not available"
  sleep 5
  DB_CLUSTER_STATUS=$(aws rds describe-db-clusters --db-cluster-identifier "$DB_CLUSTER_IDENTIFIER" --query 'DBClusters[*].Status' --output text)
done

aws rds wait db-cluster-available --db-cluster-identifier "$DB_CLUSTER_IDENTIFIER"
</code>```

i'm scared DB_CLUSTER_STATUS != "available" is invalid

How does one override the request limit?

Body:
I created a DB Cluster from snapshot and did wait command and got exceeded attempts

so I"m trying to create a script

DB_CLUSTER_IDENTIFIER=${1}
DB_CLUSTER_STATUS=$(aws rds describe-db-clusters --db-cluster-identifier "$DB_CLUSTER_IDENTIFIER" --query 'DBClusters[*].Status' --output text)

while [ "$DB_CLUSTER_STATUS" != "available" ]; do
  echo "DB cluster is not available"
  sleep 5
  DB_CLUSTER_STATUS=$(aws rds describe-db-clusters --db-cluster-identifier "$DB_CLUSTER_IDENTIFIER" --query 'DBClusters[*].Status' --output text)
done

aws rds wait db-cluster-available --db-cluster-identifier "$DB_CLUSTER_IDENTIFIER"

i'm scared DB_CLUSTER_STATUS != "available" is invalid

How does one override the request limit?


问:
Make Enter insert a newline when the autocomplete word is fully typed
In VSCode, when I type C# code like else, then I press Enter to go to the next line and type the { of the following block. But no new line is inserted. Instead, that autocomplete suggestions dropdown is closed and nothing else happens. I wasn't even looking at the screen and didn't care about that completion suggestion thing here. I just wanted to type some code and a part of it was ignored unexpectedly.

How can I stop this? When I press Enter after already fully typing the first suggestion, I want the Enter key to do its job, which is primarily insert a line break.

In Visual Studio there's an option for that but I couldn't find one in VSCode.