问:
How to use SWR with useReducer
I have useReducer  and I have action type for  fetching data inside useEffect and dispatch it  like  this.

```<code>function reducer(state, action) {
    switch (action.type) {
        case 'FETCH_REQUEST':
            return { ...state, loading: true, error: '' };
        case 'FETCH_SUCCESS':
            return { ...state, loading: false, orders: action.payload, error: '' };
        case 'FETCH_FAIL':
            return { ...state, loading: false, error: action.payload };
        default:
            return state;
    }
}
export default function OrderHistoryScreen() {
    const [{ loading, error, orders }, dispatch] = useReducer(reducer, {
        loading: true,
        orders: [],
        error: '',
    });
    useEffect(() => {
        const fetchOrders = async () => {
            try {
                dispatch({ type: 'FETCH_REQUEST' });
                const { data } = await axios.get(`/api/orders/history`);
                dispatch({ type: 'FETCH_SUCCESS', payload: data });
            } catch (err) {
                dispatch({ type: 'FETCH_FAIL', payload: getError(err) });
            }
        };
        fetchOrders();
    }, []);
</code>```

how can I use SWR for this condition SWR cant be called inside useEffect and I want to use SWR to dispatch it  to avoid fetching with useEffect

Title: How to use SWR with useReducer

Body:
I have useReducer  and I have action type for  fetching data inside useEffect and dispatch it  like  this.

function reducer(state, action) {
    switch (action.type) {
        case 'FETCH_REQUEST':
            return { ...state, loading: true, error: '' };
        case 'FETCH_SUCCESS':
            return { ...state, loading: false, orders: action.payload, error: '' };
        case 'FETCH_FAIL':
            return { ...state, loading: false, error: action.payload };
        default:
            return state;
    }
}
export default function OrderHistoryScreen() {
    const [{ loading, error, orders }, dispatch] = useReducer(reducer, {
        loading: true,
        orders: [],
        error: '',
    });
    useEffect(() => {
        const fetchOrders = async () => {
            try {
                dispatch({ type: 'FETCH_REQUEST' });
                const { data } = await axios.get(`/api/orders/history`);
                dispatch({ type: 'FETCH_SUCCESS', payload: data });
            } catch (err) {
                dispatch({ type: 'FETCH_FAIL', payload: getError(err) });
            }
        };
        fetchOrders();
    }, []);

how can I use SWR for this condition SWR cant be called inside useEffect and I want to use SWR to dispatch it  to avoid fetching with useEffect


来源: stackexchange

问:
Fonts in terminal of the Visual Studio Code (VS) Code
Visual studio code terminal

I cannot read the terminal . I changed the json file for the fonts but still I cannot read the letters in the terminal.

I changed json, terminal settings.
But unfortunately the fonts still cannot be read in the terminal.

ContentLicense: CC BY-SA 4.0


问:
angular 14 mat mat-sidenav always open in mobile
Using Angular14 material design using mat-sidenav. Its working fine in browser responsive and mobile screens. When we try to test in android mobile device sidenav is always open.

Sharing code sample, please help

```<code>  private observer: BreakpointObserver
  this.observer
  .observe(['(max-width: 800px)'])
  .pipe(delay(1), untilDestroyed(this))
  .subscribe((res) => {

      if (res.matches) {
        this.sidenav!.mode = 'over';
        this.sidenav!.close();
      } else {
        this.sidenav!.mode = 'side';
        this.sidenav!.open();
      }
    }

  });
</code>```

Body:
Using Angular14 material design using mat-sidenav. Its working fine in browser responsive and mobile screens. When we try to test in android mobile device sidenav is always open.

Sharing code sample, please help

  private observer: BreakpointObserver
  this.observer
  .observe(['(max-width: 800px)'])
  .pipe(delay(1), untilDestroyed(this))
  .subscribe((res) => {

      if (res.matches) {
        this.sidenav!.mode = 'over';
        this.sidenav!.close();
      } else {
        this.sidenav!.mode = 'side';
        this.sidenav!.open();
      }
    }

  });


问:
How to check which app user has opened in flutter
Hi is there any way to detect which app is opened by user like my app is running in background and when user open facebook my app will detect it and show some message in overlay regarding facebook same with other apps like amazon, olx, etc etc. I'm building app in flutter so is there in way to do this in flutter oherwise will figure out how to do in flutter please suggest.</p>


问:
Newton-Raphson Search for Implied Volatility Returning Low Solutions
I am working on a project for a Python class that required us to download and run a sample of code. I chose a section of code from StackExchange that calculates the implied volatility of an option using a Newton-Raphson search. I had to modify the initial code fragment slightly to get it to run. I noticed that when I compared the output to an Excel spreadsheet model that the calculated implied volatilities were consistently lower, averaging around 3% below the values produced by the Excel sheet.

For those who have experience with this type of problem, is there anything obviously incorrect in the following code that could be producing that type of error? Any suggestions would be welcome.

Please see problem description above for details. The problematic code is:

```<code># s = stock price
# k = strike
# t = time to maturity
# rf = risk free interest
# cp = +/-1 call/put
# price = option price

import math as math
import numpy as np
from scipy.stats import norm

pi = 3.14159

def newtonRap(cp, price, s, k, t, rf):
    v = math.sqrt(2*pi/t)*price/s
    print ("initial volatility: ",v)
    for i in range(1, 100):
        d1 = (math.log(s/k)+(rf+0.5*pow(v,2))*t)/(v*math.sqrt(t))
        d2 = d1 - v*math.sqrt(t)
        vega = s*norm.pdf(d1)*math.sqrt(t)
        price0 = cp*s*norm.cdf(cp*d1) - cp*k*math.exp(-rf*t)*norm.cdf(cp*d2)
        v = v - (price0 - price)/vega
        print ("price, vega, volatility\n",(price0, vega, v))
        if abs(price0 - price) < 1e-25 :
            break
    return v

# TEST using known implied volatility from standard black scholes model

v = newtonRap(cp=1, price = 12.19, s=125, k=150, t=365/365, rf=0.06)
print (v)

</code>```

Body:
I am working on a project for a Python class that required us to download and run a sample of code. I chose a section of code from StackExchange that calculates the implied volatility of an option using a Newton-Raphson search. I had to modify the initial code fragment slightly to get it to run. I noticed that when I compared the output to an Excel spreadsheet model that the calculated implied volatilities were consistently lower, averaging around 3% below the values produced by the Excel sheet.

For those who have experience with this type of problem, is there anything obviously incorrect in the following code that could be producing that type of error? Any suggestions would be welcome.

Please see problem description above for details. The problematic code is:

# s = stock price
# k = strike
# t = time to maturity
# rf = risk free interest
# cp = +/-1 call/put
# price = option price

import math as math
import numpy as np
from scipy.stats import norm

pi = 3.14159

def newtonRap(cp, price, s, k, t, rf):
    v = math.sqrt(2*pi/t)*price/s
    print ("initial volatility: ",v)
    for i in range(1, 100):
        d1 = (math.log(s/k)+(rf+0.5*pow(v,2))*t)/(v*math.sqrt(t))
        d2 = d1 - v*math.sqrt(t)
        vega = s*norm.pdf(d1)*math.sqrt(t)
        price0 = cp*s*norm.cdf(cp*d1) - cp*k*math.exp(-rf*t)*norm.cdf(cp*d2)
        v = v - (price0 - price)/vega
        print ("price, vega, volatility\n",(price0, vega, v))
        if abs(price0 - price) < 1e-25 :
            break
    return v

# TEST using known implied volatility from standard black scholes model

v = newtonRap(cp=1, price = 12.19, s=125, k=150, t=365/365, rf=0.06)
print (v)


问:
HTML5 (?) doesn't understand empty element /> syntax from XML?
This was the closest question to mine that I could find: Closing empty elements and other xhtml standards within HTML5 and it leaves me disturbed, alarmed!

I have for decades used XML / XSLT to generate web pages. At some point I just used xsl:output type xml, not even html or xhtml. I thought: HTML is XML (at least somehow). But now, as I'm back actually typing HTML I find myself teleported to the early 1990s or something, where I have to write

```<code><script src="test.js"></script>
</code>```

instead of just

```<code><script src="test.js"/>
</code>```

and

```<code><input>
<br>
<img>
</code>```

don't need to be closed at all.

I sometimes do

```<code><div/>
<p/>
</code>```

and now I notice that the /> is entirely ignored and the p sucked into the contents of the div, leading to all kinds of confusion.

Isn't there some mode I can set on top, or by content-type or whatever it is where I can tell the browser to parse my document correctly as XML? I tried to begin the file with:

```<code><?xml version="1.0"?>
</code>```

but to no avail.

It feels like I'm the only one in the world who has completely missed the boat after decades of building web applications.

Body:
This was the closest question to mine that I could find: Closing empty elements and other xhtml standards within HTML5 and it leaves me disturbed, alarmed!

I have for decades used XML / XSLT to generate web pages. At some point I just used xsl:output type xml, not even html or xhtml. I thought: HTML is XML (at least somehow). But now, as I'm back actually typing HTML I find myself teleported to the early 1990s or something, where I have to write

instead of just


问:
Cloudformation: WebACLAssociation failed to deploy at the first time since WebACL is not deployed yet
My template looks like this:

```<code>Transform: AWS::Serverless-2016-10-31

Parameters:
  Stage:
    Type: String
    Default: dev

Resources:
  ApiWebACL:
    Type: AWS::WAFv2::WebACL
    Properties:
      ...
      ...

  ApiGateway:
    Type: AWS::Serverless::Api
    Properties:
      StageName: !Ref Stage

  #HERE
  ApiGatewayWebACLAssociation:
    Type: AWS::WAFv2::WebACLAssociation
    Properties:
      ResourceArn: !Sub "arn:aws:apigateway:${AWS::Region}::/restapis/${ApiGateway}/stages/${Stage}"
      WebACLArn: !GetAtt ApiWebACL.Arn

  timerHandler:
    Type: AWS::Serverless::Function
    Properties:
      ...
      ...
</code>```

Please forcus on ApiGatewayWebACLAssociation section. At the first deployment, I must remove this section otherwise the deployment will fail since the AWS::WAFv2::WebACL is not deployed yet. So my question is: Is there any available property like "depends on" to make AWS::WAFv2::WebACLAssociation wait until AWS::WAFv2::WebACL finish its deployment?

Log:

```2022-12-19 08:35:30 - Waiting for stack create/update to complete

CloudFormation events from stack operations (refresh every 0.5 seconds)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ResourceStatus                                        ResourceType                                          LogicalResourceId                                     ResourceStatusReason
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        bulkUpsertAccommodationsFunctionRole                  -
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        gettingAccommodationCodesFunctionRole                 -
CREATE_IN_PROGRESS                                    AWS::WAFv2::WebACL                                    ApiWebACL                                             -
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        postingCredentialsFunctionRole                        -
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        gettingPinRole                                        -
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        timerHandlerRole                                      -
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        bulkUpsertAccommodationsFunctionRole                  Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        postingCredentialsFunctionRole                        Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        gettingAccommodationCodesFunctionRole                 Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        gettingPinRole                                        Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        timerHandlerRole                                      Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::WAFv2::WebACL                                    ApiWebACL                                             Resource creation Initiated
CREATE_COMPLETE                                       AWS::WAFv2::WebACL                                    ApiWebACL                                             -
CREATE_COMPLETE                                       AWS::IAM::Role                                        bulkUpsertAccommodationsFunctionRole                  -
CREATE_COMPLETE                                       AWS::IAM::Role                                        postingCredentialsFunctionRole                        -
CREATE_COMPLETE                                       AWS::IAM::Role                                        gettingPinRole                                        -
CREATE_COMPLETE                                       AWS::IAM::Role                                        timerHandlerRole                                      -
CREATE_COMPLETE                                       AWS::IAM::Role                                        gettingAccommodationCodesFunctionRole                 -
CREATE_IN_PROGRESS                                    AWS::Lambda::Function                                 postingCredentialsFunction                            -
CREATE_IN_PROGRESS                                    AWS::Lambda::Function                                 gettingPin                                            -
CREATE_IN_PROGRESS                                    AWS::Lambda::Function                                 timerHandler                                          -
CREATE_IN_PROGRESS                                    AWS::Lambda::Function                                 bulkUpsertAccommodationsFunction                      -
CREATE_IN_PROGRESS                                    AWS::Lambda::Function                                 gettingAccommodationCodesFunction                     -
CREATE_IN_PROGRESS                                    AWS::Lambda::Function                                 postingCredentialsFunction                            Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::Lambda::Function                                 gettingPin                                            Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::Lambda::Function                                 timerHandler                                          Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::Lambda::Function                                 bulkUpsertAccommodationsFunction                      Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::Lambda::Function                                 gettingAccommodationCodesFunction                     Resource creation Initiated
CREATE_COMPLETE                                       AWS::Lambda::Function                                 postingCredentialsFunction                            -
CREATE_COMPLETE                                       AWS::Lambda::Function                                 gettingPin                                            -
CREATE_COMPLETE                                       AWS::Lambda::Function                                 timerHandler                                          -
CREATE_COMPLETE                                       AWS::Lambda::Function                                 bulkUpsertAccommodationsFunction                      -
CREATE_IN_PROGRESS                                    AWS::Events::Rule                                     timerHandlerScheduledEvent                            -
CREATE_IN_PROGRESS                                    AWS::Events::Rule                                     timerHandlerScheduledEvent                            Resource creation Initiated
CREATE_COMPLETE                                       AWS::Lambda::Function                                 gettingAccommodationCodesFunction                     -
CREATE_IN_PROGRESS                                    AWS::ApiGateway::RestApi                              ApiGateway                                            -
CREATE_IN_PROGRESS                                    AWS::ApiGateway::RestApi                              ApiGateway                                            Resource creation Initiated
CREATE_COMPLETE                                       AWS::ApiGateway::RestApi                              ApiGateway                                            -
CREATE_IN_PROGRESS                                    AWS::Lambda::Permission                               gettingAccommodationCodesFunctionApiPermissionStage   -
CREATE_IN_PROGRESS                                    AWS::Lambda::Permission                               bulkUpsertAccommodationsFunctionApiPermissionStage    -
CREATE_IN_PROGRESS                                    AWS::ApiGateway::Deployment                           ApiGatewayDeploymentffab4af353                        -
CREATE_IN_PROGRESS                                    AWS::Lambda::Permission                               gettingPinApiPermissionStage                          -
CREATE_IN_PROGRESS                                    AWS::Lambda::Permission                               postingCredentialsFunctionApiPermissionStage          -
CREATE_IN_PROGRESS                                    AWS::Lambda::Permission                               gettingAccommodationCodesFunctionApiPermissionStage   Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::Lambda::Permission                               gettingPinApiPermissionStage                          Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::WAFv2::WebACLAssociation                         ApiGatewayWebACLAssociation                           -
CREATE_IN_PROGRESS                                    AWS::Lambda::Permission                               bulkUpsertAccommodationsFunctionApiPermissionStage    Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::Lambda::Permission                               postingCredentialsFunctionApiPermissionStage          Resource creation Initiated
CREATE_FAILED                                         AWS::WAFv2::WebACLAssociation                         ApiGatewayWebACLAssociation                           Resource handler returned message: "AWS WAF
                                                                                couldn?t perform the operation because your
                                                                                resource doesn?t exist. (Service: Wafv2, Status
                                                                                Code: 400, Request ID:
                                                                                80665733-a939-4fba-8773-75981f2aeec4, Extended
                                                                                Request ID: null)" (RequestToken:
                                                                                b58d050b-a45e-eed9-0c70-6c3945038640,
                                                                                HandlerErrorCode: NotFound)
CREATE_IN_PROGRESS                                    AWS::ApiGateway::Deployment                           ApiGatewayDeploymentffab4af353                        Resource creation Initiated
CREATE_FAILED                                         AWS::Lambda::Permission                               gettingPinApiPermissionStage                          Resource creation cancelled
CREATE_FAILED                                         AWS::Events::Rule                                     timerHandlerScheduledEvent                            Resource creation cancelled
CREATE_FAILED                                         AWS::Lambda::Permission                               bulkUpsertAccommodationsFunctionApiPermissionStage    Resource creation cancelled
CREATE_FAILED                                         AWS::ApiGateway::Deployment                           ApiGatewayDeploymentffab4af353                        Resource creation cancelled
CREATE_FAILED                                         AWS::Lambda::Permission                               gettingAccommodationCodesFunctionApiPermissionStage   Resource creation cancelled
CREATE_FAILED                                         AWS::Lambda::Permission                               postingCredentialsFunctionApiPermissionStage          Resource creation cancelled
ROLLBACK_IN_PROGRESS                                  AWS::CloudFormation::Stack                            ilo                                                   The following resource(s) failed to create:
                                                                                [ApiGatewayWebACLAssociation,
                                                                                gettingPinApiPermissionStage,
                                                                                timerHandlerScheduledEvent,
                                                                                ApiGatewayDeploymentffab4af353,
                                                                                bulkUpsertAccommodationsFunctionApiPermissionStage,
                                                                                gettingAccommodationCodesFunctionApiPermissionStage
                                                                                , postingCredentialsFunctionApiPermissionStage].
                                                                                Rollback requested by user.
DELETE_IN_PROGRESS                                    AWS::ApiGateway::Deployment                           ApiGatewayDeploymentffab4af353                        -
DELETE_IN_PROGRESS                                    AWS::Lambda::Permission                               gettingAccommodationCodesFunctionApiPermissionStage   -
DELETE_IN_PROGRESS                                    AWS::Events::Rule                                     timerHandlerScheduledEvent                            -
DELETE_IN_PROGRESS                                    AWS::Lambda::Permission                               postingCredentialsFunctionApiPermissionStage          -
DELETE_IN_PROGRESS                                    AWS::Lambda::Permission                               bulkUpsertAccommodationsFunctionApiPermissionStage    -
DELETE_IN_PROGRESS                                    AWS::Lambda::Permission                               gettingPinApiPermissionStage                          -
DELETE_COMPLETE                                       AWS::WAFv2::WebACLAssociation                         ApiGatewayWebACLAssociation                           -
DELETE_IN_PROGRESS                                    AWS::WAFv2::WebACL                                    ApiWebACL                                             -
DELETE_COMPLETE                                       AWS::ApiGateway::Deployment                           ApiGatewayDeploymentffab4af353                        -
DELETE_COMPLETE                                       AWS::WAFv2::WebACL                                    ApiWebACL                                             -
DELETE_COMPLETE                                       AWS::Lambda::Permission                               gettingAccommodationCodesFunctionApiPermissionStage   -
DELETE_COMPLETE                                       AWS::Lambda::Permission                               bulkUpsertAccommodationsFunctionApiPermissionStage    -
DELETE_COMPLETE                                       AWS::Lambda::Permission                               gettingPinApiPermissionStage                          -
DELETE_COMPLETE                                       AWS::Lambda::Permission                               postingCredentialsFunctionApiPermissionStage          -
DELETE_IN_PROGRESS                                    AWS::ApiGateway::RestApi                              ApiGateway                                            -
DELETE_COMPLETE                                       AWS::ApiGateway::RestApi                              ApiGateway                                            -
DELETE_IN_PROGRESS                                    AWS::Lambda::Function                                 postingCredentialsFunction                            -
DELETE_IN_PROGRESS                                    AWS::Lambda::Function                                 gettingAccommodationCodesFunction                     -
DELETE_IN_PROGRESS                                    AWS::Lambda::Function                                 bulkUpsertAccommodationsFunction                      -
DELETE_IN_PROGRESS                                    AWS::Lambda::Function                                 gettingPin                                            -
DELETE_COMPLETE                                       AWS::Lambda::Function                                 gettingAccommodationCodesFunction                     -
DELETE_COMPLETE                                       AWS::Lambda::Function                                 gettingPin                                            -
DELETE_COMPLETE                                       AWS::Lambda::Function                                 postingCredentialsFunction                            -
DELETE_COMPLETE                                       AWS::Lambda::Function                                 bulkUpsertAccommodationsFunction                      -
DELETE_IN_PROGRESS                                    AWS::IAM::Role                                        gettingPinRole                                        -
DELETE_IN_PROGRESS                                    AWS::IAM::Role                                        gettingAccommodationCodesFunctionRole                 -
DELETE_IN_PROGRESS                                    AWS::IAM::Role                                        postingCredentialsFunctionRole                        -
DELETE_IN_PROGRESS                                    AWS::IAM::Role                                        bulkUpsertAccommodationsFunctionRole                  -
DELETE_COMPLETE                                       AWS::IAM::Role                                        gettingPinRole                                        -
DELETE_COMPLETE                                       AWS::IAM::Role                                        postingCredentialsFunctionRole                        -
DELETE_COMPLETE                                       AWS::IAM::Role                                        bulkUpsertAccommodationsFunctionRole                  -
DELETE_COMPLETE                                       AWS::IAM::Role                                        gettingAccommodationCodesFunctionRole                 -
DELETE_COMPLETE                                       AWS::Events::Rule                                     timerHandlerScheduledEvent                            -
DELETE_IN_PROGRESS                                    AWS::Lambda::Function                                 timerHandler                                          -
DELETE_COMPLETE                                       AWS::Lambda::Function                                 timerHandler                                          -
DELETE_IN_PROGRESS                                    AWS::IAM::Role                                        timerHandlerRole                                      -
DELETE_COMPLETE                                       AWS::IAM::Role                                        timerHandlerRole                                      -
ROLLBACK_COMPLETE                                     AWS::CloudFormation::Stack                            ilo                                                   -
```

Im using Mac os

Body:
My template looks like this:

Transform: AWS::Serverless-2016-10-31

Parameters:
  Stage:
    Type: String
    Default: dev

Resources:
  ApiWebACL:
    Type: AWS::WAFv2::WebACL
    Properties:
      ...
      ...

  ApiGateway:
    Type: AWS::Serverless::Api
    Properties:
      StageName: !Ref Stage

  #HERE
  ApiGatewayWebACLAssociation:
    Type: AWS::WAFv2::WebACLAssociation
    Properties:
      ResourceArn: !Sub "arn:aws:apigateway:${AWS::Region}::/restapis/${ApiGateway}/stages/${Stage}"
      WebACLArn: !GetAtt ApiWebACL.Arn

  timerHandler:
    Type: AWS::Serverless::Function
    Properties:
      ...
      ...

Please forcus on ApiGatewayWebACLAssociation section. At the first deployment, I must remove this section otherwise the deployment will fail since the AWS::WAFv2::WebACL is not deployed yet. So my question is: Is there any available property like "depends on" to make AWS::WAFv2::WebACLAssociation wait until AWS::WAFv2::WebACL finish its deployment?

Log:

2022-12-19 08:35:30 - Waiting for stack create/update to complete

CloudFormation events from stack operations (refresh every 0.5 seconds)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ResourceStatus                                        ResourceType                                          LogicalResourceId                                     ResourceStatusReason
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        bulkUpsertAccommodationsFunctionRole                  -
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        gettingAccommodationCodesFunctionRole                 -
CREATE_IN_PROGRESS                                    AWS::WAFv2::WebACL                                    ApiWebACL                                             -
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        postingCredentialsFunctionRole                        -
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        gettingPinRole                                        -
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        timerHandlerRole                                      -
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        bulkUpsertAccommodationsFunctionRole                  Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        postingCredentialsFunctionRole                        Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        gettingAccommodationCodesFunctionRole                 Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        gettingPinRole                                        Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::IAM::Role                                        timerHandlerRole                                      Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::WAFv2::WebACL                                    ApiWebACL                                             Resource creation Initiated
CREATE_COMPLETE                                       AWS::WAFv2::WebACL                                    ApiWebACL                                             -
CREATE_COMPLETE                                       AWS::IAM::Role                                        bulkUpsertAccommodationsFunctionRole                  -
CREATE_COMPLETE                                       AWS::IAM::Role                                        postingCredentialsFunctionRole                        -
CREATE_COMPLETE                                       AWS::IAM::Role                                        gettingPinRole                                        -
CREATE_COMPLETE                                       AWS::IAM::Role                                        timerHandlerRole                                      -
CREATE_COMPLETE                                       AWS::IAM::Role                                        gettingAccommodationCodesFunctionRole                 -
CREATE_IN_PROGRESS                                    AWS::Lambda::Function                                 postingCredentialsFunction                            -
CREATE_IN_PROGRESS                                    AWS::Lambda::Function                                 gettingPin                                            -
CREATE_IN_PROGRESS                                    AWS::Lambda::Function                                 timerHandler                                          -
CREATE_IN_PROGRESS                                    AWS::Lambda::Function                                 bulkUpsertAccommodationsFunction                      -
CREATE_IN_PROGRESS                                    AWS::Lambda::Function                                 gettingAccommodationCodesFunction                     -
CREATE_IN_PROGRESS                                    AWS::Lambda::Function                                 postingCredentialsFunction                            Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::Lambda::Function                                 gettingPin                                            Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::Lambda::Function                                 timerHandler                                          Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::Lambda::Function                                 bulkUpsertAccommodationsFunction                      Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::Lambda::Function                                 gettingAccommodationCodesFunction                     Resource creation Initiated
CREATE_COMPLETE                                       AWS::Lambda::Function                                 postingCredentialsFunction                            -
CREATE_COMPLETE                                       AWS::Lambda::Function                                 gettingPin                                            -
CREATE_COMPLETE                                       AWS::Lambda::Function                                 timerHandler                                          -
CREATE_COMPLETE                                       AWS::Lambda::Function                                 bulkUpsertAccommodationsFunction                      -
CREATE_IN_PROGRESS                                    AWS::Events::Rule                                     timerHandlerScheduledEvent                            -
CREATE_IN_PROGRESS                                    AWS::Events::Rule                                     timerHandlerScheduledEvent                            Resource creation Initiated
CREATE_COMPLETE                                       AWS::Lambda::Function                                 gettingAccommodationCodesFunction                     -
CREATE_IN_PROGRESS                                    AWS::ApiGateway::RestApi                              ApiGateway                                            -
CREATE_IN_PROGRESS                                    AWS::ApiGateway::RestApi                              ApiGateway                                            Resource creation Initiated
CREATE_COMPLETE                                       AWS::ApiGateway::RestApi                              ApiGateway                                            -
CREATE_IN_PROGRESS                                    AWS::Lambda::Permission                               gettingAccommodationCodesFunctionApiPermissionStage   -
CREATE_IN_PROGRESS                                    AWS::Lambda::Permission                               bulkUpsertAccommodationsFunctionApiPermissionStage    -
CREATE_IN_PROGRESS                                    AWS::ApiGateway::Deployment                           ApiGatewayDeploymentffab4af353                        -
CREATE_IN_PROGRESS                                    AWS::Lambda::Permission                               gettingPinApiPermissionStage                          -
CREATE_IN_PROGRESS                                    AWS::Lambda::Permission                               postingCredentialsFunctionApiPermissionStage          -
CREATE_IN_PROGRESS                                    AWS::Lambda::Permission                               gettingAccommodationCodesFunctionApiPermissionStage   Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::Lambda::Permission                               gettingPinApiPermissionStage                          Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::WAFv2::WebACLAssociation                         ApiGatewayWebACLAssociation                           -
CREATE_IN_PROGRESS                                    AWS::Lambda::Permission                               bulkUpsertAccommodationsFunctionApiPermissionStage    Resource creation Initiated
CREATE_IN_PROGRESS                                    AWS::Lambda::Permission                               postingCredentialsFunctionApiPermissionStage          Resource creation Initiated
CREATE_FAILED                                         AWS::WAFv2::WebACLAssociation                         ApiGatewayWebACLAssociation                           Resource handler returned message: "AWS WAF
                                                                                couldn?t perform the operation because your
                                                                                resource doesn?t exist. (Service: Wafv2, Status
                                                                                Code: 400, Request ID:
                                                                                80665733-a939-4fba-8773-75981f2aeec4, Extended
                                                                                Request ID: null)" (RequestToken:
                                                                                b58d050b-a45e-eed9-0c70-6c3945038640,
                                                                                HandlerErrorCode: NotFound)
CREATE_IN_PROGRESS                                    AWS::ApiGateway::Deployment                           ApiGatewayDeploymentffab4af353                        Resource creation Initiated
CREATE_FAILED                                         AWS::Lambda::Permission                               gettingPinApiPermissionStage                          Resource creation cancelled
CREATE_FAILED                                         AWS::Events::Rule                                     timerHandlerScheduledEvent                            Resource creation cancelled
CREATE_FAILED                                         AWS::Lambda::Permission                               bulkUpsertAccommodationsFunctionApiPermissionStage    Resource creation cancelled
CREATE_FAILED                                         AWS::ApiGateway::Deployment                           ApiGatewayDeploymentffab4af353                        Resource creation cancelled
CREATE_FAILED                                         AWS::Lambda::Permission                               gettingAccommodationCodesFunctionApiPermissionStage   Resource creation cancelled
CREATE_FAILED                                         AWS::Lambda::Permission                               postingCredentialsFunctionApiPermissionStage          Resource creation cancelled
ROLLBACK_IN_PROGRESS                                  AWS::CloudFormation::Stack                            ilo                                                   The following resource(s) failed to create:
                                                                                [ApiGatewayWebACLAssociation,
                                                                                gettingPinApiPermissionStage,
                                                                                timerHandlerScheduledEvent,
                                                                                ApiGatewayDeploymentffab4af353,
                                                                                bulkUpsertAccommodationsFunctionApiPermissionStage,
                                                                                gettingAccommodationCodesFunctionApiPermissionStage
                                                                                , postingCredentialsFunctionApiPermissionStage].
                                                                                Rollback requested by user.
DELETE_IN_PROGRESS                                    AWS::ApiGateway::Deployment                           ApiGatewayDeploymentffab4af353                        -
DELETE_IN_PROGRESS                                    AWS::Lambda::Permission                               gettingAccommodationCodesFunctionApiPermissionStage   -
DELETE_IN_PROGRESS                                    AWS::Events::Rule                                     timerHandlerScheduledEvent                            -
DELETE_IN_PROGRESS                                    AWS::Lambda::Permission                               postingCredentialsFunctionApiPermissionStage          -
DELETE_IN_PROGRESS                                    AWS::Lambda::Permission                               bulkUpsertAccommodationsFunctionApiPermissionStage    -
DELETE_IN_PROGRESS                                    AWS::Lambda::Permission                               gettingPinApiPermissionStage                          -
DELETE_COMPLETE                                       AWS::WAFv2::WebACLAssociation                         ApiGatewayWebACLAssociation                           -
DELETE_IN_PROGRESS                                    AWS::WAFv2::WebACL                                    ApiWebACL                                             -
DELETE_COMPLETE                                       AWS::ApiGateway::Deployment                           ApiGatewayDeploymentffab4af353                        -
DELETE_COMPLETE                                       AWS::WAFv2::WebACL                                    ApiWebACL                                             -
DELETE_COMPLETE                                       AWS::Lambda::Permission                               gettingAccommodationCodesFunctionApiPermissionStage   -
DELETE_COMPLETE                                       AWS::Lambda::Permission                               bulkUpsertAccommodationsFunctionApiPermissionStage    -
DELETE_COMPLETE                                       AWS::Lambda::Permission                               gettingPinApiPermissionStage                          -
DELETE_COMPLETE                                       AWS::Lambda::Permission                               postingCredentialsFunctionApiPermissionStage          -
DELETE_IN_PROGRESS                                    AWS::ApiGateway::RestApi                              ApiGateway                                            -
DELETE_COMPLETE                                       AWS::ApiGateway::RestApi                              ApiGateway                                            -
DELETE_IN_PROGRESS                                    AWS::Lambda::Function                                 postingCredentialsFunction                            -
DELETE_IN_PROGRESS                                    AWS::Lambda::Function                                 gettingAccommodationCodesFunction                     -
DELETE_IN_PROGRESS                                    AWS::Lambda::Function                                 bulkUpsertAccommodationsFunction                      -
DELETE_IN_PROGRESS                                    AWS::Lambda::Function                                 gettingPin                                            -
DELETE_COMPLETE                                       AWS::Lambda::Function                                 gettingAccommodationCodesFunction                     -
DELETE_COMPLETE                                       AWS::Lambda::Function                                 gettingPin                                            -
DELETE_COMPLETE                                       AWS::Lambda::Function                                 postingCredentialsFunction                            -
DELETE_COMPLETE                                       AWS::Lambda::Function                                 bulkUpsertAccommodationsFunction                      -
DELETE_IN_PROGRESS                                    AWS::IAM::Role                                        gettingPinRole                                        -
DELETE_IN_PROGRESS                                    AWS::IAM::Role                                        gettingAccommodationCodesFunctionRole                 -
DELETE_IN_PROGRESS                                    AWS::IAM::Role                                        postingCredentialsFunctionRole                        -
DELETE_IN_PROGRESS                                    AWS::IAM::Role                                        bulkUpsertAccommodationsFunctionRole                  -
DELETE_COMPLETE                                       AWS::IAM::Role                                        gettingPinRole                                        -
DELETE_COMPLETE                                       AWS::IAM::Role                                        postingCredentialsFunctionRole                        -
DELETE_COMPLETE                                       AWS::IAM::Role                                        bulkUpsertAccommodationsFunctionRole                  -
DELETE_COMPLETE                                       AWS::IAM::Role                                        gettingAccommodationCodesFunctionRole                 -
DELETE_COMPLETE                                       AWS::Events::Rule                                     timerHandlerScheduledEvent                            -
DELETE_IN_PROGRESS                                    AWS::Lambda::Function                                 timerHandler                                          -
DELETE_COMPLETE                                       AWS::Lambda::Function                                 timerHandler                                          -
DELETE_IN_PROGRESS                                    AWS::IAM::Role                                        timerHandlerRole                                      -
DELETE_COMPLETE                                       AWS::IAM::Role                                        timerHandlerRole                                      -
ROLLBACK_COMPLETE                                     AWS::CloudFormation::Stack                            ilo                                                   -

Im using Mac os


问:
How to save a PDF opened in IE new browser
I have a scenario to save a PDF which is opened in a window. By default selenium control moves to the Window, As it is a banking application I cannot repost the URL to save the pdf, I cannot press CTRL + S and right click doesn’t have any required data but using Robot I can click or move to an element, now the save button will enable only if you mouse over at the bottom of the page. I tried using ROBOT mouse over but the pop up did not popped up may be the reason it is not navigating via UI.
I have tried Sikuli also as the save pop up only pop up while mouse over that also failed.

We cannot use Actions as it wont support Webdriver driver, I have used Sikuli and ROBOT class mouse over.
The save Pop up opens only when it is mouse over at the bottom of the page, and it is not happening in ROBOT class as it navigates via DOM. please help


问:
Which value should be used for X-Frame-Options header to allow embed a webpage in iframe only in mobile app without any domain
I have build a tiny Ionic app from scratch.
All I have - only one component, that contains an iframe to a webpage.

The webpage cannot be displayed in iframe, because of this error:
Refused to display 'my webpage url here' in a frame because it set 'X-Frame-Options' to 'sameorigin'.

I have control over the webpage, so I can add any headers.

when running ionic application it is served on localhost:8100, so I can add it to display when running in a browser.

But what about the application build, for example for Android?

As I understand - it does not have any url.
So, how can I allow to run a webpage in iframe only for mobile app, but restrict for any other websites?

When I run the application in an emulator I see error:

E/Capacitor/Console: File: http://localhost/ - Line 0 - Msg: Refused to display 'my webpage url here' in a frame because it set 'X-Frame-Options' to 'sameorigin'.

so, is the http://localhost/ - correct domain to add for mobile apps? Will it work for iOS as well?

And why mobile apps have the localhost ? they actaully shouldn't have any domain at all, ar I am not correct?


问:
mlflow ui doesn't show logged runs of my keras model
I created a sample keras model, and use mlflow.tensorflow.autolog() to track my model. However, the logged runs are not appeared in mlflow ui.

```<code>mlflow.tensorflow.autolog()

#setting hyper parameters
batch_size = 10
epochs = 100
optimizer = 'adam'
loss = 'binary_crossentropy'

def create_classifier():
    classifier = tf.keras.Sequential()
    classifier.add(tf.keras.layers.Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 12))
    classifier.add(tf.keras.layers.Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu'))
    classifier.add(tf.keras.layers.Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))
    classifier.compile(optimizer = optimizer, loss = loss, metrics = ['accuracy'])
    return classifier

classifier = create_classifier()
classifier.summary()

classifier.fit(X_train.to_numpy(), y_train.to_numpy(), batch_size = batch_size, epochs = epochs,verbose = 1)

score, acc = classifier.evaluate(X_train.to_numpy(), y_train.to_numpy(), batch_size=batch_size)

y_pred = classifier.predict(X_test.to_numpy())
y_pred = (y_pred > 0.5)

print('*'*20)
score, acc = classifier.evaluate(X_test.to_numpy(), y_test.to_numpy(),
                            batch_size=batch_size)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
</code>```

I got following warning when I call autolog

The output when I fit the model with training data:

What do I need to do in order to make the run available in mlflow ui?

Note: MlFlow doc states that it only compatible with tensorflow >=2.3 and my tensorflow is 2.10.1.

update:
I found there are 2 /mlruns directories in my project, one located where my python code located as you can see in the screen clip, "ml-flow-project-example2/model/mlruns", and another one located at "ml-flow-project-example2/venv/Scripts/mlruns". However, the /mlruns in venv is empty. But it is where the mlflow.exe located. If I move the directory "7c10db034cdd47dfbba12885da25ff0f" from /model/mlruns to venv/Scripts/mlruns, the run will appear in mlflow ui.

Is there anyway to let mlflow ui point to the correct mlruns directory?

Body:
I created a sample keras model, and use mlflow.tensorflow.autolog() to track my model. However, the logged runs are not appeared in mlflow ui.

mlflow.tensorflow.autolog()

#setting hyper parameters
batch_size = 10
epochs = 100
optimizer = 'adam'
loss = 'binary_crossentropy'

def create_classifier():
    classifier = tf.keras.Sequential()
    classifier.add(tf.keras.layers.Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 12))
    classifier.add(tf.keras.layers.Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu'))
    classifier.add(tf.keras.layers.Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))
    classifier.compile(optimizer = optimizer, loss = loss, metrics = ['accuracy'])
    return classifier

classifier = create_classifier()
classifier.summary()

classifier.fit(X_train.to_numpy(), y_train.to_numpy(), batch_size = batch_size, epochs = epochs,verbose = 1)

score, acc = classifier.evaluate(X_train.to_numpy(), y_train.to_numpy(), batch_size=batch_size)

y_pred = classifier.predict(X_test.to_numpy())
y_pred = (y_pred > 0.5)

print('*'*20)
score, acc = classifier.evaluate(X_test.to_numpy(), y_test.to_numpy(),
                            batch_size=batch_size)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

I got following warning when I call autolog

The output when I fit the model with training data:

What do I need to do in order to make the run available in mlflow ui?

Note: MlFlow doc states that it only compatible with tensorflow >=2.3 and my tensorflow is 2.10.1.

update:
I found there are 2 /mlruns directories in my project, one located where my python code located as you can see in the screen clip, "ml-flow-project-example2/model/mlruns", and another one located at "ml-flow-project-example2/venv/Scripts/mlruns". However, the /mlruns in venv is empty. But it is where the mlflow.exe located. If I move the directory "7c10db034cdd47dfbba12885da25ff0f" from /model/mlruns to venv/Scripts/mlruns, the run will appear in mlflow ui.

Is there anyway to let mlflow ui point to the correct mlruns directory?


问:
Can someone think about list of most critical api levels for testing?
I was thinking about list of API levels I should use as most important for testing out.

I mean in some versions of android there whee introduced new security features, that made some previous ways of how things where done obsolete.
Like file providers or others, as i don't have good memory for such a things, I was thinking to makes some simulators for most critical api levels from api level 24 to run locally when running automated tests or manually.

Maybe there is some simple rule for that or maybe those big changes to platform where introduced randomly so its hard to make such recommendation at all.

Any thoughts on that ?


问:
How do I bind my index finger movement read using webcam to cursor movement on screen?
I have the coordinates of my index finger that is read through a webcam. I am even able to convert them to frame coordinates. But I am unable to have the mouse respond properly to the movements. It just jumps to the right edge of the screen and sticks there.

I tried doing this using PyAutoGUI. I thought about multiplying the coordinates with the ratio of screen dimensions and frame dimensions.

This code triggers the failsafeCheck in PyAutoGUI.

move_x = index_position[0] * (screen_width / frame_width)
move_y = index_position[1] * (screen_height / frame_height)
pyautogui.moveTo(move_x, move_y)
```
<p>Changing from "moveTo" to "move" makes the mouse move extremely slowly and only to the right. Nothing on the left, up or down.</p>
<p>I also saw the one below being used in a tutorial so I modified it and tried it too.</p>
<pre class="lang-py prettyprint-override"><code>x1 = np.interp(index_position[0], (frame_reduce, image_width - frame_reduce), (0, screen_width))
y1 = np.interp(index_position[1], (frame_reduce, image_height - frame_reduce), (0, screen_height))

curr_loc_x = prev_loc_x + (x1 - prev_loc_x) / smoothening
curr_loc_y = prev_loc_y + (y1 - prev_loc_y) / smoothening
pyautogui.move(screen_width - curr_loc_x, curr_loc_y)
prev_loc_x, prev_loc_y = curr_loc_x, curr_loc_y
</code>```

Edit: This works as a basic method but it will not actually follow my finger like I want it to.

if hand_pose == "index finger":
    if zone == "left":
        pyautogui.move(-50,0)
    elif zone == "right":
        pyautogui.move(50, 0)
    elif zone == "top":
        pyautogui.move(0,-50)
    elif zone == "bottom":
        pyautogui.move(0, 50)
```

Body:
I have the coordinates of my index finger that is read through a webcam. I am even able to convert them to frame coordinates. But I am unable to have the mouse respond properly to the movements. It just jumps to the right edge of the screen and sticks there.

I tried doing this using PyAutoGUI. I thought about multiplying the coordinates with the ratio of screen dimensions and frame dimensions.

This code triggers the failsafeCheck in PyAutoGUI.

move_x = index_position[0] * (screen_width / frame_width)
move_y = index_position[1] * (screen_height / frame_height)
pyautogui.moveTo(move_x, move_y)

Changing from "moveTo" to "move" makes the mouse move extremely slowly and only to the right. Nothing on the left, up or down.

I also saw the one below being used in a tutorial so I modified it and tried it too.

x1 = np.interp(index_position[0], (frame_reduce, image_width - frame_reduce), (0, screen_width))
y1 = np.interp(index_position[1], (frame_reduce, image_height - frame_reduce), (0, screen_height))

curr_loc_x = prev_loc_x + (x1 - prev_loc_x) / smoothening
curr_loc_y = prev_loc_y + (y1 - prev_loc_y) / smoothening
pyautogui.move(screen_width - curr_loc_x, curr_loc_y)
prev_loc_x, prev_loc_y = curr_loc_x, curr_loc_y

Edit: This works as a basic method but it will not actually follow my finger like I want it to.

if hand_pose == "index finger":
    if zone == "left":
        pyautogui.move(-50,0)
    elif zone == "right":
        pyautogui.move(50, 0)
    elif zone == "top":
        pyautogui.move(0,-50)
    elif zone == "bottom":
        pyautogui.move(0, 50)


问:
Jetpack compose: Get navigation arguments inside view model
I am passing an id as part of the nav args when navigating to a new composable screen. How can I get this id argument inside viewModel of the destination screen.


问:
HTTP Status 404 – Not Found when calling servlet
// Servlet File

```<code>import java.io.IOException;
import java.io.PrintWriter;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/Index")
public class IndexServlet extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String s = req.getParameter("username");

        PrintWriter out = resp.getWriter();
        out.println("Hi " + s);

    }
}
</code>```

//home.jsp file

```<code>
    <form action="Index">
        <input type="text" name="username"> <br>
        <input type="text" name="password"> <br>
        <input type="submit">

</code>```

I want to print (Hi + username) which is coded on servlet
I am requesting the username from the JSP file but when hit submit I am getting the error

Body:
// Servlet File

import java.io.IOException;
import java.io.PrintWriter;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/Index")
public class IndexServlet extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String s = req.getParameter("username");

        PrintWriter out = resp.getWriter();
        out.println("Hi " + s);

    }
}

//home.jsp file

    <form action="Index">
        <input type="text" name="username">

        <input type="text" name="password">

        <input type="submit">

I want to print (Hi + username) which is coded on servlet
I am requesting the username from the JSP file but when hit submit I am getting the error


问:
Is there any way to preserve my data using 'write.csv' and 'read.csv'?
This is my data frame A
column : 7
row :   10000000

I tried to make this data frame into csv file.

```<code>write.csv(A, file="Bus station.csv")
</code>```

However, the csv file contains only some rows.

```<code>B <- read.csv("Bus station.csv", header = T, fileEncoding = "euc-kr")
</code>```

dim(B)
column : 8
row :  1048575

I want to preserve this data and make it into new file.
I don't care using any other functions without 'write.csv' or something.

Body:
This is my data frame A
column : 7
row :   10000000

I tried to make this data frame into csv file.

write.csv(A, file="Bus station.csv")

However, the csv file contains only some rows.

B <- read.csv("Bus station.csv", header = T, fileEncoding = "euc-kr")

dim(B)
column : 8
row :  1048575

I want to preserve this data and make it into new file.
I don't care using any other functions without 'write.csv' or something.


问:
Question about the relationship between Jena model.add and SPARQL
Does Jena's model.add method save to SDB using SPARQL? I mean how to save triple to SDB.
I'm just asking out of curiosity.
I know that SDB's project has been suspended.</p>


问:
CUDA Manjaro Nvidia gtx 970 Bus error (core dumped)
I get with this simple kernel an "Bus error (core dumped)".

Operation System: Linux-x86_64
Nvidia Driver Version: 525.60.11
NVML Version: 12.525.60.11
Kernel: 5.10.157-1-MANJARO
CUDA/CUDA Tools: 11.8.0-1

```<code>__global__
void add(char *y)
{
    int index = blockIdx.x * blockDim.x + threadIdx.x;

    int fac = 2*3*4*5*6*7*8*9*10*11*12;

printf("debug 0\n");
printf("debug 3 %d\n",fac);

    for(int i = 0; i < fac; i++){
        if(i % 1000000 == 0){
            printf("debug 7 %d\n",i);
        }
    }
printf("debug 10\n");
}

int main(void)
{
  int N = 1;
  int M = N*6;
  char *y;

  // Allocate Unified Memory – accessible from CPU or GPU
  cudaMallocManaged(&y, M*sizeof(char));

  // Run kernel on 1M elements on the GPU
  add<<<1, 1>>>(y);

  // Wait for GPU to finish before accessing on host
  cudaDeviceSynchronize();

  // Free memory
  cudaFree(y);

  return 0;
}
</code>```

It crash always at different times. debug 10will not be reached!

Has anyone an idea why?

Body:
I get with this simple kernel an "Bus error (core dumped)".

Operation System: Linux-x86_64
Nvidia Driver Version: 525.60.11
NVML Version: 12.525.60.11
Kernel: 5.10.157-1-MANJARO
CUDA/CUDA Tools: 11.8.0-1

__global__
void add(char *y)
{
    int index = blockIdx.x * blockDim.x + threadIdx.x;

    int fac = 2*3*4*5*6*7*8*9*10*11*12;

printf("debug 0\n");
printf("debug 3 %d\n",fac);

    for(int i = 0; i < fac; i++){
        if(i % 1000000 == 0){
            printf("debug 7 %d\n",i);
        }
    }
printf("debug 10\n");
}

int main(void)
{
  int N = 1;
  int M = N*6;
  char *y;

  // Allocate Unified Memory – accessible from CPU or GPU
  cudaMallocManaged(&y, M*sizeof(char));

  // Run kernel on 1M elements on the GPU
  add<<<1, 1>>>(y);

  // Wait for GPU to finish before accessing on host
  cudaDeviceSynchronize();

  // Free memory
  cudaFree(y);

  return 0;
}

It crash always at different times. debug 10will not be reached!

Has anyone an idea why?


问:
Android Google Sign-in doesn't work on different devices without adding SHA-1 key from each device in Firebase console
I've been working on an Android app with Firebase authentication via Google sign-in.

There is an issue with the Google sign-in where it doesn't allow sign-in (returns 12500 error) unless I add the SHA-1 key generated from the specific device I'm running the emulator on.

This is a problem because I have others in my team that are working on it and I have to add their device's SHA-1 key to allow them to sign in.

I've added both the SHA-1 and SHA-256 of the debug and the release key generated from my computer to the Firebase console, as well as replacing the google-services.json with the new one after having added the keys. (https://developers.google.com/android/guides/client-auth?utm_source=firebase.google.com&utm_medium=referral)

Also, I set the support email in the Firebase console as well because apparently that's what 12500 error is about.

But this is still only letting me sign in with Google and no one else, so I have to manually add their device's SHA-1 key each time.

With everyone's keys added, one thing odd is that my teammates are still able to sign in when they build the app to an Android phone connected to their PC and not the emulator running on the PC.

I'm sure this isn't the right way of doing things because one set of keys should be allowing sign-in to all devices.

Is there something I'm missing here?


问:
CNN I'm trying to generate confusion Matrix and classification report for Multiclass classification of custom model. But values didn't seems correct
```<code>#Confusion Matrix

from sklearn.metrics import confusion_matrix

plt.figure(figsize=(16,9))

y_pred_labels = [ np.argmax(label) for label in predict ]
cm = confusion_matrix(test_set.classes, y_pred_labels)

# show cm
sns.heatmap(cm, annot=True, fmt='d',xticklabels=class_labels, yticklabels=class_labels)

from sklearn.metrics import classification_report
cr= classification_report(test_set.classes, y_pred_labels, target_names=class_labels)
print(cr)
</code>```
```<code>[Load Data from directory](https://i.stack.imgur.com/p87gv.png)
[accuracy](https://i.stack.imgur.com/1dSab.png)
[evaluate](https://i.stack.imgur.com/LEV0X.png)
[predict](https://i.stack.imgur.com/Kiim2.png)
[cm and cr](https://i.stack.imgur.com/sQN9P.png)
[cr](https://i.stack.imgur.com/dMAaB.png)
[cm](https://i.stack.imgur.com/LzqcY.png)

</code>```

Complete flow is as given screenshots.
Anyone Can find where is actual problem. How can i get the correct values in classification report? While in predictions values are correct by use of model. predict method and pass there a data set.

Body:
#Confusion Matrix

from sklearn.metrics import confusion_matrix

plt.figure(figsize=(16,9))

y_pred_labels = [ np.argmax(label) for label in predict ]
cm = confusion_matrix(test_set.classes, y_pred_labels)

# show cm
sns.heatmap(cm, annot=True, fmt='d',xticklabels=class_labels, yticklabels=class_labels)

from sklearn.metrics import classification_report
cr= classification_report(test_set.classes, y_pred_labels, target_names=class_labels)
print(cr)

[Load Data from directory](https://i.stack.imgur.com/p87gv.png)
[accuracy](https://i.stack.imgur.com/1dSab.png)
[evaluate](https://i.stack.imgur.com/LEV0X.png)
[predict](https://i.stack.imgur.com/Kiim2.png)
[cm and cr](https://i.stack.imgur.com/sQN9P.png)
[cr](https://i.stack.imgur.com/dMAaB.png)
[cm](https://i.stack.imgur.com/LzqcY.png)

Complete flow is as given screenshots.
Anyone Can find where is actual problem. How can i get the correct values in classification report? While in predictions values are correct by use of model. predict method and pass there a data set.


问:
GCLB Connection Drainning for Cloud Run
How does GCLB connection drainning apply to Cloud Run when Cloud Run + Serverless NEG is used as a backend?
Also, when using http or http/2 as a connection between LB and Cloud Run, is there any difference in behavior between the two?

I am using Cloud Run in the above configuration, and I am getting 503 errors when the container drops, so I thought it might have to do with Connection Drainning in GCLB.

Title: GCLB Connection Drainning for Cloud Run


问:
Psychtoolbox flip time issue
I am running a psychophysics task on psychtoolbox that need to show each image for 16, 30, 60, and 120 milliseconds. Although my system monitor refresh rate is 16.66 ms (60 Hz) but the lowest time I get is almost 33 ms (I check this time by recording video from the screen while showing these images).

I've searched a lot and now I use flip with specifying the time with ifi and nextFrameInterval but still can't show my image for 16 milliseconds. Why is this happening and how can I fix this?

```<code>ifi = Screen('GetFlipInterval',window);

Screen('DrawTexture',window,fixation,[],fixRect);
[~,lastVisualInterval] = Screen('Flip', window);

nextStimFrameDelta= (p.pre_mask_time/ifi);
Screen('DrawTexture',window,stimulus(rec(TrialNum, 3)),[],rectStim);
[~,lastVisualInterval] = Screen('Flip', window,lastVisualInterval +((nextStimFrameDelta-0.5)*ifi));

nextStimFrameDelta= ((rec(TrialNum,2)/1000)/ifi)  % rec(TrialNum,2) is the duration of peresenting images (16,30,... ms)
Screen('DrawTexture',window,mask(TrialNum),[],rectStim);
[~,lastVisualInterval] = Screen('Flip', window,lastVisualInterval +((nextStimFrameDelta-0.5)*ifi));
% And here the facial expression must be replaced by a mask after 16 or 30,... ms
</code>```

Title: Psychtoolbox flip time issue

Body:
I am running a psychophysics task on psychtoolbox that need to show each image for 16, 30, 60, and 120 milliseconds. Although my system monitor refresh rate is 16.66 ms (60 Hz) but the lowest time I get is almost 33 ms (I check this time by recording video from the screen while showing these images).

I've searched a lot and now I use flip with specifying the time with ifi and nextFrameInterval but still can't show my image for 16 milliseconds. Why is this happening and how can I fix this?

ifi = Screen('GetFlipInterval',window);

Screen('DrawTexture',window,fixation,[],fixRect);
[~,lastVisualInterval] = Screen('Flip', window);

nextStimFrameDelta= (p.pre_mask_time/ifi);
Screen('DrawTexture',window,stimulus(rec(TrialNum, 3)),[],rectStim);
[~,lastVisualInterval] = Screen('Flip', window,lastVisualInterval +((nextStimFrameDelta-0.5)*ifi));

nextStimFrameDelta= ((rec(TrialNum,2)/1000)/ifi)  % rec(TrialNum,2) is the duration of peresenting images (16,30,... ms)
Screen('DrawTexture',window,mask(TrialNum),[],rectStim);
[~,lastVisualInterval] = Screen('Flip', window,lastVisualInterval +((nextStimFrameDelta-0.5)*ifi));
% And here the facial expression must be replaced by a mask after 16 or 30,... ms


问:
Unable to use d3.sum() multiple times in d3.flatrollup
I have a JSON data which contains mulitple objects including repeating 'branch names' and remaining unique data. I want to consolidate all the branch names data adding up all the datapoints so that there is a single object per 'branch name'.

I used d3.flatrollup(), and for addition I have used d3.sum() but it is accepting only single properties.

How can I add all the remaining fields data and assign them to a 'branch name' accordingly?

var test = [
  { branch_name: "madhapur", total_visits: "75", paid: "80", },
  { branch_name: "madhapur", total_visits: "50", paid: "55", },
  { branch_name: "manikonda", total_visits: "15", paid: "60", },
  { branch_name: "manikonda", total_visits: "35", paid: "20", },
  { branch_name: "krishna Nagar", total_visits: "95", paid: "30", },
];

var gfg1 = d3.flatRollup(
  test,
  (v) => d3.sum(v, (d) => d.total_visits),
  (d) => d.branch_name
);
console.log(gfg1);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.6.1/d3.min.js"></script></code>```

I get this output:

```<code>// output:
["madhapur", 125]
["manikonda", 50]
["krishna Nagar", 95]
</code>```

The desired output is:

```<code>// Desired Output:
["madhapur", 125, 135]
["manikonda", 50, 80]
["krishna Nagar", 95, 30];
</code>```

Body:
I have a JSON data which contains mulitple objects including repeating 'branch names' and remaining unique data. I want to consolidate all the branch names data adding up all the datapoints so that there is a single object per 'branch name'.

I used d3.flatrollup(), and for addition I have used d3.sum() but it is accepting only single properties.

How can I add all the remaining fields data and assign them to a 'branch name' accordingly?

var test = [
  { branch_name: "madhapur", total_visits: "75", paid: "80", },
  { branch_name: "madhapur", total_visits: "50", paid: "55", },
  { branch_name: "manikonda", total_visits: "15", paid: "60", },
  { branch_name: "manikonda", total_visits: "35", paid: "20", },
  { branch_name: "krishna Nagar", total_visits: "95", paid: "30", },
];

var gfg1 = d3.flatRollup(
  test,
  (v) => d3.sum(v, (d) => d.total_visits),
  (d) => d.branch_name
);
console.log(gfg1);

I get this output:

// output:
["madhapur", 125]
["manikonda", 50]
["krishna Nagar", 95]

The desired output is:

// Desired Output:
["madhapur", 125, 135]
["manikonda", 50, 80]
["krishna Nagar", 95, 30];


问:
How to access my Vue instance property inside of a web socket inside created
I'd like to know how i can access my component messages (this.messages)
from inside the chat socket on message function, so I can push a new message to my messages

Defining the websocket as a property is the way I managed to make it work. If there is a better way of doing it, I will be open to understand.

```<code><script>
import axios from 'axios'

export default{
    data () {
        return {
            messages: [],
            conversation_id: 'global',
            content: '',
            tweeker: this.$store.state.username,
            formatted_time: 'Now',
            avatar: '',
            chatSocket: null,
        }
    },
    created() {
        var loc = window.location, new_uri;
        if (loc.protocol === "https:") {
            new_uri = "wss:";
        } else {
            new_uri = "ws:";
        }
        new_uri += "//" + "127.0.0.1:8000";
        this.chatSocket = new WebSocket(
            new_uri +
            '/ws/' +
            'chat/' +
            '0' +
            '/'
        );
        this.chatSocket.onmessage = function (e) {
            const data = JSON.parse(e.data);
            // append message to messages
            this.messages.push(data);
            setTimeout(() => {
                window.scrollTo(0, document.body.scrollHeight);
            }, 0);
        };
        this.getMessages();
    },
    methods: {
        async getMessages(){
            await axios.get(`/api/messages/global`,)
            .then(response => {
                for (let i = 0; i < response.data.messages.length; i++) {
                    this.messages.push(response.data.messages[i])
                }
                this.scrollToBottom();
            }).catch(error => {
                console.log('error' + error)
            })
        },
        submitMessage() {
            if (this.content.length > 0) {
                let message = {
                    'content': this.content,
                    'tweeker_name': this.$store.state.username,
                    'formatted_time': this.formatted_time,
                    'avatar_url': this.avatar,
                    'conversation_id': '',
                };
                this.chatSocket.send(JSON.stringify(message));
                this.content = '';
            }
        },
        scrollToBottom() {
            window.scrollTo(0, document.body.scrollHeight);
        }
    }
}
</script>
</code>```


问:
Can't call Google Cloud Function from a react app. I get googleauth.js:17 Uncaught Error: Cannot find module 'child_process' in my browser's console
I have this app here: https://github.com/ChristianOConnor/google-cloudfunction-callfromreactapp. It is literally just the output of npx create-react-app google-cloudfunction-callfromreactapp --template typescript and making a few changes. I added src/api/google.ts which looks like this:

```<code>import { JWT } from "google-auth-library";
import keys from 'PATH TO KEYS HERE';

async function BasicTest() {
  const client = new JWT({
    email: keys.client_email,
    key: keys.private_key
  });
  const url = '<FUNCTION URL>';
  const res = await client.request({url});
  return res.data
  //return 'does this work'
}

export default BasicTest;
</code>```

Obviously you would replace 'PATH TO KEYS HERE' with the path to your relevant service account and '<FUNCTION URL>' with the url to trigger your Google cloud function.

This is my simple Google cloud function that outputs a simple string:

```<code>import functions_framework

@functions_framework.http
def hello_http(request):
   """HTTP Cloud Function.
   Args:
       request (flask.Request): The request object.
       <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>
   Returns:
       The response text, or any set of values that can be turned into a
       Response object using `make_response`
       <https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>.
   """
   request_json = request.get_json(silent=True)
   request_args = request.args

   if request_json and 'name' in request_json:
       name = request_json['name']
   elif request_args and 'name' in request_args:
       name = request_args['name']
   else:
       name = 'World'
   return 'Hello {}!'.format(name)
</code>```

It's a simple defualt python function that outputs a string.

I also changed the App.tsx file to this:

```<code>import logo from './logo.svg';
import './App.css';
import React, { useState } from 'react';
import BasicTest from './api/google';

function App() {
  const [resp, setResp] = useState('');

  async function callApi() {
    const calledData = await BasicTest().catch(console.error);
    setResp(calledData as string);
  }

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.tsx</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
      <div className="card">
        <button onClick={() => callApi()}>
          click this to call API
        </button>
        <p>
          {resp}
        </p>
      </div>
    </div>
  );
}

export default App;
</code>```

This app works perfectly when I remove all of the google cloud function stuff and simply have google.ts return "the function ran":

But when I put the Google cloud function stuff back in, it fails with this error in my browser.

```<code>googleauth.js:17 Uncaught Error: Cannot find module 'child_process'
    at webpackMissingModule (googleauth.js:17:1)
    at ./node_modules/google-auth-library/build/src/auth/googleauth.js (googleauth.js:17:1)
    at options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:62:1)
    at ./node_modules/google-auth-library/build/src/index.js (index.js:17:1)
    at options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:62:1)
    at ./src/api/google.ts (App.tsx:42:1)
</code>```

If it helps to debug this, lines 15 through 20 in googleauth.js looks like this:

```<code>Object.defineProperty(exports, "__esModule", { value: true });
exports.GoogleAuth = exports.CLOUD_SDK_CLIENT_ID = void 0;
const child_process_1 = require("child_process");
const fs = require("fs");
const gcpMetadata = require("gcp-metadata");
</code>```

The error is this line const child_process_1 = require("child_process");

So how can I fix this?

Body:
I have this app here: https://github.com/ChristianOConnor/google-cloudfunction-callfromreactapp. It is literally just the output of npx create-react-app google-cloudfunction-callfromreactapp --template typescript and making a few changes. I added src/api/google.ts which looks like this:

import { JWT } from "google-auth-library";
import keys from 'PATH TO KEYS HERE';

async function BasicTest() {
  const client = new JWT({
    email: keys.client_email,
    key: keys.private_key
  });
  const url = '<FUNCTION URL>';
  const res = await client.request({url});
  return res.data
  //return 'does this work'
}

export default BasicTest;

Obviously you would replace 'PATH TO KEYS HERE' with the path to your relevant service account and '<FUNCTION URL>' with the url to trigger your Google cloud function.

This is my simple Google cloud function that outputs a simple string:

import functions_framework

@functions_framework.http
def hello_http(request):
   """HTTP Cloud Function.
   Args:
       request (flask.Request): The request object.
       <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>
   Returns:
       The response text, or any set of values that can be turned into a
       Response object using `make_response`
       <https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>.
   """
   request_json = request.get_json(silent=True)
   request_args = request.args

   if request_json and 'name' in request_json:
       name = request_json['name']
   elif request_args and 'name' in request_args:
       name = request_args['name']
   else:
       name = 'World'
   return 'Hello {}!'.format(name)

It's a simple defualt python function that outputs a string.

I also changed the App.tsx file to this:

import logo from './logo.svg';
import './App.css';
import React, { useState } from 'react';
import BasicTest from './api/google';

function App() {
  const [resp, setResp] = useState('');

  async function callApi() {
    const calledData = await BasicTest().catch(console.error);
    setResp(calledData as string);
  }

  return (

          Edit src/App.tsx and save to reload.

          Learn React

        <button onClick={() => callApi()}>
          click this to call API
        </button>

          {resp}

  );
}

export default App;

This app works perfectly when I remove all of the google cloud function stuff and simply have google.ts return "the function ran":

But when I put the Google cloud function stuff back in, it fails with this error in my browser.

googleauth.js:17 Uncaught Error: Cannot find module 'child_process'
    at webpackMissingModule (googleauth.js:17:1)
    at ./node_modules/google-auth-library/build/src/auth/googleauth.js (googleauth.js:17:1)
    at options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:62:1)
    at ./node_modules/google-auth-library/build/src/index.js (index.js:17:1)
    at options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:62:1)
    at ./src/api/google.ts (App.tsx:42:1)

If it helps to debug this, lines 15 through 20 in googleauth.js looks like this:

Object.defineProperty(exports, "__esModule", { value: true });
exports.GoogleAuth = exports.CLOUD_SDK_CLIENT_ID = void 0;
const child_process_1 = require("child_process");
const fs = require("fs");
const gcpMetadata = require("gcp-metadata");

The error is this line const child_process_1 = require("child_process");

So how can I fix this?


问:
LaTeX mathematical symbols are shown incorrectly in Github Pages
I'm creating a web-site using markdown and I use VS Code and Github Pages for it. I want to include the LaTeX formula to the site. The code is:

```<code>There is a formula: $x = {-b \pm \sqrt{b^2-4ac} \over 2a}$
</code>```

The Open Preview renders it as expected:

Open Preview

I've uploaded it to Github Pages and now it looks like this:

Github Pages

Am I doing something wrong?

I had thoughts I had some syntax mistakes but when I was reading docs I found nothing wrong with my code. I tried to copy&paste but the problem was the same.

Body:
I'm creating a web-site using markdown and I use VS Code and Github Pages for it. I want to include the LaTeX formula to the site. The code is:

There is a formula: $x = {-b \pm \sqrt{b^2-4ac} \over 2a}$

The Open Preview renders it as expected:

Open Preview

I've uploaded it to Github Pages and now it looks like this:

Github Pages

Am I doing something wrong?

I had thoughts I had some syntax mistakes but when I was reading docs I found nothing wrong with my code. I tried to copy&paste but the problem was the same.


问:
The `text-paragraph` class does not exist. If `text-paragraph` is a custom class, make sure it is defined within a `@layer` directive
```<code>@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
    body {
        @apply font-body text-paragraph leading-6 bg-gray-200;
    }

</code>```

The text-paragraph class does not exist. If text-paragraph is a custom class, make sure it is defined within a @layer directive.

E:/XAMPP/htdocs/laravel/portfolio/resources/css/app.css:1:1

1  |  @tailwind base;
|   ^

```<code>

solve error
</code>```

Body:
@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
    body {
        @apply font-body text-paragraph leading-6 bg-gray-200;
    }

The text-paragraph class does not exist. If text-paragraph is a custom class, make sure it is defined within a @layer directive.

E:/XAMPP/htdocs/laravel/portfolio/resources/css/app.css:1:1

1  |  @tailwind base;
|   ^

solve error


问:
Stuck on creating the moving parts for my text based game in Python
I am creating a text-based game for my python class. I am trying to get my code to do a few things.

When a user inputs they say no to play, it tells them 'there's always next time' then I want the loop and all gameplay to end. When I execute the code with a break, it gives me my print but also continues the gameplay. The same for if a user inputs exit.

I am trying to access the room and item associated with a users cardinal direction. Ex. The user goes North, the code tells them the current room they are now in as well as the item in that room if there is one.

I have gone through zybooks and gone over dictionaries and functions a few times but I'm not sure where I am messing up at. Thank you guys in advance.

```<code>def show_game_instructions():
    #show game title and instructions
    print('Welcome to Alien v. Tuna Sandwich')
    print()
    print('Collect 6 items to make a Tuna sandwich or the Alien will stay in your house forever')
    print('Move commands: go North, go South, go East, go West')
    print("Add to inventory: get 'item name'")
    print()
    answer = input('Would you like to play? (yes, no, exit)' ) #user input to begin the game or not
    while answer != 'exit':
        if answer.lower().strip() == 'yes':
            print("Great! Let's begin...")
            break
            game_play()

        elif answer.lower().strip() == 'no':
            print("That's alright, there's always next time")
            break
        elif answer.lower().strip() == 'exit': #exit ceases the game immediately
            print('Game over, thank you for playing!')
            break
        else:
            print(f'{answer} is an invalid input')
            show_game_instructions()
        break
show_game_instructions()
</code>```
```<code>rooms = {
        'Hallway': {'North': 'Living Room', 'South': 'Bedroom_1', 'West': 'Dining Room', 'East':            'Kitchen', 'Item': 'Empty'},
        'Dining Room': {'East': 'Hallway', 'Item': 'Bread'}}

user_input = input('Would you like to go North, South, East, or West? ')
def game_play():
    while user_input != exit:
        if user_input in rooms.values():
            north = rooms[user_input]['Item']
            print(north)

        else:
            print('Thank you for playing')
            break
</code>```
```<code></code>```

Body:
I am creating a text-based game for my python class. I am trying to get my code to do a few things.

When a user inputs they say no to play, it tells them 'there's always next time' then I want the loop and all gameplay to end. When I execute the code with a break, it gives me my print but also continues the gameplay. The same for if a user inputs exit.

I am trying to access the room and item associated with a users cardinal direction. Ex. The user goes North, the code tells them the current room they are now in as well as the item in that room if there is one.

I have gone through zybooks and gone over dictionaries and functions a few times but I'm not sure where I am messing up at. Thank you guys in advance.

def show_game_instructions():
    #show game title and instructions
    print('Welcome to Alien v. Tuna Sandwich')
    print()
    print('Collect 6 items to make a Tuna sandwich or the Alien will stay in your house forever')
    print('Move commands: go North, go South, go East, go West')
    print("Add to inventory: get 'item name'")
    print()
    answer = input('Would you like to play? (yes, no, exit)' ) #user input to begin the game or not
    while answer != 'exit':
        if answer.lower().strip() == 'yes':
            print("Great! Let's begin...")
            break
            game_play()

        elif answer.lower().strip() == 'no':
            print("That's alright, there's always next time")
            break
        elif answer.lower().strip() == 'exit': #exit ceases the game immediately
            print('Game over, thank you for playing!')
            break
        else:
            print(f'{answer} is an invalid input')
            show_game_instructions()
        break
show_game_instructions()

rooms = {
        'Hallway': {'North': 'Living Room', 'South': 'Bedroom_1', 'West': 'Dining Room', 'East':            'Kitchen', 'Item': 'Empty'},
        'Dining Room': {'East': 'Hallway', 'Item': 'Bread'}}

user_input = input('Would you like to go North, South, East, or West? ')
def game_play():
    while user_input != exit:
        if user_input in rooms.values():
            north = rooms[user_input]['Item']
            print(north)

        else:
            print('Thank you for playing')
            break


问:
When I installed maskrcnn-benhmark, the following error occurred when running python setup.py build develop compilation
When I installed maskrcnn-benhmark, the following error occurred when running python setup.py build develop compilation.pytorch==1.7.1,cuda=10.2,torchvision==0.8


问:
The Cost of Applying SSR on server - Laravel & Vue
I dont know is this a right place to ask this question, so i planned to make a blog website with SPA (Single Page Application) model using vuejs, we all know SPA websites are not SEO friendly and we need SSR or Prerendering to overcome this problem.

From some source on the internet i found out that apllying SSR to a Website make it consume more server resource and i need to upgrade my hosting plan if needed and it will affect to my website operating cost.

can you guys give me advice what should i do?

from your experience did ssr cost server resources that much?

should i make my website without javascript framework and using fully dynamic php page?


问:
Get timedelta for next row within group of another pandas column
I have two columns in a pandas dataframe ('df'): one with an ID I want to group the data by, and another with a timestamp. I want to create a new column that calculates the difference between the time in the current row and the time in the next row that contains the same "ID" value. The below code achieves this, but is horribly inefficient.

```<code>dfs = []

def get_delta(id):
    id_subset = [df['ID']==id]
    id_subset['delta'] = (id_subset['time']-id_subset['time'].shift()).fillna('NaT')
    dfs.append(id_subset)

[get_delta(i) for i in df['ID'].unique()]

final_df = pd.concat(dfs)
</code>```

What is a less computationally expensive way to do this?

Body:
I have two columns in a pandas dataframe ('df'): one with an ID I want to group the data by, and another with a timestamp. I want to create a new column that calculates the difference between the time in the current row and the time in the next row that contains the same "ID" value. The below code achieves this, but is horribly inefficient.

dfs = []

def get_delta(id):
    id_subset = [df['ID']==id]
    id_subset['delta'] = (id_subset['time']-id_subset['time'].shift()).fillna('NaT')
    dfs.append(id_subset)

[get_delta(i) for i in df['ID'].unique()]

final_df = pd.concat(dfs)

What is a less computationally expensive way to do this?


问:
UnitTest Pickle Python
I am using the UnitTest module to test the correct deserialization of a dictionary, however, the result gives me NONE and the test is falling.

The code I am using is the following:

```<code>import pickle
import unittest
a_dictionary = {"a": 1, "b": 2}
def serialize():
  file_to_write = open("a_dictionary.pickle","wb")

def serialize():
    file_to_write = open("a_dictionary.pickle", "wb")
    pickle.dump(a_dictionary,file_to_write)
    file_to_write.close()

def deserialize():
    file_to_read= open("a_dictionary.pickle","rb")
    dictionary_2 = pickle.load(file_to_read)
    print(dictionary_2)

class Tests(unittest.TestCase):
def test(self):
    self.assertEqual(deserialize(),{'a': 1, 'b': 2})

if __name__=='__main__':
    unittest.main()
</code>```

And the result I am getting is:

self.assertEqual(deserialize(),{'a': 1, 'b': 2})
AssertionError: None != {'a': 1, 'b': 2}

So I don't know in which way I can prove the deserialization function is doing its job properly.

Can you give me some advise?

Regards

Title: UnitTest Pickle Python

Body:
I am using the UnitTest module to test the correct deserialization of a dictionary, however, the result gives me NONE and the test is falling.

The code I am using is the following:

import pickle
import unittest
a_dictionary = {"a": 1, "b": 2}
def serialize():
  file_to_write = open("a_dictionary.pickle","wb")

def serialize():
    file_to_write = open("a_dictionary.pickle", "wb")
    pickle.dump(a_dictionary,file_to_write)
    file_to_write.close()

def deserialize():
    file_to_read= open("a_dictionary.pickle","rb")
    dictionary_2 = pickle.load(file_to_read)
    print(dictionary_2)

class Tests(unittest.TestCase):
def test(self):
    self.assertEqual(deserialize(),{'a': 1, 'b': 2})

if __name__=='__main__':
    unittest.main()

And the result I am getting is:

self.assertEqual(deserialize(),{'a': 1, 'b': 2})
AssertionError: None != {'a': 1, 'b': 2}

So I don't know in which way I can prove the deserialization function is doing its job properly.

Can you give me some advise?

Regards


问:
Poshmark API - pip install poshmarkapi is not working
When I do:

pip install poshmarkapi

I see below error:

```<code>ERROR: Could not find a version that satisfies the requirement poshmarkapi
ERROR: No matching distribution found for poshmarkapi
Note: you may need to restart the kernel to use updated packages.
</code>```

I tried installing the Poshmark API client for Python using the following command: pip install poshmarkapi.

Can you please let me know how I can resolve this ?

Many thanks
A.T

Body:
When I do:

pip install poshmarkapi

I see below error:

ERROR: Could not find a version that satisfies the requirement poshmarkapi
ERROR: No matching distribution found for poshmarkapi
Note: you may need to restart the kernel to use updated packages.

I tried installing the Poshmark API client for Python using the following command: pip install poshmarkapi.

Can you please let me know how I can resolve this ?

Many thanks
A.T


问:
how can i estimate the radii of an ellipse from point cloud?
I have a set of data points in a pandas data frame as shown in this image

lets assume that the shape is that of a room. My goal is to determine which point belongs to the body of the room itself (wall and roof) and which point corresponds to an object held inside it.
since i don't have the exact dimensions of the room, i want to determine a radius for the ellipse and compare every point with them like so: (x/rx)^2 + (y/ry)^2 <= 1 .
Can I estimate the major and minor radius of the outermost ellipse? how can I negate the impact of the few points that are outside the room itself? treating them as outliers didn't work since they're not that far from the other points.

i wrote this function but it's output is affected by the outer points.

```<code>def find_radi(df):
rx_points = df.loc[(df['y'] > -1) & (df['y'] < 1)]
ry_points = df.loc[(df['x'] > -1) & (df['x'] < 1)]
hist_rx = plt.hist(rx_points['x'])
hist_ry = plt.hist(ry_points['y'])
rx = (max(hist_rx[1]) + abs(min(hist_rx[1]))) /2
ry = (max(hist_ry[1]) + abs(min(hist_ry[1]))) /2
return rx, ry

</code>```

Body:
I have a set of data points in a pandas data frame as shown in this image

lets assume that the shape is that of a room. My goal is to determine which point belongs to the body of the room itself (wall and roof) and which point corresponds to an object held inside it.
since i don't have the exact dimensions of the room, i want to determine a radius for the ellipse and compare every point with them like so: (x/rx)^2 + (y/ry)^2 <= 1 .
Can I estimate the major and minor radius of the outermost ellipse? how can I negate the impact of the few points that are outside the room itself? treating them as outliers didn't work since they're not that far from the other points.

i wrote this function but it's output is affected by the outer points.

def find_radi(df):
rx_points = df.loc[(df['y'] > -1) & (df['y'] < 1)]
ry_points = df.loc[(df['x'] > -1) & (df['x'] < 1)]
hist_rx = plt.hist(rx_points['x'])
hist_ry = plt.hist(ry_points['y'])
rx = (max(hist_rx[1]) + abs(min(hist_rx[1]))) /2
ry = (max(hist_ry[1]) + abs(min(hist_ry[1]))) /2
return rx, ry