问:
Rails Ransack gem slider
I want to be able to performa range search with ransack. I was hoping I could do this with a slider that has two thumbs. I'm thinking that the _in predicate would be perfect for a situation like this. However, I cannot find an example on how to appropriately configure this. Here would be some example code:

CONTROLLER `users_controller.rb:

```<code>  def index
    @page_title = 'Users'
    @page_icon = 'store'

    @q = User.search(params[:search]).ransack(params[:q])

    @retailers = @q.result.order("#{sort_column} #{sort_direction}").paginate(page: params[:page], per_page: 20)
  end
</code>```

VIEW users/index.html.erb:

```<code><%= search_form_for @q, url: users_path, class: 'form' do |f| %>
  <div class="row">
    <div class="col-sm-3">
      <div class="form-group">
        <%= label_tag :search %>
        <%= text_field_tag :search, params[:search], class: "form-control" %>
      </div>
    </div>
    <div class="col-sm-3">
      <div class="form-group">
        <%= f.label :first_name_eq, "First Name" %>
        <%= f.select :first_name_eq, {include_blank: true}, {class: "chosen-select"} %>
      </div>
    </div>
    <div class="col-sm-3">
      <div class="form-group">
        <%= f.label :team_eq, "Team" %>
        <%= f.select :team_eq, Team.options_for_select, {include_blank: true}, {class: "chosen-select"} %>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-sm-3">
      <div class="form-group">
        <%= f.label :score_in, "Score Range" %>
        <%= f.search_field :score_in, {include_blank: true} %>
      </div>
    </div>
  </div>
  <div>
    <%= f.submit 'Apply Filters', class: 'btn btn-outline-dark btn-md' %>
    <%= link_to 'Reset Filters', users_path(q: {reset: true}), class: 'btn btn-outline-danger btn-md' %>
  </div>
<% end %>
</code>```

I guess where I'm lost is how to start or implement a slider w/ two thumbs that would appropriately pass the parameters when submitted. Or even if I just create a two thumbed slider from a js library, how to connect it then to ransack, or at least pass the values of the two thumbs to ransacks params. Another thing that might be helpful is if someone has an example, both in controller/view, of what the _in predicate should look like.

Title: Rails Ransack gem slider

Body:
I want to be able to performa range search with ransack. I was hoping I could do this with a slider that has two thumbs. I'm thinking that the _in predicate would be perfect for a situation like this. However, I cannot find an example on how to appropriately configure this. Here would be some example code:

CONTROLLER `users_controller.rb:

  def index
    @page_title = 'Users'
    @page_icon = 'store'

    @q = User.search(params[:search]).ransack(params[:q])

    @retailers = @q.result.order("#{sort_column} #{sort_direction}").paginate(page: params[:page], per_page: 20)
  end

VIEW users/index.html.erb:

<%= search_form_for @q, url: users_path, class: 'form' do |f| %>

        <%= label_tag :search %>
        <%= text_field_tag :search, params[:search], class: "form-control" %>

        <%= f.label :first_name_eq, "First Name" %>
        <%= f.select :first_name_eq, {include_blank: true}, {class: "chosen-select"} %>

        <%= f.label :team_eq, "Team" %>
        <%= f.select :team_eq, Team.options_for_select, {include_blank: true}, {class: "chosen-select"} %>

        <%= f.label :score_in, "Score Range" %>
        <%= f.search_field :score_in, {include_blank: true} %>

    <%= f.submit 'Apply Filters', class: 'btn btn-outline-dark btn-md' %>
    <%= link_to 'Reset Filters', users_path(q: {reset: true}), class: 'btn btn-outline-danger btn-md' %>

<% end %>

I guess where I'm lost is how to start or implement a slider w/ two thumbs that would appropriately pass the parameters when submitted. Or even if I just create a two thumbed slider from a js library, how to connect it then to ransack, or at least pass the values of the two thumbs to ransacks params. Another thing that might be helpful is if someone has an example, both in controller/view, of what the _in predicate should look like.


来源: stackexchange

问:
React mapping error when refreshing the page after the first load
I am trying to calculate the total price from two different array props. I am using map to render the portfolio array and using the id from it to locate the price from the stock array using findIndex and multiplying it to the quantity located in the portfolio array.

I am able to render the results for the first time. However, when I hit refresh I'm hit with a mapping error. I have an idea to what is causing this error but not sure how to resolve it.

```<code>profile array = {
name,
portfolio {
   stockId (ref Stocks.id),
   stockName,
   quantity
   }
}

stocks array = {
id,
stockName,
stockPrice
}
</code>```
```<code>import React from "react";

const MyPortfolio= ({profile, stocks}) => {

    const findIndex = (id) => {
        const index = stocks.findIndex(index => index._id === id)
        return stocks[index].stockPrice;
    }
    // console.log(profile)

return (
    <section>
        <h3>{profile.username}</h3>
        <p>{profile.money}</p>
        <p>Portfolio</p>
            <ul>
                {profile.portfolio ? profile.portfolio.map((ownedStock) => (
                    <li key={ownedStock.stockId}>
                    {ownedStock.stockName} <br/>
                    {ownedStock.quantity} <br/>
                    Current Worth: {parseInt(ownedStock.quantity) * parseInt(findIndex(ownedStock.stockId}
                    </li>
                )): null}
            </ul>
    </section>
)
}

export default MyPortfolio;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to calculate the total price from two different array props. I am using map to render the portfolio array and using the id from it to locate the price from the stock array using findIndex and multiplying it to the quantity located in the portfolio array.

I am able to render the results for the first time. However, when I hit refresh I'm hit with a mapping error. I have an idea to what is causing this error but not sure how to resolve it.

profile array = {
name,
portfolio {
   stockId (ref Stocks.id),
   stockName,
   quantity
   }
}

stocks array = {
id,
stockName,
stockPrice
}

import React from "react";

const MyPortfolio= ({profile, stocks}) => {

    const findIndex = (id) => {
        const index = stocks.findIndex(index => index._id === id)
        return stocks[index].stockPrice;
    }
    // console.log(profile)

return (

{profile.username}

{profile.money}

Portfolio

                {profile.portfolio ? profile.portfolio.map((ownedStock) => (

                    {ownedStock.stockName}

                    {ownedStock.quantity}

                    Current Worth: {parseInt(ownedStock.quantity) * parseInt(findIndex(ownedStock.stockId}

                )): null}

)
}

export default MyPortfolio;


问:
devtools error in R: Could not find a root 'DESCRIPTION' file that starts with '^Package'
I'm using an M1 mac and attempting to install the package TESS3_encho_sen into R from github using the command devtools::install_github("bcm-uga/TESS3_encho_sen")

Upon doing so I receive the following error:

```<code>Error: Could not find tools necessary to compile a package
Call `pkgbuild::check_build_tools(debug = TRUE)` to diagnose the problem.
</code>```

And calling pkgbuild::check_build_tools(debug = TRUE) is redundant and gives the same error as above. However, calling devtools::load_all() generates the following:

```<code>Error in `value[[3L]]()`:
! Could not find a root 'DESCRIPTION' file that starts with '^Package' in
  ~/path/to/file.
Are you in your project directory and does your project have a 'DESCRIPTION' file?
</code>```

I found one potential workaround here HERE that suggested the errors were related to C/C++ library headers, but this solution did not work for me. Suppressing RStudio's build tools check as suggested HERE also did not work. Any help with this issue is appreciated!

Edit: I am now receiving the following error when running pkgbuild::check_build_tools(debug=TRUE):

```<code>Running /Library/Frameworks/R.framework/Resources/bin/R CMD SHLIB foo.c
/usr/local/clang4/bin/clang -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I/opt/R/arm64/include   -fPIC  -falign-functions=64 -Wall -g -O2  -c foo.c -o foo.o
warning: optimization flag '-falign-functions=64' is not supported [-Wignored-optimization-argument]
/usr/local/clang4/bin/clang -dynamiclib -Wl,-headerpad_max_install_names -undefined dynamic_lookup -single_module -multiply_defined suppress -L/Library/Frameworks/R.framework/Resources/lib -L/usr/local/opt/llvm/lib -Wl,-rpath,/usr/local/opt/llvm/lib -L/usr/local/clang4/lib -o foo.so foo.o -F/Library/Frameworks/R.framework/.. -framework R -Wl,-framework -Wl,CoreFoundation
ld: framework not found CoreFoundation
clang-4.0: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [foo.so] Error 1
</code>```

Body:
I'm using an M1 mac and attempting to install the package TESS3_encho_sen into R from github using the command devtools::install_github("bcm-uga/TESS3_encho_sen")

Upon doing so I receive the following error:

Error: Could not find tools necessary to compile a package
Call `pkgbuild::check_build_tools(debug = TRUE)` to diagnose the problem.

And calling pkgbuild::check_build_tools(debug = TRUE) is redundant and gives the same error as above. However, calling devtools::load_all() generates the following:

Error in `value[[3L]]()`:
! Could not find a root 'DESCRIPTION' file that starts with '^Package' in
  ~/path/to/file.
Are you in your project directory and does your project have a 'DESCRIPTION' file?

I found one potential workaround here HERE that suggested the errors were related to C/C++ library headers, but this solution did not work for me. Suppressing RStudio's build tools check as suggested HERE also did not work. Any help with this issue is appreciated!

Edit: I am now receiving the following error when running pkgbuild::check_build_tools(debug=TRUE):

Running /Library/Frameworks/R.framework/Resources/bin/R CMD SHLIB foo.c
/usr/local/clang4/bin/clang -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I/opt/R/arm64/include   -fPIC  -falign-functions=64 -Wall -g -O2  -c foo.c -o foo.o
warning: optimization flag '-falign-functions=64' is not supported [-Wignored-optimization-argument]
/usr/local/clang4/bin/clang -dynamiclib -Wl,-headerpad_max_install_names -undefined dynamic_lookup -single_module -multiply_defined suppress -L/Library/Frameworks/R.framework/Resources/lib -L/usr/local/opt/llvm/lib -Wl,-rpath,/usr/local/opt/llvm/lib -L/usr/local/clang4/lib -o foo.so foo.o -F/Library/Frameworks/R.framework/.. -framework R -Wl,-framework -Wl,CoreFoundation
ld: framework not found CoreFoundation
clang-4.0: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [foo.so] Error 1


问:
How to set up dataset and train whisper model from OpenAI with custom dataset
I have a dataset, audios in wav format and transcripctions on excel file, how could i create a dataset to train whisper with my own data, most of the docs connect to hugging face cloud and call mozilla dataset with a magic method</p>


问:
Reading .evtx event files to pandas data frame
I'm trying to read the data from .evtx file which are about the status of task scheduler task. To get the data I used function called get_events() from here Link.

After that I've done some simple cleanup:

```<code>raw_xml = []
for event_xml in enumerate(get_events(r'C:\Windows\System32\winevt\Logs\Microsoft-Windows-TaskScheduler%4Maintenance.evtx')):
    raw_xml.append((event_xml)
</code>```

The output is like that:

```<code>[(0,'Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"<>System<>Provider Name="Microsoft-Windows-TaskScheduler Guid"{de7b24ea-73c8}"<>/Provider>\n<EventID Qualifiers="">800</EventID>\n<Version>0</Version>\n'),(1,etc.)]
</code>```

I've wanted to get this into the data frame but I can not parse through these rows, I do not know what kind of regex is use for that.

```<code>import pandas as pd
newlist = []
for i in [*raw_xml]:
    newlist.append(i[1])
df = pd.DataFrame([*newlist]
</code>```

The path to the evtx files should be the same for every windows user. Appreciate some guidance.

Body:
I'm trying to read the data from .evtx file which are about the status of task scheduler task. To get the data I used function called get_events() from here Link.

After that I've done some simple cleanup:

raw_xml = []
for event_xml in enumerate(get_events(r'C:\Windows\System32\winevt\Logs\Microsoft-Windows-TaskScheduler%4Maintenance.evtx')):
    raw_xml.append((event_xml)

The output is like that:

[(0,'Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"<>System<>Provider Name="Microsoft-Windows-TaskScheduler Guid"{de7b24ea-73c8}"<>/Provider>\n<EventID Qualifiers="">800</EventID>\n<Version>0</Version>\n'),(1,etc.)]

I've wanted to get this into the data frame but I can not parse through these rows, I do not know what kind of regex is use for that.

import pandas as pd
newlist = []
for i in [*raw_xml]:
    newlist.append(i[1])
df = pd.DataFrame([*newlist]

The path to the evtx files should be the same for every windows user. Appreciate some guidance.


问:
String literal in IntelliJ PSI as an antoation parameter
I'm trying to make an inspection in IntelliJ Platform for Java that suggests substituting a text pattern for string literals (for training purposes). But the inspection should not work if the literal is an annotation parameter. How can I use PSI to define that a literal is an annotation parameter?

I use the visitLiteralExpression

```<code>public void visitLiteralExpression(PsiLiteralExpression expression) {

    visitExpression(expression);
    PsiType type = expression.getType();
    PsiElement parent = expression.getParent();

    // What should be the correct condition?
    boolean condition = ...;

    if ((condition) && (type.equalsToText("java.lang.String")) {
        holder.registerProblem(expression, DESCRIPTION_TEMPLATE, myQuickFix);
    }
}
</code>```

I tried checking if the parent PsiElement is an instance of PsiAnnotationParameterList or PsiAnnotation, like this

```<code>expression.getParent() instanceof PsiAnnotationParameterList
</code>```

Body:
I'm trying to make an inspection in IntelliJ Platform for Java that suggests substituting a text pattern for string literals (for training purposes). But the inspection should not work if the literal is an annotation parameter. How can I use PSI to define that a literal is an annotation parameter?

I use the visitLiteralExpression

public void visitLiteralExpression(PsiLiteralExpression expression) {

    visitExpression(expression);
    PsiType type = expression.getType();
    PsiElement parent = expression.getParent();

    // What should be the correct condition?
    boolean condition = ...;

    if ((condition) && (type.equalsToText("java.lang.String")) {
        holder.registerProblem(expression, DESCRIPTION_TEMPLATE, myQuickFix);
    }
}

I tried checking if the parent PsiElement is an instance of PsiAnnotationParameterList or PsiAnnotation, like this

expression.getParent() instanceof PsiAnnotationParameterList


问:
How to generate a cognito user pool with standard attributes through serverless
I want to be able to generate a cognito userl pool with standard attributes through serverless

Standard attributes from cognito user pool

As you can see I have defined the following schema:

```<code>            Schema:
                 - Name: uuid
                  AttributeDataType: String
                  Mutable: true
                - Name: name
                  AttributeDataType: String
                  Mutable: true`
</code>```

But it is not working.

```<code>`Resources:
    QuizCardsUserPool:
        Type: AWS::Cognito::UserPool
        Properties:
            AccountRecoverySetting:
                RecoveryMechanisms:
                    - Name: 'verified_email'
                      Priority: 1
            # AdminCreateUserConfig:
            #   InviteMessageTemplate:
            #     EmailMessage: 'Your username is {username} and temporary password is {####}.'
            AutoVerifiedAttributes:
                - 'email'
            # EmailVerificationMessage: 'email message: {####}'
            # EmailVerificationSubject: 'email subject: {####}'
            UsernameAttributes:
                - 'email'
            UsernameConfiguration:
                CaseSensitive: false
            UserPoolName: ${sls:stage}-quizcards
            Policies:
                PasswordPolicy:
                    MinimumLength: 8
                    RequireLowercase: false
                    RequireNumbers: false
                    RequireSymbols: false
                    RequireUppercase: false
                    TemporaryPasswordValidityDays: 1
            Schema:
                - Name: uuid
                  AttributeDataType: String
                  Mutable: true
                - Name: name
                  AttributeDataType: String
                  Mutable: true

    # Creates a User Pool Client to be used by the identity pool
    QuizCardsUserPoolClient:
        Type: AWS::Cognito::UserPoolClient
        Properties:
            ClientName: quizcards-client
            GenerateSecret: false
            UserPoolId: !Ref QuizCardsUserPool
            ReadAttributes:
                - "name"
                - "email"
                - "profile"
                - "preferred_username"
            WriteAttributes:
                - "name"
                - "email"
                - "profile"
                - "preferred_username"

    # Creates a federated Identity pool
    QuizCardsIdentityPool:
        Type: AWS::Cognito::IdentityPool
        Properties:
            AllowClassicFlow: true
            IdentityPoolName: ${sls:stage}-quizcards
            AllowUnauthenticatedIdentities: false
            CognitoIdentityProviders:
                - ClientId: !Ref QuizCardsUserPoolClient
                  ProviderName: !GetAtt QuizCardsUserPool.ProviderName

    # Create a role for unauthorized access to AWS resources. Very limited access. Only allows users in the previously created Identity Pool
    CognitoUnAuthorizedRole:
        Type: 'AWS::IAM::Role'
        Properties:
            AssumeRolePolicyDocument:
                Version: '2012-10-17'
                Statement:
                    - Effect: 'Allow'
                      Principal:
                          Federated: 'cognito-identity.amazonaws.com'
                      Action:
                          - 'sts:AssumeRoleWithWebIdentity'
                      Condition:
                          StringEquals:
                              'cognito-identity.amazonaws.com:aud': !Ref QuizCardsIdentityPool
                          'ForAnyValue:StringLike':
                              'cognito-identity.amazonaws.com:amr': unauthenticated
            Policies:
                - PolicyName: 'CognitoUnauthorizedPolicy'
                  PolicyDocument:
                      Version: '2012-10-17'
                      Statement:
                          - Effect: 'Allow'
                            Action:
                                - 'mobileanalytics:PutEvents'
                                - 'cognito-sync:*'
                            Resource: '*'

    # Create a role for authorized access to AWS resources. Control what your user can access. This example only allows Lambda invocation
    # Only allows users in the previously created Identity Pool
    CognitoAuthorizedRole:
        Type: 'AWS::IAM::Role'
        Properties:
            AssumeRolePolicyDocument:
                Version: '2012-10-17'
                Statement:
                    - Effect: 'Allow'
                      Principal:
                          Federated: 'cognito-identity.amazonaws.com'
                      Action:
                          - 'sts:AssumeRoleWithWebIdentity'
                      Condition:
                          StringEquals:
                              'cognito-identity.amazonaws.com:aud': !Ref QuizCardsIdentityPool
                          'ForAnyValue:StringLike':
                              'cognito-identity.amazonaws.com:amr': authenticated
            Policies:
                - PolicyName: 'CognitoAuthorizedPolicy'
                  PolicyDocument:
                      Version: '2012-10-17'
                      Statement:
                          - Effect: 'Allow'
                            Action:
                                - 'mobileanalytics:PutEvents'
                                - 'cognito-sync:*'
                                - 'cognito-identity:*'
                            Resource: '*'
                          - Effect: 'Allow'
                            Action:
                                - 'lambda:InvokeFunction'
                            Resource: '*'
                          # - Effect: "Allow"
                          #   Action:
                          #     - "s3:ListBucket"
                          #     - "s3:GetObject"
                          #     - "s3:PutObject"
                          #     - "s3:DeleteObject"
                          #   Resource:
                          #     - "arn:aws:s3:::husjournalen-property-docs/*"

    # Assigns the roles to the Identity Pool
    QuizCardsIdentityPoolRoleAttachment:
        Type: AWS::Cognito::IdentityPoolRoleAttachment
        Properties:
            IdentityPoolId: !Ref QuizCardsIdentityPool
            Roles:
                authenticated: !GetAtt CognitoAuthorizedRole.Arn
                unauthenticated: !GetAtt CognitoUnAuthorizedRole.Arn

Outputs:
    UserPoolId:
        Value: !Ref QuizCardsUserPool
        Export:
            Name: 'UserPool::Id'
    UserPoolClientId:
        Value: !Ref QuizCardsUserPoolClient
        Export:
            Name: 'UserPoolClient::Id'
    IdentityPoolId:
        Value: !Ref QuizCardsIdentityPool
        Export:
            Name: 'IdentityPool::Id'
</code>```

I have tried to find some information regarding these attributes.

As you can see in this link from AWS documentation

```<code>Schema
An array of schema attributes for the new user pool. These attributes can be standard or custom attributes.
Type: Array of SchemaAttributeType objects
Array Members: Minimum number of 1 item. Maximum number of 50 items.
Required: No
</code>```

I don´t know what else could I be missing here

Body:
I want to be able to generate a cognito userl pool with standard attributes through serverless

Standard attributes from cognito user pool

As you can see I have defined the following schema:

            Schema:
                 - Name: uuid
                  AttributeDataType: String
                  Mutable: true
                - Name: name
                  AttributeDataType: String
                  Mutable: true`

But it is not working.

`Resources:
    QuizCardsUserPool:
        Type: AWS::Cognito::UserPool
        Properties:
            AccountRecoverySetting:
                RecoveryMechanisms:
                    - Name: 'verified_email'
                      Priority: 1
            # AdminCreateUserConfig:
            #   InviteMessageTemplate:
            #     EmailMessage: 'Your username is {username} and temporary password is {####}.'
            AutoVerifiedAttributes:
                - 'email'
            # EmailVerificationMessage: 'email message: {####}'
            # EmailVerificationSubject: 'email subject: {####}'
            UsernameAttributes:
                - 'email'
            UsernameConfiguration:
                CaseSensitive: false
            UserPoolName: ${sls:stage}-quizcards
            Policies:
                PasswordPolicy:
                    MinimumLength: 8
                    RequireLowercase: false
                    RequireNumbers: false
                    RequireSymbols: false
                    RequireUppercase: false
                    TemporaryPasswordValidityDays: 1
            Schema:
                - Name: uuid
                  AttributeDataType: String
                  Mutable: true
                - Name: name
                  AttributeDataType: String
                  Mutable: true

    # Creates a User Pool Client to be used by the identity pool
    QuizCardsUserPoolClient:
        Type: AWS::Cognito::UserPoolClient
        Properties:
            ClientName: quizcards-client
            GenerateSecret: false
            UserPoolId: !Ref QuizCardsUserPool
            ReadAttributes:
                - "name"
                - "email"
                - "profile"
                - "preferred_username"
            WriteAttributes:
                - "name"
                - "email"
                - "profile"
                - "preferred_username"

    # Creates a federated Identity pool
    QuizCardsIdentityPool:
        Type: AWS::Cognito::IdentityPool
        Properties:
            AllowClassicFlow: true
            IdentityPoolName: ${sls:stage}-quizcards
            AllowUnauthenticatedIdentities: false
            CognitoIdentityProviders:
                - ClientId: !Ref QuizCardsUserPoolClient
                  ProviderName: !GetAtt QuizCardsUserPool.ProviderName

    # Create a role for unauthorized access to AWS resources. Very limited access. Only allows users in the previously created Identity Pool
    CognitoUnAuthorizedRole:
        Type: 'AWS::IAM::Role'
        Properties:
            AssumeRolePolicyDocument:
                Version: '2012-10-17'
                Statement:
                    - Effect: 'Allow'
                      Principal:
                          Federated: 'cognito-identity.amazonaws.com'
                      Action:
                          - 'sts:AssumeRoleWithWebIdentity'
                      Condition:
                          StringEquals:
                              'cognito-identity.amazonaws.com:aud': !Ref QuizCardsIdentityPool
                          'ForAnyValue:StringLike':
                              'cognito-identity.amazonaws.com:amr': unauthenticated
            Policies:
                - PolicyName: 'CognitoUnauthorizedPolicy'
                  PolicyDocument:
                      Version: '2012-10-17'
                      Statement:
                          - Effect: 'Allow'
                            Action:
                                - 'mobileanalytics:PutEvents'
                                - 'cognito-sync:*'
                            Resource: '*'

    # Create a role for authorized access to AWS resources. Control what your user can access. This example only allows Lambda invocation
    # Only allows users in the previously created Identity Pool
    CognitoAuthorizedRole:
        Type: 'AWS::IAM::Role'
        Properties:
            AssumeRolePolicyDocument:
                Version: '2012-10-17'
                Statement:
                    - Effect: 'Allow'
                      Principal:
                          Federated: 'cognito-identity.amazonaws.com'
                      Action:
                          - 'sts:AssumeRoleWithWebIdentity'
                      Condition:
                          StringEquals:
                              'cognito-identity.amazonaws.com:aud': !Ref QuizCardsIdentityPool
                          'ForAnyValue:StringLike':
                              'cognito-identity.amazonaws.com:amr': authenticated
            Policies:
                - PolicyName: 'CognitoAuthorizedPolicy'
                  PolicyDocument:
                      Version: '2012-10-17'
                      Statement:
                          - Effect: 'Allow'
                            Action:
                                - 'mobileanalytics:PutEvents'
                                - 'cognito-sync:*'
                                - 'cognito-identity:*'
                            Resource: '*'
                          - Effect: 'Allow'
                            Action:
                                - 'lambda:InvokeFunction'
                            Resource: '*'
                          # - Effect: "Allow"
                          #   Action:
                          #     - "s3:ListBucket"
                          #     - "s3:GetObject"
                          #     - "s3:PutObject"
                          #     - "s3:DeleteObject"
                          #   Resource:
                          #     - "arn:aws:s3:::husjournalen-property-docs/*"

    # Assigns the roles to the Identity Pool
    QuizCardsIdentityPoolRoleAttachment:
        Type: AWS::Cognito::IdentityPoolRoleAttachment
        Properties:
            IdentityPoolId: !Ref QuizCardsIdentityPool
            Roles:
                authenticated: !GetAtt CognitoAuthorizedRole.Arn
                unauthenticated: !GetAtt CognitoUnAuthorizedRole.Arn

Outputs:
    UserPoolId:
        Value: !Ref QuizCardsUserPool
        Export:
            Name: 'UserPool::Id'
    UserPoolClientId:
        Value: !Ref QuizCardsUserPoolClient
        Export:
            Name: 'UserPoolClient::Id'
    IdentityPoolId:
        Value: !Ref QuizCardsIdentityPool
        Export:
            Name: 'IdentityPool::Id'

I have tried to find some information regarding these attributes.

As you can see in this link from AWS documentation

Schema
An array of schema attributes for the new user pool. These attributes can be standard or custom attributes.
Type: Array of SchemaAttributeType objects
Array Members: Minimum number of 1 item. Maximum number of 50 items.
Required: No

I don´t know what else could I be missing here


问:
Turn Javascript localStorage countdown timer into an animated Progress Bar
I was searching for a sitewide javascript timer, which does not reset when a page is changed, and I have stumbled onto this one, along with its demo.

This could be a stupid question, but I was wondering if this "minutes : seconds" timer format could be turned into an animated progress bar type of countdown, meaning that as the time passes, the bar should get smaller.

Here is the code I am currently using:

```<code><div id="time"></div>
<script>
    function startTimer(duration, display) {
        var timer = duration, minutes, seconds;
        setInterval(function () {
            minutes = parseInt(timer / 60, 10)
            seconds = parseInt(timer % 60, 10);
            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;
            display.textContent = minutes + " " + " " + seconds;
            if (--timer < 0) {
                timer = duration;
            }
            console.log(parseInt(seconds))
            window.localStorage.setItem("seconds",seconds)
            window.localStorage.setItem("minutes",minutes)
        }, 1000);
    }
    window.onload = function () {
        sec  = parseInt(window.localStorage.getItem("seconds"))
        min = parseInt(window.localStorage.getItem("minutes"))
        if (parseInt(min*sec)) {
            var fiveMinutes = (parseInt(min*60)+sec);
        } else{
            var fiveMinutes = 60 * 45;
        }
        display = document.querySelector('#time');
        startTimer(fiveMinutes, display);
    };
</script>
</code>```

Any ideas?

Body:
I was searching for a sitewide javascript timer, which does not reset when a page is changed, and I have stumbled onto this one, along with its demo.

This could be a stupid question, but I was wondering if this "minutes : seconds" timer format could be turned into an animated progress bar type of countdown, meaning that as the time passes, the bar should get smaller.

Here is the code I am currently using:

Any ideas?


问:
Regex for URL filtering
I have a URL which needs to be filtered from a certain logs if it has user-specific information.

URL looks something like this:
/v1/info/infor1/users/ABC
(/v1/info/:info/users/:userID #info and userID are parameters)

If I write a regex like /v1/info/.*/users/.*, will it filter all URLs starting with /v1/info? If yes, how do I make sure the filtering happens only based on the URL containing the userUID?

Tried /v1/info/.*/users/.* and it matches URLs like /v1/info/infor1/users/ABC and not /v1/info/details and I am not sure how it works. Does .* not compare everything from that point?

Title: Regex for URL filtering


问:
Using ts-morph to transform files to handle package upgrades
I want to use ts-morph to transform files in my TS project due to upgrading some packages with breaking changes. There are basically 3 changes I need to make:

Change import statements from import { ... } from 'foo-bar'; to import { ... } from '@foo/bar';.

Change some calling patterns, e.g., transform Object.assign(new Foo(), ifoo) to new Foo(ifoo).

Change enum member names because casing changed for some of the enum members from lowercase to uppercase, e.g., transform Baz.buzz to Baz.Buzz.

I have solved problems 1 and 2 so far. I iterate through source files in my Project, make the changes, then save the source files. For problem 1, I was able to use the sourceFile.getImportDeclarations to solve the problem easily. For problem 2, I couldn't figure out how to solve the problem without using TypeScript transforms, which unfortunately throws out a lot of the ts-morph goodness, but still works.

I'm not sure how to solve problem 3. Blindly capitalizing the enum member names is easy enough, but I want to change the names according to whether they should be capitalized or not. I was thinking I would create a new ts-morph Project that has all the source files in the new packages. Then I could look up enums by name and see if the casing is correct for enum members in my TS project source files, updating them as needed. However, I'm having trouble getting all enums in the new packages. I create the Project by creating an index.ts file that imports all the packages, e.g.,

```<code>import * from '@foo/bar';
import * from '@foo/baz';
...
</code>```

However, I'm unable to find a way to iterate through all the SourceFiles in those package dependencies. I see the SourceFiles clearly in project.getProgram().compilerNode.getSourceFiles(), but I do not see them via project.getSourceFiles() or project.resolveSourceFileDependencies() (regardless of whether I put skipFileDependencyResolution: true in the Project config or not).

Any ideas how I might solve problem 3? Any potential ideas for not using TS transforms for problem 2? Thanks!

Body:
I want to use ts-morph to transform files in my TS project due to upgrading some packages with breaking changes. There are basically 3 changes I need to make:

Change import statements from import { ... } from 'foo-bar'; to import { ... } from '@foo/bar';.

Change some calling patterns, e.g., transform Object.assign(new Foo(), ifoo) to new Foo(ifoo).

Change enum member names because casing changed for some of the enum members from lowercase to uppercase, e.g., transform Baz.buzz to Baz.Buzz.

I have solved problems 1 and 2 so far. I iterate through source files in my Project, make the changes, then save the source files. For problem 1, I was able to use the sourceFile.getImportDeclarations to solve the problem easily. For problem 2, I couldn't figure out how to solve the problem without using TypeScript transforms, which unfortunately throws out a lot of the ts-morph goodness, but still works.

I'm not sure how to solve problem 3. Blindly capitalizing the enum member names is easy enough, but I want to change the names according to whether they should be capitalized or not. I was thinking I would create a new ts-morph Project that has all the source files in the new packages. Then I could look up enums by name and see if the casing is correct for enum members in my TS project source files, updating them as needed. However, I'm having trouble getting all enums in the new packages. I create the Project by creating an index.ts file that imports all the packages, e.g.,

import * from '@foo/bar';
import * from '@foo/baz';
...

However, I'm unable to find a way to iterate through all the SourceFiles in those package dependencies. I see the SourceFiles clearly in project.getProgram().compilerNode.getSourceFiles(), but I do not see them via project.getSourceFiles() or project.resolveSourceFileDependencies() (regardless of whether I put skipFileDependencyResolution: true in the Project config or not).

Any ideas how I might solve problem 3? Any potential ideas for not using TS transforms for problem 2? Thanks!


问:
Looking for free or paid FSA polygons of Canada for project. Statscan data is free but number of FSA is too low
I downloaded data showing polygons from statscan with 1643 fsa polygons (the first 3 letters of a postal code).
TWO datasets meant to be combined, hope this is clear.

DATA1 -provided to me as descriptors for specific FSA's

FSA
DATA PROVIDED

FSA1
text1

...
text ...

FSA667
text 1667

--------
--------

DATA2  - downloaded from statscan as .shp file

FSA
Polygon coords

FSA1
Cell 2

FSA1643
Cell 4

I am combining the polygons with another dataset to show layover data for each fsa. The problem is I was provided with data showing 1667 FSA's and I'm asked to produce a map that reflects their dataset (1667 items of layover information) when combined with an equal and matching number of polygons.

Effectively there are 1667-1643 = 24 missing FSA's as polygons.

Does anyone know a good source for FSA only? Other than stats canada I can't seem to find what I need. Paid and free.... I need to see what's out there and available.
Link to statscan https://www12.statcan.gc.ca/census-recensement/2021/geo/sip-pis/boundary-limites/index2021-eng.cfm?year=21

I am using leaflet.js to show the data but this is really a question about the datasets themselves. In summary I seek 1667 polygons represending canadian FSA's (forward sorting areas) and only can find 1643.
Thanks

I can successfully view and import the data I am using qgis, the issue is the data itself. I seek 1667 polygon coordinates not the 1643 I can only find online. Hopefully free... maybe paid.


问:
How to add dynamically data in form through ajax in javascript or jquery?
I got data from db through an ajax call and tried to add it in forms's input tags.
When I add data in the form dynamically through Ajax, the webpage gets stuck and a black layer is coming on the webpage, and I can't do anything.

$.ajax({
  url: url,
  method: "post",
  data: mydata,
  dataType: "json",
  success: function(data) {
    if (data.status == 1) {
      let is_free = data.value['is_free'];
      console.log(typeof data.value['is_free']);

      document.getElementById("id_Lecture_Title").value = (data.value['title']);
      document.getElementById("lec_desc").value = (data.value['desc']);
      document.getElementById("free_preview_lec").checked = true;

      $("#add_lecture_model").modal("show");
    }
  },
  error: function(data) {
    alert("Something went wrong");
  }
});
```

Image Error

Body:
I got data from db through an ajax call and tried to add it in forms's input tags.
When I add data in the form dynamically through Ajax, the webpage gets stuck and a black layer is coming on the webpage, and I can't do anything.

$.ajax({
  url: url,
  method: "post",
  data: mydata,
  dataType: "json",
  success: function(data) {
    if (data.status == 1) {
      let is_free = data.value['is_free'];
      console.log(typeof data.value['is_free']);

      document.getElementById("id_Lecture_Title").value = (data.value['title']);
      document.getElementById("lec_desc").value = (data.value['desc']);
      document.getElementById("free_preview_lec").checked = true;

      $("#add_lecture_model").modal("show");
    }
  },
  error: function(data) {
    alert("Something went wrong");
  }
});

Image Error


问:
Convert nested dictionary to object. Support recursively displaying all values of key
Here is a dictionary I have as input

```<code>user_vars = {
  "verbose": true,
  "testing": false,
  "login": {
    "username": "theadmin",
    "password": "password123"
  },
  "interfaces": {
    "trust": {
      "ip": "10.8.10.1/30"
    },
    "untrust": {
      "ip": "10.9.10.1/30"
    }
  }
}
</code>```

I found this article on how to create an object from a class:
https://bobbyhadz.com/blog/python-convert-nested-dictionary-to-object#:~:text=To%20convert%20a%20nested%20dictionary,the%20key%20to%20the%20value.

So I did this:

```<code>class payloadGen:
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            if isinstance(value, dict):
                self.__dict__[key] = payloadGen(**value)
            else:
                self.__dict__[key] = value
</code>```

So when I call it I am able to do the following just fine:

```<code>customer = payloadGen(**user_vars)
print(customer.interfaces.trust.ip)
print(customer.verbose)

#output
10.8.10.1/30
True
</code>```

But when I try to print a parent of nested values, I get the object memory address:

```<code>print(customer.interfaces)
#output
<payloadgen.payloadGen object at 0x7fbe8cedd7f0>
</code>```

This is expected. What I want to be able to do is print all child keys and values recursively:

```<code>print(customer.interfaces)
#wanted output
"trust": {"ip": "10.8.10.1/30"},"untrust": {"ip": "10.9.10.1/30"}
</code>```

I realize this maybe a complicated affair. I am new to class's, constructors, inherence, and objects. So if need to do some more reading on how to accomplish this please point me in the right direction.

EDIT:
Thanks to @Axe319. I needed to just adjust the class to add a representor call, and use a lambda function.

```<code>class payloadGen:
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            if isinstance(value, dict):
                self.__dict__[key] = payloadGen(**value)
            else:
                self.__dict__[key] = value

    __repr__ = lambda self: repr(self.__dict__)
</code>```

Now I can call individual parent entries and all child parent/children display

```<code>customer = payloadGen(**user_vars)
print(customer.interfaces.trust.ip)
print(customer.interfaces)
#output
10.8.10.1/30
{interfaces": {"trust": {"ip": "10.8.10.1/30"},"untrust": {"ip": "10.9.10.1/30"}}}
</code>```

Body:
Here is a dictionary I have as input

user_vars = {
  "verbose": true,
  "testing": false,
  "login": {
    "username": "theadmin",
    "password": "password123"
  },
  "interfaces": {
    "trust": {
      "ip": "10.8.10.1/30"
    },
    "untrust": {
      "ip": "10.9.10.1/30"
    }
  }
}

I found this article on how to create an object from a class:
https://bobbyhadz.com/blog/python-convert-nested-dictionary-to-object#:~:text=To%20convert%20a%20nested%20dictionary,the%20key%20to%20the%20value.

So I did this:

class payloadGen:
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            if isinstance(value, dict):
                self.__dict__[key] = payloadGen(**value)
            else:
                self.__dict__[key] = value

So when I call it I am able to do the following just fine:

customer = payloadGen(**user_vars)
print(customer.interfaces.trust.ip)
print(customer.verbose)

#output
10.8.10.1/30
True

But when I try to print a parent of nested values, I get the object memory address:

print(customer.interfaces)
#output
<payloadgen.payloadGen object at 0x7fbe8cedd7f0>

This is expected. What I want to be able to do is print all child keys and values recursively:

print(customer.interfaces)
#wanted output
"trust": {"ip": "10.8.10.1/30"},"untrust": {"ip": "10.9.10.1/30"}

I realize this maybe a complicated affair. I am new to class's, constructors, inherence, and objects. So if need to do some more reading on how to accomplish this please point me in the right direction.

EDIT:
Thanks to @Axe319. I needed to just adjust the class to add a representor call, and use a lambda function.

class payloadGen:
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            if isinstance(value, dict):
                self.__dict__[key] = payloadGen(**value)
            else:
                self.__dict__[key] = value

    __repr__ = lambda self: repr(self.__dict__)

Now I can call individual parent entries and all child parent/children display

customer = payloadGen(**user_vars)
print(customer.interfaces.trust.ip)
print(customer.interfaces)
#output
10.8.10.1/30
{interfaces": {"trust": {"ip": "10.8.10.1/30"},"untrust": {"ip": "10.9.10.1/30"}}}


问:
JavaScript Show/Hide HTML Elements
So I have to solve a question I got from class. I have to write an init() function in JS for the <p> elements to be visible or hidden with a click of a button. What I came up is: (which dosen't work). Note: I cannot change the HTML code; add id/class to an element.</p>
```<code>
<body>
        <p>Lorem ipsum dolor sit </p>
        <p>Lorem ipsum dolor sit </p>
        <p>Lorem ipsum dolor sit </p>

    <input type="button" onclick="init()" value="Show/Hide">

    <script>
        let x = document.getElementsByTagName("body");

        if(x.style.display === 'block') {
            x.style.display = 'none';

        } else {
            x.style.display = 'block';

        }
    </script>
</body>

</code>```

Title: JavaScript Show/Hide HTML Elements

Body:
So I have to solve a question I got from class. I have to write an init() function in JS for the
 elements to be visible or hidden with a click of a button. What I came up is: (which dosen't work). Note: I cannot change the HTML code; add id/class to an element.

Lorem ipsum dolor sit

Lorem ipsum dolor sit

Lorem ipsum dolor sit

    <input type="button" onclick="init()" value="Show/Hide">


问:
Influxdb python write_points() timeout error
I have written a simple code to extract stock market prices from a csv file, load them into a pandas dataframe, then instert them into a Influx database. My code runs smooth, and actually inserts all the rows of my csv file into but then stalls at the end and fails with a timeout error.

My CSV file is as follows:

```<code><TICKER>,<PER>,<DATE>,<TIME>,<OPEN>,<HIGH>,<LOW>,<CLOSE>,<VOL>,<OPENINT>
AAPL.US,D,19840907,000000,0.10093,0.102168,0.0997115,0.10093,97514279.963487,0
AAPL.US,D,19840910,000000,0.10093,0.101239,0.0985032,0.100331,75686989.678719,0
AAPL.US,D,19840911,000000,0.101239,0.103986,0.101239,0.102168,178474414.17812,0
AAPL.US,D,19840912,000000,0.102168,0.102767,0.0990924,0.0990924,155912622.04395,0
AAPL.US,D,19840913,000000,0.104605,0.104904,0.104605,0.104605,242828143.15321,0
</code>```

And my code is as follows:

```<code>import csv
import pandas as pd
import json
from influxdb import DataFrameClient

columns = ('date', 'ticker', 'open', 'high', 'low', 'close', 'volume')
db_name = "mydb"
db_host = "localhost"
db_user = "myusername"
db_password = "mypassword"
db_port = "8086"
table_name = "test"

# Grab data from CSV files and create Pandas Data Frames
def csv_to_pandas(csv_file_location):
    # Read CSV file
    csv_file_location = csv_file_location

    # Load CSV file into a Pandas DataFrame WITHOUT INDEX
    df = pd.read_csv(csv_file_location, index_col=False)
    print(df)

    # Delete unwanted Columns
    df.drop('<PER>', inplace=True, axis=1)
    df.drop('<TIME>', inplace=True, axis=1)
    df.drop('<OPENINT>', inplace=True, axis=1)

    # Change Column Names
    df = df.rename(columns={'<TICKER>': 'ticker',
                                '<DATE>': 'date',
                                '<OPEN>': 'open',
                                '<HIGH>': 'high',
                                '<LOW>': 'low',
                                '<CLOSE>': 'close',
                                '<VOL>': 'volume'}
                                )

    df = df[['date', 'ticker', 'open', 'high', 'low', 'close', 'volume']]

    # Convert all dates in date colmun from text to python DateTime object
    df['date'] = pd.to_datetime(df['date'], format='%Y%m%d')

    # Manually, set index to "Date" column
    df.set_index('date', inplace = True)

    print(df.head())

    # Volume column comes out as +Exponent numbers because the numbers are too long
    # Convert these back to ingteger
    df['volume'] = df['volume'].astype('int64')

    print(df)
    return df

def main():
    csv_file_location = "./aapl.us.csv"

    # convert csv to pandas data frame
    df = csv_to_pandas(csv_file_location)

    print(df.head())

    # Define columns to use as tags
    column_tags = ['ticker']

    client = DataFrameClient(db_host, db_port, db_user, db_password, db_name)

    # Write data to INFLUX.
    client.write_points(df,table_name,tag_columns=column_tags,protocol="line")
    client.close()

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

As I mentioned all the lines of my csv file get inserted in to the database, but then the program execution fails with a timeout error. See traceback below:

```<code>Traceback (most recent call last):
  File "......./test.py", line 93, in <module>
    main()
  File ......./test.py", line 90, in main
    client.write_points(df,table_name,tag_columns=column_tags,protocol="line")
  File "......./lib/python3.9/site-packages/influxdb/_dataframe_client.py", line 135, in write_points
    super(DataFrameClient, self).write_points(
  File "......./.local/lib/python3.9/site-packages/influxdb/client.py", line 603, in write_points
    return self._write_points(points=points,
  File "......./.local/lib/python3.9/site-packages/influxdb/client.py", line 681, in _write_points
    self.write(
  File "......./.local/lib/python3.9/site-packages/influxdb/client.py", line 413, in write
    self.request(
  File "......./.local/lib/python3.9/site-packages/influxdb/client.py", line 373, in request
    raise InfluxDBServerError(reformat_error(response))
influxdb.exceptions.InfluxDBServerError: {"error":"timeout"}
</code>```

I am running debian 11, and Influxdb 1.8.10. Any help would be very much appreciated. Thanks.

Body:
I have written a simple code to extract stock market prices from a csv file, load them into a pandas dataframe, then instert them into a Influx database. My code runs smooth, and actually inserts all the rows of my csv file into but then stalls at the end and fails with a timeout error.

My CSV file is as follows:

<TICKER>,<PER>,<DATE>,<TIME>,<OPEN>,<HIGH>,<LOW>,<CLOSE>,<VOL>,<OPENINT>
AAPL.US,D,19840907,000000,0.10093,0.102168,0.0997115,0.10093,97514279.963487,0
AAPL.US,D,19840910,000000,0.10093,0.101239,0.0985032,0.100331,75686989.678719,0
AAPL.US,D,19840911,000000,0.101239,0.103986,0.101239,0.102168,178474414.17812,0
AAPL.US,D,19840912,000000,0.102168,0.102767,0.0990924,0.0990924,155912622.04395,0
AAPL.US,D,19840913,000000,0.104605,0.104904,0.104605,0.104605,242828143.15321,0

And my code is as follows:

import csv
import pandas as pd
import json
from influxdb import DataFrameClient

columns = ('date', 'ticker', 'open', 'high', 'low', 'close', 'volume')
db_name = "mydb"
db_host = "localhost"
db_user = "myusername"
db_password = "mypassword"
db_port = "8086"
table_name = "test"

# Grab data from CSV files and create Pandas Data Frames
def csv_to_pandas(csv_file_location):
    # Read CSV file
    csv_file_location = csv_file_location

    # Load CSV file into a Pandas DataFrame WITHOUT INDEX
    df = pd.read_csv(csv_file_location, index_col=False)
    print(df)

    # Delete unwanted Columns
    df.drop('<PER>', inplace=True, axis=1)
    df.drop('<TIME>', inplace=True, axis=1)
    df.drop('<OPENINT>', inplace=True, axis=1)

    # Change Column Names
    df = df.rename(columns={'<TICKER>': 'ticker',
                                '<DATE>': 'date',
                                '<OPEN>': 'open',
                                '<HIGH>': 'high',
                                '<LOW>': 'low',
                                '<CLOSE>': 'close',
                                '<VOL>': 'volume'}
                                )

    df = df[['date', 'ticker', 'open', 'high', 'low', 'close', 'volume']]

    # Convert all dates in date colmun from text to python DateTime object
    df['date'] = pd.to_datetime(df['date'], format='%Y%m%d')

    # Manually, set index to "Date" column
    df.set_index('date', inplace = True)

    print(df.head())

    # Volume column comes out as +Exponent numbers because the numbers are too long
    # Convert these back to ingteger
    df['volume'] = df['volume'].astype('int64')

    print(df)
    return df

def main():
    csv_file_location = "./aapl.us.csv"

    # convert csv to pandas data frame
    df = csv_to_pandas(csv_file_location)

    print(df.head())

    # Define columns to use as tags
    column_tags = ['ticker']

    client = DataFrameClient(db_host, db_port, db_user, db_password, db_name)

    # Write data to INFLUX.
    client.write_points(df,table_name,tag_columns=column_tags,protocol="line")
    client.close()

if __name__ == '__main__':
    main()

As I mentioned all the lines of my csv file get inserted in to the database, but then the program execution fails with a timeout error. See traceback below:

Traceback (most recent call last):
  File "......./test.py", line 93, in <module>
    main()
  File ......./test.py", line 90, in main
    client.write_points(df,table_name,tag_columns=column_tags,protocol="line")
  File "......./lib/python3.9/site-packages/influxdb/_dataframe_client.py", line 135, in write_points
    super(DataFrameClient, self).write_points(
  File "......./.local/lib/python3.9/site-packages/influxdb/client.py", line 603, in write_points
    return self._write_points(points=points,
  File "......./.local/lib/python3.9/site-packages/influxdb/client.py", line 681, in _write_points
    self.write(
  File "......./.local/lib/python3.9/site-packages/influxdb/client.py", line 413, in write
    self.request(
  File "......./.local/lib/python3.9/site-packages/influxdb/client.py", line 373, in request
    raise InfluxDBServerError(reformat_error(response))
influxdb.exceptions.InfluxDBServerError: {"error":"timeout"}

I am running debian 11, and Influxdb 1.8.10. Any help would be very much appreciated. Thanks.


问:
What type of t.test would you use for reaction time? Why does shapiro-wilk Test show reaction time data as not normally distributed?
```<code>Test %>%
  filter(firstlanguage_cat %in% c("1", "2" )) %>%
  t.test(firstlanguage_cat ~ Mean_RT_SIT1_Pre, data = .,
         alternative = "two.sided")
</code>```

Error in t.test.formula(firstlanguage_cat ~ Mean_RT_SIT1_Pre, data = .,  :

grouping factor must have exactly 2 levels

How can I run the t.test?

I want to run an independent t.test for groups 1 and 2 in firstlanguage_cat for Mean Reaction Time without getting an error.

Body:
Test %>%
  filter(firstlanguage_cat %in% c("1", "2" )) %>%
  t.test(firstlanguage_cat ~ Mean_RT_SIT1_Pre, data = .,
         alternative = "two.sided")

Error in t.test.formula(firstlanguage_cat ~ Mean_RT_SIT1_Pre, data = .,  :

grouping factor must have exactly 2 levels

How can I run the t.test?

I want to run an independent t.test for groups 1 and 2 in firstlanguage_cat for Mean Reaction Time without getting an error.


问:
Logic Expression using Binary Tree (DSA) Python
i need a algorithm has a expression as input and return truth table

input : String expression

ex : "(A AND B)=>R OR D"

output : truth table

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


问:
How to do an onHover for a single point in a recharts multiline chart?
I have a multiline chart in recharts that I want to add an onHover tooltip for. The issue I have is that I want to single out the individual point the user is hovering over, but the tooltip doesn't seem to give a way to identify that point.

This can be seen in the recharts documentation for LineChart: https://recharts.org/en-US/api/LineChart

In their example there are two lines and when you hover over a point, it shows the results for both points. Is there a way to single out the data in the Tooltip payload to select the individual point you are over?

Here is the code in the example:

```<code>const data = [
  {
    "name": "Page A",
    "uv": 4000,
    "pv": 2400,
    "amt": 2400
  },
  {
    "name": "Page B",
    "uv": 3000,
    "pv": 1398,
    "amt": 2210
  },
  {
    "name": "Page C",
    "uv": 2000,
    "pv": 9800,
    "amt": 2290
  },
  {
    "name": "Page D",
    "uv": 2780,
    "pv": 3908,
    "amt": 2000
  },
  {
    "name": "Page E",
    "uv": 1890,
    "pv": 4800,
    "amt": 2181
  },
  {
    "name": "Page F",
    "uv": 2390,
    "pv": 3800,
    "amt": 2500
  },
  {
    "name": "Page G",
    "uv": 3490,
    "pv": 4300,
    "amt": 2100
  }
]

<LineChart width={730} height={250} data={data}
  margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
  <CartesianGrid strokeDasharray="3 3" />
  <XAxis dataKey="name" />
  <YAxis />
  <Tooltip />
  <Legend />
  <Line type="monotone" dataKey="pv" stroke="#8884d8" />
  <Line type="monotone" dataKey="uv" stroke="#82ca9d" />
</LineChart>
</code>```

Any help is appreciated!

Body:
I have a multiline chart in recharts that I want to add an onHover tooltip for. The issue I have is that I want to single out the individual point the user is hovering over, but the tooltip doesn't seem to give a way to identify that point.

This can be seen in the recharts documentation for LineChart: https://recharts.org/en-US/api/LineChart

In their example there are two lines and when you hover over a point, it shows the results for both points. Is there a way to single out the data in the Tooltip payload to select the individual point you are over?

Here is the code in the example:

const data = [
  {
    "name": "Page A",
    "uv": 4000,
    "pv": 2400,
    "amt": 2400
  },
  {
    "name": "Page B",
    "uv": 3000,
    "pv": 1398,
    "amt": 2210
  },
  {
    "name": "Page C",
    "uv": 2000,
    "pv": 9800,
    "amt": 2290
  },
  {
    "name": "Page D",
    "uv": 2780,
    "pv": 3908,
    "amt": 2000
  },
  {
    "name": "Page E",
    "uv": 1890,
    "pv": 4800,
    "amt": 2181
  },
  {
    "name": "Page F",
    "uv": 2390,
    "pv": 3800,
    "amt": 2500
  },
  {
    "name": "Page G",
    "uv": 3490,
    "pv": 4300,
    "amt": 2100
  }
]

<LineChart width={730} height={250} data={data}
  margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
  <CartesianGrid strokeDasharray="3 3" />
  <XAxis dataKey="name" />
  <YAxis />
  <Tooltip />
  <Legend />
  <Line type="monotone" dataKey="pv" stroke="#8884d8" />
  <Line type="monotone" dataKey="uv" stroke="#82ca9d" />
</LineChart>

Any help is appreciated!


问:
writing copy constructor, constructor and operator= for a class which contains more classes
i have a class (Team) which contains 2 AVL trees - one AVL tree's nodes contain data of shared_ptr to an object
of class Player, and the other AVL tree's nodes contain data of shared_ptr to an object of class PlayerKeyId - which is
a successor of class Player and the only differents between those classes are the operators "<" and ">".
the goal was to organize the players in the team by 2 categories.
after using this structure for a lot of functions I found out I have a lot of memory leaks because I used the default
constructor ,copy constructor and operator "=".
i tried to write those for each class but I have some SEG FAULT problems.

```<code>   //start of relevant code - class Player
class Player{
    public:
    int playerID;
    int goals;
    int cards;
    int playerGamesPlayed;
    bool goalkeeper;
    Node<shared_ptr<Player>>* followingPlayer;
    Node<shared_ptr<Player>>* previousPlayer;
    shared_ptr<Team> playerTeamPointer;
    int teamPlayerId;
    public:

    Player(int playerID,int teamID, int gamesPlayed, int goals,int cards,bool goalkeeper,  shared_ptr<Team> playerTeamPointer):playerID(playerID),goals(goals),cards(cards),playerGamesPlayed(gamesPlayed),goalkeeper(goalkeeper),playerTeamPointer(playerTeamPointer),teamPlayerId(teamID){

    };

    ~Player(){
            playerTeamPointer=nullptr;
    };

    Player( Player & p){
        followingPlayer = new Node<shared_ptr<Player>>();
        previousPlayer = new Node<shared_ptr<Player>>();
        playerID = p.playerID;
        goals = p.goals;
        cards = p.cards;
        playerGamesPlayed = p.playerGamesPlayed;
        goalkeeper = p.goalkeeper;
        *(followingPlayer)= *(p.followingPlayer);
        *(previousPlayer) = *(p.previousPlayer);
        teamPlayerId = p.teamPlayerId;
    }

     Player& operator=(Player& p){
        playerID = p.playerID;
        goals = p.goals;
        cards = p.cards;
        playerGamesPlayed = p.playerGamesPlayed;
        goalkeeper = p.goalkeeper;
        *(followingPlayer)= *(p.followingPlayer);
        *(previousPlayer) = *(p.previousPlayer);
        teamPlayerId = p.teamPlayerId;
        return *this;
    }

    Player(){}
</code>```

//end of relevant code - class Player

//start of code - class Team.

```<code>class Team{
    public:
    int teamID;
    int points;
    int playerCount;
    int teamGames;
    shared_ptr<Player> topScorer;
    int totalGoals;
    int totalCards;
    int goalKeepers;
    bool valid;
    AVLTree<shared_ptr<PlayerKeyId>> *playersId;
    AVLTree<shared_ptr<Player>> *playersGoals;

    Team(int teamID, int points):teamID(teamID),points(points){
        playerCount=0;
        teamGames=0;
        topScorer = make_shared<PlayerKeyId>(-1,-1,-1,-1,-1,false,nullptr);
        totalGoals=0;
        totalCards=0;
        goalKeepers=0;
        valid=false;

        playersId = new  AVLTree<shared_ptr<PlayerKeyId>>();
        playersGoals = new  AVLTree<shared_ptr<Player>>();
    }

    Team( Team & t){
        playersId = new AVLTree<shared_ptr<PlayerKeyId>>();
        playersGoals = new AVLTree<shared_ptr<Player>>();
        teamID = t.teamID;
        points = t.points;
        playerCount = t.playerCount;
        teamGames = t. teamGames;
        topScorer = t.topScorer;
        totalCards = t.totalCards;
        goalKeepers = t.goalKeepers;
        valid = t.valid;
        *(playersId) = *(t.playersId);
        *(playersGoals) = *(t.playersGoals);
    }

    Team& operator =(Team& t){
       teamID = t.teamID;
        points = t.points;
        playerCount = t.playerCount;
         teamGames = t. teamGames;
        topScorer = t.topScorer;
        totalCards = t.totalCards;
        goalKeepers = t.goalKeepers;
        valid = t.valid;
        *( playersId) = *(t. playersId);
        *( playersGoals) = *(t. playersGoals);
       return *this;
    }

    ~Team(){
        topScorer=nullptr;
        delete playersId;
        delete playersGoals;
    }
</code>```

//end of code relevant - class Team.

//**in class PlayerKeyId I didn't wrote those three because I wanted to use the ones of Player. here is the start of PlayerKeyId:

```<code>class PlayerKeyId:public Player{
    public:

     using Player::Player;
</code>```

//start of relevant code - AVL tree

```<code>template <class T>
class Node {
public:
    Node* left;
    T data;
    Node* right;
    int height;
     Node* parent;

     Node(){
        left=NULL;
        right=NULL;
        height=0;
        parent=NULL;
     }

     ~Node(){
        parent = nullptr;
     }

     Node<T>(Node<T>& oldNode){
        if(oldNode.left!=NULL)
            left= new Node<T>;
         if(oldNode.right!=NULL)
            right= new Node<T>;
         if(oldNode.parent!=NULL)
            parent= new Node<T>;
        data = new T();
        *left = oldNode.left;
        *right = oldNode.right;
        *parent = oldNode.parent;
        height=oldNode.height;
        *data = oldNode.data;
     }

     Node<T>& operator=(Node<T>& oldNode){
        data=oldNode.data;

            left=oldNode.left;

          right=oldNode.right;
        return *this;
     }

};

template <class T>
class AVLTree{
public:
    Node<T>* root;

    AVLTree(){ root = NULL; }

    AVLTree<T>& operator=(AVLTree<T>& oldAVL){
        root = oldAVL.root;
        return *this;
    }

     AVLTree(AVLTree& oldAVL)
     {
         root = new Node<T>;
        *(root) = oldAVL.root;
     }
</code>```

//end of relevant code - AVL tree

I tried to look how to write those 3 in the right way but something went wrong on the road.

Body:
i have a class (Team) which contains 2 AVL trees - one AVL tree's nodes contain data of shared_ptr to an object
of class Player, and the other AVL tree's nodes contain data of shared_ptr to an object of class PlayerKeyId - which is
a successor of class Player and the only differents between those classes are the operators "<" and ">".
the goal was to organize the players in the team by 2 categories.
after using this structure for a lot of functions I found out I have a lot of memory leaks because I used the default
constructor ,copy constructor and operator "=".
i tried to write those for each class but I have some SEG FAULT problems.

   //start of relevant code - class Player
class Player{
    public:
    int playerID;
    int goals;
    int cards;
    int playerGamesPlayed;
    bool goalkeeper;
    Node<shared_ptr<Player>>* followingPlayer;
    Node<shared_ptr<Player>>* previousPlayer;
    shared_ptr<Team> playerTeamPointer;
    int teamPlayerId;
    public:

    Player(int playerID,int teamID, int gamesPlayed, int goals,int cards,bool goalkeeper,  shared_ptr<Team> playerTeamPointer):playerID(playerID),goals(goals),cards(cards),playerGamesPlayed(gamesPlayed),goalkeeper(goalkeeper),playerTeamPointer(playerTeamPointer),teamPlayerId(teamID){

    };

    ~Player(){
            playerTeamPointer=nullptr;
    };

    Player( Player & p){
        followingPlayer = new Node<shared_ptr<Player>>();
        previousPlayer = new Node<shared_ptr<Player>>();
        playerID = p.playerID;
        goals = p.goals;
        cards = p.cards;
        playerGamesPlayed = p.playerGamesPlayed;
        goalkeeper = p.goalkeeper;
        *(followingPlayer)= *(p.followingPlayer);
        *(previousPlayer) = *(p.previousPlayer);
        teamPlayerId = p.teamPlayerId;
    }

     Player& operator=(Player& p){
        playerID = p.playerID;
        goals = p.goals;
        cards = p.cards;
        playerGamesPlayed = p.playerGamesPlayed;
        goalkeeper = p.goalkeeper;
        *(followingPlayer)= *(p.followingPlayer);
        *(previousPlayer) = *(p.previousPlayer);
        teamPlayerId = p.teamPlayerId;
        return *this;
    }

    Player(){}

//end of relevant code - class Player

//start of code - class Team.

class Team{
    public:
    int teamID;
    int points;
    int playerCount;
    int teamGames;
    shared_ptr<Player> topScorer;
    int totalGoals;
    int totalCards;
    int goalKeepers;
    bool valid;
    AVLTree<shared_ptr<PlayerKeyId>> *playersId;
    AVLTree<shared_ptr<Player>> *playersGoals;

    Team(int teamID, int points):teamID(teamID),points(points){
        playerCount=0;
        teamGames=0;
        topScorer = make_shared<PlayerKeyId>(-1,-1,-1,-1,-1,false,nullptr);
        totalGoals=0;
        totalCards=0;
        goalKeepers=0;
        valid=false;

        playersId = new  AVLTree<shared_ptr<PlayerKeyId>>();
        playersGoals = new  AVLTree<shared_ptr<Player>>();
    }

    Team( Team & t){
        playersId = new AVLTree<shared_ptr<PlayerKeyId>>();
        playersGoals = new AVLTree<shared_ptr<Player>>();
        teamID = t.teamID;
        points = t.points;
        playerCount = t.playerCount;
        teamGames = t. teamGames;
        topScorer = t.topScorer;
        totalCards = t.totalCards;
        goalKeepers = t.goalKeepers;
        valid = t.valid;
        *(playersId) = *(t.playersId);
        *(playersGoals) = *(t.playersGoals);
    }

    Team& operator =(Team& t){
       teamID = t.teamID;
        points = t.points;
        playerCount = t.playerCount;
         teamGames = t. teamGames;
        topScorer = t.topScorer;
        totalCards = t.totalCards;
        goalKeepers = t.goalKeepers;
        valid = t.valid;
        *( playersId) = *(t. playersId);
        *( playersGoals) = *(t. playersGoals);
       return *this;
    }

    ~Team(){
        topScorer=nullptr;
        delete playersId;
        delete playersGoals;
    }

//end of code relevant - class Team.

//**in class PlayerKeyId I didn't wrote those three because I wanted to use the ones of Player. here is the start of PlayerKeyId:

class PlayerKeyId:public Player{
    public:

     using Player::Player;

//start of relevant code - AVL tree

template <class T>
class Node {
public:
    Node* left;
    T data;
    Node* right;
    int height;
     Node* parent;

     Node(){
        left=NULL;
        right=NULL;
        height=0;
        parent=NULL;
     }

     ~Node(){
        parent = nullptr;
     }

     Node<T>(Node<T>& oldNode){
        if(oldNode.left!=NULL)
            left= new Node<T>;
         if(oldNode.right!=NULL)
            right= new Node<T>;
         if(oldNode.parent!=NULL)
            parent= new Node<T>;
        data = new T();
        *left = oldNode.left;
        *right = oldNode.right;
        *parent = oldNode.parent;
        height=oldNode.height;
        *data = oldNode.data;
     }

     Node<T>& operator=(Node<T>& oldNode){
        data=oldNode.data;

            left=oldNode.left;

          right=oldNode.right;
        return *this;
     }

};

template <class T>
class AVLTree{
public:
    Node<T>* root;

    AVLTree(){ root = NULL; }

    AVLTree<T>& operator=(AVLTree<T>& oldAVL){
        root = oldAVL.root;
        return *this;
    }

     AVLTree(AVLTree& oldAVL)
     {
         root = new Node<T>;
        *(root) = oldAVL.root;
     }

//end of relevant code - AVL tree

I tried to look how to write those 3 in the right way but something went wrong on the road.


Title: Calculate VWAP by Date (Help Running Script Please)

Body:
I'm trying to use the script given in an answer here and could really use some help figuring it out.

I'm pretty new to all this but managed to install python, pip, and the requests and pandas modules.

I am able to run the script and it outputs data; however, how do I run the script for a specific ticker and date?

For example, how do I run the script for the ticker "SPY" for the date 12/06/2022?

Thank you in advance!!!

I'm choosing the ticker "SPY" and run the script and it outputs:

python3 vwap.py SPY
                        Open     High      Low    Close    volume        Date          vwap
Time
2022-12-07 06:46:00  16975.0  16975.1  16975.0  16975.1  0.091722  2022-12-07  16975.066667
2022-12-07 06:47:00  16975.1  16975.1  16970.1  16970.1  0.356965  2022-12-07  16972.441261
2022-12-07 06:48:00  16970.1  16970.2  16970.1  16970.2  0.506126  2022-12-07  16971.235547
2022-12-07 06:49:00  16970.1  16970.2  16970.1  16970.2  0.019041  2022-12-07  16971.214648
2022-12-07 06:50:00  16970.2  16970.2  16955.4  16957.5  3.832814  2022-12-07  16963.096116
...                      ...      ...      ...      ...       ...         ...           ...
2022-12-07 18:41:00  16804.4  16804.4  16804.4  16804.4  0.471748  2022-12-07  16812.490887
2022-12-07 18:42:00  16804.4  16810.4  16804.4  16807.3  6.735564  2022-12-07  16812.464360
2022-12-07 18:43:00  16808.7  16812.1  16805.5  16805.5  3.790436  2022-12-07  16812.450520
2022-12-07 18:44:00  16805.6  16808.7  16803.0  16803.0  0.827792  2022-12-07  16812.445734
2022-12-07 18:45:00  16803.0  16803.0  16803.0  16803.0  0.000000  2022-12-07  16812.445734

[720 rows x 7 columns]

However, if I run the script and don't type a ticker it gives me the same output. So how do I run the script for a specific ticker and date?


问:
Flutter, Firebase Authentication, and Django Rest Framework - Can I use Firebase auth on the client for various authorizations?
The question is the tech stack I'm using for a Flutter Web App. I've already made a firebase authentication class on django and the two are working great so far.

My question is if it's necessary for me to use Django's permissions. For example, the IsAuthenticated permission class states that it

will deny permission to any unauthenticated user, and allow permission otherwise.This permission is suitable if you want your API to only be accessible to registered users.

I can do a similar work around with Firebase Auth as I could show the user a completely different page based on their Firebase Auth status. For example, if a user tries to navigate to a simplified dashboard in the url could I use this as a crude form of authorization?

```<code>class UserDashBoard extends StatelessWidget {
  const UserDashBoard({required Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var user = FirebaseAuth.instance.currentUser;
    return Scaffold(
      body: user == null
          ? const Text(
              'You are not signed in. Please sign in or register an account')
          : Center(
              child: Text('Welcome, ${user.displayName}'),
            ),
    );
  }
}

</code>```

It seems like sending a network request would be accomplishing the same thing. I feel like similar code can be done to accomplish Django's IsAuthenticatedOrReadOnly permisson class as well, however maybe I'm missing out on a big security issue. If that's the case, I would likely implement the same solution just with some permission classes as well on the backend just in case.

Body:
The question is the tech stack I'm using for a Flutter Web App. I've already made a firebase authentication class on django and the two are working great so far.

My question is if it's necessary for me to use Django's permissions. For example, the IsAuthenticated permission class states that it

will deny permission to any unauthenticated user, and allow permission otherwise.This permission is suitable if you want your API to only be accessible to registered users.

I can do a similar work around with Firebase Auth as I could show the user a completely different page based on their Firebase Auth status. For example, if a user tries to navigate to a simplified dashboard in the url could I use this as a crude form of authorization?

class UserDashBoard extends StatelessWidget {
  const UserDashBoard({required Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var user = FirebaseAuth.instance.currentUser;
    return Scaffold(
      body: user == null
          ? const Text(
              'You are not signed in. Please sign in or register an account')
          : Center(
              child: Text('Welcome, ${user.displayName}'),
            ),
    );
  }
}

It seems like sending a network request would be accomplishing the same thing. I feel like similar code can be done to accomplish Django's IsAuthenticatedOrReadOnly permisson class as well, however maybe I'm missing out on a big security issue. If that's the case, I would likely implement the same solution just with some permission classes as well on the backend just in case.


问:
How to solve "org.hibernate.query.sqm.UnknownEntityException: Could not resolve root entity [Table Name]"
The below block of code is not working:

```<code>private boolean checkLaptopDuplicates(String data1) {
    Session session = sessionFactory.getCurrentSession();

    String stmt = "from laptop where image_url = '" + data1 + "'";
    List<Laptop> laptopList = session.createQuery(stmt).getResultList();
    return laptopList.size() > 0;

}
</code>```

I got the following error with the above block of code:

```<code>Exception in thread "Thread-3" java.lang.IllegalArgumentException: org.hibernate.query.sqm.UnknownEntityException: Could not resolve root entity 'Laptop'
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:175)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:182)
    at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:761)
    at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:663)
    at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:127)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
    at java.base/java.lang.reflect.Method.invoke(Method.java:578)
    at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:345)
    at jdk.proxy2/jdk.proxy2.$Proxy47.createQuery(Unknown Source)
    at web_scraping_codes.scraping_codes.LaptopDataAccessObject.checkLaptopDuplicates(LaptopDataAccessObject.java:90)
    at web_scraping_codes.scraping_codes.LaptopDataAccessObject.addLaptop(LaptopDataAccessObject.java:42)
    at web_scraping_codes.scraping_codes.ValueComputersScraper.run(ValueComputersScraper.java:153)
Caused by: org.hibernate.query.sqm.UnknownEntityException: Could not resolve root entity 'Laptop'
    at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitRootEntity(SemanticQueryBuilder.java:1628)
    at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitRootEntity(SemanticQueryBuilder.java:243)
    at org.hibernate.grammars.hql.HqlParser$RootEntityContext.accept(HqlParser.java:1873)

</code>```

How this issue should be tackled?

Body:
The below block of code is not working:

private boolean checkLaptopDuplicates(String data1) {
    Session session = sessionFactory.getCurrentSession();

    String stmt = "from laptop where image_url = '" + data1 + "'";
    List<Laptop> laptopList = session.createQuery(stmt).getResultList();
    return laptopList.size() > 0;

}

I got the following error with the above block of code:

Exception in thread "Thread-3" java.lang.IllegalArgumentException: org.hibernate.query.sqm.UnknownEntityException: Could not resolve root entity 'Laptop'
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:175)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:182)
    at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:761)
    at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:663)
    at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:127)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
    at java.base/java.lang.reflect.Method.invoke(Method.java:578)
    at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:345)
    at jdk.proxy2/jdk.proxy2.$Proxy47.createQuery(Unknown Source)
    at web_scraping_codes.scraping_codes.LaptopDataAccessObject.checkLaptopDuplicates(LaptopDataAccessObject.java:90)
    at web_scraping_codes.scraping_codes.LaptopDataAccessObject.addLaptop(LaptopDataAccessObject.java:42)
    at web_scraping_codes.scraping_codes.ValueComputersScraper.run(ValueComputersScraper.java:153)
Caused by: org.hibernate.query.sqm.UnknownEntityException: Could not resolve root entity 'Laptop'
    at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitRootEntity(SemanticQueryBuilder.java:1628)
    at org.hibernate.query.hql.internal.SemanticQueryBuilder.visitRootEntity(SemanticQueryBuilder.java:243)
    at org.hibernate.grammars.hql.HqlParser$RootEntityContext.accept(HqlParser.java:1873)

How this issue should be tackled?


问:
CSS Container / Grid stacking issue
In this example, there appears to be a conflict between container-type and Grid layout that when a position element overlays outside of its own cell and over a next-door cell, some stacking issues occur.

Check the Codepen link (https://codepen.io/rctneil/pen/OJErQRr) and open the Sl-Select web component in the first grid cell (Ensure on a wider viewport) and see how the checkboxes underneath show up ontop and the menu is not usable?

Does anyone have any solutions to this issue?     Disabling the container-type property resolves the issue but obviously breaks the container query that's being used.

Title: CSS Container / Grid stacking issue


问:
Cannot install Nodejs 14 on Ubuntu 18
I want to install node 14 on Ubuntu 18 but It only install version 8

```<code> sudo apt -y install curl dirmngr apt-transport-https lsb-release ca-certificates

 curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
</code>```

console output

```<code>+ apt-get update
Obter:1 https://dl.winehq.org/wine-builds/ubuntu bionic InRelease [6.263 B]
Atingido:2 http://br.archive.ubuntu.com/ubuntu bionic InRelease
Atingido:3 https://linux.teamviewer.com/deb stable InRelease
Atingido:4 http://br.archive.ubuntu.com/ubuntu bionic-updates InRelease
Atingido:5 http://br.archive.ubuntu.com/ubuntu bionic-backports InRelease
Err:1 https://dl.winehq.org/wine-builds/ubuntu bionic InRelease
  As assinaturas a seguir não puderam ser verificadas devido à chave pública não estar disponível: NO_PUBKEY 76F1A20FF987672F
Obter:6 http://deb.anydesk.com all InRelease [5.588 B]
Ign:7 http://ppa.launchpad.net/mapopa/ppa/ubuntu bionic InRelease
Atingido:8 http://security.ubuntu.com/ubuntu bionic-security InRelease
Atingido:9 http://apt.postgresql.org/pub/repos/apt bionic-pgdg InRelease
Err:6 http://deb.anydesk.com all InRelease
  As seguintes assinaturas eram inválidas: EXPKEYSIG 18DF3741CDFFDE29 philandro Software GmbH <info@philandro.com>
Atingido:10 http://ppa.launchpad.net/webupd8team/java/ubuntu bionic InRelease
Atingido:11 https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/bionic pgadmin4 InRelease
Err:12 http://ppa.launchpad.net/mapopa/ppa/ubuntu bionic Release
  404  Not Found [IP: 185.125.190.52 80]
Lendo listas de pacotes... Pronto
W: Erro GPG: https://dl.winehq.org/wine-builds/ubuntu bionic InRelease: As assinaturas a seguir não puderam ser verificadas devido à chave pública não estar disponível: NO_PUBKEY 76F1A20FF987672F
E: The repository 'https://dl.winehq.org/wine-builds/ubuntu bionic InRelease' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
W: An error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: http://deb.anydesk.com all InRelease: As seguintes assinaturas eram inválidas: EXPKEYSIG 18DF3741CDFFDE29 philandro Software GmbH <info@philandro.com>
E: The repository 'http://ppa.launchpad.net/mapopa/ppa/ubuntu bionic Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
Error executing command, exiting
</code>```

How can I solve this?

Title: Cannot install Nodejs 14 on Ubuntu 18

Body:
I want to install node 14 on Ubuntu 18 but It only install version 8

 sudo apt -y install curl dirmngr apt-transport-https lsb-release ca-certificates

 curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -

console output

+ apt-get update
Obter:1 https://dl.winehq.org/wine-builds/ubuntu bionic InRelease [6.263 B]
Atingido:2 http://br.archive.ubuntu.com/ubuntu bionic InRelease
Atingido:3 https://linux.teamviewer.com/deb stable InRelease
Atingido:4 http://br.archive.ubuntu.com/ubuntu bionic-updates InRelease
Atingido:5 http://br.archive.ubuntu.com/ubuntu bionic-backports InRelease
Err:1 https://dl.winehq.org/wine-builds/ubuntu bionic InRelease
  As assinaturas a seguir não puderam ser verificadas devido à chave pública não estar disponível: NO_PUBKEY 76F1A20FF987672F
Obter:6 http://deb.anydesk.com all InRelease [5.588 B]
Ign:7 http://ppa.launchpad.net/mapopa/ppa/ubuntu bionic InRelease
Atingido:8 http://security.ubuntu.com/ubuntu bionic-security InRelease
Atingido:9 http://apt.postgresql.org/pub/repos/apt bionic-pgdg InRelease
Err:6 http://deb.anydesk.com all InRelease
  As seguintes assinaturas eram inválidas: EXPKEYSIG 18DF3741CDFFDE29 philandro Software GmbH <info@philandro.com>
Atingido:10 http://ppa.launchpad.net/webupd8team/java/ubuntu bionic InRelease
Atingido:11 https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/bionic pgadmin4 InRelease
Err:12 http://ppa.launchpad.net/mapopa/ppa/ubuntu bionic Release
  404  Not Found [IP: 185.125.190.52 80]
Lendo listas de pacotes... Pronto
W: Erro GPG: https://dl.winehq.org/wine-builds/ubuntu bionic InRelease: As assinaturas a seguir não puderam ser verificadas devido à chave pública não estar disponível: NO_PUBKEY 76F1A20FF987672F
E: The repository 'https://dl.winehq.org/wine-builds/ubuntu bionic InRelease' is not signed.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
W: An error occurred during the signature verification. The repository is not updated and the previous index files will be used. GPG error: http://deb.anydesk.com all InRelease: As seguintes assinaturas eram inválidas: EXPKEYSIG 18DF3741CDFFDE29 philandro Software GmbH <info@philandro.com>
E: The repository 'http://ppa.launchpad.net/mapopa/ppa/ubuntu bionic Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
Error executing command, exiting

How can I solve this?


问:
How to split an image using edge detection in python
My images are stored in an numpy array I want to split the images into individual images containing single character.

import cv2

# Load image, grayscale, Gaussian blur, Otsu's threshold, dilate
image =   arr               #numpy_arr_containing 200X200 image
original = image.copy()
gray = image
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15,15))
dilate = cv2.dilate(thresh, kernel, iterations=2)

# Find contours, obtain bounding box coordinates, and extract ROI
cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
image_number = 0
for c in cnts:
    x,y,w,h = cv2.boundingRect(c)
    cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 3)
    ROI = original[y:y+h, x:x+w]
    cv2.imwrite("ROI_{}.png".format(image_number), ROI)
    image_number += 1

# cv2.imshow('image', image)
# cv2.imshow('thresh', thresh)
# cv2.imshow('dilate', dilate)
# cv2.waitKey()
```


问:
Discord Webhook Send Message with Components
I am trying to send a message to Discord Webhook, with Components.

I have tried normal message and embed, and both give me the same result.  I get the message, but not the components.

Syntax From here:  https://discord.com/developers/docs/interactions/message-components

Here is my code:

```<code><?php

$url = "https://discord.com/api/webhooks/1234567890";

$content = '{
            "content": "This is a message with components.",
            "components": [
                {
                    "type": 1,
                    "components": [
                        {
                            "type": 2,
                            "label": "Click me!",
                            "style": 1,
                            "custom_id": "click_one"
                        }
                    ]
                }
            ]
    }';

$curl = curl_init();
$headers = array('Content-Type: application/json');
curl_setopt_array($curl, array(
    CURLOPT_URL => $url,
    CURLOPT_POSTFIELDS =>  $content,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_HEADER   => true
));

$response = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
var_dump($response);
</code>```

Here is the var_dump of the response:

Body:
I am trying to send a message to Discord Webhook, with Components.

I have tried normal message and embed, and both give me the same result.  I get the message, but not the components.

Syntax From here:  https://discord.com/developers/docs/interactions/message-components

Here is my code:

<?php

$url = "https://discord.com/api/webhooks/1234567890";

$content = '{
            "content": "This is a message with components.",
            "components": [
                {
                    "type": 1,
                    "components": [
                        {
                            "type": 2,
                            "label": "Click me!",
                            "style": 1,
                            "custom_id": "click_one"
                        }
                    ]
                }
            ]
    }';

$curl = curl_init();
$headers = array('Content-Type: application/json');
curl_setopt_array($curl, array(
    CURLOPT_URL => $url,
    CURLOPT_POSTFIELDS =>  $content,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_HEADER   => true
));

$response = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
var_dump($response);

Here is the var_dump of the response:


问:
I transfer in a link a string like this : baltus & adang. How can i keep that together
In th title i asp if i transfer a string like baltus & adang. In u link i have a variable named $NameString. This string is filled with the value 'Baltus & Adang' . When i passed it to the a second module with &NameString= Baltus & Adang? is see the when i do a $NameString=    $_GET["NameString"]; the value is still baltus & adang. When i passed it to a thrid module and i do also : $NameString=    $_GET["NameString"]; is see only Baltus.

What to do to correct it?
Thanks,
Fred

i did all kind of things..

You can see it if you go to https://fred-baltus.nl/api and type in baltus & adang in the search field. On the next screen click on a link. On the third screen when you hover over Terug you see that NaamString only contains baltus


问:
react native expo deep linking not working for android
I create app with react native expo and added deep linking. Config looks like this in app.config.ts:

```<code> android: {
          package: 'android-package-name',
          intentFilters: [
            {
              action: 'VIEW',
              autoVerify: true,
              data: [
                {
                  scheme: 'https',
                  host: '*my-app.com',
                  pathPrefix: '/claim',
                },
              ],
              category: ['BROWSABLE', 'DEFAULT'],
            },
          ],
        },
</code>```

I do have the plugin mentioned here React native expo deep linking with android and it's added in app.json plugins.

Then on my website i do have the needed ./well-known/assetslinks.json file with following config:

```<code>{
  "relation": ["delegate_permission/common.handle_all_urls"],
  "target": {
    "namespace": "android_app",
    "package_name": "android-package-name",
    "sha256_cert_fingerprints": [...sha256_cert_fingerprints]
  }
}

</code>```

And when i can the mobile application is not opening it behave like is not installed. Any ideas please

Body:
I create app with react native expo and added deep linking. Config looks like this in app.config.ts:

 android: {
          package: 'android-package-name',
          intentFilters: [
            {
              action: 'VIEW',
              autoVerify: true,
              data: [
                {
                  scheme: 'https',
                  host: '*my-app.com',
                  pathPrefix: '/claim',
                },
              ],
              category: ['BROWSABLE', 'DEFAULT'],
            },
          ],
        },

I do have the plugin mentioned here React native expo deep linking with android and it's added in app.json plugins.

Then on my website i do have the needed ./well-known/assetslinks.json file with following config:

{
  "relation": ["delegate_permission/common.handle_all_urls"],
  "target": {
    "namespace": "android_app",
    "package_name": "android-package-name",
    "sha256_cert_fingerprints": [...sha256_cert_fingerprints]
  }
}

And when i can the mobile application is not opening it behave like is not installed. Any ideas please


问:
Does XCUIElement represent a query rather than a specific element?
This example is pretty contrived, but it illustrates the behavior. I know you can use .accessibilityIdentifier to uniquely identify a control, but I'm just trying to better understand the interplay between XCUIElement and XCUIElementQuery.

Let's say you have an app like this:

```<code>import SwiftUI

struct ContentView: View {
    @State var showRedButton = true

    var body: some View {
        VStack {
            if showRedButton {
                Button("Click me") {
                    showRedButton = false
                }
                .background(.red)
            }
            else {
                HStack {
                    Button("Click me") {
                        showRedButton = true
                    }
                    .background(.blue)
                    Spacer()
                }
            }
        }
    }
}
</code>```

And you are UI testing like this:

```<code>import XCTest

final class MyAppUITests: XCTestCase {
    func testExample() throws {
        let app = XCUIApplication()
        app.launch()

        print(app.debugDescription)

        // At this point, the Element subtree shows a single Button:
        // Button, 0x14e40d290, {{162.3, 418.3}, {65.3, 20.3}}, label: 'Click me'

        let btn = app.buttons["Click me"]

        btn.tap() // <-- This tap makes the red button disappear and shows the blue button

        print(app.debugDescription)

        // Now, the Element subtree shows a single Button that has a different ID
        // and different x-y coordinates:
        // Button, 0x15dc12e50, {{0.0, 418.3}, {65.3, 20.3}}, label: 'Click me'

        btn.tap() // <-- This tap now works on the blue button?? Without requerying?

        print(app.debugDescription)

        // The red button reappears, but with a different ID (which makes sense).
    }
}

</code>```

Why does the second tap work, even though it's a different control? This must mean that SwiftUI is automatically re-running the XCUIElementQuery to find the button that matches "Click me". Apparently the variable btn isn't linked to the control with the ID 0x14e40d290. Does this mean XCUIElement actually represents an XCUIElementQuery?        I expected it to require me to explicitly re-run the query like this,

```<code>btn = app.buttons["Click me"]
</code>```

prior to running the 2nd tap, or the tap would've said that btn was no longer available.

The final print of the Element subtree shows that the red button has a different ID now. This makes sense, because when SwiftUI redraws the red button, it's not the same instance as the last time. This is explained well in the WWDC videos. Nevertheless, at the moment I connected the variable "btn" to the control, I thought there was a tighter affiliation. Maybe UI testing has to behave this way because SwiftUI redraws controls so frequently?

Body:
This example is pretty contrived, but it illustrates the behavior. I know you can use .accessibilityIdentifier to uniquely identify a control, but I'm just trying to better understand the interplay between XCUIElement and XCUIElementQuery.

Let's say you have an app like this:

import SwiftUI

struct ContentView: View {
    @State var showRedButton = true

    var body: some View {
        VStack {
            if showRedButton {
                Button("Click me") {
                    showRedButton = false
                }
                .background(.red)
            }
            else {
                HStack {
                    Button("Click me") {
                        showRedButton = true
                    }
                    .background(.blue)
                    Spacer()
                }
            }
        }
    }
}

And you are UI testing like this:

import XCTest

final class MyAppUITests: XCTestCase {
    func testExample() throws {
        let app = XCUIApplication()
        app.launch()

        print(app.debugDescription)

        // At this point, the Element subtree shows a single Button:
        // Button, 0x14e40d290, {{162.3, 418.3}, {65.3, 20.3}}, label: 'Click me'

        let btn = app.buttons["Click me"]

        btn.tap() // <-- This tap makes the red button disappear and shows the blue button

        print(app.debugDescription)

        // Now, the Element subtree shows a single Button that has a different ID
        // and different x-y coordinates:
        // Button, 0x15dc12e50, {{0.0, 418.3}, {65.3, 20.3}}, label: 'Click me'

        btn.tap() // <-- This tap now works on the blue button?? Without requerying?

        print(app.debugDescription)

        // The red button reappears, but with a different ID (which makes sense).
    }
}

Why does the second tap work, even though it's a different control? This must mean that SwiftUI is automatically re-running the XCUIElementQuery to find the button that matches "Click me". Apparently the variable btn isn't linked to the control with the ID 0x14e40d290. Does this mean XCUIElement actually represents an XCUIElementQuery?        I expected it to require me to explicitly re-run the query like this,

btn = app.buttons["Click me"]

prior to running the 2nd tap, or the tap would've said that btn was no longer available.

The final print of the Element subtree shows that the red button has a different ID now. This makes sense, because when SwiftUI redraws the red button, it's not the same instance as the last time. This is explained well in the WWDC videos. Nevertheless, at the moment I connected the variable "btn" to the control, I thought there was a tighter affiliation. Maybe UI testing has to behave this way because SwiftUI redraws controls so frequently?


问:
Time Series Analysis with weekly data, how to define frequency?
I am trying to analyze this time series data from the Wooldridge Econometrics book containing weekly data on the New York Stock Exchange, beginning in the year 1976 January and ending in 1989.

I have never worked with the ts() function before but I understand the general grammar already. What I have difficulties with, is how I should define the frequencies since every 4th year has 366 instead of 365 days. In the book is already stated that for holidays or weekends, the following day was used, when the stock exchange was open.

So how do I exactly deal with this problem of creating a time series object?

Here is a screenshot of the first rows of the data frame:
data frame of nyse