问:
cannot get a response from reddit trying to log in
I'm trying to create a program to log into reddit and do some actions for me, reddit requires:

CSRF, OTP, PASS, DEST, USER

when sending the post request and I am definitely filling all of these with the right data but for some reason I cannot get a response from reddit, the program crashes

`

```<code>using System;
using System.Net.Http;
using System.Collections.Generic;
// Set up the HTTP client
static string getBetween(string strSource, string strStart, string strEnd)
{
    if (strSource.Contains(strStart) && strSource.Contains(strEnd))
    {
        int Start, End;
        Start = strSource.IndexOf(strStart, 0) + strStart.Length;
        End = strSource.IndexOf(strEnd, Start);
        return strSource.Substring(Start, End - Start);
    }

    return "";
}

var client = new HttpClient();
client.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0");
client.DefaultRequestHeaders.Add("Pragma", "no-cache");
client.DefaultRequestHeaders.Add("Accept", "*/*");
client.DefaultRequestHeaders.Add("Referer", "https://www.google.com");
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
//client.DefaultRequestHeaders.Add("Content-Type", "application/x-www-form-urlencoded");
client.BaseAddress = new Uri("https://www.reddit.com/");
string csrf = "FAIL";
using (var response = client.GetAsync("https://www.reddit.com/login").Result)
{
    if (response.IsSuccessStatusCode)
    {
        csrf = getBetween(response.Content.ReadAsStringAsync().Result, "csrf_token\" value=\"", "\"");
    }
}
Console.WriteLine(csrf);
// Set up the login form data
var formData = new Dictionary<string, string>
            {
                { "csrf_token", csrf},
                { "otp", "" },
                { "password", "XXXX" },
                { "dest", "https://reddit.com/" },
                { "username", "XXXX" }
            };

// Post the login form
var response4 = await client.PostAsync("https://www.reddit.com/login/", new FormUrlEncodedContent(formData));

// Check the response status code
//if (response.IsSuccessStatusCode)
//{
//    Console.WriteLine("Login successful!");
//}
//else
//{
//    Console.WriteLine("Login failed!");
//}

</code>```

`

and it seems reddit just doesn't give a response, my program immediately crashes.
anyone could give me some insight maybe? thank you

I tried changing it up and playing a bit with the headers to no avail

Body:
I'm trying to create a program to log into reddit and do some actions for me, reddit requires:

CSRF, OTP, PASS, DEST, USER

when sending the post request and I am definitely filling all of these with the right data but for some reason I cannot get a response from reddit, the program crashes

`

using System;
using System.Net.Http;
using System.Collections.Generic;
// Set up the HTTP client
static string getBetween(string strSource, string strStart, string strEnd)
{
    if (strSource.Contains(strStart) && strSource.Contains(strEnd))
    {
        int Start, End;
        Start = strSource.IndexOf(strStart, 0) + strStart.Length;
        End = strSource.IndexOf(strEnd, Start);
        return strSource.Substring(Start, End - Start);
    }

    return "";
}

var client = new HttpClient();
client.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0");
client.DefaultRequestHeaders.Add("Pragma", "no-cache");
client.DefaultRequestHeaders.Add("Accept", "*/*");
client.DefaultRequestHeaders.Add("Referer", "https://www.google.com");
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
//client.DefaultRequestHeaders.Add("Content-Type", "application/x-www-form-urlencoded");
client.BaseAddress = new Uri("https://www.reddit.com/");
string csrf = "FAIL";
using (var response = client.GetAsync("https://www.reddit.com/login").Result)
{
    if (response.IsSuccessStatusCode)
    {
        csrf = getBetween(response.Content.ReadAsStringAsync().Result, "csrf_token\" value=\"", "\"");
    }
}
Console.WriteLine(csrf);
// Set up the login form data
var formData = new Dictionary<string, string>
            {
                { "csrf_token", csrf},
                { "otp", "" },
                { "password", "XXXX" },
                { "dest", "https://reddit.com/" },
                { "username", "XXXX" }
            };

// Post the login form
var response4 = await client.PostAsync("https://www.reddit.com/login/", new FormUrlEncodedContent(formData));

// Check the response status code
//if (response.IsSuccessStatusCode)
//{
//    Console.WriteLine("Login successful!");
//}
//else
//{
//    Console.WriteLine("Login failed!");
//}

`

and it seems reddit just doesn't give a response, my program immediately crashes.
anyone could give me some insight maybe? thank you

I tried changing it up and playing a bit with the headers to no avail


来源: stackexchange

问:
ASP.NET MVC 5 : get value from web.config to a controllers methode with [Authorize(Users = ADUser)]
How can I get a value from the ASP.NET MVC 5 web.config into a controller method?

At first I put the value into a string and that works:

```<code>public const string ADUser = System.Configuration.ConfigurationManager.AppSettings["ADUser"].ToString();
</code>```

There are many examples on Stackoverflow with

```<code>public const string
</code>```

but in my case it doesn't work.

```<code>[Authorize(Users = ADUser)]
public ViewResult Index()
{
    var user = db.user
                 .Where(m => m.Id != 0)
                 .ToList();

    return View(user);
}
</code>```

Here is the exception. It belong to the [Authorize(Users = ADUser)]

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type enum Description

Does anybody have any idea?

ContentLicense: CC BY-SA 4.0

Body:
How can I get a value from the ASP.NET MVC 5 web.config into a controller method?

At first I put the value into a string and that works:

public const string ADUser = System.Configuration.ConfigurationManager.AppSettings["ADUser"].ToString();

There are many examples on Stackoverflow with

public const string

but in my case it doesn't work.

[Authorize(Users = ADUser)]
public ViewResult Index()
{
    var user = db.user
                 .Where(m => m.Id != 0)
                 .ToList();

    return View(user);
}

Here is the exception. It belong to the [Authorize(Users = ADUser)]

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type enum Description

Does anybody have any idea?


问:
How to play a video with any flutter video players, where the video url is CDN signed from cloudfront
I want to play videos from a given url, but the url is CDN signed from cloudfront. As the video player expects a url with mp4 extension. Currently I'm using video_player: ^2.1.12.

One stackoverflow answer was to use flutter_playout but the package kept breaking


问:
How to dynamic this part (Features or Pricing) for my WordPress Custom theme Development
```<code><!-- Features Start -->
    <div class="container-fluid py-5 wow fadeInUp" data-wow-delay="0.1s">
        <div class="container py-5">
            <div class="section-title text-center position-relative pb-3 mb-5 mx-auto" style="max-width: 600px;">
                <h5 class="fw-bold text-primary text-uppercase">Why Choose Us</h5>
                <h1 class="mb-0">We Are Here to Grow Your Business Exponentially</h1>
            </div>
            <div class="row g-5">
                <div class="col-lg-4">
                    <div class="row g-5">
                        <div class="col-12 wow zoomIn" data-wow-delay="0.2s">
                            <div class="bg-primary rounded d-flex align-items-center justify-content-center mb-3" style="width: 60px; height: 60px;">
                                <i class="fa fa-cubes text-white"></i>
                            </div>
                            <h4>Best In Industry</h4>
                            <p class="mb-0">Magna sea eos sit dolor, ipsum amet lorem diam dolor eos et diam dolor</p>
                        </div>
                        <div class="col-12 wow zoomIn" data-wow-delay="0.6s">
                            <div class="bg-primary rounded d-flex align-items-center justify-content-center mb-3" style="width: 60px; height: 60px;">
                                <i class="fa fa-award text-white"></i>
                            </div>
                            <h4>Award Winning</h4>
                            <p class="mb-0">Magna sea eos sit dolor, ipsum amet lorem diam dolor eos et diam dolor</p>
                        </div>
                    </div>
                </div>

                <div class="col-lg-4  wow zoomIn" data-wow-delay="0.9s" style="min-height: 350px;">
                    <div class="position-relative h-100">
                        <img class="position-absolute w-100 h-100 rounded wow zoomIn" data-wow-delay="0.1s" src="img/feature.jpg" style="object-fit: cover;">
                    </div>
                </div>

                <div class="col-lg-4">
                    <div class="row g-5">
                        <div class="col-12 wow zoomIn" data-wow-delay="0.4s">
                            <div class="bg-primary rounded d-flex align-items-center justify-content-center mb-3" style="width: 60px; height: 60px;">
                                <i class="fa fa-users-cog text-white"></i>
                            </div>
                            <h4>Professional Staff</h4>
                            <p class="mb-0">Magna sea eos sit dolor, ipsum amet lorem diam dolor eos et diam dolor</p>
                        </div>
                        <div class="col-12 wow zoomIn" data-wow-delay="0.8s">
                            <div class="bg-primary rounded d-flex align-items-center justify-content-center mb-3" style="width: 60px; height: 60px;">
                                <i class="fa fa-phone-alt text-white"></i>
                            </div>
                            <h4>24/7 Support</h4>
                            <p class="mb-0">Magna sea eos sit dolor, ipsum amet lorem diam dolor eos et diam dolor</p>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>
    <!-- Features Start -->
</code>```
```<code>    <!-- Pricing Plan Start -->
    <div class="container-fluid py-5 wow fadeInUp" data-wow-delay="0.1s">
        <div class="container py-5">
            <div class="section-title text-center position-relative pb-3 mb-5 mx-auto" style="max-width: 600px;">
                <h5 class="fw-bold text-primary text-uppercase">Pricing Plans</h5>
                <h1 class="mb-0">We are Offering Competitive Prices for Our Clients</h1>
            </div>
            <div class="row g-0">
                <div class="col-lg-4 wow slideInUp" data-wow-delay="0.6s">
                    <div class="bg-light rounded">
                        <div class="border-bottom py-4 px-5 mb-4">
                            <h4 class="text-primary mb-1">Basic Plan</h4>
                            <small class="text-uppercase">For Small Size Business</small>
                        </div>
                        <div class="p-5 pt-0">
                            <h1 class="display-5 mb-3">
                                <small class="align-top" style="font-size: 22px; line-height: 45px;">$</small>49.00<small
                                    class="align-bottom" style="font-size: 16px; line-height: 40px;">/ Month</small>
                            </h1>
                            <div class="d-flex justify-content-between mb-3"><span>HTML5 & CSS3</span><i class="fa fa-check text-primary pt-1"></i></div>
                            <div class="d-flex justify-content-between mb-3"><span>Bootstrap v5</span><i class="fa fa-check text-primary pt-1"></i></div>
                            <div class="d-flex justify-content-between mb-3"><span>Responsive Layout</span><i class="fa fa-times text-danger pt-1"></i></div>
                            <div class="d-flex justify-content-between mb-2"><span>Cross-browser Support</span><i class="fa fa-times text-danger pt-1"></i></div>
                            <a href="" class="btn btn-primary py-2 px-4 mt-4">Order Now</a>
                        </div>
                    </div>
                </div>
                <div class="col-lg-4 wow slideInUp" data-wow-delay="0.3s">
                    <div class="bg-white rounded shadow position-relative" style="z-index: 1;">
                        <div class="border-bottom py-4 px-5 mb-4">
                            <h4 class="text-primary mb-1">Standard Plan</h4>
                            <small class="text-uppercase">For Medium Size Business</small>
                        </div>
                        <div class="p-5 pt-0">
                            <h1 class="display-5 mb-3">
                                <small class="align-top" style="font-size: 22px; line-height: 45px;">$</small>99.00<small
                                    class="align-bottom" style="font-size: 16px; line-height: 40px;">/ Month</small>
                            </h1>
                            <div class="d-flex justify-content-between mb-3"><span>HTML5 & CSS3</span><i class="fa fa-check text-primary pt-1"></i></div>
                            <div class="d-flex justify-content-between mb-3"><span>Bootstrap v5</span><i class="fa fa-check text-primary pt-1"></i></div>
                            <div class="d-flex justify-content-between mb-3"><span>Responsive Layout</span><i class="fa fa-check text-primary pt-1"></i></div>
                            <div class="d-flex justify-content-between mb-2"><span>Cross-browser Support</span><i class="fa fa-times text-danger pt-1"></i></div>
                            <a href="" class="btn btn-primary py-2 px-4 mt-4">Order Now</a>
                        </div>
                    </div>
                </div>
                <div class="col-lg-4 wow slideInUp" data-wow-delay="0.9s">
                    <div class="bg-light rounded">
                        <div class="border-bottom py-4 px-5 mb-4">
                            <h4 class="text-primary mb-1">Advanced Plan</h4>
                            <small class="text-uppercase">For Large Size Business</small>
                        </div>
                        <div class="p-5 pt-0">
                            <h1 class="display-5 mb-3">
                                <small class="align-top" style="font-size: 22px; line-height: 45px;">$</small>149.00<small
                                    class="align-bottom" style="font-size: 16px; line-height: 40px;">/ Month</small>
                            </h1>
                            <div class="d-flex justify-content-between mb-3"><span>HTML5 & CSS3</span><i class="fa fa-check text-primary pt-1"></i></div>
                            <div class="d-flex justify-content-between mb-3"><span>Bootstrap v5</span><i class="fa fa-check text-primary pt-1"></i></div>
                            <div class="d-flex justify-content-between mb-3"><span>Responsive Layout</span><i class="fa fa-check text-primary pt-1"></i></div>
                            <div class="d-flex justify-content-between mb-2"><span>Cross-browser Support</span><i class="fa fa-check text-primary pt-1"></i></div>
                            <a href="" class="btn btn-primary py-2 px-4 mt-4">Order Now</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- Pricing Plan End -->
</code>```

I am trying to develop a Custom WordPress theme.

How to dynamic this part? Here three col-lg-4 but I want to keep one Col-lg-4. I am trying to develop this part using acf pro and writing in the code editor while loop but it is nothig to show. besides, the Pricing section is also my problem, I can't dynamic this section using  ACF PRO. Please help me to solve this problem.
Thanks.

Body:
Why Choose Us

We Are Here to Grow Your Business Exponentially

Best In Industry

Magna sea eos sit dolor, ipsum amet lorem diam dolor eos et diam dolor

Award Winning

Magna sea eos sit dolor, ipsum amet lorem diam dolor eos et diam dolor

Professional Staff

Magna sea eos sit dolor, ipsum amet lorem diam dolor eos et diam dolor

24/7 Support

Magna sea eos sit dolor, ipsum amet lorem diam dolor eos et diam dolor

Pricing Plans

We are Offering Competitive Prices for Our Clients

Basic Plan

                            For Small Size Business

                                $49.00/ Month

HTML5 & CSS3

Bootstrap v5

Responsive Layout

Cross-browser Support

                            Order Now

Standard Plan

                            For Medium Size Business

                                $99.00/ Month

HTML5 & CSS3

Bootstrap v5

Responsive Layout

Cross-browser Support

                            Order Now

Advanced Plan

                            For Large Size Business

                                $149.00/ Month

HTML5 & CSS3

Bootstrap v5

Responsive Layout

Cross-browser Support

                            Order Now

I am trying to develop a Custom WordPress theme.

How to dynamic this part? Here three col-lg-4 but I want to keep one Col-lg-4. I am trying to develop this part using acf pro and writing in the code editor while loop but it is nothig to show. besides, the Pricing section is also my problem, I can't dynamic this section using  ACF PRO. Please help me to solve this problem.
Thanks.


问:
Use index and filter for query
I have a query to retrieve paginated results from a MongoDB collection that looks like

{
  query: {
    _id: {$lt: before_id}}
  },
  sort: '-_id'
  offset: 0
  limit: 20
}
```
<p>and executes in a reasonable time.</p>
<p>Then I add a filter and make a query like this</p>
<pre class="lang-js prettyprint-override"><code>{
  query: {
    _id: {$lt: before_id}},
    type: 'backend'
  },time
  sort: '-_id'
  offset: 0
  limit: 1
}
</code>```

that gives timeout.

I expected this to scan the table using the _id yielding documents in the correct order and then filtering.

The {type:'backend'} excludes very few documents so it should access about the same number of documents before finalising the query if executed the way I expected.

How this query is executed? and How to take advantage of the index and limit to get the correct result quickly, even if additional filters are specified?

Title: Use index and filter for query

Body:
I have a query to retrieve paginated results from a MongoDB collection that looks like

{
  query: {
    _id: {$lt: before_id}}
  },
  sort: '-_id'
  offset: 0
  limit: 20
}

and executes in a reasonable time.

Then I add a filter and make a query like this

{
  query: {
    _id: {$lt: before_id}},
    type: 'backend'
  },time
  sort: '-_id'
  offset: 0
  limit: 1
}

that gives timeout.

I expected this to scan the table using the _id yielding documents in the correct order and then filtering.

The {type:'backend'} excludes very few documents so it should access about the same number of documents before finalising the query if executed the way I expected.

How this query is executed? and How to take advantage of the index and limit to get the correct result quickly, even if additional filters are specified?


问:
Keep the last row of grouping by dates with the same year of a pandas dataframe
I have the following dataframe. lets call it df:

```<code>|Account  |Type   |Date        | Per   | Value|
-----------------------------------------------
|A        |FC     |31/03/2019  |3M     |a     |
|A        |FC     |30/06/2019  |3M     |b     |
|A        |FC     |30/09/2019  |3M     |c     |
|A        |FC     |31/12/2019  |3M     |d     |
|B        |P&G    |31/03/2019  |3M     |e     |
|B        |P&G    |30/06/2019  |3M     |f     |
|B        |P&G    |30/09/2019  |3M     |g     |
|B        |P&G    |31/12/2019  |3M     |h     |
</code>```

Where a,bc,d,e,f,g,h are numerical values.For each element of the account column I need to keep the last value of the column that are in the same year, according to the date column, getting something like this:

```<code>|Account  |Type   |Date        | Per   | Value  |
-------------------------------------------------
|A        |FC     |31/12/2019  |3M     |d       |
|B        |P&G    |30/12/2019  |3M     |h       |
</code>```

Where the value of the date column of the resulting dataframe corresponds to the last period that was added.

Can you guys help me?

Body:
I have the following dataframe. lets call it df:

|Account  |Type   |Date        | Per   | Value|
-----------------------------------------------
|A        |FC     |31/03/2019  |3M     |a     |
|A        |FC     |30/06/2019  |3M     |b     |
|A        |FC     |30/09/2019  |3M     |c     |
|A        |FC     |31/12/2019  |3M     |d     |
|B        |P&G    |31/03/2019  |3M     |e     |
|B        |P&G    |30/06/2019  |3M     |f     |
|B        |P&G    |30/09/2019  |3M     |g     |
|B        |P&G    |31/12/2019  |3M     |h     |

Where a,bc,d,e,f,g,h are numerical values.For each element of the account column I need to keep the last value of the column that are in the same year, according to the date column, getting something like this:

|Account  |Type   |Date        | Per   | Value  |
-------------------------------------------------
|A        |FC     |31/12/2019  |3M     |d       |
|B        |P&G    |30/12/2019  |3M     |h       |

Where the value of the date column of the resulting dataframe corresponds to the last period that was added.

Can you guys help me?


问:
pygsheets - change color of cell
I'm trying to change color of cells in my google sheet through api, and it just takes wayyyyy to long to do it (after 10 minutes of a single cell i/my laptop gave up).

```<code>google_worksheet.cell(column + str(j)).color = color_orange
</code>```

the column is 'A' 'B' ex, j is the row number, and color_orange is a tuple (1, 0.6235294117, 0, 1).

it just freeze over this line for couple of minutes untill it gives up.... (disconnect from the network).

Does someone know a better way to update cell's (/row's would be even better) color? or why doesn't it work?

Title: pygsheets - change color of cell

Body:
I'm trying to change color of cells in my google sheet through api, and it just takes wayyyyy to long to do it (after 10 minutes of a single cell i/my laptop gave up).

google_worksheet.cell(column + str(j)).color = color_orange

the column is 'A' 'B' ex, j is the row number, and color_orange is a tuple (1, 0.6235294117, 0, 1).

it just freeze over this line for couple of minutes untill it gives up.... (disconnect from the network).

Does someone know a better way to update cell's (/row's would be even better) color? or why doesn't it work?


问:
AASA - Apple App Site Association - Not working
I have been having a long and frustrating experience trying to get AASA to work for webcredentials. My goal here is to allow usernames and passwords to be stored in the iOS keychain.

I did have this working on a root domain the other week but it is not sufficient for my scenario as I will explain. It didn't work for me straight away I have to say but it eventually started working after a clean build so I thought this was the issue then but now I am not so sure.

I am using Expo with EAS build. We have a multi-tenant application. From a single codebase we deploy to multiple apps in the store. All are on the same team ID but they are separate applications and use separate credentials, nothing is shared.

I am confident my apps textContentType of username and password on my TextFields is correct as this has not changed from when I managed to get it working originally and I have checked it countless times.

Expectation

For the "Save Password" prompt to be displayed after login. What I have noticed however is when going to store a password manually using "add password" via iCloudKeychain from the keyboard accessory this does accurately show the correct "TENANT_SUBDOMAIN.example.com". I find this confusing.

Goal Scenario

I am hosting a site on Netlify. I have it setup to support wildcard subdomains with a LetsEncrypt provisioned wildcard SSL certificate. I then have edge functions which change the content of my index.html and apple-app-site-association file dynamically based on the requested subdomain.

I have added the Associated Domains capability to my provisioning profile.

I am using the latest Expo 47 and EAS build. I have added in the appropriate associated domains configuration and I can see this when introspecting my entitlements under com.apple.developer.associated-domains and it is correct.

I am using TestFlight for testing. I am doing a --clean-build on EAS every time and I also increase the runtime version. I have also tried manually refreshing credentials outside of the build process which does this automatically. This must be using the correct provisioning profile otherwise I would get a build failure as the requested entitlements wouldn't match.

The AASA file is currently hosted just in the .well-known directory. I have tried using the root and also tried using both. There are no redirects taking place.

I am aware the AASA file is pulled on application installation and update. I repeatedly remove the apps and then reboot my phone in an attempt to reset any device caches.

The content-type of the file is application/json and I have confirmed this using developer tools in the browser.

There is no robots.txt or anything blocking the request from an infrastructure perspective. There are no additional firewalls or geo restricted access as I am just using plain Netlify to host this, nothing fancy.

I am confident the Team ID and bundle IDs are correct in the AASA file.

I remove the content-length header in the Edge function so it is correctly calculated by the network instead and I have confirmed this using curl.

When I check the file using https://app-site-association.cdn-apple.com/a/v1/site.example.com Apple has the correct file cached on it's CDN so I would expect it to work.

I added in an applinks section so I could use the Apple App Search API validation tool and the Branch.io AASA verification tool to verify correctness. Branch.io says the file is fine and Apple says it's fine also but because the App has not been deployed to the store yet I see Error no apps with domain entitlements. From what I can tell this is normal in development and makes sense as it uses the current released version of the app to verify the deep link configuration. So to me this means Apple can parse the file correctly.

When I stream my device console logs; on install I can see the AASA requesting the correct domains. I see no errors on swcd I just see the Beginning data task AASA-XXXX with the correct domains.

When I run Charles proxy on my phone with a verified SSL installation (also reinstalled a few times now) I do not see quite what I would expect - but the device logs seem to imply it is doing the correct thing. When I view the app-site-association... URL requests in Charles there is one per application install which is correct. The request is marked as Unknown and when I look at the request the host is shown but as you would expect from SSL I see no path. The info says METHOD: CONNECT with Error - Input Error: EOF. This is the only error I see, I am not sure if it is a red herring and something to do with Charles. Given the error as you expect there is no body in the request or response. It is worth noting in general testing I have no VPN enabled and I have do not have Private Relay enabled in my iOS settings.

When I perform a sysdiagnose I see the following at the timestamp in my console log in the swcutil_show.txt device log. This looks correct in comparison to other apps webcredentials and applinks services I see there and I see no errors:

```<code>Service:              webcredentials
App ID:               MYTEAMID.com.cf.example.b2c.ios
App Version:          1.0
App PI:               <LSPersistentIdentifier 0x141816200> { v = 0, t = 0x8, u = 0x1e7c, db = 0094F7C4-3078-41A2-A33E-79D5A62C80A6, {length = 8, bytes = 0x7c1e000000000000} }
Domain:               CORRECT_SUBDOMAIN.example.app
User Approval:        unspecified
Site/Fmwk Approval:   approved
Flags:
Last Checked:         2022-12-09 14:14:32 +0000
Next Check:           2022-12-14 14:03:00 +0000

Service:              applinks
App ID:               MYTEAMID.com.cf.example.b2c.ios
App Version:          1.0
App PI:               <LSPersistentIdentifier 0x13fd38d00> { v = 0, t = 0x8, u = 0x219c, db = 0094F7C4-3078-41A2-A33E-79D5A62C80A6, {length = 8, bytes = 0x9c21000000000000} }
Domain:               CORRECT_SUBDOMAIN.example.app
Patterns:             {"/":"*"}
User Approval:        unspecified
Site/Fmwk Approval:   approved
Flags:
Last Checked:         2022-12-13 13:13:23 +0000
Next Check:           2022-12-18 13:01:51 + 0000

At end of file:

MYTEAMID.com.cf.example.b2c.ios: 8 bytes

(This seems correct for all apps)

</code>```

Other Scenario

I have tried setting this up using an apex on another domain which hasn't been seen before by Apple. I have tried using a subdomain with a root domain serving the same content and I have tried the subdomain and root domain on their own. I have also tried not using the Edge functions and having static files but to no avail.

When I do this I ensure I wait for the Apple CDN to catch up and remove/add entries prior to deleting the apps, rebooting my device, and reinstalling to test.

AASA File

AASA content comes back with the correct payload and Content-Type: application/json and Content-Length headers, both from Apples CDN and the origin. When I had this somehow working in my initial test it was on a root domain and I did not have an applinks section, this was only added so I could use the verification tools for universal links.

I am not sending back different content or duplicated content and I block the www subdomain - I have also tried it with a www subdomain for the record.

```<code>{
  "applinks": {
    "details": [
      {
        "appIDs": [
          "MYTEAMID.com.cf.example.b2c.ios"
        ],
        "components": [
          {
            "#": "no_universal_links",
            "exclude": true,
            "comment": "Matches any URL with a fragment that equals no_universal_links and instructs the system not to open it as a universal link."
          }
        ]
      }
    ]
  },
  "webcredentials": {
    "apps": [
      "MYTEAMID.com.cf.example.b2c.ios"
    ]
  }
}

</code>```

I have also tried this with the older format:

```<code>{
  "applinks": {
    "apps": [],
    "details": [
      {
        "appID": "MYTEAMID.com.cf.example.b2c.ios",
        "paths": [
          "*"
        ]
      }
    ]
  },
  "webcredentials": {
    "apps": [
      "MYTEAMID.com.cf.example.b2c.ios"
    ]
  }
}
</code>```

associatedDomains iOS. expo config

```<code>associatedDomains: [
  `webcredentials:${SUBDOMAIN}.example.app`,
  `applinks:${SUBDOMAIN}.example.app`,
],
</code>```

Help :)

I have been trying to get this to work for a long time now and I am completely out of ideas. If anybody has any suggestions I would really appreciate it. I am very confused how the devices request seems correct and the CDN content is correct but it is still not working. It's worth also reiterating that I need to have different subdomains for each tenant as the credentials must not be shared across apps so the keychain->domain association store must be different.

I am wondering if it's the LetsEncrypt wildcard SSL certificate but I wouldn't expect it to verify and for Apple to cache the file if this was the case. It seems very unlikely to me but it is the only thing I haven't tried at this point.

Many Thanks,

Mark

Body:
I have been having a long and frustrating experience trying to get AASA to work for webcredentials. My goal here is to allow usernames and passwords to be stored in the iOS keychain.

I did have this working on a root domain the other week but it is not sufficient for my scenario as I will explain. It didn't work for me straight away I have to say but it eventually started working after a clean build so I thought this was the issue then but now I am not so sure.

I am using Expo with EAS build. We have a multi-tenant application. From a single codebase we deploy to multiple apps in the store. All are on the same team ID but they are separate applications and use separate credentials, nothing is shared.

I am confident my apps textContentType of username and password on my TextFields is correct as this has not changed from when I managed to get it working originally and I have checked it countless times.

Expectation

For the "Save Password" prompt to be displayed after login. What I have noticed however is when going to store a password manually using "add password" via iCloudKeychain from the keyboard accessory this does accurately show the correct "TENANT_SUBDOMAIN.example.com". I find this confusing.

Goal Scenario

I am hosting a site on Netlify. I have it setup to support wildcard subdomains with a LetsEncrypt provisioned wildcard SSL certificate. I then have edge functions which change the content of my index.html and apple-app-site-association file dynamically based on the requested subdomain.

I have added the Associated Domains capability to my provisioning profile.

I am using the latest Expo 47 and EAS build. I have added in the appropriate associated domains configuration and I can see this when introspecting my entitlements under com.apple.developer.associated-domains and it is correct.

I am using TestFlight for testing. I am doing a --clean-build on EAS every time and I also increase the runtime version. I have also tried manually refreshing credentials outside of the build process which does this automatically. This must be using the correct provisioning profile otherwise I would get a build failure as the requested entitlements wouldn't match.

The AASA file is currently hosted just in the .well-known directory. I have tried using the root and also tried using both. There are no redirects taking place.

I am aware the AASA file is pulled on application installation and update. I repeatedly remove the apps and then reboot my phone in an attempt to reset any device caches.

The content-type of the file is application/json and I have confirmed this using developer tools in the browser.

There is no robots.txt or anything blocking the request from an infrastructure perspective. There are no additional firewalls or geo restricted access as I am just using plain Netlify to host this, nothing fancy.

I am confident the Team ID and bundle IDs are correct in the AASA file.

I remove the content-length header in the Edge function so it is correctly calculated by the network instead and I have confirmed this using curl.

When I check the file using https://app-site-association.cdn-apple.com/a/v1/site.example.com Apple has the correct file cached on it's CDN so I would expect it to work.

I added in an applinks section so I could use the Apple App Search API validation tool and the Branch.io AASA verification tool to verify correctness. Branch.io says the file is fine and Apple says it's fine also but because the App has not been deployed to the store yet I see Error no apps with domain entitlements. From what I can tell this is normal in development and makes sense as it uses the current released version of the app to verify the deep link configuration. So to me this means Apple can parse the file correctly.

When I stream my device console logs; on install I can see the AASA requesting the correct domains. I see no errors on swcd I just see the Beginning data task AASA-XXXX with the correct domains.

When I run Charles proxy on my phone with a verified SSL installation (also reinstalled a few times now) I do not see quite what I would expect - but the device logs seem to imply it is doing the correct thing. When I view the app-site-association... URL requests in Charles there is one per application install which is correct. The request is marked as Unknown and when I look at the request the host is shown but as you would expect from SSL I see no path. The info says METHOD: CONNECT with Error - Input Error: EOF. This is the only error I see, I am not sure if it is a red herring and something to do with Charles. Given the error as you expect there is no body in the request or response. It is worth noting in general testing I have no VPN enabled and I have do not have Private Relay enabled in my iOS settings.

When I perform a sysdiagnose I see the following at the timestamp in my console log in the swcutil_show.txt device log. This looks correct in comparison to other apps webcredentials and applinks services I see there and I see no errors:

Service:              webcredentials
App ID:               MYTEAMID.com.cf.example.b2c.ios
App Version:          1.0
App PI:               <LSPersistentIdentifier 0x141816200> { v = 0, t = 0x8, u = 0x1e7c, db = 0094F7C4-3078-41A2-A33E-79D5A62C80A6, {length = 8, bytes = 0x7c1e000000000000} }
Domain:               CORRECT_SUBDOMAIN.example.app
User Approval:        unspecified
Site/Fmwk Approval:   approved
Flags:
Last Checked:         2022-12-09 14:14:32 +0000
Next Check:           2022-12-14 14:03:00 +0000

Service:              applinks
App ID:               MYTEAMID.com.cf.example.b2c.ios
App Version:          1.0
App PI:               <LSPersistentIdentifier 0x13fd38d00> { v = 0, t = 0x8, u = 0x219c, db = 0094F7C4-3078-41A2-A33E-79D5A62C80A6, {length = 8, bytes = 0x9c21000000000000} }
Domain:               CORRECT_SUBDOMAIN.example.app
Patterns:             {"/":"*"}
User Approval:        unspecified
Site/Fmwk Approval:   approved
Flags:
Last Checked:         2022-12-13 13:13:23 +0000
Next Check:           2022-12-18 13:01:51 + 0000

At end of file:

MYTEAMID.com.cf.example.b2c.ios: 8 bytes

(This seems correct for all apps)

Other Scenario

I have tried setting this up using an apex on another domain which hasn't been seen before by Apple. I have tried using a subdomain with a root domain serving the same content and I have tried the subdomain and root domain on their own. I have also tried not using the Edge functions and having static files but to no avail.

When I do this I ensure I wait for the Apple CDN to catch up and remove/add entries prior to deleting the apps, rebooting my device, and reinstalling to test.

AASA File

AASA content comes back with the correct payload and Content-Type: application/json and Content-Length headers, both from Apples CDN and the origin. When I had this somehow working in my initial test it was on a root domain and I did not have an applinks section, this was only added so I could use the verification tools for universal links.

I am not sending back different content or duplicated content and I block the www subdomain - I have also tried it with a www subdomain for the record.

{
  "applinks": {
    "details": [
      {
        "appIDs": [
          "MYTEAMID.com.cf.example.b2c.ios"
        ],
        "components": [
          {
            "#": "no_universal_links",
            "exclude": true,
            "comment": "Matches any URL with a fragment that equals no_universal_links and instructs the system not to open it as a universal link."
          }
        ]
      }
    ]
  },
  "webcredentials": {
    "apps": [
      "MYTEAMID.com.cf.example.b2c.ios"
    ]
  }
}

I have also tried this with the older format:

{
  "applinks": {
    "apps": [],
    "details": [
      {
        "appID": "MYTEAMID.com.cf.example.b2c.ios",
        "paths": [
          "*"
        ]
      }
    ]
  },
  "webcredentials": {
    "apps": [
      "MYTEAMID.com.cf.example.b2c.ios"
    ]
  }
}

associatedDomains iOS. expo config

associatedDomains: [
  `webcredentials:${SUBDOMAIN}.example.app`,
  `applinks:${SUBDOMAIN}.example.app`,
],

Help :)

I have been trying to get this to work for a long time now and I am completely out of ideas. If anybody has any suggestions I would really appreciate it. I am very confused how the devices request seems correct and the CDN content is correct but it is still not working. It's worth also reiterating that I need to have different subdomains for each tenant as the credentials must not be shared across apps so the keychain->domain association store must be different.

I am wondering if it's the LetsEncrypt wildcard SSL certificate but I wouldn't expect it to verify and for Apple to cache the file if this was the case. It seems very unlikely to me but it is the only thing I haven't tried at this point.

Many Thanks,

Mark


问:
Can't run gin gonic server on domain using aws ec2
I have a domain on godaddy.com which I've given the DNS of my AWS EC2.
I can successfully run a flask application with the code

app.run(host="0.0.0.0", port=8000, debug=True,ssl_context=('fullchain.pem', 'privkey.pem'))
If I open the link https://typearncontrol.com:8000/latest in my browser I would get a result.

I'm trying to run a gin gonic application with the code

router.RunTLS(("0.0.0.0:8083"),"fullchain.pem","privkey.pem")
When I try to open the link https://typearncontrol.com:8083/2 which is a page of my gin app I get the error "This site can’t be reached"

Please help me resolve this.


问:
How to call a function which resides inside the component from parent controller in AngularJS 1.8
I have demoComponent.js which is being called in the template xyz.html of the controller xyzController. Now, I want to execute a function which resides in the demoComponent from xyzController. The angularjs version 1.8.

Example Code:

xyzController.js

```<code>
function xyzController($scope) {
   const vm = this;

   vm.$onInit = () => {
      vm.trigger_update(); // It works in AngularJS 1.5, but, not in 1.8
   };
}
</code>```

xyz.html

```<code><div ng-controller="xyzController as xyzController">
   <demo-component ng-if="some condition" on-update="xyzController.trigger_update"></demo-component>
</div>

</code>```

demoComponent.js

```<code>const demoComponent = {
    bindings: {
       on_update: '=onUpdate',
    },
    controllerAs: 'controller',
    controller: function($scope) {
      const vm = this;

      vm.on_update = () => { // some functionality }
    }
}
</code>```

Need help

I should be able to call component controller function from xyzController.

Body:
I have demoComponent.js which is being called in the template xyz.html of the controller xyzController. Now, I want to execute a function which resides in the demoComponent from xyzController. The angularjs version 1.8.

Example Code:

xyzController.js

function xyzController($scope) {
   const vm = this;

   vm.$onInit = () => {
      vm.trigger_update(); // It works in AngularJS 1.5, but, not in 1.8
   };
}

xyz.html

   <demo-component ng-if="some condition" on-update="xyzController.trigger_update"></demo-component>

demoComponent.js

const demoComponent = {
    bindings: {
       on_update: '=onUpdate',
    },
    controllerAs: 'controller',
    controller: function($scope) {
      const vm = this;

      vm.on_update = () => { // some functionality }
    }
}

Need help

I should be able to call component controller function from xyzController.


问:
How to use different weight for each base model when using a concatenate method
I am trying to merge several pre-trained models into a single model. Each model has its input and output, with the same shapes. I want to create a concatenate layer to merge these models. The function Concatenate of Keras provides me an easy way. I am wondering how to specialize the weight of each model. In my idea, each base model has a different contribution to the final output.

```<code>model_list = [model1, model2, model3]
for i, model in enumerate(model_list):
    for layer in model.layers:
        layer.trainable = False
        layer._name = 'ensemble_' + str(i+1) + '_' + layer.name
ensemble_inputs = [model.input for model in model_list]
#set the weight for each model
weights = [0.8, 0.1, 0.1]
ensemble_outputs = [model.output for model in model_list]
ensemble_outputs = [model.output * w for model, w in zip(model_list, weights)]
merge = concatenate(ensemble_outputs)
hidden = Dense(8, activation='relu')(merge)
output = Dense(1, activation='sigmoid')(hidden)
model = Model(inputs=ensemble_inputs, outputs=output)
</code>```

Does it work?

Body:
I am trying to merge several pre-trained models into a single model. Each model has its input and output, with the same shapes. I want to create a concatenate layer to merge these models. The function Concatenate of Keras provides me an easy way. I am wondering how to specialize the weight of each model. In my idea, each base model has a different contribution to the final output.

model_list = [model1, model2, model3]
for i, model in enumerate(model_list):
    for layer in model.layers:
        layer.trainable = False
        layer._name = 'ensemble_' + str(i+1) + '_' + layer.name
ensemble_inputs = [model.input for model in model_list]
#set the weight for each model
weights = [0.8, 0.1, 0.1]
ensemble_outputs = [model.output for model in model_list]
ensemble_outputs = [model.output * w for model, w in zip(model_list, weights)]
merge = concatenate(ensemble_outputs)
hidden = Dense(8, activation='relu')(merge)
output = Dense(1, activation='sigmoid')(hidden)
model = Model(inputs=ensemble_inputs, outputs=output)

Does it work?


问:
How to format crypto currency prices
I'm creating a simple crypto currency app where I have prices list

Example

```<code>Bitcoin   $17,100.90
Ethereum  $5,500.00
</code>```

The API response is the followin for any coin

```<code> "price": 0.08859786785798442
 "price": 17.10090786785798442
</code>```

What I need is this

If the number is too big I only need 2 digits after the last number, example $17,894.98 , $1,338.13

But , for example, for prices that are only 1 or a little bit more than 0 I need 3 or 4 digits after , example, for 1 I need to format $1.000 (this applies for example for USDT) and if is lower than 1 I need to display 4 digits after , example $0.9997

I'm trying to create an extension that does this

```<code>fun Double.toPrice(): String {
    return NumberFormat.getCurrencyInstance(Locale("en", "US")).format(this)
}
</code>```

The problem here is that for $1 the price returned is $1.00 and for $0,0009 the price returned is $0.00

is there any way that I can get the number and format it the way I need it ?

Examples below

```<code>$17,343.90
$1,000.00
$534.35
$15.93
$1.000
</code>```

For numbers below 1

```<code>0.9999
0.0009
</code>```

Title: How to format crypto currency prices

Body:
I'm creating a simple crypto currency app where I have prices list

Example

Bitcoin   $17,100.90
Ethereum  $5,500.00

The API response is the followin for any coin

 "price": 0.08859786785798442
 "price": 17.10090786785798442

What I need is this

If the number is too big I only need 2 digits after the last number, example $17,894.98 , $1,338.13

But , for example, for prices that are only 1 or a little bit more than 0 I need 3 or 4 digits after , example, for 1 I need to format $1.000 (this applies for example for USDT) and if is lower than 1 I need to display 4 digits after , example $0.9997

I'm trying to create an extension that does this

fun Double.toPrice(): String {
    return NumberFormat.getCurrencyInstance(Locale("en", "US")).format(this)
}

The problem here is that for $1 the price returned is $1.00 and for $0,0009 the price returned is $0.00

is there any way that I can get the number and format it the way I need it ?

Examples below

$17,343.90
$1,000.00
$534.35
$15.93
$1.000

For numbers below 1

0.9999
0.0009


问:
NLP / Generator | StopIteration Error in Pattern.text.en library at function conjugate
I'm trying to transfer a verb into its past form with the command

```<code>conjugate(oldWord, tense=this_tense, person=person, number=number)
</code>```

I'm doing this operation on 500 sentences and the first one always raise this error.
so what I did was to call this function again with the same parameters for the first sentence, and it worked.
for the purpose of cleaner code for production I would like to solve this problem for the first sentence.
any suggestions?

Error description:

```<code>Traceback (most recent call last):
  File "C:\Users\USER\PycharmProjects\zikit1\pattern\text\__init__.py", line 609, in _read
    raise StopIteration
StopIteration

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

Traceback (most recent call last):
  File "C:\Users\USER\PycharmProjects\zikit1\main.py", line 130, in <module>
    tmp = change_tense.change_tense(short_res[i], 'past')
  File "C:\Users\USER\PycharmProjects\zikit1\change_tense.py", line 124, in change_tense
    x1 = conjugate(oldWord, tense=this_tense, person=person, number=number)
  File "C:\Users\USER\PycharmProjects\zikit1\pattern\text\__init__.py", line 2208, in conjugate
    b = self.lemma(verb, parse=kwargs.get("parse", True))
  File "C:\Users\USER\PycharmProjects\zikit1\pattern\text\__init__.py", line 2172, in lemma
    self.load()
  File "C:\Users\USER\PycharmProjects\zikit1\pattern\text\__init__.py", line 2127, in load
    for v in _read(self._path):
RuntimeError: generator raised StopIteration
</code>```

I was expecting to get the verb in its past form.

Body:
I'm trying to transfer a verb into its past form with the command

conjugate(oldWord, tense=this_tense, person=person, number=number)

I'm doing this operation on 500 sentences and the first one always raise this error.
so what I did was to call this function again with the same parameters for the first sentence, and it worked.
for the purpose of cleaner code for production I would like to solve this problem for the first sentence.
any suggestions?

Error description:

Traceback (most recent call last):
  File "C:\Users\USER\PycharmProjects\zikit1\pattern\text\__init__.py", line 609, in _read
    raise StopIteration
StopIteration

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

Traceback (most recent call last):
  File "C:\Users\USER\PycharmProjects\zikit1\main.py", line 130, in <module>
    tmp = change_tense.change_tense(short_res[i], 'past')
  File "C:\Users\USER\PycharmProjects\zikit1\change_tense.py", line 124, in change_tense
    x1 = conjugate(oldWord, tense=this_tense, person=person, number=number)
  File "C:\Users\USER\PycharmProjects\zikit1\pattern\text\__init__.py", line 2208, in conjugate
    b = self.lemma(verb, parse=kwargs.get("parse", True))
  File "C:\Users\USER\PycharmProjects\zikit1\pattern\text\__init__.py", line 2172, in lemma
    self.load()
  File "C:\Users\USER\PycharmProjects\zikit1\pattern\text\__init__.py", line 2127, in load
    for v in _read(self._path):
RuntimeError: generator raised StopIteration

I was expecting to get the verb in its past form.


问:
how to read f32 audio samples from microphone in rust cpal library? trying to decode DTMF signals in realtime
I am trying to decode dtmf signals using rust in real time, and I have a working example that decodes them from wav files. But I am trying to do it in real time from the soundcard, by providing data, that came from microphone, to function (Decoder::process(&data)), but I think it receives F32 vector of samples.
Can you provide an example on how to properly read sound from microphone in a needed way?
Here is my example from https://gitlab.scd31.com/stephen/dtmf
add cargo dependency dtmf = "0.1.5"

use dtmf::decoder::Decoder;
use rodio::{Decoder as RDecoder, Source};
use std::fs::File;
use std::io::BufReader;

fn main() {
    // Load in our audio samples
    // This can also be done in real time from the sound card
    let file = BufReader::new(File::open("data/dtmf_test.wav").unwrap());
    let source = RDecoder::new(file).unwrap();
    let samples = source.convert_samples();
    let sample_rate = samples.sample_rate();
    let data: Vec<f32> = samples.collect();

    // set up our decoder
    let mut decoder = Decoder::new(sample_rate, |tone, state| {
        println!("{:?}: {:?}", tone, state);
    });

    // can process all samples at once, or in smaller batches
    decoder.process(&data);
}

```

This thing takes wav file and decodes it. but I am trying to do it real time.
Thank you.

Body:
I am trying to decode dtmf signals using rust in real time, and I have a working example that decodes them from wav files. But I am trying to do it in real time from the soundcard, by providing data, that came from microphone, to function (Decoder::process(&data)), but I think it receives F32 vector of samples.
Can you provide an example on how to properly read sound from microphone in a needed way?
Here is my example from https://gitlab.scd31.com/stephen/dtmf
add cargo dependency dtmf = "0.1.5"

use dtmf::decoder::Decoder;
use rodio::{Decoder as RDecoder, Source};
use std::fs::File;
use std::io::BufReader;

fn main() {
    // Load in our audio samples
    // This can also be done in real time from the sound card
    let file = BufReader::new(File::open("data/dtmf_test.wav").unwrap());
    let source = RDecoder::new(file).unwrap();
    let samples = source.convert_samples();
    let sample_rate = samples.sample_rate();
    let data: Vec<f32> = samples.collect();

    // set up our decoder
    let mut decoder = Decoder::new(sample_rate, |tone, state| {
        println!("{:?}: {:?}", tone, state);
    });

    // can process all samples at once, or in smaller batches
    decoder.process(&data);
}

This thing takes wav file and decodes it. but I am trying to do it real time.
Thank you.


问:
Regex pattern matching a string in Python
I want to obtain the regex pattern that is matching that specific string.

For example:

```<code>string = "every 12 weeks"
regex_patterns = '(every week)|(every \d+ weeks)|(every month)'
</code>```

I tried

```<code>pat = re.match(regex_patterns, string)
<re.Match object; span=(0, 13), match='every 12 weeks'>
</code>```

but what I get is "every 12 weeks" as a match, but I want the original pattern ("every \d+ weeks"), not that one with "every 12 weeks".

How can I achieve that using regex and Python?

Body:
I want to obtain the regex pattern that is matching that specific string.

For example:

string = "every 12 weeks"
regex_patterns = '(every week)|(every \d+ weeks)|(every month)'

I tried

pat = re.match(regex_patterns, string)
<re.Match object; span=(0, 13), match='every 12 weeks'>

but what I get is "every 12 weeks" as a match, but I want the original pattern ("every \d+ weeks"), not that one with "every 12 weeks".

How can I achieve that using regex and Python?


问:
How set dynamically input range min value in React?
I have built a React web application. I use tailwind but some own CSS.

I have an input range that uses different data. When I switch the data the input slider thumb is not at the beginning because the data static (here: 300).

But if I change dynamic min={data.width} will not move at all because the min value continuously changes as I change.

How reach that only change min value when I switch between components and not when I use range slider (and stand thumb the beginning of slider when I switch component)?

So when the table is active, the start width at 60cm and stand at the beginning of slider and not a little further.

(Originally I used context have several components that get data by api request from JSON server, but I simplified the scenario).

StackoverflowRange.jsx

```<code>import React, { useState } from "react";

const StackoverflowRange = () => {
  const [data, setData] = useState({
    id: 1,
    name: "Chair",
    width: "300",
    high: "860",
    depth: "550",
  });

  const chair={
    id: 1,
    name: "Chair",
    width: "300",
    high: "860",
    depth: "550",
  }

  const table={
    id: 1,
    name: "Table",
    width: "600",
    high: "860",
    depth: "550",
  }

  const clickHandler =(item)=>{
    if(item=='table'){
      setData(table)
    }else{
      setData(chair)
    }

  }

  const widthHandler = (event) => {
    const newWidth = { ...data, width: event };
    setData(newWidth);
  };

  return (
    <>
      <div className="flex flex-col justify-center md:flex-row">
        <div className="m-2">
          <div className="m-2">
            <div className="slidecontainer">
            <h1> {data.name}</h1>
              <h1>width: {data.width / 10} cm</h1>
              <input
                type="range"
                min="300"
                max="1200"
                step="50"
                value={data.width}
                onChange={(e) => widthHandler(e.target.value)}
                className={`slider myslider`}
              />
            </div>
          </div>
          <button
            className={`m-2
              p-2
              w-36
              md:w-36
              max-w-sm
             bg-neutral-100
              border-2
             rounded-lg
              shadow-lg
             `}
             onClick={()=>clickHandler('table')}
          >
            Table
          </button>
          <button
            className={`m-2
              p-2
              w-36
              md:w-36
              max-w-sm
             bg-neutral-100
              border-2
             rounded-lg
              shadow-lg
              `}
              onClick={()=>clickHandler('chair')}
          >
            Chair
          </button>
        </div>
      </div>
    </>
  );
};

export default StackoverflowRange;

</code>```

own.css

```<code>.slider {
  -webkit-appearance: none;
  height: 7px;
}

.slidecontainer {
  width: 100%;
}

.slider {
  -webkit-appearance: none;
  width: 200px;
  height: 7px;
  border-radius: 5px;
  background: #d3d3d3;
  outline: none;
  opacity: 0.7;
  -webkit-transition: 0.2s;
  transition: opacity 0.2s;
}

.slider:hover {
  opacity: 1;
}

.myslider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 25px;
  height: 25px;
  border-radius: 50%;
  cursor: pointer;
}
.myslider {
  background: linear-gradient(90deg, white 10%, #57534e 90%);
}
.myslider::-webkit-slider-thumb {
  background: #57534e;
}

.mybackground {
  background-repeat: repeat-y;
}
</code>```

Body:
I have built a React web application. I use tailwind but some own CSS.

I have an input range that uses different data. When I switch the data the input slider thumb is not at the beginning because the data static (here: 300).

But if I change dynamic min={data.width} will not move at all because the min value continuously changes as I change.

How reach that only change min value when I switch between components and not when I use range slider (and stand thumb the beginning of slider when I switch component)?

So when the table is active, the start width at 60cm and stand at the beginning of slider and not a little further.

(Originally I used context have several components that get data by api request from JSON server, but I simplified the scenario).

StackoverflowRange.jsx

import React, { useState } from "react";

const StackoverflowRange = () => {
  const [data, setData] = useState({
    id: 1,
    name: "Chair",
    width: "300",
    high: "860",
    depth: "550",
  });

  const chair={
    id: 1,
    name: "Chair",
    width: "300",
    high: "860",
    depth: "550",
  }

  const table={
    id: 1,
    name: "Table",
    width: "600",
    high: "860",
    depth: "550",
  }

  const clickHandler =(item)=>{
    if(item=='table'){
      setData(table)
    }else{
      setData(chair)
    }

  }

  const widthHandler = (event) => {
    const newWidth = { ...data, width: event };
    setData(newWidth);
  };

  return (
    <>

 {data.name}

width: {data.width / 10} cm

              <input
                type="range"
                min="300"
                max="1200"
                step="50"
                value={data.width}
                onChange={(e) => widthHandler(e.target.value)}
                className={`slider myslider`}
              />

          <button
            className={`m-2
              p-2
              w-36
              md:w-36
              max-w-sm
             bg-neutral-100
              border-2
             rounded-lg
              shadow-lg
             `}
             onClick={()=>clickHandler('table')}
          >
            Table
          </button>
          <button
            className={`m-2
              p-2
              w-36
              md:w-36
              max-w-sm
             bg-neutral-100
              border-2
             rounded-lg
              shadow-lg
              `}
              onClick={()=>clickHandler('chair')}
          >
            Chair
          </button>

    </>
  );
};

export default StackoverflowRange;

own.css

.slider {
  -webkit-appearance: none;
  height: 7px;
}

.slidecontainer {
  width: 100%;
}

.slider {
  -webkit-appearance: none;
  width: 200px;
  height: 7px;
  border-radius: 5px;
  background: #d3d3d3;
  outline: none;
  opacity: 0.7;
  -webkit-transition: 0.2s;
  transition: opacity 0.2s;
}

.slider:hover {
  opacity: 1;
}

.myslider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 25px;
  height: 25px;
  border-radius: 50%;
  cursor: pointer;
}
.myslider {
  background: linear-gradient(90deg, white 10%, #57534e 90%);
}
.myslider::-webkit-slider-thumb {
  background: #57534e;
}

.mybackground {
  background-repeat: repeat-y;
}


问:
Aggregating data in seaborn plots using sum function
I have a layoff dataset with PeriodIndex as shown below:

```<code>        Industry    Laid_Off_Count
Year
2022-10 Finance 0.0
2022-10 Healthcare  0.0
2022-09 Consumer    600.0
2022-09 Healthcare  113.0
2022-09 Finance 85.0
2020-03 Travel  0.0
2020-03 Transportation  8.0
2020-03 Consumer    6.0
2020-12 Retail  20.0
2020-11 All Others  75.0
1791 rows × 2 columns
</code>```

having unique Industry values as:

```<code>array(['Finance', 'Healthcare', 'Consumer', 'All Others', 'Food',
       'Transportation', 'Real Estate', 'Retail', 'Travel'], dtype=object)
</code>```

Creating a plot as below:

```<code>fig = plt.figure(figsize=(20,8))
ax = fig.add_subplot()
sns.histplot(data=df_copy3,y='Industry',hue=df_copy3.index.year,ax=ax,multiple='dodge',stat='count')
plt.savefig('Tech layoffs by Industry.jpeg')
</code>```

I'm getting result as

.

By default, stat argument is 'count' function, and other options for sns.histplot are 'frequency', 'probability', 'percent' and 'density'. I want to aggregate using 'sum' function and get a plot that looks like this:

In short, I want the sum of laid off employees along X-axis grouped by Industry and hue=df.index.year.

Can someone help me understand what I'm missing here?

Body:
I have a layoff dataset with PeriodIndex as shown below:

        Industry    Laid_Off_Count
Year
2022-10 Finance 0.0
2022-10 Healthcare  0.0
2022-09 Consumer    600.0
2022-09 Healthcare  113.0
2022-09 Finance 85.0
2020-03 Travel  0.0
2020-03 Transportation  8.0
2020-03 Consumer    6.0
2020-12 Retail  20.0
2020-11 All Others  75.0
1791 rows × 2 columns

having unique Industry values as:

array(['Finance', 'Healthcare', 'Consumer', 'All Others', 'Food',
       'Transportation', 'Real Estate', 'Retail', 'Travel'], dtype=object)

Creating a plot as below:

fig = plt.figure(figsize=(20,8))
ax = fig.add_subplot()
sns.histplot(data=df_copy3,y='Industry',hue=df_copy3.index.year,ax=ax,multiple='dodge',stat='count')
plt.savefig('Tech layoffs by Industry.jpeg')

I'm getting result as

.

By default, stat argument is 'count' function, and other options for sns.histplot are 'frequency', 'probability', 'percent' and 'density'. I want to aggregate using 'sum' function and get a plot that looks like this:

In short, I want the sum of laid off employees along X-axis grouped by Industry and hue=df.index.year.

Can someone help me understand what I'm missing here?


问:
react-d3-graph Sticking/Grouping nodes together
I am working with the react library "react-d3-graph".  I am trying to display my data set in fashion similar to the Marvel example provided. My data is a little different, in that I may have 1 or more parent nodes, each with children nodes (And each child node can then have children as well). The issue I am trying to solve is that when my graph gets displayed, all the nodes are so spread out and overlap one another. I would like to group each parent node (and their associated child nodes) locally. I noticed that on the the various examples pages (Like the Marvel example) there is a button that says "Unstick". When I click that, all the nodes in the graph become unorganized, which looks like how my graph is displayed. So, how do I "Stick" the nodes so they group by one another? I tried using the generated config, but it does not appear to make a difference. I searched through the documentation and did not see any mention of "Sticking" or "Unsticking" Thanks!

Config

```<code> const myConfig = {
    automaticRearrangeAfterDropNode: true,
    collapsible: true,
    directed: false,
    focusAnimationDuration: 0.75,
    focusZoom: 1,
    freezeAllDragEvents: false,
    height: 800,
    highlightDegree: 2,
    highlightOpacity: 0.2,
    linkHighlightBehavior: true,
    maxZoom: 12,
    minZoom: 0.05,
    nodeHighlightBehavior: true,
    panAndZoom: false,
    staticGraph: false,
    staticGraphWithDragAndDrop: false,
    width: 1000,
    d3: {
      alphaTarget: 0.05,
      gravity: -210,
      linkLength: 100,
      linkStrength: 10,
      disableLinkForce: false,
    },
    node: {
      color: "#d3d3d3",
      fontColor: "black",
      fontSize: 15,
      fontWeight: "normal",
      highlightColor: "red",
      highlightFontSize: 18,
      highlightFontWeight: "bold",
      highlightStrokeColor: "red",
      highlightStrokeWidth: 1.5,
      mouseCursor: "pointer",
      opacity: 0.9,
      renderLabel: true,
      size: 600,
      strokeColor: "none",
      strokeWidth: 1.5,
      svg: "",
      symbolType: "circle",
      labelProperty: "name",
    },
    link: {
      color: "lightgray",
      fontColor: "black",
      fontSize: 8,
      fontWeight: "normal",
      highlightColor: "red",
      highlightFontSize: 8,
      highlightFontWeight: "normal",
      labelProperty: "label",
      mouseCursor: "pointer",
      opacity: 1,
      renderLabel: false,
      semanticStrokeWidth: true,
      strokeWidth: 3,
      markerHeight: 6,
      markerWidth: 6,
      strokeDasharray: 0,
      strokeDashoffset: 0,
      strokeLinecap: "butt",
    },
  };
</code>```

Data:

```<code>{
  "nodes": [
    {
      "id": 351843720888322,
      "name": "parent 3",
      "symbolType": "circle",
      "color": "blue"
    },
    {
      "id": 369435906932740,
      "name": "child 5",
      "symbolType": "square",
      "color": "green"
    },
    {
      "id": 387028092977152,
      "name": "sub child",
      "symbolType": "triangle",
      "color": "purple"
    },
    {
      "id": 369435906932741,
      "name": "child 6",
      "symbolType": "square",
      "color": "green"
    },
    {
      "id": 369435906932742,
      "name": "child 7",
      "symbolType": "square",
      "color": "green"
    },
    {
      "id": 369435906932743,
      "name": "child 8",
      "symbolType": "square",
      "color": "green"
    },
    {
      "id": 369435906932744,
      "name": "child 9",
      "symbolType": "square",
      "color": "green"
    },
    {
      "id": 351843720888321,
      "name": "parent 2",
      "symbolType": "circle",
      "color": "blue"
    },
    {
      "id": 369435906932737,
      "name": "child 2",
      "symbolType": "square",
      "color": "green"
    },
    {
      "id": 369435906932738,
      "name": "child 3",
      "symbolType": "square",
      "color": "green"
    },
    {
      "id": 369435906932739,
      "name": "child 4",
      "symbolType": "square",
      "color": "green"
    },
    {
      "id": 351843720888320,
      "name": "parent 1",
      "symbolType": "circle",
      "color": "blue"
    },
    {
      "id": 369435906932736,
      "name": "child 1",
      "symbolType": "square",
      "color": "green"
    }
  ],
  "links": [
    {
      "source": 351843720888322,
      "target": 369435906932740
    },
    {
      "source": 369435906932740,
      "target": 387028092977152
    },
    {
      "source": 351843720888322,
      "target": 369435906932741
    },
    {
      "source": 351843720888322,
      "target": 369435906932742
    },
    {
      "source": 351843720888322,
      "target": 369435906932743
    },
    {
      "source": 351843720888322,
      "target": 369435906932744
    },
    {
      "source": 351843720888321,
      "target": 369435906932737
    },
    {
      "source": 351843720888321,
      "target": 369435906932738
    },
    {
      "source": 351843720888321,
      "target": 369435906932739
    },
    {
      "source": 351843720888320,
      "target": 369435906932736
    }
  ]
}
</code>```

Body:
I am working with the react library "react-d3-graph".  I am trying to display my data set in fashion similar to the Marvel example provided. My data is a little different, in that I may have 1 or more parent nodes, each with children nodes (And each child node can then have children as well). The issue I am trying to solve is that when my graph gets displayed, all the nodes are so spread out and overlap one another. I would like to group each parent node (and their associated child nodes) locally. I noticed that on the the various examples pages (Like the Marvel example) there is a button that says "Unstick". When I click that, all the nodes in the graph become unorganized, which looks like how my graph is displayed. So, how do I "Stick" the nodes so they group by one another? I tried using the generated config, but it does not appear to make a difference. I searched through the documentation and did not see any mention of "Sticking" or "Unsticking" Thanks!

Config

 const myConfig = {
    automaticRearrangeAfterDropNode: true,
    collapsible: true,
    directed: false,
    focusAnimationDuration: 0.75,
    focusZoom: 1,
    freezeAllDragEvents: false,
    height: 800,
    highlightDegree: 2,
    highlightOpacity: 0.2,
    linkHighlightBehavior: true,
    maxZoom: 12,
    minZoom: 0.05,
    nodeHighlightBehavior: true,
    panAndZoom: false,
    staticGraph: false,
    staticGraphWithDragAndDrop: false,
    width: 1000,
    d3: {
      alphaTarget: 0.05,
      gravity: -210,
      linkLength: 100,
      linkStrength: 10,
      disableLinkForce: false,
    },
    node: {
      color: "#d3d3d3",
      fontColor: "black",
      fontSize: 15,
      fontWeight: "normal",
      highlightColor: "red",
      highlightFontSize: 18,
      highlightFontWeight: "bold",
      highlightStrokeColor: "red",
      highlightStrokeWidth: 1.5,
      mouseCursor: "pointer",
      opacity: 0.9,
      renderLabel: true,
      size: 600,
      strokeColor: "none",
      strokeWidth: 1.5,
      svg: "",
      symbolType: "circle",
      labelProperty: "name",
    },
    link: {
      color: "lightgray",
      fontColor: "black",
      fontSize: 8,
      fontWeight: "normal",
      highlightColor: "red",
      highlightFontSize: 8,
      highlightFontWeight: "normal",
      labelProperty: "label",
      mouseCursor: "pointer",
      opacity: 1,
      renderLabel: false,
      semanticStrokeWidth: true,
      strokeWidth: 3,
      markerHeight: 6,
      markerWidth: 6,
      strokeDasharray: 0,
      strokeDashoffset: 0,
      strokeLinecap: "butt",
    },
  };

Data:

{
  "nodes": [
    {
      "id": 351843720888322,
      "name": "parent 3",
      "symbolType": "circle",
      "color": "blue"
    },
    {
      "id": 369435906932740,
      "name": "child 5",
      "symbolType": "square",
      "color": "green"
    },
    {
      "id": 387028092977152,
      "name": "sub child",
      "symbolType": "triangle",
      "color": "purple"
    },
    {
      "id": 369435906932741,
      "name": "child 6",
      "symbolType": "square",
      "color": "green"
    },
    {
      "id": 369435906932742,
      "name": "child 7",
      "symbolType": "square",
      "color": "green"
    },
    {
      "id": 369435906932743,
      "name": "child 8",
      "symbolType": "square",
      "color": "green"
    },
    {
      "id": 369435906932744,
      "name": "child 9",
      "symbolType": "square",
      "color": "green"
    },
    {
      "id": 351843720888321,
      "name": "parent 2",
      "symbolType": "circle",
      "color": "blue"
    },
    {
      "id": 369435906932737,
      "name": "child 2",
      "symbolType": "square",
      "color": "green"
    },
    {
      "id": 369435906932738,
      "name": "child 3",
      "symbolType": "square",
      "color": "green"
    },
    {
      "id": 369435906932739,
      "name": "child 4",
      "symbolType": "square",
      "color": "green"
    },
    {
      "id": 351843720888320,
      "name": "parent 1",
      "symbolType": "circle",
      "color": "blue"
    },
    {
      "id": 369435906932736,
      "name": "child 1",
      "symbolType": "square",
      "color": "green"
    }
  ],
  "links": [
    {
      "source": 351843720888322,
      "target": 369435906932740
    },
    {
      "source": 369435906932740,
      "target": 387028092977152
    },
    {
      "source": 351843720888322,
      "target": 369435906932741
    },
    {
      "source": 351843720888322,
      "target": 369435906932742
    },
    {
      "source": 351843720888322,
      "target": 369435906932743
    },
    {
      "source": 351843720888322,
      "target": 369435906932744
    },
    {
      "source": 351843720888321,
      "target": 369435906932737
    },
    {
      "source": 351843720888321,
      "target": 369435906932738
    },
    {
      "source": 351843720888321,
      "target": 369435906932739
    },
    {
      "source": 351843720888320,
      "target": 369435906932736
    }
  ]
}


问:
Geofence event transition type is always -1 suddenly
We've had a working Geofencing system in our app that used to work just fine. Recently, I checked out a reported issue and found that all transition events seem to have a -1 transition type which, according to the docs, means that the intent specified in fromIntent(Intent) is not generated for a transition alert.

I don't understand how that can be, though. We didn't change anything in our implementation and apart from that, the pending intent is triggered every time I trigger an enter/exit event, through the emulator's location setting.

Here's our flow:

```<code>// we create a geo-fence from an FCM notification payload
    override fun createGeofenceFromEvent(geoEventData: GeoEventData) =
        Geofence.Builder()
            .setRequestId(geoEventData.id)
            .setCircularRegion(
                geoEventData.latitude,
                geoEventData.longitude,
                geoEventData.radius
            )
            .setExpirationDuration(Geofence.NEVER_EXPIRE)
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT)
            .build()

// then we add it to the client (it's added successfully) like so
    override fun addGeofenceToClient(geofence: Geofence) {
        App.instance.geofencingClient.addGeofences(
            getGeofencingRequest(geofence),
            App.instance.geofencePendingIntent
        ).run {
            addOnSuccessListener {
                Log.d(tag, "Geofence with id ${geofence.requestId} added to client!")
            }
            addOnFailureListener {
                Log.d(tag, "Failed to add geofence with id ${geofence.requestId} to client!")
                it.printStackTrace()
            }
        }
    }

// here's the pending intent declaration
    val geofencePendingIntent: PendingIntent by lazy {
        val intent = Intent(appContext, GeofenceBroadcastReceiver::class.java)
        PendingIntent.getBroadcast(appContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
    }
</code>```

Then in our GeofenceBroadcastReceiver class it always logs -1 now when using:

```<code>    override fun onReceive(context: Context?, intent: Intent?) {
        if (!checkForNotificationUserChoice(context)) return
        val geofencingEvent = GeofencingEvent.fromIntent(intent!!)
        if (geofencingEvent.hasError()) {
            val errorMessage = GeofenceStatusCodes
                .getStatusCodeString(geofencingEvent.errorCode)
            Log.e(TAG, errorMessage)
            return
        }
        val geofenceTransition = geofencingEvent.geofenceTransition
        Log.e(TAG,"$geofenceTransition")
        ...
}
</code>```

Any ideas what I'm missing here? I've made sure that I'm testing on an emulator with Google Play Services & APIs enabled, that GPS/Location is enabled and that location updates work, that the “Always” option is enabled for location tracking, etc.

To sum up:

Geo-fence payloads reach the app successfully through FCM

Geo-fences are created and added to the client successfully as well

Enter/exit events triggered by changing the emulator's
location also seem to be received by the system correctly

BUT, the pending intent that handles the transport of the geo-fence
event payload seems to “lose” its transition type payload.

Body:
We've had a working Geofencing system in our app that used to work just fine. Recently, I checked out a reported issue and found that all transition events seem to have a -1 transition type which, according to the docs, means that the intent specified in fromIntent(Intent) is not generated for a transition alert.

I don't understand how that can be, though. We didn't change anything in our implementation and apart from that, the pending intent is triggered every time I trigger an enter/exit event, through the emulator's location setting.

Here's our flow:

// we create a geo-fence from an FCM notification payload
    override fun createGeofenceFromEvent(geoEventData: GeoEventData) =
        Geofence.Builder()
            .setRequestId(geoEventData.id)
            .setCircularRegion(
                geoEventData.latitude,
                geoEventData.longitude,
                geoEventData.radius
            )
            .setExpirationDuration(Geofence.NEVER_EXPIRE)
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT)
            .build()

// then we add it to the client (it's added successfully) like so
    override fun addGeofenceToClient(geofence: Geofence) {
        App.instance.geofencingClient.addGeofences(
            getGeofencingRequest(geofence),
            App.instance.geofencePendingIntent
        ).run {
            addOnSuccessListener {
                Log.d(tag, "Geofence with id ${geofence.requestId} added to client!")
            }
            addOnFailureListener {
                Log.d(tag, "Failed to add geofence with id ${geofence.requestId} to client!")
                it.printStackTrace()
            }
        }
    }

// here's the pending intent declaration
    val geofencePendingIntent: PendingIntent by lazy {
        val intent = Intent(appContext, GeofenceBroadcastReceiver::class.java)
        PendingIntent.getBroadcast(appContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
    }

Then in our GeofenceBroadcastReceiver class it always logs -1 now when using:

    override fun onReceive(context: Context?, intent: Intent?) {
        if (!checkForNotificationUserChoice(context)) return
        val geofencingEvent = GeofencingEvent.fromIntent(intent!!)
        if (geofencingEvent.hasError()) {
            val errorMessage = GeofenceStatusCodes
                .getStatusCodeString(geofencingEvent.errorCode)
            Log.e(TAG, errorMessage)
            return
        }
        val geofenceTransition = geofencingEvent.geofenceTransition
        Log.e(TAG,"$geofenceTransition")
        ...
}

Any ideas what I'm missing here? I've made sure that I'm testing on an emulator with Google Play Services & APIs enabled, that GPS/Location is enabled and that location updates work, that the “Always” option is enabled for location tracking, etc.

To sum up:

Geo-fence payloads reach the app successfully through FCM

Geo-fences are created and added to the client successfully as well

Enter/exit events triggered by changing the emulator's
location also seem to be received by the system correctly

BUT, the pending intent that handles the transport of the geo-fence
event payload seems to “lose” its transition type payload.


问:
There is any better approach on updating password and user information on single route using node Js?
I try to update all user information and then the password if the user wants to change the password I am using the passport Js. So I want if there is any better way of updating things in the database.</p>
```<code>router.route("/:id").put(async (req, res) => {
  const { id } = req.params;
  const user = await User.findByIdAndUpdate(id, { $set: req.body });
  console.log(user);
  if (req.body.password) {
    await user.setPassword(req.body.password);
    // res.status(200).json({ message: "Successful!" });
  }
  await user.save();
  res.status(200).json({ message: "Successful!" });
});
</code>```

Body:
I try to update all user information and then the password if the user wants to change the password I am using the passport Js. So I want if there is any better way of updating things in the database.

router.route("/:id").put(async (req, res) => {
  const { id } = req.params;
  const user = await User.findByIdAndUpdate(id, { $set: req.body });
  console.log(user);
  if (req.body.password) {
    await user.setPassword(req.body.password);
    // res.status(200).json({ message: "Successful!" });
  }
  await user.save();
  res.status(200).json({ message: "Successful!" });
});


问:
Commit or Rollback whole set of inserts in multiple tables Python 3 using FastApi
I have two tables say User and Enrollment, I want to commit both tables or rollback the whole transaction [no insert in both tables if there is any problem].

using Alchemi Transaction Management yes its easy to put them in one transaction like below

```<code>db.begin()
user_obj = MyUser(user_name='abc@myemail.com', password='abcd')
db.add(user_obj)
db.commit()
db.refresh(user_obj)

db.begin()
user_enrolment = UserEnrollmentModel(user_id=user_obj.id, role_id= 123)
</code>```

// until we commit user_obj dont get user_id which is required in user_enrolment

but the problem is I need User_Id [PK of User table in Enrollment table as FK].

for MyUser I have Model

```<code>class User(Model):
    __tablename__ = "user"
    id = sa.Column(sa.Integer(), primary_key=True, autoincrement=True)
    user_name = sa.Column(sa.String(), nullable=False)
    password = sa.Column(sa.String(), nullable=False)
    enrolment = relationship("Enrolment", secondary=user_enrolment, backref="user_enrol")
</code>```

but dont have model for Enrolment it is being inserted like

```<code>user_role_obj = {}
        obj["user_id"] = self.user_id
        obj["enrolment_id"] = self.enrolment_id
 result = db.execute(         ums_user_enrolments.insert().returning(ums_user_enrolment.c.id), obj)
</code>```

Body:
I have two tables say User and Enrollment, I want to commit both tables or rollback the whole transaction [no insert in both tables if there is any problem].

using Alchemi Transaction Management yes its easy to put them in one transaction like below

db.begin()
user_obj = MyUser(user_name='abc@myemail.com', password='abcd')
db.add(user_obj)
db.commit()
db.refresh(user_obj)

db.begin()
user_enrolment = UserEnrollmentModel(user_id=user_obj.id, role_id= 123)

// until we commit user_obj dont get user_id which is required in user_enrolment

but the problem is I need User_Id [PK of User table in Enrollment table as FK].

for MyUser I have Model

class User(Model):
    __tablename__ = "user"
    id = sa.Column(sa.Integer(), primary_key=True, autoincrement=True)
    user_name = sa.Column(sa.String(), nullable=False)
    password = sa.Column(sa.String(), nullable=False)
    enrolment = relationship("Enrolment", secondary=user_enrolment, backref="user_enrol")

but dont have model for Enrolment it is being inserted like

user_role_obj = {}
        obj["user_id"] = self.user_id
        obj["enrolment_id"] = self.enrolment_id
 result = db.execute(         ums_user_enrolments.insert().returning(ums_user_enrolment.c.id), obj)


问:
Celery task ran with apply() does not respect countdown
Is it possible to execute celery task locally with apply() so that it respects countdown passed to retry_kwargs?

I have the following task:

```<code>@app.task(
    autoretry_for=(Exception,),
    retry_kwargs={"max_retries": 5, "countdown": 60},
)
def my_task():
    ...
</code>```

When I run it as follows:

my_task.apply()

I can see it is retried as expected but immediately (not with 60 seconds pauses).

Body:
Is it possible to execute celery task locally with apply() so that it respects countdown passed to retry_kwargs?

I have the following task:

@app.task(
    autoretry_for=(Exception,),
    retry_kwargs={"max_retries": 5, "countdown": 60},
)
def my_task():
    ...

When I run it as follows:

my_task.apply()

I can see it is retried as expected but immediately (not with 60 seconds pauses).


问:
Function to read and parse data mixes results from different tables with different keys in React

I am trying to render 2 tables in the same page which get the data from 2 diffrent csv files

they use the same function to read and parse the data

If I load this 2 components in the same page they will mix the data and render some of the data from the second table on the first one

How do I stop the render of the "BMS table" as soon as I get all the correct values?

How do I avoid having data from the "Battery Specifications table" on the "BMS table"?

The function to get the data is:

```<code>import React, { useState, useEffect } from "react";
import * as d3 from 'd3';
import {Numbatt} from './ReadBattInfo';
import { from } from 'rxjs';

const values = [];

function GetData(props) {

    const [batt, setBatt] = useState(0);
    from(Numbatt()).subscribe(x => setBatt(x)); -- > Comes from another function that monitors the number of batteries connected. Can be replaced by a constant number.
    const [loading, setLoading] = useState(true);
    useEffect(() => {
        setLoading(true);
        const fetchData = async () => {
            try{
                for (let i = 0; i < batt; i++) {
                    let csvfile = './data/batt' + (i) + '/' + props.file;
                    await d3.csv(csvfile).then((data) => {
                      let temp=[];
                      data.map((d) => {
                        temp.push(d.value);
                        return () => undefined;
                      });
                      values[i] = temp.slice(props.slice);
                    });
                };
                setLoading(false);
            } catch (err) {
                console.log(err);
            };
        };
        fetchData()
      }, [batt]);

    return({loading, values})
}

export default GetData
</code>```

BMS render function

```<code>const file = 'bmsfault.csv';
const slice = -6;

function BMS() {
    const {loading, values} = GetData({file, slice});
    console.log(values);

    return (
        <>
        <div className="w3-main w3-panel" style={{marginLeft:"300px"}}>
        <div className="w3-row-padding" style={{margin: 0 -16+"px"}}>
            <div>
                <h5>BMS - Battery Managment System</h5>
                {loading && <div>LOADING...</div>}
                {!loading && values.map((value, i) => {
                    return (
                        <table key={'bms'+i} className="w3-table w3-border w3-white w3-half">
                            <thead className="w3-blue">
                                <tr>
                                    <th></th>
                                    <th><i>Battery {i+1} </i></th>
                                    <th>Parameters</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td><FontAwesomeIcon icon={faBolt} /></td>
                                    <td>Charge MOS State</td>
                                    <td><i>{value[0]}</i></td>
                                </tr>
</code>```

BattSpecs render function

```<code>const file = 'batt_param.csv'
const slice = -6;

function BatterySpecs() {
    const {loading, values} = GetData({file, slice});

  return (
    <>
    <div className="w3-container w3-panel w3-main" style={{marginLeft:"300px"}}>
      <div className="w3-row-padding" style={{margin:0 -16+"px"}}>
      <div>
        <h5>Battery Specifications</h5>
        {loading && <div>LOADING...</div>}
        {!loading && values.map((value, i) => {
            return (
                <table key={'battspec'+i} className="w3-table w3-border w3-white w3-half">
                    <thead className="w3-blue">
                        <tr>
                            <th></th>
                            <th><i>Battery {i+1} </i></th>
                            <th>Values</th>
                        </tr>
</code>```

I made sure I gave different keys to the html elements but I think somehow the variable "values" is rendered on the BMS table even when the GetData function is supposed to be reading the batt_param.csv

Solution:

```<code>function GetData(props) {
    const [data,setData] = useState([]); // saving values nested array inside the function.
    const [batt, setBatt] = useState(0);
    from(Numbatt()).subscribe(x => setBatt(x));
    const [loading, setLoading] = useState(true);
    useEffect(() => {
        const values = [];
        const temp = [];
        setLoading(true);
        const fetchData = async () => {
            try{
                for (let i = 0; i < batt; i++) {
                    let csvfile = './sftp/000000004b11cf51/data/batt' + (i) + '/' + props.file;
                    await d3.csv(csvfile).then((data) => {
                      data.map((d) => {
                        temp.push(d.value);
                        return () => undefined;
                      });
                      values[i] = temp.slice(props.slice);
                    });
                    if (i===batt-1){
                      setLoading(false);
                    }
                };
                setData(values); // saving values array to data
            } catch (err) {
                console.log(err);
            };
        };
        fetchData()
      }, [batt]);
      console.log(data);
</code>```

Body:
I am trying to render 2 tables in the same page which get the data from 2 diffrent csv files

they use the same function to read and parse the data

If I load this 2 components in the same page they will mix the data and render some of the data from the second table on the first one

How do I stop the render of the "BMS table" as soon as I get all the correct values?

How do I avoid having data from the "Battery Specifications table" on the "BMS table"?

The function to get the data is:

import React, { useState, useEffect } from "react";
import * as d3 from 'd3';
import {Numbatt} from './ReadBattInfo';
import { from } from 'rxjs';

const values = [];

function GetData(props) {

    const [batt, setBatt] = useState(0);
    from(Numbatt()).subscribe(x => setBatt(x)); -- > Comes from another function that monitors the number of batteries connected. Can be replaced by a constant number.
    const [loading, setLoading] = useState(true);
    useEffect(() => {
        setLoading(true);
        const fetchData = async () => {
            try{
                for (let i = 0; i < batt; i++) {
                    let csvfile = './data/batt' + (i) + '/' + props.file;
                    await d3.csv(csvfile).then((data) => {
                      let temp=[];
                      data.map((d) => {
                        temp.push(d.value);
                        return () => undefined;
                      });
                      values[i] = temp.slice(props.slice);
                    });
                };
                setLoading(false);
            } catch (err) {
                console.log(err);
            };
        };
        fetchData()
      }, [batt]);

    return({loading, values})
}

export default GetData

BMS render function

const file = 'bmsfault.csv';
const slice = -6;

function BMS() {
    const {loading, values} = GetData({file, slice});
    console.log(values);

    return (
        <>

BMS - Battery Managment System

                {loading &&
LOADING...
}
                {!loading && values.map((value, i) => {
                    return (

                                    Battery {i+1}
                                    Parameters

                                    <FontAwesomeIcon icon={faBolt} />
                                    Charge MOS State
                                    {value[0]}

BattSpecs render function

const file = 'batt_param.csv'
const slice = -6;

function BatterySpecs() {
    const {loading, values} = GetData({file, slice});

  return (
    <>

Battery Specifications

        {loading &&
LOADING...
}
        {!loading && values.map((value, i) => {
            return (

                            Battery {i+1}
                            Values

I made sure I gave different keys to the html elements but I think somehow the variable "values" is rendered on the BMS table even when the GetData function is supposed to be reading the batt_param.csv

Solution:

function GetData(props) {
    const [data,setData] = useState([]); // saving values nested array inside the function.
    const [batt, setBatt] = useState(0);
    from(Numbatt()).subscribe(x => setBatt(x));
    const [loading, setLoading] = useState(true);
    useEffect(() => {
        const values = [];
        const temp = [];
        setLoading(true);
        const fetchData = async () => {
            try{
                for (let i = 0; i < batt; i++) {
                    let csvfile = './sftp/000000004b11cf51/data/batt' + (i) + '/' + props.file;
                    await d3.csv(csvfile).then((data) => {
                      data.map((d) => {
                        temp.push(d.value);
                        return () => undefined;
                      });
                      values[i] = temp.slice(props.slice);
                    });
                    if (i===batt-1){
                      setLoading(false);
                    }
                };
                setData(values); // saving values array to data
            } catch (err) {
                console.log(err);
            };
        };
        fetchData()
      }, [batt]);
      console.log(data);


问:
How to write a recursive firestore query
Here is my Guest schema:

```<code>{
 name: 'Frank',
 date: '2022-12-12',
 tags: ['REMOVED', 'COMPLETED'],
 state: 'BOOKING',
 ...
}
</code>```

So to fetch guests,

```<code>query = query.where("date", "<=", startDate);
query = query.where("date", ">=", endDate);
query = query.where("state", "==", "BOOKING");
</code>```

I need 50 guests for the first page and I need to filter the "REMOVED" bookings, but I'm not able to include the

```<code>query = query.where("tags", "not-in", ["REMOVED"]);
</code>```

since inequality can't be with multiple attributes. So I do recursive call till I get 50 guests.

```<code>guests = snapshots.filter(snapshot => !snapshot.payload.doc.data().tags.includes("REMOVED"));

if(guests.length < 50) {
 // query again to get (50 - guests.length) guests.
}
</code>```

But recursive calls is not working as expected. I know the schema(tags) is not great.

Is there any other efficient way to achieve this instead of recursive firestore query or whats the recommended way of recursive firestore query?

Body:
Here is my Guest schema:

{
 name: 'Frank',
 date: '2022-12-12',
 tags: ['REMOVED', 'COMPLETED'],
 state: 'BOOKING',
 ...
}

So to fetch guests,

query = query.where("date", "<=", startDate);
query = query.where("date", ">=", endDate);
query = query.where("state", "==", "BOOKING");

I need 50 guests for the first page and I need to filter the "REMOVED" bookings, but I'm not able to include the

query = query.where("tags", "not-in", ["REMOVED"]);

since inequality can't be with multiple attributes. So I do recursive call till I get 50 guests.

guests = snapshots.filter(snapshot => !snapshot.payload.doc.data().tags.includes("REMOVED"));

if(guests.length < 50) {
 // query again to get (50 - guests.length) guests.
}

But recursive calls is not working as expected. I know the schema(tags) is not great.

Is there any other efficient way to achieve this instead of recursive firestore query or whats the recommended way of recursive firestore query?


问:
How to change the size of the axis values in Matplotlib
I have the following Matplotlib plot:

```<code>import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt

price_values = [[4.2],
    [4.1],
    [4],
    [3.8],
    [3.9],
    [4.2],
    [4.5],
    [4.8],
    [5.2],
    [5.2],
    [5.2],
    [5.6],
    [5.2],
    [5.1],
    [5.3],
    [6],
    [6.2],
    [6.3],
    [6.2],
    [6],
    [5.5] ,
    [5.2],
    [4.8],
    [4.6]]

sample = np.asarray(price_values).squeeze()
ecdf = sm.distributions.ECDF(sample)

x = np.linspace(min(sample), max(sample))
y = ecdf(x)
plt.step(x, y)
ax=plt.gca()
ax.set_xlabel("Price [Cent/kWh]", fontsize = 14, labelpad=8)
ax.set_ylabel("Cumulative frequency", fontsize = 14,labelpad=8)
plt.show()
fig = plt.figure(linewidth=3, figsize=(7, 4))
ax.tick_params(axis='both', which='major', labelsize=140)
plt.savefig('C:/Users/User1/Desktop/Diagramm_EDF.png', edgecolor='black', dpi=300, bbox_inches='tight')
</code>```

I would like to change the size of the values in the x and y axis (not the labels). I tried the following ax.tick_params(axis='both', which='major', labelsize=140) but this does not work. The labelsize does not have any effect. Further, I would like to increase the linewidth of the diagramm. Any suggestions how I can do that?

Body:
I have the following Matplotlib plot:

import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt

price_values = [[4.2],
    [4.1],
    [4],
    [3.8],
    [3.9],
    [4.2],
    [4.5],
    [4.8],
    [5.2],
    [5.2],
    [5.2],
    [5.6],
    [5.2],
    [5.1],
    [5.3],
    [6],
    [6.2],
    [6.3],
    [6.2],
    [6],
    [5.5] ,
    [5.2],
    [4.8],
    [4.6]]

sample = np.asarray(price_values).squeeze()
ecdf = sm.distributions.ECDF(sample)

x = np.linspace(min(sample), max(sample))
y = ecdf(x)
plt.step(x, y)
ax=plt.gca()
ax.set_xlabel("Price [Cent/kWh]", fontsize = 14, labelpad=8)
ax.set_ylabel("Cumulative frequency", fontsize = 14,labelpad=8)
plt.show()
fig = plt.figure(linewidth=3, figsize=(7, 4))
ax.tick_params(axis='both', which='major', labelsize=140)
plt.savefig('C:/Users/User1/Desktop/Diagramm_EDF.png', edgecolor='black', dpi=300, bbox_inches='tight')

I would like to change the size of the values in the x and y axis (not the labels). I tried the following ax.tick_params(axis='both', which='major', labelsize=140) but this does not work. The labelsize does not have any effect. Further, I would like to increase the linewidth of the diagramm. Any suggestions how I can do that?