问:
Graph optimization functions with manim
I need help to make an optimization graph in 3 dimensions with manim. I am having difficulty understanding how to use the projection methods and to represent the axes and data in three-dimensional space. If anyone has experience with manim and can help me understand how to do it, I would greatly appreciate it. Thank you
Note: I am trying to graph the schewefel function below I attach part of the code that I have been working on

```<code>%%manim -qm -v WARNING AckleyAnimation

class Schewefel(ThreeDScene):

def func(self,u,v):
  return x * np.sin(np.sqrt(np.abs(x))) + y * np.sin(np.sqrt(np.abs(y)))

def construct(self):
  cielo = '#C4DDFF'
  azul = '#001D6E'
  rojo = "#B20600"

  axes = ThreeDAxes()

  self.set_camera_orientation(phi=65*DEGREES,theta=60*DEGREES)
 # self.add(axes,x,y)

  name_function = Tex(r"Schwefel function." ,font_size=38).to_corner(UL)
  self.add_fixed_in_frame_mobjects(name_function)
  funcion = MathTex(r"f(x) = 418.9829d - \sum_{i=1}^{d} x_i \sin \sqrt{|x_i|}", font_size=30).to_corner(UL)
  self.play(Write(name_function))

  self.play(FadeOut(name_function))
  self.add_fixed_in_frame_mobjects(funcion)
  self.play(Write(funcion))

  surface_plane =  Surface(
        lambda u, v: np.array([u, v, self.func(u, v)]),
        u_range=[-100,100],
        v_range=[-100,100],

    resolution=(50, 50))

  self.play(Write(surface_plane))
</code>```

Graphics
function Schewefel

Correction:
So far I modified the script and I have the following

```<code>%%manim -qm -v WARNING PlotSurfaceExample

class PlotSurfaceExample(ThreeDScene):
    def construct(self):
        resolution_fa = 16
        self.set_camera_orientation(phi=75 * DEGREES, theta=-60 * DEGREES)
        axes = ThreeDAxes(x_range=(-500, 500, 1800), y_range=(-500, 500, 1800), z_range=(-500, 500, 1800))
        def param_trig(u, v):
            x = u
            y = v
            z = x * np.sin(np.sqrt(np.abs(x))) + y * np.sin(np.sqrt(np.abs(y)))
            return z
        trig_plane = axes.plot_surface(
            param_trig,
            resolution=(resolution_fa, resolution_fa),
            u_range = (-500, 500),
            v_range = (-500, 500),
            colorscale = [BLUE, GREEN, YELLOW, ORANGE, RED],
            )
        self.add(axes)
        self.play(Write(trig_plane))
</code>```

but it gives me this result

but nevertheless I hope this

Title: Graph optimization functions with manim

Body:
I need help to make an optimization graph in 3 dimensions with manim. I am having difficulty understanding how to use the projection methods and to represent the axes and data in three-dimensional space. If anyone has experience with manim and can help me understand how to do it, I would greatly appreciate it. Thank you
Note: I am trying to graph the schewefel function below I attach part of the code that I have been working on

%%manim -qm -v WARNING AckleyAnimation

class Schewefel(ThreeDScene):

def func(self,u,v):
  return x * np.sin(np.sqrt(np.abs(x))) + y * np.sin(np.sqrt(np.abs(y)))

def construct(self):
  cielo = '#C4DDFF'
  azul = '#001D6E'
  rojo = "#B20600"

  axes = ThreeDAxes()

  self.set_camera_orientation(phi=65*DEGREES,theta=60*DEGREES)
 # self.add(axes,x,y)

  name_function = Tex(r"Schwefel function." ,font_size=38).to_corner(UL)
  self.add_fixed_in_frame_mobjects(name_function)
  funcion = MathTex(r"f(x) = 418.9829d - \sum_{i=1}^{d} x_i \sin \sqrt{|x_i|}", font_size=30).to_corner(UL)
  self.play(Write(name_function))

  self.play(FadeOut(name_function))
  self.add_fixed_in_frame_mobjects(funcion)
  self.play(Write(funcion))

  surface_plane =  Surface(
        lambda u, v: np.array([u, v, self.func(u, v)]),
        u_range=[-100,100],
        v_range=[-100,100],

    resolution=(50, 50))

  self.play(Write(surface_plane))

Graphics
function Schewefel

Correction:
So far I modified the script and I have the following

%%manim -qm -v WARNING PlotSurfaceExample

class PlotSurfaceExample(ThreeDScene):
    def construct(self):
        resolution_fa = 16
        self.set_camera_orientation(phi=75 * DEGREES, theta=-60 * DEGREES)
        axes = ThreeDAxes(x_range=(-500, 500, 1800), y_range=(-500, 500, 1800), z_range=(-500, 500, 1800))
        def param_trig(u, v):
            x = u
            y = v
            z = x * np.sin(np.sqrt(np.abs(x))) + y * np.sin(np.sqrt(np.abs(y)))
            return z
        trig_plane = axes.plot_surface(
            param_trig,
            resolution=(resolution_fa, resolution_fa),
            u_range = (-500, 500),
            v_range = (-500, 500),
            colorscale = [BLUE, GREEN, YELLOW, ORANGE, RED],
            )
        self.add(axes)
        self.play(Write(trig_plane))

but it gives me this result

but nevertheless I hope this


来源: stackexchange

问:
Swift_TransportException Expected response code 250 but got code "550", with message "550 5.7.1 Mail contain spam content 204C610003B "

What could be the problem?

I set up mail on my site but now this problem started to occur
could this be blocked for my ip?
so how can i solve the problem?

```<code>Swift_Transport_AbstractSmtpTransport::assertResponseCode
vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:459

    protected function assertResponseCode($response, $wanted)

    {

        if (!$response) {

         [tag:   $this->throwException(new Swift_TransportException('Expected response code '.implode('/', $wanted).' but got an empty response'));

]        }

        list($code) = sscanf($response, '%3d');

        $valid = (empty($wanted) || \in_array($code, $wanted));

        if ($evt = $this->eventDispatcher->createResponseEvent($this, $response,

            $valid)) {

            $this->eventDispatcher->dispatchEvent($evt, 'responseReceived');

        }

        if (!$valid) {

            $this->throwException(new Swift_TransportException('Expected response code '.implode('/', $wanted).' but got code "'.$code.'", with message "'.$response.'"', $code));

        }

    }

    /** Get an entire multi-line response using its sequence number */
</code>```

I solved the problem, I'm waiting for your help

ContentLicense: CC BY-SA 4.0

Body:
What could be the problem?

I set up mail on my site but now this problem started to occur
could this be blocked for my ip?
so how can i solve the problem?

Swift_Transport_AbstractSmtpTransport::assertResponseCode
vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:459

    protected function assertResponseCode($response, $wanted)

    {

        if (!$response) {

         [tag:   $this->throwException(new Swift_TransportException('Expected response code '.implode('/', $wanted).' but got an empty response'));

]        }

        list($code) = sscanf($response, '%3d');

        $valid = (empty($wanted) || \in_array($code, $wanted));

        if ($evt = $this->eventDispatcher->createResponseEvent($this, $response,

            $valid)) {

            $this->eventDispatcher->dispatchEvent($evt, 'responseReceived');

        }

        if (!$valid) {

            $this->throwException(new Swift_TransportException('Expected response code '.implode('/', $wanted).' but got code "'.$code.'", with message "'.$response.'"', $code));

        }

    }

    /** Get an entire multi-line response using its sequence number */

I solved the problem, I'm waiting for your help


问:
How to get user role in Power BI M Query
I am using Power BI Role Level Security (RLS). In RLS, we have roles like Administrator. I have direct query in Power M Query like,

```<code>let
    SomeVar = Record.Field(Table.First(GetSomeVar(Age)), "Column"),
    Role = HowCanIGetUserRoleHere,

    Source = Sql.Database("mydb.servr", "db", [Query="SELECT ..... UserRoleHere", CreateNavigationProperties=false])
in
    Source
</code>```

How can I get the user role (who is viewing the dashboard) in above query?

Body:
I am using Power BI Role Level Security (RLS). In RLS, we have roles like Administrator. I have direct query in Power M Query like,

let
    SomeVar = Record.Field(Table.First(GetSomeVar(Age)), "Column"),
    Role = HowCanIGetUserRoleHere,

    Source = Sql.Database("mydb.servr", "db", [Query="SELECT ..... UserRoleHere", CreateNavigationProperties=false])
in
    Source

How can I get the user role (who is viewing the dashboard) in above query?


问:
How to switch roles on AWS Console while requiring sts:RoleSessionName?
I have two AWS accounts, A and B. I authenticate to account A using SAML, then to access account B I switch roles. The setup worked well until I tried to enforce that, when switching roles the users need to provide their AWS username as the RoleSessionName. When I require that, then switching roles using the AWS cli works fine, but switching roles in the AWS Console stops working.

Here's the role trust policy that works on both cli and console:

```<code>  {
      "Version": "2012-10-17",
      "Statement": [
          {
              "Sid": "",
              "Effect": "Allow",
              "Principal": {
                  "AWS": "arn:aws:iam::84...10:root"
              },
              "Action": "sts:AssumeRole"
          }
      ]
  }
</code>```

Enforcing that the RoleSessionName be the AWS username means to change the policy like this:

```<code>  {
      "Version": "2012-10-17",
      "Statement": [
          {
              "Sid": "",
              "Effect": "Allow",
              "Principal": {
                  "AWS": "arn:aws:iam::84...10:root"
              },
              "Action": "sts:AssumeRole",
              "Condition": {
                  "StringLike": {
                      "sts:RoleSessionName": "${aws:username}"
                  }
              }
          }
      ]
  }
</code>```

Note: if instead of "sts:RoleSessionName": "${aws:username}" I do "sts:RoleSessionName": "*", then I can switch roles on the AWS console, but I can't find a way to figure out a pattern that includes the user name and works. I tried *${aws:username}, ${aws:username}*, and *${aws:username}*.

Once I enforce the sts:RoleSessionName condition on the role trust policy, I can no longer switch roles on the AWS Console. What I see in the CloudTrail events (only visible on us-east-1 region), is that switching the role in the AWS Console is recorded as 2 events: a SwitchRole followed by a AssumeRole.

When I switch roles in the AWS console with the first policy, I see the two events in CloudTrail.

Successful SwitchRole event:

```<code>  {
      "eventVersion": "1.08",
      "userIdentity": {
          "type": "AssumedRole",
          "principalId": "ARO...BYP:me@email.com",
          "arn": "arn:aws:sts::84...10:assumed-role/my-saml-role/me@email.com",
          "accountId": "84...10"
      },
      "eventTime": "2022-12-21T19:34:55Z",
      "eventSource": "signin.amazonaws.com",
      "eventName": "SwitchRole",
      "awsRegion": "us-east-1",
      "sourceIPAddress": "4...0",
      "userAgent": "Mozilla/5.0 ...",
      "requestParameters": null,
      "responseElements": {
          "SwitchRole": "Success"
      },
      "additionalEventData": {
          "RedirectTo": "https://us-east-1.console.aws.amazon.com/cloudtrail/home?region=us-east-1#/events?ReadOnly=false",
          "SwitchTo": "arn:aws:iam::13...20:role/my-role"
      },
      "eventID": "ef759d28-37cb-4ece-af7d-3d7c5326691d",
      "readOnly": false,
      "eventType": "AwsConsoleSignIn",
      "managementEvent": true,
      "recipientAccountId": "84...10",
      "eventCategory": "Management",
      "tlsDetails": {
          "tlsVersion": "TLSv1.2",
          "cipherSuite": "ECDHE-RSA-AES128-GCM-SHA256",
          "clientProvidedHostHeader": "signin.aws.amazon.com"
      }
  }
</code>```

Successful AssumeRole event:

```<code>  {
      "eventVersion": "1.08",
      "userIdentity": {
          "type": "AssumedRole",
          "principalId": "ARO...BYP:me@email.com",
          "arn": "arn:aws:sts::84...10:assumed-role/my-saml-role/me@email.com",
          "accountId": "84...10",
          "accessKeyId": "ASIA...OA",
          "sessionContext": {
              "sessionIssuer": {
                  "type": "Role",
                  "principalId": "AR...BYP",
                  "arn": "arn:aws:sts::84...10:assumed-role/my-saml-role",
                  "accountId": "84...10",
                  "userName": "my-saml-role"
              },
              "webIdFederationData": {},
              "attributes": {
                  "creationDate": "2022-12-21T19:10:25Z",
                  "mfaAuthenticated": "false"
              }
          }
      },
      "eventTime": "2022-12-21T19:34:55Z",
      "eventSource": "sts.amazonaws.com",
      "eventName": "AssumeRole",
      "awsRegion": "us-east-1",
      "sourceIPAddress": "4...0",
      "userAgent": "AWS Signin, aws-internal/3 aws-sdk-java/1.12.339 Linux/5.4.215-mr.86.metal1.x86_64 OpenJDK_64-Bit_Server_VM/25.352-b09 java/1.8.0_352 kotlin/1.3.72 vendor/Oracle_Corporation cfg/retry-mode/standard",
      "requestParameters": {
          "roleArn": "arn:aws:iam::13...20:role/my-role",
          "roleSessionName": "me@email.com"
      },
      "responseElements": {
          "credentials": {
              "accessKeyId": "AS...FJ",
              "sessionToken": "IQ...VMRCMyvsQ==",
              "expiration": "Dec 21, 2022, 8:34:55 PM"
          },
          "assumedRoleUser": {
              "assumedRoleId": "AR...PX:me@email.com",
              "arn": "arn:aws:sts::13...20:assumed-role/my-role/me@email.com"
          }
      },
      "requestID": "6d9b977a-e489-4261-97b5-48c0167d82ea",
      "eventID": "1f7178bd-046b-4e20-b264-dd86b8753a45",
      "readOnly": true,
      "resources": [
          {
              "accountId": "13...20",
              "type": "AWS::IAM::Role",
              "ARN": "arn:aws:iam::13...20:role/my-role"
          }
      ],
      "eventType": "AwsApiCall",
      "managementEvent": true,
      "recipientAccountId": "84...10",
      "sharedEventID": "e49297fc-883e-4160-86bc-d157bc58a3ee",
      "eventCategory": "Management",
      "tlsDetails": {
          "tlsVersion": "TLSv1.2",
          "cipherSuite": "ECDHE-RSA-AES128-GCM-SHA256",
          "clientProvidedHostHeader": "sts.us-east-1.amazonaws.com"
      }
  }
</code>```

When I enforce the sts:RoleSessionName requirement, then the SwitchRole event fails with error switchrole.error.invalidparams.

Failed SwitchRole event

```<code>  {
      "eventVersion": "1.08",
      "userIdentity": {
          "type": "AssumedRole",
          "principalId": "AR..YP:me@email.com",
          "arn": "arn:aws:sts::84...10:assumed-role/my-saml-role/me@email.com",
          "accountId": "84...10"
      },
      "eventTime": "2022-12-21T19:25:23Z",
      "eventSource": "signin.amazonaws.com",
      "eventName": "SwitchRole",
      "awsRegion": "us-east-1",
      "sourceIPAddress": "4...0",
      "userAgent": "Mozilla/5.0 ...",
      "errorMessage": "switchrole.error.invalidparams",
      "requestParameters": null,
      "responseElements": {
          "SwitchRole": "Failure"
      },
      "additionalEventData": {
          "RedirectTo": "https://eu-central-1.console.aws.amazon.com/cloudtrail/home?region=eu-central-1#/events?ReadOnly=false",
          "SwitchTo": "arn:aws:iam::13..20:role/my-role"
      },
      "eventID": "76de870e-7e75-43a9-a908-d34616022553",
      "readOnly": false,
      "eventType": "AwsConsoleSignIn",
      "managementEvent": true,
      "recipientAccountId": "84...10",
      "eventCategory": "Management",
      "tlsDetails": {
          "tlsVersion": "TLSv1.2",
          "cipherSuite": "ECDHE-RSA-AES128-GCM-SHA256",
          "clientProvidedHostHeader": "signin.aws.amazon.com"
      }
  }
</code>```

The AWS docs mentions that sts:RoleSessionName is available when assuming a role in the AWS Console.

sts:RoleSessionName Works with string operators.

Use this key to compare the session name that a principal specifies
when assuming a role with the value that is specified in the policy.

Availability – This key is present in the request when the principal
assumes the role using the AWS Management Console, any assume-role CLI
command, or any AWS STS AssumeRole API operation.

Src: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#condition-keys-sts

Body:
I have two AWS accounts, A and B. I authenticate to account A using SAML, then to access account B I switch roles. The setup worked well until I tried to enforce that, when switching roles the users need to provide their AWS username as the RoleSessionName. When I require that, then switching roles using the AWS cli works fine, but switching roles in the AWS Console stops working.

Here's the role trust policy that works on both cli and console:

  {
      "Version": "2012-10-17",
      "Statement": [
          {
              "Sid": "",
              "Effect": "Allow",
              "Principal": {
                  "AWS": "arn:aws:iam::84...10:root"
              },
              "Action": "sts:AssumeRole"
          }
      ]
  }

Enforcing that the RoleSessionName be the AWS username means to change the policy like this:

  {
      "Version": "2012-10-17",
      "Statement": [
          {
              "Sid": "",
              "Effect": "Allow",
              "Principal": {
                  "AWS": "arn:aws:iam::84...10:root"
              },
              "Action": "sts:AssumeRole",
              "Condition": {
                  "StringLike": {
                      "sts:RoleSessionName": "${aws:username}"
                  }
              }
          }
      ]
  }

Note: if instead of "sts:RoleSessionName": "${aws:username}" I do "sts:RoleSessionName": "*", then I can switch roles on the AWS console, but I can't find a way to figure out a pattern that includes the user name and works. I tried *${aws:username}, ${aws:username}*, and *${aws:username}*.

Once I enforce the sts:RoleSessionName condition on the role trust policy, I can no longer switch roles on the AWS Console. What I see in the CloudTrail events (only visible on us-east-1 region), is that switching the role in the AWS Console is recorded as 2 events: a SwitchRole followed by a AssumeRole.

When I switch roles in the AWS console with the first policy, I see the two events in CloudTrail.

Successful SwitchRole event:

  {
      "eventVersion": "1.08",
      "userIdentity": {
          "type": "AssumedRole",
          "principalId": "ARO...BYP:me@email.com",
          "arn": "arn:aws:sts::84...10:assumed-role/my-saml-role/me@email.com",
          "accountId": "84...10"
      },
      "eventTime": "2022-12-21T19:34:55Z",
      "eventSource": "signin.amazonaws.com",
      "eventName": "SwitchRole",
      "awsRegion": "us-east-1",
      "sourceIPAddress": "4...0",
      "userAgent": "Mozilla/5.0 ...",
      "requestParameters": null,
      "responseElements": {
          "SwitchRole": "Success"
      },
      "additionalEventData": {
          "RedirectTo": "https://us-east-1.console.aws.amazon.com/cloudtrail/home?region=us-east-1#/events?ReadOnly=false",
          "SwitchTo": "arn:aws:iam::13...20:role/my-role"
      },
      "eventID": "ef759d28-37cb-4ece-af7d-3d7c5326691d",
      "readOnly": false,
      "eventType": "AwsConsoleSignIn",
      "managementEvent": true,
      "recipientAccountId": "84...10",
      "eventCategory": "Management",
      "tlsDetails": {
          "tlsVersion": "TLSv1.2",
          "cipherSuite": "ECDHE-RSA-AES128-GCM-SHA256",
          "clientProvidedHostHeader": "signin.aws.amazon.com"
      }
  }

Successful AssumeRole event:

  {
      "eventVersion": "1.08",
      "userIdentity": {
          "type": "AssumedRole",
          "principalId": "ARO...BYP:me@email.com",
          "arn": "arn:aws:sts::84...10:assumed-role/my-saml-role/me@email.com",
          "accountId": "84...10",
          "accessKeyId": "ASIA...OA",
          "sessionContext": {
              "sessionIssuer": {
                  "type": "Role",
                  "principalId": "AR...BYP",
                  "arn": "arn:aws:sts::84...10:assumed-role/my-saml-role",
                  "accountId": "84...10",
                  "userName": "my-saml-role"
              },
              "webIdFederationData": {},
              "attributes": {
                  "creationDate": "2022-12-21T19:10:25Z",
                  "mfaAuthenticated": "false"
              }
          }
      },
      "eventTime": "2022-12-21T19:34:55Z",
      "eventSource": "sts.amazonaws.com",
      "eventName": "AssumeRole",
      "awsRegion": "us-east-1",
      "sourceIPAddress": "4...0",
      "userAgent": "AWS Signin, aws-internal/3 aws-sdk-java/1.12.339 Linux/5.4.215-mr.86.metal1.x86_64 OpenJDK_64-Bit_Server_VM/25.352-b09 java/1.8.0_352 kotlin/1.3.72 vendor/Oracle_Corporation cfg/retry-mode/standard",
      "requestParameters": {
          "roleArn": "arn:aws:iam::13...20:role/my-role",
          "roleSessionName": "me@email.com"
      },
      "responseElements": {
          "credentials": {
              "accessKeyId": "AS...FJ",
              "sessionToken": "IQ...VMRCMyvsQ==",
              "expiration": "Dec 21, 2022, 8:34:55 PM"
          },
          "assumedRoleUser": {
              "assumedRoleId": "AR...PX:me@email.com",
              "arn": "arn:aws:sts::13...20:assumed-role/my-role/me@email.com"
          }
      },
      "requestID": "6d9b977a-e489-4261-97b5-48c0167d82ea",
      "eventID": "1f7178bd-046b-4e20-b264-dd86b8753a45",
      "readOnly": true,
      "resources": [
          {
              "accountId": "13...20",
              "type": "AWS::IAM::Role",
              "ARN": "arn:aws:iam::13...20:role/my-role"
          }
      ],
      "eventType": "AwsApiCall",
      "managementEvent": true,
      "recipientAccountId": "84...10",
      "sharedEventID": "e49297fc-883e-4160-86bc-d157bc58a3ee",
      "eventCategory": "Management",
      "tlsDetails": {
          "tlsVersion": "TLSv1.2",
          "cipherSuite": "ECDHE-RSA-AES128-GCM-SHA256",
          "clientProvidedHostHeader": "sts.us-east-1.amazonaws.com"
      }
  }

When I enforce the sts:RoleSessionName requirement, then the SwitchRole event fails with error switchrole.error.invalidparams.

Failed SwitchRole event

  {
      "eventVersion": "1.08",
      "userIdentity": {
          "type": "AssumedRole",
          "principalId": "AR..YP:me@email.com",
          "arn": "arn:aws:sts::84...10:assumed-role/my-saml-role/me@email.com",
          "accountId": "84...10"
      },
      "eventTime": "2022-12-21T19:25:23Z",
      "eventSource": "signin.amazonaws.com",
      "eventName": "SwitchRole",
      "awsRegion": "us-east-1",
      "sourceIPAddress": "4...0",
      "userAgent": "Mozilla/5.0 ...",
      "errorMessage": "switchrole.error.invalidparams",
      "requestParameters": null,
      "responseElements": {
          "SwitchRole": "Failure"
      },
      "additionalEventData": {
          "RedirectTo": "https://eu-central-1.console.aws.amazon.com/cloudtrail/home?region=eu-central-1#/events?ReadOnly=false",
          "SwitchTo": "arn:aws:iam::13..20:role/my-role"
      },
      "eventID": "76de870e-7e75-43a9-a908-d34616022553",
      "readOnly": false,
      "eventType": "AwsConsoleSignIn",
      "managementEvent": true,
      "recipientAccountId": "84...10",
      "eventCategory": "Management",
      "tlsDetails": {
          "tlsVersion": "TLSv1.2",
          "cipherSuite": "ECDHE-RSA-AES128-GCM-SHA256",
          "clientProvidedHostHeader": "signin.aws.amazon.com"
      }
  }

The AWS docs mentions that sts:RoleSessionName is available when assuming a role in the AWS Console.

sts:RoleSessionName Works with string operators.

Use this key to compare the session name that a principal specifies
when assuming a role with the value that is specified in the policy.

Availability – This key is present in the request when the principal
assumes the role using the AWS Management Console, any assume-role CLI
command, or any AWS STS AssumeRole API operation.

Src: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#condition-keys-sts


问:
Why am I getting the "Key error" in this code Django Rest Framework?
Well, I am trying to show ads after every 10th post in my feed in Django rest framework with both ad and post model separate.
I'm actually stuck and will really appreciate anyone that will help me solve this problem.
Here's my code:

My Post & Ad Model

```<code>class Post(models.Model):
question = models.TextField(max_length=500)
image = models.ImageField(upload_to='posts/', blank=True, null=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True)
created_at = models.DateTimeField(auto_now_add=True)
# tags = models.ManyToManyField(Tag, blank=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
upvote = models.ManyToManyField(User, related_name="like", blank=True)
downvote = models.ManyToManyField(User, related_name="dislike", blank=True)
is_ad = models.BooleanField(default=False)

ordering = ["-created_at"]

def __str__(self):
    return self.question

class Ad(models.Model):
# unique identifier for the ad
id = models.AutoField(primary_key=True)

# name of the ad
name = models.CharField(max_length=255)

# image for the ad
image = models.ImageField(upload_to='ads/images/', blank=True, null=True)

# additional images for the ad
image_2 = models.ImageField(upload_to='ads/images/', blank=True, null=True)
image_3 = models.ImageField(upload_to='ads/images/', blank=True, null=True)
image_4 = models.ImageField(upload_to='ads/images/', blank=True, null=True)
image_5 = models.ImageField(upload_to='ads/images/', blank=True, null=True)

# URL that the ad should redirect to when clicked
url = models.URLField()

# start and end dates for the ad
start_date = models.DateField()
end_date = models.DateField()

# targeting information for the ad
targeting = models.TextField()

# budget for the ad
budget = models.DecimalField(max_digits=10, decimal_places=2)

# ad delivery type (standard or accelerated)
delivery_type = models.CharField(max_length=255)

# ad optimization goal (clicks, impressions, daily unique reach, etc.)
optimization_goal = models.CharField(max_length=255)

# ad placement (desktop, mobile, etc.)
placement = models.CharField(max_length=255)

# ad status (active, paused, deleted)
status = models.CharField(max_length=255)
</code>```

My Post & Ad Serializer

```<code>class AdSerializer(serializers.ModelSerializer):
    class Meta:
       model = Ad
       fields = '__all__'

class PostSerializer(serializers.ModelSerializer):
    class Meta:
       model = Post
       fields = ['id', 'question', 'image', 'category', 'created_at', 'author', 'upvote', 'downvote', 'is_ad']
</code>```

My Views

```<code> class PostAddListView(generics.ListAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer

def list(self, request, *args, **kwargs):
    # retrieve the list of posts
    posts = self.get_queryset()

    # initialize the counter variable
    counter = 0

    # create an empty list to store the response
    response = []

    # iterate over the posts
    for post in posts:
        # increment the counter
        counter += 1

        # add the post to the response
        response.append(post)

        # check if the counter is divisible by 10
        if counter % 10 == 0:
            # retrieve a random ad
            ad = Ad.objects.order_by('?').first()
            if ad:
                # serialize the ad using the AdSerializer
                serializer = AdSerializer(ad)
                # add the ad to the response
                response.append(serializer.data)

    # serialize the response using the PostSerializer
    serializer = self.get_serializer(response, many=True)
    return Response(serializer.data)
</code>```

Body:
Well, I am trying to show ads after every 10th post in my feed in Django rest framework with both ad and post model separate.
I'm actually stuck and will really appreciate anyone that will help me solve this problem.
Here's my code:

My Post & Ad Model

class Post(models.Model):
question = models.TextField(max_length=500)
image = models.ImageField(upload_to='posts/', blank=True, null=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True)
created_at = models.DateTimeField(auto_now_add=True)
# tags = models.ManyToManyField(Tag, blank=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
upvote = models.ManyToManyField(User, related_name="like", blank=True)
downvote = models.ManyToManyField(User, related_name="dislike", blank=True)
is_ad = models.BooleanField(default=False)

ordering = ["-created_at"]

def __str__(self):
    return self.question

class Ad(models.Model):
# unique identifier for the ad
id = models.AutoField(primary_key=True)

# name of the ad
name = models.CharField(max_length=255)

# image for the ad
image = models.ImageField(upload_to='ads/images/', blank=True, null=True)

# additional images for the ad
image_2 = models.ImageField(upload_to='ads/images/', blank=True, null=True)
image_3 = models.ImageField(upload_to='ads/images/', blank=True, null=True)
image_4 = models.ImageField(upload_to='ads/images/', blank=True, null=True)
image_5 = models.ImageField(upload_to='ads/images/', blank=True, null=True)

# URL that the ad should redirect to when clicked
url = models.URLField()

# start and end dates for the ad
start_date = models.DateField()
end_date = models.DateField()

# targeting information for the ad
targeting = models.TextField()

# budget for the ad
budget = models.DecimalField(max_digits=10, decimal_places=2)

# ad delivery type (standard or accelerated)
delivery_type = models.CharField(max_length=255)

# ad optimization goal (clicks, impressions, daily unique reach, etc.)
optimization_goal = models.CharField(max_length=255)

# ad placement (desktop, mobile, etc.)
placement = models.CharField(max_length=255)

# ad status (active, paused, deleted)
status = models.CharField(max_length=255)

My Post & Ad Serializer

class AdSerializer(serializers.ModelSerializer):
    class Meta:
       model = Ad
       fields = '__all__'

class PostSerializer(serializers.ModelSerializer):
    class Meta:
       model = Post
       fields = ['id', 'question', 'image', 'category', 'created_at', 'author', 'upvote', 'downvote', 'is_ad']

My Views

 class PostAddListView(generics.ListAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer

def list(self, request, *args, **kwargs):
    # retrieve the list of posts
    posts = self.get_queryset()

    # initialize the counter variable
    counter = 0

    # create an empty list to store the response
    response = []

    # iterate over the posts
    for post in posts:
        # increment the counter
        counter += 1

        # add the post to the response
        response.append(post)

        # check if the counter is divisible by 10
        if counter % 10 == 0:
            # retrieve a random ad
            ad = Ad.objects.order_by('?').first()
            if ad:
                # serialize the ad using the AdSerializer
                serializer = AdSerializer(ad)
                # add the ad to the response
                response.append(serializer.data)

    # serialize the response using the PostSerializer
    serializer = self.get_serializer(response, many=True)
    return Response(serializer.data)


问:
Troubleshoot Session Timeout Issues in ASP.NET
I'm having issues with session timeout issues with a public facing site that is utilized by several clients that may have various "secured" browser configurations.  In general we have the session timeout set for 15 mins within the web.config.  However, they are getting a timeout within a min or within 30 seconds or so for every page postback.  Within our environment and with some other clients they have no issues and the timeout occurs as expected.  We are unable to access their systems and know very little about their infrastructure.  The only thing I'm thinking is they may have configuration to disallow cookies or delete/wipe them every few seconds etc.  Not sure....

I'm at a loss on what to look at as within our web.config we set our sessionstate as follows.

```<code><sessionState allowCustomSqlDatabase="true" cookieless="UseCookies" mode="InProc" sqlConnectionString="somestring Integrated Security=SSPI;pooling=true;encrypt=true;trustservercertificate=true" timeout="15">
</code>```

If someone has ideas on where to look.

Body:
I'm having issues with session timeout issues with a public facing site that is utilized by several clients that may have various "secured" browser configurations.  In general we have the session timeout set for 15 mins within the web.config.  However, they are getting a timeout within a min or within 30 seconds or so for every page postback.  Within our environment and with some other clients they have no issues and the timeout occurs as expected.  We are unable to access their systems and know very little about their infrastructure.  The only thing I'm thinking is they may have configuration to disallow cookies or delete/wipe them every few seconds etc.  Not sure....

I'm at a loss on what to look at as within our web.config we set our sessionstate as follows.

<sessionState allowCustomSqlDatabase="true" cookieless="UseCookies" mode="InProc" sqlConnectionString="somestring Integrated Security=SSPI;pooling=true;encrypt=true;trustservercertificate=true" timeout="15">

If someone has ideas on where to look.


问:
Is it possible to change IBM Cloud plan of existing Database?
Is it possible to change IBM Cloud plan of existing Database ?

I am expecting to change the current standard plan to elite plan as its available in Dallas region.


问:
Karma ERROR: zone-testing.js is needed for the fakeAsync() test helper but could not be found
I having issues trying to run tests for an Angular app using Karma an Jasmine. Team decided to get back to testing this app after a while, currently we are using Angular 14 here and we want to improve the testing phase for the app. All of the components fail at testing but all of them fail with the same error:

Error: zone-testing.js is needed for the fakeAsync() test helper but could not be found.

No matter which spec file I isolate with fdescribe this error will always show up

Tried many solutions but none of them have worked:

Placed import 'zone.js/testing'; at the start of test.js file

Changed the configuration from .eslintsrc.json to prevent the sorting of imports

imported zone.js/testing at the top of the spec file itself

Changed Karma an Jasmine to different versions

Created a fresh Angular app

also imported

```<code>import 'zone.js/dist/zone-testing';
import 'zone.js';
import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
</code>```

Body:
I having issues trying to run tests for an Angular app using Karma an Jasmine. Team decided to get back to testing this app after a while, currently we are using Angular 14 here and we want to improve the testing phase for the app. All of the components fail at testing but all of them fail with the same error:

Error: zone-testing.js is needed for the fakeAsync() test helper but could not be found.

No matter which spec file I isolate with fdescribe this error will always show up

Tried many solutions but none of them have worked:

Placed import 'zone.js/testing'; at the start of test.js file

Changed the configuration from .eslintsrc.json to prevent the sorting of imports

imported zone.js/testing at the top of the spec file itself

Changed Karma an Jasmine to different versions

Created a fresh Angular app

also imported

import 'zone.js/dist/zone-testing';
import 'zone.js';
import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';


问:
Gmail SMTP plugin for wordpress/woocommerce
I am trying to make Gmail SMTP puligin work with my woocommerce/wordpress site.
I'm having this notice from Google Cloud:

Verification Status
Pending developer action
Complete all actions below. Update your email thread with our Trust and Safety team after you have completed an action. The Trust and Safety team will continue the verification process once all actions are completed. Learn more
Action Required
Comply with domain verification requirements
Ensure your application's domains have completed the Search Console verification process
Update brand information
Ensure that your app's name, logo, and OAuth clients meet all requirements

I asked about this from Google and they gave me this answer:

Thanks for your patience while we reviewed your project.

Since your app is a Gmail SMTP plug-in for Wordpress, and you or the site admin are the only users of the app, we recommend that you keep using your app with the “unverified app” screen. The Gmail API isn't for public use in this case, so you do not need to get verified.

If you are having issues activating the plugin, you can see all your support options in General Support.

Please note that Google also participates in community discussion groups and mailing lists that can help you find answers or troubleshoot problems.

We strongly recommend that you submit a question via any of the below third-party community discussion groups and/or mailing lists:

Stack Overflow - A question and answer site for programmers.
Server Fault - A question and answer site for deploying and managing IT platforms.
Google Developers - Issue tracking for features and bugs. Search existing issues before creating a new one.
Google Groups - A place for non-technical how-to questions.
google-app-engine
gce-discussion
kubernetes-users
google-cloud-bigtable-discuss
google-cloud-sql-discuss
gcd-discuss
cloud-dns-discuss
cloud-dataproc-discuss
cloud-pubsub-discuss
cloud-nl-discuss
cloud-speech-discuss
google-translate-api
cloud-videointel-discuss
cloud-vision-discuss
google-cloud-dev
google-stackdriver-discussion
Android-developers

I can't use this app without Google approval. I tried to send a test email and the plugin gave me this error/answer:
Gmail SMTP plugin cannot send email until you enter your credentials in the settings and grant access to your web application.

So how can I make Gmail SMTP work with my wordpress/woocommerce site?

Best Regards,
Tuomo Nurkkala

I think I tried everything and I asked from Google about this problem, but I'm not so sure if I understood their message correctly.

Best Regards,
Tuomo Nurkkala


问:
Is this a race condition happening in the Chocolatey package install?
I have a userdata script in AWS Cloudformation that runs an install chocolatey package command. This package has all the needed steps to bootstrap the new ec2 it launches. One of these is to add an administrator group to the local group members. I have some write log commands in order to get more accurate troubleshooting, except one of the checks fail, giving a false negative. Is there a way to fix this? I think it's a race condition.
For example the code would look like :

```<code>#this checks if the feature isn't already installed. If it's not there, it will install it

If (!($getMembers.Name -Contains $groupMember))
    -add the group here

#Then I run the same check after all of the other stuff installs, just to confirm that it did:
If (!($getMembers.Name -Contains $groupMember))
    -Write event log that it didnt add the member.
</code>```

Is there a race condition happening here where the if statement checks too fast? Because I have also tried adding this second check a couple more lines below the first add command, and it still gives me false negatives. Is there no workaround to this error?

I tried adding it a few lines below the initial add, I tried sleeping the machine, and right now my makeshift solution is to write to the event log, "Install command has been run but the feature wasn't detected. Please check manually".

I want to know what kind of workarounds there are, if any. Is this because the checks are done in the same script as the install command? Should this be accomplished using 2 chocolatey packages? One for installing it all and one for logging?

Body:
I have a userdata script in AWS Cloudformation that runs an install chocolatey package command. This package has all the needed steps to bootstrap the new ec2 it launches. One of these is to add an administrator group to the local group members. I have some write log commands in order to get more accurate troubleshooting, except one of the checks fail, giving a false negative. Is there a way to fix this? I think it's a race condition.
For example the code would look like :

#this checks if the feature isn't already installed. If it's not there, it will install it

If (!($getMembers.Name -Contains $groupMember))
    -add the group here

#Then I run the same check after all of the other stuff installs, just to confirm that it did:
If (!($getMembers.Name -Contains $groupMember))
    -Write event log that it didnt add the member.

Is there a race condition happening here where the if statement checks too fast? Because I have also tried adding this second check a couple more lines below the first add command, and it still gives me false negatives. Is there no workaround to this error?

I tried adding it a few lines below the initial add, I tried sleeping the machine, and right now my makeshift solution is to write to the event log, "Install command has been run but the feature wasn't detected. Please check manually".

I want to know what kind of workarounds there are, if any. Is this because the checks are done in the same script as the install command? Should this be accomplished using 2 chocolatey packages? One for installing it all and one for logging?


问:
Trying to receive status code from meta tag, receiving null in ReactJs
I am trying to figure out how to get the status code of current page I am on without using express, nodejs, etc. I am doing this in my constructor to get the status code from meta tag, however, it is showing null when I console log it.

```<code>constructor(props) {
    super(props);
    let site = props.CONTENT.byTemplate("landing_page")[0];
    let nav = props.CONTENT.childrenById(site.id);
    this.global = props.CONTENT.byTemplate("global_page")[0];
    this.state = {
      popupOpen: false,
    };
    const metaStatus = document.querySelector('meta[name="status"]');
    this.reqStatus = metaStatus.content;
    console.log(reqStatus);
  }
</code>```

The console log always shows null for some reason. Is there a reason why this may be happening? Or is there another way to handle getting the status code being returned from the page? Any help is appreciated. Thanks!

Body:
I am trying to figure out how to get the status code of current page I am on without using express, nodejs, etc. I am doing this in my constructor to get the status code from meta tag, however, it is showing null when I console log it.

constructor(props) {
    super(props);
    let site = props.CONTENT.byTemplate("landing_page")[0];
    let nav = props.CONTENT.childrenById(site.id);
    this.global = props.CONTENT.byTemplate("global_page")[0];
    this.state = {
      popupOpen: false,
    };
    const metaStatus = document.querySelector('meta[name="status"]');
    this.reqStatus = metaStatus.content;
    console.log(reqStatus);
  }

The console log always shows null for some reason. Is there a reason why this may be happening? Or is there another way to handle getting the status code being returned from the page? Any help is appreciated. Thanks!


问:
How to get a precise value for a Docker container's network usage
For the project I'm working on, I need to be able to measure the total amount of network traffic for a specific container over a period of time. These periods of time generally are about 20 seconds, and the precision needed realistically is only in kilobytes. Ideally this solution would not involve the use of additional software either in the containers or on the host machine, and would be suitible for linux/windows hosts.

Originally I had planned to use the 'NET I/O' attribute of the 'docker stats' command, though the field is automatically formatted to a more human readable format (i.e. '200 MB') which means for containers that have been running for some time, I can't get the precision I need.

Is there any way to get the raw value of 'NET I/O' or to reset the running count? Outside of this I've explored using something tshark or iptables, but like I said above ideally the solution would not require additional programs. Though if there aren't any good solutions that fit that criteria any other suggestions would be welcome. Thank you!


问:
How do I control the overflow of an element when the parent width is defined by max-content?
I want to be able to control the width of a parent element to a child element that may exceed the width of the container - of which width is defined by min content and controlled by an element by max content.

article {
  width: min-content;

  background: cyan;
}

.max-content {
  width: max-content;
}

.overflowing-width {
  width: 100vw;
  height: 20px;

  background: darkred;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article>
  <h2 class="max-content">This should define the width of the container.</h2>

  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas ac justo tortor. Quisque interdum tempus ipsum, at facilisis libero lobortis vel. Nunc id justo quis risus porta elementum. Duis facilisis a magna sit amet tincidunt. In fermentum et erat quis imperdiet. Vivamus et orci quam. Suspendisse sollicitudin urna id neque bibendum, at luctus orci scelerisque. Integer hendrerit consectetur enim, sed accumsan risus blandit vel. Mauris efficitur orci non luctus pellentesque.</p>
</article>

<article>
  <h2 class="max-content">This should define the width of the container.</h2>

  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas ac justo tortor. Quisque interdum tempus ipsum, at facilisis libero lobortis vel. Nunc id justo quis risus porta elementum. Duis facilisis a magna sit amet tincidunt. In fermentum et erat quis imperdiet. Vivamus et orci quam. Suspendisse sollicitudin urna id neque bibendum, at luctus orci scelerisque. Integer hendrerit consectetur enim, sed accumsan risus blandit vel. Mauris efficitur orci non luctus pellentesque.</p>

  <div class="overflow-control">
    <div class="overflowing-width"></div>
  </div>
</article></code>```

The second article's overflow-control element should not exceed the width of the
.

I have tried to use relative positioning through the article element:

```<code>article {
  position: relative;
}

.overflow-control {
  max-width: 100%;

  overflow: auto;
}
</code>```

But this does not alter the behavior what-so-ever.

I have also tried adding an overflow: hidden property to the article element with no effect.

Body:
I want to be able to control the width of a parent element to a child element that may exceed the width of the container - of which width is defined by min content and controlled by an element by max content.

article {
  width: min-content;

  background: cyan;
}

.max-content {
  width: max-content;
}

.overflowing-width {
  width: 100vw;
  height: 20px;

  background: darkred;
}

This should define the width of the container.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas ac justo tortor. Quisque interdum tempus ipsum, at facilisis libero lobortis vel. Nunc id justo quis risus porta elementum. Duis facilisis a magna sit amet tincidunt. In fermentum et erat quis imperdiet. Vivamus et orci quam. Suspendisse sollicitudin urna id neque bibendum, at luctus orci scelerisque. Integer hendrerit consectetur enim, sed accumsan risus blandit vel. Mauris efficitur orci non luctus pellentesque.

This should define the width of the container.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas ac justo tortor. Quisque interdum tempus ipsum, at facilisis libero lobortis vel. Nunc id justo quis risus porta elementum. Duis facilisis a magna sit amet tincidunt. In fermentum et erat quis imperdiet. Vivamus et orci quam. Suspendisse sollicitudin urna id neque bibendum, at luctus orci scelerisque. Integer hendrerit consectetur enim, sed accumsan risus blandit vel. Mauris efficitur orci non luctus pellentesque.

The second article's overflow-control element should not exceed the width of the
.

I have tried to use relative positioning through the article element:

article {
  position: relative;
}

.overflow-control {
  max-width: 100%;

  overflow: auto;
}

But this does not alter the behavior what-so-ever.

I have also tried adding an overflow: hidden property to the article element with no effect.


问:
How to make Jest failing message more detailed?
When jest fails for a function that has an object parameter I get:

```<code>  ● myFunc function should work correctly › myFunc([ 'valueText', [Object] ]) should be null
</code>```

How can I see the contents of the 2nd parameter instead of [Object]?

I tried using printBasicPrototype: false and --verbose configs with no luck.

Body:
When jest fails for a function that has an object parameter I get:

  ● myFunc function should work correctly › myFunc([ 'valueText', [Object] ]) should be null

How can I see the contents of the 2nd parameter instead of [Object]?

I tried using printBasicPrototype: false and --verbose configs with no luck.


问:
modelsummary not reading columns from custom tidy and glance functions
Apologies for not having a full reproducible example here, but the models take a fairly long time to run and the model objects are fairly large.

I have a chunk of code that to generate a table from three multilevel multinomial logit models run using brms. This is a chunk of code that worked previously, and it's been a couple of years since I first assembled the code, but when I try to run it I'm running into problems getting modelsummary to read the contents of the custom tidy and glance functions.

There's a lot here, but here's the code. I've tried to use notes to break down what's going on at each stage. The gist of it is that I read in the models, make a list, assign a custom class to the three models, create the custom tidy and glance functions, and then run the modelsummary function at the end. It should generate a modelsummary table with 9 columns, 3 for each model.

```<code>
# Read in three files
m.c.t1 <- readRDS(here::here("../Book/Output/Chapter-Contact/m.c.t1.rds"))
m.c.g1 <- readRDS(here::here("../Book/Output/Chapter-Contact/m.c.g1.rds"))
m.c.p1 <- readRDS(here::here("../Book/Output/Chapter-Contact/m.c.p1.rds"))

# Create the list of models. Omit model names because modelsummary pastes them in the table header for every column and makes it too wide. Will add single header to span three relevant columns manually later.
mod.list <- list(" " = m.c.t1,
                 " " = m.c.p1,
                 " " = m.c.g1)

# Assign custom class to each model in the list. Maybe not necessary anymore?
for (i in seq_along(mod.list)){
  class(mod.list[[i]]) <- c("custom", class(mod.list[[i]]))
}

#### Pay close attention to how brms and/or parameters is treating the % symbols in the income variable.Depending on the output the code below will need to be updated so the income variable isn't dropped.

# brms collapes the coefficient/variable name in with the outcome level of multinomial models. Use a custom tidy method to extract level names and put them into a separate columns.
tidy_custom.brmsfit <- function(x, conf.level=.95, ...) {
  out = parameters::parameters(x, ci=conf.level, verbose=FALSE) %>%
        parameters::standardize_names(style="broom") %>%
        mutate(group = case_when(grepl("mudk", term) ~ "Don't Know",
                                 grepl("muneg", term) ~ "Negative",
                                 grepl("mupos", term) ~ "Positive"),
               term = gsub("dk|neg|pos", "", term)) %>% # remove outcome level prefix brms attaches to variable names
    as.data.frame()

  return(out)
}

# Run custom glance function to limit gof output.
glance_custom.brmsfit <- function(x, ...) {
  ret <- tibble::tibble(N = summary(x)$nobs)
  return(ret)
}

# Run through the model list and extract varying intercept/effect components and dispersion metrics. Creates a new set of rows that can be inserted at the bottom of the table.
rows <- lapply(mod.list, function(x){

  temp.sd <- parameters::parameters(x, effect = "random")  %>%
    filter(grepl(".*sd.*", Parameter)) %>%
    filter(grepl(".*persYes.*|.*nonpersYes.*|.*Intercept.*", Parameter)) %>%
    dplyr::select(Parameter, Median) %>%
    dplyr::mutate(Median = as.character(round(Median, 2)),
      y.level = case_when(
      grepl(".*mudk.*", Parameter) ~ "dk",
      grepl(".*mupos.*", Parameter) ~ "pos",
      grepl(".*muneg.*", Parameter) ~ "neg",
    ),
    Parameter = gsub("_mudk_|_mupos_|_muneg_", "_", Parameter)) %>%
    pivot_wider(id_cols = Parameter,
                values_from = Median,
                names_from = y.level) %>%
    mutate(Parameter = case_when(
      grepl(".*Intercept.*", Parameter) ~ "sd(Intercept)"
    ))

  temp.obs <- tibble::tribble(~Parameter, ~dk, ~neg, ~pos,
                              "N", as.character(nobs(x)), "", "",
                              "Group", "Country", "", "",
                              "\\# Groups", as.character(length(unique(x$data$country))), "", "")

  temp.com <- bind_rows(temp.obs, temp.sd)

  return(temp.com)

  }
)

# Combine the three outputs from the previous lapplycommand and filter out the relevant columns.
rows.com <- bind_cols(rows[[1]], rows[[2]], rows[[3]]) %>%
  dplyr::select(1, 2, 3, 4, 6, 7, 8, 10, 11, 12)

# Name the columns to facilitate appending later.
names(rows.com) <- c("term", "col1", "col2", "col3", "col4", "col5", "col6", "col7", "col8", "col9")

# Turn off GOF stuff
gof.check <- modelsummary::gof_map
gof.check$omit <- TRUE

# Create a list of coefficient names and labels
coef.list <- tibble::tribble(~raw, ~clean,
                            "b_mu_contact_persYes", "Personal Contact: Yes",
                            "b_mu_contact_persDontknowDdeclinetoanswer", "Personal Contact: DK/Decline",
                            "b_mu_contact_nonpersYes", "Network Contact: Yes",
                            "b_mu_contact_nonpersDontknowDdeclinetoanswer", "Network Contact: DK/Decline",
                            "b_mu_benefit_persYes", "Personal Benefit: Yes",
                            "b_mu_benefit_persDontknowDdeclinetoanswer", "Personal Benefit: DK/Decline",
                            "b_mu_benefit_nonpersYes", "Network Benefit: Yes",
                            "b_mu_benefit_nonpersDontknowDdeclinetoanswer", "Network Benefit: DK/Decline",
                            "b_mu_age25to34years", "25-34",
                            "b_mu_age35to44years", "35-44",
                            "b_mu_age45to54years", "45-54",
                            "b_mu_age55to64years", "55-65",
                            "b_mu_ageAge65orolder", ">65",
                            "b_mu_income.5.cat21M40%", "21-40",
                            "b_mu_income.5.cat41M60%", "41-60",
                            "b_mu_income.5.cat61M80%", "61-80",
                            "b_mu_income.5.cat81M100%", "81-100",
                            "b_mu_genderFemale", "Female",
                            "b_mu_genderNonMbinary", "Non-binary",
                            "b_mu_genderNoneoftheabove", "None of the above",
                            "b_mu_minorityYes", "Minority: Yes",
                            "b_mu_minorityDeclinetoanswer", "Minoriy: Decline to answer",
                            "b_mu_religCatholicism", "Catholic",
                            "b_mu_religChristianityprotestant", "Protestant",
                            "b_mu_religBuddhism", "Buddhism",
                            "b_mu_religHinduism", "Hindu",
                            "b_mu_religIslam", "Islam",
                            "b_mu_religJudaism", "Judaism",
                            "b_mu_religShinto", "Shinto",
                            "b_mu_religMormonism", "Mormonism",
                            "b_mu_religLocal", "Local Religion",
                            "b_mu_religOther", "Other",
                            "b_mu_religDeclinetoanswer", "Religion: Decline to answer",
                            "b_mu_ed_z", "Education",
                            "b_mu_ideology_z", "Ideology",
                            "b_mu_troops_crime_persYes", "Personal Crime Experience: Yes",
                            "b_mu_american_inf_1DontknowDdeclinetoanswer", "Influence 1: DK/Decline",
                            "b_mu_american_inf_1Alittle", "Influence 1: A little",
                            "b_mu_american_inf_1Some", "Influence 1: Some",
                            "b_mu_american_inf_1Alot", "Influence 1: A lot",
                            "b_mu_american_inf_2DontknowDdeclinetoanswer", "Influence 2: DK/Decline",
                            "b_mu_american_inf_2Veryative", "Influence 2: Very negative",
                            "b_mu_american_inf_2Negative", "Influence 2: Negative",
                            "b_mu_american_inf_2Positive", "Influence 2: Positive",
                            "b_mu_american_inf_2Veryitive", "Influence 2: Very positive",
                            "b_mu_basecount_z", "Base count",
                            "b_mu_gdp_z", "GDP",
                            "b_mu_pop_z", "Population",
                            "b_mu_troops_z", "Troop deployment size",
                            "b_mu_Intercept", "Intercept")

# Create a list of coefficient group labels to be applied in the kableExtra portion of the table formatting.
coef.list <- coef.list %>%
  mutate(group = case_when(
           grepl(".*ontact.*", raw) ~ "Contact Status",
           grepl(".*enefit.*", raw) ~ "Economic Benefits",
           grepl(".*age.*", raw) ~ "Age",
           grepl(".*ncome.*", raw) ~ "Income Quintile",
           grepl(".*gender.*", raw) ~ "Gender Identification",
           grepl(".*minority.*", raw) ~ "Minority Self-Identification",
           grepl(".*relig.*", raw) ~ "Religious Identification",
           grepl(".*ed_z.*", raw) ~ "Education",
           grepl(".*ideology_z.*", raw) ~ "Ideology",
           grepl(".*crime.*", raw) ~ "Crime Experience",
           grepl(".*inf_1.*", raw) ~ "American Influence (Amount)",
           grepl(".*inf_2.*", raw) ~ "American Influence (Quality)",
           TRUE ~ "Group-Level Variables"
         ))

# Find how long the coefficient list is for the final table hline
last.line <- length(coef.list[[1]]) * 2

# Create a coefficient map object and index objects to streamline the row groupings in kableExtra formatting below.
coef_map <- setNames(coef.list$clean, coef.list$raw)
idx <- rle(coef.list$group)
idx <- setNames(idx$lengths  * 2, idx$values)

# Run modelsummary of the model list and format output with kableExtra. Original was in latex but this has been modified to facilitate bookdown output.
panel.1 <- modelsummary::modelsummary(mod.list,
                  estimate = "{estimate}",
                  statistic = "conf.int",
                  metrics = c("LOOIC", "ELPD"),
                  fmt = 2,
                  shape = term ~ model + group,
                  gof_map = gof.check,
                  coef_map = coef_map,
                  add_rows = rows.com,
                  stars = FALSE,
                  longtable = TRUE,
                  output = "kableExtra",
                  caption = "Bayesian multilevel multinomial logistic regressions. Population level effects.") %>%
  kable_styling(font_size = 4, position = "left") %>%
  add_header_above(c(" ", "US Presence" = 3, "US People" = 3, "US Government" = 3)) %>%
  group_rows(index = idx, bold = TRUE, background = "gray", color = "white", hline_after = TRUE) %>%
  row_spec(last.line, hline_after = TRUE)

</code>```

When I run the code chunk I get the following warnings and messages:

```<code>Warning: `modelsummary could not extract goodness-of-fit statistics from a model
of class "custom". The package tried a sequence of 2 helper functions:

performance::model_performance(model)
broom::glance(model)

One of these functions must return a one-row `data.frame`. The `modelsummary` website explains how to summarize unsupported models or add support for new models yourself:

https://vincentarelbundock.github.io/modelsummary/articles/modelsummary.htmlWarning: Term name mismatch. Make sure all `tidy_custom` method returns a data frame
  with proper and matching term names.Warning: There were 1 divergent transitions after warmup. Increasing adapt_delta above 0.9 may help. See http://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmupWarning: `modelsummary could not extract goodness-of-fit statistics from a model
of class "custom". The package tried a sequence of 2 helper functions:

performance::model_performance(model)
broom::glance(model)

One of these functions must return a one-row `data.frame`. The `modelsummary` website explains how to summarize unsupported models or add support for new models yourself:

https://vincentarelbundock.github.io/modelsummary/articles/modelsummary.htmlWarning: Term name mismatch. Make sure all `tidy_custom` method returns a data frame
  with proper and matching term names.Warning: `modelsummary could not extract goodness-of-fit statistics from a model
of class "custom". The package tried a sequence of 2 helper functions:

performance::model_performance(model)
broom::glance(model)

One of these functions must return a one-row `data.frame`. The `modelsummary` website explains how to summarize unsupported models or add support for new models yourself:

https://vincentarelbundock.github.io/modelsummary/articles/modelsummary.htmlWarning: Term name mismatch. Make sure all `tidy_custom` method returns a data frame
  with proper and matching term names.Error in map_estimates(tmp, coef_rename = coef_rename, coef_map = coef_map,  :
  At least one of the term names in each model must appear in `coef_map`.
</code>```

I've tried a few potential solutions. First, I updated {modelsummary} and reviewed the online documentation and updated a couple of things that appear to have changed since I first assembled the code.

I updated some of the arguments from {modelsummary}, including the metrics and shape arguments. The latter used to be group and the former was not included in the version I ran.

I updated the syntax for the custom tidy and glance functions to tidy_custom.brmsfit from tidy.custom and glance_custom.brmsfit from glance.custom. I've also removed any redundant/incorrect versions of these functions from the environment to ensure it's not trying to use an incorrect function.

I changed the grouping variable name for the outcome variable from y.level to group in the custom tidy function to try to match what I understand get_estimates() would generate.

I've also run the custom functions on a single model to ensure that the output is matching, as the final reference to the term name mismatch in the warnings above suggests that there is either something wrong with the column name or a varaible name. The usual suspects in terms of variable names that have caused errors (e.g. income) appear to be consistent in the output and in the variable names/labels that I've listed.

Finally, an example of the custom tidy function's output is as follows, which appears to be consistent with the casing and words modelsummary uses.

```<code>> test
                                              term      estimate conf.level      conf.low    conf.high        pd      rhat       ess      group
1                                   b_mu_Intercept  -2.213180000       0.95 -2.617802e+00 -1.816212750 1.0000000 1.0008532  9956.176 Don't Know
2                                   b_mu_Intercept  -0.461685500       0.95 -9.368145e-01  0.017789295 0.9709375 1.0002866  7535.687   Negative
3                                   b_mu_Intercept  -0.236163500       0.95 -5.795692e-01  0.116061925 0.9161875 1.0001725  9122.818   Positive
</code>```

It's entirely possible I'm overlooking something or have failed to address something from an update, but any advice people can give is very welcome!

Body:
Apologies for not having a full reproducible example here, but the models take a fairly long time to run and the model objects are fairly large.

I have a chunk of code that to generate a table from three multilevel multinomial logit models run using brms. This is a chunk of code that worked previously, and it's been a couple of years since I first assembled the code, but when I try to run it I'm running into problems getting modelsummary to read the contents of the custom tidy and glance functions.

There's a lot here, but here's the code. I've tried to use notes to break down what's going on at each stage. The gist of it is that I read in the models, make a list, assign a custom class to the three models, create the custom tidy and glance functions, and then run the modelsummary function at the end. It should generate a modelsummary table with 9 columns, 3 for each model.

# Read in three files
m.c.t1 <- readRDS(here::here("../Book/Output/Chapter-Contact/m.c.t1.rds"))
m.c.g1 <- readRDS(here::here("../Book/Output/Chapter-Contact/m.c.g1.rds"))
m.c.p1 <- readRDS(here::here("../Book/Output/Chapter-Contact/m.c.p1.rds"))

# Create the list of models. Omit model names because modelsummary pastes them in the table header for every column and makes it too wide. Will add single header to span three relevant columns manually later.
mod.list <- list(" " = m.c.t1,
                 " " = m.c.p1,
                 " " = m.c.g1)

# Assign custom class to each model in the list. Maybe not necessary anymore?
for (i in seq_along(mod.list)){
  class(mod.list[[i]]) <- c("custom", class(mod.list[[i]]))
}

#### Pay close attention to how brms and/or parameters is treating the % symbols in the income variable.Depending on the output the code below will need to be updated so the income variable isn't dropped.

# brms collapes the coefficient/variable name in with the outcome level of multinomial models. Use a custom tidy method to extract level names and put them into a separate columns.
tidy_custom.brmsfit <- function(x, conf.level=.95, ...) {
  out = parameters::parameters(x, ci=conf.level, verbose=FALSE) %>%
        parameters::standardize_names(style="broom") %>%
        mutate(group = case_when(grepl("mudk", term) ~ "Don't Know",
                                 grepl("muneg", term) ~ "Negative",
                                 grepl("mupos", term) ~ "Positive"),
               term = gsub("dk|neg|pos", "", term)) %>% # remove outcome level prefix brms attaches to variable names
    as.data.frame()

  return(out)
}

# Run custom glance function to limit gof output.
glance_custom.brmsfit <- function(x, ...) {
  ret <- tibble::tibble(N = summary(x)$nobs)
  return(ret)
}

# Run through the model list and extract varying intercept/effect components and dispersion metrics. Creates a new set of rows that can be inserted at the bottom of the table.
rows <- lapply(mod.list, function(x){

  temp.sd <- parameters::parameters(x, effect = "random")  %>%
    filter(grepl(".*sd.*", Parameter)) %>%
    filter(grepl(".*persYes.*|.*nonpersYes.*|.*Intercept.*", Parameter)) %>%
    dplyr::select(Parameter, Median) %>%
    dplyr::mutate(Median = as.character(round(Median, 2)),
      y.level = case_when(
      grepl(".*mudk.*", Parameter) ~ "dk",
      grepl(".*mupos.*", Parameter) ~ "pos",
      grepl(".*muneg.*", Parameter) ~ "neg",
    ),
    Parameter = gsub("_mudk_|_mupos_|_muneg_", "_", Parameter)) %>%
    pivot_wider(id_cols = Parameter,
                values_from = Median,
                names_from = y.level) %>%
    mutate(Parameter = case_when(
      grepl(".*Intercept.*", Parameter) ~ "sd(Intercept)"
    ))

  temp.obs <- tibble::tribble(~Parameter, ~dk, ~neg, ~pos,
                              "N", as.character(nobs(x)), "", "",
                              "Group", "Country", "", "",
                              "\\# Groups", as.character(length(unique(x$data$country))), "", "")

  temp.com <- bind_rows(temp.obs, temp.sd)

  return(temp.com)

  }
)

# Combine the three outputs from the previous lapplycommand and filter out the relevant columns.
rows.com <- bind_cols(rows[[1]], rows[[2]], rows[[3]]) %>%
  dplyr::select(1, 2, 3, 4, 6, 7, 8, 10, 11, 12)

# Name the columns to facilitate appending later.
names(rows.com) <- c("term", "col1", "col2", "col3", "col4", "col5", "col6", "col7", "col8", "col9")

# Turn off GOF stuff
gof.check <- modelsummary::gof_map
gof.check$omit <- TRUE

# Create a list of coefficient names and labels
coef.list <- tibble::tribble(~raw, ~clean,
                            "b_mu_contact_persYes", "Personal Contact: Yes",
                            "b_mu_contact_persDontknowDdeclinetoanswer", "Personal Contact: DK/Decline",
                            "b_mu_contact_nonpersYes", "Network Contact: Yes",
                            "b_mu_contact_nonpersDontknowDdeclinetoanswer", "Network Contact: DK/Decline",
                            "b_mu_benefit_persYes", "Personal Benefit: Yes",
                            "b_mu_benefit_persDontknowDdeclinetoanswer", "Personal Benefit: DK/Decline",
                            "b_mu_benefit_nonpersYes", "Network Benefit: Yes",
                            "b_mu_benefit_nonpersDontknowDdeclinetoanswer", "Network Benefit: DK/Decline",
                            "b_mu_age25to34years", "25-34",
                            "b_mu_age35to44years", "35-44",
                            "b_mu_age45to54years", "45-54",
                            "b_mu_age55to64years", "55-65",
                            "b_mu_ageAge65orolder", ">65",
                            "b_mu_income.5.cat21M40%", "21-40",
                            "b_mu_income.5.cat41M60%", "41-60",
                            "b_mu_income.5.cat61M80%", "61-80",
                            "b_mu_income.5.cat81M100%", "81-100",
                            "b_mu_genderFemale", "Female",
                            "b_mu_genderNonMbinary", "Non-binary",
                            "b_mu_genderNoneoftheabove", "None of the above",
                            "b_mu_minorityYes", "Minority: Yes",
                            "b_mu_minorityDeclinetoanswer", "Minoriy: Decline to answer",
                            "b_mu_religCatholicism", "Catholic",
                            "b_mu_religChristianityprotestant", "Protestant",
                            "b_mu_religBuddhism", "Buddhism",
                            "b_mu_religHinduism", "Hindu",
                            "b_mu_religIslam", "Islam",
                            "b_mu_religJudaism", "Judaism",
                            "b_mu_religShinto", "Shinto",
                            "b_mu_religMormonism", "Mormonism",
                            "b_mu_religLocal", "Local Religion",
                            "b_mu_religOther", "Other",
                            "b_mu_religDeclinetoanswer", "Religion: Decline to answer",
                            "b_mu_ed_z", "Education",
                            "b_mu_ideology_z", "Ideology",
                            "b_mu_troops_crime_persYes", "Personal Crime Experience: Yes",
                            "b_mu_american_inf_1DontknowDdeclinetoanswer", "Influence 1: DK/Decline",
                            "b_mu_american_inf_1Alittle", "Influence 1: A little",
                            "b_mu_american_inf_1Some", "Influence 1: Some",
                            "b_mu_american_inf_1Alot", "Influence 1: A lot",
                            "b_mu_american_inf_2DontknowDdeclinetoanswer", "Influence 2: DK/Decline",
                            "b_mu_american_inf_2Veryative", "Influence 2: Very negative",
                            "b_mu_american_inf_2Negative", "Influence 2: Negative",
                            "b_mu_american_inf_2Positive", "Influence 2: Positive",
                            "b_mu_american_inf_2Veryitive", "Influence 2: Very positive",
                            "b_mu_basecount_z", "Base count",
                            "b_mu_gdp_z", "GDP",
                            "b_mu_pop_z", "Population",
                            "b_mu_troops_z", "Troop deployment size",
                            "b_mu_Intercept", "Intercept")

# Create a list of coefficient group labels to be applied in the kableExtra portion of the table formatting.
coef.list <- coef.list %>%
  mutate(group = case_when(
           grepl(".*ontact.*", raw) ~ "Contact Status",
           grepl(".*enefit.*", raw) ~ "Economic Benefits",
           grepl(".*age.*", raw) ~ "Age",
           grepl(".*ncome.*", raw) ~ "Income Quintile",
           grepl(".*gender.*", raw) ~ "Gender Identification",
           grepl(".*minority.*", raw) ~ "Minority Self-Identification",
           grepl(".*relig.*", raw) ~ "Religious Identification",
           grepl(".*ed_z.*", raw) ~ "Education",
           grepl(".*ideology_z.*", raw) ~ "Ideology",
           grepl(".*crime.*", raw) ~ "Crime Experience",
           grepl(".*inf_1.*", raw) ~ "American Influence (Amount)",
           grepl(".*inf_2.*", raw) ~ "American Influence (Quality)",
           TRUE ~ "Group-Level Variables"
         ))

# Find how long the coefficient list is for the final table hline
last.line <- length(coef.list[[1]]) * 2

# Create a coefficient map object and index objects to streamline the row groupings in kableExtra formatting below.
coef_map <- setNames(coef.list$clean, coef.list$raw)
idx <- rle(coef.list$group)
idx <- setNames(idx$lengths  * 2, idx$values)

# Run modelsummary of the model list and format output with kableExtra. Original was in latex but this has been modified to facilitate bookdown output.
panel.1 <- modelsummary::modelsummary(mod.list,
                  estimate = "{estimate}",
                  statistic = "conf.int",
                  metrics = c("LOOIC", "ELPD"),
                  fmt = 2,
                  shape = term ~ model + group,
                  gof_map = gof.check,
                  coef_map = coef_map,
                  add_rows = rows.com,
                  stars = FALSE,
                  longtable = TRUE,
                  output = "kableExtra",
                  caption = "Bayesian multilevel multinomial logistic regressions. Population level effects.") %>%
  kable_styling(font_size = 4, position = "left") %>%
  add_header_above(c(" ", "US Presence" = 3, "US People" = 3, "US Government" = 3)) %>%
  group_rows(index = idx, bold = TRUE, background = "gray", color = "white", hline_after = TRUE) %>%
  row_spec(last.line, hline_after = TRUE)

When I run the code chunk I get the following warnings and messages:

Warning: `modelsummary could not extract goodness-of-fit statistics from a model
of class "custom". The package tried a sequence of 2 helper functions:

performance::model_performance(model)
broom::glance(model)

One of these functions must return a one-row `data.frame`. The `modelsummary` website explains how to summarize unsupported models or add support for new models yourself:

https://vincentarelbundock.github.io/modelsummary/articles/modelsummary.htmlWarning: Term name mismatch. Make sure all `tidy_custom` method returns a data frame
  with proper and matching term names.Warning: There were 1 divergent transitions after warmup. Increasing adapt_delta above 0.9 may help. See http://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmupWarning: `modelsummary could not extract goodness-of-fit statistics from a model
of class "custom". The package tried a sequence of 2 helper functions:

performance::model_performance(model)
broom::glance(model)

One of these functions must return a one-row `data.frame`. The `modelsummary` website explains how to summarize unsupported models or add support for new models yourself:

https://vincentarelbundock.github.io/modelsummary/articles/modelsummary.htmlWarning: Term name mismatch. Make sure all `tidy_custom` method returns a data frame
  with proper and matching term names.Warning: `modelsummary could not extract goodness-of-fit statistics from a model
of class "custom". The package tried a sequence of 2 helper functions:

performance::model_performance(model)
broom::glance(model)

One of these functions must return a one-row `data.frame`. The `modelsummary` website explains how to summarize unsupported models or add support for new models yourself:

https://vincentarelbundock.github.io/modelsummary/articles/modelsummary.htmlWarning: Term name mismatch. Make sure all `tidy_custom` method returns a data frame
  with proper and matching term names.Error in map_estimates(tmp, coef_rename = coef_rename, coef_map = coef_map,  :
  At least one of the term names in each model must appear in `coef_map`.

I've tried a few potential solutions. First, I updated {modelsummary} and reviewed the online documentation and updated a couple of things that appear to have changed since I first assembled the code.

I updated some of the arguments from {modelsummary}, including the metrics and shape arguments. The latter used to be group and the former was not included in the version I ran.

I updated the syntax for the custom tidy and glance functions to tidy_custom.brmsfit from tidy.custom and glance_custom.brmsfit from glance.custom. I've also removed any redundant/incorrect versions of these functions from the environment to ensure it's not trying to use an incorrect function.

I changed the grouping variable name for the outcome variable from y.level to group in the custom tidy function to try to match what I understand get_estimates() would generate.

I've also run the custom functions on a single model to ensure that the output is matching, as the final reference to the term name mismatch in the warnings above suggests that there is either something wrong with the column name or a varaible name. The usual suspects in terms of variable names that have caused errors (e.g. income) appear to be consistent in the output and in the variable names/labels that I've listed.

Finally, an example of the custom tidy function's output is as follows, which appears to be consistent with the casing and words modelsummary uses.

> test
                                              term      estimate conf.level      conf.low    conf.high        pd      rhat       ess      group
1                                   b_mu_Intercept  -2.213180000       0.95 -2.617802e+00 -1.816212750 1.0000000 1.0008532  9956.176 Don't Know
2                                   b_mu_Intercept  -0.461685500       0.95 -9.368145e-01  0.017789295 0.9709375 1.0002866  7535.687   Negative
3                                   b_mu_Intercept  -0.236163500       0.95 -5.795692e-01  0.116061925 0.9161875 1.0001725  9122.818   Positive

It's entirely possible I'm overlooking something or have failed to address something from an update, but any advice people can give is very welcome!


问:
What is the recommended upgrade path for the obsolete FindServicePoint method?
I'm working on some legacy code that contains this:

ServicePointManager.FindServicePoint(new Uri(myServiceUrl)).ConnectionLeaseTimeout = 60 * 1000;
```

When I found the docs for the FindServicePoint method it says it's obsolete. There is a remark in that same doc that says to use HttpClient instead of ServicePointManager.

I can see that HttpClient has some time out properties, but I'm not sure which one replaces the functionality of ConnectionLeaseTimeout.

How can I implement what setting the ConnectionLeaseTimeout property is currently doing using the HttpClient class?

Update 1

The SocketsHttpHandler appears to be the replacement class. An instance of this class can be passed to the constructor of the HttpClient client.

There are bunch of properties that can be set on SocketsHttpHandler but not ConnectionLeaseTimeout . I'll still have to figure out which SocketsHttpHandler property or properties are a suitable replacment.

Body:
I'm working on some legacy code that contains this:

ServicePointManager.FindServicePoint(new Uri(myServiceUrl)).ConnectionLeaseTimeout = 60 * 1000;

When I found the docs for the FindServicePoint method it says it's obsolete. There is a remark in that same doc that says to use HttpClient instead of ServicePointManager.

I can see that HttpClient has some time out properties, but I'm not sure which one replaces the functionality of ConnectionLeaseTimeout.

How can I implement what setting the ConnectionLeaseTimeout property is currently doing using the HttpClient class?

Update 1

The SocketsHttpHandler appears to be the replacement class. An instance of this class can be passed to the constructor of the HttpClient client.

There are bunch of properties that can be set on SocketsHttpHandler but not ConnectionLeaseTimeout . I'll still have to figure out which SocketsHttpHandler property or properties are a suitable replacment.


问:
DraggableScrollableSheet at the bottom of the page not screen
I would like to create an effect similar to DraggableScrollableSheet but instead of it being attached to the bottom of the phone, it is at the end of a scrollable page.
So the user scrolls to the end of the page and finds this sheet, which they can drag up and then scroll through.</p>


问:
Why is Scipy's cross correlation function giving incorrect results for audio signals
I'm trying to calculate the location of a sound source using TDOA, by cross correlating audio recordings from different microphones and getting the time delay. I am fairly confident that the recording start times are synchronized to 0.01ms or less. The microphones are all plugged into a RaspberryPi.

However, when testing in a room with the microphones set up about 15 meters apart, the cross correlation is giving very incorrect and unreasonable results. I divide the lag in array distance (which are audio data recorded at a specific sample rate) by the sample rate, which should give the delay in seconds right? But the code would say that the delay is 1-2 second or more, when the entire recording is only 3 seconds. The recorded sound is otherwise crystal clear, with almost zero background noise, and several loud, prominent claps.

Here's the code I used:

from scipy import signal
from scipy.io import wavfile

r1,s1 = wavfile.read('near output.wav'). #r1 is sample rate, s1 is data
r2,s2 = wavfile.read('far output.wav')
correlation = signal.correlate(s1, s2, mode="full")
lags = signal.correlation_lags(s1.size, s2.size, mode="full")
lag = lags[np.argmax(correlation)]
print(f"Delay: {lag / r1}")
```


问:
Double press on Bottom Tab Navigation to refresh a screen
I made a WebView application with React Native. I added Bottom Tab Navigation. You can navigate between tabs. I want the page to refresh when the Bottom Tab Navigator is double-clicked. WebView is added in my pages. How can I do this in BottomTabNavigatior.</p>
```<code>import React from 'react';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';

//pages
import Location from '../../screens/Location';
import Categories from '../../screens/Categories';
import Home from '../../screens/Home';
import Search from '../../screens/Search';
import Account from '../../screens/Account';

const Tab = createBottomTabNavigator();

function BottomTabNavigator() {
    return (
        <Tab.Navigator
            initialRouteName='İlanlar'
            screenOptions={
                ({ route }) => ({
                    headerShown: false,
                    tabBarShowLabel: true,
                    tabBarStyle: {
                        position: 'absolute',
                        backgroundColor: '#fcfcfc',
                        height: 80,
                        paddingTop: 15,
                        paddingBottom: 15,
                    },
                    tabBarIcon: ({ focused, color }) => {
                        let iconName;

                        if (route.name === 'İlanlar') {
                            iconName = focused
                                ? 'paw' : 'paw-outline';
                        } else if (route.name === 'Konum') {
                            iconName = focused ? 'navigate-circle' : 'navigate-circle-outline';
                        } else if (route.name === 'Kategoriler') {
                            iconName = focused ? 'grid' : 'grid-outline';
                        } else if (route.name === 'Arama') {
                            iconName = focused ? 'search' : 'search-outline';
                        }
                        else if (route.name === 'Hesabım') {
                            iconName = focused ? 'person-circle' : 'person-circle-outline';
                        }
                        return <Ionicons name={iconName} size={32} color={color} />;
                    },
                    tabBarActiveTintColor: '#015DA3',
                    tabBarInactiveTintColor: '#3e7399',
                })}>
            <Tab.Screen name='Konum' component={Location} />
            <Tab.Screen name='Kategoriler' component={Categories} />
            <Tab.Screen name='İlanlar' component={Home} />
            <Tab.Screen name='Arama' component={Search} />
            <Tab.Screen name='Hesabım' component={Account} />
        </Tab.Navigator>
    )
}

export default BottomTabNavigator;
</code>```

Body:
I made a WebView application with React Native. I added Bottom Tab Navigation. You can navigate between tabs. I want the page to refresh when the Bottom Tab Navigator is double-clicked. WebView is added in my pages. How can I do this in BottomTabNavigatior.

import React from 'react';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';

//pages
import Location from '../../screens/Location';
import Categories from '../../screens/Categories';
import Home from '../../screens/Home';
import Search from '../../screens/Search';
import Account from '../../screens/Account';

const Tab = createBottomTabNavigator();

function BottomTabNavigator() {
    return (
        <Tab.Navigator
            initialRouteName='İlanlar'
            screenOptions={
                ({ route }) => ({
                    headerShown: false,
                    tabBarShowLabel: true,
                    tabBarStyle: {
                        position: 'absolute',
                        backgroundColor: '#fcfcfc',
                        height: 80,
                        paddingTop: 15,
                        paddingBottom: 15,
                    },
                    tabBarIcon: ({ focused, color }) => {
                        let iconName;

                        if (route.name === 'İlanlar') {
                            iconName = focused
                                ? 'paw' : 'paw-outline';
                        } else if (route.name === 'Konum') {
                            iconName = focused ? 'navigate-circle' : 'navigate-circle-outline';
                        } else if (route.name === 'Kategoriler') {
                            iconName = focused ? 'grid' : 'grid-outline';
                        } else if (route.name === 'Arama') {
                            iconName = focused ? 'search' : 'search-outline';
                        }
                        else if (route.name === 'Hesabım') {
                            iconName = focused ? 'person-circle' : 'person-circle-outline';
                        }
                        return <Ionicons name={iconName} size={32} color={color} />;
                    },
                    tabBarActiveTintColor: '#015DA3',
                    tabBarInactiveTintColor: '#3e7399',
                })}>
            <Tab.Screen name='Konum' component={Location} />
            <Tab.Screen name='Kategoriler' component={Categories} />
            <Tab.Screen name='İlanlar' component={Home} />
            <Tab.Screen name='Arama' component={Search} />
            <Tab.Screen name='Hesabım' component={Account} />
        </Tab.Navigator>
    )
}

export default BottomTabNavigator;


问:
How to deploy Python Script that requires environment variables
As the title says, I have a Python script I wrote that I would like to allow others to use.

The script is an API aggregator, and it requires a client_id and secret to access the API. As of now I have an env file which stores these values and I'm able to get the values from the env file.

My question is now that I have finished the script locally, how do I deploy with the environment variables it so others can use it given that the environment variables are required?

Sorry if this is a simple question - new to writing scripts for others to use.

The only thing I could think of was including the .env when I push to github, but not sure if that's great practice since my client_id and secret are stored there


问:
How to set up custom role provider in keycloak 18.0.2?
I want that user roles uploaded from db in keycloak. I have wrote RoleSPI for this, but roles don't load. My role-provider is displayed on server info.

I
I created CustomRoleProvider:

```<code>public class CustomRoleProvider implements RoleProvider {
 @Override
    public RoleModel addRealmRole(RealmModel realmModel, String s, String s1) {
        return null;
    }

    @Override
    public Stream<RoleModel> getRealmRolesStream(RealmModel realmModel, Integer integer, Integer integer1) {
        return null;
    }

    @Override
    public Stream<RoleModel> getRolesStream(RealmModel realmModel, Stream<String> stream, String s, Integer integer, Integer integer1) {
        return null;
    }

    @Override
    public boolean removeRole(RoleModel roleModel) {
        return false;
    }

    @Override
    public void removeRoles(RealmModel realmModel) {

    }

    @Override
    public RoleModel addClientRole(ClientModel clientModel, String s, String s1) {
        return null;
    }

    @Override
    public Stream<RoleModel> getClientRolesStream(ClientModel clientModel, Integer integer, Integer integer1) {
        return null;
    }

    @Override
    public void removeRoles(ClientModel clientModel) {

    }

    @Override
    public void close() {

    }

    @Override
    public RoleModel getRealmRole(RealmModel realmModel, String s) {
        System.out.println("getRealmRole()");
        return roleModel;
    }

    @Override
    public RoleModel getRoleById(RealmModel realmModel, String s) {
        System.out.println("getRoleById()");
        return roleModel;
    }

    @Override
    public Stream<RoleModel> searchForRolesStream(RealmModel realmModel, String s, Integer integer, Integer integer1) {
        System.out.println("searchForRolesStream()");
        return roleModelStream;
    }

    @Override
    public RoleModel getClientRole(ClientModel clientModel, String s) {
        System.out.println("getClientRole()");
        return roleModel;
    }

    @Override
    public Stream<RoleModel> searchForClientRolesStream(ClientModel clientModel, String s, Integer integer, Integer integer1) {
        System.out.println("searchForClientRolesStream()");
        return roleModelStream;
    }
}
</code>```

My CustomRoleProviderFactory:

```<code>public class CustomRoleProviderFactory implements RoleProviderFactory {
    @Override
    public RoleProvider create(KeycloakSession keycloakSession) {
        System.out.println("create");
        return new CustomRoleProvider();
    }

    @Override
    public void init(Config.Scope scope) {

    }

    @Override
    public void postInit(KeycloakSessionFactory keycloakSessionFactory) {

    }

    @Override
    public void close() {

    }

    @Override
    public String getId() {
        return "role-provider";
    }
}
</code>```

I noticed that the create method was not called after the start of keycloak.

There is org.keycloak.models.RoleProviderFactory in resources\META-INF\services packages:

```<code>com.healthec.keycloak.provider.CustomRoleProviderFactory
</code>```

Do you have any ideas why roles don't loaded?

Body:
I want that user roles uploaded from db in keycloak. I have wrote RoleSPI for this, but roles don't load. My role-provider is displayed on server info.

I
I created CustomRoleProvider:

public class CustomRoleProvider implements RoleProvider {
 @Override
    public RoleModel addRealmRole(RealmModel realmModel, String s, String s1) {
        return null;
    }

    @Override
    public Stream<RoleModel> getRealmRolesStream(RealmModel realmModel, Integer integer, Integer integer1) {
        return null;
    }

    @Override
    public Stream<RoleModel> getRolesStream(RealmModel realmModel, Stream<String> stream, String s, Integer integer, Integer integer1) {
        return null;
    }

    @Override
    public boolean removeRole(RoleModel roleModel) {
        return false;
    }

    @Override
    public void removeRoles(RealmModel realmModel) {

    }

    @Override
    public RoleModel addClientRole(ClientModel clientModel, String s, String s1) {
        return null;
    }

    @Override
    public Stream<RoleModel> getClientRolesStream(ClientModel clientModel, Integer integer, Integer integer1) {
        return null;
    }

    @Override
    public void removeRoles(ClientModel clientModel) {

    }

    @Override
    public void close() {

    }

    @Override
    public RoleModel getRealmRole(RealmModel realmModel, String s) {
        System.out.println("getRealmRole()");
        return roleModel;
    }

    @Override
    public RoleModel getRoleById(RealmModel realmModel, String s) {
        System.out.println("getRoleById()");
        return roleModel;
    }

    @Override
    public Stream<RoleModel> searchForRolesStream(RealmModel realmModel, String s, Integer integer, Integer integer1) {
        System.out.println("searchForRolesStream()");
        return roleModelStream;
    }

    @Override
    public RoleModel getClientRole(ClientModel clientModel, String s) {
        System.out.println("getClientRole()");
        return roleModel;
    }

    @Override
    public Stream<RoleModel> searchForClientRolesStream(ClientModel clientModel, String s, Integer integer, Integer integer1) {
        System.out.println("searchForClientRolesStream()");
        return roleModelStream;
    }
}

My CustomRoleProviderFactory:

public class CustomRoleProviderFactory implements RoleProviderFactory {
    @Override
    public RoleProvider create(KeycloakSession keycloakSession) {
        System.out.println("create");
        return new CustomRoleProvider();
    }

    @Override
    public void init(Config.Scope scope) {

    }

    @Override
    public void postInit(KeycloakSessionFactory keycloakSessionFactory) {

    }

    @Override
    public void close() {

    }

    @Override
    public String getId() {
        return "role-provider";
    }
}

I noticed that the create method was not called after the start of keycloak.

There is org.keycloak.models.RoleProviderFactory in resources\META-INF\services packages:

com.healthec.keycloak.provider.CustomRoleProviderFactory

Do you have any ideas why roles don't loaded?


问:
ICS file doesn't load in the calendar
I am creating this ICS file and validating it here: Validator

```<code>BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
CALSCALE:GREGORIAN
BEGIN:VEVENT
DTSTART:20221221T202256Z
DTEND:20221221T205256Z
DESCRIPTION:test
LOCATION:v gyzy
DTSTAMP:20221221T202256Z
UID:63a36b20cc912
END:VEVENT
END:VCALENDAR
</code>```

But when I double-click on it, it doesn't load as event in the calendar:

Title: ICS file doesn't load in the calendar

Body:
I am creating this ICS file and validating it here: Validator

BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
CALSCALE:GREGORIAN
BEGIN:VEVENT
DTSTART:20221221T202256Z
DTEND:20221221T205256Z
DESCRIPTION:test
LOCATION:v gyzy
DTSTAMP:20221221T202256Z
UID:63a36b20cc912
END:VEVENT
END:VCALENDAR

But when I double-click on it, it doesn't load as event in the calendar:


问:
Nesting REACT app son IIS, resulting in 500 Internal Server Error
One of our projects requires that we host multiple REACT-based apps from a single domain, in a nested configuration

www.mainapp.com
www.mainapp.com/app1
www.mainapp.com/app2

IIS configuration works fine for the main site, but when a call is made to a child application, the result is a 500 Internal Server Error.  Event Viewer provides no assistance with this.

Removing the routing rule on the main site, the child applications functioned as expected.  APIs function fine off the main site as well (.NET applications).

```<code><rule name="ReactRouter Routes" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_URI}" pattern="^/api" negate="true" />
<add input="{REQUEST_URI}" pattern="^/admin" negate="true" />
<add input="{REQUEST_URI}" pattern="^/tools/tokenization" negate="true" />
</conditions>
<action type="Rewrite" url="index.html" />
</rule>
</code>```

One thing to note, tools/tokenization is configured as an IIS application and mounted as a virtual folder.  It works, but /app1 and /app2 do not (500).  For testing I converted app1 to an application, but it made no difference.

Body:
One of our projects requires that we host multiple REACT-based apps from a single domain, in a nested configuration

www.mainapp.com
www.mainapp.com/app1
www.mainapp.com/app2

IIS configuration works fine for the main site, but when a call is made to a child application, the result is a 500 Internal Server Error.  Event Viewer provides no assistance with this.

Removing the routing rule on the main site, the child applications functioned as expected.  APIs function fine off the main site as well (.NET applications).

<rule name="ReactRouter Routes" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_URI}" pattern="^/api" negate="true" />
<add input="{REQUEST_URI}" pattern="^/admin" negate="true" />
<add input="{REQUEST_URI}" pattern="^/tools/tokenization" negate="true" />
</conditions>
<action type="Rewrite" url="index.html" />
</rule>

One thing to note, tools/tokenization is configured as an IIS application and mounted as a virtual folder.  It works, but /app1 and /app2 do not (500).  For testing I converted app1 to an application, but it made no difference.